@elliemae/ssf-host 2.29.0-alpha.0 → 2.29.0

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 (49) hide show
  1. package/dist/cjs/guest.js +5 -5
  2. package/dist/cjs/host.js +242 -199
  3. package/dist/cjs/tests/utils.js +6 -8
  4. package/dist/cjs/utils.js +1 -1
  5. package/dist/esm/guest.js +5 -5
  6. package/dist/esm/host.js +242 -199
  7. package/dist/esm/tests/utils.js +6 -8
  8. package/dist/esm/utils.js +1 -1
  9. package/dist/public/callchain-host.html +1 -1
  10. package/dist/public/callchain-intermediate.html +1 -1
  11. package/dist/public/e2e-host.html +1 -1
  12. package/dist/public/e2e-index.html +1 -1
  13. package/dist/public/index.html +1 -1
  14. package/dist/public/js/emuiSsfHost.e05998eeb058c9f027f1.js +3 -0
  15. package/dist/public/js/emuiSsfHost.e05998eeb058c9f027f1.js.br +0 -0
  16. package/dist/public/js/emuiSsfHost.e05998eeb058c9f027f1.js.gz +0 -0
  17. package/dist/public/js/emuiSsfHost.e05998eeb058c9f027f1.js.map +1 -0
  18. package/dist/public/popup-focus-host.html +1 -1
  19. package/dist/public/utils.js +1 -1
  20. package/dist/public/utils.js.br +0 -0
  21. package/dist/public/utils.js.gz +0 -0
  22. package/dist/public/utils.js.map +1 -1
  23. package/dist/public/v1-guest-v2-host.html +1 -1
  24. package/dist/public/v2-host-v1-guest.html +1 -1
  25. package/dist/types/lib/guest.d.ts +2 -2
  26. package/dist/types/lib/host.d.ts +5 -5
  27. package/dist/types/lib/ihost.d.ts +4 -4
  28. package/dist/types/lib/tests/scriptingObjects/analytics.d.ts +1 -1
  29. package/dist/types/lib/tests/scriptingObjects/appEvents.d.ts +2 -2
  30. package/dist/types/lib/tests/scriptingObjects/appObjects.d.ts +3 -3
  31. package/dist/types/lib/tests/scriptingObjects/appraisalServiceModule.d.ts +1 -1
  32. package/dist/types/lib/tests/scriptingObjects/creditServiceModule.d.ts +1 -1
  33. package/dist/types/lib/tests/server.d.ts +1 -1
  34. package/dist/types/lib/tests/utils.d.ts +13 -21
  35. package/dist/types/lib/utils.d.ts +2 -2
  36. package/dist/types/tsconfig.tsbuildinfo +1 -1
  37. package/dist/umd/index.js +1 -1
  38. package/dist/umd/index.js.br +0 -0
  39. package/dist/umd/index.js.gz +0 -0
  40. package/dist/umd/index.js.map +1 -1
  41. package/dist/umd/utils.js +1 -1
  42. package/dist/umd/utils.js.br +0 -0
  43. package/dist/umd/utils.js.gz +0 -0
  44. package/dist/umd/utils.js.map +1 -1
  45. package/package.json +10 -10
  46. package/dist/public/js/emuiSsfHost.4b00d8e6203361c7da33.js +0 -3
  47. package/dist/public/js/emuiSsfHost.4b00d8e6203361c7da33.js.br +0 -0
  48. package/dist/public/js/emuiSsfHost.4b00d8e6203361c7da33.js.gz +0 -0
  49. package/dist/public/js/emuiSsfHost.4b00d8e6203361c7da33.js.map +0 -1
package/dist/esm/host.js CHANGED
@@ -25,7 +25,16 @@ const SANDBOX_DEFAULT = [
25
25
  IFrameSandboxValues.AllowDownloads,
26
26
  IFrameSandboxValues.AllowSameOrigin
27
27
  ];
