@elliemae/ssf-host 2.25.3 → 2.25.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/host.js CHANGED
@@ -1238,30 +1238,574 @@ class SSFHost {
1238
1238
  this.#logger.debug("Dispatched config events to all guests");
1239
1239
  };
1240
1240
  /**
1241
- * unloads guest application from host
1242
- * @param guestIdOrWindowOrEle unique id of the guest application or window object or dom element of the guest application
1243
- * @throws Error if guestId or Window reference is invalid
1241
+ * Call cleanup function on guest window.emui
1242
+ * @param {object} options - Cleanup options
1243
+ * @param {any} options.guestEmui - The window.emui object
1244
+ * @param {string} options.cleanupFunctionName - Function name to call
1245
+ * @param {string} options.context - Context for logging
1244
1246
  */
1245
- unloadGuest = (guestIdOrWindowOrEle) => {
1247
+ #callGuestCleanupFunction = (options) => {
1248
+ const { guestEmui, cleanupFunctionName, context } = options;
1249
+ const emuiObj = guestEmui;
1250
+ const cleanupFn = emuiObj[cleanupFunctionName];
1251
+ if (typeof cleanupFn !== "function") {
1252
+ return;
1253
+ }
1254
+ try {
1255
+ cleanupFn();
1256
+ this.#logger.debug(
1257
+ `[SSF] Called window.emui.${String(cleanupFunctionName)}() for ${String(
1258
+ context
1259
+ )}`
1260
+ );
1261
+ } catch (e) {
1262
+ this.#logger.warn(
1263
+ `[SSF] emui.${String(cleanupFunctionName)}() threw error for ${String(
1264
+ context
1265
+ )}: ${e.message}`
1266
+ );
1267
+ } finally {
1268
+ guestEmui[cleanupFunctionName] = null;
1269
+ }
1270
+ };
1271
+ /**
1272
+ * Null window.emui.app properties
1273
+ * @param {Record<string, unknown> | unknown} app - The window.emui.app object
1274
+ */
1275
+ #nullAppProperties = (app) => {
1276
+ if (typeof app !== "object" || app === null) {
1277
+ return;
1278
+ }
1279
+ const appObj = app;
1280
+ appObj.init = null;
1281
+ appObj.mount = null;
1282
+ appObj.unmount = null;
1283
+ appObj.getRef = null;
1284
+ appObj.navigate = null;
1285
+ };
1286
+ /**
1287
+ * Null all window.emui properties
1288
+ * @param {Record<string, unknown> | unknown} guestEmui - The window.emui object
1289
+ */
1290
+ #nullEmuiProperties = (guestEmui) => {
1291
+ if (typeof guestEmui !== "object" || guestEmui === null) {
1292
+ return;
1293
+ }
1294
+ const emuiObj = guestEmui;
1295
+ if (emuiObj.app) {
1296
+ this.#nullAppProperties(emuiObj.app);
1297
+ emuiObj.app = null;
1298
+ }
1299
+ emuiObj.registerApp = null;
1300
+ emuiObj.logRocket = null;
1301
+ emuiObj.getEnvironment = null;
1302
+ emuiObj.loadScript = null;
1303
+ emuiObj.loadStylesheet = null;
1304
+ emuiObj.unmount = null;
1305
+ };
1306
+ /**
1307
+ * Disconnect FieldMutation observer for iframe
1308
+ * @param {Window | null} contentWindow - The iframe contentWindow
1309
+ * @param {string} guestId - Guest ID for logging
1310
+ */
1311
+ #disconnectFieldMutationObserver = (contentWindow, guestId) => {
1312
+ try {
1313
+ const bodyElement = contentWindow?.document?.body;
1314
+ if (!bodyElement) return;
1315
+ const { observerReferences } = window;
1316
+ if (!observerReferences || !(observerReferences instanceof Map)) {
1317
+ return;
1318
+ }
1319
+ if (!observerReferences.has(bodyElement)) return;
1320
+ const observer = observerReferences.get(bodyElement);
1321
+ if (observer && typeof observer.disconnect === "function") {
1322
+ observer.disconnect();
1323
+ observerReferences.delete(bodyElement);
1324
+ this.#logger.debug(
1325
+ `[SSF] Disconnected FieldMutation observer for guest ${guestId}`
1326
+ );
1327
+ }
1328
+ } catch (e) {
1329
+ this.#logger.debug(
1330
+ `[SSF] Failed to disconnect FieldMutation observer for guest ${guestId}: ${e.message}`
1331
+ );
1332
+ }
1333
+ };
1334
+ /**
1335
+ * Close contentWindow explicitly
1336
+ * @param {Window | null} contentWindow - The iframe contentWindow
1337
+ * @param {string} guestId - Guest ID for logging
1338
+ */
1339
+ #closeContentWindow = (contentWindow, guestId) => {
1340
+ try {
1341
+ if (!contentWindow || contentWindow.closed) return;
1342
+ contentWindow.close();
1343
+ this.#logger.debug(
1344
+ `[SSF] Called contentWindow.close() for guest ${guestId}`
1345
+ );
1346
+ } catch (e) {
1347
+ this.#logger.debug(
1348
+ `[SSF] contentWindow.close() failed for guest ${guestId}: ${e.message}`
1349
+ );
1350
+ }
1351
+ };
1352
+ /**
1353
+ * Navigate iframe to about:blank
1354
+ * @param {HTMLIFrameElement} iframe - The iframe element
1355
+ * @param {string} guestId - Guest ID for logging
1356
+ */
1357
+ #navigateToBlank = (iframe, guestId) => {
1358
+ try {
1359
+ if (!iframe.parentNode) return;
1360
+ iframe.src = "about:blank";
1361
+ this.#logger.debug(`[SSF] Navigated to about:blank for guest ${guestId}`);
1362
+ } catch (e) {
1363
+ this.#logger.debug(
1364
+ `[SSF] Navigation to about:blank failed for guest ${guestId}: ${e.message}`
1365
+ );
1366
+ }
1367
+ };
1368
+ /**
1369
+ * Cleanup window.elli.script properties
1370
+ * @param {Window} guestWindow - Guest window
1371
+ * @param {string} context - Context string for logging
1372
+ */
1373
+ #cleanupElliScript = (guestWindow, context) => {
1374
+ try {
1375
+ const windowWithElli = guestWindow;
1376
+ const { elli } = windowWithElli;
1377
+ if (elli?.script && typeof elli.script === "object") {
1378
+ const { script } = elli;
1379
+ if (script && script.guest && typeof script.guest === "object") {
1380
+ const { guest } = script;
1381
+ const guestObj = guest;
1382
+ guestObj.create = null;
1383
+ }
1384
+ if (script) {
1385
+ script.guest = null;
1386
+ script.connect = null;
1387
+ script.getObject = null;
1388
+ script.setLogLevel = null;
1389
+ script.subscribe = null;
1390
+ script.unsubscribe = null;
1391
+ elli.script = null;
1392
+ }
1393
+ this.#logger.debug(
1394
+ `[SSF] Nulled all window.elli.script properties for ${context}`
1395
+ );
1396
+ }
1397
+ } catch (e) {
1398
+ this.#logger.debug(
1399
+ `[SSF] Failed to cleanup window.elli: ${e.message}`
1400
+ );
1401
+ }
1402
+ };
1403
+ /**
1404
+ * Clear Google Tag Manager data layer
1405
+ * @param {Window} guestWindow - Guest window
1406
+ * @param {string} context - Context string for logging
1407
+ */
1408
+ #clearGtmDataLayer = (guestWindow, context) => {
1409
+ try {
1410
+ const windowWithGtm = guestWindow;
1411
+ if (windowWithGtm.gtmDataLayer) {
1412
+ windowWithGtm.gtmDataLayer = null;
1413
+ this.#logger.debug(`[SSF] Cleared gtmDataLayer for ${context}`);
1414
+ }
1415
+ } catch (e) {
1416
+ this.#logger.debug(
1417
+ `[SSF] Failed to cleanup GTM data layer: ${e.message}`
1418
+ );
1419
+ }
1420
+ };
1421
+ /**
1422
+ * Cleanup window.emui properties
1423
+ * @param {unknown} guestEmui - Guest window.emui object
1424
+ * @param {string} context - Context string for logging
1425
+ */
1426
+ #cleanupEmuiProperties = (guestEmui, context) => {
1427
+ try {
1428
+ if (typeof guestEmui === "object" && guestEmui !== null) {
1429
+ this.#nullEmuiProperties(guestEmui);
1430
+ }
1431
+ this.#logger.debug(
1432
+ `[SSF] Nulled all window.emui properties for ${context}`
1433
+ );
1434
+ } catch (e) {
1435
+ this.#logger.debug(
1436
+ `[SSF] Failed to cleanup window.emui: ${e.message}`
1437
+ );
1438
+ }
1439
+ };
1440
+ /**
1441
+ * Cleanup guest window context - nulls all window.emui and window.elli.script properties
1442
+ * This breaks closure retention chains and allows GC of webpack bundles, SDKs, and singletons
1443
+ * @param {object} options - Cleanup options
1444
+ * @param {Window | null} options.guestWindow - The guest window
1445
+ * @param {string} options.guestId - Guest ID for logging
1446
+ * @param {string} options.cleanupFunctionName - Cleanup function name
1447
+ * @param {string} options.windowType - Window type for logging
1448
+ */
1449
+ #cleanupGuestWindow = (options) => {
1450
+ const {
1451
+ guestWindow,
1452
+ guestId,
1453
+ cleanupFunctionName,
1454
+ windowType = "iframe"
1455
+ } = options;
1456
+ if (!guestWindow) {
1457
+ this.#logger.debug(
1458
+ `No ${windowType} window available for cleanup of guest ${guestId}`
1459
+ );
1460
+ return;
1461
+ }
1462
+ const context = `${windowType} ${guestId}`;
1463
+ try {
1464
+ const windowWithEmui = guestWindow;
1465
+ const guestEmui = windowWithEmui.emui;
1466
+ if (!guestEmui) {
1467
+ this.#logger.debug(`No window.emui found for ${context}`);
1468
+ return;
1469
+ }
1470
+ this.#callGuestCleanupFunction({
1471
+ guestEmui,
1472
+ cleanupFunctionName,
1473
+ context
1474
+ });
1475
+ this.#cleanupEmuiProperties(guestEmui, context);
1476
+ this.#cleanupElliScript(guestWindow, context);
1477
+ this.#clearGtmDataLayer(guestWindow, context);
1478
+ } catch (e) {
1479
+ this.#logger.debug(
1480
+ `[SSF] Could not access ${windowType} window for cleanup (guest ${guestId}): ${e.message}`
1481
+ );
1482
+ }
1483
+ };
1484
+ /**
1485
+ * Navigate to parent of target property
1486
+ * @param {string[]} parts - Path parts
1487
+ * @param {string} path - Full path for logging
1488
+ * @param {string} guestId - Guest ID for logging
1489
+ * @returns {object | null} Navigation result with current object and parent chain
1490
+ */
1491
+ #navigateToParent = (parts, path, guestId) => {
1492
+ const parentChain = [];
1493
+ let current = window;
1494
+ for (let i = 0; i < parts.length - 1; i += 1) {
1495
+ const part = parts[i];
1496
+ if (current[part] === void 0 || current[part] === null) {
1497
+ this.#logger.debug(
1498
+ `Path "${path}" does not exist (stopped at ${part}) for guest ${guestId}`
1499
+ );
1500
+ return null;
1501
+ }
1502
+ parentChain.push({ obj: current, key: part });
1503
+ current = current[part];
1504
+ }
1505
+ return { current, parentChain };
1506
+ };
1507
+ /**
1508
+ * Clean up empty parent objects in chain
1509
+ * @param {Array<{obj: Record<string, unknown>, key: string}>} parentChain - Chain of parent objects
1510
+ * @param {string[]} parts - Path parts for logging
1511
+ * @param {string} guestId - Guest ID for logging
1512
+ */
1513
+ #cleanupParentChain = (parentChain, parts, guestId) => {
1514
+ for (let i = parentChain.length - 1; i >= 0; i -= 1) {
1515
+ const { obj, key } = parentChain[i];
1516
+ const parent = obj[key];
1517
+ if (!parent || typeof parent !== "object" || !this.#isEmptyOrNullObject(parent)) {
1518
+ break;
1519
+ }
1520
+ obj[key] = null;
1521
+ this.#logger.debug(
1522
+ `Cleaned up empty parent object at ${parts.slice(0, i + 1).join(".")} for guest ${guestId}`
1523
+ );
1524
+ }
1525
+ };
1526
+ /**
1527
+ * Recursively clear window references by path string
1528
+ * Handles nested paths like "window.IMT.focusFormTitle" or "window.emui.app"
1529
+ * Sets each reference to null and cleans up empty parent objects
1530
+ * @param {string[]} paths - Array of dot-separated paths to window properties
1531
+ * @param {string} guestId - Guest ID for logging purposes
1532
+ * @example
1533
+ * // Clear window.IMT.focusFormTitle and cleanup window.IMT if empty
1534
+ * clearWindowRefs(["window.IMT.focusFormTitle"], "my-guest-id");
1535
+ * @example
1536
+ * // Clear multiple refs
1537
+ * clearWindowRefs(["window.IMT.focusFormTitle", "window.emui.app"], "my-guest-id");
1538
+ */
1539
+ #clearWindowRefs = (paths, guestId) => {
1540
+ if (!paths || paths.length === 0) return;
1541
+ paths.forEach((path) => {
1542
+ try {
1543
+ const parts = path.split(".").filter((p) => p !== "window" && p.trim() !== "");
1544
+ if (parts.length === 0) {
1545
+ this.#logger.debug(
1546
+ `Invalid path "${path}" - skipping for guest ${guestId}`
1547
+ );
1548
+ return;
1549
+ }
1550
+ const result = this.#navigateToParent(parts, path, guestId);
1551
+ if (!result) return;
1552
+ const { current, parentChain } = result;
1553
+ const targetProp = parts[parts.length - 1];
1554
+ if (current[targetProp] === void 0) {
1555
+ return;
1556
+ }
1557
+ current[targetProp] = null;
1558
+ this.#logger.debug(
1559
+ `Cleared window reference: ${path} for guest ${guestId}`
1560
+ );
1561
+ this.#cleanupParentChain(parentChain, parts, guestId);
1562
+ } catch (e) {
1563
+ this.#logger.debug(
1564
+ `Failed to clear window reference "${path}" for guest ${guestId}: ${e.message}`
1565
+ );
1566
+ }
1567
+ });
1568
+ };
1569
+ /**
1570
+ * Check if an object is empty or only contains null/undefined values
1571
+ * Used to determine if parent objects should be cleaned up after nulling child properties
1572
+ * @param {unknown} obj - Object to check
1573
+ * @returns {boolean} true if object has no properties or all properties are null/undefined
1574
+ */
1575
+ #isEmptyOrNullObject = (obj) => {
1576
+ if (obj === null || obj === void 0 || typeof obj !== "object")
1577
+ return true;
1578
+ const keys = Object.keys(obj);
1579
+ if (keys.length === 0) return true;
1580
+ const record = obj;
1581
+ return keys.every(
1582
+ (key) => record[key] === null || record[key] === void 0
1583
+ );
1584
+ };
1585
+ /**
1586
+ * Unloads guest application from host with optional enhanced cleanup.
1587
+ *
1588
+ * **Basic Mode (no options):**
1589
+ * - Standard guest disposal
1590
+ * - Removes from tracking maps
1591
+ *
1592
+ * **Enhanced Mode (with options):**
1593
+ * - `purgeOnDestroy: true` - Uses comprehensive cleanup via `unloadGuestWithFullCleanup`
1594
+ * - Calls guest cleanup function (React unmount, Redux teardown)
1595
+ * - Closes contentWindow context
1596
+ * - Navigates iframe to about:blank
1597
+ * - Removes iframe from DOM (deferred)
1598
+ * - Clears all window.emui and window.elli.script references
1599
+ * - Disconnects FieldMutation observers
1600
+ * - Removes from SSF tracking
1601
+ *
1602
+ * - `windowRefsToClear` - Array of paths to window refs to clear recursively
1603
+ * - Example: ["window.IMT.focusFormTitle", "window.emui.customApp"]
1604
+ * - Each path is parsed and set to null
1605
+ *
1606
+ * - `appId` - Optional appId for targeted window.emui[appId] cleanup
1607
+ *
1608
+ * - `cleanupFunctionName` - Name of cleanup function on window.emui (default: 'unmount')
1609
+ * @param {string | Window | HTMLIFrameElement} guestIdOrWindowOrEle - Unique id, window object, or iframe element
1610
+ * @param {object} options - Optional cleanup configuration
1611
+ * @param {boolean} options.purgeOnDestroy - When true, use comprehensive cleanup sequence
1612
+ * @param {string[]} options.windowRefsToClear - Array of window ref paths to clear
1613
+ * @param {string} options.appId - Optional appId for targeted cleanup
1614
+ * @param {string} options.cleanupFunctionName - Guest cleanup function name (default: 'unmount')
1615
+ * @example
1616
+ * // Basic cleanup
1617
+ * host.unloadGuest('my-guest-id');
1618
+ * @example
1619
+ * // Enhanced cleanup with purge
1620
+ * host.unloadGuest('my-guest-id', {
1621
+ * purgeOnDestroy: true,
1622
+ * windowRefsToClear: ["window.IMT.focusFormTitle"],
1623
+ * cleanupFunctionName: 'appCleanup'
1624
+ * });
1625
+ * @example
1626
+ * // Enhanced cleanup with appId
1627
+ * host.unloadGuest('my-guest-id', {
1628
+ * purgeOnDestroy: true,
1629
+ * appId: 'workflowtasks',
1630
+ * cleanupFunctionName: 'cleanup'
1631
+ * });
1632
+ */
1633
+ unloadGuest = (guestIdOrWindowOrEle, options) => {
1246
1634
  const guest = this.#findGuest(guestIdOrWindowOrEle);
1247
- if (guest) {
1248
- guest.dispose();
1249
- this.#guestsByWindow.delete(guest.window);
1250
- this.#guestsByUrl.delete(guest.url);
1251
- this.#guestMetadata.delete(guest.id);
1252
- this.#guests.delete(guest.id);
1635
+ if (!guest) {
1636
+ this.#logger.warn("Attempted to unload unknown guest");
1637
+ return;
1638
+ }
1639
+ const guestId = guest.id;
1640
+ if (options?.purgeOnDestroy) {
1641
+ const cleanupFunctionName = options.cleanupFunctionName || "unmount";
1642
+ if (options.windowRefsToClear && options.windowRefsToClear.length > 0) {
1643
+ this.#clearWindowRefs(options.windowRefsToClear, guestId);
1644
+ }
1645
+ this.unloadGuestWithFullCleanup(guestId, cleanupFunctionName);
1253
1646
  this.#logger.audit({
1254
- message: `Guest is removed from host`,
1647
+ message: `Guest unloaded with purge mode (windowRefs: ${options.windowRefsToClear?.length || 0})`,
1255
1648
  ...guest.getInfo()
1256
1649
  });
1257
- this.#stopMonitoringPopupGuests();
1650
+ return;
1651
+ }
1652
+ guest.dispose();
1653
+ this.#guestsByWindow.delete(guest.window);
1654
+ this.#guestsByUrl.delete(guest.url);
1655
+ this.#guestMetadata.delete(guest.id);
1656
+ this.#guests.delete(guest.id);
1657
+ this.#logger.audit({
1658
+ message: `Guest is removed from host`,
1659
+ ...guest.getInfo()
1660
+ });
1661
+ this.#stopMonitoringPopupGuests();
1662
+ };
1663
+ /**
1664
+ * Process iframe cleanup sequence
1665
+ * @param {Guest} guest - Guest object
1666
+ * @param {string} cleanupFunctionName - Cleanup function name
1667
+ */
1668
+ #processIframeCleanup = (guest, cleanupFunctionName) => {
1669
+ if (!guest.domElement) return;
1670
+ const iframe = guest.domElement;
1671
+ const contentWindow = guest.window;
1672
+ const { id: guestId } = guest;
1673
+ this.#cleanupGuestWindow({
1674
+ guestWindow: contentWindow,
1675
+ guestId,
1676
+ cleanupFunctionName,
1677
+ windowType: "iframe"
1678
+ });
1679
+ this.#disconnectFieldMutationObserver(contentWindow, guestId);
1680
+ this.#closeContentWindow(contentWindow, guestId);
1681
+ this.#navigateToBlank(iframe, guestId);
1682
+ setTimeout(() => {
1683
+ try {
1684
+ if (iframe.parentNode) {
1685
+ iframe.remove();
1686
+ this.#logger.debug(
1687
+ `[SSF] Removed iframe from DOM for guest ${guestId}`
1688
+ );
1689
+ }
1690
+ } catch (e) {
1691
+ this.#logger.warn(
1692
+ `[SSF] Failed to remove iframe for guest ${guestId}: ${e.message}`
1693
+ );
1694
+ }
1695
+ }, 10);
1696
+ };
1697
+ /**
1698
+ * Process popup cleanup sequence
1699
+ * @param {Guest} guest - Guest object
1700
+ * @param {string} cleanupFunctionName - Cleanup function name
1701
+ */
1702
+ #processPopupCleanup = (guest, cleanupFunctionName) => {
1703
+ const popupWindow = guest.window;
1704
+ const { id: guestId } = guest;
1705
+ this.#cleanupGuestWindow({
1706
+ guestWindow: popupWindow,
1707
+ guestId,
1708
+ cleanupFunctionName,
1709
+ windowType: "popup"
1710
+ });
1711
+ try {
1712
+ if (popupWindow && !popupWindow.closed) {
1713
+ popupWindow.close();
1714
+ this.#logger.debug(`[SSF] Closed popup window for guest ${guestId}`);
1715
+ }
1716
+ } catch (e) {
1717
+ this.#logger.debug(
1718
+ `[SSF] Failed to close popup window for guest ${guestId}: ${e.message}`
1719
+ );
1720
+ }
1721
+ guest.dispose();
1722
+ };
1723
+ /**
1724
+ * Unloads guest application with comprehensive memory leak prevention.
1725
+ *
1726
+ * This method implements industry best practices for iframe and popup cleanup to prevent
1727
+ * memory leaks, particularly detached window retention and webpack bundle accumulation.
1728
+ *
1729
+ * **Enhanced Cleanup Sequence for Embedded Iframes:**
1730
+ * 1. Call guest cleanup function (React unmount, Redux teardown, etc.)
1731
+ * 2. Close contentWindow context explicitly
1732
+ * 3. Navigate iframe to about:blank (Chrome GC recommendation)
1733
+ * 4. Small delay, then remove iframe from DOM
1734
+ * 5. Remove from SSF tracking maps
1735
+ * 6. Null all internal references
1736
+ *
1737
+ * **Enhanced Cleanup Sequence for Popup Windows:**
1738
+ * 1. Call guest cleanup function (React unmount, Redux teardown, etc.)
1739
+ * 2. Null all window.emui and window.elli.script references
1740
+ * 3. Clear Google Tag Manager data layer
1741
+ * 4. Close popup window explicitly
1742
+ * 5. Dispose guest (cleanup event listeners)
1743
+ * 6. Remove from SSF tracking maps
1744
+ *
1745
+ * **Memory Leak Prevention:**
1746
+ * - Breaks all closures from contentWindow/popup to parent
1747
+ * - Signals V8 to GC webpack bundle backing store strings
1748
+ * - Removes iframe from browser back/forward cache
1749
+ * - Clears all SSF remoting message handlers
1750
+ * - Nulls all window.emui and window.elli.script properties
1751
+ *
1752
+ * **Important:** This method does NOT clean up window.emui[appId] registry.
1753
+ * When using selfInitialize=true pattern, the guest application handles
1754
+ * its own emui registry cleanup internally.
1755
+ *
1756
+ * **Synchronous Design:** This method is intentionally synchronous to work
1757
+ * with React useEffect cleanup functions. Cleanup steps use setTimeout
1758
+ * for deferred operations rather than async/await.
1759
+ * @param {string | Window | HTMLIFrameElement} guestIdOrWindowOrEle - unique id of the guest application or window object or dom element
1760
+ * @param {string} cleanupFunctionName - name of cleanup function on window.emui (default: 'unmount')
1761
+ * @example
1762
+ * // Standard usage with app cleanup
1763
+ * host.unloadGuestWithFullCleanup('my-guest-id', 'appCleanup');
1764
+ * @example
1765
+ * // Usage with custom cleanup function
1766
+ * host.unloadGuestWithFullCleanup('my-guest-id', 'customUnmount');
1767
+ * @example
1768
+ * // Usage when guest uses default unmount
1769
+ * host.unloadGuestWithFullCleanup('my-guest-id');
1770
+ */
1771
+ unloadGuestWithFullCleanup = (guestIdOrWindowOrEle, cleanupFunctionName = "unmount") => {
1772
+ const guest = this.#findGuest(guestIdOrWindowOrEle);
1773
+ if (!guest) {
1774
+ this.#logger.warn("Attempted to unload unknown guest");
1775
+ return;
1776
+ }
1777
+ const { id: guestId } = guest;
1778
+ if (guest.openMode === OpenMode.Embed && guest.domElement) {
1779
+ this.#processIframeCleanup(guest, cleanupFunctionName);
1780
+ } else if (guest.openMode === OpenMode.Popup) {
1781
+ this.#processPopupCleanup(guest, cleanupFunctionName);
1782
+ } else {
1783
+ guest.dispose();
1784
+ }
1785
+ try {
1786
+ this.#remoting.removeSender({
1787
+ origin: guest.origin,
1788
+ window: guest.window
1789
+ });
1790
+ this.#logger.debug(`[SSF] Removed remoting sender for guest ${guestId}`);
1791
+ } catch (e) {
1792
+ this.#logger.debug(
1793
+ `[SSF] Failed to remove remoting sender for guest ${guestId}: ${e.message}`
1794
+ );
1258
1795
  }
1796
+ this.#guestsByWindow.delete(guest.window);
1797
+ this.#guestsByUrl.delete(guest.url);
1798
+ this.#guestMetadata.delete(guestId);
1799
+ this.#guests.delete(guestId);
1800
+ this.#stopMonitoringPopupGuests();
1801
+ this.#logger.audit({
1802
+ message: `Guest unloaded with full cleanup`,
1803
+ ...guest.getInfo()
1804
+ });
1259
1805
  };
1260
1806
  /**
1261
1807
  * monitors guest window close action and executes the callback from host.
1262
- * @param callback host callback method
1263
- * @param id unique id of the guest application
1264
- * @param param
1808
+ * @param param - Guest close parameters including id and callback
1265
1809
  */
1266
1810
  onGuestClose = (param) => {
1267
1811
  const { id, guestCloseCallback } = param;
@@ -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.110872ea16d9bc201a4f.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.1f1cbf6c2111a68bc2c8.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.110872ea16d9bc201a4f.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.1f1cbf6c2111a68bc2c8.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>