@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.
- package/CHANGELOG.md +132 -0
- package/LICENSE +21 -0
- package/README.md +236 -2
- package/dist/cjs/attribution.d.ts +105 -0
- package/dist/cjs/attribution.js +200 -0
- package/dist/cjs/browser.d.ts +41 -0
- package/dist/cjs/browser.js +88 -0
- package/dist/cjs/client.d.ts +97 -0
- package/dist/cjs/client.js +301 -0
- package/dist/cjs/consent/adapters/cookiebot.d.ts +7 -0
- package/dist/cjs/consent/adapters/cookiebot.js +49 -0
- package/dist/cjs/consent/adapters/cookiemunch.d.ts +8 -0
- package/dist/cjs/consent/adapters/cookiemunch.js +56 -0
- package/dist/cjs/consent/adapters/custom.d.ts +8 -0
- package/dist/cjs/consent/adapters/custom.js +39 -0
- package/dist/cjs/consent/adapters/didomi.d.ts +9 -0
- package/dist/cjs/consent/adapters/didomi.js +67 -0
- package/dist/cjs/consent/adapters/gcm.d.ts +10 -0
- package/dist/cjs/consent/adapters/gcm.js +78 -0
- package/dist/cjs/consent/adapters/gpp.d.ts +9 -0
- package/dist/cjs/consent/adapters/gpp.js +92 -0
- package/dist/cjs/consent/adapters/none.d.ts +3 -0
- package/dist/cjs/consent/adapters/none.js +30 -0
- package/dist/cjs/consent/adapters/onetrust.d.ts +8 -0
- package/dist/cjs/consent/adapters/onetrust.js +71 -0
- package/dist/cjs/consent/adapters/osano.d.ts +9 -0
- package/dist/cjs/consent/adapters/osano.js +71 -0
- package/dist/cjs/consent/adapters/tcf.d.ts +8 -0
- package/dist/cjs/consent/adapters/tcf.js +79 -0
- package/dist/cjs/consent/adapters/termly.d.ts +10 -0
- package/dist/cjs/consent/adapters/termly.js +61 -0
- package/dist/cjs/consent/adapters/usercentrics.d.ts +9 -0
- package/dist/cjs/consent/adapters/usercentrics.js +106 -0
- package/dist/cjs/consent/conformance.d.ts +22 -0
- package/dist/cjs/consent/conformance.js +33 -0
- package/dist/cjs/consent/gate.d.ts +23 -0
- package/dist/cjs/consent/gate.js +220 -0
- package/dist/cjs/consent/port.d.ts +105 -0
- package/dist/cjs/consent/port.js +72 -0
- package/dist/cjs/consent/registry.d.ts +17 -0
- package/dist/cjs/consent/registry.js +61 -0
- package/dist/cjs/consent/served.d.ts +15 -0
- package/dist/cjs/consent/served.js +26 -0
- package/dist/cjs/core.d.ts +77 -0
- package/dist/cjs/core.js +64 -0
- package/dist/cjs/errors.d.ts +42 -0
- package/dist/cjs/errors.generated.d.ts +183 -0
- package/dist/cjs/errors.generated.js +279 -0
- package/dist/cjs/errors.js +47 -0
- package/dist/cjs/generated.d.ts +15151 -0
- package/dist/cjs/generated.js +625 -0
- package/dist/cjs/index.d.ts +22 -0
- package/dist/cjs/index.js +93 -0
- package/dist/cjs/mobile.d.ts +66 -0
- package/dist/cjs/mobile.js +69 -0
- package/dist/cjs/node.d.ts +209 -0
- package/dist/cjs/node.js +140 -0
- package/dist/cjs/outbox.d.ts +186 -0
- package/dist/cjs/outbox.js +324 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/resources.generated.d.ts +6002 -0
- package/dist/cjs/resources.generated.js +2090 -0
- package/dist/cjs/served.d.ts +25 -0
- package/dist/cjs/served.js +214 -0
- package/dist/cjs/sha256.d.ts +2 -0
- package/dist/cjs/sha256.js +86 -0
- package/dist/cjs/snippet.d.ts +99 -0
- package/dist/cjs/snippet.js +213 -0
- package/dist/cjs/stripe-events.d.ts +25 -0
- package/dist/cjs/stripe-events.js +117 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +5 -0
- package/dist/cjs/webhooks.d.ts +76 -0
- package/dist/cjs/webhooks.js +159 -0
- package/dist/esm/attribution.d.ts +105 -0
- package/dist/esm/attribution.js +186 -0
- package/dist/esm/browser.d.ts +41 -0
- package/dist/esm/browser.js +68 -0
- package/dist/esm/client.d.ts +97 -0
- package/dist/esm/client.js +297 -0
- package/dist/esm/consent/adapters/cookiebot.d.ts +7 -0
- package/dist/esm/consent/adapters/cookiebot.js +46 -0
- package/dist/esm/consent/adapters/cookiemunch.d.ts +8 -0
- package/dist/esm/consent/adapters/cookiemunch.js +53 -0
- package/dist/esm/consent/adapters/custom.d.ts +8 -0
- package/dist/esm/consent/adapters/custom.js +36 -0
- package/dist/esm/consent/adapters/didomi.d.ts +9 -0
- package/dist/esm/consent/adapters/didomi.js +64 -0
- package/dist/esm/consent/adapters/gcm.d.ts +10 -0
- package/dist/esm/consent/adapters/gcm.js +75 -0
- package/dist/esm/consent/adapters/gpp.d.ts +9 -0
- package/dist/esm/consent/adapters/gpp.js +89 -0
- package/dist/esm/consent/adapters/none.d.ts +3 -0
- package/dist/esm/consent/adapters/none.js +27 -0
- package/dist/esm/consent/adapters/onetrust.d.ts +8 -0
- package/dist/esm/consent/adapters/onetrust.js +68 -0
- package/dist/esm/consent/adapters/osano.d.ts +9 -0
- package/dist/esm/consent/adapters/osano.js +68 -0
- package/dist/esm/consent/adapters/tcf.d.ts +8 -0
- package/dist/esm/consent/adapters/tcf.js +76 -0
- package/dist/esm/consent/adapters/termly.d.ts +10 -0
- package/dist/esm/consent/adapters/termly.js +58 -0
- package/dist/esm/consent/adapters/usercentrics.d.ts +9 -0
- package/dist/esm/consent/adapters/usercentrics.js +103 -0
- package/dist/esm/consent/conformance.d.ts +22 -0
- package/dist/esm/consent/conformance.js +30 -0
- package/dist/esm/consent/gate.d.ts +23 -0
- package/dist/esm/consent/gate.js +217 -0
- package/dist/esm/consent/port.d.ts +105 -0
- package/dist/esm/consent/port.js +67 -0
- package/dist/esm/consent/registry.d.ts +17 -0
- package/dist/esm/consent/registry.js +55 -0
- package/dist/esm/consent/served.d.ts +15 -0
- package/dist/esm/consent/served.js +22 -0
- package/dist/esm/core.d.ts +77 -0
- package/dist/esm/core.js +60 -0
- package/dist/esm/errors.d.ts +42 -0
- package/dist/esm/errors.generated.d.ts +183 -0
- package/dist/esm/errors.generated.js +231 -0
- package/dist/esm/errors.js +40 -0
- package/dist/esm/generated.d.ts +15151 -0
- package/dist/esm/generated.js +622 -0
- package/dist/esm/index.d.ts +22 -0
- package/dist/esm/index.js +22 -0
- package/dist/esm/mobile.d.ts +66 -0
- package/dist/esm/mobile.js +64 -0
- package/dist/esm/node.d.ts +209 -0
- package/dist/esm/node.js +135 -0
- package/dist/esm/outbox.d.ts +186 -0
- package/dist/esm/outbox.js +316 -0
- package/dist/esm/package.json +3 -0
- package/dist/esm/resources.generated.d.ts +6002 -0
- package/dist/esm/resources.generated.js +2086 -0
- package/dist/esm/served.d.ts +25 -0
- package/dist/esm/served.js +207 -0
- package/dist/esm/sha256.d.ts +2 -0
- package/dist/esm/sha256.js +82 -0
- package/dist/esm/snippet.d.ts +99 -0
- package/dist/esm/snippet.js +210 -0
- package/dist/esm/stripe-events.d.ts +25 -0
- package/dist/esm/stripe-events.js +114 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +2 -0
- package/dist/esm/webhooks.d.ts +76 -0
- package/dist/esm/webhooks.js +153 -0
- package/dist/tsconfig.build.tsbuildinfo +1 -0
- package/dist/tsconfig.cjs.tsbuildinfo +1 -0
- package/package.json +105 -4
- package/src/attribution.ts +216 -0
- package/src/browser.ts +107 -0
- package/src/client.ts +351 -0
- package/src/codegen.ts +130 -0
- package/src/consent/adapters/cookiebot.ts +42 -0
- package/src/consent/adapters/cookiemunch.ts +49 -0
- package/src/consent/adapters/custom.ts +37 -0
- package/src/consent/adapters/didomi.ts +59 -0
- package/src/consent/adapters/gcm.ts +68 -0
- package/src/consent/adapters/gpp.ts +81 -0
- package/src/consent/adapters/none.ts +28 -0
- package/src/consent/adapters/onetrust.ts +64 -0
- package/src/consent/adapters/osano.ts +63 -0
- package/src/consent/adapters/tcf.ts +67 -0
- package/src/consent/adapters/termly.ts +54 -0
- package/src/consent/adapters/usercentrics.ts +97 -0
- package/src/consent/conformance.ts +47 -0
- package/src/consent/gate.ts +216 -0
- package/src/consent/port.ts +148 -0
- package/src/consent/registry.ts +60 -0
- package/src/consent/served.ts +24 -0
- package/src/core.ts +127 -0
- package/src/errors.generated.ts +277 -0
- package/src/errors.ts +57 -0
- package/src/generated.ts +14545 -0
- package/src/index.ts +100 -0
- package/src/mobile.ts +96 -0
- package/src/node.ts +291 -0
- package/src/outbox.ts +452 -0
- package/src/resources.generated.ts +2097 -0
- package/src/served.ts +229 -0
- package/src/sha256.ts +82 -0
- package/src/snippet.ts +305 -0
- package/src/stripe-events.ts +130 -0
- package/src/version.ts +2 -0
- package/src/webhooks.ts +207 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type ConsentOptions } from './consent/port.js';
|
|
2
|
+
export interface SnippetOptions {
|
|
3
|
+
/** Default lifetime of the stored context; the org's longest program cookie window. */
|
|
4
|
+
cookieDays?: number;
|
|
5
|
+
/** Keep the first referral instead of the latest (every program is first_click). */
|
|
6
|
+
firstTouch?: boolean;
|
|
7
|
+
/** Extra query parameters that carry a referral code (an imported tool's, e.g. fpr), after via/ref/aff. */
|
|
8
|
+
params?: string[];
|
|
9
|
+
/** Older storage/cookie names to read a saved context from (it is re-saved under the current name). */
|
|
10
|
+
legacyKeys?: string[];
|
|
11
|
+
/** The org's consent default (`data-consent` on the tag overrides it). Default `none`. */
|
|
12
|
+
consent?: ConsentOptions;
|
|
13
|
+
/**
|
|
14
|
+
* Inline only these adapters (`?consent=<id>` on the script URL), keeping
|
|
15
|
+
* the script small. Default: every adapter.
|
|
16
|
+
*/
|
|
17
|
+
consentAdapters?: string[];
|
|
18
|
+
}
|
|
19
|
+
/** The cookie window aff.js is served with (also published at /t/{orgToken}/config.json). */
|
|
20
|
+
export declare const snippetCookieDays: (cookieDays?: number) => number;
|
|
21
|
+
export declare function renderSnippetJs(token: string, baseUrl: string, opts?: SnippetOptions): string;
|
|
22
|
+
/** The partner get-link bar, loaded by aff.js only on a page carrying a bar token (kept out of aff.js's size budget). */
|
|
23
|
+
export declare function renderBarJs(token: string, baseUrl: string): string;
|
|
24
|
+
/** Pay-per-call number swap, loaded by aff.js on `data-calls="swap"`: rewrites only elements marked `data-referalli-phone`. */
|
|
25
|
+
export declare function renderCallsJs(token: string, baseUrl: string): string;
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.snippetCookieDays = void 0;
|
|
4
|
+
exports.renderSnippetJs = renderSnippetJs;
|
|
5
|
+
exports.renderBarJs = renderBarJs;
|
|
6
|
+
exports.renderCallsJs = renderCallsJs;
|
|
7
|
+
/**
|
|
8
|
+
* The standalone `aff.js` script served from the tracking endpoint. Mirrors the
|
|
9
|
+
* behavior of snippet.ts as a dependency-free IIFE, with the org token and base
|
|
10
|
+
* URL inlined at serve time. The consent gate and its adapters are the same
|
|
11
|
+
* functions snippet.ts runs, inlined by source text (consent/served.ts).
|
|
12
|
+
*
|
|
13
|
+
* Page-level overrides go on the script tag:
|
|
14
|
+
* - `data-consent="auto" | "none" | "pending" | "<adapter id>"`: how consent
|
|
15
|
+
* is read (default: the org's tracking setting). Until a CMP grants, the
|
|
16
|
+
* context is kept in memory only: nothing stored, no visit beacon.
|
|
17
|
+
* - `data-consent-category`, `data-consent-tcf-vendor`: adapter options.
|
|
18
|
+
* - `data-persist="referral-only"`: store and send nothing unless the URL
|
|
19
|
+
* carries a referral (code or click id).
|
|
20
|
+
* - `data-cookie-days="30"`: how long the context is kept.
|
|
21
|
+
* - `data-attribution="first" | "last"`: which referral a new one replaces.
|
|
22
|
+
* - `data-cookie-domain=".app.com"`: share the cookie with subdomains (an
|
|
23
|
+
* auth page on auth.app.com can then read the referral).
|
|
24
|
+
* - `data-partner-bar="on"`: show the get-link bar to a partner the portal sent here with a bar token
|
|
25
|
+
* (sessionStorage only, no cookie; see routes/storefronts.ts).
|
|
26
|
+
* `aff.consent(true|false)` is the push path for pages without a supported
|
|
27
|
+
* CMP; `aff.forget()` deletes the stored context (consent withdrawn). Calls
|
|
28
|
+
* queued before the script loads (`window.aff = window.aff || {q: []};
|
|
29
|
+
* aff.q.push(['consent', true])`) are run on load.
|
|
30
|
+
*/
|
|
31
|
+
const attribution_js_1 = require("./attribution.js");
|
|
32
|
+
const served_js_1 = require("./consent/served.js");
|
|
33
|
+
const port_js_1 = require("./consent/port.js");
|
|
34
|
+
/** The cookie window aff.js is served with (also published at /t/{orgToken}/config.json). */
|
|
35
|
+
const snippetCookieDays = (cookieDays) => Math.max(1, Math.min(400, Math.round(cookieDays ?? 60)));
|
|
36
|
+
exports.snippetCookieDays = snippetCookieDays;
|
|
37
|
+
function renderSnippetJs(token, baseUrl, opts = {}) {
|
|
38
|
+
const days = (0, exports.snippetCookieDays)(opts.cookieDays);
|
|
39
|
+
const consent = (0, port_js_1.consentConfig)(opts.consent);
|
|
40
|
+
const ids = opts.consentAdapters?.length ? opts.consentAdapters.filter((id) => port_js_1.AUTO_ORDER.includes(id)) : [...port_js_1.AUTO_ORDER];
|
|
41
|
+
const src = (0, served_js_1.consentSource)(ids);
|
|
42
|
+
return `(function(){
|
|
43
|
+
${served_js_1.NAME_SHIM}
|
|
44
|
+
var KEY='referalli_ctx';
|
|
45
|
+
// Legacy twin referally_ctx, same value, attributes and expiry, for integrations
|
|
46
|
+
// that read the pre-rename name. Written until 2027-01-31, then dropped (see
|
|
47
|
+
// https://referalli.com/docs/renamed-from-referally).
|
|
48
|
+
var WKEYS=[KEY,${JSON.stringify(attribution_js_1.LEGACY_REFERRAL_COOKIE)}];
|
|
49
|
+
var s=document.currentScript;
|
|
50
|
+
function attr(n){return s&&s.getAttribute?s.getAttribute(n):null;}
|
|
51
|
+
var BASE=${JSON.stringify(baseUrl)};
|
|
52
|
+
try{if(s&&s.src)BASE=new URL(s.src).origin;}catch(e){}
|
|
53
|
+
var days=parseInt(attr('data-cookie-days')||'',10);if(!(days>0))days=${days};if(days>400)days=400;
|
|
54
|
+
var a=attr('data-attribution');var first=a==='first'||(a!=='last'&&${opts.firstTouch ? 'true' : 'false'});
|
|
55
|
+
var referralOnly=attr('data-persist')==='referral-only';
|
|
56
|
+
var secure=location.protocol==='https:'?'; Secure':'';
|
|
57
|
+
// Only a domain this page is on, with two labels or more; else host-only.
|
|
58
|
+
var cd=attr('data-cookie-domain'),cdh=(cd||'').replace(/^\\./,'').toLowerCase(),hn=String(location.hostname||'').toLowerCase();
|
|
59
|
+
var dom=/^[a-z0-9-]+(\\.[a-z0-9-]+)+$/.test(cdh)&&(hn===cdh||hn.slice(-cdh.length-1)==='.'+cdh)?'; domain='+cd:'';
|
|
60
|
+
var gone=false,dropped=false,sent=false,cstate='unknown',pendingId=null;
|
|
61
|
+
var KEYS=WKEYS.concat(${JSON.stringify((opts.legacyKeys ?? []).filter((k) => /^[A-Za-z0-9_]{1,64}$/.test(k) && !attribution_js_1.REFERRAL_COOKIE_NAMES.includes(k)))});
|
|
62
|
+
function readKey(k){var r=null;try{r=localStorage.getItem(k);}catch(e){}
|
|
63
|
+
if(!r){var m=document.cookie.match(new RegExp('(?:^|; )'+k+'=([^;]*)'));if(m)r=decodeURIComponent(m[1]);}
|
|
64
|
+
if(!r)return null;try{var c=JSON.parse(r);if(!c||typeof c.anonId!=='string'||(c.exp&&c.exp<Date.now()))return null;return c;}catch(e){return null;}}
|
|
65
|
+
function read(){for(var i=0;i<KEYS.length;i++){var c=readKey(KEYS[i]);if(c)return c;}return null;}
|
|
66
|
+
function write(c){if(gone||dropped)return;var r=JSON.stringify(c),v=encodeURIComponent(r);var t='='+v+'; path=/; max-age='+(days*86400)+'; SameSite=Lax';
|
|
67
|
+
for(var i=0;i<WKEYS.length;i++){var k=WKEYS[i];
|
|
68
|
+
try{localStorage.setItem(k,r);}catch(e){}
|
|
69
|
+
// A refused domain (a public suffix) doesn't read back: go host-only.
|
|
70
|
+
try{document.cookie=k+t+dom+secure;if(dom&&document.cookie.indexOf(k+'='+v)<0){dom='';document.cookie=k+t+secure;}}catch(e){}}}
|
|
71
|
+
function clear(){for(var i=0;i<KEYS.length;i++){var k=KEYS[i];try{localStorage.removeItem(k);}catch(e){}
|
|
72
|
+
try{document.cookie=k+'=; path=/; max-age=0; SameSite=Lax'+dom+secure;if(dom)document.cookie=k+'=; path=/; max-age=0; SameSite=Lax'+secure;}catch(e){}}}
|
|
73
|
+
function forget(){gone=true;clear();}
|
|
74
|
+
function rid(){var t='a_',c='abcdefghijklmnopqrstuvwxyz0123456789';
|
|
75
|
+
for(var i=0;i<20;i++)t+=c[Math.floor(Math.random()*c.length)];return t;}
|
|
76
|
+
var u=new URL(window.location.href);
|
|
77
|
+
var PARAMS=${JSON.stringify(['via', 'ref', 'aff', ...(opts.params ?? []).filter((p) => /^[a-z][a-z0-9_]{0,39}$/.test(p))])};
|
|
78
|
+
var code=null;for(var pi=0;pi<PARAMS.length&&!code;pi++)code=u.searchParams.get(PARAMS[pi]);
|
|
79
|
+
var clickId=u.searchParams.get('ref_click_id');
|
|
80
|
+
var sub=u.searchParams.get('sub');if(!/^[A-Za-z0-9_.-]{1,64}$/.test(sub||''))sub=null;
|
|
81
|
+
var st=read()||{};
|
|
82
|
+
var keep=first&&(st.code||st.clickId);
|
|
83
|
+
var ctx={anonId:st.anonId||rid(),
|
|
84
|
+
code:keep?(st.code||null):(code||st.code||null),
|
|
85
|
+
clickId:keep?(st.clickId||null):(clickId||st.clickId||null),
|
|
86
|
+
ts:st.ts||Date.now()};
|
|
87
|
+
ctx.exp=keep&&st.exp?st.exp:((code||clickId)?Date.now()+days*86400000:(st.exp||Date.now()+days*86400000));
|
|
88
|
+
function post(p,b,cb){if(gone||dropped)return;try{fetch(BASE+p,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(b),keepalive:true}).then(function(r){return cb?r.json():0;}).then(function(j){if(cb)cb(j);}).catch(function(){});}catch(e){}}
|
|
89
|
+
var active=!referralOnly||code||clickId;
|
|
90
|
+
// Consent: the org default, overridden by the tag.
|
|
91
|
+
var CFG=${JSON.stringify(consent)};
|
|
92
|
+
var cm=attr('data-consent');if(cm&&${JSON.stringify(port_js_1.CONSENT_MODES)}.indexOf(cm)>=0)CFG.mode=cm;
|
|
93
|
+
var cc=attr('data-consent-category');if(cc)CFG.category=cc.slice(0,80);
|
|
94
|
+
var tv=parseInt(attr('data-consent-tcf-vendor')||'',10);if(tv>0)CFG.tcfVendorId=tv;
|
|
95
|
+
function identify(o){o=o||{};if(gone||dropped)return;if(!active&&!st.anonId)return;
|
|
96
|
+
if(cstate!=='granted'){pendingId=o;return;}
|
|
97
|
+
post('/t/${token}/identify',{anonId:ctx.anonId,customerRef:o.customerRef,emailHash:o.emailHash});}
|
|
98
|
+
function onConsent(state,ev){cstate=state;
|
|
99
|
+
if(state==='granted'){dropped=false;
|
|
100
|
+
if(active){write(ctx);
|
|
101
|
+
if(!sent){sent=true;post('/t/${token}/visit',{anonId:ctx.anonId,code:(keep?null:code)||ctx.code||undefined,clickId:(keep?null:clickId)||ctx.clickId||undefined,url:window.location.href,sub:sub||undefined,consent:ev||undefined},function(j){var w=j&&j.cookieWindowDays;if(w>0&&!dropped&&!gone){days=Math.min(w,400);ctx.exp=Date.now()+days*86400000;write(ctx);}});}}
|
|
102
|
+
if(pendingId){var o=pendingId;pendingId=null;identify(o);}}
|
|
103
|
+
else if(state==='denied'){clear();dropped=true;pendingId=null;}}
|
|
104
|
+
var gate=${src.gate}(window,CFG,${src.adapters},${src.order},onConsent);
|
|
105
|
+
function view(){return gone||dropped?{anonId:null,code:null,clickId:null,ts:null}:{anonId:ctx.anonId,code:ctx.code,clickId:ctx.clickId,ts:ctx.ts};}
|
|
106
|
+
// Cart extension: a cart add is sent only for a visitor who came through a referral and has consented; the server also
|
|
107
|
+
// checks the referral context is still live and the program has cartWindowDays on.
|
|
108
|
+
function cartAdd(o){o=o||{};if(gone||dropped||cstate!=='granted'||!(ctx.code||ctx.clickId))return;
|
|
109
|
+
var p=o.productId!=null&&o.productId!==''?String(o.productId):undefined,k=o.sku?String(o.sku):undefined;if(!p&&!k)return;
|
|
110
|
+
var q=Math.floor(Number(o.quantity));post('/t/${token}/cart',{anonId:ctx.anonId,productId:p,sku:k,quantity:q>0?q:undefined});}
|
|
111
|
+
var api={
|
|
112
|
+
getReferral:view,
|
|
113
|
+
signupMetadata:function(){var v=view();var m={referalli_anon_id:v.anonId};if(v.clickId)m.referalli_click_id=v.clickId;if(v.code)m.referalli_coupon=v.code;return m;},
|
|
114
|
+
identify:identify,
|
|
115
|
+
getHandoffToken:function(){var v=view();if(!v.anonId)return Promise.resolve(null);
|
|
116
|
+
return fetch(BASE+'/t/${token}/handoff',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({anonId:v.anonId,clickId:v.clickId||undefined,code:v.code||undefined})})
|
|
117
|
+
.then(function(r){return r.ok?r.json():null;}).then(function(j){return j&&j.handoffToken||null;},function(){return null;});},
|
|
118
|
+
forget:forget,
|
|
119
|
+
cartAdd:cartAdd,
|
|
120
|
+
consent:function(g){gate.push(g===true);},
|
|
121
|
+
consentState:function(){return cstate;},
|
|
122
|
+
consentEvidence:function(){return gate.evidence();},
|
|
123
|
+
get consentMode(){return gate.mode();}
|
|
124
|
+
};
|
|
125
|
+
function run(e){try{if(e&&typeof api[e[0]]==='function')api[e[0]].apply(api,Array.prototype.slice.call(e,1));}catch(x){}}
|
|
126
|
+
var prev=window.aff;var queued=prev&&prev.q&&typeof prev.q.length==='number'?prev.q:[];
|
|
127
|
+
api.q={push:run};
|
|
128
|
+
window.aff=api;
|
|
129
|
+
// Get-link bar for partners (data-partner-bar="on"): bar.js loads only when the portal sent a bar token (#rl_pbar=) or one is
|
|
130
|
+
// already in sessionStorage, so shoppers never download it.
|
|
131
|
+
(function(){if(attr('data-partner-bar')!=='on')return;var has=/(^|[#&])rl_pbar=/.test(location.hash||'');
|
|
132
|
+
if(!has)try{has=!!sessionStorage.getItem('referalli_pbar');}catch(e){}
|
|
133
|
+
if(has){var b=document.createElement('script');b.async=true;b.src=BASE+'/t/${token}/bar.js';(document.head||document.body).appendChild(b);}})();
|
|
134
|
+
// data-calls="swap": calls.js (pay-per-call number swap) loads only with a live referral context.
|
|
135
|
+
(function(){if(attr('data-calls')!=='swap'||!(ctx.code||ctx.clickId))return;
|
|
136
|
+
var c=document.createElement('script');c.async=true;c.src=BASE+'/t/${token}/calls.js';(document.head||document.body).appendChild(c);})();
|
|
137
|
+
// data-cart="auto": Shopify's /cart/add (fetch, XHR; the response names product_id and sku) and WooCommerce's added_to_cart.
|
|
138
|
+
(function(){
|
|
139
|
+
if(attr('data-cart')!=='auto')return;
|
|
140
|
+
var re=/\\/cart\\/add(\\.js)?(\\?|$)/;
|
|
141
|
+
function items(j){if(!j)return;var l=j.items&&j.items.length?j.items:[j];for(var i=0;i<l.length;i++){var it=l[i];
|
|
142
|
+
if(it&&(it.product_id||it.sku))cartAdd({productId:it.product_id,sku:it.sku,quantity:it.quantity});}}
|
|
143
|
+
if(window.fetch){var of=window.fetch;window.fetch=function(a,b){var url=String(a&&a.url||a||''),r=of.apply(this,arguments);
|
|
144
|
+
if(re.test(url))r.then(function(res){if(res&&res.ok)res.clone().json().then(items,function(){});},function(){});return r;};}
|
|
145
|
+
var xo=window.XMLHttpRequest&&XMLHttpRequest.prototype.open;
|
|
146
|
+
if(xo){XMLHttpRequest.prototype.open=function(m,u){var self=this;
|
|
147
|
+
if(re.test(String(u||'')))this.addEventListener('load',function(){try{if(self.status<300)items(JSON.parse(self.responseText));}catch(e){}});
|
|
148
|
+
return xo.apply(this,arguments);};}
|
|
149
|
+
function woo(){var $=window.jQuery;if(!$)return;$(document.body).on('added_to_cart',function(e,f,h,btn){
|
|
150
|
+
var b=btn&&btn.data?btn:null;if(b)cartAdd({productId:b.data('product_id'),sku:b.data('product_sku'),quantity:b.data('quantity')});});}
|
|
151
|
+
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',woo);else woo();
|
|
152
|
+
})();
|
|
153
|
+
gate.start();
|
|
154
|
+
for(var qi=0;qi<queued.length;qi++)run(queued[qi]);
|
|
155
|
+
})();`;
|
|
156
|
+
}
|
|
157
|
+
/** The partner get-link bar, loaded by aff.js only on a page carrying a bar token (kept out of aff.js's size budget). */
|
|
158
|
+
function renderBarJs(token, baseUrl) {
|
|
159
|
+
return `(function(){
|
|
160
|
+
'use strict';
|
|
161
|
+
var BASE=${JSON.stringify(baseUrl)};
|
|
162
|
+
// Get-link bar for signed-in partners (data-partner-bar="on"). The portal opens the shop with #rl_pbar=<token>&rl_prg=<program>;
|
|
163
|
+
// the token goes to sessionStorage (no cookie) and the hash is removed. Fixed position: no layout shift. Never shown without a token.
|
|
164
|
+
(function(){
|
|
165
|
+
var SK='referalli_pbar',tok=null,prg=null;
|
|
166
|
+
try{var hp=new URLSearchParams(String(location.hash||'').replace(/^#/,''));var nt=hp.get('rl_pbar');
|
|
167
|
+
if(nt){sessionStorage.setItem(SK,JSON.stringify({t:nt,p:hp.get('rl_prg')}));hp.delete('rl_pbar');hp.delete('rl_prg');var rest=hp.toString();
|
|
168
|
+
history.replaceState(null,'',location.pathname+location.search+(rest?'#'+rest:''));}
|
|
169
|
+
var sv=JSON.parse(sessionStorage.getItem(SK)||'null');if(sv){tok=sv.t;prg=sv.p;}}catch(e){}
|
|
170
|
+
if(!tok||!prg)return;
|
|
171
|
+
function call(preview){return fetch(BASE+'/t/${token}/bar',{method:'POST',headers:{'content-type':'application/json'},
|
|
172
|
+
body:JSON.stringify({token:tok,programId:prg,url:location.origin+location.pathname+location.search,preview:preview})})
|
|
173
|
+
.then(function(r){return r.ok?r.json():null;},function(){return null;});}
|
|
174
|
+
call(true).then(function(j){
|
|
175
|
+
if(!j){try{sessionStorage.removeItem(SK);}catch(e){}return;}
|
|
176
|
+
var bar=document.createElement('div'),btn=document.createElement('button'),x=document.createElement('button');
|
|
177
|
+
bar.setAttribute('role','region');bar.setAttribute('aria-label','Partner link');
|
|
178
|
+
bar.style.cssText='position:fixed;left:50%;bottom:16px;transform:translateX(-50%);z-index:2147483000;display:flex;gap:4px;align-items:center;background:#111;color:#fff;border-radius:999px;padding:4px 6px 4px 4px;font:14px/1.2 system-ui,sans-serif;box-shadow:0 2px 12px rgba(0,0,0,.3)';
|
|
179
|
+
var css='border:0;background:transparent;color:inherit;font:inherit;cursor:pointer;padding:8px 12px;border-radius:999px';
|
|
180
|
+
btn.style.cssText=css;x.style.cssText=css;
|
|
181
|
+
btn.textContent='Get your link'+(j.earns?' · earns '+j.earns:'');x.textContent='×';x.setAttribute('aria-label','Close');
|
|
182
|
+
btn.onclick=function(){btn.textContent='Working…';call(false).then(function(r){
|
|
183
|
+
if(!r||!r.shortUrl){btn.textContent='No link for this page';return;}
|
|
184
|
+
var done=function(){btn.textContent='Link copied';};
|
|
185
|
+
try{navigator.clipboard.writeText(r.shortUrl).then(done,function(){window.prompt('Your link',r.shortUrl);});}catch(e){window.prompt('Your link',r.shortUrl);}});};
|
|
186
|
+
x.onclick=function(){try{sessionStorage.removeItem(SK);}catch(e){}bar.remove();};
|
|
187
|
+
bar.appendChild(btn);bar.appendChild(x);document.body.appendChild(bar);});
|
|
188
|
+
})();
|
|
189
|
+
})();`;
|
|
190
|
+
}
|
|
191
|
+
/** Pay-per-call number swap, loaded by aff.js on `data-calls="swap"`: rewrites only elements marked `data-referalli-phone`. */
|
|
192
|
+
function renderCallsJs(token, baseUrl) {
|
|
193
|
+
return `(function(){
|
|
194
|
+
'use strict';
|
|
195
|
+
var BASE=${JSON.stringify(baseUrl)},SK='referalli_call_number',tries=0;
|
|
196
|
+
function apply(j){
|
|
197
|
+
var els=document.querySelectorAll('[data-referalli-phone]');
|
|
198
|
+
for(var i=0;i<els.length;i++){var e=els[i];
|
|
199
|
+
if(e.tagName==='A'&&/^tel:/i.test(e.getAttribute('href')||''))e.setAttribute('href','tel:'+j.number);
|
|
200
|
+
e.textContent=j.display;}
|
|
201
|
+
}
|
|
202
|
+
function go(){
|
|
203
|
+
var a=window.aff;if(!a||!a.getReferral)return;
|
|
204
|
+
var anon=a.getReferral().anonId;
|
|
205
|
+
if(a.consentState()!=='granted'||!anon){if(++tries<10)setTimeout(go,1000);return;}
|
|
206
|
+
try{var c=JSON.parse(sessionStorage.getItem(SK)||'null');if(c&&c.a===anon){apply(c.j);return;}}catch(e){}
|
|
207
|
+
fetch(BASE+'/t/${token}/call-number?anonId='+encodeURIComponent(anon)).then(function(r){return r.ok?r.json():null;},function(){return null;}).then(function(j){
|
|
208
|
+
if(!j||!j.number)return;
|
|
209
|
+
try{sessionStorage.setItem(SK,JSON.stringify({a:anon,j:j}));}catch(e){}
|
|
210
|
+
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',function(){apply(j);});else apply(j);});
|
|
211
|
+
}
|
|
212
|
+
go();
|
|
213
|
+
})();`;
|
|
214
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.sha256 = sha256;
|
|
4
|
+
exports.hmacSha256 = hmacSha256;
|
|
5
|
+
/**
|
|
6
|
+
* Synchronous SHA-256 / HMAC-SHA256 in plain JavaScript, for the synchronous
|
|
7
|
+
* webhook verifier on runtimes without `node:crypto` (edge, Deno, Bun, browsers).
|
|
8
|
+
* The async verifier uses WebCrypto instead.
|
|
9
|
+
*/
|
|
10
|
+
const K = new Uint32Array([
|
|
11
|
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,
|
|
12
|
+
0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
|
|
13
|
+
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
|
|
14
|
+
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
|
15
|
+
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,
|
|
16
|
+
0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
|
|
17
|
+
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
|
18
|
+
]);
|
|
19
|
+
function sha256(data) {
|
|
20
|
+
const bitLen = data.length * 8;
|
|
21
|
+
const padded = new Uint8Array(((data.length + 9 + 63) >> 6) << 6);
|
|
22
|
+
padded.set(data);
|
|
23
|
+
padded[data.length] = 0x80;
|
|
24
|
+
const view = new DataView(padded.buffer);
|
|
25
|
+
view.setUint32(padded.length - 8, Math.floor(bitLen / 0x100000000));
|
|
26
|
+
view.setUint32(padded.length - 4, bitLen >>> 0);
|
|
27
|
+
const h = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);
|
|
28
|
+
const w = new Uint32Array(64);
|
|
29
|
+
const rotr = (x, n) => (x >>> n) | (x << (32 - n));
|
|
30
|
+
for (let off = 0; off < padded.length; off += 64) {
|
|
31
|
+
for (let i = 0; i < 16; i++)
|
|
32
|
+
w[i] = view.getUint32(off + i * 4);
|
|
33
|
+
for (let i = 16; i < 64; i++) {
|
|
34
|
+
const a = w[i - 15];
|
|
35
|
+
const b = w[i - 2];
|
|
36
|
+
const s0 = rotr(a, 7) ^ rotr(a, 18) ^ (a >>> 3);
|
|
37
|
+
const s1 = rotr(b, 17) ^ rotr(b, 19) ^ (b >>> 10);
|
|
38
|
+
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
|
|
39
|
+
}
|
|
40
|
+
let [a, b, c, d, e, f, g, hh] = [h[0], h[1], h[2], h[3], h[4], h[5], h[6], h[7]];
|
|
41
|
+
for (let i = 0; i < 64; i++) {
|
|
42
|
+
const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
|
|
43
|
+
const ch = (e & f) ^ (~e & g);
|
|
44
|
+
const t1 = (hh + s1 + ch + K[i] + w[i]) >>> 0;
|
|
45
|
+
const s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
|
|
46
|
+
const maj = (a & b) ^ (a & c) ^ (b & c);
|
|
47
|
+
const t2 = (s0 + maj) >>> 0;
|
|
48
|
+
hh = g;
|
|
49
|
+
g = f;
|
|
50
|
+
f = e;
|
|
51
|
+
e = (d + t1) >>> 0;
|
|
52
|
+
d = c;
|
|
53
|
+
c = b;
|
|
54
|
+
b = a;
|
|
55
|
+
a = (t1 + t2) >>> 0;
|
|
56
|
+
}
|
|
57
|
+
h[0] = (h[0] + a) >>> 0;
|
|
58
|
+
h[1] = (h[1] + b) >>> 0;
|
|
59
|
+
h[2] = (h[2] + c) >>> 0;
|
|
60
|
+
h[3] = (h[3] + d) >>> 0;
|
|
61
|
+
h[4] = (h[4] + e) >>> 0;
|
|
62
|
+
h[5] = (h[5] + f) >>> 0;
|
|
63
|
+
h[6] = (h[6] + g) >>> 0;
|
|
64
|
+
h[7] = (h[7] + hh) >>> 0;
|
|
65
|
+
}
|
|
66
|
+
const out = new Uint8Array(32);
|
|
67
|
+
const ov = new DataView(out.buffer);
|
|
68
|
+
for (let i = 0; i < 8; i++)
|
|
69
|
+
ov.setUint32(i * 4, h[i]);
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
function hmacSha256(key, message) {
|
|
73
|
+
let k = key.length > 64 ? sha256(key) : key;
|
|
74
|
+
const block = new Uint8Array(64);
|
|
75
|
+
block.set(k);
|
|
76
|
+
k = block;
|
|
77
|
+
const inner = new Uint8Array(64 + message.length);
|
|
78
|
+
const outer = new Uint8Array(64 + 32);
|
|
79
|
+
for (let i = 0; i < 64; i++) {
|
|
80
|
+
inner[i] = k[i] ^ 0x36;
|
|
81
|
+
outer[i] = k[i] ^ 0x5c;
|
|
82
|
+
}
|
|
83
|
+
inner.set(message, 64);
|
|
84
|
+
outer.set(sha256(inner), 64);
|
|
85
|
+
return sha256(outer);
|
|
86
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { type ReferralContext } from './attribution.js';
|
|
2
|
+
import { type ConsentEvidence, type ConsentOptions, type ConsentState } from './consent/port.js';
|
|
3
|
+
/**
|
|
4
|
+
* Browser tracking snippet, written against an injected environment so the
|
|
5
|
+
* logic is unit-testable without a DOM. The served `aff.js` (see served.ts)
|
|
6
|
+
* wraps this with the real window/document/fetch.
|
|
7
|
+
*/
|
|
8
|
+
export interface SnippetEnv {
|
|
9
|
+
win: {
|
|
10
|
+
location: {
|
|
11
|
+
href: string;
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
doc: {
|
|
15
|
+
cookie: string;
|
|
16
|
+
};
|
|
17
|
+
storage: {
|
|
18
|
+
getItem(key: string): string | null;
|
|
19
|
+
setItem(key: string, value: string): void;
|
|
20
|
+
removeItem?(key: string): void;
|
|
21
|
+
} | null;
|
|
22
|
+
fetchFn: (url: string, init: {
|
|
23
|
+
method: string;
|
|
24
|
+
headers: Record<string, string>;
|
|
25
|
+
body?: string;
|
|
26
|
+
}) => Promise<unknown>;
|
|
27
|
+
randomId?: () => string;
|
|
28
|
+
now?: () => number;
|
|
29
|
+
/**
|
|
30
|
+
* The window the consent adapters read CMP globals from and set timers on
|
|
31
|
+
* (`window` in a browser). Default `globalThis`.
|
|
32
|
+
*/
|
|
33
|
+
consentWindow?: unknown;
|
|
34
|
+
}
|
|
35
|
+
export interface SnippetConfig {
|
|
36
|
+
token: string;
|
|
37
|
+
baseUrl: string;
|
|
38
|
+
/** Query params that carry a referral code; default via/ref/aff. */
|
|
39
|
+
params?: string[];
|
|
40
|
+
/**
|
|
41
|
+
* `referral-only`: store and send nothing unless the URL carries a referral
|
|
42
|
+
* (use it before consent). Default `always`.
|
|
43
|
+
*/
|
|
44
|
+
persist?: 'always' | 'referral-only';
|
|
45
|
+
/** How long the context is kept, 1–400 days. Default 60. */
|
|
46
|
+
cookieDays?: number;
|
|
47
|
+
/** Keep the first referral instead of replacing it (first_click programs). */
|
|
48
|
+
firstTouch?: boolean;
|
|
49
|
+
/** Share the cookie with subdomains, e.g. `.app.com`. */
|
|
50
|
+
cookieDomain?: string;
|
|
51
|
+
/** Older storage/cookie names to read a saved context from (it is re-saved under the current name). */
|
|
52
|
+
legacyKeys?: string[];
|
|
53
|
+
/**
|
|
54
|
+
* How visitor consent is read before anything is stored or sent: a mode
|
|
55
|
+
* (`'auto'`, `'pending'`, `'onetrust'`, …) or a full config. Default
|
|
56
|
+
* `'none'` (always store, the behaviour before consent support). Until
|
|
57
|
+
* consent is granted the context is kept in memory only.
|
|
58
|
+
*/
|
|
59
|
+
consent?: ConsentOptions;
|
|
60
|
+
}
|
|
61
|
+
export type { ReferralContext } from './attribution.js';
|
|
62
|
+
export interface AffApi {
|
|
63
|
+
getReferral(): ReferralContext;
|
|
64
|
+
/** Referral context keyed for auth-platform signup metadata. */
|
|
65
|
+
signupMetadata(): {
|
|
66
|
+
referalli_click_id?: string;
|
|
67
|
+
referalli_anon_id: string;
|
|
68
|
+
referalli_coupon?: string;
|
|
69
|
+
};
|
|
70
|
+
identify(opts: {
|
|
71
|
+
customerRef?: string;
|
|
72
|
+
emailHash?: string;
|
|
73
|
+
}): Promise<void>;
|
|
74
|
+
/**
|
|
75
|
+
* The context as a signed, 24-hour hand-off token to keep in your own session
|
|
76
|
+
* and pass to `associate` as `handoffToken` (no cookie needed at sign-up).
|
|
77
|
+
* Null with no context, after `forget()` or a denial, or on a network error.
|
|
78
|
+
*/
|
|
79
|
+
getHandoffToken(): Promise<string | null>;
|
|
80
|
+
/**
|
|
81
|
+
* Record a cart add (product id or SKU) for the cart extension: sent only after consent, for a visitor who came through
|
|
82
|
+
* a referral; the server stores it while the referral is live and the program's `cartWindowDays` is on.
|
|
83
|
+
*/
|
|
84
|
+
cartAdd(opts: {
|
|
85
|
+
productId?: string | number;
|
|
86
|
+
sku?: string;
|
|
87
|
+
quantity?: number;
|
|
88
|
+
}): void;
|
|
89
|
+
/** Delete the stored context (consent withdrawn) and stop sending. */
|
|
90
|
+
forget(): void;
|
|
91
|
+
/** The push path for pages without a supported CMP. Idempotent; the latest signal wins. */
|
|
92
|
+
consent(granted: boolean): void;
|
|
93
|
+
consentState(): ConsentState;
|
|
94
|
+
/** The evidence the visit beacon carried; pass it to `associate` as `consent`. Null before a decision. */
|
|
95
|
+
consentEvidence(): ConsentEvidence | null;
|
|
96
|
+
/** The adapter in use (`onetrust`, …), `auto` while looking, `no-cmp`, `none` or `pending`. */
|
|
97
|
+
readonly consentMode: string;
|
|
98
|
+
}
|
|
99
|
+
export declare function initSnippet(env: SnippetEnv, config: SnippetConfig): Promise<AffApi>;
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.initSnippet = initSnippet;
|
|
4
|
+
const attribution_js_1 = require("./attribution.js");
|
|
5
|
+
const gate_js_1 = require("./consent/gate.js");
|
|
6
|
+
const port_js_1 = require("./consent/port.js");
|
|
7
|
+
const registry_js_1 = require("./consent/registry.js");
|
|
8
|
+
/**
|
|
9
|
+
* Every key the context is written under: `referalli_ctx` and its legacy twin
|
|
10
|
+
* `referally_ctx` (see LEGACY_REFERRAL_COOKIE for when the twin can go).
|
|
11
|
+
*/
|
|
12
|
+
const WRITE_KEYS = attribution_js_1.REFERRAL_COOKIE_NAMES;
|
|
13
|
+
function readCookie(doc, key) {
|
|
14
|
+
for (const part of doc.cookie.split(';')) {
|
|
15
|
+
const [k, ...rest] = part.trim().split('=');
|
|
16
|
+
if (k === key)
|
|
17
|
+
return decodeURIComponent(rest.join('='));
|
|
18
|
+
}
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
function loadContext(env, now, legacyKeys = []) {
|
|
22
|
+
for (const key of new Set([...WRITE_KEYS, ...legacyKeys])) {
|
|
23
|
+
let raw = null;
|
|
24
|
+
try {
|
|
25
|
+
raw = env.storage?.getItem(key) ?? null;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
/* storage may be unavailable */
|
|
29
|
+
}
|
|
30
|
+
raw ??= readCookie(env.doc, key);
|
|
31
|
+
const ctx = (0, attribution_js_1.parseReferral)(raw, now);
|
|
32
|
+
if (ctx)
|
|
33
|
+
return ctx;
|
|
34
|
+
}
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
function cookieFlags(env, config) {
|
|
38
|
+
const domain = config.cookieDomain && /^\.?[a-z0-9.-]+$/i.test(config.cookieDomain) ? `; domain=${config.cookieDomain}` : '';
|
|
39
|
+
const secure = env.win.location.href.startsWith('https:') ? '; Secure' : '';
|
|
40
|
+
return `; path=/; SameSite=Lax${domain}${secure}`;
|
|
41
|
+
}
|
|
42
|
+
function persistContext(env, config, ctx, days) {
|
|
43
|
+
const raw = JSON.stringify(ctx);
|
|
44
|
+
// Same value, attributes and expiry under every name.
|
|
45
|
+
const tail = `=${encodeURIComponent(raw)}; max-age=${days * 86_400}${cookieFlags(env, config)}`;
|
|
46
|
+
for (const key of WRITE_KEYS) {
|
|
47
|
+
try {
|
|
48
|
+
env.storage?.setItem(key, raw);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
/* storage may be unavailable */
|
|
52
|
+
}
|
|
53
|
+
try {
|
|
54
|
+
env.doc.cookie = `${key}${tail}`;
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
/* cookie write may be blocked */
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
async function initSnippet(env, config) {
|
|
62
|
+
const now = env.now?.() ?? Date.now();
|
|
63
|
+
const days = (0, attribution_js_1.clampDays)(config.cookieDays);
|
|
64
|
+
const { code, clickId: clickIdParam } = (0, attribution_js_1.referralFromUrl)(env.win.location.href, config.params ?? attribution_js_1.REFERRAL_PARAMS);
|
|
65
|
+
const referred = Boolean(code || clickIdParam);
|
|
66
|
+
const subParam = (() => {
|
|
67
|
+
try {
|
|
68
|
+
const v = new URL(env.win.location.href).searchParams.get('sub');
|
|
69
|
+
return v && /^[A-Za-z0-9_.-]{1,64}$/.test(v) ? v : undefined;
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
})();
|
|
75
|
+
const stored = loadContext(env, now, config.legacyKeys);
|
|
76
|
+
// First touch keeps a stored referral until it expires.
|
|
77
|
+
const ctx = (0, attribution_js_1.mergeReferral)(stored, { code, clickId: clickIdParam }, {
|
|
78
|
+
now,
|
|
79
|
+
cookieDays: days,
|
|
80
|
+
firstTouch: config.firstTouch,
|
|
81
|
+
randomId: env.randomId ?? attribution_js_1.newAnonId,
|
|
82
|
+
});
|
|
83
|
+
const active = config.persist !== 'referral-only' || referred;
|
|
84
|
+
let gone = false;
|
|
85
|
+
let dropped = false;
|
|
86
|
+
let sent = null;
|
|
87
|
+
let state = 'unknown';
|
|
88
|
+
let pendingIdentify = null;
|
|
89
|
+
const post = (path, body) => gone || dropped
|
|
90
|
+
? Promise.resolve()
|
|
91
|
+
: env.fetchFn(`${config.baseUrl}${path}`, {
|
|
92
|
+
method: 'POST',
|
|
93
|
+
headers: { 'content-type': 'application/json' },
|
|
94
|
+
body: JSON.stringify(body),
|
|
95
|
+
});
|
|
96
|
+
const clearStorage = () => {
|
|
97
|
+
for (const key of new Set([...WRITE_KEYS, ...(config.legacyKeys ?? [])])) {
|
|
98
|
+
try {
|
|
99
|
+
env.storage?.removeItem?.(key);
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
/* storage may be unavailable */
|
|
103
|
+
}
|
|
104
|
+
try {
|
|
105
|
+
env.doc.cookie = `${key}=; max-age=0${cookieFlags(env, config)}`;
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
/* cookie write may be blocked */
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
const sendIdentify = (opts) => post(`/t/${config.token}/identify`, {
|
|
113
|
+
anonId: ctx.anonId,
|
|
114
|
+
customerRef: opts.customerRef,
|
|
115
|
+
emailHash: opts.emailHash,
|
|
116
|
+
}).catch(() => { });
|
|
117
|
+
const onConsent = (next, evidence) => {
|
|
118
|
+
state = next;
|
|
119
|
+
if (next === 'granted') {
|
|
120
|
+
dropped = false;
|
|
121
|
+
if (active && !gone) {
|
|
122
|
+
persistContext(env, config, ctx, days);
|
|
123
|
+
// Server-side visit record: the session exists even if all storage is wiped.
|
|
124
|
+
sent ??= post(`/t/${config.token}/visit`, {
|
|
125
|
+
anonId: ctx.anonId,
|
|
126
|
+
code: ctx.code ?? undefined,
|
|
127
|
+
clickId: ctx.clickId ?? undefined,
|
|
128
|
+
url: env.win.location.href,
|
|
129
|
+
sub: subParam,
|
|
130
|
+
...(evidence ? { consent: evidence } : {}),
|
|
131
|
+
}).catch(() => { });
|
|
132
|
+
}
|
|
133
|
+
if (pendingIdentify) {
|
|
134
|
+
const queued = pendingIdentify;
|
|
135
|
+
pendingIdentify = null;
|
|
136
|
+
void sendIdentify(queued);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
else if (next === 'denied') {
|
|
140
|
+
clearStorage();
|
|
141
|
+
dropped = true;
|
|
142
|
+
pendingIdentify = null;
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
const consentCfg = (0, port_js_1.consentConfig)(config.consent);
|
|
146
|
+
const gate = (0, gate_js_1.consentGate)(env.consentWindow ?? globalThis, consentCfg, (0, registry_js_1.adapterFactories)(port_js_1.AUTO_ORDER), port_js_1.AUTO_ORDER, onConsent);
|
|
147
|
+
gate.start();
|
|
148
|
+
if (sent)
|
|
149
|
+
await sent;
|
|
150
|
+
const view = () => gone || dropped ? { anonId: '', code: null, clickId: null, ts: 0 } : { anonId: ctx.anonId, code: ctx.code, clickId: ctx.clickId, ts: ctx.ts };
|
|
151
|
+
return {
|
|
152
|
+
getReferral: view,
|
|
153
|
+
/**
|
|
154
|
+
* Referral context shaped for an auth platform's signup metadata. Spread
|
|
155
|
+
* into Clerk's `unsafeMetadata`, Supabase's `data`, or an Auth.js signup
|
|
156
|
+
* so the connector can attribute the new user server-side.
|
|
157
|
+
*/
|
|
158
|
+
signupMetadata: () => {
|
|
159
|
+
const v = view();
|
|
160
|
+
return {
|
|
161
|
+
referalli_click_id: v.clickId ?? undefined,
|
|
162
|
+
referalli_anon_id: v.anonId,
|
|
163
|
+
referalli_coupon: v.code ?? undefined,
|
|
164
|
+
};
|
|
165
|
+
},
|
|
166
|
+
identify: async (opts) => {
|
|
167
|
+
if (gone || dropped || (!active && !stored))
|
|
168
|
+
return;
|
|
169
|
+
// Before a decision, hold it: it is sent once consent is granted.
|
|
170
|
+
if (state !== 'granted') {
|
|
171
|
+
pendingIdentify = opts;
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
await sendIdentify(opts);
|
|
175
|
+
},
|
|
176
|
+
getHandoffToken: async () => {
|
|
177
|
+
const v = view();
|
|
178
|
+
if (!v.anonId)
|
|
179
|
+
return null;
|
|
180
|
+
try {
|
|
181
|
+
const res = (await env.fetchFn(`${config.baseUrl}/t/${config.token}/handoff`, {
|
|
182
|
+
method: 'POST',
|
|
183
|
+
headers: { 'content-type': 'application/json' },
|
|
184
|
+
body: JSON.stringify({ anonId: v.anonId, clickId: v.clickId ?? undefined, code: v.code ?? undefined }),
|
|
185
|
+
}));
|
|
186
|
+
if (!res?.ok || !res.json)
|
|
187
|
+
return null;
|
|
188
|
+
return (await res.json()).handoffToken ?? null;
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
},
|
|
194
|
+
cartAdd: (o) => {
|
|
195
|
+
const productId = o.productId != null && o.productId !== '' ? String(o.productId) : undefined;
|
|
196
|
+
if (gone || dropped || state !== 'granted' || !(ctx.code || ctx.clickId) || (!productId && !o.sku))
|
|
197
|
+
return;
|
|
198
|
+
const q = Math.floor(Number(o.quantity));
|
|
199
|
+
void post(`/t/${config.token}/cart`, { anonId: ctx.anonId, productId, sku: o.sku, quantity: q > 0 ? q : undefined }).catch(() => { });
|
|
200
|
+
},
|
|
201
|
+
forget: () => {
|
|
202
|
+
gone = true;
|
|
203
|
+
gate.stop();
|
|
204
|
+
clearStorage();
|
|
205
|
+
},
|
|
206
|
+
consent: (granted) => gate.push(granted === true),
|
|
207
|
+
consentState: () => state,
|
|
208
|
+
consentEvidence: () => gate.evidence(),
|
|
209
|
+
get consentMode() {
|
|
210
|
+
return gate.mode();
|
|
211
|
+
},
|
|
212
|
+
};
|
|
213
|
+
}
|