@trycurious/js 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The Curious Authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,105 @@
1
- # Temporary Holding Version
1
+ # @trycurious/js
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The [Curious](https://trycurious.ai) browser SDK. Tag text on your page with `data-curious="element_name"`, and Curious decides what each visitor sees, with the page's own text as the fallback. Publishable keys only; a secret key is refused at construction. The server package is `@trycurious/node`.
4
+
5
+ > **Early release.** Tested in Chrome on a server-rendered React page and against the API's request handlers. Other browsers are not yet tested.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @trycurious/js
11
+ ```
12
+
13
+ ```ts
14
+ import { createCurious } from "@trycurious/js";
15
+
16
+ const curious = createCurious({ publishableKey: "curious_pk_…" });
17
+ curious.start();
18
+ ```
19
+
20
+ Or the script build, once hosted: `<script defer src="…/curious.iife.js" data-curious-key="curious_pk_…"></script>`.
21
+
22
+ ## Tag content
23
+
24
+ ```html
25
+ <h1 data-curious="pricing_hero">Ship better experiments without manual analysis</h1>
26
+ <button data-curious="pricing_cta">Start free</button>
27
+ ```
28
+
29
+ The attribute value is the element name, declared beforehand with a secret key (`POST /declare` or the server SDK). The current text is the fallback and stays unless Curious answers in time. `data-curious-ignore` excludes a subtree.
30
+
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
+
33
+ ```html
34
+ <!-- child elements: tag the span, or split the sentence into tagged pieces -->
35
+ <h1 data-curious="hero">Study <span class="accent">what matters</span> for the SAT</h1>
36
+
37
+ <!-- text a template builds from several pieces, such as React's `Plan {name}` -->
38
+ <p data-curious="plan">Plan <!-- -->A</p>
39
+ ```
40
+
41
+ An element that cannot hold text at all, such as `<input>` or `<img>`, is refused the same way.
42
+
43
+ ## What happens
44
+
45
+ - 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.
46
+ - The deadline is 1 second by default (lower is allowed, removing it is not); on timeout or any failure the control stays, no retry.
47
+ - Returned content is cached in `sessionStorage` for 60 seconds, so remounts and quick back-navigation render without a call and without a new decision row.
48
+ - 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
+ - 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
+ - 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 on each `page()` call, 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.
52
+
53
+ ## API
54
+
55
+ ```ts
56
+ curious.start(); curious.stop(); curious.scan(root?);
57
+ await curious.decide({ element: "promo", fallback: "Save 20%" });
58
+ curious.track({ name: "signed_up", properties: { plan: "pro" } });
59
+ await curious.flush();
60
+ curious.page(); // after a client-side route change: one more page view (nothing when page views are off)
61
+ curious.anonymousId; // the visitor's anon_… id; send it to your backend at login
62
+ await curious.identify("user_123"); // after YOUR backend linked the anonymous id with a secret key
63
+ await curious.reset(); // on logout
64
+ curious.grantConsent(); curious.denyConsent();
65
+ ```
66
+
67
+ Options: `baseUrl`, `decideTimeoutMs`, `consent` (`implicit` | `required` | `denied`), `autocapture`, `context`, `rootMargin`, `cacheTtlMs`, `cookieMaxAgeSeconds`, and the hooks `onDecision`, `onFallback`, `onEventDrop`, `onIdentityChange`. A throwing hook never breaks serving.
68
+
69
+ ## React and other frameworks that hydrate
70
+
71
+ On a server-rendered page, the SDK must not write before your framework has hydrated. If it does, most often on a repeat view when the answer comes from the 60-second cache, React finds text that differs from what it rendered, reports hydration errors (error 418 in React 19; 418, 423 and 425 in React 18) and renders the whole root again. The page ends up correct, but the errors reach your monitoring.
72
+
73
+ - **Start the SDK after hydration.** Create the client where you like and call `start()` from an effect in your root component. Effects run after hydration, so the SDK's first write comes when React already owns the page. Tested with React 19.3 and React 18.2. A root effect covers what hydrates with the root: a server-rendered `Suspense` boundary can hydrate later, so render tagged elements inside such a boundary only once it has hydrated.
74
+
75
+ ```tsx
76
+ // curious.ts
77
+ export const curious = createCurious({ publishableKey: "curious_pk_…" });
78
+
79
+ // the root component
80
+ useEffect(() => {
81
+ curious.start(); // calling it again is harmless
82
+ }, []);
83
+ ```
84
+
85
+ - **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
+ - **Call `curious.page()` when the route changes.** The SDK records one page view on start and does not watch the History API. Call it from the place your router reports a completed navigation.
87
+ - **Your state wins.** If a component later renders different text into a tagged element, that text shows and the SDK reports `mutation_drift`.
88
+
89
+ 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.
90
+
91
+ The script build starts itself when the document has loaded, which can be before hydration. On React 19 only, `suppressHydrationWarning` on each tagged element that already has text makes that safe (an empty tagged element gains a text node, which the attribute does not cover): React 19 [does not patch mismatched text](https://react.dev/reference/react-dom/client/hydrateRoot#suppressing-unavoidable-hydration-mismatch-errors) on an element that carries it, so the SDK's text stays and hydration completes without an error. Do not rely on it with React 18, which puts the server's text back: the visitor would see your original text after a decision was recorded.
92
+
93
+ ## Consent
94
+
95
+ `consent: "required"` reads no cookie, calls nothing and attaches no listeners until `grantConsent()`. `denyConsent()` clears the queue, the cache and the identity and returns to control-only behaviour. Choosing the mode your obligations require is yours; this is product behaviour, not legal advice.
96
+
97
+ ## Development
98
+
99
+ ```bash
100
+ npm ci
101
+ npm run check # tsc
102
+ npm test # vitest under jsdom
103
+ npm run build # dist/index.js (ESM) and dist/curious.iife.js (script)
104
+ npm run size # the 15 KiB gzip budget on the script build
105
+ ```
@@ -0,0 +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);})();
2
+ Curious = Curious.default;
3
+ //# sourceMappingURL=curious.iife.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/script.ts","../src/errors.ts","../src/identity.ts","../src/cache.ts","../src/events.ts","../src/tags.ts","../src/version.ts","../src/transport.ts","../src/client.ts"],"sourcesContent":["// The script build (docs/sdk.md §13, Script installation): a page loads it\n// with `<script defer src=\"…\" data-curious-key=\"curious_pk_…\">` and it starts\n// itself from the tag's attribute. `data-curious-consent=\"required\"` defers\n// everything until `Curious.grantConsent()`. The global is the client, so\n// `Curious.track(...)`, `Curious.identify(...)` and `Curious.reset()` work from\n// page code. `data-curious-autocapture=\"off\"` disables the SDK's own events.\n// The one unconditional console line is the fatal case: no key.\nimport { createCurious, type ConsentMode, type CuriousBrowser } from \"./client.ts\";\n\nfunction boot(): CuriousBrowser | null {\n const tag = document.currentScript ?? document.querySelector(\"script[data-curious-key]\");\n const key = tag?.getAttribute(\"data-curious-key\") ?? \"\";\n if (key.length === 0) {\n console.error(\"Curious: the script tag needs data-curious-key=\\\"curious_pk_…\\\"\");\n return null;\n }\n const consent = (tag?.getAttribute(\"data-curious-consent\") ?? \"implicit\") as ConsentMode;\n const autocaptureOff = tag?.getAttribute(\"data-curious-autocapture\") === \"off\";\n const client = createCurious({ publishableKey: key, consent, ...(autocaptureOff ? { autocapture: false as const } : {}) });\n if (document.readyState === \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", () => client.start(), { once: true });\n } else {\n client.start();\n }\n return client;\n}\n\nconst instance = boot();\nexport default instance;\n","// The SDK error model (docs/sdk.md §24), shared in shape with the server\n// package: a stable code and a bounded, redacted message. Browser diagnostics\n// reach the customer only through hooks (onFallback, onEventDrop); nothing is\n// logged unless debug is on, and nothing ever carries a key, a user field,\n// content or a raw body.\n\nexport type CuriousErrorCode =\n | \"invalid_configuration\"\n | \"invalid_key_type\"\n | \"invalid_input\"\n | \"timeout\"\n | \"network_error\"\n | \"authentication_error\"\n | \"origin_not_allowed\"\n | \"rate_limited\"\n | \"undeclared_element\"\n | \"server_error\"\n | \"protocol_error\"\n | \"content_shape_mismatch\"\n | \"queue_full\"\n | \"event_rejected\"\n | \"identity_conflict\"\n | \"capability_unavailable\"\n | \"mutation_drift\"\n | \"lock_timeout\";\n\nexport type CuriousErrorSummary = {\n code: CuriousErrorCode;\n status?: number;\n retryable: boolean;\n requestId?: string;\n serverCode?: string;\n message: string;\n};\n\nexport class CuriousError extends Error {\n readonly summary: CuriousErrorSummary;\n constructor(summary: CuriousErrorSummary) {\n super(summary.message);\n this.name = \"CuriousError\";\n this.summary = summary;\n }\n get code(): CuriousErrorCode {\n return this.summary.code;\n }\n}\n\nconst LIMIT = 300;\n\nexport function summary(\n code: CuriousErrorCode,\n message: string,\n extra: Partial<Omit<CuriousErrorSummary, \"code\" | \"message\">> = {},\n): CuriousErrorSummary {\n const retryable = extra.retryable ??\n (code === \"timeout\" || code === \"network_error\" || code === \"rate_limited\" || code === \"server_error\");\n const out: CuriousErrorSummary = {\n code,\n retryable,\n message: message.length > LIMIT ? `${message.slice(0, LIMIT)}…` : message,\n };\n if (extra.status !== undefined) out.status = extra.status;\n if (extra.requestId !== undefined) out.requestId = extra.requestId;\n if (extra.serverCode !== undefined) out.serverCode = extra.serverCode;\n return out;\n}\n\ntype Envelope = { error: string; message: string };\n\nfunction envelope(body: unknown): Envelope | null {\n if (\n typeof body === \"object\" && body !== null &&\n typeof (body as Envelope).error === \"string\" && typeof (body as Envelope).message === \"string\"\n ) return body as Envelope;\n return null;\n}\n\n// Map an API error (the data plane's `{error, message}` envelope at a status)\n// onto the code a hook receives. Item-level errors inside a batch 200 pass\n// their own code with a synthetic status.\nexport function summarizeHttpError(status: number, body: unknown, requestId: string | null): CuriousErrorSummary {\n const env = envelope(body);\n const message = env?.message ?? `HTTP ${status}`;\n const extra: Partial<CuriousErrorSummary> = { status };\n if (requestId !== null) extra.requestId = requestId;\n if (env !== null) extra.serverCode = env.error;\n if (status === 401) return summary(\"authentication_error\", message, extra);\n if (status === 403) return summary(/origin/i.test(message) ? \"origin_not_allowed\" : \"authentication_error\", message, extra);\n if (status === 408) return summary(\"timeout\", message, extra);\n if (status === 429) return summary(\"rate_limited\", message, extra);\n if (status === 409) {\n if (env?.error === \"idempotency_error\") return summary(\"mutation_drift\", message, extra);\n // The user's identity changed while the decision was selecting; the same\n // request succeeds on a retry. The server package maps it the same way.\n if (env?.error === \"lock_timeout\") return summary(\"lock_timeout\", message, { ...extra, retryable: true });\n if (/no live experiment/i.test(message)) return summary(\"undeclared_element\", message, extra);\n return summary(\"invalid_input\", message, { ...extra, retryable: /retry/i.test(message) });\n }\n if (status >= 500) return summary(\"server_error\", message, extra);\n if (status === 400 || status === 413 || status === 422) return summary(\"invalid_input\", message, extra);\n return summary(\"protocol_error\", message, { ...extra, retryable: false });\n}\n","// Anonymous and known identity in the browser (docs/sdk.md §15, §21).\n//\n// The anonymous id is `anon_<uuid>` from a cryptographic source, kept in a\n// first-party host-only cookie (SameSite=Lax, Secure on https, bounded\n// lifetime) with localStorage as a recovery mirror and memory as the last\n// resort. The SDK never infers identity from a device, IP or fingerprint; the\n// known id arrives only through identify(), after the customer's backend has\n// declared the link with a secret key. Under consent mode `required`, nothing\n// is read or written until grantConsent().\n\nimport { CuriousError, summary } from \"./errors.ts\";\n\nexport const COOKIE_NAME = \"curious_anon\";\nexport const STORAGE_KEY = \"curious:anon\";\nexport const KNOWN_KEY = \"curious:user\";\n// One year: the stickiness a static assignment needs, bounded as the spec\n// asks and disclosed in the docs; the owner's retention review may shorten it.\nexport const DEFAULT_COOKIE_MAX_AGE_SECONDS = 365 * 24 * 60 * 60;\n\nexport type StorageMode = \"cookie\" | \"memory\";\n\nexport type IdentityOptions = {\n cookieMaxAgeSeconds?: number;\n /** Tests inject a document/storage pair; browsers use the globals. */\n document?: Document | undefined;\n storage?: Storage | null | undefined;\n};\n\nexport class Identity {\n private readonly maxAge: number;\n private readonly doc: Document | null;\n private readonly local: Storage | null;\n private readonly session: Storage | null;\n private anonymous: string | null = null;\n private known: string | null = null;\n private enabled = false;\n\n constructor(options: IdentityOptions = {}) {\n this.maxAge = options.cookieMaxAgeSeconds ?? DEFAULT_COOKIE_MAX_AGE_SECONDS;\n this.doc = options.document ?? (typeof document === \"undefined\" ? null : document);\n this.local = options.storage === undefined ? safeStorage(\"localStorage\") : options.storage;\n this.session = safeStorage(\"sessionStorage\");\n }\n\n /** Called when consent allows identity: reads or mints the anonymous id. */\n enable(): void {\n this.enabled = true;\n this.known = this.session === null ? null : safeGet(this.session, KNOWN_KEY);\n this.anonymous = this.readCookie() ?? (this.local === null ? null : safeGet(this.local, STORAGE_KEY));\n if (this.anonymous === null) this.anonymous = newAnonymousId();\n this.persistAnonymous();\n }\n\n /** The id decisions and events are made for: the known user when set, else the anonymous one. */\n get activeUserId(): string {\n if (!this.enabled) {\n throw new CuriousError(summary(\"capability_unavailable\", \"Identity is unavailable before consent\", { retryable: false }));\n }\n return this.known ?? (this.anonymous as string);\n }\n\n get anonymousId(): string | null {\n return this.anonymous;\n }\n\n get knownUserId(): string | null {\n return this.known;\n }\n\n /** After the customer's backend linked the anonymous id, switch the active user. The anonymous id is retained as link evidence. */\n setKnown(userId: string): void {\n this.known = userId;\n if (this.session !== null) safeSet(this.session, KNOWN_KEY, userId);\n }\n\n /** Logout: drop the known id and start a fresh anonymous history. Never unlinks server-side. */\n reset(): void {\n this.known = null;\n if (this.session !== null) safeRemove(this.session, KNOWN_KEY);\n this.anonymous = newAnonymousId();\n this.persistAnonymous();\n }\n\n /** denyConsent(): remove everything the SDK stored about this browser. */\n clear(): void {\n this.enabled = false;\n this.known = null;\n this.anonymous = null;\n if (this.session !== null) safeRemove(this.session, KNOWN_KEY);\n if (this.local !== null) safeRemove(this.local, STORAGE_KEY);\n this.writeCookie(\"\", 0);\n }\n\n private persistAnonymous(): void {\n if (this.anonymous === null) return;\n this.writeCookie(this.anonymous, this.maxAge);\n if (this.local !== null) safeSet(this.local, STORAGE_KEY, this.anonymous);\n }\n\n private readCookie(): string | null {\n if (this.doc === null) return null;\n const match = this.doc.cookie.split(\"; \").find((part) => part.startsWith(`${COOKIE_NAME}=`));\n if (match === undefined) return null;\n const value = decodeURIComponent(match.slice(COOKIE_NAME.length + 1));\n return /^anon_[0-9a-f-]{36}$/.test(value) ? value : null;\n }\n\n private writeCookie(value: string, maxAge: number): void {\n if (this.doc === null) return;\n const secure = this.doc.location?.protocol === \"https:\" ? \"; Secure\" : \"\";\n try {\n // Host-only (no Domain attribute): no widening to parent domains by default.\n this.doc.cookie = `${COOKIE_NAME}=${encodeURIComponent(value)}; Max-Age=${maxAge}; Path=/; SameSite=Lax${secure}`;\n } catch {\n // Cookies blocked: memory and localStorage carry the id for this page.\n }\n }\n}\n\nexport function newAnonymousId(): string {\n if (typeof crypto !== \"undefined\" && typeof crypto.randomUUID === \"function\") {\n return `anon_${crypto.randomUUID()}`;\n }\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n bytes[6] = (bytes[6]! & 0x0f) | 0x40;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n return `anon_${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nexport function safeStorage(kind: \"localStorage\" | \"sessionStorage\"): Storage | null {\n try {\n const store = globalThis[kind];\n const probe = \"__curious_probe__\";\n store.setItem(probe, \"1\");\n store.removeItem(probe);\n return store;\n } catch {\n return null;\n }\n}\n\nexport function safeGet(store: Storage, key: string): string | null {\n try {\n return store.getItem(key);\n } catch {\n return null;\n }\n}\n\nexport function safeSet(store: Storage, key: string, value: string): void {\n try {\n store.setItem(key, value);\n } catch {\n // Quota or privacy mode: degrade to memory.\n }\n}\n\nexport function safeRemove(store: Storage, key: string): void {\n try {\n store.removeItem(key);\n } catch {\n // Nothing to do.\n }\n}\n","// The assignment cache (docs/sdk.md §17): returned content kept in\n// sessionStorage (memory fallback) for fast remounts and short repeat\n// navigation, 60 seconds by default. A hit renders without a call, so no new\n// decision row is written; a miss decides before anything is applied. Keyed\n// by key fingerprint, origin, active user and element, so a user or key\n// change never serves another's content.\n\nimport { safeGet, safeRemove, safeSet, safeStorage } from \"./identity.ts\";\n\nexport const CACHE_SCHEMA = 1;\nexport const DEFAULT_CACHE_TTL_MS = 60_000;\nconst PREFIX = \"curious:assign:\";\n\nexport type CachedAssignment = {\n content: unknown;\n armId: string;\n armType: \"control\" | \"variant\" | null;\n experimentId: string;\n experimentStatus: string;\n storedAt: number;\n expiresAt: number;\n schema: number;\n};\n\nexport class AssignmentCache {\n private readonly store: Storage | null;\n private readonly memory = new Map<string, string>();\n private readonly ttlMs: number;\n private readonly fingerprint: string;\n\n constructor(options: { publishableKey: string; ttlMs?: number; storage?: Storage | null }) {\n this.store = options.storage === undefined ? safeStorage(\"sessionStorage\") : options.storage;\n this.ttlMs = options.ttlMs ?? DEFAULT_CACHE_TTL_MS;\n // The last characters of the key, never the key: enough to separate two\n // keys on one origin without storing anything secret-shaped.\n this.fingerprint = options.publishableKey.slice(-8);\n }\n\n private key(userId: string, element: string): string {\n const origin = typeof location === \"undefined\" ? \"\" : location.origin;\n return `${PREFIX}${this.fingerprint}:${origin}:${userId}:${element}`;\n }\n\n get(userId: string, element: string, now = Date.now()): CachedAssignment | null {\n const key = this.key(userId, element);\n const raw = this.store === null ? this.memory.get(key) ?? null : safeGet(this.store, key);\n if (raw === null) return null;\n try {\n const parsed = JSON.parse(raw) as CachedAssignment;\n if (parsed.schema !== CACHE_SCHEMA || parsed.expiresAt <= now) {\n this.remove(userId, element);\n return null;\n }\n return parsed;\n } catch {\n this.remove(userId, element);\n return null;\n }\n }\n\n set(userId: string, element: string, value: Omit<CachedAssignment, \"storedAt\" | \"expiresAt\" | \"schema\">, now = Date.now()): void {\n const entry: CachedAssignment = { ...value, storedAt: now, expiresAt: now + this.ttlMs, schema: CACHE_SCHEMA };\n const key = this.key(userId, element);\n const raw = JSON.stringify(entry);\n if (this.store === null) this.memory.set(key, raw);\n else safeSet(this.store, key, raw);\n }\n\n remove(userId: string, element: string): void {\n const key = this.key(userId, element);\n this.memory.delete(key);\n if (this.store !== null) safeRemove(this.store, key);\n }\n\n /** identify(), reset(), denyConsent(): everything this SDK cached. */\n clear(): void {\n this.memory.clear();\n if (this.store === null) return;\n try {\n const doomed: string[] = [];\n for (let i = 0; i < this.store.length; i += 1) {\n const k = this.store.key(i);\n if (k !== null && k.startsWith(PREFIX)) doomed.push(k);\n }\n for (const k of doomed) this.store.removeItem(k);\n } catch {\n // Privacy mode: nothing persisted to clear.\n }\n }\n}\n","// The browser event queue (docs/sdk.md §19): bounded, mirrored to\n// sessionStorage so a same-tab navigation can retry with the original ids,\n// flushed on interval, count, visibilitychange-to-hidden, pagehide, and\n// explicit calls, with keepalive on lifecycle flushes and the body split under\n// the keepalive budget. Partial results follow the server SDK: successes and\n// duplicates leave, terminal rejections are dropped with a diagnostic,\n// retryable items keep their ids for a later attempt while the page lives.\n\nimport { CuriousError, summarizeHttpError, summary, type CuriousErrorSummary } from \"./errors.ts\";\nimport { safeGet, safeSet, safeStorage } from \"./identity.ts\";\nimport type { Transport } from \"./transport.ts\";\n\nexport type BrowserEventInput = {\n name: string;\n value?: number | null;\n properties?: Record<string, unknown>;\n context?: Record<string, unknown>;\n timestamp?: Date | string;\n id?: string;\n};\n\nexport type QueuedEvent = {\n id: string;\n user_id: string;\n name: string;\n value?: number | null;\n properties?: Record<string, unknown>;\n context?: Record<string, unknown>;\n timestamp?: string;\n};\n\nexport type FlushSummary = { sent: number; duplicates: number; failed: number; pending: number };\n\nexport type EventQueueOptions = {\n transport: Transport;\n userId: () => string;\n flushIntervalMs?: number;\n flushCount?: number;\n queueLimit?: number;\n keepaliveBodyBytes?: number;\n requestTimeoutMs?: number;\n maxAttempts?: number;\n onEventDrop: (error: CuriousErrorSummary) => void;\n storage?: Storage | null | undefined;\n now?: () => number;\n};\n\nconst DEFAULTS = {\n flushIntervalMs: 5_000,\n flushCount: 20,\n queueLimit: 100,\n keepaliveBodyBytes: 48 * 1024,\n requestTimeoutMs: 10_000,\n maxAttempts: 5,\n itemCap: 200,\n} as const;\n\nconst QUEUE_KEY = \"curious:events\";\nexport const RESERVED_PREFIX = \"$\";\n\ntype Entry = { event: QueuedEvent; attempts: number };\n\nexport class EventQueue {\n private readonly o: Required<Omit<EventQueueOptions, \"storage\" | \"now\">>;\n private readonly store: Storage | null;\n private readonly now: () => number;\n private readonly sessionId: string;\n private sequence = 0;\n private entries: Entry[] = [];\n private timer: ReturnType<typeof setTimeout> | null = null;\n private inFlight: Promise<FlushSummary> | null = null;\n\n constructor(options: EventQueueOptions) {\n this.o = {\n transport: options.transport,\n userId: options.userId,\n flushIntervalMs: options.flushIntervalMs ?? DEFAULTS.flushIntervalMs,\n flushCount: options.flushCount ?? DEFAULTS.flushCount,\n queueLimit: options.queueLimit ?? DEFAULTS.queueLimit,\n keepaliveBodyBytes: options.keepaliveBodyBytes ?? DEFAULTS.keepaliveBodyBytes,\n requestTimeoutMs: options.requestTimeoutMs ?? DEFAULTS.requestTimeoutMs,\n maxAttempts: options.maxAttempts ?? DEFAULTS.maxAttempts,\n onEventDrop: options.onEventDrop,\n };\n this.store = options.storage === undefined ? safeStorage(\"sessionStorage\") : options.storage;\n this.now = options.now ?? Date.now;\n this.sessionId = Math.random().toString(36).slice(2, 10) + this.now().toString(36);\n this.restore();\n }\n\n get size(): number {\n return this.entries.length;\n }\n\n /** Customer events; `$` names are reserved for the SDK's own capture path. */\n track(input: BrowserEventInput): { id: string; queued: boolean } {\n if (typeof input.name === \"string\" && input.name.startsWith(RESERVED_PREFIX)) {\n throw new CuriousError(summary(\"invalid_input\", \"Event names starting with $ are reserved\", { retryable: false }));\n }\n return this.enqueue(input);\n }\n\n /** The SDK's own autocapture events (`$pageview`, `$click`, `$form_submit`). */\n system(input: BrowserEventInput): { id: string; queued: boolean } {\n return this.enqueue(input);\n }\n\n private enqueue(input: BrowserEventInput): { id: string; queued: boolean } {\n if (typeof input.name !== \"string\" || input.name.trim().length === 0) {\n throw new CuriousError(summary(\"invalid_input\", \"track: name is required\", { retryable: false }));\n }\n const event: QueuedEvent = {\n id: input.id ?? `browser:${this.sessionId}:${++this.sequence}:${Math.random().toString(36).slice(2, 8)}`,\n user_id: this.o.userId(),\n name: input.name,\n };\n if (input.value !== undefined) event.value = input.value;\n if (input.properties !== undefined) event.properties = input.properties;\n if (input.context !== undefined) event.context = input.context;\n if (input.timestamp !== undefined) {\n event.timestamp = input.timestamp instanceof Date ? input.timestamp.toISOString() : input.timestamp;\n }\n if (this.entries.length >= this.o.queueLimit) {\n this.o.onEventDrop(summary(\"queue_full\", `Event queue is full (${this.o.queueLimit}); event not queued`, { retryable: true }));\n return { id: event.id, queued: false };\n }\n this.entries.push({ event, attempts: 0 });\n this.persist();\n if (this.entries.length >= this.o.flushCount) {\n void this.flush();\n } else if (this.timer === null) {\n this.timer = setTimeout(() => {\n this.timer = null;\n void this.flush();\n }, this.o.flushIntervalMs);\n }\n return { id: event.id, queued: true };\n }\n\n /** Deliver what is queued. `keepalive` is for lifecycle flushes (hidden, pagehide, before identify/reset). */\n flush(options: { keepalive?: boolean } = {}): Promise<FlushSummary> {\n if (this.inFlight === null) {\n this.inFlight = this.run(options.keepalive === true).finally(() => {\n this.inFlight = null;\n });\n }\n return this.inFlight;\n }\n\n /** reset()/denyConsent(): forget everything queued. */\n clear(): void {\n this.entries = [];\n this.persist();\n }\n\n private async run(keepalive: boolean): Promise<FlushSummary> {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n const totals: FlushSummary = { sent: 0, duplicates: 0, failed: 0, pending: 0 };\n while (this.entries.length > 0) {\n const batch = this.takeBatch(keepalive);\n if (batch.length === 0) break;\n const retry = await this.deliver(batch, keepalive, totals);\n // Retryable items go back to the front, in order, for a later flush;\n // this pass does not spin on them (the page must never block).\n if (retry.length > 0) {\n this.entries.unshift(...retry);\n this.persist();\n break;\n }\n }\n totals.pending = this.entries.length;\n this.persist();\n return totals;\n }\n\n // Up to the API's item cap, and under the keepalive body budget when the\n // flush rides keepalive.\n private takeBatch(keepalive: boolean): Entry[] {\n const batch: Entry[] = [];\n let bytes = 2;\n while (this.entries.length > 0 && batch.length < DEFAULTS.itemCap) {\n const next = this.entries[0]!;\n const size = JSON.stringify(next.event).length + 1;\n if (keepalive && batch.length > 0 && bytes + size > this.o.keepaliveBodyBytes) break;\n batch.push(this.entries.shift()!);\n bytes += size;\n }\n return batch;\n }\n\n private async deliver(batch: Entry[], keepalive: boolean, totals: FlushSummary): Promise<Entry[]> {\n for (const item of batch) item.attempts += 1;\n let response;\n try {\n response = await this.o.transport.post(\"/events\", { events: batch.map((e) => e.event) }, {\n timeoutMs: this.o.requestTimeoutMs,\n keepalive,\n });\n } catch (error) {\n return this.retryOrDrop(batch, (error as CuriousError).summary, totals);\n }\n if (response.status !== 200) {\n const failure = summarizeHttpError(response.status, response.body, response.requestId);\n if (!failure.retryable) {\n for (const item of batch) {\n totals.failed += 1;\n this.o.onEventDrop(summary(\"event_rejected\", failure.message, { ...failure, retryable: false }));\n }\n return [];\n }\n return this.retryOrDrop(batch, failure, totals);\n }\n const results = (response.body as { results?: unknown })?.results;\n if (!Array.isArray(results)) {\n return this.retryOrDrop(batch, summary(\"protocol_error\", \"Batch response carried no results\", { retryable: true }), totals);\n }\n const retry: Entry[] = [];\n batch.forEach((item, index) => {\n const result = results[index] as { index?: number; status?: string; error?: string; message?: string; duplicate?: true } | null | undefined;\n // An acknowledgement that cannot be matched to its event is not one:\n // retried within the same attempt limit as a malformed whole response.\n if (result === undefined || result === null || typeof result !== \"object\" || result.index !== index) {\n retry.push(...this.retryOrDrop([item], summary(\"protocol_error\", \"Batch response had no result for this event\", { retryable: true }), totals));\n return;\n }\n if (result.status === \"ok\") {\n totals.sent += 1;\n if (result.duplicate === true) totals.duplicates += 1;\n return;\n }\n const itemError = summarizeHttpError(result.error === \"internal_error\" ? 500 : 400, result, response.requestId);\n if (itemError.retryable && item.attempts < this.o.maxAttempts) {\n retry.push(item);\n return;\n }\n totals.failed += 1;\n this.o.onEventDrop(summary(\"event_rejected\", itemError.message, { ...itemError, retryable: false }));\n });\n return retry;\n }\n\n private retryOrDrop(batch: Entry[], failure: CuriousErrorSummary, totals: FlushSummary): Entry[] {\n const retry: Entry[] = [];\n for (const item of batch) {\n if (item.attempts < this.o.maxAttempts) {\n retry.push(item);\n } else {\n totals.failed += 1;\n this.o.onEventDrop(summary(\"event_rejected\", `Gave up after ${item.attempts} attempts: ${failure.message}`, {\n ...failure,\n retryable: false,\n }));\n }\n }\n return retry;\n }\n\n private persist(): void {\n if (this.store === null) return;\n safeSet(this.store, QUEUE_KEY, JSON.stringify(this.entries));\n }\n\n private restore(): void {\n if (this.store === null) return;\n const raw = safeGet(this.store, QUEUE_KEY);\n if (raw === null) return;\n try {\n const parsed = JSON.parse(raw) as Entry[];\n if (Array.isArray(parsed)) this.entries = parsed.filter((e) => e && typeof e.event?.id === \"string\").slice(0, this.o.queueLimit);\n } catch {\n this.entries = [];\n }\n }\n}\n","// Tagged content (docs/sdk.md §14, §16, §18): nodes with `data-curious` keep\n// their own text as the fallback, are decided when they approach the viewport\n// (one IntersectionObserver, 200% root margin), batched into one publishable\n// decide per frame, and never fought over with the page's framework: if\n// something else rewrites an applied node, the SDK records mutation_drift\n// once and leaves it alone. One MutationObserver picks up nodes added later;\n// `data-curious-ignore` excludes a subtree.\n//\n// The SDK replaces one run of plain text and nothing else. A tagged element\n// qualifies when it holds no child elements and at most one text node; the\n// SDK then writes into that text node itself, so a framework that owns the\n// node (React, after hydration) keeps owning it: its later updates reach the\n// page and are seen as drift. An element with child elements, or with text\n// made of several text nodes (a template with expressions), is never decided\n// and never written: assigning `textContent` there would delete the children,\n// and a decision for content that cannot be shown would record an exposure\n// that did not happen.\n\nexport const TAG_ATTRIBUTE = \"data-curious\";\nexport const IGNORE_ATTRIBUTE = \"data-curious-ignore\";\nexport const CRITICAL_ATTRIBUTE = \"data-curious-critical\";\nexport const LOADING_CLASS = \"curious-loading\";\nexport const DEFAULT_ROOT_MARGIN = \"200% 0px\";\n\nexport type TaggedNode = {\n element: string;\n node: Element;\n control: string;\n applied: string | null;\n state: \"idle\" | \"pending\" | \"decided\" | \"fallback\" | \"unsupported\";\n drifted: boolean;\n};\n\n/** Why a tagged element cannot take replaced text. */\nexport type UnsupportedReason = \"child_elements\" | \"several_text_nodes\" | \"void_element\";\n\n/**\n * What became of decided content: written to at least one node, refused\n * because it is not text, or left unwritten because no node could take it\n * (each such node was already reported as unsupported, or the page has since\n * taken its text back).\n */\nexport type ApplyOutcome = \"applied\" | \"not_text\" | \"no_node\";\n\nconst ELEMENT_NODE = 1;\nconst TEXT_NODE = 3;\n// HTML's void elements: a browser never renders text placed inside one.\nconst VOID_ELEMENTS = new Set([\"AREA\", \"BASE\", \"BR\", \"COL\", \"EMBED\", \"HR\", \"IMG\", \"INPUT\", \"LINK\", \"META\", \"SOURCE\", \"TRACK\", \"WBR\"]);\n\n// The one text node the SDK may write into, `null` for an element with no\n// text yet, or the reason the element's content is not one run of plain text.\n// Comment nodes are ignored: they hold no text and are left where they are.\nexport function textSlot(node: Element): { text: Text | null } | { unsupported: UnsupportedReason } {\n if (VOID_ELEMENTS.has(node.tagName.toUpperCase())) return { unsupported: \"void_element\" };\n let text: Text | null = null;\n for (const child of Array.from(node.childNodes)) {\n if (child.nodeType === ELEMENT_NODE) return { unsupported: \"child_elements\" };\n if (child.nodeType !== TEXT_NODE) continue;\n if (text !== null) return { unsupported: \"several_text_nodes\" };\n text = child as Text;\n }\n return { text };\n}\n\nexport type TagRuntimeOptions = {\n /** Called with the set of element names that became pending in one window. */\n onPending: (elements: string[]) => void;\n /** A node the page's framework rewrote after the SDK applied content. */\n onDrift: (element: string) => void;\n /** A tagged node whose content is not one run of plain text; reported once per node, never decided. */\n onUnsupported: (element: string, reason: UnsupportedReason) => void;\n rootMargin?: string;\n root?: ParentNode;\n};\n\nexport class TagRuntime {\n private readonly nodes = new Map<Element, TaggedNode>();\n private readonly byElement = new Map<string, Set<TaggedNode>>();\n private readonly pending = new Set<string>();\n // Nodes whose text the page took back after a decision. Kept apart from\n // `nodes` so the promise survives the node being removed and attached\n // again, and weakly so a discarded node can be collected.\n private released = new WeakSet<Element>();\n private readonly o: TagRuntimeOptions;\n private intersection: IntersectionObserver | null = null;\n private mutation: MutationObserver | null = null;\n private frame: ReturnType<typeof setTimeout> | null = null;\n\n constructor(options: TagRuntimeOptions) {\n this.o = options;\n }\n\n start(): void {\n if (typeof IntersectionObserver === \"function\") {\n this.intersection = new IntersectionObserver((entries) => {\n for (const entry of entries) {\n if (!entry.isIntersecting) continue;\n const tagged = this.nodes.get(entry.target);\n if (tagged === undefined || tagged.state !== \"idle\") continue;\n tagged.state = \"pending\";\n this.pending.add(tagged.element);\n this.intersection?.unobserve(entry.target);\n }\n this.schedule();\n }, { rootMargin: this.o.rootMargin ?? DEFAULT_ROOT_MARGIN, threshold: 0 });\n }\n if (typeof MutationObserver === \"function\") {\n this.mutation = new MutationObserver((records) => {\n for (const record of records) {\n if (record.type === \"childList\") {\n // Nodes the page removed are let go of, so a page that mounts\n // and unmounts sections does not accumulate them here.\n for (const removed of record.removedNodes) {\n if (removed instanceof Element) this.forgetRemoved(removed);\n }\n for (const added of record.addedNodes) {\n if (added instanceof Element) this.scan(added);\n }\n }\n // Text rewritten under an applied node by something else.\n const target = record.target instanceof Element ? record.target : record.target.parentElement;\n if (target !== null) this.detectDrift(target);\n }\n });\n const root = this.o.root ?? document;\n this.mutation.observe(root instanceof Document ? root.documentElement : (root as Node), {\n childList: true,\n subtree: true,\n characterData: true,\n });\n }\n this.scan(this.o.root ?? document);\n }\n\n stop(): void {\n this.intersection?.disconnect();\n this.mutation?.disconnect();\n this.intersection = null;\n this.mutation = null;\n if (this.frame !== null) clearTimeout(this.frame);\n this.frame = null;\n // Nothing is remembered across a stop: a later start() scans the page as\n // it then is. Remembered nodes would be skipped by that scan and never\n // watched by the new observers.\n this.nodes.clear();\n this.byElement.clear();\n this.pending.clear();\n this.released = new WeakSet();\n }\n\n /** Register every tagged node under `root` (the whole document by default). Safe to call repeatedly. */\n scan(root: ParentNode = this.o.root ?? document): void {\n const candidates: Element[] = [];\n if (root instanceof Element && root.hasAttribute(TAG_ATTRIBUTE)) candidates.push(root);\n candidates.push(...Array.from(root.querySelectorAll(`[${TAG_ATTRIBUTE}]`)));\n for (const node of candidates) {\n if (this.nodes.has(node) || this.released.has(node) || node.closest(`[${IGNORE_ATTRIBUTE}]`) !== null) continue;\n const element = (node.getAttribute(TAG_ATTRIBUTE) ?? \"\").trim();\n if (element.length === 0) continue;\n const tagged: TaggedNode = { element, node, control: node.textContent ?? \"\", applied: null, state: \"idle\", drifted: false };\n this.nodes.set(node, tagged);\n const slot = textSlot(node);\n if (\"unsupported\" in slot) {\n // Remembered, so a rescan does not report it again; never observed,\n // never pending, so no decision is requested on its account.\n this.refuse(tagged, slot.unsupported);\n continue;\n }\n let set = this.byElement.get(element);\n if (set === undefined) {\n set = new Set();\n this.byElement.set(element, set);\n }\n set.add(tagged);\n if (this.intersection !== null) this.intersection.observe(node);\n else {\n // No IntersectionObserver (an old or headless environment): decide on scan.\n tagged.state = \"pending\";\n this.pending.add(element);\n }\n }\n if (this.pending.size > 0) this.schedule();\n }\n\n /** Apply decided content to every node of an element that can take it. Non-string content leaves the control in place. */\n apply(element: string, content: unknown): ApplyOutcome {\n const set = this.byElement.get(element);\n if (set === undefined) return \"no_node\";\n if (typeof content !== \"string\") {\n for (const tagged of set) {\n if (!tagged.drifted) tagged.state = \"fallback\";\n }\n return \"not_text\";\n }\n let applied = false;\n for (const tagged of Array.from(set)) {\n // A node the page has removed shows nothing: writing to it is not\n // serving the content.\n if (!tagged.node.isConnected) {\n this.forget(tagged);\n continue;\n }\n // The page rewrote this node after an earlier decision: it owns the\n // text now, and a later decision for the same name (another node\n // mounting, a new user) does not take it back.\n if (tagged.drifted) continue;\n // The page may have changed the node since it was scanned.\n const slot = textSlot(tagged.node);\n if (\"unsupported\" in slot) {\n this.refuse(tagged, slot.unsupported);\n continue;\n }\n // Write into the existing text node, so whatever owns that node keeps\n // owning it. An element with no text yet gets a text node of its own.\n if (slot.text === null) tagged.node.appendChild(tagged.node.ownerDocument.createTextNode(content));\n else if (slot.text.data !== content) slot.text.data = content;\n tagged.applied = content;\n tagged.state = \"decided\";\n this.revealCritical(tagged.node);\n applied = true;\n }\n return applied ? \"applied\" : \"no_node\";\n }\n\n /** Leave the control visible and mark the element as decided against. */\n fallback(element: string): void {\n const set = this.byElement.get(element);\n if (set === undefined) return;\n for (const tagged of set) {\n tagged.state = \"fallback\";\n this.revealCritical(tagged.node);\n }\n }\n\n /** Forget decisions (identify/reset) so the nodes can be decided again for the new user. */\n resetDecisions(): void {\n for (const tagged of Array.from(this.nodes.values())) {\n if (!tagged.node.isConnected) {\n this.forget(tagged);\n continue;\n }\n // A node still waiting for the previous user's answer is decided again\n // too; that answer is discarded when it arrives.\n if ((tagged.state === \"decided\" || tagged.state === \"fallback\" || tagged.state === \"pending\") && !tagged.drifted) {\n tagged.state = \"idle\";\n tagged.applied = null;\n this.intersection?.observe(tagged.node);\n if (this.intersection === null) {\n tagged.state = \"pending\";\n this.pending.add(tagged.element);\n }\n }\n }\n if (this.pending.size > 0) this.schedule();\n }\n\n elements(): string[] {\n return Array.from(this.byElement.keys());\n }\n\n private schedule(): void {\n if (this.frame !== null || this.pending.size === 0) return;\n // A short window collects the tags that became pending together into one\n // batch request.\n this.frame = setTimeout(() => {\n this.frame = null;\n // A node may have changed since it was scanned (a framework rendering\n // children into it, or removing it, before it neared the viewport). Ask\n // only for names that a node near the viewport can still show.\n const batch = Array.from(this.pending).filter((element) => this.hasWritablePendingNode(element));\n this.pending.clear();\n if (batch.length > 0) this.o.onPending(batch);\n }, 0);\n }\n\n // True when a node that neared the viewport (state `pending`) is still on\n // the page and can still take text. A plain sibling that is still off\n // screen does not count: it asks for the decision when it gets near. Nodes\n // that can no longer take text are refused here, and removed ones\n // forgotten, before a decision is requested on their account.\n private hasWritablePendingNode(element: string): boolean {\n const set = this.byElement.get(element);\n if (set === undefined) return false;\n let writable = false;\n for (const tagged of Array.from(set)) {\n if (tagged.state !== \"pending\") continue;\n if (!tagged.node.isConnected) {\n this.forget(tagged);\n continue;\n }\n const slot = textSlot(tagged.node);\n if (\"unsupported\" in slot) this.refuse(tagged, slot.unsupported);\n else writable = true;\n }\n return writable;\n }\n\n private forgetRemoved(removed: Element): void {\n const candidates: Element[] = [removed, ...Array.from(removed.querySelectorAll(`[${TAG_ATTRIBUTE}]`))];\n for (const node of candidates) {\n const tagged = this.nodes.get(node);\n // Still connected means the page moved it; it stays known.\n if (tagged !== undefined && !node.isConnected) this.forget(tagged);\n }\n }\n\n // Drop a node the page has removed. If the same node is attached again, the\n // MutationObserver scans it afresh.\n private forget(tagged: TaggedNode): void {\n this.nodes.delete(tagged.node);\n this.byElement.get(tagged.element)?.delete(tagged);\n this.intersection?.unobserve(tagged.node);\n }\n\n // Take a node out of play for good: never observed, never decided, never\n // written, reported once.\n private refuse(tagged: TaggedNode, reason: UnsupportedReason): void {\n tagged.state = \"unsupported\";\n this.byElement.get(tagged.element)?.delete(tagged);\n this.intersection?.unobserve(tagged.node);\n this.revealCritical(tagged.node);\n this.o.onUnsupported(tagged.element, reason);\n }\n\n private detectDrift(target: Element): void {\n const node = target.closest(`[${TAG_ATTRIBUTE}]`);\n if (node === null) return;\n const tagged = this.nodes.get(node);\n if (tagged === undefined || tagged.state !== \"decided\" || tagged.drifted) return;\n if ((node.textContent ?? \"\") !== tagged.applied) {\n tagged.drifted = true;\n this.released.add(node);\n this.o.onDrift(tagged.element);\n }\n }\n\n private revealCritical(node: Element): void {\n if (node.hasAttribute(CRITICAL_ATTRIBUTE)) {\n document.documentElement.classList.remove(LOADING_CLASS);\n }\n }\n}\n","// Kept in step with package.json by the release checklist; sent as\n// `X-Curious-Client: browser-js/<version>` (docs/sdk.md §6).\nexport const SDK_VERSION = \"0.1.0\";\n","// The browser transport (docs/sdk.md §6, §16, §19): authenticated fetch with\n// the publishable key, a hard deadline, optional keepalive for lifecycle\n// flushes, and the region chosen through the query parameter Supabase\n// documents for callers that cannot add headers to a preflight.\n\nimport { CuriousError, summary } from \"./errors.ts\";\nimport { SDK_VERSION } from \"./version.ts\";\n\nexport type FetchLike = (input: string, init: RequestInit) => Promise<Response>;\n\nexport type TransportResponse = {\n status: number;\n requestId: string | null;\n retryAfterMs: number | null;\n body: unknown;\n};\n\nconst MAX_RESPONSE_BYTES = 1_048_576;\n\nexport class Transport {\n private readonly fetchImpl: FetchLike;\n private readonly baseUrl: string;\n private readonly headers: Record<string, string>;\n\n constructor(options: { publishableKey: string; baseUrl: string; fetch?: FetchLike | undefined }) {\n const fetchImpl = options.fetch ?? (typeof fetch === \"function\" ? fetch.bind(globalThis) : undefined);\n if (fetchImpl === undefined) {\n throw new CuriousError(summary(\"capability_unavailable\", \"fetch is not available\", { retryable: false }));\n }\n this.fetchImpl = fetchImpl;\n this.baseUrl = options.baseUrl.replace(/\\/+$/, \"\");\n this.headers = {\n authorization: `Bearer ${options.publishableKey}`,\n \"content-type\": \"application/json\",\n \"x-curious-client\": `browser-js/${SDK_VERSION}`,\n };\n }\n\n // POST one JSON body within the deadline. Throws for a timeout, a network\n // failure or an unreadable response; returns every HTTP status.\n async post(\n path: string,\n body: unknown,\n options: { timeoutMs: number; keepalive?: boolean },\n ): Promise<TransportResponse> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), options.timeoutMs);\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.baseUrl}${path}`, {\n method: \"POST\",\n headers: this.headers,\n body: JSON.stringify(body),\n signal: controller.signal,\n keepalive: options.keepalive === true,\n credentials: \"omit\",\n mode: \"cors\",\n });\n } catch (error) {\n if (controller.signal.aborted) {\n throw new CuriousError(summary(\"timeout\", `No response within ${options.timeoutMs}ms`));\n }\n throw new CuriousError(summary(\"network_error\", describe(error)));\n } finally {\n clearTimeout(timer);\n }\n const requestId = response.headers.get(\"x-request-id\");\n const retryAfterMs = parseRetryAfter(response.headers.get(\"retry-after\"));\n let text: string;\n try {\n text = await response.text();\n } catch (error) {\n throw new CuriousError(summary(\"network_error\", describe(error), { status: response.status }));\n }\n if (text.length > MAX_RESPONSE_BYTES) {\n throw new CuriousError(summary(\"protocol_error\", \"Response exceeds the size bound\", { status: response.status, retryable: false }));\n }\n let parsed: unknown = null;\n if (text.length > 0) {\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new CuriousError(summary(\"protocol_error\", `Response ${response.status} was not JSON`, {\n status: response.status,\n retryable: false,\n }));\n }\n }\n return { status: response.status, requestId, retryAfterMs, body: parsed };\n }\n}\n\nfunction describe(error: unknown): string {\n return error instanceof Error && error.message ? `Request failed: ${error.message}` : \"Request failed\";\n}\n\nexport function parseRetryAfter(value: string | null): number | null {\n if (value === null) return null;\n const seconds = Number(value);\n if (Number.isFinite(seconds) && seconds >= 0) return Math.round(seconds * 1000);\n const at = Date.parse(value);\n return Number.isNaN(at) ? null : Math.max(0, at - Date.now());\n}\n","// @trycurious/js — Curious in the browser (docs/sdk.md §13–§23). Publishable\n// keys only. Tagged text is decided when it approaches the viewport, in one\n// batch per frame, through the page's own text as the fallback; events batch\n// through a bounded queue that survives same-tab navigation; identity is an\n// anonymous first-party cookie until the customer's backend links it.\n\nimport { AssignmentCache } from \"./cache.ts\";\nimport { CuriousError, summarizeHttpError, summary, type CuriousErrorSummary } from \"./errors.ts\";\nimport { EventQueue, type BrowserEventInput, type FlushSummary } from \"./events.ts\";\nimport { Identity } from \"./identity.ts\";\nimport { TagRuntime } from \"./tags.ts\";\nimport { Transport, type FetchLike } from \"./transport.ts\";\n\nexport type ConsentMode = \"implicit\" | \"required\" | \"denied\";\n\nexport type BrowserOptions = {\n /** A publishable key (`curious_pk_...`). A secret key is refused: it must never reach a browser. */\n publishableKey: string;\n /** Default `https://api.trycurious.ai/v1`. */\n baseUrl?: string;\n /** The decide deadline; the page's text stays when it passes. Default 1000, may be lowered, never removed. */\n decideTimeoutMs?: number;\n /** `implicit` starts at once; `required` does nothing until grantConsent(); `denied` serves controls and collects nothing. */\n consent?: ConsentMode;\n /**\n * The SDK's own events, on by default (docs/sdk.md §19, Autocapture V1): `$pageview` with the\n * normalized path on start, `$click` and `$form_submit` on tagged nodes with the element name.\n * `false` turns them all off; an object turns individual ones off. The API admits them only under\n * a publishable key with the SDK's client header, which the transport always sends.\n */\n autocapture?: { pageviews?: boolean; taggedClicks?: boolean; taggedFormSubmits?: boolean } | false;\n /** Context sent with every tagged decision; `path` and `locale` are added unless you set them. */\n context?: Record<string, unknown>;\n rootMargin?: string;\n /** Queue tuning; the defaults are the spec's (5 s, 20 events, 100 queued). */\n events?: { flushIntervalMs?: number; flushCount?: number; queueLimit?: number };\n cacheTtlMs?: number;\n cookieMaxAgeSeconds?: number;\n onDecision?: (element: string, result: DecisionResult<unknown>) => void;\n onFallback?: (element: string, error: CuriousErrorSummary) => void;\n onEventDrop?: (error: CuriousErrorSummary) => void;\n onIdentityChange?: (userId: string | null) => void;\n /** For tests. */\n fetch?: FetchLike;\n document?: Document;\n storage?: Storage | null;\n debug?: boolean;\n};\n\nexport type DecisionResult<T> = {\n content: T;\n served: \"curious\" | \"fallback\" | \"cache\";\n armId: string | null;\n armType: \"control\" | \"variant\" | null;\n experimentId: string | null;\n experimentStatus: string | null;\n error?: CuriousErrorSummary;\n requestId: string | null;\n};\n\nexport type BrowserDecisionInput<T> = {\n element: string;\n fallback: T;\n identifiers?: Record<string, unknown>;\n attributes?: Record<string, unknown>;\n context?: Record<string, unknown>;\n};\n\nexport type CuriousBrowser = {\n start(): void;\n stop(): void;\n scan(root?: ParentNode): void;\n decide<T>(input: BrowserDecisionInput<T>): Promise<DecisionResult<T>>;\n track(input: BrowserEventInput): { id: string; queued: boolean };\n flush(options?: { keepalive?: boolean }): Promise<FlushSummary>;\n /**\n * Record a page view for the current location. Call it after a client-side route change: the SDK\n * records one page view on start and does not watch the History API. It records nothing when page\n * views are turned off through `autocapture`.\n */\n page(): { id: string; queued: boolean };\n identify(userId: string): Promise<{ userId: string }>;\n reset(): Promise<void>;\n grantConsent(): void;\n denyConsent(): void;\n readonly anonymousId: string | null;\n readonly userId: string | null;\n};\n\nconst DEFAULTS = { baseUrl: \"https://api.trycurious.ai/v1\", decideTimeoutMs: 1_000 } as const;\nconst PUBLISHABLE_PREFIX = \"curious_pk_\";\nconst DECIDE_BATCH_LIMIT = 50;\n\n// A batch item reports its error code without a status; these are the\n// statuses the same codes carry on a single decide, so both map alike. Kept\n// equal to the server package's table, plus `conflict` (an undeclared\n// element), which only a publishable key meets.\nconst BATCH_ITEM_STATUS: ReadonlyMap<string, number> = new Map([\n [\"internal_error\", 500],\n [\"decision_unavailable\", 503],\n [\"idempotency_error\", 409],\n [\"lock_timeout\", 409],\n [\"conflict\", 409],\n]);\n\nconst UNSUPPORTED_MESSAGE = {\n child_elements: \"The tagged element contains other elements; the SDK replaces plain text only. Tag the innermost element that holds only text\",\n 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\",\n void_element: \"The tagged element cannot hold text (an input, an image or another empty element); tag an element whose content is text\",\n} as const;\n\ntype ItemOk = { index: number; element: string; status: \"ok\"; content: unknown; arm_id: string; arm_type: \"control\" | \"variant\" | null; experiment_id: string; experiment_status: string };\ntype ItemError = { index: number; element?: string | null; status: \"error\"; error: string; message: string };\n\nexport function createCurious(options: BrowserOptions): CuriousBrowser {\n if (typeof options.publishableKey !== \"string\" || options.publishableKey.length === 0) {\n throw new CuriousError(summary(\"invalid_configuration\", \"publishableKey is required\", { retryable: false }));\n }\n if (!options.publishableKey.startsWith(PUBLISHABLE_PREFIX)) {\n // A secret key in a page is a leak; refuse without echoing it.\n throw new CuriousError(summary(\"invalid_key_type\", \"The browser SDK takes a publishable key (curious_pk_...). Never ship a secret key to a browser\", { retryable: false }));\n }\n const timeoutMs = Math.min(options.decideTimeoutMs ?? DEFAULTS.decideTimeoutMs, DEFAULTS.decideTimeoutMs * 10);\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new CuriousError(summary(\"invalid_configuration\", \"decideTimeoutMs must be a positive number\", { retryable: false }));\n }\n const onFallback = guarded(options.onFallback);\n const onDecision = guarded(options.onDecision);\n const onEventDrop = guarded(options.onEventDrop);\n const onIdentityChange = guarded(options.onIdentityChange);\n\n const transport = new Transport({ publishableKey: options.publishableKey, baseUrl: options.baseUrl ?? DEFAULTS.baseUrl, fetch: options.fetch });\n const identity = new Identity({\n ...(options.cookieMaxAgeSeconds === undefined ? {} : { cookieMaxAgeSeconds: options.cookieMaxAgeSeconds }),\n document: options.document,\n storage: options.storage,\n });\n const cache = new AssignmentCache({ publishableKey: options.publishableKey, ...(options.cacheTtlMs === undefined ? {} : { ttlMs: options.cacheTtlMs }), ...(options.storage === undefined ? {} : { storage: options.storage }) });\n let consent: ConsentMode = options.consent ?? \"implicit\";\n let started = false;\n let active = false;\n const inFlight = new Map<string, Promise<void>>();\n let events: EventQueue | null = null;\n const listeners: Array<() => void> = [];\n\n const tags = new TagRuntime({\n ...(options.rootMargin === undefined ? {} : { rootMargin: options.rootMargin }),\n onPending: (elements) => void decideTagged(elements),\n onDrift: (element) => onFallback(element, summary(\"mutation_drift\", \"Applied content was rewritten by the page; the SDK will not reapply it\", { retryable: false })),\n onUnsupported: (element, reason) => onFallback(element, summary(\"content_shape_mismatch\", UNSUPPORTED_MESSAGE[reason], { retryable: false })),\n });\n\n function pageContext(): Record<string, unknown> {\n const base: Record<string, unknown> = {};\n if (typeof location !== \"undefined\") base.path = location.pathname;\n if (typeof navigator !== \"undefined\" && navigator.language) base.locale = navigator.language;\n return { ...base, ...(options.context ?? {}) };\n }\n\n function queue(): EventQueue {\n if (events === null) {\n const tuning = options.events ?? {};\n events = new EventQueue({\n transport,\n userId: () => identity.activeUserId,\n onEventDrop,\n storage: options.storage,\n ...(tuning.flushIntervalMs === undefined ? {} : { flushIntervalMs: tuning.flushIntervalMs }),\n ...(tuning.flushCount === undefined ? {} : { flushCount: tuning.flushCount }),\n ...(tuning.queueLimit === undefined ? {} : { queueLimit: tuning.queueLimit }),\n });\n }\n return events;\n }\n\n // One batch decide for the tags that became pending together; one in-flight\n // request per (user, element), cache hits applied without a call.\n async function decideTagged(elements: string[]): Promise<void> {\n if (!active) return;\n const userId = identity.activeUserId;\n const toRequest: string[] = [];\n for (const element of elements) {\n const hit = cache.get(userId, element);\n if (hit !== null) {\n // Reported as served only when a node took the text.\n if (tags.apply(element, hit.content) === \"applied\") {\n onDecision(element, { content: hit.content, served: \"cache\", armId: hit.armId, armType: hit.armType, experimentId: hit.experimentId, experimentStatus: hit.experimentStatus, requestId: null });\n }\n continue;\n }\n if (!inFlight.has(`${userId}:${element}`)) toRequest.push(element);\n }\n if (toRequest.length === 0) return;\n const run = (async () => {\n for (let i = 0; i < toRequest.length; i += DECIDE_BATCH_LIMIT) {\n const slice = toRequest.slice(i, i + DECIDE_BATCH_LIMIT);\n await decideBatch(userId, slice);\n }\n })();\n for (const element of toRequest) inFlight.set(`${userId}:${element}`, run);\n try {\n await run;\n } finally {\n for (const element of toRequest) inFlight.delete(`${userId}:${element}`);\n }\n }\n\n async function decideBatch(userId: string, elements: string[]): Promise<void> {\n // While the request was out the SDK may have been stopped (stop(),\n // denyConsent()) or the visitor may have become someone else (identify(),\n // reset()). An answer for the earlier state is discarded: it is not\n // written to the page, cached or reported. After an identity change the\n // tags have already been queued again for the new user.\n const stale = () => !active || identity.activeUserId !== userId;\n // A later slice of a large batch: nothing more is sent for a state that\n // has already ended.\n if (stale()) return;\n let response;\n try {\n response = await transport.post(\"/decide\", {\n user_id: userId,\n context: pageContext(),\n elements: elements.map((element) => ({ element })),\n }, { timeoutMs });\n } catch (error) {\n if (stale()) return;\n for (const element of elements) fallbackTag(element, (error as CuriousError).summary);\n return;\n }\n if (stale()) return;\n if (response.status !== 200) {\n const failure = summarizeHttpError(response.status, response.body, response.requestId);\n for (const element of elements) fallbackTag(element, failure);\n return;\n }\n const results = (response.body as { results?: unknown })?.results;\n elements.forEach((element, index) => {\n if (stale()) return;\n const item = Array.isArray(results) ? (results[index] as ItemOk | ItemError | null | undefined) : undefined;\n if (item === undefined || item === null || typeof item !== \"object\" || item.index !== index) {\n fallbackTag(element, summary(\"protocol_error\", \"Batch response had no result for this element\", { retryable: false, status: 200 }));\n return;\n }\n if (item.status === \"error\") {\n fallbackTag(element, summarizeHttpError(BATCH_ITEM_STATUS.get(item.error) ?? 400, item, response.requestId));\n return;\n }\n const outcome = tags.apply(element, item.content);\n // apply() can call the customer's onFallback hook, and a hook may stop\n // the SDK or withdraw consent; nothing is cached or reported after that.\n if (stale()) return;\n if (outcome === \"not_text\") {\n fallbackTag(element, summary(\"content_shape_mismatch\", \"Served content is not text\", { retryable: false, status: 200 }));\n return;\n }\n // The decision exists on the server whatever the page did meanwhile, so\n // it is kept for a node that mounts later. It is reported as served\n // only when a node took the text; a node that could not was already\n // reported through onFallback.\n cache.set(userId, element, { content: item.content, armId: item.arm_id, armType: item.arm_type ?? null, experimentId: item.experiment_id, experimentStatus: item.experiment_status });\n if (outcome === \"applied\") {\n onDecision(element, { content: item.content, served: \"curious\", armId: item.arm_id, armType: item.arm_type ?? null, experimentId: item.experiment_id, experimentStatus: item.experiment_status, requestId: response.requestId });\n }\n });\n }\n\n function fallbackTag(element: string, error: CuriousErrorSummary): void {\n tags.fallback(element);\n onFallback(element, error);\n }\n\n function attachLifecycle(): void {\n if (typeof document === \"undefined\") return;\n const onVisibility = () => {\n if (document.visibilityState === \"hidden\" && events !== null) void events.flush({ keepalive: true });\n };\n const onPageHide = () => {\n if (events !== null) void events.flush({ keepalive: true });\n };\n document.addEventListener(\"visibilitychange\", onVisibility);\n addEventListener(\"pagehide\", onPageHide);\n listeners.push(() => document.removeEventListener(\"visibilitychange\", onVisibility));\n listeners.push(() => removeEventListener(\"pagehide\", onPageHide));\n\n if (options.autocapture === false) return;\n const capture = { pageviews: true, taggedClicks: true, taggedFormSubmits: true, ...options.autocapture };\n if (capture.pageviews) {\n queue().system({ name: \"$pageview\", properties: { path: location.pathname } });\n }\n if (capture.taggedClicks) {\n const onClick = (event: Event) => {\n const target = event.target instanceof Element ? event.target.closest(\"[data-curious]\") : null;\n if (target === null || target.closest(\"[data-curious-ignore]\") !== null) return;\n const element = target.getAttribute(\"data-curious\");\n if (element) queue().system({ name: \"$click\", properties: { element_name: element } });\n };\n document.addEventListener(\"click\", onClick, { capture: true, passive: true });\n listeners.push(() => document.removeEventListener(\"click\", onClick, { capture: true }));\n }\n if (capture.taggedFormSubmits) {\n const onSubmit = (event: Event) => {\n const target = event.target instanceof Element ? event.target.closest(\"[data-curious]\") : null;\n if (target === null || target.closest(\"[data-curious-ignore]\") !== null) return;\n const element = target.getAttribute(\"data-curious\");\n if (element) queue().system({ name: \"$form_submit\", properties: { element_name: element } });\n };\n document.addEventListener(\"submit\", onSubmit, { capture: true, passive: true });\n listeners.push(() => document.removeEventListener(\"submit\", onSubmit, { capture: true }));\n }\n }\n\n function activate(): void {\n if (active) return;\n identity.enable();\n active = true;\n attachLifecycle();\n tags.start();\n }\n\n const client: CuriousBrowser = {\n start() {\n started = true;\n if (consent === \"implicit\") activate();\n else if (consent === \"denied\" && typeof document !== \"undefined\") {\n document.documentElement.classList.remove(\"curious-loading\");\n }\n },\n stop() {\n started = false;\n active = false;\n tags.stop();\n for (const off of listeners.splice(0)) off();\n },\n scan(root) {\n if (active) tags.scan(root);\n },\n async decide<T>(input: BrowserDecisionInput<T>): Promise<DecisionResult<T>> {\n const fallback = (error: CuriousErrorSummary, requestId: string | null): DecisionResult<T> => {\n onFallback(input.element, error);\n return { content: input.fallback, served: \"fallback\", armId: null, armType: null, experimentId: null, experimentStatus: null, error, requestId };\n };\n if (!active) return fallback(summary(\"capability_unavailable\", \"The SDK is not active (consent or start)\", { retryable: false }), null);\n const body: Record<string, unknown> = { element: input.element, user_id: identity.activeUserId, context: { ...pageContext(), ...(input.context ?? {}) } };\n if (input.identifiers !== undefined) body.identifiers = input.identifiers;\n if (input.attributes !== undefined) body.attributes = input.attributes;\n let response;\n try {\n response = await transport.post(\"/decide\", body, { timeoutMs });\n } catch (error) {\n return fallback((error as CuriousError).summary, null);\n }\n if (response.status !== 200) return fallback(summarizeHttpError(response.status, response.body, response.requestId), response.requestId);\n const decision = response.body as Partial<ItemOk> | null;\n if (decision === null || typeof decision !== \"object\" || typeof decision.arm_id !== \"string\" || !(\"content\" in decision)) {\n return fallback(summary(\"protocol_error\", \"Decision response was missing required fields\", { retryable: false, status: 200 }), response.requestId);\n }\n if (typeof decision.content !== typeof input.fallback) {\n return fallback(summary(\"content_shape_mismatch\", \"Served content does not match the fallback's shape\", { retryable: false, status: 200 }), response.requestId);\n }\n const result: DecisionResult<T> = { content: decision.content as T, served: \"curious\", armId: decision.arm_id, armType: decision.arm_type ?? null, experimentId: decision.experiment_id ?? null, experimentStatus: decision.experiment_status ?? null, requestId: response.requestId };\n onDecision(input.element, result);\n return result;\n },\n track(input) {\n if (!active) {\n onEventDrop(summary(\"capability_unavailable\", \"Events are not collected before consent\", { retryable: false }));\n return { id: \"\", queued: false };\n }\n return queue().track(input);\n },\n flush(flushOptions) {\n if (events === null) return Promise.resolve({ sent: 0, duplicates: 0, failed: 0, pending: 0 });\n return events.flush(flushOptions);\n },\n page() {\n // The same switch as the page view on start: `autocapture: false` and\n // `autocapture: { pageviews: false }` turn this event off wherever it\n // would come from.\n if (options.autocapture === false || options.autocapture?.pageviews === false) return { id: \"\", queued: false };\n if (!active) {\n onEventDrop(summary(\"capability_unavailable\", \"Events are not collected before consent\", { retryable: false }));\n return { id: \"\", queued: false };\n }\n if (typeof location === \"undefined\") return { id: \"\", queued: false };\n // The path only, as on start: no query string, no hash (docs/sdk.md §19).\n return queue().system({ name: \"$pageview\", properties: { path: location.pathname } });\n },\n // After the customer's backend has linked the anonymous id with a secret\n // key: flush anonymous events, switch the active user, forget cached\n // assignments, decide tags again for the known user.\n async identify(userId) {\n if (typeof userId !== \"string\" || userId.trim().length === 0) {\n throw new CuriousError(summary(\"invalid_input\", \"identify: userId is required\", { retryable: false }));\n }\n if (!active) throw new CuriousError(summary(\"capability_unavailable\", \"The SDK is not active (consent or start)\", { retryable: false }));\n if (events !== null) await events.flush({ keepalive: true });\n identity.setKnown(userId);\n cache.clear();\n tags.resetDecisions();\n onIdentityChange(userId);\n return { userId };\n },\n // Logout: a bounded flush, then a fresh anonymous history. Never unlinks\n // anything server-side, and a failed flush never prevents the isolation.\n async reset() {\n if (events !== null) {\n try {\n await events.flush({ keepalive: true });\n } catch {\n // Best effort.\n }\n events.clear();\n }\n if (active) identity.reset();\n cache.clear();\n tags.resetDecisions();\n onIdentityChange(null);\n },\n grantConsent() {\n consent = \"implicit\";\n if (started) activate();\n },\n denyConsent() {\n consent = \"denied\";\n active = false;\n tags.stop();\n for (const off of listeners.splice(0)) off();\n events?.clear();\n cache.clear();\n identity.clear();\n onIdentityChange(null);\n },\n get anonymousId() {\n return identity.anonymousId;\n },\n get userId() {\n return identity.knownUserId;\n },\n };\n return client;\n}\n\nfunction guarded<A extends unknown[]>(hook: ((...args: A) => void) | undefined): (...args: A) => void {\n return (...args) => {\n if (hook === undefined) return;\n try {\n hook(...args);\n } catch {\n // A customer hook never breaks serving or the queue.\n }\n };\n}\n"],"mappings":"qcAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,aAAAE,KCmCO,IAAMC,EAAN,cAA2B,KAAM,CAEtC,YAAYC,EAA8B,CACxC,MAAMA,EAAQ,OAAO,EACrB,KAAK,KAAO,eACZ,KAAK,QAAUA,CACjB,CACA,IAAI,MAAyB,CAC3B,OAAO,KAAK,QAAQ,IACtB,CACF,EAEMC,EAAQ,IAEP,SAASD,EACdE,EACAC,EACAC,EAAgE,CAAC,EAC5C,CACrB,IAAMC,EAAYD,EAAM,YACrBF,IAAS,WAAaA,IAAS,iBAAmBA,IAAS,gBAAkBA,IAAS,gBACnFI,EAA2B,CAC/B,KAAAJ,EACA,UAAAG,EACA,QAASF,EAAQ,OAASF,EAAQ,GAAGE,EAAQ,MAAM,EAAGF,CAAK,CAAC,SAAME,CACpE,EACA,OAAIC,EAAM,SAAW,SAAWE,EAAI,OAASF,EAAM,QAC/CA,EAAM,YAAc,SAAWE,EAAI,UAAYF,EAAM,WACrDA,EAAM,aAAe,SAAWE,EAAI,WAAaF,EAAM,YACpDE,CACT,CAIA,SAASC,GAASC,EAAgC,CAChD,OACE,OAAOA,GAAS,UAAYA,IAAS,MACrC,OAAQA,EAAkB,OAAU,UAAY,OAAQA,EAAkB,SAAY,SAC/EA,EACF,IACT,CAKO,SAASC,EAAmBC,EAAgBF,EAAeG,EAA+C,CAC/G,IAAMC,EAAML,GAASC,CAAI,EACnBL,EAAUS,GAAK,SAAW,QAAQF,CAAM,GACxCN,EAAsC,CAAE,OAAAM,CAAO,EAGrD,OAFIC,IAAc,OAAMP,EAAM,UAAYO,GACtCC,IAAQ,OAAMR,EAAM,WAAaQ,EAAI,OACrCF,IAAW,IAAYV,EAAQ,uBAAwBG,EAASC,CAAK,EACrEM,IAAW,I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,SAAS,aAAe,UAC1B,SAAS,iBAAiB,mBAAoB,IAAMC,EAAO,MAAM,EAAG,CAAE,KAAM,EAAK,CAAC,EAElFA,EAAO,MAAM,EAERA,CACT,CAEA,IAAME,GAAWP,GAAK,EACfQ,GAAQD","names":["script_exports","__export","script_default","CuriousError","summary","LIMIT","code","message","extra","retryable","out","envelope","body","summarizeHttpError","status","requestId","env","COOKIE_NAME","STORAGE_KEY","KNOWN_KEY","DEFAULT_COOKIE_MAX_AGE_SECONDS","Identity","options","safeStorage","safeGet","newAnonymousId","CuriousError","summary","userId","safeSet","safeRemove","match","part","value","maxAge","secure","bytes","hex","b","kind","store","probe","key","CACHE_SCHEMA","DEFAULT_CACHE_TTL_MS","PREFIX","AssignmentCache","options","safeStorage","userId","element","origin","now","key","raw","safeGet","parsed","value","entry","safeSet","safeRemove","doomed","i","k","DEFAULTS","QUEUE_KEY","RESERVED_PREFIX","EventQueue","options","safeStorage","input","CuriousError","summary","event","keepalive","totals","batch","retry","bytes","next","size","item","response","e","error","failure","summarizeHttpError","results","index","result","itemError","safeSet","raw","safeGet","parsed","TAG_ATTRIBUTE","IGNORE_ATTRIBUTE","CRITICAL_ATTRIBUTE","LOADING_CLASS","DEFAULT_ROOT_MARGIN","VOID_ELEMENTS","textSlot","node","text","child","TagRuntime","options","entries","entry","tagged","DEFAULT_ROOT_MARGIN","records","record","removed","added","target","root","candidates","TAG_ATTRIBUTE","IGNORE_ATTRIBUTE","element","slot","set","content","applied","batch","writable","reason","CRITICAL_ATTRIBUTE","LOADING_CLASS","SDK_VERSION","MAX_RESPONSE_BYTES","Transport","options","fetchImpl","CuriousError","summary","SDK_VERSION","path","body","controller","timer","response","error","describe","requestId","retryAfterMs","parseRetryAfter","text","parsed","value","seconds","at","DEFAULTS","PUBLISHABLE_PREFIX","DECIDE_BATCH_LIMIT","BATCH_ITEM_STATUS","UNSUPPORTED_MESSAGE","createCurious","options","CuriousError","summary","timeoutMs","onFallback","guarded","onDecision","onEventDrop","onIdentityChange","transport","Transport","identity","Identity","cache","AssignmentCache","consent","started","active","inFlight","events","listeners","tags","TagRuntime","elements","decideTagged","element","reason","pageContext","base","queue","tuning","EventQueue","userId","toRequest","hit","run","i","slice","decideBatch","stale","response","error","fallbackTag","failure","summarizeHttpError","results","index","item","outcome","attachLifecycle","onVisibility","onPageHide","capture","onClick","event","target","onSubmit","activate","off","root","input","fallback","requestId","body","decision","result","flushOptions","hook","args","boot","tag","key","consent","autocaptureOff","client","createCurious","instance","script_default"]}
@@ -0,0 +1,127 @@
1
+ type CuriousErrorCode = "invalid_configuration" | "invalid_key_type" | "invalid_input" | "timeout" | "network_error" | "authentication_error" | "origin_not_allowed" | "rate_limited" | "undeclared_element" | "server_error" | "protocol_error" | "content_shape_mismatch" | "queue_full" | "event_rejected" | "identity_conflict" | "capability_unavailable" | "mutation_drift" | "lock_timeout";
2
+ type CuriousErrorSummary = {
3
+ code: CuriousErrorCode;
4
+ status?: number;
5
+ retryable: boolean;
6
+ requestId?: string;
7
+ serverCode?: string;
8
+ message: string;
9
+ };
10
+ declare class CuriousError extends Error {
11
+ readonly summary: CuriousErrorSummary;
12
+ constructor(summary: CuriousErrorSummary);
13
+ get code(): CuriousErrorCode;
14
+ }
15
+
16
+ type FetchLike = (input: string, init: RequestInit) => Promise<Response>;
17
+
18
+ type BrowserEventInput = {
19
+ name: string;
20
+ value?: number | null;
21
+ properties?: Record<string, unknown>;
22
+ context?: Record<string, unknown>;
23
+ timestamp?: Date | string;
24
+ id?: string;
25
+ };
26
+ type FlushSummary = {
27
+ sent: number;
28
+ duplicates: number;
29
+ failed: number;
30
+ pending: number;
31
+ };
32
+
33
+ type ConsentMode = "implicit" | "required" | "denied";
34
+ type BrowserOptions = {
35
+ /** A publishable key (`curious_pk_...`). A secret key is refused: it must never reach a browser. */
36
+ publishableKey: string;
37
+ /** Default `https://api.trycurious.ai/v1`. */
38
+ baseUrl?: string;
39
+ /** The decide deadline; the page's text stays when it passes. Default 1000, may be lowered, never removed. */
40
+ decideTimeoutMs?: number;
41
+ /** `implicit` starts at once; `required` does nothing until grantConsent(); `denied` serves controls and collects nothing. */
42
+ consent?: ConsentMode;
43
+ /**
44
+ * The SDK's own events, on by default (docs/sdk.md §19, Autocapture V1): `$pageview` with the
45
+ * normalized path on start, `$click` and `$form_submit` on tagged nodes with the element name.
46
+ * `false` turns them all off; an object turns individual ones off. The API admits them only under
47
+ * a publishable key with the SDK's client header, which the transport always sends.
48
+ */
49
+ autocapture?: {
50
+ pageviews?: boolean;
51
+ taggedClicks?: boolean;
52
+ taggedFormSubmits?: boolean;
53
+ } | false;
54
+ /** Context sent with every tagged decision; `path` and `locale` are added unless you set them. */
55
+ context?: Record<string, unknown>;
56
+ rootMargin?: string;
57
+ /** Queue tuning; the defaults are the spec's (5 s, 20 events, 100 queued). */
58
+ events?: {
59
+ flushIntervalMs?: number;
60
+ flushCount?: number;
61
+ queueLimit?: number;
62
+ };
63
+ cacheTtlMs?: number;
64
+ cookieMaxAgeSeconds?: number;
65
+ onDecision?: (element: string, result: DecisionResult<unknown>) => void;
66
+ onFallback?: (element: string, error: CuriousErrorSummary) => void;
67
+ onEventDrop?: (error: CuriousErrorSummary) => void;
68
+ onIdentityChange?: (userId: string | null) => void;
69
+ /** For tests. */
70
+ fetch?: FetchLike;
71
+ document?: Document;
72
+ storage?: Storage | null;
73
+ debug?: boolean;
74
+ };
75
+ type DecisionResult<T> = {
76
+ content: T;
77
+ served: "curious" | "fallback" | "cache";
78
+ armId: string | null;
79
+ armType: "control" | "variant" | null;
80
+ experimentId: string | null;
81
+ experimentStatus: string | null;
82
+ error?: CuriousErrorSummary;
83
+ requestId: string | null;
84
+ };
85
+ type BrowserDecisionInput<T> = {
86
+ element: string;
87
+ fallback: T;
88
+ identifiers?: Record<string, unknown>;
89
+ attributes?: Record<string, unknown>;
90
+ context?: Record<string, unknown>;
91
+ };
92
+ type CuriousBrowser = {
93
+ start(): void;
94
+ stop(): void;
95
+ scan(root?: ParentNode): void;
96
+ decide<T>(input: BrowserDecisionInput<T>): Promise<DecisionResult<T>>;
97
+ track(input: BrowserEventInput): {
98
+ id: string;
99
+ queued: boolean;
100
+ };
101
+ flush(options?: {
102
+ keepalive?: boolean;
103
+ }): Promise<FlushSummary>;
104
+ /**
105
+ * Record a page view for the current location. Call it after a client-side route change: the SDK
106
+ * records one page view on start and does not watch the History API. It records nothing when page
107
+ * views are turned off through `autocapture`.
108
+ */
109
+ page(): {
110
+ id: string;
111
+ queued: boolean;
112
+ };
113
+ identify(userId: string): Promise<{
114
+ userId: string;
115
+ }>;
116
+ reset(): Promise<void>;
117
+ grantConsent(): void;
118
+ denyConsent(): void;
119
+ readonly anonymousId: string | null;
120
+ readonly userId: string | null;
121
+ };
122
+ declare function createCurious(options: BrowserOptions): CuriousBrowser;
123
+
124
+ declare const SDK_VERSION = "0.1.0";
125
+
126
+ export { CuriousError, SDK_VERSION, createCurious };
127
+ export type { BrowserDecisionInput, BrowserEventInput, BrowserOptions, ConsentMode, CuriousBrowser, CuriousErrorCode, CuriousErrorSummary, DecisionResult, FlushSummary };