@referalli/sdk 0.0.0-stage → 0.3.21

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.
Files changed (184) hide show
  1. package/CHANGELOG.md +132 -0
  2. package/LICENSE +21 -0
  3. package/README.md +236 -2
  4. package/dist/cjs/attribution.d.ts +105 -0
  5. package/dist/cjs/attribution.js +200 -0
  6. package/dist/cjs/browser.d.ts +41 -0
  7. package/dist/cjs/browser.js +88 -0
  8. package/dist/cjs/client.d.ts +97 -0
  9. package/dist/cjs/client.js +301 -0
  10. package/dist/cjs/consent/adapters/cookiebot.d.ts +7 -0
  11. package/dist/cjs/consent/adapters/cookiebot.js +49 -0
  12. package/dist/cjs/consent/adapters/cookiemunch.d.ts +8 -0
  13. package/dist/cjs/consent/adapters/cookiemunch.js +56 -0
  14. package/dist/cjs/consent/adapters/custom.d.ts +8 -0
  15. package/dist/cjs/consent/adapters/custom.js +39 -0
  16. package/dist/cjs/consent/adapters/didomi.d.ts +9 -0
  17. package/dist/cjs/consent/adapters/didomi.js +67 -0
  18. package/dist/cjs/consent/adapters/gcm.d.ts +10 -0
  19. package/dist/cjs/consent/adapters/gcm.js +78 -0
  20. package/dist/cjs/consent/adapters/gpp.d.ts +9 -0
  21. package/dist/cjs/consent/adapters/gpp.js +92 -0
  22. package/dist/cjs/consent/adapters/none.d.ts +3 -0
  23. package/dist/cjs/consent/adapters/none.js +30 -0
  24. package/dist/cjs/consent/adapters/onetrust.d.ts +8 -0
  25. package/dist/cjs/consent/adapters/onetrust.js +71 -0
  26. package/dist/cjs/consent/adapters/osano.d.ts +9 -0
  27. package/dist/cjs/consent/adapters/osano.js +71 -0
  28. package/dist/cjs/consent/adapters/tcf.d.ts +8 -0
  29. package/dist/cjs/consent/adapters/tcf.js +79 -0
  30. package/dist/cjs/consent/adapters/termly.d.ts +10 -0
  31. package/dist/cjs/consent/adapters/termly.js +61 -0
  32. package/dist/cjs/consent/adapters/usercentrics.d.ts +9 -0
  33. package/dist/cjs/consent/adapters/usercentrics.js +106 -0
  34. package/dist/cjs/consent/conformance.d.ts +22 -0
  35. package/dist/cjs/consent/conformance.js +33 -0
  36. package/dist/cjs/consent/gate.d.ts +23 -0
  37. package/dist/cjs/consent/gate.js +220 -0
  38. package/dist/cjs/consent/port.d.ts +105 -0
  39. package/dist/cjs/consent/port.js +72 -0
  40. package/dist/cjs/consent/registry.d.ts +17 -0
  41. package/dist/cjs/consent/registry.js +61 -0
  42. package/dist/cjs/consent/served.d.ts +15 -0
  43. package/dist/cjs/consent/served.js +26 -0
  44. package/dist/cjs/core.d.ts +77 -0
  45. package/dist/cjs/core.js +64 -0
  46. package/dist/cjs/errors.d.ts +42 -0
  47. package/dist/cjs/errors.generated.d.ts +183 -0
  48. package/dist/cjs/errors.generated.js +279 -0
  49. package/dist/cjs/errors.js +47 -0
  50. package/dist/cjs/generated.d.ts +15151 -0
  51. package/dist/cjs/generated.js +625 -0
  52. package/dist/cjs/index.d.ts +22 -0
  53. package/dist/cjs/index.js +93 -0
  54. package/dist/cjs/mobile.d.ts +66 -0
  55. package/dist/cjs/mobile.js +69 -0
  56. package/dist/cjs/node.d.ts +209 -0
  57. package/dist/cjs/node.js +140 -0
  58. package/dist/cjs/outbox.d.ts +186 -0
  59. package/dist/cjs/outbox.js +324 -0
  60. package/dist/cjs/package.json +3 -0
  61. package/dist/cjs/resources.generated.d.ts +6002 -0
  62. package/dist/cjs/resources.generated.js +2090 -0
  63. package/dist/cjs/served.d.ts +25 -0
  64. package/dist/cjs/served.js +214 -0
  65. package/dist/cjs/sha256.d.ts +2 -0
  66. package/dist/cjs/sha256.js +86 -0
  67. package/dist/cjs/snippet.d.ts +99 -0
  68. package/dist/cjs/snippet.js +213 -0
  69. package/dist/cjs/stripe-events.d.ts +25 -0
  70. package/dist/cjs/stripe-events.js +117 -0
  71. package/dist/cjs/version.d.ts +2 -0
  72. package/dist/cjs/version.js +5 -0
  73. package/dist/cjs/webhooks.d.ts +76 -0
  74. package/dist/cjs/webhooks.js +159 -0
  75. package/dist/esm/attribution.d.ts +105 -0
  76. package/dist/esm/attribution.js +186 -0
  77. package/dist/esm/browser.d.ts +41 -0
  78. package/dist/esm/browser.js +68 -0
  79. package/dist/esm/client.d.ts +97 -0
  80. package/dist/esm/client.js +297 -0
  81. package/dist/esm/consent/adapters/cookiebot.d.ts +7 -0
  82. package/dist/esm/consent/adapters/cookiebot.js +46 -0
  83. package/dist/esm/consent/adapters/cookiemunch.d.ts +8 -0
  84. package/dist/esm/consent/adapters/cookiemunch.js +53 -0
  85. package/dist/esm/consent/adapters/custom.d.ts +8 -0
  86. package/dist/esm/consent/adapters/custom.js +36 -0
  87. package/dist/esm/consent/adapters/didomi.d.ts +9 -0
  88. package/dist/esm/consent/adapters/didomi.js +64 -0
  89. package/dist/esm/consent/adapters/gcm.d.ts +10 -0
  90. package/dist/esm/consent/adapters/gcm.js +75 -0
  91. package/dist/esm/consent/adapters/gpp.d.ts +9 -0
  92. package/dist/esm/consent/adapters/gpp.js +89 -0
  93. package/dist/esm/consent/adapters/none.d.ts +3 -0
  94. package/dist/esm/consent/adapters/none.js +27 -0
  95. package/dist/esm/consent/adapters/onetrust.d.ts +8 -0
  96. package/dist/esm/consent/adapters/onetrust.js +68 -0
  97. package/dist/esm/consent/adapters/osano.d.ts +9 -0
  98. package/dist/esm/consent/adapters/osano.js +68 -0
  99. package/dist/esm/consent/adapters/tcf.d.ts +8 -0
  100. package/dist/esm/consent/adapters/tcf.js +76 -0
  101. package/dist/esm/consent/adapters/termly.d.ts +10 -0
  102. package/dist/esm/consent/adapters/termly.js +58 -0
  103. package/dist/esm/consent/adapters/usercentrics.d.ts +9 -0
  104. package/dist/esm/consent/adapters/usercentrics.js +103 -0
  105. package/dist/esm/consent/conformance.d.ts +22 -0
  106. package/dist/esm/consent/conformance.js +30 -0
  107. package/dist/esm/consent/gate.d.ts +23 -0
  108. package/dist/esm/consent/gate.js +217 -0
  109. package/dist/esm/consent/port.d.ts +105 -0
  110. package/dist/esm/consent/port.js +67 -0
  111. package/dist/esm/consent/registry.d.ts +17 -0
  112. package/dist/esm/consent/registry.js +55 -0
  113. package/dist/esm/consent/served.d.ts +15 -0
  114. package/dist/esm/consent/served.js +22 -0
  115. package/dist/esm/core.d.ts +77 -0
  116. package/dist/esm/core.js +60 -0
  117. package/dist/esm/errors.d.ts +42 -0
  118. package/dist/esm/errors.generated.d.ts +183 -0
  119. package/dist/esm/errors.generated.js +231 -0
  120. package/dist/esm/errors.js +40 -0
  121. package/dist/esm/generated.d.ts +15151 -0
  122. package/dist/esm/generated.js +622 -0
  123. package/dist/esm/index.d.ts +22 -0
  124. package/dist/esm/index.js +22 -0
  125. package/dist/esm/mobile.d.ts +66 -0
  126. package/dist/esm/mobile.js +64 -0
  127. package/dist/esm/node.d.ts +209 -0
  128. package/dist/esm/node.js +135 -0
  129. package/dist/esm/outbox.d.ts +186 -0
  130. package/dist/esm/outbox.js +316 -0
  131. package/dist/esm/package.json +3 -0
  132. package/dist/esm/resources.generated.d.ts +6002 -0
  133. package/dist/esm/resources.generated.js +2086 -0
  134. package/dist/esm/served.d.ts +25 -0
  135. package/dist/esm/served.js +207 -0
  136. package/dist/esm/sha256.d.ts +2 -0
  137. package/dist/esm/sha256.js +82 -0
  138. package/dist/esm/snippet.d.ts +99 -0
  139. package/dist/esm/snippet.js +210 -0
  140. package/dist/esm/stripe-events.d.ts +25 -0
  141. package/dist/esm/stripe-events.js +114 -0
  142. package/dist/esm/version.d.ts +2 -0
  143. package/dist/esm/version.js +2 -0
  144. package/dist/esm/webhooks.d.ts +76 -0
  145. package/dist/esm/webhooks.js +153 -0
  146. package/dist/tsconfig.build.tsbuildinfo +1 -0
  147. package/dist/tsconfig.cjs.tsbuildinfo +1 -0
  148. package/package.json +105 -4
  149. package/src/attribution.ts +216 -0
  150. package/src/browser.ts +107 -0
  151. package/src/client.ts +351 -0
  152. package/src/codegen.ts +130 -0
  153. package/src/consent/adapters/cookiebot.ts +42 -0
  154. package/src/consent/adapters/cookiemunch.ts +49 -0
  155. package/src/consent/adapters/custom.ts +37 -0
  156. package/src/consent/adapters/didomi.ts +59 -0
  157. package/src/consent/adapters/gcm.ts +68 -0
  158. package/src/consent/adapters/gpp.ts +81 -0
  159. package/src/consent/adapters/none.ts +28 -0
  160. package/src/consent/adapters/onetrust.ts +64 -0
  161. package/src/consent/adapters/osano.ts +63 -0
  162. package/src/consent/adapters/tcf.ts +67 -0
  163. package/src/consent/adapters/termly.ts +54 -0
  164. package/src/consent/adapters/usercentrics.ts +97 -0
  165. package/src/consent/conformance.ts +47 -0
  166. package/src/consent/gate.ts +216 -0
  167. package/src/consent/port.ts +148 -0
  168. package/src/consent/registry.ts +60 -0
  169. package/src/consent/served.ts +24 -0
  170. package/src/core.ts +127 -0
  171. package/src/errors.generated.ts +277 -0
  172. package/src/errors.ts +57 -0
  173. package/src/generated.ts +14545 -0
  174. package/src/index.ts +100 -0
  175. package/src/mobile.ts +96 -0
  176. package/src/node.ts +291 -0
  177. package/src/outbox.ts +452 -0
  178. package/src/resources.generated.ts +2097 -0
  179. package/src/served.ts +229 -0
  180. package/src/sha256.ts +82 -0
  181. package/src/snippet.ts +305 -0
  182. package/src/stripe-events.ts +130 -0
  183. package/src/version.ts +2 -0
  184. package/src/webhooks.ts +207 -0