28
+ const MODULE_OBJECT_ID = "module";
29
+ const MODULE_UNLOADING_EVENT = "module.unloading";
30
+ const MODULE_UNMOUNT_EVENT = "module.unmount";
31
+ const MODULE_EVENT_TIMEOUT_MS = 1e3;
32
+ const MODULE_EVENT_STUB = new ScriptingObject(MODULE_OBJECT_ID);
33
+ const isModuleUnloadVetoed = (feedback) => Array.isArray(feedback) && feedback.some((v) => v === false);
34
+ const ignoreRejectedPromise = () => {
35
+ };
28
36
  class SSFHost {
37
+ /* eslint-enable indent */
29
38
  /**
30
39
  * unique identifier for the host
31
40
  */
@@ -45,6 +54,7 @@ class SSFHost {
45
54
  /**
46
55
  * reference to the analytics object
47
56
  */
57
+ #analyticsObj;
48
58
  /**
49
59
  * list of guests
50
60
  */
@@ -100,16 +110,31 @@ class SSFHost {
100
110
  */
101
111
  constructor(hostId, option) {
102
112
  this.hostId = hostId;
103
- this.#validateHostOptions(option);
113
+ if (!option?.logger) throw new Error("Logger is required");
114
+ if (!option?.analyticsObj) throw new Error("Analytics object is required");
104
115
  this.#logger = option.logger;
105
- const trackers = this.#createPerfTrackers(option);
106
- this.#perfTracker = trackers.perfTracker;
107
- this.#guestPerfTracker = trackers.guestPerfTracker;
116
+ this.#analyticsObj = option.analyticsObj;
117
+ const perfOpts = {
118
+ analyticsObj: option.analyticsObj,
119
+ enabled: option?.measurePerformance,
120
+ samplingRatio: option?.performanceSamplingRatio,
121
+ onError: (msg) => this.#logger.debug(msg)
122
+ };
123
+ this.#perfTracker = new PerformanceTracker({
124
+ ...perfOpts,
125
+ dedupWindowMs: option?.performanceDedupWindowMs
126
+ });
127
+ this.#guestPerfTracker = new PerformanceTracker({
128
+ ...perfOpts,
129
+ dedupWindowMs: 0
130
+ });
108
131
  this.#correlationId = uuidv4();
109
132
  this.#remoting = new Remoting(this.#logger, this.#correlationId);
110
- this.#readyStateCallback = option.readyStateCallback ?? null;
111
- this.#onGuestEventSubscribe = option.onGuestEventSubscribe ?? null;
112
- this.#onGuestEventUnsubscribe = option.onGuestEventUnsubscribe ?? null;
133
+ if (option?.readyStateCallback && typeof option?.readyStateCallback !== "function")
134
+ throw new Error("readyStateCallback must be a function");
135
+ this.#readyStateCallback = option?.readyStateCallback || null;
136
+ this.#onGuestEventSubscribe = option?.onGuestEventSubscribe || null;
137
+ this.#onGuestEventUnsubscribe = option?.onGuestEventUnsubscribe || null;
113
138
  this.#soManager = new ScriptingObjectManager();
114
139
  this.#remoting.initialize(window);
115
140
  this.#connect();
@@ -118,34 +143,17 @@ class SSFHost {
118
143
  `host is initialized. hostId: ${this.hostId}, correlationId: ${this.#correlationId}`
119
144
  );
120
145
  }
121
- #validateHostOptions(option) {
122
- if (!option?.logger) throw new Error("Logger is required");
123
- if (!option?.analyticsObj) throw new Error("Analytics object is required");
124
- if (option.readyStateCallback && typeof option.readyStateCallback !== "function") {
125
- throw new Error("readyStateCallback must be a function");
126
- }
127
- }
128
- #createPerfTrackers(option) {
129
- const perfOpts = {
130
- analyticsObj: option.analyticsObj,
131
- enabled: option.measurePerformance,
132
- samplingRatio: option.performanceSamplingRatio,
133
- onError: (msg) => this.#logger.debug(msg)
134
- };
135
- return {
136
- perfTracker: new PerformanceTracker({
137
- ...perfOpts,
138
- dedupWindowMs: option.performanceDedupWindowMs
139
- }),
140
- guestPerfTracker: new PerformanceTracker({
141
- ...perfOpts,
142
- dedupWindowMs: 0
143
- })
144
- };
145
- }
146
+ #sendBAEvent = (event, data) => {
147
+ const baEvent = { event, ...data };
148
+ this.#analyticsObj.sendBAEvent(baEvent).catch((e) => {
149
+ this.#logger.debug(
150
+ `Analytics sendBAEvent failed: ${e.message}`
151
+ );
152
+ });
153
+ };
146
154
  #closeAllPopupGuests = () => {
