@elliemae/ssf-host 2.30.0 → 2.31.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 (40) hide show
  1. package/dist/cjs/guest.js +75 -31
  2. package/dist/cjs/host.js +263 -82
  3. package/dist/cjs/package.json +1 -4
  4. package/dist/cjs/tests/scriptingObjects/appraisalServiceModule.js +4 -0
  5. package/dist/cjs/tests/scriptingObjects/creditServiceModule.js +4 -0
  6. package/dist/cjs/tests/scriptingObjects/floodServiceModule.js +4 -0
  7. package/dist/esm/guest.js +75 -31
  8. package/dist/esm/host.js +263 -82
  9. package/dist/esm/package.json +1 -4
  10. package/dist/esm/tests/scriptingObjects/appraisalServiceModule.js +4 -0
  11. package/dist/esm/tests/scriptingObjects/creditServiceModule.js +4 -0
  12. package/dist/esm/tests/scriptingObjects/floodServiceModule.js +4 -0
  13. package/dist/public/callchain-host.html +1 -1
  14. package/dist/public/callchain-intermediate.html +1 -1
  15. package/dist/public/e2e-host.html +1 -1
  16. package/dist/public/e2e-index.html +1 -1
  17. package/dist/public/index.html +1 -1
  18. package/dist/public/js/emuiSsfHost.dd636c9bb8bbc719a7fd.js +3 -0
  19. package/dist/public/js/emuiSsfHost.dd636c9bb8bbc719a7fd.js.br +0 -0
  20. package/dist/public/js/emuiSsfHost.dd636c9bb8bbc719a7fd.js.gz +0 -0
  21. package/dist/public/js/emuiSsfHost.dd636c9bb8bbc719a7fd.js.map +1 -0
  22. package/dist/public/popup-focus-host.html +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/host.d.ts +11 -4
  26. package/dist/types/lib/tests/guestHandshake.test.d.ts +1 -0
  27. package/dist/types/lib/tests/scriptingObjects/appObjects.d.ts +2 -0
  28. package/dist/types/lib/tests/scriptingObjects/appraisalServiceModule.d.ts +1 -0
  29. package/dist/types/lib/tests/scriptingObjects/creditServiceModule.d.ts +1 -0
  30. package/dist/types/lib/tests/scriptingObjects/floodServiceModule.d.ts +1 -0
  31. package/dist/types/tsconfig.tsbuildinfo +1 -1
  32. package/dist/umd/index.js +1 -1
  33. package/dist/umd/index.js.br +0 -0
  34. package/dist/umd/index.js.gz +0 -0
  35. package/dist/umd/index.js.map +1 -1
  36. package/package.json +8 -8
  37. package/dist/public/js/emuiSsfHost.14d0a39ec7aadb5abeef.js +0 -3
  38. package/dist/public/js/emuiSsfHost.14d0a39ec7aadb5abeef.js.br +0 -0
  39. package/dist/public/js/emuiSsfHost.14d0a39ec7aadb5abeef.js.gz +0 -0
  40. package/dist/public/js/emuiSsfHost.14d0a39ec7aadb5abeef.js.map +0 -1
package/dist/esm/guest.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { MessageType } from "@elliemae/microfe-common";
2
2
  import { OpenMode } from "./types.js";
3
3
  import { getOrigin } from "./utils.js";
4
+ const HAND_SHAKE_INTERVAL_MS = 1e3;
5
+ const HAND_SHAKE_RETRIES = 5;
4
6
  class Guest {
5
7
  /**
6
8
  * unique id of the guest application
@@ -58,6 +60,18 @@ class Guest {
58
60
  * one-time token for popup handshake when window.opener is unavailable
59
61
  */
60
62
  #handshakeToken;
63
+ /**
64
+ * Active popup handshake interval, if any.
65
+ */
66
+ #handShakeInterval = null;
67
+ /**
68
+ * HandShakeAck listener registered for the active handshake.
69
+ */
70
+ #handShakeAckListener = null;
71
+ /**
72
+ * Resolver for the in-flight {@link handShake} promise.
73
+ */
74
+ #handShakeResolve = null;
61
75
  /**
62
76
  * Create object representing guest application
63
77
  * @param {GuestOption} option - options for creating a guest application
@@ -92,6 +106,7 @@ class Guest {
92
106
  * clean up resources
93
107
  */
94
108
  dispose = () => {
109
+ this.#cancelHandShake(false);
95
110
  if (this.openMode === OpenMode.Popup && !this.window.closed) {
96
111
  try {
97
112
  this.window.document;
@@ -118,45 +133,74 @@ class Guest {
118
133
  guestTitle: this.title,
119
134
  guestUrl: this.url
120
135
  });
136
+ /**
137
+ * Stops an in-flight popup handshake and optionally settles its promise.
138
+ * @param resolveWith when set, resolves a pending handshake with this value
139
+ */
140
+ #cancelHandShake = (resolveWith) => {
141
+ if (this.#handShakeInterval) {
142
+ clearInterval(this.#handShakeInterval);
143
+ this.#handShakeInterval = null;
144
+ }
145
+ if (this.#handShakeAckListener) {
146
+ this.#remoting.unlisten({
147
+ messageType: MessageType.HandShakeAck,
148
+ callback: this.#handShakeAckListener
149
+ });
150
+ this.#handShakeAckListener = null;
151
+ }
152
+ const resolve = this.#handShakeResolve;
153
+ this.#handShakeResolve = null;
154
+ if (resolve && resolveWith !== void 0) {
155
+ resolve(resolveWith);
156
+ }
157
+ };
158
+ /**
159
+ * Sends one HandShake message when a handshake is still active.
160
+ */
161
+ #sendHandShake = () => {
162
+ if (!this.#handShakeResolve) return;
163
+ this.#remoting.send({
164
+ targetWin: this.window,
165
+ targetOrigin: this.origin,
166
+ messageType: MessageType.HandShake,
167
+ messageBody: this.#handshakeToken ? { handshakeToken: this.#handshakeToken } : {}
168
+ });
169
+ };
121
170
  /**
122
171
  * Handshake with the guest application in the popup window
123
172
  * @returns true if the guest popup window is open & connected
124
173
  */
