@uniformdev/canvas 16.2.4 → 17.1.1-alpha.151

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -1,4 +1 @@
1
- import{d as L,e as l,f as $,g as j,h as k,i as F,j as A,k as V,l as g,m as N,n as U,o as v,p as z,q as W,r as x,s as w,t as H}from"./chunk-ADDR7SB6.mjs";function u(o,e){let t=[{ancestorsAndSelf:[{component:o,parentSlot:void 0,parentSlotIndex:void 0}]}];do{let n=t.pop();if(!n)continue;let r=n.ancestorsAndSelf[0];e(r.component,n.ancestorsAndSelf,{replaceComponent:i=>{Object.assign(r.component,i),["parameters","variant","slots","data","_pattern","_patternError"].forEach(s=>{i[s]||delete r.component[s]})},removeComponent:()=>{let{parentSlot:i,parentSlotIndex:c}=n.ancestorsAndSelf[0],s=n.ancestorsAndSelf[1];if(i&&typeof c!="undefined")s.component.slots[i].splice(c,1);else throw new Error("Unable to delete composition.")},insertAfter:i=>{let c=Array.isArray(i)?i:[i],{parentSlot:s,parentSlotIndex:p}=n.ancestorsAndSelf[0],m=n.ancestorsAndSelf[1];if(s&&typeof p!="undefined")m.component.slots[s].splice(p+1,0,...c);else throw new Error("Unable to insert after a component not in a slot.")}});let a=r.component.slots;if(a){let i=Object.keys(a);for(let c=i.length-1;c>=0;c--){let s=i[c],p=a[s];for(let m=p.length-1;m>=0;m--)t.push({ancestorsAndSelf:[{component:p[m],parentSlot:s,parentSlotIndex:m},...n.ancestorsAndSelf]})}}}while(t.length>0)}function y(o){let e=[];for(let t=o.length-1;t>=0;t--){let{parentSlot:n,parentSlotIndex:r}=o[t];n&&r!==void 0&&e.push(`${n}[${r}]`)}return`.${e.join(".")}`}var T=class{constructor(e,t){this.groups=e.reduce((n,r)=>{var i;let a=t(r.args);return n[a]=(i=n[a])!=null?i:[],n[a].push(r),n},{})}resolveKey(e,t){this.groups[e].forEach(n=>n.resolve(t))}resolveRemaining(e){Object.keys(this.groups).forEach(t=>{this.groups[t].forEach(n=>{n.isCompleted||n.resolve(e)})})}};var d=class{constructor(){this._paramMatches=Array();this._dataMatches=new Map}parameter(e){return this._paramMatches.push({enhancer:this._resolveParameterEnhancer(e)}),this}parameterName(e,t){return(Array.isArray(e)?e:[e]).forEach(r=>this._paramMatches.push({name:r,enhancer:this._resolveParameterEnhancer(t)})),this}parameterType(e,t){return(Array.isArray(e)?e:[e]).forEach(r=>this._paramMatches.push({type:r,enhancer:this._resolveParameterEnhancer(t)})),this}data(e,t){if(this._dataMatches.has(e))throw new Error(`${e} enhancer data key has been used more than once. This will cause data loss.`);return this._dataMatches.set(e,typeof t=="function"?{enhanceOne:t}:t),this}resolveParameterEnhancer(e,t){var n;return(n=this._paramMatches.find(r=>r.name&&r.name===e||r.type&&r.type===t.type||!r.type&&!r.name))==null?void 0:n.enhancer}resolveComponentEnhancers(){return this._dataMatches}_resolveParameterEnhancer(e){return typeof e=="function"?{enhanceOne:e}:e}},_=class{constructor(){this._componentIndex={};this._rootBuilder=new d}parameter(e){return this._rootBuilder.parameter(e),this}parameterName(e,t){return this._rootBuilder.parameterName(e,t),this}parameterType(e,t){return this._rootBuilder.parameterType(e,t),this}data(e,t){return this._rootBuilder.data(e,t),this}component(e,t){return(Array.isArray(e)?e:[e]).forEach(r=>{this._componentIndex[r]=this._componentIndex[r]||new d,t(this._componentIndex[r])}),this}resolveParameterEnhancer(e,t,n){let r=this._componentIndex[e.type];if(r){let a=r.resolveParameterEnhancer(t,n);if(a)return a}return this._rootBuilder.resolveParameterEnhancer(t,n)}resolveComponentEnhancers(e){let t=this._rootBuilder.resolveComponentEnhancers(),n=this._componentIndex[e.type];if(n){t=new Map(t);for(let[r,a]of n.resolveComponentEnhancers())t.set(r,a)}return t}};var C=class{constructor(e,t,n){this._resolve=e;this._reject=t;this.args=n;this._isCompleted=!1}resolve(e){this._resolve(e),this._isCompleted=!0}reject(e){this._reject(e),this._isCompleted=!0}get isCompleted(){return this._isCompleted}};function D({handleBatch:o,shouldQueue:e,limitPolicy:t}){let n=[];return{enhanceOne:async i=>{if(!e||e(i))return new Promise((c,s)=>{n.push(new C(c,s,i))})},completeAll:async()=>{if(n.length>0){try{await o(n)}catch(c){n.forEach(s=>s.reject(c))}if(n.some(c=>!c.isCompleted))throw new Error("The completeAll() function failed to resolve or reject all promises in the batch!")}let i=n.length;return n=[],i},limitPolicy:t}}async function X({composition:o,enhancers:e,context:t,onErrors:n=r=>{throw new Error(r.map(a=>`${a.message}
2
- ${typeof a.error=="object"&&"stack"in a.error?a.error.stack:a.error}`).join(`
3
-
4
- `))}}){let r=[],a=new Set,i=new Set;u(o,(s,p)=>{var h;Object.entries((h=s.parameters)!=null?h:{}).forEach(([E,P])=>{let f=e.resolveParameterEnhancer(s,E,P);f&&(i.add(f),r.push(S(s,p,E,P,f,t)))});let m=e.resolveComponentEnhancers(s);r.push(R(s,p,m,t)),a.add(m)}),r.push(...Array.from(a).flatMap(s=>Array.from(s).map(async([,p])=>{var m;try{p.completeAll&&await((m=p.limitPolicy)!=null?m:l)(()=>p.completeAll())}catch(h){return{error:h,message:"Batch component enhancer failed. Individual failed components should receive their own rejections."}}}))),r.push(...Array.from(i).map(async s=>{var p;try{s.completeAll&&await((p=s.limitPolicy)!=null?p:l)(()=>s.completeAll())}catch(m){return{error:m,message:"Batch parameter enhancer failed. Individual failed parameters should receive their own rejections."}}}));let c=(await Promise.all(r)).flatMap(s=>Array.isArray(s)?s:[s]).filter(s=>s);c.length&&n(c)}async function R(o,e,t,n){return t.size&&(o.data={}),await Promise.all(Array.from(t).map(async([r,a])=>{var i;try{let s=await(a.completeAll?l:(i=a.limitPolicy)!=null?i:l)(async()=>a.enhanceOne({component:o,context:n}));s!=null&&(o.data[r]=s)}catch(c){let s=`Component ${y(e)} (type: ${o.type}): data.${r} enhancer threw exception. Data key will not be present.`;return delete o.data[r],{message:s,error:c}}}))}async function S(o,e,t,n,r,a){var i;try{let s=await(r.completeAll?l:(i=r.limitPolicy)!=null?i:l)(async()=>r.enhanceOne({parameter:n,parameterName:t,component:o,context:a}));s===null?delete o.parameters[t]:typeof s=="undefined"?o.parameters[t]={...n,value:n.value}:o.parameters[t]={...n,value:s}}catch(c){let s=`Component ${y(e)} (type: ${o.type}): enhancing parameter ${t} (type: ${n.type}) threw exception. Parameter will be removed.`;return delete o.parameters[t],{message:s,error:c}}}var ne=(o,...e)=>({enhanceOne:n=>{let r="enhanceOne"in o?o.enhanceOne(n):o(n);for(let a of e){let i=B(r)?r:Promise.resolve(r),c="enhanceOne"in a?a.enhanceOne:a;r=i.then(s=>c({...n,parameter:{type:n.parameter.type,value:s}}))}return r},completeAll:async()=>{var n,r;for(let a of e)if("completeAll"in a)throw new Error("Only the first enhancer in a compose chain can use the completeAll function (batching)");return(r="completeAll"in o?(n=o.completeAll)==null?void 0:n.call(o):0)!=null?r:0}});function B(o){return!!o&&(typeof o=="object"||typeof o=="function")&&typeof o.then=="function"}var re=o=>o.startsWith("$");function se(o){return o?o.map((e,t)=>{var a,i;let n=(i=(a=e.parameters)==null?void 0:a[x])==null?void 0:i.value,r=(n==null?void 0:n.name)||`pz-${t}-${e.type}`;return{...e,id:r,pz:n}}):[]}function pe(o){return o?o.map((e,t)=>{var a,i,c;let n=(i=(a=e.parameters)==null?void 0:a[w])==null?void 0:i.value,r=(c=n==null?void 0:n.id)!=null?c:"testId"in e?e.testId:`ab-${t}-${e.type}`;return{...e,id:r}}):[]}var b="https://js.pusher.com/7.0.3/pusher.min.js";async function O(){if(!(typeof document=="undefined"||typeof window=="undefined"))return window.Pusher?window.Pusher:new Promise((o,e)=>{let t=setTimeout(()=>{window.Pusher&&o(window.Pusher),e(`Unable to load pusher.js; Uniform Canvas live preview disabled. Consider adding <script src="${b}"><\/script> manually.`)},5e3),n=document.createElement("script");n.src=b,n.addEventListener("load",()=>{clearTimeout(t),o(window.Pusher)}),document.head.appendChild(n)})}async function le(){let o=await O();if(!o)return;let e=window.__UNIFORM_EVENT_BUS__;if(!e){let t=new o("7b5f5abd160fea549ffe",{cluster:"mt1"});t.connect(),console.log("[canvas] \u{1F525} preview connected"),e=window.__UNIFORM_EVENT_BUS__={subscribe:n=>{let r=t.subscribe(n);return{unsubscribe:()=>t.unsubscribe(n),addEventHandler:(a,i)=>(r.bind(a,i),()=>r.unbind(a,i))}}}}return e}function I(o,e,t){return`${o}.${e}@${t}`}function fe({projectId:o,compositionId:e,compositionState:t=0,eventBus:{subscribe:n},callback:r,event:a="updated"}){let i=I(o,e,t),c=n(i),s=c.addEventHandler(a,r);return()=>{s(),c.unsubscribe()}}function M({component:o}){var n;let e={},t=(n=o.slots)==null?void 0:n[v];return t==null||t.forEach(r=>{var i;let a=(i=r.parameters)==null?void 0:i[g];(a==null?void 0:a.value)&&typeof a.value=="string"&&(e[a.value]=e[a.value]||[],e[a.value].push(r))}),e}function Pe({composition:o,locale:e}){u(o,(t,n,r)=>{if(t.type===A){let a=M({component:t}),i=typeof e=="string"?e:e({component:t,locales:a}),c;if(i&&(c=a[i]),c!=null&&c.length){let[s,...p]=c;r.replaceComponent(s),p.length&&r.insertAfter(p)}else r.removeComponent()}})}export{C as BatchEntry,z as CANVAS_DRAFT_STATE,H as CANVAS_ENRICHMENT_TAG_PARAM,V as CANVAS_INTENT_TAG_PARAM,g as CANVAS_LOCALE_TAG_PARAM,v as CANVAS_LOCALIZATION_SLOT,A as CANVAS_LOCALIZATION_TYPE,x as CANVAS_PERSONALIZATION_PARAM,N as CANVAS_PERSONALIZE_SLOT,k as CANVAS_PERSONALIZE_TYPE,W as CANVAS_PUBLISHED_STATE,U as CANVAS_TEST_SLOT,F as CANVAS_TEST_TYPE,w as CANVAS_TEST_VARIANT_PARAM,j as CanvasClient,$ as CanvasClientError,d as ChildEnhancerBuilder,_ as EnhancerBuilder,T as UniqueBatchEntries,ne as compose,D as createBatchEnhancer,le as createEventBus,L as createLimitPolicy,X as enhance,M as extractLocales,I as getChannelName,y as getComponentPath,re as isSystemComponentDefinition,Pe as localize,se as mapSlotToPersonalizedVariations,pe as mapSlotToTestVariations,l as nullLimitPolicy,fe as subscribeToComposition,u as walkComponentTree};
1
+ import{A as p,B as q,C as r,D as s,E as t,F as u,G as v,H as w,I as x,J as y,K as z,L as A,M as B,N as C,O as D,P as E,Q as F,R as G,S as H,T as I,U as J,l as a,m as b,n as c,o as d,p as e,q as f,r as g,s as h,t as i,u as j,v as k,w as l,x as m,y as n,z as o}from"./chunk-PFL3XEAQ.mjs";export{f as BatchEntry,x as CANVAS_DRAFT_STATE,B as CANVAS_ENRICHMENT_TAG_PARAM,s as CANVAS_INTENT_TAG_PARAM,t as CANVAS_LOCALE_TAG_PARAM,w as CANVAS_LOCALIZATION_SLOT,r as CANVAS_LOCALIZATION_TYPE,z as CANVAS_PERSONALIZATION_PARAM,u as CANVAS_PERSONALIZE_SLOT,p as CANVAS_PERSONALIZE_TYPE,y as CANVAS_PUBLISHED_STATE,v as CANVAS_TEST_SLOT,q as CANVAS_TEST_TYPE,A as CANVAS_TEST_VARIANT_PARAM,l as CanvasClient,n as CanvasDataConnectionClient,o as CanvasDataTypeClient,d as ChildEnhancerBuilder,e as EnhancerBuilder,m as UncachedCanvasClient,c as UniqueBatchEntries,k as compose,g as createBatchEnhancer,F as createEventBus,h as createLimitPolicy,j as enhance,I as extractLocales,G as getChannelName,b as getComponentPath,C as isSystemComponentDefinition,J as localize,D as mapSlotToPersonalizedVariations,E as mapSlotToTestVariations,i as nullLimitPolicy,H as subscribeToComposition,a as walkComponentTree};
package/dist/index.js CHANGED
@@ -1,5 +1,4 @@
1
- var B=Object.create;var C=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var F=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty;var z=(r,e)=>{for(var n in e)C(r,n,{get:e[n],enumerable:!0})},L=(r,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of U(e))!D.call(r,o)&&o!==n&&C(r,o,{get:()=>e[o],enumerable:!(t=M(e,o))||t.enumerable});return r};var N=(r,e,n)=>(n=r!=null?B(F(r)):{},L(e||!r||!r.__esModule?C(n,"default",{value:r,enumerable:!0}):n,r)),H=r=>L(C({},"__esModule",{value:!0}),r);var me={};z(me,{BatchEntry:()=>P,CANVAS_DRAFT_STATE:()=>we,CANVAS_ENRICHMENT_TAG_PARAM:()=>te,CANVAS_INTENT_TAG_PARAM:()=>X,CANVAS_LOCALE_TAG_PARAM:()=>R,CANVAS_LOCALIZATION_SLOT:()=>x,CANVAS_LOCALIZATION_TYPE:()=>v,CANVAS_PERSONALIZATION_PARAM:()=>w,CANVAS_PERSONALIZE_SLOT:()=>ee,CANVAS_PERSONALIZE_TYPE:()=>W,CANVAS_PUBLISHED_STATE:()=>_e,CANVAS_TEST_SLOT:()=>ne,CANVAS_TEST_TYPE:()=>Q,CANVAS_TEST_VARIANT_PARAM:()=>_,CanvasClient:()=>y,CanvasClientError:()=>u,ChildEnhancerBuilder:()=>f,EnhancerBuilder:()=>I,UniqueBatchEntries:()=>g,compose:()=>Y,createBatchEnhancer:()=>q,createEventBus:()=>ae,createLimitPolicy:()=>T,enhance:()=>K,extractLocales:()=>k,getChannelName:()=>b,getComponentPath:()=>A,isSystemComponentDefinition:()=>oe,localize:()=>pe,mapSlotToPersonalizedVariations:()=>re,mapSlotToTestVariations:()=>ie,nullLimitPolicy:()=>l,subscribeToComposition:()=>ce,walkComponentTree:()=>d});module.exports=H(me);function d(r,e){let n=[{ancestorsAndSelf:[{component:r,parentSlot:void 0,parentSlotIndex:void 0}]}];do{let t=n.pop();if(!t)continue;let o=t.ancestorsAndSelf[0];e(o.component,t.ancestorsAndSelf,{replaceComponent:s=>{Object.assign(o.component,s),["parameters","variant","slots","data","_pattern","_patternError"].forEach(a=>{s[a]||delete o.component[a]})},removeComponent:()=>{let{parentSlot:s,parentSlotIndex:c}=t.ancestorsAndSelf[0],a=t.ancestorsAndSelf[1];if(s&&typeof c!="undefined")a.component.slots[s].splice(c,1);else throw new Error("Unable to delete composition.")},insertAfter:s=>{let c=Array.isArray(s)?s:[s],{parentSlot:a,parentSlotIndex:p}=t.ancestorsAndSelf[0],m=t.ancestorsAndSelf[1];if(a&&typeof p!="undefined")m.component.slots[a].splice(p+1,0,...c);else throw new Error("Unable to insert after a component not in a slot.")}});let i=o.component.slots;if(i){let s=Object.keys(i);for(let c=s.length-1;c>=0;c--){let a=s[c],p=i[a];for(let m=p.length-1;m>=0;m--)n.push({ancestorsAndSelf:[{component:p[m],parentSlot:a,parentSlotIndex:m},...t.ancestorsAndSelf]})}}}while(n.length>0)}function A(r){let e=[];for(let n=r.length-1;n>=0;n--){let{parentSlot:t,parentSlotIndex:o}=r[n];t&&o!==void 0&&e.push(`${t}[${o}]`)}return`.${e.join(".")}`}var g=class{constructor(e,n){this.groups=e.reduce((t,o)=>{var s;let i=n(o.args);return t[i]=(s=t[i])!=null?s:[],t[i].push(o),t},{})}resolveKey(e,n){this.groups[e].forEach(t=>t.resolve(n))}resolveRemaining(e){Object.keys(this.groups).forEach(n=>{this.groups[n].forEach(t=>{t.isCompleted||t.resolve(e)})})}};var f=class{constructor(){this._paramMatches=Array();this._dataMatches=new Map}parameter(e){return this._paramMatches.push({enhancer:this._resolveParameterEnhancer(e)}),this}parameterName(e,n){return(Array.isArray(e)?e:[e]).forEach(o=>this._paramMatches.push({name:o,enhancer:this._resolveParameterEnhancer(n)})),this}parameterType(e,n){return(Array.isArray(e)?e:[e]).forEach(o=>this._paramMatches.push({type:o,enhancer:this._resolveParameterEnhancer(n)})),this}data(e,n){if(this._dataMatches.has(e))throw new Error(`${e} enhancer data key has been used more than once. This will cause data loss.`);return this._dataMatches.set(e,typeof n=="function"?{enhanceOne:n}:n),this}resolveParameterEnhancer(e,n){var t;return(t=this._paramMatches.find(o=>o.name&&o.name===e||o.type&&o.type===n.type||!o.type&&!o.name))==null?void 0:t.enhancer}resolveComponentEnhancers(){return this._dataMatches}_resolveParameterEnhancer(e){return typeof e=="function"?{enhanceOne:e}:e}},I=class{constructor(){this._componentIndex={};this._rootBuilder=new f}parameter(e){return this._rootBuilder.parameter(e),this}parameterName(e,n){return this._rootBuilder.parameterName(e,n),this}parameterType(e,n){return this._rootBuilder.parameterType(e,n),this}data(e,n){return this._rootBuilder.data(e,n),this}component(e,n){return(Array.isArray(e)?e:[e]).forEach(o=>{this._componentIndex[o]=this._componentIndex[o]||new f,n(this._componentIndex[o])}),this}resolveParameterEnhancer(e,n,t){let o=this._componentIndex[e.type];if(o){let i=o.resolveParameterEnhancer(n,t);if(i)return i}return this._rootBuilder.resolveParameterEnhancer(n,t)}resolveComponentEnhancers(e){let n=this._rootBuilder.resolveComponentEnhancers(),t=this._componentIndex[e.type];if(t){n=new Map(n);for(let[o,i]of t.resolveComponentEnhancers())n.set(o,i)}return n}};var P=class{constructor(e,n,t){this._resolve=e;this._reject=n;this.args=t;this._isCompleted=!1}resolve(e){this._resolve(e),this._isCompleted=!0}reject(e){this._reject(e),this._isCompleted=!0}get isCompleted(){return this._isCompleted}};function q({handleBatch:r,shouldQueue:e,limitPolicy:n}){let t=[];return{enhanceOne:async s=>{if(!e||e(s))return new Promise((c,a)=>{t.push(new P(c,a,s))})},completeAll:async()=>{if(t.length>0){try{await r(t)}catch(c){t.forEach(a=>a.reject(c))}if(t.some(c=>!c.isCompleted))throw new Error("The completeAll() function failed to resolve or reject all promises in the batch!")}let s=t.length;return t=[],s},limitPolicy:n}}var j=N(require("p-throttle")),V=N(require("p-retry"));function T({throttle:r={interval:1e3,limit:10},retry:e={retries:1,factor:1.66}}){let n=r?(0,j.default)(r):null;return function(o){let i=async()=>await o();if(n&&(i=n(i)),e){let s=i;i=()=>(0,V.default)(s,e)}return i()}}var l=async r=>await r();async function K({composition:r,enhancers:e,context:n,onErrors:t=o=>{throw new Error(o.map(i=>`${i.message}
1
+ "use strict";var se=Object.create;var _=Object.defineProperty;var ce=Object.getOwnPropertyDescriptor;var pe=Object.getOwnPropertyNames;var me=Object.getPrototypeOf,le=Object.prototype.hasOwnProperty;var R=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),ue=(n,e)=>{for(var t in e)_(n,t,{get:e[t],enumerable:!0})},J=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of pe(e))!le.call(n,o)&&o!==t&&_(n,o,{get:()=>e[o],enumerable:!(r=ce(e,o))||r.enumerable});return n};var he=(n,e,t)=>(t=n!=null?se(me(n)):{},J(e||!n||!n.__esModule?_(t,"default",{value:n,enumerable:!0}):t,n)),fe=n=>J(_({},"__esModule",{value:!0}),n);var de=(n,e,t)=>{if(!e.has(n))throw TypeError("Cannot "+t)};var v=(n,e,t)=>(de(n,e,"read from private field"),t?t.call(n):e.get(n)),Z=(n,e,t)=>{if(e.has(n))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(n):e.set(n,t)};var q=R((He,H)=>{function u(n,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(n)),this._timeouts=n,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}H.exports=u;u.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};u.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};u.prototype.retry=function(n){if(this._timeout&&clearTimeout(this._timeout),!n)return!1;var e=new Date().getTime();if(n&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(n),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(n);var t=this._timeouts.shift();if(t===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),t=this._cachedTimeouts.slice(-1);else return!1;var r=this;return this._timer=setTimeout(function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout(function(){r._operationTimeoutCb(r._attempts)},r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)},t),this._options.unref&&this._timer.unref(),!0};u.prototype.attempt=function(n,e){this._fn=n,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var t=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){t._operationTimeoutCb()},t._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};u.prototype.try=function(n){console.log("Using RetryOperation.try() is deprecated"),this.attempt(n)};u.prototype.start=function(n){console.log("Using RetryOperation.start() is deprecated"),this.attempt(n)};u.prototype.start=u.prototype.try;u.prototype.errors=function(){return this._errors};u.prototype.attempts=function(){return this._attempts};u.prototype.mainError=function(){if(this._errors.length===0)return null;for(var n={},e=null,t=0,r=0;r<this._errors.length;r++){var o=this._errors[r],i=o.message,a=(n[i]||0)+1;n[i]=a,a>=t&&(e=o,t=a)}return e}});var Y=R(d=>{var Ce=q();d.operation=function(n){var e=d.timeouts(n);return new Ce(e,{forever:n&&(n.forever||n.retries===1/0),unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})};d.timeouts=function(n){if(n instanceof Array)return[].concat(n);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var t in n)e[t]=n[t];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var r=[],o=0;o<e.retries;o++)r.push(this.createTimeout(o,e));return n&&n.forever&&!r.length&&r.push(this.createTimeout(o,e)),r.sort(function(i,a){return i-a}),r};d.createTimeout=function(n,e){var t=e.randomize?Math.random()+1:1,r=Math.round(t*Math.max(e.minTimeout,1)*Math.pow(e.factor,n));return r=Math.min(r,e.maxTimeout),r};d.wrap=function(n,e,t){if(e instanceof Array&&(t=e,e=null),!t){t=[];for(var r in n)typeof n[r]=="function"&&t.push(r)}for(var o=0;o<t.length;o++){var i=t[o],a=n[i];n[i]=function(c){var p=d.operation(e),m=Array.prototype.slice.call(arguments,1),l=m.pop();m.push(function(h){p.retry(h)||(h&&(arguments[0]=p.mainError()),l.apply(this,arguments))}),p.attempt(function(){c.apply(n,m)})}.bind(n,a),n[i].options=e}}});var K=R((Ye,Q)=>{Q.exports=Y()});var ke={};ue(ke,{BatchEntry:()=>g,CANVAS_DRAFT_STATE:()=>Ct,CANVAS_ENRICHMENT_TAG_PARAM:()=>Ne,CANVAS_INTENT_TAG_PARAM:()=>be,CANVAS_LOCALE_TAG_PARAM:()=>k,CANVAS_LOCALIZATION_SLOT:()=>G,CANVAS_LOCALIZATION_TYPE:()=>B,CANVAS_PERSONALIZATION_PARAM:()=>F,CANVAS_PERSONALIZE_SLOT:()=>Se,CANVAS_PERSONALIZE_TYPE:()=>Ie,CANVAS_PUBLISHED_STATE:()=>Et,CANVAS_TEST_SLOT:()=>Oe,CANVAS_TEST_TYPE:()=>Re,CANVAS_TEST_VARIANT_PARAM:()=>$,CanvasClient:()=>w,CanvasDataConnectionClient:()=>V,CanvasDataTypeClient:()=>I,ChildEnhancerBuilder:()=>T,EnhancerBuilder:()=>S,UncachedCanvasClient:()=>j,UniqueBatchEntries:()=>b,compose:()=>xe,createBatchEnhancer:()=>ye,createEventBus:()=>Me,createLimitPolicy:()=>L,enhance:()=>Ae,extractLocales:()=>ie,getChannelName:()=>z,getComponentPath:()=>x,isSystemComponentDefinition:()=>De,localize:()=>Be,mapSlotToPersonalizedVariations:()=>Ue,mapSlotToTestVariations:()=>Le,nullLimitPolicy:()=>f,subscribeToComposition:()=>Ve,walkComponentTree:()=>P});module.exports=fe(ke);function P(n,e){let t=[{ancestorsAndSelf:[{component:n,parentSlot:void 0,parentSlotIndex:void 0}]}];do{let r=t.pop();if(!r)continue;let o=r.ancestorsAndSelf[0],i=!0;e(o.component,r.ancestorsAndSelf,{replaceComponent:s=>{Object.assign(o.component,s),["parameters","variant","slots","data","_pattern","_patternError"].forEach(p=>{s[p]||delete o.component[p]})},removeComponent:()=>{let{parentSlot:s,parentComponent:c,correctedParentSlotIndex:p}=W(r,o.component);if(s&&typeof p!="undefined")c.component.slots[s].splice(p,1);else throw new Error("Unable to delete composition.")},insertAfter:s=>{let c=Array.isArray(s)?s:[s],{parentSlot:p,parentComponent:m,correctedParentSlotIndex:l}=W(r,o.component);if(p&&typeof l!="undefined")m.component.slots[p].splice(l+1,0,...c);else throw new Error("Unable to insert after a component not in a slot.")},stopProcessingDescendants(){i=!1}});let a=o.component.slots;if(i&&a){let s=Object.keys(a);for(let c=s.length-1;c>=0;c--){let p=s[c],m=a[p];for(let l=m.length-1;l>=0;l--)t.push({ancestorsAndSelf:[{component:m[l],parentSlot:p,parentSlotIndex:l},...r.ancestorsAndSelf]})}}}while(t.length>0)}function x(n){let e=[];for(let t=n.length-1;t>=0;t--){let{parentSlot:r,parentSlotIndex:o}=n[t];r&&o!==void 0&&e.push(`${r}[${o}]`)}return`.${e.join(".")}`}function W(n,e){let{parentSlot:t,parentSlotIndex:r}=n.ancestorsAndSelf[0],o=n.ancestorsAndSelf[1],i=r;return t&&r!==void 0&&o.component.slots&&o.component.slots[t][r]!==e&&(i=o.component.slots[t].findIndex(a=>a===e)),{parentSlot:t,parentComponent:o,correctedParentSlotIndex:i}}var b=class{constructor(e,t){this.groups=e.reduce((r,o)=>{var a;let i=t(o.args);return r[i]=(a=r[i])!=null?a:[],r[i].push(o),r},{})}resolveKey(e,t){this.groups[e].forEach(r=>r.resolve(t))}resolveRemaining(e){Object.keys(this.groups).forEach(t=>{this.groups[t].forEach(r=>{r.isCompleted||r.resolve(e)})})}};var T=class{constructor(){this._paramMatches=Array();this._dataMatches=new Map}parameter(e){return this._paramMatches.push({enhancer:this._resolveParameterEnhancer(e)}),this}parameterName(e,t){return(Array.isArray(e)?e:[e]).forEach(o=>this._paramMatches.push({name:o,enhancer:this._resolveParameterEnhancer(t)})),this}parameterType(e,t){return(Array.isArray(e)?e:[e]).forEach(o=>this._paramMatches.push({type:o,enhancer:this._resolveParameterEnhancer(t)})),this}data(e,t){if(this._dataMatches.has(e))throw new Error(`${e} enhancer data key has been used more than once. This will cause data loss.`);return this._dataMatches.set(e,typeof t=="function"?{enhanceOne:t}:t),this}resolveParameterEnhancer(e,t){var r;return(r=this._paramMatches.find(o=>o.name&&o.name===e||o.type&&o.type===t.type||!o.type&&!o.name))==null?void 0:r.enhancer}resolveComponentEnhancers(){return this._dataMatches}_resolveParameterEnhancer(e){return typeof e=="function"?{enhanceOne:e}:e}},S=class{constructor(){this._componentIndex={};this._rootBuilder=new T}parameter(e){return this._rootBuilder.parameter(e),this}parameterName(e,t){return this._rootBuilder.parameterName(e,t),this}parameterType(e,t){return this._rootBuilder.parameterType(e,t),this}data(e,t){return this._rootBuilder.data(e,t),this}component(e,t){return(Array.isArray(e)?e:[e]).forEach(o=>{this._componentIndex[o]=this._componentIndex[o]||new T,t(this._componentIndex[o])}),this}resolveParameterEnhancer(e,t,r){let o=this._componentIndex[e.type];if(o){let i=o.resolveParameterEnhancer(t,r);if(i)return i}return this._rootBuilder.resolveParameterEnhancer(t,r)}resolveComponentEnhancers(e){let t=this._rootBuilder.resolveComponentEnhancers(),r=this._componentIndex[e.type];if(r){t=new Map(t);for(let[o,i]of r.resolveComponentEnhancers())t.set(o,i)}return t}};var g=class{constructor(e,t,r){this._resolve=e;this._reject=t;this.args=r;this._isCompleted=!1}resolve(e){this._resolve(e),this._isCompleted=!0}reject(e){this._reject(e),this._isCompleted=!0}get isCompleted(){return this._isCompleted}};function ye({handleBatch:n,shouldQueue:e,limitPolicy:t}){let r=[];return{enhanceOne:async a=>{if(!e||e(a))return new Promise((s,c)=>{r.push(new g(s,c,a))})},completeAll:async()=>{if(r.length>0){try{await n(r)}catch(s){r.forEach(c=>c.reject(s))}if(r.some(s=>!s.isCompleted))throw new Error("The completeAll() function failed to resolve or reject all promises in the batch!")}let a=r.length;return r=[],a},limitPolicy:t}}var O=class extends Error{constructor(){super("Throttled function aborted"),this.name="AbortError"}};function N({limit:n,interval:e,strict:t}){if(!Number.isFinite(n))throw new TypeError("Expected `limit` to be a finite number");if(!Number.isFinite(e))throw new TypeError("Expected `interval` to be a finite number");let r=new Map,o=0,i=0;function a(){let m=Date.now();return m-o>e?(i=1,o=m,0):(i<n?i++:(o+=e,i=1),o-m)}let s=[];function c(){let m=Date.now();if(s.length<n)return s.push(m),0;let l=s.shift()+e;return m>=l?(s.push(m),0):(s.push(l),l-m)}let p=t?c:a;return m=>{let l=function(...h){if(!l.isEnabled)return(async()=>m.apply(this,h))();let y;return new Promise((E,ae)=>{y=setTimeout(()=>{E(m.apply(this,h)),r.delete(y)},p()),r.set(y,ae)})};return l.abort=()=>{for(let h of r.keys())clearTimeout(h),r.get(h)(new O);r.clear(),s.splice(0,s.length)},l.isEnabled=!0,l}}var ee=he(K(),1),Ee=new Set(["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"]),D=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},Pe=(n,e,t)=>{let r=t.retries-(e-1);return n.attemptNumber=e,n.retriesLeft=r,n},Te=n=>Ee.has(n),X=n=>globalThis.DOMException===void 0?new Error(n):new DOMException(n);async function U(n,e){return new Promise((t,r)=>{e={onFailedAttempt(){},retries:10,...e};let o=ee.default.operation(e);o.attempt(async i=>{try{t(await n(i))}catch(a){if(!(a instanceof Error)){r(new TypeError(`Non-error was thrown: "${a}". You should only throw errors.`));return}if(a instanceof D)o.stop(),r(a.originalError);else if(a instanceof TypeError&&!Te(a.message))o.stop(),r(a);else{Pe(a,i,e);try{await e.onFailedAttempt(a)}catch(s){r(s);return}o.retry(a)||r(o.mainError())}}}),e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",()=>{o.stop();let i=e.signal.reason===void 0?X("The operation was aborted."):e.signal.reason;r(i instanceof Error?i:X(i))},{once:!0})})}function L({throttle:n={interval:1e3,limit:10},retry:e={retries:1,factor:1.66}}){let t=n?N(n):null;return function(o){let i=async()=>await o();if(t&&(i=t(i)),e){let a=i;i=()=>U(a,e)}return i()}}var f=async n=>await n();async function Ae({composition:n,enhancers:e,context:t,onErrors:r=o=>{throw new Error(o.map(i=>`${i.message}
2
2
  ${typeof i.error=="object"&&"stack"in i.error?i.error.stack:i.error}`).join(`
3
3
 
4
- `))}}){let o=[],i=new Set,s=new Set;d(r,(a,p)=>{var h;Object.entries((h=a.parameters)!=null?h:{}).forEach(([S,O])=>{let E=e.resolveParameterEnhancer(a,S,O);E&&(s.add(E),o.push(G(a,p,S,O,E,n)))});let m=e.resolveComponentEnhancers(a);o.push(Z(a,p,m,n)),i.add(m)}),o.push(...Array.from(i).flatMap(a=>Array.from(a).map(async([,p])=>{var m;try{p.completeAll&&await((m=p.limitPolicy)!=null?m:l)(()=>p.completeAll())}catch(h){return{error:h,message:"Batch component enhancer failed. Individual failed components should receive their own rejections."}}}))),o.push(...Array.from(s).map(async a=>{var p;try{a.completeAll&&await((p=a.limitPolicy)!=null?p:l)(()=>a.completeAll())}catch(m){return{error:m,message:"Batch parameter enhancer failed. Individual failed parameters should receive their own rejections."}}}));let c=(await Promise.all(o)).flatMap(a=>Array.isArray(a)?a:[a]).filter(a=>a);c.length&&t(c)}async function Z(r,e,n,t){return n.size&&(r.data={}),await Promise.all(Array.from(n).map(async([o,i])=>{var s;try{let a=await(i.completeAll?l:(s=i.limitPolicy)!=null?s:l)(async()=>i.enhanceOne({component:r,context:t}));a!=null&&(r.data[o]=a)}catch(c){let a=`Component ${A(e)} (type: ${r.type}): data.${o} enhancer threw exception. Data key will not be present.`;return delete r.data[o],{message:a,error:c}}}))}async function G(r,e,n,t,o,i){var s;try{let a=await(o.completeAll?l:(s=o.limitPolicy)!=null?s:l)(async()=>o.enhanceOne({parameter:t,parameterName:n,component:r,context:i}));a===null?delete r.parameters[n]:typeof a=="undefined"?r.parameters[n]={...t,value:t.value}:r.parameters[n]={...t,value:a}}catch(c){let a=`Component ${A(e)} (type: ${r.type}): enhancing parameter ${n} (type: ${t.type}) threw exception. Parameter will be removed.`;return delete r.parameters[n],{message:a,error:c}}}var Y=(r,...e)=>({enhanceOne:t=>{let o="enhanceOne"in r?r.enhanceOne(t):r(t);for(let i of e){let s=J(o)?o:Promise.resolve(o),c="enhanceOne"in i?i.enhanceOne:i;o=s.then(a=>c({...t,parameter:{type:t.parameter.type,value:a}}))}return o},completeAll:async()=>{var t,o;for(let i of e)if("completeAll"in i)throw new Error("Only the first enhancer in a compose chain can use the completeAll function (batching)");return(o="completeAll"in r?(t=r.completeAll)==null?void 0:t.call(r):0)!=null?o:0}});function J(r){return!!r&&(typeof r=="object"||typeof r=="function")&&typeof r.then=="function"}var u=class extends Error{constructor(n,t,o,i,s,c){super(`${n}
5
- ${i}${s?" "+s:""} (${t} ${o}${c?` Request ID: ${c}`:""})`);this.errorMessage=n;this.fetchMethod=t;this.fetchUri=o;this.statusCode=i;this.statusText=s;this.requestId=c;Object.setPrototypeOf(this,u.prototype)}},y=class{constructor(e){var t,o,i,s,c;if(!e.apiKey&&!e.bearerToken)throw new Error("You must provide an API key or a bearer token");let n=e.fetch;if(!n)if(typeof window!="undefined")n=window.fetch.bind(window);else if(typeof fetch!="undefined")n=fetch;else throw new Error("You must provide or polyfill a fetch implementation when not in a browser");this.options={...e,fetch:n,apiHost:(t=e.apiHost)!=null?t:"https://uniform.app",apiKey:(o=e.apiKey)!=null?o:null,projectId:(i=e.projectId)!=null?i:null,bearerToken:(s=e.bearerToken)!=null?s:null,limitPolicy:(c=e.limitPolicy)!=null?c:T({})}}async getCompositionList(e){let{projectId:n}=this.options,t=this.createUrl("/api/v1/canvas",{...e,projectId:n});return await this.apiClient(t)}async getCompositionBySlug(e){let{projectId:n}=this.options,t=this.createUrl("/api/v1/canvas",{...e,projectId:n});return await this.apiClient(t)}async getCompositionById(e){let{projectId:n}=this.options,t=this.createUrl("/api/v1/canvas",{...e,projectId:n});return await this.apiClient(t)}async updateComposition(e){let n=this.createUrl("/api/v1/canvas");await this.apiClient(n,{method:"PUT",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async removeComposition(e){let n=this.createUrl("/api/v1/canvas");await this.apiClient(n,{method:"DELETE",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async getComponentDefinitions(e){let{projectId:n}=this.options,t=this.createUrl("/api/v1/canvas-definitions",{...e,projectId:n});return await this.apiClient(t)}async updateComponentDefinition(e){let n=this.createUrl("/api/v1/canvas-definitions");await this.apiClient(n,{method:"PUT",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async removeComponentDefinition(e){let n=this.createUrl("/api/v1/canvas-definitions");await this.apiClient(n,{method:"DELETE",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async apiClient(e,n){return this.options.limitPolicy(async()=>{var i;let t=this.options.apiKey?{"x-api-key":this.options.apiKey}:{Authorization:`Bearer ${this.options.bearerToken}`},o=await this.options.fetch(e.toString(),{...n,headers:{...n==null?void 0:n.headers,...t}});if(!o.ok){let s="";try{let c=await o.text();try{let a=JSON.parse(c);a.errorMessage?s=Array.isArray(a.errorMessage)?a.errorMessage.join(", "):a.errorMessage:s=c}catch(a){s=c}}catch(c){s="General error"}throw new u(s,(i=n==null?void 0:n.method)!=null?i:"GET",e.toString(),o.status,o.statusText,y.getRequestId(o))}return n!=null&&n.expectNoContent?null:await o.json()})}createUrl(e,n){let t=new URL(`${this.options.apiHost}${e}`);return Object.entries(n!=null?n:{}).forEach(([o,i])=>{var s;typeof i!==void 0&&i!==null&&t.searchParams.append(o,(s=i==null?void 0:i.toString())!=null?s:"")}),t}static getRequestId(e){let n=e.headers.get("x-nf-request-id");if(n)return n}};var W="$personalization",Q="$test",v="$localization",X="intentTag",R="locale",ee="pz",ne="test",x="localized",we=0,_e=64,w="$pzCrit",_="$tstVrnt",te="$enr";var oe=r=>r.startsWith("$");function re(r){return r?r.map((e,n)=>{var i,s;let t=(s=(i=e.parameters)==null?void 0:i[w])==null?void 0:s.value,o=(t==null?void 0:t.name)||`pz-${n}-${e.type}`;return{...e,id:o,pz:t}}):[]}function ie(r){return r?r.map((e,n)=>{var i,s,c;let t=(s=(i=e.parameters)==null?void 0:i[_])==null?void 0:s.value,o=(c=t==null?void 0:t.id)!=null?c:"testId"in e?e.testId:`ab-${n}-${e.type}`;return{...e,id:o}}):[]}var $="https://js.pusher.com/7.0.3/pusher.min.js";async function se(){if(!(typeof document=="undefined"||typeof window=="undefined"))return window.Pusher?window.Pusher:new Promise((r,e)=>{let n=setTimeout(()=>{window.Pusher&&r(window.Pusher),e(`Unable to load pusher.js; Uniform Canvas live preview disabled. Consider adding <script src="${$}"><\/script> manually.`)},5e3),t=document.createElement("script");t.src=$,t.addEventListener("load",()=>{clearTimeout(n),r(window.Pusher)}),document.head.appendChild(t)})}async function ae(){let r=await se();if(!r)return;let e=window.__UNIFORM_EVENT_BUS__;if(!e){let n=new r("7b5f5abd160fea549ffe",{cluster:"mt1"});n.connect(),console.log("[canvas] \u{1F525} preview connected"),e=window.__UNIFORM_EVENT_BUS__={subscribe:t=>{let o=n.subscribe(t);return{unsubscribe:()=>n.unsubscribe(t),addEventHandler:(i,s)=>(o.bind(i,s),()=>o.unbind(i,s))}}}}return e}function b(r,e,n){return`${r}.${e}@${n}`}function ce({projectId:r,compositionId:e,compositionState:n=0,eventBus:{subscribe:t},callback:o,event:i="updated"}){let s=b(r,e,n),c=t(s),a=c.addEventHandler(i,o);return()=>{a(),c.unsubscribe()}}function k({component:r}){var t;let e={},n=(t=r.slots)==null?void 0:t[x];return n==null||n.forEach(o=>{var s;let i=(s=o.parameters)==null?void 0:s[R];(i==null?void 0:i.value)&&typeof i.value=="string"&&(e[i.value]=e[i.value]||[],e[i.value].push(o))}),e}function pe({composition:r,locale:e}){d(r,(n,t,o)=>{if(n.type===v){let i=k({component:n}),s=typeof e=="string"?e:e({component:n,locales:i}),c;if(s&&(c=i[s]),c!=null&&c.length){let[a,...p]=c;o.replaceComponent(a),p.length&&o.insertAfter(p)}else o.removeComponent()}})}0&&(module.exports={BatchEntry,CANVAS_DRAFT_STATE,CANVAS_ENRICHMENT_TAG_PARAM,CANVAS_INTENT_TAG_PARAM,CANVAS_LOCALE_TAG_PARAM,CANVAS_LOCALIZATION_SLOT,CANVAS_LOCALIZATION_TYPE,CANVAS_PERSONALIZATION_PARAM,CANVAS_PERSONALIZE_SLOT,CANVAS_PERSONALIZE_TYPE,CANVAS_PUBLISHED_STATE,CANVAS_TEST_SLOT,CANVAS_TEST_TYPE,CANVAS_TEST_VARIANT_PARAM,CanvasClient,CanvasClientError,ChildEnhancerBuilder,EnhancerBuilder,UniqueBatchEntries,compose,createBatchEnhancer,createEventBus,createLimitPolicy,enhance,extractLocales,getChannelName,getComponentPath,isSystemComponentDefinition,localize,mapSlotToPersonalizedVariations,mapSlotToTestVariations,nullLimitPolicy,subscribeToComposition,walkComponentTree});
4
+ `))}}){let o=[],i=new Set,a=new Set;P(n,(c,p)=>{var l;Object.entries((l=c.parameters)!=null?l:{}).forEach(([h,y])=>{let E=e.resolveParameterEnhancer(c,h,y);E&&(a.add(E),o.push(ve(c,p,h,y,E,t)))});let m=e.resolveComponentEnhancers(c);o.push(_e(c,p,m,t)),i.add(m)}),o.push(...Array.from(i).flatMap(c=>Array.from(c).map(async([,p])=>{var m;try{p.completeAll&&await((m=p.limitPolicy)!=null?m:f)(()=>p.completeAll())}catch(l){return{error:l,message:"Batch component enhancer failed. Individual failed components should receive their own rejections."}}}))),o.push(...Array.from(a).map(async c=>{var p;try{c.completeAll&&await((p=c.limitPolicy)!=null?p:f)(()=>c.completeAll())}catch(m){return{error:m,message:"Batch parameter enhancer failed. Individual failed parameters should receive their own rejections."}}}));let s=(await Promise.all(o)).flatMap(c=>Array.isArray(c)?c:[c]).filter(c=>c);s.length&&r(s)}async function _e(n,e,t,r){return t.size&&(n.data={}),await Promise.all(Array.from(t).map(async([o,i])=>{var a;try{let c=await(i.completeAll?f:(a=i.limitPolicy)!=null?a:f)(async()=>i.enhanceOne({component:n,context:r}));c!=null&&(n.data[o]=c)}catch(s){let c=`Component ${x(e)} (type: ${n.type}): data.${o} enhancer threw exception. Data key will not be present.`;return delete n.data[o],{message:c,error:s}}}))}async function ve(n,e,t,r,o,i){var a;try{let c=await(o.completeAll?f:(a=o.limitPolicy)!=null?a:f)(async()=>o.enhanceOne({parameter:r,parameterName:t,component:n,context:i}));c===null?delete n.parameters[t]:typeof c=="undefined"?n.parameters[t]={...r,value:r.value}:n.parameters[t]={...r,value:c}}catch(s){let c=`Component ${x(e)} (type: ${n.type}): enhancing parameter ${t} (type: ${r.type}) threw exception. Parameter will be removed.`;return delete n.parameters[t],{message:c,error:s}}}var xe=(n,...e)=>({enhanceOne:r=>{let o="enhanceOne"in n?n.enhanceOne(r):n(r);for(let i of e){let a=ge(o)?o:Promise.resolve(o),s="enhanceOne"in i?i.enhanceOne:i;o=a.then(c=>s({...r,parameter:{type:r.parameter.type,value:c}}))}return o},completeAll:async()=>{var r,o;for(let i of e)if("completeAll"in i)throw new Error("Only the first enhancer in a compose chain can use the completeAll function (batching)");return(o="completeAll"in n?(r=n.completeAll)==null?void 0:r.call(n):0)!=null?o:0}});function ge(n){return!!n&&(typeof n=="object"||typeof n=="function")&&typeof n.then=="function"}var te=require("@uniformdev/context/api"),w=class extends te.ApiClient{constructor(e){e.limitPolicy||(e.limitPolicy=L({})),super(e)}get canvasUrl(){return this.options.experiment14?"/api/edge/v1/composition":"/api/v1/canvas"}async getCompositionList(e){let{projectId:t}=this.options,r=this.createUrl(this.canvasUrl,{...e,projectId:t});return await this.apiClient(r)}async getCompositionBySlug(e){let{projectId:t}=this.options,r=this.createUrl(this.canvasUrl,{...e,projectId:t});return await this.apiClient(r)}async getCompositionById(e){let{projectId:t}=this.options,r=this.createUrl(this.canvasUrl,{...e,projectId:t});return await this.apiClient(r)}async updateComposition(e){let t=this.createUrl("/api/v1/canvas");await this.apiClient(t,{method:"PUT",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async removeComposition(e){let t=this.createUrl("/api/v1/canvas"),{projectId:r}=this.options;await this.apiClient(t,{method:"DELETE",body:JSON.stringify({...e,projectId:r}),expectNoContent:!0})}async getComponentDefinitions(e){let{projectId:t}=this.options,r=this.createUrl("/api/v1/canvas-definitions",{...e,projectId:t});return await this.apiClient(r)}async updateComponentDefinition(e){let t=this.createUrl("/api/v1/canvas-definitions");await this.apiClient(t,{method:"PUT",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async removeComponentDefinition(e){let t=this.createUrl("/api/v1/canvas-definitions");await this.apiClient(t,{method:"DELETE",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}},j=class extends w{constructor(e){super({...e,bypassCache:!0})}};var ne=require("@uniformdev/context/api"),M="/api/v1/data-connection",we="/api/v1/data-connections",V=class extends ne.ApiClient{constructor(e){super(e)}async get(e){let{projectId:t}=this.options,r=this.createUrl(M,{...e,projectId:t});return await this.apiClient(r)}async getList(e){let{projectId:t}=this.options,r=this.createUrl(we,{...e,projectId:t});return await this.apiClient(r)}async upsert(e){let t=this.createUrl(M);await this.apiClient(t,{method:"PUT",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async remove(e){let t=this.createUrl(M);await this.apiClient(t,{method:"DELETE",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}};var re=require("@uniformdev/context/api");var C,A=class extends re.ApiClient{constructor(e){super(e)}async get(e){let{projectId:t}=this.options,r=this.createUrl(v(A,C),{...e,projectId:t});return await this.apiClient(r)}async upsert(e){let t=this.createUrl(v(A,C));await this.apiClient(t,{method:"PUT",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async remove(e){let t=this.createUrl(v(A,C));await this.apiClient(t,{method:"DELETE",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}},I=A;C=new WeakMap,Z(I,C,"/api/v1/data-types");var Ie="$personalization",Re="$test",B="$localization",be="intentTag",k="locale",Se="pz",Oe="test",G="localized",Ct=0,Et=64,F="$pzCrit",$="$tstVrnt",Ne="$enr";var De=n=>n.startsWith("$");function Ue(n){return n?n.map((e,t)=>{var i,a;let r=(a=(i=e.parameters)==null?void 0:i[F])==null?void 0:a.value,o=(r==null?void 0:r.name)||`pz-${t}-${e.type}`;return{...e,id:o,pz:r}}):[]}function Le(n){return n?n.map((e,t)=>{var i,a,s;let r=(a=(i=e.parameters)==null?void 0:i[$])==null?void 0:a.value,o=(s=r==null?void 0:r.id)!=null?s:"testId"in e?e.testId:`ab-${t}-${e.type}`;return{...e,id:o}}):[]}var oe="https://js.pusher.com/7.0.3/pusher.min.js";async function je(){if(!(typeof document=="undefined"||typeof window=="undefined"))return window.Pusher?window.Pusher:new Promise((n,e)=>{let t=setTimeout(()=>{window.Pusher&&n(window.Pusher),e(`Unable to load pusher.js; Uniform Canvas live preview disabled. Consider adding <script src="${oe}"><\/script> manually.`)},5e3),r=document.createElement("script");r.src=oe,r.addEventListener("load",()=>{clearTimeout(t),n(window.Pusher)}),document.head.appendChild(r)})}async function Me(){let n=await je();if(!n)return;let e=window.__UNIFORM_EVENT_BUS__;if(!e){let t=new n("7b5f5abd160fea549ffe",{cluster:"mt1"});t.connect(),console.log("[canvas] \u{1F525} preview connected"),e=window.__UNIFORM_EVENT_BUS__={subscribe:r=>{let o=t.subscribe(r);return{unsubscribe:()=>t.unsubscribe(r),addEventHandler:(i,a)=>(o.bind(i,a),()=>o.unbind(i,a))}}}}return e}function z(n,e,t){return`${n}.${e}@${t}`}function Ve({projectId:n,compositionId:e,compositionState:t=0,eventBus:{subscribe:r},callback:o,event:i="updated"}){let a=z(n,e,t),s=r(a),c=s.addEventHandler(i,o);return()=>{c(),s.unsubscribe()}}function ie({component:n}){var r;let e={},t=(r=n.slots)==null?void 0:r[G];return t==null||t.forEach(o=>{var a;let i=(a=o.parameters)==null?void 0:a[k];(i==null?void 0:i.value)&&typeof i.value=="string"&&(e[i.value]=e[i.value]||[],e[i.value].push(o))}),e}function Be({composition:n,locale:e}){P(n,(t,r,o)=>{if(t.type===B){let i=ie({component:t}),a=typeof e=="string"?e:e({component:t,locales:i}),s;if(a&&(s=i[a]),s!=null&&s.length){let[c,...p]=s;o.replaceComponent(c),p.length&&o.insertAfter(p)}else o.removeComponent()}})}0&&(module.exports={BatchEntry,CANVAS_DRAFT_STATE,CANVAS_ENRICHMENT_TAG_PARAM,CANVAS_INTENT_TAG_PARAM,CANVAS_LOCALE_TAG_PARAM,CANVAS_LOCALIZATION_SLOT,CANVAS_LOCALIZATION_TYPE,CANVAS_PERSONALIZATION_PARAM,CANVAS_PERSONALIZE_SLOT,CANVAS_PERSONALIZE_TYPE,CANVAS_PUBLISHED_STATE,CANVAS_TEST_SLOT,CANVAS_TEST_TYPE,CANVAS_TEST_VARIANT_PARAM,CanvasClient,CanvasDataConnectionClient,CanvasDataTypeClient,ChildEnhancerBuilder,EnhancerBuilder,UncachedCanvasClient,UniqueBatchEntries,compose,createBatchEnhancer,createEventBus,createLimitPolicy,enhance,extractLocales,getChannelName,getComponentPath,isSystemComponentDefinition,localize,mapSlotToPersonalizedVariations,mapSlotToTestVariations,nullLimitPolicy,subscribeToComposition,walkComponentTree});
package/dist/index.mjs CHANGED
@@ -1,4 +1 @@
1
- import{d as L,e as l,f as $,g as j,h as k,i as F,j as A,k as V,l as g,m as N,n as U,o as v,p as z,q as W,r as x,s as w,t as H}from"./chunk-ADDR7SB6.mjs";function u(o,e){let t=[{ancestorsAndSelf:[{component:o,parentSlot:void 0,parentSlotIndex:void 0}]}];do{let n=t.pop();if(!n)continue;let r=n.ancestorsAndSelf[0];e(r.component,n.ancestorsAndSelf,{replaceComponent:i=>{Object.assign(r.component,i),["parameters","variant","slots","data","_pattern","_patternError"].forEach(s=>{i[s]||delete r.component[s]})},removeComponent:()=>{let{parentSlot:i,parentSlotIndex:c}=n.ancestorsAndSelf[0],s=n.ancestorsAndSelf[1];if(i&&typeof c!="undefined")s.component.slots[i].splice(c,1);else throw new Error("Unable to delete composition.")},insertAfter:i=>{let c=Array.isArray(i)?i:[i],{parentSlot:s,parentSlotIndex:p}=n.ancestorsAndSelf[0],m=n.ancestorsAndSelf[1];if(s&&typeof p!="undefined")m.component.slots[s].splice(p+1,0,...c);else throw new Error("Unable to insert after a component not in a slot.")}});let a=r.component.slots;if(a){let i=Object.keys(a);for(let c=i.length-1;c>=0;c--){let s=i[c],p=a[s];for(let m=p.length-1;m>=0;m--)t.push({ancestorsAndSelf:[{component:p[m],parentSlot:s,parentSlotIndex:m},...n.ancestorsAndSelf]})}}}while(t.length>0)}function y(o){let e=[];for(let t=o.length-1;t>=0;t--){let{parentSlot:n,parentSlotIndex:r}=o[t];n&&r!==void 0&&e.push(`${n}[${r}]`)}return`.${e.join(".")}`}var T=class{constructor(e,t){this.groups=e.reduce((n,r)=>{var i;let a=t(r.args);return n[a]=(i=n[a])!=null?i:[],n[a].push(r),n},{})}resolveKey(e,t){this.groups[e].forEach(n=>n.resolve(t))}resolveRemaining(e){Object.keys(this.groups).forEach(t=>{this.groups[t].forEach(n=>{n.isCompleted||n.resolve(e)})})}};var d=class{constructor(){this._paramMatches=Array();this._dataMatches=new Map}parameter(e){return this._paramMatches.push({enhancer:this._resolveParameterEnhancer(e)}),this}parameterName(e,t){return(Array.isArray(e)?e:[e]).forEach(r=>this._paramMatches.push({name:r,enhancer:this._resolveParameterEnhancer(t)})),this}parameterType(e,t){return(Array.isArray(e)?e:[e]).forEach(r=>this._paramMatches.push({type:r,enhancer:this._resolveParameterEnhancer(t)})),this}data(e,t){if(this._dataMatches.has(e))throw new Error(`${e} enhancer data key has been used more than once. This will cause data loss.`);return this._dataMatches.set(e,typeof t=="function"?{enhanceOne:t}:t),this}resolveParameterEnhancer(e,t){var n;return(n=this._paramMatches.find(r=>r.name&&r.name===e||r.type&&r.type===t.type||!r.type&&!r.name))==null?void 0:n.enhancer}resolveComponentEnhancers(){return this._dataMatches}_resolveParameterEnhancer(e){return typeof e=="function"?{enhanceOne:e}:e}},_=class{constructor(){this._componentIndex={};this._rootBuilder=new d}parameter(e){return this._rootBuilder.parameter(e),this}parameterName(e,t){return this._rootBuilder.parameterName(e,t),this}parameterType(e,t){return this._rootBuilder.parameterType(e,t),this}data(e,t){return this._rootBuilder.data(e,t),this}component(e,t){return(Array.isArray(e)?e:[e]).forEach(r=>{this._componentIndex[r]=this._componentIndex[r]||new d,t(this._componentIndex[r])}),this}resolveParameterEnhancer(e,t,n){let r=this._componentIndex[e.type];if(r){let a=r.resolveParameterEnhancer(t,n);if(a)return a}return this._rootBuilder.resolveParameterEnhancer(t,n)}resolveComponentEnhancers(e){let t=this._rootBuilder.resolveComponentEnhancers(),n=this._componentIndex[e.type];if(n){t=new Map(t);for(let[r,a]of n.resolveComponentEnhancers())t.set(r,a)}return t}};var C=class{constructor(e,t,n){this._resolve=e;this._reject=t;this.args=n;this._isCompleted=!1}resolve(e){this._resolve(e),this._isCompleted=!0}reject(e){this._reject(e),this._isCompleted=!0}get isCompleted(){return this._isCompleted}};function D({handleBatch:o,shouldQueue:e,limitPolicy:t}){let n=[];return{enhanceOne:async i=>{if(!e||e(i))return new Promise((c,s)=>{n.push(new C(c,s,i))})},completeAll:async()=>{if(n.length>0){try{await o(n)}catch(c){n.forEach(s=>s.reject(c))}if(n.some(c=>!c.isCompleted))throw new Error("The completeAll() function failed to resolve or reject all promises in the batch!")}let i=n.length;return n=[],i},limitPolicy:t}}async function X({composition:o,enhancers:e,context:t,onErrors:n=r=>{throw new Error(r.map(a=>`${a.message}
2
- ${typeof a.error=="object"&&"stack"in a.error?a.error.stack:a.error}`).join(`
3
-
4
- `))}}){let r=[],a=new Set,i=new Set;u(o,(s,p)=>{var h;Object.entries((h=s.parameters)!=null?h:{}).forEach(([E,P])=>{let f=e.resolveParameterEnhancer(s,E,P);f&&(i.add(f),r.push(S(s,p,E,P,f,t)))});let m=e.resolveComponentEnhancers(s);r.push(R(s,p,m,t)),a.add(m)}),r.push(...Array.from(a).flatMap(s=>Array.from(s).map(async([,p])=>{var m;try{p.completeAll&&await((m=p.limitPolicy)!=null?m:l)(()=>p.completeAll())}catch(h){return{error:h,message:"Batch component enhancer failed. Individual failed components should receive their own rejections."}}}))),r.push(...Array.from(i).map(async s=>{var p;try{s.completeAll&&await((p=s.limitPolicy)!=null?p:l)(()=>s.completeAll())}catch(m){return{error:m,message:"Batch parameter enhancer failed. Individual failed parameters should receive their own rejections."}}}));let c=(await Promise.all(r)).flatMap(s=>Array.isArray(s)?s:[s]).filter(s=>s);c.length&&n(c)}async function R(o,e,t,n){return t.size&&(o.data={}),await Promise.all(Array.from(t).map(async([r,a])=>{var i;try{let s=await(a.completeAll?l:(i=a.limitPolicy)!=null?i:l)(async()=>a.enhanceOne({component:o,context:n}));s!=null&&(o.data[r]=s)}catch(c){let s=`Component ${y(e)} (type: ${o.type}): data.${r} enhancer threw exception. Data key will not be present.`;return delete o.data[r],{message:s,error:c}}}))}async function S(o,e,t,n,r,a){var i;try{let s=await(r.completeAll?l:(i=r.limitPolicy)!=null?i:l)(async()=>r.enhanceOne({parameter:n,parameterName:t,component:o,context:a}));s===null?delete o.parameters[t]:typeof s=="undefined"?o.parameters[t]={...n,value:n.value}:o.parameters[t]={...n,value:s}}catch(c){let s=`Component ${y(e)} (type: ${o.type}): enhancing parameter ${t} (type: ${n.type}) threw exception. Parameter will be removed.`;return delete o.parameters[t],{message:s,error:c}}}var ne=(o,...e)=>({enhanceOne:n=>{let r="enhanceOne"in o?o.enhanceOne(n):o(n);for(let a of e){let i=B(r)?r:Promise.resolve(r),c="enhanceOne"in a?a.enhanceOne:a;r=i.then(s=>c({...n,parameter:{type:n.parameter.type,value:s}}))}return r},completeAll:async()=>{var n,r;for(let a of e)if("completeAll"in a)throw new Error("Only the first enhancer in a compose chain can use the completeAll function (batching)");return(r="completeAll"in o?(n=o.completeAll)==null?void 0:n.call(o):0)!=null?r:0}});function B(o){return!!o&&(typeof o=="object"||typeof o=="function")&&typeof o.then=="function"}var re=o=>o.startsWith("$");function se(o){return o?o.map((e,t)=>{var a,i;let n=(i=(a=e.parameters)==null?void 0:a[x])==null?void 0:i.value,r=(n==null?void 0:n.name)||`pz-${t}-${e.type}`;return{...e,id:r,pz:n}}):[]}function pe(o){return o?o.map((e,t)=>{var a,i,c;let n=(i=(a=e.parameters)==null?void 0:a[w])==null?void 0:i.value,r=(c=n==null?void 0:n.id)!=null?c:"testId"in e?e.testId:`ab-${t}-${e.type}`;return{...e,id:r}}):[]}var b="https://js.pusher.com/7.0.3/pusher.min.js";async function O(){if(!(typeof document=="undefined"||typeof window=="undefined"))return window.Pusher?window.Pusher:new Promise((o,e)=>{let t=setTimeout(()=>{window.Pusher&&o(window.Pusher),e(`Unable to load pusher.js; Uniform Canvas live preview disabled. Consider adding <script src="${b}"><\/script> manually.`)},5e3),n=document.createElement("script");n.src=b,n.addEventListener("load",()=>{clearTimeout(t),o(window.Pusher)}),document.head.appendChild(n)})}async function le(){let o=await O();if(!o)return;let e=window.__UNIFORM_EVENT_BUS__;if(!e){let t=new o("7b5f5abd160fea549ffe",{cluster:"mt1"});t.connect(),console.log("[canvas] \u{1F525} preview connected"),e=window.__UNIFORM_EVENT_BUS__={subscribe:n=>{let r=t.subscribe(n);return{unsubscribe:()=>t.unsubscribe(n),addEventHandler:(a,i)=>(r.bind(a,i),()=>r.unbind(a,i))}}}}return e}function I(o,e,t){return`${o}.${e}@${t}`}function fe({projectId:o,compositionId:e,compositionState:t=0,eventBus:{subscribe:n},callback:r,event:a="updated"}){let i=I(o,e,t),c=n(i),s=c.addEventHandler(a,r);return()=>{s(),c.unsubscribe()}}function M({component:o}){var n;let e={},t=(n=o.slots)==null?void 0:n[v];return t==null||t.forEach(r=>{var i;let a=(i=r.parameters)==null?void 0:i[g];(a==null?void 0:a.value)&&typeof a.value=="string"&&(e[a.value]=e[a.value]||[],e[a.value].push(r))}),e}function Pe({composition:o,locale:e}){u(o,(t,n,r)=>{if(t.type===A){let a=M({component:t}),i=typeof e=="string"?e:e({component:t,locales:a}),c;if(i&&(c=a[i]),c!=null&&c.length){let[s,...p]=c;r.replaceComponent(s),p.length&&r.insertAfter(p)}else r.removeComponent()}})}export{C as BatchEntry,z as CANVAS_DRAFT_STATE,H as CANVAS_ENRICHMENT_TAG_PARAM,V as CANVAS_INTENT_TAG_PARAM,g as CANVAS_LOCALE_TAG_PARAM,v as CANVAS_LOCALIZATION_SLOT,A as CANVAS_LOCALIZATION_TYPE,x as CANVAS_PERSONALIZATION_PARAM,N as CANVAS_PERSONALIZE_SLOT,k as CANVAS_PERSONALIZE_TYPE,W as CANVAS_PUBLISHED_STATE,U as CANVAS_TEST_SLOT,F as CANVAS_TEST_TYPE,w as CANVAS_TEST_VARIANT_PARAM,j as CanvasClient,$ as CanvasClientError,d as ChildEnhancerBuilder,_ as EnhancerBuilder,T as UniqueBatchEntries,ne as compose,D as createBatchEnhancer,le as createEventBus,L as createLimitPolicy,X as enhance,M as extractLocales,I as getChannelName,y as getComponentPath,re as isSystemComponentDefinition,Pe as localize,se as mapSlotToPersonalizedVariations,pe as mapSlotToTestVariations,l as nullLimitPolicy,fe as subscribeToComposition,u as walkComponentTree};
1
+ import{A as p,B as q,C as r,D as s,E as t,F as u,G as v,H as w,I as x,J as y,K as z,L as A,M as B,N as C,O as D,P as E,Q as F,R as G,S as H,T as I,U as J,l as a,m as b,n as c,o as d,p as e,q as f,r as g,s as h,t as i,u as j,v as k,w as l,x as m,y as n,z as o}from"./chunk-PFL3XEAQ.mjs";export{f as BatchEntry,x as CANVAS_DRAFT_STATE,B as CANVAS_ENRICHMENT_TAG_PARAM,s as CANVAS_INTENT_TAG_PARAM,t as CANVAS_LOCALE_TAG_PARAM,w as CANVAS_LOCALIZATION_SLOT,r as CANVAS_LOCALIZATION_TYPE,z as CANVAS_PERSONALIZATION_PARAM,u as CANVAS_PERSONALIZE_SLOT,p as CANVAS_PERSONALIZE_TYPE,y as CANVAS_PUBLISHED_STATE,v as CANVAS_TEST_SLOT,q as CANVAS_TEST_TYPE,A as CANVAS_TEST_VARIANT_PARAM,l as CanvasClient,n as CanvasDataConnectionClient,o as CanvasDataTypeClient,d as ChildEnhancerBuilder,e as EnhancerBuilder,m as UncachedCanvasClient,c as UniqueBatchEntries,k as compose,g as createBatchEnhancer,F as createEventBus,h as createLimitPolicy,j as enhance,I as extractLocales,G as getChannelName,b as getComponentPath,C as isSystemComponentDefinition,J as localize,D as mapSlotToPersonalizedVariations,E as mapSlotToTestVariations,i as nullLimitPolicy,H as subscribeToComposition,a as walkComponentTree};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uniformdev/canvas",
3
- "version": "16.2.4",
3
+ "version": "17.1.1-alpha.151+3c57dd245",
4
4
  "description": "Common functionality and types for Uniform Canvas",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "main": "./dist/index.js",
@@ -36,26 +36,28 @@
36
36
  },
37
37
  "sideEffects": false,
38
38
  "scripts": {
39
- "build": "tsup --minify",
40
- "dev": "tsup --watch",
39
+ "build": "run-s update-openapi build:ts",
40
+ "build:ts": "tsup --minify",
41
+ "dev": "run-s update-openapi dev:ts",
42
+ "dev:ts": "tsup --watch",
41
43
  "clean": "rimraf dist",
42
44
  "test": "jest --maxWorkers=1",
43
45
  "lint": "eslint \"src/**/*.{js,ts,tsx}\"",
44
- "format": "prettier --write \"src/**/*.{js,ts,tsx}\""
46
+ "format": "prettier --write \"src/**/*.{js,ts,tsx}\"",
47
+ "update-openapi": "tsx ./scripts/update-openapi.cts"
45
48
  },
46
49
  "devDependencies": {
47
50
  "@types/retry": "0.12.1",
48
- "@types/yargs": "17.0.10",
49
- "@uniformdev/cli": "^16.2.4",
50
- "pusher-js": "7.0.6",
51
+ "@types/yargs": "17.0.12",
52
+ "@uniformdev/cli": "^17.1.1-alpha.151+3c57dd245",
53
+ "p-limit": "4.0.0",
54
+ "p-retry": "5.1.1",
55
+ "p-throttle": "5.0.0",
56
+ "pusher-js": "7.4.0",
51
57
  "yargs": "17.5.1"
52
58
  },
53
59
  "dependencies": {
54
- "@uniformdev/context": "^16.2.4",
55
- "isomorphic-unfetch": "^3.1.0",
56
- "p-limit": "^3.1.0",
57
- "p-retry": "^4.6.2",
58
- "p-throttle": "^4.1.1"
60
+ "@uniformdev/context": "^17.1.1-alpha.151+3c57dd245"
59
61
  },
60
62
  "files": [
61
63
  "/dist"
@@ -63,5 +65,5 @@
63
65
  "publishConfig": {
64
66
  "access": "public"
65
67
  },
66
- "gitHead": "b2ed666efec0c0e255c2a1b8561ff7899834a2d5"
68
+ "gitHead": "3c57dd245b59aa55368da8991d1e39bc633bbed8"
67
69
  }
@@ -1,2 +0,0 @@
1
- var h=Object.create;var u=Object.defineProperty;var m=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var d=Object.getPrototypeOf,I=Object.prototype.hasOwnProperty;var R=(i=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(i,{get:(t,e)=>(typeof require!="undefined"?require:t)[e]}):i)(function(i){if(typeof require!="undefined")return require.apply(this,arguments);throw new Error('Dynamic require of "'+i+'" is not supported')});var T=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports);var C=(i,t,e,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of f(t))!I.call(i,n)&&n!==e&&u(i,n,{get:()=>t[n],enumerable:!(o=m(t,n))||o.enumerable});return i};var O=(i,t,e)=>(e=i!=null?h(d(i)):{},C(t||!i||!i.__esModule?u(e,"default",{value:i,enumerable:!0}):e,i));import y from"p-throttle";import P from"p-retry";function A({throttle:i={interval:1e3,limit:10},retry:t={retries:1,factor:1.66}}){let e=i?y(i):null;return function(n){let s=async()=>await n();if(e&&(s=e(s)),t){let r=s;s=()=>P(r,t)}return s()}}var E=async i=>await i();var a=class extends Error{constructor(e,o,n,s,r,p){super(`${e}
2
- ${s}${r?" "+r:""} (${o} ${n}${p?` Request ID: ${p}`:""})`);this.errorMessage=e;this.fetchMethod=o;this.fetchUri=n;this.statusCode=s;this.statusText=r;this.requestId=p;Object.setPrototypeOf(this,a.prototype)}},l=class{constructor(t){var o,n,s,r,p;if(!t.apiKey&&!t.bearerToken)throw new Error("You must provide an API key or a bearer token");let e=t.fetch;if(!e)if(typeof window!="undefined")e=window.fetch.bind(window);else if(typeof fetch!="undefined")e=fetch;else throw new Error("You must provide or polyfill a fetch implementation when not in a browser");this.options={...t,fetch:e,apiHost:(o=t.apiHost)!=null?o:"https://uniform.app",apiKey:(n=t.apiKey)!=null?n:null,projectId:(s=t.projectId)!=null?s:null,bearerToken:(r=t.bearerToken)!=null?r:null,limitPolicy:(p=t.limitPolicy)!=null?p:A({})}}async getCompositionList(t){let{projectId:e}=this.options,o=this.createUrl("/api/v1/canvas",{...t,projectId:e});return await this.apiClient(o)}async getCompositionBySlug(t){let{projectId:e}=this.options,o=this.createUrl("/api/v1/canvas",{...t,projectId:e});return await this.apiClient(o)}async getCompositionById(t){let{projectId:e}=this.options,o=this.createUrl("/api/v1/canvas",{...t,projectId:e});return await this.apiClient(o)}async updateComposition(t){let e=this.createUrl("/api/v1/canvas");await this.apiClient(e,{method:"PUT",body:JSON.stringify({...t,projectId:this.options.projectId}),expectNoContent:!0})}async removeComposition(t){let e=this.createUrl("/api/v1/canvas");await this.apiClient(e,{method:"DELETE",body:JSON.stringify({...t,projectId:this.options.projectId}),expectNoContent:!0})}async getComponentDefinitions(t){let{projectId:e}=this.options,o=this.createUrl("/api/v1/canvas-definitions",{...t,projectId:e});return await this.apiClient(o)}async updateComponentDefinition(t){let e=this.createUrl("/api/v1/canvas-definitions");await this.apiClient(e,{method:"PUT",body:JSON.stringify({...t,projectId:this.options.projectId}),expectNoContent:!0})}async removeComponentDefinition(t){let e=this.createUrl("/api/v1/canvas-definitions");await this.apiClient(e,{method:"DELETE",body:JSON.stringify({...t,projectId:this.options.projectId}),expectNoContent:!0})}async apiClient(t,e){return this.options.limitPolicy(async()=>{var s;let o=this.options.apiKey?{"x-api-key":this.options.apiKey}:{Authorization:`Bearer ${this.options.bearerToken}`},n=await this.options.fetch(t.toString(),{...e,headers:{...e==null?void 0:e.headers,...o}});if(!n.ok){let r="";try{let p=await n.text();try{let c=JSON.parse(p);c.errorMessage?r=Array.isArray(c.errorMessage)?c.errorMessage.join(", "):c.errorMessage:r=p}catch(c){r=p}}catch(p){r="General error"}throw new a(r,(s=e==null?void 0:e.method)!=null?s:"GET",t.toString(),n.status,n.statusText,l.getRequestId(n))}return e!=null&&e.expectNoContent?null:await n.json()})}createUrl(t,e){let o=new URL(`${this.options.apiHost}${t}`);return Object.entries(e!=null?e:{}).forEach(([n,s])=>{var r;typeof s!==void 0&&s!==null&&o.searchParams.append(n,(r=s==null?void 0:s.toString())!=null?r:"")}),o}static getRequestId(t){let e=t.headers.get("x-nf-request-id");if(e)return e}};var U="$personalization",V="$test",D="$localization",v="intentTag",k="locale",$="pz",M="test",q="localized",H=0,z=64,F="$pzCrit",K="$tstVrnt",G="$enr";export{R as a,T as b,O as c,A as d,E as e,a as f,l as g,U as h,V as i,D as j,v as k,k as l,$ as m,M as n,q as o,H as p,z as q,F as r,K as s,G as t};
@@ -1,266 +0,0 @@
1
- import Pusher from 'pusher-js';
2
-
3
- /** @deprecated use CANVAS_DRAFT_STATE and CANVAS_PUBLISHED_STATE instead */
4
- declare type CompositionFetchState = 'preview' | 'published' | number;
5
- /** The GET response from /api/v1/canvas when `component` or `slug` params are specified */
6
- declare type CompositionAPIResponse = {
7
- /** The state of the layout. See CANVAS_DRAFT_STATE and CANVAS_PUBLISHED_STATE. */
8
- state: number;
9
- /** The project ID that this layout data is part of */
10
- projectId: string;
11
- /** Layout data being read or written */
12
- composition: RootComponentInstance;
13
- /** Whether this composition is a pattern (can be referenced by other compositions) */
14
- pattern: boolean;
15
- /** Created date string for this definition */
16
- created?: string;
17
- /** Modified date string for this definition */
18
- modified?: string;
19
- };
20
- /** Shape of the DELETE request body for /api/v1/canvas */
21
- declare type CompositionAPIDeleteRequest = {
22
- /** Public ID of the composition to delete */
23
- compositionId: string;
24
- /** Project ID that the composition lives on. */
25
- projectId: string;
26
- /** The state to delete. If unspecified, all states will be deleted. See CANVAS_DRAFT_STATE and CANVAS_PUBLISHED_STATE. */
27
- state?: number;
28
- };
29
- /** The GET response from /api/v1/canvas when `component` or `slug` are not specified */
30
- declare type CompositionListAPIResponse = {
31
- compositions: Array<CompositionAPIResponse>;
32
- };
33
- /** Query parameter options for GET /api/v1/canvas */
34
- declare type CompositionAPIOptions = {
35
- /** Specify a single composition ID to fetch. Changes response from list to single. */
36
- compositionId?: string;
37
- /** Specify a single composition to fetch by slug. Changes response from list to single. */
38
- slug?: string;
39
- /** The project the composition(s) are on. */
40
- projectId: string;
41
- /** The component type to filter by */
42
- type?: string;
43
- /** Number of records to skip */
44
- offset?: number;
45
- /** Max number of records to return (defaults to 100) */
46
- limit?: number;
47
- /** State of compositions to fetch. Default = 'published' */
48
- state?: number;
49
- /**
50
- * Signals a Canvas enhancer proxy to skip processing enhancements to the data and return raw data only.
51
- * This improves performance if you do not require enhanced component data.
52
- * If calling the Canvas API directly with no enhancer proxy, this has no effect.
53
- */
54
- skipEnhance?: boolean;
55
- /**
56
- * If true, any pattern references in the composition will be left unresolved.
57
- * This is appropriate if you intend to serialize the composition data without pattern
58
- * data embedded into it, and serialize the pattern data separately.
59
- */
60
- skipPatternResolution?: boolean;
61
- };
62
- declare type ComponentParameter<TValue = unknown> = {
63
- /** The type of the parameter. Determines how it is displayed when editing, and tells the consumer how to process it. */
64
- type: string;
65
- /**
66
- * The value of the parameter.
67
- * Any JSON-serializable value is acceptable.
68
- */
69
- value: TValue;
70
- };
71
- /**
72
- * Defines the shape of a component instance served by the composition API.
73
- */
74
- declare type ComponentInstance = {
75
- /** Type of the component instance (public_id of its definition) */
76
- type: string;
77
- /** Component parameter values for the component instance */
78
- parameters?: Record<string, ComponentParameter>;
79
- /** Public ID of alternate visual appearance for this component, if any selected */
80
- variant?: string;
81
- /** Slots containing any sub-components */
82
- slots?: Record<string, ComponentInstance[]>;
83
- /** Data for the component instance, provided by a component enhancer. Never set in unenhanced data. */
84
- data?: Record<string, unknown>;
85
- /** Indicates this component instance should be sourced from a pattern library pattern */
86
- _pattern?: string;
87
- /**
88
- * If an error occurs resolving a pattern reference, it is left unresolved and this property is set to indicate why.
89
- * CYCLIC: A cyclic pattern graph was detected, which could not be resolved because it would cause an infinite loop.
90
- * NOTFOUND: The pattern ID referenced could not be found. It may have been deleted, or not be published yet.
91
- */
92
- _patternError?: 'CYCLIC' | 'NOTFOUND';
93
- };
94
- /** Defines the shape of the root component in a composition */
95
- declare type RootComponentInstance = ComponentInstance & {
96
- /** The public UUID of the composition. */
97
- _id?: string;
98
- /** Slug pattern of this component. */
99
- _slug?: string | null;
100
- /** Friendly name of this component. */
101
- _name?: string;
102
- };
103
-
104
- /** Shape of the GET response from /api/v1/canvas-definitions */
105
- declare type ComponentDefinitionAPIResponse = {
106
- componentDefinitions: Array<ComponentDefinition>;
107
- };
108
- /** Shape of the PUT request body for /api/v1/canvas-definitions */
109
- declare type ComponentDefinitionAPIPutRequest = {
110
- componentDefinition: CreatingComponentDefinition;
111
- projectId: string;
112
- };
113
- /** Shape of the DELETE request body for /api/v1/canvas-definitions */
114
- declare type ComponentDefinitionAPIDeleteRequest = {
115
- /** Public ID of the component definition to delete */
116
- componentId: string;
117
- /** Project ID that the component definition lives on */
118
- projectId: string;
119
- };
120
- /** Query parameter options for GET /api/v1/canvas-definitions */
121
- declare type ComponentDefinitionListAPIOptions = {
122
- /** Limit list to one result by ID (response remains an array) */
123
- componentId?: string;
124
- /** Number of records to skip */
125
- offset?: number;
126
- /** Max number of records to return (defaults to 100) */
127
- limit?: number;
128
- projectId: string;
129
- };
130
- /** The definition of a component parameter */
131
- declare type ComponentDefinitionParameter<TConfig = unknown> = {
132
- /** Public ID of the parameter (used in code). Do not change after creation. */
133
- id: string;
134
- /** Friendly name of the parameter */
135
- name: string;
136
- /** Appears next to the parameter in the Composition editor */
137
- helpText?: string;
138
- /** Type name of the parameter (provided by a Uniform integration) */
139
- type: string;
140
- /** The configuration object for the type (type-specific) */
141
- typeConfig?: TConfig;
142
- };
143
- /** The definition of a component variant */
144
- declare type ComponentDefinitionVariant = {
145
- /** Public ID of the variant (used in code). Do not change after creation. */
146
- id: string;
147
- /** Friendly name of the variant */
148
- name: string;
149
- };
150
- /** The definition of a component slug */
151
- declare type ComponentDefinitionSlugSettings = {
152
- /**
153
- * Is slug required
154
- * no: slug is optional
155
- * yes: slug is required
156
- * disabled: slug is disabled and will not be shown in the editor
157
- * @default no
158
- */
159
- required?: 'no' | 'yes' | 'disabled';
160
- /** Slug uniqueness configuration.
161
- * no = no unique constraint
162
- * local = must be unique within this component type
163
- * global = must be unique across all component types
164
- * @default no
165
- */
166
- unique?: 'no' | 'local' | 'global';
167
- /** Regular expression slugs must match */
168
- regularExpression?: string;
169
- /**
170
- * Custom error message when regular expression validation fails.
171
- * Has no effect if `regularExpression` is not set.
172
- */
173
- regularExpressionMessage?: string;
174
- };
175
- /** The definition of a named component slot that can contain other components */
176
- declare type ComponentDefinitionSlot = {
177
- /** Public ID of the slot (used in code). Do not change after creation. */
178
- id: string;
179
- /** Friendly name of the slot */
180
- name: string;
181
- /** Whether this slot inherits its allowed components from the parent slot it lives in. If true, allowedComponents is irrelevant. */
182
- inheritAllowedComponents: boolean;
183
- /** A list of component definition public IDs that are allowed in this named slot */
184
- allowedComponents: Array<string>;
185
- /** Minimum valid number of components in this slot */
186
- minComponents?: number;
187
- /** Maximum valid number of components in this slot */
188
- maxComponents?: number;
189
- };
190
- /** Permission set for a component defintion */
191
- declare type ComponentDefinitionPermission = {
192
- /** Role ID associated with this permission */
193
- roleId: string;
194
- /** Permission type for this defintion read | write | delete. */
195
- permission: string;
196
- /** State of the component that this permission applies to */
197
- state: number;
198
- };
199
- /** Defines a component type that can live on a Composition */
200
- declare type ComponentDefinition = {
201
- /** Public ID of the component (used in code). Do not change after creation. */
202
- id: string;
203
- /** Friendly name of the component definition */
204
- name: string;
205
- /** Icon name for the component definition (e.g. 'screen') */
206
- icon: string;
207
- /** Applicable role permissions */
208
- permissions?: Array<ComponentDefinitionPermission>;
209
- /** if this component uses team permissions or custom permissions */
210
- useTeamPermissions?: boolean;
211
- /**
212
- * The public ID of the parameter whose value should be used to create a display title for this component in the UI.
213
- * The parameter type must support being used as a title parameter for this to work.
214
- */
215
- titleParameter?: string | null;
216
- /** Whether this component type can be the root of a composition. If false, this component is only used within slots on other components. */
217
- canBeComposition?: boolean;
218
- /** The parameters for this component. Parameters are key-value pairs that can be anything from text values to links to CMS entries. */
219
- parameters?: Array<ComponentDefinitionParameter>;
220
- /** The named slots for this component; placement areas where arrays of other components can be added. */
221
- slots?: Array<ComponentDefinitionSlot>;
222
- /** Default component instance value */
223
- defaults?: ComponentInstance | null;
224
- /** Named variants for this component; enables creation of visual variants that use the same parameter data/ */
225
- variants?: Array<ComponentDefinitionVariant>;
226
- /** Setting for slug validation */
227
- slugSettings?: ComponentDefinitionSlugSettings;
228
- /** Created date string for this definition */
229
- created?: string;
230
- /** Updated date string for this definition */
231
- updated?: string;
232
- /** Modified date string for this definition */
233
- modified?: string;
234
- };
235
- /** Defines a component type that can live on a Composition, when it is being created or updated */
236
- declare type CreatingComponentDefinition = Omit<Partial<ComponentDefinition>, 'created' | 'modified' | 'id' | 'name'> & {
237
- id: string;
238
- name: string;
239
- };
240
-
241
- /**
242
- * Pusher-js is large (80k) and not tree shakable so it is always bundled if directly referenced,
243
- * when it's only needed during preview mode. To avoid bundling it for all, we use an old-school
244
- * write-a-script-tag hack to load it in a poor man's approximation of a dynamic import ;)
245
- */
246
- declare type ChannelSubscription = {
247
- addEventHandler: (eventName: string, handler: (data: unknown) => void) => () => void;
248
- unsubscribe: () => void;
249
- };
250
- declare type PreviewEventBus = {
251
- subscribe: (channel: string) => ChannelSubscription;
252
- };
253
- declare global {
254
- interface Window {
255
- Pusher?: typeof Pusher;
256
- __UNIFORM_EVENT_BUS__?: PreviewEventBus;
257
- }
258
- }
259
- /**
260
- * Creates an event bus client to receive updates from Canvas
261
- * IMPORTANT: in a server-side context this will always return undefined
262
- * IMPORTANT: in a browser context this is cached in window and does not create multiple instances
263
- */
264
- declare function createEventBus(): Promise<PreviewEventBus | undefined>;
265
-
266
- export { ComponentInstance as C, PreviewEventBus as P, RootComponentInstance as R, ComponentParameter as a, CompositionAPIOptions as b, CompositionListAPIResponse as c, CompositionAPIResponse as d, CompositionAPIDeleteRequest as e, ComponentDefinitionListAPIOptions as f, ComponentDefinitionAPIResponse as g, ComponentDefinitionAPIPutRequest as h, ComponentDefinitionAPIDeleteRequest as i, ComponentDefinitionParameter as j, ComponentDefinitionVariant as k, ComponentDefinitionSlugSettings as l, ComponentDefinitionSlot as m, ComponentDefinitionPermission as n, ComponentDefinition as o, CreatingComponentDefinition as p, CompositionFetchState as q, ChannelSubscription as r, createEventBus as s };