@picked/client 0.0.1-dev.1773365725739 → 0.0.1-dev.1773371977114

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.1-dev.1773365725739", E = "v1";
8
+ const d = () => "0.0.1-dev.1773371977114", E = "v1";
9
9
  function s(n, t) {
10
10
  return new URL(`/api/${E}/${t}`, n).toString();
11
11
  }
@@ -1 +1 @@
1
- "use strict";const a="Picked-Client",d="Picked-Version";function s(e,t){return{[a]:e,[d]:t}}const o=()=>"0.0.1-dev.1773365725739",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;
1
+ "use strict";const a="Picked-Client",d="Picked-Version";function s(e,t){return{[a]:e,[d]:t}}const o=()=>"0.0.1-dev.1773371977114",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"),E=require("../logger-BsmHUUw1.cjs"),w=require("../storage-Be5xWNPC.cjs"),U=require("../api-F0IOGUor.cjs"),H=require("../id-BKIWbSTy.cjs"),G=require("../object-BbFTsGh3.cjs"),W=require("../to-kebab-case-BsOQ8CON.cjs"),k=require("../supports-YvpQZxbh.cjs"),L=g.createDomain("experience"),J=S.createFactory(({client:t,experience:e})=>{const r=L.store(e),s=g.createApi(r,{merge(u,m){return{...u,...m.experience}}}),n=r.map(u=>({name:u.name,decisionLogic:u.condition,targetSelectors:u.targets,initializeOpenLogic:e.initializeOpen})),p=t.components.listStore.map(u=>(e.componentName?u.find(m=>m.name===e.componentName):void 0)||u.find(m=>m.name===`experience:${e.id}`)||u.find(m=>m.name==="experience"),{skipVoid:!1}),o=r.map(u=>({steps:u.steps,nodes:u.nodes,edges:u.edges,conditionals:u.conditionals})),c=r.map(u=>u.fields),a=e.actions??[];return{id:e.id,configStore:n,treeStore:o,fieldsStore:c,componentStore:p,actions:a,merge:s.merge}});function Y(t){return S.invoke(J,t)}const Q=S.createFactory(({client:t})=>{const e=L.store({}),r=g.createApi(e,{register(a,u){return{...a,[u.id]:u}}});function s(a){const u=e.getState()[a.id];if(u){u.merge({experience:a,strategy:"override"});return}const m=Y({client:t,experience:a});r.register(m)}const n=e.map(a=>Object.values(a));function p(a){return e.map(u=>u[a],{skipVoid:!1})}const o=g.attach({source:e,effect:async(a,{id:u,options:m})=>{const b=a[u];if(!b){E.logger("warn",`Experience with id '${u}' not found.`);return}if(m?.bypassCondition){$(t,b,m);return}await V(t,b)&&$(t,b,m)}}),c=g.attach({source:t.experienceInstances.listStore,effect:(a,{id:u,options:m})=>{const b=a.filter(y=>y.experienceId===u);if(b.length>0)for(const y of b)y.open();else o({id:u,options:{...m,initialiseOpen:!0}})}});return{register:s,get:p,getById:p,launch:o,open:c,listStore:n}});function X(t){return S.invoke(Q,t)}const Z=(t,e)=>{e.register(t)},$=(t,e,r)=>{const{targetSelectors:s}=e.configStore.getState(),n=I.getTargetElements(s,e.id);n.forEach(({elements:o})=>o.forEach(c=>I.tagTargetElement(c,e.id))),I.createAppHosts(n,e.id).forEach(o=>{r?t.experienceInstances.spawn(e,o,r):t.experienceInstances.spawn(e,o)})},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},ee=(t,e,r)=>{const s=e.name,n=e.setup(t);if(n){const p=r[s]??{};r[s]=Object.freeze({...p,...n})}},te=g.createDomain("component"),re=S.createFactory(({client:t,component:e,name:r})=>{const s=t.frameworks.getByName(e.frameworkName);return{name:r,component:e,frameworkStore:s}});function se(t){return S.invoke(re,t)}const ne=S.createFactory(({client:t})=>{const e=te.store({}),r=g.createApi(e,{register(o,c){return{...o,[c.name]:c}}});function s(o,c){e.getState()[o]&&E.logger("warn",`Component '${o}' already registered. Registering again will override the previous registration.`);const u=se({client:t,name:o,component:c});r.register(u)}const n=e.map(o=>Object.values(o));function p(o){return e.map(c=>c[o],{skipVoid:!1})}return{register:s,getByName:p,listStore:n}});function ie(t){return S.invoke(ne,t)}const B=(t,e,r)=>{r.register(t,e)},oe=g.createDomain("framework"),ae=S.createFactory(({client:t})=>{const e=oe.store({}),r=g.createApi(e,{register(o,c){return{...o,[c.name]:c.framework}}});function s(o,c){e.getState()[o]&&E.logger("warn",`Framework '${o}' already registered. Registering again will override the previous registration.`),r.register({name:o,framework:c})}const n=e.map(o=>Object.values(o));function p(o){return e.map(c=>c[o],{skipVoid:!1})}return{register:s,getByName:p,listStore:n}});function ce(t){return S.invoke(ae,t)}const ue=(t,e)=>{e.register(t.name,t)},le=6e3,de=w.createStorageKey("last_ping","global"),pe=async t=>{try{const e=Date.now(),r=w.localStore.get(de);let s=0;if(r.isSet()&&(s=r.json()??0),s&&e-s<le)return!0;const n={projectId:t.projectId,path:window.location.pathname},p={},c=document.getElementById("picked_script")?.dataset.verceltoken;c&&(p["x-vercel-protection-bypass"]=c);const u=(await U.post(t.apiUrl,"ping",n,p)).ok;return u&&r.set(e),u}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 fe=g.createDomain("predicate"),ge=S.createFactory(({client:t})=>{const e=fe.store({}),r=g.createApi(e,{register(c,a){return{...c,[a.name]:{name:a.name,predicate:a.predicate}}}});function s(c,a){e.getState()[c]&&E.logger("warn",`Predicate '${c}' already registered. Registering again will override the previous registration.`),r.register(Object.freeze({name:c,predicate:a}))}const n=e.map(c=>Object.values(c));function p(c){return e.map(a=>a[c]?.predicate,{skipVoid:!1})}function o(c){const a=g.createStore(()=>{},{skipVoid:!1}),u=g.createEffect(async()=>{const m=p(c).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:u}),g.sample({clock:u.doneData,filter:m=>m!==void 0,target:a}),u(),a}return{register:s,getByName:p,listStore:n,getEvokablePredicate:o}});function me(t){return S.invoke(ge,t)}const ye=(t,e,r)=>{r.register(t,e)},D=g.createDomain("feature"),he=S.createFactory(({client:t})=>{const e=D.store({}),r=D.store([]),s=g.createApi(e,{register(i,l){return{...i,[l.id]:l.feature}}});function n(i,l){e.getState()[i]&&E.logger("warn",`Feature '${i}' already registered. Registering again will override the previous registration.`);const d={id:i,feature:{...l,id:i}};s.register(Object.freeze({id:i,feature:d}))}const p=g.createEffect(async({id:i,key:l,storage:f="local"})=>{const d=w.createStorageKey(`feature:${i}:${l}`,"global"),v=(f==="session"?w.sessionStore:w.localStore).get(d).boolean();return v===null?null:{id:i,key:l,bucket:v,storage:f}}),o=g.createEffect(i=>{if(!i)return null;const l=w.createStorageKey(`feature:${i.id}:${i.key}`,"global");(i.storage==="session"?w.sessionStore:w.localStore).set(l,i.bucket)}),c=new Map,a=g.attach({source:{allFeaturesStore:e,resolvedFeaturesStore:r},effect:async({allFeaturesStore:i,resolvedFeaturesStore:l},{id:f,decide:d,key:h})=>{const v=l.find(P=>P.id===f&&P.key===h);if(v)return v;const x=i[f];if(!x)throw new Error(`Feature with id '${f}' not found`);const A=c.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();c.set(`${f}:${h}`,F);const q=await F;return{id:x.id,bucket:q,key:h,storage:x.feature.storage}}});g.sample({clock:s.register,fn:i=>{const{id:l,feature:f}=i;return{id:l,key:f.feature.key,storage:f.feature.storage}},target:p}),g.sample({source:e,clock:a.doneData,fn:(i,l)=>{const{id:f,bucket:d,storage:h}=l,v=i[f]?.feature.key;return v?{key:v,id:f,bucket:d,storage:h}:null},target:o});const u=g.combine({allFeaturesStore:e,resolvedFeaturesStore:r}).map(({allFeaturesStore:i,resolvedFeaturesStore:l})=>Object.values(i).map(f=>{const d=l.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 a(f.feature),isResolved:!1}}));g.sample({clock:a.doneData,source:{resolvedFeatures:r},filter:({resolvedFeatures:i},{id:l,key:f})=>!i.some(h=>h.id===l&&h.key===f),fn:(i,l)=>l,target:t.eventBus.prepend(i=>({type:"feature_decide",feature:i}))}),g.sample({clock:[p.doneData,a.doneData],source:r,fn:(i,l)=>!l||i.some(d=>d.id===l.id&&d.key===l.key)?i:[...i,l],target:r});function m(i){return u.map(l=>l.find(f=>f.id===i))}function b(i){return e.map(l=>l[i],{skipVoid:!1})}function y(i){const l=g.createStore(async()=>{},{skipVoid:!1}),f=g.createEffect(async()=>{const d=m(i).getState();if(d)return async()=>(await d.getBucket()).bucket});return g.sample({source:r,filter:d=>d.some(h=>h.id===i),target:f}),g.sample({clock:f.doneData,filter:d=>d!==void 0,target:l}),f(),l}return{register:n,getById:m,getByName:b,listStore:u,getEvokableFeature:y}});function Se(t){return S.invoke(he,t)}const ve=(t,e,r)=>{r.register(t,e)},j=g.createDomain("history");function O(t,e){return{id:H.generateId(`history-entry-${Date.now()}-${Math.random()}}`),node:e,at:Date.now(),experienceId:t}}const ke=S.createFactory(()=>{const t=j.store({entries:[]}),e=j.event(),r=j.event(),s=j.event(),n=j.event();t.on(e,(o,c)=>({entries:[...o.entries,O(c.experienceId,c.node)]})),t.on(r,(o,c)=>({entries:[...o.entries.slice(0,-1),O(c.experienceId,c.node)]})),t.on(n,(o,c)=>c);function p(o,c){const a={lastStepIndex:-1,secondLastStepIndex:-1};for(let u=o.length-1;u>=0;u--){const m=o[u],b=m?.node;if(!(!b||!I.isStepNode(b))&&!(c&&m?.experienceId!==c))if(a.lastStepIndex===-1)a.lastStepIndex=u;else{a.secondLastStepIndex=u;break}}return a}return t.on(s,(o,c)=>{const{secondLastStepIndex:a}=p(o.entries,c.experienceId),u=a!==-1?o.entries.slice(0,a+1):o.entries;return{...o,entries:u}}),{push:e,replace:r,back:s,restore:n,entriesStore:t.map(o=>o.entries)}});function be(){return S.invoke(ke)}let we=0;const Ie=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},Fe=g.createDomain("field"),Ee=S.createFactory(()=>{const t=Fe.store({}),e=g.createApi(t,{register(a,u){return{...a,[u.resolvedKey]:{...u.field,key:u.resolvedKey}}}});function r(a){e.register({field:a,resolvedKey:a.key})}function s(a,u){const m=p(a).getState();if(!m)return;const b=Object.assign({},m,{...u});e.register({field:{...b},resolvedKey:a})}const n=t.map(a=>Object.values(a));function p(a){return t.map(u=>u[a]||null)}function o(a){return t.map(u=>Object.values(u).find(m=>m.id===a)||null)}function c(a){return t.map(u=>Object.values(u).find(m=>m.name===a)||null)}return{register:r,update:s,getByKey:p,getById:o,listStore:n,getByName:c}});function xe(){return S.invoke(Ee)}const je=(t,e)=>{e.register(t)},Ae=g.createDomain("action"),Pe=S.createFactory(()=>{const t=Ae.store({}),e=g.createApi(t,{register(o,c){return{...o,[c.name]:{name:c.name,action:c.action}}}});function r(o,c){e.register({name:o,action:c})}const s=t.map(o=>Object.values(o));function n(o){return t.map(c=>c[o],{skipVoid:!1})}function p(o){return t.map(c=>{const a=c[o];return a?a.action:void 0},{skipVoid:!1})}return{register:r,getByName:n,listStore:s,getEvokableAction:p}});function Re(){return S.invoke(Pe)}const Ce=(t,e,r)=>{r.register(t,e)};function C(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 ze=g.createDomain("response"),Be=S.createFactory(({client:t})=>{const e=ze.store({}),r=g.createEvent(),s=g.createEvent(),n=g.createApi(e,{register(y,i){return{...y,[i.fieldId]:i.response}},registerBatch(y,i){return{...y,...i}},clear(y,i){const{[i]:l,...f}=y;return f},clearAll(){return{}}});function p(y,i){if(typeof y=="string"){if(i===void 0)throw new Error("Response is required when registering a single field");n.register({fieldId:y,response:i})}else n.registerBatch(y)}async function o(y){const i=[];return await Promise.allSettled(Object.entries(y).map(async([l,f])=>{let d=f;const h=t.fields.getByKey(l).getState();if(!h){i.push({fieldId:l,userMessage:`Field '${l}' not found`,systemMessage:`No field with ID '${l}' 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"){i.push({fieldId:l,userMessage:v,systemMessage:`Field validation resulted in an error: ${v}.`,value:d});return}if(v===!1){i.push({fieldId:l,userMessage:"This field is invalid",systemMessage:"Field validation resulted in an unspecified error.",value:d});return}}if(h.required&&C(d)){i.push({fieldId:l,userMessage:"This field is required",systemMessage:"Field is required.",value:d});return}if(!h.multiple&&Array.isArray(d)&&d.length>1){i.push({fieldId:l,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)){i.push({fieldId:l,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){i.push({fieldId:l,userMessage:"This field expects object values",systemMessage:"Field expects an array of objects, but received non-object value.",value:d});return}if(!M(v)){i.push({fieldId:l,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)){i.push({fieldId:l,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){i.push({fieldId:l,userMessage:"This field expects an object value",systemMessage:"Field expects an object value.",value:d});return}if(!M(d)){i.push({fieldId:l,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)))||i.push({fieldId:l,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=>!$e(F)||F===null?!1:x.includes(F))||i.push({fieldId:l,userMessage:"This field expects a valid option",systemMessage:`Field expects a valid option. Valid options are: ${x.join(", ")}`,value:d})}}})),{responsesToCommit:y,validationErrors:i}}async function c(y){const{responsesToCommit:i,validationErrors:l}=await o(y);return l.length?{errors:l}:(n.registerBatch(i),{errors:[]})}const a=e.map(y=>y),u=e.map(y=>Object.keys(y).map(l=>({fieldId:l,value:y[l]})));function m(y){const i=t.fields.getByKey(y),l=e.map(f=>f[y]||null);return g.combine({f:i,r:l},({f,r:d})=>d||(f?.defaultValue?f.defaultValue:null))}function b(y){const i=t.fields.getByName(y);return g.combine({f:i,s:e},({f:l,s:f})=>{const d=l&&f[l.key??W.toKebabCase(l.name)]||null;return d||(l?.defaultValue?l.defaultValue:null)})}return g.sample({clock:r,target:n.clearAll}),g.sample({clock:s,target:n.clear}),{register:p,clearAll:r,clear:s,commit:c,getResponsesToCommit:o,listStore:u,getAllStore:a,getByFieldId:m,getByFieldName:b}});function De(t){return S.invoke(Be,t)}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[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 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=n=>t.set({id:n.id,isUser:n.isUser,identifiers:n.identifiers}),s={id:e?.id??Ue(),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},Ne=()=>k.supportsLocalStorage()?Ve():null;function T(){if(k.supportsWindow())return globalThis.window.pickedConfig}function Te(){if(!k.supportsWindow())return;const t=T(),e=t?.organizationId,r=t?.projectId;return e&&r?{organizationId:e,projectId:r}:void 0}function Ke(){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 n=Ke();if(n)return n;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"),b=require("../storage-Be5xWNPC.cjs"),L=require("../api-Cn-rv5A5.cjs"),H=require("../id-BKIWbSTy.cjs"),G=require("../object-BbFTsGh3.cjs"),v=require("../supports-YvpQZxbh.cjs"),V=g.createDomain("experience"),W=S.createFactory(({client:t,experience:e})=>{const r=V.store(e),s=g.createApi(r,{merge(c,m){return{...c,...m.experience}}}),n=r.map(c=>({name:c.name,decisionLogic:c.condition,targetSelectors:c.targets,initializeOpenLogic:e.initializeOpen})),f=t.components.listStore.map(c=>(e.componentName?c.find(m=>m.name===e.componentName):void 0)||c.find(m=>m.name===`experience:${e.id}`)||c.find(m=>m.name==="experience"),{skipVoid:!1}),i=r.map(c=>({steps:c.steps,nodes:c.nodes,edges:c.edges,conditionals:c.conditionals})),a=r.map(c=>c.fields),o=e.actions??[];return{id:e.id,configStore:n,treeStore:i,fieldsStore:a,componentStore:f,actions:o,merge:s.merge}});function J(t){return S.invoke(W,t)}const Y=S.createFactory(({client:t})=>{const e=V.store({}),r=g.createApi(e,{register(o,c){return{...o,[c.id]:c}}});function s(o){const c=e.getState()[o.id];if(c){c.merge({experience:o,strategy:"override"});return}const m=J({client:t,experience:o});r.register(m)}const n=e.map(o=>Object.values(o));function f(o){return e.map(c=>c[o],{skipVoid:!1})}const i=g.attach({source:e,effect:async(o,{id:c,options:m})=>{const k=o[c];if(!k){E.logger("warn",`Experience with id '${c}' not found.`);return}if(m?.bypassCondition){B(t,k,m);return}await N(t,k)&&B(t,k,m)}}),a=g.attach({source:t.experienceInstances.listStore,effect:(o,{id:c,options:m})=>{const k=o.filter(x=>x.experienceId===c);if(k.length>0)for(const x of k)x.open();else i({id:c,options:{...m,initialiseOpen:!0}})}});return{register:s,get:f,getById:f,launch:i,open:a,listStore:n}});function Q(t){return S.invoke(Y,t)}const X=(t,e)=>{e.register(t)},B=(t,e,r)=>{const{targetSelectors:s}=e.configStore.getState(),n=I.getTargetElements(s,e.id);n.forEach(({elements:i})=>i.forEach(a=>I.tagTargetElement(a,e.id))),I.createAppHosts(n,e.id).forEach(i=>{r?t.experienceInstances.spawn(e,i,r):t.experienceInstances.spawn(e,i)})},z=async t=>{await Promise.all(t.experiences.listStore.getState().map(async e=>{await N(t,e)&&B(t,e)}))},N=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 f=r[s]??{};r[s]=Object.freeze({...f,...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(i,a){return{...i,[a.name]:a}}});function s(i,a){e.getState()[i]&&E.logger("warn",`Component '${i}' already registered. Registering again will override the previous registration.`);const c=re({client:t,name:i,component:a});r.register(c)}const n=e.map(i=>Object.values(i));function f(i){return e.map(a=>a[i],{skipVoid:!1})}return{register:s,getByName:f,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(i,a){return{...i,[a.name]:a.framework}}});function s(i,a){e.getState()[i]&&E.logger("warn",`Framework '${i}' already registered. Registering again will override the previous registration.`),r.register({name:i,framework:a})}const n=e.map(i=>Object.values(i));function f(i){return e.map(a=>a[i],{skipVoid:!1})}return{register:s,getByName:f,listStore:n}});function ae(t){return S.invoke(oe,t)}const ce=(t,e)=>{e.register(t.name,t)},ue=6e3,le=b.createStorageKey("last_ping","global"),de=async t=>{try{const e=Date.now(),r=b.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},f={},a=document.getElementById("picked_script")?.dataset.verceltoken;a&&(f["x-vercel-protection-bypass"]=a);const c=(await L.post(t.apiUrl,"ping",n,f)).ok;return c&&r.set(e),c}catch(e){return E.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(a,o){return{...a,[o.name]:{name:o.name,predicate:o.predicate}}}});function s(a,o){e.getState()[a]&&E.logger("warn",`Predicate '${a}' already registered. Registering again will override the previous registration.`),r.register(Object.freeze({name:a,predicate:o}))}const n=e.map(a=>Object.values(a));function f(a){return e.map(o=>o[a]?.predicate,{skipVoid:!1})}function i(a){const o=g.createStore(()=>{},{skipVoid:!1}),c=g.createEffect(async()=>{const m=f(a).getState();if(!m)return;const k=T(t);return(...x)=>m({...k,args:x})});return g.sample({source:{responses:t.responses.listStore,fields:t.fields.listStore},target:c}),g.sample({clock:c.doneData,filter:m=>m!==void 0,target:o}),c(),o}return{register:s,getByName:f,listStore:n,getEvokablePredicate:i}});function ge(t){return S.invoke(fe,t)}const me=(t,e,r)=>{r.register(t,e)},O=g.createDomain("feature"),ye=S.createFactory(({client:t})=>{const e=O.store({}),r=O.store([]),s=g.createApi(e,{register(l,d){return{...l,[d.id]:d.feature}}});function n(l,d){e.getState()[l]&&E.logger("warn",`Feature '${l}' already registered. Registering again will override the previous registration.`);const y={id:l,feature:{...d,id:l}};s.register(Object.freeze({id:l,feature:y}))}const f=g.createEffect(async({id:l,key:d,storage:u="local"})=>{const y=b.createStorageKey(`feature:${l}:${d}`,"global"),h=(u==="session"?b.sessionStore:b.localStore).get(y).boolean();return h===null?null:{id:l,key:d,bucket:h,storage:u}}),i=g.createEffect(l=>{if(!l)return null;const d=b.createStorageKey(`feature:${l.id}:${l.key}`,"global");(l.storage==="session"?b.sessionStore:b.localStore).set(d,l.bucket)}),a=new Map,o=g.attach({source:{allFeaturesStore:e,resolvedFeaturesStore:r},effect:async({allFeaturesStore:l,resolvedFeaturesStore:d},{id:u,decide:y,key:p})=>{const h=d.find(R=>R.id===u&&R.key===p);if(h)return h;const w=l[u];if(!w)throw new Error(`Feature with id '${u}' not found`);const j=a.get(`${u}:${p}`);if(j!==void 0){const R=await j;return{id:w.id,bucket:R,key:p,storage:w.feature.storage}}const P=y();a.set(`${u}:${p}`,P);const F=await P;return{id:w.id,bucket:F,key:p,storage:w.feature.storage}}});g.sample({clock:s.register,fn:l=>{const{id:d,feature:u}=l;return{id:d,key:u.feature.key,storage:u.feature.storage}},target:f}),g.sample({source:e,clock:o.doneData,fn:(l,d)=>{const{id:u,bucket:y,storage:p}=d,h=l[u]?.feature.key;return h?{key:h,id:u,bucket:y,storage:p}:null},target:i});const c=g.combine({allFeaturesStore:e,resolvedFeaturesStore:r}).map(({allFeaturesStore:l,resolvedFeaturesStore:d})=>Object.values(l).map(u=>{const y=d.find(p=>p.id===u.id&&p.key===u.feature.key);return y?{id:u.id,name:u.feature.name,key:u.feature.key,getBucket:()=>({id:u.id,bucket:y.bucket}),isResolved:!0}:{id:u.id,name:u.feature.name,key:u.feature.key,getBucket:async()=>await o(u.feature),isResolved:!1}}));g.sample({clock:o.doneData,source:{resolvedFeatures:r},filter:({resolvedFeatures:l},{id:d,key:u})=>!l.some(p=>p.id===d&&p.key===u),fn:(l,d)=>d,target:t.eventBus.prepend(l=>({type:"feature_decide",feature:l}))}),g.sample({clock:[f.doneData,o.doneData],source:r,fn:(l,d)=>!d||l.some(y=>y.id===d.id&&y.key===d.key)?l:[...l,d],target:r});function m(l){return c.map(d=>d.find(u=>u.id===l))}function k(l){return e.map(d=>d[l],{skipVoid:!1})}function x(l){const d=g.createStore(async()=>{},{skipVoid:!1}),u=g.createEffect(async()=>{const y=m(l).getState();if(y)return async()=>(await y.getBucket()).bucket});return g.sample({source:r,filter:y=>y.some(p=>p.id===l),target:u}),g.sample({clock:u.doneData,filter:y=>y!==void 0,target:d}),u(),d}return{register:n,getById:m,getByName:k,listStore:c,getEvokableFeature:x}});function he(t){return S.invoke(ye,t)}const Se=(t,e,r)=>{r.register(t,e)},A=g.createDomain("history");function M(t,e){return{id:H.generateId(`history-entry-${Date.now()}-${Math.random()}}`),node:e,at:Date.now(),experienceId:t}}const ve=S.createFactory(()=>{const t=A.store({entries:[]}),e=A.event(),r=A.event(),s=A.event(),n=A.event();t.on(e,(i,a)=>({entries:[...i.entries,M(a.experienceId,a.node)]})),t.on(r,(i,a)=>({entries:[...i.entries.slice(0,-1),M(a.experienceId,a.node)]})),t.on(n,(i,a)=>a);function f(i,a){const o={lastStepIndex:-1,secondLastStepIndex:-1};for(let c=i.length-1;c>=0;c--){const m=i[c],k=m?.node;if(!(!k||!I.isStepNode(k))&&!(a&&m?.experienceId!==a))if(o.lastStepIndex===-1)o.lastStepIndex=c;else{o.secondLastStepIndex=c;break}}return o}return t.on(s,(i,a)=>{const{secondLastStepIndex:o}=f(i.entries,a.experienceId),c=o!==-1?i.entries.slice(0,o+1):i.entries;return{...i,entries:c}}),{push:e,replace:r,back:s,restore:n,entriesStore:t.map(i=>i.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(o,c){return{...o,[c.resolvedKey]:{...c.field,key:c.resolvedKey}}}});function r(o){e.register({field:o,resolvedKey:o.key})}function s(o,c){const m=f(o).getState();if(!m)return;const k=Object.assign({},m,{...c});e.register({field:{...k},resolvedKey:o})}const n=t.map(o=>Object.values(o));function f(o){return t.map(c=>c[o]||null)}function i(o){return t.map(c=>Object.values(c).find(m=>m.id===o)||null)}function a(o){return t.map(c=>Object.values(c).find(m=>m.name===o)||null)}return{register:r,update:s,getByKey:f,getById:i,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(i,a){return{...i,[a.name]:{name:a.name,action:a.action}}}});function r(i,a){e.register({name:i,action:a})}const s=t.map(i=>Object.values(i));function n(i){return t.map(a=>a[i],{skipVoid:!1})}function f(i){return t.map(a=>{const o=a[i];return o?o.action:void 0},{skipVoid:!1})}return{register:r,getByName:n,listStore:s,getEvokableAction:f}});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 Ce(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||t===null}function U(t){try{return JSON.stringify(t),!0}catch{return!1}}const $e=g.createDomain("response"),Be=S.createFactory(({client:t})=>{const e=$e.store({}),r=g.createEvent(),s=g.createEvent(),n=g.createApi(e,{register(l,d){return{...l,[d.fieldKey]:d.response}},registerBatch(l,d){return{...l,...d}},clear(l,d){const{[d]:u,...y}=l;return y},clearAll(){return{}}});function f(l,d){if(typeof l=="string"){if(d===void 0)throw new Error("Response is required when registering a single field");n.register({fieldKey:l,response:d})}else n.registerBatch(l)}async function i(l){const d=[];return await Promise.allSettled(Object.entries(l).map(async([u,y])=>{let p=y;const h=t.fields.getByKey(u).getState();if(!h){d.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:p});return}if(h.multiple&&(typeof p=="string"||typeof p=="number"||typeof p=="boolean")&&(p=[p]),h.validation&&!G.isEmpty(h.validation)&&!$(p)){const w=await I.evaluateRuleLogic(t,h.validation,{$input:p});if(typeof w=="string"){d.push({fieldId:u,userMessage:w,systemMessage:`Field validation resulted in an error: ${w}.`,value:p});return}if(w===!1){d.push({fieldId:u,userMessage:"This field is invalid",systemMessage:"Field validation resulted in an unspecified error.",value:p});return}}if(h.required&&$(p)){d.push({fieldId:u,userMessage:"This field is required",systemMessage:"Field is required.",value:p});return}if(!h.multiple&&Array.isArray(p)&&p.length>1){d.push({fieldId:u,userMessage:"This field expects a single response",systemMessage:"Field expects a single response.",value:p});return}if(h.type==="object"&&!$(p))if(h.multiple){if(!Array.isArray(p)){d.push({fieldId:u,userMessage:"This field expects multiple values",systemMessage:"Field expects an array of objects.",value:p});return}for(const w of p){if(typeof w!="object"||w===null){d.push({fieldId:u,userMessage:"This field expects object values",systemMessage:"Field expects an array of objects, but received non-object value.",value:p});return}if(!U(w)){d.push({fieldId:u,userMessage:"This field contains non-serializable data",systemMessage:"Field value contains non-JSON-serializable data (functions, circular references, etc.).",value:p});return}}}else{if(Array.isArray(p)){d.push({fieldId:u,userMessage:"This field expects a single value",systemMessage:"Field expects a single object, not an array.",value:p});return}if(typeof p!="object"||p===null){d.push({fieldId:u,userMessage:"This field expects an object value",systemMessage:"Field expects an object value.",value:p});return}if(!U(p)){d.push({fieldId:u,userMessage:"This field contains non-serializable data",systemMessage:"Field value contains non-JSON-serializable data (functions, circular references, etc.).",value:p});return}}if(Array.isArray(h.options)&&h.options.length>0){const w=Array.isArray(p)?p:[p];if(h.type==="object"){const j=h.options.map(F=>JSON.stringify(F.value));w.every(F=>j.includes(JSON.stringify(F)))||d.push({fieldId:u,userMessage:"This field expects a valid option",systemMessage:"Field expects a valid option from the defined choices.",value:p})}else{const j=h.options.map(F=>F.value);w.every(F=>!Ce(F)||F===null?!1:j.includes(F))||d.push({fieldId:u,userMessage:"This field expects a valid option",systemMessage:`Field expects a valid option. Valid options are: ${j.join(", ")}`,value:p})}}})),{responsesToCommit:l,validationErrors:d}}async function a(l){const{responsesToCommit:d,validationErrors:u}=await i(l);return u.length?{errors:u}:(n.registerBatch(d),{errors:[]})}const o=e.map(l=>l),c=e.map(l=>Object.keys(l).map(u=>({fieldId:u,value:l[u]})));function m(l){const d=t.fields.getByKey(l),u=e.map(y=>y[l]||null);return g.combine({f:d,r:u},({f:y,r:p})=>p||(y?.defaultValue?y.defaultValue:null))}const k=m;function x(l){const d=t.fields.getByName(l);return g.combine({f:d,s:e},({f:u,s:y})=>{const p=u&&y[u.key]||null;return p||(u?.defaultValue?u.defaultValue:null)})}return g.sample({clock:r,target:n.clearAll}),g.sample({clock:s,target:n.clear}),{register:f,clearAll:r,clear:s,commit:a,getResponsesToCommit:i,listStore:c,getAllStore:o,getByFieldKey:m,getByFieldId:k,getByFieldName:x}});function ze(t){return S.invoke(Be,t)}function De(){if(v.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(!v.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 f=n.replace("picked-","");e[f]=t.getAll(n)}const s=b.createStorageKey("s");if(r.size>0)b.sessionStore.set(s,e);else{const n=b.sessionStore.get(s);if(n)return n.json()||{}}return e}function Me(){if(v.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=b.createStorageKey("session","global"),Le=()=>{const t=b.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,f){this.identifiers={...this.identifiers,[n]:f},r(this)},removeIdentifier(n){this.identifiers&&(this.identifiers=Object.fromEntries(Object.entries(this.identifiers).filter(([f])=>f!==n)),this.identifiers=Object.keys(this.identifiers).length?this.identifiers:void 0,r(this))}};return r(s),s},Ve=()=>v.supportsLocalStorage()?Le():null;function K(){if(v.supportsWindow())return globalThis.window.pickedConfig}function Ne(){if(!v.supportsWindow())return;const t=K(),e=t?.organizationId,r=t?.projectId;return e&&r?{organizationId:e,projectId:r}:void 0}function Te(){if(!v.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 Ke(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,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 Ge(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 We(t,e){const r=t.split("|").map(p=>p.trim()),s=r.shift()??"";let n=Ge(s,e);for(const p of r){const[o,...c]=p.split(":"),a=o?.trim()??"",u=c.join(":").trim().replaceAll(/(?:^['"]|['"]$)/g,""),m=qe[a];m&&(n=m(n,u))}return R(n)?"":typeof n=="object"?JSON.stringify(n):String(n)}function Je(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+=We(n.trim(),e)}else r+=t[s++];return r}class K{static logger=E.logger;options;isReady=!1;project;plugins={};pluginStartHooks=[];eventBus=g.createEvent();events;organizationId;projectId;apiUrl;dashboardUrl;documentationSiteUrl;session;precondition;condition;preconditionPassed;searchParams=Me();history=be();components=ie({client:this});experienceInstances=I.createExperienceInstanceIndex({client:this});experiences=X({client:this});frameworks=ce({client:this});predicates=me({client:this});features=Se({client:this});responses=De({client:this});fields=xe();actions=Re();constructor(e){E.logger("info","Picked client initializing."),this.events=Ie(this.eventBus);const{organizationId:r,projectId:s}=_e(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=Ne(),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=()=>{pe(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:o,identifiers:c}=this.session;this.eventBus({type:"session",id:p,isUser:o,identifiers:c})}})()};registerFramework=e=>{ue(e,this.frameworks)};registerComponent=(e,r)=>{B(e,r,this.components)};registerPlugin=e=>{ee(this,e,this.plugins);const r=this.plugins[e.name];r?.onStart&&this.pluginStartHooks.push(r.onStart)};registerFeature=(e,r)=>{ve(e,r,this.features)};registerPredicate=(e,r)=>{ye(e,r,this.predicates)};registerField=e=>{je(e,this.fields)};registerAction=(e,r)=>{Ce(e,r,this.actions)};registerExperience=e=>{e.component&&B(`experience:${e.id}`,e.component,this.components),Z(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 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 o=(await Promise.all(s.options.map(async a=>a.condition?await I.evaluateRuleLogic(t,a.condition)?a:null:a))).filter(a=>a!==null);return o.length===s.options.length?s:o.length===0?null:{...s,options:o}}))).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 K(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=K;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 C(t){return t==null||t===""||Number.isNaN(t)}const _e={default:(t,e)=>C(t)?String(e??""):String(t),append:(t,e)=>e&&!C(t)?`${t} ${e}`:t,prepend:(t,e)=>e&&!C(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 qe(t){return typeof t=="object"&&t!==null}function He(t,e){let r=e;for(const s of t.split("."))if(qe(r)&&s in r)r=r[s];else return;return typeof r=="function"?r():r}function Ge(t,e){const r=t.split("|").map(f=>f.trim()),s=r.shift()??"";let n=He(s,e);for(const f of r){const[i,...a]=f.split(":"),o=i?.trim()??"",c=a.join(":").trim().replaceAll(/(?:^['"]|['"]$)/g,""),m=_e[o];m&&(n=m(n,c))}return C(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=ze({client:this});fields=Ee();actions=Pe();constructor(e){E.logger("info","Picked client initializing."),this.events=be(this.eventBus);const{organizationId:r,projectId:s}=Ke(e);this.organizationId=r,this.projectId=s,this.options=Object.freeze(e),this.apiUrl=e.apiUrl||De(),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:L.getVersion()}),E.logger("info","Picked client initialized.")}start=()=>{de(this),(async()=>{if(!v.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 f=s;this.session.setIsUser(f),this.eventBus({type:"user_decide",value:f})}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:f,isUser:i,identifiers:a}=this.session;this.eventBus({type:"session",id:f,isUser:i,identifiers:a})}})()};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=()=>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 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 f=n;f==="true"&&(f=!0),f==="false"&&(f=!1),this.registerFeature(s,{key:`${f}`,name:s,decide:()=>f,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,f)=>(n[f.fieldId]=f.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 i=(await Promise.all(s.options.map(async o=>o.condition?await I.evaluateRuleLogic(t,o.condition)?o:null:o))).filter(o=>o!==null);return i.length===s.options.length?s:i.length===0?null:{...s,options:i}}))).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 v.bindClient(e),e};exports.evaluateRuleLogic=I.evaluateRuleLogic;exports.isPickedRoot=I.isPickedRoot;exports.createStorageKey=b.createStorageKey;exports.localStore=b.localStore;exports.sessionStore=b.sessionStore;exports.subscribe=b.subscribe;exports.supportsCookies=v.supportsCookies;exports.supportsCryptoRandomUUID=v.supportsCryptoRandomUUID;exports.supportsDocument=v.supportsDocument;exports.supportsHistory=v.supportsHistory;exports.supportsIntersectionObserver=v.supportsIntersectionObserver;exports.supportsLocalStorage=v.supportsLocalStorage;exports.supportsLocation=v.supportsLocation;exports.supportsSessionStorage=v.supportsSessionStorage;exports.supportsShadowRoot=v.supportsShadowRoot;exports.supportsWebComponents=v.supportsWebComponents;exports.supportsWindow=v.supportsWindow;exports.Picked=_;exports.createClient=Ze;exports.getPickedConfig=K;exports.getStepFields=Ye;exports.isLazyLoader=Xe;exports.lazyComponent=Qe;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const h=require("../../../id-BKIWbSTy.cjs"),m=require("../../../to-kebab-case-BsOQ8CON.cjs"),r={serialize(i){return JSON.stringify(i)},deserialize(i){return JSON.parse(i)}},N=i=>({name:"create-experience",setup:o=>{i.experiences.forEach(t=>{const s=t.serialize(),a=r.deserialize(s);a.component=t.component,o.registerExperience(a),a.fields.forEach(f=>{o.registerField(f)})})}}),b=(i,o)=>({id:h.generateId("node"),experience:o,type:"action",action:i.action,addNext(s){if(!s.node)throw new Error("Cannot connect to node");const a=c({sourceNode:this,destinationNode:s.node,sourceNodeHandle:null},o);o.edges.push(a)},onSuccess(s){if(!s.node)throw new Error("Cannot connect to node");const a=c({sourceNode:this,destinationNode:s.node,sourceNodeHandle:"true"},o);o.edges.push(a)},onFail(s){if(!s.node)throw new Error("Cannot connect to node");const a=c({sourceNode:this,destinationNode:s.node,sourceNodeHandle:"false"},o);o.edges.push(a)},serialize(){return r.serialize({id:this.id,type:this.type,action:this.action})}}),z=i=>({id:i.id??h.generateId("step"),key:i.key??m.toKebabCase(i.name),name:i.name,fields:i.fields??[],addField(o){const t="serialize"in o?o:y(o);return this.fields.includes(t)||this.fields.push(t),t}}),v=(i,o)=>{const t={id:i.id??h.generateId("step"),key:i.key??m.toKebabCase(i.name),name:i.name,experience:o,fields:i.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,key:m.toKebabCase(this.name),name:this.name,fieldIds:this.fields.map(s=>s.id)})}};return p({step:t,type:"step"},o),t},p=(i,o)=>{const t={id:h.generateId("node"),experience:o};if(i.type==="step"){const a={...t,type:"step",connectedStep:i.step,serialize(){return r.serialize({id:this.id,type:this.type,stepId:this.connectedStep.id,name:this.connectedStep.name})}};return a.connectedStep.node=a,a}if(i.type==="conditional"){const a={...t,type:"conditional",connectedConditional:i.conditional,serialize(){return r.serialize({id:this.id,type:this.type,conditionalId:this.connectedConditional.id})}};return a.connectedConditional.node=a,a}return i.type==="experience"?{...t,type:"experience",connectedExperience:i.experience,serialize(){return r.serialize({id:this.id,type:this.type,experienceId:this.connectedExperience.id})}}:{...t,type:"origin",serialize(){return r.serialize({id:this.id,type:this.type})}}},c=(i,o)=>({id:h.generateId("edge"),sourceNode:i.sourceNode,sourceNodeHandle:i.sourceNodeHandle,destinationNode:i.destinationNode,experience:o,serialize(){return r.serialize({id:this.id,sourceNodeHandle:this.sourceNodeHandle??void 0,sourceNodeId:this.sourceNode.id,destinationNodeId:this.destinationNode.id})}}),g=(i,o)=>{const t={id:h.generateId("conditional"),label:i.label,condition:i.condition,node:null,experience:o,addTrue(s){if(!this.node||!s.node)throw new Error("todo no node");const a=c({sourceNode:this.node,destinationNode:s.node,sourceNodeHandle:"true"},this.experience);this.experience.edges.push(a)},addFalse(s){if(!this.node||!s.node)throw new Error("todo no node");const a=c({sourceNode:this.node,destinationNode:s.node,sourceNodeHandle:"false"},this.experience);this.experience.edges.push(a)},serialize(){return r.serialize({id:this.id,label:this.label,condition:this.condition})}};return p({conditional:t,type:"conditional"},o),t},y=i=>({id:i.id??h.generateId("field"),key:i.key??m.toKebabCase(i.name),name:i.name,type:i.type,label:i.label,placeholder:i.placeholder,description:i.description,helpText:i.helpText,defaultValue:i.defaultValue??null,multiple:i.multiple,validation:i.validation??{},condition:i.condition,required:i.required,options:i.options?.map(t=>({id:"id"in t?t.id:h.generateId("option"),...t}))??null,policies:i.policies,serialize(){const t={id:this.id,key:this.key,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,a=typeof this.defaultValue=="number"?this.defaultValue:void 0,f=typeof this.defaultValue=="boolean"?this.defaultValue:void 0;switch(this.type){case"text":if(this.multiple){let e;if(Array.isArray(this.defaultValue)){e=[];for(const n of this.defaultValue)typeof n=="string"&&e.push(n);e.length===0&&(e=void 0)}return r.serialize({...t,type:"text",multiple:!0,defaultValue:e,options:this.options?this.options.map(n=>({id:n.id,label:n.label,value:`${n.value}`,condition:n.condition})):null})}return r.serialize({...t,type:"text",multiple:!1,defaultValue:s,options:this.options?this.options.map(e=>({id:e.id,label:e.label,value:`${e.value}`,condition:e.condition})):null});case"number":if(this.multiple){let e;if(Array.isArray(this.defaultValue)){e=[];for(const n of this.defaultValue)typeof n=="number"&&e.push(n);e.length===0&&(e=void 0)}return r.serialize({...t,type:"number",multiple:!0,defaultValue:e,options:this.options?this.options.map(n=>({id:n.id,label:n.label,value:Number(n.value),condition:n.condition})):null})}return r.serialize({...t,type:"number",multiple:!1,defaultValue:a,options:this.options?this.options.map(e=>({id:e.id,label:e.label,value:Number(e.value),condition:e.condition})):null});case"boolean":if(this.multiple){let e;if(Array.isArray(this.defaultValue)){e=[];for(const n of this.defaultValue)typeof n=="boolean"&&e.push(n);e.length===0&&(e=void 0)}return r.serialize({...t,type:"boolean",multiple:!0,defaultValue:e,options:this.options?this.options.map(n=>({id:n.id,label:n.label,value:!!n.value,condition:n.condition})):null})}return r.serialize({...t,type:"boolean",multiple:!1,defaultValue:f,options:this.options?this.options.map(e=>({id:e.id,label:e.label,value:!!e.value,condition:e.condition})):null});case"object":return this.multiple?r.serialize({...t,type:"object",multiple:!0,defaultValue:this.defaultValue,options:this.options?this.options.map(e=>({id:e.id,label:e.label,description:e.description,value:e.value,condition:e.condition})):null}):r.serialize({...t,type:"object",multiple:!1,defaultValue:this.defaultValue,options:this.options?this.options.map(e=>({id:e.id,label:e.label,description:e.description,value:e.value,condition:e.condition})):null});default:throw new Error("Unsupported field type")}}}),x=i=>{const o=[],t=[],s=[],a=[],f=[];return{id:i.id,component:i.component,name:i.name,initializeOpen:i.initializeOpen,condition:i.condition,targets:i.targets,steps:o,nodes:t,edges:s,fields:f,conditionals:a,addStep(e,n){let l=n?.node;this.nodes.length===0&&(l=p({type:"origin"},this),this.nodes.push(l));let d="serialize"in e?e:v(e,this);if(d={...d,id:d.id??h.generateId("step"),key:d.key??m.toKebabCase(d.name)},l){if(!d.node)throw new Error("todo no node");const u=c({sourceNode:l,destinationNode:d.node,sourceNodeHandle:null},this);this.edges.push(u)}return d.fields.length>0&&d.fields.forEach(u=>{this.fields.includes(u)||this.fields.push(u)}),this.steps.includes(d)||(this.steps.push(d),d.node&&this.nodes.push(d.node)),d},addAction(e,n){let l=n?.node;this.nodes.length===0&&(l=p({type:"origin"},this),this.nodes.push(l));const d="serialize"in e?e:b(e,this);if(l){const u=c({sourceNode:l,destinationNode:d,sourceNodeHandle:null},this);this.edges.push(u)}return this.nodes.push(d),d},addConditional(e,n){let l=n?.node;this.nodes.length===0&&(l=p({type:"origin"},this),this.nodes.push(l));const d="serialize"in e?e:g(e,this);if(l){if(!d.node)throw new Error("todo no node");const u=c({sourceNode:l,destinationNode:d.node,sourceNodeHandle:null},this);this.edges.push(u)}return this.conditionals.includes(d)||(this.conditionals.push(d),d.node&&this.nodes.push(d.node)),d},addExperience(e,n){let l=n?.node;this.nodes.length===0&&(l=p({type:"origin"},this),this.nodes.push(l));const d=p({type:"experience",experience:e},this);if(this.nodes.push(d),l){const u=c({sourceNode:l,destinationNode:d,sourceNodeHandle:null},this);this.edges.push(u)}return e},addField(e,n){const l="serialize"in e?e:y(e);return n&&n.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,targets:this.targets,steps:this.steps.map(e=>r.deserialize(e.serialize())),nodes:this.nodes.map(e=>r.deserialize(e.serialize())),edges:this.edges.map(e=>r.deserialize(e.serialize())),conditionals:this.conditionals.map(e=>r.deserialize(e.serialize())),fields:this.fields.map(e=>r.deserialize(e.serialize()))})}}};exports.createConditional=g;exports.createEdge=c;exports.createExperience=x;exports.createExperiencePlugin=N;exports.createField=y;exports.createNode=p;exports.createStep=z;exports.serialization=r;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("../../../id-BKIWbSTy.cjs"),m=require("../../../to-kebab-case-BsOQ8CON.cjs"),r={serialize(i){return JSON.stringify(i)},deserialize(i){return JSON.parse(i)}},N=i=>({name:"create-experience",setup:o=>{i.experiences.forEach(n=>{const d=n.serialize(),s=r.deserialize(d);s.component=n.component,o.registerExperience(s),s.fields.forEach(u=>{o.registerField(u)})})}}),b=(i,o)=>({id:f.generateId("node"),experience:o,type:"action",action:i.action,addNext(d){if(!d.node)throw new Error("Cannot connect to node");const s=h({sourceNode:this,destinationNode:d.node,sourceNodeHandle:null},o);o.edges.push(s)},onSuccess(d){if(!d.node)throw new Error("Cannot connect to node");const s=h({sourceNode:this,destinationNode:d.node,sourceNodeHandle:"true"},o);o.edges.push(s)},onFail(d){if(!d.node)throw new Error("Cannot connect to node");const s=h({sourceNode:this,destinationNode:d.node,sourceNodeHandle:"false"},o);o.edges.push(s)},serialize(){return r.serialize({id:this.id,type:this.type,action:this.action})}}),z=i=>{const o=i.name??i.label??"";return{id:i.id??f.generateId("step"),key:i.key??m.toKebabCase(o),name:o,fields:i.fields??[],addField(n){const d="serialize"in n?n:y(n);return this.fields.includes(d)||this.fields.push(d),d}}},v=(i,o)=>{const n="label"in i?i.label:void 0,d=i.name??n??"",s={id:i.id??f.generateId("step"),key:i.key??m.toKebabCase(d),name:d,experience:o,fields:i.fields??[],node:null,nextStep(u){return this.experience.addStep(u,this)},nextConditional(u){return this.experience.addConditional(u,this)},addNextExperience(u){return this.experience.addExperience(u,this)},addField(u){return this.experience.addField(u,this)},serialize(){return r.serialize({id:this.id,key:m.toKebabCase(this.name),name:this.name,fieldIds:this.fields.map(u=>u.id)})}};return p({step:s,type:"step"},o),s},p=(i,o)=>{const n={id:f.generateId("node"),experience:o};if(i.type==="step"){const s={...n,type:"step",connectedStep:i.step,serialize(){return r.serialize({id:this.id,type:this.type,stepId:this.connectedStep.id,name:this.connectedStep.name})}};return s.connectedStep.node=s,s}if(i.type==="conditional"){const s={...n,type:"conditional",connectedConditional:i.conditional,serialize(){return r.serialize({id:this.id,type:this.type,conditionalId:this.connectedConditional.id})}};return s.connectedConditional.node=s,s}return i.type==="experience"?{...n,type:"experience",connectedExperience:i.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=(i,o)=>({id:f.generateId("edge"),sourceNode:i.sourceNode,sourceNodeHandle:i.sourceNodeHandle,destinationNode:i.destinationNode,experience:o,serialize(){return r.serialize({id:this.id,sourceNodeHandle:this.sourceNodeHandle??void 0,sourceNodeId:this.sourceNode.id,destinationNodeId:this.destinationNode.id})}}),g=(i,o)=>{const n={id:f.generateId("conditional"),label:i.label,condition:i.condition,node:null,experience:o,addTrue(d){if(!this.node||!d.node)throw new Error("todo no node");const s=h({sourceNode:this.node,destinationNode:d.node,sourceNodeHandle:"true"},this.experience);this.experience.edges.push(s)},addFalse(d){if(!this.node||!d.node)throw new Error("todo no node");const s=h({sourceNode:this.node,destinationNode:d.node,sourceNodeHandle:"false"},this.experience);this.experience.edges.push(s)},serialize(){return r.serialize({id:this.id,label:this.label,condition:this.condition})}};return p({conditional:n,type:"conditional"},o),n},y=i=>({id:i.id??f.generateId("field"),key:i.key??m.toKebabCase(i.name),name:i.name,type:i.type,label:i.label,placeholder:i.placeholder,description:i.description,helpText:i.helpText,defaultValue:i.defaultValue??null,multiple:i.multiple,validation:i.validation??{},condition:i.condition,required:i.required,options:i.options?.map(n=>({id:"id"in n?n.id:f.generateId("option"),...n}))??null,policies:i.policies,serialize(){const n={id:this.id,key:this.key,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},d=typeof this.defaultValue=="string"?this.defaultValue:void 0,s=typeof this.defaultValue=="number"?this.defaultValue:void 0,u=typeof this.defaultValue=="boolean"?this.defaultValue:void 0;switch(this.type){case"text":if(this.multiple){let e;if(Array.isArray(this.defaultValue)){e=[];for(const t of this.defaultValue)typeof t=="string"&&e.push(t);e.length===0&&(e=void 0)}return r.serialize({...n,type:"text",multiple:!0,defaultValue:e,options:this.options?this.options.map(t=>({id:t.id,label:t.label,value:`${t.value}`,condition:t.condition})):null})}return r.serialize({...n,type:"text",multiple:!1,defaultValue:d,options:this.options?this.options.map(e=>({id:e.id,label:e.label,value:`${e.value}`,condition:e.condition})):null});case"number":if(this.multiple){let e;if(Array.isArray(this.defaultValue)){e=[];for(const t of this.defaultValue)typeof t=="number"&&e.push(t);e.length===0&&(e=void 0)}return r.serialize({...n,type:"number",multiple:!0,defaultValue:e,options:this.options?this.options.map(t=>({id:t.id,label:t.label,value:Number(t.value),condition:t.condition})):null})}return r.serialize({...n,type:"number",multiple:!1,defaultValue:s,options:this.options?this.options.map(e=>({id:e.id,label:e.label,value:Number(e.value),condition:e.condition})):null});case"boolean":if(this.multiple){let e;if(Array.isArray(this.defaultValue)){e=[];for(const t of this.defaultValue)typeof t=="boolean"&&e.push(t);e.length===0&&(e=void 0)}return r.serialize({...n,type:"boolean",multiple:!0,defaultValue:e,options:this.options?this.options.map(t=>({id:t.id,label:t.label,value:!!t.value,condition:t.condition})):null})}return r.serialize({...n,type:"boolean",multiple:!1,defaultValue:u,options:this.options?this.options.map(e=>({id:e.id,label:e.label,value:!!e.value,condition:e.condition})):null});case"object":return this.multiple?r.serialize({...n,type:"object",multiple:!0,defaultValue:this.defaultValue,options:this.options?this.options.map(e=>({id:e.id,label:e.label,description:e.description,value:e.value,condition:e.condition})):null}):r.serialize({...n,type:"object",multiple:!1,defaultValue:this.defaultValue,options:this.options?this.options.map(e=>({id:e.id,label:e.label,description:e.description,value:e.value,condition:e.condition})):null});default:throw new Error("Unsupported field type")}}}),x=i=>{const o=[],n=[],d=[],s=[],u=[];return{id:i.id,component:i.component,name:i.name,initializeOpen:i.initializeOpen,condition:i.condition,targets:i.targets,steps:o,nodes:n,edges:d,fields:u,conditionals:s,addStep(e,t){let a=t?.node;this.nodes.length===0&&(a=p({type:"origin"},this),this.nodes.push(a));const l="serialize"in e?e:v(e,this);if(a){if(!l.node)throw new Error("todo no node");const c=h({sourceNode:a,destinationNode:l.node,sourceNodeHandle:null},this);this.edges.push(c)}return l.fields.length>0&&l.fields.forEach(c=>{this.fields.includes(c)||this.fields.push(c)}),this.steps.includes(l)||(this.steps.push(l),l.node&&this.nodes.push(l.node)),l},addAction(e,t){let a=t?.node;this.nodes.length===0&&(a=p({type:"origin"},this),this.nodes.push(a));const l="serialize"in e?e:b(e,this);if(a){const c=h({sourceNode:a,destinationNode:l,sourceNodeHandle:null},this);this.edges.push(c)}return this.nodes.push(l),l},addConditional(e,t){let a=t?.node;this.nodes.length===0&&(a=p({type:"origin"},this),this.nodes.push(a));const l="serialize"in e?e:g(e,this);if(a){if(!l.node)throw new Error("todo no node");const c=h({sourceNode:a,destinationNode:l.node,sourceNodeHandle:null},this);this.edges.push(c)}return this.conditionals.includes(l)||(this.conditionals.push(l),l.node&&this.nodes.push(l.node)),l},addExperience(e,t){let a=t?.node;this.nodes.length===0&&(a=p({type:"origin"},this),this.nodes.push(a));const l=p({type:"experience",experience:e},this);if(this.nodes.push(l),a){const c=h({sourceNode:a,destinationNode:l,sourceNodeHandle:null},this);this.edges.push(c)}return e},addField(e,t){const a="serialize"in e?e:y(e);return t&&t.fields.push(a),this.fields.includes(a)||this.fields.push(a),a},serialize(){return r.serialize({id:this.id,component:this.component,name:this.name,initializeOpen:this.initializeOpen,condition:this.condition,targets:this.targets,steps:this.steps.map(e=>r.deserialize(e.serialize())),nodes:this.nodes.map(e=>r.deserialize(e.serialize())),edges:this.edges.map(e=>r.deserialize(e.serialize())),conditionals:this.conditionals.map(e=>r.deserialize(e.serialize())),fields:this.fields.map(e=>r.deserialize(e.serialize()))})}}};exports.createConditional=g;exports.createEdge=h;exports.createExperience=x;exports.createExperiencePlugin=N;exports.createField=y;exports.createNode=p;exports.createStep=z;exports.serialization=r;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const f=require("../../../api-F0IOGUor.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 h(e){return typeof e!="object"||e===null||!("key"in e&&"name"in e&&"enabled"in e&&"weight"in e&&"version"in e)?!1:typeof e.key=="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 o of n){const t=o.indexOf(":");t>0&&r.add(o.substring(0,t))}return r}function c(e,r,n){const o=m(e),t=e.session?.id;if(!t)throw new Error("Session ID is required for feature registration");const i=d(t);for(const s of r.features)o.has(s.key)||v(e,s,n,i)}function v(e,r,n,o){e.registerFeature(r.key,{key:`v${r.version}`,name:r.name,storage:n?"session":"local",decide:()=>r.enabled?p(o,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 o=n?.previewToken?`projects/${r}?preview_token=${encodeURIComponent(n.previewToken)}`:`projects/${r}`;let t;try{t=await f.get(e,o,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 i;try{i=await t.json()}catch{return a.logger("warn","Failed to parse project config response"),null}return l(i)?i:(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 o=y(r);if(o){const s=await u(n,r.projectId,{previewToken:o});s&&c(r,s,!0);return}const t=e?.projectConfig??w();if(t){c(r,t,!1);return}const i=await u(n,r.projectId);i&&c(r,i,!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-Cn-rv5A5.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 h(e){return typeof e!="object"||e===null||!("key"in e&&"name"in e&&"enabled"in e&&"weight"in e&&"version"in e)?!1:typeof e.key=="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 o of n){const t=o.indexOf(":");t>0&&r.add(o.substring(0,t))}return r}function c(e,r,n){const o=m(e),t=e.session?.id;if(!t)throw new Error("Session ID is required for feature registration");const i=d(t);for(const s of r.features)o.has(s.key)||v(e,s,n,i)}function v(e,r,n,o){e.registerFeature(r.key,{key:`v${r.version}`,name:r.name,storage:n?"session":"local",decide:()=>r.enabled?p(o,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 o=n?.previewToken?`projects/${r}?preview_token=${encodeURIComponent(n.previewToken)}`:`projects/${r}`;let t;try{t=await f.get(e,o,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 i;try{i=await t.json()}catch{return a.logger("warn","Failed to parse project config response"),null}return l(i)?i:(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 o=y(r);if(o){const s=await u(n,r.projectId,{previewToken:o});s&&c(r,s,!0);return}const t=e?.projectConfig??w();if(t){c(r,t,!1);return}const i=await u(n,r.projectId);i&&c(r,i,!1)}}}}}exports.createClientHeaders=f.createClientHeaders;exports.dynamicExperiencesPlugin=P;exports.fetchProject=u;