@trackunit/iris-app-runtime-core 0.3.92 → 0.3.93

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.
Files changed (3) hide show
  1. package/index.cjs.js +2 -436
  2. package/index.esm.js +1 -435
  3. package/package.json +7 -6
package/index.cjs.js CHANGED
@@ -3,6 +3,7 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var irisAppRuntimeCoreApi = require('@trackunit/iris-app-runtime-core-api');
6
+ var penpal = require('penpal');
6
7
 
7
8
  /******************************************************************************
8
9
  Copyright (c) Microsoft Corporation.
@@ -29,441 +30,6 @@ function __awaiter(thisArg, _arguments, P, generator) {
29
30
  });
30
31
  }
31
32
 
32
- var MessageType;
33
- (function (MessageType) {
34
- MessageType["Call"] = "call";
35
- MessageType["Reply"] = "reply";
36
- MessageType["Syn"] = "syn";
37
- MessageType["SynAck"] = "synAck";
38
- MessageType["Ack"] = "ack";
39
- })(MessageType || (MessageType = {}));
40
- var Resolution;
41
- (function (Resolution) {
42
- Resolution["Fulfilled"] = "fulfilled";
43
- Resolution["Rejected"] = "rejected";
44
- })(Resolution || (Resolution = {}));
45
- var ErrorCode;
46
- (function (ErrorCode) {
47
- ErrorCode["ConnectionDestroyed"] = "ConnectionDestroyed";
48
- ErrorCode["ConnectionTimeout"] = "ConnectionTimeout";
49
- ErrorCode["NoIframeSrc"] = "NoIframeSrc";
50
- })(ErrorCode || (ErrorCode = {}));
51
- var NativeErrorName;
52
- (function (NativeErrorName) {
53
- NativeErrorName["DataCloneError"] = "DataCloneError";
54
- })(NativeErrorName || (NativeErrorName = {}));
55
- var NativeEventType;
56
- (function (NativeEventType) {
57
- NativeEventType["Message"] = "message";
58
- })(NativeEventType || (NativeEventType = {}));
59
-
60
- var createDestructor = (localName, log) => {
61
- const callbacks = [];
62
- let destroyed = false;
63
- return {
64
- destroy(error) {
65
- if (!destroyed) {
66
- destroyed = true;
67
- log(`${localName}: Destroying connection`);
68
- callbacks.forEach((callback) => {
69
- callback(error);
70
- });
71
- }
72
- },
73
- onDestroy(callback) {
74
- destroyed ? callback() : callbacks.push(callback);
75
- },
76
- };
77
- };
78
-
79
- var createLogger = (debug) => {
80
- /**
81
- * Logs a message if debug is enabled.
82
- */
83
- return (...args) => {
84
- if (debug) {
85
- console.log('[Penpal]', ...args); // eslint-disable-line no-console
86
- }
87
- };
88
- };
89
-
90
- /**
91
- * Converts an error object into a plain object.
92
- */
93
- const serializeError = ({ name, message, stack, }) => ({
94
- name,
95
- message,
96
- stack,
97
- });
98
- /**
99
- * Converts a plain object into an error object.
100
- */
101
- const deserializeError = (obj) => {
102
- const deserializedError = new Error();
103
- // @ts-ignore
104
- Object.keys(obj).forEach((key) => (deserializedError[key] = obj[key]));
105
- return deserializedError;
106
- };
107
-
108
- /**
109
- * Listens for "call" messages coming from the remote, executes the corresponding method, and
110
- * responds with the return value.
111
- */
112
- var connectCallReceiver = (info, serializedMethods, log) => {
113
- const { localName, local, remote, originForSending, originForReceiving, } = info;
114
- let destroyed = false;
115
- const handleMessageEvent = (event) => {
116
- if (event.source !== remote || event.data.penpal !== MessageType.Call) {
117
- return;
118
- }
119
- if (originForReceiving !== '*' && event.origin !== originForReceiving) {
120
- log(`${localName} received message from origin ${event.origin} which did not match expected origin ${originForReceiving}`);
121
- return;
122
- }
123
- const callMessage = event.data;
124
- const { methodName, args, id } = callMessage;
125
- log(`${localName}: Received ${methodName}() call`);
126
- const createPromiseHandler = (resolution) => {
127
- return (returnValue) => {
128
- log(`${localName}: Sending ${methodName}() reply`);
129
- if (destroyed) {
130
- // It's possible to throw an error here, but it would need to be thrown asynchronously
131
- // and would only be catchable using window.onerror. This is because the consumer
132
- // is merely returning a value from their method and not calling any function
133
- // that they could wrap in a try-catch. Even if the consumer were to catch the error,
134
- // the value of doing so is questionable. Instead, we'll just log a message.
135
- log(`${localName}: Unable to send ${methodName}() reply due to destroyed connection`);
136
- return;
137
- }
138
- const message = {
139
- penpal: MessageType.Reply,
140
- id,
141
- resolution,
142
- returnValue,
143
- };
144
- if (resolution === Resolution.Rejected &&
145
- returnValue instanceof Error) {
146
- message.returnValue = serializeError(returnValue);
147
- message.returnValueIsError = true;
148
- }
149
- try {
150
- remote.postMessage(message, originForSending);
151
- }
152
- catch (err) {
153
- // If a consumer attempts to send an object that's not cloneable (e.g., window),
154
- // we want to ensure the receiver's promise gets rejected.
155
- if (err.name === NativeErrorName.DataCloneError) {
156
- const errorReplyMessage = {
157
- penpal: MessageType.Reply,
158
- id,
159
- resolution: Resolution.Rejected,
160
- returnValue: serializeError(err),
161
- returnValueIsError: true,
162
- };
163
- remote.postMessage(errorReplyMessage, originForSending);
164
- }
165
- throw err;
166
- }
167
- };
168
- };
169
- new Promise((resolve) => resolve(serializedMethods[methodName].apply(serializedMethods, args))).then(createPromiseHandler(Resolution.Fulfilled), createPromiseHandler(Resolution.Rejected));
170
- };
171
- local.addEventListener(NativeEventType.Message, handleMessageEvent);
172
- return () => {
173
- destroyed = true;
174
- local.removeEventListener(NativeEventType.Message, handleMessageEvent);
175
- };
176
- };
177
-
178
- let id = 0;
179
- /**
180
- * @return {number} A unique ID (not universally unique)
181
- */
182
- var generateId = () => ++id;
183
-
184
- const KEY_PATH_DELIMITER = '.';
185
- const keyPathToSegments = (keyPath) => keyPath ? keyPath.split(KEY_PATH_DELIMITER) : [];
186
- const segmentsToKeyPath = (segments) => segments.join(KEY_PATH_DELIMITER);
187
- const createKeyPath = (key, prefix) => {
188
- const segments = keyPathToSegments(prefix || '');
189
- segments.push(key);
190
- return segmentsToKeyPath(segments);
191
- };
192
- /**
193
- * Given a `keyPath`, set it to be `value` on `subject`, creating any intermediate
194
- * objects along the way.
195
- *
196
- * @param {Object} subject The object on which to set value.
197
- * @param {string} keyPath The key path at which to set value.
198
- * @param {Object} value The value to store at the given key path.
199
- * @returns {Object} Updated subject.
200
- */
201
- const setAtKeyPath = (subject, keyPath, value) => {
202
- const segments = keyPathToSegments(keyPath);
203
- segments.reduce((prevSubject, key, idx) => {
204
- if (typeof prevSubject[key] === 'undefined') {
205
- prevSubject[key] = {};
206
- }
207
- if (idx === segments.length - 1) {
208
- prevSubject[key] = value;
209
- }
210
- return prevSubject[key];
211
- }, subject);
212
- return subject;
213
- };
214
- /**
215
- * Given a dictionary of (nested) keys to function, flatten them to a map
216
- * from key path to function.
217
- *
218
- * @param {Object} methods The (potentially nested) object to serialize.
219
- * @param {string} prefix A string with which to prefix entries. Typically not intended to be used by consumers.
220
- * @returns {Object} An map from key path in `methods` to functions.
221
- */
222
- const serializeMethods = (methods, prefix) => {
223
- const flattenedMethods = {};
224
- Object.keys(methods).forEach((key) => {
225
- const value = methods[key];
226
- const keyPath = createKeyPath(key, prefix);
227
- if (typeof value === 'object') {
228
- // Recurse into any nested children.
229
- Object.assign(flattenedMethods, serializeMethods(value, keyPath));
230
- }
231
- if (typeof value === 'function') {
232
- // If we've found a method, expose it.
233
- flattenedMethods[keyPath] = value;
234
- }
235
- });
236
- return flattenedMethods;
237
- };
238
- /**
239
- * Given a map of key paths to functions, unpack the key paths to an object.
240
- *
241
- * @param {Object} flattenedMethods A map of key paths to functions to unpack.
242
- * @returns {Object} A (potentially nested) map of functions.
243
- */
244
- const deserializeMethods = (flattenedMethods) => {
245
- const methods = {};
246
- for (const keyPath in flattenedMethods) {
247
- setAtKeyPath(methods, keyPath, flattenedMethods[keyPath]);
248
- }
249
- return methods;
250
- };
251
-
252
- /**
253
- * Augments an object with methods that match those defined by the remote. When these methods are
254
- * called, a "call" message will be sent to the remote, the remote's corresponding method will be
255
- * executed, and the method's return value will be returned via a message.
256
- * @param {Object} callSender Sender object that should be augmented with methods.
257
- * @param {Object} info Information about the local and remote windows.
258
- * @param {Array} methodKeyPaths Key paths of methods available to be called on the remote.
259
- * @param {Promise} destructionPromise A promise resolved when destroy() is called on the penpal
260
- * connection.
261
- * @returns {Object} The call sender object with methods that may be called.
262
- */
263
- var connectCallSender = (callSender, info, methodKeyPaths, destroyConnection, log) => {
264
- const { localName, local, remote, originForSending, originForReceiving, } = info;
265
- let destroyed = false;
266
- log(`${localName}: Connecting call sender`);
267
- const createMethodProxy = (methodName) => {
268
- return (...args) => {
269
- log(`${localName}: Sending ${methodName}() call`);
270
- // This handles the case where the iframe has been removed from the DOM
271
- // (and therefore its window closed), the consumer has not yet
272
- // called destroy(), and the user calls a method exposed by
273
- // the remote. We detect the iframe has been removed and force
274
- // a destroy() immediately so that the consumer sees the error saying
275
- // the connection has been destroyed. We wrap this check in a try catch
276
- // because Edge throws an "Object expected" error when accessing
277
- // contentWindow.closed on a contentWindow from an iframe that's been
278
- // removed from the DOM.
279
- let iframeRemoved;
280
- try {
281
- if (remote.closed) {
282
- iframeRemoved = true;
283
- }
284
- }
285
- catch (e) {
286
- iframeRemoved = true;
287
- }
288
- if (iframeRemoved) {
289
- destroyConnection();
290
- }
291
- if (destroyed) {
292
- const error = new Error(`Unable to send ${methodName}() call due ` + `to destroyed connection`);
293
- error.code = ErrorCode.ConnectionDestroyed;
294
- throw error;
295
- }
296
- return new Promise((resolve, reject) => {
297
- const id = generateId();
298
- const handleMessageEvent = (event) => {
299
- if (event.source !== remote ||
300
- event.data.penpal !== MessageType.Reply ||
301
- event.data.id !== id) {
302
- return;
303
- }
304
- if (originForReceiving !== '*' &&
305
- event.origin !== originForReceiving) {
306
- log(`${localName} received message from origin ${event.origin} which did not match expected origin ${originForReceiving}`);
307
- return;
308
- }
309
- const replyMessage = event.data;
310
- log(`${localName}: Received ${methodName}() reply`);
311
- local.removeEventListener(NativeEventType.Message, handleMessageEvent);
312
- let returnValue = replyMessage.returnValue;
313
- if (replyMessage.returnValueIsError) {
314
- returnValue = deserializeError(returnValue);
315
- }
316
- (replyMessage.resolution === Resolution.Fulfilled ? resolve : reject)(returnValue);
317
- };
318
- local.addEventListener(NativeEventType.Message, handleMessageEvent);
319
- const callMessage = {
320
- penpal: MessageType.Call,
321
- id,
322
- methodName,
323
- args,
324
- };
325
- remote.postMessage(callMessage, originForSending);
326
- });
327
- };
328
- };
329
- // Wrap each method in a proxy which sends it to the corresponding receiver.
330
- const flattenedMethods = methodKeyPaths.reduce((api, name) => {
331
- api[name] = createMethodProxy(name);
332
- return api;
333
- }, {});
334
- // Unpack the structure of the provided methods object onto the CallSender, exposing
335
- // the methods in the same shape they were provided.
336
- Object.assign(callSender, deserializeMethods(flattenedMethods));
337
- return () => {
338
- destroyed = true;
339
- };
340
- };
341
-
342
- /**
343
- * Starts a timeout and calls the callback with an error
344
- * if the timeout completes before the stop function is called.
345
- */
346
- var startConnectionTimeout = (timeout, callback) => {
347
- let timeoutId;
348
- if (timeout !== undefined) {
349
- timeoutId = window.setTimeout(() => {
350
- const error = new Error(`Connection timed out after ${timeout}ms`);
351
- error.code = ErrorCode.ConnectionTimeout;
352
- callback(error);
353
- }, timeout);
354
- }
355
- return () => {
356
- clearTimeout(timeoutId);
357
- };
358
- };
359
-
360
- /**
361
- * Handles a SYN-ACK handshake message.
362
- */
363
- var handleSynAckMessageFactory = (parentOrigin, serializedMethods, destructor, log) => {
364
- const { destroy, onDestroy } = destructor;
365
- return (event) => {
366
- let originQualifies = parentOrigin instanceof RegExp
367
- ? parentOrigin.test(event.origin)
368
- : parentOrigin === '*' || parentOrigin === event.origin;
369
- if (!originQualifies) {
370
- log(`Child: Handshake - Received SYN-ACK from origin ${event.origin} which did not match expected origin ${parentOrigin}`);
371
- return;
372
- }
373
- log('Child: Handshake - Received SYN-ACK, responding with ACK');
374
- // If event.origin is "null", the remote protocol is file: or data: and we
375
- // must post messages with "*" as targetOrigin when sending messages.
376
- // https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#Using_window.postMessage_in_extensions
377
- const originForSending = event.origin === 'null' ? '*' : event.origin;
378
- const ackMessage = {
379
- penpal: MessageType.Ack,
380
- methodNames: Object.keys(serializedMethods),
381
- };
382
- window.parent.postMessage(ackMessage, originForSending);
383
- const info = {
384
- localName: 'Child',
385
- local: window,
386
- remote: window.parent,
387
- originForSending,
388
- originForReceiving: event.origin,
389
- };
390
- const destroyCallReceiver = connectCallReceiver(info, serializedMethods, log);
391
- onDestroy(destroyCallReceiver);
392
- const callSender = {};
393
- const destroyCallSender = connectCallSender(callSender, info, event.data.methodNames, destroy, log);
394
- onDestroy(destroyCallSender);
395
- return callSender;
396
- };
397
- };
398
-
399
- const areGlobalsAccessible = () => {
400
- try {
401
- clearTimeout();
402
- }
403
- catch (e) {
404
- return false;
405
- }
406
- return true;
407
- };
408
- /**
409
- * Attempts to establish communication with the parent window.
410
- */
411
- var connectToParent = (options = {}) => {
412
- const { parentOrigin = '*', methods = {}, timeout, debug = false } = options;
413
- const log = createLogger(debug);
414
- const destructor = createDestructor('Child', log);
415
- const { destroy, onDestroy } = destructor;
416
- const serializedMethods = serializeMethods(methods);
417
- const handleSynAckMessage = handleSynAckMessageFactory(parentOrigin, serializedMethods, destructor, log);
418
- const sendSynMessage = () => {
419
- log('Child: Handshake - Sending SYN');
420
- const synMessage = { penpal: MessageType.Syn };
421
- const parentOriginForSyn = parentOrigin instanceof RegExp ? '*' : parentOrigin;
422
- window.parent.postMessage(synMessage, parentOriginForSyn);
423
- };
424
- const promise = new Promise((resolve, reject) => {
425
- const stopConnectionTimeout = startConnectionTimeout(timeout, destroy);
426
- const handleMessage = (event) => {
427
- // Under niche scenarios, we get into this function after
428
- // the iframe has been removed from the DOM. In Edge, this
429
- // results in "Object expected" errors being thrown when we
430
- // try to access properties on window (global properties).
431
- // For this reason, we try to access a global up front (clearTimeout)
432
- // and if it fails we can assume the iframe has been removed
433
- // and we ignore the message event.
434
- if (!areGlobalsAccessible()) {
435
- return;
436
- }
437
- if (event.source !== parent || !event.data) {
438
- return;
439
- }
440
- if (event.data.penpal === MessageType.SynAck) {
441
- const callSender = handleSynAckMessage(event);
442
- if (callSender) {
443
- window.removeEventListener(NativeEventType.Message, handleMessage);
444
- stopConnectionTimeout();
445
- resolve(callSender);
446
- }
447
- }
448
- };
449
- window.addEventListener(NativeEventType.Message, handleMessage);
450
- sendSynMessage();
451
- onDestroy((error) => {
452
- window.removeEventListener(NativeEventType.Message, handleMessage);
453
- if (error) {
454
- reject(error);
455
- }
456
- });
457
- });
458
- return {
459
- promise,
460
- destroy() {
461
- // Don't allow consumer to pass an error into destroy.
462
- destroy();
463
- },
464
- };
465
- };
466
-
467
33
  const doNothingByDefault = () => { };
