@picked/client 0.0.47 → 0.0.48

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.
@@ -0,0 +1,32 @@
1
+ const i = "Picked-Client", a = "Picked-Version";
2
+ function u(n, t) {
3
+ return {
4
+ [i]: n,
5
+ [a]: t
6
+ };
7
+ }
8
+ const d = () => "0.0.48", E = "v1";
9
+ function s(n, t) {
10
+ return new URL(`/api/${E}/${t}`, n).toString();
11
+ }
12
+ function o(n) {
13
+ return { ...u("sdk", d()), ...n };
14
+ }
15
+ async function f(n, t, e) {
16
+ const r = s(n, t);
17
+ return fetch(r, { headers: o(e) });
18
+ }
19
+ async function p(n, t, e, r) {
20
+ const c = s(n, t);
21
+ return fetch(c, {
22
+ method: "POST",
23
+ headers: { "Content-Type": "application/json", ...o(r) },
24
+ body: JSON.stringify(e)
25
+ });
26
+ }
27
+ export {
28
+ f as a,
29
+ u as c,
30
+ d as g,
31
+ p
32
+ };
@@ -0,0 +1 @@
1
+ "use strict";const a="Picked-Client",d="Picked-Version";function s(e,t){return{[a]:e,[d]:t}}const o=()=>"0.0.48",E="v1";function c(e,t){return new URL(`/api/${E}/${t}`,e).toString()}function i(e){return{...s("sdk",o()),...e}}async function f(e,t,n){const r=c(e,t);return fetch(r,{headers:i(n)})}async function l(e,t,n,r){const u=c(e,t);return fetch(u,{method:"POST",headers:{"Content-Type":"application/json",...i(r)},body:JSON.stringify(n)})}exports.createClientHeaders=s;exports.get=f;exports.getVersion=o;exports.post=l;
package/dist/cjs/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("effector"),S=require("@withease/factories"),I=require("../experience-instance-BsXG5XJ4.cjs"),x=require("../logger-BsmHUUw1.cjs"),w=require("../storage-Be5xWNPC.cjs"),H=require("../api-DzSCgBQ2.cjs"),K=require("../id-BKIWbSTy.cjs"),G=require("../object-BbFTsGh3.cjs"),k=require("../supports-YvpQZxbh.cjs"),U=g.createDomain("experience"),W=S.createFactory(({client:t,experience:e})=>{const r=U.store(e),s=g.createApi(r,{merge(u,m){return{...u,...m.experience}}}),i=r.map(u=>({name:u.name,decisionLogic:u.condition??u.decide,targetSelectors:u.targets,initializeOpenLogic:e.initializeOpen})),d=t.components.listStore.map(u=>u.find(m=>m.name===`experience:${e.id}`)||u.find(m=>m.name==="experience"),{skipVoid:!1}),a=r.map(u=>({steps:u.steps,nodes:u.nodes,edges:u.edges,conditionals:u.conditionals})),n=r.map(u=>u.fields),p=e.actions??[];return{id:e.id,configStore:i,treeStore:a,fieldsStore:n,componentStore:d,actions:p,merge:s.merge}});function J(t){return S.invoke(W,t)}const Y=S.createFactory(({client:t})=>{const e=U.store({}),r=g.createApi(e,{register(u,m){return{...u,[m.id]:m}}});function s(u){const m=e.getState()[u.id];if(m){m.merge({experience:u,strategy:"override"});return}const b=J({client:t,experience:u});r.register(b)}const i=e.map(u=>Object.values(u));function d(u){return e.map(m=>m[u],{skipVoid:!1})}const a=d,n=g.attach({source:e,effect:async(u,{id:m,options:b})=>{const y=u[m];if(!y){x.logger("warn",`Experience with id '${m}' not found.`);return}if(b?.bypassCondition){C(t,y,b);return}await L(t,y)&&C(t,y,b)}}),p=g.attach({source:t.experienceInstances.listStore,effect:(u,{id:m,options:b})=>{const y=u.filter(o=>o.experienceId===m);if(y.length>0)for(const o of y)o.open();else n({id:m,options:{...b,initialiseOpen:!0}})}});return{register:s,get:d,getById:a,launch:n,open:p,listStore:i}});function Q(t){return S.invoke(Y,t)}const X=(t,e)=>{e.register(t)},C=(t,e,r)=>{const{targetSelectors:s}=e.configStore.getState(),i=I.getTargetElements(s,e.id);i.forEach(({elements:a})=>a.forEach(n=>I.tagTargetElement(n,e.id))),I.createAppHosts(i,e.id).forEach(a=>{r?t.experienceInstances.spawn(e,a,r):t.experienceInstances.spawn(e,a)})},z=async t=>{await Promise.all(t.experiences.listStore.getState().map(async e=>{await L(t,e)&&C(t,e)}))},L=async(t,e)=>{if(!t.session?.isUser)return!1;const{decisionLogic:r,targetSelectors:s}=e.configStore.getState();return I.getTargetElements(s,e.id).length<1||s.length===0?!1:r===void 0?!0:I.isRulesLogic(r)?await I.evaluateRuleLogic(t,r)===!0:!0},Z=(t,e,r)=>{const s=e.name,i=e.setup(t);if(i){const d=r[s]??{};r[s]=Object.freeze({...d,...i})}},ee=g.createDomain("component"),te=S.createFactory(({client:t,component:e,name:r})=>{const s=t.frameworks.getByName(e.frameworkName);return{name:r,component:e,frameworkStore:s}});function re(t){return S.invoke(te,t)}const se=S.createFactory(({client:t})=>{const e=ee.store({}),r=g.createApi(e,{register(a,n){return{...a,[n.name]:n}}});function s(a,n){e.getState()[a]&&x.logger("warn",`Component '${a}' already registered. Registering again will override the previous registration.`);const u=re({client:t,name:a,component:n});r.register(u)}const i=e.map(a=>Object.values(a));function d(a){return e.map(n=>n[a],{skipVoid:!1})}return{register:s,getByName:d,listStore:i}});function ne(t){return S.invoke(se,t)}const D=(t,e,r)=>{r.register(t,e)},ie=g.createDomain("framework"),oe=S.createFactory(({client:t})=>{const e=ie.store({}),r=g.createApi(e,{register(a,n){return{...a,[n.name]:n.framework}}});function s(a,n){e.getState()[a]&&x.logger("warn",`Framework '${a}' already registered. Registering again will override the previous registration.`),r.register({name:a,framework:n})}const i=e.map(a=>Object.values(a));function d(a){return e.map(n=>n[a],{skipVoid:!1})}return{register:s,getByName:d,listStore:i}});function ae(t){return S.invoke(oe,t)}const ce=(t,e)=>{e.register(t.name,t)},ue=6e3,le=w.createStorageKey("last_ping","global"),de=async t=>{try{const e=Date.now(),r=w.localStore.get(le);let s=0;if(r.isSet()&&(s=r.json()??0),s&&e-s<ue)return!0;const i={projectId:t.projectId,path:window.location.pathname},d={},n=document.getElementById("picked_script")?.dataset.verceltoken;n&&(d["x-vercel-protection-bypass"]=n);const u=(await H.post(t.apiUrl,"ping",i,d)).ok;return u&&r.set(e),u}catch(e){return x.logger("error",e),!1}};function V(t){const e=typeof window<"u",r={client:t,responses:t.responses.listStore.getState(),fields:t.fields.listStore.getState(),location:e?window.location:void 0,document:e?window.document:void 0,sessionStorage:e?window.sessionStorage:void 0,localStorage:e?window.localStorage:void 0};return Object.freeze(r)}const pe=g.createDomain("predicate"),fe=S.createFactory(({client:t})=>{const e=pe.store({}),r=g.createApi(e,{register(n,p){return{...n,[p.name]:{name:p.name,predicate:p.predicate}}}});function s(n,p){e.getState()[n]&&x.logger("warn",`Predicate '${n}' already registered. Registering again will override the previous registration.`),r.register(Object.freeze({name:n,predicate:p}))}const i=e.map(n=>Object.values(n));function d(n){return e.map(p=>p[n]?.predicate,{skipVoid:!1})}function a(n){const p=g.createStore(()=>{},{skipVoid:!1}),u=g.createEffect(async()=>{const m=d(n).getState();if(!m)return;const b=V(t);return(...y)=>m({...b,args:y})});return g.sample({source:{responses:t.responses.listStore,fields:t.fields.listStore},target:u}),g.sample({clock:u.doneData,filter:m=>m!==void 0,target:p}),u(),p}return{register:s,getByName:d,listStore:i,getEvokablePredicate:a}});function ge(t){return S.invoke(fe,t)}const me=(t,e,r)=>{r.register(t,e)},B=g.createDomain("feature"),ye=S.createFactory(({client:t})=>{const e=B.store({}),r=B.store([]),s=g.createApi(e,{register(o,c){return{...o,[c.id]:c.feature}}});function i(o,c){e.getState()[o]&&x.logger("warn",`Feature '${o}' already registered. Registering again will override the previous registration.`);const l={id:o,feature:{...c,id:o}};s.register(Object.freeze({id:o,feature:l}))}const d=g.createEffect(async({id:o,key:c,storage:f="local"})=>{const l=w.createStorageKey(`feature:${o}:${c}`,"global"),v=(f==="session"?w.sessionStore:w.localStore).get(l).boolean();return v===null?null:{id:o,key:c,bucket:v,storage:f}}),a=g.createEffect(o=>{if(!o)return null;const c=w.createStorageKey(`feature:${o.id}:${o.key}`,"global");(o.storage==="session"?w.sessionStore:w.localStore).set(c,o.bucket)}),n=new Map,p=g.attach({source:{allFeaturesStore:e,resolvedFeaturesStore:r},effect:async({allFeaturesStore:o,resolvedFeaturesStore:c},{id:f,decide:l,key:h})=>{const v=c.find(P=>P.id===f&&P.key===h);if(v)return v;const E=o[f];if(!E)throw new Error(`Feature with id '${f}' not found`);const A=n.get(`${f}:${h}`);if(A!==void 0){const P=await A;return{id:E.id,bucket:P,key:h,storage:E.feature.storage}}const F=l();n.set(`${f}:${h}`,F);const q=await F;return{id:E.id,bucket:q,key:h,storage:E.feature.storage}}});g.sample({clock:s.register,fn:o=>{const{id:c,feature:f}=o;return{id:c,key:f.feature.key,storage:f.feature.storage}},target:d}),g.sample({source:e,clock:p.doneData,fn:(o,c)=>{const{id:f,bucket:l,storage:h}=c,v=o[f]?.feature.key;return v?{key:v,id:f,bucket:l,storage:h}:null},target:a});const u=g.combine({allFeaturesStore:e,resolvedFeaturesStore:r}).map(({allFeaturesStore:o,resolvedFeaturesStore:c})=>Object.values(o).map(f=>{const l=c.find(h=>h.id===f.id&&h.key===f.feature.key);return l?{id:f.id,name:f.feature.name,key:f.feature.key,getBucket:()=>({id:f.id,bucket:l.bucket}),isResolved:!0}:{id:f.id,name:f.feature.name,key:f.feature.key,getBucket:async()=>await p(f.feature),isResolved:!1}}));g.sample({clock:p.doneData,source:{resolvedFeatures:r},filter:({resolvedFeatures:o},{id:c,key:f})=>!o.some(h=>h.id===c&&h.key===f),fn:(o,c)=>c,target:t.eventBus.prepend(o=>({type:"feature_decide",feature:o}))}),g.sample({clock:[d.doneData,p.doneData],source:r,fn:(o,c)=>!c||o.some(l=>l.id===c.id&&l.key===c.key)?o:[...o,c],target:r});function m(o){return u.map(c=>c.find(f=>f.id===o))}function b(o){return e.map(c=>c[o],{skipVoid:!1})}function y(o){const c=g.createStore(async()=>{},{skipVoid:!1}),f=g.createEffect(async()=>{const l=m(o).getState();if(l)return async()=>(await l.getBucket()).bucket});return g.sample({source:r,filter:l=>l.some(h=>h.id===o),target:f}),g.sample({clock:f.doneData,filter:l=>l!==void 0,target:c}),f(),c}return{register:i,getById:m,getByName:b,listStore:u,getEvokableFeature:y}});function he(t){return S.invoke(ye,t)}const Se=(t,e,r)=>{r.register(t,e)},j=g.createDomain("history");function O(t,e){return{id:K.generateId(`history-entry-${Date.now()}-${Math.random()}}`),node:e,at:Date.now(),experienceId:t}}const ve=S.createFactory(()=>{const t=j.store({entries:[]}),e=j.event(),r=j.event(),s=j.event(),i=j.event();t.on(e,(a,n)=>({entries:[...a.entries,O(n.experienceId,n.node)]})),t.on(r,(a,n)=>({entries:[...a.entries.slice(0,-1),O(n.experienceId,n.node)]})),t.on(i,(a,n)=>n);function d(a,n){const p={lastStepIndex:-1,secondLastStepIndex:-1};for(let u=a.length-1;u>=0;u--){const m=a[u],b=m?.node;if(!(!b||!I.isStepNode(b))&&!(n&&m?.experienceId!==n))if(p.lastStepIndex===-1)p.lastStepIndex=u;else{p.secondLastStepIndex=u;break}}return p}return t.on(s,(a,n)=>{const{secondLastStepIndex:p}=d(a.entries,n.experienceId),u=p!==-1?a.entries.slice(0,p+1):a.entries;return{...a,entries:u}}),{push:e,replace:r,back:s,restore:i,entriesStore:t.map(a=>a.entries)}});function ke(){return S.invoke(ve)}let we=0;const be=t=>{const e=g.createStore([]);return g.sample({clock:t,source:e,fn:(r,s)=>[...r,{id:we++,at:new Date,payload:s}],target:e}),e},Ie=g.createDomain("field"),Fe=S.createFactory(()=>{const t=Ie.store({}),e=g.createApi(t,{register(n,p){return{...n,[p.field.id]:p.field}}});function r(n){e.register({field:n})}function s(n,p){const u=d(n).getState();if(!u)return;const m=Object.assign({},u,{...p});e.register({field:{...m}})}const i=t.map(n=>Object.values(n));function d(n){return t.map(p=>p[n]||null)}function a(n){return t.map(p=>Object.values(p).find(u=>u.name===n)||null)}return{register:r,update:s,getById:d,listStore:i,getByName:a}});function xe(){return S.invoke(Fe)}const Ee=(t,e)=>{e.register(t)},je=g.createDomain("action"),Ae=S.createFactory(()=>{const t=je.store({}),e=g.createApi(t,{register(a,n){return{...a,[n.name]:{name:n.name,action:n.action}}}});function r(a,n){e.register({name:a,action:n})}const s=t.map(a=>Object.values(a));function i(a){return t.map(n=>n[a],{skipVoid:!1})}function d(a){return t.map(n=>{const p=n[a];return p?p.action:void 0},{skipVoid:!1})}return{register:r,getByName:i,listStore:s,getEvokableAction:d}});function Pe(){return S.invoke(Ae)}const Re=(t,e,r)=>{r.register(t,e)};function $(t){return typeof t>"u"||t===null||t===""||Array.isArray(t)&&!t.length}function $e(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t===null}function M(t){try{return JSON.stringify(t),!0}catch{return!1}}const Ce=g.createDomain("response"),ze=S.createFactory(({client:t})=>{const e=Ce.store({}),r=g.createEvent(),s=g.createEvent(),i=g.createApi(e,{register(y,o){return{...y,[o.fieldId]:o.response}},registerBatch(y,o){return{...y,...o}},clear(y,o){const{[o]:c,...f}=y;return f},clearAll(){return{}}});function d(y,o){if(typeof y=="string"){if(o===void 0)throw new Error("Response is required when registering a single field");i.register({fieldId:y,response:o})}else i.registerBatch(y)}async function a(y){const o=[];return await Promise.allSettled(Object.entries(y).map(async([c,f])=>{let l=f;const h=t.fields.getById(c).getState();if(!h){o.push({fieldId:c,userMessage:`Field '${c}' not found`,systemMessage:`No field with ID '${c}' exists. Available field IDs are: ${Object.keys(t.fields.listStore.getState()).join(",")}.`,value:l});return}if(h.multiple&&(typeof l=="string"||typeof l=="number"||typeof l=="boolean")&&(l=[l]),h.validation&&!G.isEmpty(h.validation)&&!$(l)){const v=await I.evaluateRuleLogic(t,h.validation,{$input:l});if(typeof v=="string"){o.push({fieldId:c,userMessage:v,systemMessage:`Field validation resulted in an error: ${v}.`,value:l});return}if(v===!1){o.push({fieldId:c,userMessage:"This field is invalid",systemMessage:"Field validation resulted in an unspecified error.",value:l});return}}if(h.required&&$(l)){o.push({fieldId:c,userMessage:"This field is required",systemMessage:"Field is required.",value:l});return}if(!h.multiple&&Array.isArray(l)&&l.length>1){o.push({fieldId:c,userMessage:"This field expects a single response",systemMessage:"Field expects a single response.",value:l});return}if(h.type==="object"&&!$(l))if(h.multiple){if(!Array.isArray(l)){o.push({fieldId:c,userMessage:"This field expects multiple values",systemMessage:"Field expects an array of objects.",value:l});return}for(const v of l){if(typeof v!="object"||v===null){o.push({fieldId:c,userMessage:"This field expects object values",systemMessage:"Field expects an array of objects, but received non-object value.",value:l});return}if(!M(v)){o.push({fieldId:c,userMessage:"This field contains non-serializable data",systemMessage:"Field value contains non-JSON-serializable data (functions, circular references, etc.).",value:l});return}}}else{if(Array.isArray(l)){o.push({fieldId:c,userMessage:"This field expects a single value",systemMessage:"Field expects a single object, not an array.",value:l});return}if(typeof l!="object"||l===null){o.push({fieldId:c,userMessage:"This field expects an object value",systemMessage:"Field expects an object value.",value:l});return}if(!M(l)){o.push({fieldId:c,userMessage:"This field contains non-serializable data",systemMessage:"Field value contains non-JSON-serializable data (functions, circular references, etc.).",value:l});return}}if(Array.isArray(h.options)&&h.options.length>0){const v=Array.isArray(l)?l:[l];if(h.type==="object"){const E=h.options.map(F=>JSON.stringify(F.value));v.every(F=>E.includes(JSON.stringify(F)))||o.push({fieldId:c,userMessage:"This field expects a valid option",systemMessage:"Field expects a valid option from the defined choices.",value:l})}else{const E=h.options.map(F=>F.value);v.every(F=>!$e(F)||F===null?!1:E.includes(F))||o.push({fieldId:c,userMessage:"This field expects a valid option",systemMessage:`Field expects a valid option. Valid options are: ${E.join(", ")}`,value:l})}}})),{responsesToCommit:y,validationErrors:o}}async function n(y){const{responsesToCommit:o,validationErrors:c}=await a(y);return c.length?{errors:c}:(i.registerBatch(o),{errors:[]})}const p=e.map(y=>y),u=e.map(y=>Object.keys(y).map(c=>({fieldId:c,value:y[c]})));function m(y){const o=t.fields.getById(y),c=e.map(f=>f[y]||null);return g.combine({f:o,r:c},({f,r:l})=>l||(f?.defaultValue?f.defaultValue:null))}function b(y){const o=t.fields.getByName(y);return g.combine({f:o,s:e},({f:c,s:f})=>{const l=c&&f[c.id]||null;return l||(c?.defaultValue?c.defaultValue:null)})}return g.sample({clock:r,target:i.clearAll}),g.sample({clock:s,target:i.clear}),{register:d,clearAll:r,clear:s,commit:n,getResponsesToCommit:a,listStore:u,getAllStore:p,getByFieldId:m,getByFieldName:b}});function De(t){return S.invoke(ze,t)}const Be=()=>"0.0.47";function Oe(){if(k.supportsDocument()){const t=[document.currentScript,document.getElementById("picked_script"),document.getElementById("picked"),document.getElementById("cvly"),document.getElementById("cvly-x")];for(const e of t)if(e?.dataset.api)return e.dataset.api}return"https://api.picked.app"}function Me(){if(!k.supportsWindow())return{};const t=new URLSearchParams(window.location.search),e={},r=new Set;for(const[i]of t.entries())i.startsWith("picked-")&&r.add(i);for(const i of r){const d=i.replace("picked-","");e[d]=t.getAll(i)}const s=w.createStorageKey("s");if(r.size>0)w.sessionStore.set(s,e);else{const i=w.sessionStore.get(s);if(i)return i.json()||{}}return e}function Ue(){if(k.supportsCryptoRandomUUID())return crypto.randomUUID();const t=Date.now().toString(36),e=Math.random().toString(36).substring(2,15),r=Math.random().toString(36).substring(2,15),s=Math.random().toString(36).substring(2,15);return`${t}-${e}-${r}-${s}`}const Le=w.createStorageKey("session","global"),Ve=()=>{const t=w.localStore.get(Le);let e;t.isSet()&&(e=t.json());const r=i=>t.set({id:i.id,isUser:i.isUser,identifiers:i.identifiers}),s={id:e?.id??Ue(),isUser:e?.isUser??void 0,identifiers:e?.identifiers??void 0,setIsUser(i){this.isUser=i,r(this)},setIdentifier(i,d){this.identifiers={...this.identifiers,[i]:d},r(this)},removeIdentifier(i){this.identifiers&&(this.identifiers=Object.fromEntries(Object.entries(this.identifiers).filter(([d])=>d!==i)),this.identifiers=Object.keys(this.identifiers).length?this.identifiers:void 0,r(this))}};return r(s),s},Te=()=>k.supportsLocalStorage()?Ve():null;function T(){if(k.supportsWindow())return globalThis.window.pickedConfig}function Ne(){if(!k.supportsWindow())return;const t=T(),e=t?.organizationId,r=t?.projectId;return e&&r?{organizationId:e,projectId:r}:void 0}function _e(){if(!k.supportsDocument())return;const t=document.getElementById("picked_script")||document.querySelector("script#picked")||document.getElementById("cvly");if(!t)return;const e=t.dataset.organizationid||t.getAttribute("organization-id"),r=t.dataset.projectid||t.getAttribute("project-id");return e&&r?{organizationId:e,projectId:r}:void 0}function qe(t){const{organizationId:e,projectId:r}=t;if(e&&r)return{organizationId:e,projectId:r};const s=Ne();if(s)return s;const i=_e();if(i)return i;throw new Error(`organizationId and projectId are required. You can provide them via one of:
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("effector"),S=require("@withease/factories"),I=require("../experience-instance-BsXG5XJ4.cjs"),x=require("../logger-BsmHUUw1.cjs"),w=require("../storage-Be5xWNPC.cjs"),U=require("../api-CbpxV_xX.cjs"),K=require("../id-BKIWbSTy.cjs"),G=require("../object-BbFTsGh3.cjs"),k=require("../supports-YvpQZxbh.cjs"),L=g.createDomain("experience"),W=S.createFactory(({client:t,experience:e})=>{const r=L.store(e),s=g.createApi(r,{merge(u,m){return{...u,...m.experience}}}),i=r.map(u=>({name:u.name,decisionLogic:u.condition??u.decide,targetSelectors:u.targets,initializeOpenLogic:e.initializeOpen})),d=t.components.listStore.map(u=>u.find(m=>m.name===`experience:${e.id}`)||u.find(m=>m.name==="experience"),{skipVoid:!1}),a=r.map(u=>({steps:u.steps,nodes:u.nodes,edges:u.edges,conditionals:u.conditionals})),n=r.map(u=>u.fields),p=e.actions??[];return{id:e.id,configStore:i,treeStore:a,fieldsStore:n,componentStore:d,actions:p,merge:s.merge}});function J(t){return S.invoke(W,t)}const Y=S.createFactory(({client:t})=>{const e=L.store({}),r=g.createApi(e,{register(u,m){return{...u,[m.id]:m}}});function s(u){const m=e.getState()[u.id];if(m){m.merge({experience:u,strategy:"override"});return}const b=J({client:t,experience:u});r.register(b)}const i=e.map(u=>Object.values(u));function d(u){return e.map(m=>m[u],{skipVoid:!1})}const a=d,n=g.attach({source:e,effect:async(u,{id:m,options:b})=>{const y=u[m];if(!y){x.logger("warn",`Experience with id '${m}' not found.`);return}if(b?.bypassCondition){C(t,y,b);return}await V(t,y)&&C(t,y,b)}}),p=g.attach({source:t.experienceInstances.listStore,effect:(u,{id:m,options:b})=>{const y=u.filter(o=>o.experienceId===m);if(y.length>0)for(const o of y)o.open();else n({id:m,options:{...b,initialiseOpen:!0}})}});return{register:s,get:d,getById:a,launch:n,open:p,listStore:i}});function Q(t){return S.invoke(Y,t)}const X=(t,e)=>{e.register(t)},C=(t,e,r)=>{const{targetSelectors:s}=e.configStore.getState(),i=I.getTargetElements(s,e.id);i.forEach(({elements:a})=>a.forEach(n=>I.tagTargetElement(n,e.id))),I.createAppHosts(i,e.id).forEach(a=>{r?t.experienceInstances.spawn(e,a,r):t.experienceInstances.spawn(e,a)})},z=async t=>{await Promise.all(t.experiences.listStore.getState().map(async e=>{await V(t,e)&&C(t,e)}))},V=async(t,e)=>{if(!t.session?.isUser)return!1;const{decisionLogic:r,targetSelectors:s}=e.configStore.getState();return I.getTargetElements(s,e.id).length<1||s.length===0?!1:r===void 0?!0:I.isRulesLogic(r)?await I.evaluateRuleLogic(t,r)===!0:!0},Z=(t,e,r)=>{const s=e.name,i=e.setup(t);if(i){const d=r[s]??{};r[s]=Object.freeze({...d,...i})}},ee=g.createDomain("component"),te=S.createFactory(({client:t,component:e,name:r})=>{const s=t.frameworks.getByName(e.frameworkName);return{name:r,component:e,frameworkStore:s}});function re(t){return S.invoke(te,t)}const se=S.createFactory(({client:t})=>{const e=ee.store({}),r=g.createApi(e,{register(a,n){return{...a,[n.name]:n}}});function s(a,n){e.getState()[a]&&x.logger("warn",`Component '${a}' already registered. Registering again will override the previous registration.`);const u=re({client:t,name:a,component:n});r.register(u)}const i=e.map(a=>Object.values(a));function d(a){return e.map(n=>n[a],{skipVoid:!1})}return{register:s,getByName:d,listStore:i}});function ne(t){return S.invoke(se,t)}const D=(t,e,r)=>{r.register(t,e)},ie=g.createDomain("framework"),oe=S.createFactory(({client:t})=>{const e=ie.store({}),r=g.createApi(e,{register(a,n){return{...a,[n.name]:n.framework}}});function s(a,n){e.getState()[a]&&x.logger("warn",`Framework '${a}' already registered. Registering again will override the previous registration.`),r.register({name:a,framework:n})}const i=e.map(a=>Object.values(a));function d(a){return e.map(n=>n[a],{skipVoid:!1})}return{register:s,getByName:d,listStore:i}});function ae(t){return S.invoke(oe,t)}const ce=(t,e)=>{e.register(t.name,t)},ue=6e3,le=w.createStorageKey("last_ping","global"),de=async t=>{try{const e=Date.now(),r=w.localStore.get(le);let s=0;if(r.isSet()&&(s=r.json()??0),s&&e-s<ue)return!0;const i={projectId:t.projectId,path:window.location.pathname},d={},n=document.getElementById("picked_script")?.dataset.verceltoken;n&&(d["x-vercel-protection-bypass"]=n);const u=(await U.post(t.apiUrl,"ping",i,d)).ok;return u&&r.set(e),u}catch(e){return x.logger("error",e),!1}};function T(t){const e=typeof window<"u",r={client:t,responses:t.responses.listStore.getState(),fields:t.fields.listStore.getState(),location:e?window.location:void 0,document:e?window.document:void 0,sessionStorage:e?window.sessionStorage:void 0,localStorage:e?window.localStorage:void 0};return Object.freeze(r)}const pe=g.createDomain("predicate"),fe=S.createFactory(({client:t})=>{const e=pe.store({}),r=g.createApi(e,{register(n,p){return{...n,[p.name]:{name:p.name,predicate:p.predicate}}}});function s(n,p){e.getState()[n]&&x.logger("warn",`Predicate '${n}' already registered. Registering again will override the previous registration.`),r.register(Object.freeze({name:n,predicate:p}))}const i=e.map(n=>Object.values(n));function d(n){return e.map(p=>p[n]?.predicate,{skipVoid:!1})}function a(n){const p=g.createStore(()=>{},{skipVoid:!1}),u=g.createEffect(async()=>{const m=d(n).getState();if(!m)return;const b=T(t);return(...y)=>m({...b,args:y})});return g.sample({source:{responses:t.responses.listStore,fields:t.fields.listStore},target:u}),g.sample({clock:u.doneData,filter:m=>m!==void 0,target:p}),u(),p}return{register:s,getByName:d,listStore:i,getEvokablePredicate:a}});function ge(t){return S.invoke(fe,t)}const me=(t,e,r)=>{r.register(t,e)},B=g.createDomain("feature"),ye=S.createFactory(({client:t})=>{const e=B.store({}),r=B.store([]),s=g.createApi(e,{register(o,c){return{...o,[c.id]:c.feature}}});function i(o,c){e.getState()[o]&&x.logger("warn",`Feature '${o}' already registered. Registering again will override the previous registration.`);const l={id:o,feature:{...c,id:o}};s.register(Object.freeze({id:o,feature:l}))}const d=g.createEffect(async({id:o,key:c,storage:f="local"})=>{const l=w.createStorageKey(`feature:${o}:${c}`,"global"),v=(f==="session"?w.sessionStore:w.localStore).get(l).boolean();return v===null?null:{id:o,key:c,bucket:v,storage:f}}),a=g.createEffect(o=>{if(!o)return null;const c=w.createStorageKey(`feature:${o.id}:${o.key}`,"global");(o.storage==="session"?w.sessionStore:w.localStore).set(c,o.bucket)}),n=new Map,p=g.attach({source:{allFeaturesStore:e,resolvedFeaturesStore:r},effect:async({allFeaturesStore:o,resolvedFeaturesStore:c},{id:f,decide:l,key:h})=>{const v=c.find(P=>P.id===f&&P.key===h);if(v)return v;const E=o[f];if(!E)throw new Error(`Feature with id '${f}' not found`);const A=n.get(`${f}:${h}`);if(A!==void 0){const P=await A;return{id:E.id,bucket:P,key:h,storage:E.feature.storage}}const F=l();n.set(`${f}:${h}`,F);const H=await F;return{id:E.id,bucket:H,key:h,storage:E.feature.storage}}});g.sample({clock:s.register,fn:o=>{const{id:c,feature:f}=o;return{id:c,key:f.feature.key,storage:f.feature.storage}},target:d}),g.sample({source:e,clock:p.doneData,fn:(o,c)=>{const{id:f,bucket:l,storage:h}=c,v=o[f]?.feature.key;return v?{key:v,id:f,bucket:l,storage:h}:null},target:a});const u=g.combine({allFeaturesStore:e,resolvedFeaturesStore:r}).map(({allFeaturesStore:o,resolvedFeaturesStore:c})=>Object.values(o).map(f=>{const l=c.find(h=>h.id===f.id&&h.key===f.feature.key);return l?{id:f.id,name:f.feature.name,key:f.feature.key,getBucket:()=>({id:f.id,bucket:l.bucket}),isResolved:!0}:{id:f.id,name:f.feature.name,key:f.feature.key,getBucket:async()=>await p(f.feature),isResolved:!1}}));g.sample({clock:p.doneData,source:{resolvedFeatures:r},filter:({resolvedFeatures:o},{id:c,key:f})=>!o.some(h=>h.id===c&&h.key===f),fn:(o,c)=>c,target:t.eventBus.prepend(o=>({type:"feature_decide",feature:o}))}),g.sample({clock:[d.doneData,p.doneData],source:r,fn:(o,c)=>!c||o.some(l=>l.id===c.id&&l.key===c.key)?o:[...o,c],target:r});function m(o){return u.map(c=>c.find(f=>f.id===o))}function b(o){return e.map(c=>c[o],{skipVoid:!1})}function y(o){const c=g.createStore(async()=>{},{skipVoid:!1}),f=g.createEffect(async()=>{const l=m(o).getState();if(l)return async()=>(await l.getBucket()).bucket});return g.sample({source:r,filter:l=>l.some(h=>h.id===o),target:f}),g.sample({clock:f.doneData,filter:l=>l!==void 0,target:c}),f(),c}return{register:i,getById:m,getByName:b,listStore:u,getEvokableFeature:y}});function he(t){return S.invoke(ye,t)}const Se=(t,e,r)=>{r.register(t,e)},j=g.createDomain("history");function O(t,e){return{id:K.generateId(`history-entry-${Date.now()}-${Math.random()}}`),node:e,at:Date.now(),experienceId:t}}const ve=S.createFactory(()=>{const t=j.store({entries:[]}),e=j.event(),r=j.event(),s=j.event(),i=j.event();t.on(e,(a,n)=>({entries:[...a.entries,O(n.experienceId,n.node)]})),t.on(r,(a,n)=>({entries:[...a.entries.slice(0,-1),O(n.experienceId,n.node)]})),t.on(i,(a,n)=>n);function d(a,n){const p={lastStepIndex:-1,secondLastStepIndex:-1};for(let u=a.length-1;u>=0;u--){const m=a[u],b=m?.node;if(!(!b||!I.isStepNode(b))&&!(n&&m?.experienceId!==n))if(p.lastStepIndex===-1)p.lastStepIndex=u;else{p.secondLastStepIndex=u;break}}return p}return t.on(s,(a,n)=>{const{secondLastStepIndex:p}=d(a.entries,n.experienceId),u=p!==-1?a.entries.slice(0,p+1):a.entries;return{...a,entries:u}}),{push:e,replace:r,back:s,restore:i,entriesStore:t.map(a=>a.entries)}});function ke(){return S.invoke(ve)}let we=0;const be=t=>{const e=g.createStore([]);return g.sample({clock:t,source:e,fn:(r,s)=>[...r,{id:we++,at:new Date,payload:s}],target:e}),e},Ie=g.createDomain("field"),Fe=S.createFactory(()=>{const t=Ie.store({}),e=g.createApi(t,{register(n,p){return{...n,[p.field.id]:p.field}}});function r(n){e.register({field:n})}function s(n,p){const u=d(n).getState();if(!u)return;const m=Object.assign({},u,{...p});e.register({field:{...m}})}const i=t.map(n=>Object.values(n));function d(n){return t.map(p=>p[n]||null)}function a(n){return t.map(p=>Object.values(p).find(u=>u.name===n)||null)}return{register:r,update:s,getById:d,listStore:i,getByName:a}});function xe(){return S.invoke(Fe)}const Ee=(t,e)=>{e.register(t)},je=g.createDomain("action"),Ae=S.createFactory(()=>{const t=je.store({}),e=g.createApi(t,{register(a,n){return{...a,[n.name]:{name:n.name,action:n.action}}}});function r(a,n){e.register({name:a,action:n})}const s=t.map(a=>Object.values(a));function i(a){return t.map(n=>n[a],{skipVoid:!1})}function d(a){return t.map(n=>{const p=n[a];return p?p.action:void 0},{skipVoid:!1})}return{register:r,getByName:i,listStore:s,getEvokableAction:d}});function Pe(){return S.invoke(Ae)}const Re=(t,e,r)=>{r.register(t,e)};function $(t){return typeof t>"u"||t===null||t===""||Array.isArray(t)&&!t.length}function $e(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t===null}function M(t){try{return JSON.stringify(t),!0}catch{return!1}}const Ce=g.createDomain("response"),ze=S.createFactory(({client:t})=>{const e=Ce.store({}),r=g.createEvent(),s=g.createEvent(),i=g.createApi(e,{register(y,o){return{...y,[o.fieldId]:o.response}},registerBatch(y,o){return{...y,...o}},clear(y,o){const{[o]:c,...f}=y;return f},clearAll(){return{}}});function d(y,o){if(typeof y=="string"){if(o===void 0)throw new Error("Response is required when registering a single field");i.register({fieldId:y,response:o})}else i.registerBatch(y)}async function a(y){const o=[];return await Promise.allSettled(Object.entries(y).map(async([c,f])=>{let l=f;const h=t.fields.getById(c).getState();if(!h){o.push({fieldId:c,userMessage:`Field '${c}' not found`,systemMessage:`No field with ID '${c}' exists. Available field IDs are: ${Object.keys(t.fields.listStore.getState()).join(",")}.`,value:l});return}if(h.multiple&&(typeof l=="string"||typeof l=="number"||typeof l=="boolean")&&(l=[l]),h.validation&&!G.isEmpty(h.validation)&&!$(l)){const v=await I.evaluateRuleLogic(t,h.validation,{$input:l});if(typeof v=="string"){o.push({fieldId:c,userMessage:v,systemMessage:`Field validation resulted in an error: ${v}.`,value:l});return}if(v===!1){o.push({fieldId:c,userMessage:"This field is invalid",systemMessage:"Field validation resulted in an unspecified error.",value:l});return}}if(h.required&&$(l)){o.push({fieldId:c,userMessage:"This field is required",systemMessage:"Field is required.",value:l});return}if(!h.multiple&&Array.isArray(l)&&l.length>1){o.push({fieldId:c,userMessage:"This field expects a single response",systemMessage:"Field expects a single response.",value:l});return}if(h.type==="object"&&!$(l))if(h.multiple){if(!Array.isArray(l)){o.push({fieldId:c,userMessage:"This field expects multiple values",systemMessage:"Field expects an array of objects.",value:l});return}for(const v of l){if(typeof v!="object"||v===null){o.push({fieldId:c,userMessage:"This field expects object values",systemMessage:"Field expects an array of objects, but received non-object value.",value:l});return}if(!M(v)){o.push({fieldId:c,userMessage:"This field contains non-serializable data",systemMessage:"Field value contains non-JSON-serializable data (functions, circular references, etc.).",value:l});return}}}else{if(Array.isArray(l)){o.push({fieldId:c,userMessage:"This field expects a single value",systemMessage:"Field expects a single object, not an array.",value:l});return}if(typeof l!="object"||l===null){o.push({fieldId:c,userMessage:"This field expects an object value",systemMessage:"Field expects an object value.",value:l});return}if(!M(l)){o.push({fieldId:c,userMessage:"This field contains non-serializable data",systemMessage:"Field value contains non-JSON-serializable data (functions, circular references, etc.).",value:l});return}}if(Array.isArray(h.options)&&h.options.length>0){const v=Array.isArray(l)?l:[l];if(h.type==="object"){const E=h.options.map(F=>JSON.stringify(F.value));v.every(F=>E.includes(JSON.stringify(F)))||o.push({fieldId:c,userMessage:"This field expects a valid option",systemMessage:"Field expects a valid option from the defined choices.",value:l})}else{const E=h.options.map(F=>F.value);v.every(F=>!$e(F)||F===null?!1:E.includes(F))||o.push({fieldId:c,userMessage:"This field expects a valid option",systemMessage:`Field expects a valid option. Valid options are: ${E.join(", ")}`,value:l})}}})),{responsesToCommit:y,validationErrors:o}}async function n(y){const{responsesToCommit:o,validationErrors:c}=await a(y);return c.length?{errors:c}:(i.registerBatch(o),{errors:[]})}const p=e.map(y=>y),u=e.map(y=>Object.keys(y).map(c=>({fieldId:c,value:y[c]})));function m(y){const o=t.fields.getById(y),c=e.map(f=>f[y]||null);return g.combine({f:o,r:c},({f,r:l})=>l||(f?.defaultValue?f.defaultValue:null))}function b(y){const o=t.fields.getByName(y);return g.combine({f:o,s:e},({f:c,s:f})=>{const l=c&&f[c.id]||null;return l||(c?.defaultValue?c.defaultValue:null)})}return g.sample({clock:r,target:i.clearAll}),g.sample({clock:s,target:i.clear}),{register:d,clearAll:r,clear:s,commit:n,getResponsesToCommit:a,listStore:u,getAllStore:p,getByFieldId:m,getByFieldName:b}});function De(t){return S.invoke(ze,t)}function Be(){if(k.supportsDocument()){const t=[document.currentScript,document.getElementById("picked_script"),document.getElementById("picked"),document.getElementById("cvly"),document.getElementById("cvly-x")];for(const e of t)if(e?.dataset.api)return e.dataset.api}return"https://api.picked.app"}function Oe(){if(!k.supportsWindow())return{};const t=new URLSearchParams(window.location.search),e={},r=new Set;for(const[i]of t.entries())i.startsWith("picked-")&&r.add(i);for(const i of r){const d=i.replace("picked-","");e[d]=t.getAll(i)}const s=w.createStorageKey("s");if(r.size>0)w.sessionStore.set(s,e);else{const i=w.sessionStore.get(s);if(i)return i.json()||{}}return e}function Me(){if(k.supportsCryptoRandomUUID())return crypto.randomUUID();const t=Date.now().toString(36),e=Math.random().toString(36).substring(2,15),r=Math.random().toString(36).substring(2,15),s=Math.random().toString(36).substring(2,15);return`${t}-${e}-${r}-${s}`}const Ue=w.createStorageKey("session","global"),Le=()=>{const t=w.localStore.get(Ue);let e;t.isSet()&&(e=t.json());const r=i=>t.set({id:i.id,isUser:i.isUser,identifiers:i.identifiers}),s={id:e?.id??Me(),isUser:e?.isUser??void 0,identifiers:e?.identifiers??void 0,setIsUser(i){this.isUser=i,r(this)},setIdentifier(i,d){this.identifiers={...this.identifiers,[i]:d},r(this)},removeIdentifier(i){this.identifiers&&(this.identifiers=Object.fromEntries(Object.entries(this.identifiers).filter(([d])=>d!==i)),this.identifiers=Object.keys(this.identifiers).length?this.identifiers:void 0,r(this))}};return r(s),s},Ve=()=>k.supportsLocalStorage()?Le():null;function N(){if(k.supportsWindow())return globalThis.window.pickedConfig}function Te(){if(!k.supportsWindow())return;const t=N(),e=t?.organizationId,r=t?.projectId;return e&&r?{organizationId:e,projectId:r}:void 0}function Ne(){if(!k.supportsDocument())return;const t=document.getElementById("picked_script")||document.querySelector("script#picked")||document.getElementById("cvly");if(!t)return;const e=t.dataset.organizationid||t.getAttribute("organization-id"),r=t.dataset.projectid||t.getAttribute("project-id");return e&&r?{organizationId:e,projectId:r}:void 0}function _e(t){const{organizationId:e,projectId:r}=t;if(e&&r)return{organizationId:e,projectId:r};const s=Te();if(s)return s;const i=Ne();if(i)return i;throw new Error(`organizationId and projectId are required. You can provide them via one of:
2
2
  (1) createClient({ organizationId, projectId }) options;
3
3
  (2) window.pickedConfig = { organizationId, projectId };
4
- (3) a <script> tag with id 'picked_script', 'picked', or 'cvly' that includes data-organizationid/data-projectid (or organization-id/project-id) attributes.`)}function R(t){return t==null||t===""||Number.isNaN(t)}const He={default:(t,e)=>R(t)?String(e??""):String(t),append:(t,e)=>e&&!R(t)?`${t} ${e}`:t,prepend:(t,e)=>e&&!R(t)?`${e} ${t}`:t,upper:t=>typeof t=="string"?t.toUpperCase():t,lower:t=>typeof t=="string"?t.toLowerCase():t,capitalize:t=>typeof t=="string"?t.charAt(0).toUpperCase()+t.slice(1):t,list:t=>{if(!t||typeof t!="object")return t;const e=new Intl.ListFormat("en",{style:"long",type:"conjunction"});if(Array.isArray(t))return e.format(t.map(String));if(t instanceof Map){const r=Array.from(t.entries()).map(([s,i])=>`${s}: ${i}`);return e.format(r)}return t instanceof Set?e.format(Array.from(t).map(String)):t}};function Ke(t){return typeof t=="object"&&t!==null}function Ge(t,e){let r=e;for(const s of t.split("."))if(Ke(r)&&s in r)r=r[s];else return;return typeof r=="function"?r():r}function We(t,e){const r=t.split("|").map(d=>d.trim()),s=r.shift()??"";let i=Ge(s,e);for(const d of r){const[a,...n]=d.split(":"),p=a?.trim()??"",u=n.join(":").trim().replaceAll(/(?:^['"]|['"]$)/g,""),m=He[p];m&&(i=m(i,u))}return R(i)?"":typeof i=="object"?JSON.stringify(i):String(i)}function Je(t,e){let r="",s=0;for(;s<t.length;)if(t[s]==="{"&&t[s+1]==="{"){s+=2;let i="";for(;s<t.length;){if(t[s]==="}"&&t[s+1]==="}"){s+=2;break}i+=t[s++]}r+=We(i.trim(),e)}else r+=t[s++];return r}class N{static logger=x.logger;options;isReady=!1;project;plugins={};pluginStartHooks=[];eventBus=g.createEvent();events;organizationId;projectId;apiUrl;dashboardUrl;documentationSiteUrl;session;precondition;condition;searchParams=Me();history=ke();components=ne({client:this});experienceInstances=I.createExperienceInstanceIndex({client:this});experiences=Q({client:this});frameworks=ae({client:this});predicates=ge({client:this});features=he({client:this});responses=De({client:this});fields=xe();actions=Pe();constructor(e){x.logger("info","Picked client initializing."),this.events=be(this.eventBus);const{organizationId:r,projectId:s}=qe(e);this.organizationId=r,this.projectId=s,this.options=Object.freeze(e),this.apiUrl=e.apiUrl||Oe(),this.dashboardUrl=e.dashboardUrl??"https://dashboard.picked.app",this.documentationSiteUrl=e.documentationSiteUrl??"https://docs.picked.app",this.session=Te(),this.setupPlugins(),this.setupFeatures(),this.setupPredicates(),this.setupActions(),this.precondition=e.precondition,this.condition=e.condition,this.eventBus({type:"load",version:Be()}),x.logger("info","Picked client initialized.")}start=()=>{de(this),(async()=>{if(!k.supportsDocument())return;await this.runPluginStartHooks();const r=await this.evaluateGate(this.precondition);let s;r&&(s=await this.evaluateGate(this.condition));const i=r&&s===!0;if(typeof s=="boolean"&&this.session){const d=s;this.session.setIsUser(d),this.eventBus({type:"user_decide",value:d})}if(this.eventBus({type:"initialize"}),i&&z(this),await I.domInteractive(),i&&z(this),this.eventBus({type:"ready"}),this.isReady=!0,this.session){const{id:d,isUser:a,identifiers:n}=this.session;this.eventBus({type:"session",id:d,isUser:a,identifiers:n})}})()};registerFramework=e=>{ce(e,this.frameworks)};registerComponent=(e,r)=>{D(e,r,this.components)};registerPlugin=e=>{Z(this,e,this.plugins);const r=this.plugins[e.name];r?.onStart&&this.pluginStartHooks.push(r.onStart)};registerFeature=(e,r)=>{Se(e,r,this.features)};registerPredicate=(e,r)=>{me(e,r,this.predicates)};registerField=e=>{Ee(e,this.fields)};registerAction=(e,r)=>{Re(e,r,this.actions)};registerExperience=e=>{e.component&&D(`experience:${e.id}`,e.component,this.components),X(e,this.experiences)};getStateSnapshot=()=>V(this);launchExperienceById=async(e,r)=>{this.experiences.launch({id:e,options:r})};openExperienceById=async e=>{this.experiences.open({id:e})};async runPluginStartHooks(){for(const e of this.pluginStartHooks)await e()}async evaluateGate(e){return e===void 0?!0:typeof e=="boolean"?e:await I.evaluateRuleLogic(this,e)===!0}setupPlugins(){this.options.plugins?.forEach(e=>{if(Array.isArray(e)){e.forEach(s=>{this.registerPlugin(s)});return}const r=typeof e=="function"?e():e;if(Array.isArray(r)){r.forEach(s=>this.registerPlugin(s));return}this.registerPlugin(r)})}setupFeatures(){const e=this.options.features;e&&(Object.entries(e).forEach(([r,s])=>{const i=typeof s=="function"?s():s;this.registerFeature(r,i)}),this.searchParams.feature&&this.searchParams.feature.forEach(r=>{try{const[s,i]=r.split(":");if(!s||!i)return;let d=i;d==="true"&&(d=!0),d==="false"&&(d=!1),this.registerFeature(s,{key:`${d}`,name:s,decide:()=>d,storage:"session"})}catch{}}))}setupPredicates(){const e=this.options.predicates;e&&Object.entries(e).forEach(([r,s])=>{if(typeof s!="function"){x.logger("warn",`Predicate "${r}" is not a function.`);return}this.registerPredicate(r,s)})}setupActions(){const e=this.options.actions;e&&Object.entries(e).forEach(([r,s])=>{if(typeof s!="function"){x.logger("warn",`Action "${r}" is not a function.`);return}this.registerAction(r,s)})}getPluginConfig=e=>this.plugins[e]??{};renderString=(e,r)=>{const s=this.responses.listStore.getState().reduce((i,d)=>(i[d.fieldId]=d.value,i),{});return Je(e,{...r,responses:s})}}function _(t){return t.options?.some(e=>"condition"in e)??!1}function Ye(t){return t.some(e=>e.condition||_(e))}async function Qe(t,e){return e.length===0||!Ye(e)?e:(await Promise.all(e.map(async s=>{if(!(s.condition?await I.evaluateRuleLogic(t,s.condition):!0))return null;if(!s.options||!_(s))return s;const a=(await Promise.all(s.options.map(async p=>p.condition?await I.evaluateRuleLogic(t,p.condition)?p:null:p))).filter(p=>p!==null);return a.length===s.options.length?s:a.length===0?null:{...s,options:a}}))).filter(s=>s!==null)}function Xe(t){return{$$type:"lazy-component",load:t}}function Ze(t){return typeof t=="object"&&t!==null&&"$$type"in t&&t.$$type==="lazy-component"}const et=t=>{const e=new N(t);return k.bindClient(e),e};exports.evaluateRuleLogic=I.evaluateRuleLogic;exports.isPickedRoot=I.isPickedRoot;exports.createStorageKey=w.createStorageKey;exports.localStore=w.localStore;exports.sessionStore=w.sessionStore;exports.subscribe=w.subscribe;exports.supportsCookies=k.supportsCookies;exports.supportsCryptoRandomUUID=k.supportsCryptoRandomUUID;exports.supportsDocument=k.supportsDocument;exports.supportsHistory=k.supportsHistory;exports.supportsIntersectionObserver=k.supportsIntersectionObserver;exports.supportsLocalStorage=k.supportsLocalStorage;exports.supportsLocation=k.supportsLocation;exports.supportsSessionStorage=k.supportsSessionStorage;exports.supportsShadowRoot=k.supportsShadowRoot;exports.supportsWebComponents=k.supportsWebComponents;exports.supportsWindow=k.supportsWindow;exports.Picked=N;exports.createClient=et;exports.getPickedConfig=T;exports.getStepFields=Qe;exports.isLazyLoader=Ze;exports.lazyComponent=Xe;
4
+ (3) a <script> tag with id 'picked_script', 'picked', or 'cvly' that includes data-organizationid/data-projectid (or organization-id/project-id) attributes.`)}function R(t){return t==null||t===""||Number.isNaN(t)}const qe={default:(t,e)=>R(t)?String(e??""):String(t),append:(t,e)=>e&&!R(t)?`${t} ${e}`:t,prepend:(t,e)=>e&&!R(t)?`${e} ${t}`:t,upper:t=>typeof t=="string"?t.toUpperCase():t,lower:t=>typeof t=="string"?t.toLowerCase():t,capitalize:t=>typeof t=="string"?t.charAt(0).toUpperCase()+t.slice(1):t,list:t=>{if(!t||typeof t!="object")return t;const e=new Intl.ListFormat("en",{style:"long",type:"conjunction"});if(Array.isArray(t))return e.format(t.map(String));if(t instanceof Map){const r=Array.from(t.entries()).map(([s,i])=>`${s}: ${i}`);return e.format(r)}return t instanceof Set?e.format(Array.from(t).map(String)):t}};function He(t){return typeof t=="object"&&t!==null}function Ke(t,e){let r=e;for(const s of t.split("."))if(He(r)&&s in r)r=r[s];else return;return typeof r=="function"?r():r}function Ge(t,e){const r=t.split("|").map(d=>d.trim()),s=r.shift()??"";let i=Ke(s,e);for(const d of r){const[a,...n]=d.split(":"),p=a?.trim()??"",u=n.join(":").trim().replaceAll(/(?:^['"]|['"]$)/g,""),m=qe[p];m&&(i=m(i,u))}return R(i)?"":typeof i=="object"?JSON.stringify(i):String(i)}function We(t,e){let r="",s=0;for(;s<t.length;)if(t[s]==="{"&&t[s+1]==="{"){s+=2;let i="";for(;s<t.length;){if(t[s]==="}"&&t[s+1]==="}"){s+=2;break}i+=t[s++]}r+=Ge(i.trim(),e)}else r+=t[s++];return r}class _{static logger=x.logger;options;isReady=!1;project;plugins={};pluginStartHooks=[];eventBus=g.createEvent();events;organizationId;projectId;apiUrl;dashboardUrl;documentationSiteUrl;session;precondition;condition;searchParams=Oe();history=ke();components=ne({client:this});experienceInstances=I.createExperienceInstanceIndex({client:this});experiences=Q({client:this});frameworks=ae({client:this});predicates=ge({client:this});features=he({client:this});responses=De({client:this});fields=xe();actions=Pe();constructor(e){x.logger("info","Picked client initializing."),this.events=be(this.eventBus);const{organizationId:r,projectId:s}=_e(e);this.organizationId=r,this.projectId=s,this.options=Object.freeze(e),this.apiUrl=e.apiUrl||Be(),this.dashboardUrl=e.dashboardUrl??"https://dashboard.picked.app",this.documentationSiteUrl=e.documentationSiteUrl??"https://docs.picked.app",this.session=Ve(),this.setupPlugins(),this.setupFeatures(),this.setupPredicates(),this.setupActions(),this.precondition=e.precondition,this.condition=e.condition,this.eventBus({type:"load",version:U.getVersion()}),x.logger("info","Picked client initialized.")}start=()=>{de(this),(async()=>{if(!k.supportsDocument())return;await this.runPluginStartHooks();const r=await this.evaluateGate(this.precondition);let s;r&&(s=await this.evaluateGate(this.condition));const i=r&&s===!0;if(typeof s=="boolean"&&this.session){const d=s;this.session.setIsUser(d),this.eventBus({type:"user_decide",value:d})}if(this.eventBus({type:"initialize"}),i&&z(this),await I.domInteractive(),i&&z(this),this.eventBus({type:"ready"}),this.isReady=!0,this.session){const{id:d,isUser:a,identifiers:n}=this.session;this.eventBus({type:"session",id:d,isUser:a,identifiers:n})}})()};registerFramework=e=>{ce(e,this.frameworks)};registerComponent=(e,r)=>{D(e,r,this.components)};registerPlugin=e=>{Z(this,e,this.plugins);const r=this.plugins[e.name];r?.onStart&&this.pluginStartHooks.push(r.onStart)};registerFeature=(e,r)=>{Se(e,r,this.features)};registerPredicate=(e,r)=>{me(e,r,this.predicates)};registerField=e=>{Ee(e,this.fields)};registerAction=(e,r)=>{Re(e,r,this.actions)};registerExperience=e=>{e.component&&D(`experience:${e.id}`,e.component,this.components),X(e,this.experiences)};getStateSnapshot=()=>T(this);launchExperienceById=async(e,r)=>{this.experiences.launch({id:e,options:r})};openExperienceById=async e=>{this.experiences.open({id:e})};async runPluginStartHooks(){for(const e of this.pluginStartHooks)await e()}async evaluateGate(e){return e===void 0?!0:typeof e=="boolean"?e:await I.evaluateRuleLogic(this,e)===!0}setupPlugins(){this.options.plugins?.forEach(e=>{if(Array.isArray(e)){e.forEach(s=>{this.registerPlugin(s)});return}const r=typeof e=="function"?e():e;if(Array.isArray(r)){r.forEach(s=>this.registerPlugin(s));return}this.registerPlugin(r)})}setupFeatures(){const e=this.options.features;e&&(Object.entries(e).forEach(([r,s])=>{const i=typeof s=="function"?s():s;this.registerFeature(r,i)}),this.searchParams.feature&&this.searchParams.feature.forEach(r=>{try{const[s,i]=r.split(":");if(!s||!i)return;let d=i;d==="true"&&(d=!0),d==="false"&&(d=!1),this.registerFeature(s,{key:`${d}`,name:s,decide:()=>d,storage:"session"})}catch{}}))}setupPredicates(){const e=this.options.predicates;e&&Object.entries(e).forEach(([r,s])=>{if(typeof s!="function"){x.logger("warn",`Predicate "${r}" is not a function.`);return}this.registerPredicate(r,s)})}setupActions(){const e=this.options.actions;e&&Object.entries(e).forEach(([r,s])=>{if(typeof s!="function"){x.logger("warn",`Action "${r}" is not a function.`);return}this.registerAction(r,s)})}getPluginConfig=e=>this.plugins[e]??{};renderString=(e,r)=>{const s=this.responses.listStore.getState().reduce((i,d)=>(i[d.fieldId]=d.value,i),{});return We(e,{...r,responses:s})}}function q(t){return t.options?.some(e=>"condition"in e)??!1}function Je(t){return t.some(e=>e.condition||q(e))}async function Ye(t,e){return e.length===0||!Je(e)?e:(await Promise.all(e.map(async s=>{if(!(s.condition?await I.evaluateRuleLogic(t,s.condition):!0))return null;if(!s.options||!q(s))return s;const a=(await Promise.all(s.options.map(async p=>p.condition?await I.evaluateRuleLogic(t,p.condition)?p:null:p))).filter(p=>p!==null);return a.length===s.options.length?s:a.length===0?null:{...s,options:a}}))).filter(s=>s!==null)}function Qe(t){return{$$type:"lazy-component",load:t}}function Xe(t){return typeof t=="object"&&t!==null&&"$$type"in t&&t.$$type==="lazy-component"}const Ze=t=>{const e=new _(t);return k.bindClient(e),e};exports.evaluateRuleLogic=I.evaluateRuleLogic;exports.isPickedRoot=I.isPickedRoot;exports.createStorageKey=w.createStorageKey;exports.localStore=w.localStore;exports.sessionStore=w.sessionStore;exports.subscribe=w.subscribe;exports.supportsCookies=k.supportsCookies;exports.supportsCryptoRandomUUID=k.supportsCryptoRandomUUID;exports.supportsDocument=k.supportsDocument;exports.supportsHistory=k.supportsHistory;exports.supportsIntersectionObserver=k.supportsIntersectionObserver;exports.supportsLocalStorage=k.supportsLocalStorage;exports.supportsLocation=k.supportsLocation;exports.supportsSessionStorage=k.supportsSessionStorage;exports.supportsShadowRoot=k.supportsShadowRoot;exports.supportsWebComponents=k.supportsWebComponents;exports.supportsWindow=k.supportsWindow;exports.Picked=_;exports.createClient=Ze;exports.getPickedConfig=N;exports.getStepFields=Ye;exports.isLazyLoader=Xe;exports.lazyComponent=Qe;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("../../../api-DzSCgBQ2.cjs"),a=require("../../../logger-BsmHUUw1.cjs");function g(e){let r=2166136261;for(let n=0;n<e.length;n++)r^=e.charCodeAt(n),r=Math.imul(r,16777619);return r>>>0}function d(e){return g(e)%100}function p(e,r){return r<=0?!1:r>=100?!0:e<r}function _(e){return typeof e!="object"||e===null||!("id"in e&&"name"in e&&"enabled"in e&&"weight"in e&&"version"in e)?!1:typeof e.id=="string"&&typeof e.name=="string"&&typeof e.enabled=="boolean"&&typeof e.weight=="number"&&typeof e.version=="number"}function f(e){return typeof e!="object"||e===null||!("features"in e)||!Array.isArray(e.features)?!1:e.features.every(_)}function h(e){const r=e.searchParams["preview-token"];if(r&&r.length>0)return r[0]}function m(e){const r=new Set,n=e.searchParams.feature;if(!n)return r;for(const i of n){const t=i.indexOf(":");t>0&&r.add(i.substring(0,t))}return r}function u(e,r,n){const i=m(e),t=e.session?.id;if(!t)throw new Error("Session ID is required for feature registration");const o=d(t);for(const s of r.features)i.has(s.id)||y(e,s,n,o)}function y(e,r,n,i){e.registerFeature(r.id,{key:`v${r.version}`,name:r.name,storage:n?"session":"local",decide:()=>r.enabled?p(i,r.weight):!1})}function P(){if(typeof __PICKED_PROJECT_CONFIG__>"u")return;let e;if(typeof __PICKED_PROJECT_CONFIG__=="string")try{e=JSON.parse(__PICKED_PROJECT_CONFIG__)}catch{a.logger("warn","Build-time project config is not valid JSON");return}else e=__PICKED_PROJECT_CONFIG__;if(f(e))return e;a.logger("warn","Build-time project config has invalid shape, falling back to runtime fetch")}async function c(e,r,n){const i=n?`projects/${r}?preview_token=${encodeURIComponent(n)}`:`projects/${r}`;let t;try{t=await l.get(e,i)}catch(s){return a.logger("warn","Failed to fetch project config",s),null}if(!t.ok)return a.logger("warn",`Project config request failed with status ${t.status.toString()}`),null;let o;try{o=await t.json()}catch{return a.logger("warn","Failed to parse project config response"),null}return f(o)?o:(a.logger("warn","Invalid project config response shape"),null)}function C(e){return{name:"dynamic-experiences",setup:r=>{const n=e?.apiUrl??r.apiUrl;return{onStart:async()=>{const i=h(r);if(i){const s=await c(n,r.projectId,i);s&&u(r,s,!0);return}const t=e?.projectConfig??P();if(t){u(r,t,!1);return}const o=await c(n,r.projectId);o&&u(r,o,!1)}}}}}exports.dynamicExperiencesPlugin=C;exports.fetchProject=c;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("../../../api-CbpxV_xX.cjs"),a=require("../../../logger-BsmHUUw1.cjs");function d(e){let r=2166136261;for(let n=0;n<e.length;n++)r^=e.charCodeAt(n),r=Math.imul(r,16777619);return r>>>0}function g(e){return d(e)%100}function p(e,r){return r<=0?!1:r>=100?!0:e<r}function h(e){return typeof e!="object"||e===null||!("id"in e&&"name"in e&&"enabled"in e&&"weight"in e&&"version"in e)?!1:typeof e.id=="string"&&typeof e.name=="string"&&typeof e.enabled=="boolean"&&typeof e.weight=="number"&&typeof e.version=="number"}function l(e){return typeof e!="object"||e===null||!("features"in e)||!Array.isArray(e.features)?!1:e.features.every(h)}function y(e){const r=e.searchParams["preview-token"];if(r&&r.length>0)return r[0]}function m(e){const r=new Set,n=e.searchParams.feature;if(!n)return r;for(const i of n){const t=i.indexOf(":");t>0&&r.add(i.substring(0,t))}return r}function c(e,r,n){const i=m(e),t=e.session?.id;if(!t)throw new Error("Session ID is required for feature registration");const o=g(t);for(const s of r.features)i.has(s.id)||v(e,s,n,o)}function v(e,r,n,i){e.registerFeature(r.id,{key:`v${r.version}`,name:r.name,storage:n?"session":"local",decide:()=>r.enabled?p(i,r.weight):!1})}function w(){let e;try{e=__PICKED_PROJECT_CONFIG__}catch{return}if(e===void 0)return;let r;if(typeof e=="string")try{r=JSON.parse(e)}catch{a.logger("warn","Build-time project config is not valid JSON");return}else r=e;if(l(r))return r;a.logger("warn","Build-time project config has invalid shape, falling back to runtime fetch")}function j(e){try{const r=new URL(e).hostname;return r==="localhost"||r==="127.0.0.1"||r==="::1"}catch{return!1}}function b(e){if(typeof e!="object"||e===null||!("cause"in e))return!1;const{cause:r}=e;return typeof r!="object"||r===null||!("code"in r)?!1:r.code==="ECONNREFUSED"}async function u(e,r,n){const i=n?.previewToken?`projects/${r}?preview_token=${encodeURIComponent(n.previewToken)}`:`projects/${r}`;let t;try{t=await f.get(e,i,n?.headers)}catch(s){return j(e)&&b(s)||a.logger("warn","Failed to fetch project config",s),null}if(!t.ok)return a.logger("warn",`Project config request failed with status ${t.status.toString()}`),null;let o;try{o=await t.json()}catch{return a.logger("warn","Failed to parse project config response"),null}return l(o)?o:(a.logger("warn","Invalid project config response shape"),null)}function P(e){return{name:"dynamic-experiences",setup:r=>{const n=e?.apiUrl??r.apiUrl;return{onStart:async()=>{const i=y(r);if(i){const s=await u(n,r.projectId,{previewToken:i});s&&c(r,s,!0);return}const t=e?.projectConfig??w();if(t){c(r,t,!1);return}const o=await u(n,r.projectId);o&&c(r,o,!1)}}}}}exports.createClientHeaders=f.createClientHeaders;exports.dynamicExperiencesPlugin=P;exports.fetchProject=u;
package/dist/esm/index.js CHANGED
@@ -5,12 +5,12 @@ import { f as zt } from "../experience-instance-fvSEb72i.js";
5
5
  import { l as w } from "../logger-C9a75KZn.js";
6
6
  import { c as A, l as C, s as M } from "../storage-Co_LbKr_.js";
7
7
  import { a as Mt } from "../storage-Co_LbKr_.js";
8
- import { p as ae } from "../api-CbXfbi_s.js";
9
- import { g as ce } from "../id-BW-g3y32.js";
10
- import { i as ue } from "../object-JwZ58NOH.js";
11
- import { s as L, a as _, b as de, c as le, d as pe } from "../supports-8YT4QKI7.js";
8
+ import { p as ae, g as ce } from "../api-CTXU-Aoh.js";
9
+ import { g as ue } from "../id-BW-g3y32.js";
10
+ import { i as de } from "../object-JwZ58NOH.js";
11
+ import { s as L, a as _, b as le, c as pe, d as fe } from "../supports-8YT4QKI7.js";
12
12
  import { e as Ut, f as Dt, g as Vt, h as Nt, i as Tt, j as Lt, k as _t } from "../supports-8YT4QKI7.js";
13
- const Y = x("experience"), fe = b(
13
+ const Y = x("experience"), ge = b(
14
14
  ({ client: t, experience: e }) => {
15
15
  const r = Y.store(e), s = j(r, {
16
16
  merge(u, g) {
@@ -44,10 +44,10 @@ const Y = x("experience"), fe = b(
44
44
  };
45
45
  }
46
46
  );
47
- function ge(t) {
48
- return I(fe, t);
47
+ function me(t) {
48
+ return I(ge, t);
49
49
  }
50
- const me = b(({ client: t }) => {
50
+ const he = b(({ client: t }) => {
51
51
  const e = Y.store({}), r = j(e, {
52
52
  register(u, g) {
53
53
  return {
@@ -62,7 +62,7 @@ const me = b(({ client: t }) => {
62
62
  g.merge({ experience: u, strategy: "override" });
63
63
  return;
64
64
  }
65
- const S = ge({ client: t, experience: u });
65
+ const S = me({ client: t, experience: u });
66
66
  r.register(S);
67
67
  }
68
68
  const i = e.map((u) => Object.values(u));
@@ -109,10 +109,10 @@ const me = b(({ client: t }) => {
109
109
  listStore: i
110
110
  };
111
111
  });
112
- function he(t) {
113
- return I(me, t);
112
+ function ye(t) {
113
+ return I(he, t);
114
114
  }
115
- const ye = (t, e) => {
115
+ const Se = (t, e) => {
116
116
  e.register(t);
117
117
  }, N = (t, e, r) => {
118
118
  const { targetSelectors: s } = e.configStore.getState(), i = W(s, e.id);
@@ -132,13 +132,13 @@ const ye = (t, e) => {
132
132
  return !1;
133
133
  const { decisionLogic: r, targetSelectors: s } = e.configStore.getState();
134
134
  return W(s, e.id).length < 1 || s.length === 0 ? !1 : r === void 0 ? !0 : se(r) ? await P(t, r) === !0 : !0;
135
- }, Se = (t, e, r) => {
135
+ }, ve = (t, e, r) => {
136
136
  const s = e.name, i = e.setup(t);
137
137
  if (i) {
138
138
  const l = r[s] ?? {};
139
139
  r[s] = Object.freeze({ ...l, ...i });
140
140
  }
141
- }, ve = x("component"), ke = b(
141
+ }, ke = x("component"), we = b(
142
142
  ({ client: t, component: e, name: r }) => {
143
143
  const s = t.frameworks.getByName(e.frameworkName);
144
144
  return {
@@ -148,11 +148,11 @@ const ye = (t, e) => {
148
148
  };
149
149
  }
150
150
  );
151
- function we(t) {
152
- return I(ke, t);
151
+ function be(t) {
152
+ return I(we, t);
153
153
  }
154
- const be = b(({ client: t }) => {
155
- const e = ve.store({}), r = j(e, {
154
+ const Ie = b(({ client: t }) => {
155
+ const e = ke.store({}), r = j(e, {
156
156
  register(a, n) {
157
157
  return {
158
158
  ...a,
@@ -165,7 +165,7 @@ const be = b(({ client: t }) => {
165
165
  "warn",
166
166
  `Component '${a}' already registered. Registering again will override the previous registration.`
167
167
  );
168
- const u = we({ client: t, name: a, component: n });
168
+ const u = be({ client: t, name: a, component: n });
169
169
  r.register(u);
170
170
  }
171
171
  const i = e.map((a) => Object.values(a));
@@ -178,13 +178,13 @@ const be = b(({ client: t }) => {
178
178
  listStore: i
179
179
  };
180
180
  });
181
- function Ie(t) {
182
- return I(be, t);
181
+ function Fe(t) {
182
+ return I(Ie, t);
183
183
  }
184
184
  const G = (t, e, r) => {
185
185
  r.register(t, e);
186
- }, Fe = x("framework"), xe = b(({ client: t }) => {
187
- const e = Fe.store({}), r = j(e, {
186
+ }, xe = x("framework"), je = b(({ client: t }) => {
187
+ const e = xe.store({}), r = j(e, {
188
188
  register(a, n) {
189
189
  return {
190
190
  ...a,
@@ -208,16 +208,16 @@ const G = (t, e, r) => {
208
208
  listStore: i
209
209
  };
210
210
  });
211
- function je(t) {
212
- return I(xe, t);
211
+ function Ee(t) {
212
+ return I(je, t);
213
213
  }
214
- const Ee = (t, e) => {
214
+ const Pe = (t, e) => {
215
215
  e.register(t.name, t);
216
- }, Pe = 6e3, Ae = A("last_ping", "global"), $e = async (t) => {
216
+ }, Ae = 6e3, $e = A("last_ping", "global"), Be = async (t) => {
217
217
  try {
218
- const e = Date.now(), r = C.get(Ae);
218
+ const e = Date.now(), r = C.get($e);
219
219
  let s = 0;
220
- if (r.isSet() && (s = r.json() ?? 0), s && e - s < Pe)
220
+ if (r.isSet() && (s = r.json() ?? 0), s && e - s < Ae)
221
221
  return !0;
222
222
  const i = {
223
223
  projectId: t.projectId,
@@ -242,8 +242,8 @@ function X(t) {
242
242
  };
243
243
  return Object.freeze(r);
244
244
  }
245
- const Be = x("predicate"), Re = b(({ client: t }) => {
246
- const e = Be.store({}), r = j(e, {
245
+ const Re = x("predicate"), ze = b(({ client: t }) => {
246
+ const e = Re.store({}), r = j(e, {
247
247
  register(n, p) {
248
248
  return {
249
249
  ...n,
@@ -291,12 +291,12 @@ const Be = x("predicate"), Re = b(({ client: t }) => {
291
291
  getEvokablePredicate: a
292
292
  };
293
293
  });
294
- function ze(t) {
295
- return I(Re, t);
294
+ function Ce(t) {
295
+ return I(ze, t);
296
296
  }
297
- const Ce = (t, e, r) => {
297
+ const Me = (t, e, r) => {
298
298
  r.register(t, e);
299
- }, J = x("feature"), Me = b(({ client: t }) => {
299
+ }, J = x("feature"), Oe = b(({ client: t }) => {
300
300
  const e = J.store({}), r = J.store([]), s = j(e, {
301
301
  register(o, c) {
302
302
  return {
@@ -452,22 +452,22 @@ const Ce = (t, e, r) => {
452
452
  getEvokableFeature: m
453
453
  };
454
454
  });
455
- function Oe(t) {
456
- return I(Me, t);
455
+ function Ue(t) {
456
+ return I(Oe, t);
457
457
  }
458
- const Ue = (t, e, r) => {
458
+ const De = (t, e, r) => {
459
459
  r.register(t, e);
460
460
  }, E = x("history");
461
461
  function q(t, e) {
462
462
  return {
463
463
  // eslint-disable-next-line sonarjs/pseudo-random
464
- id: ce(`history-entry-${Date.now()}-${Math.random()}}`),
464
+ id: ue(`history-entry-${Date.now()}-${Math.random()}}`),
465
465
  node: e,
466
466
  at: Date.now(),
467
467
  experienceId: t
468
468
  };
469
469
  }
470
- const De = b(() => {
470
+ const Ve = b(() => {
471
471
  const t = E.store({ entries: [] }), e = E.event(), r = E.event(), s = E.event(), i = E.event();
472
472
  t.on(e, (a, n) => ({
473
473
  entries: [...a.entries, q(n.experienceId, n.node)]
@@ -505,11 +505,11 @@ const De = b(() => {
505
505
  entriesStore: t.map((a) => a.entries)
506
506
  };
507
507
  });
508
- function Ve() {
509
- return I(De);
508
+ function Ne() {
509
+ return I(Ve);
510
510
  }
511
- let Ne = 0;
512
- const Te = (t) => {
511
+ let Te = 0;
512
+ const Le = (t) => {
513
513
  const e = T([]);
514
514
  return k({
515
515
  clock: t,
@@ -517,15 +517,15 @@ const Te = (t) => {
517
517
  fn: (r, s) => [
518
518
  ...r,
519
519
  {
520
- id: Ne++,
520
+ id: Te++,
521
521
  at: /* @__PURE__ */ new Date(),
522
522
  payload: s
523
523
  }
524
524
  ],
525
525
  target: e
526
526
  }), e;
527
- }, Le = x("field"), _e = b(() => {
528
- const t = Le.store({}), e = j(t, {
527
+ }, _e = x("field"), He = b(() => {
528
+ const t = _e.store({}), e = j(t, {
529
529
  register(n, p) {
530
530
  return {
531
531
  ...n,
@@ -560,13 +560,13 @@ const Te = (t) => {
560
560
  getByName: a
561
561
  };
562
562
  });
563
- function He() {
564
- return I(_e);
563
+ function Ge() {
564
+ return I(He);
565
565
  }
566
- const Ge = (t, e) => {
566
+ const Je = (t, e) => {
567
567
  e.register(t);
568
- }, Je = x("action"), qe = b(() => {
569
- const t = Je.store({}), e = j(t, {
568
+ }, qe = x("action"), Ke = b(() => {
569
+ const t = qe.store({}), e = j(t, {
570
570
  register(a, n) {
571
571
  return {
572
572
  ...a,
@@ -600,16 +600,16 @@ const Ge = (t, e) => {
600
600
  getEvokableAction: l
601
601
  };
602
602
  });
603
- function Ke() {
604
- return I(qe);
603
+ function We() {
604
+ return I(Ke);
605
605
  }
606
- const We = (t, e, r) => {
606
+ const Ye = (t, e, r) => {
607
607
  r.register(t, e);
608
608
  };
609
609
  function O(t) {
610
610
  return typeof t > "u" || t === null || t === "" || Array.isArray(t) && !t.length;
611
611
  }
612
- function Ye(t) {
612
+ function Qe(t) {
613
613
  return typeof t == "string" || typeof t == "number" || typeof t == "boolean" || t === null;
614
614
  }
615
615
  function K(t) {
@@ -619,8 +619,8 @@ function K(t) {
619
619
  return !1;
620
620
  }
621
621
  }
622
- const Qe = x("response"), Xe = b(({ client: t }) => {
623
- const e = Qe.store({}), r = V(), s = V(), i = j(e, {
622
+ const Xe = x("response"), Ze = b(({ client: t }) => {
623
+ const e = Xe.store({}), r = V(), s = V(), i = j(e, {
624
624
  register(m, o) {
625
625
  return {
626
626
  ...m,
@@ -664,7 +664,7 @@ const Qe = x("response"), Xe = b(({ client: t }) => {
664
664
  });
665
665
  return;
666
666
  }
667
- if (h.multiple && (typeof d == "string" || typeof d == "number" || typeof d == "boolean") && (d = [d]), h.validation && !ue(h.validation) && !O(d)) {
667
+ if (h.multiple && (typeof d == "string" || typeof d == "number" || typeof d == "boolean") && (d = [d]), h.validation && !de(h.validation) && !O(d)) {
668
668
  const y = await P(t, h.validation, {
669
669
  $input: d
670
670
  });
@@ -777,7 +777,7 @@ const Qe = x("response"), Xe = b(({ client: t }) => {
777
777
  });
778
778
  } else {
779
779
  const F = h.options.map((v) => v.value);
780
- y.every((v) => !Ye(v) || v === null ? !1 : F.includes(v)) || o.push({
780
+ y.every((v) => !Qe(v) || v === null ? !1 : F.includes(v)) || o.push({
781
781
  fieldId: c,
782
782
  userMessage: "This field expects a valid option",
783
783
  systemMessage: `Field expects a valid option. Valid options are: ${F.join(", ")}`,
@@ -825,10 +825,9 @@ const Qe = x("response"), Xe = b(({ client: t }) => {
825
825
  getByFieldName: S
826
826
  };
827
827
  });
828
- function Ze(t) {
829
- return I(Xe, t);
828
+ function et(t) {
829
+ return I(Ze, t);
830
830
  }
831
- const et = () => "0.0.47";
832
831
  function tt() {
833
832
  if (L()) {
834
833
  const t = [
@@ -865,7 +864,7 @@ function rt() {
865
864
  return e;
866
865
  }
867
866
  function st() {
868
- if (le())
867
+ if (pe())
869
868
  return crypto.randomUUID();
870
869
  const t = Date.now().toString(36), e = Math.random().toString(36).substring(2, 15), r = Math.random().toString(36).substring(2, 15), s = Math.random().toString(36).substring(2, 15);
871
870
  return `${t}-${e}-${r}-${s}`;
@@ -895,7 +894,7 @@ const nt = A("session", "global"), it = () => {
895
894
  }
896
895
  };
897
896
  return r(s), s;
898
- }, ot = () => de() ? it() : null;
897
+ }, ot = () => le() ? it() : null;
899
898
  function at() {
900
899
  if (_())
901
900
  return globalThis.window.pickedConfig;
@@ -1013,23 +1012,23 @@ class ht {
1013
1012
  precondition;
1014
1013
  condition;
1015
1014
  searchParams = rt();
1016
- history = Ve();
1017
- components = Ie({ client: this });
1015
+ history = Ne();
1016
+ components = Fe({ client: this });
1018
1017
  experienceInstances = ie({ client: this });
1019
- experiences = he({ client: this });
1020
- frameworks = je({ client: this });
1021
- predicates = ze({ client: this });
1022
- features = Oe({ client: this });
1023
- responses = Ze({ client: this });
1024
- fields = He();
1025
- actions = Ke();
1018
+ experiences = ye({ client: this });
1019
+ frameworks = Ee({ client: this });
1020
+ predicates = Ce({ client: this });
1021
+ features = Ue({ client: this });
1022
+ responses = et({ client: this });
1023
+ fields = Ge();
1024
+ actions = We();
1026
1025
  constructor(e) {
1027
- w("info", "Picked client initializing."), this.events = Te(this.eventBus);
1026
+ w("info", "Picked client initializing."), this.events = Le(this.eventBus);
1028
1027
  const { organizationId: r, projectId: s } = dt(e);
1029
- this.organizationId = r, this.projectId = s, this.options = Object.freeze(e), this.apiUrl = e.apiUrl || tt(), this.dashboardUrl = e.dashboardUrl ?? "https://dashboard.picked.app", this.documentationSiteUrl = e.documentationSiteUrl ?? "https://docs.picked.app", this.session = ot(), this.setupPlugins(), this.setupFeatures(), this.setupPredicates(), this.setupActions(), this.precondition = e.precondition, this.condition = e.condition, this.eventBus({ type: "load", version: et() }), w("info", "Picked client initialized.");
1028
+ this.organizationId = r, this.projectId = s, this.options = Object.freeze(e), this.apiUrl = e.apiUrl || tt(), this.dashboardUrl = e.dashboardUrl ?? "https://dashboard.picked.app", this.documentationSiteUrl = e.documentationSiteUrl ?? "https://docs.picked.app", this.session = ot(), this.setupPlugins(), this.setupFeatures(), this.setupPredicates(), this.setupActions(), this.precondition = e.precondition, this.condition = e.condition, this.eventBus({ type: "load", version: ce() }), w("info", "Picked client initialized.");
1030
1029
  }
1031
1030
  start = () => {
1032
- $e(this), (async () => {
1031
+ Be(this), (async () => {
1033
1032
  if (!L())
1034
1033
  return;
1035
1034
  await this.runPluginStartHooks();
@@ -1048,30 +1047,30 @@ class ht {
1048
1047
  })();
1049
1048
  };
1050
1049
  registerFramework = (e) => {
1051
- Ee(e, this.frameworks);
1050
+ Pe(e, this.frameworks);
1052
1051
  };
1053
1052
  registerComponent = (e, r) => {
1054
1053
  G(e, r, this.components);
1055
1054
  };
1056
1055
  registerPlugin = (e) => {
1057
- Se(this, e, this.plugins);
1056
+ ve(this, e, this.plugins);
1058
1057
  const r = this.plugins[e.name];
1059
1058
  r?.onStart && this.pluginStartHooks.push(r.onStart);
1060
1059
  };
1061
1060
  registerFeature = (e, r) => {
1062
- Ue(e, r, this.features);
1061
+ De(e, r, this.features);
1063
1062
  };
1064
1063
  registerPredicate = (e, r) => {
1065
- Ce(e, r, this.predicates);
1064
+ Me(e, r, this.predicates);
1066
1065
  };
1067
1066
  registerField = (e) => {
1068
- Ge(e, this.fields);
1067
+ Je(e, this.fields);
1069
1068
  };
1070
1069
  registerAction = (e, r) => {
1071
- We(e, r, this.actions);
1070
+ Ye(e, r, this.actions);
1072
1071
  };
1073
1072
  registerExperience = (e) => {
1074
- e.component && G(`experience:${e.id}`, e.component, this.components), ye(e, this.experiences);
1073
+ e.component && G(`experience:${e.id}`, e.component, this.components), Se(e, this.experiences);
1075
1074
  };
1076
1075
  getStateSnapshot = () => X(this);
1077
1076
  /** @deprecated Use `client.experiences.launch({ id: experienceId })` instead. */
@@ -1230,7 +1229,7 @@ function At(t) {
1230
1229
  }
1231
1230
  const $t = (t) => {
1232
1231
  const e = new ht(t);
1233
- return pe(e), e;
1232
+ return fe(e), e;
1234
1233
  };
1235
1234
  export {
1236
1235
  ht as Picked,
@@ -1246,11 +1245,11 @@ export {
1246
1245
  M as sessionStore,
1247
1246
  Mt as subscribe,
1248
1247
  Ut as supportsCookies,
1249
- le as supportsCryptoRandomUUID,
1248
+ pe as supportsCryptoRandomUUID,
1250
1249
  L as supportsDocument,
1251
1250
  Dt as supportsHistory,
1252
1251
  Vt as supportsIntersectionObserver,
1253
- de as supportsLocalStorage,
1252
+ le as supportsLocalStorage,
1254
1253
  Nt as supportsLocation,
1255
1254
  Tt as supportsSessionStorage,
1256
1255
  Lt as supportsShadowRoot,
@@ -1,4 +1,5 @@
1
- import { g as l } from "../../../api-CbXfbi_s.js";
1
+ import { a as l } from "../../../api-CTXU-Aoh.js";
2
+ import { c as S } from "../../../api-CTXU-Aoh.js";
2
3
  import { l as a } from "../../../logger-C9a75KZn.js";
3
4
  function d(e) {
4
5
  let r = 2166136261;
@@ -12,104 +13,125 @@ function p(e) {
12
13
  function g(e, r) {
13
14
  return r <= 0 ? !1 : r >= 100 ? !0 : e < r;
14
15
  }
15
- function m(e) {
16
+ function h(e) {
16
17
  return typeof e != "object" || e === null || !("id" in e && "name" in e && "enabled" in e && "weight" in e && "version" in e) ? !1 : typeof e.id == "string" && typeof e.name == "string" && typeof e.enabled == "boolean" && typeof e.weight == "number" && typeof e.version == "number";
17
18
  }
18
- function c(e) {
19
- return typeof e != "object" || e === null || !("features" in e) || !Array.isArray(e.features) ? !1 : e.features.every(m);
19
+ function f(e) {
20
+ return typeof e != "object" || e === null || !("features" in e) || !Array.isArray(e.features) ? !1 : e.features.every(h);
20
21
  }
21
- function _(e) {
22
+ function m(e) {
22
23
  const r = e.searchParams["preview-token"];
23
24
  if (r && r.length > 0)
24
25
  return r[0];
25
26
  }
26
- function h(e) {
27
+ function w(e) {
27
28
  const r = /* @__PURE__ */ new Set(), n = e.searchParams.feature;
28
29
  if (!n)
29
30
  return r;
30
- for (const i of n) {
31
- const t = i.indexOf(":");
32
- t > 0 && r.add(i.substring(0, t));
31
+ for (const o of n) {
32
+ const t = o.indexOf(":");
33
+ t > 0 && r.add(o.substring(0, t));
33
34
  }
34
35
  return r;
35
36
  }
36
- function u(e, r, n) {
37
- const i = h(e), t = e.session?.id;
37
+ function c(e, r, n) {
38
+ const o = w(e), t = e.session?.id;
38
39
  if (!t)
39
40
  throw new Error("Session ID is required for feature registration");
40
- const o = p(t);
41
+ const i = p(t);
41
42
  for (const s of r.features)
42
- i.has(s.id) || y(e, s, n, o);
43
+ o.has(s.id) || y(e, s, n, i);
43
44
  }
44
- function y(e, r, n, i) {
45
+ function y(e, r, n, o) {
45
46
  e.registerFeature(r.id, {
46
47
  key: `v${r.version}`,
47
48
  name: r.name,
48
49
  storage: n ? "session" : "local",
49
- decide: () => r.enabled ? g(i, r.weight) : !1
50
+ decide: () => r.enabled ? g(o, r.weight) : !1
50
51
  });
51
52
  }
52
- function C() {
53
- if (typeof __PICKED_PROJECT_CONFIG__ > "u")
54
- return;
53
+ function v() {
55
54
  let e;
56
- if (typeof __PICKED_PROJECT_CONFIG__ == "string")
55
+ try {
56
+ e = __PICKED_PROJECT_CONFIG__;
57
+ } catch {
58
+ return;
59
+ }
60
+ if (e === void 0)
61
+ return;
62
+ let r;
63
+ if (typeof e == "string")
57
64
  try {
58
- e = JSON.parse(__PICKED_PROJECT_CONFIG__);
65
+ r = JSON.parse(e);
59
66
  } catch {
60
67
  a("warn", "Build-time project config is not valid JSON");
61
68
  return;
62
69
  }
63
70
  else
64
- e = __PICKED_PROJECT_CONFIG__;
65
- if (c(e))
66
- return e;
71
+ r = e;
72
+ if (f(r))
73
+ return r;
67
74
  a("warn", "Build-time project config has invalid shape, falling back to runtime fetch");
68
75
  }
69
- async function f(e, r, n) {
70
- const i = n ? `projects/${r}?preview_token=${encodeURIComponent(n)}` : `projects/${r}`;
76
+ function j(e) {
77
+ try {
78
+ const r = new URL(e).hostname;
79
+ return r === "localhost" || r === "127.0.0.1" || r === "::1";
80
+ } catch {
81
+ return !1;
82
+ }
83
+ }
84
+ function b(e) {
85
+ if (typeof e != "object" || e === null || !("cause" in e))
86
+ return !1;
87
+ const { cause: r } = e;
88
+ return typeof r != "object" || r === null || !("code" in r) ? !1 : r.code === "ECONNREFUSED";
89
+ }
90
+ async function u(e, r, n) {
91
+ const o = n?.previewToken ? `projects/${r}?preview_token=${encodeURIComponent(n.previewToken)}` : `projects/${r}`;
71
92
  let t;
72
93
  try {
73
- t = await l(e, i);
94
+ t = await l(e, o, n?.headers);
74
95
  } catch (s) {
75
- return a("warn", "Failed to fetch project config", s), null;
96
+ return j(e) && b(s) || a("warn", "Failed to fetch project config", s), null;
76
97
  }
77
98
  if (!t.ok)
78
99
  return a("warn", `Project config request failed with status ${t.status.toString()}`), null;
79
- let o;
100
+ let i;
80
101
  try {
81
- o = await t.json();
102
+ i = await t.json();
82
103
  } catch {
83
104
  return a("warn", "Failed to parse project config response"), null;
84
105
  }
85
- return c(o) ? o : (a("warn", "Invalid project config response shape"), null);
106
+ return f(i) ? i : (a("warn", "Invalid project config response shape"), null);
86
107
  }
87
- function v(e) {
108
+ function k(e) {
88
109
  return {
89
110
  name: "dynamic-experiences",
90
111
  setup: (r) => {
91
112
  const n = e?.apiUrl ?? r.apiUrl;
92
113
  return {
93
114
  onStart: async () => {
94
- const i = _(r);
95
- if (i) {
96
- const s = await f(n, r.projectId, i);
97
- s && u(r, s, !0);
115
+ const o = m(r);
116
+ if (o) {
117
+ const s = await u(n, r.projectId, { previewToken: o });
118
+ s && c(r, s, !0);
98
119
  return;
99
120
  }
100
- const t = e?.projectConfig ?? C();
121
+ const t = e?.projectConfig ?? v();
101
122
  if (t) {
102
- u(r, t, !1);
123
+ c(r, t, !1);
103
124
  return;
104
125
  }
105
- const o = await f(n, r.projectId);
106
- o && u(r, o, !1);
126
+ const i = await u(n, r.projectId);
127
+ i && c(r, i, !1);
107
128
  }
108
129
  };
109
130
  }
110
131
  };
111
132
  }
112
133
  export {
113
- v as dynamicExperiencesPlugin,
114
- f as fetchProject
134
+ S as createClientHeaders,
135
+ k as dynamicExperiencesPlugin,
136
+ u as fetchProject
115
137
  };
@@ -1,3 +1,4 @@
1
1
  export { dynamicExperiencesPlugin, fetchProject } from './plugin';
2
+ export { createClientHeaders } from '../../utils/client-headers';
2
3
  export type * from './types';
3
4
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/plugins/dynamic-experiences/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,YAAY,EAAE,MAAM,UAAU,CAAA;AACjE,mBAAmB,SAAS,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/plugins/dynamic-experiences/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,YAAY,EAAE,MAAM,UAAU,CAAA;AACjE,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAA;AAChE,mBAAmB,SAAS,CAAA"}
@@ -1,6 +1,6 @@
1
1
  import { Plugin } from '../../entities/plugin/plugin';
2
- import { DynamicExperiencesPluginOptions, ProjectConfig } from './types';
3
- export declare function fetchProject(apiUrl: string, projectId: string, previewToken?: string): Promise<ProjectConfig | null>;
2
+ import { DynamicExperiencesPluginOptions, FetchProjectOptions, ProjectConfig } from './types';
3
+ export declare function fetchProject(apiUrl: string, projectId: string, options?: FetchProjectOptions): Promise<ProjectConfig | null>;
4
4
  /**
5
5
  * Plugin that fetches feature configuration from the Picked REST API
6
6
  * and registers features with deterministic bucket allocation.
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../../../src/plugins/dynamic-experiences/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,8BAA8B,CAAA;AAK1D,OAAO,KAAK,EAAE,+BAA+B,EAAE,aAAa,EAAwB,MAAM,SAAS,CAAA;AAgInG,wBAAsB,YAAY,CAChC,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,YAAY,CAAC,EAAE,MAAM,GACpB,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC,CAgC/B;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,wBAAwB,CAAC,OAAO,CAAC,EAAE,+BAA+B,GAAG,MAAM,CAoC1F"}
1
+ {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../../../src/plugins/dynamic-experiences/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,8BAA8B,CAAA;AAK1D,OAAO,KAAK,EACV,+BAA+B,EAC/B,mBAAmB,EACnB,aAAa,EAEd,MAAM,SAAS,CAAA;AA8JhB,wBAAsB,YAAY,CAChC,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,OAAO,CAAC,EAAE,mBAAmB,GAC5B,OAAO,CAAC,aAAa,GAAG,IAAI,CAAC,CAmC/B;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,wBAAwB,CAAC,OAAO,CAAC,EAAE,+BAA+B,GAAG,MAAM,CAoC1F"}
@@ -12,4 +12,8 @@ export interface DynamicExperiencesPluginOptions {
12
12
  apiUrl?: string;
13
13
  projectConfig?: ProjectConfig;
14
14
  }
15
+ export interface FetchProjectOptions {
16
+ previewToken?: string;
17
+ headers?: Record<string, string>;
18
+ }
15
19
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/plugins/dynamic-experiences/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,oBAAoB;IACnC,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,EAAE,MAAM,CAAA;IACZ,OAAO,EAAE,OAAO,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,EAAE,MAAM,CAAA;CAChB;AAED,MAAM,WAAW,aAAa;IAC5B,QAAQ,EAAE,oBAAoB,EAAE,CAAA;CACjC;AAED,MAAM,WAAW,+BAA+B;IAC9C,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,aAAa,CAAC,EAAE,aAAa,CAAA;CAC9B"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/plugins/dynamic-experiences/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,oBAAoB;IACnC,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,EAAE,MAAM,CAAA;IACZ,OAAO,EAAE,OAAO,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,EAAE,MAAM,CAAA;CAChB;AAED,MAAM,WAAW,aAAa;IAC5B,QAAQ,EAAE,oBAAoB,EAAE,CAAA;CACjC;AAED,MAAM,WAAW,+BAA+B;IAC9C,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,aAAa,CAAC,EAAE,aAAa,CAAA;CAC9B;AAED,MAAM,WAAW,mBAAmB;IAClC,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CACjC"}
@@ -1,3 +1,3 @@
1
- export declare function get(baseUrl: string, path: string): Promise<Response>;
1
+ export declare function get(baseUrl: string, path: string, headers?: Record<string, string>): Promise<Response>;
2
2
  export declare function post(baseUrl: string, path: string, data: unknown, headers?: Record<string, string>): Promise<Response>;
3
3
  //# sourceMappingURL=api.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../../src/utils/api.ts"],"names":[],"mappings":"AAMA,wBAAsB,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAI1E;AAED,wBAAsB,IAAI,CACxB,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,OAAO,EACb,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAC/B,OAAO,CAAC,QAAQ,CAAC,CAQnB"}
1
+ {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../../src/utils/api.ts"],"names":[],"mappings":"AAaA,wBAAsB,GAAG,CACvB,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAC/B,OAAO,CAAC,QAAQ,CAAC,CAInB;AAED,wBAAsB,IAAI,CACxB,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,OAAO,EACb,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAC/B,OAAO,CAAC,QAAQ,CAAC,CAQnB"}
@@ -0,0 +1,2 @@
1
+ export declare function createClientHeaders(name: string, version: string): Record<string, string>;
2
+ //# sourceMappingURL=client-headers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-headers.d.ts","sourceRoot":"","sources":["../../../src/utils/client-headers.ts"],"names":[],"mappings":"AAGA,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAKzF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@picked/client",
3
- "version": "0.0.47",
3
+ "version": "0.0.48",
4
4
  "dependencies": {
5
5
  "@withease/factories": "^1.0.5"
6
6
  },
@@ -8,11 +8,13 @@
8
8
  "@repo/eslint-config": "workspace:*",
9
9
  "@repo/typescript-config": "workspace:*",
10
10
  "@rollup/plugin-replace": "^6.0.2",
11
+ "@size-limit/preset-small-lib": "^12.0.0",
11
12
  "@testing-library/dom": "^10.4.0",
12
13
  "@vitest/browser": "^4.0.17",
13
14
  "@vitest/coverage-istanbul": "^4.0.17",
14
15
  "effector": "^23.3.0",
15
16
  "happy-dom": "^20.0.2",
17
+ "size-limit": "^12.0.0",
16
18
  "tslib": "^2.8.1",
17
19
  "typedoc": "^0.28.5",
18
20
  "typedoc-plugin-markdown": "^4.6.3",
@@ -116,12 +118,55 @@
116
118
  "lint-files": "eslint",
117
119
  "lint:format": "eslint . --fix",
118
120
  "lint:report": "eslint . -o './.reports/eslint.json' -f json || [ -f './.reports/eslint.json' ]",
121
+ "size": "size-limit",
119
122
  "test": "vitest run",
120
123
  "test:coverage": "vitest run --coverage",
121
124
  "test:packaged-types": "attw --pack",
122
125
  "test:watch": "vitest",
123
126
  "type-check": "tsc -p . --noEmit"
124
127
  },
128
+ "size-limit": [
129
+ {
130
+ "path": "dist/esm/index.js",
131
+ "limit": "12 kB"
132
+ },
133
+ {
134
+ "path": "dist/esm/server/index.js",
135
+ "limit": "10 kB"
136
+ },
137
+ {
138
+ "path": "dist/esm/plugins/single-page-app/index.js",
139
+ "limit": "5 kB"
140
+ },
141
+ {
142
+ "path": "dist/esm/plugins/create-experience/index.js",
143
+ "limit": "5 kB"
144
+ },
145
+ {
146
+ "path": "dist/esm/plugins/window-object/index.js",
147
+ "limit": "5 kB"
148
+ },
149
+ {
150
+ "path": "dist/esm/plugins/responses-indexeddb/index.js",
151
+ "limit": "5 kB"
152
+ },
153
+ {
154
+ "path": "dist/esm/plugins/responses-browser-storage/index.js",
155
+ "limit": "5 kB"
156
+ },
157
+ {
158
+ "path": "dist/esm/plugins/history-browser-storage/index.js",
159
+ "limit": "5 kB"
160
+ },
161
+ {
162
+ "path": "dist/esm/plugins/experience-browser-storage/index.js",
163
+ "limit": "5 kB"
164
+ },
165
+ {
166
+ "path": "dist/esm/plugins/web-components/index.js",
167
+ "limit": "10 kB"
168
+ }
169
+ ],
125
170
  "type": "module",
126
171
  "types": "./dist/types/index.d.ts"
127
172
  }
@@ -1,19 +0,0 @@
1
- function o(t, n) {
2
- return new URL(`/api/v1/${n}`, t).toString();
3
- }
4
- async function s(t, n) {
5
- const e = o(t, n);
6
- return fetch(e);
7
- }
8
- async function i(t, n, e, r) {
9
- const c = o(t, n);
10
- return fetch(c, {
11
- method: "POST",
12
- headers: { "Content-Type": "application/json", ...r },
13
- body: JSON.stringify(e)
14
- });
15
- }
16
- export {
17
- s as g,
18
- i as p
19
- };
@@ -1 +0,0 @@
1
- "use strict";function o(t,n){return new URL(`/api/v1/${n}`,t).toString()}async function s(t,n){const e=o(t,n);return fetch(e)}async function i(t,n,e,r){const c=o(t,n);return fetch(c,{method:"POST",headers:{"Content-Type":"application/json",...r},body:JSON.stringify(e)})}exports.get=s;exports.post=i;