@uniformdev/canvas 17.7.0 → 17.7.1-alpha.167
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/chunk-FIKDTGXG.mjs +1495 -0
- package/dist/cli/cli.d.ts +2 -2
- package/dist/cli/cli.js +19772 -74
- package/dist/cli/cli.mjs +19183 -74
- package/dist/{createEventBus-bb2f5866.d.ts → createEventBus-bd2e0a92.d.ts} +99 -133
- package/dist/index.d.ts +31 -39
- package/dist/index.esm.js +118 -1
- package/dist/index.js +1519 -3
- package/dist/index.mjs +118 -1
- package/package.json +8 -8
- package/dist/chunk-PVRSC7Y6.mjs +0 -4
package/dist/index.js
CHANGED
@@ -1,4 +1,1520 @@
|
|
1
|
-
"use strict";var le=Object.create;var A=Object.defineProperty;var ue=Object.getOwnPropertyDescriptor;var de=Object.getOwnPropertyNames;var he=Object.getPrototypeOf,fe=Object.prototype.hasOwnProperty;var D=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ye=(t,e)=>{for(var n in e)A(t,n,{get:e[n],enumerable:!0})},Q=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of de(e))!fe.call(t,r)&&r!==n&&A(t,r,{get:()=>e[r],enumerable:!(o=ue(e,r))||o.enumerable});return t};var Ce=(t,e,n)=>(n=t!=null?le(he(t)):{},Q(e||!t||!t.__esModule?A(n,"default",{value:t,enumerable:!0}):n,t)),ge=t=>Q(A({},"__esModule",{value:!0}),t);var Pe=(t,e,n)=>{if(!e.has(t))throw TypeError("Cannot "+n)};var R=(t,e,n)=>(Pe(t,e,"read from private field"),n?n.call(t):e.get(t)),X=(t,e,n)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,n)};var ee=D((rt,K)=>{function g(t,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(t)),this._timeouts=t,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))}K.exports=g;g.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};g.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};g.prototype.retry=function(t){if(this._timeout&&clearTimeout(this._timeout),!t)return!1;var e=new Date().getTime();if(t&&e-this._operationStart>=this._maxRetryTime)return this._errors.push(t),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(t);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1);else return!1;var o=this;return this._timer=setTimeout(function(){o._attempts++,o._operationTimeoutCb&&(o._timeout=setTimeout(function(){o._operationTimeoutCb(o._attempts)},o._operationTimeout),o._options.unref&&o._timeout.unref()),o._fn(o._attempts)},n),this._options.unref&&this._timer.unref(),!0};g.prototype.attempt=function(t,e){this._fn=t,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};g.prototype.try=function(t){console.log("Using RetryOperation.try() is deprecated"),this.attempt(t)};g.prototype.start=function(t){console.log("Using RetryOperation.start() is deprecated"),this.attempt(t)};g.prototype.start=g.prototype.try;g.prototype.errors=function(){return this._errors};g.prototype.attempts=function(){return this._attempts};g.prototype.mainError=function(){if(this._errors.length===0)return null;for(var t={},e=null,n=0,o=0;o<this._errors.length;o++){var r=this._errors[o],s=r.message,i=(t[s]||0)+1;t[s]=i,i>=n&&(e=r,n=i)}return e}});var te=D(E=>{var Ee=ee();E.operation=function(t){var e=E.timeouts(t);return new Ee(e,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})};E.timeouts=function(t){if(t instanceof Array)return[].concat(t);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var n in t)e[n]=t[n];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var o=[],r=0;r<e.retries;r++)o.push(this.createTimeout(r,e));return t&&t.forever&&!o.length&&o.push(this.createTimeout(r,e)),o.sort(function(s,i){return s-i}),o};E.createTimeout=function(t,e){var n=e.randomize?Math.random()+1:1,o=Math.round(n*Math.max(e.minTimeout,1)*Math.pow(e.factor,t));return o=Math.min(o,e.maxTimeout),o};E.wrap=function(t,e,n){if(e instanceof Array&&(n=e,e=null),!n){n=[];for(var o in t)typeof t[o]=="function"&&n.push(o)}for(var r=0;r<n.length;r++){var s=n[r],i=t[s];t[s]=function(a){var d=E.operation(e),l=Array.prototype.slice.call(arguments,1),c=l.pop();l.push(function(u){d.retry(u)||(u&&(arguments[0]=d.mainError()),c.apply(this,arguments))}),d.attempt(function(){a.apply(t,l)})}.bind(t,i),t[s].options=e}}});var oe=D((it,ne)=>{ne.exports=te()});var nt={};ye(nt,{ApiClientError:()=>Y.ApiClientError,BatchEntry:()=>S,CANVAS_DRAFT_STATE:()=>bt,CANVAS_ENRICHMENT_TAG_PARAM:()=>Le,CANVAS_INTENT_TAG_PARAM:()=>Ne,CANVAS_LOCALE_TAG_PARAM:()=>F,CANVAS_LOCALIZATION_SLOT:()=>k,CANVAS_LOCALIZATION_TYPE:()=>$,CANVAS_PERSONALIZATION_PARAM:()=>H,CANVAS_PERSONALIZE_SLOT:()=>Ge,CANVAS_PERSONALIZE_TYPE:()=>be,CANVAS_PUBLISHED_STATE:()=>Mt,CANVAS_TEST_SLOT:()=>Be,CANVAS_TEST_TYPE:()=>Me,CANVAS_TEST_VARIANT_PARAM:()=>J,CanvasClient:()=>I,CanvasClientError:()=>tt,ChildEnhancerBuilder:()=>v,DataSourceClient:()=>j,DataTypeClient:()=>w,EDGE_CACHE_DISABLED:()=>Lt,EDGE_DEFAULT_CACHE_TTL:()=>Bt,EDGE_DEFAULT_L2_CACHE_TTL_IN_HOURS:()=>Vt,EDGE_MAX_CACHE_TTL:()=>Gt,EDGE_MAX_L2_CACHE_TTL_IN_HOURS:()=>jt,EDGE_MIN_CACHE_TTL:()=>Nt,EDGE_MIN_L2_CACHE_TTL_IN_HOURS:()=>Ut,EnhancerBuilder:()=>V,IN_CONTEXT_EDITOR_COMPONENT_START_ROLE:()=>je,IN_CONTEXT_EDITOR_QUERY_STRING_PARAM:()=>Ue,PLACEHOLDER_ID:()=>Ve,UncachedCanvasClient:()=>L,UniqueBatchEntries:()=>z,compose:()=>Re,createBatchEnhancer:()=>Ae,createCanvasChannel:()=>Ze,createEventBus:()=>qe,createLimitPolicy:()=>B,enhance:()=>Se,extractLocales:()=>ce,generateHash:()=>W,getChannelName:()=>Z,getComponentJsonPointer:()=>we,getComponentPath:()=>O,isAddComponentMessage:()=>Je,isDismissPlaceholderMessage:()=>We,isMovingComponentMessage:()=>ze,isReadyMessage:()=>ke,isSelectComponentMessage:()=>Fe,isSystemComponentDefinition:()=>Xe,isUpdateCompositionMessage:()=>He,localize:()=>$e,mapSlotToPersonalizedVariations:()=>Ke,mapSlotToTestVariations:()=>et,nullLimitPolicy:()=>P,subscribeToComposition:()=>Qe,walkComponentTree:()=>x});module.exports=ge(nt);var ie=require("@uniformdev/context/api");var se=Ce(oe(),1),Te=new Set(["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"]),b=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}},_e=(t,e,n)=>{let o=n.retries-(e-1);return t.attemptNumber=e,t.retriesLeft=o,t},xe=t=>Te.has(t),re=t=>globalThis.DOMException===void 0?new Error(t):new DOMException(t);async function M(t,e){return new Promise((n,o)=>{e={onFailedAttempt(){},retries:10,...e};let r=se.default.operation(e);r.attempt(async s=>{try{n(await t(s))}catch(i){if(!(i instanceof Error)){o(new TypeError(`Non-error was thrown: "${i}". You should only throw errors.`));return}if(i instanceof b)r.stop(),o(i.originalError);else if(i instanceof TypeError&&!xe(i.message))r.stop(),o(i);else{_e(i,s,e);try{await e.onFailedAttempt(i)}catch(p){o(p);return}r.retry(i)||o(r.mainError())}}}),e.signal&&!e.signal.aborted&&e.signal.addEventListener("abort",()=>{r.stop();let s=e.signal.reason===void 0?re("The operation was aborted."):e.signal.reason;o(s instanceof Error?s:re(s))},{once:!0})})}var N=class extends Error{constructor(){super("Throttled function aborted"),this.name="AbortError"}};function G({limit:t,interval:e,strict:n}){if(!Number.isFinite(t))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 o=new Map,r=0,s=0;function i(){let l=Date.now();return l-r>e?(s=1,r=l,0):(s<t?s++:(r+=e,s=1),r-l)}let p=[];function a(){let l=Date.now();if(p.length<t)return p.push(l),0;let c=p.shift()+e;return l>=c?(p.push(l),0):(p.push(c),c-l)}let d=n?a:i;return l=>{let c=function(...u){if(!c.isEnabled)return(async()=>l.apply(this,u))();let f;return new Promise((C,m)=>{f=setTimeout(()=>{C(l.apply(this,u)),o.delete(f)},d()),o.set(f,m)})};return c.abort=()=>{for(let u of o.keys())clearTimeout(u),o.get(u)(new N);o.clear(),p.splice(0,p.length)},c.isEnabled=!0,c}}function B({throttle:t={interval:1e3,limit:10},retry:e={retries:1,factor:1.66}}){let n=t?G(t):null;return function(r){let s=async()=>await r();if(n&&(s=n(s)),e){let i=s;s=()=>M(i,e)}return s()}}var P=async t=>await t();var I=class extends ie.ApiClient{constructor(n){n.limitPolicy||(n.limitPolicy=B({}));super(n);this.canvasUrl="/api/v1/canvas"}async getCompositionList(n){let{projectId:o}=this.options,r=this.createUrl(this.canvasUrl,{...n,projectId:o});return await this.apiClient(r)}unstable_getCompositionByNodePath(n){return this.getOneComposition(n)}unstable_getCompositionByNodeId(n){return this.getOneComposition(n)}getCompositionBySlug(n){return this.getOneComposition(n)}getCompositionById(n){return this.getOneComposition(n)}getOneComposition({unstable_resolveData:n,unstable_dynamicVariables:o,unstable_dataDiagnostics:r,...s}){let{projectId:i}=this.options,p=n?"/api/edge/v1/composition":this.canvasUrl,a={};return n&&(o&&(a.dynamicVariables=JSON.stringify(o)),r&&(a.dataDiagnostics="true")),this.apiClient(this.createUrl(p,{...s,...a,projectId:i}))}async updateComposition(n){let o=this.createUrl("/api/v1/canvas");await this.apiClient(o,{method:"PUT",body:JSON.stringify({...n,projectId:this.options.projectId}),expectNoContent:!0})}async removeComposition(n){let o=this.createUrl("/api/v1/canvas"),{projectId:r}=this.options;await this.apiClient(o,{method:"DELETE",body:JSON.stringify({...n,projectId:r}),expectNoContent:!0})}async getComponentDefinitions(n){let{projectId:o}=this.options,r=this.createUrl("/api/v1/canvas-definitions",{...n,projectId:o});return await this.apiClient(r)}async updateComponentDefinition(n){let o=this.createUrl("/api/v1/canvas-definitions");await this.apiClient(o,{method:"PUT",body:JSON.stringify({...n,projectId:this.options.projectId}),expectNoContent:!0})}async removeComponentDefinition(n){let o=this.createUrl("/api/v1/canvas-definitions");await this.apiClient(o,{method:"DELETE",body:JSON.stringify({...n,projectId:this.options.projectId}),expectNoContent:!0})}},L=class extends I{constructor(e){super({...e,bypassCache:!0})}};var ae=require("@uniformdev/context/api"),U="/api/v1/data-source",ve="/api/v1/data-sources",j=class extends ae.ApiClient{constructor(e){super(e)}async get(e){let{projectId:n}=this.options,o=this.createUrl(U,{...e,projectId:n});return await this.apiClient(o)}async getList(e){let{projectId:n}=this.options,o=this.createUrl(ve,{...e,projectId:n});return await this.apiClient(o)}async upsert(e){let n=this.createUrl(U);await this.apiClient(n,{method:"PUT",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async remove(e){let n=this.createUrl(U);await this.apiClient(n,{method:"DELETE",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}};var pe=require("@uniformdev/context/api");var T,_=class extends pe.ApiClient{constructor(e){super(e)}async get(e){let{projectId:n}=this.options,o=this.createUrl(R(_,T),{...e,projectId:n});return await this.apiClient(o)}async upsert(e){let n=this.createUrl(R(_,T));await this.apiClient(n,{method:"PUT",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async remove(e){let n=this.createUrl(R(_,T));await this.apiClient(n,{method:"DELETE",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}},w=_;T=new WeakMap,X(w,T,"/api/v1/data-types");var S=class{constructor(e,n,o){this._resolve=e;this._reject=n;this.args=o;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 Ae({handleBatch:t,shouldQueue:e,limitPolicy:n}){let o=[];return{enhanceOne:async i=>{if(!e||e(i))return new Promise((p,a)=>{o.push(new S(p,a,i))})},completeAll:async()=>{if(o.length>0){try{await t(o)}catch(p){o.forEach(a=>a.reject(p))}if(o.some(p=>!p.isCompleted))throw new Error("The completeAll() function failed to resolve or reject all promises in the batch!")}let i=o.length;return o=[],i},limitPolicy:n}}var Re=(t,...e)=>({enhanceOne:o=>{let r="enhanceOne"in t?t.enhanceOne(o):t(o);for(let s of e){let i=Ie(r)?r:Promise.resolve(r),p="enhanceOne"in s?s.enhanceOne:s;r=i.then(a=>p({...o,parameter:{type:o.parameter.type,value:a}}))}return r},completeAll:async()=>{var o,r;for(let s of e)if("completeAll"in s)throw new Error("Only the first enhancer in a compose chain can use the completeAll function (batching)");return(r="completeAll"in t?(o=t.completeAll)==null?void 0:o.call(t):0)!=null?r:0}});function Ie(t){return!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function"}function x(t,e,n){var s;let o=[{ancestorsAndSelf:[{component:t,parentSlot:void 0,parentSlotIndex:void 0}],context:n}],r=new Map;do{let i=o.pop();if(!i)continue;let p=i.ancestorsAndSelf[0],a=!0,d=(s=r.get(p.component))!=null?s:i.context;e(p.component,i.ancestorsAndSelf,{replaceComponent:c=>{Object.assign(p.component,c),["parameters","variant","slots","data","_pattern","_patternError"].forEach(f=>{c[f]||delete p.component[f]})},removeComponent:()=>{let{parentSlot:c,parentSlotIndex:u}=i.ancestorsAndSelf[0],f=i.ancestorsAndSelf[1];if(c&&typeof u!="undefined")f.component.slots[c].splice(u,1);else throw new Error("Unable to delete composition.")},insertAfter:c=>{let u=Array.isArray(c)?c:[c],{parentSlot:f,parentSlotIndex:C}=i.ancestorsAndSelf[0],m=i.ancestorsAndSelf[1];if(f&&typeof C!="undefined")m.component.slots[f].splice(C+1,0,...u),o.unshift(...u.map(h=>({ancestorsAndSelf:[{component:h,parentSlot:f,get parentSlotIndex(){return m.component.slots[f].findIndex(y=>y===h)}},...i.ancestorsAndSelf],context:d})));else throw new Error("Unable to insert after a component not in a slot.")},stopProcessingDescendants(){a=!1},setDescendantsContext(c){d=c},setChildContext(c,u){r.set(c,u)}},d);let l=p.component.slots;if(a&&l){let c=Object.keys(l);for(let u=c.length-1;u>=0;u--){let f=c[u],C=l[f];for(let m=C.length-1;m>=0;m--){let h=C[m];o.push({ancestorsAndSelf:[{component:h,parentSlot:f,get parentSlotIndex(){return p.component.slots[f].findIndex(y=>y===h)}},...i.ancestorsAndSelf],context:d})}}}}while(o.length>0)}function O(t){let e=[];for(let n=t.length-1;n>=0;n--){let{parentSlot:o,parentSlotIndex:r}=t[n];o&&r!==void 0&&e.push(`${o}[${r}]`)}return`.${e.join(".")}`}function we(t,{withSlots:e=!1}={}){let n=[];for(let o=t.length-1;o>=0;o--){let{parentSlot:r,parentSlotIndex:s}=t[o];r&&s!==void 0&&n.push(`${r}/${s}`)}return e?`/slots/${n.join("/slots/")}`:`/${n.join("/")}`}async function Se({composition:t,enhancers:e,context:n,onErrors:o=r=>{throw new Error(r.map(s=>`${s.message}
|
2
|
-
|
1
|
+
"use strict";
|
2
|
+
var __create = Object.create;
|
3
|
+
var __defProp = Object.defineProperty;
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
8
|
+
var __commonJS = (cb, mod) => function __require() {
|
9
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
10
|
+
};
|
11
|
+
var __export = (target, all) => {
|
12
|
+
for (var name in all)
|
13
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
14
|
+
};
|
15
|
+
var __copyProps = (to, from, except, desc) => {
|
16
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
17
|
+
for (let key of __getOwnPropNames(from))
|
18
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
19
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
20
|
+
}
|
21
|
+
return to;
|
22
|
+
};
|
23
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
24
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
25
|
+
mod
|
26
|
+
));
|
27
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
28
|
+
var __accessCheck = (obj, member, msg) => {
|
29
|
+
if (!member.has(obj))
|
30
|
+
throw TypeError("Cannot " + msg);
|
31
|
+
};
|
32
|
+
var __privateGet = (obj, member, getter) => {
|
33
|
+
__accessCheck(obj, member, "read from private field");
|
34
|
+
return getter ? getter.call(obj) : member.get(obj);
|
35
|
+
};
|
36
|
+
var __privateAdd = (obj, member, value) => {
|
37
|
+
if (member.has(obj))
|
38
|
+
throw TypeError("Cannot add the same private member more than once");
|
39
|
+
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
40
|
+
};
|
3
41
|
|
4
|
-
|
42
|
+
// ../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js
|
43
|
+
var require_retry_operation = __commonJS({
|
44
|
+
"../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry_operation.js"(exports, module2) {
|
45
|
+
function RetryOperation(timeouts, options) {
|
46
|
+
if (typeof options === "boolean") {
|
47
|
+
options = { forever: options };
|
48
|
+
}
|
49
|
+
this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
|
50
|
+
this._timeouts = timeouts;
|
51
|
+
this._options = options || {};
|
52
|
+
this._maxRetryTime = options && options.maxRetryTime || Infinity;
|
53
|
+
this._fn = null;
|
54
|
+
this._errors = [];
|
55
|
+
this._attempts = 1;
|
56
|
+
this._operationTimeout = null;
|
57
|
+
this._operationTimeoutCb = null;
|
58
|
+
this._timeout = null;
|
59
|
+
this._operationStart = null;
|
60
|
+
this._timer = null;
|
61
|
+
if (this._options.forever) {
|
62
|
+
this._cachedTimeouts = this._timeouts.slice(0);
|
63
|
+
}
|
64
|
+
}
|
65
|
+
module2.exports = RetryOperation;
|
66
|
+
RetryOperation.prototype.reset = function() {
|
67
|
+
this._attempts = 1;
|
68
|
+
this._timeouts = this._originalTimeouts.slice(0);
|
69
|
+
};
|
70
|
+
RetryOperation.prototype.stop = function() {
|
71
|
+
if (this._timeout) {
|
72
|
+
clearTimeout(this._timeout);
|
73
|
+
}
|
74
|
+
if (this._timer) {
|
75
|
+
clearTimeout(this._timer);
|
76
|
+
}
|
77
|
+
this._timeouts = [];
|
78
|
+
this._cachedTimeouts = null;
|
79
|
+
};
|
80
|
+
RetryOperation.prototype.retry = function(err) {
|
81
|
+
if (this._timeout) {
|
82
|
+
clearTimeout(this._timeout);
|
83
|
+
}
|
84
|
+
if (!err) {
|
85
|
+
return false;
|
86
|
+
}
|
87
|
+
var currentTime = new Date().getTime();
|
88
|
+
if (err && currentTime - this._operationStart >= this._maxRetryTime) {
|
89
|
+
this._errors.push(err);
|
90
|
+
this._errors.unshift(new Error("RetryOperation timeout occurred"));
|
91
|
+
return false;
|
92
|
+
}
|
93
|
+
this._errors.push(err);
|
94
|
+
var timeout = this._timeouts.shift();
|
95
|
+
if (timeout === void 0) {
|
96
|
+
if (this._cachedTimeouts) {
|
97
|
+
this._errors.splice(0, this._errors.length - 1);
|
98
|
+
timeout = this._cachedTimeouts.slice(-1);
|
99
|
+
} else {
|
100
|
+
return false;
|
101
|
+
}
|
102
|
+
}
|
103
|
+
var self = this;
|
104
|
+
this._timer = setTimeout(function() {
|
105
|
+
self._attempts++;
|
106
|
+
if (self._operationTimeoutCb) {
|
107
|
+
self._timeout = setTimeout(function() {
|
108
|
+
self._operationTimeoutCb(self._attempts);
|
109
|
+
}, self._operationTimeout);
|
110
|
+
if (self._options.unref) {
|
111
|
+
self._timeout.unref();
|
112
|
+
}
|
113
|
+
}
|
114
|
+
self._fn(self._attempts);
|
115
|
+
}, timeout);
|
116
|
+
if (this._options.unref) {
|
117
|
+
this._timer.unref();
|
118
|
+
}
|
119
|
+
return true;
|
120
|
+
};
|
121
|
+
RetryOperation.prototype.attempt = function(fn, timeoutOps) {
|
122
|
+
this._fn = fn;
|
123
|
+
if (timeoutOps) {
|
124
|
+
if (timeoutOps.timeout) {
|
125
|
+
this._operationTimeout = timeoutOps.timeout;
|
126
|
+
}
|
127
|
+
if (timeoutOps.cb) {
|
128
|
+
this._operationTimeoutCb = timeoutOps.cb;
|
129
|
+
}
|
130
|
+
}
|
131
|
+
var self = this;
|
132
|
+
if (this._operationTimeoutCb) {
|
133
|
+
this._timeout = setTimeout(function() {
|
134
|
+
self._operationTimeoutCb();
|
135
|
+
}, self._operationTimeout);
|
136
|
+
}
|
137
|
+
this._operationStart = new Date().getTime();
|
138
|
+
this._fn(this._attempts);
|
139
|
+
};
|
140
|
+
RetryOperation.prototype.try = function(fn) {
|
141
|
+
console.log("Using RetryOperation.try() is deprecated");
|
142
|
+
this.attempt(fn);
|
143
|
+
};
|
144
|
+
RetryOperation.prototype.start = function(fn) {
|
145
|
+
console.log("Using RetryOperation.start() is deprecated");
|
146
|
+
this.attempt(fn);
|
147
|
+
};
|
148
|
+
RetryOperation.prototype.start = RetryOperation.prototype.try;
|
149
|
+
RetryOperation.prototype.errors = function() {
|
150
|
+
return this._errors;
|
151
|
+
};
|
152
|
+
RetryOperation.prototype.attempts = function() {
|
153
|
+
return this._attempts;
|
154
|
+
};
|
155
|
+
RetryOperation.prototype.mainError = function() {
|
156
|
+
if (this._errors.length === 0) {
|
157
|
+
return null;
|
158
|
+
}
|
159
|
+
var counts = {};
|
160
|
+
var mainError = null;
|
161
|
+
var mainErrorCount = 0;
|
162
|
+
for (var i = 0; i < this._errors.length; i++) {
|
163
|
+
var error = this._errors[i];
|
164
|
+
var message = error.message;
|
165
|
+
var count = (counts[message] || 0) + 1;
|
166
|
+
counts[message] = count;
|
167
|
+
if (count >= mainErrorCount) {
|
168
|
+
mainError = error;
|
169
|
+
mainErrorCount = count;
|
170
|
+
}
|
171
|
+
}
|
172
|
+
return mainError;
|
173
|
+
};
|
174
|
+
}
|
175
|
+
});
|
176
|
+
|
177
|
+
// ../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js
|
178
|
+
var require_retry = __commonJS({
|
179
|
+
"../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/lib/retry.js"(exports) {
|
180
|
+
var RetryOperation = require_retry_operation();
|
181
|
+
exports.operation = function(options) {
|
182
|
+
var timeouts = exports.timeouts(options);
|
183
|
+
return new RetryOperation(timeouts, {
|
184
|
+
forever: options && (options.forever || options.retries === Infinity),
|
185
|
+
unref: options && options.unref,
|
186
|
+
maxRetryTime: options && options.maxRetryTime
|
187
|
+
});
|
188
|
+
};
|
189
|
+
exports.timeouts = function(options) {
|
190
|
+
if (options instanceof Array) {
|
191
|
+
return [].concat(options);
|
192
|
+
}
|
193
|
+
var opts = {
|
194
|
+
retries: 10,
|
195
|
+
factor: 2,
|
196
|
+
minTimeout: 1 * 1e3,
|
197
|
+
maxTimeout: Infinity,
|
198
|
+
randomize: false
|
199
|
+
};
|
200
|
+
for (var key in options) {
|
201
|
+
opts[key] = options[key];
|
202
|
+
}
|
203
|
+
if (opts.minTimeout > opts.maxTimeout) {
|
204
|
+
throw new Error("minTimeout is greater than maxTimeout");
|
205
|
+
}
|
206
|
+
var timeouts = [];
|
207
|
+
for (var i = 0; i < opts.retries; i++) {
|
208
|
+
timeouts.push(this.createTimeout(i, opts));
|
209
|
+
}
|
210
|
+
if (options && options.forever && !timeouts.length) {
|
211
|
+
timeouts.push(this.createTimeout(i, opts));
|
212
|
+
}
|
213
|
+
timeouts.sort(function(a, b) {
|
214
|
+
return a - b;
|
215
|
+
});
|
216
|
+
return timeouts;
|
217
|
+
};
|
218
|
+
exports.createTimeout = function(attempt, opts) {
|
219
|
+
var random = opts.randomize ? Math.random() + 1 : 1;
|
220
|
+
var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));
|
221
|
+
timeout = Math.min(timeout, opts.maxTimeout);
|
222
|
+
return timeout;
|
223
|
+
};
|
224
|
+
exports.wrap = function(obj, options, methods) {
|
225
|
+
if (options instanceof Array) {
|
226
|
+
methods = options;
|
227
|
+
options = null;
|
228
|
+
}
|
229
|
+
if (!methods) {
|
230
|
+
methods = [];
|
231
|
+
for (var key in obj) {
|
232
|
+
if (typeof obj[key] === "function") {
|
233
|
+
methods.push(key);
|
234
|
+
}
|
235
|
+
}
|
236
|
+
}
|
237
|
+
for (var i = 0; i < methods.length; i++) {
|
238
|
+
var method = methods[i];
|
239
|
+
var original = obj[method];
|
240
|
+
obj[method] = function retryWrapper(original2) {
|
241
|
+
var op = exports.operation(options);
|
242
|
+
var args = Array.prototype.slice.call(arguments, 1);
|
243
|
+
var callback = args.pop();
|
244
|
+
args.push(function(err) {
|
245
|
+
if (op.retry(err)) {
|
246
|
+
return;
|
247
|
+
}
|
248
|
+
if (err) {
|
249
|
+
arguments[0] = op.mainError();
|
250
|
+
}
|
251
|
+
callback.apply(this, arguments);
|
252
|
+
});
|
253
|
+
op.attempt(function() {
|
254
|
+
original2.apply(obj, args);
|
255
|
+
});
|
256
|
+
}.bind(obj, original);
|
257
|
+
obj[method].options = options;
|
258
|
+
}
|
259
|
+
};
|
260
|
+
}
|
261
|
+
});
|
262
|
+
|
263
|
+
// ../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js
|
264
|
+
var require_retry2 = __commonJS({
|
265
|
+
"../../node_modules/.pnpm/retry@0.13.1/node_modules/retry/index.js"(exports, module2) {
|
266
|
+
module2.exports = require_retry();
|
267
|
+
}
|
268
|
+
});
|
269
|
+
|
270
|
+
// src/index.ts
|
271
|
+
var src_exports = {};
|
272
|
+
__export(src_exports, {
|
273
|
+
ApiClientError: () => import_api4.ApiClientError,
|
274
|
+
BatchEntry: () => BatchEntry,
|
275
|
+
CANVAS_DRAFT_STATE: () => CANVAS_DRAFT_STATE,
|
276
|
+
CANVAS_ENRICHMENT_TAG_PARAM: () => CANVAS_ENRICHMENT_TAG_PARAM,
|
277
|
+
CANVAS_INTENT_TAG_PARAM: () => CANVAS_INTENT_TAG_PARAM,
|
278
|
+
CANVAS_LOCALE_TAG_PARAM: () => CANVAS_LOCALE_TAG_PARAM,
|
279
|
+
CANVAS_LOCALIZATION_SLOT: () => CANVAS_LOCALIZATION_SLOT,
|
280
|
+
CANVAS_LOCALIZATION_TYPE: () => CANVAS_LOCALIZATION_TYPE,
|
281
|
+
CANVAS_PERSONALIZATION_PARAM: () => CANVAS_PERSONALIZATION_PARAM,
|
282
|
+
CANVAS_PERSONALIZE_SLOT: () => CANVAS_PERSONALIZE_SLOT,
|
283
|
+
CANVAS_PERSONALIZE_TYPE: () => CANVAS_PERSONALIZE_TYPE,
|
284
|
+
CANVAS_PUBLISHED_STATE: () => CANVAS_PUBLISHED_STATE,
|
285
|
+
CANVAS_TEST_SLOT: () => CANVAS_TEST_SLOT,
|
286
|
+
CANVAS_TEST_TYPE: () => CANVAS_TEST_TYPE,
|
287
|
+
CANVAS_TEST_VARIANT_PARAM: () => CANVAS_TEST_VARIANT_PARAM,
|
288
|
+
CanvasClient: () => CanvasClient,
|
289
|
+
CanvasClientError: () => CanvasClientError,
|
290
|
+
ChildEnhancerBuilder: () => ChildEnhancerBuilder,
|
291
|
+
DataSourceClient: () => DataSourceClient,
|
292
|
+
DataTypeClient: () => DataTypeClient,
|
293
|
+
EDGE_CACHE_DISABLED: () => EDGE_CACHE_DISABLED,
|
294
|
+
EDGE_DEFAULT_CACHE_TTL: () => EDGE_DEFAULT_CACHE_TTL,
|
295
|
+
EDGE_DEFAULT_L2_CACHE_TTL_IN_HOURS: () => EDGE_DEFAULT_L2_CACHE_TTL_IN_HOURS,
|
296
|
+
EDGE_MAX_CACHE_TTL: () => EDGE_MAX_CACHE_TTL,
|
297
|
+
EDGE_MAX_L2_CACHE_TTL_IN_HOURS: () => EDGE_MAX_L2_CACHE_TTL_IN_HOURS,
|
298
|
+
EDGE_MIN_CACHE_TTL: () => EDGE_MIN_CACHE_TTL,
|
299
|
+
EDGE_MIN_L2_CACHE_TTL_IN_HOURS: () => EDGE_MIN_L2_CACHE_TTL_IN_HOURS,
|
300
|
+
EnhancerBuilder: () => EnhancerBuilder,
|
301
|
+
IN_CONTEXT_EDITOR_COMPONENT_START_ROLE: () => IN_CONTEXT_EDITOR_COMPONENT_START_ROLE,
|
302
|
+
IN_CONTEXT_EDITOR_QUERY_STRING_PARAM: () => IN_CONTEXT_EDITOR_QUERY_STRING_PARAM,
|
303
|
+
PLACEHOLDER_ID: () => PLACEHOLDER_ID,
|
304
|
+
UncachedCanvasClient: () => UncachedCanvasClient,
|
305
|
+
UniqueBatchEntries: () => UniqueBatchEntries,
|
306
|
+
compose: () => compose,
|
307
|
+
createBatchEnhancer: () => createBatchEnhancer,
|
308
|
+
createCanvasChannel: () => createCanvasChannel,
|
309
|
+
createEventBus: () => createEventBus,
|
310
|
+
createLimitPolicy: () => createLimitPolicy,
|
311
|
+
enhance: () => enhance,
|
312
|
+
extractLocales: () => extractLocales,
|
313
|
+
generateHash: () => generateHash,
|
314
|
+
getChannelName: () => getChannelName,
|
315
|
+
getComponentJsonPointer: () => getComponentJsonPointer,
|
316
|
+
getComponentPath: () => getComponentPath,
|
317
|
+
isAddComponentMessage: () => isAddComponentMessage,
|
318
|
+
isDismissPlaceholderMessage: () => isDismissPlaceholderMessage,
|
319
|
+
isMovingComponentMessage: () => isMovingComponentMessage,
|
320
|
+
isReadyMessage: () => isReadyMessage,
|
321
|
+
isSelectComponentMessage: () => isSelectComponentMessage,
|
322
|
+
isSystemComponentDefinition: () => isSystemComponentDefinition,
|
323
|
+
isUpdateCompositionMessage: () => isUpdateCompositionMessage,
|
324
|
+
localize: () => localize,
|
325
|
+
mapSlotToPersonalizedVariations: () => mapSlotToPersonalizedVariations,
|
326
|
+
mapSlotToTestVariations: () => mapSlotToTestVariations,
|
327
|
+
nullLimitPolicy: () => nullLimitPolicy,
|
328
|
+
subscribeToComposition: () => subscribeToComposition,
|
329
|
+
walkComponentTree: () => walkComponentTree
|
330
|
+
});
|
331
|
+
module.exports = __toCommonJS(src_exports);
|
332
|
+
|
333
|
+
// src/CanvasClient.ts
|
334
|
+
var import_api = require("@uniformdev/context/api");
|
335
|
+
|
336
|
+
// ../../node_modules/.pnpm/p-retry@5.1.2/node_modules/p-retry/index.js
|
337
|
+
var import_retry = __toESM(require_retry2(), 1);
|
338
|
+
var networkErrorMsgs = /* @__PURE__ */ new Set([
|
339
|
+
"Failed to fetch",
|
340
|
+
"NetworkError when attempting to fetch resource.",
|
341
|
+
"The Internet connection appears to be offline.",
|
342
|
+
"Network request failed",
|
343
|
+
"fetch failed"
|
344
|
+
]);
|
345
|
+
var AbortError = class extends Error {
|
346
|
+
constructor(message) {
|
347
|
+
super();
|
348
|
+
if (message instanceof Error) {
|
349
|
+
this.originalError = message;
|
350
|
+
({ message } = message);
|
351
|
+
} else {
|
352
|
+
this.originalError = new Error(message);
|
353
|
+
this.originalError.stack = this.stack;
|
354
|
+
}
|
355
|
+
this.name = "AbortError";
|
356
|
+
this.message = message;
|
357
|
+
}
|
358
|
+
};
|
359
|
+
var decorateErrorWithCounts = (error, attemptNumber, options) => {
|
360
|
+
const retriesLeft = options.retries - (attemptNumber - 1);
|
361
|
+
error.attemptNumber = attemptNumber;
|
362
|
+
error.retriesLeft = retriesLeft;
|
363
|
+
return error;
|
364
|
+
};
|
365
|
+
var isNetworkError = (errorMessage) => networkErrorMsgs.has(errorMessage);
|
366
|
+
var getDOMException = (errorMessage) => globalThis.DOMException === void 0 ? new Error(errorMessage) : new DOMException(errorMessage);
|
367
|
+
async function pRetry(input, options) {
|
368
|
+
return new Promise((resolve, reject) => {
|
369
|
+
options = {
|
370
|
+
onFailedAttempt() {
|
371
|
+
},
|
372
|
+
retries: 10,
|
373
|
+
...options
|
374
|
+
};
|
375
|
+
const operation = import_retry.default.operation(options);
|
376
|
+
operation.attempt(async (attemptNumber) => {
|
377
|
+
try {
|
378
|
+
resolve(await input(attemptNumber));
|
379
|
+
} catch (error) {
|
380
|
+
if (!(error instanceof Error)) {
|
381
|
+
reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));
|
382
|
+
return;
|
383
|
+
}
|
384
|
+
if (error instanceof AbortError) {
|
385
|
+
operation.stop();
|
386
|
+
reject(error.originalError);
|
387
|
+
} else if (error instanceof TypeError && !isNetworkError(error.message)) {
|
388
|
+
operation.stop();
|
389
|
+
reject(error);
|
390
|
+
} else {
|
391
|
+
decorateErrorWithCounts(error, attemptNumber, options);
|
392
|
+
try {
|
393
|
+
await options.onFailedAttempt(error);
|
394
|
+
} catch (error2) {
|
395
|
+
reject(error2);
|
396
|
+
return;
|
397
|
+
}
|
398
|
+
if (!operation.retry(error)) {
|
399
|
+
reject(operation.mainError());
|
400
|
+
}
|
401
|
+
}
|
402
|
+
}
|
403
|
+
});
|
404
|
+
if (options.signal && !options.signal.aborted) {
|
405
|
+
options.signal.addEventListener("abort", () => {
|
406
|
+
operation.stop();
|
407
|
+
const reason = options.signal.reason === void 0 ? getDOMException("The operation was aborted.") : options.signal.reason;
|
408
|
+
reject(reason instanceof Error ? reason : getDOMException(reason));
|
409
|
+
}, {
|
410
|
+
once: true
|
411
|
+
});
|
412
|
+
}
|
413
|
+
});
|
414
|
+
}
|
415
|
+
|
416
|
+
// ../../node_modules/.pnpm/p-throttle@5.0.0/node_modules/p-throttle/index.js
|
417
|
+
var AbortError2 = class extends Error {
|
418
|
+
constructor() {
|
419
|
+
super("Throttled function aborted");
|
420
|
+
this.name = "AbortError";
|
421
|
+
}
|
422
|
+
};
|
423
|
+
function pThrottle({ limit, interval, strict }) {
|
424
|
+
if (!Number.isFinite(limit)) {
|
425
|
+
throw new TypeError("Expected `limit` to be a finite number");
|
426
|
+
}
|
427
|
+
if (!Number.isFinite(interval)) {
|
428
|
+
throw new TypeError("Expected `interval` to be a finite number");
|
429
|
+
}
|
430
|
+
const queue = /* @__PURE__ */ new Map();
|
431
|
+
let currentTick = 0;
|
432
|
+
let activeCount = 0;
|
433
|
+
function windowedDelay() {
|
434
|
+
const now = Date.now();
|
435
|
+
if (now - currentTick > interval) {
|
436
|
+
activeCount = 1;
|
437
|
+
currentTick = now;
|
438
|
+
return 0;
|
439
|
+
}
|
440
|
+
if (activeCount < limit) {
|
441
|
+
activeCount++;
|
442
|
+
} else {
|
443
|
+
currentTick += interval;
|
444
|
+
activeCount = 1;
|
445
|
+
}
|
446
|
+
return currentTick - now;
|
447
|
+
}
|
448
|
+
const strictTicks = [];
|
449
|
+
function strictDelay() {
|
450
|
+
const now = Date.now();
|
451
|
+
if (strictTicks.length < limit) {
|
452
|
+
strictTicks.push(now);
|
453
|
+
return 0;
|
454
|
+
}
|
455
|
+
const earliestTime = strictTicks.shift() + interval;
|
456
|
+
if (now >= earliestTime) {
|
457
|
+
strictTicks.push(now);
|
458
|
+
return 0;
|
459
|
+
}
|
460
|
+
strictTicks.push(earliestTime);
|
461
|
+
return earliestTime - now;
|
462
|
+
}
|
463
|
+
const getDelay = strict ? strictDelay : windowedDelay;
|
464
|
+
return (function_) => {
|
465
|
+
const throttled = function(...args) {
|
466
|
+
if (!throttled.isEnabled) {
|
467
|
+
return (async () => function_.apply(this, args))();
|
468
|
+
}
|
469
|
+
let timeout;
|
470
|
+
return new Promise((resolve, reject) => {
|
471
|
+
const execute = () => {
|
472
|
+
resolve(function_.apply(this, args));
|
473
|
+
queue.delete(timeout);
|
474
|
+
};
|
475
|
+
timeout = setTimeout(execute, getDelay());
|
476
|
+
queue.set(timeout, reject);
|
477
|
+
});
|
478
|
+
};
|
479
|
+
throttled.abort = () => {
|
480
|
+
for (const timeout of queue.keys()) {
|
481
|
+
clearTimeout(timeout);
|
482
|
+
queue.get(timeout)(new AbortError2());
|
483
|
+
}
|
484
|
+
queue.clear();
|
485
|
+
strictTicks.splice(0, strictTicks.length);
|
486
|
+
};
|
487
|
+
throttled.isEnabled = true;
|
488
|
+
return throttled;
|
489
|
+
};
|
490
|
+
}
|
491
|
+
|
492
|
+
// src/enhancement/createLimitPolicy.ts
|
493
|
+
function createLimitPolicy({
|
494
|
+
throttle = { interval: 1e3, limit: 10 },
|
495
|
+
retry: retry2 = { retries: 1, factor: 1.66 }
|
496
|
+
}) {
|
497
|
+
const throttler = throttle ? pThrottle(throttle) : null;
|
498
|
+
return function limitPolicy(func) {
|
499
|
+
let currentFunc = async () => await func();
|
500
|
+
if (throttler) {
|
501
|
+
const throttleFunc = currentFunc;
|
502
|
+
currentFunc = throttler(throttleFunc);
|
503
|
+
}
|
504
|
+
if (retry2) {
|
505
|
+
const retryFunc = currentFunc;
|
506
|
+
currentFunc = () => pRetry(retryFunc, retry2);
|
507
|
+
}
|
508
|
+
return currentFunc();
|
509
|
+
};
|
510
|
+
}
|
511
|
+
var nullLimitPolicy = async (func) => await func();
|
512
|
+
|
513
|
+
// src/CanvasClient.ts
|
514
|
+
var CanvasClient = class extends import_api.ApiClient {
|
515
|
+
constructor(options) {
|
516
|
+
if (!options.limitPolicy) {
|
517
|
+
options.limitPolicy = createLimitPolicy({});
|
518
|
+
}
|
519
|
+
super(options);
|
520
|
+
this.canvasUrl = "/api/v1/canvas";
|
521
|
+
}
|
522
|
+
async getCompositionList(options) {
|
523
|
+
const { projectId } = this.options;
|
524
|
+
const fetchUri = this.createUrl(this.canvasUrl, { ...options, projectId });
|
525
|
+
return await this.apiClient(fetchUri);
|
526
|
+
}
|
527
|
+
unstable_getCompositionByNodePath(options) {
|
528
|
+
return this.getOneComposition(options);
|
529
|
+
}
|
530
|
+
unstable_getCompositionByNodeId(options) {
|
531
|
+
return this.getOneComposition(options);
|
532
|
+
}
|
533
|
+
getCompositionBySlug(options) {
|
534
|
+
return this.getOneComposition(options);
|
535
|
+
}
|
536
|
+
getCompositionById(options) {
|
537
|
+
return this.getOneComposition(options);
|
538
|
+
}
|
539
|
+
getOneComposition({
|
540
|
+
unstable_resolveData: resolveData,
|
541
|
+
unstable_dynamicVariables: dynamicVariables,
|
542
|
+
unstable_dataDiagnostics: dataDiagnostics,
|
543
|
+
...params
|
544
|
+
}) {
|
545
|
+
const { projectId } = this.options;
|
546
|
+
const url = resolveData ? "/api/edge/v1/composition" : this.canvasUrl;
|
547
|
+
const dataResolutionParams = {};
|
548
|
+
if (resolveData) {
|
549
|
+
if (dynamicVariables) {
|
550
|
+
dataResolutionParams.dynamicVariables = JSON.stringify(dynamicVariables);
|
551
|
+
}
|
552
|
+
if (dataDiagnostics) {
|
553
|
+
dataResolutionParams.dataDiagnostics = "true";
|
554
|
+
}
|
555
|
+
}
|
556
|
+
return this.apiClient(this.createUrl(url, { ...params, ...dataResolutionParams, projectId }));
|
557
|
+
}
|
558
|
+
async updateComposition(body) {
|
559
|
+
const fetchUri = this.createUrl("/api/v1/canvas");
|
560
|
+
await this.apiClient(fetchUri, {
|
561
|
+
method: "PUT",
|
562
|
+
body: JSON.stringify({ ...body, projectId: this.options.projectId }),
|
563
|
+
expectNoContent: true
|
564
|
+
});
|
565
|
+
}
|
566
|
+
async removeComposition(body) {
|
567
|
+
const fetchUri = this.createUrl("/api/v1/canvas");
|
568
|
+
const { projectId } = this.options;
|
569
|
+
await this.apiClient(fetchUri, {
|
570
|
+
method: "DELETE",
|
571
|
+
body: JSON.stringify({ ...body, projectId }),
|
572
|
+
expectNoContent: true
|
573
|
+
});
|
574
|
+
}
|
575
|
+
async getComponentDefinitions(options) {
|
576
|
+
const { projectId } = this.options;
|
577
|
+
const fetchUri = this.createUrl("/api/v1/canvas-definitions", { ...options, projectId });
|
578
|
+
return await this.apiClient(fetchUri);
|
579
|
+
}
|
580
|
+
async updateComponentDefinition(body) {
|
581
|
+
const fetchUri = this.createUrl("/api/v1/canvas-definitions");
|
582
|
+
await this.apiClient(fetchUri, {
|
583
|
+
method: "PUT",
|
584
|
+
body: JSON.stringify({ ...body, projectId: this.options.projectId }),
|
585
|
+
expectNoContent: true
|
586
|
+
});
|
587
|
+
}
|
588
|
+
async removeComponentDefinition(body) {
|
589
|
+
const fetchUri = this.createUrl("/api/v1/canvas-definitions");
|
590
|
+
await this.apiClient(fetchUri, {
|
591
|
+
method: "DELETE",
|
592
|
+
body: JSON.stringify({ ...body, projectId: this.options.projectId }),
|
593
|
+
expectNoContent: true
|
594
|
+
});
|
595
|
+
}
|
596
|
+
};
|
597
|
+
var UncachedCanvasClient = class extends CanvasClient {
|
598
|
+
constructor(options) {
|
599
|
+
super({ ...options, bypassCache: true });
|
600
|
+
}
|
601
|
+
};
|
602
|
+
|
603
|
+
// src/DataSourceClient.ts
|
604
|
+
var import_api2 = require("@uniformdev/context/api");
|
605
|
+
var dataSourceUrl = "/api/v1/data-source";
|
606
|
+
var dataSourcesUrl = "/api/v1/data-sources";
|
607
|
+
var DataSourceClient = class extends import_api2.ApiClient {
|
608
|
+
constructor(options) {
|
609
|
+
super(options);
|
610
|
+
}
|
611
|
+
async get(options) {
|
612
|
+
const { projectId } = this.options;
|
613
|
+
const fetchUri = this.createUrl(dataSourceUrl, { ...options, projectId });
|
614
|
+
return await this.apiClient(fetchUri);
|
615
|
+
}
|
616
|
+
async getList(options) {
|
617
|
+
const { projectId } = this.options;
|
618
|
+
const fetchUri = this.createUrl(dataSourcesUrl, { ...options, projectId });
|
619
|
+
return await this.apiClient(fetchUri);
|
620
|
+
}
|
621
|
+
async upsert(body) {
|
622
|
+
const fetchUri = this.createUrl(dataSourceUrl);
|
623
|
+
await this.apiClient(fetchUri, {
|
624
|
+
method: "PUT",
|
625
|
+
body: JSON.stringify({ ...body, projectId: this.options.projectId }),
|
626
|
+
expectNoContent: true
|
627
|
+
});
|
628
|
+
}
|
629
|
+
async remove(body) {
|
630
|
+
const fetchUri = this.createUrl(dataSourceUrl);
|
631
|
+
await this.apiClient(fetchUri, {
|
632
|
+
method: "DELETE",
|
633
|
+
body: JSON.stringify({ ...body, projectId: this.options.projectId }),
|
634
|
+
expectNoContent: true
|
635
|
+
});
|
636
|
+
}
|
637
|
+
};
|
638
|
+
|
639
|
+
// src/DataTypeClient.ts
|
640
|
+
var import_api3 = require("@uniformdev/context/api");
|
641
|
+
var _url;
|
642
|
+
var _DataTypeClient = class extends import_api3.ApiClient {
|
643
|
+
constructor(options) {
|
644
|
+
super(options);
|
645
|
+
}
|
646
|
+
async get(options) {
|
647
|
+
const { projectId } = this.options;
|
648
|
+
const fetchUri = this.createUrl(__privateGet(_DataTypeClient, _url), { ...options, projectId });
|
649
|
+
return await this.apiClient(fetchUri);
|
650
|
+
}
|
651
|
+
async upsert(body) {
|
652
|
+
const fetchUri = this.createUrl(__privateGet(_DataTypeClient, _url));
|
653
|
+
await this.apiClient(fetchUri, {
|
654
|
+
method: "PUT",
|
655
|
+
body: JSON.stringify({ ...body, projectId: this.options.projectId }),
|
656
|
+
expectNoContent: true
|
657
|
+
});
|
658
|
+
}
|
659
|
+
async remove(body) {
|
660
|
+
const fetchUri = this.createUrl(__privateGet(_DataTypeClient, _url));
|
661
|
+
await this.apiClient(fetchUri, {
|
662
|
+
method: "DELETE",
|
663
|
+
body: JSON.stringify({ ...body, projectId: this.options.projectId }),
|
664
|
+
expectNoContent: true
|
665
|
+
});
|
666
|
+
}
|
667
|
+
};
|
668
|
+
var DataTypeClient = _DataTypeClient;
|
669
|
+
_url = new WeakMap();
|
670
|
+
__privateAdd(DataTypeClient, _url, "/api/v1/data-types");
|
671
|
+
|
672
|
+
// src/enhancement/batchEnhancer.ts
|
673
|
+
var BatchEntry = class {
|
674
|
+
constructor(_resolve, _reject, args) {
|
675
|
+
this._resolve = _resolve;
|
676
|
+
this._reject = _reject;
|
677
|
+
this.args = args;
|
678
|
+
this._isCompleted = false;
|
679
|
+
}
|
680
|
+
resolve(result) {
|
681
|
+
this._resolve(result);
|
682
|
+
this._isCompleted = true;
|
683
|
+
}
|
684
|
+
reject(reason) {
|
685
|
+
this._reject(reason);
|
686
|
+
this._isCompleted = true;
|
687
|
+
}
|
688
|
+
get isCompleted() {
|
689
|
+
return this._isCompleted;
|
690
|
+
}
|
691
|
+
};
|
692
|
+
function createBatchEnhancer({
|
693
|
+
handleBatch,
|
694
|
+
shouldQueue,
|
695
|
+
limitPolicy
|
696
|
+
}) {
|
697
|
+
let queue = [];
|
698
|
+
const batchedFn = async (options) => {
|
699
|
+
if (!shouldQueue || shouldQueue(options)) {
|
700
|
+
return new Promise((resolve, reject) => {
|
701
|
+
queue.push(new BatchEntry(resolve, reject, options));
|
702
|
+
});
|
703
|
+
} else {
|
704
|
+
return void 0;
|
705
|
+
}
|
706
|
+
};
|
707
|
+
const complete = async () => {
|
708
|
+
if (queue.length > 0) {
|
709
|
+
try {
|
710
|
+
await handleBatch(queue);
|
711
|
+
} catch (e) {
|
712
|
+
queue.forEach((entry) => entry.reject(e));
|
713
|
+
}
|
714
|
+
if (queue.some((entry) => !entry.isCompleted)) {
|
715
|
+
throw new Error("The completeAll() function failed to resolve or reject all promises in the batch!");
|
716
|
+
}
|
717
|
+
}
|
718
|
+
const processed = queue.length;
|
719
|
+
queue = [];
|
720
|
+
return processed;
|
721
|
+
};
|
722
|
+
return { enhanceOne: batchedFn, completeAll: complete, limitPolicy };
|
723
|
+
}
|
724
|
+
|
725
|
+
// src/enhancement/compose.ts
|
726
|
+
var compose = (input, ...composers) => {
|
727
|
+
const composed = {
|
728
|
+
enhanceOne: (value) => {
|
729
|
+
let result = "enhanceOne" in input ? input.enhanceOne(value) : input(value);
|
730
|
+
for (const currentComposed of composers) {
|
731
|
+
const current = isPromise(result) ? result : Promise.resolve(result);
|
732
|
+
const enhanceOne = "enhanceOne" in currentComposed ? currentComposed.enhanceOne : currentComposed;
|
733
|
+
result = current.then(
|
734
|
+
(res) => enhanceOne({
|
735
|
+
...value,
|
736
|
+
parameter: {
|
737
|
+
type: value.parameter.type,
|
738
|
+
value: res
|
739
|
+
}
|
740
|
+
})
|
741
|
+
);
|
742
|
+
}
|
743
|
+
return result;
|
744
|
+
},
|
745
|
+
completeAll: async () => {
|
746
|
+
var _a, _b;
|
747
|
+
for (const currentComposed of composers) {
|
748
|
+
if ("completeAll" in currentComposed) {
|
749
|
+
throw new Error(
|
750
|
+
"Only the first enhancer in a compose chain can use the completeAll function (batching)"
|
751
|
+
);
|
752
|
+
}
|
753
|
+
}
|
754
|
+
return (_b = "completeAll" in input ? (_a = input.completeAll) == null ? void 0 : _a.call(input) : 0) != null ? _b : 0;
|
755
|
+
}
|
756
|
+
};
|
757
|
+
return composed;
|
758
|
+
};
|
759
|
+
function isPromise(obj) {
|
760
|
+
return !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function";
|
761
|
+
}
|
762
|
+
|
763
|
+
// src/enhancement/walkComponentTree.ts
|
764
|
+
function walkComponentTree(component, visitor, initialContext) {
|
765
|
+
var _a;
|
766
|
+
const componentQueue = [
|
767
|
+
{
|
768
|
+
ancestorsAndSelf: [{ component, parentSlot: void 0, parentSlotIndex: void 0 }],
|
769
|
+
context: initialContext
|
770
|
+
}
|
771
|
+
];
|
772
|
+
const childContexts = /* @__PURE__ */ new Map();
|
773
|
+
do {
|
774
|
+
const currentQueueEntry = componentQueue.pop();
|
775
|
+
if (!currentQueueEntry)
|
776
|
+
continue;
|
777
|
+
const currentComponent = currentQueueEntry.ancestorsAndSelf[0];
|
778
|
+
let visitDescendants = true;
|
779
|
+
let descendantContext = (_a = childContexts.get(currentComponent.component)) != null ? _a : currentQueueEntry.context;
|
780
|
+
visitor(
|
781
|
+
currentComponent.component,
|
782
|
+
currentQueueEntry.ancestorsAndSelf,
|
783
|
+
{
|
784
|
+
replaceComponent: (replacementComponent) => {
|
785
|
+
Object.assign(currentComponent.component, replacementComponent);
|
786
|
+
const propertiesToCheck = [
|
787
|
+
"parameters",
|
788
|
+
"variant",
|
789
|
+
"slots",
|
790
|
+
"data",
|
791
|
+
"_pattern",
|
792
|
+
"_patternError"
|
793
|
+
];
|
794
|
+
propertiesToCheck.forEach((property) => {
|
795
|
+
if (!replacementComponent[property]) {
|
796
|
+
delete currentComponent.component[property];
|
797
|
+
}
|
798
|
+
});
|
799
|
+
},
|
800
|
+
removeComponent: () => {
|
801
|
+
const { parentSlot, parentSlotIndex } = currentQueueEntry.ancestorsAndSelf[0];
|
802
|
+
const parentComponent = currentQueueEntry.ancestorsAndSelf[1];
|
803
|
+
if (parentSlot && typeof parentSlotIndex !== "undefined") {
|
804
|
+
parentComponent.component.slots[parentSlot].splice(parentSlotIndex, 1);
|
805
|
+
} else {
|
806
|
+
throw new Error("Unable to delete composition.");
|
807
|
+
}
|
808
|
+
},
|
809
|
+
insertAfter: (components) => {
|
810
|
+
const componentsToInsert = Array.isArray(components) ? components : [components];
|
811
|
+
const { parentSlot, parentSlotIndex } = currentQueueEntry.ancestorsAndSelf[0];
|
812
|
+
const parentComponent = currentQueueEntry.ancestorsAndSelf[1];
|
813
|
+
if (parentSlot && typeof parentSlotIndex !== "undefined") {
|
814
|
+
parentComponent.component.slots[parentSlot].splice(
|
815
|
+
parentSlotIndex + 1,
|
816
|
+
0,
|
817
|
+
...componentsToInsert
|
818
|
+
);
|
819
|
+
componentQueue.unshift(
|
820
|
+
...componentsToInsert.map((enqueueingComponent) => ({
|
821
|
+
ancestorsAndSelf: [
|
822
|
+
{
|
823
|
+
component: enqueueingComponent,
|
824
|
+
parentSlot,
|
825
|
+
get parentSlotIndex() {
|
826
|
+
return parentComponent.component.slots[parentSlot].findIndex(
|
827
|
+
(x) => x === enqueueingComponent
|
828
|
+
);
|
829
|
+
}
|
830
|
+
},
|
831
|
+
...currentQueueEntry.ancestorsAndSelf
|
832
|
+
],
|
833
|
+
context: descendantContext
|
834
|
+
}))
|
835
|
+
);
|
836
|
+
} else {
|
837
|
+
throw new Error("Unable to insert after a component not in a slot.");
|
838
|
+
}
|
839
|
+
},
|
840
|
+
stopProcessingDescendants() {
|
841
|
+
visitDescendants = false;
|
842
|
+
},
|
843
|
+
setDescendantsContext(context) {
|
844
|
+
descendantContext = context;
|
845
|
+
},
|
846
|
+
setChildContext(child, context) {
|
847
|
+
childContexts.set(child, context);
|
848
|
+
}
|
849
|
+
},
|
850
|
+
descendantContext
|
851
|
+
);
|
852
|
+
const slots = currentComponent.component.slots;
|
853
|
+
if (visitDescendants && slots) {
|
854
|
+
const slotKeys = Object.keys(slots);
|
855
|
+
for (let slotIndex = slotKeys.length - 1; slotIndex >= 0; slotIndex--) {
|
856
|
+
const slotKey = slotKeys[slotIndex];
|
857
|
+
const components = slots[slotKey];
|
858
|
+
for (let componentIndex = components.length - 1; componentIndex >= 0; componentIndex--) {
|
859
|
+
const enqueueingComponent = components[componentIndex];
|
860
|
+
componentQueue.push({
|
861
|
+
ancestorsAndSelf: [
|
862
|
+
{
|
863
|
+
component: enqueueingComponent,
|
864
|
+
parentSlot: slotKey,
|
865
|
+
get parentSlotIndex() {
|
866
|
+
return currentComponent.component.slots[slotKey].findIndex(
|
867
|
+
(x) => x === enqueueingComponent
|
868
|
+
);
|
869
|
+
}
|
870
|
+
},
|
871
|
+
...currentQueueEntry.ancestorsAndSelf
|
872
|
+
],
|
873
|
+
context: descendantContext
|
874
|
+
});
|
875
|
+
}
|
876
|
+
}
|
877
|
+
}
|
878
|
+
} while (componentQueue.length > 0);
|
879
|
+
}
|
880
|
+
function getComponentPath(ancestorsAndSelf) {
|
881
|
+
const path = [];
|
882
|
+
for (let i = ancestorsAndSelf.length - 1; i >= 0; i--) {
|
883
|
+
const { parentSlot, parentSlotIndex } = ancestorsAndSelf[i];
|
884
|
+
if (parentSlot && parentSlotIndex !== void 0) {
|
885
|
+
path.push(`${parentSlot}[${parentSlotIndex}]`);
|
886
|
+
}
|
887
|
+
}
|
888
|
+
return `.${path.join(".")}`;
|
889
|
+
}
|
890
|
+
function getComponentJsonPointer(ancestorsAndSelf, { withSlots = false } = {}) {
|
891
|
+
const path = [];
|
892
|
+
for (let i = ancestorsAndSelf.length - 1; i >= 0; i--) {
|
893
|
+
const { parentSlot, parentSlotIndex } = ancestorsAndSelf[i];
|
894
|
+
if (parentSlot && parentSlotIndex !== void 0) {
|
895
|
+
path.push(`${parentSlot}/${parentSlotIndex}`);
|
896
|
+
}
|
897
|
+
}
|
898
|
+
return withSlots ? `/slots/${path.join("/slots/")}` : `/${path.join("/")}`;
|
899
|
+
}
|
900
|
+
|
901
|
+
// src/enhancement/enhance.ts
|
902
|
+
async function enhance({
|
903
|
+
composition,
|
904
|
+
enhancers,
|
905
|
+
context,
|
906
|
+
onErrors = (errors) => {
|
907
|
+
throw new Error(
|
908
|
+
errors.map(
|
909
|
+
(error) => `${error.message}
|
910
|
+
${typeof error.error === "object" && "stack" in error.error ? error.error.stack : error.error}`
|
911
|
+
).join("\n\n")
|
912
|
+
);
|
913
|
+
}
|
914
|
+
}) {
|
915
|
+
const promises = [];
|
916
|
+
const usedComponentEnhancers = /* @__PURE__ */ new Set();
|
917
|
+
const usedParameterEnhancers = /* @__PURE__ */ new Set();
|
918
|
+
walkComponentTree(composition, (currentComponent, componentContext) => {
|
919
|
+
var _a;
|
920
|
+
Object.entries((_a = currentComponent.parameters) != null ? _a : {}).forEach(([paramName, paramValue]) => {
|
921
|
+
const enhancer = enhancers.resolveParameterEnhancer(currentComponent, paramName, paramValue);
|
922
|
+
if (enhancer) {
|
923
|
+
usedParameterEnhancers.add(enhancer);
|
924
|
+
promises.push(
|
925
|
+
enhanceParameter(currentComponent, componentContext, paramName, paramValue, enhancer, context)
|
926
|
+
);
|
927
|
+
}
|
928
|
+
});
|
929
|
+
const componentEnhancers = enhancers.resolveComponentEnhancers(currentComponent);
|
930
|
+
promises.push(enhanceComponent(currentComponent, componentContext, componentEnhancers, context));
|
931
|
+
usedComponentEnhancers.add(componentEnhancers);
|
932
|
+
});
|
933
|
+
promises.push(
|
934
|
+
...Array.from(usedComponentEnhancers).flatMap(
|
935
|
+
(enhancerSet) => Array.from(enhancerSet).map(async ([, enhancer]) => {
|
936
|
+
var _a;
|
937
|
+
try {
|
938
|
+
if (enhancer.completeAll) {
|
939
|
+
const limitPolicy = (_a = enhancer.limitPolicy) != null ? _a : nullLimitPolicy;
|
940
|
+
await limitPolicy(() => enhancer.completeAll());
|
941
|
+
}
|
942
|
+
} catch (error) {
|
943
|
+
return {
|
944
|
+
error,
|
945
|
+
message: "Batch component enhancer failed. Individual failed components should receive their own rejections."
|
946
|
+
};
|
947
|
+
}
|
948
|
+
})
|
949
|
+
)
|
950
|
+
);
|
951
|
+
promises.push(
|
952
|
+
...Array.from(usedParameterEnhancers).map(async (enhancer) => {
|
953
|
+
var _a;
|
954
|
+
try {
|
955
|
+
if (enhancer.completeAll) {
|
956
|
+
const limitPolicy = (_a = enhancer.limitPolicy) != null ? _a : nullLimitPolicy;
|
957
|
+
await limitPolicy(() => enhancer.completeAll());
|
958
|
+
}
|
959
|
+
} catch (error) {
|
960
|
+
return {
|
961
|
+
error,
|
962
|
+
message: "Batch parameter enhancer failed. Individual failed parameters should receive their own rejections."
|
963
|
+
};
|
964
|
+
}
|
965
|
+
})
|
966
|
+
);
|
967
|
+
const issues = (await Promise.all(promises)).flatMap((issue) => Array.isArray(issue) ? issue : [issue]).filter((issue) => issue);
|
968
|
+
if (issues.length) {
|
969
|
+
onErrors(issues);
|
970
|
+
}
|
971
|
+
}
|
972
|
+
async function enhanceComponent(component, componentContext, enhancers, context) {
|
973
|
+
if (enhancers.size) {
|
974
|
+
component.data = {};
|
975
|
+
}
|
976
|
+
return await Promise.all(
|
977
|
+
Array.from(enhancers).map(async ([enhancerName, enhancer]) => {
|
978
|
+
var _a;
|
979
|
+
try {
|
980
|
+
const limitPolicy = enhancer.completeAll ? nullLimitPolicy : (_a = enhancer.limitPolicy) != null ? _a : nullLimitPolicy;
|
981
|
+
const result = await limitPolicy(async () => enhancer.enhanceOne({ component, context }));
|
982
|
+
if (result !== void 0 && result !== null) {
|
983
|
+
component.data[enhancerName] = result;
|
984
|
+
}
|
985
|
+
} catch (error) {
|
986
|
+
const message = `Component ${getComponentPath(componentContext)} (type: ${component.type}): data.${enhancerName} enhancer threw exception. Data key will not be present.`;
|
987
|
+
delete component.data[enhancerName];
|
988
|
+
return { message, error };
|
989
|
+
}
|
990
|
+
})
|
991
|
+
);
|
992
|
+
}
|
993
|
+
async function enhanceParameter(component, componentContext, parameterName, parameter, enhancer, context) {
|
994
|
+
var _a;
|
995
|
+
try {
|
996
|
+
const limitPolicy = enhancer.completeAll ? nullLimitPolicy : (_a = enhancer.limitPolicy) != null ? _a : nullLimitPolicy;
|
997
|
+
const enhancedValue = await limitPolicy(
|
998
|
+
async () => enhancer.enhanceOne({ parameter, parameterName, component, context })
|
999
|
+
);
|
1000
|
+
if (enhancedValue === null) {
|
1001
|
+
delete component.parameters[parameterName];
|
1002
|
+
} else if (typeof enhancedValue === "undefined") {
|
1003
|
+
component.parameters[parameterName] = { ...parameter, value: parameter.value };
|
1004
|
+
} else {
|
1005
|
+
component.parameters[parameterName] = { ...parameter, value: enhancedValue };
|
1006
|
+
}
|
1007
|
+
} catch (error) {
|
1008
|
+
const message = `Component ${getComponentPath(componentContext)} (type: ${component.type}): enhancing parameter ${parameterName} (type: ${parameter.type}) threw exception. Parameter will be removed.`;
|
1009
|
+
delete component.parameters[parameterName];
|
1010
|
+
return { message, error };
|
1011
|
+
}
|
1012
|
+
}
|
1013
|
+
|
1014
|
+
// src/enhancement/EnhancerBuilder.ts
|
1015
|
+
var ChildEnhancerBuilder = class {
|
1016
|
+
constructor() {
|
1017
|
+
this._paramMatches = Array();
|
1018
|
+
this._dataMatches = /* @__PURE__ */ new Map();
|
1019
|
+
}
|
1020
|
+
parameter(enhancer) {
|
1021
|
+
this._paramMatches.push({ enhancer: this._resolveParameterEnhancer(enhancer) });
|
1022
|
+
return this;
|
1023
|
+
}
|
1024
|
+
parameterName(name, enhancer) {
|
1025
|
+
const names = Array.isArray(name) ? name : [name];
|
1026
|
+
names.forEach(
|
1027
|
+
(name2) => this._paramMatches.push({ name: name2, enhancer: this._resolveParameterEnhancer(enhancer) })
|
1028
|
+
);
|
1029
|
+
return this;
|
1030
|
+
}
|
1031
|
+
parameterType(type, enhancer) {
|
1032
|
+
const types = Array.isArray(type) ? type : [type];
|
1033
|
+
types.forEach(
|
1034
|
+
(type2) => this._paramMatches.push({ type: type2, enhancer: this._resolveParameterEnhancer(enhancer) })
|
1035
|
+
);
|
1036
|
+
return this;
|
1037
|
+
}
|
1038
|
+
data(name, enhancer) {
|
1039
|
+
if (this._dataMatches.has(name)) {
|
1040
|
+
throw new Error(`${name} enhancer data key has been used more than once. This will cause data loss.`);
|
1041
|
+
}
|
1042
|
+
this._dataMatches.set(name, typeof enhancer === "function" ? { enhanceOne: enhancer } : enhancer);
|
1043
|
+
return this;
|
1044
|
+
}
|
1045
|
+
resolveParameterEnhancer(parameterName, parameter) {
|
1046
|
+
var _a;
|
1047
|
+
return (_a = this._paramMatches.find(
|
1048
|
+
(m) => m.name && m.name === parameterName || m.type && m.type === parameter.type || !m.type && !m.name
|
1049
|
+
)) == null ? void 0 : _a.enhancer;
|
1050
|
+
}
|
1051
|
+
resolveComponentEnhancers() {
|
1052
|
+
return this._dataMatches;
|
1053
|
+
}
|
1054
|
+
_resolveParameterEnhancer(enhancer) {
|
1055
|
+
if (typeof enhancer === "function") {
|
1056
|
+
return { enhanceOne: enhancer };
|
1057
|
+
} else {
|
1058
|
+
return enhancer;
|
1059
|
+
}
|
1060
|
+
}
|
1061
|
+
};
|
1062
|
+
var EnhancerBuilder = class {
|
1063
|
+
constructor() {
|
1064
|
+
this._componentIndex = {};
|
1065
|
+
this._rootBuilder = new ChildEnhancerBuilder();
|
1066
|
+
}
|
1067
|
+
parameter(enhancer) {
|
1068
|
+
this._rootBuilder.parameter(enhancer);
|
1069
|
+
return this;
|
1070
|
+
}
|
1071
|
+
parameterName(name, enhancer) {
|
1072
|
+
this._rootBuilder.parameterName(name, enhancer);
|
1073
|
+
return this;
|
1074
|
+
}
|
1075
|
+
parameterType(type, enhancer) {
|
1076
|
+
this._rootBuilder.parameterType(type, enhancer);
|
1077
|
+
return this;
|
1078
|
+
}
|
1079
|
+
data(name, enhancer) {
|
1080
|
+
this._rootBuilder.data(name, enhancer);
|
1081
|
+
return this;
|
1082
|
+
}
|
1083
|
+
component(name, builder) {
|
1084
|
+
const names = Array.isArray(name) ? name : [name];
|
1085
|
+
names.forEach((name2) => {
|
1086
|
+
this._componentIndex[name2] = this._componentIndex[name2] || new ChildEnhancerBuilder();
|
1087
|
+
builder(this._componentIndex[name2]);
|
1088
|
+
});
|
1089
|
+
return this;
|
1090
|
+
}
|
1091
|
+
resolveParameterEnhancer(component, parameterName, parameter) {
|
1092
|
+
const eb = this._componentIndex[component.type];
|
1093
|
+
if (eb) {
|
1094
|
+
const targetedResolver = eb.resolveParameterEnhancer(parameterName, parameter);
|
1095
|
+
if (targetedResolver) {
|
1096
|
+
return targetedResolver;
|
1097
|
+
}
|
1098
|
+
}
|
1099
|
+
return this._rootBuilder.resolveParameterEnhancer(parameterName, parameter);
|
1100
|
+
}
|
1101
|
+
resolveComponentEnhancers(component) {
|
1102
|
+
let componentEnhancers = this._rootBuilder.resolveComponentEnhancers();
|
1103
|
+
const eb = this._componentIndex[component.type];
|
1104
|
+
if (eb) {
|
1105
|
+
componentEnhancers = new Map(componentEnhancers);
|
1106
|
+
for (const [key, value] of eb.resolveComponentEnhancers()) {
|
1107
|
+
componentEnhancers.set(key, value);
|
1108
|
+
}
|
1109
|
+
}
|
1110
|
+
return componentEnhancers;
|
1111
|
+
}
|
1112
|
+
};
|
1113
|
+
|
1114
|
+
// src/utils/constants.ts
|
1115
|
+
var CANVAS_PERSONALIZE_TYPE = "$personalization";
|
1116
|
+
var CANVAS_TEST_TYPE = "$test";
|
1117
|
+
var CANVAS_LOCALIZATION_TYPE = "$localization";
|
1118
|
+
var CANVAS_INTENT_TAG_PARAM = "intentTag";
|
1119
|
+
var CANVAS_LOCALE_TAG_PARAM = "locale";
|
1120
|
+
var CANVAS_PERSONALIZE_SLOT = "pz";
|
1121
|
+
var CANVAS_TEST_SLOT = "test";
|
1122
|
+
var CANVAS_LOCALIZATION_SLOT = "localized";
|
1123
|
+
var CANVAS_DRAFT_STATE = 0;
|
1124
|
+
var CANVAS_PUBLISHED_STATE = 64;
|
1125
|
+
var CANVAS_PERSONALIZATION_PARAM = "$pzCrit";
|
1126
|
+
var CANVAS_TEST_VARIANT_PARAM = "$tstVrnt";
|
1127
|
+
var CANVAS_ENRICHMENT_TAG_PARAM = "$enr";
|
1128
|
+
var IN_CONTEXT_EDITOR_QUERY_STRING_PARAM = "is_incontext_editing_mode";
|
1129
|
+
var IN_CONTEXT_EDITOR_COMPONENT_START_ROLE = "uniform-component-start";
|
1130
|
+
var PLACEHOLDER_ID = "placeholder";
|
1131
|
+
var EDGE_MIN_CACHE_TTL = 15;
|
1132
|
+
var EDGE_MAX_CACHE_TTL = 600;
|
1133
|
+
var EDGE_DEFAULT_CACHE_TTL = 30;
|
1134
|
+
var EDGE_CACHE_DISABLED = -1;
|
1135
|
+
var EDGE_MIN_L2_CACHE_TTL_IN_HOURS = 1;
|
1136
|
+
var EDGE_MAX_L2_CACHE_TTL_IN_HOURS = 4 * 7 * 24;
|
1137
|
+
var EDGE_DEFAULT_L2_CACHE_TTL_IN_HOURS = 24;
|
1138
|
+
|
1139
|
+
// src/enhancement/localize.ts
|
1140
|
+
function extractLocales({ component }) {
|
1141
|
+
var _a;
|
1142
|
+
const variations = {};
|
1143
|
+
const slot = (_a = component.slots) == null ? void 0 : _a[CANVAS_LOCALIZATION_SLOT];
|
1144
|
+
slot == null ? void 0 : slot.forEach((slotComponent) => {
|
1145
|
+
var _a2;
|
1146
|
+
const localeParameter = (_a2 = slotComponent.parameters) == null ? void 0 : _a2[CANVAS_LOCALE_TAG_PARAM];
|
1147
|
+
if ((localeParameter == null ? void 0 : localeParameter.value) && typeof localeParameter.value === "string") {
|
1148
|
+
variations[localeParameter.value] = variations[localeParameter.value] || [];
|
1149
|
+
variations[localeParameter.value].push(slotComponent);
|
1150
|
+
}
|
1151
|
+
});
|
1152
|
+
return variations;
|
1153
|
+
}
|
1154
|
+
function localize({
|
1155
|
+
composition,
|
1156
|
+
locale
|
1157
|
+
}) {
|
1158
|
+
walkComponentTree(composition, (currentComponent, _componentContext, actions) => {
|
1159
|
+
if (currentComponent.type === CANVAS_LOCALIZATION_TYPE) {
|
1160
|
+
const locales = extractLocales({ component: currentComponent });
|
1161
|
+
const resolvedLocale = typeof locale === "string" ? locale : locale({ component: currentComponent, locales });
|
1162
|
+
let replaceComponent;
|
1163
|
+
if (resolvedLocale) {
|
1164
|
+
replaceComponent = locales[resolvedLocale];
|
1165
|
+
}
|
1166
|
+
if (replaceComponent == null ? void 0 : replaceComponent.length) {
|
1167
|
+
const [first, ...rest] = replaceComponent;
|
1168
|
+
actions.replaceComponent(first);
|
1169
|
+
if (rest.length) {
|
1170
|
+
actions.insertAfter(rest);
|
1171
|
+
}
|
1172
|
+
} else {
|
1173
|
+
actions.removeComponent();
|
1174
|
+
}
|
1175
|
+
}
|
1176
|
+
});
|
1177
|
+
}
|
1178
|
+
|
1179
|
+
// src/enhancement/UniqueBatchEntries.ts
|
1180
|
+
var UniqueBatchEntries = class {
|
1181
|
+
constructor(entries, uniqueKeySelector) {
|
1182
|
+
this.groups = entries.reduce((acc, task) => {
|
1183
|
+
var _a;
|
1184
|
+
const key = uniqueKeySelector(task.args);
|
1185
|
+
acc[key] = (_a = acc[key]) != null ? _a : [];
|
1186
|
+
acc[key].push(task);
|
1187
|
+
return acc;
|
1188
|
+
}, {});
|
1189
|
+
}
|
1190
|
+
resolveKey(key, result) {
|
1191
|
+
this.groups[key].forEach((task) => task.resolve(result));
|
1192
|
+
}
|
1193
|
+
resolveRemaining(value) {
|
1194
|
+
Object.keys(this.groups).forEach((key) => {
|
1195
|
+
this.groups[key].forEach((task) => {
|
1196
|
+
if (!task.isCompleted) {
|
1197
|
+
task.resolve(value);
|
1198
|
+
}
|
1199
|
+
});
|
1200
|
+
});
|
1201
|
+
}
|
1202
|
+
};
|
1203
|
+
|
1204
|
+
// src/utils/hash.ts
|
1205
|
+
var generateHash = ({
|
1206
|
+
composition,
|
1207
|
+
secret
|
1208
|
+
}) => {
|
1209
|
+
if (!secret) {
|
1210
|
+
return void 0;
|
1211
|
+
}
|
1212
|
+
const str = `${JSON.stringify(composition)}-${secret}`;
|
1213
|
+
let hash = 0;
|
1214
|
+
for (let i = 0; i < str.length; i++) {
|
1215
|
+
const chr = str.charCodeAt(i);
|
1216
|
+
hash = (hash << 5) - hash + chr;
|
1217
|
+
hash |= 0;
|
1218
|
+
}
|
1219
|
+
return hash;
|
1220
|
+
};
|
1221
|
+
|
1222
|
+
// src/messaging/channel.ts
|
1223
|
+
var isSelectComponentMessage = (message) => {
|
1224
|
+
return message.type === "select-component" && message.id !== void 0;
|
1225
|
+
};
|
1226
|
+
var isReadyMessage = (message) => {
|
1227
|
+
return message.type === "ready";
|
1228
|
+
};
|
1229
|
+
var isUpdateCompositionMessage = (message) => {
|
1230
|
+
return message.type === "update-composition";
|
1231
|
+
};
|
1232
|
+
var isAddComponentMessage = (message) => {
|
1233
|
+
return message.type === "add-component";
|
1234
|
+
};
|
1235
|
+
var isMovingComponentMessage = (message) => {
|
1236
|
+
return message.type === "move-component";
|
1237
|
+
};
|
1238
|
+
var isDismissPlaceholderMessage = (message) => {
|
1239
|
+
return message.type === "dismiss-placeholder";
|
1240
|
+
};
|
1241
|
+
var createCanvasChannel = ({
|
1242
|
+
listenTo,
|
1243
|
+
broadcastTo
|
1244
|
+
}) => {
|
1245
|
+
let handlerCounter = 0;
|
1246
|
+
const handlers = {};
|
1247
|
+
const broadcastToItems = [...broadcastTo];
|
1248
|
+
const postMessage = (message) => {
|
1249
|
+
broadcastToItems.forEach((item) => item.postMessage(JSON.stringify(message), "*"));
|
1250
|
+
};
|
1251
|
+
const selectComponent = (id) => {
|
1252
|
+
const message = {
|
1253
|
+
type: "select-component",
|
1254
|
+
id
|
1255
|
+
};
|
1256
|
+
postMessage(message);
|
1257
|
+
};
|
1258
|
+
const ready = () => {
|
1259
|
+
const message = {
|
1260
|
+
type: "ready"
|
1261
|
+
};
|
1262
|
+
postMessage(message);
|
1263
|
+
};
|
1264
|
+
const on = (types, handler) => {
|
1265
|
+
const handlerId = ++handlerCounter;
|
1266
|
+
handlers[handlerId] = {
|
1267
|
+
types: Array.isArray(types) ? types : [types],
|
1268
|
+
handler
|
1269
|
+
};
|
1270
|
+
return () => {
|
1271
|
+
delete handlers[handlerId];
|
1272
|
+
};
|
1273
|
+
};
|
1274
|
+
const updateComposition = (composition, secret) => {
|
1275
|
+
const message = {
|
1276
|
+
type: "update-composition",
|
1277
|
+
composition,
|
1278
|
+
hash: generateHash({
|
1279
|
+
composition,
|
1280
|
+
secret
|
1281
|
+
})
|
1282
|
+
};
|
1283
|
+
postMessage(message);
|
1284
|
+
};
|
1285
|
+
const addComponent = (options) => {
|
1286
|
+
const message = {
|
1287
|
+
...options,
|
1288
|
+
type: "add-component"
|
1289
|
+
};
|
1290
|
+
postMessage(message);
|
1291
|
+
};
|
1292
|
+
const moveComponent = (options) => {
|
1293
|
+
const message = {
|
1294
|
+
...options,
|
1295
|
+
type: "move-component"
|
1296
|
+
};
|
1297
|
+
postMessage(message);
|
1298
|
+
};
|
1299
|
+
const dismissPlaceholder = (options) => {
|
1300
|
+
const message = {
|
1301
|
+
...options,
|
1302
|
+
type: "dismiss-placeholder"
|
1303
|
+
};
|
1304
|
+
postMessage(message);
|
1305
|
+
};
|
1306
|
+
const messageEventListener = (event) => {
|
1307
|
+
if (typeof event.data !== "string" || event.source === window) {
|
1308
|
+
return;
|
1309
|
+
}
|
1310
|
+
let message = null;
|
1311
|
+
try {
|
1312
|
+
const parsedMessage = JSON.parse(event.data);
|
1313
|
+
if (Object.hasOwn(parsedMessage, "type")) {
|
1314
|
+
message = parsedMessage;
|
1315
|
+
}
|
1316
|
+
} catch (e) {
|
1317
|
+
}
|
1318
|
+
if (!message) {
|
1319
|
+
return;
|
1320
|
+
}
|
1321
|
+
for (const handlerId in handlers) {
|
1322
|
+
const handler = handlers[handlerId];
|
1323
|
+
if (handler.types.includes(message.type)) {
|
1324
|
+
handler.handler(message, event);
|
1325
|
+
}
|
1326
|
+
}
|
1327
|
+
};
|
1328
|
+
listenTo.forEach((item) => item.addEventListener("message", messageEventListener));
|
1329
|
+
const destroy = () => {
|
1330
|
+
listenTo.forEach((item) => item.removeEventListener("message", messageEventListener));
|
1331
|
+
};
|
1332
|
+
return {
|
1333
|
+
ready,
|
1334
|
+
destroy,
|
1335
|
+
selectComponent,
|
1336
|
+
updateComposition,
|
1337
|
+
on,
|
1338
|
+
addComponent,
|
1339
|
+
moveComponent,
|
1340
|
+
dismissPlaceholder
|
1341
|
+
};
|
1342
|
+
};
|
1343
|
+
|
1344
|
+
// src/preview/createEventBus.ts
|
1345
|
+
var PUSHER_SRC = "https://js.pusher.com/7.0.3/pusher.min.js";
|
1346
|
+
async function loadPusher() {
|
1347
|
+
if (typeof document === "undefined" || typeof window === "undefined") {
|
1348
|
+
return;
|
1349
|
+
}
|
1350
|
+
if (window.Pusher) {
|
1351
|
+
return window.Pusher;
|
1352
|
+
}
|
1353
|
+
return new Promise((resolve, reject) => {
|
1354
|
+
const timeout = setTimeout(() => {
|
1355
|
+
if (window.Pusher) {
|
1356
|
+
resolve(window.Pusher);
|
1357
|
+
}
|
1358
|
+
reject(
|
1359
|
+
`Unable to load pusher.js; Uniform Canvas live preview disabled. Consider adding <script src="${PUSHER_SRC}"><\/script> manually.`
|
1360
|
+
);
|
1361
|
+
}, 5e3);
|
1362
|
+
const pusher = document.createElement("script");
|
1363
|
+
pusher.src = PUSHER_SRC;
|
1364
|
+
pusher.addEventListener("load", () => {
|
1365
|
+
clearTimeout(timeout);
|
1366
|
+
resolve(window.Pusher);
|
1367
|
+
});
|
1368
|
+
document.head.appendChild(pusher);
|
1369
|
+
});
|
1370
|
+
}
|
1371
|
+
async function createEventBus() {
|
1372
|
+
const WindowPusher = await loadPusher();
|
1373
|
+
if (!WindowPusher) {
|
1374
|
+
return;
|
1375
|
+
}
|
1376
|
+
let bus = window.__UNIFORM_EVENT_BUS__;
|
1377
|
+
if (!bus) {
|
1378
|
+
const pusher = new WindowPusher("7b5f5abd160fea549ffe", {
|
1379
|
+
cluster: "mt1"
|
1380
|
+
});
|
1381
|
+
pusher.connect();
|
1382
|
+
console.log("[canvas] \u{1F525} preview connected");
|
1383
|
+
bus = window.__UNIFORM_EVENT_BUS__ = {
|
1384
|
+
subscribe: (channel) => {
|
1385
|
+
const channelObj = pusher.subscribe(channel);
|
1386
|
+
return {
|
1387
|
+
unsubscribe: () => pusher.unsubscribe(channel),
|
1388
|
+
addEventHandler: (eventName, handler) => {
|
1389
|
+
channelObj.bind(eventName, handler);
|
1390
|
+
return () => channelObj.unbind(eventName, handler);
|
1391
|
+
}
|
1392
|
+
};
|
1393
|
+
}
|
1394
|
+
};
|
1395
|
+
}
|
1396
|
+
return bus;
|
1397
|
+
}
|
1398
|
+
|
1399
|
+
// src/preview/getChannelName.ts
|
1400
|
+
function getChannelName(projectId, compositionId, state) {
|
1401
|
+
return `${projectId}.${compositionId}@${state}`;
|
1402
|
+
}
|
1403
|
+
|
1404
|
+
// src/preview/subscribeToComposition.ts
|
1405
|
+
function subscribeToComposition({
|
1406
|
+
projectId,
|
1407
|
+
compositionId,
|
1408
|
+
compositionState = 0,
|
1409
|
+
eventBus: { subscribe },
|
1410
|
+
callback,
|
1411
|
+
event = "updated"
|
1412
|
+
}) {
|
1413
|
+
const channelName = getChannelName(projectId, compositionId, compositionState);
|
1414
|
+
const channel = subscribe(channelName);
|
1415
|
+
const off = channel.addEventHandler(event, callback);
|
1416
|
+
return () => {
|
1417
|
+
off();
|
1418
|
+
channel.unsubscribe();
|
1419
|
+
};
|
1420
|
+
}
|
1421
|
+
|
1422
|
+
// src/utils/isSystemComponentDefinition.ts
|
1423
|
+
var isSystemComponentDefinition = (componentType) => {
|
1424
|
+
return componentType.startsWith("$");
|
1425
|
+
};
|
1426
|
+
|
1427
|
+
// src/utils/mapSlotToPersonalizedVariations.ts
|
1428
|
+
function mapSlotToPersonalizedVariations(slot) {
|
1429
|
+
if (!slot)
|
1430
|
+
return [];
|
1431
|
+
return slot.map((v, i) => {
|
1432
|
+
var _a, _b;
|
1433
|
+
const contextTag = (_b = (_a = v.parameters) == null ? void 0 : _a[CANVAS_PERSONALIZATION_PARAM]) == null ? void 0 : _b.value;
|
1434
|
+
const id = (contextTag == null ? void 0 : contextTag.name) || `pz-${i}-${v.type}`;
|
1435
|
+
return {
|
1436
|
+
...v,
|
1437
|
+
id,
|
1438
|
+
pz: contextTag
|
1439
|
+
};
|
1440
|
+
});
|
1441
|
+
}
|
1442
|
+
|
1443
|
+
// src/utils/mapSlotToTestVariations.ts
|
1444
|
+
function mapSlotToTestVariations(slot) {
|
1445
|
+
if (!slot)
|
1446
|
+
return [];
|
1447
|
+
return slot.map((v, i) => {
|
1448
|
+
var _a, _b, _c;
|
1449
|
+
const contextTag = (_b = (_a = v.parameters) == null ? void 0 : _a[CANVAS_TEST_VARIANT_PARAM]) == null ? void 0 : _b.value;
|
1450
|
+
const id = (_c = contextTag == null ? void 0 : contextTag.id) != null ? _c : "testId" in v ? v.testId : `ab-${i}-${v.type}`;
|
1451
|
+
return {
|
1452
|
+
...v,
|
1453
|
+
id
|
1454
|
+
};
|
1455
|
+
});
|
1456
|
+
}
|
1457
|
+
|
1458
|
+
// src/index.ts
|
1459
|
+
var import_api4 = require("@uniformdev/context/api");
|
1460
|
+
var CanvasClientError = import_api4.ApiClientError;
|
1461
|
+
// Annotate the CommonJS export names for ESM import in node:
|
1462
|
+
0 && (module.exports = {
|
1463
|
+
ApiClientError,
|
1464
|
+
BatchEntry,
|
1465
|
+
CANVAS_DRAFT_STATE,
|
1466
|
+
CANVAS_ENRICHMENT_TAG_PARAM,
|
1467
|
+
CANVAS_INTENT_TAG_PARAM,
|
1468
|
+
CANVAS_LOCALE_TAG_PARAM,
|
1469
|
+
CANVAS_LOCALIZATION_SLOT,
|
1470
|
+
CANVAS_LOCALIZATION_TYPE,
|
1471
|
+
CANVAS_PERSONALIZATION_PARAM,
|
1472
|
+
CANVAS_PERSONALIZE_SLOT,
|
1473
|
+
CANVAS_PERSONALIZE_TYPE,
|
1474
|
+
CANVAS_PUBLISHED_STATE,
|
1475
|
+
CANVAS_TEST_SLOT,
|
1476
|
+
CANVAS_TEST_TYPE,
|
1477
|
+
CANVAS_TEST_VARIANT_PARAM,
|
1478
|
+
CanvasClient,
|
1479
|
+
CanvasClientError,
|
1480
|
+
ChildEnhancerBuilder,
|
1481
|
+
DataSourceClient,
|
1482
|
+
DataTypeClient,
|
1483
|
+
EDGE_CACHE_DISABLED,
|
1484
|
+
EDGE_DEFAULT_CACHE_TTL,
|
1485
|
+
EDGE_DEFAULT_L2_CACHE_TTL_IN_HOURS,
|
1486
|
+
EDGE_MAX_CACHE_TTL,
|
1487
|
+
EDGE_MAX_L2_CACHE_TTL_IN_HOURS,
|
1488
|
+
EDGE_MIN_CACHE_TTL,
|
1489
|
+
EDGE_MIN_L2_CACHE_TTL_IN_HOURS,
|
1490
|
+
EnhancerBuilder,
|
1491
|
+
IN_CONTEXT_EDITOR_COMPONENT_START_ROLE,
|
1492
|
+
IN_CONTEXT_EDITOR_QUERY_STRING_PARAM,
|
1493
|
+
PLACEHOLDER_ID,
|
1494
|
+
UncachedCanvasClient,
|
1495
|
+
UniqueBatchEntries,
|
1496
|
+
compose,
|
1497
|
+
createBatchEnhancer,
|
1498
|
+
createCanvasChannel,
|
1499
|
+
createEventBus,
|
1500
|
+
createLimitPolicy,
|
1501
|
+
enhance,
|
1502
|
+
extractLocales,
|
1503
|
+
generateHash,
|
1504
|
+
getChannelName,
|
1505
|
+
getComponentJsonPointer,
|
1506
|
+
getComponentPath,
|
1507
|
+
isAddComponentMessage,
|
1508
|
+
isDismissPlaceholderMessage,
|
1509
|
+
isMovingComponentMessage,
|
1510
|
+
isReadyMessage,
|
1511
|
+
isSelectComponentMessage,
|
1512
|
+
isSystemComponentDefinition,
|
1513
|
+
isUpdateCompositionMessage,
|
1514
|
+
localize,
|
1515
|
+
mapSlotToPersonalizedVariations,
|
1516
|
+
mapSlotToTestVariations,
|
1517
|
+
nullLimitPolicy,
|
1518
|
+
subscribeToComposition,
|
1519
|
+
walkComponentTree
|
1520
|
+
});
|