125
- handShake = () => new Promise((resolve) => {
126
- let handShakeCount = 0;
127
- const handShakeRetries = 5;
128
- let handShakeHandle;
129
- const onAck = () => {
130
- clearInterval(handShakeHandle);
131
- this.#remoting.unlisten({
174
+ handShake = () => {
175
+ this.#cancelHandShake(false);
176
+ if (this.openMode !== OpenMode.Popup) {
177
+ return Promise.resolve(false);
178
+ }
179
+ return new Promise((resolve) => {
180
+ let handShakeCount = 0;
181
+ this.#handShakeResolve = resolve;
182
+ const onAck = () => {
183
+ if (!this.#handShakeResolve) return;
184
+ this.#cancelHandShake(true);
185
+ };
186
+ this.#handShakeAckListener = onAck;
187
+ this.#sendHandShake();
188
+ handShakeCount = 1;
189
+ this.#handShakeInterval = setInterval(() => {
190
+ if (!this.#handShakeResolve) return;
191
+ if (handShakeCount >= HAND_SHAKE_RETRIES) {
192
+ this.#cancelHandShake(false);
193
+ return;
194
+ }
195
+ this.#sendHandShake();
196
+ handShakeCount += 1;
197
+ }, HAND_SHAKE_INTERVAL_MS);
198
+ this.#remoting.listen({
132
199
  messageType: MessageType.HandShakeAck,
133
200
  callback: onAck
134
201
  });
135
- resolve(true);
136
- };
137
- handShakeHandle = setInterval(() => {
138
- if (handShakeCount >= handShakeRetries) {
139
- clearInterval(handShakeHandle);
140
- this.#remoting.unlisten({
141
- messageType: MessageType.HandShakeAck,
142
- callback: onAck
143
- });
144
- resolve(false);
145
- } else {
146
- this.#remoting.send({
147
- targetWin: this.window,
148
- targetOrigin: this.origin,
149
- messageType: MessageType.HandShake,
150
- messageBody: this.#handshakeToken ? { handshakeToken: this.#handshakeToken } : {}
151
- });
152
- handShakeCount += 1;
153
- }
154
- }, 1e3);
155
- this.#remoting.listen({
156
- messageType: MessageType.HandShakeAck,
157
- callback: onAck
158
202
  });
159
- });
203
+ };
160
204
  /**
161
205
  * initialize guest messaging
162
206
  */