@@ -0,0 +1,186 @@
1
+ import { Referalli } from './client.js';
2
+ export declare const APPROX_USD_PER_UNIT: Record<string, number>;
3
+ /** One event for a `generic` billing connection (amounts in integer minor units). */
4
+ export interface GenericBillingEvent {
5
+ /** Your id for this event: Referalli records it once, so resending is safe. */
6
+ providerEventId: string;
7
+ type: 'invoice_paid' | 'sub_created' | 'sub_updated' | 'refund' | 'dispute' | 'sub_canceled' | 'customer_updated';
8
+ customerRef?: string;
9
+ subscriptionRef?: string;
10
+ invoiceRef?: string;
11
+ productRef?: string;
12
+ amountGross?: number;
13
+ tax?: number;
14
+ fees?: number;
15
+ currency?: string;
16
+ mrrDelta?: number;
17
+ /** ISO 8601 instant. */
18
+ occurredAt: string;
19
+ metadata?: Record<string, unknown>;
20
+ linkedCustomerRef?: string;
21
+ customerEmail?: string;
22
+ productIds?: string[];
23
+ priceIds?: string[];
24
+ skus?: string[];
25
+ }
26
+ /** A queued event. Times are epoch milliseconds. */
27
+ export interface OutboxEntry {
28
+ /** The event's `providerEventId`. */
29
+ id: string;
30
+ event: GenericBillingEvent;
31
+ attempts: number;
32
+ /** `null` once the outbox gave up on it. */
33
+ nextAttemptAt: number | null;
34
+ lastError: string | null;
35
+ }
36
+ /**
37
+ * Where the outbox keeps events. Back it with a table in your own database so
38
+ * a queued payment survives restarts: `pgOutboxStore` (Postgres) and
39
+ * `sqliteOutboxStore` (SQLite, libSQL/Turso) implement it; any other store
40
+ * needs these four methods (and `claim` for several workers).
41
+ */
42
+ export interface OutboxStore {
43
+ /** Save an entry. An entry with the same id already queued is kept as it is. */
44
+ add(entry: OutboxEntry): Promise<void>;
45
+ /** Up to `limit` entries still to send whose `nextAttemptAt <= now`, oldest first. */
46
+ due(now: number, limit: number): Promise<OutboxEntry[]>;
47
+ /** Referalli accepted it: delete the entry (or mark it sent). */
48
+ markSent(id: string): Promise<void>;
49
+ /** A failed attempt. `nextAttemptAt: null` means give up: keep the entry, but `due` no longer returns it. */
50
+ markFailed(id: string, update: {
51
+ attempts: number;
52
+ nextAttemptAt: number | null;
53
+ lastError: string;
54
+ }): Promise<void>;
55
+ /**
56
+ * Optional: atomically take the oldest due entry for `leaseMs`, so other
57
+ * workers skip it and it comes due again if this process dies. When present,
58
+ * `flush` uses it instead of `due`.
59
+ */
60
+ claim?(now: number, leaseMs: number): Promise<OutboxEntry | null>;
61
+ }
62
+ export interface OutboxOptions {
63
+ store: OutboxStore;
64
+ /** The `generic` billing connection (`bcon_…`). */
65
+ connectionId: string;
66
+ /**
67
+ * The connection's webhook secret: events go to the signed
68
+ * `POST /webhooks/billing/{connectionId}`. Without it they go to
69
+ * `POST /v1/billing/connections/{id}/events` with `client`'s API key.
70
+ */
71
+ secret?: string;
72
+ /** Default `new Referalli()` (reads `REFERALLI_API_KEY`). */
73
+ client?: Referalli;
74
+ /** The signed route's host. Default `client.baseUrl`, then https://referalli.com. */
75
+ baseUrl?: string;
76
+ /** The signed route's fetch. Default the global fetch. */
77
+ fetch?: (url: string, init: RequestInit) => Promise<Response>;
78
+ /** Attempts before an event is given up on (kept in the store). Default 50, about two days with the default delays. */
79
+ maxAttempts?: number;
80
+ /** First retry delay in ms; doubles per attempt, with jitter. Default 30 000. */
81
+ baseDelayMs?: number;
82
+ /** Longest retry delay in ms. Default 3 600 000 (1 hour). */
83
+ maxDelayMs?: number;
84
+ /** Called when an event hits `maxAttempts`, after it is marked dead in the store. A throw here is ignored. */
85
+ onDead?: (entry: OutboxEntry) => void | Promise<void>;
86
+ /** Clock for tests. Default `Date.now`. */
87
+ now?: () => number;
88
+ }
89
+ export interface FlushResult {
90
+ sent: number;
91
+ /** Failed this round; retried later. */
92
+ failed: number;
93
+ /** Failed for the last time; left in the store with `nextAttemptAt: null`. */
94
+ gaveUp: number;
95
+ }
96
+ export interface Outbox {
97
+ /** Queue an event durably. Then call `flush()` (right away, and on a timer). */
98
+ enqueue(event: GenericBillingEvent): Promise<void>;
99
+ /** Send every due event, one at a time. Concurrent calls share one run. */
100
+ flush(options?: {
101
+ limit?: number;
102
+ }): Promise<FlushResult>;
103
+ }
104
+ /**
105
+ * A durable queue for billing events, so an outage longer than the client's
106
+ * own retries does not lose a payment:
107
+ *
108
+ * const outbox = createOutbox({ store, connectionId: 'bcon_…', secret: process.env.REFERALLI_BILLING_SECRET });
109
+ * await outbox.enqueue({ providerEventId: invoice.id, type: 'invoice_paid', ... });
110
+ * void outbox.flush();
111
+ * setInterval(() => void outbox.flush(), 60_000);
112
+ *
113
+ * Every send carries the event's `providerEventId`, so a redelivery (two
114
+ * workers, a crash after sending) is recorded once.
115
+ */
116
+ export declare function createOutbox(options: OutboxOptions): Outbox;
117
+ /** An in-memory `OutboxStore`, for tests and scripts. It does not survive a restart. */
118
+ export declare function memoryOutboxStore(): OutboxStore & {
119
+ entries(): OutboxEntry[];
120
+ };
121
+ /** A query function shaped like node-postgres's `pool.query`. */
122
+ export type PgQuery = (sql: string, params: unknown[]) => Promise<{
123
+ rows: any[];
124
+ }>;
125
+ /**
126
+ * An `OutboxStore` on a Postgres table, through your own query function, for
127
+ * several replicas:
128
+ *
129
+ * const store = pgOutboxStore({ query: (sql, params) => pool.query(sql, params), table: 'referalli_outbox' });
130
+ * await store.migrate();
131
+ *
132
+ * Columns: `id` text primary key (the providerEventId), `event` jsonb,
133
+ * `attempts` int, `next_attempt_at` bigint (epoch ms; null = dead),
134
+ * `last_error` text. A sent row is deleted; a dead row stays until you remove
135
+ * or requeue it (`store.dead()` lists them).
136
+ */
137
+ export declare function pgOutboxStore(options: {
138
+ query: PgQuery;
139
+ table: string;
140
+ }): OutboxStore & {
141
+ claim(now: number, leaseMs: number): Promise<OutboxEntry | null>;
142
+ /** Create the table and its index if missing. Safe from replicas booting together. */
143
+ migrate(): Promise<void>;
144
+ /** Entries that hit the attempt cap. */
145
+ dead(): Promise<OutboxEntry[]>;
146
+ };
147
+ /**
148
+ * Runs one SQL statement with `?` placeholders and answers its rows (none for a
149
+ * statement that returns none). Shaped so libSQL's `client.execute` fits as it is.
150
+ */
151
+ export type SqlExecute = (sql: string, params: unknown[]) => Promise<{
152
+ rows: unknown[];
153
+ }>;
154
+ /**
155
+ * An `OutboxStore` on a SQLite or libSQL (Turso) table, through your own
156
+ * `execute` function, so the SDK adds no driver:
157
+ *
158
+ * // libSQL / Turso
159
+ * const store = sqliteOutboxStore({ execute: (sql, args) => client.execute({ sql, args: args as InArgs }), table: 'referalli_outbox' });
160
+ * // better-sqlite3 (synchronous)
161
+ * const store = sqliteOutboxStore({ execute: async (sql, p) => { const st = db.prepare(sql); return { rows: st.reader ? st.all(p) : (st.run(p), []) }; }, table: 'referalli_outbox' });
162
+ * await store.migrate();
163
+ *
164
+ * Columns: `id` TEXT primary key (the providerEventId), `event` TEXT (JSON),
165
+ * `attempts` INTEGER, `next_attempt_at` INTEGER (epoch ms; NULL = dead),
166
+ * `last_error` TEXT. A sent row is deleted. `claim` is one `UPDATE … RETURNING`
167
+ * statement (SQLite 3.35+), atomic because SQLite runs one writer at a time, so
168
+ * several processes on the same database each get a different row.
169
+ */
170
+ export declare function sqliteOutboxStore(options: {
171
+ execute: SqlExecute;
172
+ table: string;
173
+ }): OutboxStore & {
174
+ claim(now: number, leaseMs: number): Promise<OutboxEntry | null>;
175
+ /** Create the table and its index if missing. */
176
+ migrate(): Promise<void>;
177
+ /** Entries that hit the attempt cap. */
178
+ dead(): Promise<OutboxEntry[]>;
179
+ };
180
+ /**
181
+ * Type-checks a generic billing event and refuses `amountMinor`: the API
182
+ * ignores unknown fields, so that payment would be recorded as 0 and earn nothing.
183
+ */
184
+ export declare function buildBillingEvent(event: GenericBillingEvent & {
185
+ amountMinor?: never;
186
+ }): GenericBillingEvent;
@@ -0,0 +1,324 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.APPROX_USD_PER_UNIT = void 0;
4
+ exports.createOutbox = createOutbox;
5
+ exports.memoryOutboxStore = memoryOutboxStore;
6
+ exports.pgOutboxStore = pgOutboxStore;
7
+ exports.sqliteOutboxStore = sqliteOutboxStore;
8
+ exports.buildBillingEvent = buildBillingEvent;
9
+ const client_js_1 = require("./client.js");
10
+ const sha256_js_1 = require("./sha256.js");
11
+ // The server's rough rates for its payment limit, kept in step with the server's table by a monorepo test.
12
+ exports.APPROX_USD_PER_UNIT = { aed: 0.27, afn: 0.014, all: 0.011, amd: 0.0026, ang: 0.56, aoa: 0.0011, ars: 0.001, aud: 0.65, awg: 0.56, azn: 0.59, bam: 0.56, bbd: 0.5, bdt: 0.0082, bgn: 0.56, bhd: 2.65, bif: 0.00034, bmd: 1, bnd: 0.77, bob: 0.145, brl: 0.18, bsd: 1, btn: 0.012, bwp: 0.074, byn: 0.31, bzd: 0.5, cad: 0.72, cdf: 0.00035, chf: 1.15, clp: 0.00105, cny: 0.14, cop: 0.00025, crc: 0.002, cuc: 1, cup: 0.042, cve: 0.01, czk: 0.044, djf: 0.0056, dkk: 0.15, dop: 0.016, dzd: 0.0075, egp: 0.02, ern: 0.067, etb: 0.0071, eur: 1.1, fjd: 0.44, fkp: 1.3, gbp: 1.3, gel: 0.37, ghs: 0.065, gip: 1.3, gmd: 0.014, gnf: 0.000116, gtq: 0.13, gyd: 0.0048, hkd: 0.13, hnl: 0.038, hrk: 0.146, htg: 0.0076, huf: 0.0027, idr: 0.000063, ils: 0.28, inr: 0.012, iqd: 0.00076, irr: 0.000024, isk: 0.0072, jmd: 0.0063, jod: 1.41, jpy: 0.0066, kes: 0.0077, kgs: 0.0114, khr: 0.00025, kmf: 0.0023, kpw: 0.0011, krw: 0.00072, kwd: 3.26, kyd: 1.2, kzt: 0.002, lak: 0.000046, lbp: 0.000011, lkr: 0.0033, lrd: 0.0055, lsl: 0.055, lyd: 0.18, mad: 0.1, mdl: 0.057, mga: 0.00022, mkd: 0.018, mmk: 0.00048, mnt: 0.00029, mop: 0.125, mru: 0.025, mur: 0.022, mvr: 0.065, mwk: 0.00058, mxn: 0.054, myr: 0.23, mzn: 0.0156, nad: 0.055, ngn: 0.00065, nio: 0.027, nok: 0.095, npr: 0.0074, nzd: 0.6, omr: 2.6, pab: 1, pen: 0.27, pgk: 0.25, php: 0.017, pkr: 0.0036, pln: 0.26, pyg: 0.000125, qar: 0.27, ron: 0.22, rsd: 0.0093, rub: 0.012, rwf: 0.00072, sar: 0.27, sbd: 0.12, scr: 0.07, sdg: 0.0017, sek: 0.1, sgd: 0.77, shp: 1.3, sle: 0.044, sll: 0.000044, sos: 0.00175, srd: 0.027, ssp: 0.00022, stn: 0.045, svc: 0.114, syp: 0.000077, szl: 0.055, thb: 0.029, tjs: 0.094, tmt: 0.29, tnd: 0.33, top: 0.42, try: 0.029, ttd: 0.147, twd: 0.031, tzs: 0.00037, uah: 0.024, ugx: 0.00027, usd: 1, uyu: 0.025, uzs: 0.00008, ves: 0.005, vnd: 0.00004, vuv: 0.0083, wst: 0.36, xaf: 0.0017, xcd: 0.37, xcg: 0.56, xdr: 1.35, xof: 0.0017, xpf: 0.0094, xsu: 1.25, yer: 0.004, zar: 0.055, zmw: 0.04, zwg: 0.037, zwl: 0.0031 };
13
+ const ZERO = new Set(['bif', 'clp', 'djf', 'gnf', 'jpy', 'kmf', 'krw', 'mga', 'pyg', 'rwf', 'ugx', 'vnd', 'vuv', 'xaf', 'xof', 'xpf']);
14
+ const THREE = new Set(['bhd', 'iqd', 'jod', 'kwd', 'lyd', 'omr', 'tnd']);
15
+ const approxUsdMinor = (minor, currency) => {
16
+ const c = currency.toLowerCase();
17
+ return Math.round((minor / 10 ** (ZERO.has(c) ? 0 : THREE.has(c) ? 3 : 2)) * (exports.APPROX_USD_PER_UNIT[c] ?? 1) * 100);
18
+ };
19
+ const EVENT_TYPES = new Set(['invoice_paid', 'sub_created', 'sub_updated', 'refund', 'dispute', 'sub_canceled', 'customer_updated']);
20
+ /** The server's rules for a generic event: what fails here could only ever be refused later, after the caller has moved on. */
21
+ function assertSendable(e) {
22
+ const refuse = (why) => new TypeError(`createOutbox: event ${e.providerEventId}: ${why}`);
23
+ if (!EVENT_TYPES.has(e.type))
24
+ throw refuse(`unknown type ${String(e.type)}`);
25
+ if (typeof e.occurredAt !== 'string' || Number.isNaN(Date.parse(e.occurredAt)))
26
+ throw refuse('occurredAt must be an ISO 8601 instant');
27
+ for (const k of ['amountGross', 'tax', 'fees', 'mrrDelta']) {
28
+ if (e[k] !== undefined && !Number.isInteger(e[k]))
29
+ throw refuse(`${k} must be an integer in minor units`);
30
+ }
31
+ if ((e.amountGross ?? 0) < 0)
32
+ throw refuse('amountGross must not be negative: send a refund to reverse a payment');
33
+ if (e.currency !== undefined && !Intl.supportedValuesOf('currency').includes(e.currency.toUpperCase())) {
34
+ throw refuse('currency must be an ISO 4217 code such as usd');
35
+ }
36
+ // shortcut: the server's default limit, since a connection's own isn't known here; it warns rather than refuses because the server holds these for release.
37
+ if ((e.type ?? 'invoice_paid') === 'invoice_paid' && approxUsdMinor(e.amountGross ?? 0, e.currency ?? 'usd') > 1_000_000_000)
38
+ console.warn(`createOutbox: event ${e.providerEventId}: amountGross ${e.amountGross} is over the default limit ($10M), so Referalli will hold it for release`);
39
+ const chargeRef = e.metadata?.chargeRef;
40
+ if (!e.customerRef && !((e.type === 'refund' || e.type === 'dispute') && (e.invoiceRef || chargeRef))) {
41
+ throw refuse('customerRef is required (a refund or dispute may send only invoiceRef or metadata.chargeRef)');
42
+ }
43
+ }
44
+ const SEND_TIMEOUT_MS = 60_000;
45
+ /** Longer than a send can take, so a live worker's claim never expires under it. */
46
+ const LEASE_MS = 5 * 60_000;
47
+ /**
48
+ * A durable queue for billing events, so an outage longer than the client's
49
+ * own retries does not lose a payment:
50
+ *
51
+ * const outbox = createOutbox({ store, connectionId: 'bcon_…', secret: process.env.REFERALLI_BILLING_SECRET });
52
+ * await outbox.enqueue({ providerEventId: invoice.id, type: 'invoice_paid', ... });
53
+ * void outbox.flush();
54
+ * setInterval(() => void outbox.flush(), 60_000);
55
+ *
56
+ * Every send carries the event's `providerEventId`, so a redelivery (two
57
+ * workers, a crash after sending) is recorded once.
58
+ */
59
+ function createOutbox(options) {
60
+ const { store, connectionId, secret } = options;
61
+ const now = options.now ?? Date.now;
62
+ const maxAttempts = options.maxAttempts ?? 50;
63
+ const baseDelay = options.baseDelayMs ?? 30_000;
64
+ const maxDelay = options.maxDelayMs ?? 3_600_000;
65
+ let client = options.client;
66
+ const api = () => (client ??= new client_js_1.Referalli());
67
+ const send = async (event) => {
68
+ if (!secret) {
69
+ // maxRetries 0: the outbox does the waiting, so a flush never blocks on backoff.
70
+ await api().billing.connections.events(connectionId, { events: [event] }, { idempotencyKey: `outbox:${connectionId}:${event.providerEventId}`, maxRetries: 0 });
71
+ return;
72
+ }
73
+ const body = JSON.stringify({ events: [event] });
74
+ const signature = toHex((0, sha256_js_1.hmacSha256)(new TextEncoder().encode(secret), new TextEncoder().encode(body)));
75
+ const base = (options.baseUrl ?? options.client?.baseUrl ?? client_js_1.DEFAULT_BASE_URL).replace(/\/+$/, '');
76
+ const res = await (options.fetch ?? ((url, init) => globalThis.fetch(url, init)))(`${base}/webhooks/billing/${encodeURIComponent(connectionId)}`, {
77
+ method: 'POST',
78
+ headers: { 'content-type': 'application/json', 'x-webhook-signature': signature },
79
+ body,
80
+ signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
81
+ });
82
+ if (!res.ok)
83
+ throw Object.assign(new Error(`POST /webhooks/billing/${connectionId} answered ${res.status}: ${(await res.text().catch(() => '')).slice(0, 500)}`), { status: res.status });
84
+ };
85
+ // Whole milliseconds: a fraction is refused by a bigint column.
86
+ const delay = (attempts) => Math.round(Math.min(baseDelay * 2 ** (attempts - 1), maxDelay) * (0.75 + Math.random() * 0.25));
87
+ const run = async (limit) => {
88
+ const result = { sent: 0, failed: 0, gaveUp: 0 };
89
+ const attempt = async (entry) => {
90
+ try {
91
+ await send(entry.event);
92
+ }
93
+ catch (err) {
94
+ // A paused connection, a rotated key or an outage can recover, so those retry up to maxAttempts.
95
+ // A refused event never will: resending the same bytes gets the same 400.
96
+ const attempts = entry.attempts + 1;
97
+ const status = err?.status;
98
+ const giveUp = attempts >= maxAttempts || status === 400 || status === 422;
99
+ const lastError = err instanceof Error ? err.message : String(err);
100
+ const nextAttemptAt = giveUp ? null : now() + delay(attempts);
101
+ await store.markFailed(entry.id, { attempts, nextAttemptAt, lastError });
102
+ if (!giveUp) {
103
+ result.failed++;
104
+ return;
105
+ }
106
+ result.gaveUp++;
107
+ try {
108
+ await options.onDead?.({ ...entry, attempts, nextAttemptAt, lastError });
109
+ }
110
+ catch {
111
+ // The entry is safe in the store; a broken reporter must not stop the flush.
112
+ }
113
+ return;
114
+ }
115
+ await store.markSent(entry.id);
116
+ result.sent++;
117
+ };
118
+ if (store.claim) {
119
+ // One at a time, so the lease only has to outlast one send rather than a whole batch.
120
+ for (let i = 0; i < limit; i++) {
121
+ const entry = await store.claim(now(), LEASE_MS);
122
+ if (!entry)
123
+ break;
124
+ await attempt(entry);
125
+ }
126
+ }
127
+ else {
128
+ for (const entry of await store.due(now(), limit))
129
+ await attempt(entry);
130
+ }
131
+ return result;
132
+ };
133
+ let running = null;
134
+ return {
135
+ async enqueue(event) {
136
+ if (!event?.providerEventId)
137
+ throw new TypeError('createOutbox: an event needs a providerEventId');
138
+ assertSendable(event);
139
+ await store.add({ id: event.providerEventId, event, attempts: 0, nextAttemptAt: now(), lastError: null });
140
+ },
141
+ flush({ limit = 100 } = {}) {
142
+ running ??= run(limit).finally(() => {
143
+ running = null;
144
+ });
145
+ return running;
146
+ },
147
+ };
148
+ }
149
+ /** An in-memory `OutboxStore`, for tests and scripts. It does not survive a restart. */
150
+ function memoryOutboxStore() {
151
+ const rows = new Map();
152
+ return {
153
+ async add(entry) {
154
+ if (!rows.has(entry.id))
155
+ rows.set(entry.id, { ...entry });
156
+ },
157
+ async due(at, limit) {
158
+ return [...rows.values()]
159
+ .filter((e) => e.nextAttemptAt !== null && e.nextAttemptAt <= at)
160
+ .sort((a, b) => a.nextAttemptAt - b.nextAttemptAt)
161
+ .slice(0, limit)
162
+ .map((e) => ({ ...e }));
163
+ },
164
+ async markSent(id) {
165
+ rows.delete(id);
166
+ },
167
+ async markFailed(id, u) {
168
+ const e = rows.get(id);
169
+ if (!e)
170
+ return;
171
+ Object.assign(e, u);
172
+ },
173
+ entries() {
174
+ return [...rows.values()].map((e) => ({ ...e }));
175
+ },
176
+ };
177
+ }
178
+ const fromRow = (r) => ({
179
+ id: r.id,
180
+ event: r.event,
181
+ attempts: r.attempts,
182
+ nextAttemptAt: r.next_attempt_at === null ? null : Number(r.next_attempt_at),
183
+ lastError: r.last_error,
184
+ });
185
+ /**
186
+ * An `OutboxStore` on a Postgres table, through your own query function, for
187
+ * several replicas:
188
+ *
189
+ * const store = pgOutboxStore({ query: (sql, params) => pool.query(sql, params), table: 'referalli_outbox' });
190
+ * await store.migrate();
191
+ *
192
+ * Columns: `id` text primary key (the providerEventId), `event` jsonb,
193
+ * `attempts` int, `next_attempt_at` bigint (epoch ms; null = dead),
194
+ * `last_error` text. A sent row is deleted; a dead row stays until you remove
195
+ * or requeue it (`store.dead()` lists them).
196
+ */
197
+ function pgOutboxStore(options) {
198
+ const { query, table: t } = options;
199
+ // It goes into the SQL text, so nothing but a plain identifier gets through.
200
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))
201
+ throw new TypeError(`pgOutboxStore: table must be a plain identifier, got ${JSON.stringify(t)}`);
202
+ const columns = 'id, event, attempts, next_attempt_at, last_error';
203
+ return {
204
+ async migrate() {
205
+ // One statement, so it runs in one transaction: the lock stops the catalog race between concurrent CREATE ... IF NOT EXISTS.
206
+ await query(`DO $$ BEGIN
207
+ PERFORM pg_advisory_xact_lock(hashtext('${t}'));
208
+ CREATE TABLE IF NOT EXISTS ${t} (
209
+ id text PRIMARY KEY,
210
+ event jsonb NOT NULL,
211
+ attempts int NOT NULL DEFAULT 0,
212
+ next_attempt_at bigint,
213
+ last_error text
214
+ );
215
+ CREATE INDEX IF NOT EXISTS ${t}_due_idx ON ${t} (next_attempt_at) WHERE next_attempt_at IS NOT NULL;
216
+ END $$`, []);
217
+ },
218
+ async add(e) {
219
+ // ::text first so every driver sends the JSON as text; a driver that sees a jsonb parameter may encode the string again.
220
+ await query(`INSERT INTO ${t} (${columns}) VALUES ($1, $2::text::jsonb, $3, $4, $5) ON CONFLICT (id) DO NOTHING`, [
221
+ e.id,
222
+ JSON.stringify(e.event),
223
+ e.attempts,
224
+ e.nextAttemptAt,
225
+ e.lastError,
226
+ ]);
227
+ },
228
+ async due(now, limit) {
229
+ const { rows } = await query(`SELECT ${columns} FROM ${t} WHERE next_attempt_at <= $1 ORDER BY next_attempt_at, id LIMIT $2`, [now, limit]);
230
+ return rows.map(fromRow);
231
+ },
232
+ async claim(now, leaseMs) {
233
+ // The lease is next_attempt_at itself: committed in the future, it hides the row from other workers and brings it back if this one dies.
234
+ const { rows } = await query(`WITH due AS (
235
+ SELECT id FROM ${t} WHERE next_attempt_at <= $1 ORDER BY next_attempt_at, id LIMIT 1 FOR UPDATE SKIP LOCKED
236
+ )
237
+ UPDATE ${t} SET next_attempt_at = $2 FROM due WHERE ${t}.id = due.id
238
+ RETURNING ${t}.id, ${t}.event, ${t}.attempts, ${t}.next_attempt_at, ${t}.last_error`, [now, now + leaseMs]);
239
+ return rows[0] ? fromRow(rows[0]) : null;
240
+ },
241
+ async markSent(id) {
242
+ await query(`DELETE FROM ${t} WHERE id = $1`, [id]);
243
+ },
244
+ async markFailed(id, u) {
245
+ await query(`UPDATE ${t} SET attempts = $2, next_attempt_at = $3, last_error = $4 WHERE id = $1`, [id, u.attempts, u.nextAttemptAt, u.lastError]);
246
+ },
247
+ async dead() {
248
+ const { rows } = await query(`SELECT ${columns} FROM ${t} WHERE next_attempt_at IS NULL ORDER BY id`, []);
249
+ return rows.map(fromRow);
250
+ },
251
+ };
252
+ }
253
+ const fromSqliteRow = (r) => ({
254
+ id: String(r.id),
255
+ event: typeof r.event === 'string' ? JSON.parse(r.event) : r.event,
256
+ attempts: Number(r.attempts),
257
+ nextAttemptAt: r.next_attempt_at === null || r.next_attempt_at === undefined ? null : Number(r.next_attempt_at),
258
+ lastError: r.last_error ?? null,
259
+ });
260
+ /**
261
+ * An `OutboxStore` on a SQLite or libSQL (Turso) table, through your own
262
+ * `execute` function, so the SDK adds no driver:
263
+ *
264
+ * // libSQL / Turso
265
+ * const store = sqliteOutboxStore({ execute: (sql, args) => client.execute({ sql, args: args as InArgs }), table: 'referalli_outbox' });
266
+ * // better-sqlite3 (synchronous)
267
+ * const store = sqliteOutboxStore({ execute: async (sql, p) => { const st = db.prepare(sql); return { rows: st.reader ? st.all(p) : (st.run(p), []) }; }, table: 'referalli_outbox' });
268
+ * await store.migrate();
269
+ *
270
+ * Columns: `id` TEXT primary key (the providerEventId), `event` TEXT (JSON),
271
+ * `attempts` INTEGER, `next_attempt_at` INTEGER (epoch ms; NULL = dead),
272
+ * `last_error` TEXT. A sent row is deleted. `claim` is one `UPDATE … RETURNING`
273
+ * statement (SQLite 3.35+), atomic because SQLite runs one writer at a time, so
274
+ * several processes on the same database each get a different row.
275
+ */
276
+ function sqliteOutboxStore(options) {
277
+ const { execute, table: t } = options;
278
+ // It goes into the SQL text, so nothing but a plain identifier gets through.
279
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))
280
+ throw new TypeError(`sqliteOutboxStore: table must be a plain identifier, got ${JSON.stringify(t)}`);
281
+ const columns = 'id, event, attempts, next_attempt_at, last_error';
282
+ const rows = async (sql, params) => (await execute(sql, params)).rows.map(fromSqliteRow);
283
+ return {
284
+ async migrate() {
285
+ await execute(`CREATE TABLE IF NOT EXISTS ${t} (id TEXT PRIMARY KEY, event TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0, next_attempt_at INTEGER, last_error TEXT)`, []);
286
+ await execute(`CREATE INDEX IF NOT EXISTS ${t}_due_idx ON ${t} (next_attempt_at) WHERE next_attempt_at IS NOT NULL`, []);
287
+ },
288
+ async add(e) {
289
+ await execute(`INSERT OR IGNORE INTO ${t} (${columns}) VALUES (?, ?, ?, ?, ?)`, [e.id, JSON.stringify(e.event), e.attempts, e.nextAttemptAt, e.lastError]);
290
+ },
291
+ async due(now, limit) {
292
+ return rows(`SELECT ${columns} FROM ${t} WHERE next_attempt_at <= ? ORDER BY next_attempt_at, id LIMIT ?`, [now, limit]);
293
+ },
294
+ async claim(now, leaseMs) {
295
+ // The lease is next_attempt_at itself: set in the future, it hides the row from other workers and brings it back if this one dies.
296
+ const [entry] = await rows(`UPDATE ${t} SET next_attempt_at = ? WHERE id = (SELECT id FROM ${t} WHERE next_attempt_at <= ? ORDER BY next_attempt_at, id LIMIT 1) RETURNING ${columns}`, [now + leaseMs, now]);
297
+ return entry ?? null;
298
+ },
299
+ async markSent(id) {
300
+ await execute(`DELETE FROM ${t} WHERE id = ?`, [id]);
301
+ },
302
+ async markFailed(id, u) {
303
+ await execute(`UPDATE ${t} SET attempts = ?, next_attempt_at = ?, last_error = ? WHERE id = ?`, [u.attempts, u.nextAttemptAt, u.lastError, id]);
304
+ },
305
+ async dead() {
306
+ return rows(`SELECT ${columns} FROM ${t} WHERE next_attempt_at IS NULL ORDER BY id`, []);
307
+ },
308
+ };
309
+ }
310
+ /**
311
+ * Type-checks a generic billing event and refuses `amountMinor`: the API
312
+ * ignores unknown fields, so that payment would be recorded as 0 and earn nothing.
313
+ */
314
+ function buildBillingEvent(event) {
315
+ if ('amountMinor' in event)
316
+ throw new TypeError('buildBillingEvent: billing events use amountGross (integer minor units), not amountMinor');
317
+ return event;
318
+ }
319
+ function toHex(bytes) {
320
+ let s = '';
321
+ for (const b of bytes)
322
+ s += b.toString(16).padStart(2, '0');
323
+ return s;
324
+ }
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }