@uniformdev/mesh-sdk 17.1.1-alpha.452 → 17.1.1-alpha.498

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,5 +1,109 @@
1
- interface ContextData {
1
+ import { Emitter } from 'mitt';
2
+ import { RootComponentInstance, ComponentInstance, ComponentDefinition, ComponentDefinitionParameter, DataConnection, DataConnectionInfo, DataType, CompositionDataVariables } from '@uniformdev/canvas';
3
+
4
+ /** Core shared generic for a mesh location context */
5
+ interface MeshLocationCore<TValue = unknown, TMetadata = unknown, TSetValue = TValue, TType extends MeshLocationTypes = MeshLocationTypes> {
6
+ /** The current location type (where in the Uniform app the mesh app is rendering) */
7
+ type: TType;
8
+ /** If true, any editable fields on the current location should be disabled as the user does not have permission or otherwise cannot change them. */
9
+ isReadOnly: boolean;
10
+ /** @deprecated use value property instead */
11
+ getValue: () => TValue;
12
+ /** The current value of the location. Some locations have fixed types (i.e. dataType), and others have user-selected types (i.e. paramType) */
13
+ value: TValue;
14
+ /**
15
+ * Sets the current value of the location.
16
+ * All locations other than 'settings' update into a parent form state and should be updated live as changes occur in the Mesh app.
17
+ * 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.
18
+ */
19
+ setValue: (value: TSetValue, options?: SetValueOptions) => Promise<void>;
20
+ /** @deprecated use metadata property instead */
21
+ getMetadata: () => TMetadata;
22
+ /**
23
+ * Gets the current location metadata, context data which is provided from the Uniform app to assist in rendering the Mesh UI
24
+ * Each location has a specific type of metadata that it is provided, which is typed automatically when the location is known.
25
+ */
26
+ metadata: TMetadata;
27
+ /**
28
+ * Instructs Uniform to set the validity of the location in the parent app.
29
+ */
30
+ setValidationResult: (value: ValidationResult) => Promise<void>;
31
+ /**
32
+ * Context of a location when it is rendering inside a dialog in the Uniform app.
33
+ * This is set when:
34
+ * - You pop out the app using sdk.openCurrentLocationDialog() so the location is rendered in a dialog for more screen space
35
+ * - The current location is a named dialog that was opened from the location using sdk.openLocationDialog()
36
+ *
37
+ * This is undefined when the current location is not a dialog.
38
+ */
39
+ dialogContext?: DialogContext & {
40
+ params: unknown;
41
+ returnDialogValue: (value: unknown) => Promise<void>;
42
+ };
43
+ }
44
+ /**
45
+ * Known location types that can be passed to a mesh location
46
+ */
47
+ declare type MeshLocationTypes = 'paramType' | 'paramTypeConfig' | 'settings' | 'dataConnection' | 'dataType' | 'dataTypeInstance';
48
+ declare type SetValueOptions = ValidationResult;
49
+
50
+ declare type ParamTypeLocationMetadata<TParamConfiguration = unknown, TIntegrationConfiguration = unknown> = {
51
+ rootNode: Omit<RootComponentInstance, 'slots' | '_data'>;
52
+ parameterConfiguration: TParamConfiguration;
53
+ component: Omit<ComponentInstance, 'slots' | '_parameters' | '_id'>;
54
+ componentDefinitions: Record<string, ComponentDefinition | undefined>;
55
+ parameterDefinition: ComponentDefinitionParameter;
56
+ settings: TIntegrationConfiguration;
57
+ projectId: string;
58
+ };
59
+ declare type ParamTypeLocation<TParamValue = unknown, TParamConfiguration = unknown, TParamSetValue = TParamValue, TIntegrationConfiguration = unknown> = MeshLocationCore<TParamValue, ParamTypeLocationMetadata<TParamConfiguration, TIntegrationConfiguration>, TParamSetValue, 'paramType'>;
60
+
61
+ declare type ParamTypeConfigLocationMetadata<TIntegrationConfiguration = unknown> = {
62
+ settings: TIntegrationConfiguration;
63
+ projectId: string;
64
+ };
65
+ declare type ParamTypeConfigLocation<TParamValue = unknown, TIntegrationConfiguration = unknown> = MeshLocationCore<TParamValue | undefined, ParamTypeConfigLocationMetadata<TIntegrationConfiguration>, TParamValue, 'paramTypeConfig'>;
66
+
67
+ declare type SettingsLocation<TSettingsType> = MeshLocationCore<TSettingsType, undefined, TSettingsType, 'settings'>;
68
+
69
+ declare type DataConnectionLocationValue = Pick<DataConnection, 'baseUrl' | 'custom' | 'headers' | 'parameters' | 'variables'>;
70
+ declare type DataConnectionLocationMetadata<TIntegrationConfiguration = unknown> = {
71
+ settings: TIntegrationConfiguration;
72
+ projectId: string;
73
+ };
74
+ declare type DataConnectionLocation = MeshLocationCore<DataConnectionLocationValue, DataConnectionLocationMetadata, DataConnectionLocationValue, 'dataConnection'>;
75
+
76
+ declare type DataTypeValue = Pick<DataType, 'body' | 'method' | 'path' | 'custom' | 'headers' | 'parameters' | 'variables'>;
77
+ declare type DataConnectorInfo = {
78
+ type: string;
79
+ displayName: string;
80
+ installedIntegrationId: string;
81
+ };
82
+ declare type DataTypeLocationMetadata<TIntegrationConfiguration = unknown> = {
83
+ settings: TIntegrationConfiguration;
84
+ projectId: string;
85
+ dataConnection: DataConnectionInfo;
86
+ dataConnector: DataConnectorInfo;
87
+ };
88
+ declare type DataTypeLocation = MeshLocationCore<DataTypeValue, DataTypeLocationMetadata, DataTypeValue, 'dataType'>;
89
+
90
+ declare type DataTypeInstanceLocationMetadata<TIntegrationConfiguration = unknown> = {
91
+ settings: TIntegrationConfiguration;
92
+ dataType: DataType;
93
+ dataConnector: DataConnectorInfo;
94
+ projectId: string;
95
+ };
96
+ declare type DataTypeInstanceLocation = MeshLocationCore<CompositionDataVariables, DataTypeInstanceLocationMetadata, CompositionDataVariables, 'dataTypeInstance'>;
97
+
98
+ /**
99
+ * Defines methods used for interacting with a Mesh location
100
+ * To receive useful typings, check the `type` property of the location to narrow the typing.
101
+ */
102
+ declare type MeshLocation<TValue = unknown, TSetValue = TValue> = ParamTypeLocation<TValue, unknown, TSetValue> | ParamTypeConfigLocation<TValue> | SettingsLocation<TValue> | DataConnectionLocation | DataTypeLocation | DataTypeInstanceLocation;
103
+ interface MeshContextData {
2
104
  locationKey: string;
105
+ locationType: MeshLocationTypes;
106
+ isReadOnly: boolean;
3
107
  locationValue: any;
4
108
  locationMetadata: any;
5
109
  uniformApiVersion: string;
@@ -7,6 +111,7 @@ interface ContextData {
7
111
  }
8
112
  interface DialogContext {
9
113
  dialogId: string;
114
+ dialogLocation?: string;
10
115
  contentHeight?: CSSHeight;
11
116
  }
12
117
  interface DialogResponseHandlers {
@@ -22,7 +127,17 @@ interface DialogResponseData {
22
127
  error?: string;
23
128
  }
24
129
  declare type DialogType = 'location' | 'confirm';
25
- interface DialogOptions {
130
+ declare type OpenDialogResult = {
131
+ /** Unique ID of this dialog which can be used to close it */
132
+ dialogId: string;
133
+ /**
134
+ * For custom location based dialogs, this is the name of the location from the Mesh app manifest.
135
+ * e.g. if you define a dialog location in the manifestunder locations.settings.locations.fooFooFoo,
136
+ * this would be 'fooFooFoo'
137
+ */
138
+ dialogLocation?: string;
139
+ };
140
+ interface DialogOptions<TDialogParams = DialogParams> {
26
141
  /**
27
142
  * By default, dialogs will be closed when they set a value.
28
143
  * You can disable this behavior by setting the `disableCloseDialogOnSetValue`
@@ -41,7 +156,7 @@ interface DialogOptions {
41
156
  * Parameters should be simple (serializable) types, not functions or DOM
42
157
  * elements or similar non-serializable objects.
43
158
  */
44
- params?: DialogParams;
159
+ params?: TDialogParams;
45
160
  /**
46
161
  * Allows you to specify the height of the dialog content upon open. Note: the
47
162
  * dialog itself will always be full height to match the Uniform dashboard UI.
@@ -61,7 +176,6 @@ declare type DialogParams = {
61
176
  [paramName: string]: DialogParamValue;
62
177
  };
63
178
  declare type CSSHeight = '-moz-initial' | 'inherit' | 'initial' | 'revert' | 'unset' | '-moz-max-content' | '-moz-min-content' | '-webkit-fit-content' | 'auto' | 'fit-content' | 'max-content' | 'min-content' | `${number}${'px' | 'em' | 'rem' | 'vh'}`;
64
- declare type SetValueOptions = Pick<ValidationResult, 'isValid' | 'validationMessage'>;
65
179
  interface ValidationResult {
66
180
  isValid?: boolean;
67
181
  validationMessage?: string;
@@ -84,33 +198,30 @@ interface SdkWindow {
84
198
  updateHeight: (height: CSSHeight) => void;
85
199
  }
86
200
 
87
- interface UniformMeshSDK {
88
- getCurrentLocation: <TValue = unknown, TMetadata = unknown>() => MeshLocation<TValue, TMetadata>;
89
- currentWindow: SdkWindow | undefined;
90
- version: string;
91
- openLocationDialog: <TDialogValue>({ locationKey, options, }: {
92
- locationKey: string;
93
- options?: DialogOptions;
94
- }) => Promise<LocationDialogResponse<TDialogValue> | undefined>;
95
- closeLocationDialog: ({ dialogId, }: {
96
- /** Id of the dialog to close. If no dialog with the given id exists, nothing will happen. */
97
- dialogId: string;
98
- }) => Promise<void>;
99
- openConfirmationDialog({ titleText, bodyText, options, }: {
100
- titleText: string;
101
- bodyText: string;
102
- options?: DialogOptions;
103
- }): Promise<{
104
- value: 'confirm' | 'cancel';
105
- closeDialog: () => Promise<void>;
106
- } | undefined>;
107
- closeConfirmationDialog(): Promise<void>;
108
- openCurrentLocationDialog<TDialogValue>({ options, }: {
109
- options?: DialogOptions;
110
- }): Promise<LocationDialogResponse<TDialogValue> | undefined>;
111
- closeCurrentLocationDialog(): Promise<void>;
112
- dialogContext?: DialogContext;
113
- }
201
+ declare type OpenLocationDialogOptions<TDialogParams> = {
202
+ /**
203
+ * Name of the location key in the Mesh App definition (stored on uniform.app) to open in a dialog.
204
+ * For example if the current location is integration settings, this would be an object key on:
205
+ * locations.settings.locations.<thisKey>
206
+ * and the URL to the dialog would be in
207
+ * locations.settings.locations.<thisKey>.url.
208
+ */
209
+ locationKey: string;
210
+ options?: DialogOptions<TDialogParams>;
211
+ };
212
+ declare type OpenConfirmationDialogOptions = {
213
+ titleText: string;
214
+ bodyText: string;
215
+ options?: Omit<DialogOptions<void>, 'disableCloseDialogOnSetValue' | 'params'>;
216
+ };
217
+ declare type OpenConfirmationDialogResult = {
218
+ value: 'confirm' | 'cancel';
219
+ closeDialog: () => Promise<void>;
220
+ };
221
+ declare type CloseLocationDialogOptions = {
222
+ /** Id of the dialog to close. If no dialog with the given id exists, nothing will happen. */
223
+ dialogId: string;
224
+ };
114
225
  interface LocationDialogResponse<TDialogValue> {
115
226
  /** Generated id for the dialog. */
116
227
  dialogId: string;
@@ -120,18 +231,43 @@ interface LocationDialogResponse<TDialogValue> {
120
231
  * Typically used when `closeDialogOnSetValue` is false. */
121
232
  closeDialog: () => Promise<void>;
122
233
  }
234
+ /** Events that can be emitted from the Mesh SDK */
235
+ declare type UniformMeshSDKEvents = {
236
+ /** Fired when the location value has changed */
237
+ onValueChanged: {
238
+ newValue: unknown;
239
+ };
240
+ };
241
+ interface UniformMeshSDK {
242
+ events: Emitter<UniformMeshSDKEvents>;
243
+ /** Gets the current location that the Mesh App is being displayed on. */
244
+ getCurrentLocation: <TValue = unknown, TSetValue = unknown>() => MeshLocation<TValue, TSetValue>;
245
+ /** The current `window` object being used for the SDK */
246
+ currentWindow: SdkWindow | undefined;
247
+ /** The version of the Mesh framework being used */
248
+ version: string;
249
+ /** Opens a dialog in the Uniform app with the URL set to a specific named dialog registered for the current location in the Mesh app manifest */
250
+ openLocationDialog: <TExpectedDialogResult = unknown, TDialogParams = void>(options: OpenLocationDialogOptions<TDialogParams>) => Promise<LocationDialogResponse<TExpectedDialogResult> | undefined>;
251
+ /** Explicitly close a location dialog. Called within the dialog. */
252
+ closeLocationDialog: (options: CloseLocationDialogOptions) => Promise<void>;
253
+ /** Opens a confirmation dialog to get a confirm/cancel question answered. Does not require any registration with the Mesh app manifest. */
254
+ openConfirmationDialog(options: OpenConfirmationDialogOptions): Promise<OpenConfirmationDialogResult | undefined>;
255
+ /** Opens the current location within a dialog, enabling to to break out of the layout it was loaded in. */
256
+ openCurrentLocationDialog<TLocationType extends MeshLocation['type'], TLocationSetValue = unknown, TDialogParams = void>(options?: {
257
+ options?: DialogOptions<TDialogParams>;
258
+ }): Promise<LocationDialogResponse<Parameters<Extract<MeshLocation<TLocationSetValue, TLocationSetValue>, {
259
+ type: TLocationType;
260
+ }>['setValue']>[0]> | undefined>;
261
+ /** Explicitly close a location dialog. Called when rendering current location in the dialog. */
262
+ closeCurrentLocationDialog(): Promise<void>;
263
+ /** @deprecated prefer getCurrentLocation().dialogContext */
264
+ dialogContext?: DialogContext;
265
+ }
123
266
  declare global {
124
267
  interface Window {
125
- UniformMeshSDK: UniformMeshSDK;
268
+ UniformMeshSDK: UniformMeshSDK | undefined;
126
269
  }
127
270
  }
128
- /** Defines methods used for interacting with a Mesh location */
129
- interface MeshLocation<TValue = unknown, TMetadata = unknown, TSetValue = TValue> {
130
- getValue: () => TValue;
131
- setValue: (value: TSetValue, options?: SetValueOptions) => Promise<void>;
132
- getMetadata: () => TMetadata;
133
- setValidationResult: (value: ValidationResult) => Promise<void>;
134
- }
135
271
  /**
136
272
  * Initializes the Uniform Mesh SDK. Intended to be called (and awaited) prior to any
137
273
  * attempted interaction with the Uniform Mesh SDK.
@@ -140,4 +276,4 @@ declare function initializeUniformMeshSDK({ autoResizingDisabled, }?: {
140
276
  autoResizingDisabled?: boolean;
141
277
  }): Promise<UniformMeshSDK | undefined>;
142
278
 
143
- export { CSSHeight, ContextData, DialogContext, DialogOptions, DialogParamValue, DialogParams, DialogResponseData, DialogResponseHandler, DialogResponseHandlers, DialogType, LocationDialogResponse, MeshLocation, SdkWindow, SetValueOptions, UniformMeshSDK, ValidationResult, initializeUniformMeshSDK };
279
+ export { CSSHeight, CloseLocationDialogOptions, DataConnectionLocation, DataConnectionLocationMetadata, DataConnectionLocationValue, DataConnectorInfo, 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 };
package/dist/index.esm.js CHANGED
@@ -1 +1 @@
1
- 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},I=n=>({message:n.message,name:n.name,stack:n.stack}),O=({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=I(e)),{...n,serialization:o,data:e}},b=n=>n.serialization==="error"?{...n,data:O(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,C=(R,V)=>{clearTimeout(y),s(),r(),V.type==="error_response"?c(R):l(R)},x=()=>{clearTimeout(y),c(new g)};this.responseSubscriptions[a]=C,this.onDestroyRequestHandlers[a]=x,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=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,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 v({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 L={},D=!1;async function te({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 v({dialogResponseHandlers:L}),{initData:t,parent:i}=o,a={getCurrentLocation:()=>({getValue:()=>t.locationValue,setValue:async(s,r)=>{await i.setValue(s,r),t.locationValue=s},getMetadata:()=>t.locationMetadata,setValidationResult:async s=>{await i.setValidationResult(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"})}}},closeLocationDialog:async({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"})}}},closeConfirmationDialog:async()=>{await i.closeDialog({dialogId:void 0,dialogType:"confirm"})},openCurrentLocationDialog:async({options:s})=>{let r=await i.openDialog({dialogType:"location",data:{},options:s});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{te as initializeUniformMeshSDK};
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};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var w=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var L=Object.prototype.hasOwnProperty;var P=(n,e)=>{for(var o in e)w(n,o,{get:e[o],enumerable:!0})},q=(n,e,o,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of k(e))!L.call(n,i)&&i!==o&&w(n,i,{get:()=>e[i],enumerable:!(t=O(e,i))||t.enumerable});return n};var z=n=>q(w({},"__esModule",{value:!0}),n);var A={};P(A,{initializeUniformMeshSDK:()=>Q});module.exports=z(A);var E=(n,e)=>e?{log(o,...t){return console.log(`${n}: ${o}`,...t)},error(o,...t){return console.error(`${n}: ${o}`,...t)}}:{log(){},error(){}};var T=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}},p=(n=16)=>[...Array(n)].map(()=>(~~(Math.random()*36)).toString(36)).join(""),u=(n,e)=>{let{[e]:o,...t}=n;return t},H=n=>({message:n.message,name:n.name,stack:n.stack}),N=({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=H(e)),{...n,serialization:o,data:e}},v=n=>n.serialization==="error"?{...n,data:N(n.data)}:n;var h=class{constructor({debug:e=!1,requestTimeout:o=T}={}){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=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=(S,I)=>{clearTimeout(y),s(),r(),I.type==="error_response"?c(S):l(S)},V=()=>{clearTimeout(y),c(new g)};this.responseSubscriptions[a]=x,this.onDestroyRequestHandlers[a]=V,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=D({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 D({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 E("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 M({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(U(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 U(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))},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 W={},R=!1;async function Q({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 M({dialogResponseHandlers:W}),{initData:t,parent:i}=o,a={getCurrentLocation:()=>({getValue:()=>t.locationValue,setValue:async(s,r)=>{await i.setValue(s,r),t.locationValue=s},getMetadata:()=>t.locationMetadata,setValidationResult:async s=>{await i.setValidationResult(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"})}}},closeLocationDialog:async({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"})}}},closeConfirmationDialog:async()=>{await i.closeDialog({dialogId:void 0,dialogType:"confirm"})},openCurrentLocationDialog:async({options:s})=>{let r=await i.openDialog({dialogType:"location",data:{},options:s});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 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});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- 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},I=n=>({message:n.message,name:n.name,stack:n.stack}),O=({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=I(e)),{...n,serialization:o,data:e}},b=n=>n.serialization==="error"?{...n,data:O(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,C=(R,V)=>{clearTimeout(y),s(),r(),V.type==="error_response"?c(R):l(R)},x=()=>{clearTimeout(y),c(new g)};this.responseSubscriptions[a]=C,this.onDestroyRequestHandlers[a]=x,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=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,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 v({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 L={},D=!1;async function te({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 v({dialogResponseHandlers:L}),{initData:t,parent:i}=o,a={getCurrentLocation:()=>({getValue:()=>t.locationValue,setValue:async(s,r)=>{await i.setValue(s,r),t.locationValue=s},getMetadata:()=>t.locationMetadata,setValidationResult:async s=>{await i.setValidationResult(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"})}}},closeLocationDialog:async({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"})}}},closeConfirmationDialog:async()=>{await i.closeDialog({dialogId:void 0,dialogType:"confirm"})},openCurrentLocationDialog:async({options:s})=>{let r=await i.openDialog({dialogType:"location",data:{},options:s});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{te as initializeUniformMeshSDK};
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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uniformdev/mesh-sdk",
3
- "version": "17.1.1-alpha.452+d6844716c",
3
+ "version": "17.1.1-alpha.498+8b406a3f5",
4
4
  "description": "Uniform Mesh Framework SDK",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "main": "./dist/index.js",
@@ -28,5 +28,9 @@
28
28
  "publishConfig": {
29
29
  "access": "public"
30
30
  },
31
- "gitHead": "d6844716c10cd3f918bf5337fee88d3849a02fc0"
31
+ "dependencies": {
32
+ "@uniformdev/canvas": "^17.1.1-alpha.498+8b406a3f5",
33
+ "mitt": "^3.0.0"
34
+ },
35
+ "gitHead": "8b406a3f5371b2910459a25883bd14ff5c94cd69"
32
36
  }