package/dist/esm/host.js CHANGED
@@ -80,9 +80,26 @@ class SSFHost {
80
80
  */
81
81
  #readyStateCallback = null;
82
82
  /**
83
- *
83
+ * Interval handle for polling popup guests whose window was closed externally.
84
+ */
85
+ #guestLifecycleMonitor = null;
86
+ /**
87
+ * Observes embed iframe removal from the host DOM (replaces polling for embeds).
88
+ */
89
+ #embedDetachObservers = /* @__PURE__ */ new Map();
90
+ /**
91
+ * Guest ids using fitToContent; drives GuestResize Remoting listener lifecycle.
92
+ */
93
+ #fitToContentGuestIds = /* @__PURE__ */ new Set();
94
+ /**
95
+ * Guest ids currently being unloaded (guards observer + explicit double-unload).
96
+ */
97
+ #guestsUnloading = /* @__PURE__ */ new Set();
98
+ /**
99
+ * Guest ids for which {@link onGuestClose} callbacks were already invoked
100
+ * for the current close attempt (dedupes concurrent exit paths).
84
101
  */
85
- #popupGuestMonitor = null;
102
+ #guestCloseNotified = /* @__PURE__ */ new Set();
86
103
  /**
87
104
  * callback for guest event subscription
88
105
  */
@@ -138,7 +155,8 @@ class SSFHost {
138
155
  this.#soManager = new ScriptingObjectManager();
139
156
  this.#remoting.initialize(window);
140
157
  this.#connect();
141
- window.addEventListener("beforeunload", this.#closeAllPopupGuests);
158
+ window.addEventListener("beforeunload", this.#closeAllGuests);
159
+ window.addEventListener("pagehide", this.#closeAllGuests);
142
160
  this.#logger.debug(
143
161
  `host is initialized. hostId: ${this.hostId}, correlationId: ${this.#correlationId}`
144
162
  );
@@ -151,9 +169,29 @@ class SSFHost {
151
169
  );
152
170
  });
153
171
  };
154
- #closeAllPopupGuests = () => {
155
- const popupIds = Array.from(this.#guests.values()).filter((guest) => guest.openMode === OpenMode.Popup).map((guest) => guest.id);
156
- popupIds.forEach((id) => this.#unloadGuestInBackground(id));
172
+ /**
173
+ * Synchronously closes open popup guest windows.
174
+ *
175
+ * During page unload the browser may terminate the host before async
176
+ * {@link unloadGuest} (module.unloading / unmount) completes.
177
+ */
178
+ #closePopupWindowsSync = () => {
179
+ this.#guests.forEach((guest) => {
180
+ if (guest.openMode !== OpenMode.Popup || guest.window?.closed) return;
181
+ guest.dispose();
182
+ });
183
+ };
184
+ /**
185
+ * Unloads every registered guest without awaiting completion.
186
+ *
187
+ * Used on host {@link close}, `beforeunload`, and `pagehide` so embed and
188
+ * popup guests are torn down when the host page unloads.
189
+ */
190
+ #closeAllGuests = () => {
191
+ this.#closePopupWindowsSync();
192
+ Array.from(this.#guests.keys()).forEach(
193
+ (id) => this.#unloadGuestInBackground(id)
194
+ );
157
195
  };
158
196
  /**
159
197
  * get the reference to the guest application by its window
@@ -320,17 +358,18 @@ class SSFHost {
320
358
  }
321
359
  };
322
360
  /**
323
- * cleanup the guest reference when it is closed
324
- * @param param0
325
- * @param param0.sourceWin
361
+ * Handles {@link MessageType.GuestClose} from a guest application.
362
+ *
363
+ * GuestClose is authoritative: the guest has initiated shutdown, so unload
364
+ * immediately regardless of open mode (embed or popup).
365
+ * @param param remoting listener parameters
366
+ * @param param.sourceWin guest window that sent GuestClose
326
367
  */
327
- #handleGuestClose = async ({ sourceWin }) => {
328
- if (sourceWin?.window) {
329
- const guest = this.#findGuest(sourceWin);
330
- if (guest && !await guest.handShake()) {
331
- this.#unloadGuestInBackground(sourceWin);
332
- }
333
- }
368
+ #handleGuestClose = ({ sourceWin }) => {
369
+ if (!sourceWin) return;
370
+ const guest = this.#findGuest(sourceWin);
371
+ if (!guest) return;
372
+ this.#unloadGuestAndNotifyHost(guest.id);
334
373
  };
335
374
  // Handles list objects requests from the remote automation framework
336
375
  #handleListObjects = ({
@@ -503,10 +542,16 @@ class SSFHost {
503
542
  body
504
543
  }) => {
505
544
  const guest = this.#getGuestForWindow(sourceWin);
506
- if (!guest) {
507
- this.#logger.warn(
508
- `Received resize event from unknown guest. requestid = ${requestId}`
509
- );
545
+ if (!guest || !this.#fitToContentGuestIds.has(guest.id) || this.#guestsUnloading.has(guest.id)) {
546
+ if (guest) {
547
+ this.#logger.debug(
548
+ `Ignored resize event from guest ${guest.id}. requestId = ${requestId}`
549
+ );
550
+ } else {
551
+ this.#logger.warn(
552
+ `Received resize event from unknown guest. requestid = ${requestId}`
553
+ );
554
+ }
510
555
  return;
511
556
  }
512
557
  if (guest.domElement) {
@@ -601,7 +646,7 @@ class SSFHost {
601
646
  return true;
602
647
  };
603
648
  /**
604
- * subscribe to guest resize event
649
+ * Registers the shared GuestResize listener when the first fit-to-content guest loads.
605
650
  */
606
651
  #subscribeToGuestResizeEvent = () => {
607
652
  this.#remoting.listen({
@@ -609,6 +654,35 @@ class SSFHost {
609
654
  callback: this.#handleGuestResize
610
655
  });
611
656
  };
