@referalli/sdk 0.0.0-stage → 0.3.20

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 +128 -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 +15146 -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 +15146 -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 +14540 -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,67 @@
1
+ import { browserCheck, type ConsentSource } from '../port.js';
2
+
3
+ /**
4
+ * IAB TCF v2.2: `__tcfapi('addEventListener', 2, cb)`. Granted when purpose 1
5
+ * (store/access) and purpose 7 or 9 are consented (publisher or global
6
+ * purpose consent), or, when `tcfVendorId` is set, purpose 1 plus that
7
+ * vendor's consent. `gdprApplies: false` is granted. Evidence: `tcString`.
8
+ */
9
+ export const tcf: ConsentSource = {
10
+ id: 'tcf',
11
+ name: 'IAB TCF v2.2',
12
+ defaultCategory: 'purposes 1 + 7/9',
13
+ status: 'ga',
14
+ docsUrl: 'https://referalli.com/docs/tracking-consent#tcf',
15
+ vendorDocsUrl: 'https://github.com/InteractiveAdvertisingBureau/GDPR-Transparency-and-Consent-Framework',
16
+ check: (cfg) => browserCheck(tcf, cfg),
17
+ factory: function tcfConsent(w: any) {
18
+ let data: any = null;
19
+ let listening = false;
20
+ const subs: Array<() => void> = [];
21
+ function listen(): void {
22
+ if (listening || typeof w.__tcfapi !== 'function') return;
23
+ listening = true;
24
+ w.__tcfapi('addEventListener', 2, function (tc: any, ok: boolean) {
25
+ if (ok === false || !tc) return;
26
+ data = tc;
27
+ const list = subs.slice();
28
+ for (let i = 0; i < list.length; i++) (list[i] as () => void)();
29
+ });
30
+ }
31
+ function has(n: number): boolean {
32
+ const pur = (data && data.purpose && data.purpose.consents) || {};
33
+ const pub = (data && data.publisher && data.publisher.consents) || {};
34
+ return !!(pur[n] || pub[n]);
35
+ }
36
+ return {
37
+ detect(): boolean {
38
+ return typeof w.__tcfapi === 'function';
39
+ },
40
+ state(cfg) {
41
+ listen();
42
+ if (!data) return 'unknown';
43
+ if (data.gdprApplies === false) return 'granted';
44
+ if (data.eventStatus !== 'tcloaded' && data.eventStatus !== 'useractioncomplete') return 'unknown';
45
+ if (cfg.tcfVendorId) {
46
+ const vc = (data.vendor && data.vendor.consents) || {};
47
+ return has(1) && vc[cfg.tcfVendorId] ? 'granted' : 'denied';
48
+ }
49
+ return has(1) && (has(7) || has(9)) ? 'granted' : 'denied';
50
+ },
51
+ subscribe(_cfg, cb) {
52
+ subs.push(cb);
53
+ listen();
54
+ return function () {
55
+ const i = subs.indexOf(cb);
56
+ if (i >= 0) subs.splice(i, 1);
57
+ };
58
+ },
59
+ evidence() {
60
+ if (!data) return null;
61
+ const purposes: string[] = [];
62
+ for (let n = 1; n <= 11; n++) if (has(n)) purposes.push(String(n));
63
+ return { tcString: typeof data.tcString === 'string' ? data.tcString : undefined, purposes };
64
+ },
65
+ };
66
+ },
67
+ };
@@ -0,0 +1,54 @@
1
+ import { browserCheck, type ConsentSource } from '../port.js';
2
+
3
+ /**
4
+ * Termly: `Termly.getConsentState()` (`{ advertising: true, … }`) and
5
+ * `Termly.on('consent' | 'initialized', cb)`. Category `advertising` by
6
+ * default. A category that isn't true counts as denied only after a consent
7
+ * event on this page, so a returning visitor who declined stays memory-only
8
+ * (never stored) rather than being read as granted. Shape per Termly's
9
+ * consent API docs; not yet checked against a live Termly site.
10
+ */
11
+ export const termly: ConsentSource = {
12
+ id: 'termly',
13
+ name: 'Termly',
14
+ defaultCategory: 'advertising',
15
+ status: 'beta',
16
+ docsUrl: 'https://referalli.com/docs/tracking-consent#termly',
17
+ vendorDocsUrl: 'https://termly.io/',
18
+ check: (cfg) => browserCheck(termly, cfg),
19
+ factory: function termlyConsent(w: any) {
20
+ let decided = false;
21
+ return {
22
+ detect(): boolean {
23
+ return !!w.Termly;
24
+ },
25
+ state(cfg) {
26
+ const t = w.Termly;
27
+ if (!t || typeof t.getConsentState !== 'function') return 'unknown';
28
+ const s = t.getConsentState();
29
+ if (!s || typeof s !== 'object') return 'unknown';
30
+ if (s[cfg.category || 'advertising'] === true) return 'granted';
31
+ return decided ? 'denied' : 'unknown';
32
+ },
33
+ subscribe(_cfg, cb) {
34
+ let off = false;
35
+ const t = w.Termly;
36
+ if (t && typeof t.on === 'function') {
37
+ t.on('consent', function () {
38
+ decided = true;
39
+ if (!off) cb();
40
+ });
41
+ t.on('initialized', function () {
42
+ if (!off) cb();
43
+ });
44
+ }
45
+ return function () {
46
+ off = true;
47
+ };
48
+ },
49
+ evidence(cfg) {
50
+ return { purposes: [cfg.category || 'advertising'] };
51
+ },
52
+ };
53
+ },
54
+ };
@@ -0,0 +1,97 @@
1
+ import { browserCheck, type ConsentSource } from '../port.js';
2
+
3
+ /**
4
+ * Usercentrics: v2 `UC_UI.getServicesBaseInfo()` (services with
5
+ * `consent.status` and `categorySlug`) and v3 `__ucCmp.getConsentDetails()`
6
+ * (async; cached and refreshed on each event). `category` matches a service
7
+ * name (add a "Referalli" service and set it) or a category slug; default
8
+ * `marketing`. Events: `UC_UI_CMP_EVENT`, `UC_UI_INITIALIZED`, `UC_CONSENT`.
9
+ */
10
+ export const usercentrics: ConsentSource = {
11
+ id: 'usercentrics',
12
+ name: 'Usercentrics',
13
+ defaultCategory: 'marketing',
14
+ status: 'beta',
15
+ docsUrl: 'https://referalli.com/docs/tracking-consent#usercentrics',
16
+ vendorDocsUrl: 'https://docs.usercentrics.com/',
17
+ check: (cfg) => browserCheck(usercentrics, cfg),
18
+ factory: function usercentricsConsent(w: any) {
19
+ const EVENTS = ['UC_UI_CMP_EVENT', 'UC_UI_INITIALIZED', 'UC_CONSENT', 'UC_UI_VIEW_CHANGED'];
20
+ let v3: any = null;
21
+ function refresh(done: () => void): void {
22
+ const api = w.__ucCmp;
23
+ if (!api || typeof api.getConsentDetails !== 'function') {
24
+ done();
25
+ return;
26
+ }
27
+ try {
28
+ Promise.resolve(api.getConsentDetails()).then(
29
+ function (d: any) {
30
+ v3 = d || null;
31
+ done();
32
+ },
33
+ function () {
34
+ done();
35
+ },
36
+ );
37
+ } catch {
38
+ done();
39
+ }
40
+ }
41
+ return {
42
+ detect(): boolean {
43
+ if (w.UC_UI || w.__ucCmp) return true;
44
+ const d = w.document;
45
+ return !!(d && typeof d.getElementById === 'function' && d.getElementById('usercentrics-cmp'));
46
+ },
47
+ state(cfg) {
48
+ const cat = cfg.category || 'marketing';
49
+ const ui = w.UC_UI;
50
+ if (ui && typeof ui.getServicesBaseInfo === 'function') {
51
+ if (typeof ui.isInitialized === 'function' && !ui.isInitialized()) return 'unknown';
52
+ const list: any[] = ui.getServicesBaseInfo() || [];
53
+ const hit = list.filter(function (s) {
54
+ return s && (s.name === cat || s.categorySlug === cat);
55
+ });
56
+ if (!hit.length) return 'unknown';
57
+ if (
58
+ hit.every(function (s) {
59
+ return s.consent && s.consent.status === true;
60
+ })
61
+ )
62
+ return 'granted';
63
+ if (typeof ui.isConsentRequired === 'function' && ui.isConsentRequired()) return 'unknown';
64
+ return 'denied';
65
+ }
66
+ if (!v3) return 'unknown';
67
+ const services = v3.services || {};
68
+ for (const k in services) {
69
+ const s = services[k];
70
+ if (s && s.name === cat) return s.consent && s.consent.given === true ? 'granted' : v3.consent && v3.consent.required ? 'unknown' : 'denied';
71
+ }
72
+ const c = v3.categories && v3.categories[cat];
73
+ if (c && c.state === 'ALL_ACCEPTED') return 'granted';
74
+ if (v3.consent && v3.consent.required) return 'unknown';
75
+ return c ? 'denied' : 'unknown';
76
+ },
77
+ subscribe(_cfg, cb) {
78
+ let off = false;
79
+ const fire = function () {
80
+ refresh(function () {
81
+ if (!off) cb();
82
+ });
83
+ };
84
+ for (let i = 0; i < EVENTS.length; i++) w.addEventListener(EVENTS[i], fire);
85
+ fire();
86
+ return function () {
87
+ off = true;
88
+ for (let i = 0; i < EVENTS.length; i++) w.removeEventListener(EVENTS[i], fire);
89
+ };
90
+ },
91
+ evidence() {
92
+ const id = v3 && v3.consent && v3.consent.controllerId;
93
+ return id ? { stamp: String(id) } : {};
94
+ },
95
+ };
96
+ },
97
+ };
@@ -0,0 +1,47 @@
1
+ import type { ConsentSource } from './port.js';
2
+
3
+ /** The vitest functions, passed in so this module never imports a test runner at runtime. */
4
+ export interface TestApi {
5
+ describe: (name: string, fn: () => void) => void;
6
+ it: (name: string, fn: () => unknown) => void;
7
+ expect: (value: unknown) => any;
8
+ }
9
+
10
+ /** A fake CMP built from the vendor's documented browser API (test/fixtures/consent/<id>/). */
11
+ export interface ConsentFixture {
12
+ install(w: any): void;
13
+ grant(w: any): void;
14
+ deny(w: any): void;
15
+ broken(w: any): void;
16
+ }
17
+
18
+ /**
19
+ * The runtime-free half of the consent conformance suite (REF-P01,
20
+ * docs/PORTS.md): every adapter declares its docs and status, answers check(),
21
+ * is not detected on a page without its CMP, and never throws out of state()
22
+ * when the CMP's API throws (the gate reads that as `unknown`). The full
23
+ * served-script and module-build cases run in test/consent/conformance.ts.
24
+ */
25
+ export function runConformance(source: ConsentSource, fx: ConsentFixture, newWindow: () => any, t: TestApi): void {
26
+ const { describe, it, expect } = t;
27
+ describe(`consent adapter ${source.id} conformance`, () => {
28
+ it('declares its docs, vendor docs and status', () => {
29
+ expect(source.docsUrl).toMatch(/^https:\/\/referalli\.com\/docs\//);
30
+ expect(source.vendorDocsUrl).toMatch(/^https:\/\//);
31
+ expect(['ga', 'beta']).toContain(source.status);
32
+ });
33
+ it('answers check()', async () => {
34
+ const r = await source.check();
35
+ expect(typeof r.ok).toBe('boolean');
36
+ expect(typeof r.detail).toBe('string');
37
+ });
38
+ it('is not detected on a page without its CMP', () => {
39
+ expect(source.factory(newWindow()).detect()).toBe(false);
40
+ });
41
+ it('is detected once its CMP is on the page', () => {
42
+ const w = newWindow();
43
+ fx.install(w);
44
+ expect(source.factory(w).detect()).toBe(true);
45
+ });
46
+ });
47
+ }
@@ -0,0 +1,216 @@
1
+ import type { ConsentAdapterFactory, ConsentConfig, ConsentEvidence, ConsentState } from './port.js';
2
+
3
+ export interface ConsentGate {
4
+ /** Begin detecting (call once the change handler is ready). */
5
+ start(): void;
6
+ state(): ConsentState;
7
+ /** The adapter in use: an adapter id, `auto` while still looking, `none`, `no-cmp` or `pending`. */
8
+ mode(): string;
9
+ /** The push path: `aff.consent(true|false)`. The latest signal (push or CMP) wins. Idempotent. */
10
+ push(granted: boolean): void;
11
+ evidence(): ConsentEvidence | null;
12
+ stop(): void;
13
+ }
14
+
15
+ /**
16
+ * The one consent state machine, shared by `referalli/browser` (snippet.ts)
17
+ * and the served `aff.js` (served.ts inlines this function's source text, so
18
+ * it must stay self-contained: parameters and browser globals only).
19
+ *
20
+ * `change(state, evidence)` is called on every transition (never for the
21
+ * initial `unknown`). `auto` polls every 100 ms for up to `waitMs` for a CMP
22
+ * to appear; if the page is being left before then with none found, the
23
+ * no-CMP rule applies at once so a quick click-through still keeps its referral.
24
+ */
25
+ export function consentGate(
26
+ w: any,
27
+ cfg: ConsentConfig,
28
+ adapters: Record<string, ConsentAdapterFactory>,
29
+ order: readonly string[],
30
+ change: (state: ConsentState, evidence: ConsentEvidence | null) => void,
31
+ ): ConsentGate {
32
+ let reader: ReturnType<ConsentAdapterFactory> | null = null;
33
+ let readerId: string | null = null;
34
+ let current: ConsentState = 'unknown';
35
+ let pushed: boolean | null = null;
36
+ let fallback = false;
37
+ let finished = false;
38
+ let timer: any = null;
39
+ let unsub: (() => void) | null = null;
40
+ let started = false;
41
+ const wait = typeof cfg.waitMs === 'number' ? cfg.waitMs : 3000;
42
+ let deadline = 0;
43
+
44
+ function read(): ConsentState {
45
+ if (pushed !== null) return pushed ? 'granted' : 'denied';
46
+ if (cfg.mode === 'none') return 'granted';
47
+ if (reader) {
48
+ try {
49
+ const s = reader.state(cfg);
50
+ return s === 'granted' || s === 'denied' ? s : 'unknown';
51
+ } catch {
52
+ return 'unknown';
53
+ }
54
+ }
55
+ if (fallback && cfg.noCmp === 'persist') return 'granted';
56
+ return 'unknown';
57
+ }
58
+
59
+ function provider(): string {
60
+ if (pushed !== null) return 'custom';
61
+ if (readerId) return readerId;
62
+ if (cfg.mode === 'none') return 'none';
63
+ if (fallback) return 'no-cmp';
64
+ return String(cfg.mode);
65
+ }
66
+
67
+ function evidence(s: ConsentState): ConsentEvidence {
68
+ const ev: ConsentEvidence = { provider: provider(), state: s, at: new Date().toISOString() };
69
+ if (reader && pushed === null) {
70
+ try {
71
+ const x = reader.evidence(cfg);
72
+ if (x) {
73
+ if (typeof x.stamp === 'string' && x.stamp) ev.stamp = x.stamp.slice(0, 200);
74
+ if (typeof x.tcString === 'string' && x.tcString) ev.tcString = x.tcString.slice(0, 4000);
75
+ if (typeof x.gppString === 'string' && x.gppString) ev.gppString = x.gppString.slice(0, 4000);
76
+ if (x.purposes && x.purposes.length) ev.purposes = x.purposes.slice(0, 40).map(String);
77
+ }
78
+ } catch {
79
+ /* evidence is best-effort */
80
+ }
81
+ }
82
+ return ev;
83
+ }
84
+
85
+ function emit(): void {
86
+ if (!started) return;
87
+ const s = read();
88
+ if (s === current) return;
89
+ current = s;
90
+ change(s, s === 'unknown' ? null : evidence(s));
91
+ }
92
+
93
+ function onCmp(): void {
94
+ pushed = null;
95
+ emit();
96
+ }
97
+
98
+ function attach(): boolean {
99
+ const ids = cfg.mode === 'auto' ? order : [String(cfg.mode)];
100
+ for (let i = 0; i < ids.length; i++) {
101
+ const id = ids[i] as string;
102
+ const factory = adapters[id];
103
+ if (!factory) continue;
104
+ let r: ReturnType<ConsentAdapterFactory>;
105
+ try {
106
+ r = factory(w);
107
+ if (!r.detect()) continue;
108
+ } catch {
109
+ continue;
110
+ }
111
+ reader = r;
112
+ readerId = id;
113
+ try {
114
+ unsub = r.subscribe(cfg, onCmp);
115
+ } catch {
116
+ unsub = null;
117
+ }
118
+ return true;
119
+ }
120
+ return false;
121
+ }
122
+
123
+ function settle(): void {
124
+ finished = true;
125
+ if (timer !== null) {
126
+ try {
127
+ w.clearTimeout(timer);
128
+ } catch {
129
+ /* ignore */
130
+ }
131
+ timer = null;
132
+ }
133
+ }
134
+
135
+ function poll(): void {
136
+ timer = null;
137
+ if (finished) return;
138
+ if (attach()) {
139
+ settle();
140
+ emit();
141
+ return;
142
+ }
143
+ if (Date.now() >= deadline) {
144
+ settle();
145
+ if (cfg.mode === 'auto') fallback = true;
146
+ emit();
147
+ return;
148
+ }
149
+ try {
150
+ timer = w.setTimeout(poll, 100);
151
+ } catch {
152
+ settle();
153
+ }
154
+ }
155
+
156
+ // Leaving the page before a CMP showed up: apply the no-CMP rule now.
157
+ function onHide(e?: { type?: string }): void {
158
+ if (finished || cfg.mode !== 'auto') return;
159
+ if (e && e.type === 'visibilitychange' && w.document && w.document.visibilityState !== 'hidden') return;
160
+ if (attach()) {
161
+ settle();
162
+ emit();
163
+ return;
164
+ }
165
+ settle();
166
+ fallback = true;
167
+ emit();
168
+ }
169
+
170
+ return {
171
+ start(): void {
172
+ if (started) return;
173
+ started = true;
174
+ deadline = Date.now() + wait;
175
+ if (cfg.mode === 'none' || cfg.mode === 'pending') {
176
+ finished = true;
177
+ emit();
178
+ return;
179
+ }
180
+ try {
181
+ w.addEventListener('pagehide', onHide);
182
+ w.addEventListener('visibilitychange', onHide);
183
+ } catch {
184
+ /* no events: rely on the timer */
185
+ }
186
+ poll();
187
+ },
188
+ state: () => current,
189
+ mode(): string {
190
+ if (readerId) return readerId;
191
+ if (cfg.mode === 'auto') return fallback ? 'no-cmp' : 'auto';
192
+ return String(cfg.mode);
193
+ },
194
+ push(granted: boolean): void {
195
+ pushed = granted === true;
196
+ emit();
197
+ },
198
+ evidence: () => (current === 'unknown' ? null : evidence(current)),
199
+ stop(): void {
200
+ settle();
201
+ if (unsub) {
202
+ try {
203
+ unsub();
204
+ } catch {
205
+ /* ignore */
206
+ }
207
+ }
208
+ try {
209
+ w.removeEventListener('pagehide', onHide);
210
+ w.removeEventListener('visibilitychange', onHide);
211
+ } catch {
212
+ /* ignore */
213
+ }
214
+ },
215
+ };
216
+ }
@@ -0,0 +1,148 @@
1
+ /**
2
+ * The consent port: how the browser tracker (`aff.js`, `referalli/browser`)
3
+ * learns whether the visitor allows the referral context to be stored.
4
+ *
5
+ * Each adapter reads one consent-management platform (CMP) through that
6
+ * vendor's documented browser API. One state machine (gate.ts) turns the
7
+ * adapter's answer into what the tracker may do:
8
+ *
9
+ * unknown nothing stored, no beacon; the referral stays in memory, so
10
+ * `getReferral()` / `signupMetadata()` still attribute a sign-up
11
+ * granted `referalli_ctx` (and its legacy twin) written, visit beacon sent
12
+ * with consent evidence
13
+ * denied storage cleared within one tick, nothing sent, referral dropped
14
+ *
15
+ * Adapter factories and the gate are SELF-CONTAINED functions: the served
16
+ * `aff.js` (served.ts) inlines their source text, so they may only use their
17
+ * parameters and browser globals, never an import or a module-level helper.
18
+ * `test/consent/conformance.ts` runs every adapter through the same cases in
19
+ * both the module build and the served script.
20
+ */
21
+
22
+ /** `unknown` means no decision yet (or no readable CMP). It is never "declined". */
23
+ export type ConsentState = 'granted' | 'denied' | 'unknown';
24
+
25
+ /**
26
+ * Adapters `auto` tries, in this order. The merchant's own `referalliConsent`
27
+ * hook wins, then vendor CMPs (their own category model), then the IAB
28
+ * frameworks and Google Consent Mode, which many CMPs also feed.
29
+ */
30
+ export const AUTO_ORDER = [
31
+ 'custom',
32
+ 'cookiemunch',
33
+ 'onetrust',
34
+ 'cookiebot',
35
+ 'usercentrics',
36
+ 'didomi',
37
+ 'osano',
38
+ 'termly',
39
+ 'tcf',
40
+ 'gpp',
41
+ 'gcm',
42
+ ] as const;
43
+
44
+ export type ConsentAdapterId = (typeof AUTO_ORDER)[number] | 'none';
45
+ export const CONSENT_ADAPTER_IDS: readonly ConsentAdapterId[] = [...AUTO_ORDER, 'none'];
46
+
47
+ /**
48
+ * `auto`: the first CMP detected, in `AUTO_ORDER`. `none`: always granted
49
+ * (the tracker's behaviour before consent support; only for sites that need
50
+ * no opt-in). `pending`: unknown until the page calls `aff.consent(true|false)`.
51
+ */
52
+ export type ConsentMode = 'auto' | 'none' | 'pending' | ConsentAdapterId;
53
+ export const CONSENT_MODES: readonly ConsentMode[] = ['auto', 'pending', ...CONSENT_ADAPTER_IDS];
54
+
55
+ export interface ConsentEvidence {
56
+ /** The adapter that decided (`onetrust`, `tcf`, …), `custom` for `aff.consent()`, `none`, or `no-cmp` for auto's fallback. */
57
+ provider: string;
58
+ state: ConsentState;
59
+ /** ISO time the state was read. */
60
+ at: string;
61
+ /** The CMP's consent record id, when it exposes one. */
62
+ stamp?: string;
63
+ tcString?: string;
64
+ gppString?: string;
65
+ /** Purposes, categories or groups the CMP reported as allowed. */
66
+ purposes?: string[];
67
+ }
68
+
69
+ export interface ConsentConfig {
70
+ mode: ConsentMode;
71
+ /** Adapter-specific category, group, purpose or service; each adapter has a default. */
72
+ category?: string;
73
+ /** IAB TCF vendor id; when set, TCF requires that vendor's consent instead of publisher purposes 7/9. */
74
+ tcfVendorId?: number;
75
+ /** Google Consent Mode signal to follow. Default `ad_storage`. */
76
+ gcmSignal?: 'ad_storage' | 'analytics_storage';
77
+ /** `auto` with no CMP found: `persist` behaves as granted, `memory` stays unknown. */
78
+ noCmp: 'persist' | 'memory';
79
+ /** How long to wait for a late CMP before `auto` gives up. Default 3000, at most 10000. */
80
+ waitMs?: number;
81
+ }
82
+
83
+ /** What a merchant passes to `initSnippet` / `createTracker`: any subset, mode defaulting to `none`. */
84
+ export type ConsentOptions = Partial<ConsentConfig> | ConsentMode;
85
+
86
+ /** One adapter bound to a window. Every method may throw; the gate reads a throw as `unknown`. */
87
+ export interface ConsentReader {
88
+ /** Is this CMP's API (or its stub) on the page? */
89
+ detect(): boolean;
90
+ state(cfg: ConsentConfig): ConsentState;
91
+ /** Calls `cb` whenever the CMP reports a load, a decision or a change. Returns an unsubscribe. */
92
+ subscribe(cfg: ConsentConfig, cb: () => void): () => void;
93
+ /** Extra evidence fields (stamp, tcString, gppString, purposes). */
94
+ evidence(cfg: ConsentConfig): Omit<ConsentEvidence, 'provider' | 'state' | 'at'> | null;
95
+ }
96
+
97
+ /** Self-contained: inlined into aff.js by its source text. */
98
+ export type ConsentAdapterFactory = (w: any) => ConsentReader;
99
+
100
+ export interface ConsentSource {
101
+ readonly id: ConsentAdapterId;
102
+ readonly name: string;
103
+ /** What the adapter reads when no `category` is configured. */
104
+ readonly defaultCategory: string | null;
105
+ readonly factory: ConsentAdapterFactory;
106
+ readonly status: 'ga' | 'beta';
107
+ /** Referalli's page for this CMP. */
108
+ readonly docsUrl: string;
109
+ /** The vendor's API documentation the adapter follows. */
110
+ readonly vendorDocsUrl: string;
111
+ /** Health (docs/PORTS.md): cheap, read-only, never throws. */
112
+ readonly check: (cfg?: Partial<ConsentConfig>) => Promise<PortCheck>;
113
+ }
114
+
115
+ export interface PortCheck {
116
+ ok: boolean;
117
+ detail: string;
118
+ fix?: string;
119
+ }
120
+
121
+ /**
122
+ * Every consent adapter's `check()`. The CMP lives in the visitor's browser,
123
+ * so there is nothing to probe from a server: the health signal is the
124
+ * consent evidence each visit carries (its `provider` and `state`). This says
125
+ * what the adapter will read with the given config.
126
+ */
127
+ export async function browserCheck(source: Pick<ConsentSource, 'name' | 'defaultCategory'>, cfg?: Partial<ConsentConfig>): Promise<PortCheck> {
128
+ const what = cfg?.category ?? source.defaultCategory;
129
+ return {
130
+ ok: true,
131
+ detail: `${source.name} is read in the visitor's browser${what ? ` (${what})` : ''}; each visit's consent evidence shows its answer.`,
132
+ };
133
+ }
134
+
135
+ /** Normalise merchant options into a full config (mode `none` when absent: the pre-consent behaviour). */
136
+ export function consentConfig(opts: ConsentOptions | undefined | null): ConsentConfig {
137
+ const o: Partial<ConsentConfig> = typeof opts === 'string' ? { mode: opts } : (opts ?? {});
138
+ const mode = o.mode && CONSENT_MODES.includes(o.mode) ? o.mode : 'none';
139
+ const waitMs = typeof o.waitMs === 'number' && o.waitMs >= 0 ? Math.min(10_000, Math.round(o.waitMs)) : 3000;
140
+ return {
141
+ mode,
142
+ ...(typeof o.category === 'string' && o.category ? { category: o.category.slice(0, 80) } : {}),
143
+ ...(typeof o.tcfVendorId === 'number' && o.tcfVendorId > 0 ? { tcfVendorId: Math.round(o.tcfVendorId) } : {}),
144
+ ...(o.gcmSignal === 'analytics_storage' || o.gcmSignal === 'ad_storage' ? { gcmSignal: o.gcmSignal } : {}),
145
+ noCmp: o.noCmp === 'memory' ? 'memory' : 'persist',
146
+ waitMs,
147
+ };
148
+ }
@@ -0,0 +1,60 @@
1
+ import { cookiebot } from './adapters/cookiebot.js';
2
+ import { cookiemunch } from './adapters/cookiemunch.js';
3
+ import { custom } from './adapters/custom.js';
4
+ import { didomi } from './adapters/didomi.js';
5
+ import { gcm } from './adapters/gcm.js';
6
+ import { gpp } from './adapters/gpp.js';
7
+ import { none } from './adapters/none.js';
8
+ import { onetrust } from './adapters/onetrust.js';
9
+ import { osano } from './adapters/osano.js';
10
+ import { tcf } from './adapters/tcf.js';
11
+ import { termly } from './adapters/termly.js';
12
+ import { usercentrics } from './adapters/usercentrics.js';
13
+ import { AUTO_ORDER, type ConsentAdapterFactory, type ConsentAdapterId, type ConsentSource } from './port.js';
14
+
15
+ /**
16
+ * Every consent adapter, `auto`'s detection order first, then `none`.
17
+ * (`fd-consent`, the suite's `window.__fdConsent`, joins when Cookie Munch
18
+ * ships that contract: CMU-X16.)
19
+ */
20
+ export const CONSENT_SOURCES: readonly ConsentSource[] = [
21
+ custom,
22
+ cookiemunch,
23
+ onetrust,
24
+ cookiebot,
25
+ usercentrics,
26
+ didomi,
27
+ osano,
28
+ termly,
29
+ tcf,
30
+ gpp,
31
+ gcm,
32
+ none,
33
+ ];
34
+
35
+ /**
36
+ * The consent port's adapters (docs/PORTS.md): every CMP reader, `custom`
37
+ * first. `none` is left out: it reads nothing (it is the "always store" mode,
38
+ * like `auto` and `pending`), so it has no vendor, fixtures or conformance run.
39
+ */
40
+ export const ADAPTERS: readonly ConsentSource[] = CONSENT_SOURCES.filter((s) => s.id !== 'none');
41
+
42
+ const BY_ID = new Map<string, ConsentSource>(CONSENT_SOURCES.map((s) => [s.id, s]));
43
+
44
+ export function adapterOf(id: string): ConsentSource | undefined {
45
+ return BY_ID.get(id);
46
+ }
47
+
48
+ /** `{ id: factory }` for the gate, limited to `ids` (default: every adapter). */
49
+ export function adapterFactories(ids: readonly string[] = AUTO_ORDER): Record<string, ConsentAdapterFactory> {
50
+ const out: Record<string, ConsentAdapterFactory> = {};
51
+ for (const id of ids) {
52
+ const s = BY_ID.get(id);
53
+ if (s) out[id] = s.factory;
54
+ }
55
+ return out;
56
+ }
57
+
58
+ export function isConsentAdapterId(id: unknown): id is ConsentAdapterId {
59
+ return typeof id === 'string' && BY_ID.has(id);
60
+ }