@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/refunds.ts ADDED
@@ -0,0 +1,88 @@
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 type { Refund, Refunded } from 'jsr:@yaks/host@0.2.36/payments'
6
+ import { ask, idOf, type Keyed } from './mod.js'
7
+
8
+ /** A refund read from Stripe's create response or its verified event. */
9
+ export let refundedOf = (o: Record<string, unknown>): Refunded => ({
10
+ id: String(o.id ?? ''),
11
+ payment: idOf(o.payment_intent as string | { id?: string }),
12
+ amount: Number(o.amount ?? 0),
13
+ status: o.status == 'succeeded'
14
+ ? 'succeeded'
15
+ : o.status == 'failed'
16
+ ? 'failed'
17
+ : o.status == 'canceled'
18
+ ? 'canceled'
19
+ : 'pending',
20
+ tags: { ...(o.metadata as Record<string, string> ?? {}) },
21
+ })
22
+
23
+ // Stripe retains idempotency keys for a day. The refund's own metadata keeps
24
+ // recovery safe after that window, including a lost create response.
25
+ let priorRefund = async (
26
+ options: Keyed,
27
+ on: string | undefined,
28
+ request: Refund,
29
+ ) => {
30
+ let after = ''
31
+ for (;;) {
32
+ let query = new URLSearchParams({
33
+ payment_intent: request.payment,
34
+ limit: '100',
35
+ ...(after ? { starting_after: after } : {}),
36
+ })
37
+ let page = await ask(options, `/v1/refunds?${query}`, undefined, on)
38
+ if (!Array.isArray(page.data) || typeof page.has_more != 'boolean') {
39
+ throw new Error('stripe returned an invalid refund list')
40
+ }
41
+ let rows = page.data as Record<string, unknown>[]
42
+ let old = rows.find((r) =>
43
+ (r.metadata as Record<string, string>)?.request == request.key
44
+ )
45
+ if (old) {
46
+ let refund = refundedOf(old)
47
+ if (
48
+ refund.amount != request.amount || refund.payment != request.payment
49
+ ) throw new Error('stripe refund request identity was reused')
50
+ return refund
51
+ }
52
+ if (!page.has_more) return null
53
+ let next = String(rows?.at(-1)?.id ?? '')
54
+ if (!next || next == after) {
55
+ throw new Error('stripe refund list did not advance')
56
+ }
57
+ after = next
58
+ }
59
+ }
60
+
61
+ /** Refund `request` on the account `on` (the platform's own where none),
62
+ * returning the application fee in proportion where it says `fee`. Asked
63
+ * again with the same key and request, it refunds nothing twice. */
64
+ export let refund = async (
65
+ options: Keyed,
66
+ on: string | undefined,
67
+ request: Refund,
68
+ ): Promise<Refunded> => {
69
+ let old = await priorRefund(options, on, request)
70
+ if (old) return old
71
+ let made = refundedOf(
72
+ await ask(
73
+ options,
74
+ '/v1/refunds',
75
+ {
76
+ payment_intent: request.payment,
77
+ amount: request.amount,
78
+ ...(request.fee ? { refund_application_fee: true } : {}),
79
+ metadata: { ...request.tags, request: request.key },
80
+ },
81
+ on,
82
+ 'POST',
83
+ request.key,
84
+ ),
85
+ )
86
+ if (!made.id) throw new Error('stripe made a refund with no id')
87
+ return made
88
+ }
package/shop-portal.js ADDED
@@ -0,0 +1,79 @@
1
+ import { ask } from "./mod.js";
2
+ let profiles = {
3
+ gift: {
4
+ name: 'yaks.app monthly gifts',
5
+ key: 'yaks-gifts-portal-v1',
6
+ features: {
7
+ subscription_cancel: {
8
+ enabled: true,
9
+ mode: 'immediately',
10
+ proration_behavior: 'none'
11
+ }
12
+ }
13
+ },
14
+ subscription: {
15
+ name: 'yaks.app subscriptions',
16
+ key: 'yaks-subscriptions-portal-v1',
17
+ features: {
18
+ payment_method_update: {
19
+ enabled: true
20
+ },
21
+ invoice_history: {
22
+ enabled: true
23
+ },
24
+ subscription_cancel: {
25
+ enabled: true,
26
+ mode: 'at_period_end',
27
+ proration_behavior: 'none'
28
+ }
29
+ }
30
+ }
31
+ };
32
+ let configuration = async (options, account, { name, key, features })=>{
33
+ let next;
34
+ do {
35
+ let params = new URLSearchParams({
36
+ active: 'true',
37
+ limit: '100'
38
+ });
39
+ if (next) params.set('starting_after', next);
40
+ let page = await ask(options, `/v1/billing_portal/configurations?${params}`, undefined, account);
41
+ let held = page.data.find((c)=>c.metadata?.yaks == name);
42
+ if (held) return held.id;
43
+ next = page.has_more ? page.data.at(-1)?.id : undefined;
44
+ }while (next)
45
+ let made = await ask(options, '/v1/billing_portal/configurations', {
46
+ name,
47
+ metadata: {
48
+ yaks: name
49
+ },
50
+ features
51
+ }, account, 'POST', key);
52
+ if (!made.id) throw new Error('stripe made a portal configuration with no id');
53
+ return String(made.id);
54
+ };
55
+ export let shopPortal = async (options, account, payer, subscription, back, purpose = 'gift')=>{
56
+ if (!account) throw new Error('a shop portal requires a connected account');
57
+ let portal = await ask(options, '/v1/billing_portal/sessions', {
58
+ customer: payer,
59
+ return_url: back,
60
+ configuration: await configuration(options, account, profiles[purpose]),
61
+ ...purpose == 'gift' ? {
62
+ flow_data: {
63
+ type: 'subscription_cancel',
64
+ subscription_cancel: {
65
+ subscription
66
+ },
67
+ after_completion: {
68
+ type: 'redirect',
69
+ redirect: {
70
+ return_url: back
71
+ }
72
+ }
73
+ }
74
+ } : {}
75
+ }, account);
76
+ if (!portal.url) throw new Error('stripe made a portal session with no url');
77
+ return String(portal.url);
78
+ };
79
+ //# sourceMappingURL=shop-portal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shop-portal.js","sources":["./shop-portal.ts"],"names":[],"mappings":"AAAA,SAAS,GAAG,mBAA8B;AAE1C,IAAI,WAAW;EACb,MAAM;IACJ,MAAM;IACN,KAAK;IACL,UAAU;MACR,qBAAqB;QACnB,SAAS;QACT,MAAM;QACN,oBAAoB;MACtB;IACF;EACF;EACA,cAAc;IACZ,MAAM;IACN,KAAK;IACL,UAAU;MACR,uBAAuB;QAAE,SAAS;MAAK;MACvC,iBAAiB;QAAE,SAAS;MAAK;MACjC,qBAAqB;QACnB,SAAS;QACT,MAAM;QACN,oBAAoB;MACtB;IACF;EACF;AACF;AAEA,IAAI,gBAAgB,OAClB,SACA,SACA,EAAE,IAAI,EAAE,GAAG,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
+ gift: {
5
+ name: 'yaks.app monthly gifts',
6
+ key: 'yaks-gifts-portal-v1',
7
+ features: {
8
+ subscription_cancel: {
9
+ enabled: true,
10
+ mode: 'immediately',
11
+ proration_behavior: 'none',
12
+ },
13
+ },
14
+ },
15
+ subscription: {
16
+ name: 'yaks.app subscriptions',
17
+ key: 'yaks-subscriptions-portal-v1',
18
+ features: {
19
+ payment_method_update: { enabled: true },
20
+ invoice_history: { enabled: true },
21
+ subscription_cancel: {
22
+ enabled: true,
23
+ mode: 'at_period_end',
24
+ proration_behavior: 'none',
25
+ },
26
+ },
27
+ },
28
+ }
29
+
30
+ let configuration = async (
31
+ options: Keyed,
32
+ account: string,
33
+ { name, key, features }: (typeof profiles)[keyof typeof profiles],
34
+ ) => {
35
+ let next: string | undefined
36
+ do {
37
+ let params = new URLSearchParams({ active: 'true', limit: '100' })
38
+ if (next) params.set('starting_after', next)
39
+ let page = await ask(
40
+ options,
41
+ `/v1/billing_portal/configurations?${params}`,
42
+ undefined,
43
+ account,
44
+ ) as {
45
+ data: { id: string; metadata?: { yaks?: string } }[]
46
+ has_more: boolean
47
+ }
48
+ let held = page.data.find((c) => c.metadata?.yaks == name)
49
+ if (held) return held.id
50
+ next = page.has_more ? page.data.at(-1)?.id : undefined
51
+ } while (next)
52
+ let made = await ask(
53
+ options,
54
+ '/v1/billing_portal/configurations',
55
+ { name, metadata: { yaks: name }, features },
56
+ account,
57
+ 'POST',
58
+ key,
59
+ )
60
+ if (!made.id) throw new Error('stripe made a portal configuration with no id')
61
+ return String(made.id)
62
+ }
63
+
64
+ export let shopPortal = async (
65
+ options: Keyed,
66
+ account: string,
67
+ payer: string,
68
+ subscription: string,
69
+ back: string,
70
+ purpose: keyof typeof profiles = 'gift',
71
+ ) => {
72
+ if (!account) throw new Error('a shop portal requires a connected account')
73
+ let portal = await ask(options, '/v1/billing_portal/sessions', {
74
+ customer: payer,
75
+ return_url: back,
76
+ configuration: await configuration(options, account, profiles[purpose]),
77
+ ...(purpose == 'gift'
78
+ ? {
79
+ flow_data: {
80
+ type: 'subscription_cancel',
81
+ subscription_cancel: { subscription },
82
+ after_completion: {
83
+ type: 'redirect',
84
+ redirect: { return_url: back },
85
+ },
86
+ },
87
+ }
88
+ : {}),
89
+ }, account)
90
+ if (!portal.url) throw new Error('stripe made a portal session with no url')
91
+ return String(portal.url)
92
+ }
package/shop-term.js ADDED
@@ -0,0 +1,52 @@
1
+ import { ask, found } from "./mod.js";
2
+ import { ending, when } from "./plans.js";
3
+ let periodOf = (invoice)=>{
4
+ let ends = (invoice?.lines?.data ?? []).flatMap((line)=>{
5
+ let item = line.parent?.subscription_item_details;
6
+ let recurring = item ? !item.proration : line.type == 'subscription' && !line.proration;
7
+ return recurring && typeof line.period?.end == 'number' ? [
8
+ line.period.end
9
+ ] : [];
10
+ });
11
+ return ends.length ? Math.min(...ends) : null;
12
+ };
13
+ let invoiceOf = (sub)=>typeof sub.latest_invoice == 'object' ? sub.latest_invoice ?? undefined : undefined;
14
+ /** Stripe advances subscription periods while it is still collecting payment.
15
+ * The paid invoice's line period is the period covered by the payment. */ let paidThrough = async (options, account, sub)=>{
16
+ if (sub.status == 'incomplete' || sub.status == 'incomplete_expired') {
17
+ return null;
18
+ }
19
+ let invoice = invoiceOf(sub);
20
+ let until = invoice?.status == 'paid' ? periodOf(invoice) : null;
21
+ if (until == null && sub.id) {
22
+ let params = new URLSearchParams({
23
+ subscription: sub.id,
24
+ status: 'paid',
25
+ limit: '1'
26
+ });
27
+ let paid = await ask(options, `/v1/invoices?${params}`, undefined, account);
28
+ until = periodOf(paid.data[0]);
29
+ }
30
+ let ended = sub.status == 'canceled' ? sub.ended_at ?? sub.canceled_at : null;
31
+ return until != null && ended != null ? Math.min(until, ended) : until;
32
+ };
33
+ let termOf = async (options, account, sub)=>({
34
+ id: String(sub.id ?? ''),
35
+ until: when(await paidThrough(options, account, sub)),
36
+ ending: ending(sub, sub.status ?? ''),
37
+ tags: {
38
+ ...sub.metadata
39
+ }
40
+ });
41
+ let pathOf = (id)=>`/v1/subscriptions/${encodeURIComponent(id)}`;
42
+ export let termAt = async (options, account, id)=>{
43
+ let sub = await found(options, `${pathOf(id)}?expand[]=latest_invoice`, account);
44
+ return sub && await termOf(options, account, sub);
45
+ };
46
+ export let cancelTerm = async (options, account, id)=>termOf(options, account, await ask(options, pathOf(id), {
47
+ cancel_at_period_end: true,
48
+ expand: [
49
+ 'latest_invoice'
50
+ ]
51
+ }, account));
52
+ //# sourceMappingURL=shop-term.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shop-term.js","sources":["./shop-term.ts"],"names":[],"mappings":"AACA,SAAS,GAAG,EAAE,KAAK,mBAA8B;AACjD,SAAoB,MAAM,EAAY,IAAI,qBAAoB;AAW9D,IAAI,WAAW,CAAC;EACd,IAAI,OAAO,CAAC,SAAS,OAAO,QAAQ,EAAE,EAAE,OAAO,CAAC,CAAC;IAC/C,IAAI,OAAO,KAAK,MAAM,EAAE;IACxB,IAAI,YAAY,OAAO,CAAC,KAAK,SAAS,GAAG,KAAK,IAAI,IAAI,kBACpD,CAAC,KAAK,SAAS;IACjB,OAAO,aAAa,OAAO,KAAK,MAAM,EAAE,OAAO,WAC3C;MAAC,KAAK,MAAM,CAAC,GAAG;KAAC,GACjB,EAAE;EACR;EACA,OAAO,KAAK,MAAM,GAAG,KAAK,GAAG,IAAI,QAAQ;AAC3C;AAEA,IAAI,YAAY,CAAC,MACf,OAAO,IAAI,cAAc,IAAI,WACzB,IAAI,cAAc,IAAI,YACtB;AAEN;wEACwE,GACxE,IAAI,cAAc,OAAO,SAAgB,SAAiB;EACxD,IAAI,IAAI,MAAM,IAAI,gBAAgB,IAAI,MAAM,IAAI,sBAAsB;IACpE,OAAO;EACT;EACA,IAAI,UAAU,UAAU;EACxB,IAAI,QAAQ,SAAS,UAAU,SAAS,SAAS,WAAW;EAC5D,IAAI,SAAS,QAAQ,IAAI,EAAE,EAAE;IAC3B,IAAI,SAAS,IAAI,gBAAgB;MAC/B,cAAc,IAAI,EAAE;MACpB,QAAQ;MACR,OAAO;IACT;IACA,IAAI,OAAO,MAAM,IACf,SACA,CAAC,aAAa,EAAE,QAAQ,EACxB,WACA;IAIF,QAAQ,SAAS,KAAK,IAAI,CAAC,EAAE;EAC/B;EACA,IAAI,QAAQ,IAAI,MAAM,IAAI,aAAa,IAAI,QAAQ,IAAI,IAAI,WAAW,GAAG;EACzE,OAAO,SAAS,QAAQ,SAAS,OAAO,KAAK,GAAG,CAAC,OAAO,SAAS;AACnE;AAEA,IAAI,SAAS,OACX,SACA,SACA,MACkB,CAAC;IACnB,IAAI,OAAO,IAAI,EAAE,IAAI;IACrB,OAAO,KAAK,MAAM,YAAY,SAAS,SAAS;IAChD,QAAQ,OAAO,KAAK,IAAI,MAAM,IAAI;IAClC,MAAM;MAAE,GAAG,IAAI,QAAQ;IAAC;EAC1B,CAAC;AAED,IAAI,SAAS,CAAC,KAAe,CAAC,kBAAkB,EAAE,mBAAmB,KAAK;AAE1E,OAAO,IAAI,SAAS,OAAO,SAAgB,SAAiB;EAC1D,IAAI,MAAM,MAAM,MACd,SACA,GAAG,OAAO,IAAI,wBAAwB,CAAC,EACvC;EAEF,OAAO,OAAO,MAAM,OAAO,SAAS,SAAS;AAC/C,EAAC;AAED,OAAO,IAAI,aAAa,OAAO,SAAgB,SAAiB,KAC9D,OACE,SACA,SACA,MAAM,IAAI,SAAS,OAAO,KAAK;IAC7B,sBAAsB;IACtB,QAAQ;MAAC;KAAiB;EAC5B,GAAG,UACJ"}
package/shop-term.ts ADDED
@@ -0,0 +1,89 @@
1
+ import type { Term } from 'jsr:@yaks/host@0.2.36/payments'
2
+ import { ask, found, type Keyed } from './mod.js'
3
+ import { type Bill, ending, type Sub, when } from './plans.js'
4
+
5
+ type InvoiceLine = {
6
+ type?: string
7
+ proration?: boolean
8
+ parent?: { subscription_item_details?: { proration?: boolean } | null }
9
+ period?: { end?: number }
10
+ }
11
+
12
+ type Invoice = Bill & { lines?: { data: InvoiceLine[] } }
13
+
14
+ let periodOf = (invoice?: Invoice): number | null => {
15
+ let ends = (invoice?.lines?.data ?? []).flatMap((line) => {
16
+ let item = line.parent?.subscription_item_details
17
+ let recurring = item ? !item.proration : line.type == 'subscription' &&
18
+ !line.proration
19
+ return recurring && typeof line.period?.end == 'number'
20
+ ? [line.period.end]
21
+ : []
22
+ })
23
+ return ends.length ? Math.min(...ends) : null
24
+ }
25
+
26
+ let invoiceOf = (sub: Sub): Invoice | undefined =>
27
+ typeof sub.latest_invoice == 'object'
28
+ ? sub.latest_invoice ?? undefined
29
+ : undefined
30
+
31
+ /** Stripe advances subscription periods while it is still collecting payment.
32
+ * The paid invoice's line period is the period covered by the payment. */
33
+ let paidThrough = async (options: Keyed, account: string, sub: Sub) => {
34
+ if (sub.status == 'incomplete' || sub.status == 'incomplete_expired') {
35
+ return null
36
+ }
37
+ let invoice = invoiceOf(sub)
38
+ let until = invoice?.status == 'paid' ? periodOf(invoice) : null
39
+ if (until == null && sub.id) {
40
+ let params = new URLSearchParams({
41
+ subscription: sub.id,
42
+ status: 'paid',
43
+ limit: '1',
44
+ })
45
+ let paid = await ask(
46
+ options,
47
+ `/v1/invoices?${params}`,
48
+ undefined,
49
+ account,
50
+ ) as {
51
+ data: Invoice[]
52
+ }
53
+ until = periodOf(paid.data[0])
54
+ }
55
+ let ended = sub.status == 'canceled' ? sub.ended_at ?? sub.canceled_at : null
56
+ return until != null && ended != null ? Math.min(until, ended) : until
57
+ }
58
+
59
+ let termOf = async (
60
+ options: Keyed,
61
+ account: string,
62
+ sub: Sub,
63
+ ): Promise<Term> => ({
64
+ id: String(sub.id ?? ''),
65
+ until: when(await paidThrough(options, account, sub)),
66
+ ending: ending(sub, sub.status ?? ''),
67
+ tags: { ...sub.metadata },
68
+ })
69
+
70
+ let pathOf = (id: string) => `/v1/subscriptions/${encodeURIComponent(id)}`
71
+
72
+ export let termAt = async (options: Keyed, account: string, id: string) => {
73
+ let sub = await found(
74
+ options,
75
+ `${pathOf(id)}?expand[]=latest_invoice`,
76
+ account,
77
+ ) as Sub | null
78
+ return sub && await termOf(options, account, sub)
79
+ }
80
+
81
+ export let cancelTerm = async (options: Keyed, account: string, id: string) =>
82
+ termOf(
83
+ options,
84
+ account,
85
+ await ask(options, pathOf(id), {
86
+ cancel_at_period_end: true,
87
+ expand: ['latest_invoice'],
88
+ }, account) as Sub,
89
+ )