@trycurious/js 0.1.0 → 0.2.0
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/README.md +41 -4
- package/dist/curious.iife.js +1 -1
- package/dist/curious.iife.js.map +1 -1
- package/dist/index.d.ts +14 -8
- package/dist/index.js +141 -21
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -31,7 +31,7 @@ The attribute value is the element name, declared beforehand with a secret key (
|
|
|
31
31
|
The SDK replaces one run of plain text and nothing else: attributes, handlers and comments are untouched. Put the tag on the innermost element that holds only text. Two shapes are left exactly as they are, are never decided, and are reported once through `onFallback` as `content_shape_mismatch`:
|
|
32
32
|
|
|
33
33
|
```html
|
|
34
|
-
<!-- child elements:
|
|
34
|
+
<!-- child elements: see "Content with markup inside it" below -->
|
|
35
35
|
<h1 data-curious="hero">Study <span class="accent">what matters</span> for the SAT</h1>
|
|
36
36
|
|
|
37
37
|
<!-- text a template builds from several pieces, such as React's `Plan {name}` -->
|
|
@@ -40,6 +40,42 @@ The SDK replaces one run of plain text and nothing else: attributes, handlers an
|
|
|
40
40
|
|
|
41
41
|
An element that cannot hold text at all, such as `<input>` or `<img>`, is refused the same way.
|
|
42
42
|
|
|
43
|
+
## Content with markup inside it
|
|
44
|
+
|
|
45
|
+
A headline with a styled phrase, such as `Study <span>what matters</span> for the SAT`, is not something a tag can replace. Ask for the content yourself with `decide()` and render it in your own markup. Declare the element (with a secret key, as for any element) with one text field per piece, for example the format `{ "lead": { "type": "text" }, "emphasis": { "type": "text" }, "tail": { "type": "text" } }`, and pass the same fields as the fallback:
|
|
46
|
+
|
|
47
|
+
```tsx
|
|
48
|
+
const CONTROL = { lead: "Study", emphasis: "what matters", tail: "for the SAT" };
|
|
49
|
+
|
|
50
|
+
function Hero() {
|
|
51
|
+
const [parts, setParts] = useState(CONTROL);
|
|
52
|
+
useEffect(() => {
|
|
53
|
+
let mounted = true;
|
|
54
|
+
curious.start(); // a child's effect runs before the root's; calling it again is harmless
|
|
55
|
+
curious.decide({ element: "home_hero", fallback: CONTROL }).then((result) => {
|
|
56
|
+
if (mounted) setParts(result.content);
|
|
57
|
+
});
|
|
58
|
+
return () => {
|
|
59
|
+
mounted = false;
|
|
60
|
+
};
|
|
61
|
+
}, []);
|
|
62
|
+
return (
|
|
63
|
+
<h1>
|
|
64
|
+
{parts.lead} <span className="accent">{parts.emphasis}</span> {parts.tail}
|
|
65
|
+
</h1>
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
- **The fallback is your control and states the shape you render.** You get it back, with `served: "fallback"`, on a timeout, on any failure, and when the served content lacks one of the fallback's fields or has one of another kind (`content_shape_mismatch`). In a list, the fallback's first item states the shape of every item.
|
|
71
|
+
- **A remount does not decide again.** Within the cache's 60 seconds the same visitor gets the same answer with `served: "cache"` and no request, and a second call made while the first is still out shares its request (React runs an effect twice on a development mount). A call that carries `identifiers`, `attributes` or its own `context` is always sent, alone, and an answer decided for a `context` you passed is not kept for later calls.
|
|
72
|
+
- **`decide()` asks when you call it,** not when the element nears the viewport. Call it for content the visitor is about to see.
|
|
73
|
+
- **If you wait for consent, use `consent: "required"`,** not a delayed `start()`: the component's own `start()` would open that gate. Until `grantConsent()` the call returns the fallback (`capability_unavailable`); call `decide()` again once consent is given.
|
|
74
|
+
- **A `stop()` does not cancel a call that is out.** Ignore the result yourself when the component has unmounted, as the example does.
|
|
75
|
+
- **Do not also tag that element.** A tag on it would be refused for its child elements. Clicks on a tagged button elsewhere are still captured, and `track()` records anything else.
|
|
76
|
+
|
|
77
|
+
Tested in Chrome on a server-rendered React 19 page against a stand-in for the API.
|
|
78
|
+
|
|
43
79
|
## What happens
|
|
44
80
|
|
|
45
81
|
- Tags are decided when they approach the viewport (one `IntersectionObserver`, 200% root margin), batched into one publishable-key request per frame; nothing below the fold is decided until it matters.
|
|
@@ -48,7 +84,8 @@ An element that cannot hold text at all, such as `<input>` or `<img>`, is refuse
|
|
|
48
84
|
- Visitors get an `anon_<uuid>` id in a first-party, host-only cookie (`curious_anon`, `SameSite=Lax`, `Secure` on https, one year), mirrored to `localStorage`, memory when storage is blocked. Nothing is inferred from the device.
|
|
49
85
|
- Events queue in `sessionStorage` with ids that survive retries, and flush on an interval, on count, when the tab is hidden and on `pagehide`, with `keepalive` under the browser's budget.
|
|
50
86
|
- If your page later rewrites text the SDK applied, your text is what shows; the SDK reports `mutation_drift` once through `onFallback` and does not apply its text again.
|
|
51
|
-
- Autocapture is on by default and narrow: `$pageview` with the page's path (no query string or hash) on start and
|
|
87
|
+
- Autocapture is on by default and narrow: `$pageview` with the page's path (no query string or hash) on start and whenever client-side navigation changes the path, and `$click` and `$form_submit` on tagged nodes with the element name. Nothing else is captured: no text, values, URLs or referrers. `autocapture: false` (or `data-curious-autocapture="off"` on the script tag) turns it off; an object turns individual events off. The API accepts these names only from this SDK under a publishable key.
|
|
88
|
+
- Client-side navigation is detected by wrapping `history.pushState` and `history.replaceState` and listening for `popstate` (back and forward). A page view is recorded only when the path changes, so a router that touches the History API for a query string, a hash or a scroll position adds nothing. `autocapture: { pageviews: { historyChanges: false } }` turns detection off and leaves navigation to your own `page()` calls; use that for a hash router, whose path never changes.
|
|
52
89
|
|
|
53
90
|
## API
|
|
54
91
|
|
|
@@ -57,7 +94,7 @@ curious.start(); curious.stop(); curious.scan(root?);
|
|
|
57
94
|
await curious.decide({ element: "promo", fallback: "Save 20%" });
|
|
58
95
|
curious.track({ name: "signed_up", properties: { plan: "pro" } });
|
|
59
96
|
await curious.flush();
|
|
60
|
-
curious.page(); //
|
|
97
|
+
curious.page(); // only with detection off: a page view for the current path (see What happens)
|
|
61
98
|
curious.anonymousId; // the visitor's anon_… id; send it to your backend at login
|
|
62
99
|
await curious.identify("user_123"); // after YOUR backend linked the anonymous id with a secret key
|
|
63
100
|
await curious.reset(); // on logout
|
|
@@ -83,7 +120,7 @@ On a server-rendered page, the SDK must not write before your framework has hydr
|
|
|
83
120
|
```
|
|
84
121
|
|
|
85
122
|
- **Tag elements that hold one piece of text.** `<p data-curious="plan">Plan {name}</p>` renders as several text nodes and is left alone (see Tag content); `<p data-curious="plan">{label}</p>` is one and is replaced.
|
|
86
|
-
- **
|
|
123
|
+
- **Route changes need nothing from you.** The SDK records a page view on start and each time your router changes the path. If your code also calls `curious.page()` for the same navigation, it is counted once.
|
|
87
124
|
- **Your state wins.** If a component later renders different text into a tagged element, that text shows and the SDK reports `mutation_drift`.
|
|
88
125
|
|
|
89
126
|
Tagged elements that mount later (a route change, a lazy section) are found by a `MutationObserver`; a decision already made for the visitor is reused from the cache.
|
package/dist/curious.iife.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var Curious=(()=>{var K=Object.defineProperty;var ue=Object.getOwnPropertyDescriptor;var le=Object.getOwnPropertyNames;var de=Object.prototype.hasOwnProperty;var ce=(r,e)=>{for(var t in e)K(r,t,{get:e[t],enumerable:!0})},me=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of le(e))!de.call(r,s)&&s!==t&&K(r,s,{get:()=>e[s],enumerable:!(n=ue(e,s))||n.enumerable});return r};var fe=r=>me(K({},"__esModule",{value:!0}),r);var De={};ce(De,{default:()=>Me});var g=class extends Error{constructor(e){super(e.message),this.name="CuriousError",this.summary=e}get code(){return this.summary.code}},X=300;function a(r,e,t={}){let n=t.retryable??(r==="timeout"||r==="network_error"||r==="rate_limited"||r==="server_error"),s={code:r,retryable:n,message:e.length>X?`${e.slice(0,X)}\u2026`:e};return t.status!==void 0&&(s.status=t.status),t.requestId!==void 0&&(s.requestId=t.requestId),t.serverCode!==void 0&&(s.serverCode=t.serverCode),s}function pe(r){return typeof r=="object"&&r!==null&&typeof r.error=="string"&&typeof r.message=="string"?r:null}function k(r,e,t){let n=pe(e),s=n?.message??`HTTP ${r}`,i={status:r};return t!==null&&(i.requestId=t),n!==null&&(i.serverCode=n.error),r===401?a("authentication_error",s,i):r===403?a(/origin/i.test(s)?"origin_not_allowed":"authentication_error",s,i):r===408?a("timeout",s,i):r===429?a("rate_limited",s,i):r===409?n?.error==="idempotency_error"?a("mutation_drift",s,i):n?.error==="lock_timeout"?a("lock_timeout",s,{...i,retryable:!0}):/no live experiment/i.test(s)?a("undeclared_element",s,i):a("invalid_input",s,{...i,retryable:/retry/i.test(s)}):r>=500?a("server_error",s,i):r===400||r===413||r===422?a("invalid_input",s,i):a("protocol_error",s,{...i,retryable:!1})}var G="curious_anon",H="curious:anon",O="curious:user",he=365*24*60*60,N=class{constructor(e={}){this.anonymous=null;this.known=null;this.enabled=!1;this.maxAge=e.cookieMaxAgeSeconds??he,this.doc=e.document??(typeof document>"u"?null:document),this.local=e.storage===void 0?T("localStorage"):e.storage,this.session=T("sessionStorage")}enable(){this.enabled=!0,this.known=this.session===null?null:C(this.session,O),this.anonymous=this.readCookie()??(this.local===null?null:C(this.local,H)),this.anonymous===null&&(this.anonymous=V()),this.persistAnonymous()}get activeUserId(){if(!this.enabled)throw new g(a("capability_unavailable","Identity is unavailable before consent",{retryable:!1}));return this.known??this.anonymous}get anonymousId(){return this.anonymous}get knownUserId(){return this.known}setKnown(e){this.known=e,this.session!==null&&A(this.session,O,e)}reset(){this.known=null,this.session!==null&&q(this.session,O),this.anonymous=V(),this.persistAnonymous()}clear(){this.enabled=!1,this.known=null,this.anonymous=null,this.session!==null&&q(this.session,O),this.local!==null&&q(this.local,H),this.writeCookie("",0)}persistAnonymous(){this.anonymous!==null&&(this.writeCookie(this.anonymous,this.maxAge),this.local!==null&&A(this.local,H,this.anonymous))}readCookie(){if(this.doc===null)return null;let e=this.doc.cookie.split("; ").find(n=>n.startsWith(`${G}=`));if(e===void 0)return null;let t=decodeURIComponent(e.slice(G.length+1));return/^anon_[0-9a-f-]{36}$/.test(t)?t:null}writeCookie(e,t){if(this.doc===null)return;let n=this.doc.location?.protocol==="https:"?"; Secure":"";try{this.doc.cookie=`${G}=${encodeURIComponent(e)}; Max-Age=${t}; Path=/; SameSite=Lax${n}`}catch{}}};function V(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return`anon_${crypto.randomUUID()}`;let r=new Uint8Array(16);crypto.getRandomValues(r),r[6]=r[6]&15|64,r[8]=r[8]&63|128;let e=Array.from(r,t=>t.toString(16).padStart(2,"0")).join("");return`anon_${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function T(r){try{let e=globalThis[r],t="__curious_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}function C(r,e){try{return r.getItem(e)}catch{return null}}function A(r,e,t){try{r.setItem(e,t)}catch{}}function q(r,e){try{r.removeItem(e)}catch{}}var Y=1,ge=6e4,Z="curious:assign:",L=class{constructor(e){this.memory=new Map;this.store=e.storage===void 0?T("sessionStorage"):e.storage,this.ttlMs=e.ttlMs??ge,this.fingerprint=e.publishableKey.slice(-8)}key(e,t){let n=typeof location>"u"?"":location.origin;return`${Z}${this.fingerprint}:${n}:${e}:${t}`}get(e,t,n=Date.now()){let s=this.key(e,t),i=this.store===null?this.memory.get(s)??null:C(this.store,s);if(i===null)return null;try{let d=JSON.parse(i);return d.schema!==Y||d.expiresAt<=n?(this.remove(e,t),null):d}catch{return this.remove(e,t),null}}set(e,t,n,s=Date.now()){let i={...n,storedAt:s,expiresAt:s+this.ttlMs,schema:Y},d=this.key(e,t),u=JSON.stringify(i);this.store===null?this.memory.set(d,u):A(this.store,d,u)}remove(e,t){let n=this.key(e,t);this.memory.delete(n),this.store!==null&&q(this.store,n)}clear(){if(this.memory.clear(),this.store!==null)try{let e=[];for(let t=0;t<this.store.length;t+=1){let n=this.store.key(t);n!==null&&n.startsWith(Z)&&e.push(n)}for(let t of e)this.store.removeItem(t)}catch{}}};var S={flushIntervalMs:5e3,flushCount:20,queueLimit:100,keepaliveBodyBytes:48*1024,requestTimeoutMs:1e4,maxAttempts:5,itemCap:200},ee="curious:events",ye="$",$=class{constructor(e){this.sequence=0;this.entries=[];this.timer=null;this.inFlight=null;this.o={transport:e.transport,userId:e.userId,flushIntervalMs:e.flushIntervalMs??S.flushIntervalMs,flushCount:e.flushCount??S.flushCount,queueLimit:e.queueLimit??S.queueLimit,keepaliveBodyBytes:e.keepaliveBodyBytes??S.keepaliveBodyBytes,requestTimeoutMs:e.requestTimeoutMs??S.requestTimeoutMs,maxAttempts:e.maxAttempts??S.maxAttempts,onEventDrop:e.onEventDrop},this.store=e.storage===void 0?T("sessionStorage"):e.storage,this.now=e.now??Date.now,this.sessionId=Math.random().toString(36).slice(2,10)+this.now().toString(36),this.restore()}get size(){return this.entries.length}track(e){if(typeof e.name=="string"&&e.name.startsWith(ye))throw new g(a("invalid_input","Event names starting with $ are reserved",{retryable:!1}));return this.enqueue(e)}system(e){return this.enqueue(e)}enqueue(e){if(typeof e.name!="string"||e.name.trim().length===0)throw new g(a("invalid_input","track: name is required",{retryable:!1}));let t={id:e.id??`browser:${this.sessionId}:${++this.sequence}:${Math.random().toString(36).slice(2,8)}`,user_id:this.o.userId(),name:e.name};return e.value!==void 0&&(t.value=e.value),e.properties!==void 0&&(t.properties=e.properties),e.context!==void 0&&(t.context=e.context),e.timestamp!==void 0&&(t.timestamp=e.timestamp instanceof Date?e.timestamp.toISOString():e.timestamp),this.entries.length>=this.o.queueLimit?(this.o.onEventDrop(a("queue_full",`Event queue is full (${this.o.queueLimit}); event not queued`,{retryable:!0})),{id:t.id,queued:!1}):(this.entries.push({event:t,attempts:0}),this.persist(),this.entries.length>=this.o.flushCount?this.flush():this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.o.flushIntervalMs)),{id:t.id,queued:!0})}flush(e={}){return this.inFlight===null&&(this.inFlight=this.run(e.keepalive===!0).finally(()=>{this.inFlight=null})),this.inFlight}clear(){this.entries=[],this.persist()}async run(e){this.timer!==null&&(clearTimeout(this.timer),this.timer=null);let t={sent:0,duplicates:0,failed:0,pending:0};for(;this.entries.length>0;){let n=this.takeBatch(e);if(n.length===0)break;let s=await this.deliver(n,e,t);if(s.length>0){this.entries.unshift(...s),this.persist();break}}return t.pending=this.entries.length,this.persist(),t}takeBatch(e){let t=[],n=2;for(;this.entries.length>0&&t.length<S.itemCap;){let s=this.entries[0],i=JSON.stringify(s.event).length+1;if(e&&t.length>0&&n+i>this.o.keepaliveBodyBytes)break;t.push(this.entries.shift()),n+=i}return t}async deliver(e,t,n){for(let u of e)u.attempts+=1;let s;try{s=await this.o.transport.post("/events",{events:e.map(u=>u.event)},{timeoutMs:this.o.requestTimeoutMs,keepalive:t})}catch(u){return this.retryOrDrop(e,u.summary,n)}if(s.status!==200){let u=k(s.status,s.body,s.requestId);if(!u.retryable){for(let _ of e)n.failed+=1,this.o.onEventDrop(a("event_rejected",u.message,{...u,retryable:!1}));return[]}return this.retryOrDrop(e,u,n)}let i=s.body?.results;if(!Array.isArray(i))return this.retryOrDrop(e,a("protocol_error","Batch response carried no results",{retryable:!0}),n);let d=[];return e.forEach((u,_)=>{let y=i[_];if(y==null||typeof y!="object"||y.index!==_){d.push(...this.retryOrDrop([u],a("protocol_error","Batch response had no result for this event",{retryable:!0}),n));return}if(y.status==="ok"){n.sent+=1,y.duplicate===!0&&(n.duplicates+=1);return}let w=k(y.error==="internal_error"?500:400,y,s.requestId);if(w.retryable&&u.attempts<this.o.maxAttempts){d.push(u);return}n.failed+=1,this.o.onEventDrop(a("event_rejected",w.message,{...w,retryable:!1}))}),d}retryOrDrop(e,t,n){let s=[];for(let i of e)i.attempts<this.o.maxAttempts?s.push(i):(n.failed+=1,this.o.onEventDrop(a("event_rejected",`Gave up after ${i.attempts} attempts: ${t.message}`,{...t,retryable:!1})));return s}persist(){this.store!==null&&A(this.store,ee,JSON.stringify(this.entries))}restore(){if(this.store===null)return;let e=C(this.store,ee);if(e!==null)try{let t=JSON.parse(e);Array.isArray(t)&&(this.entries=t.filter(n=>n&&typeof n.event?.id=="string").slice(0,this.o.queueLimit))}catch{this.entries=[]}}};var R="data-curious",ve="data-curious-ignore",be="data-curious-critical",Ee="curious-loading",_e="200% 0px";var we=new Set(["AREA","BASE","BR","COL","EMBED","HR","IMG","INPUT","LINK","META","SOURCE","TRACK","WBR"]);function j(r){if(we.has(r.tagName.toUpperCase()))return{unsupported:"void_element"};let e=null;for(let t of Array.from(r.childNodes)){if(t.nodeType===1)return{unsupported:"child_elements"};if(t.nodeType===3){if(e!==null)return{unsupported:"several_text_nodes"};e=t}}return{text:e}}var U=class{constructor(e){this.nodes=new Map;this.byElement=new Map;this.pending=new Set;this.released=new WeakSet;this.intersection=null;this.mutation=null;this.frame=null;this.o=e}start(){if(typeof IntersectionObserver=="function"&&(this.intersection=new IntersectionObserver(e=>{for(let t of e){if(!t.isIntersecting)continue;let n=this.nodes.get(t.target);n===void 0||n.state!=="idle"||(n.state="pending",this.pending.add(n.element),this.intersection?.unobserve(t.target))}this.schedule()},{rootMargin:this.o.rootMargin??_e,threshold:0})),typeof MutationObserver=="function"){this.mutation=new MutationObserver(t=>{for(let n of t){if(n.type==="childList"){for(let i of n.removedNodes)i instanceof Element&&this.forgetRemoved(i);for(let i of n.addedNodes)i instanceof Element&&this.scan(i)}let s=n.target instanceof Element?n.target:n.target.parentElement;s!==null&&this.detectDrift(s)}});let e=this.o.root??document;this.mutation.observe(e instanceof Document?e.documentElement:e,{childList:!0,subtree:!0,characterData:!0})}this.scan(this.o.root??document)}stop(){this.intersection?.disconnect(),this.mutation?.disconnect(),this.intersection=null,this.mutation=null,this.frame!==null&&clearTimeout(this.frame),this.frame=null,this.nodes.clear(),this.byElement.clear(),this.pending.clear(),this.released=new WeakSet}scan(e=this.o.root??document){let t=[];e instanceof Element&&e.hasAttribute(R)&&t.push(e),t.push(...Array.from(e.querySelectorAll(`[${R}]`)));for(let n of t){if(this.nodes.has(n)||this.released.has(n)||n.closest(`[${ve}]`)!==null)continue;let s=(n.getAttribute(R)??"").trim();if(s.length===0)continue;let i={element:s,node:n,control:n.textContent??"",applied:null,state:"idle",drifted:!1};this.nodes.set(n,i);let d=j(n);if("unsupported"in d){this.refuse(i,d.unsupported);continue}let u=this.byElement.get(s);u===void 0&&(u=new Set,this.byElement.set(s,u)),u.add(i),this.intersection!==null?this.intersection.observe(n):(i.state="pending",this.pending.add(s))}this.pending.size>0&&this.schedule()}apply(e,t){let n=this.byElement.get(e);if(n===void 0)return"no_node";if(typeof t!="string"){for(let i of n)i.drifted||(i.state="fallback");return"not_text"}let s=!1;for(let i of Array.from(n)){if(!i.node.isConnected){this.forget(i);continue}if(i.drifted)continue;let d=j(i.node);if("unsupported"in d){this.refuse(i,d.unsupported);continue}d.text===null?i.node.appendChild(i.node.ownerDocument.createTextNode(t)):d.text.data!==t&&(d.text.data=t),i.applied=t,i.state="decided",this.revealCritical(i.node),s=!0}return s?"applied":"no_node"}fallback(e){let t=this.byElement.get(e);if(t!==void 0)for(let n of t)n.state="fallback",this.revealCritical(n.node)}resetDecisions(){for(let e of Array.from(this.nodes.values())){if(!e.node.isConnected){this.forget(e);continue}(e.state==="decided"||e.state==="fallback"||e.state==="pending")&&!e.drifted&&(e.state="idle",e.applied=null,this.intersection?.observe(e.node),this.intersection===null&&(e.state="pending",this.pending.add(e.element)))}this.pending.size>0&&this.schedule()}elements(){return Array.from(this.byElement.keys())}schedule(){this.frame!==null||this.pending.size===0||(this.frame=setTimeout(()=>{this.frame=null;let e=Array.from(this.pending).filter(t=>this.hasWritablePendingNode(t));this.pending.clear(),e.length>0&&this.o.onPending(e)},0))}hasWritablePendingNode(e){let t=this.byElement.get(e);if(t===void 0)return!1;let n=!1;for(let s of Array.from(t)){if(s.state!=="pending")continue;if(!s.node.isConnected){this.forget(s);continue}let i=j(s.node);"unsupported"in i?this.refuse(s,i.unsupported):n=!0}return n}forgetRemoved(e){let t=[e,...Array.from(e.querySelectorAll(`[${R}]`))];for(let n of t){let s=this.nodes.get(n);s!==void 0&&!n.isConnected&&this.forget(s)}}forget(e){this.nodes.delete(e.node),this.byElement.get(e.element)?.delete(e),this.intersection?.unobserve(e.node)}refuse(e,t){e.state="unsupported",this.byElement.get(e.element)?.delete(e),this.intersection?.unobserve(e.node),this.revealCritical(e.node),this.o.onUnsupported(e.element,t)}detectDrift(e){let t=e.closest(`[${R}]`);if(t===null)return;let n=this.nodes.get(t);n===void 0||n.state!=="decided"||n.drifted||(t.textContent??"")!==n.applied&&(n.drifted=!0,this.released.add(t),this.o.onDrift(n.element))}revealCritical(e){e.hasAttribute(be)&&document.documentElement.classList.remove(Ee)}};var te="0.1.0";var xe=1048576,B=class{constructor(e){let t=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(t===void 0)throw new g(a("capability_unavailable","fetch is not available",{retryable:!1}));this.fetchImpl=t,this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.headers={authorization:`Bearer ${e.publishableKey}`,"content-type":"application/json","x-curious-client":`browser-js/${te}`}}async post(e,t,n){let s=new AbortController,i=setTimeout(()=>s.abort(),n.timeoutMs),d;try{d=await this.fetchImpl(`${this.baseUrl}${e}`,{method:"POST",headers:this.headers,body:JSON.stringify(t),signal:s.signal,keepalive:n.keepalive===!0,credentials:"omit",mode:"cors"})}catch(b){throw s.signal.aborted?new g(a("timeout",`No response within ${n.timeoutMs}ms`)):new g(a("network_error",re(b)))}finally{clearTimeout(i)}let u=d.headers.get("x-request-id"),_=ke(d.headers.get("retry-after")),y;try{y=await d.text()}catch(b){throw new g(a("network_error",re(b),{status:d.status}))}if(y.length>xe)throw new g(a("protocol_error","Response exceeds the size bound",{status:d.status,retryable:!1}));let w=null;if(y.length>0)try{w=JSON.parse(y)}catch{throw new g(a("protocol_error",`Response ${d.status} was not JSON`,{status:d.status,retryable:!1}))}return{status:d.status,requestId:u,retryAfterMs:_,body:w}}};function re(r){return r instanceof Error&&r.message?`Request failed: ${r.message}`:"Request failed"}function ke(r){if(r===null)return null;let e=Number(r);if(Number.isFinite(e)&&e>=0)return Math.round(e*1e3);let t=Date.parse(r);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var z={baseUrl:"https://api.trycurious.ai/v1",decideTimeoutMs:1e3},Se="curious_pk_",ne=50,Ie=new Map([["internal_error",500],["decision_unavailable",503],["idempotency_error",409],["lock_timeout",409],["conflict",409]]),Te={child_elements:"The tagged element contains other elements; the SDK replaces plain text only. Tag the innermost element that holds only text",several_text_nodes:"The tagged element's text is made of several pieces (a template with expressions); the SDK replaces one run of plain text only",void_element:"The tagged element cannot hold text (an input, an image or another empty element); tag an element whose content is text"};function se(r){if(typeof r.publishableKey!="string"||r.publishableKey.length===0)throw new g(a("invalid_configuration","publishableKey is required",{retryable:!1}));if(!r.publishableKey.startsWith(Se))throw new g(a("invalid_key_type","The browser SDK takes a publishable key (curious_pk_...). Never ship a secret key to a browser",{retryable:!1}));let e=Math.min(r.decideTimeoutMs??z.decideTimeoutMs,z.decideTimeoutMs*10);if(!Number.isFinite(e)||e<=0)throw new g(a("invalid_configuration","decideTimeoutMs must be a positive number",{retryable:!1}));let t=P(r.onFallback),n=P(r.onDecision),s=P(r.onEventDrop),i=P(r.onIdentityChange),d=new B({publishableKey:r.publishableKey,baseUrl:r.baseUrl??z.baseUrl,fetch:r.fetch}),u=new N({...r.cookieMaxAgeSeconds===void 0?{}:{cookieMaxAgeSeconds:r.cookieMaxAgeSeconds},document:r.document,storage:r.storage}),_=new L({publishableKey:r.publishableKey,...r.cacheTtlMs===void 0?{}:{ttlMs:r.cacheTtlMs},...r.storage===void 0?{}:{storage:r.storage}}),y=r.consent??"implicit",w=!1,b=!1,F=new Map,E=null,I=[],x=new U({...r.rootMargin===void 0?{}:{rootMargin:r.rootMargin},onPending:o=>{ie(o)},onDrift:o=>t(o,a("mutation_drift","Applied content was rewritten by the page; the SDK will not reapply it",{retryable:!1})),onUnsupported:(o,f)=>t(o,a("content_shape_mismatch",Te[f],{retryable:!1}))});function W(){let o={};return typeof location<"u"&&(o.path=location.pathname),typeof navigator<"u"&&navigator.language&&(o.locale=navigator.language),{...o,...r.context??{}}}function M(){if(E===null){let o=r.events??{};E=new $({transport:d,userId:()=>u.activeUserId,onEventDrop:s,storage:r.storage,...o.flushIntervalMs===void 0?{}:{flushIntervalMs:o.flushIntervalMs},...o.flushCount===void 0?{}:{flushCount:o.flushCount},...o.queueLimit===void 0?{}:{queueLimit:o.queueLimit}})}return E}async function ie(o){if(!b)return;let f=u.activeUserId,p=[];for(let l of o){let c=_.get(f,l);if(c!==null){x.apply(l,c.content)==="applied"&&n(l,{content:c.content,served:"cache",armId:c.armId,armType:c.armType,experimentId:c.experimentId,experimentStatus:c.experimentStatus,requestId:null});continue}F.has(`${f}:${l}`)||p.push(l)}if(p.length===0)return;let m=(async()=>{for(let l=0;l<p.length;l+=ne){let c=p.slice(l,l+ne);await oe(f,c)}})();for(let l of p)F.set(`${f}:${l}`,m);try{await m}finally{for(let l of p)F.delete(`${f}:${l}`)}}async function oe(o,f){let p=()=>!b||u.activeUserId!==o;if(p())return;let m;try{m=await d.post("/decide",{user_id:o,context:W(),elements:f.map(c=>({element:c}))},{timeoutMs:e})}catch(c){if(p())return;for(let v of f)D(v,c.summary);return}if(p())return;if(m.status!==200){let c=k(m.status,m.body,m.requestId);for(let v of f)D(v,c);return}let l=m.body?.results;f.forEach((c,v)=>{if(p())return;let h=Array.isArray(l)?l[v]:void 0;if(h==null||typeof h!="object"||h.index!==v){D(c,a("protocol_error","Batch response had no result for this element",{retryable:!1,status:200}));return}if(h.status==="error"){D(c,k(Ie.get(h.error)??400,h,m.requestId));return}let J=x.apply(c,h.content);if(!p()){if(J==="not_text"){D(c,a("content_shape_mismatch","Served content is not text",{retryable:!1,status:200}));return}_.set(o,c,{content:h.content,armId:h.arm_id,armType:h.arm_type??null,experimentId:h.experiment_id,experimentStatus:h.experiment_status}),J==="applied"&&n(c,{content:h.content,served:"curious",armId:h.arm_id,armType:h.arm_type??null,experimentId:h.experiment_id,experimentStatus:h.experiment_status,requestId:m.requestId})}})}function D(o,f){x.fallback(o),t(o,f)}function ae(){if(typeof document>"u")return;let o=()=>{document.visibilityState==="hidden"&&E!==null&&E.flush({keepalive:!0})},f=()=>{E!==null&&E.flush({keepalive:!0})};if(document.addEventListener("visibilitychange",o),addEventListener("pagehide",f),I.push(()=>document.removeEventListener("visibilitychange",o)),I.push(()=>removeEventListener("pagehide",f)),r.autocapture===!1)return;let p={pageviews:!0,taggedClicks:!0,taggedFormSubmits:!0,...r.autocapture};if(p.pageviews&&M().system({name:"$pageview",properties:{path:location.pathname}}),p.taggedClicks){let m=l=>{let c=l.target instanceof Element?l.target.closest("[data-curious]"):null;if(c===null||c.closest("[data-curious-ignore]")!==null)return;let v=c.getAttribute("data-curious");v&&M().system({name:"$click",properties:{element_name:v}})};document.addEventListener("click",m,{capture:!0,passive:!0}),I.push(()=>document.removeEventListener("click",m,{capture:!0}))}if(p.taggedFormSubmits){let m=l=>{let c=l.target instanceof Element?l.target.closest("[data-curious]"):null;if(c===null||c.closest("[data-curious-ignore]")!==null)return;let v=c.getAttribute("data-curious");v&&M().system({name:"$form_submit",properties:{element_name:v}})};document.addEventListener("submit",m,{capture:!0,passive:!0}),I.push(()=>document.removeEventListener("submit",m,{capture:!0}))}}function Q(){b||(u.enable(),b=!0,ae(),x.start())}return{start(){w=!0,y==="implicit"?Q():y==="denied"&&typeof document<"u"&&document.documentElement.classList.remove("curious-loading")},stop(){w=!1,b=!1,x.stop();for(let o of I.splice(0))o()},scan(o){b&&x.scan(o)},async decide(o){let f=(v,h)=>(t(o.element,v),{content:o.fallback,served:"fallback",armId:null,armType:null,experimentId:null,experimentStatus:null,error:v,requestId:h});if(!b)return f(a("capability_unavailable","The SDK is not active (consent or start)",{retryable:!1}),null);let p={element:o.element,user_id:u.activeUserId,context:{...W(),...o.context??{}}};o.identifiers!==void 0&&(p.identifiers=o.identifiers),o.attributes!==void 0&&(p.attributes=o.attributes);let m;try{m=await d.post("/decide",p,{timeoutMs:e})}catch(v){return f(v.summary,null)}if(m.status!==200)return f(k(m.status,m.body,m.requestId),m.requestId);let l=m.body;if(l===null||typeof l!="object"||typeof l.arm_id!="string"||!("content"in l))return f(a("protocol_error","Decision response was missing required fields",{retryable:!1,status:200}),m.requestId);if(typeof l.content!=typeof o.fallback)return f(a("content_shape_mismatch","Served content does not match the fallback's shape",{retryable:!1,status:200}),m.requestId);let c={content:l.content,served:"curious",armId:l.arm_id,armType:l.arm_type??null,experimentId:l.experiment_id??null,experimentStatus:l.experiment_status??null,requestId:m.requestId};return n(o.element,c),c},track(o){return b?M().track(o):(s(a("capability_unavailable","Events are not collected before consent",{retryable:!1})),{id:"",queued:!1})},flush(o){return E===null?Promise.resolve({sent:0,duplicates:0,failed:0,pending:0}):E.flush(o)},page(){return r.autocapture===!1||r.autocapture?.pageviews===!1?{id:"",queued:!1}:b?typeof location>"u"?{id:"",queued:!1}:M().system({name:"$pageview",properties:{path:location.pathname}}):(s(a("capability_unavailable","Events are not collected before consent",{retryable:!1})),{id:"",queued:!1})},async identify(o){if(typeof o!="string"||o.trim().length===0)throw new g(a("invalid_input","identify: userId is required",{retryable:!1}));if(!b)throw new g(a("capability_unavailable","The SDK is not active (consent or start)",{retryable:!1}));return E!==null&&await E.flush({keepalive:!0}),u.setKnown(o),_.clear(),x.resetDecisions(),i(o),{userId:o}},async reset(){if(E!==null){try{await E.flush({keepalive:!0})}catch{}E.clear()}b&&u.reset(),_.clear(),x.resetDecisions(),i(null)},grantConsent(){y="implicit",w&&Q()},denyConsent(){y="denied",b=!1,x.stop();for(let o of I.splice(0))o();E?.clear(),_.clear(),u.clear(),i(null)},get anonymousId(){return u.anonymousId},get userId(){return u.knownUserId}}}function P(r){return(...e)=>{if(r!==void 0)try{r(...e)}catch{}}}function Ce(){let r=document.currentScript??document.querySelector("script[data-curious-key]"),e=r?.getAttribute("data-curious-key")??"";if(e.length===0)return console.error('Curious: the script tag needs data-curious-key="curious_pk_\u2026"'),null;let t=r?.getAttribute("data-curious-consent")??"implicit",n=r?.getAttribute("data-curious-autocapture")==="off",s=se({publishableKey:e,consent:t,...n?{autocapture:!1}:{}});return document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>s.start(),{once:!0}):s.start(),s}var Ae=Ce(),Me=Ae;return fe(De);})();
|
|
1
|
+
"use strict";var Curious=(()=>{var Y=Object.defineProperty;var Ie=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var ke=Object.prototype.hasOwnProperty;var Te=(r,e)=>{for(var t in e)Y(r,t,{get:e[t],enumerable:!0})},Ce=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Se(e))!ke.call(r,s)&&s!==t&&Y(r,s,{get:()=>e[s],enumerable:!(n=Ie(e,s))||n.enumerable});return r};var Ae=r=>Ce(Y({},"__esModule",{value:!0}),r);var Qe={};Te(Qe,{default:()=>ze});var y=class extends Error{constructor(e){super(e.message),this.name="CuriousError",this.summary=e}get code(){return this.summary.code}},ae=300;function a(r,e,t={}){let n=t.retryable??(r==="timeout"||r==="network_error"||r==="rate_limited"||r==="server_error"),s={code:r,retryable:n,message:e.length>ae?`${e.slice(0,ae)}\u2026`:e};return t.status!==void 0&&(s.status=t.status),t.requestId!==void 0&&(s.requestId=t.requestId),t.serverCode!==void 0&&(s.serverCode=t.serverCode),s}function Me(r){return typeof r=="object"&&r!==null&&typeof r.error=="string"&&typeof r.message=="string"?r:null}function k(r,e,t){let n=Me(e),s=n?.message??`HTTP ${r}`,o={status:r};return t!==null&&(o.requestId=t),n!==null&&(o.serverCode=n.error),r===401?a("authentication_error",s,o):r===403?a(/origin/i.test(s)?"origin_not_allowed":"authentication_error",s,o):r===408?a("timeout",s,o):r===429?a("rate_limited",s,o):r===409?n?.error==="idempotency_error"?a("mutation_drift",s,o):n?.error==="lock_timeout"?a("lock_timeout",s,{...o,retryable:!0}):/no live experiment/i.test(s)?a("undeclared_element",s,o):a("invalid_input",s,{...o,retryable:/retry/i.test(s)}):r>=500?a("server_error",s,o):r===400||r===413||r===422?a("invalid_input",s,o):a("protocol_error",s,{...o,retryable:!1})}var Z="curious_anon",ee="curious:anon",U="curious:user",qe=365*24*60*60,B=class{constructor(e={}){this.anonymous=null;this.known=null;this.enabled=!1;this.maxAge=e.cookieMaxAgeSeconds??qe,this.doc=e.document??(typeof document>"u"?null:document),this.local=e.storage===void 0?A("localStorage"):e.storage,this.session=A("sessionStorage")}enable(){this.enabled=!0,this.known=this.session===null?null:M(this.session,U),this.anonymous=this.readCookie()??(this.local===null?null:M(this.local,ee)),this.anonymous===null&&(this.anonymous=ue()),this.persistAnonymous()}get activeUserId(){if(!this.enabled)throw new y(a("capability_unavailable","Identity is unavailable before consent",{retryable:!1}));return this.known??this.anonymous}get anonymousId(){return this.anonymous}get knownUserId(){return this.known}setKnown(e){this.known=e,this.session!==null&&q(this.session,U,e)}reset(){this.known=null,this.session!==null&&R(this.session,U),this.anonymous=ue(),this.persistAnonymous()}clear(){this.enabled=!1,this.known=null,this.anonymous=null,this.session!==null&&R(this.session,U),this.local!==null&&R(this.local,ee),this.writeCookie("",0)}persistAnonymous(){this.anonymous!==null&&(this.writeCookie(this.anonymous,this.maxAge),this.local!==null&&q(this.local,ee,this.anonymous))}readCookie(){if(this.doc===null)return null;let e=this.doc.cookie.split("; ").find(n=>n.startsWith(`${Z}=`));if(e===void 0)return null;let t=decodeURIComponent(e.slice(Z.length+1));return/^anon_[0-9a-f-]{36}$/.test(t)?t:null}writeCookie(e,t){if(this.doc===null)return;let n=this.doc.location?.protocol==="https:"?"; Secure":"";try{this.doc.cookie=`${Z}=${encodeURIComponent(e)}; Max-Age=${t}; Path=/; SameSite=Lax${n}`}catch{}}};function ue(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return`anon_${crypto.randomUUID()}`;let r=new Uint8Array(16);crypto.getRandomValues(r),r[6]=r[6]&15|64,r[8]=r[8]&63|128;let e=Array.from(r,t=>t.toString(16).padStart(2,"0")).join("");return`anon_${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function A(r){try{let e=globalThis[r],t="__curious_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}function M(r,e){try{return r.getItem(e)}catch{return null}}function q(r,e,t){try{r.setItem(e,t)}catch{}}function R(r,e){try{r.removeItem(e)}catch{}}var le=1,De=6e4,de="curious:assign:",P=class{constructor(e){this.memory=new Map;this.store=e.storage===void 0?A("sessionStorage"):e.storage,this.ttlMs=e.ttlMs??De,this.fingerprint=e.publishableKey.slice(-8)}key(e,t){let n=typeof location>"u"?"":location.origin;return`${de}${this.fingerprint}:${n}:${e}:${t}`}get(e,t,n=Date.now()){let s=this.key(e,t),o=this.store===null?this.memory.get(s)??null:M(this.store,s);if(o===null)return null;try{let c=JSON.parse(o);return c.schema!==le||c.expiresAt<=n?(this.remove(e,t),null):c}catch{return this.remove(e,t),null}}set(e,t,n,s=Date.now()){let o={...n,storedAt:s,expiresAt:s+this.ttlMs,schema:le},c=this.key(e,t),d=JSON.stringify(o);this.store===null?this.memory.set(c,d):q(this.store,c,d)}remove(e,t){let n=this.key(e,t);this.memory.delete(n),this.store!==null&&R(this.store,n)}clear(){if(this.memory.clear(),this.store!==null)try{let e=[];for(let t=0;t<this.store.length;t+=1){let n=this.store.key(t);n!==null&&n.startsWith(de)&&e.push(n)}for(let t of e)this.store.removeItem(t)}catch{}}};var ce=new WeakMap;function me(r){for(let e of Array.from(r))try{e()}catch{}}function Re(r){let e=ce.get(r);if(e!==void 0)return e;let t=new Set;ce.set(r,t);for(let n of["pushState","replaceState"]){let s=r[n];if(typeof s=="function")try{r[n]=function(...o){let c=s.apply(this,o);return me(t),c}}catch{}}return addEventListener("popstate",()=>me(t)),t}function fe(r){if(typeof history>"u"||typeof addEventListener>"u")return()=>{};let e=Re(history);return e.add(r),()=>{e.delete(r)}}var T={flushIntervalMs:5e3,flushCount:20,queueLimit:100,keepaliveBodyBytes:48*1024,requestTimeoutMs:1e4,maxAttempts:5,itemCap:200},pe="curious:events",Oe="$",F=class{constructor(e){this.sequence=0;this.entries=[];this.timer=null;this.inFlight=null;this.o={transport:e.transport,userId:e.userId,flushIntervalMs:e.flushIntervalMs??T.flushIntervalMs,flushCount:e.flushCount??T.flushCount,queueLimit:e.queueLimit??T.queueLimit,keepaliveBodyBytes:e.keepaliveBodyBytes??T.keepaliveBodyBytes,requestTimeoutMs:e.requestTimeoutMs??T.requestTimeoutMs,maxAttempts:e.maxAttempts??T.maxAttempts,onEventDrop:e.onEventDrop},this.store=e.storage===void 0?A("sessionStorage"):e.storage,this.now=e.now??Date.now,this.sessionId=Math.random().toString(36).slice(2,10)+this.now().toString(36),this.restore()}get size(){return this.entries.length}track(e){if(typeof e.name=="string"&&e.name.startsWith(Oe))throw new y(a("invalid_input","Event names starting with $ are reserved",{retryable:!1}));return this.enqueue(e)}system(e){return this.enqueue(e)}enqueue(e){if(typeof e.name!="string"||e.name.trim().length===0)throw new y(a("invalid_input","track: name is required",{retryable:!1}));let t={id:e.id??`browser:${this.sessionId}:${++this.sequence}:${Math.random().toString(36).slice(2,8)}`,user_id:this.o.userId(),name:e.name};return e.value!==void 0&&(t.value=e.value),e.properties!==void 0&&(t.properties=e.properties),e.context!==void 0&&(t.context=e.context),e.timestamp!==void 0&&(t.timestamp=e.timestamp instanceof Date?e.timestamp.toISOString():e.timestamp),this.entries.length>=this.o.queueLimit?(this.o.onEventDrop(a("queue_full",`Event queue is full (${this.o.queueLimit}); event not queued`,{retryable:!0})),{id:t.id,queued:!1}):(this.entries.push({event:t,attempts:0}),this.persist(),this.entries.length>=this.o.flushCount?this.flush():this.timer===null&&(this.timer=setTimeout(()=>{this.timer=null,this.flush()},this.o.flushIntervalMs)),{id:t.id,queued:!0})}flush(e={}){return this.inFlight===null&&(this.inFlight=this.run(e.keepalive===!0).finally(()=>{this.inFlight=null})),this.inFlight}clear(){this.entries=[],this.persist()}async run(e){this.timer!==null&&(clearTimeout(this.timer),this.timer=null);let t={sent:0,duplicates:0,failed:0,pending:0};for(;this.entries.length>0;){let n=this.takeBatch(e);if(n.length===0)break;let s=await this.deliver(n,e,t);if(s.length>0){this.entries.unshift(...s),this.persist();break}}return t.pending=this.entries.length,this.persist(),t}takeBatch(e){let t=[],n=2;for(;this.entries.length>0&&t.length<T.itemCap;){let s=this.entries[0],o=JSON.stringify(s.event).length+1;if(e&&t.length>0&&n+o>this.o.keepaliveBodyBytes)break;t.push(this.entries.shift()),n+=o}return t}async deliver(e,t,n){for(let d of e)d.attempts+=1;let s;try{s=await this.o.transport.post("/events",{events:e.map(d=>d.event)},{timeoutMs:this.o.requestTimeoutMs,keepalive:t})}catch(d){return this.retryOrDrop(e,d.summary,n)}if(s.status!==200){let d=k(s.status,s.body,s.requestId);if(!d.retryable){for(let w of e)n.failed+=1,this.o.onEventDrop(a("event_rejected",d.message,{...d,retryable:!1}));return[]}return this.retryOrDrop(e,d,n)}let o=s.body?.results;if(!Array.isArray(o))return this.retryOrDrop(e,a("protocol_error","Batch response carried no results",{retryable:!0}),n);let c=[];return e.forEach((d,w)=>{let v=o[w];if(v==null||typeof v!="object"||v.index!==w){c.push(...this.retryOrDrop([d],a("protocol_error","Batch response had no result for this event",{retryable:!0}),n));return}if(v.status==="ok"){n.sent+=1,v.duplicate===!0&&(n.duplicates+=1);return}let x=k(v.error==="internal_error"?500:400,v,s.requestId);if(x.retryable&&d.attempts<this.o.maxAttempts){c.push(d);return}n.failed+=1,this.o.onEventDrop(a("event_rejected",x.message,{...x,retryable:!1}))}),c}retryOrDrop(e,t,n){let s=[];for(let o of e)o.attempts<this.o.maxAttempts?s.push(o):(n.failed+=1,this.o.onEventDrop(a("event_rejected",`Gave up after ${o.attempts} attempts: ${t.message}`,{...t,retryable:!1})));return s}persist(){this.store!==null&&q(this.store,pe,JSON.stringify(this.entries))}restore(){if(this.store===null)return;let e=M(this.store,pe);if(e!==null)try{let t=JSON.parse(e);Array.isArray(t)&&(this.entries=t.filter(n=>n&&typeof n.event?.id=="string").slice(0,this.o.queueLimit))}catch{this.entries=[]}}};var O="data-curious",Le="data-curious-ignore",Ne="data-curious-critical",$e="curious-loading",Ue="200% 0px";var Be=new Set(["AREA","BASE","BR","COL","EMBED","HR","IMG","INPUT","LINK","META","SOURCE","TRACK","WBR"]);function te(r){if(Be.has(r.tagName.toUpperCase()))return{unsupported:"void_element"};let e=null;for(let t of Array.from(r.childNodes)){if(t.nodeType===1)return{unsupported:"child_elements"};if(t.nodeType===3){if(e!==null)return{unsupported:"several_text_nodes"};e=t}}return{text:e}}var K=class{constructor(e){this.nodes=new Map;this.byElement=new Map;this.pending=new Set;this.released=new WeakSet;this.intersection=null;this.mutation=null;this.frame=null;this.o=e}start(){if(typeof IntersectionObserver=="function"&&(this.intersection=new IntersectionObserver(e=>{for(let t of e){if(!t.isIntersecting)continue;let n=this.nodes.get(t.target);n===void 0||n.state!=="idle"||(n.state="pending",this.pending.add(n.element),this.intersection?.unobserve(t.target))}this.schedule()},{rootMargin:this.o.rootMargin??Ue,threshold:0})),typeof MutationObserver=="function"){this.mutation=new MutationObserver(t=>{for(let n of t){if(n.type==="childList"){for(let o of n.removedNodes)o instanceof Element&&this.forgetRemoved(o);for(let o of n.addedNodes)o instanceof Element&&this.scan(o)}let s=n.target instanceof Element?n.target:n.target.parentElement;s!==null&&this.detectDrift(s)}});let e=this.o.root??document;this.mutation.observe(e instanceof Document?e.documentElement:e,{childList:!0,subtree:!0,characterData:!0})}this.scan(this.o.root??document)}stop(){this.intersection?.disconnect(),this.mutation?.disconnect(),this.intersection=null,this.mutation=null,this.frame!==null&&clearTimeout(this.frame),this.frame=null,this.nodes.clear(),this.byElement.clear(),this.pending.clear(),this.released=new WeakSet}scan(e=this.o.root??document){let t=[];e instanceof Element&&e.hasAttribute(O)&&t.push(e),t.push(...Array.from(e.querySelectorAll(`[${O}]`)));for(let n of t){if(this.nodes.has(n)||this.released.has(n)||n.closest(`[${Le}]`)!==null)continue;let s=(n.getAttribute(O)??"").trim();if(s.length===0)continue;let o={element:s,node:n,control:n.textContent??"",applied:null,state:"idle",drifted:!1};this.nodes.set(n,o);let c=te(n);if("unsupported"in c){this.refuse(o,c.unsupported);continue}let d=this.byElement.get(s);d===void 0&&(d=new Set,this.byElement.set(s,d)),d.add(o),this.intersection!==null?this.intersection.observe(n):(o.state="pending",this.pending.add(s))}this.pending.size>0&&this.schedule()}apply(e,t){let n=this.byElement.get(e);if(n===void 0)return"no_node";if(typeof t!="string"){for(let o of n)o.drifted||(o.state="fallback");return"not_text"}let s=!1;for(let o of Array.from(n)){if(!o.node.isConnected){this.forget(o);continue}if(o.drifted)continue;let c=te(o.node);if("unsupported"in c){this.refuse(o,c.unsupported);continue}c.text===null?o.node.appendChild(o.node.ownerDocument.createTextNode(t)):c.text.data!==t&&(c.text.data=t),o.applied=t,o.state="decided",this.revealCritical(o.node),s=!0}return s?"applied":"no_node"}fallback(e){let t=this.byElement.get(e);if(t!==void 0)for(let n of t)n.state="fallback",this.revealCritical(n.node)}resetDecisions(){for(let e of Array.from(this.nodes.values())){if(!e.node.isConnected){this.forget(e);continue}(e.state==="decided"||e.state==="fallback"||e.state==="pending")&&!e.drifted&&(e.state="idle",e.applied=null,this.intersection?.observe(e.node),this.intersection===null&&(e.state="pending",this.pending.add(e.element)))}this.pending.size>0&&this.schedule()}elements(){return Array.from(this.byElement.keys())}schedule(){this.frame!==null||this.pending.size===0||(this.frame=setTimeout(()=>{this.frame=null;let e=Array.from(this.pending).filter(t=>this.hasWritablePendingNode(t));this.pending.clear(),e.length>0&&this.o.onPending(e)},0))}hasWritablePendingNode(e){let t=this.byElement.get(e);if(t===void 0)return!1;let n=!1;for(let s of Array.from(t)){if(s.state!=="pending")continue;if(!s.node.isConnected){this.forget(s);continue}let o=te(s.node);"unsupported"in o?this.refuse(s,o.unsupported):n=!0}return n}forgetRemoved(e){let t=[e,...Array.from(e.querySelectorAll(`[${O}]`))];for(let n of t){let s=this.nodes.get(n);s!==void 0&&!n.isConnected&&this.forget(s)}}forget(e){this.nodes.delete(e.node),this.byElement.get(e.element)?.delete(e),this.intersection?.unobserve(e.node)}refuse(e,t){e.state="unsupported",this.byElement.get(e.element)?.delete(e),this.intersection?.unobserve(e.node),this.revealCritical(e.node),this.o.onUnsupported(e.element,t)}detectDrift(e){let t=e.closest(`[${O}]`);if(t===null)return;let n=this.nodes.get(t);n===void 0||n.state!=="decided"||n.drifted||(t.textContent??"")!==n.applied&&(n.drifted=!0,this.released.add(t),this.o.onDrift(n.element))}revealCritical(e){e.hasAttribute(Ne)&&document.documentElement.classList.remove($e)}};var he="0.2.0";var Pe=1048576,H=class{constructor(e){let t=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(t===void 0)throw new y(a("capability_unavailable","fetch is not available",{retryable:!1}));this.fetchImpl=t,this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.headers={authorization:`Bearer ${e.publishableKey}`,"content-type":"application/json","x-curious-client":`browser-js/${he}`}}async post(e,t,n){let s=new AbortController,o=setTimeout(()=>s.abort(),n.timeoutMs),c;try{c=await this.fetchImpl(`${this.baseUrl}${e}`,{method:"POST",headers:this.headers,body:JSON.stringify(t),signal:s.signal,keepalive:n.keepalive===!0,credentials:"omit",mode:"cors"})}catch(b){throw s.signal.aborted?new y(a("timeout",`No response within ${n.timeoutMs}ms`)):new y(a("network_error",ge(b)))}finally{clearTimeout(o)}let d=c.headers.get("x-request-id"),w=Fe(c.headers.get("retry-after")),v;try{v=await c.text()}catch(b){throw new y(a("network_error",ge(b),{status:c.status}))}if(v.length>Pe)throw new y(a("protocol_error","Response exceeds the size bound",{status:c.status,retryable:!1}));let x=null;if(v.length>0)try{x=JSON.parse(v)}catch{throw new y(a("protocol_error",`Response ${c.status} was not JSON`,{status:c.status,retryable:!1}))}return{status:c.status,requestId:d,retryAfterMs:w,body:x}}};function ge(r){return r instanceof Error&&r.message?`Request failed: ${r.message}`:"Request failed"}function Fe(r){if(r===null)return null;let e=Number(r);if(Number.isFinite(e)&&e>=0)return Math.round(e*1e3);let t=Date.parse(r);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var re={baseUrl:"https://api.trycurious.ai/v1",decideTimeoutMs:1e3},Ke="curious_pk_",ye=50,He=new Map([["internal_error",500],["decision_unavailable",503],["idempotency_error",409],["lock_timeout",409],["conflict",409]]),je={child_elements:"The tagged element contains other elements; the SDK replaces plain text only. Tag the innermost element that holds only text",several_text_nodes:"The tagged element's text is made of several pieces (a template with expressions); the SDK replaces one run of plain text only",void_element:"The tagged element cannot hold text (an input, an image or another empty element); tag an element whose content is text"};function ve(r){if(typeof r.publishableKey!="string"||r.publishableKey.length===0)throw new y(a("invalid_configuration","publishableKey is required",{retryable:!1}));if(!r.publishableKey.startsWith(Ke))throw new y(a("invalid_key_type","The browser SDK takes a publishable key (curious_pk_...). Never ship a secret key to a browser",{retryable:!1}));let e=Math.min(r.decideTimeoutMs??re.decideTimeoutMs,re.decideTimeoutMs*10);if(!Number.isFinite(e)||e<=0)throw new y(a("invalid_configuration","decideTimeoutMs must be a positive number",{retryable:!1}));let t=j(r.onFallback),n=j(r.onDecision),s=j(r.onEventDrop),o=j(r.onIdentityChange),c=new H({publishableKey:r.publishableKey,baseUrl:r.baseUrl??re.baseUrl,fetch:r.fetch}),d=new B({...r.cookieMaxAgeSeconds===void 0?{}:{cookieMaxAgeSeconds:r.cookieMaxAgeSeconds},document:r.document,storage:r.storage}),w=new P({publishableKey:r.publishableKey,...r.cacheTtlMs===void 0?{}:{ttlMs:r.cacheTtlMs},...r.storage===void 0?{}:{storage:r.storage}}),v=r.consent??"implicit",x=!1,b=!1,W=new Map,L=new Map,_=null,S=[],z=r.autocapture===!1?!1:r.autocapture?.pageviews??!0,Q=z!==!1,ne=Q&&(z===!0||z.historyChanges!==!1),J=null,N=!1,I=new K({...r.rootMargin===void 0?{}:{rootMargin:r.rootMargin},onPending:i=>{be(i)},onDrift:i=>t(i,a("mutation_drift","Applied content was rewritten by the page; the SDK will not reapply it",{retryable:!1})),onUnsupported:(i,f)=>t(i,a("content_shape_mismatch",je[f],{retryable:!1}))});function se(){let i={};return typeof location<"u"&&(i.path=location.pathname),typeof navigator<"u"&&navigator.language&&(i.locale=navigator.language),{...i,...r.context??{}}}function X(){J=location.pathname;let i=$().system({name:"$pageview",properties:{path:J}});return N=i.queued,i}function V(){return N&&location.pathname===J}function $(){if(_===null){let i=r.events??{};_=new F({transport:c,userId:()=>d.activeUserId,onEventDrop:s,storage:r.storage,...i.flushIntervalMs===void 0?{}:{flushIntervalMs:i.flushIntervalMs},...i.flushCount===void 0?{}:{flushCount:i.flushCount},...i.queueLimit===void 0?{}:{queueLimit:i.queueLimit}})}return _}async function be(i){if(!b)return;let f=d.activeUserId,p=[];for(let u of i){let l=w.get(f,u);if(l!==null){if(typeof l.content!="string"){C(u,a("content_shape_mismatch","Served content is not text",{retryable:!1,status:200}));continue}I.apply(u,l.content)==="applied"&&n(u,{content:l.content,served:"cache",armId:l.armId,armType:l.armType,experimentId:l.experimentId,experimentStatus:l.experimentStatus,requestId:null});continue}W.has(`${f}:${u}`)||p.push(u)}if(p.length===0)return;let m=(async()=>{for(let u=0;u<p.length;u+=ye){let l=p.slice(u,u+ye);await Ee(f,l)}})();for(let u of p)W.set(`${f}:${u}`,m);try{await m}finally{for(let u of p)W.delete(`${f}:${u}`)}}async function Ee(i,f){let p=()=>!b||d.activeUserId!==i;if(p())return;let m;try{m=await c.post("/decide",{user_id:i,context:se(),elements:f.map(l=>({element:l}))},{timeoutMs:e})}catch(l){if(p())return;for(let E of f)C(E,l.summary);return}if(p())return;if(m.status!==200){let l=k(m.status,m.body,m.requestId);for(let E of f)C(E,l);return}let u=m.body?.results;f.forEach((l,E)=>{if(p())return;let h=Array.isArray(u)?u[E]:void 0;if(h==null||typeof h!="object"||h.index!==E){C(l,a("protocol_error","Batch response had no result for this element",{retryable:!1,status:200}));return}if(h.status==="error"){C(l,k(He.get(h.error)??400,h,m.requestId));return}let g=I.apply(l,h.content);if(!p()){if(g==="not_text"){C(l,a("content_shape_mismatch","Served content is not text",{retryable:!1,status:200}));return}w.set(i,l,{content:h.content,armId:h.arm_id,armType:h.arm_type??null,experimentId:h.experiment_id,experimentStatus:h.experiment_status}),g==="applied"&&n(l,{content:h.content,served:"curious",armId:h.arm_id,armType:h.arm_type??null,experimentId:h.experiment_id,experimentStatus:h.experiment_status,requestId:m.requestId})}})}async function _e(i,f){let p={element:f.element,user_id:i,context:{...se(),...f.context??{}}};f.identifiers!==void 0&&(p.identifiers=f.identifiers),f.attributes!==void 0&&(p.attributes=f.attributes);let m;try{m=await c.post("/decide",p,{timeoutMs:e})}catch(l){return{ok:!1,error:l.summary,requestId:null}}if(m.status!==200)return{ok:!1,error:k(m.status,m.body,m.requestId),requestId:m.requestId};let u=m.body;return u===null||typeof u!="object"||typeof u.arm_id!="string"||!("content"in u)?{ok:!1,error:a("protocol_error","Decision response was missing required fields",{retryable:!1,status:200}),requestId:m.requestId}:{ok:!0,content:u.content,armId:u.arm_id,armType:u.arm_type??null,experimentId:typeof u.experiment_id=="string"?u.experiment_id:null,experimentStatus:typeof u.experiment_status=="string"?u.experiment_status:null,requestId:m.requestId}}function C(i,f){I.fallback(i),t(i,f)}function we(){if(typeof document>"u")return;let i=()=>{document.visibilityState==="hidden"&&_!==null&&_.flush({keepalive:!0})},f=()=>{_!==null&&_.flush({keepalive:!0})};if(document.addEventListener("visibilitychange",i),addEventListener("pagehide",f),S.push(()=>document.removeEventListener("visibilitychange",i)),S.push(()=>removeEventListener("pagehide",f)),r.autocapture===!1)return;let p={taggedClicks:!0,taggedFormSubmits:!0,...r.autocapture};if(Q&&!V()&&X(),ne&&S.push(fe(()=>{b&&!V()&&X()})),p.taggedClicks){let m=u=>{let l=u.target instanceof Element?u.target.closest("[data-curious]"):null;if(l===null||l.closest("[data-curious-ignore]")!==null)return;let E=l.getAttribute("data-curious");E&&$().system({name:"$click",properties:{element_name:E}})};document.addEventListener("click",m,{capture:!0,passive:!0}),S.push(()=>document.removeEventListener("click",m,{capture:!0}))}if(p.taggedFormSubmits){let m=u=>{let l=u.target instanceof Element?u.target.closest("[data-curious]"):null;if(l===null||l.closest("[data-curious-ignore]")!==null)return;let E=l.getAttribute("data-curious");E&&$().system({name:"$form_submit",properties:{element_name:E}})};document.addEventListener("submit",m,{capture:!0,passive:!0}),S.push(()=>document.removeEventListener("submit",m,{capture:!0}))}}function ie(){b||(d.enable(),b=!0,we(),I.start())}return{start(){x=!0,v==="implicit"?ie():v==="denied"&&typeof document<"u"&&document.documentElement.classList.remove("curious-loading")},stop(){x=!1,b=!1,I.stop();for(let i of S.splice(0))i()},scan(i){b&&I.scan(i)},async decide(i){let f=(D,xe)=>(t(i.element,D),{content:i.fallback,served:"fallback",armId:null,armType:null,experimentId:null,experimentStatus:null,error:D,requestId:xe});if(!b)return f(a("capability_unavailable","The SDK is not active (consent or start)",{retryable:!1}),null);let p=d.activeUserId,m=i.identifiers===void 0&&i.attributes===void 0&&i.context===void 0,u=m?w.get(p,i.element):null;if(u!==null&&G(u.content,i.fallback)){let D={content:u.content,served:"cache",armId:u.armId,armType:u.armType,experimentId:u.experimentId,experimentStatus:u.experimentStatus,requestId:null};return n(i.element,D),D}let l=`${p}:${i.element}`,E=m?L.get(l):void 0,h=E??_e(p,i);m&&E===void 0&&(L.set(l,h),h.then(()=>{L.get(l)===h&&L.delete(l)}));let g=await h;if(!b||d.activeUserId!==p)return f(a("capability_unavailable","The SDK was stopped, or the visitor changed, while the decision was in flight",{retryable:!1}),g.requestId);if(!g.ok)return f(g.error,g.requestId);if(!G(g.content,i.fallback))return f(a("content_shape_mismatch","Served content does not match the fallback's shape",{retryable:!1,status:200}),g.requestId);let oe={content:g.content,served:E===void 0?"curious":"cache",armId:g.armId,armType:g.armType,experimentId:g.experimentId,experimentStatus:g.experimentStatus,requestId:g.requestId};return m&&g.experimentId!==null&&g.experimentStatus!==null?w.set(p,i.element,{content:g.content,armId:g.armId,armType:g.armType,experimentId:g.experimentId,experimentStatus:g.experimentStatus}):(i.identifiers!==void 0||i.attributes!==void 0)&&w.remove(p,i.element),n(i.element,oe),oe},track(i){return b?$().track(i):(s(a("capability_unavailable","Events are not collected before consent",{retryable:!1})),{id:"",queued:!1})},flush(i){return _===null?Promise.resolve({sent:0,duplicates:0,failed:0,pending:0}):_.flush(i)},page(){return Q?b?typeof location>"u"?{id:"",queued:!1}:ne&&V()?{id:"",queued:!1}:X():(s(a("capability_unavailable","Events are not collected before consent",{retryable:!1})),{id:"",queued:!1}):{id:"",queued:!1}},async identify(i){if(typeof i!="string"||i.trim().length===0)throw new y(a("invalid_input","identify: userId is required",{retryable:!1}));if(!b)throw new y(a("capability_unavailable","The SDK is not active (consent or start)",{retryable:!1}));return _!==null&&await _.flush({keepalive:!0}),d.setKnown(i),w.clear(),I.resetDecisions(),o(i),{userId:i}},async reset(){if(_!==null){try{await _.flush({keepalive:!0})}catch{}_.clear()}b&&d.reset(),w.clear(),I.resetDecisions(),N=!1,o(null)},grantConsent(){v="implicit",x&&ie()},denyConsent(){v="denied",b=!1,I.stop();for(let i of S.splice(0))i();_?.clear(),w.clear(),d.clear(),N=!1,o(null)},get anonymousId(){return d.anonymousId},get userId(){return d.knownUserId}}}function G(r,e){if(e==null)return!0;if(r==null)return!1;if(Array.isArray(e)||Array.isArray(r))return!Array.isArray(e)||!Array.isArray(r)?!1:e.length===0||r.every(t=>G(t,e[0]));if(typeof e!="object")return typeof r==typeof e;if(typeof r!="object")return!1;for(let[t,n]of Object.entries(e))if(!Object.prototype.hasOwnProperty.call(r,t)||!G(r[t],n))return!1;return!0}function j(r){return(...e)=>{if(r!==void 0)try{r(...e)}catch{}}}function Ge(){let r=document.currentScript??document.querySelector("script[data-curious-key]"),e=r?.getAttribute("data-curious-key")??"";if(e.length===0)return console.error('Curious: the script tag needs data-curious-key="curious_pk_\u2026"'),null;let t=r?.getAttribute("data-curious-consent")??"implicit",n=r?.getAttribute("data-curious-autocapture")==="off",s=ve({publishableKey:e,consent:t,...n?{autocapture:!1}:{}});return document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>s.start(),{once:!0}):s.start(),s}var We=Ge(),ze=We;return Ae(Qe);})();
|
|
2
2
|
Curious = Curious.default;
|
|
3
3
|
//# sourceMappingURL=curious.iife.js.map
|