Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(traffic): follow an AI visitor to conversions in the tracking snippet, consent first (CE-017, part 2) (#1528)

Cihan1ed971dfc977
diff --git a/server/src/lib/tracking-script.js b/server/src/lib/tracking-script.js
index 95bf3e5e0..6f615b6a1 100644
--- a/server/src/lib/tracking-script.js
+++ b/server/src/lib/tracking-script.js
@@ -28,11 +28,50 @@
* on: the server marks that visit's pageview, it doesn't count another
* (gkhngyk on #1247).
*
+ * Conversions (CE-017, 00286), only on a brand that turned them on and
+ * installed the tag with data-c="1": everything above stays as it was
+ * without it, and nothing is kept in the browser. With it, a visitor who
+ * came from an AI assistant gets a random id (ansvisor_v in localStorage,
+ * with the first AI visit: source, page and time), and the snippet sends
+ * the pages they go on to (k: "pv"), the forms they send and the site's
+ * own ansvisor('conversion', …) calls (k: "cv"), each with that first
+ * visit, for 30 days from it (first touch). The id is kept only once the
+ * site says the visitor agreed (data-consent="wait", the default):
+ * ansvisor('consent', 'granted'), or Google Consent Mode granting
+ * analytics_storage in an update, or in a default on the page before t.js
+ * that names no region (a regional default, "denied in the EU", can't say
+ * which this visitor got; a default after t.js only ever pauses). An id
+ * kept earlier says the visitor agreed then, on the pages after.
+ * Until then events wait on the page; ansvisor('consent', 'denied'), or a
+ * Consent Mode update taking analytics_storage back, deletes the stored id
+ * and what waited, and a default that denies it only pauses. The page keeps
+ * the id in memory, so a grant later on it (a banner pushing "denied" until
+ * the visitor chooses, a visitor changing their mind) still keeps the AI
+ * landing. Calls queued before t.js run consent first, so a queued
+ * "denied" comes before anything is sent. data-consent="always" keeps it at
+ * once, for a site whose own banner covers it, unless Consent Mode says
+ * otherwise. Pages go without their query string, forms without anything
+ * typed in them; an id past its 30 days is deleted. A visitor it doesn't
+ * follow (no AI visit, no id kept) gets no hooks: no dataLayer made, no
+ * wrapped push or pushState, no submit listener; and the hooks it adds
+ * never stop the site's own push or route change.
+ *
+ * Forms: one with an email field counts as a signup once per page, unless
+ * it says otherwise (data-ansvisor-goal="demo", "newsletter"…) or opts out
+ * (data-ansvisor="off"); one with a password field counts only as a signup
+ * (autocomplete="new-password"), not as a login, or when it says its goal.
+ * Not seen: forms in an iframe (a Typeform, a Calendly) or a shadow root,
+ * form.submit() from script, posts without a form, and journeys across
+ * subdomains (storage is per origin). ansvisor() may be called before t.js
+ * loads (from GTM, say) through the queue stub:
+ * window.ansvisor = window.ansvisor || function () { (ansvisor.q = ansvisor.q || []).push(arguments) };
+ *
* Plain ES5 apart from URL / URLSearchParams, as before: it runs on the
* customer's pages, in whatever browser their visitors have.
*/
import { AI_SOURCES, AI_SOURCES_VERSION } from './ai-sources.js';
+import { CONVERSION_GOALS } from './traffic-events.js';
/** The list in the snippet's compact shape: k key, h hosts, a aliases, p referrer path, u 0 = not by utm. */
export function snippetSources() {
@@ -64,9 +103,10 @@ return"";
}
var pf=m(h,false);
if(!pf){try{pf=m(new URLSearchParams(location.search).get("utm_source"),true)}catch(e){}}
-if(!pf)return;
+var c=document.currentScript,cv=!!c&&c.getAttribute("data-c")==="1";
+if(!pf&&!cv)return;
window.__at=1;
-var c=document.currentScript,k=c.getAttribute("data-t"),o=c.src.replace(/\\/t\\.js(\\?.*)?$/,"");
+var k=c.getAttribute("data-t"),o=c.src.replace(/\\/t\\.js(\\?.*)?$/,"");
var u=location.href,st=0,x=o+"/track/"+k;
try{var n=performance.getEntriesByType("navigation")[0];st=n&&n.responseStatus||0}catch(e){}
function post(d){
@@ -78,12 +118,83 @@ function nfOf(ti){
if(!st)return /(^|[^0-9])404([^0-9]|$)|not found/i.test(ti)?1:0;
return st>199&&st<300&&/(^|[|:\\u00b7\\u2022\\u2013\\u2014-]\\s*)(404 page not found|404 not found|404 error|error 404|page not found|not found|404)\\s*([|:\\u00b7\\u2022\\u2013\\u2014-]|$)/i.test(ti)?1:0;
}
+if(pf){
var nf=nfOf(document.title||"");
post({u:u,r:r,s:pf,v:V,a:navigator.userAgent,t:Date.now(),l:navigator.language,d:screen.width+"x"+screen.height,st:st,nf:nf});
if(!nf&&(!st||st>199&&st<300)){
var again=function(){setTimeout(function(){if(nfOf(document.title||""))post({k:"nf",u:u,s:pf,a:navigator.userAgent,st:st})},1500)};
if(document.readyState==="complete")again();else window.addEventListener("load",again);
}
+}
+if(!cv)return;
+var G=${JSON.stringify(CONVERSION_GOALS)},K="ansvisor_v",W=2592e6,now=Date.now();
+var ok=!1,q=[],v=null,old=!1,last="";
+function here(){return location.origin+location.pathname}
+try{var j=JSON.parse(localStorage.getItem(K)||"null");if(j&&j.id&&j.f&&now-j.f.at<W){v=j;old=!0}else if(j)localStorage.removeItem(K)}catch(e){}
+if(!v&&pf){
+var a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",id="",rb=null;
+try{rb=crypto.getRandomValues(new Uint8Array(22))}catch(e){}
+for(var i=0;i<22;i++)id+=a.charAt((rb?rb[i]:Math.floor(Math.random()*256))&63);
+v={id:id,f:{s:pf,u:here(),at:now}};
+}
+function keep(){if(v)try{localStorage.setItem(K,JSON.stringify(v))}catch(e){}}
+function send(d){if(!v)return;d.id=v.id;d.f=v.f;d.u=d.u||here();if(ok)post(d);else q.push(d)}
+function grant(){ok=!0;keep();var w=q;q=[];for(var i=0;i<w.length;i++)post(w[i])}
+function deny(){ok=!1;q=[];try{localStorage.removeItem(K)}catch(e){}}
+function pv(){var p=here();if(p===last)return;last=p;send({k:"pv"})}
+function gc(it){return it&&it[0]==="consent"&&it[2]&&it[2].analytics_storage?it:null}
+var dl=window.dataLayer||[],up="",df="",rg=!1;
+for(var i=0;i<dl.length;i++){var it=gc(dl[i]);if(!it)continue;if(it[1]==="update")up=it[2].analytics_storage;else if(it[2].region)rg=!0;else df=it[2].analytics_storage}
+if(up==="denied")deny();
+else if(up==="granted")ok=!0;
+else if(df==="denied")ok=!1;
+else if(rg)ok=old;
+else ok=df==="granted"||old||c.getAttribute("data-consent")==="always";
+function num(x,max,whole){if(typeof x==="string"&&x!=="")x=+x;return typeof x==="number"&&isFinite(x)&&x>=0&&x<=max&&(!whole||x%1===0)?x:void 0}
+function cmd(t,a){
+if(t==="consent"){if(a==="granted")grant();else if(a==="denied")deny();return}
+if(t!=="conversion")return;
+if(typeof a==="string")a={type:a};
+a=a||{};
+var g=String(a.type||a.goal||"custom"),known=G.indexOf(g)!==-1,d={k:"cv",g:known?g:"custom",o:"call"},x;
+if(a.label||!known)d.n=String(a.label||g).slice(0,80);
+x=num(a.value,1e9);if(x!==void 0)d.val=x;
+if(a.currency)d.cur=String(a.currency).slice(0,10);
+x=num(a.units,1e5,!0);if(x!==void 0)d.q=x;
+if(a.order!=null)d.ref=String(a.order).slice(0,200);
+send(d);
+}
+var Q=window.ansvisor&&window.ansvisor.q||[];
+window.ansvisor=function(t,a){cmd(t,a)};
+for(var i=0;i<Q.length;i++)if(Q[i][0]==="consent")cmd(Q[i][0],Q[i][1]);
+for(var i=0;i<Q.length;i++)if(Q[i][0]!=="consent")cmd(Q[i][0],Q[i][1]);
+if(!v)return;
+window.dataLayer=dl;
+if(ok)keep();
+if(old)pv();else last=here();
+var dp=dl.push;
+dl.push=function(){
+try{for(var i=0;i<arguments.length;i++){var it=gc(arguments[i]);if(!it)continue;var s=it[2].analytics_storage;
+if(it[1]==="update"){if(s==="granted")grant();else deny()}else if(s==="denied")ok=!1}}catch(e){}
+return dp.apply(dl,arguments);
+};
+document.addEventListener("submit",function(e){
+var f=e.target;
+if(!v||!f||f.tagName!=="FORM"||f.__av||f.getAttribute("data-ansvisor")==="off")return;
+var g=f.getAttribute("data-ansvisor-goal");
+if(!g){
+if(!f.querySelector("input[type=email],input[name*=email]"))return;
+if(f.querySelector("input[type=password]")&&!f.querySelector("input[autocomplete=new-password]"))return;
+g="signup";
+}
+f.__av=1;
+var d={k:"cv",g:G.indexOf(g)!==-1?g:"custom",o:"form"},n=f.getAttribute("data-ansvisor-label")||f.getAttribute("id")||f.getAttribute("name");
+if(n)d.n=String(n).slice(0,80);
+send(d);
+},!0);
+var hp=window.history&&history.pushState;
+if(hp)history.pushState=function(){var res=hp.apply(history,arguments);try{pv()}catch(e){}return res};
+window.addEventListener("popstate",function(){try{pv()}catch(e){}});
})();
`;
}
diff --git a/server/src/lib/tracking-script.test.js b/server/src/lib/tracking-script.test.js
index d903bb88b..b81a32187 100644
--- a/server/src/lib/tracking-script.test.js
+++ b/server/src/lib/tracking-script.test.js
@@ -8,6 +8,7 @@ import {
landingMedium,
} from './ai-sources.js';
import { buildTrackingScript } from './tracking-script.js';
+import { eventRow } from './traffic-events.js';
/**
* The tracking snippet (AT-004) counts what the AI source list counts, the
@@ -269,3 +270,484 @@ describe('the tracking snippet', () => {
}
});
});
+
+/**
+ * Runs t.js installed with conversions (data-c="1", CE-017) on a page of the
+ * site: `stored` is what localStorage already holds, `dataLayer` Google's,
+ * `queue` the site's calls made before t.js loaded. Returns the beacons, the
+ * storage, and the page's window, document listeners and history to go on.
+ */
+function runWithConversions({
+ referrer = '',
+ path = '/pricing',
+ consent = null,
+ stored = null,
+ dataLayer,
+ queue,
+ installed = true,
+ crypto,
+ storageThrows = false,
+} = {}) {
+ const sent = [];
+ let sendsFail = false;
+ const storage = new Map(stored ? [['ansvisor_v', JSON.stringify(stored)]] : []);
+ const listeners = {};
+ const on = (scope) => (type, fn) => (listeners[`${scope}:${type}`] ||= []).push(fn);
+ const window = { addEventListener: on('window') };
+ if (dataLayer) window.dataLayer = dataLayer;
+ if (queue) window.ansvisor = { q: queue };
+ const attributes = {
+ 'data-t': 'abcdef123',
+ ...(installed ? { 'data-c': '1' } : {}),
+ ...(consent ? { 'data-consent': consent } : {}),
+ };
+ const location = {
+ origin: 'https://acme.example',
+ pathname: path,
+ href: `https://acme.example${path}[email protected]`,
+ search: '[email protected]',
+ };
+ const history = { pushState: (state, title, url) => (location.pathname = url) };
+ window.history = history;
+ const context = {
+ window,
+ document: {
+ title: 'Acme',
+ referrer,
+ readyState: 'complete',
+ addEventListener: on('document'),
+ currentScript: {
+ src: 'https://api.ansvisor.test/t.js',
+ getAttribute: (name) => attributes[name] ?? null,
+ },
+ },
+ location,
+ history,
+ localStorage: storageThrows
+ ? {
+ getItem: () => {
+ throw new Error('SecurityError');
+ },
+ setItem: () => {
+ throw new Error('QuotaExceededError');
+ },
+ removeItem: () => {
+ throw new Error('SecurityError');
+ },
+ }
+ : {
+ getItem: (key) => storage.get(key) ?? null,
+ setItem: (key, value) => storage.set(key, String(value)),
+ removeItem: (key) => storage.delete(key),
+ },
+ ...(crypto ? { crypto } : {}),
+ setTimeout: () => {},
+ navigator: {
+ userAgent: 'Mozilla/5.0',
+ language: 'en-US',
+ sendBeacon: (url, blob) => {
+ if (sendsFail) throw new Error('beacon failed');
+ sent.push({ url, blob });
+ },
+ },
+ screen: { width: 1440, height: 900 },
+ URL,
+ URLSearchParams,
+ Blob: class {
+ constructor(parts) {
+ this.text = parts.join('');
+ }
+ },
+ JSON,
+ Date,
+ String,
+ };
+ runInNewContext(SCRIPT, context);
+ return {
+ get beacons() {
+ return sent.map((b) => JSON.parse(b.blob.text));
+ },
+ get stored() {
+ return storage.has('ansvisor_v') ? JSON.parse(storage.get('ansvisor_v')) : null;
+ },
+ window,
+ history,
+ storage,
+ submit: (form) => (listeners['document:submit'] || []).forEach((fn) => fn({ target: form })),
+ listeners,
+ location,
+ failSends: () => {
+ sendsFail = true;
+ },
+ popstate: () => (listeners['window:popstate'] || []).forEach((fn) => fn()),
+ };
+}
+
+/** A form as the submit listener reads it: its attributes and the inputs it has. */
+const form = (attributes = {}, inputs = ['email']) => ({
+ tagName: 'FORM',
+ // An input named "id" shadows the property: the snippet reads the attribute.
+ id: { tagName: 'INPUT' },
+ getAttribute: (name) => attributes[name] ?? null,
+ // An input matches [attr=value] by its value, [attr*=value] by part of it.
+ querySelector: (selector) =>
+ [...selector.matchAll(/(\*?)=([\w-]+)\]/g)].some(([, part, value]) =>
+ inputs.some((input) => (part ? input.includes(value) : input === value)),
+ )
+ ? {}
+ : null,
+});
+
+const DAY = 24 * 60 * 60 * 1000;
+const earlier = (days, extra = {}) => ({
+ id: 'Vq3xT0mZ8kLp2RwYbN5sQa',
+ f: { s: 'chatgpt.com', u: 'https://acme.example/blog/crm', at: Date.now() - days * DAY },
+ ...extra,
+});
+
+describe('the tracking snippet with conversions (CE-017)', () => {
+ it('keeps nothing in the browser and sends nothing new without data-c', () => {
+ const page = runWithConversions({
+ referrer: 'https://chatgpt.com/',
+ installed: false,
+ consent: 'always',
+ });
+ expect(page.beacons).toHaveLength(1);
+ expect(page.stored).toBeNull();
+ expect(page.window.ansvisor).toBeUndefined();
+ // Other traffic, as ever: nothing at all.
+ expect(runWithConversions({ installed: false }).beacons).toEqual([]);
+ });
+
+ it('keeps an AI visitor’s id only once the site says they agreed, and sends what waited then', () => {
+ const page = runWithConversions({ referrer: 'https://chatgpt.com/', path: '/blog/crm' });
+ // The visit goes as ever; the id waits.
+ expect(page.beacons).toHaveLength(1);
+ expect(page.stored).toBeNull();
+ page.window.ansvisor('conversion', { type: 'newsletter' });
+ expect(page.beacons).toHaveLength(1);
+
+ page.window.ansvisor('consent', 'granted');
+ expect(page.stored).toMatchObject({
+ id: expect.stringMatching(/^[A-Za-z0-9_-]{22}$/),
+ f: { s: 'chatgpt.com', u: 'https://acme.example/blog/crm' },
+ });
+ expect(page.beacons[1]).toMatchObject({
+ k: 'cv',
+ g: 'newsletter',
+ o: 'call',
+ id: page.stored.id,
+ f: page.stored.f,
+ // Never the query string.
+ u: 'https://acme.example/blog/crm',
+ });
+ });
+
+ it('keeps it at once with data-consent="always", and takes it back when the visitor says no', () => {
+ const page = runWithConversions({ referrer: 'https://perplexity.ai/', consent: 'always' });
+ expect(page.stored.f.s).toBe('perplexity.ai');
+ page.window.ansvisor('consent', 'denied');
+ expect(page.stored).toBeNull();
+ page.window.ansvisor('conversion', { type: 'signup' });
+ expect(page.beacons).toHaveLength(1);
+ });
+
+ it('follows Google Consent Mode: a grant keeps the id, an update that takes it back deletes it', () => {
+ const dataLayer = [['consent', 'default', { analytics_storage: 'denied' }]];
+ const page = runWithConversions({ referrer: 'https://chatgpt.com/', dataLayer });
+ expect(page.stored).toBeNull();
+ dataLayer.push(['consent', 'update', { analytics_storage: 'granted' }]);
+ expect(page.stored).not.toBeNull();
+ dataLayer.push(['consent', 'update', { analytics_storage: 'denied' }]);
+ expect(page.stored).toBeNull();
+ });
+
+ it('sends the pages an AI visitor goes on to, single-page app routes too, without repeats', () => {
+ const stored = earlier(2);
+ const page = runWithConversions({ stored, consent: 'always' });
+ expect(page.beacons).toEqual([
+ {
+ k: 'pv',
+ id: 'Vq3xT0mZ8kLp2RwYbN5sQa',
+ f: stored.f,
+ u: 'https://acme.example/pricing',
+ },
+ ]);
+ page.history.pushState({}, '', '/demo');
+ page.popstate();
+ expect(page.beacons.map((b) => b.u)).toEqual([
+ 'https://acme.example/pricing',
+ 'https://acme.example/demo',
+ ]);
+ });
+
+ it('credits the first AI visit: a later one keeps it; past 30 days a new journey starts', () => {
+ const again = runWithConversions({
+ referrer: 'https://gemini.google.com/',
+ stored: earlier(3),
+ consent: 'always',
+ });
+ expect(again.stored.f.s).toBe('chatgpt.com');
+ // This landing is a page of the journey too.
+ expect(again.beacons.map((b) => b.k ?? 'visit')).toEqual(['visit', 'pv']);
+
+ const later = runWithConversions({
+ referrer: 'https://gemini.google.com/',
+ stored: earlier(31),
+ consent: 'always',
+ });
+ expect(later.stored.f.s).toBe('gemini.google.com');
+ expect(later.stored.id).not.toBe('Vq3xT0mZ8kLp2RwYbN5sQa');
+ // Not from an AI assistant, and the journey is over: nothing.
+ expect(runWithConversions({ stored: earlier(31), consent: 'always' }).beacons).toEqual([]);
+ });
+
+ it('counts a form with an email field as a signup, unless it says otherwise or opts out', () => {
+ const page = runWithConversions({ stored: earlier(1), consent: 'always' });
+ page.submit(form({ id: 'trial' }));
+ page.submit(form({ 'data-ansvisor-goal': 'demo', name: 'book-a-demo' }, ['email', 'text']));
+ page.submit(form({ 'data-ansvisor': 'off' }));
+ // A login, a search box: not conversions.
+ page.submit(form({}, ['email', 'password']));
+ page.submit(form({}, ['search']));
+ expect(page.beacons.filter((b) => b.k === 'cv')).toEqual([
+ expect.objectContaining({ g: 'signup', o: 'form', n: 'trial' }),
+ expect.objectContaining({ g: 'demo', o: 'form', n: 'book-a-demo' }),
+ ]);
+ });
+
+ it('runs the calls the site made before t.js loaded, and reads an order’s value and units', () => {
+ const queue = [
+ ['consent', 'granted'],
+ ['conversion', { type: 'order', value: 129.5, currency: 'EUR', units: 2, order: 1001 }],
+ ['conversion', { type: 'trial_to_paid' }],
+ ];
+ const page = runWithConversions({ referrer: 'https://chatgpt.com/', queue });
+ expect(page.beacons.filter((b) => b.k === 'cv')).toEqual([
+ expect.objectContaining({ g: 'order', val: 129.5, cur: 'EUR', q: 2, ref: '1001' }),
+ // A type of the site's own: a custom goal named after it.
+ expect.objectContaining({ g: 'custom', n: 'trial_to_paid' }),
+ ]);
+ });
+
+ it('sends events the server stores as they are (traffic-events.js)', () => {
+ const page = runWithConversions({ stored: earlier(1), consent: 'always' });
+ page.window.ansvisor('conversion', { type: 'demo', label: 'pricing-demo' });
+ const [pageview, conversion] = page.beacons.map((beacon) => eventRow('b1', beacon));
+ expect(pageview).toMatchObject({ kind: 'page', url: 'https://acme.example/pricing' });
+ expect(conversion).toMatchObject({
+ kind: 'conversion',
+ goal: 'demo',
+ label: 'pricing-demo',
+ origin: 'call',
+ first_source: 'chatgpt.com',
+ });
+ });
+
+ it('waits for the visitor’s own choice when Consent Mode’s default names a region', () => {
+ // Google's own example: denied in the EU, granted elsewhere — this visitor may be in the EU.
+ const dataLayer = [
+ ['consent', 'default', { analytics_storage: 'denied', region: ['DE', 'FR'] }],
+ ['consent', 'default', { analytics_storage: 'granted' }],
+ ];
+ const page = runWithConversions({ referrer: 'https://chatgpt.com/', dataLayer });
+ page.window.ansvisor('conversion', { type: 'signup' });
+ expect(page.stored).toBeNull();
+ expect(page.beacons).toHaveLength(1);
+ // The visitor says yes: the id is kept and what waited goes.
+ dataLayer.push(['consent', 'update', { analytics_storage: 'granted' }]);
+ expect(page.stored).not.toBeNull();
+ expect(page.beacons.map((b) => b.k ?? 'visit')).toEqual(['visit', 'cv']);
+ });
+
+ it('never takes a default pushed after t.js as consent: only the visitor’s update grants', () => {
+ // A CMP or GTM's Consent Initialization tag that runs after t.js, with Google's regional example.
+ const page = runWithConversions({ referrer: 'https://chatgpt.com/' });
+ page.window.dataLayer.push([
+ 'consent',
+ 'default',
+ { analytics_storage: 'denied', region: ['DE'] },
+ ]);
+ page.window.dataLayer.push(['consent', 'default', { analytics_storage: 'granted' }]);
+ page.window.ansvisor('conversion', { type: 'signup' });
+ expect(page.stored).toBeNull();
+ expect(page.beacons).toHaveLength(1);
+ });
+
+ it('pauses a returning visitor whose page denies by default, regional defaults or not', () => {
+ const dataLayer = [
+ ['consent', 'default', { analytics_storage: 'granted', region: ['US'] }],
+ ['consent', 'default', { analytics_storage: 'denied' }],
+ ];
+ const page = runWithConversions({ stored: earlier(1), dataLayer });
+ expect(page.beacons).toEqual([]);
+ dataLayer.push(['consent', 'update', { analytics_storage: 'granted' }]);
+ expect(page.beacons.map((b) => b.k)).toEqual(['pv']);
+ });
+
+ it('takes a "denied" the site queued before t.js before keeping or sending anything', () => {
+ const page = runWithConversions({
+ stored: earlier(1),
+ consent: 'always',
+ queue: [['consent', 'denied']],
+ });
+ expect(page.beacons).toEqual([]);
+ expect(page.stored).toBeNull();
+ });
+
+ it('keeps the AI landing through a "denied" the visitor takes back: the grant keeps it and sends what waited', () => {
+ const dataLayer = [];
+ const page = runWithConversions({ referrer: 'https://chatgpt.com/', dataLayer });
+ // A banner pushing the visitor's state before they choose.
+ dataLayer.push(['consent', 'update', { analytics_storage: 'denied' }]);
+ expect(page.stored).toBeNull();
+ page.window.ansvisor('conversion', { type: 'demo' });
+ dataLayer.push(['consent', 'update', { analytics_storage: 'granted' }]);
+ expect(page.stored.f.s).toBe('chatgpt.com');
+ expect(page.beacons.filter((b) => b.k === 'cv')).toMatchObject([
+ { g: 'demo', f: { s: 'chatgpt.com' } },
+ ]);
+ // The site's call says no again: the stored id goes, what waited too.
+ page.window.ansvisor('consent', 'denied');
+ expect(page.stored).toBeNull();
+ });
+
+ it('runs the queued consent calls first: a "denied" queued after a conversion still comes first', () => {
+ const page = runWithConversions({
+ stored: earlier(1),
+ queue: [
+ ['conversion', { type: 'demo' }],
+ ['consent', 'denied'],
+ ],
+ });
+ expect(page.beacons).toEqual([]);
+ expect(page.stored).toBeNull();
+ });
+
+ it('adds no hooks for a visitor it doesn’t follow: no dataLayer, push, route or form hook', () => {
+ const page = runWithConversions({ referrer: '', consent: 'always' });
+ const pushState = page.history.pushState;
+ expect(page.window.dataLayer).toBeUndefined();
+ expect(page.window.history.pushState).toBe(pushState);
+ expect(page.listeners['document:submit']).toBeUndefined();
+ expect(page.listeners['window:popstate']).toBeUndefined();
+ // The site's calls still find ansvisor() and do nothing.
+ page.window.ansvisor('conversion', { type: 'signup' });
+ page.window.ansvisor('consent', 'granted');
+ expect(page.beacons).toEqual([]);
+ expect(page.stored).toBeNull();
+ });
+
+ it('never stops the site’s own push or route change when its own part fails', () => {
+ const page = runWithConversions({ stored: earlier(1) });
+ page.failSends();
+ expect(() => page.window.history.pushState({}, '', '/checkout')).not.toThrow();
+ expect(page.location.pathname).toBe('/checkout');
+ expect(() => page.popstate()).not.toThrow();
+ // A grant sending what waited, with the beacon failing: the push still goes in.
+ const dataLayer = [];
+ const landing = runWithConversions({ referrer: 'https://chatgpt.com/', dataLayer });
+ landing.window.ansvisor('conversion', { type: 'demo' });
+ landing.failSends();
+ expect(() =>
+ dataLayer.push(['consent', 'update', { analytics_storage: 'granted' }]),
+ ).not.toThrow();
+ expect(dataLayer).toHaveLength(1);
+ });
+
+ it('takes an id kept earlier as the visitor’s consent then, on the pages after', () => {
+ const page = runWithConversions({ stored: earlier(1) });
+ page.window.ansvisor('conversion', { type: 'demo' });
+ expect(page.beacons.map((b) => b.k)).toEqual(['pv', 'cv']);
+ });
+
+ it('pauses an "always" site whose Consent Mode default denies it, until it’s granted', () => {
+ const dataLayer = [['consent', 'default', { analytics_storage: 'denied' }]];
+ const page = runWithConversions({
+ referrer: 'https://chatgpt.com/',
+ consent: 'always',
+ dataLayer,
+ });
+ expect(page.stored).toBeNull();
+ page.window.ansvisor('conversion', { type: 'order', value: 10, currency: 'USD' });
+ expect(page.beacons).toHaveLength(1);
+ dataLayer.push(['consent', 'update', { analytics_storage: 'granted' }]);
+ expect(page.beacons[1]).toMatchObject({ k: 'cv', g: 'order', val: 10 });
+ });
+
+ it('listens to Consent Mode on a page whose dataLayer isn’t there yet', () => {
+ const page = runWithConversions({ referrer: 'https://chatgpt.com/' });
+ page.window.dataLayer.push(['consent', 'update', { analytics_storage: 'granted' }]);
+ expect(page.stored).not.toBeNull();
+ });
+
+ it('sends a value, units and an order only as the server takes them', () => {
+ const page = runWithConversions({ stored: earlier(1), consent: 'always' });
+ page.window.ansvisor('conversion', {
+ type: 'order',
+ value: Number.NaN,
+ units: 1.5,
+ currency: 'EUR',
+ });
+ page.window.ansvisor('conversion', {
+ type: 'order',
+ value: '49.90',
+ units: 2,
+ order: 'x'.repeat(300),
+ });
+ page.window.ansvisor('conversion', 'demo');
+ const [nan, text, short] = page.beacons.filter((b) => b.k === 'cv');
+ expect(nan).not.toHaveProperty('val');
+ expect(nan).not.toHaveProperty('q');
+ expect(text).toMatchObject({ val: 49.9, q: 2 });
+ expect(text.ref).toHaveLength(200);
+ expect(short).toMatchObject({ g: 'demo' });
+ // Each makes a row (or, past the server's own limits, still none that fails).
+ expect(eventRow('b1', nan)).not.toBeNull();
+ expect(eventRow('b1', short)).not.toBeNull();
+ });
+
+ it('counts a form once a page, a signup with a new password, and an email field by its name', () => {
+ const page = runWithConversions({ stored: earlier(1), consent: 'always' });
+ const trial = form({ id: 'trial' });
+ page.submit(trial);
+ page.submit(trial);
+ page.submit(form({ name: 'join' }, ['email', 'password', 'new-password']));
+ page.submit(form({ name: 'subscribe' }, ['email-field']));
+ expect(page.beacons.filter((b) => b.k === 'cv').map((b) => b.n)).toEqual([
+ 'trial',
+ 'join',
+ 'subscribe',
+ ]);
+ });
+
+ it('makes the id from crypto where there is one, and deletes one past its 30 days', () => {
+ const crypto = { getRandomValues: (bytes) => bytes.fill(1) };
+ const page = runWithConversions({
+ referrer: 'https://chatgpt.com/',
+ consent: 'always',
+ crypto,
+ });
+ expect(page.stored.id).toBe('B'.repeat(22));
+ const expired = runWithConversions({ stored: earlier(31) });
+ expect(expired.storage.has('ansvisor_v')).toBe(false);
+ });
+
+ it('still sends the visit, and breaks nothing, where storage throws', () => {
+ const page = runWithConversions({
+ referrer: 'https://chatgpt.com/',
+ consent: 'always',
+ storageThrows: true,
+ });
+ page.window.ansvisor('conversion', { type: 'signup' });
+ expect(page.beacons.map((b) => b.k ?? 'visit')).toEqual(['visit', 'cv']);
+ });
+
+ it('sends nothing for a visitor who never came from an AI assistant', () => {
+ const page = runWithConversions({ consent: 'always' });
+ page.window.ansvisor('conversion', { type: 'signup' });
+ page.submit(form({ id: 'trial' }));
+ expect(page.beacons).toEqual([]);
+ expect(page.stored).toBeNull();
+ });
+});