@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,301 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Referalli = exports.DEFAULT_BASE_URL = void 0;
4
+ const core_js_1 = require("./core.js");
5
+ const errors_js_1 = require("./errors.js");
6
+ const errors_generated_js_1 = require("./errors.generated.js");
7
+ const resources_generated_js_1 = require("./resources.generated.js");
8
+ const version_js_1 = require("./version.js");
9
+ const OPTION_KEYS = new Set(['idempotencyKey', 'timeout', 'maxRetries', 'signal', 'headers', 'apiVersion']);
10
+ /** A method that gained a query parameter keeps its old `(id, options)` call working: request options in the query slot move back. */
11
+ function splitOptions(queryNames, input, options) {
12
+ const q = input.query;
13
+ if (!q || Object.keys(q).length === 0 || !Object.keys(q).every((k) => OPTION_KEYS.has(k) && !queryNames.includes(k)))
14
+ return { input, options };
15
+ return { input: { ...input, query: undefined }, options: { ...q, ...options } };
16
+ }
17
+ const webhooks_js_1 = require("./webhooks.js");
18
+ /** Production API. */
19
+ exports.DEFAULT_BASE_URL = 'https://referalli.com';
20
+ const RETRY_STATUSES = new Set([408, 429, 500, 502, 503, 504]);
21
+ const IDEMPOTENT = new Set(['GET', 'HEAD', 'PUT', 'DELETE', 'OPTIONS']);
22
+ const MAX_BACKOFF_MS = 8_000;
23
+ const MAX_RETRY_AFTER_MS = 60_000;
24
+ const env = (name) => {
25
+ try {
26
+ return globalThis.process?.env?.[name];
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ };
32
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
33
+ class Referalli {
34
+ baseUrl;
35
+ apiVersion;
36
+ mode;
37
+ timeout;
38
+ maxRetries;
39
+ retryBaseDelay;
40
+ /** Webhook verification (`await referalli.webhooks.constructEvent(body, headers, secret)`). */
41
+ webhooks = webhooks_js_1.webhooks;
42
+ apiKey;
43
+ fetchFn;
44
+ headers;
45
+ constructor(options = {}) {
46
+ this.apiKey = options.apiKey ?? env('REFERALLI_API_KEY');
47
+ this.baseUrl = (options.baseUrl ?? env('REFERALLI_BASE_URL') ?? exports.DEFAULT_BASE_URL).replace(/\/+$/, '');
48
+ this.apiVersion = options.apiVersion === undefined ? resources_generated_js_1.API_VERSION : options.apiVersion;
49
+ this.mode = options.mode;
50
+ this.timeout = options.timeout ?? 60_000;
51
+ this.maxRetries = Math.max(0, options.maxRetries ?? 2);
52
+ this.retryBaseDelay = options.retryBaseDelay ?? 500;
53
+ this.fetchFn = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
54
+ this.headers = { ...(options.headers ?? {}) };
55
+ const transport = {
56
+ op: (id, input, opts) => this.call(id, input, opts),
57
+ list: (id, input, opts) => this.listPages(id, input, opts),
58
+ };
59
+ Object.assign(this, (0, resources_generated_js_1.buildResources)(transport));
60
+ }
61
+ /** Call any operation by its id (`postPartners`, `getReferralsId`, … see `operations`). */
62
+ async call(id, input = {}, options = {}) {
63
+ const spec = resources_generated_js_1.operations[id];
64
+ if (!spec)
65
+ throw new errors_js_1.ReferalliError(`unknown operation ${String(id)}`);
66
+ ({ input, options } = splitOptions(spec.query, input, options));
67
+ const path = spec.path.replace(/\{(\w+)\}/g, (_, name) => {
68
+ const value = input.path?.[name];
69
+ if (value === undefined || value === null || value === '')
70
+ throw new errors_js_1.ReferalliError(`${id}: missing path parameter "${name}"`);
71
+ return encodeURIComponent(String(value));
72
+ });
73
+ return this.request({
74
+ ...options,
75
+ idempotencyKey: options.idempotencyKey ?? input.idempotencyKey,
76
+ method: spec.method,
77
+ path,
78
+ query: input.query,
79
+ body: spec.body ? input.body : undefined,
80
+ kind: spec.kind,
81
+ });
82
+ }
83
+ /** Every item of a list operation, following `next_cursor`: `for await (const p of referalli.listAll('getPartners'))`. */
84
+ listAll(id, input = {}, options = {}) {
85
+ return this.listPages(id, input, options);
86
+ }
87
+ listPages(id, input, options = {}) {
88
+ ({ input, options } = splitOptions(resources_generated_js_1.operations[id]?.query ?? [], input, options));
89
+ return new core_js_1.ListPromise((cursor) => this.call(id, cursor ? { ...input, query: { ...(input.query ?? {}), starting_after: cursor } } : input, options));
90
+ }
91
+ /** A raw request to any path (`/v1/...`), with the client's auth, retries and error mapping. */
92
+ async request(req) {
93
+ const method = req.method.toUpperCase();
94
+ const url = this.baseUrl + req.path + encodeQuery(req.query);
95
+ const version = req.apiVersion === undefined ? this.apiVersion : req.apiVersion;
96
+ const headers = { accept: 'application/json', ...this.headers };
97
+ if (version)
98
+ headers['referalli-version'] = version;
99
+ if (this.mode)
100
+ headers['referalli-mode'] = this.mode;
101
+ if (this.apiKey)
102
+ headers.authorization = `Bearer ${this.apiKey}`;
103
+ if (typeof globalThis.window === 'undefined')
104
+ headers['user-agent'] = `referalli-js/${version_js_1.SDK_VERSION}`;
105
+ const hasBody = req.body !== undefined;
106
+ if (hasBody)
107
+ headers['content-type'] = 'application/json';
108
+ const key = req.idempotencyKey ?? (method === 'POST' ? await newIdempotencyKey() : undefined);
109
+ if (key)
110
+ headers['idempotency-key'] = key;
111
+ Object.assign(headers, req.headers ?? {});
112
+ const body = hasBody ? JSON.stringify(req.body) : undefined;
113
+ const retryable = IDEMPOTENT.has(method) || Boolean(key);
114
+ const maxRetries = retryable ? Math.max(0, req.maxRetries ?? this.maxRetries) : 0;
115
+ const timeout = req.timeout ?? this.timeout;
116
+ for (let attempt = 0;; attempt++) {
117
+ let res;
118
+ const { signal, cancel, timedOut } = withTimeout(timeout, req.signal);
119
+ try {
120
+ res = await this.fetchFn(url, { method, headers, body, signal });
121
+ }
122
+ catch (err) {
123
+ cancel();
124
+ if (req.signal?.aborted)
125
+ throw req.signal.reason ?? err;
126
+ if (attempt < maxRetries) {
127
+ await sleep(this.backoff(attempt), req.signal);
128
+ continue;
129
+ }
130
+ if (timedOut())
131
+ throw new errors_js_1.ApiTimeoutError(`${method} ${req.path} timed out after ${timeout} ms`, { cause: err });
132
+ throw new errors_js_1.ApiConnectionError(`${method} ${req.path} failed: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
133
+ }
134
+ try {
135
+ if (res.ok) {
136
+ if (req.kind === 'text')
137
+ return (await res.text());
138
+ const raw = await res.text();
139
+ if (req.kind === 'empty' || raw === '')
140
+ return undefined;
141
+ return JSON.parse(raw);
142
+ }
143
+ const raw = await res.text().catch(() => '');
144
+ const resHeaders = headerRecord(res.headers);
145
+ const retryAfterMs = parseRetryAfter(resHeaders);
146
+ if (RETRY_STATUSES.has(res.status) && attempt < maxRetries && resHeaders['x-should-retry'] !== 'false') {
147
+ await sleep(retryAfterMs ?? this.backoff(attempt), req.signal);
148
+ continue;
149
+ }
150
+ throw toApiError(res.status, raw, resHeaders, retryAfterMs);
151
+ }
152
+ catch (err) {
153
+ if (err instanceof errors_js_1.ReferalliError || req.signal?.aborted)
154
+ throw err;
155
+ if (timedOut()) {
156
+ if (attempt < maxRetries)
157
+ continue;
158
+ throw new errors_js_1.ApiTimeoutError(`${method} ${req.path} timed out after ${timeout} ms`, { cause: err });
159
+ }
160
+ throw new errors_js_1.ApiConnectionError(`${method} ${req.path}: could not read the response`, { cause: err });
161
+ }
162
+ finally {
163
+ cancel();
164
+ }
165
+ }
166
+ }
167
+ backoff(attempt) {
168
+ const base = Math.min(this.retryBaseDelay * 2 ** attempt, MAX_BACKOFF_MS);
169
+ return base * (0.75 + Math.random() * 0.25);
170
+ }
171
+ // --- Helpers kept from the hand-written SDK -----------------------------------------
172
+ /** Attribute a new customer to the partner who referred them: the key server-side call at signup. */
173
+ associate(body, options) {
174
+ return this.referrals.associate(body, { idempotencyKey: body.idempotencyKey, ...options });
175
+ }
176
+ /** Report a customer's product event (`activation` or a custom name) that can pay a bounty. */
177
+ trackEvent(body, options) {
178
+ return this.track.events({ type: 'event', ...body }, { idempotencyKey: body.idempotencyKey, ...options });
179
+ }
180
+ /** Report value facts (payments, credit, costs). Up to 500 per call, each idempotent by `externalId`. */
181
+ reportValueEvents(events, options) {
182
+ return this.value.events({ events }, options);
183
+ }
184
+ /** A payment, with the cash received and any store credit or discount that paid part of it. */
185
+ reportPayment(input, options) {
186
+ return this.reportValueEvents([{ ...input, kind: 'payment' }], options);
187
+ }
188
+ }
189
+ exports.Referalli = Referalli;
190
+ function encodeQuery(query) {
191
+ if (!query)
192
+ return '';
193
+ const qs = new URLSearchParams();
194
+ for (const [k, v] of Object.entries(query)) {
195
+ if (v === undefined || v === null)
196
+ continue;
197
+ if (Array.isArray(v))
198
+ for (const x of v)
199
+ qs.append(k, String(x));
200
+ else
201
+ qs.append(k, v instanceof Date ? v.toISOString() : String(v));
202
+ }
203
+ const s = qs.toString();
204
+ return s ? `?${s}` : '';
205
+ }
206
+ function headerRecord(h) {
207
+ const out = {};
208
+ h.forEach((v, k) => (out[k.toLowerCase()] = v));
209
+ return out;
210
+ }
211
+ /** Milliseconds from `retry-after-ms` / `retry-after` (seconds or an HTTP date), capped at 60 s. */
212
+ function parseRetryAfter(h) {
213
+ const ms = Number(h['retry-after-ms']);
214
+ if (h['retry-after-ms'] && Number.isFinite(ms))
215
+ return Math.min(Math.max(0, ms), MAX_RETRY_AFTER_MS);
216
+ const v = h['retry-after'];
217
+ if (!v)
218
+ return null;
219
+ const secs = Number(v);
220
+ if (Number.isFinite(secs))
221
+ return Math.min(Math.max(0, secs * 1000), MAX_RETRY_AFTER_MS);
222
+ const at = Date.parse(v);
223
+ return Number.isNaN(at) ? null : Math.min(Math.max(0, at - Date.now()), MAX_RETRY_AFTER_MS);
224
+ }
225
+ function toApiError(status, raw, headers, retryAfterMs) {
226
+ let err = {};
227
+ try {
228
+ const parsed = JSON.parse(raw);
229
+ if (parsed && typeof parsed.error === 'object' && parsed.error)
230
+ err = parsed.error;
231
+ }
232
+ catch {
233
+ /* not JSON */
234
+ }
235
+ const code = typeof err.code === 'string' && err.code ? err.code : 'http_error';
236
+ const Cls = errors_generated_js_1.errorClasses[code] ?? errors_js_1.ApiError;
237
+ return new Cls({
238
+ status,
239
+ code,
240
+ message: typeof err.message === 'string' ? err.message : raw.slice(0, 500) || `HTTP ${status}`,
241
+ requestId: (typeof err.requestId === 'string' ? err.requestId : undefined) ?? headers['x-request-id'] ?? null,
242
+ docsUrl: typeof err.docs_url === 'string' ? err.docs_url : null,
243
+ details: err.details,
244
+ retryAfter: retryAfterMs === null ? null : retryAfterMs / 1000,
245
+ headers,
246
+ });
247
+ }
248
+ /** An AbortSignal that fires on `timeout` ms or when `parent` aborts (no `AbortSignal.any`: Node 18). */
249
+ function withTimeout(timeout, parent) {
250
+ const controller = new AbortController();
251
+ let fired = false;
252
+ const timer = timeout > 0 && Number.isFinite(timeout) ? setTimeout(() => ((fired = true), controller.abort()), timeout) : undefined;
253
+ const onAbort = () => controller.abort(parent?.reason);
254
+ if (parent) {
255
+ if (parent.aborted)
256
+ controller.abort(parent.reason);
257
+ else
258
+ parent.addEventListener('abort', onAbort, { once: true });
259
+ }
260
+ return {
261
+ signal: controller.signal,
262
+ cancel: () => {
263
+ if (timer)
264
+ clearTimeout(timer);
265
+ parent?.removeEventListener('abort', onAbort);
266
+ },
267
+ timedOut: () => fired,
268
+ };
269
+ }
270
+ function sleep(ms, signal) {
271
+ return new Promise((resolve, reject) => {
272
+ if (signal?.aborted)
273
+ return reject(signal.reason);
274
+ const t = setTimeout(() => {
275
+ signal?.removeEventListener('abort', onAbort);
276
+ resolve();
277
+ }, ms);
278
+ const onAbort = () => {
279
+ clearTimeout(t);
280
+ reject(signal?.reason);
281
+ };
282
+ signal?.addEventListener('abort', onAbort, { once: true });
283
+ });
284
+ }
285
+ async function newIdempotencyKey() {
286
+ const c = globalThis.crypto;
287
+ if (c?.randomUUID)
288
+ return c.randomUUID();
289
+ let bytes = new Uint8Array(16);
290
+ if (c?.getRandomValues)
291
+ c.getRandomValues(bytes);
292
+ else {
293
+ const mod = 'node:crypto';
294
+ const nodeCrypto = (await Promise.resolve(`${mod}`).then(s => require(s)));
295
+ bytes = new Uint8Array(nodeCrypto.randomBytes(16));
296
+ }
297
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
298
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
299
+ const hex = [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');
300
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
301
+ }
@@ -0,0 +1,7 @@
1
+ import { type ConsentSource } from '../port.js';
2
+ /**
3
+ * Cookiebot: `Cookiebot.consent.<category>`, `Cookiebot.hasResponse` and the
4
+ * `CookiebotOnConsentReady` / `OnAccept` / `OnDecline` window events.
5
+ * Category `marketing` by default; `consentID` is the evidence stamp.
6
+ */
7
+ export declare const cookiebot: ConsentSource;
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.cookiebot = void 0;
4
+ const port_js_1 = require("../port.js");
5
+ /**
6
+ * Cookiebot: `Cookiebot.consent.<category>`, `Cookiebot.hasResponse` and the
7
+ * `CookiebotOnConsentReady` / `OnAccept` / `OnDecline` window events.
8
+ * Category `marketing` by default; `consentID` is the evidence stamp.
9
+ */
10
+ exports.cookiebot = {
11
+ id: 'cookiebot',
12
+ name: 'Cookiebot',
13
+ defaultCategory: 'marketing',
14
+ status: 'ga',
15
+ docsUrl: 'https://referalli.com/docs/tracking-consent#cookiebot',
16
+ vendorDocsUrl: 'https://www.cookiebot.com/en/developer/',
17
+ check: (cfg) => (0, port_js_1.browserCheck)(exports.cookiebot, cfg),
18
+ factory: function cookiebotConsent(w) {
19
+ const EVENTS = ['CookiebotOnConsentReady', 'CookiebotOnAccept', 'CookiebotOnDecline', 'CookiebotOnLoad'];
20
+ return {
21
+ detect() {
22
+ if (w.Cookiebot)
23
+ return true;
24
+ const d = w.document;
25
+ return !!(d && typeof d.getElementById === 'function' && d.getElementById('Cookiebot'));
26
+ },
27
+ state(cfg) {
28
+ const cb = w.Cookiebot;
29
+ if (!cb || !cb.consent)
30
+ return 'unknown';
31
+ if (cb.consent[cfg.category || 'marketing'] === true)
32
+ return 'granted';
33
+ return cb.hasResponse ? 'denied' : 'unknown';
34
+ },
35
+ subscribe(_cfg, cb) {
36
+ for (let i = 0; i < EVENTS.length; i++)
37
+ w.addEventListener(EVENTS[i], cb);
38
+ return function () {
39
+ for (let i = 0; i < EVENTS.length; i++)
40
+ w.removeEventListener(EVENTS[i], cb);
41
+ };
42
+ },
43
+ evidence() {
44
+ const c = w.Cookiebot;
45
+ return c && c.consentID ? { stamp: String(c.consentID) } : {};
46
+ },
47
+ };
48
+ },
49
+ };
@@ -0,0 +1,8 @@
1
+ import { type ConsentSource } from '../port.js';
2
+ /**
3
+ * Cookie Munch: `window.CookieMunch.{hasResponse, consent}` and the
4
+ * `CookieMunchOnChange` window event (Cookie Munch guide R4: read the
5
+ * snapshot, never the event payload). Category `referrals`, falling back to
6
+ * `marketing` when the site declares no `referrals` category.
7
+ */
8
+ export declare const cookiemunch: ConsentSource;
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.cookiemunch = void 0;
4
+ const port_js_1 = require("../port.js");
5
+ /**
6
+ * Cookie Munch: `window.CookieMunch.{hasResponse, consent}` and the
7
+ * `CookieMunchOnChange` window event (Cookie Munch guide R4: read the
8
+ * snapshot, never the event payload). Category `referrals`, falling back to
9
+ * `marketing` when the site declares no `referrals` category.
10
+ */
11
+ exports.cookiemunch = {
12
+ id: 'cookiemunch',
13
+ name: 'Cookie Munch',
14
+ defaultCategory: 'referrals',
15
+ status: 'ga',
16
+ docsUrl: 'https://referalli.com/docs/tracking-consent#cookie-munch',
17
+ vendorDocsUrl: 'https://cookiemunch.net/docs',
18
+ check: (cfg) => (0, port_js_1.browserCheck)(exports.cookiemunch, cfg),
19
+ factory: function cookiemunchConsent(w) {
20
+ return {
21
+ detect() {
22
+ if (w.CookieMunch)
23
+ return true;
24
+ const d = w.document;
25
+ return !!(d && typeof d.getElementById === 'function' && d.getElementById('CookieMunch'));
26
+ },
27
+ state(cfg) {
28
+ const cm = w.CookieMunch;
29
+ if (!cm || !cm.hasResponse)
30
+ return 'unknown';
31
+ const consent = cm.consent || {};
32
+ let v = consent[cfg.category || 'referrals'];
33
+ if (typeof v !== 'boolean' && !cfg.category)
34
+ v = consent.marketing;
35
+ return v === true ? 'granted' : 'denied';
36
+ },
37
+ subscribe(_cfg, cb) {
38
+ w.addEventListener('CookieMunchOnChange', cb);
39
+ w.addEventListener('CookieMunchOnLoad', cb);
40
+ return function () {
41
+ w.removeEventListener('CookieMunchOnChange', cb);
42
+ w.removeEventListener('CookieMunchOnLoad', cb);
43
+ };
44
+ },
45
+ evidence() {
46
+ const cm = w.CookieMunch;
47
+ let stamp = null;
48
+ if (cm && typeof cm.consentId === 'function')
49
+ stamp = cm.consentId();
50
+ else if (cm && cm.consent && cm.consent.stamp)
51
+ stamp = cm.consent.stamp;
52
+ return stamp ? { stamp: String(stamp) } : {};
53
+ },
54
+ };
55
+ },
56
+ };
@@ -0,0 +1,8 @@
1
+ import { type ConsentSource } from '../port.js';
2
+ /**
3
+ * The contract for any CMP we don't cover: define `window.referalliConsent()`
4
+ * returning `true` (granted), `false` (denied) or `null` (no decision yet),
5
+ * and dispatch a `referalli:consent` window event when it changes. The push
6
+ * path (`aff.consent(true|false)`) needs no adapter at all.
7
+ */
8
+ export declare const custom: ConsentSource;
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.custom = void 0;
4
+ const port_js_1 = require("../port.js");
5
+ /**
6
+ * The contract for any CMP we don't cover: define `window.referalliConsent()`
7
+ * returning `true` (granted), `false` (denied) or `null` (no decision yet),
8
+ * and dispatch a `referalli:consent` window event when it changes. The push
9
+ * path (`aff.consent(true|false)`) needs no adapter at all.
10
+ */
11
+ exports.custom = {
12
+ id: 'custom',
13
+ name: 'Custom (window.referalliConsent)',
14
+ defaultCategory: null,
15
+ status: 'ga',
16
+ docsUrl: 'https://referalli.com/docs/tracking-consent#custom',
17
+ vendorDocsUrl: 'https://referalli.com/docs/tracking-consent#custom',
18
+ check: (cfg) => (0, port_js_1.browserCheck)(exports.custom, cfg),
19
+ factory: function customConsent(w) {
20
+ return {
21
+ detect() {
22
+ return typeof w.referalliConsent === 'function';
23
+ },
24
+ state() {
25
+ const v = w.referalliConsent();
26
+ return v === true ? 'granted' : v === false ? 'denied' : 'unknown';
27
+ },
28
+ subscribe(_cfg, cb) {
29
+ w.addEventListener('referalli:consent', cb);
30
+ return function () {
31
+ w.removeEventListener('referalli:consent', cb);
32
+ };
33
+ },
34
+ evidence() {
35
+ return {};
36
+ },
37
+ };
38
+ },
39
+ };
@@ -0,0 +1,9 @@
1
+ import { type ConsentSource } from '../port.js';
2
+ /**
3
+ * Didomi: `Didomi.getUserStatus()` (purposes and vendors, each with
4
+ * `global.enabled`), `didomiOnReady` and the `consent.changed` event via
5
+ * `didomiEventListeners`. `category` is a purpose id (default `cookies`), or a
6
+ * vendor id when it contains a colon (`c:referalli-…`) or is numeric (IAB).
7
+ * Not enabled counts as denied only once `shouldConsentBeCollected()` is false.
8
+ */
9
+ export declare const didomi: ConsentSource;
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.didomi = void 0;
4
+ const port_js_1 = require("../port.js");
5
+ /**
6
+ * Didomi: `Didomi.getUserStatus()` (purposes and vendors, each with
7
+ * `global.enabled`), `didomiOnReady` and the `consent.changed` event via
8
+ * `didomiEventListeners`. `category` is a purpose id (default `cookies`), or a
9
+ * vendor id when it contains a colon (`c:referalli-…`) or is numeric (IAB).
10
+ * Not enabled counts as denied only once `shouldConsentBeCollected()` is false.
11
+ */
12
+ exports.didomi = {
13
+ id: 'didomi',
14
+ name: 'Didomi',
15
+ defaultCategory: 'cookies',
16
+ status: 'beta',
17
+ docsUrl: 'https://referalli.com/docs/tracking-consent#didomi',
18
+ vendorDocsUrl: 'https://developers.didomi.io/',
19
+ check: (cfg) => (0, port_js_1.browserCheck)(exports.didomi, cfg),
20
+ factory: function didomiConsent(w) {
21
+ return {
22
+ detect() {
23
+ return !!(w.Didomi || w.didomiOnReady || w.didomiConfig);
24
+ },
25
+ state(cfg) {
26
+ const d = w.Didomi;
27
+ if (!d || typeof d.getUserStatus !== 'function')
28
+ return 'unknown';
29
+ if (typeof d.isConsentRequired === 'function' && d.isConsentRequired() === false)
30
+ return 'granted';
31
+ const cat = String(cfg.category || 'cookies');
32
+ const vendor = cat.indexOf(':') >= 0 || /^\d+$/.test(cat);
33
+ const st = d.getUserStatus() || {};
34
+ const set = vendor ? st.vendors : st.purposes;
35
+ const enabled = (set && set.global && set.global.enabled) || [];
36
+ for (let i = 0; i < enabled.length; i++)
37
+ if (String(enabled[i]) === cat)
38
+ return 'granted';
39
+ if (typeof d.shouldConsentBeCollected === 'function' && d.shouldConsentBeCollected())
40
+ return 'unknown';
41
+ return 'denied';
42
+ },
43
+ subscribe(_cfg, cb) {
44
+ let off = false;
45
+ const fire = function () {
46
+ if (!off)
47
+ cb();
48
+ };
49
+ w.didomiEventListeners = w.didomiEventListeners || [];
50
+ w.didomiEventListeners.push({ event: 'consent.changed', listener: fire });
51
+ w.didomiOnReady = w.didomiOnReady || [];
52
+ w.didomiOnReady.push(fire);
53
+ return function () {
54
+ off = true;
55
+ };
56
+ },
57
+ evidence() {
58
+ const d = w.Didomi;
59
+ const st = d && typeof d.getUserStatus === 'function' ? d.getUserStatus() || {} : {};
60
+ return {
61
+ ...(st.user_id ? { stamp: String(st.user_id) } : {}),
62
+ ...(typeof st.consent_string === 'string' && st.consent_string ? { tcString: st.consent_string } : {}),
63
+ };
64
+ },
65
+ };
66
+ },
67
+ };
@@ -0,0 +1,10 @@
1
+ import { type ConsentSource } from '../port.js';
2
+ /**
3
+ * Google Consent Mode v2: `gtag('consent', 'default' | 'update', {...})`
4
+ * commands in `window.dataLayer`, following `ad_storage` (or
5
+ * `analytics_storage` via `gcmSignal`). An `update` decides. A default of
6
+ * `granted` everywhere grants; a `denied` default (often region-scoped) with
7
+ * no update yet is no decision. gtag.js replaces `dataLayer.push`, so changes
8
+ * are picked up by watching the queue (every 250 ms).
9
+ */
10
+ export declare const gcm: ConsentSource;
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.gcm = void 0;
4
+ const port_js_1 = require("../port.js");
5
+ /**
6
+ * Google Consent Mode v2: `gtag('consent', 'default' | 'update', {...})`
7
+ * commands in `window.dataLayer`, following `ad_storage` (or
8
+ * `analytics_storage` via `gcmSignal`). An `update` decides. A default of
9
+ * `granted` everywhere grants; a `denied` default (often region-scoped) with
10
+ * no update yet is no decision. gtag.js replaces `dataLayer.push`, so changes
11
+ * are picked up by watching the queue (every 250 ms).
12
+ */
13
+ exports.gcm = {
14
+ id: 'gcm',
15
+ name: 'Google Consent Mode v2',
16
+ defaultCategory: 'ad_storage',
17
+ status: 'ga',
18
+ docsUrl: 'https://referalli.com/docs/tracking-consent#google-consent-mode',
19
+ vendorDocsUrl: 'https://developers.google.com/tag-platform/security/guides/consent',
20
+ check: (cfg) => (0, port_js_1.browserCheck)(exports.gcm, cfg),
21
+ factory: function gcmConsent(w) {
22
+ function cmd(e) {
23
+ return !!(e && typeof e === 'object' && e[0] === 'consent' && (e[1] === 'default' || e[1] === 'update') && e[2] && typeof e[2] === 'object');
24
+ }
25
+ function queue() {
26
+ const dl = w.dataLayer;
27
+ return dl && typeof dl.length === 'number' ? dl : [];
28
+ }
29
+ return {
30
+ detect() {
31
+ const dl = queue();
32
+ for (let i = 0; i < dl.length; i++)
33
+ if (cmd(dl[i]))
34
+ return true;
35
+ return false;
36
+ },
37
+ state(cfg) {
38
+ const sig = cfg.gcmSignal || 'ad_storage';
39
+ const dl = queue();
40
+ let update = null;
41
+ let anyDenied = false;
42
+ let anyGranted = false;
43
+ for (let i = 0; i < dl.length; i++) {
44
+ const e = dl[i];
45
+ if (!cmd(e) || typeof e[2][sig] !== 'string')
46
+ continue;
47
+ if (e[1] === 'update')
48
+ update = e[2][sig];
49
+ else if (e[2][sig] === 'granted')
50
+ anyGranted = true;
51
+ else
52
+ anyDenied = true;
53
+ }
54
+ if (update !== null)
55
+ return update === 'granted' ? 'granted' : 'denied';
56
+ if (anyGranted && !anyDenied)
57
+ return 'granted';
58
+ return 'unknown';
59
+ },
60
+ subscribe(_cfg, cb) {
61
+ let n = queue().length;
62
+ const t = w.setInterval(function () {
63
+ const l = queue().length;
64
+ if (l !== n) {
65
+ n = l;
66
+ cb();
67
+ }
68
+ }, 250);
69
+ return function () {
70
+ w.clearInterval(t);
71
+ };
72
+ },
73
+ evidence(cfg) {
74
+ return { purposes: [cfg.gcmSignal || 'ad_storage'] };
75
+ },
76
+ };
77
+ },
78
+ };
@@ -0,0 +1,9 @@
1
+ import { type ConsentSource } from '../port.js';
2
+ /**
3
+ * IAB GPP: `__gpp('addEventListener', cb)` and `__gpp('ping', cb)`. Waits for
4
+ * `signalStatus: 'ready'`. The EU TCF section (id 2) follows the `tcf`
5
+ * rules (purpose 1 plus 7 or 9); US state sections are opt-out, so any
6
+ * `SaleOptOut`, `SharingOptOut` or `TargetedAdvertisingOptOut` of 1 (opted
7
+ * out) denies and anything else grants. Evidence: `gppString`.
8
+ */
9
+ export declare const gpp: ConsentSource;