@elliemae/ssf-host 2.25.4 → 2.25.6

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
@@ -25,6 +25,14 @@ 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 {
29
37
  /* eslint-enable indent */
30
38
  /**
@@ -147,7 +155,7 @@ class SSFHost {
147
155
  };
148
156
  #closeAllPopupGuests = () => {
149
157
  const popupIds = Array.from(this.#guests.values()).filter((guest) => guest.openMode === OpenMode.Popup).map((guest) => guest.id);
150
- popupIds.forEach((id) => this.unloadGuest(id));
158
+ popupIds.forEach((id) => this.#unloadGuestInBackground(id));
151
159
  };
152
160
  /**
153
161
  * get the reference to the guest application by its window
@@ -320,7 +328,7 @@ class SSFHost {
320
328
  if (sourceWin?.window) {
321
329
  const guest = this.#findGuest(sourceWin);
322
330
  if (guest && !await guest.handShake()) {
323
- this.unloadGuest(sourceWin);
331
+ this.#unloadGuestInBackground(sourceWin);
324
332
  }
325
333
  }
326
334
  };
@@ -693,7 +701,7 @@ class SSFHost {
693
701
  });
694
702
  guestsToRemove.forEach((guest) => {
695
703
  const { id } = guest;
696
- this.unloadGuest(id);
704
+ this.#unloadGuestInBackground(id);
697
705
  const callbacks = this.#guestCloseCallbackList.get(id);
698
706
  callbacks?.forEach((callback) => {
699
707
  Promise.resolve(callback({ id })).catch(() => {
@@ -1012,6 +1020,10 @@ class SSFHost {
1012
1020
  this.#guests.forEach(tryDispatch);
1013
1021
  }
1014
1022
  };
1023
+ #resolveEventSourceObject = (objectId, targetGuest) => {
1024
+ const scriptingObject = targetGuest ? this.getScriptingObject(objectId, { guest: targetGuest }) : this.getScriptingObject(objectId);
1025
+ return scriptingObject ?? (objectId === MODULE_OBJECT_ID && targetGuest ? MODULE_EVENT_STUB : null);
1026
+ };
1015
1027
  /**
1016
1028
  * dispatch event to guest application(s)
1017
1029
  * @param {EventDetail} params details of the event to be dispatched
@@ -1033,8 +1045,11 @@ class SSFHost {
1033
1045
  const objectId = id.split(".")[0];
1034
1046
  const guestIdorWnd = guestId || targetWindow;
1035
1047
  const targetGuest = guestIdorWnd ? this.#findGuest(guestIdorWnd) : null;
1036
- const scriptingObject = targetGuest ? this.getScriptingObject(objectId, { guest: targetGuest }) : this.getScriptingObject(objectId);
1037
- if (!scriptingObject) {
1048
+ const eventSourceObject = this.#resolveEventSourceObject(
1049
+ objectId,
1050
+ targetGuest ?? null
1051
+ );
1052
+ if (!eventSourceObject) {
1038
1053
  this.#logger.warn(
1039
1054
  `Attempt to dispatch event ${name} on unknown object ${objectId}`
1040
1055
  );
@@ -1042,7 +1057,7 @@ class SSFHost {
1042
1057
  }
1043
1058
  const eventObj = {
1044
1059
  // eslint-disable-next-line no-underscore-dangle
1045
- object: scriptingObject._toJSON(),
1060
+ object: eventSourceObject._toJSON(),
1046
1061
  eventName: name,
1047
1062
  eventParams,
1048
1063
  eventHandler,
@@ -1064,7 +1079,7 @@ class SSFHost {
1064
1079
  guestPromises.push(guest.dispatchEvent(eventObj, timeout));
1065
1080
  if (!eventTimingToken && this.#perfTracker.enabled) {
1066
1081
  eventTimingToken = this.#perfTracker.start(
1067
- `ScriptingObject.Event.${scriptingObject.id}.${name}`,
1082
+ `ScriptingObject.Event.${eventSourceObject.id}.${name}`,
1068
1083
  { appId: this.hostId, appUrl: window.location.href }
1069
1084
  );
1070
1085
  }
@@ -1237,417 +1252,72 @@ class SSFHost {
1237
1252
  this.#guests.forEach(this.#dispatchConfigEvent);
1238
1253
  this.#logger.debug("Dispatched config events to all guests");
1239
1254
  };
1240
- /**
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
1246
- */
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
- );
1255
+ #dispatchGuestModuleEvent = async (guest, eventId, eventName) => (
1256
+ /* eslint-disable @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any */
1257
+ this.dispatchEvent({
1258
+ event: { id: eventId, name: eventName },
1259
+ eventParams: { moduleId: guest.id },
1260
+ eventOptions: {
1261
+ timeout: MODULE_EVENT_TIMEOUT_MS,
1262
+ guestId: guest.id
1327
1263
  }
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) => {
1264
+ })
1265
+ );
1266
+ /* eslint-enable @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any */
1267
+ #canUnloadGuest = async (guest) => {
1358
1268
  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}`
1269
+ const feedback = await this.#dispatchGuestModuleEvent(
1270
+ guest,
1271
+ MODULE_UNLOADING_EVENT,
1272
+ "unloading"
1365
1273
  );
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}`
1274
+ if (isModuleUnloadVetoed(feedback)) {
1275
+ this.#logger.info(
1276
+ `Unload denied by guest ${guest.id} via module.unloading event`
1395
1277
  );