147
155
  const popupIds = Array.from(this.#guests.values()).filter((guest) => guest.openMode === OpenMode.Popup).map((guest) => guest.id);
148
- popupIds.forEach((id) => this.unloadGuest(id));
156
+ popupIds.forEach((id) => this.#unloadGuestInBackground(id));
149
157
  };
150
158
  /**
151
159
  * get the reference to the guest application by its window
@@ -164,7 +172,10 @@ class SSFHost {
164
172
  * @param value javascript object
165
173
  * @returns true if the object is a scripting object
166
174
  */
167
- #isScriptingObject = (value) => typeof value === "object" && value !== null && "_toJSON" in value && typeof value._toJSON === "function";
175
+ #isScriptingObject = (value) => (
176
+ // eslint-disable-next-line no-underscore-dangle, @typescript-eslint/no-unsafe-member-access
177
+ typeof value?._toJSON === "function"
178
+ );
168
179
  #encodeResponse = (val, guest) => {
169
180
  if (this.#isScriptingObject(val)) {
170
181
  if (!this.#soManager.has(
@@ -179,6 +190,15 @@ class SSFHost {
179
190
  }
180
191
  return { type: "value", value: val };
181
192
  };
193
+ #encodeException = (ex) => {
194
+ if (typeof ex === "string") {
195
+ return ex;
196
+ }
197
+ if (ex instanceof Error) {
198
+ return ex.message;
199
+ }
200
+ return "An unexpected error occurred in the host application";
201
+ };
182
202
  #dispatchConfigEvent = (guest) => {
183
203
  if (guest.ready) {
184
204
  this.#remoting.send({
@@ -223,7 +243,7 @@ class SSFHost {
223
243
  enumerable: true,
224
244
  writable: true
225
245
  });
226
- resolve(Reflect.apply(func, obj, functionParams));
246
+ resolve(func(...functionParams));
227
247
  });
228
248
  };
229
249
  #handleGuestReadyComplete = ({
@@ -286,6 +306,8 @@ class SSFHost {
286
306
  message: `Guest is initialized`,
287
307
  ...guest.getInfo()
288
308
  });
309
+ } else if (body) {
310
+ guest.capabilities = { ...guest.capabilities, ...body };
289
311
  }
