@uniformdev/canvas 13.0.1-alpha.73 → 14.0.1-alpha.101
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/LICENSE.txt +1 -1
- package/README.md +5 -5
- package/dist/{chunk-FS5XXLSV.mjs → chunk-34U4J6TI.mjs} +2 -2
- package/dist/cli/cli.d.ts +1 -1
- package/dist/cli/cli.js +4 -4
- package/dist/cli/cli.mjs +3 -3
- package/dist/{createEventBus-39df132f.d.ts → createEventBus-ca90547e.d.ts} +107 -105
- package/dist/index.d.ts +2 -2
- package/dist/index.esm.js +2 -2
- package/dist/index.js +3 -3
- package/dist/index.mjs +2 -2
- package/package.json +15 -15
package/LICENSE.txt
CHANGED
@@ -1,2 +1,2 @@
|
|
1
|
-
© 2021 Uniform Systems, Inc. All Rights Reserved.
|
1
|
+
© 2021 Uniform Systems, Inc. All Rights Reserved.
|
2
2
|
See details of Uniform Systems, Inc. Master Subscription Agreement here: https://uniform.dev/eula
|
package/README.md
CHANGED
@@ -1,5 +1,5 @@
|
|
1
|
-
Uniform Canvas JavaScript SDK
|
2
|
-
|
3
|
-
Contains the Canvas API client, Canvas CLI, and core typings.
|
4
|
-
|
5
|
-
part of the [Uniform Platform](https://uniform.app). See our [documentation](https://docs.uniform.app) for more details.
|
1
|
+
Uniform Canvas JavaScript SDK
|
2
|
+
|
3
|
+
Contains the Canvas API client, Canvas CLI, and core typings.
|
4
|
+
|
5
|
+
part of the [Uniform Platform](https://uniform.app). See our [documentation](https://docs.uniform.app) for more details.
|
@@ -1,2 +1,2 @@
|
|
1
|
-
import
|
2
|
-
${s}${i?" "+i:""} (${t} ${o})`);this.errorMessage=e;this.fetchMethod=t;this.fetchUri=o;this.statusCode=s;this.statusText=i;Object.setPrototypeOf(this,
|
1
|
+
import h from"p-throttle";import f from"p-retry";function u({throttle:p={interval:1e3,limit:10},retry:e={retries:1,factor:1.66}}){let t=p?h(p):null;return function(s){let i=async()=>await s();if(t&&(i=t(i)),e){let n=i;i=()=>f(n,e)}return i()}}var P=async p=>await p();var c=class extends Error{constructor(e,t,o,s,i){super(`${e}
|
2
|
+
${s}${i?" "+i:""} (${t} ${o})`);this.errorMessage=e;this.fetchMethod=t;this.fetchUri=o;this.statusCode=s;this.statusText=i;Object.setPrototypeOf(this,c.prototype)}},A=class{constructor(e){var o,s,i,n,r;if(!e.apiKey&&!e.bearerToken)throw new Error("You must provide an API key or a bearer token");let t=e.fetch;if(!t)if(typeof window!="undefined")t=window.fetch.bind(window);else if(typeof fetch!="undefined")t=fetch;else throw new Error("You must provide or polyfill a fetch implementation when not in a browser");this.options={...e,fetch:t,apiHost:(o=e.apiHost)!=null?o:"https://uniform.app",apiKey:(s=e.apiKey)!=null?s:null,projectId:(i=e.projectId)!=null?i:null,bearerToken:(n=e.bearerToken)!=null?n:null,limitPolicy:(r=e.limitPolicy)!=null?r:u({})}}async getCompositionList(e){let{projectId:t}=this.options,o=this.createUrl("/api/v1/canvas",{...e,projectId:t});return await this.apiClient(o)}async getCompositionBySlug(e){let{projectId:t}=this.options,o=this.createUrl("/api/v1/canvas",{...e,projectId:t});return await this.apiClient(o)}async getCompositionById(e){let{projectId:t}=this.options,o=this.createUrl("/api/v1/canvas",{...e,projectId:t});return await this.apiClient(o)}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");await this.apiClient(t,{method:"DELETE",body:JSON.stringify({...e,projectId:this.options.projectId}),expectNoContent:!0})}async getComponentDefinitions(e){let{projectId:t}=this.options,o=this.createUrl("/api/v1/canvas-definitions",{...e,projectId:t});return await this.apiClient(o)}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})}async apiClient(e,t){return this.options.limitPolicy(async()=>{var i;let o=this.options.apiKey?{"x-api-key":this.options.apiKey}:{Authorization:`Bearer ${this.options.bearerToken}`},s=await this.options.fetch(e.toString(),{...t,headers:{...t==null?void 0:t.headers,...o}});if(!s.ok){let n="";try{let r=await s.text();try{let a=JSON.parse(r);a.errorMessage?n=Array.isArray(a.errorMessage)?a.errorMessage.join(", "):a.errorMessage:n=r}catch(a){n=r}}catch(r){n="General error"}throw new c(n,(i=t==null?void 0:t.method)!=null?i:"GET",e.toString(),s.status)}return(t==null?void 0:t.expectNoContent)?null:await s.json()})}createUrl(e,t){let o=new URL(`${this.options.apiHost}${e}`);return Object.entries(t!=null?t:{}).forEach(([s,i])=>{var n;typeof i!==void 0&&i!==null&&o.searchParams.append(s,(n=i==null?void 0:i.toString())!=null?n:"")}),o}};var L="$personalization",S="$test",w="$localization",N="intentTag",E="locale",j="pz",x="test",b="localized",U=0,_=64;export{u as a,P as b,c,A as d,L as e,S as f,w as g,N as h,E as i,j,x as k,b as l,U as m,_ as n};
|
package/dist/cli/cli.d.ts
CHANGED
@@ -1,5 +1,5 @@
|
|
1
1
|
import { UniformCLIPlugin } from '@uniformdev/cli';
|
2
|
-
import { o as ComponentDefinition, d as CompositionAPIResponse } from '../createEventBus-
|
2
|
+
import { o as ComponentDefinition, d as CompositionAPIResponse } from '../createEventBus-ca90547e';
|
3
3
|
import 'pusher-js';
|
4
4
|
|
5
5
|
declare type CanvasPackage = {
|
package/dist/cli/cli.js
CHANGED
@@ -1,4 +1,4 @@
|
|
1
|
-
var
|
2
|
-
${
|
3
|
-
${C==null?void 0:C.message}`)),C}}}return{objects:
|
4
|
-
`+r.map(c=>c.added?F.default.green(c.value):c.removed?F.default.red(c.value):c.value).join("")),console.log(`${i?F.default.gray("[WHATIF]"):""}${a} ${n}${s}`)}}var ye=m(require("fs"));function w(e,t){if(!t&&!ye.default.existsSync(e))return{};let o=E(e);if(typeof o!="object")throw new Error(`Package ${e} does not appear valid.`);return o}function G(e,t){O(t,void 0,e)}async function _({objects:e,selectIdentifier:t,selectDisplayName:o=t,onSyncComplete:n}){let i=e.reduce((s,c)=>{let p=t(c);if(s[p])throw new Error(`Identifier ${p} was not unique.`);return s[p]={id:p,object:c,providerId:p,displayName:o(c)},s},{});async function*r(){for(let s of Object.values(i))yield s}function a(){return Object.entries(i).sort((s,c)=>s[0].localeCompare(c[0])).map(s=>s[1].object)}return{objects:r(),deleteObject:async s=>{delete i[s]},writeObject:async s=>{let c=t(s.object);i[c]=s},extractCurrent:a,onSyncComplete:n?s=>n(s,a()):void 0}}var he={command:"pull <directory>",describe:"Pulls all component definitions to local files in a directory",builder:e=>f(u(I(e.positional("directory",{describe:"Directory to save the component definitions to. If a filename ending in yaml or json is used, a package file will be created instead of files in the directory.",type:"string"}).option("format",{alias:["f"],describe:"Output format",default:"yaml",choices:["yaml","json"],type:"string"}).option("what-if",{alias:["w"],describe:"What-if mode reports what would be done but changes no files",default:!1,type:"boolean"}).option("mode",{alias:["m"],describe:'What kind of changes can be made. "create" = create new files, update nothing. "createOrUpdate" = create new files, update existing, delete nothing. "mirror" = create, update, and delete to mirror state',choices:["create","createOrUpdate","mirror"],default:"mirror",type:"string"})))),handler:async({apiHost:e,apiKey:t,directory:o,format:n,mode:i,whatIf:r,project:a,diff:s})=>{var g;let c=new d({apiKey:t,apiHost:e,fetch:Ce.default,projectId:a,limitPolicy:T}),p=Q({client:c}),y;if(D(o)){let h=w(o,!1);y=await _({objects:(g=h.components)!=null?g:[],selectIdentifier:R,selectDisplayName:L,onSyncComplete:async(S,b)=>{h.components=b,G(o,h)}})}else y=await M({directory:o,selectIdentifier:R,selectDisplayName:L,format:n});await x({source:p,target:y,mode:i,whatIf:r,log:k({diffMode:s})})}};var Ae=m(require("isomorphic-unfetch"));var be={command:"push <directory>",describe:"Pushes all component definitions from files in a directory to Uniform Optimize",builder:e=>f(u(I(e.positional("directory",{describe:"Directory to read the component definitions from. If a filename is used, a package will be read instead.",type:"string"}).option("what-if",{alias:["w"],describe:"What-if mode reports what would be done but changes nothing",default:!1,type:"boolean"}).option("mode",{alias:["m"],describe:'What kind of changes can be made. "create" = create new, update nothing. "createOrUpdate" = create new, update existing, delete nothing. "mirror" = create, update, and delete',choices:["create","createOrUpdate","mirror"],default:"mirror",type:"string"})))),handler:async({apiHost:e,apiKey:t,directory:o,mode:n,whatIf:i,project:r,diff:a})=>{var C;let s=new d({apiKey:t,apiHost:e,fetch:Ae.default,projectId:r,limitPolicy:T}),c;if(D(o)){let g=w(o,!0);c=await _({objects:(C=g.components)!=null?C:[],selectIdentifier:R,selectDisplayName:L})}else c=await M({directory:o,selectIdentifier:R,selectDisplayName:L});let y=Q({client:s});await x({source:c,target:y,mode:n,whatIf:i,log:k({diffMode:a})})}};var Se=m(require("isomorphic-unfetch")),Oe={command:"remove <id>",aliases:["delete","rm"],describe:"Delete a component definition",builder:e=>f(u(e.positional("id",{demandOption:!0,describe:"Component definition public ID to delete"}))),handler:async({apiHost:e,apiKey:t,id:o,project:n})=>{await new d({apiKey:t,apiHost:e,fetch:Se.default,projectId:n}).removeComponentDefinition({componentId:o})}};var Pe=m(require("isomorphic-unfetch")),we={command:"update <filename>",aliases:["put"],describe:"Insert or update a component definition",builder:e=>f(u(e.positional("filename",{demandOption:!0,describe:"Component definition file to put"}))),handler:async({apiHost:e,apiKey:t,filename:o,project:n})=>{let i=new d({apiKey:t,apiHost:e,fetch:Pe.default,projectId:n}),r=E(o);await i.updateComponentDefinition({componentDefinition:r})}};var Ie={command:"component <command>",aliases:["def"],describe:"Commands for Canvas component definitions",builder:e=>e.command(he).command(be).command(le).command(Oe).command(fe).command(we).demandCommand(),handler:()=>je.default.help()};var Fe=m(require("yargs"));var De=m(require("isomorphic-unfetch")),Ee={command:"get <id>",describe:"Fetch a composition",builder:e=>j(f(u(P(e.positional("id",{demandOption:!0,describe:"Composition public ID to fetch"}).option({resolvePatterns:{type:"boolean",default:!1,describe:"Resolve pattern references in the composition"}}))))),handler:async({apiHost:e,apiKey:t,id:o,format:n,filename:i,state:r,project:a,resolvePatterns:s})=>{let c=new d({apiKey:t,apiHost:e,fetch:De.default,projectId:a}),p=Y(await c.getCompositionById({compositionId:o,state:v(r),skipPatternResolution:!s}));O(p,n,i)}};var ve=m(require("isomorphic-unfetch")),Te={command:"list",describe:"List compositions",aliases:["ls"],builder:e=>j(f(u(P(e.options({offset:{describe:"Number of rows to skip before fetching",type:"number",default:0},limit:{describe:"Number of rows to fetch",type:"number",default:20},resolvePatterns:{type:"boolean",default:!1,describe:"Resolve pattern references in the composition"}}))))),handler:async({apiHost:e,apiKey:t,limit:o,offset:n,format:i,filename:r,project:a,state:s,resolvePatterns:c})=>{let y=await new d({apiKey:t,apiHost:e,fetch:ve.default,projectId:a}).getCompositionList({limit:o,offset:n,state:v(s),skipPatternResolution:!c});O(y.compositions,i,r)}};var xe=m(require("isomorphic-unfetch"));var N=e=>e.composition._id,U=e=>{var t,o;return`${(o=(t=e.composition._name)!=null?t:e.composition._slug)!=null?o:e.composition._id} (pid: ${e.composition._id})`};function X({client:e,state:t}){let o=v(t);async function*n(){let i=q(async(r,a)=>(await e.getCompositionList({limit:a,offset:r,state:o,skipPatternResolution:!0})).compositions,{pageSize:100});for await(let r of i)yield{id:N(r),displayName:U(r),providerId:r.composition._id,object:Y(r)}}return{objects:n(),deleteObject:async i=>{await e.removeComposition({compositionId:i})},writeObject:async i=>{await e.updateComposition({...i.object,state:o})}}}var Me={command:"pull <directory>",describe:"Pulls all compositions to local files in a directory",builder:e=>f(u(P(I(e.positional("directory",{describe:"Directory to save the component definitions to. If a filename ending in yaml or json is used, a package file will be created instead of files in the directory.",type:"string"}).option("format",{alias:["f"],describe:"Output format",default:"yaml",choices:["yaml","json"],type:"string"}).option("what-if",{alias:["w"],describe:"What-if mode reports what would be done but changes no files",default:!1,type:"boolean"}).option("mode",{alias:["m"],describe:'What kind of changes can be made. "create" = create new files, update nothing. "createOrUpdate" = create new files, update existing, delete nothing. "mirror" = create, update, and delete to mirror state',choices:["create","createOrUpdate","mirror"],default:"mirror",type:"string"}))))),handler:async({apiHost:e,apiKey:t,directory:o,format:n,mode:i,whatIf:r,state:a,project:s,diff:c})=>{var h;let p=new d({apiKey:t,apiHost:e,fetch:xe.default,projectId:s,limitPolicy:T}),y=X({client:p,state:a}),C=D(o),g;if(C){let S=w(o,!1);g=await _({objects:(h=S==null?void 0:S.compositions)!=null?h:[],selectIdentifier:N,selectDisplayName:U,onSyncComplete:async(b,A)=>{S.compositions=A,G(o,S)}})}else g=await M({directory:o,selectIdentifier:N,selectDisplayName:U,format:n});await x({source:y,target:g,mode:i,whatIf:r,log:k({diffMode:c})})}};var Re=m(require("isomorphic-unfetch"));var Le={command:"push <directory>",describe:"Pushes all compositions from files in a directory to Uniform Optimize",builder:e=>f(u(P(I(e.positional("directory",{describe:"Directory to read the component definitions from. If a filename is used, a package will be read instead.",type:"string"}).option("what-if",{alias:["w"],describe:"What-if mode reports what would be done but changes nothing",default:!1,type:"boolean"}).option("mode",{alias:["m"],describe:'What kind of changes can be made. "create" = create new, update nothing. "createOrUpdate" = create new, update existing, delete nothing. "mirror" = create, update, and delete',choices:["create","createOrUpdate","mirror"],default:"mirror",type:"string"}))))),handler:async({apiHost:e,apiKey:t,directory:o,mode:n,whatIf:i,state:r,project:a,diff:s})=>{var g;let c=new d({apiKey:t,apiHost:e,fetch:Re.default,projectId:a,limitPolicy:T}),p;if(D(o)){let h=w(o,!0);p=await _({objects:(g=h.compositions)!=null?g:[],selectIdentifier:N,selectDisplayName:U})}else p=await M({directory:o,selectIdentifier:N,selectDisplayName:U});let C=X({client:c,state:r});await x({source:p,target:C,mode:n,whatIf:i,log:k({diffMode:s})})}};var ke=m(require("isomorphic-unfetch")),_e={command:"remove <id>",aliases:["delete","rm"],describe:"Delete a composition",builder:e=>f(u(e.positional("id",{demandOption:!0,describe:"Composition public ID to delete"}))),handler:async({apiHost:e,apiKey:t,id:o,project:n})=>{await new d({apiKey:t,apiHost:e,fetch:ke.default,projectId:n}).removeComposition({compositionId:o})}};var Ne=m(require("isomorphic-unfetch")),Ue={command:"update <filename>",aliases:["put"],describe:"Insert or update a composition",builder:e=>f(u(P(e.positional("filename",{demandOption:!0,describe:"Composition file to put"})))),handler:async({apiHost:e,apiKey:t,filename:o,project:n,state:i})=>{let r=new d({apiKey:t,apiHost:e,fetch:Ne.default,projectId:n}),a=E(o);await r.updateComposition({...a,state:v(i)})}};var $e={command:"composition <command>",describe:"Commands for Canvas compositions",aliases:["comp"],builder:e=>e.command(Me).command(Le).command(Ee).command(_e).command(Te).command(Ue).demandCommand(),handler:()=>Fe.default.help()};var qe={commands:[{command:"canvas <command>",aliases:["cv","pm","presentation"],describe:"Uniform Canvas commands",builder:e=>e.command($e).command(Ie).demandCommand(),handler:()=>{Ve.default.showHelp()}}]};0&&(module.exports={readCanvasPackage,uniformCLI,writeCanvasPackage});
|
1
|
+
var Ge=Object.create;var H=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Ke=Object.getPrototypeOf,ze=Object.prototype.hasOwnProperty;var oe=e=>H(e,"__esModule",{value:!0});var Ye=(e,t)=>{for(var o in t)H(e,o,{get:t[o],enumerable:!0})},ie=(e,t,o,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of He(t))!ze.call(e,n)&&(o||n!=="default")&&H(e,n,{get:()=>t[n],enumerable:!(i=Je(t,n))||i.enumerable});return e},y=(e,t)=>ie(oe(H(e!=null?Ge(Ke(e)):{},"default",!t&&e&&e.__esModule?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e),qe=(e=>(t,o)=>e&&e.get(t)||(o=ie(oe({}),t,1),e&&e.set(t,o),o))(typeof WeakMap!="undefined"?new WeakMap:0);var Ze={};Ye(Ze,{readCanvasPackage:()=>j,uniformCLI:()=>Be,writeCanvasPackage:()=>G});var We=y(require("yargs"));var Ie=y(require("yargs"));var ne=y(require("p-throttle")),re=y(require("p-retry"));function se({throttle:e={interval:1e3,limit:10},retry:t={retries:1,factor:1.66}}){let o=e?(0,ne.default)(e):null;return function(n){let r=async()=>await n();if(o&&(r=o(r)),t){let a=r;r=()=>(0,re.default)(a,t)}return r()}}var K=class extends Error{constructor(t,o,i,n,r){super(`${t}
|
2
|
+
${n}${r?" "+r:""} (${o} ${i})`);this.errorMessage=t;this.fetchMethod=o;this.fetchUri=i;this.statusCode=n;this.statusText=r;Object.setPrototypeOf(this,K.prototype)}},d=class{constructor(t){var i,n,r,a,s;if(!t.apiKey&&!t.bearerToken)throw new Error("You must provide an API key or a bearer token");let o=t.fetch;if(!o)if(typeof window!="undefined")o=window.fetch.bind(window);else if(typeof fetch!="undefined")o=fetch;else throw new Error("You must provide or polyfill a fetch implementation when not in a browser");this.options={...t,fetch:o,apiHost:(i=t.apiHost)!=null?i:"https://uniform.app",apiKey:(n=t.apiKey)!=null?n:null,projectId:(r=t.projectId)!=null?r:null,bearerToken:(a=t.bearerToken)!=null?a:null,limitPolicy:(s=t.limitPolicy)!=null?s:se({})}}async getCompositionList(t){let{projectId:o}=this.options,i=this.createUrl("/api/v1/canvas",{...t,projectId:o});return await this.apiClient(i)}async getCompositionBySlug(t){let{projectId:o}=this.options,i=this.createUrl("/api/v1/canvas",{...t,projectId:o});return await this.apiClient(i)}async getCompositionById(t){let{projectId:o}=this.options,i=this.createUrl("/api/v1/canvas",{...t,projectId:o});return await this.apiClient(i)}async updateComposition(t){let o=this.createUrl("/api/v1/canvas");await this.apiClient(o,{method:"PUT",body:JSON.stringify({...t,projectId:this.options.projectId}),expectNoContent:!0})}async removeComposition(t){let o=this.createUrl("/api/v1/canvas");await this.apiClient(o,{method:"DELETE",body:JSON.stringify({...t,projectId:this.options.projectId}),expectNoContent:!0})}async getComponentDefinitions(t){let{projectId:o}=this.options,i=this.createUrl("/api/v1/canvas-definitions",{...t,projectId:o});return await this.apiClient(i)}async updateComponentDefinition(t){let o=this.createUrl("/api/v1/canvas-definitions");await this.apiClient(o,{method:"PUT",body:JSON.stringify({...t,projectId:this.options.projectId}),expectNoContent:!0})}async removeComponentDefinition(t){let o=this.createUrl("/api/v1/canvas-definitions");await this.apiClient(o,{method:"DELETE",body:JSON.stringify({...t,projectId:this.options.projectId}),expectNoContent:!0})}async apiClient(t,o){return this.options.limitPolicy(async()=>{var r;let i=this.options.apiKey?{"x-api-key":this.options.apiKey}:{Authorization:`Bearer ${this.options.bearerToken}`},n=await this.options.fetch(t.toString(),{...o,headers:{...o==null?void 0:o.headers,...i}});if(!n.ok){let a="";try{let s=await n.text();try{let p=JSON.parse(s);p.errorMessage?a=Array.isArray(p.errorMessage)?p.errorMessage.join(", "):p.errorMessage:a=s}catch(p){a=s}}catch(s){a="General error"}throw new K(a,(r=o==null?void 0:o.method)!=null?r:"GET",t.toString(),n.status)}return(o==null?void 0:o.expectNoContent)?null:await n.json()})}createUrl(t,o){let i=new URL(`${this.options.apiHost}${t}`);return Object.entries(o!=null?o:{}).forEach(([n,r])=>{var a;typeof r!==void 0&&r!==null&&i.searchParams.append(n,(a=r==null?void 0:r.toString())!=null?a:"")}),i}};var z=require("js-yaml"),pe=require("fs"),te=require("path"),ce=require("fs");var ae=0,ee=64;var me=y(require("p-limit"));function l(e){var t,o;return e.option("apiKey",{describe:"Uniform API key. Defaults to CANVAS_CLI_API_KEY or UNIFORM_API_KEY env. Supports dotenv.",default:(o=(t=process.env.CANVAS_CLI_API_KEY)!=null?t:process.env.UPM_CLI_API_KEY)!=null?o:process.env.UNIFORM_API_KEY,demandOption:!0,type:"string"}).option("apiHost",{describe:"Uniform host. Defaults to UNIFORM_CLI_BASE_URL env or https://uniform.app. Supports dotenv.",default:process.env.UNIFORM_CLI_BASE_URL||"https://uniform.app",demandOption:!0,type:"string"})}function f(e){var t,o;return e.option("project",{describe:"Uniform project ID. Defaults to CANVAS_CLI_PROJECT_ID or UNIFORM_PROJECT_ID env. Supports dotenv.",default:(o=(t=process.env.CANVAS_CLI_PROJECT_ID)!=null?t:process.env.UPM_CLI_PROJECT_ID)!=null?o:process.env.UNIFORM_PROJECT_ID,demandOption:!0,type:"string",alias:["p"]})}function S(e){return e.option("format",{alias:["f"],describe:"Output format",default:"yaml",choices:["yaml","json"],type:"string"}).option("filename",{alias:["o"],describe:"Output filename. If not specified, write to stdout.",type:"string"})}function I(e){return e.option("diff",{describe:"Whether to show diffs in stdout. off = no diffs; update = on for updates; on = updates, creates, deletes",default:"off",type:"string",choices:["off","update","on"],alias:["d"]})}function D(e){let t=(0,te.extname)(e);return t===".yaml"||t===".yml"||t===".json"}function P(e,t,o){let i;if(o&&!t){let n=(0,te.extname)(o);n===".yaml"||n===".yml"?t="yaml":n===".json"&&(t="json")}else if(!t)throw new Error("Format must be specified when no filename is passed");switch(t){case"json":i=JSON.stringify(e,null,2);break;case"yaml":i=(0,z.dump)(e);break;default:throw new Error(`Unsupported format: ${t}`)}o?(0,pe.writeFileSync)(o,i,"utf8"):console.log(i)}function v(e){let t=(0,ce.readFileSync)(e,"utf8");return(0,z.load)(t,{filename:e,json:!0})}function Y(e){let t={...e};return delete t.projectId,delete t.state,t}function w(e){return e.option("state",{type:"string",describe:"Composition state to fetch.",choices:["preview","published"],default:"preview"})}async function*q(e,t){let o=t.pageSize||100,i=0,n=[];do{n=await e(i,o);for(let r of n)yield r;i+=o}while(n.length===o)}function E(e){let t=Number(e);if(!isNaN(t))return t;if(!e)return ee;if(typeof e!="string")throw new Error('state must be "published", "preview", or a number');return e==="preview"?ae:ee}var T=(0,me.default)(8);var de=y(require("isomorphic-unfetch")),le={command:"get <id>",describe:"Fetch a component definition",builder:e=>S(l(f(e.positional("id",{demandOption:!0,describe:"Component definition public ID to fetch"})))),handler:async({apiHost:e,apiKey:t,id:o,format:i,project:n,filename:r})=>{let s=await new d({apiKey:t,apiHost:e,fetch:de.default,projectId:n}).getComponentDefinitions({componentId:o,limit:1});s.componentDefinitions.length===0?(console.error("Component did not exist"),process.exit(1)):P(s.componentDefinitions[0],i,r)}};var fe=y(require("isomorphic-unfetch")),ue={command:"list",describe:"List component definitions",aliases:["ls"],builder:e=>S(l(f(e.options({offset:{describe:"Number of rows to skip before fetching",type:"number",default:0},limit:{describe:"Number of rows to fetch",type:"number",default:20}})))),handler:async({apiHost:e,apiKey:t,limit:o,offset:i,format:n,filename:r,project:a})=>{let p=await new d({apiKey:t,apiHost:e,fetch:fe.default,projectId:a}).getComponentDefinitions({limit:o,offset:i});P(p.componentDefinitions,n,r)}};var Ae=y(require("isomorphic-unfetch"));var V=require("diff"),ge=y(require("lodash.isequalwith"));async function x({source:e,target:t,compareContents:o=(s,p)=>(0,ge.default)(s.object,p.object,(c,g,C)=>C==="created"||C==="updated"?!0:void 0),mode:i,allowEmptySource:n=!1,whatIf:r=!1,log:a=()=>{}}){var g,C;let s=new Map;for await(let u of t.objects)s.set(u.id,u);let p=[],c=!1;for await(let u of e.objects){c=!0;let A=u.id,O=s.get(A);if(O){if(!o(u,O)&&(i==="createOrUpdate"||i==="mirror")){let b=async(h,J)=>{var $;r||await t.writeObject(h),a({action:"update",id:A,providerId:h.providerId,displayName:($=h.displayName)!=null?$:h.providerId,whatIf:r,diff:(0,V.diffJson)(J.object,h.object)})};p.push(b(u,O))}s.delete(A)}else{let b=async(h,J)=>{var $;r||await t.writeObject(h),a({action:"create",id:J,providerId:J,displayName:($=h.displayName)!=null?$:h.providerId,whatIf:r,diff:(0,V.diffLines)("",JSON.stringify(h.object,null,2))})};p.push(b(u,A))}}if(await Promise.all(p),i==="mirror"){if(!c&&!n)throw new Error("Source is empty and mode is mirror. This would cause deletion of everything in the target, and most likely indicates an error in source definition.");let u=[];s.forEach(async A=>{let O=async b=>{var h;r||await t.deleteObject(b.providerId),a({action:"delete",id:b.id,providerId:b.providerId,displayName:(h=b.displayName)!=null?h:b.providerId,whatIf:r,diff:(0,V.diffLines)(JSON.stringify(b.object,null,2),"")})};u.push(O(A))}),await Promise.all(u)}await Promise.all([(g=e.onSyncComplete)==null?void 0:g.call(e,!1),(C=t.onSyncComplete)==null?void 0:C.call(t,!0)])}var Ce=y(require("chalk")),B=require("fs"),Z=require("fs/promises"),W=require("path");async function M({directory:e,format:t="yaml",selectIdentifier:o,selectDisplayName:i=o}){(0,B.existsSync)(e)||(0,B.mkdirSync)(e,{recursive:!0});let r=await(0,Z.readdir)(e,"utf-8"),a=new Set(r.filter(c=>{let g=(0,W.extname)(c);return g===".json"||g===".yaml"||g===".yml"})),s=c=>(0,W.join)(e,`${c}.${t}`);async function*p(){for(let c of a){let g=(0,W.join)(e,c);try{let C=await v(g);yield{id:o(C),displayName:i(C),providerId:g,object:C}}catch(C){throw console.error(Ce.default.red(`Failed to read ${g}, data is likely invalid.
|
3
|
+
${C==null?void 0:C.message}`)),C}}}return{objects:p(),deleteObject:async c=>{await(0,Z.unlink)(c)},writeObject:async c=>{P(c.object,t,s(c.id))}}}var R=e=>e.id,L=e=>`${e.name} (pid: ${e.id})`;function Q({client:e}){async function*t(){let o=q(async(i,n)=>(await e.getComponentDefinitions({limit:n,offset:i})).componentDefinitions,{pageSize:100});for await(let i of o)yield{id:R(i),displayName:L(i),providerId:i.id,object:i}}return{objects:t(),deleteObject:async o=>{await e.removeComponentDefinition({componentId:o})},writeObject:async o=>{await e.updateComponentDefinition({componentDefinition:o.object})}}}var F=y(require("chalk"));function k({diffMode:e}){return function({action:o,displayName:i,whatIf:n,diff:r}){let a="";switch(o){case"create":a=F.default.green("[A]");break;case"update":a=F.default.white("[U]");break;case"delete":a=F.default.yellow("[D]");break}let s="";(e==="on"||e==="update"&&o==="update")&&(s=`
|
4
|
+
`+r.map(p=>p.added?F.default.green(p.value):p.removed?F.default.red(p.value):p.value).join("")),console.log(`${n?F.default.gray("[WHATIF]"):""}${a} ${i}${s}`)}}var ye=y(require("fs"));function j(e,t){if(!t&&!ye.default.existsSync(e))return{};let o=v(e);if(typeof o!="object")throw new Error(`Package ${e} does not appear valid.`);return o}function G(e,t){P(t,void 0,e)}async function N({objects:e,selectIdentifier:t,selectDisplayName:o=t,onSyncComplete:i}){let n=e.reduce((s,p)=>{let c=t(p);if(s[c])throw new Error(`Identifier ${c} was not unique.`);return s[c]={id:c,object:p,providerId:c,displayName:o(p)},s},{});async function*r(){for(let s of Object.values(n))yield s}function a(){return Object.entries(n).sort((s,p)=>s[0].localeCompare(p[0])).map(s=>s[1].object)}return{objects:r(),deleteObject:async s=>{delete n[s]},writeObject:async s=>{let p=t(s.object);n[p]=s},extractCurrent:a,onSyncComplete:i?s=>i(s,a()):void 0}}var he={command:"pull <directory>",describe:"Pulls all component definitions to local files in a directory",builder:e=>l(f(I(e.positional("directory",{describe:"Directory to save the component definitions to. If a filename ending in yaml or json is used, a package file will be created instead of files in the directory.",type:"string"}).option("format",{alias:["f"],describe:"Output format",default:"yaml",choices:["yaml","json"],type:"string"}).option("what-if",{alias:["w"],describe:"What-if mode reports what would be done but changes no files",default:!1,type:"boolean"}).option("mode",{alias:["m"],describe:'What kind of changes can be made. "create" = create new files, update nothing. "createOrUpdate" = create new files, update existing, delete nothing. "mirror" = create, update, and delete to mirror state',choices:["create","createOrUpdate","mirror"],default:"mirror",type:"string"})))),handler:async({apiHost:e,apiKey:t,directory:o,format:i,mode:n,whatIf:r,project:a,diff:s})=>{var u;let p=new d({apiKey:t,apiHost:e,fetch:Ae.default,projectId:a,limitPolicy:T}),c=Q({client:p}),g;if(D(o)){let A=j(o,!1);g=await N({objects:(u=A.components)!=null?u:[],selectIdentifier:R,selectDisplayName:L,onSyncComplete:async(O,b)=>{A.components=b,G(o,A)}})}else g=await M({directory:o,selectIdentifier:R,selectDisplayName:L,format:i});await x({source:c,target:g,mode:n,whatIf:r,log:k({diffMode:s})})}};var be=y(require("isomorphic-unfetch"));var Oe={command:"push <directory>",describe:"Pushes all component definitions from files in a directory to Uniform Optimize",builder:e=>l(f(I(e.positional("directory",{describe:"Directory to read the component definitions from. If a filename is used, a package will be read instead.",type:"string"}).option("what-if",{alias:["w"],describe:"What-if mode reports what would be done but changes nothing",default:!1,type:"boolean"}).option("mode",{alias:["m"],describe:'What kind of changes can be made. "create" = create new, update nothing. "createOrUpdate" = create new, update existing, delete nothing. "mirror" = create, update, and delete',choices:["create","createOrUpdate","mirror"],default:"mirror",type:"string"})))),handler:async({apiHost:e,apiKey:t,directory:o,mode:i,whatIf:n,project:r,diff:a})=>{var C;let s=new d({apiKey:t,apiHost:e,fetch:be.default,projectId:r,limitPolicy:T}),p;if(D(o)){let u=j(o,!0);p=await N({objects:(C=u.components)!=null?C:[],selectIdentifier:R,selectDisplayName:L})}else p=await M({directory:o,selectIdentifier:R,selectDisplayName:L});let g=Q({client:s});await x({source:p,target:g,mode:i,whatIf:n,log:k({diffMode:a})})}};var Pe=y(require("isomorphic-unfetch")),we={command:"remove <id>",aliases:["delete","rm"],describe:"Delete a component definition",builder:e=>l(f(e.positional("id",{demandOption:!0,describe:"Component definition public ID to delete"}))),handler:async({apiHost:e,apiKey:t,id:o,project:i})=>{await new d({apiKey:t,apiHost:e,fetch:Pe.default,projectId:i}).removeComponentDefinition({componentId:o})}};var je=y(require("isomorphic-unfetch")),Se={command:"update <filename>",aliases:["put"],describe:"Insert or update a component definition",builder:e=>l(f(e.positional("filename",{demandOption:!0,describe:"Component definition file to put"}))),handler:async({apiHost:e,apiKey:t,filename:o,project:i})=>{let n=new d({apiKey:t,apiHost:e,fetch:je.default,projectId:i}),r=v(o);await n.updateComponentDefinition({componentDefinition:r})}};var De={command:"component <command>",aliases:["def"],describe:"Commands for Canvas component definitions",builder:e=>e.command(he).command(Oe).command(le).command(we).command(ue).command(Se).demandCommand(),handler:()=>Ie.default.help()};var $e=y(require("yargs"));var ve=y(require("isomorphic-unfetch")),Ee={command:"get <id>",describe:"Fetch a composition",builder:e=>S(l(f(w(e.positional("id",{demandOption:!0,describe:"Composition public ID to fetch"}).option({resolvePatterns:{type:"boolean",default:!1,describe:"Resolve pattern references in the composition"}}))))),handler:async({apiHost:e,apiKey:t,id:o,format:i,filename:n,state:r,project:a,resolvePatterns:s})=>{let p=new d({apiKey:t,apiHost:e,fetch:ve.default,projectId:a}),c=Y(await p.getCompositionById({compositionId:o,state:E(r),skipPatternResolution:!s}));P(c,i,n)}};var Te=y(require("isomorphic-unfetch")),xe={command:"list",describe:"List compositions",aliases:["ls"],builder:e=>S(l(f(w(e.options({offset:{describe:"Number of rows to skip before fetching",type:"number",default:0},limit:{describe:"Number of rows to fetch",type:"number",default:20},resolvePatterns:{type:"boolean",default:!1,describe:"Resolve pattern references in the composition"}}))))),handler:async({apiHost:e,apiKey:t,limit:o,offset:i,format:n,filename:r,project:a,state:s,resolvePatterns:p})=>{let g=await new d({apiKey:t,apiHost:e,fetch:Te.default,projectId:a}).getCompositionList({limit:o,offset:i,state:E(s),skipPatternResolution:!p});P(g.compositions,n,r)}};var Me=y(require("isomorphic-unfetch"));var U=e=>e.composition._id,_=e=>{var t,o;return`${(o=(t=e.composition._name)!=null?t:e.composition._slug)!=null?o:e.composition._id} (pid: ${e.composition._id})`};function X({client:e,state:t}){let o=E(t);async function*i(){let n=q(async(r,a)=>(await e.getCompositionList({limit:a,offset:r,state:o,skipPatternResolution:!0})).compositions,{pageSize:100});for await(let r of n)yield{id:U(r),displayName:_(r),providerId:r.composition._id,object:Y(r)}}return{objects:i(),deleteObject:async n=>{await e.removeComposition({compositionId:n})},writeObject:async n=>{await e.updateComposition({...n.object,state:o})}}}var Re={command:"pull <directory>",describe:"Pulls all compositions to local files in a directory",builder:e=>l(f(w(I(e.positional("directory",{describe:"Directory to save the component definitions to. If a filename ending in yaml or json is used, a package file will be created instead of files in the directory.",type:"string"}).option("format",{alias:["f"],describe:"Output format",default:"yaml",choices:["yaml","json"],type:"string"}).option("what-if",{alias:["w"],describe:"What-if mode reports what would be done but changes no files",default:!1,type:"boolean"}).option("mode",{alias:["m"],describe:'What kind of changes can be made. "create" = create new files, update nothing. "createOrUpdate" = create new files, update existing, delete nothing. "mirror" = create, update, and delete to mirror state',choices:["create","createOrUpdate","mirror"],default:"mirror",type:"string"}))))),handler:async({apiHost:e,apiKey:t,directory:o,format:i,mode:n,whatIf:r,state:a,project:s,diff:p})=>{var A;let c=new d({apiKey:t,apiHost:e,fetch:Me.default,projectId:s,limitPolicy:T}),g=X({client:c,state:a}),C=D(o),u;if(C){let O=j(o,!1);u=await N({objects:(A=O==null?void 0:O.compositions)!=null?A:[],selectIdentifier:U,selectDisplayName:_,onSyncComplete:async(b,h)=>{O.compositions=h,G(o,O)}})}else u=await M({directory:o,selectIdentifier:U,selectDisplayName:_,format:i});await x({source:g,target:u,mode:n,whatIf:r,log:k({diffMode:p})})}};var Le=y(require("isomorphic-unfetch"));var ke={command:"push <directory>",describe:"Pushes all compositions from files in a directory to Uniform Optimize",builder:e=>l(f(w(I(e.positional("directory",{describe:"Directory to read the component definitions from. If a filename is used, a package will be read instead.",type:"string"}).option("what-if",{alias:["w"],describe:"What-if mode reports what would be done but changes nothing",default:!1,type:"boolean"}).option("mode",{alias:["m"],describe:'What kind of changes can be made. "create" = create new, update nothing. "createOrUpdate" = create new, update existing, delete nothing. "mirror" = create, update, and delete',choices:["create","createOrUpdate","mirror"],default:"mirror",type:"string"}))))),handler:async({apiHost:e,apiKey:t,directory:o,mode:i,whatIf:n,state:r,project:a,diff:s})=>{var u;let p=new d({apiKey:t,apiHost:e,fetch:Le.default,projectId:a,limitPolicy:T}),c;if(D(o)){let A=j(o,!0);c=await N({objects:(u=A.compositions)!=null?u:[],selectIdentifier:U,selectDisplayName:_})}else c=await M({directory:o,selectIdentifier:U,selectDisplayName:_});let C=X({client:p,state:r});await x({source:c,target:C,mode:i,whatIf:n,log:k({diffMode:s})})}};var Ne=y(require("isomorphic-unfetch")),Ue={command:"remove <id>",aliases:["delete","rm"],describe:"Delete a composition",builder:e=>l(f(e.positional("id",{demandOption:!0,describe:"Composition public ID to delete"}))),handler:async({apiHost:e,apiKey:t,id:o,project:i})=>{await new d({apiKey:t,apiHost:e,fetch:Ne.default,projectId:i}).removeComposition({compositionId:o})}};var _e=y(require("isomorphic-unfetch")),Fe={command:"update <filename>",aliases:["put"],describe:"Insert or update a composition",builder:e=>l(f(w(e.positional("filename",{demandOption:!0,describe:"Composition file to put"})))),handler:async({apiHost:e,apiKey:t,filename:o,project:i,state:n})=>{let r=new d({apiKey:t,apiHost:e,fetch:_e.default,projectId:i}),a=v(o);await r.updateComposition({...a,state:E(n)})}};var Ve={command:"composition <command>",describe:"Commands for Canvas compositions",aliases:["comp"],builder:e=>e.command(Re).command(ke).command(Ee).command(Ue).command(xe).command(Fe).demandCommand(),handler:()=>$e.default.help()};var Be={commands:[{command:"canvas <command>",aliases:["cv","pm","presentation"],describe:"Uniform Canvas commands",builder:e=>e.command(Ve).command(De).demandCommand(),handler:()=>{We.default.showHelp()}}]};module.exports=qe(Ze);0&&(module.exports={readCanvasPackage,uniformCLI,writeCanvasPackage});
|
package/dist/cli/cli.mjs
CHANGED
@@ -1,3 +1,3 @@
|
|
1
|
-
import{d as
|
2
|
-
${
|
3
|
-
`+s.map(a=>a.added?R.green(a.value):a.removed?R.red(a.value):a.value).join("")),console.log(`${i?R.gray("[WHATIF]"):""}${c} ${n}${r}`)}}import ve from"fs";function L(e,o){if(!o&&!ve.existsSync(e))return{};let t=v(e);if(typeof t!="object")throw new Error(`Package ${e} does not appear valid.`);return t}function z(e,o){j(o,void 0,e)}async function _({objects:e,selectIdentifier:o,selectDisplayName:t=o,onSyncComplete:n}){let i=e.reduce((r,a)=>{let m=o(a);if(r[m])throw new Error(`Identifier ${m} was not unique.`);return r[m]={id:m,object:a,providerId:m,displayName:t(a)},r},{});async function*s(){for(let r of Object.values(i))yield r}function c(){return Object.entries(i).sort((r,a)=>r[0].localeCompare(a[0])).map(r=>r[1].object)}return{objects:s(),deleteObject:async r=>{delete i[r]},writeObject:async r=>{let a=o(r.object);i[a]=r},extractCurrent:c,onSyncComplete:n?r=>n(r,c()):void 0}}var ee={command:"pull <directory>",describe:"Pulls all component definitions to local files in a directory",builder:e=>f(g(D(e.positional("directory",{describe:"Directory to save the component definitions to. If a filename ending in yaml or json is used, a package file will be created instead of files in the directory.",type:"string"}).option("format",{alias:["f"],describe:"Output format",default:"yaml",choices:["yaml","json"],type:"string"}).option("what-if",{alias:["w"],describe:"What-if mode reports what would be done but changes no files",default:!1,type:"boolean"}).option("mode",{alias:["m"],describe:'What kind of changes can be made. "create" = create new files, update nothing. "createOrUpdate" = create new files, update existing, delete nothing. "mirror" = create, update, and delete to mirror state',choices:["create","createOrUpdate","mirror"],default:"mirror",type:"string"})))),handler:async({apiHost:e,apiKey:o,directory:t,format:n,mode:i,whatIf:s,project:c,diff:r})=>{var u;let a=new p({apiKey:o,apiHost:e,fetch:Ee,projectId:c,limitPolicy:I}),m=K({client:a}),y;if(P(t)){let b=L(t,!1);y=await _({objects:(u=b.components)!=null?u:[],selectIdentifier:x,selectDisplayName:k,onSyncComplete:async(S,h)=>{b.components=h,z(t,b)}})}else y=await T({directory:t,selectIdentifier:x,selectDisplayName:k,format:n});await M({source:m,target:y,mode:i,whatIf:s,log:F({diffMode:r})})}};import Ie from"isomorphic-unfetch";var oe={command:"push <directory>",describe:"Pushes all component definitions from files in a directory to Uniform Optimize",builder:e=>f(g(D(e.positional("directory",{describe:"Directory to read the component definitions from. If a filename is used, a package will be read instead.",type:"string"}).option("what-if",{alias:["w"],describe:"What-if mode reports what would be done but changes nothing",default:!1,type:"boolean"}).option("mode",{alias:["m"],describe:'What kind of changes can be made. "create" = create new, update nothing. "createOrUpdate" = create new, update existing, delete nothing. "mirror" = create, update, and delete',choices:["create","createOrUpdate","mirror"],default:"mirror",type:"string"})))),handler:async({apiHost:e,apiKey:o,directory:t,mode:n,whatIf:i,project:s,diff:c})=>{var C;let r=new p({apiKey:o,apiHost:e,fetch:Ie,projectId:s,limitPolicy:I}),a;if(P(t)){let u=L(t,!0);a=await _({objects:(C=u.components)!=null?C:[],selectIdentifier:x,selectDisplayName:k})}else a=await T({directory:t,selectIdentifier:x,selectDisplayName:k});let y=K({client:r});await M({source:a,target:y,mode:n,whatIf:i,log:F({diffMode:c})})}};import Me from"isomorphic-unfetch";var te={command:"remove <id>",aliases:["delete","rm"],describe:"Delete a component definition",builder:e=>f(g(e.positional("id",{demandOption:!0,describe:"Component definition public ID to delete"}))),handler:async({apiHost:e,apiKey:o,id:t,project:n})=>{await new p({apiKey:o,apiHost:e,fetch:Me,projectId:n}).removeComponentDefinition({componentId:t})}};import Te from"isomorphic-unfetch";var ne={command:"update <filename>",aliases:["put"],describe:"Insert or update a component definition",builder:e=>f(g(e.positional("filename",{demandOption:!0,describe:"Component definition file to put"}))),handler:async({apiHost:e,apiKey:o,filename:t,project:n})=>{let i=new p({apiKey:o,apiHost:e,fetch:Te,projectId:n}),s=v(t);await i.updateComponentDefinition({componentDefinition:s})}};var ie={command:"component <command>",aliases:["def"],describe:"Commands for Canvas component definitions",builder:e=>e.command(ee).command(oe).command(q).command(te).command(Q).command(ne).demandCommand(),handler:()=>xe.help()};import Re from"yargs";import ke from"isomorphic-unfetch";var re={command:"get <id>",describe:"Fetch a composition",builder:e=>O(f(g(w(e.positional("id",{demandOption:!0,describe:"Composition public ID to fetch"}).option({resolvePatterns:{type:"boolean",default:!1,describe:"Resolve pattern references in the composition"}}))))),handler:async({apiHost:e,apiKey:o,id:t,format:n,filename:i,state:s,project:c,resolvePatterns:r})=>{let a=new p({apiKey:o,apiHost:e,fetch:ke,projectId:c}),m=G(await a.getCompositionById({compositionId:t,state:E(s),skipPatternResolution:!r}));j(m,n,i)}};import Fe from"isomorphic-unfetch";var se={command:"list",describe:"List compositions",aliases:["ls"],builder:e=>O(f(g(w(e.options({offset:{describe:"Number of rows to skip before fetching",type:"number",default:0},limit:{describe:"Number of rows to fetch",type:"number",default:20},resolvePatterns:{type:"boolean",default:!1,describe:"Resolve pattern references in the composition"}}))))),handler:async({apiHost:e,apiKey:o,limit:t,offset:n,format:i,filename:s,project:c,state:r,resolvePatterns:a})=>{let y=await new p({apiKey:o,apiHost:e,fetch:Fe,projectId:c}).getCompositionList({limit:t,offset:n,state:E(r),skipPatternResolution:!a});j(y.compositions,i,s)}};import Le from"isomorphic-unfetch";var U=e=>e.composition._id,N=e=>{var o,t;return`${(t=(o=e.composition._name)!=null?o:e.composition._slug)!=null?t:e.composition._id} (pid: ${e.composition._id})`};function H({client:e,state:o}){let t=E(o);async function*n(){let i=J(async(s,c)=>(await e.getCompositionList({limit:c,offset:s,state:t,skipPatternResolution:!0})).compositions,{pageSize:100});for await(let s of i)yield{id:U(s),displayName:N(s),providerId:s.composition._id,object:G(s)}}return{objects:n(),deleteObject:async i=>{await e.removeComposition({compositionId:i})},writeObject:async i=>{await e.updateComposition({...i.object,state:t})}}}var ae={command:"pull <directory>",describe:"Pulls all compositions to local files in a directory",builder:e=>f(g(w(D(e.positional("directory",{describe:"Directory to save the component definitions to. If a filename ending in yaml or json is used, a package file will be created instead of files in the directory.",type:"string"}).option("format",{alias:["f"],describe:"Output format",default:"yaml",choices:["yaml","json"],type:"string"}).option("what-if",{alias:["w"],describe:"What-if mode reports what would be done but changes no files",default:!1,type:"boolean"}).option("mode",{alias:["m"],describe:'What kind of changes can be made. "create" = create new files, update nothing. "createOrUpdate" = create new files, update existing, delete nothing. "mirror" = create, update, and delete to mirror state',choices:["create","createOrUpdate","mirror"],default:"mirror",type:"string"}))))),handler:async({apiHost:e,apiKey:o,directory:t,format:n,mode:i,whatIf:s,state:c,project:r,diff:a})=>{var b;let m=new p({apiKey:o,apiHost:e,fetch:Le,projectId:r,limitPolicy:I}),y=H({client:m,state:c}),C=P(t),u;if(C){let S=L(t,!1);u=await _({objects:(b=S==null?void 0:S.compositions)!=null?b:[],selectIdentifier:U,selectDisplayName:N,onSyncComplete:async(h,A)=>{S.compositions=A,z(t,S)}})}else u=await T({directory:t,selectIdentifier:U,selectDisplayName:N,format:n});await M({source:y,target:u,mode:i,whatIf:s,log:F({diffMode:a})})}};import _e from"isomorphic-unfetch";var ce={command:"push <directory>",describe:"Pushes all compositions from files in a directory to Uniform Optimize",builder:e=>f(g(w(D(e.positional("directory",{describe:"Directory to read the component definitions from. If a filename is used, a package will be read instead.",type:"string"}).option("what-if",{alias:["w"],describe:"What-if mode reports what would be done but changes nothing",default:!1,type:"boolean"}).option("mode",{alias:["m"],describe:'What kind of changes can be made. "create" = create new, update nothing. "createOrUpdate" = create new, update existing, delete nothing. "mirror" = create, update, and delete',choices:["create","createOrUpdate","mirror"],default:"mirror",type:"string"}))))),handler:async({apiHost:e,apiKey:o,directory:t,mode:n,whatIf:i,state:s,project:c,diff:r})=>{var u;let a=new p({apiKey:o,apiHost:e,fetch:_e,projectId:c,limitPolicy:I}),m;if(P(t)){let b=L(t,!0);m=await _({objects:(u=b.compositions)!=null?u:[],selectIdentifier:U,selectDisplayName:N})}else m=await T({directory:t,selectIdentifier:U,selectDisplayName:N});let C=H({client:a,state:s});await M({source:m,target:C,mode:n,whatIf:i,log:F({diffMode:r})})}};import Ue from"isomorphic-unfetch";var me={command:"remove <id>",aliases:["delete","rm"],describe:"Delete a composition",builder:e=>f(g(e.positional("id",{demandOption:!0,describe:"Composition public ID to delete"}))),handler:async({apiHost:e,apiKey:o,id:t,project:n})=>{await new p({apiKey:o,apiHost:e,fetch:Ue,projectId:n}).removeComposition({compositionId:t})}};import Ne from"isomorphic-unfetch";var pe={command:"update <filename>",aliases:["put"],describe:"Insert or update a composition",builder:e=>f(g(w(e.positional("filename",{demandOption:!0,describe:"Composition file to put"})))),handler:async({apiHost:e,apiKey:o,filename:t,project:n,state:i})=>{let s=new p({apiKey:o,apiHost:e,fetch:Ne,projectId:n}),c=v(t);await s.updateComposition({...c,state:E(i)})}};var de={command:"composition <command>",describe:"Commands for Canvas compositions",aliases:["comp"],builder:e=>e.command(ae).command(ce).command(re).command(me).command(se).command(pe).demandCommand(),handler:()=>Re.help()};var Qn={commands:[{command:"canvas <command>",aliases:["cv","pm","presentation"],describe:"Uniform Canvas commands",builder:e=>e.command(de).command(ie).demandCommand(),handler:()=>{We.showHelp()}}]};export{L as readCanvasPackage,Qn as uniformCLI,z as writeCanvasPackage};
|
1
|
+
import{d as c,m as Y,n as V}from"../chunk-34U4J6TI.mjs";import We from"yargs";import xe from"yargs";import{dump as le,load as fe}from"js-yaml";import{writeFileSync as ge}from"fs";import{extname as B}from"path";import{readFileSync as ue}from"fs";import Ce from"p-limit";function f(e){var o,t;return e.option("apiKey",{describe:"Uniform API key. Defaults to CANVAS_CLI_API_KEY or UNIFORM_API_KEY env. Supports dotenv.",default:(t=(o=process.env.CANVAS_CLI_API_KEY)!=null?o:process.env.UPM_CLI_API_KEY)!=null?t:process.env.UNIFORM_API_KEY,demandOption:!0,type:"string"}).option("apiHost",{describe:"Uniform host. Defaults to UNIFORM_CLI_BASE_URL env or https://uniform.app. Supports dotenv.",default:process.env.UNIFORM_CLI_BASE_URL||"https://uniform.app",demandOption:!0,type:"string"})}function g(e){var o,t;return e.option("project",{describe:"Uniform project ID. Defaults to CANVAS_CLI_PROJECT_ID or UNIFORM_PROJECT_ID env. Supports dotenv.",default:(t=(o=process.env.CANVAS_CLI_PROJECT_ID)!=null?o:process.env.UPM_CLI_PROJECT_ID)!=null?t:process.env.UNIFORM_PROJECT_ID,demandOption:!0,type:"string",alias:["p"]})}function S(e){return e.option("format",{alias:["f"],describe:"Output format",default:"yaml",choices:["yaml","json"],type:"string"}).option("filename",{alias:["o"],describe:"Output filename. If not specified, write to stdout.",type:"string"})}function P(e){return e.option("diff",{describe:"Whether to show diffs in stdout. off = no diffs; update = on for updates; on = updates, creates, deletes",default:"off",type:"string",choices:["off","update","on"],alias:["d"]})}function D(e){let o=B(e);return o===".yaml"||o===".yml"||o===".json"}function w(e,o,t){let i;if(t&&!o){let n=B(t);n===".yaml"||n===".yml"?o="yaml":n===".json"&&(o="json")}else if(!o)throw new Error("Format must be specified when no filename is passed");switch(o){case"json":i=JSON.stringify(e,null,2);break;case"yaml":i=le(e);break;default:throw new Error(`Unsupported format: ${o}`)}t?ge(t,i,"utf8"):console.log(i)}function v(e){let o=ue(e,"utf8");return fe(o,{filename:e,json:!0})}function G(e){let o={...e};return delete o.projectId,delete o.state,o}function O(e){return e.option("state",{type:"string",describe:"Composition state to fetch.",choices:["preview","published"],default:"preview"})}async function*J(e,o){let t=o.pageSize||100,i=0,n=[];do{n=await e(i,t);for(let s of n)yield s;i+=t}while(n.length===t)}function I(e){let o=Number(e);if(!isNaN(o))return o;if(!e)return V;if(typeof e!="string")throw new Error('state must be "published", "preview", or a number');return e==="preview"?Y:V}var E=Ce(8);import ye from"isomorphic-unfetch";var q={command:"get <id>",describe:"Fetch a component definition",builder:e=>S(f(g(e.positional("id",{demandOption:!0,describe:"Component definition public ID to fetch"})))),handler:async({apiHost:e,apiKey:o,id:t,format:i,project:n,filename:s})=>{let r=await new c({apiKey:o,apiHost:e,fetch:ye,projectId:n}).getComponentDefinitions({componentId:t,limit:1});r.componentDefinitions.length===0?(console.error("Component did not exist"),process.exit(1)):w(r.componentDefinitions[0],i,s)}};import be from"isomorphic-unfetch";var Q={command:"list",describe:"List component definitions",aliases:["ls"],builder:e=>S(f(g(e.options({offset:{describe:"Number of rows to skip before fetching",type:"number",default:0},limit:{describe:"Number of rows to fetch",type:"number",default:20}})))),handler:async({apiHost:e,apiKey:o,limit:t,offset:i,format:n,filename:s,project:m})=>{let a=await new c({apiKey:o,apiHost:e,fetch:be,projectId:m}).getComponentDefinitions({limit:t,offset:i});w(a.componentDefinitions,n,s)}};import Ie from"isomorphic-unfetch";import{diffJson as Ae,diffLines as X}from"diff";import he from"lodash.isequalwith";async function M({source:e,target:o,compareContents:t=(r,a)=>he(r.object,a.object,(p,C,y)=>y==="created"||y==="updated"?!0:void 0),mode:i,allowEmptySource:n=!1,whatIf:s=!1,log:m=()=>{}}){var C,y;let r=new Map;for await(let u of o.objects)r.set(u.id,u);let a=[],p=!1;for await(let u of e.objects){p=!0;let b=u.id,j=r.get(b);if(j){if(!t(u,j)&&(i==="createOrUpdate"||i==="mirror")){let h=async(A,$)=>{var W;s||await o.writeObject(A),m({action:"update",id:b,providerId:A.providerId,displayName:(W=A.displayName)!=null?W:A.providerId,whatIf:s,diff:Ae($.object,A.object)})};a.push(h(u,j))}r.delete(b)}else{let h=async(A,$)=>{var W;s||await o.writeObject(A),m({action:"create",id:$,providerId:$,displayName:(W=A.displayName)!=null?W:A.providerId,whatIf:s,diff:X("",JSON.stringify(A.object,null,2))})};a.push(h(u,b))}}if(await Promise.all(a),i==="mirror"){if(!p&&!n)throw new Error("Source is empty and mode is mirror. This would cause deletion of everything in the target, and most likely indicates an error in source definition.");let u=[];r.forEach(async b=>{let j=async h=>{var A;s||await o.deleteObject(h.providerId),m({action:"delete",id:h.id,providerId:h.providerId,displayName:(A=h.displayName)!=null?A:h.providerId,whatIf:s,diff:X(JSON.stringify(h.object,null,2),"")})};u.push(j(b))}),await Promise.all(u)}await Promise.all([(C=e.onSyncComplete)==null?void 0:C.call(e,!1),(y=o.onSyncComplete)==null?void 0:y.call(o,!0)])}import je from"chalk";import{existsSync as we,mkdirSync as Oe}from"fs";import{readdir as Se,unlink as Pe}from"fs/promises";import{extname as De,join as Z}from"path";async function T({directory:e,format:o="yaml",selectIdentifier:t,selectDisplayName:i=t}){we(e)||Oe(e,{recursive:!0});let s=await Se(e,"utf-8"),m=new Set(s.filter(p=>{let C=De(p);return C===".json"||C===".yaml"||C===".yml"})),r=p=>Z(e,`${p}.${o}`);async function*a(){for(let p of m){let C=Z(e,p);try{let y=await v(C);yield{id:t(y),displayName:i(y),providerId:C,object:y}}catch(y){throw console.error(je.red(`Failed to read ${C}, data is likely invalid.
|
2
|
+
${y==null?void 0:y.message}`)),y}}}return{objects:a(),deleteObject:async p=>{await Pe(p)},writeObject:async p=>{w(p.object,o,r(p.id))}}}var x=e=>e.id,F=e=>`${e.name} (pid: ${e.id})`;function K({client:e}){async function*o(){let t=J(async(i,n)=>(await e.getComponentDefinitions({limit:n,offset:i})).componentDefinitions,{pageSize:100});for await(let i of t)yield{id:x(i),displayName:F(i),providerId:i.id,object:i}}return{objects:o(),deleteObject:async t=>{await e.removeComponentDefinition({componentId:t})},writeObject:async t=>{await e.updateComponentDefinition({componentDefinition:t.object})}}}import R from"chalk";function k({diffMode:e}){return function({action:t,displayName:i,whatIf:n,diff:s}){let m="";switch(t){case"create":m=R.green("[A]");break;case"update":m=R.white("[U]");break;case"delete":m=R.yellow("[D]");break}let r="";(e==="on"||e==="update"&&t==="update")&&(r=`
|
3
|
+
`+s.map(a=>a.added?R.green(a.value):a.removed?R.red(a.value):a.value).join("")),console.log(`${n?R.gray("[WHATIF]"):""}${m} ${i}${r}`)}}import ve from"fs";function L(e,o){if(!o&&!ve.existsSync(e))return{};let t=v(e);if(typeof t!="object")throw new Error(`Package ${e} does not appear valid.`);return t}function z(e,o){w(o,void 0,e)}async function _({objects:e,selectIdentifier:o,selectDisplayName:t=o,onSyncComplete:i}){let n=e.reduce((r,a)=>{let p=o(a);if(r[p])throw new Error(`Identifier ${p} was not unique.`);return r[p]={id:p,object:a,providerId:p,displayName:t(a)},r},{});async function*s(){for(let r of Object.values(n))yield r}function m(){return Object.entries(n).sort((r,a)=>r[0].localeCompare(a[0])).map(r=>r[1].object)}return{objects:s(),deleteObject:async r=>{delete n[r]},writeObject:async r=>{let a=o(r.object);n[a]=r},extractCurrent:m,onSyncComplete:i?r=>i(r,m()):void 0}}var ee={command:"pull <directory>",describe:"Pulls all component definitions to local files in a directory",builder:e=>f(g(P(e.positional("directory",{describe:"Directory to save the component definitions to. If a filename ending in yaml or json is used, a package file will be created instead of files in the directory.",type:"string"}).option("format",{alias:["f"],describe:"Output format",default:"yaml",choices:["yaml","json"],type:"string"}).option("what-if",{alias:["w"],describe:"What-if mode reports what would be done but changes no files",default:!1,type:"boolean"}).option("mode",{alias:["m"],describe:'What kind of changes can be made. "create" = create new files, update nothing. "createOrUpdate" = create new files, update existing, delete nothing. "mirror" = create, update, and delete to mirror state',choices:["create","createOrUpdate","mirror"],default:"mirror",type:"string"})))),handler:async({apiHost:e,apiKey:o,directory:t,format:i,mode:n,whatIf:s,project:m,diff:r})=>{var u;let a=new c({apiKey:o,apiHost:e,fetch:Ie,projectId:m,limitPolicy:E}),p=K({client:a}),C;if(D(t)){let b=L(t,!1);C=await _({objects:(u=b.components)!=null?u:[],selectIdentifier:x,selectDisplayName:F,onSyncComplete:async(j,h)=>{b.components=h,z(t,b)}})}else C=await T({directory:t,selectIdentifier:x,selectDisplayName:F,format:i});await M({source:p,target:C,mode:n,whatIf:s,log:k({diffMode:r})})}};import Ee from"isomorphic-unfetch";var oe={command:"push <directory>",describe:"Pushes all component definitions from files in a directory to Uniform Optimize",builder:e=>f(g(P(e.positional("directory",{describe:"Directory to read the component definitions from. If a filename is used, a package will be read instead.",type:"string"}).option("what-if",{alias:["w"],describe:"What-if mode reports what would be done but changes nothing",default:!1,type:"boolean"}).option("mode",{alias:["m"],describe:'What kind of changes can be made. "create" = create new, update nothing. "createOrUpdate" = create new, update existing, delete nothing. "mirror" = create, update, and delete',choices:["create","createOrUpdate","mirror"],default:"mirror",type:"string"})))),handler:async({apiHost:e,apiKey:o,directory:t,mode:i,whatIf:n,project:s,diff:m})=>{var y;let r=new c({apiKey:o,apiHost:e,fetch:Ee,projectId:s,limitPolicy:E}),a;if(D(t)){let u=L(t,!0);a=await _({objects:(y=u.components)!=null?y:[],selectIdentifier:x,selectDisplayName:F})}else a=await T({directory:t,selectIdentifier:x,selectDisplayName:F});let C=K({client:r});await M({source:a,target:C,mode:i,whatIf:n,log:k({diffMode:m})})}};import Me from"isomorphic-unfetch";var te={command:"remove <id>",aliases:["delete","rm"],describe:"Delete a component definition",builder:e=>f(g(e.positional("id",{demandOption:!0,describe:"Component definition public ID to delete"}))),handler:async({apiHost:e,apiKey:o,id:t,project:i})=>{await new c({apiKey:o,apiHost:e,fetch:Me,projectId:i}).removeComponentDefinition({componentId:t})}};import Te from"isomorphic-unfetch";var ie={command:"update <filename>",aliases:["put"],describe:"Insert or update a component definition",builder:e=>f(g(e.positional("filename",{demandOption:!0,describe:"Component definition file to put"}))),handler:async({apiHost:e,apiKey:o,filename:t,project:i})=>{let n=new c({apiKey:o,apiHost:e,fetch:Te,projectId:i}),s=v(t);await n.updateComponentDefinition({componentDefinition:s})}};var ne={command:"component <command>",aliases:["def"],describe:"Commands for Canvas component definitions",builder:e=>e.command(ee).command(oe).command(q).command(te).command(Q).command(ie).demandCommand(),handler:()=>xe.help()};import Re from"yargs";import Fe from"isomorphic-unfetch";var re={command:"get <id>",describe:"Fetch a composition",builder:e=>S(f(g(O(e.positional("id",{demandOption:!0,describe:"Composition public ID to fetch"}).option({resolvePatterns:{type:"boolean",default:!1,describe:"Resolve pattern references in the composition"}}))))),handler:async({apiHost:e,apiKey:o,id:t,format:i,filename:n,state:s,project:m,resolvePatterns:r})=>{let a=new c({apiKey:o,apiHost:e,fetch:Fe,projectId:m}),p=G(await a.getCompositionById({compositionId:t,state:I(s),skipPatternResolution:!r}));w(p,i,n)}};import ke from"isomorphic-unfetch";var se={command:"list",describe:"List compositions",aliases:["ls"],builder:e=>S(f(g(O(e.options({offset:{describe:"Number of rows to skip before fetching",type:"number",default:0},limit:{describe:"Number of rows to fetch",type:"number",default:20},resolvePatterns:{type:"boolean",default:!1,describe:"Resolve pattern references in the composition"}}))))),handler:async({apiHost:e,apiKey:o,limit:t,offset:i,format:n,filename:s,project:m,state:r,resolvePatterns:a})=>{let C=await new c({apiKey:o,apiHost:e,fetch:ke,projectId:m}).getCompositionList({limit:t,offset:i,state:I(r),skipPatternResolution:!a});w(C.compositions,n,s)}};import Le from"isomorphic-unfetch";var U=e=>e.composition._id,N=e=>{var o,t;return`${(t=(o=e.composition._name)!=null?o:e.composition._slug)!=null?t:e.composition._id} (pid: ${e.composition._id})`};function H({client:e,state:o}){let t=I(o);async function*i(){let n=J(async(s,m)=>(await e.getCompositionList({limit:m,offset:s,state:t,skipPatternResolution:!0})).compositions,{pageSize:100});for await(let s of n)yield{id:U(s),displayName:N(s),providerId:s.composition._id,object:G(s)}}return{objects:i(),deleteObject:async n=>{await e.removeComposition({compositionId:n})},writeObject:async n=>{await e.updateComposition({...n.object,state:t})}}}var ae={command:"pull <directory>",describe:"Pulls all compositions to local files in a directory",builder:e=>f(g(O(P(e.positional("directory",{describe:"Directory to save the component definitions to. If a filename ending in yaml or json is used, a package file will be created instead of files in the directory.",type:"string"}).option("format",{alias:["f"],describe:"Output format",default:"yaml",choices:["yaml","json"],type:"string"}).option("what-if",{alias:["w"],describe:"What-if mode reports what would be done but changes no files",default:!1,type:"boolean"}).option("mode",{alias:["m"],describe:'What kind of changes can be made. "create" = create new files, update nothing. "createOrUpdate" = create new files, update existing, delete nothing. "mirror" = create, update, and delete to mirror state',choices:["create","createOrUpdate","mirror"],default:"mirror",type:"string"}))))),handler:async({apiHost:e,apiKey:o,directory:t,format:i,mode:n,whatIf:s,state:m,project:r,diff:a})=>{var b;let p=new c({apiKey:o,apiHost:e,fetch:Le,projectId:r,limitPolicy:E}),C=H({client:p,state:m}),y=D(t),u;if(y){let j=L(t,!1);u=await _({objects:(b=j==null?void 0:j.compositions)!=null?b:[],selectIdentifier:U,selectDisplayName:N,onSyncComplete:async(h,A)=>{j.compositions=A,z(t,j)}})}else u=await T({directory:t,selectIdentifier:U,selectDisplayName:N,format:i});await M({source:C,target:u,mode:n,whatIf:s,log:k({diffMode:a})})}};import _e from"isomorphic-unfetch";var me={command:"push <directory>",describe:"Pushes all compositions from files in a directory to Uniform Optimize",builder:e=>f(g(O(P(e.positional("directory",{describe:"Directory to read the component definitions from. If a filename is used, a package will be read instead.",type:"string"}).option("what-if",{alias:["w"],describe:"What-if mode reports what would be done but changes nothing",default:!1,type:"boolean"}).option("mode",{alias:["m"],describe:'What kind of changes can be made. "create" = create new, update nothing. "createOrUpdate" = create new, update existing, delete nothing. "mirror" = create, update, and delete',choices:["create","createOrUpdate","mirror"],default:"mirror",type:"string"}))))),handler:async({apiHost:e,apiKey:o,directory:t,mode:i,whatIf:n,state:s,project:m,diff:r})=>{var u;let a=new c({apiKey:o,apiHost:e,fetch:_e,projectId:m,limitPolicy:E}),p;if(D(t)){let b=L(t,!0);p=await _({objects:(u=b.compositions)!=null?u:[],selectIdentifier:U,selectDisplayName:N})}else p=await T({directory:t,selectIdentifier:U,selectDisplayName:N});let y=H({client:a,state:s});await M({source:p,target:y,mode:i,whatIf:n,log:k({diffMode:r})})}};import Ue from"isomorphic-unfetch";var pe={command:"remove <id>",aliases:["delete","rm"],describe:"Delete a composition",builder:e=>f(g(e.positional("id",{demandOption:!0,describe:"Composition public ID to delete"}))),handler:async({apiHost:e,apiKey:o,id:t,project:i})=>{await new c({apiKey:o,apiHost:e,fetch:Ue,projectId:i}).removeComposition({compositionId:t})}};import Ne from"isomorphic-unfetch";var ce={command:"update <filename>",aliases:["put"],describe:"Insert or update a composition",builder:e=>f(g(O(e.positional("filename",{demandOption:!0,describe:"Composition file to put"})))),handler:async({apiHost:e,apiKey:o,filename:t,project:i,state:n})=>{let s=new c({apiKey:o,apiHost:e,fetch:Ne,projectId:i}),m=v(t);await s.updateComposition({...m,state:I(n)})}};var de={command:"composition <command>",describe:"Commands for Canvas compositions",aliases:["comp"],builder:e=>e.command(ae).command(me).command(re).command(pe).command(se).command(ce).demandCommand(),handler:()=>Re.help()};var qi={commands:[{command:"canvas <command>",aliases:["cv","pm","presentation"],describe:"Uniform Canvas commands",builder:e=>e.command(de).command(ne).demandCommand(),handler:()=>{We.showHelp()}}]};export{L as readCanvasPackage,qi as uniformCLI,z as writeCanvasPackage};
|
@@ -1,5 +1,110 @@
|
|
1
1
|
import Pusher from 'pusher-js';
|
2
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 PUT request body for /api/v1/canvas */
|
21
|
+
declare type CompositionAPIPutRequest = Omit<CompositionAPIResponse, 'projectId'> & {
|
22
|
+
projectId: string;
|
23
|
+
};
|
24
|
+
/** Shape of the DELETE request body for /api/v1/canvas */
|
25
|
+
declare type CompositionAPIDeleteRequest = {
|
26
|
+
/** Public ID of the composition to delete */
|
27
|
+
compositionId: string;
|
28
|
+
/** Project ID that the composition lives on. */
|
29
|
+
projectId: string;
|
30
|
+
/** The state to delete. If unspecified, all states will be deleted. See CANVAS_DRAFT_STATE and CANVAS_PUBLISHED_STATE. */
|
31
|
+
state?: number;
|
32
|
+
};
|
33
|
+
/** The GET response from /api/v1/canvas when `component` or `slug` are not specified */
|
34
|
+
declare type CompositionListAPIResponse = {
|
35
|
+
compositions: Array<CompositionAPIResponse>;
|
36
|
+
};
|
37
|
+
/** Query parameter options for GET /api/v1/canvas */
|
38
|
+
declare type CompositionAPIOptions = {
|
39
|
+
/** Specify a single composition ID to fetch. Changes response from list to single. */
|
40
|
+
compositionId?: string;
|
41
|
+
/** Specify a single composition to fetch by slug. Changes response from list to single. */
|
42
|
+
slug?: string;
|
43
|
+
/** The project the composition(s) are on. */
|
44
|
+
projectId: string;
|
45
|
+
/** The component type to filter by */
|
46
|
+
type?: string;
|
47
|
+
/** Number of records to skip */
|
48
|
+
offset?: number;
|
49
|
+
/** Max number of records to return (defaults to 100) */
|
50
|
+
limit?: number;
|
51
|
+
/** State of compositions to fetch. Default = 'published' */
|
52
|
+
state?: number;
|
53
|
+
/**
|
54
|
+
* Signals a Canvas enhancer proxy to skip processing enhancements to the data and return raw data only.
|
55
|
+
* This improves performance if you do not require enhanced component data.
|
56
|
+
* If calling the Canvas API directly with no enhancer proxy, this has no effect.
|
57
|
+
*/
|
58
|
+
skipEnhance?: boolean;
|
59
|
+
/**
|
60
|
+
* If true, any pattern references in the composition will be left unresolved.
|
61
|
+
* This is appropriate if you intend to serialize the composition data without pattern
|
62
|
+
* data embedded into it, and serialize the pattern data separately.
|
63
|
+
*/
|
64
|
+
skipPatternResolution?: boolean;
|
65
|
+
};
|
66
|
+
declare type ComponentParameter<TValue = unknown> = {
|
67
|
+
/** The type of the parameter. Determines how it is displayed when editing, and tells the consumer how to process it. */
|
68
|
+
type: string;
|
69
|
+
/**
|
70
|
+
* The value of the parameter.
|
71
|
+
* Any JSON-serializable value is acceptable.
|
72
|
+
*/
|
73
|
+
value: TValue;
|
74
|
+
};
|
75
|
+
/**
|
76
|
+
* Defines the shape of a component instance served by the composition API.
|
77
|
+
*/
|
78
|
+
declare type ComponentInstance = {
|
79
|
+
/** Type of the component instance (public_id of its definition) */
|
80
|
+
type: string;
|
81
|
+
/** Component parameter values for the component instance */
|
82
|
+
parameters?: Record<string, ComponentParameter>;
|
83
|
+
/** Public ID of alternate visual appearance for this component, if any selected */
|
84
|
+
variant?: string;
|
85
|
+
/** Slots containing any sub-components */
|
86
|
+
slots?: Record<string, ComponentInstance[]>;
|
87
|
+
/** Data for the component instance, provided by a component enhancer. Never set in unenhanced data. */
|
88
|
+
data?: Record<string, unknown>;
|
89
|
+
/** Indicates this component instance should be sourced from a pattern library pattern */
|
90
|
+
_pattern?: string;
|
91
|
+
/**
|
92
|
+
* If an error occurs resolving a pattern reference, it is left unresolved and this property is set to indicate why.
|
93
|
+
* CYCLIC: A cyclic pattern graph was detected, which could not be resolved because it would cause an infinite loop.
|
94
|
+
* NOTFOUND: The pattern ID referenced could not be found. It may have been deleted, or not be published yet.
|
95
|
+
*/
|
96
|
+
_patternError?: 'CYCLIC' | 'NOTFOUND';
|
97
|
+
};
|
98
|
+
/** Defines the shape of the root component in a composition */
|
99
|
+
declare type RootComponentInstance = ComponentInstance & {
|
100
|
+
/** The public UUID of the composition. */
|
101
|
+
_id?: string;
|
102
|
+
/** Slug pattern of this component. */
|
103
|
+
_slug?: string | null;
|
104
|
+
/** Friendly name of this component. */
|
105
|
+
_name?: string;
|
106
|
+
};
|
107
|
+
|
3
108
|
/** Shape of the GET response from /api/v1/canvas-definitions */
|
4
109
|
declare type ComponentDefinitionAPIResponse = {
|
5
110
|
componentDefinitions: Array<ComponentDefinition>;
|
@@ -103,6 +208,8 @@ declare type ComponentDefinition = {
|
|
103
208
|
parameters?: Array<ComponentDefinitionParameter>;
|
104
209
|
/** The named slots for this component; placement areas where arrays of other components can be added. */
|
105
210
|
slots?: Array<ComponentDefinitionSlot>;
|
211
|
+
/** Default component instance value */
|
212
|
+
defaults?: ComponentInstance | null;
|
106
213
|
/** Named variants for this component; enables creation of visual variants that use the same parameter data/ */
|
107
214
|
variants?: Array<ComponentDefinitionVariant>;
|
108
215
|
/** Setting for slug validation */
|
@@ -120,111 +227,6 @@ declare type CreatingComponentDefinition = Omit<Partial<ComponentDefinition>, 'c
|
|
120
227
|
name: string;
|
121
228
|
};
|
122
229
|
|
123
|
-
/** @deprecated use CANVAS_DRAFT_STATE and CANVAS_PUBLISHED_STATE instead */
|
124
|
-
declare type CompositionFetchState = 'preview' | 'published' | number;
|
125
|
-
/** The GET response from /api/v1/canvas when `component` or `slug` params are specified */
|
126
|
-
declare type CompositionAPIResponse = {
|
127
|
-
/** The state of the layout. See CANVAS_DRAFT_STATE and CANVAS_PUBLISHED_STATE. */
|
128
|
-
state: number;
|
129
|
-
/** The project ID that this layout data is part of */
|
130
|
-
projectId: string;
|
131
|
-
/** Layout data being read or written */
|
132
|
-
composition: RootComponentInstance;
|
133
|
-
/** Whether this composition is a pattern (can be referenced by other compositions) */
|
134
|
-
pattern: boolean;
|
135
|
-
/** Created date string for this definition */
|
136
|
-
created?: string;
|
137
|
-
/** Modified date string for this definition */
|
138
|
-
modified?: string;
|
139
|
-
};
|
140
|
-
/** Shape of the PUT request body for /api/v1/canvas */
|
141
|
-
declare type CompositionAPIPutRequest = Omit<CompositionAPIResponse, 'projectId'> & {
|
142
|
-
projectId: string;
|
143
|
-
};
|
144
|
-
/** Shape of the DELETE request body for /api/v1/canvas */
|
145
|
-
declare type CompositionAPIDeleteRequest = {
|
146
|
-
/** Public ID of the composition to delete */
|
147
|
-
compositionId: string;
|
148
|
-
/** Project ID that the composition lives on. */
|
149
|
-
projectId: string;
|
150
|
-
/** The state to delete. If unspecified, all states will be deleted. See CANVAS_DRAFT_STATE and CANVAS_PUBLISHED_STATE. */
|
151
|
-
state?: number;
|
152
|
-
};
|
153
|
-
/** The GET response from /api/v1/canvas when `component` or `slug` are not specified */
|
154
|
-
declare type CompositionListAPIResponse = {
|
155
|
-
compositions: Array<CompositionAPIResponse>;
|
156
|
-
};
|
157
|
-
/** Query parameter options for GET /api/v1/canvas */
|
158
|
-
declare type CompositionAPIOptions = {
|
159
|
-
/** Specify a single composition ID to fetch. Changes response from list to single. */
|
160
|
-
compositionId?: string;
|
161
|
-
/** Specify a single composition to fetch by slug. Changes response from list to single. */
|
162
|
-
slug?: string;
|
163
|
-
/** The project the composition(s) are on. */
|
164
|
-
projectId: string;
|
165
|
-
/** The component type to filter by */
|
166
|
-
type?: string;
|
167
|
-
/** Number of records to skip */
|
168
|
-
offset?: number;
|
169
|
-
/** Max number of records to return (defaults to 100) */
|
170
|
-
limit?: number;
|
171
|
-
/** State of compositions to fetch. Default = 'published' */
|
172
|
-
state?: number;
|
173
|
-
/**
|
174
|
-
* Signals a Canvas enhancer proxy to skip processing enhancements to the data and return raw data only.
|
175
|
-
* This improves performance if you do not require enhanced component data.
|
176
|
-
* If calling the Canvas API directly with no enhancer proxy, this has no effect.
|
177
|
-
*/
|
178
|
-
skipEnhance?: boolean;
|
179
|
-
/**
|
180
|
-
* If true, any pattern references in the composition will be left unresolved.
|
181
|
-
* This is appropriate if you intend to serialize the composition data without pattern
|
182
|
-
* data embedded into it, and serialize the pattern data separately.
|
183
|
-
*/
|
184
|
-
skipPatternResolution?: boolean;
|
185
|
-
};
|
186
|
-
declare type ComponentParameter<TValue = unknown> = {
|
187
|
-
/** The type of the parameter. Determines how it is displayed when editing, and tells the consumer how to process it. */
|
188
|
-
type: string;
|
189
|
-
/**
|
190
|
-
* The value of the parameter.
|
191
|
-
* Any JSON-serializable value is acceptable.
|
192
|
-
*/
|
193
|
-
value: TValue;
|
194
|
-
};
|
195
|
-
/**
|
196
|
-
* Defines the shape of a component instance served by the composition API.
|
197
|
-
*/
|
198
|
-
declare type ComponentInstance = {
|
199
|
-
/** Type of the component instance (public_id of its definition) */
|
200
|
-
type: string;
|
201
|
-
/** Component parameter values for the component instance */
|
202
|
-
parameters?: Record<string, ComponentParameter>;
|
203
|
-
/** Public ID of alternate visual appearance for this component, if any selected */
|
204
|
-
variant?: string;
|
205
|
-
/** Slots containing any sub-components */
|
206
|
-
slots?: Record<string, ComponentInstance[]>;
|
207
|
-
/** Data for the component instance, provided by a component enhancer. Never set in unenhanced data. */
|
208
|
-
data?: Record<string, unknown>;
|
209
|
-
/** Indicates this component instance should be sourced from a pattern library pattern */
|
210
|
-
_pattern?: string;
|
211
|
-
/**
|
212
|
-
* If an error occurs resolving a pattern reference, it is left unresolved and this property is set to indicate why.
|
213
|
-
* CYCLIC: A cyclic pattern graph was detected, which could not be resolved because it would cause an infinite loop.
|
214
|
-
* NOTFOUND: The pattern ID referenced could not be found. It may have been deleted, or not be published yet.
|
215
|
-
*/
|
216
|
-
_patternError?: 'CYCLIC' | 'NOTFOUND';
|
217
|
-
};
|
218
|
-
/** Defines the shape of the root component in a composition */
|
219
|
-
declare type RootComponentInstance = ComponentInstance & {
|
220
|
-
/** The public UUID of the composition. */
|
221
|
-
_id?: string;
|
222
|
-
/** Slug pattern of this component. */
|
223
|
-
_slug?: string | null;
|
224
|
-
/** Friendly name of this component. */
|
225
|
-
_name?: string;
|
226
|
-
};
|
227
|
-
|
228
230
|
/**
|
229
231
|
* Pusher-js is large (80k) and not tree shakable so it is always bundled if directly referenced,
|
230
232
|
* when it's only needed during preview mode. To avoid bundling it for all, we use an old-school
|
package/dist/index.d.ts
CHANGED
@@ -1,5 +1,5 @@
|
|
1
|
-
import { C as ComponentInstance, a as ComponentParameter, b as CompositionAPIOptions, c as CompositionListAPIResponse, d as CompositionAPIResponse, e as CompositionAPIPutRequest, f as CompositionAPIDeleteRequest, g as ComponentDefinitionListAPIOptions, h as ComponentDefinitionAPIResponse, i as ComponentDefinitionAPIPutRequest, j as ComponentDefinitionAPIDeleteRequest, P as PreviewEventBus } from './createEventBus-
|
2
|
-
export { r as ChannelSubscription, o as ComponentDefinition, j as ComponentDefinitionAPIDeleteRequest, i as ComponentDefinitionAPIPutRequest, h as ComponentDefinitionAPIResponse, g as ComponentDefinitionListAPIOptions, k as ComponentDefinitionParameter, n as ComponentDefinitionSlot, m as ComponentDefinitionSlugSettings, l as ComponentDefinitionVariant, C as ComponentInstance, a as ComponentParameter, f as CompositionAPIDeleteRequest, b as CompositionAPIOptions, e as CompositionAPIPutRequest, d as CompositionAPIResponse, q as CompositionFetchState, c as CompositionListAPIResponse, p as CreatingComponentDefinition, P as PreviewEventBus, R as RootComponentInstance, s as createEventBus } from './createEventBus-
|
1
|
+
import { C as ComponentInstance, a as ComponentParameter, b as CompositionAPIOptions, c as CompositionListAPIResponse, d as CompositionAPIResponse, e as CompositionAPIPutRequest, f as CompositionAPIDeleteRequest, g as ComponentDefinitionListAPIOptions, h as ComponentDefinitionAPIResponse, i as ComponentDefinitionAPIPutRequest, j as ComponentDefinitionAPIDeleteRequest, P as PreviewEventBus } from './createEventBus-ca90547e';
|
2
|
+
export { r as ChannelSubscription, o as ComponentDefinition, j as ComponentDefinitionAPIDeleteRequest, i as ComponentDefinitionAPIPutRequest, h as ComponentDefinitionAPIResponse, g as ComponentDefinitionListAPIOptions, k as ComponentDefinitionParameter, n as ComponentDefinitionSlot, m as ComponentDefinitionSlugSettings, l as ComponentDefinitionVariant, C as ComponentInstance, a as ComponentParameter, f as CompositionAPIDeleteRequest, b as CompositionAPIOptions, e as CompositionAPIPutRequest, d as CompositionAPIResponse, q as CompositionFetchState, c as CompositionListAPIResponse, p as CreatingComponentDefinition, P as PreviewEventBus, R as RootComponentInstance, s as createEventBus } from './createEventBus-ca90547e';
|
3
3
|
import { Options } from 'p-throttle';
|
4
4
|
import { Options as Options$1 } from 'p-retry';
|
5
5
|
import { PersonalizableListItem } from '@uniformdev/optimize-tracker-common';
|
package/dist/index.esm.js
CHANGED
@@ -1,4 +1,4 @@
|
|
1
|
-
import{a as
|
1
|
+
import{a as j,b as u,c as k,d as F,e as $,f as N,g as v,h as A,i as x,j as U,k as V,l as w,m as z,n as W}from"./chunk-34U4J6TI.mjs";function f(o,e){let n=[{ancestorsAndSelf:[{component:o,parentSlot:void 0,parentSlotIndex:void 0}]}];do{let t=n.pop();if(!t)continue;let r=t.ancestorsAndSelf[0];e(r.component,t.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}=t.ancestorsAndSelf[0],s=t.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}=t.ancestorsAndSelf[0],m=t.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--)n.push({ancestorsAndSelf:[{component:p[m],parentSlot:s,parentSlotIndex:m},...t.ancestorsAndSelf]})}}}while(n.length>0)}function C(o){let e=[];for(let n=o.length-1;n>=0;n--){let{parentSlot:t,parentSlotIndex:r}=o[n];t&&r!==void 0&&e.push(`${t}[${r}]`)}return`.${e.join(".")}`}var I=class{constructor(e,n){this.groups=e.reduce((t,r)=>{var i;let a=n(r.args);return t[a]=(i=t[a])!=null?i:[],t[a].push(r),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 E=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(r=>this._paramMatches.push({name:r,enhancer:this._resolveParameterEnhancer(n)})),this}parameterType(e,n){return(Array.isArray(e)?e:[e]).forEach(r=>this._paramMatches.push({type:r,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(r=>r.name&&r.name===e||r.type&&r.type===n.type||!r.type&&!r.name))==null?void 0:t.enhancer}resolveComponentEnhancers(){return this._dataMatches}_resolveParameterEnhancer(e){return typeof e=="function"?{enhanceOne:e}:e}},R=class{constructor(){this._componentIndex={};this._rootBuilder=new E}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(r=>{this._componentIndex[r]=this._componentIndex[r]||new E,n(this._componentIndex[r])}),this}resolveParameterEnhancer(e,n,t){let r=this._componentIndex[e.type];if(r){let a=r.resolveParameterEnhancer(n,t);if(a)return a}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[r,a]of t.resolveComponentEnhancers())n.set(r,a)}return n}};var T=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:o,shouldQueue:e,limitPolicy:n}){let t=[];return{enhanceOne:async i=>{if(!e||e(i))return new Promise((c,s)=>{t.push(new T(c,s,i))})},completeAll:async()=>{if(t.length>0){try{await o(t)}catch(c){t.forEach(s=>s.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 i=t.length;return t=[],i},limitPolicy:n}}async function J({composition:o,enhancers:e,context:n,onErrors:t=r=>{throw new Error(r.map(a=>`${a.message}
|
2
2
|
${typeof a.error=="object"&&"stack"in a.error?a.error.stack:a.error}`).join(`
|
3
3
|
|
4
|
-
`))}}){let r=[],a=new Set,i=new Set;f(o,(s,p)=>{var d;Object.entries((d=s.parameters)!=null?d:{}).forEach(([P,
|
4
|
+
`))}}){let r=[],a=new Set,i=new Set;f(o,(s,p)=>{var d;Object.entries((d=s.parameters)!=null?d:{}).forEach(([P,g])=>{let y=e.resolveParameterEnhancer(s,P,g);y&&(i.add(y),r.push(B(s,p,P,g,y,n)))});let m=e.resolveComponentEnhancers(s);r.push(S(s,p,m,n)),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:u)(()=>p.completeAll())}catch(d){return{error:d,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:u)(()=>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&&t(c)}async function S(o,e,n,t){return n.size&&(o.data={}),await Promise.all(Array.from(n).map(async([r,a])=>{var i;try{let s=await(a.completeAll?u:(i=a.limitPolicy)!=null?i:u)(async()=>a.enhanceOne({component:o,context:t}));s!=null&&(o.data[r]=s)}catch(c){let s=`Component ${C(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 B(o,e,n,t,r,a){var i;try{let s=await(r.completeAll?u:(i=r.limitPolicy)!=null?i:u)(async()=>r.enhanceOne({parameter:t,parameterName:n,component:o,context:a}));s===null?delete o.parameters[n]:typeof s=="undefined"?o.parameters[n]={...t,value:t.value}:o.parameters[n]={...t,value:s}}catch(c){let s=`Component ${C(e)} (type: ${o.type}): enhancing parameter ${n} (type: ${t.type}) threw exception. Parameter will be removed.`;return delete o.parameters[n],{message:s,error:c}}}var ee=(o,...e)=>({enhanceOne:t=>{let r=o.enhanceOne(t);for(let a of e){let i=O(r)?r:Promise.resolve(r),c="enhanceOne"in a?a.enhanceOne:a;r=i.then(s=>c({...t,parameter:{type:t.parameter.type,value:s}}))}return r},completeAll:()=>{var t,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=(t=o.completeAll)==null?void 0:t.call(o))!=null?r:Promise.resolve(0)}});function O(o){return!!o&&(typeof o=="object"||typeof o=="function")&&typeof o.then=="function"}var te=o=>o.startsWith("$");function ae(o){return o?o.map(e=>{var n,t;return{...e,intentTag:(t=(n=e.parameters)==null?void 0:n[A])==null?void 0:t.value}}):[]}var _="https://js.pusher.com/7.0.3/pusher.min.js";async function L(){if(!(typeof document=="undefined"||typeof window=="undefined"))return window.Pusher?window.Pusher:new Promise((o,e)=>{let n=setTimeout(()=>{window.Pusher&&o(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),o(window.Pusher)}),document.head.appendChild(t)})}async function ie(){let o=await L();if(!o)return;let e=window.__UNIFORM_EVENT_BUS__;if(!e){let n=new o("7b5f5abd160fea549ffe",{cluster:"mt1"});n.connect(),console.log("[canvas] \u{1F525} preview connected"),e=window.__UNIFORM_EVENT_BUS__={subscribe:t=>{let r=n.subscribe(t);return{unsubscribe:()=>n.unsubscribe(t),addEventHandler:(a,i)=>(r.bind(a,i),()=>r.unbind(a,i))}}}}return e}function b(o,e,n){return`${o}.${e}@${n}`}function le({projectId:o,compositionId:e,compositionState:n=0,eventBus:{subscribe:t},callback:r,event:a="updated"}){let i=b(o,e,n),c=t(i),s=c.addEventHandler(a,r);return()=>{s(),c.unsubscribe()}}function M({component:o}){var t;let e={},n=(t=o.slots)==null?void 0:t[w];return n==null||n.forEach(r=>{var i;let a=(i=r.parameters)==null?void 0:i[x];(a==null?void 0:a.value)&&typeof a.value=="string"&&(e[a.value]=e[a.value]||[],e[a.value].push(r))}),e}function fe({composition:o,locale:e}){f(o,(n,t,r)=>{if(n.type===v){let a=M({component:n}),i=typeof e=="string"?e:e({component:n,locales:a}),c;if(i&&(c=a[i]),c==null?void 0:c.length){let[s,...p]=c;r.replaceComponent(s),p.length&&r.insertAfter(p)}else r.removeComponent()}})}export{T as BatchEntry,z as CANVAS_DRAFT_STATE,A as CANVAS_INTENT_TAG_PARAM,x as CANVAS_LOCALE_TAG_PARAM,w as CANVAS_LOCALIZATION_SLOT,v as CANVAS_LOCALIZATION_TYPE,U as CANVAS_PERSONALIZE_SLOT,$ as CANVAS_PERSONALIZE_TYPE,W as CANVAS_PUBLISHED_STATE,V as CANVAS_TEST_SLOT,N as CANVAS_TEST_TYPE,F as CanvasClient,k as CanvasClientError,E as ChildEnhancerBuilder,R as EnhancerBuilder,I as UniqueBatchEntries,ee as compose,q as createBatchEnhancer,ie as createEventBus,j as createLimitPolicy,J as enhance,M as extractLocales,b as getChannelName,C as getComponentPath,te as isSystemComponentDefinition,fe as localize,ae as mapSlotToPersonalizedVariations,u as nullLimitPolicy,le as subscribeToComposition,f as walkComponentTree};
|
package/dist/index.js
CHANGED
@@ -1,5 +1,5 @@
|
|
1
|
-
var
|
1
|
+
var M=Object.create;var y=Object.defineProperty;var F=Object.getOwnPropertyDescriptor;var V=Object.getOwnPropertyNames;var D=Object.getPrototypeOf,H=Object.prototype.hasOwnProperty;var b=r=>y(r,"__esModule",{value:!0});var z=(r,e)=>{for(var n in e)y(r,n,{get:e[n],enumerable:!0})},S=(r,e,n,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of V(e))!H.call(r,o)&&(n||o!=="default")&&y(r,o,{get:()=>e[o],enumerable:!(t=F(e,o))||t.enumerable});return r},O=(r,e)=>S(b(y(r!=null?M(D(r)):{},"default",!e&&r&&r.__esModule?{get:()=>r.default,enumerable:!0}:{value:r,enumerable:!0})),r),K=(r=>(e,n)=>r&&r.get(e)||(n=S(b({}),e,1),r&&r.set(e,n),n))(typeof WeakMap!="undefined"?new WeakMap:0);var le={};z(le,{BatchEntry:()=>A,CANVAS_DRAFT_STATE:()=>te,CANVAS_INTENT_TAG_PARAM:()=>I,CANVAS_LOCALE_TAG_PARAM:()=>T,CANVAS_LOCALIZATION_SLOT:()=>w,CANVAS_LOCALIZATION_TYPE:()=>v,CANVAS_PERSONALIZE_SLOT:()=>ee,CANVAS_PERSONALIZE_TYPE:()=>Q,CANVAS_PUBLISHED_STATE:()=>oe,CANVAS_TEST_SLOT:()=>ne,CANVAS_TEST_TYPE:()=>X,CanvasClient:()=>U,CanvasClientError:()=>f,ChildEnhancerBuilder:()=>P,EnhancerBuilder:()=>j,UniqueBatchEntries:()=>L,compose:()=>J,createBatchEnhancer:()=>q,createEventBus:()=>ae,createLimitPolicy:()=>g,enhance:()=>G,extractLocales:()=>$,getChannelName:()=>x,getComponentPath:()=>C,isSystemComponentDefinition:()=>re,localize:()=>pe,mapSlotToPersonalizedVariations:()=>ie,nullLimitPolicy:()=>h,subscribeToComposition:()=>ce,walkComponentTree:()=>d});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],l=t.ancestorsAndSelf[1];if(a&&typeof p!="undefined")l.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 l=p.length-1;l>=0;l--)n.push({ancestorsAndSelf:[{component:p[l],parentSlot:a,parentSlotIndex:l},...t.ancestorsAndSelf]})}}}while(n.length>0)}function C(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 L=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 P=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}},j=class{constructor(){this._componentIndex={};this._rootBuilder=new P}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 P,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 A=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 A(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 N=O(require("p-throttle")),B=O(require("p-retry"));function g({throttle:r={interval:1e3,limit:10},retry:e={retries:1,factor:1.66}}){let n=r?(0,N.default)(r):null;return function(o){let i=async()=>await o();if(n&&(i=n(i)),e){let s=i;i=()=>(0,B.default)(s,e)}return i()}}var h=async r=>await r();async function G({composition:r,enhancers:e,context:n,onErrors:t=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 u;Object.entries((u=a.parameters)!=null?u:{}).forEach(([
|
5
|
-
${o}${i?" "+i:""} (${n} ${t})`);this.errorMessage=e;this.fetchMethod=n;this.fetchUri=t;this.statusCode=o;this.statusText=i;Object.setPrototypeOf(this,f.prototype)}},
|
4
|
+
`))}}){let o=[],i=new Set,s=new Set;d(r,(a,p)=>{var u;Object.entries((u=a.parameters)!=null?u:{}).forEach(([R,_])=>{let E=e.resolveParameterEnhancer(a,R,_);E&&(s.add(E),o.push(Z(a,p,R,_,E,n)))});let l=e.resolveComponentEnhancers(a);o.push(Y(a,p,l,n)),i.add(l)}),o.push(...Array.from(i).flatMap(a=>Array.from(a).map(async([,p])=>{var l;try{p.completeAll&&await((l=p.limitPolicy)!=null?l:h)(()=>p.completeAll())}catch(u){return{error:u,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:h)(()=>a.completeAll())}catch(l){return{error:l,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 Y(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?h:(s=i.limitPolicy)!=null?s:h)(async()=>i.enhanceOne({component:r,context:t}));a!=null&&(r.data[o]=a)}catch(c){let a=`Component ${C(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 Z(r,e,n,t,o,i){var s;try{let a=await(o.completeAll?h:(s=o.limitPolicy)!=null?s:h)(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 ${C(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 J=(r,...e)=>({enhanceOne:t=>{let o=r.enhanceOne(t);for(let i of e){let s=W(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:()=>{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=(t=r.completeAll)==null?void 0:t.call(r))!=null?o:Promise.resolve(0)}});function W(r){return!!r&&(typeof r=="object"||typeof r=="function")&&typeof r.then=="function"}var f=class extends Error{constructor(e,n,t,o,i){super(`${e}
|
5
|
+
${o}${i?" "+i:""} (${n} ${t})`);this.errorMessage=e;this.fetchMethod=n;this.fetchUri=t;this.statusCode=o;this.statusText=i;Object.setPrototypeOf(this,f.prototype)}},U=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:g({})}}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 f(s,(i=n==null?void 0:n.method)!=null?i:"GET",e.toString(),o.status)}return(n==null?void 0: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}};var Q="$personalization",X="$test",v="$localization",I="intentTag",T="locale",ee="pz",ne="test",w="localized",te=0,oe=64;var re=r=>r.startsWith("$");function ie(r){return r?r.map(e=>{var n,t;return{...e,intentTag:(t=(n=e.parameters)==null?void 0:n[I])==null?void 0:t.value}}):[]}var k="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="${k}"><\/script> manually.`)},5e3),t=document.createElement("script");t.src=k,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 x(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=x(r,e,n),c=t(s),a=c.addEventHandler(i,o);return()=>{a(),c.unsubscribe()}}function $({component:r}){var t;let e={},n=(t=r.slots)==null?void 0:t[w];return n==null||n.forEach(o=>{var s;let i=(s=o.parameters)==null?void 0:s[T];(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=$({component:n}),s=typeof e=="string"?e:e({component:n,locales:i}),c;if(s&&(c=i[s]),c==null?void 0:c.length){let[a,...p]=c;o.replaceComponent(a),p.length&&o.insertAfter(p)}else o.removeComponent()}})}module.exports=K(le);0&&(module.exports={BatchEntry,CANVAS_DRAFT_STATE,CANVAS_INTENT_TAG_PARAM,CANVAS_LOCALE_TAG_PARAM,CANVAS_LOCALIZATION_SLOT,CANVAS_LOCALIZATION_TYPE,CANVAS_PERSONALIZE_SLOT,CANVAS_PERSONALIZE_TYPE,CANVAS_PUBLISHED_STATE,CANVAS_TEST_SLOT,CANVAS_TEST_TYPE,CanvasClient,CanvasClientError,ChildEnhancerBuilder,EnhancerBuilder,UniqueBatchEntries,compose,createBatchEnhancer,createEventBus,createLimitPolicy,enhance,extractLocales,getChannelName,getComponentPath,isSystemComponentDefinition,localize,mapSlotToPersonalizedVariations,nullLimitPolicy,subscribeToComposition,walkComponentTree});
|
package/dist/index.mjs
CHANGED
@@ -1,4 +1,4 @@
|
|
1
|
-
import{a as
|
1
|
+
import{a as j,b as u,c as k,d as F,e as $,f as N,g as v,h as A,i as x,j as U,k as V,l as w,m as z,n as W}from"./chunk-34U4J6TI.mjs";function f(o,e){let n=[{ancestorsAndSelf:[{component:o,parentSlot:void 0,parentSlotIndex:void 0}]}];do{let t=n.pop();if(!t)continue;let r=t.ancestorsAndSelf[0];e(r.component,t.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}=t.ancestorsAndSelf[0],s=t.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}=t.ancestorsAndSelf[0],m=t.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--)n.push({ancestorsAndSelf:[{component:p[m],parentSlot:s,parentSlotIndex:m},...t.ancestorsAndSelf]})}}}while(n.length>0)}function C(o){let e=[];for(let n=o.length-1;n>=0;n--){let{parentSlot:t,parentSlotIndex:r}=o[n];t&&r!==void 0&&e.push(`${t}[${r}]`)}return`.${e.join(".")}`}var I=class{constructor(e,n){this.groups=e.reduce((t,r)=>{var i;let a=n(r.args);return t[a]=(i=t[a])!=null?i:[],t[a].push(r),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 E=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(r=>this._paramMatches.push({name:r,enhancer:this._resolveParameterEnhancer(n)})),this}parameterType(e,n){return(Array.isArray(e)?e:[e]).forEach(r=>this._paramMatches.push({type:r,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(r=>r.name&&r.name===e||r.type&&r.type===n.type||!r.type&&!r.name))==null?void 0:t.enhancer}resolveComponentEnhancers(){return this._dataMatches}_resolveParameterEnhancer(e){return typeof e=="function"?{enhanceOne:e}:e}},R=class{constructor(){this._componentIndex={};this._rootBuilder=new E}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(r=>{this._componentIndex[r]=this._componentIndex[r]||new E,n(this._componentIndex[r])}),this}resolveParameterEnhancer(e,n,t){let r=this._componentIndex[e.type];if(r){let a=r.resolveParameterEnhancer(n,t);if(a)return a}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[r,a]of t.resolveComponentEnhancers())n.set(r,a)}return n}};var T=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:o,shouldQueue:e,limitPolicy:n}){let t=[];return{enhanceOne:async i=>{if(!e||e(i))return new Promise((c,s)=>{t.push(new T(c,s,i))})},completeAll:async()=>{if(t.length>0){try{await o(t)}catch(c){t.forEach(s=>s.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 i=t.length;return t=[],i},limitPolicy:n}}async function J({composition:o,enhancers:e,context:n,onErrors:t=r=>{throw new Error(r.map(a=>`${a.message}
|
2
2
|
${typeof a.error=="object"&&"stack"in a.error?a.error.stack:a.error}`).join(`
|
3
3
|
|
4
|
-
`))}}){let r=[],a=new Set,i=new Set;f(o,(s,p)=>{var d;Object.entries((d=s.parameters)!=null?d:{}).forEach(([P,
|
4
|
+
`))}}){let r=[],a=new Set,i=new Set;f(o,(s,p)=>{var d;Object.entries((d=s.parameters)!=null?d:{}).forEach(([P,g])=>{let y=e.resolveParameterEnhancer(s,P,g);y&&(i.add(y),r.push(B(s,p,P,g,y,n)))});let m=e.resolveComponentEnhancers(s);r.push(S(s,p,m,n)),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:u)(()=>p.completeAll())}catch(d){return{error:d,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:u)(()=>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&&t(c)}async function S(o,e,n,t){return n.size&&(o.data={}),await Promise.all(Array.from(n).map(async([r,a])=>{var i;try{let s=await(a.completeAll?u:(i=a.limitPolicy)!=null?i:u)(async()=>a.enhanceOne({component:o,context:t}));s!=null&&(o.data[r]=s)}catch(c){let s=`Component ${C(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 B(o,e,n,t,r,a){var i;try{let s=await(r.completeAll?u:(i=r.limitPolicy)!=null?i:u)(async()=>r.enhanceOne({parameter:t,parameterName:n,component:o,context:a}));s===null?delete o.parameters[n]:typeof s=="undefined"?o.parameters[n]={...t,value:t.value}:o.parameters[n]={...t,value:s}}catch(c){let s=`Component ${C(e)} (type: ${o.type}): enhancing parameter ${n} (type: ${t.type}) threw exception. Parameter will be removed.`;return delete o.parameters[n],{message:s,error:c}}}var ee=(o,...e)=>({enhanceOne:t=>{let r=o.enhanceOne(t);for(let a of e){let i=O(r)?r:Promise.resolve(r),c="enhanceOne"in a?a.enhanceOne:a;r=i.then(s=>c({...t,parameter:{type:t.parameter.type,value:s}}))}return r},completeAll:()=>{var t,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=(t=o.completeAll)==null?void 0:t.call(o))!=null?r:Promise.resolve(0)}});function O(o){return!!o&&(typeof o=="object"||typeof o=="function")&&typeof o.then=="function"}var te=o=>o.startsWith("$");function ae(o){return o?o.map(e=>{var n,t;return{...e,intentTag:(t=(n=e.parameters)==null?void 0:n[A])==null?void 0:t.value}}):[]}var _="https://js.pusher.com/7.0.3/pusher.min.js";async function L(){if(!(typeof document=="undefined"||typeof window=="undefined"))return window.Pusher?window.Pusher:new Promise((o,e)=>{let n=setTimeout(()=>{window.Pusher&&o(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),o(window.Pusher)}),document.head.appendChild(t)})}async function ie(){let o=await L();if(!o)return;let e=window.__UNIFORM_EVENT_BUS__;if(!e){let n=new o("7b5f5abd160fea549ffe",{cluster:"mt1"});n.connect(),console.log("[canvas] \u{1F525} preview connected"),e=window.__UNIFORM_EVENT_BUS__={subscribe:t=>{let r=n.subscribe(t);return{unsubscribe:()=>n.unsubscribe(t),addEventHandler:(a,i)=>(r.bind(a,i),()=>r.unbind(a,i))}}}}return e}function b(o,e,n){return`${o}.${e}@${n}`}function le({projectId:o,compositionId:e,compositionState:n=0,eventBus:{subscribe:t},callback:r,event:a="updated"}){let i=b(o,e,n),c=t(i),s=c.addEventHandler(a,r);return()=>{s(),c.unsubscribe()}}function M({component:o}){var t;let e={},n=(t=o.slots)==null?void 0:t[w];return n==null||n.forEach(r=>{var i;let a=(i=r.parameters)==null?void 0:i[x];(a==null?void 0:a.value)&&typeof a.value=="string"&&(e[a.value]=e[a.value]||[],e[a.value].push(r))}),e}function fe({composition:o,locale:e}){f(o,(n,t,r)=>{if(n.type===v){let a=M({component:n}),i=typeof e=="string"?e:e({component:n,locales:a}),c;if(i&&(c=a[i]),c==null?void 0:c.length){let[s,...p]=c;r.replaceComponent(s),p.length&&r.insertAfter(p)}else r.removeComponent()}})}export{T as BatchEntry,z as CANVAS_DRAFT_STATE,A as CANVAS_INTENT_TAG_PARAM,x as CANVAS_LOCALE_TAG_PARAM,w as CANVAS_LOCALIZATION_SLOT,v as CANVAS_LOCALIZATION_TYPE,U as CANVAS_PERSONALIZE_SLOT,$ as CANVAS_PERSONALIZE_TYPE,W as CANVAS_PUBLISHED_STATE,V as CANVAS_TEST_SLOT,N as CANVAS_TEST_TYPE,F as CanvasClient,k as CanvasClientError,E as ChildEnhancerBuilder,R as EnhancerBuilder,I as UniqueBatchEntries,ee as compose,q as createBatchEnhancer,ie as createEventBus,j as createLimitPolicy,J as enhance,M as extractLocales,b as getChannelName,C as getComponentPath,te as isSystemComponentDefinition,fe as localize,ae as mapSlotToPersonalizedVariations,u as nullLimitPolicy,le as subscribeToComposition,f as walkComponentTree};
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@uniformdev/canvas",
|
3
|
-
"version": "
|
3
|
+
"version": "14.0.1-alpha.101+61fc2a31",
|
4
4
|
"description": "Common functionality and types for Uniform Canvas",
|
5
5
|
"license": "SEE LICENSE IN LICENSE.txt",
|
6
6
|
"main": "./dist/index.js",
|
@@ -41,30 +41,30 @@
|
|
41
41
|
"ci:build": "tsup --minify --clean"
|
42
42
|
},
|
43
43
|
"devDependencies": {
|
44
|
-
"@types/diff": "5.0.
|
45
|
-
"@types/jest": "27.0
|
44
|
+
"@types/diff": "5.0.2",
|
45
|
+
"@types/jest": "27.4.0",
|
46
46
|
"@types/js-yaml": "4.0.5",
|
47
47
|
"@types/lodash.isequalwith": "4.4.6",
|
48
|
-
"@types/node": "16.11.
|
49
|
-
"@types/yargs": "17.0.
|
50
|
-
"@uniformdev/cli": "^
|
51
|
-
"eslint": "8.
|
52
|
-
"eslint-plugin-react": "7.
|
48
|
+
"@types/node": "16.11.21",
|
49
|
+
"@types/yargs": "17.0.8",
|
50
|
+
"@uniformdev/cli": "^14.0.1-alpha.101+61fc2a31",
|
51
|
+
"eslint": "8.7.0",
|
52
|
+
"eslint-plugin-react": "7.28.0",
|
53
53
|
"eslint-plugin-react-hooks": "4.3.0",
|
54
|
-
"jest": "27.4.
|
54
|
+
"jest": "27.4.7",
|
55
55
|
"npm-run-all": "4.1.5",
|
56
56
|
"pusher-js": "7.0.3",
|
57
57
|
"rimraf": "3.0.2",
|
58
|
-
"ts-jest": "27.1.
|
59
|
-
"tsup": "5.11.
|
60
|
-
"yargs": "17.3.
|
58
|
+
"ts-jest": "27.1.3",
|
59
|
+
"tsup": "5.11.11",
|
60
|
+
"yargs": "17.3.1"
|
61
61
|
},
|
62
62
|
"peerDependencies": {
|
63
63
|
"yargs": "^17.0.1"
|
64
64
|
},
|
65
65
|
"dependencies": {
|
66
|
-
"@uniformdev/optimize-common": "^
|
67
|
-
"@uniformdev/optimize-tracker-common": "^
|
66
|
+
"@uniformdev/optimize-common": "^14.0.1-alpha.101+61fc2a31",
|
67
|
+
"@uniformdev/optimize-tracker-common": "^14.0.1-alpha.101+61fc2a31",
|
68
68
|
"chalk": "^4.1.2",
|
69
69
|
"diff": "^5.0.0",
|
70
70
|
"isomorphic-unfetch": "^3.1.0",
|
@@ -80,5 +80,5 @@
|
|
80
80
|
"publishConfig": {
|
81
81
|
"access": "public"
|
82
82
|
},
|
83
|
-
"gitHead": "
|
83
|
+
"gitHead": "61fc2a311b553e21d03b1b70ec6db0ada73974b7"
|
84
84
|
}
|