1278
+ return false;
1396
1279
  }
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
- );
1280
+ } catch (err) {
1281
+ this.#logger.warn({
1282
+ message: `Error dispatching module.unloading event for ${guest.id}; proceeding with unload`,
1283
+ exception: err
1284
+ });
1419
1285
  }
1286
+ return true;
1420
1287
  };
1421
1288
  /**
1422
- * Cleanup window.emui properties
1423
- * @param {unknown} guestEmui - Guest window.emui object
1424
- * @param {string} context - Context string for logging
1289
+ * Signal SDK teardown after the module.unloading veto phase passes.
1290
+ * @param guest
1425
1291
  */
1426
- #cleanupEmuiProperties = (guestEmui, context) => {
1292
+ #dispatchModuleUnmount = async (guest) => {
1427
1293
  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}`
1294
+ await this.#dispatchGuestModuleEvent(
1295
+ guest,
1296
+ MODULE_UNMOUNT_EVENT,
1297
+ "unmount"
1433
1298
  );
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
1299
+ } catch (err) {
1300
+ this.#logger.warn({
1301
+ message: `Error dispatching module.unmount event for ${guest.id}`,
1302
+ exception: err
1474
1303
  });
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
1304
  }
1483
1305
  };
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
- );
1306
+ #unloadGuestInBackground = (guestIdOrWindowOrEle) => {
1307
+ this.unloadGuest(guestIdOrWindowOrEle).catch(ignoreRejectedPromise);
1584
1308
  };
1585
1309
  /**
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
- * });
1310
+ * unloads guest application from host
1311
+ * @param guestIdOrWindowOrEle unique id of the guest application or window object or dom element of the guest application
1312
+ * @throws Error if guestId or Window reference is invalid
1632
1313
  */
1633
- unloadGuest = (guestIdOrWindowOrEle, options) => {
1314
+ unloadGuest = async (guestIdOrWindowOrEle) => {
1634
1315
  const guest = this.#findGuest(guestIdOrWindowOrEle);
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);
1646
- this.#logger.audit({
1647
- message: `Guest unloaded with purge mode (windowRefs: ${options.windowRefsToClear?.length || 0})`,
1648
- ...guest.getInfo()
1649
- });
1650
- return;
1316
+ if (!guest) return;
1317
+ const windowAlreadyClosed = Boolean(guest.window?.closed);
1318
+ if (!windowAlreadyClosed) {
1319
+ if (!await this.#canUnloadGuest(guest)) return;
1320
+ await this.#dispatchModuleUnmount(guest);
1651
1321
  }
1652
1322
  guest.dispose();
1653
1323
  this.#guestsByWindow.delete(guest.window);
@@ -1660,153 +1330,741 @@ class SSFHost {
1660
1330
  });
1661
1331
  this.#stopMonitoringPopupGuests();
1662
1332
  };
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
- );
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
- });
1805
- };
1806
- /**
1807
- * monitors guest window close action and executes the callback from host.
1808
- * @param param - Guest close parameters including id and callback
1809
- */
1333
+ // 2.25.x full-cleanup unload path (disabled for PUI-18792 backport)
1334
+ // /**
1335
+ // * Call cleanup function on guest window.emui
1336
+ // * @param {object} options - Cleanup options
1337
+ // * @param {any} options.guestEmui - The window.emui object
1338
+ // * @param {string} options.cleanupFunctionName - Function name to call
1339
+ // * @param {string} options.context - Context for logging
1340
+ // */
1341
+ // #callGuestCleanupFunction = (options: {
1342
+ // guestEmui: any;
1343
+ // cleanupFunctionName: string;
1344
+ // context: string;
1345
+ // }): void => {
1346
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1347
+ // const { guestEmui, cleanupFunctionName, context } = options;
1348
+ // const emuiObj: Record<string, unknown> = guestEmui as Record<
1349
+ // string,
1350
+ // unknown
1351
+ // >;
1352
+ // const cleanupFn = emuiObj[cleanupFunctionName];
1353
+ //
1354
+ // if (typeof cleanupFn !== 'function') {
1355
+ // return;
1356
+ // }
1357
+ //
1358
+ // try {
1359
+ // (cleanupFn as () => void)();
1360
+ // this.#logger.debug(
1361
+ // `[SSF] Called window.emui.${String(cleanupFunctionName)}() for ${String(
1362
+ // context,
1363
+ // )}`,
1364
+ // );
1365
+ // } catch (e) {
1366
+ // this.#logger.warn(
1367
+ // `[SSF] emui.${String(cleanupFunctionName)}() threw error for ${String(
1368
+ // context,
1369
+ // )}: ${(e as Error).message}`,
1370
+ // );
1371
+ // } finally {
1372
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1373
+ // guestEmui[cleanupFunctionName] = null;
1374
+ // }
1375
+ // };
1376
+ //
1377
+ // /**
1378
+ // * Null window.emui.app properties
1379
+ // * @param {Record<string, unknown> | unknown} app - The window.emui.app object
1380
+ // */
1381
+ // #nullAppProperties = (app: Record<string, unknown> | unknown): void => {
1382
+ // if (typeof app !== 'object' || app === null) {
1383
+ // return;
1384
+ // }
1385
+ //
1386
+ // const appObj = app as Record<string, unknown>;
1387
+ // appObj.init = null;
1388
+ // appObj.mount = null;
1389
+ // appObj.unmount = null;
1390
+ // appObj.getRef = null;
1391
+ // appObj.navigate = null;
1392
+ // };
1393
+ //
1394
+ // /**
1395
+ // * Null all window.emui properties
1396
+ // * @param {Record<string, unknown> | unknown} guestEmui - The window.emui object
1397
+ // */
1398
+ // #nullEmuiProperties = (
1399
+ // guestEmui: Record<string, unknown> | unknown,
1400
+ // ): void => {
1401
+ // if (typeof guestEmui !== 'object' || guestEmui === null) {
1402
+ // return;
1403
+ // }
1404
+ //
1405
+ // const emuiObj = guestEmui as Record<string, unknown>;
1406
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1407
+ // if (emuiObj.app) {
1408
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument
1409
+ // this.#nullAppProperties(emuiObj.app);
1410
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1411
+ // emuiObj.app = null;
1412
+ // }
1413
+ //
1414
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1415
+ // emuiObj.registerApp = null;
1416
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1417
+ // emuiObj.logRocket = null;
1418
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1419
+ // emuiObj.getEnvironment = null;
1420
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1421
+ // emuiObj.loadScript = null;
1422
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1423
+ // emuiObj.loadStylesheet = null;
1424
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1425
+ // emuiObj.unmount = null;
1426
+ // };
1427
+ //
1428
+ // /**
1429
+ // * Disconnect FieldMutation observer for iframe
1430
+ // * @param {Window | null} contentWindow - The iframe contentWindow
1431
+ // * @param {string} guestId - Guest ID for logging
1432
+ // */
1433
+ // #disconnectFieldMutationObserver = (
1434
+ // contentWindow: Window | null,
1435
+ // guestId: string,
1436
+ // ): void => {
1437
+ // try {
1438
+ // const bodyElement = contentWindow?.document?.body;
1439
+ // if (!bodyElement) return;
1440
+ //
1441
+ // const { observerReferences } = window as unknown as {
1442
+ // observerReferences?: Map<unknown, unknown>;
1443
+ // };
1444
+ // if (!observerReferences || !(observerReferences instanceof Map)) {
1445
+ // return;
1446
+ // }
1447
+ //
1448
+ // if (!observerReferences.has(bodyElement)) return;
1449
+ //
1450
+ // const observer = observerReferences.get(bodyElement) as
1451
+ // | { disconnect?: () => void }
1452
+ // | undefined;
1453
+ // if (observer && typeof observer.disconnect === 'function') {
1454
+ // observer.disconnect();
1455
+ // observerReferences.delete(bodyElement);
1456
+ // this.#logger.debug(
1457
+ // `[SSF] Disconnected FieldMutation observer for guest ${guestId}`,
1458
+ // );
1459
+ // }
1460
+ // } catch (e) {
1461
+ // this.#logger.debug(
1462
+ // `[SSF] Failed to disconnect FieldMutation observer for guest ${guestId}: ${
1463
+ // (e as Error).message
1464
+ // }`,
1465
+ // );
1466
+ // }
1467
+ // };
1468
+ //
1469
+ // /**
1470
+ // * Close contentWindow explicitly
1471
+ // * @param {Window | null} contentWindow - The iframe contentWindow
1472
+ // * @param {string} guestId - Guest ID for logging
1473
+ // */
1474
+ // #closeContentWindow = (
1475
+ // contentWindow: Window | null,
1476
+ // guestId: string,
1477
+ // ): void => {
1478
+ // try {
1479
+ // if (!contentWindow || contentWindow.closed) return;
1480
+ //
1481
+ // contentWindow.close();
1482
+ // this.#logger.debug(
1483
+ // `[SSF] Called contentWindow.close() for guest ${guestId}`,
1484
+ // );
1485
+ // } catch (e) {
1486
+ // this.#logger.debug(
1487
+ // `[SSF] contentWindow.close() failed for guest ${guestId}: ${
1488
+ // (e as Error).message
1489
+ // }`,
1490
+ // );
1491
+ // }
1492
+ // };
1493
+ //
1494
+ // /**
1495
+ // * Navigate iframe to about:blank
1496
+ // * @param {HTMLIFrameElement} iframe - The iframe element
1497
+ // * @param {string} guestId - Guest ID for logging
1498
+ // */
1499
+ // #navigateToBlank = (iframe: HTMLIFrameElement, guestId: string): void => {
1500
+ // try {
1501
+ // if (!iframe.parentNode) return;
1502
+ //
1503
+ // iframe.src = 'about:blank';
1504
+ // this.#logger.debug(`[SSF] Navigated to about:blank for guest ${guestId}`);
1505
+ // } catch (e) {
1506
+ // this.#logger.debug(
1507
+ // `[SSF] Navigation to about:blank failed for guest ${guestId}: ${
1508
+ // (e as Error).message
1509
+ // }`,
1510
+ // );
1511
+ // }
1512
+ // };
1513
+ //
1514
+ // /**
1515
+ // * Cleanup window.elli.script properties
1516
+ // * @param {Window} guestWindow - Guest window
1517
+ // * @param {string} context - Context string for logging
1518
+ // */
1519
+ // #cleanupElliScript = (guestWindow: Window, context: string): void => {
1520
+ // try {
1521
+ // const windowWithElli = guestWindow as Window & {
1522
+ // elli?: Record<string, unknown> & {
1523
+ // script?: Record<string, unknown> | null;
1524
+ // };
1525
+ // };
1526
+ // const { elli } = windowWithElli;
1527
+ // if (elli?.script && typeof elli.script === 'object') {
1528
+ // const { script } = elli;
1529
+ // if (script && script.guest && typeof script.guest === 'object') {
1530
+ // const { guest } = script;
1531
+ // const guestObj = guest as Record<string, unknown>;
1532
+ // guestObj.create = null;
1533
+ // }
1534
+ // if (script) {
1535
+ // script.guest = null;
1536
+ // script.connect = null;
1537
+ // script.getObject = null;
1538
+ // script.setLogLevel = null;
1539
+ // script.subscribe = null;
1540
+ // script.unsubscribe = null;
1541
+ // elli.script = null;
1542
+ // }
1543
+ // this.#logger.debug(
1544
+ // `[SSF] Nulled all window.elli.script properties for ${context}`,
1545
+ // );
1546
+ // }
1547
+ // } catch (e) {
1548
+ // this.#logger.debug(
1549
+ // `[SSF] Failed to cleanup window.elli: ${(e as Error).message}`,
1550
+ // );
1551
+ // }
1552
+ // };
1553
+ //
1554
+ // /**
1555
+ // * Clear Google Tag Manager data layer
1556
+ // * @param {Window} guestWindow - Guest window
1557
+ // * @param {string} context - Context string for logging
1558
+ // */
1559
+ // #clearGtmDataLayer = (guestWindow: Window, context: string): void => {
1560
+ // try {
1561
+ // const windowWithGtm = guestWindow as Window & {
1562
+ // gtmDataLayer?: unknown;
1563
+ // };
1564
+ // if (windowWithGtm.gtmDataLayer) {
1565
+ // windowWithGtm.gtmDataLayer = null;
1566
+ // this.#logger.debug(`[SSF] Cleared gtmDataLayer for ${context}`);
1567
+ // }
1568
+ // } catch (e) {
1569
+ // this.#logger.debug(
1570
+ // `[SSF] Failed to cleanup GTM data layer: ${(e as Error).message}`,
1571
+ // );
1572
+ // }
1573
+ // };
1574
+ //
1575
+ // /**
1576
+ // * Cleanup window.emui properties
1577
+ // * @param {unknown} guestEmui - Guest window.emui object
1578
+ // * @param {string} context - Context string for logging
1579
+ // */
1580
+ // #cleanupEmuiProperties = (guestEmui: unknown, context: string): void => {
1581
+ // try {
1582
+ // if (typeof guestEmui === 'object' && guestEmui !== null) {
1583
+ // this.#nullEmuiProperties(guestEmui);
1584
+ // }
1585
+ // this.#logger.debug(
1586
+ // `[SSF] Nulled all window.emui properties for ${context}`,
1587
+ // );
1588
+ // } catch (e) {
1589
+ // this.#logger.debug(
1590
+ // `[SSF] Failed to cleanup window.emui: ${(e as Error).message}`,
1591
+ // );
1592
+ // }
1593
+ // };
1594
+ //
1595
+ // /**
1596
+ // * Cleanup guest window context - nulls all window.emui and window.elli.script properties
1597
+ // * This breaks closure retention chains and allows GC of webpack bundles, SDKs, and singletons
1598
+ // * @param {object} options - Cleanup options
1599
+ // * @param {Window | null} options.guestWindow - The guest window
1600
+ // * @param {string} options.guestId - Guest ID for logging
1601
+ // * @param {string} options.cleanupFunctionName - Cleanup function name
1602
+ // * @param {string} options.windowType - Window type for logging
1603
+ // */
1604
+ // #cleanupGuestWindow = (options: {
1605
+ // guestWindow: Window | null;
1606
+ // guestId: string;
1607
+ // cleanupFunctionName: string;
1608
+ // windowType?: 'iframe' | 'popup';
1609
+ // }) => {
1610
+ // const {
1611
+ // guestWindow,
1612
+ // guestId,
1613
+ // cleanupFunctionName,
1614
+ // windowType = 'iframe',
1615
+ // } = options;
1616
+ //
1617
+ // if (!guestWindow) {
1618
+ // this.#logger.debug(
1619
+ // `No ${windowType} window available for cleanup of guest ${guestId}`,
1620
+ // );
1621
+ // return;
1622
+ // }
1623
+ //
1624
+ // const context = `${windowType} ${guestId}`;
1625
+ //
1626
+ // try {
1627
+ // const windowWithEmui = guestWindow as Window & { emui?: unknown };
1628
+ // const guestEmui = windowWithEmui.emui;
1629
+ //
1630
+ // if (!guestEmui) {
1631
+ // this.#logger.debug(`No window.emui found for ${context}`);
1632
+ // return;
1633
+ // }
1634
+ //
1635
+ // this.#callGuestCleanupFunction({
1636
+ // guestEmui,
1637
+ // cleanupFunctionName,
1638
+ // context,
1639
+ // });
1640
+ //
1641
+ // this.#cleanupEmuiProperties(guestEmui, context);
1642
+ // this.#cleanupElliScript(guestWindow, context);
1643
+ // this.#clearGtmDataLayer(guestWindow, context);
1644
+ // } catch (e) {
1645
+ // this.#logger.debug(
1646
+ // `[SSF] Could not access ${windowType} window for cleanup (guest ${guestId}): ${
1647
+ // (e as Error).message
1648
+ // }`,
1649
+ // );
1650
+ // }
1651
+ // };
1652
+ //
1653
+ // /**
1654
+ // * Navigate to parent of target property
1655
+ // * @param {string[]} parts - Path parts
1656
+ // * @param {string} path - Full path for logging
1657
+ // * @param {string} guestId - Guest ID for logging
1658
+ // * @returns {object | null} Navigation result with current object and parent chain
1659
+ // */
1660
+ // #navigateToParent = (
1661
+ // parts: string[],
1662
+ // path: string,
1663
+ // guestId: string,
1664
+ // ): {
1665
+ // current: Record<string, unknown>;
1666
+ // parentChain: Array<{ obj: Record<string, unknown>; key: string }>;
1667
+ // } | null => {
1668
+ // const parentChain: Array<{ obj: Record<string, unknown>; key: string }> =
1669
+ // [];
1670
+ // let current: Record<string, unknown> = window as unknown as Record<
1671
+ // string,
1672
+ // unknown
1673
+ // >;
1674
+ //
1675
+ // for (let i = 0; i < parts.length - 1; i += 1) {
1676
+ // const part = parts[i];
1677
+ // if (current[part] === undefined || current[part] === null) {
1678
+ // this.#logger.debug(
1679
+ // `Path "${path}" does not exist (stopped at ${part}) for guest ${guestId}`,
1680
+ // );
1681
+ // return null;
1682
+ // }
1683
+ // parentChain.push({ obj: current, key: part });
1684
+ // current = current[part] as Record<string, unknown>;
1685
+ // }
1686
+ //
1687
+ // return { current, parentChain };
1688
+ // };
1689
+ //
1690
+ // /**
1691
+ // * Clean up empty parent objects in chain
1692
+ // * @param {Array<{obj: Record<string, unknown>, key: string}>} parentChain - Chain of parent objects
1693
+ // * @param {string[]} parts - Path parts for logging
1694
+ // * @param {string} guestId - Guest ID for logging
1695
+ // */
1696
+ // #cleanupParentChain = (
1697
+ // parentChain: Array<{ obj: Record<string, unknown>; key: string }>,
1698
+ // parts: string[],
1699
+ // guestId: string,
1700
+ // ): void => {
1701
+ // for (let i = parentChain.length - 1; i >= 0; i -= 1) {
1702
+ // const { obj, key } = parentChain[i];
1703
+ // const parent = obj[key];
1704
+ //
1705
+ // if (
1706
+ // !parent ||
1707
+ // typeof parent !== 'object' ||
1708
+ // !this.#isEmptyOrNullObject(parent)
1709
+ // ) {
1710
+ // break;
1711
+ // }
1712
+ //
1713
+ // obj[key] = null;
1714
+ // this.#logger.debug(
1715
+ // `Cleaned up empty parent object at ${parts
1716
+ // .slice(0, i + 1)
1717
+ // .join('.')} for guest ${guestId}`,
1718
+ // );
1719
+ // }
1720
+ // };
1721
+ //
1722
+ // /**
1723
+ // * Recursively clear window references by path string
1724
+ // * Handles nested paths like "window.IMT.focusFormTitle" or "window.emui.app"
1725
+ // * Sets each reference to null and cleans up empty parent objects
1726
+ // * @param {string[]} paths - Array of dot-separated paths to window properties
1727
+ // * @param {string} guestId - Guest ID for logging purposes
1728
+ // * @example
1729
+ // * // Clear window.IMT.focusFormTitle and cleanup window.IMT if empty
1730
+ // * clearWindowRefs(["window.IMT.focusFormTitle"], "my-guest-id");
1731
+ // * @example
1732
+ // * // Clear multiple refs
1733
+ // * clearWindowRefs(["window.IMT.focusFormTitle", "window.emui.app"], "my-guest-id");
1734
+ // */
1735
+ // #clearWindowRefs = (paths: string[], guestId: string) => {
1736
+ // if (!paths || paths.length === 0) return;
1737
+ //
1738
+ // paths.forEach((path) => {
1739
+ // try {
1740
+ // const parts = path
1741
+ // .split('.')
1742
+ // .filter((p) => p !== 'window' && p.trim() !== '');
1743
+ //
1744
+ // if (parts.length === 0) {
1745
+ // this.#logger.debug(
1746
+ // `Invalid path "${path}" - skipping for guest ${guestId}`,
1747
+ // );
1748
+ // return;
1749
+ // }
1750
+ //
1751
+ // const result = this.#navigateToParent(parts, path, guestId);
1752
+ // if (!result) return;
1753
+ //
1754
+ // const { current, parentChain } = result;
1755
+ // const targetProp = parts[parts.length - 1];
1756
+ //
1757
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1758
+ // if (current[targetProp] === undefined) {
1759
+ // return;
1760
+ // }
1761
+ //
1762
+ // // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1763
+ // current[targetProp] = null;
1764
+ // this.#logger.debug(
1765
+ // `Cleared window reference: ${path} for guest ${guestId}`,
1766
+ // );
1767
+ //
1768
+ // this.#cleanupParentChain(parentChain, parts, guestId);
1769
+ // } catch (e) {
1770
+ // this.#logger.debug(
1771
+ // `Failed to clear window reference "${path}" for guest ${guestId}: ${
1772
+ // (e as Error).message
1773
+ // }`,
1774
+ // );
1775
+ // }
1776
+ // });
1777
+ // };
1778
+ //
1779
+ // /**
1780
+ // * Check if an object is empty or only contains null/undefined values
1781
+ // * Used to determine if parent objects should be cleaned up after nulling child properties
1782
+ // * @param {unknown} obj - Object to check
1783
+ // * @returns {boolean} true if object has no properties or all properties are null/undefined
1784
+ // */
1785
+ // #isEmptyOrNullObject = (obj: unknown): boolean => {
1786
+ // if (obj === null || obj === undefined || typeof obj !== 'object')
1787
+ // return true;
1788
+ // const keys = Object.keys(obj);
1789
+ // if (keys.length === 0) return true;
1790
+ //
1791
+ // const record = obj as Record<string, unknown>;
1792
+ // // Check if all properties are null or undefined
1793
+ // return keys.every(
1794
+ // (key) => record[key] === null || record[key] === undefined,
1795
+ // );
1796
+ // };
1797
+ //
1798
+ // /**
1799
+ // * Unloads guest application from host with optional enhanced cleanup.
1800
+ // *
1801
+ // * **Basic Mode (no options):**
1802
+ // * - Standard guest disposal
1803
+ // * - Removes from tracking maps
1804
+ // *
1805
+ // * **Enhanced Mode (with options):**
1806
+ // * - `purgeOnDestroy: true` - Uses comprehensive cleanup via `unloadGuestWithFullCleanup`
1807
+ // * - Calls guest cleanup function (React unmount, Redux teardown)
1808
+ // * - Closes contentWindow context
1809
+ // * - Navigates iframe to about:blank
1810
+ // * - Removes iframe from DOM (deferred)
1811
+ // * - Clears all window.emui and window.elli.script references
1812
+ // * - Disconnects FieldMutation observers
1813
+ // * - Removes from SSF tracking
1814
+ // *
1815
+ // * - `windowRefsToClear` - Array of paths to window refs to clear recursively
1816
+ // * - Example: ["window.IMT.focusFormTitle", "window.emui.customApp"]
1817
+ // * - Each path is parsed and set to null
1818
+ // *
1819
+ // * - `appId` - Optional appId for targeted window.emui[appId] cleanup
1820
+ // *
1821
+ // * - `cleanupFunctionName` - Name of cleanup function on window.emui (default: 'unmount')
1822
+ // * @param {string | Window | HTMLIFrameElement} guestIdOrWindowOrEle - Unique id, window object, or iframe element
1823
+ // * @param {object} options - Optional cleanup configuration
1824
+ // * @param {boolean} options.purgeOnDestroy - When true, use comprehensive cleanup sequence
1825
+ // * @param {string[]} options.windowRefsToClear - Array of window ref paths to clear
1826
+ // * @param {string} options.appId - Optional appId for targeted cleanup
1827
+ // * @param {string} options.cleanupFunctionName - Guest cleanup function name (default: 'unmount')
1828
+ // * @example
1829
+ // * // Basic cleanup
1830
+ // * host.unloadGuest('my-guest-id');
1831
+ // * @example
1832
+ // * // Enhanced cleanup with purge
1833
+ // * host.unloadGuest('my-guest-id', {
1834
+ // * purgeOnDestroy: true,
1835
+ // * windowRefsToClear: ["window.IMT.focusFormTitle"],
1836
+ // * cleanupFunctionName: 'appCleanup'
1837
+ // * });
1838
+ // * @example
1839
+ // * // Enhanced cleanup with appId
1840
+ // * host.unloadGuest('my-guest-id', {
1841
+ // * purgeOnDestroy: true,
1842
+ // * appId: 'workflowtasks',
1843
+ // * cleanupFunctionName: 'cleanup'
1844
+ // * });
1845
+ // */
1846
+ // unloadGuest = (
1847
+ // guestIdOrWindowOrEle: string | Window | HTMLIFrameElement,
1848
+ // options?: UnloadOptions,
1849
+ // ) => {
1850
+ // const guest = this.#findGuest(guestIdOrWindowOrEle);
1851
+ // if (!guest) {
1852
+ // this.#logger.warn('Attempted to unload unknown guest');
1853
+ // return;
1854
+ // }
1855
+ //
1856
+ // const guestId = guest.id;
1857
+ //
1858
+ // // Enhanced cleanup mode when purgeOnDestroy is true
1859
+ // if (options?.purgeOnDestroy) {
1860
+ // const cleanupFunctionName = options.cleanupFunctionName || 'unmount';
1861
+ //
1862
+ // // Clear custom window references if specified
1863
+ // if (options.windowRefsToClear && options.windowRefsToClear.length > 0) {
1864
+ // this.#clearWindowRefs(options.windowRefsToClear, guestId);
1865
+ // }
1866
+ //
1867
+ // // Use comprehensive cleanup
1868
+ // this.unloadGuestWithFullCleanup(guestId, cleanupFunctionName);
1869
+ //
1870
+ // this.#logger.audit({
1871
+ // message: `Guest unloaded with purge mode (windowRefs: ${
1872
+ // options.windowRefsToClear?.length || 0
1873
+ // })`,
1874
+ // ...guest.getInfo(),
1875
+ // });
1876
+ // return;
1877
+ // }
1878
+ //
1879
+ // // Standard cleanup mode (legacy behavior)
1880
+ // guest.dispose();
1881
+ // this.#guestsByWindow.delete(guest.window);
1882
+ // this.#guestsByUrl.delete(guest.url);
1883
+ // this.#guestMetadata.delete(guest.id);
1884
+ // this.#guests.delete(guest.id);
1885
+ // this.#logger.audit({
1886
+ // message: `Guest is removed from host`,
1887
+ // ...guest.getInfo(),
1888
+ // });
1889
+ // this.#stopMonitoringPopupGuests();
1890
+ // };
1891
+ //
1892
+ // /**
1893
+ // * Process iframe cleanup sequence
1894
+ // * @param {Guest} guest - Guest object
1895
+ // * @param {string} cleanupFunctionName - Cleanup function name
1896
+ // */
1897
+ // #processIframeCleanup = (guest: Guest, cleanupFunctionName: string): void => {
1898
+ // if (!guest.domElement) return;
1899
+ //
1900
+ // const iframe = guest.domElement;
1901
+ // const contentWindow = guest.window;
1902
+ // const { id: guestId } = guest;
1903
+ //
1904
+ // this.#cleanupGuestWindow({
1905
+ // guestWindow: contentWindow,
1906
+ // guestId,
1907
+ // cleanupFunctionName,
1908
+ // windowType: 'iframe',
1909
+ // });
1910
+ //
1911
+ // this.#disconnectFieldMutationObserver(contentWindow, guestId);
1912
+ // this.#closeContentWindow(contentWindow, guestId);
1913
+ // this.#navigateToBlank(iframe, guestId);
1914
+ //
1915
+ // setTimeout(() => {
1916
+ // try {
1917
+ // if (iframe.parentNode) {
1918
+ // iframe.remove();
1919
+ // this.#logger.debug(
1920
+ // `[SSF] Removed iframe from DOM for guest ${guestId}`,
1921
+ // );
1922
+ // }
1923
+ // } catch (e) {
1924
+ // this.#logger.warn(
1925
+ // `[SSF] Failed to remove iframe for guest ${guestId}: ${
1926
+ // (e as Error).message
1927
+ // }`,
1928
+ // );
1929
+ // }
1930
+ // }, 10);
1931
+ // };
1932
+ //
1933
+ // /**
1934
+ // * Process popup cleanup sequence
1935
+ // * @param {Guest} guest - Guest object
1936
+ // * @param {string} cleanupFunctionName - Cleanup function name
1937
+ // */
1938
+ // #processPopupCleanup = (guest: Guest, cleanupFunctionName: string): void => {
1939
+ // const popupWindow = guest.window;
1940
+ // const { id: guestId } = guest;
1941
+ //
1942
+ // this.#cleanupGuestWindow({
1943
+ // guestWindow: popupWindow,
1944
+ // guestId,
1945
+ // cleanupFunctionName,
1946
+ // windowType: 'popup',
1947
+ // });
1948
+ //
1949
+ // try {
1950
+ // if (popupWindow && !popupWindow.closed) {
1951
+ // popupWindow.close();
1952
+ // this.#logger.debug(`[SSF] Closed popup window for guest ${guestId}`);
1953
+ // }
1954
+ // } catch (e) {
1955
+ // this.#logger.debug(
1956
+ // `[SSF] Failed to close popup window for guest ${guestId}: ${
1957
+ // (e as Error).message
1958
+ // }`,
1959
+ // );
1960
+ // }
1961
+ //
1962
+ // guest.dispose();
1963
+ // };
1964
+ //
1965
+ // /**
1966
+ // * Unloads guest application with comprehensive memory leak prevention.
1967
+ // *
1968
+ // * This method implements industry best practices for iframe and popup cleanup to prevent
1969
+ // * memory leaks, particularly detached window retention and webpack bundle accumulation.
1970
+ // *
1971
+ // * **Enhanced Cleanup Sequence for Embedded Iframes:**
1972
+ // * 1. Call guest cleanup function (React unmount, Redux teardown, etc.)
1973
+ // * 2. Close contentWindow context explicitly
1974
+ // * 3. Navigate iframe to about:blank (Chrome GC recommendation)
1975
+ // * 4. Small delay, then remove iframe from DOM
1976
+ // * 5. Remove from SSF tracking maps
1977
+ // * 6. Null all internal references
1978
+ // *
1979
+ // * **Enhanced Cleanup Sequence for Popup Windows:**
1980
+ // * 1. Call guest cleanup function (React unmount, Redux teardown, etc.)
1981
+ // * 2. Null all window.emui and window.elli.script references
1982
+ // * 3. Clear Google Tag Manager data layer
1983
+ // * 4. Close popup window explicitly
1984
+ // * 5. Dispose guest (cleanup event listeners)
1985
+ // * 6. Remove from SSF tracking maps
1986
+ // *
1987
+ // * **Memory Leak Prevention:**
1988
+ // * - Breaks all closures from contentWindow/popup to parent
1989
+ // * - Signals V8 to GC webpack bundle backing store strings
1990
+ // * - Removes iframe from browser back/forward cache
1991
+ // * - Clears all SSF remoting message handlers
1992
+ // * - Nulls all window.emui and window.elli.script properties
1993
+ // *
1994
+ // * **Important:** This method does NOT clean up window.emui[appId] registry.
1995
+ // * When using selfInitialize=true pattern, the guest application handles
1996
+ // * its own emui registry cleanup internally.
1997
+ // *
1998
+ // * **Synchronous Design:** This method is intentionally synchronous to work
1999
+ // * with React useEffect cleanup functions. Cleanup steps use setTimeout
2000
+ // * for deferred operations rather than async/await.
2001
+ // * @param {string | Window | HTMLIFrameElement} guestIdOrWindowOrEle - unique id of the guest application or window object or dom element
2002
+ // * @param {string} cleanupFunctionName - name of cleanup function on window.emui (default: 'unmount')
2003
+ // * @example
2004
+ // * // Standard usage with app cleanup
2005
+ // * host.unloadGuestWithFullCleanup('my-guest-id', 'appCleanup');
2006
+ // * @example
2007
+ // * // Usage with custom cleanup function
2008
+ // * host.unloadGuestWithFullCleanup('my-guest-id', 'customUnmount');
2009
+ // * @example
2010
+ // * // Usage when guest uses default unmount
2011
+ // * host.unloadGuestWithFullCleanup('my-guest-id');
2012
+ // */
2013
+ // unloadGuestWithFullCleanup = (
2014
+ // guestIdOrWindowOrEle: string | Window | HTMLIFrameElement,
2015
+ // cleanupFunctionName = 'unmount',
2016
+ // ): void => {
2017
+ // const guest = this.#findGuest(guestIdOrWindowOrEle);
2018
+ // if (!guest) {
2019
+ // this.#logger.warn('Attempted to unload unknown guest');
2020
+ // return;
2021
+ // }
2022
+ //
2023
+ // const { id: guestId } = guest;
2024
+ //
2025
+ // if (guest.openMode === OpenMode.Embed && guest.domElement) {
2026
+ // this.#processIframeCleanup(guest, cleanupFunctionName);
2027
+ // } else if (guest.openMode === OpenMode.Popup) {
2028
+ // this.#processPopupCleanup(guest, cleanupFunctionName);
2029
+ // } else {
2030
+ // guest.dispose();
2031
+ // }
2032
+ //
2033
+ // // Step 5: Remove from remoting allowed senders
2034
+ // // This prevents any further postMessage communication
2035
+ // try {
2036
+ // this.#remoting.removeSender({
2037
+ // origin: guest.origin,
2038
+ // window: guest.window,
2039
+ // });
2040
+ // this.#logger.debug(`[SSF] Removed remoting sender for guest ${guestId}`);
2041
+ // } catch (e) {
2042
+ // this.#logger.debug(
2043
+ // `[SSF] Failed to remove remoting sender for guest ${guestId}: ${
2044
+ // (e as Error).message
2045
+ // }`,
2046
+ // );
2047
+ // }
2048
+ //
2049
+ // // Step 6: Remove from all SSF tracking maps
2050
+ // this.#guestsByWindow.delete(guest.window);
2051
+ // this.#guestsByUrl.delete(guest.url);
2052
+ // this.#guestMetadata.delete(guestId);
2053
+ // this.#guests.delete(guestId);
2054
+ //
2055
+ // // Step 7: Stop monitoring popup guests if none remain
2056
+ // this.#stopMonitoringPopupGuests();
2057
+ //
2058
+ // this.#logger.audit({
2059
+ // message: `Guest unloaded with full cleanup`,
2060
+ // ...guest.getInfo(),
2061
+ // });
2062
+ // };
2063
+ //
2064
+ // /**
2065
+ // * monitors guest window close action and executes the callback from host.
2066
+ // * @param param - Guest close parameters including id and callback
2067
+ // */
1810
2068
  onGuestClose = (param) => {
1811
2069
  const { id, guestCloseCallback } = param;
1812
2070
  const callbacks = this.#guestCloseCallbackList.get(id) || [];