290
312
  if (!body || !body.onReady) {
291
313
  this.#handleGuestReadyComplete({
@@ -306,7 +328,7 @@ class SSFHost {
306
328
  if (sourceWin?.window) {
307
329
  const guest = this.#findGuest(sourceWin);
308
330
  if (guest && !await guest.handShake()) {
309
- this.unloadGuest(sourceWin);
331
+ this.#unloadGuestInBackground(sourceWin);
310
332
  }
311
333
  }
312
334
  };
@@ -630,7 +652,12 @@ class SSFHost {
630
652
  * @param value
631
653
  * @returns
632
654
  */
633
- #isProxyEvent = (value) => value instanceof ProxyEvent || typeof value === "object" && value !== null && "subscribe" in value && typeof value.subscribe === "function";
655
+ #isProxyEvent = (value) => (
656
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
657
+ value instanceof ProxyEvent || // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
658
+ typeof value?.subscribe === "function"
659
+ );
660
+ // support v1 scripting objects
634
661
  /**
635
662
  * Register pre-rendered guest application to host
636
663
  * @param {AttachParam} param - parameters for attaching the guest
@@ -674,7 +701,7 @@ class SSFHost {
674
701
  });
675
702
  guestsToRemove.forEach((guest) => {
676
703
  const { id } = guest;
677
- this.unloadGuest(id);
704
+ this.#unloadGuestInBackground(id);
678
705
  const callbacks = this.#guestCloseCallbackList.get(id);
679
706
  callbacks?.forEach((callback) => {
680
707
  Promise.resolve(callback({ id })).catch(() => {
@@ -699,25 +726,6 @@ class SSFHost {
699
726
  const popupUrl = handshakeToken ? `${url}#hs=${handshakeToken}` : url;
700
727
  return { popupUrl, handshakeToken, trusted };
701
728
  };
702
- #focusExistingPopupGuest = (guest, url, title) => {
703
- if (guest.window.closed) return;
704
- if (isTrustedDomain(url)) {
705
- window.open("", title);
706
- } else {
707
- guest.window.focus();
708
- }
709
- };
710
- #scheduleGuestLifecycleCallback = (callback, guestId, label) => {
711
- setTimeout(() => {
712
- try {
713
- callback?.(guestId);
714
- } catch (error) {
715
- this.#logger.debug(
716
- `Error occurred in ${label} for guest with id '${guestId}': ${error.message}`
717
- );
718
- }
719
- }, 0);
720
- };
721
729
  #openPopupGuest = (param) => {
722
730
  const {
723
731
  url,
@@ -736,7 +744,13 @@ class SSFHost {
736
744
  } = popupWindowFeatures;
737
745
  let guest = this.#getGuestForUrl(url);
738
746
  if (guest) {
739
- this.#focusExistingPopupGuest(guest, url, title);
747
+ if (!guest.window.closed) {
748
+ if (isTrustedDomain(url)) {
749
+ window.open("", title);
750
+ } else {
751
+ guest.window.focus();
752
+ }
753
+ }
740
754
  } else {
741
755
  const windowFeatures = Object.entries({ width, height, top, left }).filter(([, v]) => v).map(([k, v]) => `${k}=${v}`).join(",");
742
756
  const { popupUrl, handshakeToken, trusted } = this.#buildPopupUrl(url);
@@ -746,10 +760,27 @@ class SSFHost {
746
760
  `popup, ${windowFeatures}`
747
761
  );
748
762
  if (!guestWindow) {
749
- this.#scheduleGuestLifecycleCallback(onError, guestId, "onError");
763
+ setTimeout(() => {
764
+ try {
765
+ onError?.(guestId);
766
+ } catch (error) {
767
+ this.#logger.debug(
768
+ `Error occurred in onError for guest with id '${guestId}': ${error.message}`
769
+ );
770
+ }
771
+ }, 0);
750
772
  throw new Error("Failed to open guest application in popup window");
773
+ } else {
774
+ setTimeout(() => {
775
+ try {
776
+ onLoad?.(guestId);
777
+ } catch (error) {
778
+ this.#logger.debug(
779
+ `Error occurred in onLoad for guest with id '${guestId}': ${error.message}`
780
+ );
781
+ }
782
+ }, 0);
751
783
  }
752
- this.#scheduleGuestLifecycleCallback(onLoad, guestId, "onLoad");
753
784
  if (!trusted) {
754
785
  guestWindow.opener = null;
755
786
  }
@@ -766,28 +797,53 @@ class SSFHost {
766
797
  }
767
798
  return guest;
768
799
  };
769
- #createEmbedGuestFrame = ({
770
- targetElementDocument,
771
- guestId,
772
- title,
773
- url,
774
- style,
775
- disableSandbox,
776
- sandboxValues,
777
- customSandboxValues,
778
- permissionPolicy,
779
- onLoad,
780
- onError
781
- }) => {
800
+ #openEmbedGuest = (param) => {
801
+ const {
802
+ url,
803
+ title,
804
+ targetElement,
805
+ searchParams,
806
+ guestId,
807
+ onLoad,
808
+ onError,
809
+ options = {}
810
+ } = param;
811
+ const targetElementDocument = targetElement.ownerDocument ?? document;
812
+ const {
813
+ fitToContent = false,
814
+ disableSandbox = false,
815
+ sandboxValues = [],
816
+ customSandboxValues = [],
817
+ style = "",
818
+ permissionPolicy = ""
819
+ } = options;
820
+ if (!title) throw new Error("title is required");
821
+ if (fitToContent) this.#subscribeToGuestResizeEvent();
782
822
  const frame = targetElementDocument.createElement("iframe");
783
823
  frame.setAttribute("id", guestId);
784
824
  const onFrameLoad = () => {
785
- this.#scheduleGuestLifecycleCallback(onLoad, guestId, "onLoad");
825
+ setTimeout(() => {
826
+ try {
827
+ onLoad?.(guestId);
828
+ } catch (error) {
829
+ this.#logger.debug(
830
+ `Error occurred in onLoad for guest with id '${guestId}': ${error.message}`
831
+ );
832
+ }
833
+ }, 0);
786
834
  this.#logger.debug(`frame loaded for guest with id '${guestId}'`);
787
835
  frame.removeEventListener("load", onFrameLoad);
788
836
  };
789
837
  const onFrameLoadFailure = () => {
790
- this.#scheduleGuestLifecycleCallback(onError, guestId, "onError");
838
+ setTimeout(() => {
839
+ try {
840
+ onError?.(guestId);
841
+ } catch (error) {
842
+ this.#logger.debug(
843
+ `Error occurred in onError for guest with id '${guestId}': ${error.message}`
844
+ );
845
+ }
846
+ }, 0);
791
847
  this.#logger.error(`frame load failed for guest with id '${guestId}'`);
792
848
  frame.removeEventListener("error", onFrameLoadFailure);
793
849
  };
@@ -806,41 +862,6 @@ class SSFHost {
806
862
  frame.setAttribute("title", title);
807
863
  frame.setAttribute("src", url);
808
864
  if (permissionPolicy) frame.setAttribute("allow", permissionPolicy);
809
- return frame;
810
- };
811
- #mountEmbedGuest = ({
812
- guestId,
813
- url,
814
- title,
815
- searchParams,
816
- targetElement,
817
- targetElementDocument,
818
- onLoad,
819
- onError,
820
- options
821
- }) => {
822
- const {
823
- fitToContent = false,
824
- disableSandbox = false,
825
- sandboxValues = [],
826
- customSandboxValues = [],
827
- style = "",
828
- permissionPolicy = ""
829
- } = options;
830
- if (fitToContent) this.#subscribeToGuestResizeEvent();
831
- const frame = this.#createEmbedGuestFrame({
832
- targetElementDocument,
833
- guestId,
834
- title,
835
- url,
836
- style,
837
- disableSandbox,
838
- sandboxValues,
839
- customSandboxValues,
840
- permissionPolicy,
841
- onLoad,
842
- onError
843
- });
844
865
  targetElement.appendChild(frame);
845
866
  const guestFrameEle = targetElementDocument.getElementById(
846
867
  guestId
@@ -855,31 +876,6 @@ class SSFHost {
855
876
  openMode: OpenMode.Embed
856
877
  });
857
878
  };
858
- #openEmbedGuest = (param) => {
859
- const {
860
- url,
861
- title,
862
- targetElement,
863
- searchParams,
864
- guestId,
865
- onLoad,
866
- onError,
867
- options = {}
868
- } = param;
869
- if (!title) throw new Error("title is required");
870
- const targetElementDocument = targetElement.ownerDocument ?? document;
871
- return this.#mountEmbedGuest({
872
- guestId,
873
- url,
874
- title,
875
- searchParams,
876
- targetElement,
877
- targetElementDocument,
878
- onLoad,
879
- onError,
880
- options
881
- });
882
- };
883
879
  #getGuestUrl = (url, params) => {
884
880
  let querystring = "";
885
881
  Object.keys(params).forEach((queryParam) => {
@@ -930,7 +926,9 @@ class SSFHost {
930
926
  eventOptions
931
927
  }) => this.dispatchEvent({
932
928
  event,
929
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
933
930
  eventParams,
931
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
934
932
  eventOptions
935
933
  });
936
934
  const token = propValue.subscribe(
@@ -940,18 +938,17 @@ class SSFHost {
940
938
  propValue.unsubscribe(token);
941
939
  });
942
940
  } else {
943
- const v1Proxy = propValue;
944
- const token = v1Proxy.subscribe?.(
945
- (_obj, params, options) => {
946
- void this.dispatchEvent({
947
- event,
948
- eventParams: params,
949
- eventOptions: options
950
- });
951
- }
941
+ const token = propValue.subscribe?.(
942
+ (obj, params, options) => this.dispatchEvent({
943
+ event,
944
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
945
+ eventParams: params,
946
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
947
+ eventOptions: options
948
+ })
952
949
  );
953
950
  unsubscribers.push(() => {
954
- if (token) v1Proxy.unsubscribe?.(token);
951
+ propValue.unsubscribe?.(token);
955
952
  });
956
953
  }
957
954
  } else if (isFunction(propValue)) {
@@ -1014,30 +1011,6 @@ class SSFHost {
1014
1011
  `host is closed. hostId: ${this.hostId}, correlationId: ${this.#correlationId}`
1015
1012
  );
1016
1013
  };
1017
- #buildEventObject = ({
1018
- scriptingObject,
1019
- eventName,
1020
- eventParams,
1021
- eventHandler,
1022
- timeout
1023
- }) => {
1024
- const eventObj = {
1025
- object: scriptingObject._toJSON(),
1026
- eventName,
1027
- eventParams,
1028
- eventHandler,
1029
- eventOptions: {
1030
- allowsFeedback: false
1031
- }
1032
- };
1033
- if (timeout && !Number.isNaN(timeout)) {
1034
- eventObj.eventOptions = {
1035
- allowsFeedback: true,
1036
- timeout: Number(timeout)
1037
- };
1038
- }
1039
- return eventObj;
1040
- };
1041
1014
  #dispatchEventToMatchingGuests = ({
1042
1015
  targetGuest,
1043
1016
  guestCapabilities,
@@ -1062,6 +1035,10 @@ class SSFHost {
1062
1035
  this.#guests.forEach(tryDispatch);
1063
1036
  }
1064
1037
  };
1038
+ #resolveEventSourceObject = (objectId, targetGuest) => {
1039
+ const scriptingObject = targetGuest ? this.getScriptingObject(objectId, { guest: targetGuest }) : this.getScriptingObject(objectId);
1040
+ return scriptingObject ?? (objectId === MODULE_OBJECT_ID && targetGuest ? MODULE_EVENT_STUB : null);
1041
+ };
1065
1042
  /**
1066
1043
  * dispatch event to guest application(s)
1067
1044
  * @param {EventDetail} params details of the event to be dispatched
@@ -1083,20 +1060,32 @@ class SSFHost {
1083
1060
  const objectId = id.split(".")[0];
1084
1061
  const guestIdorWnd = guestId || targetWindow;
1085
1062
  const targetGuest = guestIdorWnd ? this.#findGuest(guestIdorWnd) : null;
1086
- const scriptingObject = targetGuest ? this.getScriptingObject(objectId, { guest: targetGuest }) : this.getScriptingObject(objectId);
1087
- if (!scriptingObject) {
1063
+ const eventSourceObject = this.#resolveEventSourceObject(
1064
+ objectId,
1065
+ targetGuest ?? null
1066
+ );
1067
+ if (!eventSourceObject) {
1088
1068
  this.#logger.warn(
1089
1069
  `Attempt to dispatch event ${name} on unknown object ${objectId}`
1090
1070
  );
1091
1071
  return Promise.resolve([]);
1092
1072
  }
1093
- const eventObj = this.#buildEventObject({
1094
- scriptingObject,
1073
+ const eventObj = {
1074
+ // eslint-disable-next-line no-underscore-dangle
1075
+ object: eventSourceObject._toJSON(),
1095
1076
  eventName: name,
1096
1077
  eventParams,
1097
1078
  eventHandler,
1098
- timeout
1099
- });
1079
+ eventOptions: {
1080
+ allowsFeedback: false
1081
+ }
1082
+ };
1083
+ if (timeout && !Number.isNaN(timeout)) {
1084
+ eventObj.eventOptions = {
1085
+ allowsFeedback: true,
1086
+ timeout: Number(timeout)
1087
+ };
1088
+ }
1100
1089
  const guestPromises = [];
1101
1090
  let eventTimingToken;
1102
1091
  const dispatchToGuest = (guest) => {
@@ -1105,7 +1094,7 @@ class SSFHost {
1105
1094
  guestPromises.push(guest.dispatchEvent(eventObj, timeout));
1106
1095
  if (!eventTimingToken && this.#perfTracker.enabled) {
1107
1096
  eventTimingToken = this.#perfTracker.start(
1108
- `ScriptingObject.Event.${scriptingObject.id}.${name}`,
1097
+ `ScriptingObject.Event.${eventSourceObject.id}.${name}`,
1109
1098
  { appId: this.hostId, appUrl: window.location.href }
1110
1099
  );
1111
1100
  }
@@ -1166,14 +1155,6 @@ class SSFHost {
1166
1155
  * @returns scripting object
1167
1156
  */
1168
1157
  getScriptingObject = (objectId, params) => this.#soManager.getObject(objectId, params?.guest);
1169
- #resolveUniqueGuestInstanceId = (guestId) => {
1170
- if (!this.#guests.has(guestId)) return guestId;
1171
- let counter = 1;
1172
- while (this.#guests.has(`${guestId}-${counter}`)) {
1173
- counter += 1;
1174
- }
1175
- return `${guestId}-${counter}`;
1176
- };
1177
1158
  /**
1178
1159
  * loads guest application inside sandboxed iframe
1179
1160
  * @param {LoadGuestParam} param - parameters for loading the guest application
@@ -1192,14 +1173,21 @@ class SSFHost {
1192
1173
  metadata
1193
1174
  } = param;
1194
1175
  if (!guestId) throw new Error("id for guest application is required");
1195
- const instanceId = this.#resolveUniqueGuestInstanceId(guestId);
1176
+ let instanceId = guestId;
1177
+ if (this.#guests.has(instanceId)) {
1178
+ let counter = 1;
1179
+ while (this.#guests.has(`${guestId}-${counter}`)) {
1180
+ counter += 1;
1181
+ }
1182
+ instanceId = `${guestId}-${counter}`;
1183
+ }
1196
1184
  const { openMode = OpenMode.Embed, popupWindowFeatures = {} } = options;
1197
1185
  const srcUrl = this.#getGuestUrl(url, searchParams);
1186
+ let guest = null;
1198
1187
  this.#perfTracker.start("SSF.Guest.Load", {
1199
1188
  appId: instanceId,
1200
1189
  appUrl: srcUrl
1201
1190
  });
1202
- let guest;
1203
1191
  if (openMode === OpenMode.Popup) {
1204
1192
  guest = this.#openPopupGuest({
1205
1193
  guestId: instanceId,
@@ -1279,25 +1267,80 @@ class SSFHost {
1279
1267
  this.#guests.forEach(this.#dispatchConfigEvent);
1280
1268
  this.#logger.debug("Dispatched config events to all guests");
1281
1269
  };
1270
+ #dispatchGuestModuleEvent = async (guest, eventId, eventName) => (
1271
+ /* eslint-disable @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any */
1272
+ this.dispatchEvent({
1273
+ event: { id: eventId, name: eventName },
1274
+ eventParams: { moduleId: guest.id },
1275
+ eventOptions: {
1276
+ timeout: MODULE_EVENT_TIMEOUT_MS,
1277
+ guestId: guest.id
1278
+ }
1279
+ })
1280
+ );
1281
+ /* eslint-enable @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any */
1282
+ #canUnloadGuest = async (guest) => {
1283
+ try {
1284
+ const feedback = await this.#dispatchGuestModuleEvent(
1285
+ guest,
1286
+ MODULE_UNLOADING_EVENT,
1287
+ "unloading"
1288
+ );
1289
+ if (isModuleUnloadVetoed(feedback)) {
1290
+ this.#logger.info(
1291
+ `Unload denied by guest ${guest.id} via module.unloading event`
1292
+ );
1293
+ return false;
1294
+ }
1295
+ } catch (err) {
1296
+ this.#logger.warn({
1297
+ message: `Error dispatching module.unloading event for ${guest.id}; proceeding with unload`,
1298
+ exception: err
1299
+ });
1300
+ }
1301
+ return true;
1302
+ };
1303
+ /**
1304
+ * Signal SDK teardown after the module.unloading veto phase passes.
1305
+ * @param guest
1306
+ */
1307
+ #dispatchModuleUnmount = async (guest) => {
1308
+ try {
1309
+ await this.#dispatchGuestModuleEvent(
1310
+ guest,
1311
+ MODULE_UNMOUNT_EVENT,
1312
+ "unmount"
1313
+ );
1314
+ } catch (err) {
1315
+ this.#logger.warn({
1316
+ message: `Error dispatching module.unmount event for ${guest.id}`,
1317
+ exception: err
1318
+ });
1319
+ }
1320
+ };
1321
+ #unloadGuestInBackground = (guestIdOrWindowOrEle) => {
1322
+ this.unloadGuest(guestIdOrWindowOrEle).catch(ignoreRejectedPromise);
1323
+ };
1282
1324
  /**
1283
1325
  * unloads guest application from host
1284
1326
  * @param guestIdOrWindowOrEle unique id of the guest application or window object or dom element of the guest application
1285
1327
  * @throws Error if guestId or Window reference is invalid
1286
1328
  */
1287
- unloadGuest = (guestIdOrWindowOrEle) => {
1329
+ unloadGuest = async (guestIdOrWindowOrEle) => {
1288
1330
  const guest = this.#findGuest(guestIdOrWindowOrEle);
1289
- if (guest) {
1290
- guest.dispose();
1291
- this.#guestsByWindow.delete(guest.window);
1292
- this.#guestsByUrl.delete(guest.url);
1293
- this.#guestMetadata.delete(guest.id);
1294
- this.#guests.delete(guest.id);
1295
- this.#logger.audit({
1296
- message: `Guest is removed from host`,
1297
- ...guest.getInfo()
1298
- });
1299
- this.#stopMonitoringPopupGuests();
1300
- }
1331
+ if (!guest) return;
1332
+ if (!await this.#canUnloadGuest(guest)) return;
1333
+ await this.#dispatchModuleUnmount(guest);
1334
+ guest.dispose();
1335
+ this.#guestsByWindow.delete(guest.window);
1336
+ this.#guestsByUrl.delete(guest.url);
1337
+ this.#guestMetadata.delete(guest.id);
1338
+ this.#guests.delete(guest.id);
1339
+ this.#logger.audit({
1340
+ message: `Guest is removed from host`,
1341
+ ...guest.getInfo()
1342
+ });
1343
+ this.#stopMonitoringPopupGuests();
1301
1344
  };
