emailengine-app 2.72.2 → 2.72.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.
@@ -3,7 +3,20 @@ export class EmailEngineClient {
3
3
  this.apiUrl = options.apiUrl || 'http://127.0.0.1:3000';
4
4
  this.account = options.account;
5
5
  this.accessToken = options.accessToken;
6
- this.container = options.container;
6
+ this.container = options.container || null;
7
+ // Resolve containerId when no element was passed directly, so
8
+ // `new EmailEngineClient({ containerId })` renders UI too (not only the
9
+ // factory). In a non-DOM env this stays null - an API-only client.
10
+ if (!this.container && options.containerId && typeof document !== 'undefined') {
11
+ this.container = document.getElementById(options.containerId);
12
+ // A containerId that matches nothing is almost always a typo; warn
13
+ // rather than silently degrading to a UI-less, API-only client.
14
+ if (!this.container) {
15
+ console.warn(
16
+ `EmailEngineClient: no element found for containerId "${options.containerId}"; UI rendering disabled`
17
+ );
18
+ }
19
+ }
7
20
  this.confirmMethod =
8
21
  options.confirmMethod ||
9
22
  ((message, _title = 'Confirm', _cancelText = 'Cancel', _okText = 'OK') => confirm(message));
@@ -17,6 +30,11 @@ export class EmailEngineClient {
17
30
  this.nextPageCursor = null;
18
31
  this.prevPageCursor = null;
19
32
 
33
+ // Set once destroy() runs; guards async completions (loadFolders,
34
+ // loadMessages, loadMessage) from re-rendering or scrolling into a
35
+ // torn-down - or recreated - container.
36
+ this._destroyed = false;
37
+
20
38
  // Keep-alive timer for sess_ tokens
21
39
  this.keepAliveTimer = null;
22
40
  this.lastActivity = Date.now();
@@ -30,7 +48,8 @@ export class EmailEngineClient {
30
48
  // Get page size from localStorage or options or default
31
49
  const savedPageSize =
32
50
  typeof window !== 'undefined' && window.localStorage ? localStorage.getItem('ee-client-page-size') : null;
33
- this.pageSize = savedPageSize ? parseInt(savedPageSize) : options.pageSize || 20;
51
+ const requestedPageSize = savedPageSize ? parseInt(savedPageSize, 10) : parseInt(options.pageSize, 10);
52
+ this.pageSize = requestedPageSize > 0 ? requestedPageSize : 20;
34
53
 
35
54
  if (this.container) {
36
55
  this.init();
@@ -48,32 +67,32 @@ export class EmailEngineClient {
48
67
  const options = {
49
68
  method: method,
50
69
  headers: {
51
- 'Content-Type': 'application/json'
70
+ 'Content-Type': 'application/json',
71
+ ...this._authHeaders()
52
72
  }
53
73
  };
54
74
 
55
- if (this.accessToken) {
56
- options.headers['Authorization'] = `Bearer ${this.accessToken}`;
57
- }
58
-
59
75
  if (data) {
60
76
  options.body = JSON.stringify(data);
61
77
  }
62
78
 
63
79
  let fetchFn = globalThis.fetch;
64
- if (!fetchFn && typeof require !== 'undefined') {
80
+ if (!fetchFn) {
81
+ // Native fetch is missing (older Node.js). Fall back to node-fetch.
82
+ // This is a dynamic import so browsers and modern Node never load it.
65
83
  try {
66
84
  const nodeFetch = await import('node-fetch');
67
85
  fetchFn = nodeFetch.default;
68
86
  } catch (err) {
69
- throw new Error(
70
- 'fetch is not available. In Node.js environments, please install node-fetch: npm install node-fetch'
71
- );
87
+ // node-fetch is not installed; the guard below reports it
72
88
  }
73
89
  }
74
90
 
75
91
  if (!fetchFn) {
76
- throw new Error('fetch is not available');
92
+ // Either node-fetch is missing or it exposed no callable default export
93
+ throw new Error(
94
+ 'fetch is not available. In Node.js environments, please install node-fetch: npm install node-fetch'
95
+ );
77
96
  }
78
97
 
79
98
  const response = await fetchFn(url, options);
@@ -99,6 +118,7 @@ export class EmailEngineClient {
99
118
  try {
100
119
  const data = await this.apiRequest('GET', `/v1/account/${this.account}/mailboxes`);
101
120
  this.folders = data.mailboxes || [];
121
+ this._folderTreeCache = null;
102
122
  if (this.container) {
103
123
  this.renderFolderList();
104
124
  }
@@ -181,7 +201,7 @@ export class EmailEngineClient {
181
201
  }
182
202
  }
183
203
 
184
- if (this.container) {
204
+ if (this.container && !this._destroyed) {
185
205
  this.renderMessage();
186
206
 
187
207
  // Scroll to top of the email client container
@@ -321,23 +341,18 @@ export class EmailEngineClient {
321
341
  _formatSendError(error) {
322
342
  // If we have detailed error information from the API
323
343
  if (error.details && error.details.fields && Array.isArray(error.details.fields)) {
324
- const fieldErrors = error.details.fields.map(field => {
325
- // Try to make field errors more user-friendly
326
- let message = field.message;
327
-
328
- // Map technical field names to user-friendly names
329
- if (message.includes('to[0].address') || message.includes('"address"')) {
330
- message = message.replace(/to\[\d+\]\.address|"address"/g, 'email address');
331
- }
332
- if (message.includes('"subject"')) {
333
- message = message.replace('"subject"', 'subject');
334
- }
335
- if (message.includes('"text"')) {
336
- message = message.replace('"text"', 'message');
337
- }
338
-
339
- return message;
340
- });
344
+ const fieldErrors = error.details.fields
345
+ // Keep only entries that carry a usable message string.
346
+ .filter(field => field && typeof field.message === 'string')
347
+ // Map technical field names to user-friendly ones. Each replace
348
+ // is a no-op when its pattern is absent, so no includes-guards
349
+ // are needed - and to[N] for any index is handled, not just to[0].
350
+ .map(field =>
351
+ field.message
352
+ .replace(/to\[\d+\]\.address|"address"/g, 'email address')
353
+ .replace(/"subject"/g, 'subject')
354
+ .replace(/"text"/g, 'message')
355
+ );
341
356
 
342
357
  const mainMessage = error.details.message || 'Failed to send email';
343
358
  if (fieldErrors.length > 0) {
@@ -373,21 +388,51 @@ export class EmailEngineClient {
373
388
  return Math.round((bytes / Math.pow(1024, i)) * 100) / 100 + ' ' + sizes[i];
374
389
  }
375
390
 
376
- async downloadAttachment(attachmentId, suggestedFilename = null) {
377
- try {
378
- const headers = {};
379
- if (this.accessToken) {
380
- headers['Authorization'] = `Bearer ${this.accessToken}`;
381
- }
391
+ escapeHtml(value) {
392
+ if (value === null || value === undefined) {
393
+ return '';
394
+ }
395
+ const htmlEscapes = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
396
+ return String(value).replace(/[&<>"']/g, ch => htmlEscapes[ch]);
397
+ }
382
398
 
383
- const response = await fetch(`${this.apiUrl}/v1/account/${this.account}/attachment/${attachmentId}`, {
384
- headers,
385
- credentials: 'include'
386
- });
399
+ _authHeaders() {
400
+ const headers = {};
401
+ if (this.accessToken) {
402
+ headers['Authorization'] = `Bearer ${this.accessToken}`;
403
+ }
404
+ return headers;
405
+ }
387
406
 
388
- if (!response.ok) {
389
- throw new Error(`HTTP error! status: ${response.status}`);
390
- }
407
+ _saveBlob(blob, filename) {
408
+ const url = window.URL.createObjectURL(blob);
409
+ const a = document.createElement('a');
410
+ a.href = url;
411
+ a.download = filename;
412
+ document.body.appendChild(a);
413
+ a.click();
414
+ document.body.removeChild(a);
415
+ window.URL.revokeObjectURL(url);
416
+ }
417
+
418
+ // Authenticated GET for binary payloads (attachments, message source).
419
+ // apiRequest is not reused here - it always parses the body as JSON.
420
+ async _fetchBlob(endpoint) {
421
+ const response = await fetch(`${this.apiUrl}${endpoint}`, {
422
+ headers: this._authHeaders(),
423
+ credentials: 'include'
424
+ });
425
+
426
+ if (!response.ok) {
427
+ throw new Error(`HTTP error! status: ${response.status}`);
428
+ }
429
+
430
+ return response;
431
+ }
432
+
433
+ async downloadAttachment(attachmentId, suggestedFilename = null) {
434
+ try {
435
+ const response = await this._fetchBlob(`/v1/account/${this.account}/attachment/${attachmentId}`);
391
436
 
392
437
  // Get filename from Content-Disposition header if available
393
438
  const contentDisposition = response.headers.get('content-disposition');
@@ -399,18 +444,9 @@ export class EmailEngineClient {
399
444
  }
400
445
  }
401
446
 
402
- // Get the attachment data
447
+ // Get the attachment data and trigger the download
403
448
  const blob = await response.blob();
404
-
405
- // Create a download link
406
- const url = window.URL.createObjectURL(blob);
407
- const a = document.createElement('a');
408
- a.href = url;
409
- a.download = filename;
410
- document.body.appendChild(a);
411
- a.click();
412
- document.body.removeChild(a);
413
- window.URL.revokeObjectURL(url);
449
+ this._saveBlob(blob, filename);
414
450
  } catch (error) {
415
451
  console.error('Failed to download attachment:', error);
416
452
  this.alertMethod('Failed to download attachment. Please try again.', 'Download Error', null, 'OK');
@@ -419,19 +455,7 @@ export class EmailEngineClient {
419
455
 
420
456
  async downloadOriginalMessage(messageId, subject = null) {
421
457
  try {
422
- const headers = {};
423
- if (this.accessToken) {
424
- headers['Authorization'] = `Bearer ${this.accessToken}`;
425
- }
426
-
427
- const response = await fetch(`${this.apiUrl}/v1/account/${this.account}/message/${messageId}/source`, {
428
- headers,
429
- credentials: 'include'
430
- });
431
-
432
- if (!response.ok) {
433
- throw new Error(`HTTP error! status: ${response.status}`);
434
- }
458
+ const response = await this._fetchBlob(`/v1/account/${this.account}/message/${messageId}/source`);
435
459
 
436
460
  // Get the email data
437
461
  const blob = await response.blob();
@@ -442,15 +466,7 @@ export class EmailEngineClient {
442
466
  const safeSubject = subject ? subject.replace(/[^a-z0-9]/gi, '_').substring(0, 50) : 'email';
443
467
  const filename = `${dateStr}_${safeSubject}.eml`;
444
468
 
445
- // Create a download link
446
- const url = window.URL.createObjectURL(blob);
447
- const a = document.createElement('a');
448
- a.href = url;
449
- a.download = filename;
450
- document.body.appendChild(a);
451
- a.click();
452
- document.body.removeChild(a);
453
- window.URL.revokeObjectURL(url);
469
+ this._saveBlob(blob, filename);
454
470
  } catch (error) {
455
471
  console.error('Failed to download original message:', error);
456
472
  this.alertMethod('Failed to download original message. Please try again.', 'Download Error', null, 'OK');
@@ -1265,18 +1281,14 @@ export class EmailEngineClient {
1265
1281
  }
1266
1282
  `;
1267
1283
  document.head.appendChild(style);
1284
+ this._styleElement = style;
1268
1285
  }
1269
1286
 
1270
- calculateFolderDepth(folder) {
1271
- if (!folder.parentPath || !folder.delimiter) {
1272
- return 0;
1287
+ buildFolderTree() {
1288
+ if (this._folderTreeCache) {
1289
+ return this._folderTreeCache;
1273
1290
  }
1274
1291
 
1275
- const pathParts = folder.path.split(folder.delimiter);
1276
- return Math.max(0, pathParts.length - 1);
1277
- }
1278
-
1279
- buildFolderTree() {
1280
1292
  const specialFolders = [];
1281
1293
  const regularFolders = [];
1282
1294
 
@@ -1311,34 +1323,52 @@ export class EmailEngineClient {
1311
1323
  return a.name.localeCompare(b.name);
1312
1324
  });
1313
1325
 
1314
- const buildHierarchy = (folders, parentPath = null, depth = 0) => {
1315
- const result = [];
1326
+ // Index children by parent in a single pass so the hierarchy walk is
1327
+ // O(n) instead of re-filtering the whole list at every level. A folder
1328
+ // whose parent is not among the regular folders (special-use parent,
1329
+ // missing parent, or no parent) is a root, keyed under null - those must
1330
+ // still surface at the top level rather than be dropped.
1331
+ const regularPaths = new Set(regularFolders.map(f => f.path));
1332
+ const childrenByParent = new Map();
1333
+ regularFolders.forEach(folder => {
1334
+ const key = regularPaths.has(folder.parentPath) ? folder.parentPath : null;
1335
+ const siblings = childrenByParent.get(key);
1336
+ if (siblings) {
1337
+ siblings.push(folder);
1338
+ } else {
1339
+ childrenByParent.set(key, [folder]);
1340
+ }
1341
+ });
1342
+ childrenByParent.forEach(siblings => siblings.sort((a, b) => a.name.localeCompare(b.name)));
1316
1343
 
1317
- const children = folders.filter(f => {
1318
- if (parentPath === null) {
1319
- return f.parentPath === 'INBOX' || !f.parentPath || f.parentPath === '';
1320
- } else {
1321
- return f.parentPath === parentPath;
1344
+ // Each entry carries its depth in the rendered tree (roots = 0). Depth
1345
+ // comes from tree position, not the path string, so a folder whose
1346
+ // parent is a special-use or missing folder renders flush at the top.
1347
+ const visited = new Set();
1348
+ const walk = (parentKey, depth) => {
1349
+ const result = [];
1350
+ const siblings = childrenByParent.get(parentKey) || [];
1351
+ siblings.forEach(folder => {
1352
+ // Guard against cyclic/self-referential parentPath values.
1353
+ if (visited.has(folder.path)) {
1354
+ return;
1322
1355
  }
1356
+ visited.add(folder.path);
1357
+ result.push({ folder, depth });
1358
+ result.push(...walk(folder.path, depth + 1));
1323
1359
  });
1324
-
1325
- children.sort((a, b) => a.name.localeCompare(b.name));
1326
-
1327
- children.forEach(folder => {
1328
- result.push(folder);
1329
- result.push(...buildHierarchy(folders, folder.path, depth + 1));
1330
- });
1331
-
1332
1360
  return result;
1333
1361
  };
1334
1362
 
1335
- const hierarchicalRegular = buildHierarchy(regularFolders);
1363
+ const hierarchicalRegular = walk(null, 0);
1336
1364
 
1337
- return [...specialFolders, ...hierarchicalRegular];
1365
+ const tree = [...specialFolders.map(folder => ({ folder, depth: 0 })), ...hierarchicalRegular];
1366
+ this._folderTreeCache = tree;
1367
+ return tree;
1338
1368
  }
1339
1369
 
1340
1370
  renderFolderList() {
1341
- if (typeof document === 'undefined' || !this.container) {
1371
+ if (typeof document === 'undefined' || !this.container || this._destroyed) {
1342
1372
  return;
1343
1373
  }
1344
1374
 
@@ -1348,20 +1378,22 @@ export class EmailEngineClient {
1348
1378
  }
1349
1379
 
1350
1380
  const sortedFolders = this.buildFolderTree();
1381
+ // Precompute which paths are some folder's parent so the per-row
1382
+ // has-children check is O(1) instead of scanning this.folders each time.
1383
+ const parentPaths = new Set(this.folders.map(f => f.parentPath));
1351
1384
 
1352
1385
  const html = `
1353
1386
  <ul class="ee-folder-list">
1354
1387
  ${sortedFolders
1355
- .map(folder => {
1356
- const depth = this.calculateFolderDepth(folder);
1357
- const hasChildren = this.folders.some(f => f.parentPath === folder.path);
1388
+ .map(({ folder, depth }) => {
1389
+ const hasChildren = parentPaths.has(folder.path);
1358
1390
  return `
1359
1391
  <li class="ee-folder-item ${folder.path === this.currentFolder ? 'active' : ''}"
1360
- data-path="${folder.path}"
1392
+ data-path="${this.escapeHtml(folder.path)}"
1361
1393
  data-depth="${depth}">
1362
1394
  <div class="ee-folder-content" style="padding-left: ${8 + depth * 12}px;">
1363
1395
  ${depth > 0 ? '<span class="ee-folder-indent">└ </span>' : ''}
1364
- <span class="ee-folder-name ${hasChildren ? 'has-children' : ''}">${folder.name}</span>
1396
+ <span class="ee-folder-name ${hasChildren ? 'has-children' : ''}">${this.escapeHtml(folder.name)}</span>
1365
1397
  ${folder.status && folder.status.messages > 0 ? `<span class="ee-folder-count">${folder.status.messages}</span>` : ''}
1366
1398
  </div>
1367
1399
  </li>
@@ -1381,7 +1413,7 @@ export class EmailEngineClient {
1381
1413
  }
1382
1414
 
1383
1415
  renderMessageList() {
1384
- if (typeof document === 'undefined' || !this.container) {
1416
+ if (typeof document === 'undefined' || !this.container || this._destroyed) {
1385
1417
  return;
1386
1418
  }
1387
1419
 
@@ -1430,16 +1462,16 @@ export class EmailEngineClient {
1430
1462
  ${this.messages
1431
1463
  .map(
1432
1464
  msg => `
1433
- <div class="ee-message-item ${msg.unseen ? 'unread' : ''} ${msg.id === (this.currentMessage && this.currentMessage.id) ? 'active' : ''}" data-id="${msg.id}">
1465
+ <div class="ee-message-item ${msg.unseen ? 'unread' : ''} ${msg.id === (this.currentMessage && this.currentMessage.id) ? 'active' : ''}" data-id="${this.escapeHtml(msg.id)}">
1434
1466
  <div class="ee-message-header">
1435
- <span class="ee-message-from">${msg.from ? msg.from.name || msg.from.address : 'Unknown'}</span>
1467
+ <span class="ee-message-from">${this.escapeHtml(msg.from ? msg.from.name || msg.from.address : 'Unknown')}</span>
1436
1468
  <span class="ee-message-date">${this.formatDate(msg.date)}</span>
1437
1469
  </div>
1438
1470
  <div class="ee-message-subject">
1439
- <span class="ee-message-subject-text">${msg.subject || '(no subject)'}</span>
1471
+ <span class="ee-message-subject-text">${this.escapeHtml(msg.subject || '(no subject)')}</span>
1440
1472
  ${msg.attachments && msg.attachments.length > 0 ? `<span class="ee-attachment-indicator">${msg.attachments.length}</span>` : ''}
1441
1473
  </div>
1442
- <div class="ee-message-preview">${msg.intro || ''}</div>
1474
+ <div class="ee-message-preview">${this.escapeHtml(msg.intro || '')}</div>
1443
1475
  </div>
1444
1476
  `
1445
1477
  )
@@ -1481,7 +1513,7 @@ export class EmailEngineClient {
1481
1513
  }
1482
1514
 
1483
1515
  renderMessage() {
1484
- if (typeof document === 'undefined' || !this.container) {
1516
+ if (typeof document === 'undefined' || !this.container || this._destroyed) {
1485
1517
  return;
1486
1518
  }
1487
1519
 
@@ -1505,11 +1537,10 @@ export class EmailEngineClient {
1505
1537
  <select class="ee-button" data-action="move">
1506
1538
  <option value="">Move to...</option>
1507
1539
  ${this.buildFolderTree()
1508
- .map(folder => {
1509
- const depth = this.calculateFolderDepth(folder);
1540
+ .map(({ folder, depth }) => {
1510
1541
  const indent = ' '.repeat(depth);
1511
1542
  const prefix = depth > 0 ? '└ ' : '';
1512
- return `<option value="${folder.path}" ${folder.path === this.currentFolder ? 'disabled' : ''}>${indent}${prefix}${folder.name}</option>`;
1543
+ return `<option value="${this.escapeHtml(folder.path)}" ${folder.path === this.currentFolder ? 'disabled' : ''}>${indent}${prefix}${this.escapeHtml(folder.name)}</option>`;
1513
1544
  })
1514
1545
  .join('')}
1515
1546
  </select>
@@ -1518,18 +1549,18 @@ export class EmailEngineClient {
1518
1549
  <div class="ee-message-meta">
1519
1550
  <div class="ee-message-meta-row">
1520
1551
  <span class="ee-message-meta-label">From:</span>
1521
- ${msg.from ? `${msg.from.name || ''} &lt;${msg.from.address}&gt;` : 'Unknown'}
1552
+ ${msg.from ? `${this.escapeHtml(msg.from.name || '')} &lt;${this.escapeHtml(msg.from.address)}&gt;` : 'Unknown'}
1522
1553
  </div>
1523
1554
  <div class="ee-message-meta-row">
1524
1555
  <span class="ee-message-meta-label">To:</span>
1525
- ${msg.to ? msg.to.map(t => `${t.name || ''} &lt;${t.address}&gt;`).join(', ') : ''}
1556
+ ${msg.to ? msg.to.map(t => `${this.escapeHtml(t.name || '')} &lt;${this.escapeHtml(t.address)}&gt;`).join(', ') : ''}
1526
1557
  </div>
1527
1558
  ${
1528
1559
  msg.cc && msg.cc.length
1529
1560
  ? `
1530
1561
  <div class="ee-message-meta-row">
1531
1562
  <span class="ee-message-meta-label">Cc:</span>
1532
- ${msg.cc.map(c => `${c.name || ''} &lt;${c.address}&gt;`).join(', ')}
1563
+ ${msg.cc.map(c => `${this.escapeHtml(c.name || '')} &lt;${this.escapeHtml(c.address)}&gt;`).join(', ')}
1533
1564
  </div>
1534
1565
  `
1535
1566
  : ''
@@ -1540,11 +1571,11 @@ export class EmailEngineClient {
1540
1571
  </div>
1541
1572
  <div class="ee-message-meta-row">
1542
1573
  <span class="ee-message-meta-label">Subject:</span>
1543
- ${msg.subject || '(no subject)'}
1574
+ ${this.escapeHtml(msg.subject || '(no subject)')}
1544
1575
  </div>
1545
1576
  </div>
1546
1577
  <div class="ee-message-body">
1547
- ${msg.text && msg.text.html ? msg.text.html : msg.text && msg.text.plain ? `<pre>${msg.text.plain}</pre>` : ''}
1578
+ ${msg.text && msg.text.html ? msg.text.html : msg.text && msg.text.plain ? `<pre>${this.escapeHtml(msg.text.plain)}</pre>` : ''}
1548
1579
  </div>
1549
1580
  ${
1550
1581
  msg.attachments && msg.attachments.length > 0
@@ -1554,10 +1585,10 @@ export class EmailEngineClient {
1554
1585
  ${msg.attachments
1555
1586
  .map(
1556
1587
  att => `
1557
- <div class="ee-attachment-item" data-attachment-id="${att.id}">
1588
+ <div class="ee-attachment-item" data-attachment-id="${this.escapeHtml(att.id)}">
1558
1589
  <div class="ee-attachment-icon">📎</div>
1559
1590
  <div class="ee-attachment-info">
1560
- <div class="ee-attachment-name">${att.filename || 'Unnamed attachment'}</div>
1591
+ <div class="ee-attachment-name">${this.escapeHtml(att.filename || 'Unnamed attachment')}</div>
1561
1592
  ${att.size ? `<div class="ee-attachment-size">${this.formatFileSize(att.size)}</div>` : ''}
1562
1593
  </div>
1563
1594
  </div>
@@ -1713,11 +1744,12 @@ export class EmailEngineClient {
1713
1744
  });
1714
1745
 
1715
1746
  // Close on Escape key
1716
- document.addEventListener('keydown', e => {
1747
+ this._composeKeydownHandler = e => {
1717
1748
  if (e.key === 'Escape' && modal.classList.contains('show')) {
1718
1749
  closeModal();
1719
1750
  }
1720
- });
1751
+ };
1752
+ document.addEventListener('keydown', this._composeKeydownHandler);
1721
1753
 
1722
1754
  // Send email
1723
1755
  sendButton.addEventListener('click', async () => {
@@ -1920,6 +1952,11 @@ export class EmailEngineClient {
1920
1952
  localStorage.setItem('ee-client-dark-mode', this.darkMode.toString());
1921
1953
  }
1922
1954
 
1955
+ // DOM updates only apply to the rendered UI; skip without a container
1956
+ if (!this.container) {
1957
+ return;
1958
+ }
1959
+
1923
1960
  // Update UI
1924
1961
  const client = this.container.querySelector('.ee-client');
1925
1962
  if (client) {
@@ -1938,40 +1975,61 @@ export class EmailEngineClient {
1938
1975
  }
1939
1976
 
1940
1977
  destroy() {
1978
+ // Mark destroyed first so any in-flight async completion skips
1979
+ // re-rendering into a torn-down or recreated container.
1980
+ this._destroyed = true;
1981
+
1941
1982
  // Clean up keep-alive timer
1942
1983
  if (this.keepAliveTimer) {
1943
1984
  clearInterval(this.keepAliveTimer);
1944
1985
  this.keepAliveTimer = null;
1945
1986
  }
1987
+
1988
+ // Remove the compose button's window scroll/resize listeners
1989
+ if (this._composeButtonCleanup) {
1990
+ this._composeButtonCleanup();
1991
+ this._composeButtonCleanup = null;
1992
+ }
1993
+
1994
+ // Remove the document-level Escape keydown listener
1995
+ if (this._composeKeydownHandler && typeof document !== 'undefined') {
1996
+ document.removeEventListener('keydown', this._composeKeydownHandler);
1997
+ this._composeKeydownHandler = null;
1998
+ }
1999
+
2000
+ // Remove the injected stylesheet
2001
+ if (this._styleElement && this._styleElement.parentNode) {
2002
+ this._styleElement.parentNode.removeChild(this._styleElement);
2003
+ this._styleElement = null;
2004
+ }
1946
2005
  }
1947
2006
  }
1948
2007
 
1949
2008
  export function createEmailEngineClient(options) {
1950
- if (typeof options === 'string') {
1951
- options = {
1952
- container: typeof document !== 'undefined' ? document.getElementById(options) : null
1953
- };
1954
- } else if (typeof HTMLElement !== 'undefined' && options instanceof HTMLElement) {
1955
- options = {
1956
- container: options
1957
- };
1958
- } else if (typeof options === 'object' && options.containerId) {
1959
- options.container = typeof document !== 'undefined' ? document.getElementById(options.containerId) : null;
2009
+ if (!options || typeof options !== 'object') {
2010
+ throw new Error('Invalid options: expected an options object');
1960
2011
  }
1961
2012
 
1962
- if (options.container && !options.container) {
1963
- throw new Error('Container element not found');
2013
+ if (!options.account) {
2014
+ throw new Error('Account identifier is required');
1964
2015
  }
1965
2016
 
1966
2017
  if (!options.apiUrl) {
1967
2018
  console.warn('No API URL specified, using default http://127.0.0.1:3000');
1968
2019
  }
1969
2020
 
1970
- if (!options.account) {
1971
- throw new Error('Account identifier is required');
2021
+ const client = new EmailEngineClient(options);
2022
+
2023
+ // The constructor is the single place that resolves containerId to an
2024
+ // element. In a DOM environment a containerId that matches nothing is a
2025
+ // caller error, so fail loudly here - and tear down the half-built client
2026
+ // so its keep-alive timer does not leak.
2027
+ if (options.containerId && !client.container && typeof document !== 'undefined') {
2028
+ client.destroy();
2029
+ throw new Error('Container element not found');
1972
2030
  }
1973
2031
 
1974
- return new EmailEngineClient(options);
2032
+ return client;
1975
2033
  }
1976
2034
 
1977
2035
  export default EmailEngineClient;