@picked/client 0.0.48 → 0.0.49-next.1

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.
@@ -5,7 +5,7 @@ function u(n, t) {
5
5
  [a]: t
6
6
  };
7
7
  }
8
- const d = () => "0.0.48", E = "v1";
8
+ const d = () => "0.0.49-next.1", E = "v1";
9
9
  function s(n, t) {
10
10
  return new URL(`/api/${E}/${t}`, n).toString();
11
11
  }
@@ -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.49-next.1",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"),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:
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("effector"),S=require("@withease/factories"),I=require("../experience-instance-BsXG5XJ4.cjs"),E=require("../logger-BsmHUUw1.cjs"),w=require("../storage-Be5xWNPC.cjs"),U=require("../api-sPUT21Vf.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(l,m){return{...l,...m.experience}}}),n=r.map(l=>({name:l.name,decisionLogic:l.condition??l.decide,targetSelectors:l.targets,initializeOpenLogic:e.initializeOpen})),p=t.components.listStore.map(l=>(e.componentName?l.find(m=>m.name===e.componentName):void 0)||l.find(m=>m.name===`experience:${e.id}`)||l.find(m=>m.name==="experience"),{skipVoid:!1}),a=r.map(l=>({steps:l.steps,nodes:l.nodes,edges:l.edges,conditionals:l.conditionals})),i=r.map(l=>l.fields),c=e.actions??[];return{id:e.id,configStore:n,treeStore:a,fieldsStore:i,componentStore:p,actions:c,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(c,l){return{...c,[l.id]:l}}});function s(c){const l=e.getState()[c.id];if(l){l.merge({experience:c,strategy:"override"});return}const m=J({client:t,experience:c});r.register(m)}const n=e.map(c=>Object.values(c));function p(c){return e.map(l=>l[c],{skipVoid:!1})}const a=g.attach({source:e,effect:async(c,{id:l,options:m})=>{const b=c[l];if(!b){E.logger("warn",`Experience with id '${l}' not found.`);return}if(m?.bypassCondition){$(t,b,m);return}await V(t,b)&&$(t,b,m)}}),i=g.attach({source:t.experienceInstances.listStore,effect:(c,{id:l,options:m})=>{const b=c.filter(y=>y.experienceId===l);if(b.length>0)for(const y of b)y.open();else a({id:l,options:{...m,initialiseOpen:!0}})}});return{register:s,get:p,getById:p,launch:a,open:i,listStore:n}});function Q(t){return S.invoke(Y,t)}const X=(t,e)=>{e.register(t)},$=(t,e,r)=>{const{targetSelectors:s}=e.configStore.getState(),n=I.getTargetElements(s,e.id);n.forEach(({elements:a})=>a.forEach(i=>I.tagTargetElement(i,e.id))),I.createAppHosts(n,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)&&$(t,e)}))},V=async(t,e)=>{if(!t.preconditionPassed||!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,n=e.setup(t);if(n){const p=r[s]??{};r[s]=Object.freeze({...p,...n})}},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,i){return{...a,[i.name]:i}}});function s(a,i){e.getState()[a]&&E.logger("warn",`Component '${a}' already registered. Registering again will override the previous registration.`);const l=re({client:t,name:a,component:i});r.register(l)}const n=e.map(a=>Object.values(a));function p(a){return e.map(i=>i[a],{skipVoid:!1})}return{register:s,getByName:p,listStore:n}});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,i){return{...a,[i.name]:i.framework}}});function s(a,i){e.getState()[a]&&E.logger("warn",`Framework '${a}' already registered. Registering again will override the previous registration.`),r.register({name:a,framework:i})}const n=e.map(a=>Object.values(a));function p(a){return e.map(i=>i[a],{skipVoid:!1})}return{register:s,getByName:p,listStore:n}});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 n={projectId:t.projectId,path:window.location.pathname},p={},i=document.getElementById("picked_script")?.dataset.verceltoken;i&&(p["x-vercel-protection-bypass"]=i);const l=(await U.post(t.apiUrl,"ping",n,p)).ok;return l&&r.set(e),l}catch(e){return E.logger("error",e),!1}};function N(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(i,c){return{...i,[c.name]:{name:c.name,predicate:c.predicate}}}});function s(i,c){e.getState()[i]&&E.logger("warn",`Predicate '${i}' already registered. Registering again will override the previous registration.`),r.register(Object.freeze({name:i,predicate:c}))}const n=e.map(i=>Object.values(i));function p(i){return e.map(c=>c[i]?.predicate,{skipVoid:!1})}function a(i){const c=g.createStore(()=>{},{skipVoid:!1}),l=g.createEffect(async()=>{const m=p(i).getState();if(!m)return;const b=N(t);return(...y)=>m({...b,args:y})});return g.sample({source:{responses:t.responses.listStore,fields:t.fields.listStore},target:l}),g.sample({clock:l.doneData,filter:m=>m!==void 0,target:c}),l(),c}return{register:s,getByName:p,listStore:n,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,u){return{...o,[u.id]:u.feature}}});function n(o,u){e.getState()[o]&&E.logger("warn",`Feature '${o}' already registered. Registering again will override the previous registration.`);const d={id:o,feature:{...u,id:o}};s.register(Object.freeze({id:o,feature:d}))}const p=g.createEffect(async({id:o,key:u,storage:f="local"})=>{const d=w.createStorageKey(`feature:${o}:${u}`,"global"),v=(f==="session"?w.sessionStore:w.localStore).get(d).boolean();return v===null?null:{id:o,key:u,bucket:v,storage:f}}),a=g.createEffect(o=>{if(!o)return null;const u=w.createStorageKey(`feature:${o.id}:${o.key}`,"global");(o.storage==="session"?w.sessionStore:w.localStore).set(u,o.bucket)}),i=new Map,c=g.attach({source:{allFeaturesStore:e,resolvedFeaturesStore:r},effect:async({allFeaturesStore:o,resolvedFeaturesStore:u},{id:f,decide:d,key:h})=>{const v=u.find(P=>P.id===f&&P.key===h);if(v)return v;const x=o[f];if(!x)throw new Error(`Feature with id '${f}' not found`);const A=i.get(`${f}:${h}`);if(A!==void 0){const P=await A;return{id:x.id,bucket:P,key:h,storage:x.feature.storage}}const F=d();i.set(`${f}:${h}`,F);const H=await F;return{id:x.id,bucket:H,key:h,storage:x.feature.storage}}});g.sample({clock:s.register,fn:o=>{const{id:u,feature:f}=o;return{id:u,key:f.feature.key,storage:f.feature.storage}},target:p}),g.sample({source:e,clock:c.doneData,fn:(o,u)=>{const{id:f,bucket:d,storage:h}=u,v=o[f]?.feature.key;return v?{key:v,id:f,bucket:d,storage:h}:null},target:a});const l=g.combine({allFeaturesStore:e,resolvedFeaturesStore:r}).map(({allFeaturesStore:o,resolvedFeaturesStore:u})=>Object.values(o).map(f=>{const d=u.find(h=>h.id===f.id&&h.key===f.feature.key);return d?{id:f.id,name:f.feature.name,key:f.feature.key,getBucket:()=>({id:f.id,bucket:d.bucket}),isResolved:!0}:{id:f.id,name:f.feature.name,key:f.feature.key,getBucket:async()=>await c(f.feature),isResolved:!1}}));g.sample({clock:c.doneData,source:{resolvedFeatures:r},filter:({resolvedFeatures:o},{id:u,key:f})=>!o.some(h=>h.id===u&&h.key===f),fn:(o,u)=>u,target:t.eventBus.prepend(o=>({type:"feature_decide",feature:o}))}),g.sample({clock:[p.doneData,c.doneData],source:r,fn:(o,u)=>!u||o.some(d=>d.id===u.id&&d.key===u.key)?o:[...o,u],target:r});function m(o){return l.map(u=>u.find(f=>f.id===o))}function b(o){return e.map(u=>u[o],{skipVoid:!1})}function y(o){const u=g.createStore(async()=>{},{skipVoid:!1}),f=g.createEffect(async()=>{const d=m(o).getState();if(d)return async()=>(await d.getBucket()).bucket});return g.sample({source:r,filter:d=>d.some(h=>h.id===o),target:f}),g.sample({clock:f.doneData,filter:d=>d!==void 0,target:u}),f(),u}return{register:n,getById:m,getByName:b,listStore:l,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(),n=j.event();t.on(e,(a,i)=>({entries:[...a.entries,O(i.experienceId,i.node)]})),t.on(r,(a,i)=>({entries:[...a.entries.slice(0,-1),O(i.experienceId,i.node)]})),t.on(n,(a,i)=>i);function p(a,i){const c={lastStepIndex:-1,secondLastStepIndex:-1};for(let l=a.length-1;l>=0;l--){const m=a[l],b=m?.node;if(!(!b||!I.isStepNode(b))&&!(i&&m?.experienceId!==i))if(c.lastStepIndex===-1)c.lastStepIndex=l;else{c.secondLastStepIndex=l;break}}return c}return t.on(s,(a,i)=>{const{secondLastStepIndex:c}=p(a.entries,i.experienceId),l=c!==-1?a.entries.slice(0,c+1):a.entries;return{...a,entries:l}}),{push:e,replace:r,back:s,restore:n,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(i,c){return{...i,[c.field.id]:c.field}}});function r(i){e.register({field:i})}function s(i,c){const l=p(i).getState();if(!l)return;const m=Object.assign({},l,{...c});e.register({field:{...m}})}const n=t.map(i=>Object.values(i));function p(i){return t.map(c=>c[i]||null)}function a(i){return t.map(c=>Object.values(c).find(l=>l.name===i)||null)}return{register:r,update:s,getById:p,listStore:n,getByName:a}});function Ee(){return S.invoke(Fe)}const xe=(t,e)=>{e.register(t)},je=g.createDomain("action"),Ae=S.createFactory(()=>{const t=je.store({}),e=g.createApi(t,{register(a,i){return{...a,[i.name]:{name:i.name,action:i.action}}}});function r(a,i){e.register({name:a,action:i})}const s=t.map(a=>Object.values(a));function n(a){return t.map(i=>i[a],{skipVoid:!1})}function p(a){return t.map(i=>{const c=i[a];return c?c.action:void 0},{skipVoid:!1})}return{register:r,getByName:n,listStore:s,getEvokableAction:p}});function Pe(){return S.invoke(Ae)}const Re=(t,e,r)=>{r.register(t,e)};function C(t){return typeof t>"u"||t===null||t===""||Array.isArray(t)&&!t.length}function Ce(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 $e=g.createDomain("response"),ze=S.createFactory(({client:t})=>{const e=$e.store({}),r=g.createEvent(),s=g.createEvent(),n=g.createApi(e,{register(y,o){return{...y,[o.fieldId]:o.response}},registerBatch(y,o){return{...y,...o}},clear(y,o){const{[o]:u,...f}=y;return f},clearAll(){return{}}});function p(y,o){if(typeof y=="string"){if(o===void 0)throw new Error("Response is required when registering a single field");n.register({fieldId:y,response:o})}else n.registerBatch(y)}async function a(y){const o=[];return await Promise.allSettled(Object.entries(y).map(async([u,f])=>{let d=f;const h=t.fields.getById(u).getState();if(!h){o.push({fieldId:u,userMessage:`Field '${u}' not found`,systemMessage:`No field with ID '${u}' exists. Available field IDs are: ${Object.keys(t.fields.listStore.getState()).join(",")}.`,value:d});return}if(h.multiple&&(typeof d=="string"||typeof d=="number"||typeof d=="boolean")&&(d=[d]),h.validation&&!G.isEmpty(h.validation)&&!C(d)){const v=await I.evaluateRuleLogic(t,h.validation,{$input:d});if(typeof v=="string"){o.push({fieldId:u,userMessage:v,systemMessage:`Field validation resulted in an error: ${v}.`,value:d});return}if(v===!1){o.push({fieldId:u,userMessage:"This field is invalid",systemMessage:"Field validation resulted in an unspecified error.",value:d});return}}if(h.required&&C(d)){o.push({fieldId:u,userMessage:"This field is required",systemMessage:"Field is required.",value:d});return}if(!h.multiple&&Array.isArray(d)&&d.length>1){o.push({fieldId:u,userMessage:"This field expects a single response",systemMessage:"Field expects a single response.",value:d});return}if(h.type==="object"&&!C(d))if(h.multiple){if(!Array.isArray(d)){o.push({fieldId:u,userMessage:"This field expects multiple values",systemMessage:"Field expects an array of objects.",value:d});return}for(const v of d){if(typeof v!="object"||v===null){o.push({fieldId:u,userMessage:"This field expects object values",systemMessage:"Field expects an array of objects, but received non-object value.",value:d});return}if(!M(v)){o.push({fieldId:u,userMessage:"This field contains non-serializable data",systemMessage:"Field value contains non-JSON-serializable data (functions, circular references, etc.).",value:d});return}}}else{if(Array.isArray(d)){o.push({fieldId:u,userMessage:"This field expects a single value",systemMessage:"Field expects a single object, not an array.",value:d});return}if(typeof d!="object"||d===null){o.push({fieldId:u,userMessage:"This field expects an object value",systemMessage:"Field expects an object value.",value:d});return}if(!M(d)){o.push({fieldId:u,userMessage:"This field contains non-serializable data",systemMessage:"Field value contains non-JSON-serializable data (functions, circular references, etc.).",value:d});return}}if(Array.isArray(h.options)&&h.options.length>0){const v=Array.isArray(d)?d:[d];if(h.type==="object"){const x=h.options.map(F=>JSON.stringify(F.value));v.every(F=>x.includes(JSON.stringify(F)))||o.push({fieldId:u,userMessage:"This field expects a valid option",systemMessage:"Field expects a valid option from the defined choices.",value:d})}else{const x=h.options.map(F=>F.value);v.every(F=>!Ce(F)||F===null?!1:x.includes(F))||o.push({fieldId:u,userMessage:"This field expects a valid option",systemMessage:`Field expects a valid option. Valid options are: ${x.join(", ")}`,value:d})}}})),{responsesToCommit:y,validationErrors:o}}async function i(y){const{responsesToCommit:o,validationErrors:u}=await a(y);return u.length?{errors:u}:(n.registerBatch(o),{errors:[]})}const c=e.map(y=>y),l=e.map(y=>Object.keys(y).map(u=>({fieldId:u,value:y[u]})));function m(y){const o=t.fields.getById(y),u=e.map(f=>f[y]||null);return g.combine({f:o,r:u},({f,r:d})=>d||(f?.defaultValue?f.defaultValue:null))}function b(y){const o=t.fields.getByName(y);return g.combine({f:o,s:e},({f:u,s:f})=>{const d=u&&f[u.id]||null;return d||(u?.defaultValue?u.defaultValue:null)})}return g.sample({clock:r,target:n.clearAll}),g.sample({clock:s,target:n.clear}),{register:p,clearAll:r,clear:s,commit:i,getResponsesToCommit:a,listStore:l,getAllStore:c,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[n]of t.entries())n.startsWith("picked-")&&r.add(n);for(const n of r){const p=n.replace("picked-","");e[p]=t.getAll(n)}const s=w.createStorageKey("s");if(r.size>0)w.sessionStore.set(s,e);else{const n=w.sessionStore.get(s);if(n)return n.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=n=>t.set({id:n.id,isUser:n.isUser,identifiers:n.identifiers}),s={id:e?.id??Me(),isUser:e?.isUser??void 0,identifiers:e?.identifiers??void 0,setIsUser(n){this.isUser=n,r(this)},setIdentifier(n,p){this.identifiers={...this.identifiers,[n]:p},r(this)},removeIdentifier(n){this.identifiers&&(this.identifiers=Object.fromEntries(Object.entries(this.identifiers).filter(([p])=>p!==n)),this.identifiers=Object.keys(this.identifiers).length?this.identifiers:void 0,r(this))}};return r(s),s},Ve=()=>k.supportsLocalStorage()?Le():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 Te(){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=Ne();if(s)return s;const n=Te();if(n)return n;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 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;
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,n])=>`${s}: ${n}`);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(p=>p.trim()),s=r.shift()??"";let n=Ke(s,e);for(const p of r){const[a,...i]=p.split(":"),c=a?.trim()??"",l=i.join(":").trim().replaceAll(/(?:^['"]|['"]$)/g,""),m=qe[c];m&&(n=m(n,l))}return R(n)?"":typeof n=="object"?JSON.stringify(n):String(n)}function We(t,e){let r="",s=0;for(;s<t.length;)if(t[s]==="{"&&t[s+1]==="{"){s+=2;let n="";for(;s<t.length;){if(t[s]==="}"&&t[s+1]==="}"){s+=2;break}n+=t[s++]}r+=Ge(n.trim(),e)}else r+=t[s++];return r}class _{static logger=E.logger;options;isReady=!1;project;plugins={};pluginStartHooks=[];eventBus=g.createEvent();events;organizationId;projectId;apiUrl;dashboardUrl;documentationSiteUrl;session;precondition;condition;preconditionPassed;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=Ee();actions=Pe();constructor(e){E.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.setupComponents(),this.precondition=e.precondition,this.condition=e.condition,this.eventBus({type:"load",version:U.getVersion()}),E.logger("info","Picked client initialized.")}start=()=>{de(this),(async()=>{if(!k.supportsDocument())return;await this.runPluginStartHooks();const r=await this.evaluateGate(this.precondition);this.preconditionPassed=r;let s;r&&(s=await this.evaluateGate(this.condition));const n=r&&s===!0;if(typeof s=="boolean"&&this.session){const p=s;this.session.setIsUser(p),this.eventBus({type:"user_decide",value:p})}if(this.eventBus({type:"initialize"}),n&&z(this),await I.domInteractive(),n&&z(this),this.eventBus({type:"ready"}),this.isReady=!0,this.session){const{id:p,isUser:a,identifiers:i}=this.session;this.eventBus({type:"session",id:p,isUser:a,identifiers:i})}})()};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=>{xe(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=()=>N(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 n=typeof s=="function"?s():s;this.registerFeature(r,n)}),this.searchParams.feature&&this.searchParams.feature.forEach(r=>{try{const[s,n]=r.split(":");if(!s||!n)return;let p=n;p==="true"&&(p=!0),p==="false"&&(p=!1),this.registerFeature(s,{key:`${p}`,name:s,decide:()=>p,storage:"session"})}catch{}}))}setupPredicates(){const e=this.options.predicates;e&&Object.entries(e).forEach(([r,s])=>{if(typeof s!="function"){E.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"){E.logger("warn",`Action "${r}" is not a function.`);return}this.registerAction(r,s)})}setupComponents(){const e=this.options.components;e&&Object.entries(e).forEach(([r,s])=>{this.registerComponent(r,s)})}getPluginConfig=e=>this.plugins[e]??{};renderString=(e,r)=>{const s=this.responses.listStore.getState().reduce((n,p)=>(n[p.fieldId]=p.value,n),{});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 c=>c.condition?await I.evaluateRuleLogic(t,c.condition)?c:null:c))).filter(c=>c!==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=T;exports.getStepFields=Ye;exports.isLazyLoader=Xe;exports.lazyComponent=Qe;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("../../../id-BKIWbSTy.cjs"),r={serialize(e){return JSON.stringify(e)},deserialize(e){return JSON.parse(e)}},y=e=>({name:"create-experience",setup:o=>{e.experiences.forEach(s=>{const n=s.serialize(),d=r.deserialize(n);d.component=s.component,o.registerExperience(d),d.fields.forEach(g=>{o.registerField(g)})})}}),z=(e,o)=>({id:f.generateId("node"),position:[0,0],experience:o,type:"action",action:e.action,addNext(n){if(!n.node)throw new Error("Cannot connect to node");const d=h({sourceNode:this,destinationNode:n.node,sourceNodeHandle:null},o);o.edges.push(d)},onSuccess(n){if(!n.node)throw new Error("Cannot connect to node");const d=h({sourceNode:this,destinationNode:n.node,sourceNodeHandle:"true"},o);o.edges.push(d)},onFail(n){if(!n.node)throw new Error("Cannot connect to node");const d=h({sourceNode:this,destinationNode:n.node,sourceNodeHandle:"false"},o);o.edges.push(d)},serialize(){return r.serialize({id:this.id,type:this.type,action:this.action,position:this.position})}}),b=e=>({id:e.id??f.generateId("step"),label:e.label,fields:e.fields??[],addField(o){const s="serialize"in o?o:N(o);return this.fields?.includes(s)||this.fields?.push(s),s}}),v=(e,o)=>{const s={id:e.id??f.generateId("step"),label:e.label,experience:o,fields:e.fields??[],node:null,nextStep(n){return this.experience.addStep(n,this)},nextConditional(n){return this.experience.addConditional(n,this)},addNextExperience(n){return this.experience.addExperience(n,this)},addField(n){return this.experience.addField(n,this)},serialize(){return r.serialize({id:this.id,label:this.label,fieldIds:this.fields.map(n=>n.id)})}};return p({step:s,type:"step"},o),s},x=()=>[0,0],p=(e,o)=>{const s={id:f.generateId("node"),position:x(),experience:o};if(e.type==="step"){const d={...s,type:"step",connectedStep:e.step,serialize(){return r.serialize({id:this.id,type:this.type,stepId:this.connectedStep.id,position:this.position,label:this.connectedStep.label})}};return d.connectedStep.node=d,d}if(e.type==="conditional"){const d={...s,type:"conditional",connectedConditional:e.conditional,serialize(){return r.serialize({id:this.id,type:this.type,conditionalId:this.connectedConditional.id,position:this.position})}};return d.connectedConditional.node=d,d}return e.type==="experience"?{...s,type:"experience",connectedExperience:e.experience,serialize(){return r.serialize({id:this.id,type:this.type,experienceId:this.connectedExperience.id,position:this.position})}}:{...s,type:"origin",serialize(){return r.serialize({id:this.id,type:this.type,position:this.position})}}},h=(e,o)=>({id:f.generateId("edge"),sourceNode:e.sourceNode,sourceNodeHandle:e.sourceNodeHandle,destinationNode:e.destinationNode,experience:o,serialize(){return r.serialize({id:this.id,sourceNodeHandle:this.sourceNodeHandle??void 0,sourceNodeId:this.sourceNode.id,destinationNodeId:this.destinationNode.id})}}),m=(e,o)=>{const s={id:f.generateId("conditional"),label:e.label,condition:e.condition,node:null,experience:o,addTrue(n){if(!this.node||!n.node)throw new Error("todo no node");const d=h({sourceNode:this.node,destinationNode:n.node,sourceNodeHandle:"true"},this.experience);this.experience.edges.push(d)},addFalse(n){if(!this.node||!n.node)throw new Error("todo no node");const d=h({sourceNode:this.node,destinationNode:n.node,sourceNodeHandle:"false"},this.experience);this.experience.edges.push(d)},serialize(){return r.serialize({id:this.id,label:this.label,condition:this.condition})}};return p({conditional:s,type:"conditional"},o),s},N=e=>({id:e.id,name:e.name,type:e.type,label:e.label,placeholder:e.placeholder,description:e.description,helpText:e.helpText,defaultValue:e.defaultValue??null,multiple:e.multiple,validation:e.validation??{},condition:e.condition,required:e.required,options:e.options?.map(s=>({id:"id"in s?s.id:f.generateId("option"),...s}))??null,policies:e.policies,serialize(){const s={id:this.id,name:this.name,label:this.label,placeholder:this.placeholder,required:this.required,description:this.description,helpText:this.helpText,validation:this.validation,condition:this.condition,policies:this.policies},n=typeof this.defaultValue=="string"?this.defaultValue:void 0,d=typeof this.defaultValue=="number"?this.defaultValue:void 0,g=typeof this.defaultValue=="boolean"?this.defaultValue:void 0;switch(this.type){case"text":if(this.multiple){let t;if(Array.isArray(this.defaultValue)){t=[];for(const i of this.defaultValue)typeof i=="string"&&t.push(i);t.length===0&&(t=void 0)}return r.serialize({...s,type:"text",multiple:!0,defaultValue:t,options:this.options?this.options.map(i=>({id:i.id,label:i.label,value:`${i.value}`,condition:i.condition})):null})}return r.serialize({...s,type:"text",multiple:!1,defaultValue:n,options:this.options?this.options.map(t=>({id:t.id,label:t.label,value:`${t.value}`,condition:t.condition})):null});case"number":if(this.multiple){let t;if(Array.isArray(this.defaultValue)){t=[];for(const i of this.defaultValue)typeof i=="number"&&t.push(i);t.length===0&&(t=void 0)}return r.serialize({...s,type:"number",multiple:!0,defaultValue:t,options:this.options?this.options.map(i=>({id:i.id,label:i.label,value:Number(i.value),condition:i.condition})):null})}return r.serialize({...s,type:"number",multiple:!1,defaultValue:d,options:this.options?this.options.map(t=>({id:t.id,label:t.label,value:Number(t.value),condition:t.condition})):null});case"boolean":if(this.multiple){let t;if(Array.isArray(this.defaultValue)){t=[];for(const i of this.defaultValue)typeof i=="boolean"&&t.push(i);t.length===0&&(t=void 0)}return r.serialize({...s,type:"boolean",multiple:!0,defaultValue:t,options:this.options?this.options.map(i=>({id:i.id,label:i.label,value:!!i.value,condition:i.condition})):null})}return r.serialize({...s,type:"boolean",multiple:!1,defaultValue:g,options:this.options?this.options.map(t=>({id:t.id,label:t.label,value:!!t.value,condition:t.condition})):null});case"object":return this.multiple?r.serialize({...s,type:"object",multiple:!0,defaultValue:this.defaultValue,options:this.options?this.options.map(t=>({id:t.id,label:t.label,description:t.description,value:t.value,condition:t.condition})):null}):r.serialize({...s,type:"object",multiple:!1,defaultValue:this.defaultValue,options:this.options?this.options.map(t=>({id:t.id,label:t.label,description:t.description,value:t.value,condition:t.condition})):null});default:throw new Error("Unsupported field type")}}}),E=e=>{const o=[],s=[],n=[],d=[],g=[],t=e.condition??e.decide;return{id:e.id,component:e.component,name:e.name,initializeOpen:e.initializeOpen,condition:t,decide:e.decide,targets:e.targets,steps:o,nodes:s,edges:n,fields:g,conditionals:d,addStep(i,u){let l=u?.node;this.nodes.length===0&&(l=p({type:"origin"},this),this.nodes.push(l));const a="serialize"in i?i:v(i,this);if(l){if(!a.node)throw new Error("todo no node");const c=h({sourceNode:l,destinationNode:a.node,sourceNodeHandle:null},this);this.edges.push(c)}return a.fields.length>0&&a.fields.forEach(c=>{this.fields.includes(c)||this.fields.push(c)}),this.steps.includes(a)||(this.steps.push(a),a.node&&this.nodes.push(a.node)),a},addAction(i,u){let l=u?.node;this.nodes.length===0&&(l=p({type:"origin"},this),this.nodes.push(l));const a="serialize"in i?i:z(i,this);if(l){const c=h({sourceNode:l,destinationNode:a,sourceNodeHandle:null},this);this.edges.push(c)}return this.nodes.push(a),a},addConditional(i,u){let l=u?.node;this.nodes.length===0&&(l=p({type:"origin"},this),this.nodes.push(l));const a="serialize"in i?i:m(i,this);if(l){if(!a.node)throw new Error("todo no node");const c=h({sourceNode:l,destinationNode:a.node,sourceNodeHandle:null},this);this.edges.push(c)}return this.conditionals.includes(a)||(this.conditionals.push(a),a.node&&this.nodes.push(a.node)),a},addExperience(i,u){let l=u?.node;this.nodes.length===0&&(l=p({type:"origin"},this),this.nodes.push(l));const a=p({type:"experience",experience:i},this);if(this.nodes.push(a),l){const c=h({sourceNode:l,destinationNode:a,sourceNodeHandle:null},this);this.edges.push(c)}return i},addField(i,u){const l="serialize"in i?i:N(i);return u&&u.fields.push(l),this.fields.includes(l)||this.fields.push(l),l},serialize(){return r.serialize({id:this.id,component:this.component,name:this.name,initializeOpen:this.initializeOpen,condition:this.condition??this.decide,decide:this.decide,targets:this.targets,steps:this.steps.map(i=>r.deserialize(i.serialize())),nodes:this.nodes.map(i=>r.deserialize(i.serialize())),edges:this.edges.map(i=>r.deserialize(i.serialize())),conditionals:this.conditionals.map(i=>r.deserialize(i.serialize())),fields:this.fields.map(i=>r.deserialize(i.serialize()))})}}};exports.createConditional=m;exports.createEdge=h;exports.createExperience=E;exports.createExperiencePlugin=y;exports.createField=N;exports.createNode=p;exports.createStep=b;exports.serialization=r;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("../../../id-BKIWbSTy.cjs"),r={serialize(e){return JSON.stringify(e)},deserialize(e){return JSON.parse(e)}},y=e=>({name:"create-experience",setup:d=>{e.experiences.forEach(n=>{const s=n.serialize(),o=r.deserialize(s);o.component=n.component,d.registerExperience(o),o.fields.forEach(g=>{d.registerField(g)})})}}),z=(e,d)=>({id:f.generateId("node"),experience:d,type:"action",action:e.action,addNext(s){if(!s.node)throw new Error("Cannot connect to node");const o=h({sourceNode:this,destinationNode:s.node,sourceNodeHandle:null},d);d.edges.push(o)},onSuccess(s){if(!s.node)throw new Error("Cannot connect to node");const o=h({sourceNode:this,destinationNode:s.node,sourceNodeHandle:"true"},d);d.edges.push(o)},onFail(s){if(!s.node)throw new Error("Cannot connect to node");const o=h({sourceNode:this,destinationNode:s.node,sourceNodeHandle:"false"},d);d.edges.push(o)},serialize(){return r.serialize({id:this.id,type:this.type,action:this.action})}}),b=e=>({id:e.id??f.generateId("step"),label:e.label,fields:e.fields??[],addField(d){const n="serialize"in d?d:N(d);return this.fields.includes(n)||this.fields.push(n),n}}),v=(e,d)=>{const n={id:e.id??f.generateId("step"),label:e.label,experience:d,fields:e.fields??[],node:null,nextStep(s){return this.experience.addStep(s,this)},nextConditional(s){return this.experience.addConditional(s,this)},addNextExperience(s){return this.experience.addExperience(s,this)},addField(s){return this.experience.addField(s,this)},serialize(){return r.serialize({id:this.id,label:this.label,fieldIds:this.fields.map(s=>s.id)})}};return p({step:n,type:"step"},d),n},p=(e,d)=>{const n={id:f.generateId("node"),experience:d};if(e.type==="step"){const o={...n,type:"step",connectedStep:e.step,serialize(){return r.serialize({id:this.id,type:this.type,stepId:this.connectedStep.id,label:this.connectedStep.label})}};return o.connectedStep.node=o,o}if(e.type==="conditional"){const o={...n,type:"conditional",connectedConditional:e.conditional,serialize(){return r.serialize({id:this.id,type:this.type,conditionalId:this.connectedConditional.id})}};return o.connectedConditional.node=o,o}return e.type==="experience"?{...n,type:"experience",connectedExperience:e.experience,serialize(){return r.serialize({id:this.id,type:this.type,experienceId:this.connectedExperience.id})}}:{...n,type:"origin",serialize(){return r.serialize({id:this.id,type:this.type})}}},h=(e,d)=>({id:f.generateId("edge"),sourceNode:e.sourceNode,sourceNodeHandle:e.sourceNodeHandle,destinationNode:e.destinationNode,experience:d,serialize(){return r.serialize({id:this.id,sourceNodeHandle:this.sourceNodeHandle??void 0,sourceNodeId:this.sourceNode.id,destinationNodeId:this.destinationNode.id})}}),m=(e,d)=>{const n={id:f.generateId("conditional"),label:e.label,condition:e.condition,node:null,experience:d,addTrue(s){if(!this.node||!s.node)throw new Error("todo no node");const o=h({sourceNode:this.node,destinationNode:s.node,sourceNodeHandle:"true"},this.experience);this.experience.edges.push(o)},addFalse(s){if(!this.node||!s.node)throw new Error("todo no node");const o=h({sourceNode:this.node,destinationNode:s.node,sourceNodeHandle:"false"},this.experience);this.experience.edges.push(o)},serialize(){return r.serialize({id:this.id,label:this.label,condition:this.condition})}};return p({conditional:n,type:"conditional"},d),n},N=e=>({id:e.id,name:e.name,type:e.type,label:e.label,placeholder:e.placeholder,description:e.description,helpText:e.helpText,defaultValue:e.defaultValue??null,multiple:e.multiple,validation:e.validation??{},condition:e.condition,required:e.required,options:e.options?.map(n=>({id:"id"in n?n.id:f.generateId("option"),...n}))??null,policies:e.policies,serialize(){const n={id:this.id,name:this.name,label:this.label,placeholder:this.placeholder,required:this.required,description:this.description,helpText:this.helpText,validation:this.validation,condition:this.condition,policies:this.policies},s=typeof this.defaultValue=="string"?this.defaultValue:void 0,o=typeof this.defaultValue=="number"?this.defaultValue:void 0,g=typeof this.defaultValue=="boolean"?this.defaultValue:void 0;switch(this.type){case"text":if(this.multiple){let t;if(Array.isArray(this.defaultValue)){t=[];for(const i of this.defaultValue)typeof i=="string"&&t.push(i);t.length===0&&(t=void 0)}return r.serialize({...n,type:"text",multiple:!0,defaultValue:t,options:this.options?this.options.map(i=>({id:i.id,label:i.label,value:`${i.value}`,condition:i.condition})):null})}return r.serialize({...n,type:"text",multiple:!1,defaultValue:s,options:this.options?this.options.map(t=>({id:t.id,label:t.label,value:`${t.value}`,condition:t.condition})):null});case"number":if(this.multiple){let t;if(Array.isArray(this.defaultValue)){t=[];for(const i of this.defaultValue)typeof i=="number"&&t.push(i);t.length===0&&(t=void 0)}return r.serialize({...n,type:"number",multiple:!0,defaultValue:t,options:this.options?this.options.map(i=>({id:i.id,label:i.label,value:Number(i.value),condition:i.condition})):null})}return r.serialize({...n,type:"number",multiple:!1,defaultValue:o,options:this.options?this.options.map(t=>({id:t.id,label:t.label,value:Number(t.value),condition:t.condition})):null});case"boolean":if(this.multiple){let t;if(Array.isArray(this.defaultValue)){t=[];for(const i of this.defaultValue)typeof i=="boolean"&&t.push(i);t.length===0&&(t=void 0)}return r.serialize({...n,type:"boolean",multiple:!0,defaultValue:t,options:this.options?this.options.map(i=>({id:i.id,label:i.label,value:!!i.value,condition:i.condition})):null})}return r.serialize({...n,type:"boolean",multiple:!1,defaultValue:g,options:this.options?this.options.map(t=>({id:t.id,label:t.label,value:!!t.value,condition:t.condition})):null});case"object":return this.multiple?r.serialize({...n,type:"object",multiple:!0,defaultValue:this.defaultValue,options:this.options?this.options.map(t=>({id:t.id,label:t.label,description:t.description,value:t.value,condition:t.condition})):null}):r.serialize({...n,type:"object",multiple:!1,defaultValue:this.defaultValue,options:this.options?this.options.map(t=>({id:t.id,label:t.label,description:t.description,value:t.value,condition:t.condition})):null});default:throw new Error("Unsupported field type")}}}),x=e=>{const d=[],n=[],s=[],o=[],g=[],t=e.condition??e.decide;return{id:e.id,component:e.component,name:e.name,initializeOpen:e.initializeOpen,condition:t,decide:e.decide,targets:e.targets,steps:d,nodes:n,edges:s,fields:g,conditionals:o,addStep(i,u){let l=u?.node;this.nodes.length===0&&(l=p({type:"origin"},this),this.nodes.push(l));const a="serialize"in i?i:v(i,this);if(l){if(!a.node)throw new Error("todo no node");const c=h({sourceNode:l,destinationNode:a.node,sourceNodeHandle:null},this);this.edges.push(c)}return a.fields.length>0&&a.fields.forEach(c=>{this.fields.includes(c)||this.fields.push(c)}),this.steps.includes(a)||(this.steps.push(a),a.node&&this.nodes.push(a.node)),a},addAction(i,u){let l=u?.node;this.nodes.length===0&&(l=p({type:"origin"},this),this.nodes.push(l));const a="serialize"in i?i:z(i,this);if(l){const c=h({sourceNode:l,destinationNode:a,sourceNodeHandle:null},this);this.edges.push(c)}return this.nodes.push(a),a},addConditional(i,u){let l=u?.node;this.nodes.length===0&&(l=p({type:"origin"},this),this.nodes.push(l));const a="serialize"in i?i:m(i,this);if(l){if(!a.node)throw new Error("todo no node");const c=h({sourceNode:l,destinationNode:a.node,sourceNodeHandle:null},this);this.edges.push(c)}return this.conditionals.includes(a)||(this.conditionals.push(a),a.node&&this.nodes.push(a.node)),a},addExperience(i,u){let l=u?.node;this.nodes.length===0&&(l=p({type:"origin"},this),this.nodes.push(l));const a=p({type:"experience",experience:i},this);if(this.nodes.push(a),l){const c=h({sourceNode:l,destinationNode:a,sourceNodeHandle:null},this);this.edges.push(c)}return i},addField(i,u){const l="serialize"in i?i:N(i);return u&&u.fields.push(l),this.fields.includes(l)||this.fields.push(l),l},serialize(){return r.serialize({id:this.id,component:this.component,name:this.name,initializeOpen:this.initializeOpen,condition:this.condition??this.decide,decide:this.decide,targets:this.targets,steps:this.steps.map(i=>r.deserialize(i.serialize())),nodes:this.nodes.map(i=>r.deserialize(i.serialize())),edges:this.edges.map(i=>r.deserialize(i.serialize())),conditionals:this.conditionals.map(i=>r.deserialize(i.serialize())),fields:this.fields.map(i=>r.deserialize(i.serialize()))})}}};exports.createConditional=m;exports.createEdge=h;exports.createExperience=x;exports.createExperiencePlugin=y;exports.createField=N;exports.createNode=p;exports.createStep=b;exports.serialization=r;
@@ -1 +1 @@
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;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("../../../api-sPUT21Vf.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;