657
+ /**
658
+ * Removes the shared GuestResize listener when no fit-to-content guests remain.
659
+ */
660
+ #unsubscribeFromGuestResizeEvent = () => {
661
+ this.#remoting.unlisten({
662
+ messageType: MessageType.GuestResize,
663
+ callback: this.#handleGuestResize
664
+ });
665
+ };
666
+ /**
667
+ * Tracks a fit-to-content embed and ensures the GuestResize listener is active.
668
+ * @param guestId embed guest id
669
+ */
670
+ #registerFitToContentGuest = (guestId) => {
671
+ if (this.#fitToContentGuestIds.has(guestId)) return;
672
+ const isFirst = this.#fitToContentGuestIds.size === 0;
673
+ this.#fitToContentGuestIds.add(guestId);
674
+ if (isFirst) this.#subscribeToGuestResizeEvent();
675
+ };
676
+ /**
677
+ * Stops tracking a fit-to-content embed and unlistens when none remain.
678
+ * @param guestId embed guest id
679
+ */
680
+ #unregisterFitToContentGuest = (guestId) => {
681
+ if (!this.#fitToContentGuestIds.delete(guestId)) return;
682
+ if (this.#fitToContentGuestIds.size === 0) {
683
+ this.#unsubscribeFromGuestResizeEvent();
684
+ }
685
+ };
612
686
  /**
613
687
  * start listening to the remoting messages
614
688
  */
@@ -690,9 +764,83 @@ class SSFHost {
690
764
  (value) => value.domElement === guestIdOrWindowOrEle
691
765
  );
692
766
  };
767
+ /**
768
+ * Returns true when an embed guest's iframe is no longer in the host DOM.
769
+ * @param guest embed guest to inspect
770
+ */
771
+ #isEmbedGuestDetached = (guest) => guest.openMode === OpenMode.Embed && (!guest.domElement || !guest.domElement.isConnected);
772
+ /**
773
+ * Invokes {@link onGuestClose} callbacks registered for a guest id.
774
+ * @param guestId guest application id
775
+ */
776
+ #fireGuestCloseCallbacks = (guestId) => {
777
+ const callbacks = this.#guestCloseCallbackList.get(guestId);
778
+ callbacks?.forEach((callback) => {
779
+ Promise.resolve(callback({ id: guestId })).catch(ignoreRejectedPromise);
780
+ });
781
+ };
782
+ /**
783
+ * Starts guest unload and notifies host {@link onGuestClose} listeners.
784
+ *
785
+ * Used by {@link #handleGuestClose}, embed detach monitoring, and popup
786
+ * lifecycle polling so every exit path behaves consistently.
787
+ * @param guestId guest application id
788
+ */
789
+ #unloadGuestAndNotifyHost = (guestId) => {
790
+ if (!this.#guests.has(guestId)) return;
791
+ if (!this.#guestCloseNotified.has(guestId)) {
792
+ this.#guestCloseNotified.add(guestId);
793
+ this.#fireGuestCloseCallbacks(guestId);
794
+ }
795
+ if (!this.#guestsUnloading.has(guestId)) {
796
+ this.#unloadGuestInBackground(guestId);
797
+ }
798
+ };
799
+ /**
800
+ * Watches an embed iframe's parent for DOM removal and unloads the guest
801
+ * when the iframe is detached (including cross-origin embeds).
802
+ *
803
+ * Uses {@link #isEmbedGuestDetached} in the mutation callback so moving an
804
+ * iframe between containers does not trigger a false unload.
805
+ * @param guest embed guest whose iframe should be observed
806
+ */
807
+ #observeEmbedGuestDetach = (guest) => {
808
+ const iframe = guest.domElement;
809
+ const parent = iframe?.parentNode;
810
+ if (!iframe || !parent) return;
811
+ const observer = new MutationObserver(() => {
812
+ if (!this.#isEmbedGuestDetached(guest)) return;
813
+ this.#unobserveEmbedGuestDetach(guest.id);
814
+ this.#unloadGuestAndNotifyHost(guest.id);
815
+ });
816
+ observer.observe(parent, { childList: true });
817
+ this.#embedDetachObservers.set(guest.id, observer);
818
+ };
819
+ /**
820
+ * Stops observing embed iframe detachment for a guest.
821
+ * @param guestId guest application id
822
+ */
823
+ #unobserveEmbedGuestDetach = (guestId) => {
824
+ this.#embedDetachObservers.get(guestId)?.disconnect();
825
+ this.#embedDetachObservers.delete(guestId);
826
+ };
827
+ /**
828
+ * Disconnects all embed detach {@link MutationObserver} instances.
829
+ *
830
+ * Called from {@link close} before unloading guests.
831
+ */
832
+ #disconnectAllEmbedObservers = () => {
833
+ this.#embedDetachObservers.forEach((observer) => observer.disconnect());
834
+ this.#embedDetachObservers.clear();
835
+ };
836
+ /**
837
+ * Polls open popup guests and unloads any whose window was closed externally.
838
+ *
839
+ * Embed guests use {@link #observeEmbedGuestDetach} instead of this interval.
840
+ */
693
841
  #monitorPopupGuests = () => {
694
- if (this.#popupGuestMonitor) return;
695
- this.#popupGuestMonitor = setInterval(() => {
842
+ if (this.#guestLifecycleMonitor) return;
843
+ this.#guestLifecycleMonitor = setInterval(() => {
696
844
  const guestsToRemove = [];
697
845
  this.#guests.forEach((guest) => {
698
846
  if (guest.openMode === OpenMode.Popup && guest.window.closed) {
@@ -700,24 +848,21 @@ class SSFHost {
700
848
  }
701
849
  });
702
850
  guestsToRemove.forEach((guest) => {
703
- const { id } = guest;
704
- this.#unloadGuestInBackground(id);
705
- const callbacks = this.#guestCloseCallbackList.get(id);
706
- callbacks?.forEach((callback) => {
707
- Promise.resolve(callback({ id })).catch(() => {
708
- });
709
- });
851
+ this.#unloadGuestAndNotifyHost(guest.id);
710
852
  });
711
853
  }, 1e3);
712
854
  };
855
+ /**
856
+ * Stops the popup close poll when no popup guests remain.
857
+ */
713
858
  #stopMonitoringPopupGuests = () => {
714
- if (!this.#popupGuestMonitor) return;
859
+ if (!this.#guestLifecycleMonitor) return;
715
860
  const hasPopups = Array.from(this.#guests.values()).some(
716
861
  (guest) => guest.openMode === OpenMode.Popup
717
862
  );
718
863
  if (!hasPopups) {
719
- clearInterval(this.#popupGuestMonitor);
720
- this.#popupGuestMonitor = null;
864
+ clearInterval(this.#guestLifecycleMonitor);
865
+ this.#guestLifecycleMonitor = null;
721
866
  }
722
867
  };
723
868
  #buildPopupUrl = (url) => {
@@ -797,6 +942,32 @@ class SSFHost {
797
942
  }
798
943
  return guest;
799
944
  };
945
+ #notifyGuestFrameCallback = (guestId, callback, label) => {
946
+ setTimeout(() => {
947
+ try {
948
+ callback?.(guestId);
949
+ } catch (error) {
950
+ this.#logger.debug(
951
+ `Error occurred in ${label} for guest with id '${guestId}': ${error.message}`
952
+ );
953
+ }
954
+ }, 0);
955
+ };
956
+ #bindEmbedFrameEvents = (frame, guestId, callbacks = {}) => {
957
+ const { onLoad, onError } = callbacks;
958
+ const onFrameLoad = () => {
959
+ this.#notifyGuestFrameCallback(guestId, onLoad, "onLoad");
960
+ this.#logger.debug(`frame loaded for guest with id '${guestId}'`);
961
+ frame.removeEventListener("load", onFrameLoad);
962
+ };
963
+ const onFrameLoadFailure = () => {
964
+ this.#notifyGuestFrameCallback(guestId, onError, "onError");
965
+ this.#logger.error(`frame load failed for guest with id '${guestId}'`);
966
+ frame.removeEventListener("error", onFrameLoadFailure);
967
+ };
968
+ frame.addEventListener("load", onFrameLoad);
969
+ frame.addEventListener("error", onFrameLoadFailure);
970
+ };
800
971
  #openEmbedGuest = (param) => {
801
972
  const {
802
973
  url,
@@ -818,37 +989,9 @@ class SSFHost {
818
989
  permissionPolicy = ""
819
990
  } = options;
820
991
  if (!title) throw new Error("title is required");
821
- if (fitToContent) this.#subscribeToGuestResizeEvent();
822
992
  const frame = targetElementDocument.createElement("iframe");
823
993
  frame.setAttribute("id", guestId);
824
- const onFrameLoad = () => {
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);
834
- this.#logger.debug(`frame loaded for guest with id '${guestId}'`);
835
- frame.removeEventListener("load", onFrameLoad);
836
- };
837
- const onFrameLoadFailure = () => {
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);
847
- this.#logger.error(`frame load failed for guest with id '${guestId}'`);
848
- frame.removeEventListener("error", onFrameLoadFailure);
849
- };
850
- frame.addEventListener("load", onFrameLoad);
851
- frame.addEventListener("error", onFrameLoadFailure);
994
+ this.#bindEmbedFrameEvents(frame, guestId, { onLoad, onError });
852
995
  frame.setAttribute(
853
996
  "style",
854
997
  `min-width: 100%; height: 100%; border: 0px; ${style}`
@@ -866,7 +1009,7 @@ class SSFHost {
866
1009
  const guestFrameEle = targetElementDocument.getElementById(
867
1010
  guestId
868
1011
  );
869
- return this.#attachGuest({
1012
+ const guest = this.#attachGuest({
870
1013
  guestId,
871
1014
  domElement: guestFrameEle,
872
1015
  window: guestFrameEle.contentWindow,
@@ -875,6 +1018,9 @@ class SSFHost {
875
1018
  searchParams,
876
1019
  openMode: OpenMode.Embed
877
1020
  });
1021
+ if (fitToContent) this.#registerFitToContentGuest(guest.id);
1022
+ this.#observeEmbedGuestDetach(guest);
1023
+ return guest;
878
1024
  };