468
34
  /**
469
35
  * Setup using the subscribedMethods to subscribe to events from the host.
@@ -474,7 +40,7 @@ const doNothingByDefault = () => { };
474
40
  const setupHostConnector = (subscribedMethods) => {
475
41
  var _a;
476
42
  const methods = Object.assign({ onGlobalSelectionChanged: doNothingByDefault, onFilterBarValuesChanged: doNothingByDefault, onTokenChanged: doNothingByDefault, onAssetSortingStateChanged: doNothingByDefault }, subscribedMethods);
477
- const connection = connectToParent({ methods });
43
+ const connection = penpal.connectToParent({ methods });
478
44
  (_a = connection.promise) === null || _a === void 0 ? void 0 : _a.catch(err => {
479
45
  // TODO consider how to handle this catch
480
46
  // eslint-disable-next-line no-console
package/index.esm.js CHANGED
@@ -1,5 +1,6 @@
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';
3
4
 
4
5
  /******************************************************************************
5
6
  Copyright (c) Microsoft Corporation.
@@ -26,441 +27,6 @@ function __awaiter(thisArg, _arguments, P, generator) {
26
27
  });
27
28
  }
28
29
 
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
- };
85
- };
86
-
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;
103
- };
104
-
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
- };
173
- };
174
-
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;
247
- };
248
-
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
- };
462
- };
463
-
464
30
  const doNothingByDefault = () => { };
465
31
  /**
466
32
  * Setup using the subscribedMethods to subscribe to events from the host.
package/package.json CHANGED
@@ -1,16 +1,17 @@
1
1
  {
2
2
  "name": "@trackunit/iris-app-runtime-core",
3
- "version": "0.3.92",
3
+ "version": "0.3.93",
4
4
  "repository": "https://github.com/Trackunit/manager",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "engines": {
7
7
  "node": ">=18.x"
8
8
  },
9
- "module": "./index.esm.js",
10
- "main": "./index.cjs.js",
11
9
  "dependencies": {
12
- "@trackunit/iris-app-runtime-core-api": "0.3.83",
13
- "@trackunit/react-core-contexts-api": "0.2.69"
10
+ "@trackunit/react-core-contexts-api": "*",
11
+ "@trackunit/iris-app-runtime-core-api": "*",
12
+ "penpal": "^6.2.2",
13
+ "jest-fetch-mock": "^3.0.3"
14
14
  },
15
- "peerDependencies": {}
15
+ "module": "./index.esm.js",
16
+ "main": "./index.cjs.js"
16
17
  }