Line data Source code
1 : /**
2 : * What a settled billing operation may have changed in the billing context:
3 : * `account` refetches status and balance; `subscription` reconciles a plan
4 : * change on the checkout rail as well.
5 : */
6 : export type BillingRefreshScope = 'account' | 'subscription'
7 :
8 : type BillingRefreshListener = (
9 : scope: BillingRefreshScope
10 : ) => Promise<unknown> | void
11 :
12 : type CheckoutOperationReader = () => Promise<boolean>
13 :
14 2356 : const listeners = new Set<BillingRefreshListener>()
15 2356 : let checkoutOperationReader: CheckoutOperationReader | undefined
16 :
17 : /**
18 : * Registers a reader of billing state. The rails and operation stores that
19 : * settle a mutation announce it through {@link refreshBilling} without
20 : * knowing which readers exist, so the readers can sit above them in the
21 : * import graph.
22 : */
23 2355 : export function onBillingRefresh(listener: BillingRefreshListener): () => void {
24 2355 : listeners.add(listener)
25 2355 : return () => {
26 0 : listeners.delete(listener)
27 : }
28 : }
29 :
30 : /** Starts every registered reader's refetch; settles once they all have. */
31 0 : export function refreshBilling(scope: BillingRefreshScope): Promise<unknown> {
32 0 : return Promise.allSettled(
33 : Array.from(listeners, (listener) => listener(scope))
34 : )
35 : }
36 :
37 : /**
38 : * Registers the billing context's checkout-operation read, which knows the
39 : * rail that serves the checkout. Only one context exists at a time.
40 : */
41 2355 : export function provideCheckoutOperationReader(
42 : reader: CheckoutOperationReader
43 : ): () => void {
44 2355 : checkoutOperationReader = reader
45 2355 : return () => {
46 0 : if (checkoutOperationReader === reader) checkoutOperationReader = undefined
47 : }
48 : }
49 :
50 : /**
51 : * Reads the checkout rail's status, which resumes any operation the server
52 : * reports pending. True once that operation was adopted; false while no
53 : * billing context is registered.
54 : */
55 0 : export async function readCheckoutOperation(): Promise<boolean> {
56 0 : return (await checkoutOperationReader?.()) ?? false
57 : }
|