1302
1345
  /**
1303
1346
  * monitors guest window close action and executes the callback from host.
@@ -49,17 +49,15 @@ const initGuest = (guestId, capabilities = { eventFeedback: true }) => {
49
49
  const releaseJSThread = () => new Promise((resolve) => {
50
50
  setTimeout(resolve, 0);
51
51
  });
52
- const getCallContext = (fn) => {
53
- const callContext = fn.callContext;
54
- if (!callContext) {
55
- throw new Error("callContext not set on function");
56
- }
57
- return callContext;
52
+ const ignoreRejectedPromise = () => {
53
+ };
54
+ const unloadGuestSilently = (host, guestId) => {
55
+ host?.unloadGuest(guestId).catch(ignoreRejectedPromise);
58
56
  };
59
57
  export {
60
58
  createHost,
61
- getCallContext,
62
59
  initGuest,
63
60
  postMessage,
64
- releaseJSThread
61
+ releaseJSThread,
62
+ unloadGuestSilently
65
63
  };
package/dist/esm/utils.js CHANGED
@@ -3,7 +3,7 @@ const getOrigin = (url) => {
3
3
  try {
4
4
  const { origin } = new URL(url);
5
5
  return origin === "null" || !origin ? url : origin;
6
- } catch {
6
+ } catch (e) {
7
7
  const { origin } = new URL(url, document.baseURI);
8
8
  return origin;
9
9
  }