@trackunit/iris-app-runtime-core 0.3.49 → 0.3.51

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/index.js CHANGED
@@ -1,6 +1,5 @@
1
1
  import { CustomFieldType } from '@trackunit/iris-app-runtime-core-api';
2
2
  export * from '@trackunit/iris-app-runtime-core-api';
3
- import { connectToParent } from 'penpal';
4
3
 
5
4
  /******************************************************************************
6
5
  Copyright (c) Microsoft Corporation.
@@ -27,324 +26,759 @@ function __awaiter(thisArg, _arguments, P, generator) {
27
26
  });
28
27
  }
29
28
 
30
- /**
31
- * Setup using the subscribedMethods to subscribe to events from the host.
32
- *
33
- * @param subscribedMethods the methods to subscribe to
34
- * @returns { Connection<HostConnectorApi> } the connection to the host
35
- */
36
- const setupHostConnector = (subscribedMethods) => {
37
- var _a;
38
- const methods = Object.assign({ onGlobalSelectionChanged: () => { }, onTokenChanged: () => { }, onAssetSortingStateChanged: () => { } }, subscribedMethods);
39
- const connection = connectToParent({ methods });
40
- (_a = connection.promise) === null || _a === void 0 ? void 0 : _a.catch(err => {
41
- // TODO consider how to handle this catch
42
- // eslint-disable-next-line no-console
43
- console.log(err);
44
- });
45
- return connection;
46
- };
47
- const hostConnector = setupHostConnector({});
48
- /**
49
- * Gets the host connector.
50
- *
51
- * @returns { Promise<HostConnectorApi> } the connection to the host
52
- */
53
- const getHostConnector = () => {
54
- return hostConnector.promise;
29
+ var MessageType;
30
+ (function (MessageType) {
31
+ MessageType["Call"] = "call";
32
+ MessageType["Reply"] = "reply";
33
+ MessageType["Syn"] = "syn";
34
+ MessageType["SynAck"] = "synAck";
35
+ MessageType["Ack"] = "ack";
36
+ })(MessageType || (MessageType = {}));
37
+ var Resolution;
38
+ (function (Resolution) {
39
+ Resolution["Fulfilled"] = "fulfilled";
40
+ Resolution["Rejected"] = "rejected";
41
+ })(Resolution || (Resolution = {}));
42
+ var ErrorCode;
43
+ (function (ErrorCode) {
44
+ ErrorCode["ConnectionDestroyed"] = "ConnectionDestroyed";
45
+ ErrorCode["ConnectionTimeout"] = "ConnectionTimeout";
46
+ ErrorCode["NoIframeSrc"] = "NoIframeSrc";
47
+ })(ErrorCode || (ErrorCode = {}));
48
+ var NativeErrorName;
49
+ (function (NativeErrorName) {
50
+ NativeErrorName["DataCloneError"] = "DataCloneError";
51
+ })(NativeErrorName || (NativeErrorName = {}));
52
+ var NativeEventType;
53
+ (function (NativeEventType) {
54
+ NativeEventType["Message"] = "message";
55
+ })(NativeEventType || (NativeEventType = {}));
56
+
57
+ var createDestructor = (localName, log) => {
58
+ const callbacks = [];
59
+ let destroyed = false;
60
+ return {
61
+ destroy(error) {
62
+ if (!destroyed) {
63
+ destroyed = true;
64
+ log(`${localName}: Destroying connection`);
65
+ callbacks.forEach((callback) => {
66
+ callback(error);
67
+ });
68
+ }
69
+ },
70
+ onDestroy(callback) {
71
+ destroyed ? callback() : callbacks.push(callback);
72
+ },
73
+ };
74
+ };
75
+
76
+ var createLogger = (debug) => {
77
+ /**
78
+ * Logs a message if debug is enabled.
79
+ */
80
+ return (...args) => {
81
+ if (debug) {
82
+ console.log('[Penpal]', ...args); // eslint-disable-line no-console
83
+ }
84
+ };
55
85
  };
56
86
 
57
- const AnalyticsContextRuntime = {
58
- logPageView: (details) => __awaiter(void 0, void 0, void 0, function* () {
59
- const api = yield getHostConnector();
60
- api.logPageView(details);
61
- }),
62
- logError: (details) => __awaiter(void 0, void 0, void 0, function* () {
63
- const api = yield getHostConnector();
64
- api.logError(details);
65
- }),
66
- logEvent: (eventName, details, nameSupplement) => __awaiter(void 0, void 0, void 0, function* () {
67
- const api = yield getHostConnector();
68
- api.logEvent(eventName, details, nameSupplement);
69
- }),
70
- setUserProperty: (name, data) => __awaiter(void 0, void 0, void 0, function* () {
71
- const api = yield getHostConnector();
72
- api.setUserProperty(name, data);
73
- }),
87
+ /**
88
+ * Converts an error object into a plain object.
89
+ */
90
+ const serializeError = ({ name, message, stack, }) => ({
91
+ name,
92
+ message,
93
+ stack,
94
+ });
95
+ /**
96
+ * Converts a plain object into an error object.
97
+ */
98
+ const deserializeError = (obj) => {
99
+ const deserializedError = new Error();
100
+ // @ts-ignore
101
+ Object.keys(obj).forEach((key) => (deserializedError[key] = obj[key]));
102
+ return deserializedError;
74
103
  };
75
104
 
76
- const AssetRuntime = {
77
- getAssetInfo: () => __awaiter(void 0, void 0, void 0, function* () {
78
- const api = yield getHostConnector();
79
- return api.getAssetInfo();
80
- }),
105
+ /**
106
+ * Listens for "call" messages coming from the remote, executes the corresponding method, and
107
+ * responds with the return value.
108
+ */
109
+ var connectCallReceiver = (info, serializedMethods, log) => {
110
+ const { localName, local, remote, originForSending, originForReceiving, } = info;
111
+ let destroyed = false;
112
+ const handleMessageEvent = (event) => {
113
+ if (event.source !== remote || event.data.penpal !== MessageType.Call) {
114
+ return;
115
+ }
116
+ if (originForReceiving !== '*' && event.origin !== originForReceiving) {
117
+ log(`${localName} received message from origin ${event.origin} which did not match expected origin ${originForReceiving}`);
118
+ return;
119
+ }
120
+ const callMessage = event.data;
121
+ const { methodName, args, id } = callMessage;
122
+ log(`${localName}: Received ${methodName}() call`);
123
+ const createPromiseHandler = (resolution) => {
124
+ return (returnValue) => {
125
+ log(`${localName}: Sending ${methodName}() reply`);
126
+ if (destroyed) {
127
+ // It's possible to throw an error here, but it would need to be thrown asynchronously
128
+ // and would only be catchable using window.onerror. This is because the consumer
129
+ // is merely returning a value from their method and not calling any function
130
+ // that they could wrap in a try-catch. Even if the consumer were to catch the error,
131
+ // the value of doing so is questionable. Instead, we'll just log a message.
132
+ log(`${localName}: Unable to send ${methodName}() reply due to destroyed connection`);
133
+ return;
134
+ }
135
+ const message = {
136
+ penpal: MessageType.Reply,
137
+ id,
138
+ resolution,
139
+ returnValue,
140
+ };
141
+ if (resolution === Resolution.Rejected &&
142
+ returnValue instanceof Error) {
143
+ message.returnValue = serializeError(returnValue);
144
+ message.returnValueIsError = true;
145
+ }
146
+ try {
147
+ remote.postMessage(message, originForSending);
148
+ }
149
+ catch (err) {
150
+ // If a consumer attempts to send an object that's not cloneable (e.g., window),
151
+ // we want to ensure the receiver's promise gets rejected.
152
+ if (err.name === NativeErrorName.DataCloneError) {
153
+ const errorReplyMessage = {
154
+ penpal: MessageType.Reply,
155
+ id,
156
+ resolution: Resolution.Rejected,
157
+ returnValue: serializeError(err),
158
+ returnValueIsError: true,
159
+ };
160
+ remote.postMessage(errorReplyMessage, originForSending);
161
+ }
162
+ throw err;
163
+ }
164
+ };
165
+ };
166
+ new Promise((resolve) => resolve(serializedMethods[methodName].apply(serializedMethods, args))).then(createPromiseHandler(Resolution.Fulfilled), createPromiseHandler(Resolution.Rejected));
167
+ };
168
+ local.addEventListener(NativeEventType.Message, handleMessageEvent);
169
+ return () => {
170
+ destroyed = true;
171
+ local.removeEventListener(NativeEventType.Message, handleMessageEvent);
172
+ };
81
173
  };
82
174
 
83
- const AssetSortingRuntime = {
84
- getAssetSortingState: () => __awaiter(void 0, void 0, void 0, function* () {
85
- const api = yield getHostConnector();
86
- return api.getAssetSortingState();
87
- }),
88
- setAssetSortingState: (...args) => __awaiter(void 0, void 0, void 0, function* () {
89
- const api = yield getHostConnector();
90
- return api.setAssetSortingState(...args);
91
- }),
175
+ let id = 0;
176
+ /**
177
+ * @return {number} A unique ID (not universally unique)
178
+ */
179
+ var generateId = () => ++id;
180
+
181
+ const KEY_PATH_DELIMITER = '.';
182
+ const keyPathToSegments = (keyPath) => keyPath ? keyPath.split(KEY_PATH_DELIMITER) : [];
183
+ const segmentsToKeyPath = (segments) => segments.join(KEY_PATH_DELIMITER);
184
+ const createKeyPath = (key, prefix) => {
185
+ const segments = keyPathToSegments(prefix || '');
186
+ segments.push(key);
187
+ return segmentsToKeyPath(segments);
188
+ };
189
+ /**
190
+ * Given a `keyPath`, set it to be `value` on `subject`, creating any intermediate
191
+ * objects along the way.
192
+ *
193
+ * @param {Object} subject The object on which to set value.
194
+ * @param {string} keyPath The key path at which to set value.
195
+ * @param {Object} value The value to store at the given key path.
196
+ * @returns {Object} Updated subject.
197
+ */
198
+ const setAtKeyPath = (subject, keyPath, value) => {
199
+ const segments = keyPathToSegments(keyPath);
200
+ segments.reduce((prevSubject, key, idx) => {
201
+ if (typeof prevSubject[key] === 'undefined') {
202
+ prevSubject[key] = {};
203
+ }
204
+ if (idx === segments.length - 1) {
205
+ prevSubject[key] = value;
206
+ }
207
+ return prevSubject[key];
208
+ }, subject);
209
+ return subject;
210
+ };
211
+ /**
212
+ * Given a dictionary of (nested) keys to function, flatten them to a map
213
+ * from key path to function.
214
+ *
215
+ * @param {Object} methods The (potentially nested) object to serialize.
216
+ * @param {string} prefix A string with which to prefix entries. Typically not intended to be used by consumers.
217
+ * @returns {Object} An map from key path in `methods` to functions.
218
+ */
219
+ const serializeMethods = (methods, prefix) => {
220
+ const flattenedMethods = {};
221
+ Object.keys(methods).forEach((key) => {
222
+ const value = methods[key];
223
+ const keyPath = createKeyPath(key, prefix);
224
+ if (typeof value === 'object') {
225
+ // Recurse into any nested children.
226
+ Object.assign(flattenedMethods, serializeMethods(value, keyPath));
227
+ }
228
+ if (typeof value === 'function') {
229
+ // If we've found a method, expose it.
230
+ flattenedMethods[keyPath] = value;
231
+ }
232
+ });
233
+ return flattenedMethods;
234
+ };
235
+ /**
236
+ * Given a map of key paths to functions, unpack the key paths to an object.
237
+ *
238
+ * @param {Object} flattenedMethods A map of key paths to functions to unpack.
239
+ * @returns {Object} A (potentially nested) map of functions.
240
+ */
241
+ const deserializeMethods = (flattenedMethods) => {
242
+ const methods = {};
243
+ for (const keyPath in flattenedMethods) {
244
+ setAtKeyPath(methods, keyPath, flattenedMethods[keyPath]);
245
+ }
246
+ return methods;
92
247
  };
93
248
 
94
- const CurrentUserRuntime = {
95
- getCurrentUserContext: () => __awaiter(void 0, void 0, void 0, function* () {
96
- const api = yield getHostConnector();
97
- return api.getCurrentUserContext();
98
- }),
99
- getCurrentUserRole: (userIds) => __awaiter(void 0, void 0, void 0, function* () {
100
- const api = yield getHostConnector();
101
- return api.getCurrentUserRole(userIds);
102
- }),
249
+ /**
250
+ * Augments an object with methods that match those defined by the remote. When these methods are
251
+ * called, a "call" message will be sent to the remote, the remote's corresponding method will be
252
+ * executed, and the method's return value will be returned via a message.
253
+ * @param {Object} callSender Sender object that should be augmented with methods.
254
+ * @param {Object} info Information about the local and remote windows.
255
+ * @param {Array} methodKeyPaths Key paths of methods available to be called on the remote.
256
+ * @param {Promise} destructionPromise A promise resolved when destroy() is called on the penpal
257
+ * connection.
258
+ * @returns {Object} The call sender object with methods that may be called.
259
+ */
260
+ var connectCallSender = (callSender, info, methodKeyPaths, destroyConnection, log) => {
261
+ const { localName, local, remote, originForSending, originForReceiving, } = info;
262
+ let destroyed = false;
263
+ log(`${localName}: Connecting call sender`);
264
+ const createMethodProxy = (methodName) => {
265
+ return (...args) => {
266
+ log(`${localName}: Sending ${methodName}() call`);
267
+ // This handles the case where the iframe has been removed from the DOM
268
+ // (and therefore its window closed), the consumer has not yet
269
+ // called destroy(), and the user calls a method exposed by
270
+ // the remote. We detect the iframe has been removed and force
271
+ // a destroy() immediately so that the consumer sees the error saying
272
+ // the connection has been destroyed. We wrap this check in a try catch
273
+ // because Edge throws an "Object expected" error when accessing
274
+ // contentWindow.closed on a contentWindow from an iframe that's been
275
+ // removed from the DOM.
276
+ let iframeRemoved;
277
+ try {
278
+ if (remote.closed) {
279
+ iframeRemoved = true;
280
+ }
281
+ }
282
+ catch (e) {
283
+ iframeRemoved = true;
284
+ }
285
+ if (iframeRemoved) {
286
+ destroyConnection();
287
+ }
288
+ if (destroyed) {
289
+ const error = new Error(`Unable to send ${methodName}() call due ` + `to destroyed connection`);
290
+ error.code = ErrorCode.ConnectionDestroyed;
291
+ throw error;
292
+ }
293
+ return new Promise((resolve, reject) => {
294
+ const id = generateId();
295
+ const handleMessageEvent = (event) => {
296
+ if (event.source !== remote ||
297
+ event.data.penpal !== MessageType.Reply ||
298
+ event.data.id !== id) {
299
+ return;
300
+ }
301
+ if (originForReceiving !== '*' &&
302
+ event.origin !== originForReceiving) {
303
+ log(`${localName} received message from origin ${event.origin} which did not match expected origin ${originForReceiving}`);
304
+ return;
305
+ }
306
+ const replyMessage = event.data;
307
+ log(`${localName}: Received ${methodName}() reply`);
308
+ local.removeEventListener(NativeEventType.Message, handleMessageEvent);
309
+ let returnValue = replyMessage.returnValue;
310
+ if (replyMessage.returnValueIsError) {
311
+ returnValue = deserializeError(returnValue);
312
+ }
313
+ (replyMessage.resolution === Resolution.Fulfilled ? resolve : reject)(returnValue);
314
+ };
315
+ local.addEventListener(NativeEventType.Message, handleMessageEvent);
316
+ const callMessage = {
317
+ penpal: MessageType.Call,
318
+ id,
319
+ methodName,
320
+ args,
321
+ };
322
+ remote.postMessage(callMessage, originForSending);
323
+ });
324
+ };
325
+ };
326
+ // Wrap each method in a proxy which sends it to the corresponding receiver.
327
+ const flattenedMethods = methodKeyPaths.reduce((api, name) => {
328
+ api[name] = createMethodProxy(name);
329
+ return api;
330
+ }, {});
331
+ // Unpack the structure of the provided methods object onto the CallSender, exposing
332
+ // the methods in the same shape they were provided.
333
+ Object.assign(callSender, deserializeMethods(flattenedMethods));
334
+ return () => {
335
+ destroyed = true;
336
+ };
337
+ };
338
+
339
+ /**
340
+ * Starts a timeout and calls the callback with an error
341
+ * if the timeout completes before the stop function is called.
342
+ */
343
+ var startConnectionTimeout = (timeout, callback) => {
344
+ let timeoutId;
345
+ if (timeout !== undefined) {
346
+ timeoutId = window.setTimeout(() => {
347
+ const error = new Error(`Connection timed out after ${timeout}ms`);
348
+ error.code = ErrorCode.ConnectionTimeout;
349
+ callback(error);
350
+ }, timeout);
351
+ }
352
+ return () => {
353
+ clearTimeout(timeoutId);
354
+ };
355
+ };
356
+
357
+ /**
358
+ * Handles a SYN-ACK handshake message.
359
+ */
360
+ var handleSynAckMessageFactory = (parentOrigin, serializedMethods, destructor, log) => {
361
+ const { destroy, onDestroy } = destructor;
362
+ return (event) => {
363
+ let originQualifies = parentOrigin instanceof RegExp
364
+ ? parentOrigin.test(event.origin)
365
+ : parentOrigin === '*' || parentOrigin === event.origin;
366
+ if (!originQualifies) {
367
+ log(`Child: Handshake - Received SYN-ACK from origin ${event.origin} which did not match expected origin ${parentOrigin}`);
368
+ return;
369
+ }
370
+ log('Child: Handshake - Received SYN-ACK, responding with ACK');
371
+ // If event.origin is "null", the remote protocol is file: or data: and we
372
+ // must post messages with "*" as targetOrigin when sending messages.
373
+ // https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#Using_window.postMessage_in_extensions
374
+ const originForSending = event.origin === 'null' ? '*' : event.origin;
375
+ const ackMessage = {
376
+ penpal: MessageType.Ack,
377
+ methodNames: Object.keys(serializedMethods),
378
+ };
379
+ window.parent.postMessage(ackMessage, originForSending);
380
+ const info = {
381
+ localName: 'Child',
382
+ local: window,
383
+ remote: window.parent,
384
+ originForSending,
385
+ originForReceiving: event.origin,
386
+ };
387
+ const destroyCallReceiver = connectCallReceiver(info, serializedMethods, log);
388
+ onDestroy(destroyCallReceiver);
389
+ const callSender = {};
390
+ const destroyCallSender = connectCallSender(callSender, info, event.data.methodNames, destroy, log);
391
+ onDestroy(destroyCallSender);
392
+ return callSender;
393
+ };
394
+ };
395
+
396
+ const areGlobalsAccessible = () => {
397
+ try {
398
+ clearTimeout();
399
+ }
400
+ catch (e) {
401
+ return false;
402
+ }
403
+ return true;
404
+ };
405
+ /**
406
+ * Attempts to establish communication with the parent window.
407
+ */
408
+ var connectToParent = (options = {}) => {
409
+ const { parentOrigin = '*', methods = {}, timeout, debug = false } = options;
410
+ const log = createLogger(debug);
411
+ const destructor = createDestructor('Child', log);
412
+ const { destroy, onDestroy } = destructor;
413
+ const serializedMethods = serializeMethods(methods);
414
+ const handleSynAckMessage = handleSynAckMessageFactory(parentOrigin, serializedMethods, destructor, log);
415
+ const sendSynMessage = () => {
416
+ log('Child: Handshake - Sending SYN');
417
+ const synMessage = { penpal: MessageType.Syn };
418
+ const parentOriginForSyn = parentOrigin instanceof RegExp ? '*' : parentOrigin;
419
+ window.parent.postMessage(synMessage, parentOriginForSyn);
420
+ };
421
+ const promise = new Promise((resolve, reject) => {
422
+ const stopConnectionTimeout = startConnectionTimeout(timeout, destroy);
423
+ const handleMessage = (event) => {
424
+ // Under niche scenarios, we get into this function after
425
+ // the iframe has been removed from the DOM. In Edge, this
426
+ // results in "Object expected" errors being thrown when we
427
+ // try to access properties on window (global properties).
428
+ // For this reason, we try to access a global up front (clearTimeout)
429
+ // and if it fails we can assume the iframe has been removed
430
+ // and we ignore the message event.
431
+ if (!areGlobalsAccessible()) {
432
+ return;
433
+ }
434
+ if (event.source !== parent || !event.data) {
435
+ return;
436
+ }
437
+ if (event.data.penpal === MessageType.SynAck) {
438
+ const callSender = handleSynAckMessage(event);
439
+ if (callSender) {
440
+ window.removeEventListener(NativeEventType.Message, handleMessage);
441
+ stopConnectionTimeout();
442
+ resolve(callSender);
443
+ }
444
+ }
445
+ };
446
+ window.addEventListener(NativeEventType.Message, handleMessage);
447
+ sendSynMessage();
448
+ onDestroy((error) => {
449
+ window.removeEventListener(NativeEventType.Message, handleMessage);
450
+ if (error) {
451
+ reject(error);
452
+ }
453
+ });
454
+ });
455
+ return {
456
+ promise,
457
+ destroy() {
458
+ // Don't allow consumer to pass an error into destroy.
459
+ destroy();
460
+ },
461
+ };
103
462
  };
104
463
 
105
- /**
106
- * Get the value of a custom field from a raw value.
107
- *
108
- * @param customFieldDefinition the definition of the custom field
109
- * @param newValue the new value to set
110
- * @returns { CustomFieldValue } an updated CustomFieldValue
111
- */
112
- const getCustomFieldValueFromRawValue = (customFieldDefinition, newValue) => {
113
- if (customFieldDefinition.type === CustomFieldType.BOOLEAN) {
114
- return {
115
- booleanValue: newValue ? true : false,
116
- type: CustomFieldType.BOOLEAN,
117
- };
118
- }
119
- else if (customFieldDefinition.type === CustomFieldType.DATE) {
120
- return {
121
- dateValue: getDateValue(newValue),
122
- type: CustomFieldType.DATE,
123
- };
124
- }
125
- else if (customFieldDefinition.type === CustomFieldType.DROPDOWN) {
126
- const stringArrayValue = [];
127
- if (Array.isArray(newValue)) {
128
- newValue.forEach(item => {
129
- if (typeof item === "string") {
130
- stringArrayValue.push(item);
131
- }
132
- else {
133
- stringArrayValue.push(item === null || item === void 0 ? void 0 : item.value);
134
- }
135
- });
136
- }
137
- else {
138
- if (typeof newValue === "string") {
139
- stringArrayValue.push(newValue);
140
- }
141
- else if (typeof newValue === "object") {
142
- stringArrayValue.push(newValue === null || newValue === void 0 ? void 0 : newValue.value);
143
- }
144
- }
145
- return {
146
- stringArrayValue: stringArrayValue,
147
- type: CustomFieldType.DROPDOWN,
148
- };
149
- }
150
- else if (customFieldDefinition.type === CustomFieldType.EMAIL) {
151
- return {
152
- stringValue: getStringValue(newValue),
153
- type: CustomFieldType.EMAIL,
154
- };
155
- }
156
- else if (customFieldDefinition.type === CustomFieldType.NUMBER) {
157
- let value = customFieldDefinition.isInteger
158
- ? parseInt(newValue)
159
- : parseFloat(newValue);
160
- if (isNaN(value)) {
161
- value = null;
162
- }
163
- return {
164
- numberValue: value,
165
- type: CustomFieldType.NUMBER,
166
- };
167
- }
168
- else if (customFieldDefinition.type === CustomFieldType.PHONE_NUMBER) {
169
- return {
170
- stringValue: getStringValue(newValue),
171
- type: CustomFieldType.PHONE_NUMBER,
172
- };
173
- }
174
- else if (customFieldDefinition.type === CustomFieldType.STRING) {
175
- return {
176
- stringValue: getStringValue(newValue),
177
- type: CustomFieldType.STRING,
178
- };
179
- }
180
- else if (customFieldDefinition.type === CustomFieldType.WEB_ADDRESS) {
181
- return {
182
- stringValue: getStringValue(newValue),
183
- type: CustomFieldType.WEB_ADDRESS,
184
- };
185
- }
186
- throw new Error("Unsupported custom field type");
187
- };
188
- /**
189
- * Convert the received value to a string
190
- */
191
- const getStringValue = (value) => {
192
- const stringValue = value;
193
- if (stringValue === null || stringValue === undefined) {
194
- return null;
195
- }
196
- else if (stringValue.trim().length === 0) {
197
- return null;
198
- }
199
- else {
200
- return stringValue.trim();
201
- }
202
- };
203
- /**
204
- * Format the received value to a date string
205
- * yyyy-mm-dd
206
- */
207
- const getDateValue = (value) => {
208
- const date = new Date(value);
209
- const day = date.toLocaleString("en-US", { day: "2-digit" });
210
- const month = date.toLocaleString("en-US", { month: "2-digit" });
211
- const year = date.toLocaleString("en-US", { year: "numeric" });
212
- return `${year}-${month}-${day}`;
213
- };
214
- const CustomFieldRuntime = {
215
- getCustomFieldsFor: (entity) => __awaiter(void 0, void 0, void 0, function* () {
216
- const api = yield getHostConnector();
217
- return api.getCustomFieldsFor(entity);
218
- }),
219
- setCustomFieldsFor: (entity, values) => __awaiter(void 0, void 0, void 0, function* () {
220
- const api = yield getHostConnector();
221
- return api.setCustomFieldsFor(entity, values);
222
- }),
223
- setCustomFieldsFromFormData: (entity, formData, originalDefinitions) => __awaiter(void 0, void 0, void 0, function* () {
224
- const api = yield getHostConnector();
225
- const values = [];
226
- Object.keys(formData).forEach(key => {
227
- var _a;
228
- const found = (_a = originalDefinitions.find(originalDefinition => originalDefinition.definition.key === key)) === null || _a === void 0 ? void 0 : _a.definition;
229
- if (found) {
230
- values.push({
231
- definitionKey: key,
232
- value: getCustomFieldValueFromRawValue(found, formData[key]),
233
- });
234
- }
235
- else {
236
- throw new Error("Unsupported custom field type: " + key);
237
- }
238
- });
239
- return api.setCustomFieldsFor(entity, values);
240
- }),
464
+ /**
465
+ * Setup using the subscribedMethods to subscribe to events from the host.
466
+ *
467
+ * @param subscribedMethods the methods to subscribe to
468
+ * @returns { Connection<HostConnectorApi> } the connection to the host
469
+ */
470
+ const setupHostConnector = (subscribedMethods) => {
471
+ var _a;
472
+ const methods = Object.assign({ onGlobalSelectionChanged: () => { }, onTokenChanged: () => { }, onAssetSortingStateChanged: () => { } }, subscribedMethods);
473
+ const connection = connectToParent({ methods });
474
+ (_a = connection.promise) === null || _a === void 0 ? void 0 : _a.catch(err => {
475
+ // TODO consider how to handle this catch
476
+ // eslint-disable-next-line no-console
477
+ console.log(err);
478
+ });
479
+ return connection;
480
+ };
481
+ const hostConnector = setupHostConnector({});
482
+ /**
483
+ * Gets the host connector.
484
+ *
485
+ * @returns { Promise<HostConnectorApi> } the connection to the host
486
+ */
487
+ const getHostConnector = () => {
488
+ return hostConnector.promise;
489
+ };
490
+
491
+ const AnalyticsContextRuntime = {
492
+ logPageView: (details) => __awaiter(void 0, void 0, void 0, function* () {
493
+ const api = yield getHostConnector();
494
+ api.logPageView(details);
495
+ }),
496
+ logError: (details) => __awaiter(void 0, void 0, void 0, function* () {
497
+ const api = yield getHostConnector();
498
+ api.logError(details);
499
+ }),
500
+ logEvent: (eventName, details, nameSupplement) => __awaiter(void 0, void 0, void 0, function* () {
501
+ const api = yield getHostConnector();
502
+ api.logEvent(eventName, details, nameSupplement);
503
+ }),
504
+ setUserProperty: (name, data) => __awaiter(void 0, void 0, void 0, function* () {
505
+ const api = yield getHostConnector();
506
+ api.setUserProperty(name, data);
507
+ }),
508
+ };
509
+
510
+ const AssetRuntime = {
511
+ getAssetInfo: () => __awaiter(void 0, void 0, void 0, function* () {
512
+ const api = yield getHostConnector();
513
+ return api.getAssetInfo();
514
+ }),
515
+ };
516
+
517
+ const AssetSortingRuntime = {
518
+ getAssetSortingState: () => __awaiter(void 0, void 0, void 0, function* () {
519
+ const api = yield getHostConnector();
520
+ return api.getAssetSortingState();
521
+ }),
522
+ setAssetSortingState: (...args) => __awaiter(void 0, void 0, void 0, function* () {
523
+ const api = yield getHostConnector();
524
+ return api.setAssetSortingState(...args);
525
+ }),
526
+ };
527
+
528
+ const CurrentUserRuntime = {
529
+ getCurrentUserContext: () => __awaiter(void 0, void 0, void 0, function* () {
530
+ const api = yield getHostConnector();
531
+ return api.getCurrentUserContext();
532
+ }),
533
+ getCurrentUserRole: (userIds) => __awaiter(void 0, void 0, void 0, function* () {
534
+ const api = yield getHostConnector();
535
+ return api.getCurrentUserRole(userIds);
536
+ }),
537
+ };
538
+
539
+ /**
540
+ * Get the value of a custom field from a raw value.
541
+ *
542
+ * @param customFieldDefinition the definition of the custom field
543
+ * @param newValue the new value to set
544
+ * @returns { CustomFieldValue } an updated CustomFieldValue
545
+ */
546
+ const getCustomFieldValueFromRawValue = (customFieldDefinition, newValue) => {
547
+ if (customFieldDefinition.type === CustomFieldType.BOOLEAN) {
548
+ return {
549
+ booleanValue: newValue ? true : false,
550
+ type: CustomFieldType.BOOLEAN,
551
+ };
552
+ }
553
+ else if (customFieldDefinition.type === CustomFieldType.DATE) {
554
+ return {
555
+ dateValue: getDateValue(newValue),
556
+ type: CustomFieldType.DATE,
557
+ };
558
+ }
559
+ else if (customFieldDefinition.type === CustomFieldType.DROPDOWN) {
560
+ const stringArrayValue = [];
561
+ if (Array.isArray(newValue)) {
562
+ newValue.forEach(item => {
563
+ if (typeof item === "string") {
564
+ stringArrayValue.push(item);
565
+ }
566
+ else {
567
+ stringArrayValue.push(item === null || item === void 0 ? void 0 : item.value);
568
+ }
569
+ });
570
+ }
571
+ else {
572
+ if (typeof newValue === "string") {
573
+ stringArrayValue.push(newValue);
574
+ }
575
+ else if (typeof newValue === "object") {
576
+ stringArrayValue.push(newValue === null || newValue === void 0 ? void 0 : newValue.value);
577
+ }
578
+ }
579
+ return {
580
+ stringArrayValue: stringArrayValue,
581
+ type: CustomFieldType.DROPDOWN,
582
+ };
583
+ }
584
+ else if (customFieldDefinition.type === CustomFieldType.EMAIL) {
585
+ return {
586
+ stringValue: getStringValue(newValue),
587
+ type: CustomFieldType.EMAIL,
588
+ };
589
+ }
590
+ else if (customFieldDefinition.type === CustomFieldType.NUMBER) {
591
+ let value = customFieldDefinition.isInteger
592
+ ? parseInt(newValue)
593
+ : parseFloat(newValue);
594
+ if (isNaN(value)) {
595
+ value = null;
596
+ }
597
+ return {
598
+ numberValue: value,
599
+ type: CustomFieldType.NUMBER,
600
+ };
601
+ }
602
+ else if (customFieldDefinition.type === CustomFieldType.PHONE_NUMBER) {
603
+ return {
604
+ stringValue: getStringValue(newValue),
605
+ type: CustomFieldType.PHONE_NUMBER,
606
+ };
607
+ }
608
+ else if (customFieldDefinition.type === CustomFieldType.STRING) {
609
+ return {
610
+ stringValue: getStringValue(newValue),
611
+ type: CustomFieldType.STRING,
612
+ };
613
+ }
614
+ else if (customFieldDefinition.type === CustomFieldType.WEB_ADDRESS) {
615
+ return {
616
+ stringValue: getStringValue(newValue),
617
+ type: CustomFieldType.WEB_ADDRESS,
618
+ };
619
+ }
620
+ throw new Error("Unsupported custom field type");
621
+ };
622
+ /**
623
+ * Convert the received value to a string
624
+ */
625
+ const getStringValue = (value) => {
626
+ const stringValue = value;
627
+ if (stringValue === null || stringValue === undefined) {
628
+ return null;
629
+ }
630
+ else if (stringValue.trim().length === 0) {
631
+ return null;
632
+ }
633
+ else {
634
+ return stringValue.trim();
635
+ }
636
+ };
637
+ /**
638
+ * Format the received value to a date string
639
+ * yyyy-mm-dd
640
+ */
641
+ const getDateValue = (value) => {
642
+ const date = new Date(value);
643
+ const day = date.toLocaleString("en-US", { day: "2-digit" });
644
+ const month = date.toLocaleString("en-US", { month: "2-digit" });
645
+ const year = date.toLocaleString("en-US", { year: "numeric" });
646
+ return `${year}-${month}-${day}`;
647
+ };
648
+ const CustomFieldRuntime = {
649
+ getCustomFieldsFor: (entity) => __awaiter(void 0, void 0, void 0, function* () {
650
+ const api = yield getHostConnector();
651
+ return api.getCustomFieldsFor(entity);
652
+ }),
653
+ setCustomFieldsFor: (entity, values) => __awaiter(void 0, void 0, void 0, function* () {
654
+ const api = yield getHostConnector();
655
+ return api.setCustomFieldsFor(entity, values);
656
+ }),
657
+ setCustomFieldsFromFormData: (entity, formData, originalDefinitions) => __awaiter(void 0, void 0, void 0, function* () {
658
+ const api = yield getHostConnector();
659
+ const values = [];
660
+ Object.keys(formData).forEach(key => {
661
+ var _a;
662
+ const found = (_a = originalDefinitions.find(originalDefinition => originalDefinition.definition.key === key)) === null || _a === void 0 ? void 0 : _a.definition;
663
+ if (found) {
664
+ values.push({
665
+ definitionKey: key,
666
+ value: getCustomFieldValueFromRawValue(found, formData[key]),
667
+ });
668
+ }
669
+ else {
670
+ throw new Error("Unsupported custom field type: " + key);
671
+ }
672
+ });
673
+ return api.setCustomFieldsFor(entity, values);
674
+ }),
241
675
  };
242
676
 
243
- const EnvironmentRuntime = {
244
- getEnvironmentContext: () => __awaiter(void 0, void 0, void 0, function* () {
245
- const api = yield getHostConnector();
246
- return api.getEnvironmentContext();
247
- }),
677
+ const EnvironmentRuntime = {
678
+ getEnvironmentContext: () => __awaiter(void 0, void 0, void 0, function* () {
679
+ const api = yield getHostConnector();
680
+ return api.getEnvironmentContext();
681
+ }),
248
682
  };
249
683
 
250
- const GlobalSelectionRuntime = {
251
- getGlobalSelection: () => __awaiter(void 0, void 0, void 0, function* () {
252
- const api = yield getHostConnector();
253
- return api.getGlobalSelectionContext();
254
- }),
684
+ const GlobalSelectionRuntime = {
685
+ getGlobalSelection: () => __awaiter(void 0, void 0, void 0, function* () {
686
+ const api = yield getHostConnector();
687
+ return api.getGlobalSelectionContext();
688
+ }),
255
689
  };
256
690
 
257
- const OemBrandingContextRuntime = {
258
- getOemBrandingContextRuntime: () => __awaiter(void 0, void 0, void 0, function* () {
259
- const api = yield getHostConnector();
260
- return {
261
- getOemImage: api.getOemImage,
262
- getOemBranding: api.getOemBranding,
263
- };
264
- }),
691
+ const OemBrandingContextRuntime = {
692
+ getOemBrandingContextRuntime: () => __awaiter(void 0, void 0, void 0, function* () {
693
+ const api = yield getHostConnector();
694
+ return {
695
+ getOemImage: api.getOemImage,
696
+ getOemBranding: api.getOemBranding,
697
+ };
698
+ }),
265
699
  };
266
700
 
267
- const NavigationRuntime = {
268
- setDeepLink: (props) => __awaiter(void 0, void 0, void 0, function* () {
269
- const api = yield getHostConnector();
270
- return api.setDeepLink(props);
271
- }),
272
- gotoAssetHome: (assetId, options) => __awaiter(void 0, void 0, void 0, function* () {
273
- const api = yield getHostConnector();
274
- return api.gotoAssetHome(assetId, options);
275
- }),
276
- gotoSiteHome: (siteId, options) => __awaiter(void 0, void 0, void 0, function* () {
277
- const api = yield getHostConnector();
278
- return api.gotoSiteHome(siteId, options);
279
- }),
701
+ const NavigationRuntime = {
702
+ setDeepLink: (props) => __awaiter(void 0, void 0, void 0, function* () {
703
+ const api = yield getHostConnector();
704
+ return api.setDeepLink(props);
705
+ }),
706
+ gotoAssetHome: (assetId, options) => __awaiter(void 0, void 0, void 0, function* () {
707
+ const api = yield getHostConnector();
708
+ return api.gotoAssetHome(assetId, options);
709
+ }),
710
+ gotoSiteHome: (siteId, options) => __awaiter(void 0, void 0, void 0, function* () {
711
+ const api = yield getHostConnector();
712
+ return api.gotoSiteHome(siteId, options);
713
+ }),
280
714
  };
281
715
 
282
- const ParamsRuntime = {
283
- getAppName: () => __awaiter(void 0, void 0, void 0, function* () {
284
- const api = yield getHostConnector();
285
- return api.getAppName();
286
- }),
287
- getOrgName: () => __awaiter(void 0, void 0, void 0, function* () {
288
- const api = yield getHostConnector();
289
- return api.getOrgName();
290
- }),
291
- getExtensionName: () => __awaiter(void 0, void 0, void 0, function* () {
292
- const api = yield getHostConnector();
293
- return api.getExtensionName();
294
- }),
716
+ const ParamsRuntime = {
717
+ getAppName: () => __awaiter(void 0, void 0, void 0, function* () {
718
+ const api = yield getHostConnector();
719
+ return api.getAppName();
720
+ }),
721
+ getOrgName: () => __awaiter(void 0, void 0, void 0, function* () {
722
+ const api = yield getHostConnector();
723
+ return api.getOrgName();
724
+ }),
725
+ getExtensionName: () => __awaiter(void 0, void 0, void 0, function* () {
726
+ const api = yield getHostConnector();
727
+ return api.getExtensionName();
728
+ }),
295
729
  };
296
730
 
297
- const RestRuntime = {
298
- apiHost: "https://API_HOST",
299
- request(path, method, requestParams, body, bodyType, secureByDefault) {
300
- return __awaiter(this, void 0, void 0, function* () {
301
- const api = yield getHostConnector();
302
- return api.requestTrackunitRestApi(path, method, requestParams, body, bodyType, secureByDefault);
303
- });
304
- },
731
+ const RestRuntime = {
732
+ apiHost: "https://API_HOST",
733
+ request(path, method, requestParams, body, bodyType, secureByDefault) {
734
+ return __awaiter(this, void 0, void 0, function* () {
735
+ const api = yield getHostConnector();
736
+ return api.requestTrackunitRestApi(path, method, requestParams, body, bodyType, secureByDefault);
737
+ });
738
+ },
305
739
  };
306
740
 
307
- const SiteRuntime = {
308
- getSiteInfo: () => __awaiter(void 0, void 0, void 0, function* () {
309
- const api = yield getHostConnector();
310
- return api.getSiteInfo();
311
- }),
741
+ const SiteRuntime = {
742
+ getSiteInfo: () => __awaiter(void 0, void 0, void 0, function* () {
743
+ const api = yield getHostConnector();
744
+ return api.getSiteInfo();
745
+ }),
312
746
  };
313
747
 
314
- const ToastRuntime = {
315
- addToast(toast) {
316
- var _a, _b;
317
- return __awaiter(this, void 0, void 0, function* () {
318
- const api = yield getHostConnector();
319
- return api
320
- .addToast(Object.assign(Object.assign({}, toast), { primaryAction: (_a = toast.primaryAction) === null || _a === void 0 ? void 0 : _a.label, secondaryAction: (_b = toast.secondaryAction) === null || _b === void 0 ? void 0 : _b.label }))
321
- .then(res => {
322
- var _a, _b, _c, _d;
323
- switch (res) {
324
- case "primaryAction":
325
- (_b = (_a = toast.primaryAction) === null || _a === void 0 ? void 0 : _a.onClick) === null || _b === void 0 ? void 0 : _b.call(_a);
326
- break;
327
- case "secondaryAction":
328
- (_d = (_c = toast.secondaryAction) === null || _c === void 0 ? void 0 : _c.onClick) === null || _d === void 0 ? void 0 : _d.call(_c);
329
- break;
330
- }
331
- });
332
- });
333
- },
748
+ const ToastRuntime = {
749
+ addToast(toast) {
750
+ var _a, _b;
751
+ return __awaiter(this, void 0, void 0, function* () {
752
+ const api = yield getHostConnector();
753
+ return api
754
+ .addToast(Object.assign(Object.assign({}, toast), { primaryAction: (_a = toast.primaryAction) === null || _a === void 0 ? void 0 : _a.label, secondaryAction: (_b = toast.secondaryAction) === null || _b === void 0 ? void 0 : _b.label }))
755
+ .then(res => {
756
+ var _a, _b, _c, _d;
757
+ switch (res) {
758
+ case "primaryAction":
759
+ (_b = (_a = toast.primaryAction) === null || _a === void 0 ? void 0 : _a.onClick) === null || _b === void 0 ? void 0 : _b.call(_a);
760
+ break;
761
+ case "secondaryAction":
762
+ (_d = (_c = toast.secondaryAction) === null || _c === void 0 ? void 0 : _c.onClick) === null || _d === void 0 ? void 0 : _d.call(_c);
763
+ break;
764
+ }
765
+ });
766
+ });
767
+ },
334
768
  };
335
769
 
336
- const TokenRuntime = {
337
- getTokenContext: () => __awaiter(void 0, void 0, void 0, function* () {
338
- const api = yield getHostConnector();
339
- return api.getTokenContext();
340
- }),
770
+ const TokenRuntime = {
771
+ getTokenContext: () => __awaiter(void 0, void 0, void 0, function* () {
772
+ const api = yield getHostConnector();
773
+ return api.getTokenContext();
774
+ }),
341
775
  };
342
776
 
343
- const UserSubscriptionRuntime = {
344
- getUserSubscriptionContext: () => __awaiter(void 0, void 0, void 0, function* () {
345
- const api = yield getHostConnector();
346
- return api.getUserSubscriptionContext();
347
- }),
777
+ const UserSubscriptionRuntime = {
778
+ getUserSubscriptionContext: () => __awaiter(void 0, void 0, void 0, function* () {
779
+ const api = yield getHostConnector();
780
+ return api.getUserSubscriptionContext();
781
+ }),
348
782
  };
349
783
 
350
784
  export { AnalyticsContextRuntime, AssetRuntime, AssetSortingRuntime, CurrentUserRuntime, CustomFieldRuntime, EnvironmentRuntime, GlobalSelectionRuntime, NavigationRuntime, OemBrandingContextRuntime, ParamsRuntime, RestRuntime, SiteRuntime, ToastRuntime, TokenRuntime, UserSubscriptionRuntime, getCustomFieldValueFromRawValue, getDateValue, getHostConnector, getStringValue, setupHostConnector };