879
1025
  #getGuestUrl = (url, params) => {
880
1026
  let querystring = "";
@@ -996,17 +1142,27 @@ class SSFHost {
996
1142
  return so;
997
1143
  };
998
1144
  /**
999
- * dispose the resources used by the host application
1145
+ * Disposes resources used by the host application.
1146
+ *
1147
+ * Stops guest monitors, unloads all guests (embed and popup), clears
1148
+ * guest-scoped scripting objects, close callbacks, metadata, and remoting.
1000
1149
  */
1001
1150
  close = () => {
1002
- if (this.#popupGuestMonitor) {
1003
- clearInterval(this.#popupGuestMonitor);
1004
- this.#popupGuestMonitor = null;
1151
+ if (this.#guestLifecycleMonitor) {
1152
+ clearInterval(this.#guestLifecycleMonitor);
1153
+ this.#guestLifecycleMonitor = null;
1005
1154
  }
1006
- this.#closeAllPopupGuests();
1155
+ this.#disconnectAllEmbedObservers();
1156
+ this.#closeAllGuests();
1157
+ this.#fitToContentGuestIds.clear();
1158
+ this.#guestCloseNotified.clear();
1159
+ this.#unsubscribeFromGuestResizeEvent();
1160
+ this.#guestCloseCallbackList.clear();
1161
+ this.removeAllScriptingObjects();
1007
1162
  this.#guestMetadata.clear();
1008
1163
  this.#remoting.close();
1009
- window.removeEventListener("beforeunload", this.#closeAllPopupGuests);
1164
+ window.removeEventListener("beforeunload", this.#closeAllGuests);
1165
+ window.removeEventListener("pagehide", this.#closeAllGuests);
1010
1166
  this.#logger.debug(
1011
1167
  `host is closed. hostId: ${this.hostId}, correlationId: ${this.#correlationId}`
1012
1168
  );
@@ -1318,33 +1474,58 @@ class SSFHost {
1318
1474
  });
1319
1475
  }
1320
1476
  };
1477
+ /**
1478
+ * Fire-and-forget wrapper around {@link unloadGuest} for monitors and event handlers.
1479
+ * @param guestIdOrWindowOrEle unique id, window, or iframe element of the guest
1480
+ */
1321
1481
  #unloadGuestInBackground = (guestIdOrWindowOrEle) => {
1322
1482
  this.unloadGuest(guestIdOrWindowOrEle).catch(ignoreRejectedPromise);
1323
1483
  };
1324
- /**
1325
- * unloads guest application from host
1326
- * @param guestIdOrWindowOrEle unique id of the guest application or window object or dom element of the guest application
1327
- * @throws Error if guestId or Window reference is invalid
1328
- */
1329
- unloadGuest = async (guestIdOrWindowOrEle) => {
1330
- const guest = this.#findGuest(guestIdOrWindowOrEle);
1331
- if (!guest) return;
1332
- const windowAlreadyClosed = Boolean(guest.window?.closed);
1333
- if (!windowAlreadyClosed) {
1334
- if (!await this.#canUnloadGuest(guest)) return;
1335
- await this.#dispatchModuleUnmount(guest);
1336
- }
1484
+ #finalizeGuestRemoval = (guest) => {
1485
+ this.#unobserveEmbedGuestDetach(guest.id);
1486
+ this.#unregisterFitToContentGuest(guest.id);
1337
1487
  guest.dispose();
1488
+ this.removeAllScriptingObjects(guest.id);
1338
1489
  this.#guestsByWindow.delete(guest.window);
1339
1490
  this.#guestsByUrl.delete(guest.url);
1340
1491
  this.#guestMetadata.delete(guest.id);
1341
1492
  this.#guests.delete(guest.id);
1493
+ this.#guestCloseCallbackList.delete(guest.id);
1494
+ this.#guestCloseNotified.delete(guest.id);
1342
1495
  this.#logger.audit({
1343
1496
  message: `Guest is removed from host`,
1344
1497
  ...guest.getInfo()
1345
1498
  });
1346
1499
  this.#stopMonitoringPopupGuests();
1347
1500
  };
1501
+ /**
1502
+ * Unloads a guest application from the host.
1503
+ *
1504
+ * Disposes the guest, removes guest-scoped scripting objects, and clears
1505
+ * host registries. When the popup window is already closed or the embed
1506
+ * iframe was removed from the DOM, module unload veto/unmount is skipped
1507
+ * and host-side cleanup proceeds immediately.
1508
+ * @param guestIdOrWindowOrEle unique id, window, or iframe element of the guest
1509
+ */
1510
+ unloadGuest = async (guestIdOrWindowOrEle) => {
1511
+ const guest = this.#findGuest(guestIdOrWindowOrEle);
1512
+ if (!guest) return;
1513
+ if (this.#guestsUnloading.has(guest.id)) return;
1514
+ this.#guestsUnloading.add(guest.id);
1515
+ try {
1516
+ const guestContextDestroyed = Boolean(guest.window?.closed) || this.#isEmbedGuestDetached(guest);
1517
+ if (!guestContextDestroyed) {
1518
+ if (!await this.#canUnloadGuest(guest)) {
1519
+ this.#guestCloseNotified.delete(guest.id);
1520
+ return;
1521
+ }
1522
+ await this.#dispatchModuleUnmount(guest);
1523
+ }
1524
+ this.#finalizeGuestRemoval(guest);
1525
+ } finally {
1526
+ this.#guestsUnloading.delete(guest.id);
1527
+ }
1528
+ };
1348
1529
  /**
1349
1530
  * monitors guest window close action and executes the callback from host.
1350
1531
  * @param callback host callback method
@@ -1,7 +1,4 @@
1
1
  {
2
2
  "type": "module",
3
- "sideEffects": false,
4
- "publishConfig": {
5
- "access": "public"
6
- }
3
+ "sideEffects": false
7
4
  }
@@ -18,6 +18,10 @@ class AppraisalService extends ScriptingObject {
18
18
  name: "Unloading",
19
19
  objectId: this.constructor.name
20
20
  });
21
+ Unmount = new Event({
22
+ name: "Unmount",
23
+ objectId: this.constructor.name
24
+ });
21
25
  onPreCommit = new Event({
22
26
  name: "onPreCommit",
23
27
  objectId: this.constructor.name
@@ -10,6 +10,10 @@ class CreditService extends ScriptingObject {
10
10
  name: "Unloading",
11
11
  objectId: this.constructor.name
12
12
  });
13
+ Unmount = new Event({
14
+ name: "Unmount",
15
+ objectId: this.constructor.name
16
+ });
13
17
  constructor() {
14
18
  super(CREDIT_SERVICE_OBJECT);
15
19
  }
@@ -11,6 +11,10 @@ class FloodService extends ScriptingObject {
11
11
  name: "Unloading",
12
12
  objectId: this.constructor.name
13
13
  });
14
+ Unmount = new Event({
15
+ name: "Unmount",
16
+ objectId: this.constructor.name
17
+ });
14
18
  constructor() {
15
19
  super("FloodService");
16
20
  this.firstName = "John";
@@ -1,4 +1,4 @@
1
- <!doctype html><html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>CallChain E2E Test - Root Host</title><script src="https://cdn.tailwindcss.com?plugins=forms"></script><script src="https://cdn.mortgagetech.q1.ice.com/pui-diagnostics@3"></script><script defer="defer" src="js/emuiSsfHost.14d0a39ec7aadb5abeef.js"></script></head><body class="bg-gray-50"><header class="bg-indigo-600 text-white px-4 py-3 flex items-center justify-between"><h1 class="text-lg font-semibold">CallChain E2E Test — Root Host (A)</h1><a href="./index.html" class="text-indigo-200 hover:text-white text-sm">&larr; Back to main</a></header><main class="mx-auto max-w-7xl px-4 py-4"><div class="grid grid-cols-2 gap-4 mb-4"><div class="bg-blue-50 border border-blue-200 rounded-md p-3"><h2 class="text-sm font-bold text-blue-900 mb-2">Architecture</h2><pre class="text-xs text-blue-800 leading-relaxed">
1
+ <!doctype html><html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>CallChain E2E Test - Root Host</title><script src="https://cdn.tailwindcss.com?plugins=forms"></script><script src="https://cdn.mortgagetech.q1.ice.com/pui-diagnostics@3"></script><script defer="defer" src="js/emuiSsfHost.dd636c9bb8bbc719a7fd.js"></script></head><body class="bg-gray-50"><header class="bg-indigo-600 text-white px-4 py-3 flex items-center justify-between"><h1 class="text-lg font-semibold">CallChain E2E Test — Root Host (A)</h1><a href="./index.html" class="text-indigo-200 hover:text-white text-sm">&larr; Back to main</a></header><main class="mx-auto max-w-7xl px-4 py-4"><div class="grid grid-cols-2 gap-4 mb-4"><div class="bg-blue-50 border border-blue-200 rounded-md p-3"><h2 class="text-sm font-bold text-blue-900 mb-2">Architecture</h2><pre class="text-xs text-blue-800 leading-relaxed">
2
2
  Root Host (A) [localhost:4000]
3
3
  ├─ Exposes: <strong>TestService</strong> scripting object
4
4
  ├─ Loads guest <strong>"intermediateHost"</strong>
@@ -1 +1 @@
1
- <!doctype html><html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>Intermediate Guest+Host (B)</title><script src="https://cdn.tailwindcss.com?plugins=forms"></script><script src="https://cdn.mortgagetech.q1.ice.com/pui-diagnostics@3"></script><script src="http://localhost:4001/index.js"></script><script defer="defer" src="js/emuiSsfHost.14d0a39ec7aadb5abeef.js"></script></head><body class="bg-orange-50 p-2"><h2 class="text-sm font-semibold text-orange-800 mb-1">Intermediate (B) — Guest + Host</h2><div data-testid="intermediate-status" id="status" class="text-xs bg-orange-100 rounded p-2 mb-2 min-h-[30px]">Initializing...</div><div data-testid="grandchild-container" id="grandchild-container" class="border border-dashed border-orange-400 rounded h-[250px]"></div><script type="module">import{Analytics}from"./analytics-object-v2.js";import{getGuestBaseUrl,getHost}from"./utils.js";const statusEl=document.getElementById("status"),log=t=>{const e=(new Date).toLocaleTimeString();statusEl.innerHTML+=`<div>[${e}] ${t}</div>`};(async()=>{try{log("Connecting to Root Host (A) as V2 guest...");const t=new ice.guest.SSFGuest({logger:{index:"intermediate-guest",team:"ui platform",appName:"intermediate-b"},keepAlive:!1});await t.connect(),log("Connected to Root Host (A)");const e=await t.getObject("TestService");log("Got TestService proxy from Root Host (A)");const o=new Analytics,a=getHost(o);if(!a)return void log("ERROR: Failed to create intermediate SSFHost");log("Created intermediate SSFHost (B)");const n=a.cloneScriptingObject(e);a.addScriptingObject(n),log("Cloned TestService for grandchild guests");const i=await getGuestBaseUrl();a.loadGuest({id:"grandchildGuest",url:new URL("./callchain-grandchild.html",i).href,title:"Grandchild Guest (C)",targetElement:document.getElementById("grandchild-container"),metadata:{role:"validator",region:"US-East"},onLoad:()=>log("Grandchild guest (C) loaded"),onError:()=>log("ERROR: Grandchild guest (C) failed to load")}),log("Intermediate (B) ready")}catch(t){log(`ERROR: ${t.message}`)}})()</script></body></html>
1
+ <!doctype html><html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>Intermediate Guest+Host (B)</title><script src="https://cdn.tailwindcss.com?plugins=forms"></script><script src="https://cdn.mortgagetech.q1.ice.com/pui-diagnostics@3"></script><script src="http://localhost:4001/index.js"></script><script defer="defer" src="js/emuiSsfHost.dd636c9bb8bbc719a7fd.js"></script></head><body class="bg-orange-50 p-2"><h2 class="text-sm font-semibold text-orange-800 mb-1">Intermediate (B) — Guest + Host</h2><div data-testid="intermediate-status" id="status" class="text-xs bg-orange-100 rounded p-2 mb-2 min-h-[30px]">Initializing...</div><div data-testid="grandchild-container" id="grandchild-container" class="border border-dashed border-orange-400 rounded h-[250px]"></div><script type="module">import{Analytics}from"./analytics-object-v2.js";import{getGuestBaseUrl,getHost}from"./utils.js";const statusEl=document.getElementById("status"),log=t=>{const e=(new Date).toLocaleTimeString();statusEl.innerHTML+=`<div>[${e}] ${t}</div>`};(async()=>{try{log("Connecting to Root Host (A) as V2 guest...");const t=new ice.guest.SSFGuest({logger:{index:"intermediate-guest",team:"ui platform",appName:"intermediate-b"},keepAlive:!1});await t.connect(),log("Connected to Root Host (A)");const e=await t.getObject("TestService");log("Got TestService proxy from Root Host (A)");const o=new Analytics,a=getHost(o);if(!a)return void log("ERROR: Failed to create intermediate SSFHost");log("Created intermediate SSFHost (B)");const n=a.cloneScriptingObject(e);a.addScriptingObject(n),log("Cloned TestService for grandchild guests");const i=await getGuestBaseUrl();a.loadGuest({id:"grandchildGuest",url:new URL("./callchain-grandchild.html",i).href,title:"Grandchild Guest (C)",targetElement:document.getElementById("grandchild-container"),metadata:{role:"validator",region:"US-East"},onLoad:()=>log("Grandchild guest (C) loaded"),onError:()=>log("ERROR: Grandchild guest (C) failed to load")}),log("Intermediate (B) ready")}catch(t){log(`ERROR: ${t.message}`)}})()</script></body></html>