@uniformdev/mesh-sdk 17.6.1-alpha.60 → 17.7.1-alpha.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,27 +1,15 @@
1
- import { DataSource, DataType, DataResourceVariables, RootComponentInstance, ComponentInstance, ComponentDefinition, ComponentDefinitionParameter } from '@uniformdev/canvas';
1
+ import { DataSource, RootComponentInstance, ComponentInstance, ComponentDefinition, ComponentDefinitionParameter, DataType as DataType$1, DataResourceVariables } from '@uniformdev/canvas';
2
+ import { DataType } from '@uniformdev/canvas/.';
2
3
  import { Emitter } from 'mitt';
3
4
 
4
- declare type DataTypeValue = Pick<DataType, 'body' | 'method' | 'path' | 'custom' | 'headers' | 'parameters' | 'variables'>;
5
- declare type DataConnectorInfo = {
6
- type: string;
7
- displayName: string;
8
- installedIntegrationId: string;
9
- };
10
- declare type DataTypeLocationMetadata<TIntegrationConfiguration = unknown> = {
11
- settings: TIntegrationConfiguration;
12
- projectId: string;
13
- dataSource: DataSource;
14
- dataConnector: DataConnectorInfo;
15
- };
16
- declare type DataTypeLocation = MeshLocationCore<DataTypeValue, DataTypeLocationMetadata, DataTypeValue, 'dataType'>;
17
-
18
- declare type DataTypeInstanceLocationMetadata<TIntegrationConfiguration = unknown> = {
5
+ declare type DataSourceLocationValue = Pick<DataSource, 'baseUrl' | 'custom' | 'headers' | 'parameters' | 'variables'>;
6
+ declare type DataSourceLocationMetadata<TIntegrationConfiguration = unknown> = {
7
+ /** Settings defined at the integration level (arbitrary type used on settings location) */
19
8
  settings: TIntegrationConfiguration;
20
- dataType: DataType;
21
- dataConnector: DataConnectorInfo;
9
+ /** The Uniform project ID */
22
10
  projectId: string;
23
11
  };
24
- declare type DataTypeInstanceLocation = MeshLocationCore<DataResourceVariables, DataTypeInstanceLocationMetadata, DataResourceVariables, 'dataTypeInstance'>;
12
+ declare type DataSourceLocation = MeshLocationCore<DataSourceLocationValue, DataSourceLocationMetadata, DataSourceLocationValue, 'dataSource'>;
25
13
 
26
14
  declare type ParamTypeLocationMetadata<TParamConfiguration = unknown, TIntegrationConfiguration = unknown> = {
27
15
  rootNode: Omit<RootComponentInstance, 'slots' | '_data'>;
@@ -29,7 +17,9 @@ declare type ParamTypeLocationMetadata<TParamConfiguration = unknown, TIntegrati
29
17
  component: Omit<ComponentInstance, 'slots' | '_parameters' | '_id'>;
30
18
  componentDefinitions: Record<string, ComponentDefinition | undefined>;
31
19
  parameterDefinition: ComponentDefinitionParameter;
20
+ /** Settings defined at the integration level (arbitrary type used on settings location) */
32
21
  settings: TIntegrationConfiguration;
22
+ /** The Uniform project ID */
33
23
  projectId: string;
34
24
  };
35
25
  declare type ParamTypeLocation<TParamValue = unknown, TParamConfiguration = unknown, TParamSetValue = TParamValue, TIntegrationConfiguration = unknown> = MeshLocationCore<TParamValue, ParamTypeLocationMetadata<TParamConfiguration, TIntegrationConfiguration>, TParamSetValue, 'paramType'>;
@@ -40,7 +30,7 @@ declare type SettingsLocation<TSettingsType> = MeshLocationCore<TSettingsType, u
40
30
  * Defines methods used for interacting with a Mesh location
41
31
  * To receive useful typings, check the `type` property of the location to narrow the typing.
42
32
  */
43
- declare type MeshLocation<TValue = unknown, TSetValue = TValue> = ParamTypeLocation<TValue, unknown, TSetValue> | ParamTypeConfigLocation<TValue> | SettingsLocation<TValue> | DataSourceLocation | DataTypeLocation | DataTypeInstanceLocation;
33
+ declare type MeshLocation<TValue = unknown, TSetValue = TValue> = ParamTypeLocation<TValue, unknown, TSetValue> | ParamTypeConfigLocation<TValue> | SettingsLocation<TValue> | DataSourceLocation | DataTypeLocation | DataTypeInstanceLocation | DataResourceLocation;
44
34
  interface MeshContextData {
45
35
  locationKey: string;
46
36
  locationType: MeshLocationTypes;
@@ -123,7 +113,38 @@ declare type ValidationResult = {
123
113
  } | {
124
114
  isValid: true;
125
115
  };
116
+ declare type OpenDialogMessage = {
117
+ dialogType: DialogType;
118
+ dialogData: unknown;
119
+ options?: DialogOptions;
120
+ };
121
+ declare type CloseDialogMessage = {
122
+ dialogId: string | undefined;
123
+ dialogType: DialogType;
124
+ dialogData?: unknown;
125
+ };
126
+ declare type GetDataResourceMessage = Pick<DataType, 'path' | 'headers' | 'parameters' | 'body' | 'method'>;
126
127
 
128
+ /**
129
+ * Imports the iframe communications library and provides an interface for interacting with
130
+ * the parent window via said communications library.
131
+ */
132
+ declare function connectToParent({ dialogResponseHandlers, }: {
133
+ dialogResponseHandlers: DialogResponseHandlers;
134
+ }): Promise<{
135
+ initData: MeshContextData;
136
+ parent: {
137
+ resize: (height: CSSHeight) => Promise<void>;
138
+ getValue: () => Promise<unknown>;
139
+ setValue: (value: unknown, options?: SetValueOptions) => Promise<void>;
140
+ getMetadata: () => Promise<unknown>;
141
+ openDialog: (message: OpenDialogMessage) => Promise<Pick<DialogResponseData, "value" | "dialogId"> | undefined>;
142
+ closeDialog: (message: CloseDialogMessage) => Promise<void>;
143
+ getDataResource: <TExpectedResult>(message: GetDataResourceMessage) => Promise<TExpectedResult>;
144
+ };
145
+ }>;
146
+
147
+ declare type SetLocationFunction<TSetValue> = (value: TSetValue, options?: SetValueOptions) => Promise<void> | void;
127
148
  /** Core shared generic for a mesh location context */
128
149
  interface MeshLocationCore<TValue = unknown, TMetadata = unknown, TSetValue = TValue, TType extends MeshLocationTypes = MeshLocationTypes> {
129
150
  /** The current location type (where in the Uniform app the mesh app is rendering) */
@@ -139,7 +160,7 @@ interface MeshLocationCore<TValue = unknown, TMetadata = unknown, TSetValue = TV
139
160
  * All locations other than 'settings' update into a parent form state and should be updated live as changes occur in the Mesh app.
140
161
  * The 'settings' location writes to the database each time its value is set, and it should be treated as a form with a submit button.
141
162
  */
142
- setValue: (value: TSetValue, options?: SetValueOptions) => Promise<void>;
163
+ setValue: SetLocationFunction<TSetValue>;
143
164
  /** @deprecated use metadata property instead */
144
165
  getMetadata: () => TMetadata;
145
166
  /**
@@ -172,18 +193,66 @@ interface MeshLocationCore<TValue = unknown, TMetadata = unknown, TSetValue = TV
172
193
  /**
173
194
  * Known location types that can be passed to a mesh location
174
195
  */
175
- declare type MeshLocationTypes = 'paramType' | 'paramTypeConfig' | 'settings' | 'dataSource' | 'dataType' | 'dataTypeInstance';
196
+ declare type MeshLocationTypes = 'paramType' | 'paramTypeConfig' | 'settings' | 'dataSource' | 'dataType'
197
+ /** @deprecated use dataResource */
198
+ | 'dataTypeInstance' | 'dataResource';
176
199
  declare type SetValueOptions = ValidationResult;
200
+ declare type SetValueMessage = {
201
+ uniformMeshLocationValue: unknown;
202
+ options?: SetValueOptions;
203
+ };
204
+ declare type GetDataResourceLocation = {
205
+ getDataResource: Awaited<ReturnType<typeof connectToParent>>['parent']['getDataResource'];
206
+ };
177
207
 
178
- declare type DataSourceLocationValue = Pick<DataSource, 'baseUrl' | 'custom' | 'headers' | 'parameters' | 'variables'>;
179
- declare type DataSourceLocationMetadata<TIntegrationConfiguration = unknown> = {
208
+ declare type DataTypeLocationValue = Pick<DataType$1, 'body' | 'method' | 'path' | 'custom' | 'headers' | 'parameters' | 'variables'>;
209
+ declare type DataConnectorInfo = {
210
+ type: string;
211
+ displayName: string;
212
+ installedIntegrationId: string;
213
+ };
214
+ declare type DataTypeLocationMetadata<TIntegrationConfiguration = unknown> = {
215
+ /** Settings defined at the integration level (arbitrary type used on settings location) */
216
+ settings: TIntegrationConfiguration;
217
+ /** The Uniform project ID */
218
+ projectId: string;
219
+ /**
220
+ * The current data type's data source. NOTE: param and header values are not available in this context.
221
+ */
222
+ dataSource: DataSource;
223
+ /** The data connector type of the current data type's data source */
224
+ dataConnector: DataConnectorInfo;
225
+ /** The data type's archetype value. */
226
+ archetype: string;
227
+ };
228
+ declare type DataTypeLocation = MeshLocationCore<DataTypeLocationValue, DataTypeLocationMetadata, DataTypeLocationValue, 'dataType'> & GetDataResourceLocation;
229
+
230
+ /** @deprecated use DataResourceLocationMetadata */
231
+ declare type DataTypeInstanceLocationMetadata<TIntegrationConfiguration = unknown> = DataResourceLocationMetadata<TIntegrationConfiguration>;
232
+ declare type DataResourceLocationMetadata<TIntegrationConfiguration = unknown> = {
233
+ /** Settings defined at the integration level (arbitrary type used on settings location) */
180
234
  settings: TIntegrationConfiguration;
235
+ /** The current data resource's data type */
236
+ dataType: DataType$1;
237
+ /** The data type's archetype value. */
238
+ archetype: string;
239
+ /**
240
+ * The current data resource's data source. NOTE: param and header values are not available in this context.
241
+ */
242
+ dataSource: DataSource;
243
+ /** The data connector type of the current data resource's data source */
244
+ dataConnector: DataConnectorInfo;
245
+ /** The Uniform project ID */
181
246
  projectId: string;
182
247
  };
183
- declare type DataSourceLocation = MeshLocationCore<DataSourceLocationValue, DataSourceLocationMetadata, DataSourceLocationValue, 'dataSource'>;
248
+ declare type DataResourceLocation = MeshLocationCore<DataResourceVariables, DataResourceLocationMetadata, DataResourceVariables, 'dataResource'> & GetDataResourceLocation;
249
+ /** @deprecated use DataResourceLocation */
250
+ declare type DataTypeInstanceLocation = MeshLocationCore<DataResourceVariables, DataResourceLocationMetadata, DataResourceVariables, 'dataTypeInstance'>;
184
251
 
185
252
  declare type ParamTypeConfigLocationMetadata<TIntegrationConfiguration = unknown> = {
253
+ /** Settings defined at the integration level (arbitrary type used on settings location) */
186
254
  settings: TIntegrationConfiguration;
255
+ /** The Uniform project ID */
187
256
  projectId: string;
188
257
  };
189
258
  declare type ParamTypeConfigLocation<TParamValue = unknown, TIntegrationConfiguration = unknown> = MeshLocationCore<TParamValue | undefined, ParamTypeConfigLocationMetadata<TIntegrationConfiguration>, TParamValue, 'paramTypeConfig'>;
@@ -283,4 +352,4 @@ declare function initializeUniformMeshSDK({ autoResizingDisabled, }?: {
283
352
  autoResizingDisabled?: boolean;
284
353
  }): Promise<UniformMeshSDK | undefined>;
285
354
 
286
- export { CSSHeight, CloseLocationDialogOptions, DataConnectorInfo, DataSourceLocation, DataSourceLocationMetadata, DataSourceLocationValue, DataTypeInstanceLocation, DataTypeInstanceLocationMetadata, DataTypeLocation, DataTypeLocationMetadata, DialogContext, DialogOptions, DialogParamValue, DialogParams, DialogResponseData, DialogResponseHandler, DialogResponseHandlers, DialogType, LocationDialogResponse, MeshContextData, MeshLocation, MeshLocationCore, MeshLocationTypes, OpenConfirmationDialogOptions, OpenConfirmationDialogResult, OpenDialogResult, OpenLocationDialogOptions, ParamTypeConfigLocation, ParamTypeConfigLocationMetadata, ParamTypeLocation, ParamTypeLocationMetadata, SdkWindow, SetValueOptions, SettingsLocation, UniformMeshSDK, UniformMeshSDKEvents, ValidationResult, initializeUniformMeshSDK };
355
+ export { CSSHeight, CloseDialogMessage, CloseLocationDialogOptions, DataConnectorInfo, DataResourceLocation, DataResourceLocationMetadata, DataSourceLocation, DataSourceLocationMetadata, DataSourceLocationValue, DataTypeInstanceLocation, DataTypeInstanceLocationMetadata, DataTypeLocation, DataTypeLocationMetadata, DataTypeLocationValue, DialogContext, DialogOptions, DialogParamValue, DialogParams, DialogResponseData, DialogResponseHandler, DialogResponseHandlers, DialogType, GetDataResourceLocation, GetDataResourceMessage, LocationDialogResponse, MeshContextData, MeshLocation, MeshLocationCore, MeshLocationTypes, OpenConfirmationDialogOptions, OpenConfirmationDialogResult, OpenDialogMessage, OpenDialogResult, OpenLocationDialogOptions, ParamTypeConfigLocation, ParamTypeConfigLocationMetadata, ParamTypeLocation, ParamTypeLocationMetadata, SdkWindow, SetLocationFunction, SetValueMessage, SetValueOptions, SettingsLocation, UniformMeshSDK, UniformMeshSDKEvents, ValidationResult, initializeUniformMeshSDK };
package/dist/index.esm.js CHANGED
@@ -1 +1 @@
1
- import P from"mitt";var S=(n,e)=>e?{log(o,...t){return console.log(`${n}: ${o}`,...t)},error(o,...t){return console.error(`${n}: ${o}`,...t)}}:{log(){},error(){}};var E=5e3;var d=class extends Error{constructor(){super("Request timed out"),Object.setPrototypeOf(this,d.prototype),this.name="RequestTimeoutError"}},g=class extends Error{constructor(){super("Client destroyed"),Object.setPrototypeOf(this,g.prototype),this.name="ClientDestroyedError"}};var T=()=>{let n=()=>{},e=()=>{},o=new Promise((t,i)=>{n=t,e=i});return{resolve:n,reject:e,promise:o}},p=(n=16)=>[...Array(n)].map(()=>(~~(Math.random()*36)).toString(36)).join(""),u=(n,e)=>{let{[e]:o,...t}=n;return t},L=n=>({message:n.message,name:n.name,stack:n.stack}),V=({name:n,message:e,stack:o})=>{switch(n){case d.name:return new d;default:{let t=new Error(e);return t.name=n,t.stack=o,t}}},w=n=>{let e=n.data,o="none";return e instanceof Error&&(o="error",e=L(e)),{...n,serialization:o,data:e}},v=n=>n.serialization==="error"?{...n,data:V(n.data)}:n;var h=class{constructor({debug:e=!1,requestTimeout:o=E}={}){this.debug=e,this.requestTimeout=o,this.channel=T(),this.eventSubscriptions={},this.responseSubscriptions={},this.requestSubscriptions={},this.onDestroyRequestHandlers={},this.destroyed=!1,this.logger=this.getLogger(),this.getChannel().then(()=>{this.logger.log("Secure parent <-> child channel established")}).catch(t=>{this.logger.log(t)})}async send(e,o){return this.postMessage("event",e,o)}on(e,o){this.eventSubscriptions[e]||(this.eventSubscriptions[e]={});let t=p(8);return this.eventSubscriptions[e][t]=o,this.logger.log(`Registered handler for event "${e}"`),()=>{this.eventSubscriptions[e]=u(this.eventSubscriptions[e],t),this.logger.log(`Unsubscribed handler for event ${e}`)}}async request(e,o,t={}){let a=(await this.postMessage("request",e,o)).id,s=()=>{this.responseSubscriptions=u(this.responseSubscriptions,a)},r=()=>{this.onDestroyRequestHandlers=u(this.responseSubscriptions,a)};return new Promise((l,c)=>{let y,x=(R,O)=>{clearTimeout(y),s(),r(),O.type==="error_response"?c(R):l(R)},C=()=>{clearTimeout(y),c(new g)};this.responseSubscriptions[a]=x,this.onDestroyRequestHandlers[a]=C,y=setTimeout(()=>{s(),r(),c(new d)},t.timeout||this.requestTimeout)})}onRequest(e,o){let t=async(i,a)=>{try{let s=await o(i,a);this.postMessage("response",e,s,a.id)}catch(s){this.postMessage("error_response",e,s,a.id)}};return this.requestSubscriptions[e]=t,()=>{this.requestSubscriptions=u(this.requestSubscriptions,e)}}async getChannel(){if(await this.channel.promise,this.destroyed)throw new g;return this.channel.promise}async messageListener(e){try{await this.getChannel();let o=this.isValidMessage(e),t=v(e.data);if(o)switch(t.type){case"event":{this.handleEvent(t);break}case"request":{this.handleRequest(t);break}case"error_response":case"response":{this.handleResponse(t);break}}else this.logger.error("Invalid message format. Skipping.")}catch(o){this.logger.error(o)}}handleEvent(e){let o=this.eventSubscriptions[e.key];o&&Object.values(o).forEach(t=>t(e.data,e))}handleRequest(e){let o=this.requestSubscriptions[e.key];o&&(o(e.data,e),this.logger.log(`Handled request type ${e.key}`))}handleResponse(e){let o=e.requestId,t=o&&this.responseSubscriptions[o];t&&t(e.data,e)}async postMessage(e,o,t,i){let{port:a}=await this.getChannel();if(this.destroyed)throw new g;let s=w({type:e,apiVersion:"framepost/v1",key:o,data:t,id:p(),requestId:i});return this.logger.log("posting message from child to parent",s),a.postMessage(s),s}initListener(e){this.isInitMessage(e)?(this.onChannelInit(e),this.messagePort&&(this.messagePort.onmessage=this.messageListener.bind(this)),this.resolveChannel(e)):this.logger.error("Invalid message format. Skipping.")}isValidMessage(e){let o=e.data;return o.type&&o.id&&o.apiVersion==="framepost/v1"}isInitMessage(e){return this.isValidMessage(e)&&e.data.type==="channel_init"}resolveChannel(e){if(this.messagePort){let o={port:this.messagePort,origin:e.origin,context:e.data.data};this.channel.resolve(o)}}getInitMessage(e){return w({type:"channel_init",apiVersion:"framepost/v1",key:"",data:e,id:p()})}destroy(){this.destroyed=!0,this.channel.reject(new g),this.messagePort&&this.messagePort.close(),Object.values(this.onDestroyRequestHandlers).forEach(e=>e())}};var m=class extends h{constructor(o={}){super(o);this.context=o.context||null,this.initListener=this.initListener.bind(this),window.addEventListener("message",this.initListener)}getLogger(){return S("child-client",this.debug)}onChannelInit(o){window.removeEventListener("message",this.initListener),this.messagePort=o.ports[0];let t=this.getInitMessage(this.context);this.logger.log("channel init, posting init message from child to parent",t),this.messagePort.postMessage(t)}destroy(){super.destroy(),window.removeEventListener("message",this.initListener)}};async function b({dialogResponseHandlers:n}){let e=new m({debug:!1});window.parent.postMessage("parents just don't understand","*");let o=await e.request("initialize");return e.onRequest("dialog-value",async t=>{let i=n[t.dialogId];!i||(t.value?i.resolve({value:t.value,dialogId:t.dialogId}):t.error&&i.reject(t.error),delete n[t.dialogId])}),{initData:o,parent:{resize:async t=>{e.request("resize",{height:t})},getValue:async()=>{let t=await e.request("getValue");return t==null?void 0:t.data},setValue:async(t,i)=>{await e.request("setValue",{uniformMeshLocationValue:t,options:i})},setValidationResult:async t=>{await e.request("setValidationResult",{value:t})},getMetadata:async()=>{let t=await e.request("getMetadata");return t==null?void 0:t.data},openDialog:async({dialogType:t,data:i,options:a})=>{if(k(a==null?void 0:a.params)>1e5)throw new Error("Dialog parameters object is too large, maximum size is 100KB");let s=await e.request("openDialog",{dialogType:t,dialogData:i,options:a}),r=s==null?void 0:s.dialogId;if(!!r)return new Promise((l,c)=>{n[r]={resolve:l,reject:c}})},closeDialog:async({dialogId:t,dialogType:i,dialogData:a})=>{await e.request("closeDialog",{dialogId:t,dialogType:i,dialogData:a})}}}}function k(n){if(!n||typeof Blob=="undefined")return 0;try{let e=JSON.stringify(n);return new Blob([e]).size}catch(e){throw new Error("Error calculating object size: "+e.message)}}var f,M=({onHeightChange:n,autoResizingDisabled:e})=>{if(typeof window=="undefined")return;let o=window,t=r=>{if(r&&r!==f){f=r,n==null||n(r);return}let l=`${Math.ceil(o.document.documentElement.getBoundingClientRect().height)}px`;l!==f&&(f=l,n==null||n(l))},i=()=>{t()},a=e?void 0:new MutationObserver(i),s={instance:o,height:o.document.documentElement.getBoundingClientRect().height,observer:a,enableAutoResizing:()=>{a==null||a.observe(document.body,{attributes:!0,childList:!0,subtree:!0,characterData:!0}),o.addEventListener("resize",i)},disableAutoResizing:()=>{a==null||a.disconnect(),o.removeEventListener("resize",i)},updateHeight:t};return e||s.enableAutoResizing(),s};var I={},D=!1;async function ie({autoResizingDisabled:n}={}){var e;if(typeof window!="undefined"&&typeof window.UniformMeshSDK=="undefined"&&!D){if(typeof window.parent=="undefined"||window.parent==window)throw new Error("It appears you are trying to connect with the Uniform Mesh SDK outside of an iframe. Be sure you are loading your app via a location URL configured in the Uniform dashboard.");D=!0;let o=await b({dialogResponseHandlers:I}),{initData:t,parent:i}=o,a={events:P(),getCurrentLocation:()=>{let s={type:t.locationType,isReadOnly:t.isReadOnly,getValue:()=>s.value,value:t.locationValue,setValue:async(r,l)=>{t.dialogContext&&console.warn("Using setValue() inside a dialog is deprecated. Use dialogContext.returnDialogValue() instead."),t.locationValue=r,a.events.emit("onValueChanged",{newValue:r}),await i.setValue(r,l)},getMetadata:()=>t.locationMetadata,metadata:t.locationMetadata,setValidationResult:async r=>{await i.setValidationResult(r)},dialogContext:t.dialogContext?{...t.dialogContext,params:t.locationMetadata.dialogParams,returnDialogValue:async r=>{t.locationValue=r,a.events.emit("onValueChanged",{newValue:r}),await i.setValue(r)}}:void 0};return s},currentWindow:M({onHeightChange:s=>{i.resize(s)},autoResizingDisabled:(e=t.dialogContext)!=null&&e.contentHeight?!0:n}),version:t.uniformApiVersion,openLocationDialog:async({locationKey:s,options:r})=>{let l=await i.openDialog({dialogType:"location",data:{locationKey:s},options:r});if(!!l)return{dialogId:l.dialogId,value:l.value,closeDialog:async()=>{await i.closeDialog({dialogId:l.dialogId,dialogType:"location"})}}},async closeLocationDialog({dialogId:s}){await i.closeDialog({dialogId:s,dialogType:"location"})},openConfirmationDialog:async({titleText:s,bodyText:r})=>{let l=await i.openDialog({dialogType:"confirm",data:{titleText:s,bodyText:r}});if(!!l)return{dialogId:l.dialogId,value:l.value,closeDialog:async()=>{await i.closeDialog({dialogId:void 0,dialogType:"confirm"})}}},openCurrentLocationDialog:async s=>{let r=await i.openDialog({dialogType:"location",data:{},options:s==null?void 0:s.options});if(!!r)return{dialogId:r.dialogId,value:r.value,closeDialog:async()=>{await i.closeDialog({dialogId:void 0,dialogType:"location"})}}},closeCurrentLocationDialog:async()=>{await i.closeDialog({dialogId:void 0,dialogType:"location"})},dialogContext:t.dialogContext};return window.UniformMeshSDK=a,D=!1,a}}export{ie as initializeUniformMeshSDK};
1
+ import I from"mitt";var S=(n,e)=>e?{log(o,...t){return console.log(`${n}: ${o}`,...t)},error(o,...t){return console.error(`${n}: ${o}`,...t)}}:{log(){},error(){}};var E=5e3;var d=class extends Error{constructor(){super("Request timed out"),Object.setPrototypeOf(this,d.prototype),this.name="RequestTimeoutError"}},c=class extends Error{constructor(){super("Client destroyed"),Object.setPrototypeOf(this,c.prototype),this.name="ClientDestroyedError"}};var T=()=>{let n=()=>{},e=()=>{},o=new Promise((t,s)=>{n=t,e=s});return{resolve:n,reject:e,promise:o}},u=(n=16)=>[...Array(n)].map(()=>(~~(Math.random()*36)).toString(36)).join(""),g=(n,e)=>{let{[e]:o,...t}=n;return t},L=n=>({message:n.message,name:n.name,stack:n.stack}),V=({name:n,message:e,stack:o})=>{switch(n){case d.name:return new d;default:{let t=new Error(e);return t.name=n,t.stack=o,t}}},D=n=>{let e=n.data,o="none";return e instanceof Error&&(o="error",e=L(e)),{...n,serialization:o,data:e}},M=n=>n.serialization==="error"?{...n,data:V(n.data)}:n;var p=class{constructor({debug:e=!1,requestTimeout:o=E}={}){this.debug=e,this.requestTimeout=o,this.channel=T(),this.eventSubscriptions={},this.responseSubscriptions={},this.requestSubscriptions={},this.onDestroyRequestHandlers={},this.destroyed=!1,this.logger=this.getLogger(),this.getChannel().then(()=>{this.logger.log("Secure parent <-> child channel established")}).catch(t=>{this.logger.log(t)})}async send(e,o){return this.postMessage("event",e,o)}on(e,o){this.eventSubscriptions[e]||(this.eventSubscriptions[e]={});let t=u(8);return this.eventSubscriptions[e][t]=o,this.logger.log(`Registered handler for event "${e}"`),()=>{this.eventSubscriptions[e]=g(this.eventSubscriptions[e],t),this.logger.log(`Unsubscribed handler for event ${e}`)}}async request(e,o,t={}){let a=(await this.postMessage("request",e,o)).id,i=()=>{this.responseSubscriptions=g(this.responseSubscriptions,a)},r=()=>{this.onDestroyRequestHandlers=g(this.responseSubscriptions,a)};return new Promise((l,f)=>{let y,x=(R,O)=>{clearTimeout(y),i(),r(),O.type==="error_response"?f(R):l(R)},C=()=>{clearTimeout(y),f(new c)};this.responseSubscriptions[a]=x,this.onDestroyRequestHandlers[a]=C,y=setTimeout(()=>{i(),r(),f(new d)},t.timeout||this.requestTimeout)})}onRequest(e,o){let t=async(s,a)=>{try{let i=await o(s,a);this.postMessage("response",e,i,a.id)}catch(i){this.postMessage("error_response",e,i,a.id)}};return this.requestSubscriptions[e]=t,()=>{this.requestSubscriptions=g(this.requestSubscriptions,e)}}async getChannel(){if(await this.channel.promise,this.destroyed)throw new c;return this.channel.promise}async messageListener(e){try{await this.getChannel();let o=this.isValidMessage(e),t=M(e.data);if(o)switch(t.type){case"event":{this.handleEvent(t);break}case"request":{this.handleRequest(t);break}case"error_response":case"response":{this.handleResponse(t);break}}else this.logger.error("Invalid message format. Skipping.")}catch(o){this.logger.error(o)}}handleEvent(e){let o=this.eventSubscriptions[e.key];o&&Object.values(o).forEach(t=>t(e.data,e))}handleRequest(e){let o=this.requestSubscriptions[e.key];o&&(o(e.data,e),this.logger.log(`Handled request type ${e.key}`))}handleResponse(e){let o=e.requestId,t=o&&this.responseSubscriptions[o];t&&t(e.data,e)}async postMessage(e,o,t,s){let{port:a}=await this.getChannel();if(this.destroyed)throw new c;let i=D({type:e,apiVersion:"framepost/v1",key:o,data:t,id:u(),requestId:s});return this.logger.log("posting message from child to parent",i),a.postMessage(i),i}initListener(e){this.isInitMessage(e)?(this.onChannelInit(e),this.messagePort&&(this.messagePort.onmessage=this.messageListener.bind(this)),this.resolveChannel(e)):this.logger.error("Invalid message format. Skipping.")}isValidMessage(e){let o=e.data;return o.type&&o.id&&o.apiVersion==="framepost/v1"}isInitMessage(e){return this.isValidMessage(e)&&e.data.type==="channel_init"}resolveChannel(e){if(this.messagePort){let o={port:this.messagePort,origin:e.origin,context:e.data.data};this.channel.resolve(o)}}getInitMessage(e){return D({type:"channel_init",apiVersion:"framepost/v1",key:"",data:e,id:u()})}destroy(){this.destroyed=!0,this.channel.reject(new c),this.messagePort&&this.messagePort.close(),Object.values(this.onDestroyRequestHandlers).forEach(e=>e())}};var h=class extends p{constructor(o={}){super(o);this.context=o.context||null,this.initListener=this.initListener.bind(this),window.addEventListener("message",this.initListener)}getLogger(){return S("child-client",this.debug)}onChannelInit(o){window.removeEventListener("message",this.initListener),this.messagePort=o.ports[0];let t=this.getInitMessage(this.context);this.logger.log("channel init, posting init message from child to parent",t),this.messagePort.postMessage(t)}destroy(){super.destroy(),window.removeEventListener("message",this.initListener)}};async function v({dialogResponseHandlers:n}){let e=new h({debug:!1});window.parent.postMessage("parents just don't understand","*");let o=await e.request("initialize");return e.onRequest("dialog-value",async t=>{let s=n[t.dialogId];!s||(t.value?s.resolve({value:t.value,dialogId:t.dialogId}):t.error&&s.reject(t.error),delete n[t.dialogId])}),{initData:o,parent:{resize:async t=>{await e.request("resize",{height:t})},getValue:async()=>{let t=await e.request("getValue");return t==null?void 0:t.data},setValue:async(t,s)=>{let a={uniformMeshLocationValue:t,options:s};await e.request("setValue",a)},getMetadata:async()=>{let t=await e.request("getMetadata");return t==null?void 0:t.data},openDialog:async t=>{var i;if(P((i=t.options)==null?void 0:i.params)>1e5)throw new Error("Dialog parameters object is too large, maximum size is 100KB");let s=await e.request("openDialog",t),a=s==null?void 0:s.dialogId;if(!!a)return new Promise((r,l)=>{n[a]={resolve:r,reject:l}})},closeDialog:async t=>{await e.request("closeDialog",t)},getDataResource:async t=>await e.request("getDataResource",t,{timeout:3e4})}}}function P(n){if(!n||typeof Blob=="undefined")return 0;try{let e=JSON.stringify(n);return new Blob([e]).size}catch(e){throw new Error("Error calculating object size: "+e.message)}}var m,b=({onHeightChange:n,autoResizingDisabled:e})=>{if(typeof window=="undefined")return;let o=window,t=r=>{if(r&&r!==m){m=r,n==null||n(r);return}let l=`${Math.ceil(o.document.documentElement.getBoundingClientRect().height)}px`;l!==m&&(m=l,n==null||n(l))},s=()=>{t()},a=e?void 0:new MutationObserver(s),i={instance:o,height:o.document.documentElement.getBoundingClientRect().height,observer:a,enableAutoResizing:()=>{a==null||a.observe(document.body,{attributes:!0,childList:!0,subtree:!0,characterData:!0}),o.addEventListener("resize",s)},disableAutoResizing:()=>{a==null||a.disconnect(),o.removeEventListener("resize",s)},updateHeight:t};return e||i.enableAutoResizing(),i};var k={},w=!1;async function se({autoResizingDisabled:n}={}){var e;if(typeof window!="undefined"&&typeof window.UniformMeshSDK=="undefined"&&!w){if(typeof window.parent=="undefined"||window.parent==window)throw new Error("It appears you are trying to connect with the Uniform Mesh SDK outside of an iframe. Be sure you are loading your app via a location URL configured in the Uniform dashboard.");w=!0;let o=await v({dialogResponseHandlers:k}),{initData:t,parent:s}=o,a={events:I(),getCurrentLocation:()=>{let i={getDataResource:s.getDataResource,type:t.locationType,isReadOnly:t.isReadOnly,getValue:()=>i.value,value:t.locationValue,setValue:async(r,l)=>{t.dialogContext&&console.warn("Using setValue() inside a dialog is deprecated. Use dialogContext.returnDialogValue() instead."),t.locationValue=r,a.events.emit("onValueChanged",{newValue:r}),await s.setValue(r,l)},getMetadata:()=>t.locationMetadata,metadata:t.locationMetadata,setValidationResult:async r=>{await i.setValue(t.locationValue,r)},dialogContext:t.dialogContext?{...t.dialogContext,params:t.locationMetadata.dialogParams,returnDialogValue:async r=>{t.locationValue=r,a.events.emit("onValueChanged",{newValue:r}),await s.setValue(r)}}:void 0};return i},currentWindow:b({onHeightChange:i=>{s.resize(i)},autoResizingDisabled:(e=t.dialogContext)!=null&&e.contentHeight?!0:n}),version:t.uniformApiVersion,openLocationDialog:async({locationKey:i,options:r})=>{let l=await s.openDialog({dialogType:"location",dialogData:{locationKey:i},options:r});if(!!l)return{dialogId:l.dialogId,value:l.value,closeDialog:async()=>{await s.closeDialog({dialogId:l.dialogId,dialogType:"location"})}}},async closeLocationDialog({dialogId:i}){await s.closeDialog({dialogId:i,dialogType:"location"})},openConfirmationDialog:async({titleText:i,bodyText:r})=>{let l=await s.openDialog({dialogType:"confirm",dialogData:{titleText:i,bodyText:r}});if(!!l)return{dialogId:l.dialogId,value:l.value,closeDialog:async()=>{await s.closeDialog({dialogId:void 0,dialogType:"confirm"})}}},openCurrentLocationDialog:async i=>{let r=await s.openDialog({dialogType:"location",dialogData:{},options:i==null?void 0:i.options});if(!!r)return{dialogId:r.dialogId,value:r.value,closeDialog:async()=>{await s.closeDialog({dialogId:void 0,dialogType:"location"})}}},closeCurrentLocationDialog:async()=>{await s.closeDialog({dialogId:void 0,dialogType:"location"})},dialogContext:t.dialogContext};return window.UniformMeshSDK=a,w=!1,a}}export{se as initializeUniformMeshSDK};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var P=Object.create;var p=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var z=Object.getPrototypeOf,H=Object.prototype.hasOwnProperty;var N=(n,e)=>{for(var o in e)p(n,o,{get:e[o],enumerable:!0})},E=(n,e,o,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of q(e))!H.call(n,i)&&i!==o&&p(n,i,{get:()=>e[i],enumerable:!(t=I(e,i))||t.enumerable});return n};var U=(n,e,o)=>(o=n!=null?P(z(n)):{},E(e||!n||!n.__esModule?p(o,"default",{value:n,enumerable:!0}):o,n)),W=n=>E(p({},"__esModule",{value:!0}),n);var $={};N($,{initializeUniformMeshSDK:()=>j});module.exports=W($);var O=U(require("mitt"));var T=(n,e)=>e?{log(o,...t){return console.log(`${n}: ${o}`,...t)},error(o,...t){return console.error(`${n}: ${o}`,...t)}}:{log(){},error(){}};var v=5e3;var d=class extends Error{constructor(){super("Request timed out"),Object.setPrototypeOf(this,d.prototype),this.name="RequestTimeoutError"}},g=class extends Error{constructor(){super("Client destroyed"),Object.setPrototypeOf(this,g.prototype),this.name="ClientDestroyedError"}};var b=()=>{let n=()=>{},e=()=>{},o=new Promise((t,i)=>{n=t,e=i});return{resolve:n,reject:e,promise:o}},h=(n=16)=>[...Array(n)].map(()=>(~~(Math.random()*36)).toString(36)).join(""),u=(n,e)=>{let{[e]:o,...t}=n;return t},Q=n=>({message:n.message,name:n.name,stack:n.stack}),A=({name:n,message:e,stack:o})=>{switch(n){case d.name:return new d;default:{let t=new Error(e);return t.name=n,t.stack=o,t}}},D=n=>{let e=n.data,o="none";return e instanceof Error&&(o="error",e=Q(e)),{...n,serialization:o,data:e}},M=n=>n.serialization==="error"?{...n,data:A(n.data)}:n;var m=class{constructor({debug:e=!1,requestTimeout:o=v}={}){this.debug=e,this.requestTimeout=o,this.channel=b(),this.eventSubscriptions={},this.responseSubscriptions={},this.requestSubscriptions={},this.onDestroyRequestHandlers={},this.destroyed=!1,this.logger=this.getLogger(),this.getChannel().then(()=>{this.logger.log("Secure parent <-> child channel established")}).catch(t=>{this.logger.log(t)})}async send(e,o){return this.postMessage("event",e,o)}on(e,o){this.eventSubscriptions[e]||(this.eventSubscriptions[e]={});let t=h(8);return this.eventSubscriptions[e][t]=o,this.logger.log(`Registered handler for event "${e}"`),()=>{this.eventSubscriptions[e]=u(this.eventSubscriptions[e],t),this.logger.log(`Unsubscribed handler for event ${e}`)}}async request(e,o,t={}){let a=(await this.postMessage("request",e,o)).id,s=()=>{this.responseSubscriptions=u(this.responseSubscriptions,a)},r=()=>{this.onDestroyRequestHandlers=u(this.responseSubscriptions,a)};return new Promise((l,c)=>{let w,L=(S,k)=>{clearTimeout(w),s(),r(),k.type==="error_response"?c(S):l(S)},V=()=>{clearTimeout(w),c(new g)};this.responseSubscriptions[a]=L,this.onDestroyRequestHandlers[a]=V,w=setTimeout(()=>{s(),r(),c(new d)},t.timeout||this.requestTimeout)})}onRequest(e,o){let t=async(i,a)=>{try{let s=await o(i,a);this.postMessage("response",e,s,a.id)}catch(s){this.postMessage("error_response",e,s,a.id)}};return this.requestSubscriptions[e]=t,()=>{this.requestSubscriptions=u(this.requestSubscriptions,e)}}async getChannel(){if(await this.channel.promise,this.destroyed)throw new g;return this.channel.promise}async messageListener(e){try{await this.getChannel();let o=this.isValidMessage(e),t=M(e.data);if(o)switch(t.type){case"event":{this.handleEvent(t);break}case"request":{this.handleRequest(t);break}case"error_response":case"response":{this.handleResponse(t);break}}else this.logger.error("Invalid message format. Skipping.")}catch(o){this.logger.error(o)}}handleEvent(e){let o=this.eventSubscriptions[e.key];o&&Object.values(o).forEach(t=>t(e.data,e))}handleRequest(e){let o=this.requestSubscriptions[e.key];o&&(o(e.data,e),this.logger.log(`Handled request type ${e.key}`))}handleResponse(e){let o=e.requestId,t=o&&this.responseSubscriptions[o];t&&t(e.data,e)}async postMessage(e,o,t,i){let{port:a}=await this.getChannel();if(this.destroyed)throw new g;let s=D({type:e,apiVersion:"framepost/v1",key:o,data:t,id:h(),requestId:i});return this.logger.log("posting message from child to parent",s),a.postMessage(s),s}initListener(e){this.isInitMessage(e)?(this.onChannelInit(e),this.messagePort&&(this.messagePort.onmessage=this.messageListener.bind(this)),this.resolveChannel(e)):this.logger.error("Invalid message format. Skipping.")}isValidMessage(e){let o=e.data;return o.type&&o.id&&o.apiVersion==="framepost/v1"}isInitMessage(e){return this.isValidMessage(e)&&e.data.type==="channel_init"}resolveChannel(e){if(this.messagePort){let o={port:this.messagePort,origin:e.origin,context:e.data.data};this.channel.resolve(o)}}getInitMessage(e){return D({type:"channel_init",apiVersion:"framepost/v1",key:"",data:e,id:h()})}destroy(){this.destroyed=!0,this.channel.reject(new g),this.messagePort&&this.messagePort.close(),Object.values(this.onDestroyRequestHandlers).forEach(e=>e())}};var f=class extends m{constructor(o={}){super(o);this.context=o.context||null,this.initListener=this.initListener.bind(this),window.addEventListener("message",this.initListener)}getLogger(){return T("child-client",this.debug)}onChannelInit(o){window.removeEventListener("message",this.initListener),this.messagePort=o.ports[0];let t=this.getInitMessage(this.context);this.logger.log("channel init, posting init message from child to parent",t),this.messagePort.postMessage(t)}destroy(){super.destroy(),window.removeEventListener("message",this.initListener)}};async function x({dialogResponseHandlers:n}){let e=new f({debug:!1});window.parent.postMessage("parents just don't understand","*");let o=await e.request("initialize");return e.onRequest("dialog-value",async t=>{let i=n[t.dialogId];!i||(t.value?i.resolve({value:t.value,dialogId:t.dialogId}):t.error&&i.reject(t.error),delete n[t.dialogId])}),{initData:o,parent:{resize:async t=>{e.request("resize",{height:t})},getValue:async()=>{let t=await e.request("getValue");return t==null?void 0:t.data},setValue:async(t,i)=>{await e.request("setValue",{uniformMeshLocationValue:t,options:i})},setValidationResult:async t=>{await e.request("setValidationResult",{value:t})},getMetadata:async()=>{let t=await e.request("getMetadata");return t==null?void 0:t.data},openDialog:async({dialogType:t,data:i,options:a})=>{if(_(a==null?void 0:a.params)>1e5)throw new Error("Dialog parameters object is too large, maximum size is 100KB");let s=await e.request("openDialog",{dialogType:t,dialogData:i,options:a}),r=s==null?void 0:s.dialogId;if(!!r)return new Promise((l,c)=>{n[r]={resolve:l,reject:c}})},closeDialog:async({dialogId:t,dialogType:i,dialogData:a})=>{await e.request("closeDialog",{dialogId:t,dialogType:i,dialogData:a})}}}}function _(n){if(!n||typeof Blob=="undefined")return 0;try{let e=JSON.stringify(n);return new Blob([e]).size}catch(e){throw new Error("Error calculating object size: "+e.message)}}var y,C=({onHeightChange:n,autoResizingDisabled:e})=>{if(typeof window=="undefined")return;let o=window,t=r=>{if(r&&r!==y){y=r,n==null||n(r);return}let l=`${Math.ceil(o.document.documentElement.getBoundingClientRect().height)}px`;l!==y&&(y=l,n==null||n(l))},i=()=>{t()},a=e?void 0:new MutationObserver(i),s={instance:o,height:o.document.documentElement.getBoundingClientRect().height,observer:a,enableAutoResizing:()=>{a==null||a.observe(document.body,{attributes:!0,childList:!0,subtree:!0,characterData:!0}),o.addEventListener("resize",i)},disableAutoResizing:()=>{a==null||a.disconnect(),o.removeEventListener("resize",i)},updateHeight:t};return e||s.enableAutoResizing(),s};var K={},R=!1;async function j({autoResizingDisabled:n}={}){var e;if(typeof window!="undefined"&&typeof window.UniformMeshSDK=="undefined"&&!R){if(typeof window.parent=="undefined"||window.parent==window)throw new Error("It appears you are trying to connect with the Uniform Mesh SDK outside of an iframe. Be sure you are loading your app via a location URL configured in the Uniform dashboard.");R=!0;let o=await x({dialogResponseHandlers:K}),{initData:t,parent:i}=o,a={events:(0,O.default)(),getCurrentLocation:()=>{let s={type:t.locationType,isReadOnly:t.isReadOnly,getValue:()=>s.value,value:t.locationValue,setValue:async(r,l)=>{t.dialogContext&&console.warn("Using setValue() inside a dialog is deprecated. Use dialogContext.returnDialogValue() instead."),t.locationValue=r,a.events.emit("onValueChanged",{newValue:r}),await i.setValue(r,l)},getMetadata:()=>t.locationMetadata,metadata:t.locationMetadata,setValidationResult:async r=>{await i.setValidationResult(r)},dialogContext:t.dialogContext?{...t.dialogContext,params:t.locationMetadata.dialogParams,returnDialogValue:async r=>{t.locationValue=r,a.events.emit("onValueChanged",{newValue:r}),await i.setValue(r)}}:void 0};return s},currentWindow:C({onHeightChange:s=>{i.resize(s)},autoResizingDisabled:(e=t.dialogContext)!=null&&e.contentHeight?!0:n}),version:t.uniformApiVersion,openLocationDialog:async({locationKey:s,options:r})=>{let l=await i.openDialog({dialogType:"location",data:{locationKey:s},options:r});if(!!l)return{dialogId:l.dialogId,value:l.value,closeDialog:async()=>{await i.closeDialog({dialogId:l.dialogId,dialogType:"location"})}}},async closeLocationDialog({dialogId:s}){await i.closeDialog({dialogId:s,dialogType:"location"})},openConfirmationDialog:async({titleText:s,bodyText:r})=>{let l=await i.openDialog({dialogType:"confirm",data:{titleText:s,bodyText:r}});if(!!l)return{dialogId:l.dialogId,value:l.value,closeDialog:async()=>{await i.closeDialog({dialogId:void 0,dialogType:"confirm"})}}},openCurrentLocationDialog:async s=>{let r=await i.openDialog({dialogType:"location",data:{},options:s==null?void 0:s.options});if(!!r)return{dialogId:r.dialogId,value:r.value,closeDialog:async()=>{await i.closeDialog({dialogId:void 0,dialogType:"location"})}}},closeCurrentLocationDialog:async()=>{await i.closeDialog({dialogId:void 0,dialogType:"location"})},dialogContext:t.dialogContext};return window.UniformMeshSDK=a,R=!1,a}}0&&(module.exports={initializeUniformMeshSDK});
1
+ "use strict";var I=Object.create;var u=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var z=Object.getPrototypeOf,H=Object.prototype.hasOwnProperty;var N=(n,e)=>{for(var o in e)u(n,o,{get:e[o],enumerable:!0})},E=(n,e,o,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of q(e))!H.call(n,s)&&s!==o&&u(n,s,{get:()=>e[s],enumerable:!(t=k(e,s))||t.enumerable});return n};var U=(n,e,o)=>(o=n!=null?I(z(n)):{},E(e||!n||!n.__esModule?u(o,"default",{value:n,enumerable:!0}):o,n)),W=n=>E(u({},"__esModule",{value:!0}),n);var $={};N($,{initializeUniformMeshSDK:()=>j});module.exports=W($);var O=U(require("mitt"));var T=(n,e)=>e?{log(o,...t){return console.log(`${n}: ${o}`,...t)},error(o,...t){return console.error(`${n}: ${o}`,...t)}}:{log(){},error(){}};var M=5e3;var d=class extends Error{constructor(){super("Request timed out"),Object.setPrototypeOf(this,d.prototype),this.name="RequestTimeoutError"}},c=class extends Error{constructor(){super("Client destroyed"),Object.setPrototypeOf(this,c.prototype),this.name="ClientDestroyedError"}};var v=()=>{let n=()=>{},e=()=>{},o=new Promise((t,s)=>{n=t,e=s});return{resolve:n,reject:e,promise:o}},p=(n=16)=>[...Array(n)].map(()=>(~~(Math.random()*36)).toString(36)).join(""),g=(n,e)=>{let{[e]:o,...t}=n;return t},Q=n=>({message:n.message,name:n.name,stack:n.stack}),A=({name:n,message:e,stack:o})=>{switch(n){case d.name:return new d;default:{let t=new Error(e);return t.name=n,t.stack=o,t}}},w=n=>{let e=n.data,o="none";return e instanceof Error&&(o="error",e=Q(e)),{...n,serialization:o,data:e}},b=n=>n.serialization==="error"?{...n,data:A(n.data)}:n;var h=class{constructor({debug:e=!1,requestTimeout:o=M}={}){this.debug=e,this.requestTimeout=o,this.channel=v(),this.eventSubscriptions={},this.responseSubscriptions={},this.requestSubscriptions={},this.onDestroyRequestHandlers={},this.destroyed=!1,this.logger=this.getLogger(),this.getChannel().then(()=>{this.logger.log("Secure parent <-> child channel established")}).catch(t=>{this.logger.log(t)})}async send(e,o){return this.postMessage("event",e,o)}on(e,o){this.eventSubscriptions[e]||(this.eventSubscriptions[e]={});let t=p(8);return this.eventSubscriptions[e][t]=o,this.logger.log(`Registered handler for event "${e}"`),()=>{this.eventSubscriptions[e]=g(this.eventSubscriptions[e],t),this.logger.log(`Unsubscribed handler for event ${e}`)}}async request(e,o,t={}){let a=(await this.postMessage("request",e,o)).id,i=()=>{this.responseSubscriptions=g(this.responseSubscriptions,a)},r=()=>{this.onDestroyRequestHandlers=g(this.responseSubscriptions,a)};return new Promise((l,y)=>{let D,L=(S,P)=>{clearTimeout(D),i(),r(),P.type==="error_response"?y(S):l(S)},V=()=>{clearTimeout(D),y(new c)};this.responseSubscriptions[a]=L,this.onDestroyRequestHandlers[a]=V,D=setTimeout(()=>{i(),r(),y(new d)},t.timeout||this.requestTimeout)})}onRequest(e,o){let t=async(s,a)=>{try{let i=await o(s,a);this.postMessage("response",e,i,a.id)}catch(i){this.postMessage("error_response",e,i,a.id)}};return this.requestSubscriptions[e]=t,()=>{this.requestSubscriptions=g(this.requestSubscriptions,e)}}async getChannel(){if(await this.channel.promise,this.destroyed)throw new c;return this.channel.promise}async messageListener(e){try{await this.getChannel();let o=this.isValidMessage(e),t=b(e.data);if(o)switch(t.type){case"event":{this.handleEvent(t);break}case"request":{this.handleRequest(t);break}case"error_response":case"response":{this.handleResponse(t);break}}else this.logger.error("Invalid message format. Skipping.")}catch(o){this.logger.error(o)}}handleEvent(e){let o=this.eventSubscriptions[e.key];o&&Object.values(o).forEach(t=>t(e.data,e))}handleRequest(e){let o=this.requestSubscriptions[e.key];o&&(o(e.data,e),this.logger.log(`Handled request type ${e.key}`))}handleResponse(e){let o=e.requestId,t=o&&this.responseSubscriptions[o];t&&t(e.data,e)}async postMessage(e,o,t,s){let{port:a}=await this.getChannel();if(this.destroyed)throw new c;let i=w({type:e,apiVersion:"framepost/v1",key:o,data:t,id:p(),requestId:s});return this.logger.log("posting message from child to parent",i),a.postMessage(i),i}initListener(e){this.isInitMessage(e)?(this.onChannelInit(e),this.messagePort&&(this.messagePort.onmessage=this.messageListener.bind(this)),this.resolveChannel(e)):this.logger.error("Invalid message format. Skipping.")}isValidMessage(e){let o=e.data;return o.type&&o.id&&o.apiVersion==="framepost/v1"}isInitMessage(e){return this.isValidMessage(e)&&e.data.type==="channel_init"}resolveChannel(e){if(this.messagePort){let o={port:this.messagePort,origin:e.origin,context:e.data.data};this.channel.resolve(o)}}getInitMessage(e){return w({type:"channel_init",apiVersion:"framepost/v1",key:"",data:e,id:p()})}destroy(){this.destroyed=!0,this.channel.reject(new c),this.messagePort&&this.messagePort.close(),Object.values(this.onDestroyRequestHandlers).forEach(e=>e())}};var m=class extends h{constructor(o={}){super(o);this.context=o.context||null,this.initListener=this.initListener.bind(this),window.addEventListener("message",this.initListener)}getLogger(){return T("child-client",this.debug)}onChannelInit(o){window.removeEventListener("message",this.initListener),this.messagePort=o.ports[0];let t=this.getInitMessage(this.context);this.logger.log("channel init, posting init message from child to parent",t),this.messagePort.postMessage(t)}destroy(){super.destroy(),window.removeEventListener("message",this.initListener)}};async function x({dialogResponseHandlers:n}){let e=new m({debug:!1});window.parent.postMessage("parents just don't understand","*");let o=await e.request("initialize");return e.onRequest("dialog-value",async t=>{let s=n[t.dialogId];!s||(t.value?s.resolve({value:t.value,dialogId:t.dialogId}):t.error&&s.reject(t.error),delete n[t.dialogId])}),{initData:o,parent:{resize:async t=>{await e.request("resize",{height:t})},getValue:async()=>{let t=await e.request("getValue");return t==null?void 0:t.data},setValue:async(t,s)=>{let a={uniformMeshLocationValue:t,options:s};await e.request("setValue",a)},getMetadata:async()=>{let t=await e.request("getMetadata");return t==null?void 0:t.data},openDialog:async t=>{var i;if(_((i=t.options)==null?void 0:i.params)>1e5)throw new Error("Dialog parameters object is too large, maximum size is 100KB");let s=await e.request("openDialog",t),a=s==null?void 0:s.dialogId;if(!!a)return new Promise((r,l)=>{n[a]={resolve:r,reject:l}})},closeDialog:async t=>{await e.request("closeDialog",t)},getDataResource:async t=>await e.request("getDataResource",t,{timeout:3e4})}}}function _(n){if(!n||typeof Blob=="undefined")return 0;try{let e=JSON.stringify(n);return new Blob([e]).size}catch(e){throw new Error("Error calculating object size: "+e.message)}}var f,C=({onHeightChange:n,autoResizingDisabled:e})=>{if(typeof window=="undefined")return;let o=window,t=r=>{if(r&&r!==f){f=r,n==null||n(r);return}let l=`${Math.ceil(o.document.documentElement.getBoundingClientRect().height)}px`;l!==f&&(f=l,n==null||n(l))},s=()=>{t()},a=e?void 0:new MutationObserver(s),i={instance:o,height:o.document.documentElement.getBoundingClientRect().height,observer:a,enableAutoResizing:()=>{a==null||a.observe(document.body,{attributes:!0,childList:!0,subtree:!0,characterData:!0}),o.addEventListener("resize",s)},disableAutoResizing:()=>{a==null||a.disconnect(),o.removeEventListener("resize",s)},updateHeight:t};return e||i.enableAutoResizing(),i};var K={},R=!1;async function j({autoResizingDisabled:n}={}){var e;if(typeof window!="undefined"&&typeof window.UniformMeshSDK=="undefined"&&!R){if(typeof window.parent=="undefined"||window.parent==window)throw new Error("It appears you are trying to connect with the Uniform Mesh SDK outside of an iframe. Be sure you are loading your app via a location URL configured in the Uniform dashboard.");R=!0;let o=await x({dialogResponseHandlers:K}),{initData:t,parent:s}=o,a={events:(0,O.default)(),getCurrentLocation:()=>{let i={getDataResource:s.getDataResource,type:t.locationType,isReadOnly:t.isReadOnly,getValue:()=>i.value,value:t.locationValue,setValue:async(r,l)=>{t.dialogContext&&console.warn("Using setValue() inside a dialog is deprecated. Use dialogContext.returnDialogValue() instead."),t.locationValue=r,a.events.emit("onValueChanged",{newValue:r}),await s.setValue(r,l)},getMetadata:()=>t.locationMetadata,metadata:t.locationMetadata,setValidationResult:async r=>{await i.setValue(t.locationValue,r)},dialogContext:t.dialogContext?{...t.dialogContext,params:t.locationMetadata.dialogParams,returnDialogValue:async r=>{t.locationValue=r,a.events.emit("onValueChanged",{newValue:r}),await s.setValue(r)}}:void 0};return i},currentWindow:C({onHeightChange:i=>{s.resize(i)},autoResizingDisabled:(e=t.dialogContext)!=null&&e.contentHeight?!0:n}),version:t.uniformApiVersion,openLocationDialog:async({locationKey:i,options:r})=>{let l=await s.openDialog({dialogType:"location",dialogData:{locationKey:i},options:r});if(!!l)return{dialogId:l.dialogId,value:l.value,closeDialog:async()=>{await s.closeDialog({dialogId:l.dialogId,dialogType:"location"})}}},async closeLocationDialog({dialogId:i}){await s.closeDialog({dialogId:i,dialogType:"location"})},openConfirmationDialog:async({titleText:i,bodyText:r})=>{let l=await s.openDialog({dialogType:"confirm",dialogData:{titleText:i,bodyText:r}});if(!!l)return{dialogId:l.dialogId,value:l.value,closeDialog:async()=>{await s.closeDialog({dialogId:void 0,dialogType:"confirm"})}}},openCurrentLocationDialog:async i=>{let r=await s.openDialog({dialogType:"location",dialogData:{},options:i==null?void 0:i.options});if(!!r)return{dialogId:r.dialogId,value:r.value,closeDialog:async()=>{await s.closeDialog({dialogId:void 0,dialogType:"location"})}}},closeCurrentLocationDialog:async()=>{await s.closeDialog({dialogId:void 0,dialogType:"location"})},dialogContext:t.dialogContext};return window.UniformMeshSDK=a,R=!1,a}}0&&(module.exports={initializeUniformMeshSDK});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import P from"mitt";var S=(n,e)=>e?{log(o,...t){return console.log(`${n}: ${o}`,...t)},error(o,...t){return console.error(`${n}: ${o}`,...t)}}:{log(){},error(){}};var E=5e3;var d=class extends Error{constructor(){super("Request timed out"),Object.setPrototypeOf(this,d.prototype),this.name="RequestTimeoutError"}},g=class extends Error{constructor(){super("Client destroyed"),Object.setPrototypeOf(this,g.prototype),this.name="ClientDestroyedError"}};var T=()=>{let n=()=>{},e=()=>{},o=new Promise((t,i)=>{n=t,e=i});return{resolve:n,reject:e,promise:o}},p=(n=16)=>[...Array(n)].map(()=>(~~(Math.random()*36)).toString(36)).join(""),u=(n,e)=>{let{[e]:o,...t}=n;return t},L=n=>({message:n.message,name:n.name,stack:n.stack}),V=({name:n,message:e,stack:o})=>{switch(n){case d.name:return new d;default:{let t=new Error(e);return t.name=n,t.stack=o,t}}},w=n=>{let e=n.data,o="none";return e instanceof Error&&(o="error",e=L(e)),{...n,serialization:o,data:e}},v=n=>n.serialization==="error"?{...n,data:V(n.data)}:n;var h=class{constructor({debug:e=!1,requestTimeout:o=E}={}){this.debug=e,this.requestTimeout=o,this.channel=T(),this.eventSubscriptions={},this.responseSubscriptions={},this.requestSubscriptions={},this.onDestroyRequestHandlers={},this.destroyed=!1,this.logger=this.getLogger(),this.getChannel().then(()=>{this.logger.log("Secure parent <-> child channel established")}).catch(t=>{this.logger.log(t)})}async send(e,o){return this.postMessage("event",e,o)}on(e,o){this.eventSubscriptions[e]||(this.eventSubscriptions[e]={});let t=p(8);return this.eventSubscriptions[e][t]=o,this.logger.log(`Registered handler for event "${e}"`),()=>{this.eventSubscriptions[e]=u(this.eventSubscriptions[e],t),this.logger.log(`Unsubscribed handler for event ${e}`)}}async request(e,o,t={}){let a=(await this.postMessage("request",e,o)).id,s=()=>{this.responseSubscriptions=u(this.responseSubscriptions,a)},r=()=>{this.onDestroyRequestHandlers=u(this.responseSubscriptions,a)};return new Promise((l,c)=>{let y,x=(R,O)=>{clearTimeout(y),s(),r(),O.type==="error_response"?c(R):l(R)},C=()=>{clearTimeout(y),c(new g)};this.responseSubscriptions[a]=x,this.onDestroyRequestHandlers[a]=C,y=setTimeout(()=>{s(),r(),c(new d)},t.timeout||this.requestTimeout)})}onRequest(e,o){let t=async(i,a)=>{try{let s=await o(i,a);this.postMessage("response",e,s,a.id)}catch(s){this.postMessage("error_response",e,s,a.id)}};return this.requestSubscriptions[e]=t,()=>{this.requestSubscriptions=u(this.requestSubscriptions,e)}}async getChannel(){if(await this.channel.promise,this.destroyed)throw new g;return this.channel.promise}async messageListener(e){try{await this.getChannel();let o=this.isValidMessage(e),t=v(e.data);if(o)switch(t.type){case"event":{this.handleEvent(t);break}case"request":{this.handleRequest(t);break}case"error_response":case"response":{this.handleResponse(t);break}}else this.logger.error("Invalid message format. Skipping.")}catch(o){this.logger.error(o)}}handleEvent(e){let o=this.eventSubscriptions[e.key];o&&Object.values(o).forEach(t=>t(e.data,e))}handleRequest(e){let o=this.requestSubscriptions[e.key];o&&(o(e.data,e),this.logger.log(`Handled request type ${e.key}`))}handleResponse(e){let o=e.requestId,t=o&&this.responseSubscriptions[o];t&&t(e.data,e)}async postMessage(e,o,t,i){let{port:a}=await this.getChannel();if(this.destroyed)throw new g;let s=w({type:e,apiVersion:"framepost/v1",key:o,data:t,id:p(),requestId:i});return this.logger.log("posting message from child to parent",s),a.postMessage(s),s}initListener(e){this.isInitMessage(e)?(this.onChannelInit(e),this.messagePort&&(this.messagePort.onmessage=this.messageListener.bind(this)),this.resolveChannel(e)):this.logger.error("Invalid message format. Skipping.")}isValidMessage(e){let o=e.data;return o.type&&o.id&&o.apiVersion==="framepost/v1"}isInitMessage(e){return this.isValidMessage(e)&&e.data.type==="channel_init"}resolveChannel(e){if(this.messagePort){let o={port:this.messagePort,origin:e.origin,context:e.data.data};this.channel.resolve(o)}}getInitMessage(e){return w({type:"channel_init",apiVersion:"framepost/v1",key:"",data:e,id:p()})}destroy(){this.destroyed=!0,this.channel.reject(new g),this.messagePort&&this.messagePort.close(),Object.values(this.onDestroyRequestHandlers).forEach(e=>e())}};var m=class extends h{constructor(o={}){super(o);this.context=o.context||null,this.initListener=this.initListener.bind(this),window.addEventListener("message",this.initListener)}getLogger(){return S("child-client",this.debug)}onChannelInit(o){window.removeEventListener("message",this.initListener),this.messagePort=o.ports[0];let t=this.getInitMessage(this.context);this.logger.log("channel init, posting init message from child to parent",t),this.messagePort.postMessage(t)}destroy(){super.destroy(),window.removeEventListener("message",this.initListener)}};async function b({dialogResponseHandlers:n}){let e=new m({debug:!1});window.parent.postMessage("parents just don't understand","*");let o=await e.request("initialize");return e.onRequest("dialog-value",async t=>{let i=n[t.dialogId];!i||(t.value?i.resolve({value:t.value,dialogId:t.dialogId}):t.error&&i.reject(t.error),delete n[t.dialogId])}),{initData:o,parent:{resize:async t=>{e.request("resize",{height:t})},getValue:async()=>{let t=await e.request("getValue");return t==null?void 0:t.data},setValue:async(t,i)=>{await e.request("setValue",{uniformMeshLocationValue:t,options:i})},setValidationResult:async t=>{await e.request("setValidationResult",{value:t})},getMetadata:async()=>{let t=await e.request("getMetadata");return t==null?void 0:t.data},openDialog:async({dialogType:t,data:i,options:a})=>{if(k(a==null?void 0:a.params)>1e5)throw new Error("Dialog parameters object is too large, maximum size is 100KB");let s=await e.request("openDialog",{dialogType:t,dialogData:i,options:a}),r=s==null?void 0:s.dialogId;if(!!r)return new Promise((l,c)=>{n[r]={resolve:l,reject:c}})},closeDialog:async({dialogId:t,dialogType:i,dialogData:a})=>{await e.request("closeDialog",{dialogId:t,dialogType:i,dialogData:a})}}}}function k(n){if(!n||typeof Blob=="undefined")return 0;try{let e=JSON.stringify(n);return new Blob([e]).size}catch(e){throw new Error("Error calculating object size: "+e.message)}}var f,M=({onHeightChange:n,autoResizingDisabled:e})=>{if(typeof window=="undefined")return;let o=window,t=r=>{if(r&&r!==f){f=r,n==null||n(r);return}let l=`${Math.ceil(o.document.documentElement.getBoundingClientRect().height)}px`;l!==f&&(f=l,n==null||n(l))},i=()=>{t()},a=e?void 0:new MutationObserver(i),s={instance:o,height:o.document.documentElement.getBoundingClientRect().height,observer:a,enableAutoResizing:()=>{a==null||a.observe(document.body,{attributes:!0,childList:!0,subtree:!0,characterData:!0}),o.addEventListener("resize",i)},disableAutoResizing:()=>{a==null||a.disconnect(),o.removeEventListener("resize",i)},updateHeight:t};return e||s.enableAutoResizing(),s};var I={},D=!1;async function ie({autoResizingDisabled:n}={}){var e;if(typeof window!="undefined"&&typeof window.UniformMeshSDK=="undefined"&&!D){if(typeof window.parent=="undefined"||window.parent==window)throw new Error("It appears you are trying to connect with the Uniform Mesh SDK outside of an iframe. Be sure you are loading your app via a location URL configured in the Uniform dashboard.");D=!0;let o=await b({dialogResponseHandlers:I}),{initData:t,parent:i}=o,a={events:P(),getCurrentLocation:()=>{let s={type:t.locationType,isReadOnly:t.isReadOnly,getValue:()=>s.value,value:t.locationValue,setValue:async(r,l)=>{t.dialogContext&&console.warn("Using setValue() inside a dialog is deprecated. Use dialogContext.returnDialogValue() instead."),t.locationValue=r,a.events.emit("onValueChanged",{newValue:r}),await i.setValue(r,l)},getMetadata:()=>t.locationMetadata,metadata:t.locationMetadata,setValidationResult:async r=>{await i.setValidationResult(r)},dialogContext:t.dialogContext?{...t.dialogContext,params:t.locationMetadata.dialogParams,returnDialogValue:async r=>{t.locationValue=r,a.events.emit("onValueChanged",{newValue:r}),await i.setValue(r)}}:void 0};return s},currentWindow:M({onHeightChange:s=>{i.resize(s)},autoResizingDisabled:(e=t.dialogContext)!=null&&e.contentHeight?!0:n}),version:t.uniformApiVersion,openLocationDialog:async({locationKey:s,options:r})=>{let l=await i.openDialog({dialogType:"location",data:{locationKey:s},options:r});if(!!l)return{dialogId:l.dialogId,value:l.value,closeDialog:async()=>{await i.closeDialog({dialogId:l.dialogId,dialogType:"location"})}}},async closeLocationDialog({dialogId:s}){await i.closeDialog({dialogId:s,dialogType:"location"})},openConfirmationDialog:async({titleText:s,bodyText:r})=>{let l=await i.openDialog({dialogType:"confirm",data:{titleText:s,bodyText:r}});if(!!l)return{dialogId:l.dialogId,value:l.value,closeDialog:async()=>{await i.closeDialog({dialogId:void 0,dialogType:"confirm"})}}},openCurrentLocationDialog:async s=>{let r=await i.openDialog({dialogType:"location",data:{},options:s==null?void 0:s.options});if(!!r)return{dialogId:r.dialogId,value:r.value,closeDialog:async()=>{await i.closeDialog({dialogId:void 0,dialogType:"location"})}}},closeCurrentLocationDialog:async()=>{await i.closeDialog({dialogId:void 0,dialogType:"location"})},dialogContext:t.dialogContext};return window.UniformMeshSDK=a,D=!1,a}}export{ie as initializeUniformMeshSDK};
1
+ import I from"mitt";var S=(n,e)=>e?{log(o,...t){return console.log(`${n}: ${o}`,...t)},error(o,...t){return console.error(`${n}: ${o}`,...t)}}:{log(){},error(){}};var E=5e3;var d=class extends Error{constructor(){super("Request timed out"),Object.setPrototypeOf(this,d.prototype),this.name="RequestTimeoutError"}},c=class extends Error{constructor(){super("Client destroyed"),Object.setPrototypeOf(this,c.prototype),this.name="ClientDestroyedError"}};var T=()=>{let n=()=>{},e=()=>{},o=new Promise((t,s)=>{n=t,e=s});return{resolve:n,reject:e,promise:o}},u=(n=16)=>[...Array(n)].map(()=>(~~(Math.random()*36)).toString(36)).join(""),g=(n,e)=>{let{[e]:o,...t}=n;return t},L=n=>({message:n.message,name:n.name,stack:n.stack}),V=({name:n,message:e,stack:o})=>{switch(n){case d.name:return new d;default:{let t=new Error(e);return t.name=n,t.stack=o,t}}},D=n=>{let e=n.data,o="none";return e instanceof Error&&(o="error",e=L(e)),{...n,serialization:o,data:e}},M=n=>n.serialization==="error"?{...n,data:V(n.data)}:n;var p=class{constructor({debug:e=!1,requestTimeout:o=E}={}){this.debug=e,this.requestTimeout=o,this.channel=T(),this.eventSubscriptions={},this.responseSubscriptions={},this.requestSubscriptions={},this.onDestroyRequestHandlers={},this.destroyed=!1,this.logger=this.getLogger(),this.getChannel().then(()=>{this.logger.log("Secure parent <-> child channel established")}).catch(t=>{this.logger.log(t)})}async send(e,o){return this.postMessage("event",e,o)}on(e,o){this.eventSubscriptions[e]||(this.eventSubscriptions[e]={});let t=u(8);return this.eventSubscriptions[e][t]=o,this.logger.log(`Registered handler for event "${e}"`),()=>{this.eventSubscriptions[e]=g(this.eventSubscriptions[e],t),this.logger.log(`Unsubscribed handler for event ${e}`)}}async request(e,o,t={}){let a=(await this.postMessage("request",e,o)).id,i=()=>{this.responseSubscriptions=g(this.responseSubscriptions,a)},r=()=>{this.onDestroyRequestHandlers=g(this.responseSubscriptions,a)};return new Promise((l,f)=>{let y,x=(R,O)=>{clearTimeout(y),i(),r(),O.type==="error_response"?f(R):l(R)},C=()=>{clearTimeout(y),f(new c)};this.responseSubscriptions[a]=x,this.onDestroyRequestHandlers[a]=C,y=setTimeout(()=>{i(),r(),f(new d)},t.timeout||this.requestTimeout)})}onRequest(e,o){let t=async(s,a)=>{try{let i=await o(s,a);this.postMessage("response",e,i,a.id)}catch(i){this.postMessage("error_response",e,i,a.id)}};return this.requestSubscriptions[e]=t,()=>{this.requestSubscriptions=g(this.requestSubscriptions,e)}}async getChannel(){if(await this.channel.promise,this.destroyed)throw new c;return this.channel.promise}async messageListener(e){try{await this.getChannel();let o=this.isValidMessage(e),t=M(e.data);if(o)switch(t.type){case"event":{this.handleEvent(t);break}case"request":{this.handleRequest(t);break}case"error_response":case"response":{this.handleResponse(t);break}}else this.logger.error("Invalid message format. Skipping.")}catch(o){this.logger.error(o)}}handleEvent(e){let o=this.eventSubscriptions[e.key];o&&Object.values(o).forEach(t=>t(e.data,e))}handleRequest(e){let o=this.requestSubscriptions[e.key];o&&(o(e.data,e),this.logger.log(`Handled request type ${e.key}`))}handleResponse(e){let o=e.requestId,t=o&&this.responseSubscriptions[o];t&&t(e.data,e)}async postMessage(e,o,t,s){let{port:a}=await this.getChannel();if(this.destroyed)throw new c;let i=D({type:e,apiVersion:"framepost/v1",key:o,data:t,id:u(),requestId:s});return this.logger.log("posting message from child to parent",i),a.postMessage(i),i}initListener(e){this.isInitMessage(e)?(this.onChannelInit(e),this.messagePort&&(this.messagePort.onmessage=this.messageListener.bind(this)),this.resolveChannel(e)):this.logger.error("Invalid message format. Skipping.")}isValidMessage(e){let o=e.data;return o.type&&o.id&&o.apiVersion==="framepost/v1"}isInitMessage(e){return this.isValidMessage(e)&&e.data.type==="channel_init"}resolveChannel(e){if(this.messagePort){let o={port:this.messagePort,origin:e.origin,context:e.data.data};this.channel.resolve(o)}}getInitMessage(e){return D({type:"channel_init",apiVersion:"framepost/v1",key:"",data:e,id:u()})}destroy(){this.destroyed=!0,this.channel.reject(new c),this.messagePort&&this.messagePort.close(),Object.values(this.onDestroyRequestHandlers).forEach(e=>e())}};var h=class extends p{constructor(o={}){super(o);this.context=o.context||null,this.initListener=this.initListener.bind(this),window.addEventListener("message",this.initListener)}getLogger(){return S("child-client",this.debug)}onChannelInit(o){window.removeEventListener("message",this.initListener),this.messagePort=o.ports[0];let t=this.getInitMessage(this.context);this.logger.log("channel init, posting init message from child to parent",t),this.messagePort.postMessage(t)}destroy(){super.destroy(),window.removeEventListener("message",this.initListener)}};async function v({dialogResponseHandlers:n}){let e=new h({debug:!1});window.parent.postMessage("parents just don't understand","*");let o=await e.request("initialize");return e.onRequest("dialog-value",async t=>{let s=n[t.dialogId];!s||(t.value?s.resolve({value:t.value,dialogId:t.dialogId}):t.error&&s.reject(t.error),delete n[t.dialogId])}),{initData:o,parent:{resize:async t=>{await e.request("resize",{height:t})},getValue:async()=>{let t=await e.request("getValue");return t==null?void 0:t.data},setValue:async(t,s)=>{let a={uniformMeshLocationValue:t,options:s};await e.request("setValue",a)},getMetadata:async()=>{let t=await e.request("getMetadata");return t==null?void 0:t.data},openDialog:async t=>{var i;if(P((i=t.options)==null?void 0:i.params)>1e5)throw new Error("Dialog parameters object is too large, maximum size is 100KB");let s=await e.request("openDialog",t),a=s==null?void 0:s.dialogId;if(!!a)return new Promise((r,l)=>{n[a]={resolve:r,reject:l}})},closeDialog:async t=>{await e.request("closeDialog",t)},getDataResource:async t=>await e.request("getDataResource",t,{timeout:3e4})}}}function P(n){if(!n||typeof Blob=="undefined")return 0;try{let e=JSON.stringify(n);return new Blob([e]).size}catch(e){throw new Error("Error calculating object size: "+e.message)}}var m,b=({onHeightChange:n,autoResizingDisabled:e})=>{if(typeof window=="undefined")return;let o=window,t=r=>{if(r&&r!==m){m=r,n==null||n(r);return}let l=`${Math.ceil(o.document.documentElement.getBoundingClientRect().height)}px`;l!==m&&(m=l,n==null||n(l))},s=()=>{t()},a=e?void 0:new MutationObserver(s),i={instance:o,height:o.document.documentElement.getBoundingClientRect().height,observer:a,enableAutoResizing:()=>{a==null||a.observe(document.body,{attributes:!0,childList:!0,subtree:!0,characterData:!0}),o.addEventListener("resize",s)},disableAutoResizing:()=>{a==null||a.disconnect(),o.removeEventListener("resize",s)},updateHeight:t};return e||i.enableAutoResizing(),i};var k={},w=!1;async function se({autoResizingDisabled:n}={}){var e;if(typeof window!="undefined"&&typeof window.UniformMeshSDK=="undefined"&&!w){if(typeof window.parent=="undefined"||window.parent==window)throw new Error("It appears you are trying to connect with the Uniform Mesh SDK outside of an iframe. Be sure you are loading your app via a location URL configured in the Uniform dashboard.");w=!0;let o=await v({dialogResponseHandlers:k}),{initData:t,parent:s}=o,a={events:I(),getCurrentLocation:()=>{let i={getDataResource:s.getDataResource,type:t.locationType,isReadOnly:t.isReadOnly,getValue:()=>i.value,value:t.locationValue,setValue:async(r,l)=>{t.dialogContext&&console.warn("Using setValue() inside a dialog is deprecated. Use dialogContext.returnDialogValue() instead."),t.locationValue=r,a.events.emit("onValueChanged",{newValue:r}),await s.setValue(r,l)},getMetadata:()=>t.locationMetadata,metadata:t.locationMetadata,setValidationResult:async r=>{await i.setValue(t.locationValue,r)},dialogContext:t.dialogContext?{...t.dialogContext,params:t.locationMetadata.dialogParams,returnDialogValue:async r=>{t.locationValue=r,a.events.emit("onValueChanged",{newValue:r}),await s.setValue(r)}}:void 0};return i},currentWindow:b({onHeightChange:i=>{s.resize(i)},autoResizingDisabled:(e=t.dialogContext)!=null&&e.contentHeight?!0:n}),version:t.uniformApiVersion,openLocationDialog:async({locationKey:i,options:r})=>{let l=await s.openDialog({dialogType:"location",dialogData:{locationKey:i},options:r});if(!!l)return{dialogId:l.dialogId,value:l.value,closeDialog:async()=>{await s.closeDialog({dialogId:l.dialogId,dialogType:"location"})}}},async closeLocationDialog({dialogId:i}){await s.closeDialog({dialogId:i,dialogType:"location"})},openConfirmationDialog:async({titleText:i,bodyText:r})=>{let l=await s.openDialog({dialogType:"confirm",dialogData:{titleText:i,bodyText:r}});if(!!l)return{dialogId:l.dialogId,value:l.value,closeDialog:async()=>{await s.closeDialog({dialogId:void 0,dialogType:"confirm"})}}},openCurrentLocationDialog:async i=>{let r=await s.openDialog({dialogType:"location",dialogData:{},options:i==null?void 0:i.options});if(!!r)return{dialogId:r.dialogId,value:r.value,closeDialog:async()=>{await s.closeDialog({dialogId:void 0,dialogType:"location"})}}},closeCurrentLocationDialog:async()=>{await s.closeDialog({dialogId:void 0,dialogType:"location"})},dialogContext:t.dialogContext};return window.UniformMeshSDK=a,w=!1,a}}export{se as initializeUniformMeshSDK};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uniformdev/mesh-sdk",
3
- "version": "17.6.1-alpha.60+dce2049a1",
3
+ "version": "17.7.1-alpha.34+084da3172",
4
4
  "description": "Uniform Mesh Framework SDK",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "main": "./dist/index.js",
@@ -29,8 +29,8 @@
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
- "@uniformdev/canvas": "^17.6.1-alpha.60+dce2049a1",
32
+ "@uniformdev/canvas": "^17.7.1-alpha.34+084da3172",
33
33
  "mitt": "^3.0.0"
34
34
  },
35
- "gitHead": "dce2049a142bec6e78cda9d976eacf13a96aa483"
35
+ "gitHead": "084da31729798e2c1a1f26ba38c764caabebc958"
36
36
  }