@prodantix/sdk 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -1
- package/dist/chat.cjs +6 -6
- package/dist/chat.js +6 -6
- package/dist/chunk-4RLPQZ5L.js +2 -0
- package/dist/chunk-ODN4ZELX.js +2 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/messenger.cjs +1 -1
- package/dist/messenger.iife.js +6 -6
- package/dist/messenger.js +1 -1
- package/dist/node.cjs +1 -1
- package/dist/node.js +1 -1
- package/dist/web.cjs +1 -1
- package/dist/web.d.cts +5 -1
- package/dist/web.d.ts +5 -1
- package/dist/web.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-ESOQKMEE.js +0 -2
- package/dist/chunk-VG77TYVX.js +0 -2
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var ue=Object.defineProperty;var pe=(n,e,t)=>e in n?ue(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var o=(n,e,t)=>pe(n,typeof e!="symbol"?e+"":e,t);var u=class extends Error{constructor(t,s,r){super(s,r);o(this,"code");this.code=t,this.name="ProdantixError";}},y=class extends u{constructor(e){super("config",e),this.name="ConfigError";}},h=class extends u{constructor(t,s){super("validation",s);o(this,"field");this.field=t,this.name="ValidationError";}},l=class extends u{constructor(t,s,r){super("transport",t,r);o(this,"status");this.status=s,this.name="TransportError";}};function v(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function p(){let n=globalThis.AbortController;return n?new n:void 0}var G=n=>new Promise(e=>{setTimeout(e,n);});function f(n){return n.replace(/\/+$/,"")}var k=class{constructor(){o(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,t){this.store.set(e,t);}};var J={now:()=>new Date};function F(n){return n.toISOString()}function he(){return globalThis.crypto}function fe(n){n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=[];for(let t=0;t<16;t+=1)e.push(n[t].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function ge(){let n=he();if(n?.randomUUID)return n.randomUUID();let e=new Uint8Array(16);if(n?.getRandomValues)n.getRandomValues(e);else for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);return fe(e)}var H={uuid:ge};var me=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var ye=/^(?:\$|[a-z])[a-z0-9_.]*$/;function U(n){let e=0;for(let t of n)e+=1;return e}function B(n){return me.test(n)}function ve(n){return ye.test(n)}function z(n){let e=U(n);if(e<1||e>200)throw new h("distinct_id","distinct_id must be between 1 and 200 characters")}function Q(n){let e=U(n);if(e<1||e>200)throw new h("event_name","event_name must be between 1 and 200 characters");if(!ve(n))throw new h("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var $="prodantix-js",N="0.0.1";var ke=n=>{};function Y(n){if(!n.apiKey||!B(n.apiKey))throw new y("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!n.host)throw new y("host is required (the ingest base URL)");let e=f(n.host),t=n.defaultProperties,s=n.storage??new k;return {apiKey:n.apiKey,autocapture:n.autocapture??false,clock:n.clock??J,consent:n.consent,defaultProperties:typeof t=="function"?t:()=>t??{},flagsHost:n.flagsHost?f(n.flagsHost):e,flushAt:n.flushAt??20,flushIntervalMs:n.flushIntervalMs??1e4,host:e,ids:n.ids??H,locale:n.locale,maxQueueSize:n.maxQueueSize??1e3,maxRetries:n.maxRetries??3,namespace:be(n.apiKey),onError:n.onError??ke,os:n.os,requestTimeoutMs:n.requestTimeoutMs??1e4,sdkName:n.sdkName??$,sdkVersion:n.sdkVersion??N,sessionTracking:n.sessionTracking??false,sharedStorage:n.sharedStorage??s,socketFactory:n.socketFactory,storage:s,streamFlags:n.streamFlags??false,transport:n.transport}}function be(n){return n.slice(0,16)}function W(n,e,t){Q(n.eventName),z(n.distinctId);let s={distinct_id:n.distinctId,event_id:n.eventId??t.uuid(),event_name:n.eventName,properties:n.properties??{},schema_version:1,timestamp:F(n.timestamp??e.now())};return n.context&&(s.context=n.context),n.sessionId&&(s.session_id=n.sessionId),s}var m=Symbol("absent");function Ee(n,e){if(n==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,n))return t[n];let s=e.attributes??{};return Object.prototype.hasOwnProperty.call(s,n)?s[n]:m}function g(n){return n===m?"undefined":String(n)}function X(n){return n===m?Number.NaN:Number(n)}function Z(n){return n!==m&&n!==null&&n!==""}function ee(n,e){if(!Array.isArray(e))return false;let t=g(n);return e.map(s=>String(s)).includes(t)}function R(n,e){let t=Ee(n.attribute,e),s=n.value;switch(n.op){case "is_set":return Z(t);case "is_not_set":return !Z(t);case "eq":return g(t)===g(s===void 0?m:s);case "neq":return g(t)!==g(s===void 0?m:s);case "contains":return g(t).includes(g(s===void 0?m:s));case "in":return ee(t,s);case "not_in":return Array.isArray(s)?!ee(t,s):false;case "gt":return C(t,s,(r,i)=>r>i);case "gte":return C(t,s,(r,i)=>r>=i);case "lt":return C(t,s,(r,i)=>r<i);case "lte":return C(t,s,(r,i)=>r<=i);case "in_cohort":return typeof s=="string"&&s!==""&&(e.cohorts??[]).includes(s);case "not_in_cohort":return typeof s=="string"&&s!==""&&!(e.cohorts??[]).includes(s);default:return false}}function C(n,e,t){let s=X(n),r=e===void 0?Number.NaN:X(e);return Number.isNaN(s)||Number.isNaN(r)?false:t(s,r)}function M(n,e){let t=`${n}:${e}`,s=2166136261;for(let r=0;r<t.length;r++)s^=t.charCodeAt(r),s=Math.imul(s,16777619);return (s>>>0)%100}function O(n,e){return n.targeting.length===0||n.targeting.every(t=>R(t,e))}function te(n,e){let t=M(n.key,e.distinctId),s=n.variations??[];if(s.length===0)return n.rolloutPercentage>=100||t<n.rolloutPercentage?"true":"false";let r=0;for(let i=s.length-1;i>=0;i--)if(r+=s[i].weight,t<r)return s[i].key;return s[0].key}function q(n,e,t,s){for(let r of n.prerequisites??[]){if(s.includes(r.flagKey))return false;let i=e.find(d=>d.key===r.flagKey);if(!i||!i.enabled)return false;s.push(i.key);let a=q(i,e,t,s)&&O(i,t)&&te(i,t)===r.variationKey;if(s.pop(),!a)return false}return true}function b(n,e,t){return n.enabled?q(n,e,t,[n.key])?O(n,t)?n.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:M(n.key,t.distinctId)<n.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function xe(n,e){return b(n,[],e)}function K(n,e){let t={};for(let s of n)t[s.key]=b(s,n,e).enabled;return t}function E(n,e,t){let s=n.variations??[],r=s[0];if(!r)return null;if(!n.enabled||!q(n,e,t,[n.key])||!O(n,t))return r;let i=te(n,t);return s.find(a=>a.key===i)??r}function Se(n,e){return E(n,[],e)}function Ie(n,e,t){let s=n.find(r=>r.key===e);return s?E(s,n,t)?.value??null:null}function ne(n){return n.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}function se(n){return `40${JSON.stringify(n)}`}function re(){return "3"}function ie(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let a=L(t);return {kind:"open",pingInterval:typeof a?.pingInterval=="number"?a.pingInterval:25e3,pingTimeout:typeof a?.pingTimeout=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let s=t.charAt(0),r=t.slice(1);if(s==="0")return {kind:"connected"};if(s==="1")return {kind:"disconnect"};if(s==="4"){let a=L(r);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(s!=="2")return {kind:"other"};let i=L(r);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function L(n){try{return JSON.parse(n)}catch{return null}}var Fe="/socket.io/?EIO=4&transport=websocket",Ce=250,T=class{constructor(e){this.options=e;o(this,"socket",null);o(this,"heartbeat",null);o(this,"pending",null);o(this,"lastKey","");o(this,"ready",false);o(this,"closed",false);o(this,"heartbeatWindow",45e3);o(this,"factory");o(this,"setTimer");o(this,"clearTimer");this.factory=e.socketFactory??Te,this.setTimer=e.setTimer??((t,s)=>setTimeout(t,s)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Fe}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=s=>this.receive(String(s.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat(),this.pending!==null&&this.clearTimer(this.pending),this.pending=null;let e=this.socket;this.socket=null,e?.close();}receive(e){let t=ie(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(se({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(re());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true;return}if(t.name==="flagChange"){let s=t.payload?.key;this.lastKey=typeof s=="string"?s:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},Ce));}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function Te(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}var x=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=v(e.fetch),this.host=f(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,r=p(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new l(`flags request failed with status ${a.status}`,a.status);let d=JSON.parse(await a.text());return {flags:d.flags??{},variants:d.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new l("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,s=p(),r=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let i=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!i.ok)throw new l(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),d={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(d.socketUrl=a.socketUrl),d}finally{r!==void 0&&clearTimeout(r);}}async memberships(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,r=p(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new l(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};function D(n){if(typeof n!="string")return;let e=Array.from(n).length;return e>=1&&e<=200?n:void 0}function V(n,e){return `pdx.${n}.${e}`}var oe="consent";function we(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e.identityLink;return typeof t=="boolean"?{identityLink:t}:null}catch{return null}}function _e(n,e){return we(n.getItem(V(e,oe)))}function Ae(n,e,t){let s=V(e,oe);if(typeof t.identityLink!="boolean"){n.removeItem(s);return}n.setItem(s,JSON.stringify({identityLink:t.identityLink}));}var w=class{constructor(e,t,s,r){this.storage=e;this.shared=t;this.ids=s;this.namespace=r;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");this.refresh();}refresh(){let e=D(this.shared.getItem(this.key("anonymous_id"))),t=D(this.storage.getItem(this.key("anonymous_id")));e?(this.anonymousId=e,t!==e&&this.storage.setItem(this.key("anonymous_id"),e)):t?(this.anonymousId=t,this.shared.setItem(this.key("anonymous_id"),t)):(this.anonymousId=this.ids.uuid(),this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId));let s=D(this.storage.getItem(this.key("distinct_id")));s?(this.distinctId=s,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}consent(){return _e(this.shared,this.namespace)}setConsent(e){Ae(this.shared,this.namespace,e);}identify(e){let t=!this.identified||this.distinctId!==e,s=this.storage.getItem(this.key("linked_anonymous_id")),r=t||s!==this.anonymousId;return this.distinctId=e,this.identified=true,t&&this.storage.setItem(this.key("distinct_id"),e),!r||this.consent()?.identityLink===false?{changed:t}:(this.storage.setItem(this.key("linked_anonymous_id"),this.anonymousId),{anonymousToLink:this.anonymousId,changed:t})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id")),this.storage.removeItem(this.key("linked_anonymous_id"));}key(e){return V(this.namespace,e)}};var S=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=v(e.fetch),this.host=f(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),s=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,r=await this.request(t,s,{headers:this.authHeaders(),method:"GET"});if(!r.ok)throw new l(`inbox request failed with status ${r.status}`,r.status);return JSON.parse(await r.text()).messages??[]}async markRead(e,t){let s=this.requireFetch(),r=`${this.host}/v1/messages/read`,i=await this.request(s,r,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new l(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new l("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,s){let r=p(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...s,signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var _=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;o(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let t=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,t)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};var Pe={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function $e(n){return `pdx.${n}.session`}var A=class{constructor(e,t,s,r,i=Pe){this.storage=e;this.ids=t;this.clock=s;this.namespace=r;this.options=i;}current(){return this.touch().id}startedAt(){return this.touch().startedAt}reset(){this.storage.removeItem(this.key());}touch(){let e=this.clock.now().getTime(),t=this.live(this.read(),e);if(t===void 0)return this.write({id:this.ids.uuid(),lastActivityAt:e,startedAt:e});if(e-t.lastActivityAt<=this.options.throttleMs)return t;let s=this.live(this.read(),e),r=s!==void 0&&s.id!==t.id?s:t;return this.write({...r,lastActivityAt:e})}live(e,t){if(e!==void 0&&!(t-e.lastActivityAt>this.options.idleMs||t-e.startedAt>this.options.maxMs))return e}write(e){return this.storage.setItem(this.key(),JSON.stringify(e)),e}read(){let e=this.storage.getItem(this.key());if(e)try{let t=JSON.parse(e);return typeof t.id=="string"&&typeof t.startedAt=="number"&&typeof t.lastActivityAt=="number"?{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt}:void 0}catch{return}}key(){return $e(this.namespace)}};var c={autocapture:"$autocapture",createAlias:"$create_alias",featureFlagCalled:"$feature_flag_called",group:"$group",identify:"$identify",pageview:"$pageview",screen:"$screen",set:"$set"},ae=[{emittedBy:"web",meaning:"A click anywhere on the page, with the element that was clicked. The web SDK sends it by default; autocapture: false or autocaptureOptions.clicks: false turns it off.",name:c.autocapture,properties:["$event_type","$el_tag","$el_text","$el_id","$el_classes","$el_href","$current_url","$pathname","$host","$title","$referrer"]},{emittedBy:"web",meaning:"A page shown, including every client-side navigation the History API makes: one per distinct path and query.",name:c.pageview,properties:["$current_url","$pathname","$host","$title","$referrer"]},{emittedBy:"flutter",meaning:"A named route pushed or replaced in a Flutter app, the mobile counterpart of $pageview.",name:c.screen,properties:["screen"]},{emittedBy:"every",meaning:"A person becomes known by a distinct id. The anonymous trail before it is joined to them, and any traits ride along under $set.",name:c.identify,properties:["$anon_distinct_id","$set"]},{emittedBy:"every",meaning:"A second id for the same person, so events sent under either resolve to one profile.",name:c.createAlias,properties:["alias"]},{emittedBy:"every",meaning:"The person is placed in a group such as a company or a team; group properties ride along under $set.",name:c.group,properties:["$group_type","$group_key","$set"]},{emittedBy:"every",meaning:"Person properties written without an identify: $set overwrites, $set_once fills only what is still empty.",name:c.set,properties:["$set","$set_once"]},{emittedBy:"every",meaning:"A flag was evaluated for this person, sent once per distinct answer. Experiments attribute exposure from it.",name:c.featureFlagCalled,properties:["$feature_flag","$feature_flag_response"]}],Ne=n=>n.startsWith("$"),Re=n=>ae.find(e=>e.name===n);function le(n){return n>=400&&n<500&&n!==429}var I=class{constructor(e={}){o(this,"fetch");o(this,"maxRetries");o(this,"requestTimeoutMs");o(this,"baseDelayMs");o(this,"maxDelayMs");o(this,"sleep");o(this,"random");this.fetch=v(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??G,this.random=e.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let s=JSON.stringify(e.body),r;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,s);if(a.ok)return;if(le(a.status))throw new l(`ingest rejected batch with status ${a.status}`,a.status);r=new l(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof l&&a.status!==void 0&&le(a.status))throw a;r=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new l("ingest delivery failed after retries",void 0,{cause:r})}async attempt(e,t,s){let r=p(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:s,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},method:"POST",signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var Me="queue",Oe=1e3,ce=3e4,j=n=>{let e={};return n.avatar!==void 0&&(e.$avatar=n.avatar),n.email!==void 0&&(e.$email=n.email),n.name!==void 0&&(e.$name=n.name),n.phone!==void 0&&(e.$phone=n.phone),e},P=class{constructor(e){o(this,"config");o(this,"identity");o(this,"session");o(this,"queue");o(this,"transport");o(this,"flagsClient");o(this,"messagesClient");o(this,"context");o(this,"flushTimer");o(this,"flushing",false);o(this,"cachedFlags");o(this,"cachedSnapshot");o(this,"membershipCache");o(this,"stream");o(this,"shutDown",false);o(this,"exposures",new Set);this.config=Y(e),this.identity=new w(this.config.storage,this.config.sharedStorage,this.config.ids,this.config.namespace),this.config.consent!==void 0&&this.identity.setConsent(this.config.consent),this.session=this.config.sessionTracking?new A(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new _(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new u("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new I({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new x({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new S({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}get isIdentified(){return this.identity.isIdentified()}get sessionId(){return this.session?.current()}get sessionStartedAt(){return this.session?.startedAt()}capture(e,t={}){try{this.identity.refresh();let s={...this.config.defaultProperties(),...t.properties??{}},r=W({context:this.context,distinctId:t.distinctId??this.identity.getDistinctId(),eventName:e,properties:s,sessionId:t.sessionId??this.session?.current(),timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(r);}catch(s){this.config.onError(s);}}identify(e,t={}){this.identity.refresh();let s=this.identity.identify(e),r={};s.anonymousToLink!==void 0&&(r.$anon_distinct_id=s.anonymousToLink);let i={...j(t.traits??{}),...t.set??{}};Object.keys(i).length>0&&(r.$set=i),this.capture(c.identify,{properties:r});}link(e,t,s){let r={$anon_distinct_id:t},i=j(s??{});Object.keys(i).length>0&&(r.$set=i),this.capture(c.identify,{distinctId:e,properties:r});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture(c.createAlias,{properties:{alias:e}});}group(e,t,s){let r={$group_key:t,$group_type:e};s&&(r.$set=s),this.capture(c.group,{properties:r});}setPersonProperties(e,t){let s={};e&&(s.$set=e),t&&(s.$set_once=t),this.capture(c.set,{properties:s});}setPersonTraits(e){let t=j(e);Object.keys(t).length!==0&&this.capture(c.set,{properties:{$set:t}});}async getAllFlags(){let e=this.identity.getDistinctId(),t=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:t.flags,variants:t.variants??{}},t.flags}async isFeatureEnabled(e){let s=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(s)),s}async getVariant(e){let t=await this.getAllFlags(),s=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,s?.key??String(t[e]??false)),s}async getVariantLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(de=>de.key===e),i=await this.localContext(t,s.flags),a=r?E(r,s.flags,i):null,d=r?b(r,s.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(d)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let s=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(s)||(this.exposures.add(s),this.capture(c.featureFlagCalled,{properties:{$feature_flag:e,$feature_flag_response:t}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let t=await this.flagSnapshot();return K(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(d=>d.key===e),i=await this.localContext(t,s.flags),a=r?b(r,s.flags,i).enabled:false;return this.recordExposure(e,(r?E(r,s.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let s=this.identity.getDistinctId(),r=e.cohorts;if(r===void 0&&ne(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===s&&i-this.membershipCache.fetchedAt<ce?r=this.membershipCache.cohorts:(r=await this.flagsClient.memberships(s),this.membershipCache={cohorts:r,distinctId:s,fetchedAt:i});}return {attributes:e.attributes,cohorts:r,distinctId:s,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<ce)return this.cachedSnapshot.snapshot;let t=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:t},this.maybeStream(t),t}maybeStream(e){if(!this.config.streamFlags||this.shutDown||this.stream||!e.socketUrl)return;let t=new T({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(s=>this.config.onError(s));},onClosed:s=>{this.stream=void 0,s&&this.maybeStream(e);},projectKey:this.config.apiKey,socketFactory:this.config.socketFactory});this.stream=t,t.open();}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(Oe);try{await this.transport.send({body:{events:e,sent_at:F(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(t){this.queue.requeue(e),this.persistQueue(),this.config.onError(t);}finally{this.flushing=false;}}reset(){this.session?.reset(),this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0,this.membershipCache=void 0;}async shutdown(){this.shutDown=true,this.stopTimer(),this.stream?.close(),this.stream=void 0,await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&this.queue.restore(t);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),t=e;typeof t.unref=="function"&&t.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${Me}`}};function qe(n){return new P(n)}exports.ConfigError=y;exports.FetchTransport=I;exports.FlagsClient=x;exports.MemoryStorage=k;exports.MessagesClient=S;exports.ProdantixClient=P;exports.ProdantixError=u;exports.SDK_NAME=$;exports.SDK_VERSION=N;exports.SYSTEM_EVENT=c;exports.SYSTEM_EVENTS=ae;exports.TransportError=l;exports.ValidationError=h;exports.assignVariant=Se;exports.bucket=M;exports.createClient=qe;exports.evaluateAll=K;exports.evaluateFlag=xe;exports.getVariant=Ie;exports.isSystemEventName=Ne;exports.matches=R;exports.systemEvent=Re;//# sourceMappingURL=index.cjs.map
|
|
1
|
+
'use strict';var ue=Object.defineProperty;var pe=(n,e,t)=>e in n?ue(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var o=(n,e,t)=>pe(n,typeof e!="symbol"?e+"":e,t);var u=class extends Error{constructor(t,s,r){super(s,r);o(this,"code");this.code=t,this.name="ProdantixError";}},y=class extends u{constructor(e){super("config",e),this.name="ConfigError";}},h=class extends u{constructor(t,s){super("validation",s);o(this,"field");this.field=t,this.name="ValidationError";}},l=class extends u{constructor(t,s,r){super("transport",t,r);o(this,"status");this.status=s,this.name="TransportError";}};function v(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function p(){let n=globalThis.AbortController;return n?new n:void 0}var G=n=>new Promise(e=>{setTimeout(e,n);});function f(n){return n.replace(/\/+$/,"")}var k=class{constructor(){o(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,t){this.store.set(e,t);}};var J={now:()=>new Date};function F(n){return n.toISOString()}function he(){return globalThis.crypto}function fe(n){n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=[];for(let t=0;t<16;t+=1)e.push(n[t].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function ge(){let n=he();if(n?.randomUUID)return n.randomUUID();let e=new Uint8Array(16);if(n?.getRandomValues)n.getRandomValues(e);else for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);return fe(e)}var H={uuid:ge};var me=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var ye=/^(?:\$|[a-z])[a-z0-9_.]*$/;function U(n){let e=0;for(let t of n)e+=1;return e}function B(n){return me.test(n)}function ve(n){return ye.test(n)}function z(n){let e=U(n);if(e<1||e>200)throw new h("distinct_id","distinct_id must be between 1 and 200 characters")}function Q(n){let e=U(n);if(e<1||e>200)throw new h("event_name","event_name must be between 1 and 200 characters");if(!ve(n))throw new h("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var $="prodantix-js",N="0.0.1";var ke=n=>{};function Y(n){if(!n.apiKey||!B(n.apiKey))throw new y("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!n.host)throw new y("host is required (the ingest base URL)");let e=f(n.host),t=n.defaultProperties,s=n.storage??new k;return {apiKey:n.apiKey,autocapture:n.autocapture??false,clock:n.clock??J,consent:n.consent,defaultProperties:typeof t=="function"?t:()=>t??{},flagsHost:n.flagsHost?f(n.flagsHost):e,flushAt:n.flushAt??20,flushIntervalMs:n.flushIntervalMs??1e4,host:e,ids:n.ids??H,locale:n.locale,maxQueueSize:n.maxQueueSize??1e3,maxRetries:n.maxRetries??3,namespace:be(n.apiKey),onError:n.onError??ke,os:n.os,requestTimeoutMs:n.requestTimeoutMs??1e4,sdkName:n.sdkName??$,sdkVersion:n.sdkVersion??N,sessionTracking:n.sessionTracking??false,sharedStorage:n.sharedStorage??s,socketFactory:n.socketFactory,storage:s,streamFlags:n.streamFlags??false,transport:n.transport}}function be(n){return n.slice(0,16)}function W(n,e,t){Q(n.eventName),z(n.distinctId);let s={distinct_id:n.distinctId,event_id:n.eventId??t.uuid(),event_name:n.eventName,properties:n.properties??{},schema_version:1,timestamp:F(n.timestamp??e.now())};return n.context&&(s.context=n.context),n.sessionId&&(s.session_id=n.sessionId),s}var m=Symbol("absent");function Ee(n,e){if(n==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,n))return t[n];let s=e.attributes??{};return Object.prototype.hasOwnProperty.call(s,n)?s[n]:m}function g(n){return n===m?"undefined":String(n)}function X(n){return n===m?Number.NaN:Number(n)}function Z(n){return n!==m&&n!==null&&n!==""}function ee(n,e){if(!Array.isArray(e))return false;let t=g(n);return e.map(s=>String(s)).includes(t)}function R(n,e){let t=Ee(n.attribute,e),s=n.value;switch(n.op){case "is_set":return Z(t);case "is_not_set":return !Z(t);case "eq":return g(t)===g(s===void 0?m:s);case "neq":return g(t)!==g(s===void 0?m:s);case "contains":return g(t).includes(g(s===void 0?m:s));case "in":return ee(t,s);case "not_in":return Array.isArray(s)?!ee(t,s):false;case "gt":return C(t,s,(r,i)=>r>i);case "gte":return C(t,s,(r,i)=>r>=i);case "lt":return C(t,s,(r,i)=>r<i);case "lte":return C(t,s,(r,i)=>r<=i);case "in_cohort":return typeof s=="string"&&s!==""&&(e.cohorts??[]).includes(s);case "not_in_cohort":return typeof s=="string"&&s!==""&&!(e.cohorts??[]).includes(s);default:return false}}function C(n,e,t){let s=X(n),r=e===void 0?Number.NaN:X(e);return Number.isNaN(s)||Number.isNaN(r)?false:t(s,r)}function M(n,e){let t=`${n}:${e}`,s=2166136261;for(let r=0;r<t.length;r++)s^=t.charCodeAt(r),s=Math.imul(s,16777619);return (s>>>0)%100}function O(n,e){return n.targeting.length===0||n.targeting.every(t=>R(t,e))}function te(n,e){let t=M(n.key,e.distinctId),s=n.variations??[];if(s.length===0)return n.rolloutPercentage>=100||t<n.rolloutPercentage?"true":"false";let r=0;for(let i=s.length-1;i>=0;i--)if(r+=s[i].weight,t<r)return s[i].key;return s[0].key}function q(n,e,t,s){for(let r of n.prerequisites??[]){if(s.includes(r.flagKey))return false;let i=e.find(d=>d.key===r.flagKey);if(!i||!i.enabled)return false;s.push(i.key);let a=q(i,e,t,s)&&O(i,t)&&te(i,t)===r.variationKey;if(s.pop(),!a)return false}return true}function b(n,e,t){return n.enabled?q(n,e,t,[n.key])?O(n,t)?n.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:M(n.key,t.distinctId)<n.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function xe(n,e){return b(n,[],e)}function K(n,e){let t={};for(let s of n)t[s.key]=b(s,n,e).enabled;return t}function E(n,e,t){let s=n.variations??[],r=s[0];if(!r)return null;if(!n.enabled||!q(n,e,t,[n.key])||!O(n,t))return r;let i=te(n,t);return s.find(a=>a.key===i)??r}function Se(n,e){return E(n,[],e)}function Ie(n,e,t){let s=n.find(r=>r.key===e);return s?E(s,n,t)?.value??null:null}function ne(n){return n.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}function se(n){return `40${JSON.stringify(n)}`}function re(){return "3"}function ie(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let a=L(t);return {kind:"open",pingInterval:typeof a?.pingInterval=="number"?a.pingInterval:25e3,pingTimeout:typeof a?.pingTimeout=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let s=t.charAt(0),r=t.slice(1);if(s==="0")return {kind:"connected"};if(s==="1")return {kind:"disconnect"};if(s==="4"){let a=L(r);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(s!=="2")return {kind:"other"};let i=L(r);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function L(n){try{return JSON.parse(n)}catch{return null}}var Fe="/socket.io/?EIO=4&transport=websocket",Ce=250,T=class{constructor(e){this.options=e;o(this,"socket",null);o(this,"heartbeat",null);o(this,"pending",null);o(this,"lastKey","");o(this,"ready",false);o(this,"closed",false);o(this,"heartbeatWindow",45e3);o(this,"factory");o(this,"setTimer");o(this,"clearTimer");this.factory=e.socketFactory??Te,this.setTimer=e.setTimer??((t,s)=>setTimeout(t,s)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Fe}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=s=>this.receive(String(s.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat(),this.pending!==null&&this.clearTimer(this.pending),this.pending=null;let e=this.socket;this.socket=null,e?.close();}receive(e){let t=ie(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(se({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(re());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true;return}if(t.name==="flagChange"){let s=t.payload?.key;this.lastKey=typeof s=="string"?s:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},Ce));}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function Te(n){let e=globalThis.WebSocket;if(!e)throw new l("no WebSocket");return new e(n)}var x=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=v(e.fetch),this.host=f(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,r=p(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new l(`flags request failed with status ${a.status}`,a.status);let d=JSON.parse(await a.text());return {flags:d.flags??{},variants:d.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new l("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,s=p(),r=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let i=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!i.ok)throw new l(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),d={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(d.socketUrl=a.socketUrl),d}finally{r!==void 0&&clearTimeout(r);}}async memberships(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,r=p(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new l(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};function D(n){if(typeof n!="string")return;let e=Array.from(n).length;return e>=1&&e<=200?n:void 0}function V(n,e){return `pdx.${n}.${e}`}var oe="consent";function we(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e.identityLink;return typeof t=="boolean"?{identityLink:t}:null}catch{return null}}function _e(n,e){return we(n.getItem(V(e,oe)))}function Ae(n,e,t){let s=V(e,oe);if(typeof t.identityLink!="boolean"){n.removeItem(s);return}n.setItem(s,JSON.stringify({identityLink:t.identityLink}));}var w=class{constructor(e,t,s,r){this.storage=e;this.shared=t;this.ids=s;this.namespace=r;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");this.refresh();}refresh(){let e=D(this.shared.getItem(this.key("anonymous_id"))),t=D(this.storage.getItem(this.key("anonymous_id")));e?(this.anonymousId=e,t!==e&&this.storage.setItem(this.key("anonymous_id"),e)):t?(this.anonymousId=t,this.shared.setItem(this.key("anonymous_id"),t)):(this.anonymousId=this.ids.uuid(),this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId));let s=D(this.storage.getItem(this.key("distinct_id")));s?(this.distinctId=s,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}consent(){return _e(this.shared,this.namespace)}setConsent(e){Ae(this.shared,this.namespace,e);}identify(e){let t=!this.identified||this.distinctId!==e,s=this.storage.getItem(this.key("linked_anonymous_id")),r=t||s!==this.anonymousId;return this.distinctId=e,this.identified=true,t&&this.storage.setItem(this.key("distinct_id"),e),!r||this.consent()?.identityLink===false?{changed:t}:(this.storage.setItem(this.key("linked_anonymous_id"),this.anonymousId),{anonymousToLink:this.anonymousId,changed:t})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id")),this.storage.removeItem(this.key("linked_anonymous_id"));}key(e){return V(this.namespace,e)}};var S=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=v(e.fetch),this.host=f(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),s=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,r=await this.request(t,s,{headers:this.authHeaders(),method:"GET"});if(!r.ok)throw new l(`inbox request failed with status ${r.status}`,r.status);return JSON.parse(await r.text()).messages??[]}async markRead(e,t){let s=this.requireFetch(),r=`${this.host}/v1/messages/read`,i=await this.request(s,r,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new l(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new l("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,s){let r=p(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...s,signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var _=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;o(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let t=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,t)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};var Pe={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function $e(n){return `pdx.${n}.session`}var A=class{constructor(e,t,s,r,i=Pe){this.storage=e;this.ids=t;this.clock=s;this.namespace=r;this.options=i;}current(){return this.touch().id}startedAt(){return this.touch().startedAt}reset(){this.storage.removeItem(this.key());}touch(){let e=this.clock.now().getTime(),t=this.live(this.read(),e);if(t===void 0)return this.write({id:this.ids.uuid(),lastActivityAt:e,startedAt:e});if(e-t.lastActivityAt<=this.options.throttleMs)return t;let s=this.live(this.read(),e),r=s!==void 0&&s.id!==t.id?s:t;return this.write({...r,lastActivityAt:e})}live(e,t){if(e!==void 0&&!(t-e.lastActivityAt>this.options.idleMs||t-e.startedAt>this.options.maxMs))return e}write(e){return this.storage.setItem(this.key(),JSON.stringify(e)),e}read(){let e=this.storage.getItem(this.key());if(e)try{let t=JSON.parse(e);return typeof t.id=="string"&&typeof t.startedAt=="number"&&typeof t.lastActivityAt=="number"?{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt}:void 0}catch{return}}key(){return $e(this.namespace)}};var c={autocapture:"$autocapture",createAlias:"$create_alias",featureFlagCalled:"$feature_flag_called",group:"$group",identify:"$identify",pageview:"$pageview",screen:"$screen",set:"$set"},ae=[{emittedBy:"web",meaning:"A click anywhere on the page, with the element that was clicked. The web SDK sends it by default; autocapture: false or autocaptureOptions.clicks: false turns it off.",name:c.autocapture,properties:["$event_type","$el_tag","$el_text","$el_id","$el_classes","$el_href","$current_url","$pathname","$host","$title","$referrer"]},{emittedBy:"web",meaning:"A page shown, including every client-side navigation the History API makes: one per distinct path and query.",name:c.pageview,properties:["$current_url","$pathname","$host","$title","$referrer"]},{emittedBy:"flutter",meaning:"A named route pushed or replaced in a Flutter app, the mobile counterpart of $pageview.",name:c.screen,properties:["screen"]},{emittedBy:"every",meaning:"A person becomes known by a distinct id. The anonymous trail before it is joined to them, and any traits ride along under $set.",name:c.identify,properties:["$anon_distinct_id","$set"]},{emittedBy:"every",meaning:"A second id for the same person, so events sent under either resolve to one profile.",name:c.createAlias,properties:["alias"]},{emittedBy:"every",meaning:"The person is placed in a group such as a company or a team; group properties ride along under $set.",name:c.group,properties:["$group_type","$group_key","$set"]},{emittedBy:"every",meaning:"Person properties written without an identify: $set overwrites, $set_once fills only what is still empty.",name:c.set,properties:["$set","$set_once"]},{emittedBy:"every",meaning:"A flag was evaluated for this person, sent once per distinct answer. Experiments attribute exposure from it.",name:c.featureFlagCalled,properties:["$feature_flag","$feature_flag_response"]}],Ne=n=>n.startsWith("$"),Re=n=>ae.find(e=>e.name===n);function le(n){return n>=400&&n<500&&n!==429}var I=class{constructor(e={}){o(this,"fetch");o(this,"maxRetries");o(this,"requestTimeoutMs");o(this,"baseDelayMs");o(this,"maxDelayMs");o(this,"sleep");o(this,"random");this.fetch=v(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??G,this.random=e.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let s=JSON.stringify(e.body),r;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,s);if(a.ok)return;if(le(a.status))throw new l(`ingest rejected batch with status ${a.status}`,a.status);r=new l(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof l&&a.status!==void 0&&le(a.status))throw a;r=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new l("ingest delivery failed after retries",void 0,{cause:r})}async attempt(e,t,s){let r=p(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:s,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},method:"POST",signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var Me="queue",Oe=1e3,ce=3e4,j=n=>{let e={};return n.avatar!==void 0&&(e.$avatar=n.avatar),n.email!==void 0&&(e.$email=n.email),n.name!==void 0&&(e.$name=n.name),n.phone!==void 0&&(e.$phone=n.phone),e},P=class{constructor(e){o(this,"config");o(this,"identity");o(this,"session");o(this,"queue");o(this,"transport");o(this,"flagsClient");o(this,"messagesClient");o(this,"context");o(this,"flushTimer");o(this,"flushing",false);o(this,"cachedFlags");o(this,"cachedSnapshot");o(this,"membershipCache");o(this,"stream");o(this,"shutDown",false);o(this,"exposures",new Set);this.config=Y(e),this.identity=new w(this.config.storage,this.config.sharedStorage,this.config.ids,this.config.namespace),this.config.consent!==void 0&&this.identity.setConsent(this.config.consent),this.session=this.config.sessionTracking?new A(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new _(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new u("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new I({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new x({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new S({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}get isIdentified(){return this.identity.isIdentified()}get sessionId(){return this.session?.current()}get sessionStartedAt(){return this.session?.startedAt()}capture(e,t={}){try{this.identity.refresh();let s={...this.config.defaultProperties(),...t.properties??{}},r=W({context:this.context,distinctId:t.distinctId??this.identity.getDistinctId(),eventName:e,properties:s,sessionId:t.sessionId??this.session?.current(),timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(r);}catch(s){this.config.onError(s);}}identify(e,t={}){this.identity.refresh();let s=this.identity.identify(e),r={};s.anonymousToLink!==void 0&&(r.$anon_distinct_id=s.anonymousToLink);let i={...j(t.traits??{}),...t.set??{}};Object.keys(i).length>0&&(r.$set=i),this.capture(c.identify,{properties:r});}link(e,t,s){let r={$anon_distinct_id:t},i=j(s??{});Object.keys(i).length>0&&(r.$set=i),this.capture(c.identify,{distinctId:e,properties:r});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture(c.createAlias,{properties:{alias:e}});}group(e,t,s){let r={$group_key:t,$group_type:e};s&&(r.$set=s),this.capture(c.group,{properties:r});}setPersonProperties(e,t){let s={};e&&(s.$set=e),t&&(s.$set_once=t),this.capture(c.set,{properties:s});}setPersonTraits(e){let t=j(e);Object.keys(t).length!==0&&this.capture(c.set,{properties:{$set:t}});}async getAllFlags(){let e=this.identity.getDistinctId(),t=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:t.flags,variants:t.variants??{}},t.flags}async isFeatureEnabled(e){let s=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(s)),s}async getVariant(e){let t=await this.getAllFlags(),s=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,s?.key??String(t[e]??false)),s}async getVariantLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(de=>de.key===e),i=await this.localContext(t,s.flags),a=r?E(r,s.flags,i):null,d=r?b(r,s.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(d)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let s=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(s)||(this.exposures.add(s),this.capture(c.featureFlagCalled,{properties:{$feature_flag:e,$feature_flag_response:t}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let t=await this.flagSnapshot();return K(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(d=>d.key===e),i=await this.localContext(t,s.flags),a=r?b(r,s.flags,i).enabled:false;return this.recordExposure(e,(r?E(r,s.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let s=this.identity.getDistinctId(),r=e.cohorts;if(r===void 0&&ne(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===s&&i-this.membershipCache.fetchedAt<ce?r=this.membershipCache.cohorts:(r=await this.flagsClient.memberships(s),this.membershipCache={cohorts:r,distinctId:s,fetchedAt:i});}return {attributes:e.attributes,cohorts:r,distinctId:s,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<ce)return this.cachedSnapshot.snapshot;let t=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:t},this.maybeStream(t),t}maybeStream(e){if(!this.config.streamFlags||this.shutDown||this.stream||!e.socketUrl)return;let t=new T({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(s=>this.config.onError(s));},onClosed:s=>{this.stream=void 0,s&&this.maybeStream(e);},projectKey:this.config.apiKey,socketFactory:this.config.socketFactory});this.stream=t,t.open();}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(Oe);try{await this.transport.send({body:{events:e,sent_at:F(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(t){this.queue.requeue(e),this.persistQueue(),this.config.onError(t);}finally{this.flushing=false;}}reset(){this.session?.reset(),this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0,this.membershipCache=void 0;}async shutdown(){this.shutDown=true,this.stopTimer(),this.stream?.close(),this.stream=void 0,await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&this.queue.restore(t);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),t=e;typeof t.unref=="function"&&t.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${Me}`}};function qe(n){return new P(n)}exports.ConfigError=y;exports.FetchTransport=I;exports.FlagsClient=x;exports.MemoryStorage=k;exports.MessagesClient=S;exports.ProdantixClient=P;exports.ProdantixError=u;exports.SDK_NAME=$;exports.SDK_VERSION=N;exports.SYSTEM_EVENT=c;exports.SYSTEM_EVENTS=ae;exports.TransportError=l;exports.ValidationError=h;exports.assignVariant=Se;exports.bucket=M;exports.createClient=qe;exports.evaluateAll=K;exports.evaluateFlag=xe;exports.getVariant=Ie;exports.isSystemEventName=Ne;exports.matches=R;exports.systemEvent=Re;//# sourceMappingURL=index.cjs.map
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{
|
|
1
|
+
export{x as FetchTransport,o as FlagsClient,a as MemoryStorage,r as MessagesClient,y as ProdantixClient,f as SDK_NAME,g as SDK_VERSION,t as SYSTEM_EVENT,u as SYSTEM_EVENTS,m as assignVariant,j as bucket,z as createClient,l as evaluateAll,k as evaluateFlag,n as getVariant,v as isSystemEventName,i as matches,w as systemEvent}from'./chunk-4RLPQZ5L.js';import'./chunk-V77KYPOF.js';export{b as ConfigError,a as ProdantixError,d as TransportError,c as ValidationError}from'./chunk-ODN4ZELX.js';import'./chunk-5XGN7UAV.js';//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/messenger.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';function
|
|
1
|
+
'use strict';var d=Object.defineProperty;var h=(e,t,r)=>t in e?d(e,t,{enumerable:true,configurable:true,writable:true,value:r}):e[t]=r;var c=(e,t,r)=>h(e,typeof t!="symbol"?t+"":t,r);var l=class extends Error{constructor(r,n,o){super(n,o);c(this,"code");this.code=r,this.name="ProdantixError";}};var i=class extends l{constructor(r,n,o){super("transport",r,o);c(this,"status");this.status=n,this.name="TransportError";}};function g(e){if(e)return e;let t=globalThis.fetch;if(typeof t=="function")return t.bind(globalThis)}function u(e){return e.replace(/\/+$/,"")}var p="prodantix.messenger.config",S=e=>{let t=e.navigator?.languages;return Array.isArray(t)&&t.length>0?t.join(","):e.navigator?.language||e.document?.documentElement?.lang||void 0},f=(e,t)=>`${p}:${e}:${t??""}`;function k(e,t,r){let n=e?.get(f(t,r));if(!n)return null;try{let o=JSON.parse(n);return o?.apiKey===t?o.config:null}catch{return null}}async function v(e){let t=g(e.fetchImpl);if(!t)return e.onError?.(new i("no fetch available for the prodantix messenger")),null;let r=u(e.host),n=f(e.apiKey,e.locale),o=e.locale?`?locale=${encodeURIComponent(e.locale)}`:"";try{let s=await t(`${r}/v1/messenger/config${o}`,{headers:{authorization:`Bearer ${e.apiKey}`},method:"GET"});if(!s.ok)return e.onError?.(new i(`prodantix messenger config: ${s.status}`,s.status)),null;let a=JSON.parse(await s.text());return a.enabled?(e.storage?.set(n,JSON.stringify({apiKey:e.apiKey,config:a})),a):(e.storage?.remove(n),a)}catch(s){return e.onError?.(s),null}}exports.MESSENGER_CACHE_KEY=p;exports.cacheKeyFor=f;exports.cachedMessengerConfig=k;exports.fetchMessengerConfig=v;exports.localeCandidates=S;//# sourceMappingURL=messenger.cjs.map
|
|
2
2
|
//# sourceMappingURL=messenger.cjs.map
|
package/dist/messenger.iife.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
(function(){'use strict';var se=Object.defineProperty;var le=(n,e,t)=>e in n?se(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var m=(n,e,t)=>le(n,typeof e!="symbol"?e+"":e,t);function L(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function P(n){return n.replace(/\/+$/,"")}var K="X-Prodantix-Conversation-Token",H="prodantix.chat.handle";function ce(){let n=globalThis.localStorage;if(n)return {get:e=>n.getItem(e),remove:e=>n.removeItem(e),set:(e,t)=>n.setItem(e,t)}}var N=class{constructor(e){this.options=e;m(this,"fetchImpl");m(this,"fileFetchImpl");m(this,"host");m(this,"storage");m(this,"handle");m(this,"identity",null);var t,r;this.fetchImpl=L(e.fetchImpl),this.fileFetchImpl=(t=e.fileFetchImpl)!=null?t:((i,a)=>fetch(i,a)),this.host=P(e.host),this.storage=(r=e.storage)!=null?r:ce(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}avatarUrl(e){return e.startsWith("/")?`${this.host}${e}?api_key=${encodeURIComponent(this.options.apiKey)}`:e}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){var r,i,a;if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:(r=this.identity)==null?void 0:r.userHash,userId:(i=this.identity)==null?void 0:i.userId}});return !(t!=null&&t.conversationId)||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},(a=this.storage)==null||a.set(H,JSON.stringify(this.handle)),true)}async send(e,t,r){var o;if(!await this.ensureThread())return null;let i=this.handle;if(!i)return null;let a=await this.request("POST",`/v1/conversations/${encodeURIComponent(i.conversationId)}/turns`,{body:{attachmentIds:r,body:e,pageContext:t},token:i.token});return (o=a==null?void 0:a.turn)!=null?o:null}async upload(e){if(!await this.ensureThread())return null;let t=this.handle;return t?this.fileRequest("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/attachments?name=${encodeURIComponent(e.name)}`,t.token,async r=>JSON.parse(await r.text()),e):null}async file(e){let t=this.handle;return t?this.fileRequest("GET",e,t.token,r=>r.blob()):null}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){var t,r;let e=(t=this.storage)==null?void 0:t.get(H);if(!e)return null;try{let i=JSON.parse(e);if(typeof i.conversationId=="string"&&typeof i.token=="string")return {conversationId:i.conversationId,token:i.token}}catch(i){}return (r=this.storage)==null||r.remove(H),null}async fileRequest(e,t,r,i,a){var s,d,p,c;let o={authorization:`Bearer ${this.options.apiKey}`,[K]:r};a&&(o["content-type"]=a.type||"application/octet-stream");try{let l=await this.fileFetchImpl(`${this.host}${t}`,{body:a,headers:o,method:e});if(l.ok)return await i(l);(d=(s=this.options).onError)==null||d.call(s,new Error(`prodantix chat ${t}: ${l.status}`));}catch(l){(c=(p=this.options).onError)==null||c.call(p,l);}return null}async request(e,t,r={}){var o,s,d,p,c,l;let i=this.fetchImpl;if(!i)return (s=(o=this.options).onError)==null||s.call(o,new Error("no fetch available for prodantix chat")),null;let a={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};r.token&&(a[K]=r.token);try{let h=await i(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:a,method:e}),g=await h.text();return h.ok?g?JSON.parse(g):{}:((p=(d=this.options).onError)==null||p.call(d,new Error(`prodantix chat ${t}: ${h.status}`)),null)}catch(h){return (l=(c=this.options).onError)==null||l.call(c,h),null}}};var de={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function _(n,e){var s,d,p,c,l,h;let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:n.timezone,weekday:"short"}).formatToParts(e),r=de[(d=(s=t.find(g=>g.type==="weekday"))==null?void 0:s.value)!=null?d:""];if(!r)return false;let i=(c=(p=t.find(g=>g.type==="hour"))==null?void 0:p.value)!=null?c:"",a=(h=(l=t.find(g=>g.type==="minute"))==null?void 0:l.value)!=null?h:"",o=`${i}:${a}`;return n.windows.some(g=>g.days.includes(r)&&g.open<=o&&o<g.close)}var k={bubbleFill:"filled",bubbleShape:"tailed",composerShape:"round",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"standard",stampContent:"time",stampPlacement:"none"},pe=["quiet","standard"],ue=["round","square"],he=["rounded","tailed"],me=["filled","outlined"],ge=["circle","pill","squircle"],fe=["filled","outlined"],be=["avatar","glyph","team_faces"],xe=["large","medium","small"],ye=["above","hidden","inline"],ve=["beside_name","none","under_turn"],Se=["time","time_and_latency"],C=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t,G=(n,e)=>typeof n=="boolean"?n:e,ke={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},Ce={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},Ee={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]},we={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},Te={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function F(n){var g,v,S,f,b,u,x,E,y,w,z,B,D;let e=typeof n=="object"&&n!==null?n:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,r=t===void 0?void 0:ke[t],i=typeof e.namePlacement=="string"?e.namePlacement:void 0,a=i===void 0?void 0:Ce[i],o=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,s=o===void 0?void 0:Ee[o],d=typeof e.skin=="string"?e.skin:void 0,p=d===void 0?void 0:we[d],c=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,l=c===void 0?void 0:Te[c],h={bubbleFill:C(e.bubbleFill,me,(g=l==null?void 0:l[1])!=null?g:k.bubbleFill),bubbleShape:C(e.bubbleShape,he,(v=l==null?void 0:l[0])!=null?v:k.bubbleShape),composerShape:C(e.composerShape,ue,(S=p==null?void 0:p[1])!=null?S:k.composerShape),dayDividers:G(e.dayDividers,(f=s==null?void 0:s[0])!=null?f:k.dayDividers),launcherContent:C(e.launcherContent,be,(b=r==null?void 0:r[2])!=null?b:k.launcherContent),launcherFill:C(e.launcherFill,fe,(u=r==null?void 0:r[1])!=null?u:k.launcherFill),launcherShape:C(e.launcherShape,ge,(x=r==null?void 0:r[0])!=null?x:k.launcherShape),launcherSize:C(e.launcherSize,xe,(E=r==null?void 0:r[3])!=null?E:k.launcherSize),nameAvatar:G(e.nameAvatar,(y=a==null?void 0:a[1])!=null?y:k.nameAvatar),namePlacement:C(e.namePlacement,ye,(w=a==null?void 0:a[0])!=null?w:k.namePlacement),skin:C(e.skin,pe,(z=p==null?void 0:p[0])!=null?z:k.skin),stampContent:C(e.stampContent,Se,(B=s==null?void 0:s[2])!=null?B:k.stampContent),stampPlacement:C(e.stampPlacement,ve,(D=s==null?void 0:s[1])!=null?D:k.stampPlacement)};return h.stampPlacement==="beside_name"&&h.namePlacement==="hidden"&&(h.stampPlacement="under_turn"),h}function q(n){var r,i,a,o;let e=n.split(/\s+/).filter(s=>s.length>0);return (e.length>1?`${(r=e[0])==null?void 0:r.slice(0,1)}${(i=e[1])==null?void 0:i.slice(0,1)}`:(o=(a=e[0])==null?void 0:a.slice(0,2))!=null?o:"").toUpperCase()}var Ae="M20 11.6a7.4 7.4 0 0 1-7.4 7.4H8.2L4 21.8l1-4.1A7.4 7.4 0 1 1 20 11.6Z",Le={large:66,medium:56,small:46},Pe={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},Ne={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},_e={avatar:"",glyph:".launcher svg{width:calc(var(--fab-size) * 0.375);height:calc(var(--fab-size) * 0.375);}",team_faces:".launcher .faces{display:flex;}.launcher .faces .av{box-shadow:0 0 0 2px var(--paper);}.launcher .faces .av+.av{margin-left:-10px;}"},Fe=".launcher .live{width:10px;height:10px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}.launcher.closed .live{display:none}",Ie={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},Me={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},He={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},$e={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function j(n,e,t,r){return `.launcher{--fab-size:${Le[r]}px;${Pe[n]}${Ne[e]}}${_e[t]}${Fe}${Ie[n]}${Me[e]}${He[n]}${$e[n]}`}function W(n,e,t,r=i=>i){let i=document.createDocumentFragment();if(n==="glyph"||t.length===0){let a=document.createElement("span");return a.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${Ae}"/></svg>`,i.append(...a.childNodes,$()),i}return n==="avatar"?(i.append(Y(t[0],e,r),$()),i):(i.append(R(t,e,r),$()),i)}function R(n,e,t=r=>r){let r=document.createElement("span");r.className="faces";for(let i of n.slice(0,2))r.append(Y(i,e,t));return r}function Y(n,e,t){let r=document.createElement("span");if(r.className="av",r.setAttribute("aria-hidden","true"),n&&(r.style.background=n.tone),n!=null&&n.avatarUrl){let i=document.createElement("img");return i.alt="",i.src=t(n.avatarUrl),r.append(i),r}return r.textContent=n?n.initials:e.agentLabel.slice(0,2).toUpperCase(),r}function $(){let n=document.createElement("span");return n.className="live",n.setAttribute("aria-hidden","true"),n}var Re={agentLabel:"Agent",aiLabel:"AI",attachLabel:"Attach a file",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",fileRefusal:(n,e)=>`That file is ${n}. Send a PNG, JPEG, WebP, GIF or PDF up to ${e}.`,inputPlaceholder:"Type a message",launcherLabel:"Chat with us",removeFileLabel:"Remove file",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel:n=>{let e=new Date(n);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:n=>`${n} unread`},T={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...k},Oe={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .faces,.header .status{display:none}.header .close{top:6px}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},Ue={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},ze={rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},Be={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},De={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},Ke=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",Ge='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',qe={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},je=".lat{font-size:11px;opacity:.7;margin-left:6px}",We=".att{display:block;width:180px;margin-bottom:6px;border-radius:8px;overflow:hidden}.att img{display:block;width:100%}.pdfc{display:inline-flex;gap:8px;align-items:center;margin-bottom:6px;padding:6px 8px;border-radius:8px;background:color-mix(in srgb,currentColor 16%,transparent);color:inherit;font-size:12.5px;text-decoration:none;overflow-wrap:anywhere}.pdfc b,.file b{flex:none;display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:4px;font-size:9px;letter-spacing:.04em;background:color-mix(in srgb,currentColor 22%,transparent)}.att:last-child,.pdfc:last-child{margin-bottom:0}";function Ye(n){let e=n==="round"?14:12;return `.field{position:relative;flex:1;min-width:0;display:flex}.composer .field input{padding-left:${e+26}px}.composer button.clip{position:absolute;top:50%;left:${e-5}px;right:auto;width:28px;min-width:28px;height:28px;padding:0;border-radius:7px;background:none;color:var(--ink-2);transform:translateY(-50%)}.composer button.clip:hover{background:color-mix(in srgb,currentColor 14%,transparent)}.clip svg{display:block;width:18px;height:18px}.file{display:inline-flex;gap:8px;align-items:center;align-self:flex-start;max-width:calc(100% - 20px);margin:0 10px 8px;padding:6px 10px 6px 6px;font-size:12.5px;color:var(--ink);border:1px solid var(--hairline);border-radius:8px}.file .th{flex:none;width:28px;height:28px;border-radius:4px;object-fit:cover}.file .name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.file .sz,.file .x{flex:none;color:var(--ink-3)}.file .x{margin-left:4px;padding:0;border:0;background:none;font:inherit;font-size:16px;line-height:1;cursor:pointer}.ferr{margin:0 10px 6px;font-size:12px;color:oklch(60% 0.2 27)}`}function O(n){return n<999500?`${Math.max(1,Math.round(n/1e3))} KB`:`${(n/1e6).toFixed(1)} MB`}var J=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
1
|
+
(function(){'use strict';var de=Object.defineProperty;var pe=(n,e,t)=>e in n?de(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var m=(n,e,t)=>pe(n,typeof e!="symbol"?e+"":e,t);var P=class extends Error{constructor(t,r,i){super(r,i);m(this,"code");this.code=t,this.name="ProdantixError";}},N=class extends P{constructor(e){super("config",e),this.name="ConfigError";}};var C=class extends P{constructor(t,r,i){super("transport",t,i);m(this,"status");this.status=r,this.name="TransportError";}};function _(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function F(n){return n.replace(/\/+$/,"")}var j="X-Prodantix-Conversation-Token",O="prodantix.chat.handle";function ue(){let n=globalThis.localStorage;if(n)return {get:e=>n.getItem(e),remove:e=>n.removeItem(e),set:(e,t)=>n.setItem(e,t)}}var I=class{constructor(e){this.options=e;m(this,"fetchImpl");m(this,"fileFetchImpl");m(this,"host");m(this,"storage");m(this,"handle");m(this,"identity",null);var t,r;this.fetchImpl=_(e.fetchImpl),this.fileFetchImpl=(t=e.fileFetchImpl)!=null?t:((i,o)=>fetch(i,o)),this.host=F(e.host),this.storage=(r=e.storage)!=null?r:ue(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}avatarUrl(e){return e.startsWith("/")?`${this.host}${e}?api_key=${encodeURIComponent(this.options.apiKey)}`:e}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){var r,i,o;if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:(r=this.identity)==null?void 0:r.userHash,userId:(i=this.identity)==null?void 0:i.userId}});return !(t!=null&&t.conversationId)||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},(o=this.storage)==null||o.set(O,JSON.stringify(this.handle)),true)}async send(e,t,r){var a;if(!await this.ensureThread())return null;let i=this.handle;if(!i)return null;let o=await this.request("POST",`/v1/conversations/${encodeURIComponent(i.conversationId)}/turns`,{body:{attachmentIds:r,body:e,pageContext:t},token:i.token});return (a=o==null?void 0:o.turn)!=null?a:null}async upload(e){if(!await this.ensureThread())return null;let t=this.handle;return t?this.fileRequest("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/attachments?name=${encodeURIComponent(e.name)}`,t.token,async r=>JSON.parse(await r.text()),e):null}async file(e){let t=this.handle;return t?this.fileRequest("GET",e,t.token,r=>r.blob()):null}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){var t,r,i,o;let e=(t=this.storage)==null?void 0:t.get(O);if(!e)return null;try{let a=JSON.parse(e);if(typeof a.conversationId=="string"&&typeof a.token=="string")return {conversationId:a.conversationId,token:a.token}}catch(a){(i=(r=this.options).onError)==null||i.call(r,a);}return (o=this.storage)==null||o.remove(O),null}async fileRequest(e,t,r,i,o){var s,d,p,c;let a={authorization:`Bearer ${this.options.apiKey}`,[j]:r};o&&(a["content-type"]=o.type||"application/octet-stream");try{let l=await this.fileFetchImpl(`${this.host}${t}`,{body:o,headers:a,method:e});if(l.ok)return await i(l);(d=(s=this.options).onError)==null||d.call(s,new C(`prodantix chat ${t}: ${l.status}`,l.status));}catch(l){(c=(p=this.options).onError)==null||c.call(p,l);}return null}async request(e,t,r={}){var a,s,d,p,c,l;let i=this.fetchImpl;if(!i)return (s=(a=this.options).onError)==null||s.call(a,new C("no fetch available for prodantix chat")),null;let o={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};r.token&&(o[j]=r.token);try{let u=await i(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:o,method:e}),g=await u.text();return u.ok?g?JSON.parse(g):{}:((p=(d=this.options).onError)==null||p.call(d,new C(`prodantix chat ${t}: ${u.status}`,u.status)),null)}catch(u){return (l=(c=this.options).onError)==null||l.call(c,u),null}}};var he={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function M(n,e){var s,d,p,c,l,u;let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:n.timezone,weekday:"short"}).formatToParts(e),r=he[(d=(s=t.find(g=>g.type==="weekday"))==null?void 0:s.value)!=null?d:""];if(!r)return false;let i=(c=(p=t.find(g=>g.type==="hour"))==null?void 0:p.value)!=null?c:"",o=(u=(l=t.find(g=>g.type==="minute"))==null?void 0:l.value)!=null?u:"",a=`${i}:${o}`;return n.windows.some(g=>g.days.includes(r)&&g.open<=a&&a<g.close)}var k={bubbleFill:"filled",bubbleShape:"tailed",composerShape:"round",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"standard",stampContent:"time",stampPlacement:"none"},me=["quiet","standard"],ge=["round","square"],fe=["rounded","tailed"],be=["filled","outlined"],xe=["circle","pill","squircle"],ye=["filled","outlined"],ve=["avatar","glyph","team_faces"],Se=["large","medium","small"],ke=["above","hidden","inline"],Ce=["beside_name","none","under_turn"],Ee=["time","time_and_latency"],E=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t,W=(n,e)=>typeof n=="boolean"?n:e,we={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},Te={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},Ae={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]},Le={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},Pe={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function H(n){var g,v,S,f,b,h,x,w,y,T,K,G,q;let e=typeof n=="object"&&n!==null?n:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,r=t===void 0?void 0:we[t],i=typeof e.namePlacement=="string"?e.namePlacement:void 0,o=i===void 0?void 0:Te[i],a=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,s=a===void 0?void 0:Ae[a],d=typeof e.skin=="string"?e.skin:void 0,p=d===void 0?void 0:Le[d],c=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,l=c===void 0?void 0:Pe[c],u={bubbleFill:E(e.bubbleFill,be,(g=l==null?void 0:l[1])!=null?g:k.bubbleFill),bubbleShape:E(e.bubbleShape,fe,(v=l==null?void 0:l[0])!=null?v:k.bubbleShape),composerShape:E(e.composerShape,ge,(S=p==null?void 0:p[1])!=null?S:k.composerShape),dayDividers:W(e.dayDividers,(f=s==null?void 0:s[0])!=null?f:k.dayDividers),launcherContent:E(e.launcherContent,ve,(b=r==null?void 0:r[2])!=null?b:k.launcherContent),launcherFill:E(e.launcherFill,ye,(h=r==null?void 0:r[1])!=null?h:k.launcherFill),launcherShape:E(e.launcherShape,xe,(x=r==null?void 0:r[0])!=null?x:k.launcherShape),launcherSize:E(e.launcherSize,Se,(w=r==null?void 0:r[3])!=null?w:k.launcherSize),nameAvatar:W(e.nameAvatar,(y=o==null?void 0:o[1])!=null?y:k.nameAvatar),namePlacement:E(e.namePlacement,ke,(T=o==null?void 0:o[0])!=null?T:k.namePlacement),skin:E(e.skin,me,(K=p==null?void 0:p[0])!=null?K:k.skin),stampContent:E(e.stampContent,Ee,(G=s==null?void 0:s[2])!=null?G:k.stampContent),stampPlacement:E(e.stampPlacement,Ce,(q=s==null?void 0:s[1])!=null?q:k.stampPlacement)};return u.stampPlacement==="beside_name"&&u.namePlacement==="hidden"&&(u.stampPlacement="under_turn"),u}function Y(n){var r,i,o,a;let e=n.split(/\s+/).filter(s=>s.length>0);return (e.length>1?`${(r=e[0])==null?void 0:r.slice(0,1)}${(i=e[1])==null?void 0:i.slice(0,1)}`:(a=(o=e[0])==null?void 0:o.slice(0,2))!=null?a:"").toUpperCase()}var Ne="M20 11.6a7.4 7.4 0 0 1-7.4 7.4H8.2L4 21.8l1-4.1A7.4 7.4 0 1 1 20 11.6Z",_e={large:66,medium:56,small:46},Fe={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},Ie={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},Me={avatar:"",glyph:".launcher svg{width:calc(var(--fab-size) * 0.375);height:calc(var(--fab-size) * 0.375);}",team_faces:".launcher .faces{display:flex;}.launcher .faces .av{box-shadow:0 0 0 2px var(--paper);}.launcher .faces .av+.av{margin-left:-10px;}"},He=".launcher .live{width:10px;height:10px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}.launcher.closed .live{display:none}",$e={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},Re={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},Oe={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},Ue={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function J(n,e,t,r){return `.launcher{--fab-size:${_e[r]}px;${Fe[n]}${Ie[e]}}${Me[t]}${He}${$e[n]}${Re[e]}${Oe[n]}${Ue[n]}`}function X(n,e,t,r=i=>i){let i=document.createDocumentFragment();if(n==="glyph"||t.length===0){let o=document.createElement("span");return o.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${Ne}"/></svg>`,i.append(...o.childNodes,U()),i}return n==="avatar"?(i.append(V(t[0],e,r),U()),i):(i.append(z(t,e,r),U()),i)}function z(n,e,t=r=>r){let r=document.createElement("span");r.className="faces";for(let i of n.slice(0,2))r.append(V(i,e,t));return r}function V(n,e,t){let r=document.createElement("span");if(r.className="av",r.setAttribute("aria-hidden","true"),n&&(r.style.background=n.tone),n!=null&&n.avatarUrl){let i=document.createElement("img");return i.alt="",i.src=t(n.avatarUrl),r.append(i),r}return r.textContent=n?n.initials:e.agentLabel.slice(0,2).toUpperCase(),r}function U(){let n=document.createElement("span");return n.className="live",n.setAttribute("aria-hidden","true"),n}var ze={agentLabel:"Agent",aiLabel:"AI",attachLabel:"Attach a file",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",fileRefusal:(n,e)=>`That file is ${n}. Send a PNG, JPEG, WebP, GIF or PDF up to ${e}.`,inputPlaceholder:"Type a message",launcherLabel:"Chat with us",removeFileLabel:"Remove file",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel:n=>{let e=new Date(n);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:n=>`${n} unread`},A={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...k},Be={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .faces,.header .status{display:none}.header .close{top:6px}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},De={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},Ke={rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},Ge={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},qe={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},je=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",We='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',Ye={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},Je=".lat{font-size:11px;opacity:.7;margin-left:6px}",Xe=".att{display:block;width:180px;margin-bottom:6px;border-radius:8px;overflow:hidden}.att img{display:block;width:100%}.pdfc{display:inline-flex;gap:8px;align-items:center;margin-bottom:6px;padding:6px 8px;border-radius:8px;background:color-mix(in srgb,currentColor 16%,transparent);color:inherit;font-size:12.5px;text-decoration:none;overflow-wrap:anywhere}.pdfc b,.file b{flex:none;display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:4px;font-size:9px;letter-spacing:.04em;background:color-mix(in srgb,currentColor 22%,transparent)}.att:last-child,.pdfc:last-child{margin-bottom:0}";function Ve(n){let e=n==="round"?14:12;return `.field{position:relative;flex:1;min-width:0;display:flex}.composer .field input{padding-left:${e+26}px}.composer button.clip{position:absolute;top:50%;left:${e-5}px;right:auto;width:28px;min-width:28px;height:28px;padding:0;border-radius:7px;background:none;color:var(--ink-2);transform:translateY(-50%)}.composer button.clip:hover{background:color-mix(in srgb,currentColor 14%,transparent)}.clip svg{display:block;width:18px;height:18px}.file{display:inline-flex;gap:8px;align-items:center;align-self:flex-start;max-width:calc(100% - 20px);margin:0 10px 8px;padding:6px 10px 6px 6px;font-size:12.5px;color:var(--ink);border:1px solid var(--hairline);border-radius:8px}.file .th{flex:none;width:28px;height:28px;border-radius:4px;object-fit:cover}.file .name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.file .sz,.file .x{flex:none;color:var(--ink-3)}.file .x{margin-left:4px;padding:0;border:0;background:none;font:inherit;font-size:16px;line-height:1;cursor:pointer}.ferr{margin:0 10px 6px;font-size:12px;color:oklch(60% 0.2 27)}`}function B(n){return n<999500?`${Math.max(1,Math.round(n/1e3))} KB`:`${(n/1e6).toFixed(1)} MB`}var Q=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
2
2
|
--fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --ink-2: rgba(255,255,255,.70);
|
|
3
|
-
--online: oklch(72% 0.13 163.23);`;function
|
|
3
|
+
--online: oklch(72% 0.13 163.23);`;function Qe(n){return n==="light"?"":n==="dark"?`:host { ${Q} }`:`@media (prefers-color-scheme: dark) {
|
|
4
4
|
:host {
|
|
5
|
-
${
|
|
5
|
+
${Q}
|
|
6
6
|
}
|
|
7
|
-
}`}var
|
|
7
|
+
}`}var Ze=/https?:\/\/[^\s<>"]+/g,et=/[.,;:!?)]$/,tt=n=>{let e=n;for(;et.test(e);){let t=e.split("(").length-1,r=e.split(")").length-1;if(e.endsWith(")")&&t>=r)break;e=e.slice(0,-1);}return e};function nt(n,e){var r;let t=0;for(let i of e.matchAll(Ze)){let o=(r=i.index)!=null?r:0,a=tt(i[0]);o>t&&n.append(e.slice(t,o));let s=document.createElement("a");s.href=a,s.target="_blank",s.rel="noopener noreferrer",s.textContent=a,n.append(s),t=o+a.length;}t<e.length&&n.append(e.slice(t));}var rt=["P","BR","STRONG","EM","A","UL","OL","LI"],it=n=>typeof n=="object"&&n!==null&&"html"in n&&typeof n.html=="string"&&"text"in n&&typeof n.text=="string",at=(n,e)=>e.name==="class"||e.name==="data-block-type"?true:n!=="A"?false:e.name==="target"||e.name==="rel"?true:e.name==="href"&&/^https?:\/\//i.test(e.value.trim()),ot=n=>[...n.querySelectorAll("*")].every(e=>rt.includes(e.tagName)&&[...e.attributes].every(t=>at(e.tagName,t)));function Z(n,e="system"){var a;let t=H(n),r=n.launcherPosition==="bottom_left"?"left":"right",i=n.accentColor;return `${`
|
|
8
8
|
:host {
|
|
9
9
|
all: initial; z-index: 2147483000; --a: ${i};
|
|
10
10
|
--paper: #fff; --ink: #0f172a; --ink-3: rgba(0,0,0,.55);
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
--online: oklch(53.8% 0.1274 163.23);
|
|
13
13
|
color-scheme: ${e==="system"?"light dark":e};
|
|
14
14
|
}
|
|
15
|
-
${
|
|
15
|
+
${Qe(e)}
|
|
16
16
|
* { box-sizing: border-box; font-family: system-ui, sans-serif; }
|
|
17
17
|
.launcher {
|
|
18
18
|
z-index: 2147483000; position: fixed; ${r}: ${n.launcherOffsetX}px; bottom: ${n.launcherOffsetY}px; width: 56px; height: 56px;
|
|
@@ -102,5 +102,5 @@ ${Je(e)}
|
|
|
102
102
|
.panel { animation: rise 180ms ease-out; }
|
|
103
103
|
@keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
|
|
104
104
|
}
|
|
105
|
-
`}${Ue[t.composerShape]}${Oe[t.skin]}${j(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${ze[t.bubbleShape]}${Be[t.bubbleFill]}${De[t.namePlacement]}${t.nameAvatar?Ke:""}${t.dayDividers?Ge:""}${qe[t.stampPlacement]}${t.stampContent==="time_and_latency"?je:""}${We}${(o=n.attachments)!=null&&o.enabled?Ye(t.composerShape):""}`}var it=["end_user","agent","ai"];function at(){let n=globalThis.location;if(n)return {host:n.host,path:n.pathname,title:document.title}}var ot='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m16.5 6.5-7.8 7.8a2.1 2.1 0 0 0 3 3l8.1-8.1a4.2 4.2 0 0 0-6-6L5.7 11.3a6.3 6.3 0 0 0 8.9 8.9l6.6-6.6"/></svg>',st='<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M15.88 9.29 12 13.17 8.12 9.29a.996.996 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l4.59 4.59c.39.39 1.02.39 1.41 0l4.59-4.59c.39-.39.39-1.02 0-1.41-.39-.38-1.03-.39-1.42 0"/></svg>',I=class{constructor(e,t,r={},i={},a={}){this.host=e;this.client=t;m(this,"root");m(this,"strings");m(this,"settings");m(this,"appearance");m(this,"launcher");m(this,"badge");m(this,"panel",null);m(this,"lastFocused",null);m(this,"unread",0);m(this,"pendingTurns",0);m(this,"openNow");m(this,"style");m(this,"scheme");m(this,"picked",null);m(this,"objectUrls",[]);var o;this.strings={...Re,...r},this.appearance={...T,...i},this.settings=F({...T,...i}),this.root=e.attachShadow({mode:(o=a.shadowMode)!=null?o:"closed"}),this.openNow=_(this.appearance.availability,new Date),this.scheme=a.scheme,this.style=document.createElement("style"),this.style.textContent=X(this.appearance,this.scheme),this.root.append(this.style),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append(W(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.settings.launcherContent==="team_faces"?this.strings.agentLabel:this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...T,...e},this.settings=F(this.appearance),t!==void 0&&(this.scheme=t),this.style.textContent=X(this.appearance,this.scheme),this.drawLauncher(),this.panel&&(this.close(),this.open());}toggle(){this.panel?this.close():this.open();}setOpenNow(e){var t;this.openNow=e,this.launcher.classList.toggle("closed",!e),(t=this.panel)==null||t.classList.toggle("closed",!e);}async open(){var f;if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let r=(f=this.appearance.team)!=null?f:[];r.length>0&&t.append(R(r,this.strings,b=>this.client.avatarUrl(b)));let i=document.createElement("div");i.className="headmain";let a=document.createElement("h2");a.textContent=this.strings.title;let o=document.createElement("p");o.className="status";let s=document.createElement("span");s.className="live",s.setAttribute("aria-hidden","true"),o.append(s,this.strings.replyTime),i.append(a,o);let d=document.createElement("button");d.className="close",d.type="button",d.setAttribute("aria-label",this.strings.closeLabel),d.innerHTML=st,d.addEventListener("click",()=>this.close()),t.append(i,d);let p=document.createElement("div");p.className="log",p.setAttribute("role","log"),p.setAttribute("aria-live","polite"),p.setAttribute("aria-label",this.strings.title);let c=document.createElement("form");c.className="composer";let l=document.createElement("input");l.type="text",l.setAttribute("aria-label",this.strings.inputPlaceholder),l.placeholder=this.strings.inputPlaceholder;let h=document.createElement("button");h.type="submit",h.setAttribute("aria-label",this.strings.sendLabel),h.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let g=document.createElement("span");g.className="sendtext",g.textContent=this.strings.sendLabel,h.append(g);let v=this.appearance.attachments;if(v!=null&&v.enabled&&this.client.upload){let b=document.createElement("span");b.className="field";let u=document.createElement("input");u.type="file",u.accept=v.accept.join(","),u.hidden=true,u.addEventListener("change",()=>{var y;let E=(y=u.files)==null?void 0:y[0];u.value="",E&&this.pick(p,c,v,E);});let x=document.createElement("button");x.type="button",x.className="clip",x.setAttribute("aria-label",this.strings.attachLabel),x.innerHTML=ot,x.addEventListener("click",()=>u.click()),b.append(x,l,u),c.append(b,h);}else c.append(l,h);c.addEventListener("submit",b=>{b.preventDefault(),this.submit(l,p);}),e.append(t,p,c),e.addEventListener("keydown",b=>this.onKeydown(b,e,d)),this.root.append(e),this.panel=e,l.focus();let S=await this.client.load();S&&S.turns.length>0?this.renderThread(p,S):this.renderFirstRun(p,l),this.openNow||this.renderAway(t);}renderFirstRun(e,t){let r=document.createElement("div");r.className="empty";let i=document.createElement("h3");i.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle;let a=document.createElement("p");a.textContent=this.strings.emptyBody,r.append(i,a),this.appearance.starterPrompts.filter(tt).forEach((s,d)=>{let p=document.createElement("div");p.className="prompt";let c=document.createElement("div");c.className="promptwords",c.id=`prompt-${d}`;let l=document.createElement("template");l.innerHTML=s.html,rt(l.content)?c.append(l.content):c.textContent=s.text;for(let g of c.querySelectorAll("a"))g.target="_blank",g.rel="noopener noreferrer";let h=document.createElement("button");h.className="promptpress",h.type="button",h.setAttribute("aria-labelledby",c.id),h.addEventListener("click",()=>{t.value=s.text,this.submit(t,e);}),p.append(c,h),r.append(p);}),e.replaceChildren(r);}renderAway(e){let t=document.createElement("div");t.className="away";let r=document.createElement("span");r.className="awayglyph",r.setAttribute("aria-hidden","true");let i=document.createElement("span");i.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,t.append(r,i),e.after(t);}pick(e,t,r,i){let a=i.size>r.maxBytes||!r.accept.includes(i.type);for(let l of this.root.querySelectorAll(a?".ferr":".file,.ferr"))l.remove();if(a){let l=document.createElement("p");l.className="ferr",l.setAttribute("role","alert"),l.textContent=this.strings.fileRefusal(O(i.size),`${r.maxBytes/1e6} MB`),t.before(l),e.scrollTop=e.scrollHeight;return}this.picked=i;let o=document.createElement("span");o.className="file";let s;if(i.type==="application/pdf")s=document.createElement("b"),s.textContent="PDF";else {let l=document.createElement("img");l.className="th",l.alt="",l.src=this.objectUrl(i),s=l;}let d=document.createElement("span");d.className="name",d.textContent=i.name;let p=document.createElement("span");p.className="sz",p.textContent=`\xB7 ${O(i.size)}`;let c=document.createElement("button");c.type="button",c.className="x",c.setAttribute("aria-label",this.strings.removeFileLabel),c.textContent="\xD7",c.addEventListener("click",()=>{this.picked=null,o.remove();}),o.append(s,d,p,c),t.before(o),e.scrollTop=e.scrollHeight;}objectUrl(e){let t=URL.createObjectURL(e);return this.objectUrls.push(t),t}close(){if(this.panel){this.panel.remove(),this.panel=null,this.picked=null;for(let e of this.objectUrls)URL.revokeObjectURL(e);this.objectUrls=[],this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus();}}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let r=e.value.trim(),i=this.picked;if(!(!r&&!i)){e.value="",this.picked=null;for(let a of this.root.querySelectorAll(".file,.ferr"))a.remove();await this.sendBody(t,r,i);}}async sendBody(e,t,r=null){var s,d,p;(s=e.querySelector(".empty"))==null||s.remove(),this.pendingTurns+=1;let i=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`},r);i.setAttribute("data-pending","");let a=r?await((p=(d=this.client).upload)==null?void 0:p.call(d,r)):void 0,o=a===null?null:await this.client.send(t,at(),a?[a.id]:void 0);if(i.removeAttribute("data-pending"),o){i.dataset.turnId=o.id;return}this.markFailed(e,i,t,r);}markFailed(e,t,r,i){var o;t.setAttribute("data-failed","");let a=document.createElement("button");a.type="button",a.className="retry",a.textContent=this.strings.retryLabel,a.addEventListener("click",()=>{t.remove(),this.sendBody(e,r,i);}),((o=t.querySelector(".body"))!=null?o:t).append(a);}hasTurn(e,t){for(let r of e.children)if(r instanceof HTMLElement&&r.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let r of t.turns)this.appendTurn(e,r);}appendTurn(e,t,r=null){var l,h,g,v,S,f,b;(l=e.querySelector(".empty"))==null||l.remove();let i=it.includes(t.authorKind)?t.authorKind:"agent",a=this.settings,o=document.createElement("div");if(o.className=`turn ${i}`,o.dataset.turnId=t.id,i!=="end_user"&&a.nameAvatar){let u=document.createElement("span");if(u.className=i==="ai"?"av bot":"av",u.setAttribute("aria-hidden","true"),i==="agent"&&t.authorAvatarUrl){let x=document.createElement("img");x.alt="",x.src=this.client.avatarUrl(t.authorAvatarUrl),u.append(x);}else {u.textContent=i==="ai"?this.strings.aiLabel:q(this.agentName(t));let x=i==="agent"?(g=(h=this.appearance.team)==null?void 0:h.find(E=>E.name===t.authorName))==null?void 0:g.tone:void 0;x&&(u.style.background=x);}o.append(u);}let d=document.createElement("div");if(d.className="body",i==="end_user"){r&&this.drawFile(d,r.name,r.type,r.size,Promise.resolve(r));for(let u of (v=t.attachments)!=null?v:[])this.drawFile(d,u.name,u.contentType,u.bytes,(b=(f=(S=this.client).file)==null?void 0:f.call(S,u.url))!=null?b:Promise.resolve(null));}let p=i!=="end_user"&&a.namePlacement!=="hidden",c=document.createElement("div");if(i==="ai"?Ze(c,t.body):c.textContent=t.body,p||i==="ai"&&a.namePlacement==="hidden"){let u=document.createElement("div");u.className=i==="ai"?"author ai":"author",u.textContent=i==="ai"?this.strings.aiLabel:this.agentName(t),a.stampPlacement==="beside_name"&&u.append(this.stamp(t)),a.namePlacement==="inline"?(u.classList.add("below"),d.append(c,u)):d.append(u,c);}else t.body&&d.append(c);return a.stampPlacement==="under_turn"&&d.append(this.stamp(t)),o.append(d),e.append(o),e.scrollTop=e.scrollHeight,o}drawFile(e,t,r,i,a){let o=document.createElement("a");if(r==="application/pdf"){o.className="pdfc",o.download=t;let s=document.createElement("b");s.textContent="PDF",o.append(s,`${t} \xB7 ${O(i)}`);}else {o.className="att",o.target="_blank",o.rel="noopener noreferrer";let s=document.createElement("img");s.alt=t,s.addEventListener("load",()=>{let d=o.closest(".log");d&&(d.scrollTop=d.scrollHeight);}),o.append(s);}e.append(o),a.then(s=>{var d;s&&(o.href=this.objectUrl(s),(d=o.querySelector("img"))==null||d.setAttribute("src",o.href));});}agentName(e){return e.authorName||this.strings.agentLabel}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,r){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let i=t.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');if(i.length===0)return;let a=i[0],o=i[i.length-1],s=this.root.activeElement;e.shiftKey&&s===a?(e.preventDefault(),o.focus()):!e.shiftKey&&s===o?(e.preventDefault(),a.focus()):s===null&&(e.preventDefault(),r.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}};function V(n){return `40${JSON.stringify(n)}`}function Q(){return "3"}function Z(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let o=U(t);return {kind:"open",pingInterval:typeof(o==null?void 0:o.pingInterval)=="number"?o.pingInterval:25e3,pingTimeout:typeof(o==null?void 0:o.pingTimeout)=="number"?o.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=t.charAt(0),i=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let o=U(i);return {kind:"connectError",message:typeof(o==null?void 0:o.message)=="string"?o.message:"refused"}}if(r!=="2")return {kind:"other"};let a=U(i);return !Array.isArray(a)||typeof a[0]!="string"?{kind:"other"}:{kind:"event",name:a[0],payload:a[1]}}function U(n){try{return JSON.parse(n)}catch(e){return null}}var lt="/socket.io/?EIO=4&transport=websocket",M=class{constructor(e){this.options=e;m(this,"socket",null);m(this,"heartbeat",null);m(this,"ready",false);m(this,"closed",false);m(this,"heartbeatWindow",45e3);m(this,"factory");m(this,"setTimer");m(this,"clearTimer");var t,r,i;this.factory=(t=e.socketFactory)!=null?t:ct,this.setTimer=(r=e.setTimer)!=null?r:((a,o)=>setTimeout(a,o)),this.clearTimer=(i=e.clearTimer)!=null?i:(a=>clearTimeout(a));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${lt}`,t;try{t=this.factory(e);}catch(r){this.options.onClosed(false);return}this.socket=t,t.onmessage=r=>this.receive(String(r.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e==null||e.close();}receive(e){var r,i,a,o;let t=Z(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),(r=this.socket)==null||r.send(V(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),(i=this.socket)==null||i.send(Q());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),(a=this.socket)==null||a.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let s=(o=t.payload)==null?void 0:o.turn;s&&this.options.onTurn(s);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>{var t;return (t=this.socket)==null?void 0:t.close()},this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function ct(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}var dt=6e4;function ee(n){var b,u,x,E;let e=globalThis.document;if(!e)throw new Error("prodantix chat requires a document; mount it in the browser");let t=(b=n.mountPoint)!=null?b:e.createElement("div");n.mountPoint||e.body.append(t);let r=new N(n),i=new I(t,r,n.strings,n.appearance),a=(x=(u=n.appearance)==null?void 0:u.availability)!=null?x:T.availability,o,s=()=>{i.setOpenNow(_(a,new Date)),o=setTimeout(s,dt);};s();let d=new Set,p,c=null,l=(E=n.pollIntervalMs)!=null?E:15e3,h=y=>{d.has(y.id)||y.authorKind==="end_user"||(d.add(y.id),i.onIncomingTurn(y));},g=async()=>{if(!r.hasThread)return;let y=await r.load();if(y){for(let w of y.turns)h(w);d=new Set(y.turns.map(w=>w.id));}},v=()=>{p||l<=0||(p=setInterval(()=>void g(),l));},S=()=>{p&&clearInterval(p),p=void 0;},f=()=>{if(c||!n.socketHost)return;let y=r.socketAuth;y&&(c=new M({auth:y,host:n.socketHost,onClosed:w=>{c=null,v(),w&&f();},onReady:S,onTurn:h,socketFactory:n.socketFactory}),c.open());};return v(),f(),{close:()=>i.close(),destroy:()=>{S(),clearTimeout(o),c==null||c.close(),c=null,i.close(),t.remove();},identify:y=>r.identify(y),open:()=>{i.open().then(f);}}}var pt="prodantix.messenger.config",te=n=>{var t,r,i,a;let e=(t=n.navigator)==null?void 0:t.languages;return Array.isArray(e)&&e.length>0?e.join(","):((r=n.navigator)==null?void 0:r.language)||((a=(i=n.document)==null?void 0:i.documentElement)==null?void 0:a.lang)||void 0},ne=(n,e)=>`${pt}:${n}:${e!=null?e:""}`;function re(n,e,t){let r=n==null?void 0:n.get(ne(e,t));if(!r)return null;try{let i=JSON.parse(r);return (i==null?void 0:i.apiKey)===e?i.config:null}catch(i){return null}}async function ie(n){var a,o,s,d,p;let e=L(n.fetchImpl);if(!e)return (a=n.onError)==null||a.call(n,new Error("no fetch available for the prodantix messenger")),null;let t=P(n.host),r=ne(n.apiKey,n.locale),i=n.locale?`?locale=${encodeURIComponent(n.locale)}`:"";try{let c=await e(`${t}/v1/messenger/config${i}`,{headers:{authorization:`Bearer ${n.apiKey}`},method:"GET"});if(!c.ok)return (o=n.onError)==null||o.call(n,new Error(`prodantix messenger config: ${c.status}`)),null;let l=JSON.parse(await c.text());return l.enabled?((d=n.storage)==null||d.set(r,JSON.stringify({apiKey:n.apiKey,config:l})),l):((s=n.storage)==null||s.remove(r),l)}catch(c){return (p=n.onError)==null||p.call(n,c),null}}var ut=["close","identify","open","shutdown","toggle"],A="[prodantix/messenger]";function ht(n,e){for(let t of n){let[r,...i]=t!=null?t:[];typeof r!="string"||!ut.includes(r)||e(r,...i);}}function mt(n){if(!n)return null;try{return new URL(n).origin}catch(e){return null}}async function oe(n,e={}){var g,v,S;let t=(g=e.warn)!=null?g:(f=>console.warn(f)),r=n.prodantix,i=r==null?void 0:r.k;if(!i)return t(`${A} no project key on the install snippet; nothing will load.`),null;let a=mt((v=e.scriptSrc)!=null?v:gt(n));if(!a)return t(`${A} could not tell which host served this script; nothing will load.`),null;let o=ft(n),s=te(n),d=re(o,i,s),p=await ie({apiKey:i,host:a,locale:s,onError:f=>t(`${A} settings could not be read: ${String(f)}`),storage:o}),c=p!=null?p:d;if(!c)return t(`${A} no settings available; the messenger will not render.`),null;if(!c.enabled)return null;let l=ee({apiKey:i,appearance:c,distinctId:xt(n,o),host:a,socketHost:c.socketUrl||void 0}),h=(f,...b)=>{if((f==="open"||f==="toggle")&&l.open(),f==="close"&&l.close(),f==="shutdown"&&l.destroy(),f==="identify"){let u=bt(b[0]);if(!u){console.error(`${A} identify needs { userId, userHash }: the hash is HMAC-SHA256 of the user id under the project signing secret, computed on your server. Without it the visitor stays anonymous.`);return}l.identify(u);}};return ht((S=r==null?void 0:r.q)!=null?S:[],h),n.prodantix=Object.assign((f,...b)=>h(f,...b),{k:i,q:[]}),l}function gt(n){var t;let e=(t=n.document)==null?void 0:t.currentScript;return e==null?void 0:e.src}function ft(n){let e=n.localStorage;if(e)return {get:t=>e.getItem(t),remove:t=>e.removeItem(t),set:(t,r)=>e.setItem(t,r)}}function bt(n){if(typeof n!="object"||n===null)return null;let{userHash:e,userId:t}=n;return typeof t!="string"||typeof e!="string"||t.trim()===""||e.trim()===""?null:{userHash:e,userId:t}}var ae="prodantix.messenger.anon";function xt(n,e){var i,a,o;let t=e==null?void 0:e.get(ae);if(t)return t;let r=`anon_${(o=(a=(i=n.crypto)==null?void 0:i.randomUUID)==null?void 0:a.call(i))!=null?o:Math.random().toString(36).slice(2)}`;return e==null||e.set(ae,r),r}oe(globalThis);})();//# sourceMappingURL=messenger.iife.js.map
|
|
105
|
+
`}${De[t.composerShape]}${Be[t.skin]}${J(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${Ke[t.bubbleShape]}${Ge[t.bubbleFill]}${qe[t.namePlacement]}${t.nameAvatar?je:""}${t.dayDividers?We:""}${Ye[t.stampPlacement]}${t.stampContent==="time_and_latency"?Je:""}${Xe}${(a=n.attachments)!=null&&a.enabled?Ve(t.composerShape):""}`}var st=["end_user","agent","ai"];function lt(){let n=globalThis.location;if(n)return {host:n.host,path:n.pathname,title:document.title}}var ct='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m16.5 6.5-7.8 7.8a2.1 2.1 0 0 0 3 3l8.1-8.1a4.2 4.2 0 0 0-6-6L5.7 11.3a6.3 6.3 0 0 0 8.9 8.9l6.6-6.6"/></svg>',dt='<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M15.88 9.29 12 13.17 8.12 9.29a.996.996 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l4.59 4.59c.39.39 1.02.39 1.41 0l4.59-4.59c.39-.39.39-1.02 0-1.41-.39-.38-1.03-.39-1.42 0"/></svg>',$=class{constructor(e,t,r={},i={},o={}){this.host=e;this.client=t;m(this,"root");m(this,"strings");m(this,"settings");m(this,"appearance");m(this,"launcher");m(this,"badge");m(this,"panel",null);m(this,"lastFocused",null);m(this,"unread",0);m(this,"pendingTurns",0);m(this,"openNow");m(this,"style");m(this,"scheme");m(this,"picked",null);m(this,"objectUrls",[]);var a;this.strings={...ze,...r},this.appearance={...A,...i},this.settings=H({...A,...i}),this.root=e.attachShadow({mode:(a=o.shadowMode)!=null?a:"closed"}),this.openNow=M(this.appearance.availability,new Date),this.scheme=o.scheme,this.style=document.createElement("style"),this.style.textContent=Z(this.appearance,this.scheme),this.root.append(this.style),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append(X(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.settings.launcherContent==="team_faces"?this.strings.agentLabel:this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...A,...e},this.settings=H(this.appearance),t!==void 0&&(this.scheme=t),this.style.textContent=Z(this.appearance,this.scheme),this.drawLauncher(),this.panel&&(this.close(),this.open());}toggle(){this.panel?this.close():this.open();}setOpenNow(e){var t;this.openNow=e,this.launcher.classList.toggle("closed",!e),(t=this.panel)==null||t.classList.toggle("closed",!e);}async open(){var f;if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let r=(f=this.appearance.team)!=null?f:[];r.length>0&&t.append(z(r,this.strings,b=>this.client.avatarUrl(b)));let i=document.createElement("div");i.className="headmain";let o=document.createElement("h2");o.textContent=this.strings.title;let a=document.createElement("p");a.className="status";let s=document.createElement("span");s.className="live",s.setAttribute("aria-hidden","true"),a.append(s,this.strings.replyTime),i.append(o,a);let d=document.createElement("button");d.className="close",d.type="button",d.setAttribute("aria-label",this.strings.closeLabel),d.innerHTML=dt,d.addEventListener("click",()=>this.close()),t.append(i,d);let p=document.createElement("div");p.className="log",p.setAttribute("role","log"),p.setAttribute("aria-live","polite"),p.setAttribute("aria-label",this.strings.title);let c=document.createElement("form");c.className="composer";let l=document.createElement("input");l.type="text",l.setAttribute("aria-label",this.strings.inputPlaceholder),l.placeholder=this.strings.inputPlaceholder;let u=document.createElement("button");u.type="submit",u.setAttribute("aria-label",this.strings.sendLabel),u.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let g=document.createElement("span");g.className="sendtext",g.textContent=this.strings.sendLabel,u.append(g);let v=this.appearance.attachments;if(v!=null&&v.enabled&&this.client.upload){let b=document.createElement("span");b.className="field";let h=document.createElement("input");h.type="file",h.accept=v.accept.join(","),h.hidden=true,h.addEventListener("change",()=>{var y;let w=(y=h.files)==null?void 0:y[0];h.value="",w&&this.pick(p,c,v,w);});let x=document.createElement("button");x.type="button",x.className="clip",x.setAttribute("aria-label",this.strings.attachLabel),x.innerHTML=ct,x.addEventListener("click",()=>h.click()),b.append(x,l,h),c.append(b,u);}else c.append(l,u);c.addEventListener("submit",b=>{b.preventDefault(),this.submit(l,p);}),e.append(t,p,c),e.addEventListener("keydown",b=>this.onKeydown(b,e,d)),this.root.append(e),this.panel=e,l.focus();let S=await this.client.load();S&&S.turns.length>0?this.renderThread(p,S):this.renderFirstRun(p,l),this.openNow||this.renderAway(t);}renderFirstRun(e,t){let r=document.createElement("div");r.className="empty";let i=document.createElement("h3");i.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle;let o=document.createElement("p");o.textContent=this.strings.emptyBody,r.append(i,o),this.appearance.starterPrompts.filter(it).forEach((s,d)=>{let p=document.createElement("div");p.className="prompt";let c=document.createElement("div");c.className="promptwords",c.id=`prompt-${d}`;let l=document.createElement("template");l.innerHTML=s.html,ot(l.content)?c.append(l.content):c.textContent=s.text;for(let g of c.querySelectorAll("a"))g.target="_blank",g.rel="noopener noreferrer";let u=document.createElement("button");u.className="promptpress",u.type="button",u.setAttribute("aria-labelledby",c.id),u.addEventListener("click",()=>{t.value=s.text,this.submit(t,e);}),p.append(c,u),r.append(p);}),e.replaceChildren(r);}renderAway(e){let t=document.createElement("div");t.className="away";let r=document.createElement("span");r.className="awayglyph",r.setAttribute("aria-hidden","true");let i=document.createElement("span");i.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,t.append(r,i),e.after(t);}pick(e,t,r,i){let o=i.size>r.maxBytes||!r.accept.includes(i.type);for(let l of this.root.querySelectorAll(o?".ferr":".file,.ferr"))l.remove();if(o){let l=document.createElement("p");l.className="ferr",l.setAttribute("role","alert"),l.textContent=this.strings.fileRefusal(B(i.size),`${r.maxBytes/1e6} MB`),t.before(l),e.scrollTop=e.scrollHeight;return}this.picked=i;let a=document.createElement("span");a.className="file";let s;if(i.type==="application/pdf")s=document.createElement("b"),s.textContent="PDF";else {let l=document.createElement("img");l.className="th",l.alt="",l.src=this.objectUrl(i),s=l;}let d=document.createElement("span");d.className="name",d.textContent=i.name;let p=document.createElement("span");p.className="sz",p.textContent=`\xB7 ${B(i.size)}`;let c=document.createElement("button");c.type="button",c.className="x",c.setAttribute("aria-label",this.strings.removeFileLabel),c.textContent="\xD7",c.addEventListener("click",()=>{this.picked=null,a.remove();}),a.append(s,d,p,c),t.before(a),e.scrollTop=e.scrollHeight;}objectUrl(e){let t=URL.createObjectURL(e);return this.objectUrls.push(t),t}close(){if(this.panel){this.panel.remove(),this.panel=null,this.picked=null;for(let e of this.objectUrls)URL.revokeObjectURL(e);this.objectUrls=[],this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus();}}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let r=e.value.trim(),i=this.picked;if(!(!r&&!i)){e.value="",this.picked=null;for(let o of this.root.querySelectorAll(".file,.ferr"))o.remove();await this.sendBody(t,r,i);}}async sendBody(e,t,r=null){var s,d,p;(s=e.querySelector(".empty"))==null||s.remove(),this.pendingTurns+=1;let i=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`},r);i.setAttribute("data-pending","");let o=r?await((p=(d=this.client).upload)==null?void 0:p.call(d,r)):void 0,a=o===null?null:await this.client.send(t,lt(),o?[o.id]:void 0);if(i.removeAttribute("data-pending"),a){i.dataset.turnId=a.id;return}this.markFailed(e,i,t,r);}markFailed(e,t,r,i){var a;t.setAttribute("data-failed","");let o=document.createElement("button");o.type="button",o.className="retry",o.textContent=this.strings.retryLabel,o.addEventListener("click",()=>{t.remove(),this.sendBody(e,r,i);}),((a=t.querySelector(".body"))!=null?a:t).append(o);}hasTurn(e,t){for(let r of e.children)if(r instanceof HTMLElement&&r.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let r of t.turns)this.appendTurn(e,r);}appendTurn(e,t,r=null){var l,u,g,v,S,f,b;(l=e.querySelector(".empty"))==null||l.remove();let i=st.includes(t.authorKind)?t.authorKind:"agent",o=this.settings,a=document.createElement("div");if(a.className=`turn ${i}`,a.dataset.turnId=t.id,i!=="end_user"&&o.nameAvatar){let h=document.createElement("span");if(h.className=i==="ai"?"av bot":"av",h.setAttribute("aria-hidden","true"),i==="agent"&&t.authorAvatarUrl){let x=document.createElement("img");x.alt="",x.src=this.client.avatarUrl(t.authorAvatarUrl),h.append(x);}else {h.textContent=i==="ai"?this.strings.aiLabel:Y(this.agentName(t));let x=i==="agent"?(g=(u=this.appearance.team)==null?void 0:u.find(w=>w.name===t.authorName))==null?void 0:g.tone:void 0;x&&(h.style.background=x);}a.append(h);}let d=document.createElement("div");if(d.className="body",i==="end_user"){r&&this.drawFile(d,r.name,r.type,r.size,Promise.resolve(r));for(let h of (v=t.attachments)!=null?v:[])this.drawFile(d,h.name,h.contentType,h.bytes,(b=(f=(S=this.client).file)==null?void 0:f.call(S,h.url))!=null?b:Promise.resolve(null));}let p=i!=="end_user"&&o.namePlacement!=="hidden",c=document.createElement("div");if(i==="ai"?nt(c,t.body):c.textContent=t.body,p||i==="ai"&&o.namePlacement==="hidden"){let h=document.createElement("div");h.className=i==="ai"?"author ai":"author",h.textContent=i==="ai"?this.strings.aiLabel:this.agentName(t),o.stampPlacement==="beside_name"&&h.append(this.stamp(t)),o.namePlacement==="inline"?(h.classList.add("below"),d.append(c,h)):d.append(h,c);}else t.body&&d.append(c);return o.stampPlacement==="under_turn"&&d.append(this.stamp(t)),a.append(d),e.append(a),e.scrollTop=e.scrollHeight,a}drawFile(e,t,r,i,o){let a=document.createElement("a");if(r==="application/pdf"){a.className="pdfc",a.download=t;let s=document.createElement("b");s.textContent="PDF",a.append(s,`${t} \xB7 ${B(i)}`);}else {a.className="att",a.target="_blank",a.rel="noopener noreferrer";let s=document.createElement("img");s.alt=t,s.addEventListener("load",()=>{let d=a.closest(".log");d&&(d.scrollTop=d.scrollHeight);}),a.append(s);}e.append(a),o.then(s=>{var d;s&&(a.href=this.objectUrl(s),(d=a.querySelector("img"))==null||d.setAttribute("src",a.href));});}agentName(e){return e.authorName||this.strings.agentLabel}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,r){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let i=t.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');if(i.length===0)return;let o=i[0],a=i[i.length-1],s=this.root.activeElement;e.shiftKey&&s===o?(e.preventDefault(),a.focus()):!e.shiftKey&&s===a?(e.preventDefault(),o.focus()):s===null&&(e.preventDefault(),r.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}};function ee(n){return `40${JSON.stringify(n)}`}function te(){return "3"}function ne(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let a=D(t);return {kind:"open",pingInterval:typeof(a==null?void 0:a.pingInterval)=="number"?a.pingInterval:25e3,pingTimeout:typeof(a==null?void 0:a.pingTimeout)=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=t.charAt(0),i=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let a=D(i);return {kind:"connectError",message:typeof(a==null?void 0:a.message)=="string"?a.message:"refused"}}if(r!=="2")return {kind:"other"};let o=D(i);return !Array.isArray(o)||typeof o[0]!="string"?{kind:"other"}:{kind:"event",name:o[0],payload:o[1]}}function D(n){try{return JSON.parse(n)}catch(e){return null}}var pt="/socket.io/?EIO=4&transport=websocket",R=class{constructor(e){this.options=e;m(this,"socket",null);m(this,"heartbeat",null);m(this,"ready",false);m(this,"closed",false);m(this,"heartbeatWindow",45e3);m(this,"factory");m(this,"setTimer");m(this,"clearTimer");var t,r,i;this.factory=(t=e.socketFactory)!=null?t:ut,this.setTimer=(r=e.setTimer)!=null?r:((o,a)=>setTimeout(o,a)),this.clearTimer=(i=e.clearTimer)!=null?i:(o=>clearTimeout(o));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${pt}`,t;try{t=this.factory(e);}catch(r){this.options.onClosed(false);return}this.socket=t,t.onmessage=r=>this.receive(String(r.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e==null||e.close();}receive(e){var r,i,o,a;let t=ne(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),(r=this.socket)==null||r.send(ee(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),(i=this.socket)==null||i.send(te());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),(o=this.socket)==null||o.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let s=(a=t.payload)==null?void 0:a.turn;s&&this.options.onTurn(s);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>{var t;return (t=this.socket)==null?void 0:t.close()},this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function ut(n){let e=globalThis.WebSocket;if(!e)throw new C("no WebSocket");return new e(n)}var ht=6e4;function re(n){var b,h,x,w;let e=globalThis.document;if(!e)throw new N("prodantix chat requires a document; mount it in the browser");let t=(b=n.mountPoint)!=null?b:e.createElement("div");n.mountPoint||e.body.append(t);let r=new I(n),i=new $(t,r,n.strings,n.appearance),o=(x=(h=n.appearance)==null?void 0:h.availability)!=null?x:A.availability,a,s=()=>{i.setOpenNow(M(o,new Date)),a=setTimeout(s,ht);};s();let d=new Set,p,c=null,l=(w=n.pollIntervalMs)!=null?w:15e3,u=y=>{d.has(y.id)||y.authorKind==="end_user"||(d.add(y.id),i.onIncomingTurn(y));},g=async()=>{if(!r.hasThread)return;let y=await r.load();if(y){for(let T of y.turns)u(T);d=new Set(y.turns.map(T=>T.id));}},v=()=>{p||l<=0||(p=setInterval(()=>void g(),l));},S=()=>{p&&clearInterval(p),p=void 0;},f=()=>{if(c||!n.socketHost)return;let y=r.socketAuth;y&&(c=new R({auth:y,host:n.socketHost,onClosed:T=>{c=null,v(),T&&f();},onReady:S,onTurn:u,socketFactory:n.socketFactory}),c.open());};return v(),f(),{close:()=>i.close(),destroy:()=>{S(),clearTimeout(a),c==null||c.close(),c=null,i.close(),t.remove();},identify:y=>r.identify(y),open:()=>{i.open().then(f);}}}var mt="prodantix.messenger.config",ie=n=>{var t,r,i,o;let e=(t=n.navigator)==null?void 0:t.languages;return Array.isArray(e)&&e.length>0?e.join(","):((r=n.navigator)==null?void 0:r.language)||((o=(i=n.document)==null?void 0:i.documentElement)==null?void 0:o.lang)||void 0},ae=(n,e)=>`${mt}:${n}:${e!=null?e:""}`;function oe(n,e,t){let r=n==null?void 0:n.get(ae(e,t));if(!r)return null;try{let i=JSON.parse(r);return (i==null?void 0:i.apiKey)===e?i.config:null}catch(i){return null}}async function se(n){var o,a,s,d,p;let e=_(n.fetchImpl);if(!e)return (o=n.onError)==null||o.call(n,new C("no fetch available for the prodantix messenger")),null;let t=F(n.host),r=ae(n.apiKey,n.locale),i=n.locale?`?locale=${encodeURIComponent(n.locale)}`:"";try{let c=await e(`${t}/v1/messenger/config${i}`,{headers:{authorization:`Bearer ${n.apiKey}`},method:"GET"});if(!c.ok)return (a=n.onError)==null||a.call(n,new C(`prodantix messenger config: ${c.status}`,c.status)),null;let l=JSON.parse(await c.text());return l.enabled?((d=n.storage)==null||d.set(r,JSON.stringify({apiKey:n.apiKey,config:l})),l):((s=n.storage)==null||s.remove(r),l)}catch(c){return (p=n.onError)==null||p.call(n,c),null}}var gt=["close","identify","open","shutdown","toggle"],L="[prodantix/messenger]";function ft(n,e){for(let t of n){let[r,...i]=t!=null?t:[];typeof r!="string"||!gt.includes(r)||e(r,...i);}}function bt(n){if(!n)return null;try{return new URL(n).origin}catch(e){return null}}async function ce(n,e={}){var g,v,S;let t=(g=e.warn)!=null?g:(f=>console.warn(f)),r=n.prodantix,i=r==null?void 0:r.k;if(!i)return t(`${L} no project key on the install snippet; nothing will load.`),null;let o=bt((v=e.scriptSrc)!=null?v:xt(n));if(!o)return t(`${L} could not tell which host served this script; nothing will load.`),null;let a=yt(n),s=ie(n),d=oe(a,i,s),p=await se({apiKey:i,host:o,locale:s,onError:f=>t(`${L} settings could not be read: ${String(f)}`),storage:a}),c=p!=null?p:d;if(!c)return t(`${L} no settings available; the messenger will not render.`),null;if(!c.enabled)return null;let l=re({apiKey:i,appearance:c,distinctId:St(n,a),host:o,socketHost:c.socketUrl||void 0}),u=(f,...b)=>{if((f==="open"||f==="toggle")&&l.open(),f==="close"&&l.close(),f==="shutdown"&&l.destroy(),f==="identify"){let h=vt(b[0]);if(!h){console.error(`${L} identify needs { userId, userHash }: the hash is HMAC-SHA256 of the user id under the project signing secret, computed on your server. Without it the visitor stays anonymous.`);return}l.identify(h);}};return ft((S=r==null?void 0:r.q)!=null?S:[],u),n.prodantix=Object.assign((f,...b)=>u(f,...b),{k:i,q:[]}),l}function xt(n){var t;let e=(t=n.document)==null?void 0:t.currentScript;return e==null?void 0:e.src}function yt(n){let e=n.localStorage;if(e)return {get:t=>e.getItem(t),remove:t=>e.removeItem(t),set:(t,r)=>e.setItem(t,r)}}function vt(n){if(typeof n!="object"||n===null)return null;let{userHash:e,userId:t}=n;return typeof t!="string"||typeof e!="string"||t.trim()===""||e.trim()===""?null:{userHash:e,userId:t}}var le="prodantix.messenger.anon";function St(n,e){var i,o,a;let t=e==null?void 0:e.get(le);if(t)return t;let r=`anon_${(a=(o=(i=n.crypto)==null?void 0:i.randomUUID)==null?void 0:o.call(i))!=null?a:Math.random().toString(36).slice(2)}`;return e==null||e.set(le,r),r}ce(window);})();//# sourceMappingURL=messenger.iife.js.map
|
|
106
106
|
//# sourceMappingURL=messenger.iife.js.map
|
package/dist/messenger.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {e,d as d$1,h}from'./chunk-ODN4ZELX.js';import'./chunk-5XGN7UAV.js';var f="prodantix.messenger.config",u=e=>{let r=e.navigator?.languages;return Array.isArray(r)&&r.length>0?r.join(","):e.navigator?.language||e.document?.documentElement?.lang||void 0},l=(e,r)=>`${f}:${e}:${r??""}`;function p(e,r,s){let n=e?.get(l(r,s));if(!n)return null;try{let a=JSON.parse(n);return a?.apiKey===r?a.config:null}catch{return null}}async function d(e$1){let r=e(e$1.fetchImpl);if(!r)return e$1.onError?.(new d$1("no fetch available for the prodantix messenger")),null;let s=h(e$1.host),n=l(e$1.apiKey,e$1.locale),a=e$1.locale?`?locale=${encodeURIComponent(e$1.locale)}`:"";try{let t=await r(`${s}/v1/messenger/config${a}`,{headers:{authorization:`Bearer ${e$1.apiKey}`},method:"GET"});if(!t.ok)return e$1.onError?.(new d$1(`prodantix messenger config: ${t.status}`,t.status)),null;let o=JSON.parse(await t.text());return o.enabled?(e$1.storage?.set(n,JSON.stringify({apiKey:e$1.apiKey,config:o})),o):(e$1.storage?.remove(n),o)}catch(t){return e$1.onError?.(t),null}}export{f as MESSENGER_CACHE_KEY,l as cacheKeyFor,p as cachedMessengerConfig,d as fetchMessengerConfig,u as localeCandidates};//# sourceMappingURL=messenger.js.map
|
|
2
2
|
//# sourceMappingURL=messenger.js.map
|
package/dist/node.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var fe=Object.defineProperty;var ge=(n,e,t)=>e in n?fe(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var o=(n,e,t)=>ge(n,typeof e!="symbol"?e+"":e,t);var p=class extends Error{constructor(t,s,r){super(s,r);o(this,"code");this.code=t,this.name="ProdantixError";}},v=class extends p{constructor(e){super("config",e),this.name="ConfigError";}},m=class extends p{constructor(t,s){super("validation",s);o(this,"field");this.field=t,this.name="ValidationError";}},c=class extends p{constructor(t,s,r){super("transport",t,r);o(this,"status");this.status=s,this.name="TransportError";}};function y(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function u(){let n=globalThis.AbortController;return n?new n:void 0}var V=n=>new Promise(e=>{setTimeout(e,n);});function h(n){return n.replace(/\/+$/,"")}var k=class{constructor(){o(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,t){this.store.set(e,t);}};var j={now:()=>new Date};function b(n){return n.toISOString()}function me(){return globalThis.crypto}function ye(n){n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=[];for(let t=0;t<16;t+=1)e.push(n[t].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function ve(){let n=me();if(n?.randomUUID)return n.randomUUID();let e=new Uint8Array(16);if(n?.getRandomValues)n.getRandomValues(e);else for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);return ye(e)}var G={uuid:ve};var ke=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var be=/^(?:\$|[a-z])[a-z0-9_.]*$/;function x(n){let e=0;for(let t of n)e+=1;return e}function J(n){return ke.test(n)}function xe(n){return be.test(n)}function H(n){let e=x(n);if(e<1||e>200)throw new m("distinct_id","distinct_id must be between 1 and 200 characters")}function U(n){let e=x(n);if(e<1||e>200)throw new m("event_name","event_name must be between 1 and 200 characters");if(!xe(n))throw new m("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var B="prodantix-js",z="0.0.1";var Ee=n=>{};function Q(n){if(!n.apiKey||!J(n.apiKey))throw new v("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!n.host)throw new v("host is required (the ingest base URL)");let e=h(n.host),t=n.defaultProperties,s=n.storage??new k;return {apiKey:n.apiKey,autocapture:n.autocapture??false,clock:n.clock??j,consent:n.consent,defaultProperties:typeof t=="function"?t:()=>t??{},flagsHost:n.flagsHost?h(n.flagsHost):e,flushAt:n.flushAt??20,flushIntervalMs:n.flushIntervalMs??1e4,host:e,ids:n.ids??G,locale:n.locale,maxQueueSize:n.maxQueueSize??1e3,maxRetries:n.maxRetries??3,namespace:$(n.apiKey),onError:n.onError??Ee,os:n.os,requestTimeoutMs:n.requestTimeoutMs??1e4,sdkName:n.sdkName??B,sdkVersion:n.sdkVersion??z,sessionTracking:n.sessionTracking??false,sharedStorage:n.sharedStorage??s,socketFactory:n.socketFactory,storage:s,streamFlags:n.streamFlags??false,transport:n.transport}}function $(n){return n.slice(0,16)}function W(n,e,t){U(n.eventName),H(n.distinctId);let s={distinct_id:n.distinctId,event_id:n.eventId??t.uuid(),event_name:n.eventName,properties:n.properties??{},schema_version:1,timestamp:b(n.timestamp??e.now())};return n.context&&(s.context=n.context),n.sessionId&&(s.session_id=n.sessionId),s}var g=Symbol("absent");function Se(n,e){if(n==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,n))return t[n];let s=e.attributes??{};return Object.prototype.hasOwnProperty.call(s,n)?s[n]:g}function f(n){return n===g?"undefined":String(n)}function Y(n){return n===g?Number.NaN:Number(n)}function X(n){return n!==g&&n!==null&&n!==""}function Z(n,e){if(!Array.isArray(e))return false;let t=f(n);return e.map(s=>String(s)).includes(t)}function ee(n,e){let t=Se(n.attribute,e),s=n.value;switch(n.op){case "is_set":return X(t);case "is_not_set":return !X(t);case "eq":return f(t)===f(s===void 0?g:s);case "neq":return f(t)!==f(s===void 0?g:s);case "contains":return f(t).includes(f(s===void 0?g:s));case "in":return Z(t,s);case "not_in":return Array.isArray(s)?!Z(t,s):false;case "gt":return E(t,s,(r,i)=>r>i);case "gte":return E(t,s,(r,i)=>r>=i);case "lt":return E(t,s,(r,i)=>r<i);case "lte":return E(t,s,(r,i)=>r<=i);case "in_cohort":return typeof s=="string"&&s!==""&&(e.cohorts??[]).includes(s);case "not_in_cohort":return typeof s=="string"&&s!==""&&!(e.cohorts??[]).includes(s);default:return false}}function E(n,e,t){let s=Y(n),r=e===void 0?Number.NaN:Y(e);return Number.isNaN(s)||Number.isNaN(r)?false:t(s,r)}function te(n,e){let t=`${n}:${e}`,s=2166136261;for(let r=0;r<t.length;r++)s^=t.charCodeAt(r),s=Math.imul(s,16777619);return (s>>>0)%100}function N(n,e){return n.targeting.length===0||n.targeting.every(t=>ee(t,e))}function ne(n,e){let t=te(n.key,e.distinctId),s=n.variations??[];if(s.length===0)return n.rolloutPercentage>=100||t<n.rolloutPercentage?"true":"false";let r=0;for(let i=s.length-1;i>=0;i--)if(r+=s[i].weight,t<r)return s[i].key;return s[0].key}function R(n,e,t,s){for(let r of n.prerequisites??[]){if(s.includes(r.flagKey))return false;let i=e.find(l=>l.key===r.flagKey);if(!i||!i.enabled)return false;s.push(i.key);let a=R(i,e,t,s)&&N(i,t)&&ne(i,t)===r.variationKey;if(s.pop(),!a)return false}return true}function S(n,e,t){return n.enabled?R(n,e,t,[n.key])?N(n,t)?n.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:te(n.key,t.distinctId)<n.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function se(n,e){let t={};for(let s of n)t[s.key]=S(s,n,e).enabled;return t}function O(n,e,t){let s=n.variations??[],r=s[0];if(!r)return null;if(!n.enabled||!R(n,e,t,[n.key])||!N(n,t))return r;let i=ne(n,t);return s.find(a=>a.key===i)??r}function re(n){return n.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}function ie(n){return `40${JSON.stringify(n)}`}function oe(){return "3"}function ae(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let a=M(t);return {kind:"open",pingInterval:typeof a?.pingInterval=="number"?a.pingInterval:25e3,pingTimeout:typeof a?.pingTimeout=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let s=t.charAt(0),r=t.slice(1);if(s==="0")return {kind:"connected"};if(s==="1")return {kind:"disconnect"};if(s==="4"){let a=M(r);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(s!=="2")return {kind:"other"};let i=M(r);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function M(n){try{return JSON.parse(n)}catch{return null}}var Ie="/socket.io/?EIO=4&transport=websocket",we=250,I=class{constructor(e){this.options=e;o(this,"socket",null);o(this,"heartbeat",null);o(this,"pending",null);o(this,"lastKey","");o(this,"ready",false);o(this,"closed",false);o(this,"heartbeatWindow",45e3);o(this,"factory");o(this,"setTimer");o(this,"clearTimer");this.factory=e.socketFactory??Ce,this.setTimer=e.setTimer??((t,s)=>setTimeout(t,s)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Ie}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=s=>this.receive(String(s.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat(),this.pending!==null&&this.clearTimer(this.pending),this.pending=null;let e=this.socket;this.socket=null,e?.close();}receive(e){let t=ae(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(ie({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(oe());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true;return}if(t.name==="flagChange"){let s=t.payload?.key;this.lastKey=typeof s=="string"?s:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},we));}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function Ce(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}var w=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=y(e.fetch),this.host=h(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new c(`flags request failed with status ${a.status}`,a.status);let l=JSON.parse(await a.text());return {flags:l.flags??{},variants:l.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new c("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,s=u(),r=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let i=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!i.ok)throw new c(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),l={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(l.socketUrl=a.socketUrl),l}finally{r!==void 0&&clearTimeout(r);}}async memberships(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new c(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};function q(n){if(typeof n!="string")return;let e=Array.from(n).length;return e>=1&&e<=200?n:void 0}function L(n,e){return `pdx.${n}.${e}`}var ce="consent";function K(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e.identityLink;return typeof t=="boolean"?{identityLink:t}:null}catch{return null}}function Fe(n,e){return K(n.getItem(L(e,ce)))}function Te(n,e,t){let s=L(e,ce);if(typeof t.identityLink!="boolean"){n.removeItem(s);return}n.setItem(s,JSON.stringify({identityLink:t.identityLink}));}var C=class{constructor(e,t,s,r){this.storage=e;this.shared=t;this.ids=s;this.namespace=r;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");this.refresh();}refresh(){let e=q(this.shared.getItem(this.key("anonymous_id"))),t=q(this.storage.getItem(this.key("anonymous_id")));e?(this.anonymousId=e,t!==e&&this.storage.setItem(this.key("anonymous_id"),e)):t?(this.anonymousId=t,this.shared.setItem(this.key("anonymous_id"),t)):(this.anonymousId=this.ids.uuid(),this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId));let s=q(this.storage.getItem(this.key("distinct_id")));s?(this.distinctId=s,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}consent(){return Fe(this.shared,this.namespace)}setConsent(e){Te(this.shared,this.namespace,e);}identify(e){let t=!this.identified||this.distinctId!==e,s=this.storage.getItem(this.key("linked_anonymous_id")),r=t||s!==this.anonymousId;return this.distinctId=e,this.identified=true,t&&this.storage.setItem(this.key("distinct_id"),e),!r||this.consent()?.identityLink===false?{changed:t}:(this.storage.setItem(this.key("linked_anonymous_id"),this.anonymousId),{anonymousToLink:this.anonymousId,changed:t})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id")),this.storage.removeItem(this.key("linked_anonymous_id"));}key(e){return L(this.namespace,e)}};var F=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=y(e.fetch),this.host=h(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),s=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,r=await this.request(t,s,{headers:this.authHeaders(),method:"GET"});if(!r.ok)throw new c(`inbox request failed with status ${r.status}`,r.status);return JSON.parse(await r.text()).messages??[]}async markRead(e,t){let s=this.requireFetch(),r=`${this.host}/v1/messages/read`,i=await this.request(s,r,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new c(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new c("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,s){let r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...s,signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var T=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;o(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let t=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,t)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};var _e={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function Ae(n){return `pdx.${n}.session`}var _=class{constructor(e,t,s,r,i=_e){this.storage=e;this.ids=t;this.clock=s;this.namespace=r;this.options=i;}current(){return this.touch().id}startedAt(){return this.touch().startedAt}reset(){this.storage.removeItem(this.key());}touch(){let e=this.clock.now().getTime(),t=this.live(this.read(),e);if(t===void 0)return this.write({id:this.ids.uuid(),lastActivityAt:e,startedAt:e});if(e-t.lastActivityAt<=this.options.throttleMs)return t;let s=this.live(this.read(),e),r=s!==void 0&&s.id!==t.id?s:t;return this.write({...r,lastActivityAt:e})}live(e,t){if(e!==void 0&&!(t-e.lastActivityAt>this.options.idleMs||t-e.startedAt>this.options.maxMs))return e}write(e){return this.storage.setItem(this.key(),JSON.stringify(e)),e}read(){let e=this.storage.getItem(this.key());if(e)try{let t=JSON.parse(e);return typeof t.id=="string"&&typeof t.startedAt=="number"&&typeof t.lastActivityAt=="number"?{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt}:void 0}catch{return}}key(){return Ae(this.namespace)}};var d={createAlias:"$create_alias",featureFlagCalled:"$feature_flag_called",group:"$group",identify:"$identify",set:"$set"};function de(n){return n>=400&&n<500&&n!==429}var A=class{constructor(e={}){o(this,"fetch");o(this,"maxRetries");o(this,"requestTimeoutMs");o(this,"baseDelayMs");o(this,"maxDelayMs");o(this,"sleep");o(this,"random");this.fetch=y(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??V,this.random=e.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=JSON.stringify(e.body),r;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,s);if(a.ok)return;if(de(a.status))throw new c(`ingest rejected batch with status ${a.status}`,a.status);r=new c(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof c&&a.status!==void 0&&de(a.status))throw a;r=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new c("ingest delivery failed after retries",void 0,{cause:r})}async attempt(e,t,s){let r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:s,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},method:"POST",signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var Pe="queue",$e=1e3,le=3e4,D=n=>{let e={};return n.avatar!==void 0&&(e.$avatar=n.avatar),n.email!==void 0&&(e.$email=n.email),n.name!==void 0&&(e.$name=n.name),n.phone!==void 0&&(e.$phone=n.phone),e},P=class{constructor(e){o(this,"config");o(this,"identity");o(this,"session");o(this,"queue");o(this,"transport");o(this,"flagsClient");o(this,"messagesClient");o(this,"context");o(this,"flushTimer");o(this,"flushing",false);o(this,"cachedFlags");o(this,"cachedSnapshot");o(this,"membershipCache");o(this,"stream");o(this,"shutDown",false);o(this,"exposures",new Set);this.config=Q(e),this.identity=new C(this.config.storage,this.config.sharedStorage,this.config.ids,this.config.namespace),this.config.consent!==void 0&&this.identity.setConsent(this.config.consent),this.session=this.config.sessionTracking?new _(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new T(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new p("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new A({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new w({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new F({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}get isIdentified(){return this.identity.isIdentified()}get sessionId(){return this.session?.current()}get sessionStartedAt(){return this.session?.startedAt()}capture(e,t={}){try{this.identity.refresh();let s={...this.config.defaultProperties(),...t.properties??{}},r=W({context:this.context,distinctId:t.distinctId??this.identity.getDistinctId(),eventName:e,properties:s,sessionId:t.sessionId??this.session?.current(),timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(r);}catch(s){this.config.onError(s);}}identify(e,t={}){this.identity.refresh();let s=this.identity.identify(e),r={};s.anonymousToLink!==void 0&&(r.$anon_distinct_id=s.anonymousToLink);let i={...D(t.traits??{}),...t.set??{}};Object.keys(i).length>0&&(r.$set=i),this.capture(d.identify,{properties:r});}link(e,t,s){let r={$anon_distinct_id:t},i=D(s??{});Object.keys(i).length>0&&(r.$set=i),this.capture(d.identify,{distinctId:e,properties:r});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture(d.createAlias,{properties:{alias:e}});}group(e,t,s){let r={$group_key:t,$group_type:e};s&&(r.$set=s),this.capture(d.group,{properties:r});}setPersonProperties(e,t){let s={};e&&(s.$set=e),t&&(s.$set_once=t),this.capture(d.set,{properties:s});}setPersonTraits(e){let t=D(e);Object.keys(t).length!==0&&this.capture(d.set,{properties:{$set:t}});}async getAllFlags(){let e=this.identity.getDistinctId(),t=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:t.flags,variants:t.variants??{}},t.flags}async isFeatureEnabled(e){let s=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(s)),s}async getVariant(e){let t=await this.getAllFlags(),s=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,s?.key??String(t[e]??false)),s}async getVariantLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(he=>he.key===e),i=await this.localContext(t,s.flags),a=r?O(r,s.flags,i):null,l=r?S(r,s.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(l)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let s=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(s)||(this.exposures.add(s),this.capture(d.featureFlagCalled,{properties:{$feature_flag:e,$feature_flag_response:t}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let t=await this.flagSnapshot();return se(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(l=>l.key===e),i=await this.localContext(t,s.flags),a=r?S(r,s.flags,i).enabled:false;return this.recordExposure(e,(r?O(r,s.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let s=this.identity.getDistinctId(),r=e.cohorts;if(r===void 0&&re(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===s&&i-this.membershipCache.fetchedAt<le?r=this.membershipCache.cohorts:(r=await this.flagsClient.memberships(s),this.membershipCache={cohorts:r,distinctId:s,fetchedAt:i});}return {attributes:e.attributes,cohorts:r,distinctId:s,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<le)return this.cachedSnapshot.snapshot;let t=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:t},this.maybeStream(t),t}maybeStream(e){if(!this.config.streamFlags||this.shutDown||this.stream||!e.socketUrl)return;let t=new I({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(s=>this.config.onError(s));},onClosed:s=>{this.stream=void 0,s&&this.maybeStream(e);},projectKey:this.config.apiKey,socketFactory:this.config.socketFactory});this.stream=t,t.open();}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain($e);try{await this.transport.send({body:{events:e,sent_at:b(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(t){this.queue.requeue(e),this.persistQueue(),this.config.onError(t);}finally{this.flushing=false;}}reset(){this.session?.reset(),this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0,this.membershipCache=void 0;}async shutdown(){this.shutDown=true,this.stopTimer(),this.stream?.close(),this.stream=void 0,await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&this.queue.restore(t);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),t=e;typeof t.unref=="function"&&t.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${Pe}`}};var Ne=200;function ue(){return globalThis.process}function Re(n){ue()?.on("beforeExit",()=>{n.flush();});}function Yt(n){let e=ue(),t={...n,os:n.os??(e?.platform?e.platform.slice(0,50):void 0),streamFlags:n.streamFlags??true},s=new P(t);return Re(s),s}function Xt(n,e){let t=$(e),s=Oe(n,`pdx_${t}`);if(s===void 0)return null;let r=Me(s);if(r===void 0)return null;let i=pe(r[`pdx.${t}.anonymous_id`]);return i===void 0?null:{anonymousId:i,consent:K(r[`pdx.${t}.consent`]),sessionId:qe(r[`pdx.${t}.session`])}}function Oe(n,e){let t=`${e}=`;for(let s of n.split(";")){let r=s.trim();if(r.startsWith(t))return r.slice(t.length)}}function Me(n){try{let e=JSON.parse(decodeURIComponent(n));return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}function pe(n){if(typeof n!="string")return;let e=x(n);return e>=1&&e<=Ne?n:void 0}function qe(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);return e===null||typeof e!="object"||typeof e.startedAt!="number"||typeof e.lastActivityAt!="number"?null:pe(e.id)??null}catch{return null}}exports.createNodeClient=Yt;exports.readSharedIdentity=Xt;//# sourceMappingURL=node.cjs.map
|
|
1
|
+
'use strict';var fe=Object.defineProperty;var ge=(n,e,t)=>e in n?fe(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var o=(n,e,t)=>ge(n,typeof e!="symbol"?e+"":e,t);var p=class extends Error{constructor(t,s,r){super(s,r);o(this,"code");this.code=t,this.name="ProdantixError";}},v=class extends p{constructor(e){super("config",e),this.name="ConfigError";}},m=class extends p{constructor(t,s){super("validation",s);o(this,"field");this.field=t,this.name="ValidationError";}},c=class extends p{constructor(t,s,r){super("transport",t,r);o(this,"status");this.status=s,this.name="TransportError";}};function y(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function u(){let n=globalThis.AbortController;return n?new n:void 0}var V=n=>new Promise(e=>{setTimeout(e,n);});function h(n){return n.replace(/\/+$/,"")}var k=class{constructor(){o(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,t){this.store.set(e,t);}};var j={now:()=>new Date};function b(n){return n.toISOString()}function me(){return globalThis.crypto}function ye(n){n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=[];for(let t=0;t<16;t+=1)e.push(n[t].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function ve(){let n=me();if(n?.randomUUID)return n.randomUUID();let e=new Uint8Array(16);if(n?.getRandomValues)n.getRandomValues(e);else for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);return ye(e)}var G={uuid:ve};var ke=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var be=/^(?:\$|[a-z])[a-z0-9_.]*$/;function x(n){let e=0;for(let t of n)e+=1;return e}function J(n){return ke.test(n)}function xe(n){return be.test(n)}function H(n){let e=x(n);if(e<1||e>200)throw new m("distinct_id","distinct_id must be between 1 and 200 characters")}function U(n){let e=x(n);if(e<1||e>200)throw new m("event_name","event_name must be between 1 and 200 characters");if(!xe(n))throw new m("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var B="prodantix-js",z="0.0.1";var Ee=n=>{};function Q(n){if(!n.apiKey||!J(n.apiKey))throw new v("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!n.host)throw new v("host is required (the ingest base URL)");let e=h(n.host),t=n.defaultProperties,s=n.storage??new k;return {apiKey:n.apiKey,autocapture:n.autocapture??false,clock:n.clock??j,consent:n.consent,defaultProperties:typeof t=="function"?t:()=>t??{},flagsHost:n.flagsHost?h(n.flagsHost):e,flushAt:n.flushAt??20,flushIntervalMs:n.flushIntervalMs??1e4,host:e,ids:n.ids??G,locale:n.locale,maxQueueSize:n.maxQueueSize??1e3,maxRetries:n.maxRetries??3,namespace:$(n.apiKey),onError:n.onError??Ee,os:n.os,requestTimeoutMs:n.requestTimeoutMs??1e4,sdkName:n.sdkName??B,sdkVersion:n.sdkVersion??z,sessionTracking:n.sessionTracking??false,sharedStorage:n.sharedStorage??s,socketFactory:n.socketFactory,storage:s,streamFlags:n.streamFlags??false,transport:n.transport}}function $(n){return n.slice(0,16)}function W(n,e,t){U(n.eventName),H(n.distinctId);let s={distinct_id:n.distinctId,event_id:n.eventId??t.uuid(),event_name:n.eventName,properties:n.properties??{},schema_version:1,timestamp:b(n.timestamp??e.now())};return n.context&&(s.context=n.context),n.sessionId&&(s.session_id=n.sessionId),s}var g=Symbol("absent");function Se(n,e){if(n==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,n))return t[n];let s=e.attributes??{};return Object.prototype.hasOwnProperty.call(s,n)?s[n]:g}function f(n){return n===g?"undefined":String(n)}function Y(n){return n===g?Number.NaN:Number(n)}function X(n){return n!==g&&n!==null&&n!==""}function Z(n,e){if(!Array.isArray(e))return false;let t=f(n);return e.map(s=>String(s)).includes(t)}function ee(n,e){let t=Se(n.attribute,e),s=n.value;switch(n.op){case "is_set":return X(t);case "is_not_set":return !X(t);case "eq":return f(t)===f(s===void 0?g:s);case "neq":return f(t)!==f(s===void 0?g:s);case "contains":return f(t).includes(f(s===void 0?g:s));case "in":return Z(t,s);case "not_in":return Array.isArray(s)?!Z(t,s):false;case "gt":return E(t,s,(r,i)=>r>i);case "gte":return E(t,s,(r,i)=>r>=i);case "lt":return E(t,s,(r,i)=>r<i);case "lte":return E(t,s,(r,i)=>r<=i);case "in_cohort":return typeof s=="string"&&s!==""&&(e.cohorts??[]).includes(s);case "not_in_cohort":return typeof s=="string"&&s!==""&&!(e.cohorts??[]).includes(s);default:return false}}function E(n,e,t){let s=Y(n),r=e===void 0?Number.NaN:Y(e);return Number.isNaN(s)||Number.isNaN(r)?false:t(s,r)}function te(n,e){let t=`${n}:${e}`,s=2166136261;for(let r=0;r<t.length;r++)s^=t.charCodeAt(r),s=Math.imul(s,16777619);return (s>>>0)%100}function N(n,e){return n.targeting.length===0||n.targeting.every(t=>ee(t,e))}function ne(n,e){let t=te(n.key,e.distinctId),s=n.variations??[];if(s.length===0)return n.rolloutPercentage>=100||t<n.rolloutPercentage?"true":"false";let r=0;for(let i=s.length-1;i>=0;i--)if(r+=s[i].weight,t<r)return s[i].key;return s[0].key}function R(n,e,t,s){for(let r of n.prerequisites??[]){if(s.includes(r.flagKey))return false;let i=e.find(l=>l.key===r.flagKey);if(!i||!i.enabled)return false;s.push(i.key);let a=R(i,e,t,s)&&N(i,t)&&ne(i,t)===r.variationKey;if(s.pop(),!a)return false}return true}function S(n,e,t){return n.enabled?R(n,e,t,[n.key])?N(n,t)?n.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:te(n.key,t.distinctId)<n.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function se(n,e){let t={};for(let s of n)t[s.key]=S(s,n,e).enabled;return t}function O(n,e,t){let s=n.variations??[],r=s[0];if(!r)return null;if(!n.enabled||!R(n,e,t,[n.key])||!N(n,t))return r;let i=ne(n,t);return s.find(a=>a.key===i)??r}function re(n){return n.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}function ie(n){return `40${JSON.stringify(n)}`}function oe(){return "3"}function ae(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let a=M(t);return {kind:"open",pingInterval:typeof a?.pingInterval=="number"?a.pingInterval:25e3,pingTimeout:typeof a?.pingTimeout=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let s=t.charAt(0),r=t.slice(1);if(s==="0")return {kind:"connected"};if(s==="1")return {kind:"disconnect"};if(s==="4"){let a=M(r);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(s!=="2")return {kind:"other"};let i=M(r);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function M(n){try{return JSON.parse(n)}catch{return null}}var Ie="/socket.io/?EIO=4&transport=websocket",we=250,I=class{constructor(e){this.options=e;o(this,"socket",null);o(this,"heartbeat",null);o(this,"pending",null);o(this,"lastKey","");o(this,"ready",false);o(this,"closed",false);o(this,"heartbeatWindow",45e3);o(this,"factory");o(this,"setTimer");o(this,"clearTimer");this.factory=e.socketFactory??Ce,this.setTimer=e.setTimer??((t,s)=>setTimeout(t,s)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Ie}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=s=>this.receive(String(s.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat(),this.pending!==null&&this.clearTimer(this.pending),this.pending=null;let e=this.socket;this.socket=null,e?.close();}receive(e){let t=ae(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(ie({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(oe());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true;return}if(t.name==="flagChange"){let s=t.payload?.key;this.lastKey=typeof s=="string"?s:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},we));}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function Ce(n){let e=globalThis.WebSocket;if(!e)throw new c("no WebSocket");return new e(n)}var w=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=y(e.fetch),this.host=h(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new c(`flags request failed with status ${a.status}`,a.status);let l=JSON.parse(await a.text());return {flags:l.flags??{},variants:l.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new c("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,s=u(),r=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let i=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!i.ok)throw new c(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),l={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(l.socketUrl=a.socketUrl),l}finally{r!==void 0&&clearTimeout(r);}}async memberships(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new c(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};function q(n){if(typeof n!="string")return;let e=Array.from(n).length;return e>=1&&e<=200?n:void 0}function L(n,e){return `pdx.${n}.${e}`}var ce="consent";function K(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e.identityLink;return typeof t=="boolean"?{identityLink:t}:null}catch{return null}}function Fe(n,e){return K(n.getItem(L(e,ce)))}function Te(n,e,t){let s=L(e,ce);if(typeof t.identityLink!="boolean"){n.removeItem(s);return}n.setItem(s,JSON.stringify({identityLink:t.identityLink}));}var C=class{constructor(e,t,s,r){this.storage=e;this.shared=t;this.ids=s;this.namespace=r;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");this.refresh();}refresh(){let e=q(this.shared.getItem(this.key("anonymous_id"))),t=q(this.storage.getItem(this.key("anonymous_id")));e?(this.anonymousId=e,t!==e&&this.storage.setItem(this.key("anonymous_id"),e)):t?(this.anonymousId=t,this.shared.setItem(this.key("anonymous_id"),t)):(this.anonymousId=this.ids.uuid(),this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId));let s=q(this.storage.getItem(this.key("distinct_id")));s?(this.distinctId=s,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}consent(){return Fe(this.shared,this.namespace)}setConsent(e){Te(this.shared,this.namespace,e);}identify(e){let t=!this.identified||this.distinctId!==e,s=this.storage.getItem(this.key("linked_anonymous_id")),r=t||s!==this.anonymousId;return this.distinctId=e,this.identified=true,t&&this.storage.setItem(this.key("distinct_id"),e),!r||this.consent()?.identityLink===false?{changed:t}:(this.storage.setItem(this.key("linked_anonymous_id"),this.anonymousId),{anonymousToLink:this.anonymousId,changed:t})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id")),this.storage.removeItem(this.key("linked_anonymous_id"));}key(e){return L(this.namespace,e)}};var F=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=y(e.fetch),this.host=h(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),s=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,r=await this.request(t,s,{headers:this.authHeaders(),method:"GET"});if(!r.ok)throw new c(`inbox request failed with status ${r.status}`,r.status);return JSON.parse(await r.text()).messages??[]}async markRead(e,t){let s=this.requireFetch(),r=`${this.host}/v1/messages/read`,i=await this.request(s,r,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new c(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new c("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,s){let r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...s,signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var T=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;o(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let t=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,t)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};var _e={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function Ae(n){return `pdx.${n}.session`}var _=class{constructor(e,t,s,r,i=_e){this.storage=e;this.ids=t;this.clock=s;this.namespace=r;this.options=i;}current(){return this.touch().id}startedAt(){return this.touch().startedAt}reset(){this.storage.removeItem(this.key());}touch(){let e=this.clock.now().getTime(),t=this.live(this.read(),e);if(t===void 0)return this.write({id:this.ids.uuid(),lastActivityAt:e,startedAt:e});if(e-t.lastActivityAt<=this.options.throttleMs)return t;let s=this.live(this.read(),e),r=s!==void 0&&s.id!==t.id?s:t;return this.write({...r,lastActivityAt:e})}live(e,t){if(e!==void 0&&!(t-e.lastActivityAt>this.options.idleMs||t-e.startedAt>this.options.maxMs))return e}write(e){return this.storage.setItem(this.key(),JSON.stringify(e)),e}read(){let e=this.storage.getItem(this.key());if(e)try{let t=JSON.parse(e);return typeof t.id=="string"&&typeof t.startedAt=="number"&&typeof t.lastActivityAt=="number"?{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt}:void 0}catch{return}}key(){return Ae(this.namespace)}};var d={createAlias:"$create_alias",featureFlagCalled:"$feature_flag_called",group:"$group",identify:"$identify",set:"$set"};function de(n){return n>=400&&n<500&&n!==429}var A=class{constructor(e={}){o(this,"fetch");o(this,"maxRetries");o(this,"requestTimeoutMs");o(this,"baseDelayMs");o(this,"maxDelayMs");o(this,"sleep");o(this,"random");this.fetch=y(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??V,this.random=e.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=JSON.stringify(e.body),r;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,s);if(a.ok)return;if(de(a.status))throw new c(`ingest rejected batch with status ${a.status}`,a.status);r=new c(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof c&&a.status!==void 0&&de(a.status))throw a;r=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new c("ingest delivery failed after retries",void 0,{cause:r})}async attempt(e,t,s){let r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:s,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},method:"POST",signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var Pe="queue",$e=1e3,le=3e4,D=n=>{let e={};return n.avatar!==void 0&&(e.$avatar=n.avatar),n.email!==void 0&&(e.$email=n.email),n.name!==void 0&&(e.$name=n.name),n.phone!==void 0&&(e.$phone=n.phone),e},P=class{constructor(e){o(this,"config");o(this,"identity");o(this,"session");o(this,"queue");o(this,"transport");o(this,"flagsClient");o(this,"messagesClient");o(this,"context");o(this,"flushTimer");o(this,"flushing",false);o(this,"cachedFlags");o(this,"cachedSnapshot");o(this,"membershipCache");o(this,"stream");o(this,"shutDown",false);o(this,"exposures",new Set);this.config=Q(e),this.identity=new C(this.config.storage,this.config.sharedStorage,this.config.ids,this.config.namespace),this.config.consent!==void 0&&this.identity.setConsent(this.config.consent),this.session=this.config.sessionTracking?new _(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new T(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new p("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new A({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new w({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new F({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}get isIdentified(){return this.identity.isIdentified()}get sessionId(){return this.session?.current()}get sessionStartedAt(){return this.session?.startedAt()}capture(e,t={}){try{this.identity.refresh();let s={...this.config.defaultProperties(),...t.properties??{}},r=W({context:this.context,distinctId:t.distinctId??this.identity.getDistinctId(),eventName:e,properties:s,sessionId:t.sessionId??this.session?.current(),timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(r);}catch(s){this.config.onError(s);}}identify(e,t={}){this.identity.refresh();let s=this.identity.identify(e),r={};s.anonymousToLink!==void 0&&(r.$anon_distinct_id=s.anonymousToLink);let i={...D(t.traits??{}),...t.set??{}};Object.keys(i).length>0&&(r.$set=i),this.capture(d.identify,{properties:r});}link(e,t,s){let r={$anon_distinct_id:t},i=D(s??{});Object.keys(i).length>0&&(r.$set=i),this.capture(d.identify,{distinctId:e,properties:r});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture(d.createAlias,{properties:{alias:e}});}group(e,t,s){let r={$group_key:t,$group_type:e};s&&(r.$set=s),this.capture(d.group,{properties:r});}setPersonProperties(e,t){let s={};e&&(s.$set=e),t&&(s.$set_once=t),this.capture(d.set,{properties:s});}setPersonTraits(e){let t=D(e);Object.keys(t).length!==0&&this.capture(d.set,{properties:{$set:t}});}async getAllFlags(){let e=this.identity.getDistinctId(),t=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:t.flags,variants:t.variants??{}},t.flags}async isFeatureEnabled(e){let s=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(s)),s}async getVariant(e){let t=await this.getAllFlags(),s=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,s?.key??String(t[e]??false)),s}async getVariantLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(he=>he.key===e),i=await this.localContext(t,s.flags),a=r?O(r,s.flags,i):null,l=r?S(r,s.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(l)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let s=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(s)||(this.exposures.add(s),this.capture(d.featureFlagCalled,{properties:{$feature_flag:e,$feature_flag_response:t}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let t=await this.flagSnapshot();return se(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(l=>l.key===e),i=await this.localContext(t,s.flags),a=r?S(r,s.flags,i).enabled:false;return this.recordExposure(e,(r?O(r,s.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let s=this.identity.getDistinctId(),r=e.cohorts;if(r===void 0&&re(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===s&&i-this.membershipCache.fetchedAt<le?r=this.membershipCache.cohorts:(r=await this.flagsClient.memberships(s),this.membershipCache={cohorts:r,distinctId:s,fetchedAt:i});}return {attributes:e.attributes,cohorts:r,distinctId:s,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<le)return this.cachedSnapshot.snapshot;let t=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:t},this.maybeStream(t),t}maybeStream(e){if(!this.config.streamFlags||this.shutDown||this.stream||!e.socketUrl)return;let t=new I({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(s=>this.config.onError(s));},onClosed:s=>{this.stream=void 0,s&&this.maybeStream(e);},projectKey:this.config.apiKey,socketFactory:this.config.socketFactory});this.stream=t,t.open();}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain($e);try{await this.transport.send({body:{events:e,sent_at:b(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(t){this.queue.requeue(e),this.persistQueue(),this.config.onError(t);}finally{this.flushing=false;}}reset(){this.session?.reset(),this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0,this.membershipCache=void 0;}async shutdown(){this.shutDown=true,this.stopTimer(),this.stream?.close(),this.stream=void 0,await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&this.queue.restore(t);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),t=e;typeof t.unref=="function"&&t.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${Pe}`}};var Ne=200;function ue(){return globalThis.process}function Re(n){ue()?.on("beforeExit",()=>{n.flush();});}function Xt(n){let e=ue(),t={...n,os:n.os??(e?.platform?e.platform.slice(0,50):void 0),streamFlags:n.streamFlags??true},s=new P(t);return Re(s),s}function Zt(n,e){let t=$(e),s=Oe(n,`pdx_${t}`);if(s===void 0)return null;let r=Me(s);if(r===void 0)return null;let i=pe(r[`pdx.${t}.anonymous_id`]);return i===void 0?null:{anonymousId:i,consent:K(r[`pdx.${t}.consent`]),sessionId:qe(r[`pdx.${t}.session`])}}function Oe(n,e){let t=`${e}=`;for(let s of n.split(";")){let r=s.trim();if(r.startsWith(t))return r.slice(t.length)}}function Me(n){try{let e=JSON.parse(decodeURIComponent(n));return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}function pe(n){if(typeof n!="string")return;let e=x(n);return e>=1&&e<=Ne?n:void 0}function qe(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);return e===null||typeof e!="object"||typeof e.startedAt!="number"||typeof e.lastActivityAt!="number"?null:pe(e.id)??null}catch{return null}}exports.createNodeClient=Xt;exports.readSharedIdentity=Zt;//# sourceMappingURL=node.cjs.map
|
|
2
2
|
//# sourceMappingURL=node.cjs.map
|
package/dist/node.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {y as y$1,h as h$1,p as p$1,e}from'./chunk-4RLPQZ5L.js';import'./chunk-V77KYPOF.js';import'./chunk-ODN4ZELX.js';import'./chunk-5XGN7UAV.js';var a=200;function f(){return globalThis.process}function p(t){f()?.on("beforeExit",()=>{t.flush();});}function h(t){let n=f(),e={...t,os:t.os??(n?.platform?n.platform.slice(0,50):void 0),streamFlags:t.streamFlags??true},r=new y$1(e);return p(r),r}function w(t,n){let e=h$1(n),r=m(t,`pdx_${e}`);if(r===void 0)return null;let o=g(r);if(o===void 0)return null;let i=l(o[`pdx.${e}.anonymous_id`]);return i===void 0?null:{anonymousId:i,consent:p$1(o[`pdx.${e}.consent`]),sessionId:y(o[`pdx.${e}.session`])}}function m(t,n){let e=`${n}=`;for(let r of t.split(";")){let o=r.trim();if(o.startsWith(e))return o.slice(e.length)}}function g(t){try{let n=JSON.parse(decodeURIComponent(t));return n===null||typeof n!="object"||Array.isArray(n)?void 0:n}catch{return}}function l(t){if(typeof t!="string")return;let n=e(t);return n>=1&&n<=a?t:void 0}function y(t){if(typeof t!="string")return null;try{let n=JSON.parse(t);return n===null||typeof n!="object"||typeof n.startedAt!="number"||typeof n.lastActivityAt!="number"?null:l(n.id)??null}catch{return null}}export{h as createNodeClient,w as readSharedIdentity};//# sourceMappingURL=node.js.map
|
|
2
2
|
//# sourceMappingURL=node.js.map
|