@journyio/messaging-sdk 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +256 -0
- package/dist/index.d.ts +6 -0
- package/dist/journy-messages.css +1 -0
- package/dist/journy-messages.esm.js +2833 -0
- package/dist/journy-messages.js +2860 -0
- package/dist/journy-messages.min.js +4 -0
- package/dist/types.d.ts +42 -0
- package/package.json +28 -0
|
@@ -0,0 +1,2833 @@
|
|
|
1
|
+
import * as React from 'react';
|
|
2
|
+
import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
|
|
3
|
+
|
|
4
|
+
class MessageQueue {
|
|
5
|
+
constructor() {
|
|
6
|
+
this.queue = [];
|
|
7
|
+
this.messageMap = {};
|
|
8
|
+
this.allFetchedMessages = [];
|
|
9
|
+
this.readMessageIds = new Set();
|
|
10
|
+
}
|
|
11
|
+
addMessage(message) {
|
|
12
|
+
// Check if message already exists
|
|
13
|
+
const queueMessage = this.messageMap[message.id];
|
|
14
|
+
if (queueMessage) {
|
|
15
|
+
this.updateMessageReceived(queueMessage, message);
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
if (message.expiredAt && new Date(message.expiredAt) < new Date()) {
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
this.queue.push(message);
|
|
22
|
+
this.messageMap[message.id] = message;
|
|
23
|
+
this.allFetchedMessages.push(message);
|
|
24
|
+
this.sortByPriority();
|
|
25
|
+
}
|
|
26
|
+
addMessages(messages) {
|
|
27
|
+
messages.forEach((message) => this.addMessage(message));
|
|
28
|
+
}
|
|
29
|
+
getNextMessage() {
|
|
30
|
+
this.removeExpiredMessages();
|
|
31
|
+
if (this.queue.length === 0) {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
return this.queue[0];
|
|
35
|
+
}
|
|
36
|
+
getAlreadyReceivedIds(messageIds) {
|
|
37
|
+
return messageIds.filter((id) => this.messageMap[id]?.received || this.readMessageIds.has(id));
|
|
38
|
+
}
|
|
39
|
+
removeMessage(messageIds) {
|
|
40
|
+
this.queue = this.queue.filter((m) => !messageIds.includes(m.id));
|
|
41
|
+
messageIds.forEach(id => this.readMessageIds.add(id));
|
|
42
|
+
}
|
|
43
|
+
/** Mark a message as received (user clicked/viewed it) without removing from queue */
|
|
44
|
+
markMessageAsReceived(messageIds) {
|
|
45
|
+
const updateReceived = (m) => messageIds.includes(m.id) ? { ...m, received: true } : m;
|
|
46
|
+
this.queue = this.queue.map(updateReceived);
|
|
47
|
+
this.allFetchedMessages = this.allFetchedMessages.map(updateReceived);
|
|
48
|
+
// Keep messageMap in sync so subsequent addMessages calls see received=true
|
|
49
|
+
for (const id of messageIds) {
|
|
50
|
+
if (this.messageMap[id]) {
|
|
51
|
+
this.messageMap[id] = { ...this.messageMap[id], received: true };
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
getAllMessages() {
|
|
56
|
+
this.removeExpiredMessages();
|
|
57
|
+
return [...this.queue];
|
|
58
|
+
}
|
|
59
|
+
getAllFetchedMessages() {
|
|
60
|
+
return [...this.allFetchedMessages];
|
|
61
|
+
}
|
|
62
|
+
getActiveCount() {
|
|
63
|
+
return this.queue.length;
|
|
64
|
+
}
|
|
65
|
+
getReadCount() {
|
|
66
|
+
return this.allFetchedMessages.filter((m) => this.readMessageIds.has(m.id) && !this.queue.find((q) => q.id === m.id)).length;
|
|
67
|
+
}
|
|
68
|
+
clear() {
|
|
69
|
+
this.queue = [];
|
|
70
|
+
this.allFetchedMessages = [];
|
|
71
|
+
this.readMessageIds.clear();
|
|
72
|
+
}
|
|
73
|
+
size() {
|
|
74
|
+
return this.queue.length;
|
|
75
|
+
}
|
|
76
|
+
sortByCreatedAt(a, b) {
|
|
77
|
+
return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
|
|
78
|
+
}
|
|
79
|
+
sortByPriority() {
|
|
80
|
+
const unreadMessages = this.queue.filter((m) => !m.received);
|
|
81
|
+
const readMessages = this.queue.filter((m) => m.received);
|
|
82
|
+
this.queue = [...unreadMessages.sort(this.sortByCreatedAt), ...readMessages.sort(this.sortByCreatedAt)];
|
|
83
|
+
}
|
|
84
|
+
removeExpiredMessages() {
|
|
85
|
+
const now = new Date();
|
|
86
|
+
this.queue = this.queue.filter((message) => {
|
|
87
|
+
if (message.expiredAt) {
|
|
88
|
+
return new Date(message.expiredAt) >= now;
|
|
89
|
+
}
|
|
90
|
+
return true;
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
updateMessageReceived(queueMessage, message) {
|
|
94
|
+
const updated = { ...queueMessage, received: message.received, expired: message.expired, status: message.status };
|
|
95
|
+
const idx = this.queue.indexOf(queueMessage);
|
|
96
|
+
if (idx !== -1)
|
|
97
|
+
this.queue[idx] = updated;
|
|
98
|
+
const fetchedIdx = this.allFetchedMessages.indexOf(queueMessage);
|
|
99
|
+
if (fetchedIdx !== -1)
|
|
100
|
+
this.allFetchedMessages[fetchedIdx] = updated;
|
|
101
|
+
this.messageMap[updated.id] = updated;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const API_PATHS = {
|
|
106
|
+
IN_APP_MESSAGES: '/sdk/in-app-messages',
|
|
107
|
+
};
|
|
108
|
+
class ApiClient {
|
|
109
|
+
constructor(config) {
|
|
110
|
+
this.config = config;
|
|
111
|
+
}
|
|
112
|
+
getHeaders() {
|
|
113
|
+
const headers = {
|
|
114
|
+
'Content-Type': 'application/json',
|
|
115
|
+
};
|
|
116
|
+
if (this.config.writeKey) {
|
|
117
|
+
headers['Authorization'] = `Bearer ${this.config.writeKey}`;
|
|
118
|
+
headers['x-write-key'] = this.config.writeKey;
|
|
119
|
+
}
|
|
120
|
+
return headers;
|
|
121
|
+
}
|
|
122
|
+
buildUrl(endpoint) {
|
|
123
|
+
const baseUrl = (this.config.apiEndpoint || 'https://jtm.journy.io').replace(/\/$/, '');
|
|
124
|
+
const entityId = this.config.entityType === 'user'
|
|
125
|
+
? this.config.userId
|
|
126
|
+
: this.config.accountId;
|
|
127
|
+
if (!entityId) {
|
|
128
|
+
throw new Error(`${this.config.entityType}Id is required`);
|
|
129
|
+
}
|
|
130
|
+
const targetPath = `${API_PATHS.IN_APP_MESSAGES}/${this.config.entityType}/${entityId}${endpoint}`;
|
|
131
|
+
return new URL(targetPath, baseUrl).toString();
|
|
132
|
+
}
|
|
133
|
+
async getUnreadMessages() {
|
|
134
|
+
try {
|
|
135
|
+
const url = this.buildUrl('/unread');
|
|
136
|
+
const response = await fetch(url, {
|
|
137
|
+
method: 'GET',
|
|
138
|
+
headers: this.getHeaders(),
|
|
139
|
+
mode: 'cors', // Explicitly set CORS mode
|
|
140
|
+
});
|
|
141
|
+
if (!response.ok) {
|
|
142
|
+
throw new Error(`HTTP error! status: ${response.status}`);
|
|
143
|
+
}
|
|
144
|
+
const data = await response.json();
|
|
145
|
+
return data.data || [];
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
console.error('Failed to fetch unread messages:', error);
|
|
149
|
+
return [];
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
async markAsRead(messageIds) {
|
|
153
|
+
try {
|
|
154
|
+
const url = this.buildUrl('/received');
|
|
155
|
+
const response = await fetch(url, {
|
|
156
|
+
method: 'POST',
|
|
157
|
+
headers: this.getHeaders(),
|
|
158
|
+
mode: 'cors',
|
|
159
|
+
body: JSON.stringify({
|
|
160
|
+
messageIds: messageIds,
|
|
161
|
+
}),
|
|
162
|
+
});
|
|
163
|
+
if (!response.ok) {
|
|
164
|
+
throw new Error(`HTTP error! status: ${response.status}`);
|
|
165
|
+
}
|
|
166
|
+
const data = await response.json();
|
|
167
|
+
if (data.data && data.data.markedCount !== messageIds.length) {
|
|
168
|
+
throw new Error(`Failed to mark all messages as read. Expected ${messageIds.length} messages, got ${data.data.markedCount}`);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
catch (error) {
|
|
172
|
+
console.error('Failed to mark message as read:', error);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
var SDKEventType;
|
|
178
|
+
(function (SDKEventType) {
|
|
179
|
+
SDKEventType["MessageReceived"] = "In-App Message Received";
|
|
180
|
+
SDKEventType["MessageOpened"] = "In-App Message Opened";
|
|
181
|
+
SDKEventType["MessageClosed"] = "In-App Message Closed";
|
|
182
|
+
SDKEventType["MessageLinkClicked"] = "In-App Message Link Clicked";
|
|
183
|
+
})(SDKEventType || (SDKEventType = {}));
|
|
184
|
+
const DEFAULT_WIDGET_SETTINGS = {
|
|
185
|
+
pollingInterval: 30000,
|
|
186
|
+
showReadMessages: true,
|
|
187
|
+
autoExpandOnNew: true,
|
|
188
|
+
displayMode: 'widget',
|
|
189
|
+
apiEndpoint: 'https://jtm.journy.io',
|
|
190
|
+
styles: 'default',
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
const STORAGE_PREFIX = 'journy_messages_';
|
|
194
|
+
function getStorageKey(key) {
|
|
195
|
+
return `${STORAGE_PREFIX}${key}`;
|
|
196
|
+
}
|
|
197
|
+
function setItem(key, value) {
|
|
198
|
+
try {
|
|
199
|
+
const storageKey = getStorageKey(key);
|
|
200
|
+
localStorage.setItem(storageKey, JSON.stringify(value));
|
|
201
|
+
}
|
|
202
|
+
catch (error) {
|
|
203
|
+
console.warn('Failed to set item in localStorage:', error);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
function getItem(key) {
|
|
207
|
+
try {
|
|
208
|
+
const storageKey = getStorageKey(key);
|
|
209
|
+
const item = localStorage.getItem(storageKey);
|
|
210
|
+
return item ? JSON.parse(item) : null;
|
|
211
|
+
}
|
|
212
|
+
catch (error) {
|
|
213
|
+
console.warn('Failed to get item from localStorage:', error);
|
|
214
|
+
return null;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
function removeItem(key) {
|
|
218
|
+
try {
|
|
219
|
+
const storageKey = getStorageKey(key);
|
|
220
|
+
localStorage.removeItem(storageKey);
|
|
221
|
+
}
|
|
222
|
+
catch (error) {
|
|
223
|
+
console.warn('Failed to remove item from localStorage:', error);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
class EventTracker {
|
|
228
|
+
constructor(analyticsClient) {
|
|
229
|
+
this.analyticsClient = analyticsClient;
|
|
230
|
+
this.eventQueue = [];
|
|
231
|
+
this.flushInterval = null;
|
|
232
|
+
this.loadQueuedEvents();
|
|
233
|
+
this.startFlushInterval();
|
|
234
|
+
}
|
|
235
|
+
track(event, properties) {
|
|
236
|
+
const eventData = {
|
|
237
|
+
event,
|
|
238
|
+
properties,
|
|
239
|
+
timestamp: new Date().toISOString(),
|
|
240
|
+
};
|
|
241
|
+
this.eventQueue.push(eventData);
|
|
242
|
+
this.saveQueuedEvents();
|
|
243
|
+
if (this.isImportantEvent(event)) {
|
|
244
|
+
this.flush().catch((error) => {
|
|
245
|
+
console.error('Failed to flush events:', error);
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
async flush() {
|
|
250
|
+
if (this.eventQueue.length === 0) {
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
const eventsToSend = [...this.eventQueue];
|
|
254
|
+
try {
|
|
255
|
+
const success = await this.analyticsClient.trackEvents(eventsToSend.map(({ event, properties }) => ({
|
|
256
|
+
event,
|
|
257
|
+
properties: properties || {},
|
|
258
|
+
})));
|
|
259
|
+
if (success) {
|
|
260
|
+
// Remove successfully sent events from queue
|
|
261
|
+
this.eventQueue = this.eventQueue.filter(e => !eventsToSend.includes(e));
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
console.error('Failed to flush events:', error);
|
|
266
|
+
}
|
|
267
|
+
this.saveQueuedEvents();
|
|
268
|
+
}
|
|
269
|
+
startFlushInterval() {
|
|
270
|
+
this.flushInterval = window.setInterval(() => {
|
|
271
|
+
this.flush().catch((error) => {
|
|
272
|
+
console.error('Failed to flush events:', error);
|
|
273
|
+
});
|
|
274
|
+
}, EventTracker.FLUSH_INTERVAL_MS);
|
|
275
|
+
}
|
|
276
|
+
destroy() {
|
|
277
|
+
if (this.flushInterval !== null) {
|
|
278
|
+
clearInterval(this.flushInterval);
|
|
279
|
+
this.flushInterval = null;
|
|
280
|
+
}
|
|
281
|
+
// Flush remaining events before destroying
|
|
282
|
+
this.flush().catch((error) => {
|
|
283
|
+
console.error('Failed to flush events on destroy:', error);
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
isImportantEvent(event) {
|
|
287
|
+
return EventTracker.IMPORTANT_MESSAGES.includes(event);
|
|
288
|
+
}
|
|
289
|
+
saveQueuedEvents() {
|
|
290
|
+
setItem('event_queue', this.eventQueue);
|
|
291
|
+
}
|
|
292
|
+
loadQueuedEvents() {
|
|
293
|
+
const queued = getItem('event_queue');
|
|
294
|
+
if (queued && Array.isArray(queued)) {
|
|
295
|
+
this.eventQueue = queued;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
EventTracker.FLUSH_INTERVAL_MS = 5000;
|
|
300
|
+
EventTracker.IMPORTANT_MESSAGES = [
|
|
301
|
+
SDKEventType.MessageOpened,
|
|
302
|
+
SDKEventType.MessageClosed,
|
|
303
|
+
SDKEventType.MessageLinkClicked,
|
|
304
|
+
];
|
|
305
|
+
|
|
306
|
+
class MessagingStore {
|
|
307
|
+
constructor(initialState) {
|
|
308
|
+
this.listeners = new Set();
|
|
309
|
+
this.state = initialState;
|
|
310
|
+
}
|
|
311
|
+
getState() {
|
|
312
|
+
return this.state;
|
|
313
|
+
}
|
|
314
|
+
setState(partial) {
|
|
315
|
+
this.state = { ...this.state, ...partial };
|
|
316
|
+
this.listeners.forEach(l => l());
|
|
317
|
+
}
|
|
318
|
+
subscribe(listener) {
|
|
319
|
+
this.listeners.add(listener);
|
|
320
|
+
return () => {
|
|
321
|
+
this.listeners.delete(listener);
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
destroy() {
|
|
325
|
+
this.listeners.clear();
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
function createRootElement(id) {
|
|
330
|
+
let element = document.getElementById(id);
|
|
331
|
+
if (!element) {
|
|
332
|
+
element = document.createElement('div');
|
|
333
|
+
element.id = id;
|
|
334
|
+
document.body.appendChild(element);
|
|
335
|
+
}
|
|
336
|
+
return element;
|
|
337
|
+
}
|
|
338
|
+
function removeRootElement(id) {
|
|
339
|
+
const element = document.getElementById(id);
|
|
340
|
+
if (element) {
|
|
341
|
+
element.remove();
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
const STYLES_LINK_ID = 'journy-messages-styles-link';
|
|
345
|
+
const STYLES_TAG_ID = 'journy-messages-custom';
|
|
346
|
+
const DEFAULT_STYLES_TAG_ID = 'journy-messages-default';
|
|
347
|
+
function injectStyleLink(href) {
|
|
348
|
+
if (typeof document === 'undefined' || !document.head)
|
|
349
|
+
return;
|
|
350
|
+
const existing = document.getElementById(STYLES_LINK_ID);
|
|
351
|
+
if (existing && existing instanceof HTMLLinkElement && existing.href === href)
|
|
352
|
+
return;
|
|
353
|
+
if (existing)
|
|
354
|
+
existing.remove();
|
|
355
|
+
const link = document.createElement('link');
|
|
356
|
+
link.id = STYLES_LINK_ID;
|
|
357
|
+
link.rel = 'stylesheet';
|
|
358
|
+
link.href = href;
|
|
359
|
+
document.head.appendChild(link);
|
|
360
|
+
}
|
|
361
|
+
function injectStyleTag(css, id = STYLES_TAG_ID) {
|
|
362
|
+
if (typeof document === 'undefined' || !document.head)
|
|
363
|
+
return;
|
|
364
|
+
let style = document.getElementById(id);
|
|
365
|
+
if (style) {
|
|
366
|
+
style.textContent = css;
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
style = document.createElement('style');
|
|
370
|
+
style.id = id;
|
|
371
|
+
style.textContent = css;
|
|
372
|
+
document.head.appendChild(style);
|
|
373
|
+
}
|
|
374
|
+
function removeInjectedStyles() {
|
|
375
|
+
if (typeof document === 'undefined')
|
|
376
|
+
return;
|
|
377
|
+
const link = document.getElementById(STYLES_LINK_ID);
|
|
378
|
+
if (link)
|
|
379
|
+
link.remove();
|
|
380
|
+
const style = document.getElementById(STYLES_TAG_ID);
|
|
381
|
+
if (style)
|
|
382
|
+
style.remove();
|
|
383
|
+
const defaultStyle = document.getElementById(DEFAULT_STYLES_TAG_ID);
|
|
384
|
+
if (defaultStyle)
|
|
385
|
+
defaultStyle.remove();
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
var defaultStyles = "/* Widget Container */\n.journy-message-widget {\n position: fixed;\n z-index: 10000;\n background: white;\n border-radius: 12px;\n box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);\n overflow: hidden;\n user-select: none;\n transform-origin: bottom right;\n}\n\n.journy-message-widget.journy-message-widget-dragging {\n cursor: grabbing;\n transition: none;\n z-index: 10001;\n}\n\n.journy-message-widget.journy-message-widget-expanded {\n display: flex;\n flex-direction: column;\n min-height: 0;\n}\n\n.journy-message-widget.journy-message-widget-resizing {\n transition: none;\n}\n\n/* Expand/collapse: height and top are animated via inline transition so bottom-right stays fixed */\n\n/* Widget Header */\n.journy-message-widget-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 12px 16px;\n background: #f9fafb;\n border-bottom: 1px solid #e5e7eb;\n user-select: none;\n}\n\n.journy-message-widget-drag-handle {\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 4px 8px;\n margin-right: 8px;\n cursor: grab;\n color: #9ca3af;\n transition: color 0.2s;\n flex-shrink: 0;\n}\n\n.journy-message-widget-drag-handle:active {\n cursor: grabbing;\n color: #6b7280;\n}\n\n.journy-message-widget-drag-handle:hover {\n color: #6b7280;\n}\n\n.journy-message-widget-drag-handle svg {\n display: block;\n}\n\n.journy-message-widget-header-content {\n display: flex;\n align-items: center;\n gap: 10px;\n flex: 1;\n flex-wrap: wrap;\n cursor: pointer;\n}\n\n.journy-message-widget-badge {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n min-width: 24px;\n height: 24px;\n padding: 0 8px;\n background: #3b82f6;\n color: white;\n border-radius: 12px;\n font-size: 12px;\n font-weight: 600;\n}\n\n.journy-message-widget-title {\n font-size: 14px;\n font-weight: 600;\n color: #111827;\n}\n\n.journy-message-widget-read-count {\n font-size: 12px;\n color: #6b7280;\n font-weight: 400;\n}\n\n.journy-message-widget-controls {\n display: flex;\n align-items: center;\n gap: 8px;\n}\n\n.journy-message-widget-toggle,\n.journy-message-widget-close {\n background: none;\n border: none;\n font-size: 18px;\n line-height: 1;\n cursor: pointer;\n color: #6b7280;\n padding: 4px 8px;\n border-radius: 4px;\n transition: background-color 0.2s, color 0.2s;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n}\n\n.journy-message-widget-toggle:hover,\n.journy-message-widget-close:hover {\n background-color: #e5e7eb;\n color: #374151;\n}\n\n/* Widget Content */\n.journy-message-widget-content {\n padding: 16px;\n flex: 1;\n overflow-y: auto;\n overflow-x: hidden;\n min-height: 0;\n display: flex;\n flex-direction: column;\n}\n\n.journy-message-widget-content--single .journy-message-widget-message {\n flex: 1;\n min-height: 0;\n display: flex;\n flex-direction: column;\n}\n\n.journy-message-widget-content--single .journy-message-widget-message .journy-message-content {\n flex: 1;\n min-height: 0;\n overflow-y: auto;\n}\n\n/* Resize Handle */\n.journy-message-widget-resize-handle {\n position: absolute;\n bottom: 0;\n right: 0;\n width: 20px;\n height: 20px;\n cursor: nwse-resize;\n display: flex;\n align-items: center;\n justify-content: center;\n background: linear-gradient(135deg, transparent 0%, transparent 40%, #e5e7eb 40%, #e5e7eb 100%);\n z-index: 10;\n transition: background 0.2s;\n}\n\n.journy-message-widget-resize-handle:hover {\n background: linear-gradient(135deg, transparent 0%, transparent 40%, #d1d5db 40%, #d1d5db 100%);\n}\n\n.journy-message-widget-resize-handle svg {\n width: 12px;\n height: 12px;\n opacity: 0.6;\n}\n\n.journy-message-widget-resize-handle:hover svg {\n opacity: 1;\n}\n\n.journy-message-widget-message {\n padding: 0;\n position: relative;\n min-height: 60px;\n}\n\n.journy-message-widget-message-close {\n position: absolute;\n top: 4px;\n right: 4px;\n width: 24px;\n height: 24px;\n padding: 0;\n border: none;\n background: transparent;\n color: #6b7280;\n font-size: 18px;\n line-height: 1;\n cursor: pointer;\n border-radius: 4px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: background-color 0.2s, color 0.2s;\n z-index: 1;\n}\n\n.journy-message-widget-message-close:hover {\n background-color: #e5e7eb;\n color: #374151;\n}\n\n.journy-message-widget-message:has(.journy-message-widget-message-close) .journy-message-content {\n padding-right: 28px;\n}\n\n.journy-message-widget-nav {\n background: none;\n border: none;\n font-size: 18px;\n line-height: 1;\n cursor: pointer;\n color: #6b7280;\n padding: 4px 6px;\n border-radius: 4px;\n transition: background-color 0.2s, color 0.2s;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n}\n\n.journy-message-widget-nav:hover:not(:disabled) {\n background-color: #e5e7eb;\n color: #374151;\n}\n\n.journy-message-widget-nav:disabled {\n opacity: 0.4;\n cursor: default;\n}\n\n.journy-message-widget-message-separated {\n margin-bottom: 24px;\n padding-bottom: 24px;\n border-bottom: 1px solid #e5e7eb;\n}\n\n.journy-message-widget-message-count {\n font-size: 12px;\n color: #6b7280;\n font-weight: 400;\n margin-left: 8px;\n}\n\n.journy-message-widget-position {\n padding: 4px 12px;\n font-size: 11px;\n color: #9ca3af;\n font-weight: 500;\n text-align: right;\n flex-shrink: 0;\n}\n\n.journy-message-widget-message.journy-message-info {\n border-left: 4px solid #3b82f6;\n padding-left: 12px;\n}\n\n.journy-message-widget-message.journy-message-success {\n border-left: 4px solid #10b981;\n padding-left: 12px;\n}\n\n.journy-message-widget-message.journy-message-warning {\n border-left: 4px solid #f59e0b;\n padding-left: 12px;\n}\n\n.journy-message-widget-message.journy-message-error {\n border-left: 4px solid #ef4444;\n padding-left: 12px;\n}\n\n.journy-message-widget-message.journy-message-viewed {\n border-left: 4px solid #6b7280;\n padding-left: 12px;\n}\n\n/* Message modal (80vw x 60vh) */\n.journy-message-modal-overlay {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: rgba(0, 0, 0, 0.5);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 10002;\n padding: 20px;\n}\n\n.journy-message-modal {\n width: 80vw;\n max-width: 80vw;\n height: 60vh;\n max-height: 60vh;\n background: white;\n border-radius: 12px;\n box-shadow: 0 4px 24px rgba(0, 0, 0, 0.2);\n overflow: hidden;\n display: flex;\n flex-direction: column;\n position: relative;\n}\n\n.journy-message-modal-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 16px 24px;\n background: #f9fafb;\n border-bottom: 1px solid #e5e7eb;\n flex-shrink: 0;\n}\n\n.journy-message-modal-title {\n font-size: 18px;\n font-weight: 600;\n color: #111827;\n}\n\n.journy-message-modal-close {\n background: none;\n border: none;\n font-size: 24px;\n line-height: 1;\n cursor: pointer;\n color: #6b7280;\n padding: 4px 8px;\n border-radius: 4px;\n transition: background-color 0.2s, color 0.2s;\n}\n\n.journy-message-modal-close:hover {\n background-color: #e5e7eb;\n color: #374151;\n}\n\n.journy-message-modal .journy-message-widget-message {\n padding: 24px 24px 24px 24px;\n overflow-y: auto;\n flex: 1;\n min-height: 0;\n}\n\n/* Timestamp */\n.journy-message-timestamp {\n font-size: 12px;\n color: #6b7280;\n margin-top: 4px;\n line-height: 1.4;\n}\n\n.journy-message-content-clickable {\n cursor: pointer;\n}\n\n.journy-message-content-clickable:hover {\n opacity: 0.95;\n}\n\n/* Legacy Modal Overlay Styles (kept for backward compatibility) */\n.journy-message-overlay {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background-color: rgba(0, 0, 0, 0.5);\n display: flex;\n align-items: center;\n justify-content: center;\n z-index: 10000;\n opacity: 0;\n transition: opacity 0.3s ease-in-out;\n pointer-events: none;\n}\n\n.journy-message-overlay.journy-message-visible {\n opacity: 1;\n pointer-events: all;\n}\n\n.journy-message-popup {\n background: white;\n border-radius: 8px;\n padding: 24px;\n max-width: 500px;\n width: 90%;\n max-height: 80vh;\n overflow-y: auto;\n box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);\n position: relative;\n transform: scale(0.9);\n transition: transform 0.3s ease-in-out;\n}\n\n.journy-message-overlay.journy-message-visible .journy-message-popup {\n transform: scale(1);\n}\n\n.journy-message-popup.journy-message-info {\n border-top: 4px solid #3b82f6;\n}\n\n.journy-message-popup.journy-message-success {\n border-top: 4px solid #10b981;\n}\n\n.journy-message-popup.journy-message-warning {\n border-top: 4px solid #f59e0b;\n}\n\n.journy-message-popup.journy-message-error {\n border-top: 4px solid #ef4444;\n}\n\n.journy-message-popup.journy-message-viewed {\n border-top: 4px solid #6b7280;\n}\n\n.journy-message-close {\n position: absolute;\n top: 12px;\n right: 12px;\n background: none;\n border: none;\n font-size: 24px;\n line-height: 1;\n cursor: pointer;\n color: #6b7280;\n padding: 4px 8px;\n border-radius: 4px;\n transition: background-color 0.2s, color 0.2s;\n}\n\n.journy-message-close:hover {\n background-color: #f3f4f6;\n color: #374151;\n}\n\n.journy-message-title {\n font-size: 20px;\n font-weight: 600;\n margin-bottom: 12px;\n color: #111827;\n}\n\n.journy-message-content {\n font-size: 16px;\n line-height: 1.6;\n color: #374151;\n margin-bottom: 16px;\n}\n\n.journy-message-content a {\n color: #3b82f6;\n text-decoration: underline;\n transition: color 0.2s;\n}\n\n.journy-message-content a:hover {\n color: #2563eb;\n}\n\n.journy-message-content p {\n margin: 0 0 12px 0;\n}\n\n.journy-message-content p:last-child {\n margin-bottom: 0;\n}\n\n.journy-message-content ul,\n.journy-message-content ol {\n margin: 12px 0;\n padding-left: 24px;\n}\n\n.journy-message-content li {\n margin-bottom: 8px;\n}\n\n/* Headings */\n.journy-message-content h1,\n.journy-message-content h2,\n.journy-message-content h3,\n.journy-message-content h4,\n.journy-message-content h5,\n.journy-message-content h6 {\n margin: 16px 0 12px 0;\n font-weight: 600;\n line-height: 1.3;\n color: #111827;\n}\n\n.journy-message-content h1 {\n font-size: 24px;\n}\n\n.journy-message-content h2 {\n font-size: 20px;\n}\n\n.journy-message-content h3 {\n font-size: 18px;\n}\n\n.journy-message-content h4 {\n font-size: 16px;\n}\n\n.journy-message-content h5,\n.journy-message-content h6 {\n font-size: 14px;\n}\n\n/* Code blocks */\n.journy-message-content code {\n background-color: #f3f4f6;\n color: #ef4444;\n padding: 2px 6px;\n border-radius: 4px;\n font-size: 0.9em;\n font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;\n}\n\n.journy-message-content pre {\n background-color: #1f2937;\n color: #f9fafb;\n padding: 16px;\n border-radius: 8px;\n overflow-x: auto;\n margin: 12px 0;\n font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;\n font-size: 14px;\n line-height: 1.5;\n}\n\n.journy-message-content pre code {\n background-color: transparent;\n color: inherit;\n padding: 0;\n border-radius: 0;\n font-size: inherit;\n}\n\n/* Text formatting */\n.journy-message-content u {\n text-decoration: underline;\n}\n\n.journy-message-content s,\n.journy-message-content strike,\n.journy-message-content del {\n text-decoration: line-through;\n}\n\n.journy-message-content strong {\n font-weight: 600;\n}\n\n.journy-message-content em {\n font-style: italic;\n}\n\n/* Blockquotes */\n.journy-message-content blockquote {\n border-left: 4px solid #e5e7eb;\n padding-left: 16px;\n margin: 12px 0;\n color: #6b7280;\n font-style: italic;\n}\n\n/* Tables */\n.journy-message-content table {\n width: 100%;\n border-collapse: collapse;\n margin: 12px 0;\n}\n\n.journy-message-content th,\n.journy-message-content td {\n border: 1px solid #e5e7eb;\n padding: 8px 12px;\n text-align: left;\n}\n\n.journy-message-content th {\n background-color: #f9fafb;\n font-weight: 600;\n}\n\n/* Horizontal rule */\n.journy-message-content hr {\n border: none;\n border-top: 1px solid #e5e7eb;\n margin: 16px 0;\n}\n\n.journy-message-actions {\n display: flex;\n gap: 12px;\n margin-top: 20px;\n flex-wrap: wrap;\n}\n\n.journy-message-action {\n padding: 10px 20px;\n border-radius: 6px;\n font-size: 14px;\n font-weight: 500;\n cursor: pointer;\n border: none;\n transition: all 0.2s;\n}\n\n.journy-message-action-primary {\n background-color: #3b82f6;\n color: white;\n}\n\n.journy-message-action-primary:hover {\n background-color: #2563eb;\n}\n\n.journy-message-action-secondary {\n background-color: #e5e7eb;\n color: #374151;\n}\n\n.journy-message-action-secondary:hover {\n background-color: #d1d5db;\n}\n\n.journy-message-action-link {\n background: none;\n color: #3b82f6;\n text-decoration: underline;\n padding: 10px 0;\n}\n\n.journy-message-action-link:hover {\n color: #2563eb;\n}\n\n/* Settings Panel */\n.journy-settings-panel {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n width: 100%;\n background: white;\n z-index: 10;\n display: flex;\n flex-direction: column;\n transform: translateX(100%);\n transition: transform 0.3s ease;\n}\n\n.journy-settings-panel-open {\n transform: translateX(0);\n}\n\n.journy-settings-panel-closed {\n transform: translateX(100%);\n}\n\n.journy-settings-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 12px 16px;\n background: #f9fafb;\n border-bottom: 1px solid #e5e7eb;\n flex-shrink: 0;\n}\n\n.journy-settings-title {\n font-size: 14px;\n font-weight: 600;\n color: #111827;\n}\n\n.journy-settings-close {\n background: none;\n border: none;\n font-size: 18px;\n line-height: 1;\n cursor: pointer;\n color: #6b7280;\n padding: 4px 8px;\n border-radius: 4px;\n transition: background-color 0.2s, color 0.2s;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n}\n\n.journy-settings-close:hover {\n background-color: #e5e7eb;\n color: #374151;\n}\n\n.journy-settings-body {\n padding: 16px;\n overflow-y: auto;\n flex: 1;\n}\n\n.journy-settings-item {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 12px 0;\n border-bottom: 1px solid #f3f4f6;\n}\n\n.journy-settings-item:last-child {\n border-bottom: none;\n}\n\n.journy-settings-label {\n font-size: 13px;\n font-weight: 500;\n color: #374151;\n}\n\n.journy-settings-select {\n padding: 6px 10px;\n border: 1px solid #d1d5db;\n border-radius: 6px;\n font-size: 13px;\n color: #374151;\n background: white;\n cursor: pointer;\n outline: none;\n transition: border-color 0.2s;\n}\n\n.journy-settings-select:focus {\n border-color: #3b82f6;\n}\n\n.journy-settings-toggle {\n position: relative;\n width: 40px;\n height: 22px;\n border-radius: 11px;\n border: none;\n background: #d1d5db;\n cursor: pointer;\n padding: 0;\n transition: background-color 0.2s;\n flex-shrink: 0;\n}\n\n.journy-settings-toggle-on {\n background: #3b82f6;\n}\n\n.journy-settings-toggle-knob {\n position: absolute;\n top: 2px;\n left: 2px;\n width: 18px;\n height: 18px;\n border-radius: 50%;\n background: white;\n box-shadow: 0 1px 3px rgba(0, 0, 0, 0.15);\n transition: transform 0.2s;\n}\n\n.journy-settings-toggle-on .journy-settings-toggle-knob {\n transform: translateX(18px);\n}\n\n.journy-settings-item-vertical {\n flex-direction: column;\n align-items: flex-start;\n gap: 6px;\n}\n\n.journy-settings-input {\n width: 100%;\n padding: 6px 10px;\n border: 1px solid #d1d5db;\n border-radius: 6px;\n font-size: 13px;\n color: #374151;\n background: white;\n outline: none;\n transition: border-color 0.2s;\n box-sizing: border-box;\n}\n\n.journy-settings-input:focus {\n border-color: #3b82f6;\n}\n\n.journy-settings-input::placeholder {\n color: #9ca3af;\n}\n\n.journy-settings-value {\n font-size: 13px;\n color: #6b7280;\n font-weight: 400;\n max-width: 60%;\n text-align: right;\n word-break: break-all;\n}\n\n.journy-message-widget-empty {\n display: flex;\n align-items: center;\n justify-content: center;\n color: #9ca3af;\n font-size: 14px;\n flex: 1;\n min-height: 80px;\n}\n\n.journy-settings-advanced-btn {\n background: none;\n border: none;\n font-size: 13px;\n font-weight: 500;\n color: #6b7280;\n cursor: pointer;\n padding: 0;\n transition: color 0.2s;\n}\n\n.journy-settings-advanced-btn:hover {\n color: #374151;\n}\n\n.journy-message-widget-settings-btn {\n background: none;\n border: none;\n font-size: 16px;\n line-height: 1;\n cursor: pointer;\n color: #6b7280;\n padding: 4px 8px;\n border-radius: 4px;\n transition: background-color 0.2s, color 0.2s;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n}\n\n.journy-message-widget-settings-btn:hover {\n background-color: #e5e7eb;\n color: #374151;\n}\n\n/* Responsive design */\n@media (max-width: 640px) {\n .journy-message-widget {\n min-width: calc(100vw - 32px);\n max-width: calc(100vw - 32px);\n left: 16px !important;\n right: 16px !important;\n }\n\n .journy-message-popup {\n width: 95%;\n padding: 20px;\n }\n\n .journy-message-title {\n font-size: 18px;\n }\n\n .journy-message-content {\n font-size: 14px;\n }\n\n .journy-message-actions {\n flex-direction: column;\n }\n\n .journy-message-action {\n width: 100%;\n }\n}\n";
|
|
389
|
+
|
|
390
|
+
function useMessagingStore(store) {
|
|
391
|
+
const [state, setState] = useState(() => store.getState());
|
|
392
|
+
useEffect(() => {
|
|
393
|
+
// Sync in case state changed between render and effect
|
|
394
|
+
setState(store.getState());
|
|
395
|
+
return store.subscribe(() => setState(store.getState()));
|
|
396
|
+
}, [store]);
|
|
397
|
+
return state;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/*! @license DOMPurify 3.3.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.1/LICENSE */
|
|
401
|
+
|
|
402
|
+
const {
|
|
403
|
+
entries,
|
|
404
|
+
setPrototypeOf,
|
|
405
|
+
isFrozen,
|
|
406
|
+
getPrototypeOf,
|
|
407
|
+
getOwnPropertyDescriptor
|
|
408
|
+
} = Object;
|
|
409
|
+
let {
|
|
410
|
+
freeze,
|
|
411
|
+
seal,
|
|
412
|
+
create
|
|
413
|
+
} = Object; // eslint-disable-line import/no-mutable-exports
|
|
414
|
+
let {
|
|
415
|
+
apply,
|
|
416
|
+
construct
|
|
417
|
+
} = typeof Reflect !== 'undefined' && Reflect;
|
|
418
|
+
if (!freeze) {
|
|
419
|
+
freeze = function freeze(x) {
|
|
420
|
+
return x;
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
if (!seal) {
|
|
424
|
+
seal = function seal(x) {
|
|
425
|
+
return x;
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
if (!apply) {
|
|
429
|
+
apply = function apply(func, thisArg) {
|
|
430
|
+
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
|
|
431
|
+
args[_key - 2] = arguments[_key];
|
|
432
|
+
}
|
|
433
|
+
return func.apply(thisArg, args);
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
if (!construct) {
|
|
437
|
+
construct = function construct(Func) {
|
|
438
|
+
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
|
|
439
|
+
args[_key2 - 1] = arguments[_key2];
|
|
440
|
+
}
|
|
441
|
+
return new Func(...args);
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
const arrayForEach = unapply(Array.prototype.forEach);
|
|
445
|
+
const arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);
|
|
446
|
+
const arrayPop = unapply(Array.prototype.pop);
|
|
447
|
+
const arrayPush = unapply(Array.prototype.push);
|
|
448
|
+
const arraySplice = unapply(Array.prototype.splice);
|
|
449
|
+
const stringToLowerCase = unapply(String.prototype.toLowerCase);
|
|
450
|
+
const stringToString = unapply(String.prototype.toString);
|
|
451
|
+
const stringMatch = unapply(String.prototype.match);
|
|
452
|
+
const stringReplace = unapply(String.prototype.replace);
|
|
453
|
+
const stringIndexOf = unapply(String.prototype.indexOf);
|
|
454
|
+
const stringTrim = unapply(String.prototype.trim);
|
|
455
|
+
const objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);
|
|
456
|
+
const regExpTest = unapply(RegExp.prototype.test);
|
|
457
|
+
const typeErrorCreate = unconstruct(TypeError);
|
|
458
|
+
/**
|
|
459
|
+
* Creates a new function that calls the given function with a specified thisArg and arguments.
|
|
460
|
+
*
|
|
461
|
+
* @param func - The function to be wrapped and called.
|
|
462
|
+
* @returns A new function that calls the given function with a specified thisArg and arguments.
|
|
463
|
+
*/
|
|
464
|
+
function unapply(func) {
|
|
465
|
+
return function (thisArg) {
|
|
466
|
+
if (thisArg instanceof RegExp) {
|
|
467
|
+
thisArg.lastIndex = 0;
|
|
468
|
+
}
|
|
469
|
+
for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
|
|
470
|
+
args[_key3 - 1] = arguments[_key3];
|
|
471
|
+
}
|
|
472
|
+
return apply(func, thisArg, args);
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* Creates a new function that constructs an instance of the given constructor function with the provided arguments.
|
|
477
|
+
*
|
|
478
|
+
* @param func - The constructor function to be wrapped and called.
|
|
479
|
+
* @returns A new function that constructs an instance of the given constructor function with the provided arguments.
|
|
480
|
+
*/
|
|
481
|
+
function unconstruct(Func) {
|
|
482
|
+
return function () {
|
|
483
|
+
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
|
|
484
|
+
args[_key4] = arguments[_key4];
|
|
485
|
+
}
|
|
486
|
+
return construct(Func, args);
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* Add properties to a lookup table
|
|
491
|
+
*
|
|
492
|
+
* @param set - The set to which elements will be added.
|
|
493
|
+
* @param array - The array containing elements to be added to the set.
|
|
494
|
+
* @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.
|
|
495
|
+
* @returns The modified set with added elements.
|
|
496
|
+
*/
|
|
497
|
+
function addToSet(set, array) {
|
|
498
|
+
let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;
|
|
499
|
+
if (setPrototypeOf) {
|
|
500
|
+
// Make 'in' and truthy checks like Boolean(set.constructor)
|
|
501
|
+
// independent of any properties defined on Object.prototype.
|
|
502
|
+
// Prevent prototype setters from intercepting set as a this value.
|
|
503
|
+
setPrototypeOf(set, null);
|
|
504
|
+
}
|
|
505
|
+
let l = array.length;
|
|
506
|
+
while (l--) {
|
|
507
|
+
let element = array[l];
|
|
508
|
+
if (typeof element === 'string') {
|
|
509
|
+
const lcElement = transformCaseFunc(element);
|
|
510
|
+
if (lcElement !== element) {
|
|
511
|
+
// Config presets (e.g. tags.js, attrs.js) are immutable.
|
|
512
|
+
if (!isFrozen(array)) {
|
|
513
|
+
array[l] = lcElement;
|
|
514
|
+
}
|
|
515
|
+
element = lcElement;
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
set[element] = true;
|
|
519
|
+
}
|
|
520
|
+
return set;
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
523
|
+
* Clean up an array to harden against CSPP
|
|
524
|
+
*
|
|
525
|
+
* @param array - The array to be cleaned.
|
|
526
|
+
* @returns The cleaned version of the array
|
|
527
|
+
*/
|
|
528
|
+
function cleanArray(array) {
|
|
529
|
+
for (let index = 0; index < array.length; index++) {
|
|
530
|
+
const isPropertyExist = objectHasOwnProperty(array, index);
|
|
531
|
+
if (!isPropertyExist) {
|
|
532
|
+
array[index] = null;
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
return array;
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* Shallow clone an object
|
|
539
|
+
*
|
|
540
|
+
* @param object - The object to be cloned.
|
|
541
|
+
* @returns A new object that copies the original.
|
|
542
|
+
*/
|
|
543
|
+
function clone(object) {
|
|
544
|
+
const newObject = create(null);
|
|
545
|
+
for (const [property, value] of entries(object)) {
|
|
546
|
+
const isPropertyExist = objectHasOwnProperty(object, property);
|
|
547
|
+
if (isPropertyExist) {
|
|
548
|
+
if (Array.isArray(value)) {
|
|
549
|
+
newObject[property] = cleanArray(value);
|
|
550
|
+
} else if (value && typeof value === 'object' && value.constructor === Object) {
|
|
551
|
+
newObject[property] = clone(value);
|
|
552
|
+
} else {
|
|
553
|
+
newObject[property] = value;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
return newObject;
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* This method automatically checks if the prop is function or getter and behaves accordingly.
|
|
561
|
+
*
|
|
562
|
+
* @param object - The object to look up the getter function in its prototype chain.
|
|
563
|
+
* @param prop - The property name for which to find the getter function.
|
|
564
|
+
* @returns The getter function found in the prototype chain or a fallback function.
|
|
565
|
+
*/
|
|
566
|
+
function lookupGetter(object, prop) {
|
|
567
|
+
while (object !== null) {
|
|
568
|
+
const desc = getOwnPropertyDescriptor(object, prop);
|
|
569
|
+
if (desc) {
|
|
570
|
+
if (desc.get) {
|
|
571
|
+
return unapply(desc.get);
|
|
572
|
+
}
|
|
573
|
+
if (typeof desc.value === 'function') {
|
|
574
|
+
return unapply(desc.value);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
object = getPrototypeOf(object);
|
|
578
|
+
}
|
|
579
|
+
function fallbackValue() {
|
|
580
|
+
return null;
|
|
581
|
+
}
|
|
582
|
+
return fallbackValue;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
const html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'search', 'section', 'select', 'shadow', 'slot', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);
|
|
586
|
+
const svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'enterkeyhint', 'exportparts', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'inputmode', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'part', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);
|
|
587
|
+
const svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);
|
|
588
|
+
// List of SVG elements that are disallowed by default.
|
|
589
|
+
// We still need to know them so that we can do namespace
|
|
590
|
+
// checks properly in case one wants to add them to
|
|
591
|
+
// allow-list.
|
|
592
|
+
const svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);
|
|
593
|
+
const mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']);
|
|
594
|
+
// Similarly to SVG, we want to know all MathML elements,
|
|
595
|
+
// even those that we disallow by default.
|
|
596
|
+
const mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);
|
|
597
|
+
const text = freeze(['#text']);
|
|
598
|
+
|
|
599
|
+
const html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns', 'slot']);
|
|
600
|
+
const svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);
|
|
601
|
+
const mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);
|
|
602
|
+
const xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);
|
|
603
|
+
|
|
604
|
+
// eslint-disable-next-line unicorn/better-regex
|
|
605
|
+
const MUSTACHE_EXPR = seal(/\{\{[\w\W]*|[\w\W]*\}\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode
|
|
606
|
+
const ERB_EXPR = seal(/<%[\w\W]*|[\w\W]*%>/gm);
|
|
607
|
+
const TMPLIT_EXPR = seal(/\$\{[\w\W]*/gm); // eslint-disable-line unicorn/better-regex
|
|
608
|
+
const DATA_ATTR = seal(/^data-[\-\w.\u00B7-\uFFFF]+$/); // eslint-disable-line no-useless-escape
|
|
609
|
+
const ARIA_ATTR = seal(/^aria-[\-\w]+$/); // eslint-disable-line no-useless-escape
|
|
610
|
+
const IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape
|
|
611
|
+
);
|
|
612
|
+
const IS_SCRIPT_OR_DATA = seal(/^(?:\w+script|data):/i);
|
|
613
|
+
const ATTR_WHITESPACE = seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g // eslint-disable-line no-control-regex
|
|
614
|
+
);
|
|
615
|
+
const DOCTYPE_NAME = seal(/^html$/i);
|
|
616
|
+
const CUSTOM_ELEMENT = seal(/^[a-z][.\w]*(-[.\w]+)+$/i);
|
|
617
|
+
|
|
618
|
+
var EXPRESSIONS = /*#__PURE__*/Object.freeze({
|
|
619
|
+
__proto__: null,
|
|
620
|
+
ARIA_ATTR: ARIA_ATTR,
|
|
621
|
+
ATTR_WHITESPACE: ATTR_WHITESPACE,
|
|
622
|
+
CUSTOM_ELEMENT: CUSTOM_ELEMENT,
|
|
623
|
+
DATA_ATTR: DATA_ATTR,
|
|
624
|
+
DOCTYPE_NAME: DOCTYPE_NAME,
|
|
625
|
+
ERB_EXPR: ERB_EXPR,
|
|
626
|
+
IS_ALLOWED_URI: IS_ALLOWED_URI,
|
|
627
|
+
IS_SCRIPT_OR_DATA: IS_SCRIPT_OR_DATA,
|
|
628
|
+
MUSTACHE_EXPR: MUSTACHE_EXPR,
|
|
629
|
+
TMPLIT_EXPR: TMPLIT_EXPR
|
|
630
|
+
});
|
|
631
|
+
|
|
632
|
+
/* eslint-disable @typescript-eslint/indent */
|
|
633
|
+
// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
|
|
634
|
+
const NODE_TYPE = {
|
|
635
|
+
element: 1,
|
|
636
|
+
text: 3,
|
|
637
|
+
// Deprecated
|
|
638
|
+
progressingInstruction: 7,
|
|
639
|
+
comment: 8,
|
|
640
|
+
document: 9};
|
|
641
|
+
const getGlobal = function getGlobal() {
|
|
642
|
+
return typeof window === 'undefined' ? null : window;
|
|
643
|
+
};
|
|
644
|
+
/**
|
|
645
|
+
* Creates a no-op policy for internal use only.
|
|
646
|
+
* Don't export this function outside this module!
|
|
647
|
+
* @param trustedTypes The policy factory.
|
|
648
|
+
* @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).
|
|
649
|
+
* @return The policy created (or null, if Trusted Types
|
|
650
|
+
* are not supported or creating the policy failed).
|
|
651
|
+
*/
|
|
652
|
+
const _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {
|
|
653
|
+
if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {
|
|
654
|
+
return null;
|
|
655
|
+
}
|
|
656
|
+
// Allow the callers to control the unique policy name
|
|
657
|
+
// by adding a data-tt-policy-suffix to the script element with the DOMPurify.
|
|
658
|
+
// Policy creation with duplicate names throws in Trusted Types.
|
|
659
|
+
let suffix = null;
|
|
660
|
+
const ATTR_NAME = 'data-tt-policy-suffix';
|
|
661
|
+
if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {
|
|
662
|
+
suffix = purifyHostElement.getAttribute(ATTR_NAME);
|
|
663
|
+
}
|
|
664
|
+
const policyName = 'dompurify' + (suffix ? '#' + suffix : '');
|
|
665
|
+
try {
|
|
666
|
+
return trustedTypes.createPolicy(policyName, {
|
|
667
|
+
createHTML(html) {
|
|
668
|
+
return html;
|
|
669
|
+
},
|
|
670
|
+
createScriptURL(scriptUrl) {
|
|
671
|
+
return scriptUrl;
|
|
672
|
+
}
|
|
673
|
+
});
|
|
674
|
+
} catch (_) {
|
|
675
|
+
// Policy creation failed (most likely another DOMPurify script has
|
|
676
|
+
// already run). Skip creating the policy, as this will only cause errors
|
|
677
|
+
// if TT are enforced.
|
|
678
|
+
console.warn('TrustedTypes policy ' + policyName + ' could not be created.');
|
|
679
|
+
return null;
|
|
680
|
+
}
|
|
681
|
+
};
|
|
682
|
+
const _createHooksMap = function _createHooksMap() {
|
|
683
|
+
return {
|
|
684
|
+
afterSanitizeAttributes: [],
|
|
685
|
+
afterSanitizeElements: [],
|
|
686
|
+
afterSanitizeShadowDOM: [],
|
|
687
|
+
beforeSanitizeAttributes: [],
|
|
688
|
+
beforeSanitizeElements: [],
|
|
689
|
+
beforeSanitizeShadowDOM: [],
|
|
690
|
+
uponSanitizeAttribute: [],
|
|
691
|
+
uponSanitizeElement: [],
|
|
692
|
+
uponSanitizeShadowNode: []
|
|
693
|
+
};
|
|
694
|
+
};
|
|
695
|
+
function createDOMPurify() {
|
|
696
|
+
let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();
|
|
697
|
+
const DOMPurify = root => createDOMPurify(root);
|
|
698
|
+
DOMPurify.version = '3.3.1';
|
|
699
|
+
DOMPurify.removed = [];
|
|
700
|
+
if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {
|
|
701
|
+
// Not running in a browser, provide a factory function
|
|
702
|
+
// so that you can pass your own Window
|
|
703
|
+
DOMPurify.isSupported = false;
|
|
704
|
+
return DOMPurify;
|
|
705
|
+
}
|
|
706
|
+
let {
|
|
707
|
+
document
|
|
708
|
+
} = window;
|
|
709
|
+
const originalDocument = document;
|
|
710
|
+
const currentScript = originalDocument.currentScript;
|
|
711
|
+
const {
|
|
712
|
+
DocumentFragment,
|
|
713
|
+
HTMLTemplateElement,
|
|
714
|
+
Node,
|
|
715
|
+
Element,
|
|
716
|
+
NodeFilter,
|
|
717
|
+
NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap,
|
|
718
|
+
HTMLFormElement,
|
|
719
|
+
DOMParser,
|
|
720
|
+
trustedTypes
|
|
721
|
+
} = window;
|
|
722
|
+
const ElementPrototype = Element.prototype;
|
|
723
|
+
const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');
|
|
724
|
+
const remove = lookupGetter(ElementPrototype, 'remove');
|
|
725
|
+
const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');
|
|
726
|
+
const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');
|
|
727
|
+
const getParentNode = lookupGetter(ElementPrototype, 'parentNode');
|
|
728
|
+
// As per issue #47, the web-components registry is inherited by a
|
|
729
|
+
// new document created via createHTMLDocument. As per the spec
|
|
730
|
+
// (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
|
|
731
|
+
// a new empty registry is used when creating a template contents owner
|
|
732
|
+
// document, so we use that as our parent document to ensure nothing
|
|
733
|
+
// is inherited.
|
|
734
|
+
if (typeof HTMLTemplateElement === 'function') {
|
|
735
|
+
const template = document.createElement('template');
|
|
736
|
+
if (template.content && template.content.ownerDocument) {
|
|
737
|
+
document = template.content.ownerDocument;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
let trustedTypesPolicy;
|
|
741
|
+
let emptyHTML = '';
|
|
742
|
+
const {
|
|
743
|
+
implementation,
|
|
744
|
+
createNodeIterator,
|
|
745
|
+
createDocumentFragment,
|
|
746
|
+
getElementsByTagName
|
|
747
|
+
} = document;
|
|
748
|
+
const {
|
|
749
|
+
importNode
|
|
750
|
+
} = originalDocument;
|
|
751
|
+
let hooks = _createHooksMap();
|
|
752
|
+
/**
|
|
753
|
+
* Expose whether this browser supports running the full DOMPurify.
|
|
754
|
+
*/
|
|
755
|
+
DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;
|
|
756
|
+
const {
|
|
757
|
+
MUSTACHE_EXPR,
|
|
758
|
+
ERB_EXPR,
|
|
759
|
+
TMPLIT_EXPR,
|
|
760
|
+
DATA_ATTR,
|
|
761
|
+
ARIA_ATTR,
|
|
762
|
+
IS_SCRIPT_OR_DATA,
|
|
763
|
+
ATTR_WHITESPACE,
|
|
764
|
+
CUSTOM_ELEMENT
|
|
765
|
+
} = EXPRESSIONS;
|
|
766
|
+
let {
|
|
767
|
+
IS_ALLOWED_URI: IS_ALLOWED_URI$1
|
|
768
|
+
} = EXPRESSIONS;
|
|
769
|
+
/**
|
|
770
|
+
* We consider the elements and attributes below to be safe. Ideally
|
|
771
|
+
* don't add any new ones but feel free to remove unwanted ones.
|
|
772
|
+
*/
|
|
773
|
+
/* allowed element names */
|
|
774
|
+
let ALLOWED_TAGS = null;
|
|
775
|
+
const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);
|
|
776
|
+
/* Allowed attribute names */
|
|
777
|
+
let ALLOWED_ATTR = null;
|
|
778
|
+
const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);
|
|
779
|
+
/*
|
|
780
|
+
* Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.
|
|
781
|
+
* @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)
|
|
782
|
+
* @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)
|
|
783
|
+
* @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.
|
|
784
|
+
*/
|
|
785
|
+
let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {
|
|
786
|
+
tagNameCheck: {
|
|
787
|
+
writable: true,
|
|
788
|
+
configurable: false,
|
|
789
|
+
enumerable: true,
|
|
790
|
+
value: null
|
|
791
|
+
},
|
|
792
|
+
attributeNameCheck: {
|
|
793
|
+
writable: true,
|
|
794
|
+
configurable: false,
|
|
795
|
+
enumerable: true,
|
|
796
|
+
value: null
|
|
797
|
+
},
|
|
798
|
+
allowCustomizedBuiltInElements: {
|
|
799
|
+
writable: true,
|
|
800
|
+
configurable: false,
|
|
801
|
+
enumerable: true,
|
|
802
|
+
value: false
|
|
803
|
+
}
|
|
804
|
+
}));
|
|
805
|
+
/* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
|
|
806
|
+
let FORBID_TAGS = null;
|
|
807
|
+
/* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
|
|
808
|
+
let FORBID_ATTR = null;
|
|
809
|
+
/* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */
|
|
810
|
+
const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {
|
|
811
|
+
tagCheck: {
|
|
812
|
+
writable: true,
|
|
813
|
+
configurable: false,
|
|
814
|
+
enumerable: true,
|
|
815
|
+
value: null
|
|
816
|
+
},
|
|
817
|
+
attributeCheck: {
|
|
818
|
+
writable: true,
|
|
819
|
+
configurable: false,
|
|
820
|
+
enumerable: true,
|
|
821
|
+
value: null
|
|
822
|
+
}
|
|
823
|
+
}));
|
|
824
|
+
/* Decide if ARIA attributes are okay */
|
|
825
|
+
let ALLOW_ARIA_ATTR = true;
|
|
826
|
+
/* Decide if custom data attributes are okay */
|
|
827
|
+
let ALLOW_DATA_ATTR = true;
|
|
828
|
+
/* Decide if unknown protocols are okay */
|
|
829
|
+
let ALLOW_UNKNOWN_PROTOCOLS = false;
|
|
830
|
+
/* Decide if self-closing tags in attributes are allowed.
|
|
831
|
+
* Usually removed due to a mXSS issue in jQuery 3.0 */
|
|
832
|
+
let ALLOW_SELF_CLOSE_IN_ATTR = true;
|
|
833
|
+
/* Output should be safe for common template engines.
|
|
834
|
+
* This means, DOMPurify removes data attributes, mustaches and ERB
|
|
835
|
+
*/
|
|
836
|
+
let SAFE_FOR_TEMPLATES = false;
|
|
837
|
+
/* Output should be safe even for XML used within HTML and alike.
|
|
838
|
+
* This means, DOMPurify removes comments when containing risky content.
|
|
839
|
+
*/
|
|
840
|
+
let SAFE_FOR_XML = true;
|
|
841
|
+
/* Decide if document with <html>... should be returned */
|
|
842
|
+
let WHOLE_DOCUMENT = false;
|
|
843
|
+
/* Track whether config is already set on this instance of DOMPurify. */
|
|
844
|
+
let SET_CONFIG = false;
|
|
845
|
+
/* Decide if all elements (e.g. style, script) must be children of
|
|
846
|
+
* document.body. By default, browsers might move them to document.head */
|
|
847
|
+
let FORCE_BODY = false;
|
|
848
|
+
/* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html
|
|
849
|
+
* string (or a TrustedHTML object if Trusted Types are supported).
|
|
850
|
+
* If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
|
|
851
|
+
*/
|
|
852
|
+
let RETURN_DOM = false;
|
|
853
|
+
/* Decide if a DOM `DocumentFragment` should be returned, instead of a html
|
|
854
|
+
* string (or a TrustedHTML object if Trusted Types are supported) */
|
|
855
|
+
let RETURN_DOM_FRAGMENT = false;
|
|
856
|
+
/* Try to return a Trusted Type object instead of a string, return a string in
|
|
857
|
+
* case Trusted Types are not supported */
|
|
858
|
+
let RETURN_TRUSTED_TYPE = false;
|
|
859
|
+
/* Output should be free from DOM clobbering attacks?
|
|
860
|
+
* This sanitizes markups named with colliding, clobberable built-in DOM APIs.
|
|
861
|
+
*/
|
|
862
|
+
let SANITIZE_DOM = true;
|
|
863
|
+
/* Achieve full DOM Clobbering protection by isolating the namespace of named
|
|
864
|
+
* properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.
|
|
865
|
+
*
|
|
866
|
+
* HTML/DOM spec rules that enable DOM Clobbering:
|
|
867
|
+
* - Named Access on Window (§7.3.3)
|
|
868
|
+
* - DOM Tree Accessors (§3.1.5)
|
|
869
|
+
* - Form Element Parent-Child Relations (§4.10.3)
|
|
870
|
+
* - Iframe srcdoc / Nested WindowProxies (§4.8.5)
|
|
871
|
+
* - HTMLCollection (§4.2.10.2)
|
|
872
|
+
*
|
|
873
|
+
* Namespace isolation is implemented by prefixing `id` and `name` attributes
|
|
874
|
+
* with a constant string, i.e., `user-content-`
|
|
875
|
+
*/
|
|
876
|
+
let SANITIZE_NAMED_PROPS = false;
|
|
877
|
+
const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';
|
|
878
|
+
/* Keep element content when removing element? */
|
|
879
|
+
let KEEP_CONTENT = true;
|
|
880
|
+
/* If a `Node` is passed to sanitize(), then performs sanitization in-place instead
|
|
881
|
+
* of importing it into a new Document and returning a sanitized copy */
|
|
882
|
+
let IN_PLACE = false;
|
|
883
|
+
/* Allow usage of profiles like html, svg and mathMl */
|
|
884
|
+
let USE_PROFILES = {};
|
|
885
|
+
/* Tags to ignore content of when KEEP_CONTENT is true */
|
|
886
|
+
let FORBID_CONTENTS = null;
|
|
887
|
+
const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);
|
|
888
|
+
/* Tags that are safe for data: URIs */
|
|
889
|
+
let DATA_URI_TAGS = null;
|
|
890
|
+
const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);
|
|
891
|
+
/* Attributes safe for values like "javascript:" */
|
|
892
|
+
let URI_SAFE_ATTRIBUTES = null;
|
|
893
|
+
const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);
|
|
894
|
+
const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
|
|
895
|
+
const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
|
|
896
|
+
const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
|
|
897
|
+
/* Document namespace */
|
|
898
|
+
let NAMESPACE = HTML_NAMESPACE;
|
|
899
|
+
let IS_EMPTY_INPUT = false;
|
|
900
|
+
/* Allowed XHTML+XML namespaces */
|
|
901
|
+
let ALLOWED_NAMESPACES = null;
|
|
902
|
+
const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);
|
|
903
|
+
let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);
|
|
904
|
+
let HTML_INTEGRATION_POINTS = addToSet({}, ['annotation-xml']);
|
|
905
|
+
// Certain elements are allowed in both SVG and HTML
|
|
906
|
+
// namespace. We need to specify them explicitly
|
|
907
|
+
// so that they don't get erroneously deleted from
|
|
908
|
+
// HTML namespace.
|
|
909
|
+
const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);
|
|
910
|
+
/* Parsing of strict XHTML documents */
|
|
911
|
+
let PARSER_MEDIA_TYPE = null;
|
|
912
|
+
const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];
|
|
913
|
+
const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';
|
|
914
|
+
let transformCaseFunc = null;
|
|
915
|
+
/* Keep a reference to config to pass to hooks */
|
|
916
|
+
let CONFIG = null;
|
|
917
|
+
/* Ideally, do not touch anything below this line */
|
|
918
|
+
/* ______________________________________________ */
|
|
919
|
+
const formElement = document.createElement('form');
|
|
920
|
+
const isRegexOrFunction = function isRegexOrFunction(testValue) {
|
|
921
|
+
return testValue instanceof RegExp || testValue instanceof Function;
|
|
922
|
+
};
|
|
923
|
+
/**
|
|
924
|
+
* _parseConfig
|
|
925
|
+
*
|
|
926
|
+
* @param cfg optional config literal
|
|
927
|
+
*/
|
|
928
|
+
// eslint-disable-next-line complexity
|
|
929
|
+
const _parseConfig = function _parseConfig() {
|
|
930
|
+
let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
|
931
|
+
if (CONFIG && CONFIG === cfg) {
|
|
932
|
+
return;
|
|
933
|
+
}
|
|
934
|
+
/* Shield configuration object from tampering */
|
|
935
|
+
if (!cfg || typeof cfg !== 'object') {
|
|
936
|
+
cfg = {};
|
|
937
|
+
}
|
|
938
|
+
/* Shield configuration object from prototype pollution */
|
|
939
|
+
cfg = clone(cfg);
|
|
940
|
+
PARSER_MEDIA_TYPE =
|
|
941
|
+
// eslint-disable-next-line unicorn/prefer-includes
|
|
942
|
+
SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;
|
|
943
|
+
// HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.
|
|
944
|
+
transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;
|
|
945
|
+
/* Set configuration parameters */
|
|
946
|
+
ALLOWED_TAGS = objectHasOwnProperty(cfg, 'ALLOWED_TAGS') ? addToSet({}, cfg.ALLOWED_TAGS, transformCaseFunc) : DEFAULT_ALLOWED_TAGS;
|
|
947
|
+
ALLOWED_ATTR = objectHasOwnProperty(cfg, 'ALLOWED_ATTR') ? addToSet({}, cfg.ALLOWED_ATTR, transformCaseFunc) : DEFAULT_ALLOWED_ATTR;
|
|
948
|
+
ALLOWED_NAMESPACES = objectHasOwnProperty(cfg, 'ALLOWED_NAMESPACES') ? addToSet({}, cfg.ALLOWED_NAMESPACES, stringToString) : DEFAULT_ALLOWED_NAMESPACES;
|
|
949
|
+
URI_SAFE_ATTRIBUTES = objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR, transformCaseFunc) : DEFAULT_URI_SAFE_ATTRIBUTES;
|
|
950
|
+
DATA_URI_TAGS = objectHasOwnProperty(cfg, 'ADD_DATA_URI_TAGS') ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS, transformCaseFunc) : DEFAULT_DATA_URI_TAGS;
|
|
951
|
+
FORBID_CONTENTS = objectHasOwnProperty(cfg, 'FORBID_CONTENTS') ? addToSet({}, cfg.FORBID_CONTENTS, transformCaseFunc) : DEFAULT_FORBID_CONTENTS;
|
|
952
|
+
FORBID_TAGS = objectHasOwnProperty(cfg, 'FORBID_TAGS') ? addToSet({}, cfg.FORBID_TAGS, transformCaseFunc) : clone({});
|
|
953
|
+
FORBID_ATTR = objectHasOwnProperty(cfg, 'FORBID_ATTR') ? addToSet({}, cfg.FORBID_ATTR, transformCaseFunc) : clone({});
|
|
954
|
+
USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES : false;
|
|
955
|
+
ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
|
|
956
|
+
ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
|
|
957
|
+
ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
|
|
958
|
+
ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true
|
|
959
|
+
SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
|
|
960
|
+
SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true
|
|
961
|
+
WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
|
|
962
|
+
RETURN_DOM = cfg.RETURN_DOM || false; // Default false
|
|
963
|
+
RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
|
|
964
|
+
RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false
|
|
965
|
+
FORCE_BODY = cfg.FORCE_BODY || false; // Default false
|
|
966
|
+
SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
|
|
967
|
+
SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false
|
|
968
|
+
KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
|
|
969
|
+
IN_PLACE = cfg.IN_PLACE || false; // Default false
|
|
970
|
+
IS_ALLOWED_URI$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI;
|
|
971
|
+
NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;
|
|
972
|
+
MATHML_TEXT_INTEGRATION_POINTS = cfg.MATHML_TEXT_INTEGRATION_POINTS || MATHML_TEXT_INTEGRATION_POINTS;
|
|
973
|
+
HTML_INTEGRATION_POINTS = cfg.HTML_INTEGRATION_POINTS || HTML_INTEGRATION_POINTS;
|
|
974
|
+
CUSTOM_ELEMENT_HANDLING = cfg.CUSTOM_ELEMENT_HANDLING || {};
|
|
975
|
+
if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck)) {
|
|
976
|
+
CUSTOM_ELEMENT_HANDLING.tagNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.tagNameCheck;
|
|
977
|
+
}
|
|
978
|
+
if (cfg.CUSTOM_ELEMENT_HANDLING && isRegexOrFunction(cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)) {
|
|
979
|
+
CUSTOM_ELEMENT_HANDLING.attributeNameCheck = cfg.CUSTOM_ELEMENT_HANDLING.attributeNameCheck;
|
|
980
|
+
}
|
|
981
|
+
if (cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements === 'boolean') {
|
|
982
|
+
CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = cfg.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements;
|
|
983
|
+
}
|
|
984
|
+
if (SAFE_FOR_TEMPLATES) {
|
|
985
|
+
ALLOW_DATA_ATTR = false;
|
|
986
|
+
}
|
|
987
|
+
if (RETURN_DOM_FRAGMENT) {
|
|
988
|
+
RETURN_DOM = true;
|
|
989
|
+
}
|
|
990
|
+
/* Parse profile info */
|
|
991
|
+
if (USE_PROFILES) {
|
|
992
|
+
ALLOWED_TAGS = addToSet({}, text);
|
|
993
|
+
ALLOWED_ATTR = [];
|
|
994
|
+
if (USE_PROFILES.html === true) {
|
|
995
|
+
addToSet(ALLOWED_TAGS, html$1);
|
|
996
|
+
addToSet(ALLOWED_ATTR, html);
|
|
997
|
+
}
|
|
998
|
+
if (USE_PROFILES.svg === true) {
|
|
999
|
+
addToSet(ALLOWED_TAGS, svg$1);
|
|
1000
|
+
addToSet(ALLOWED_ATTR, svg);
|
|
1001
|
+
addToSet(ALLOWED_ATTR, xml);
|
|
1002
|
+
}
|
|
1003
|
+
if (USE_PROFILES.svgFilters === true) {
|
|
1004
|
+
addToSet(ALLOWED_TAGS, svgFilters);
|
|
1005
|
+
addToSet(ALLOWED_ATTR, svg);
|
|
1006
|
+
addToSet(ALLOWED_ATTR, xml);
|
|
1007
|
+
}
|
|
1008
|
+
if (USE_PROFILES.mathMl === true) {
|
|
1009
|
+
addToSet(ALLOWED_TAGS, mathMl$1);
|
|
1010
|
+
addToSet(ALLOWED_ATTR, mathMl);
|
|
1011
|
+
addToSet(ALLOWED_ATTR, xml);
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
/* Merge configuration parameters */
|
|
1015
|
+
if (cfg.ADD_TAGS) {
|
|
1016
|
+
if (typeof cfg.ADD_TAGS === 'function') {
|
|
1017
|
+
EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;
|
|
1018
|
+
} else {
|
|
1019
|
+
if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
|
|
1020
|
+
ALLOWED_TAGS = clone(ALLOWED_TAGS);
|
|
1021
|
+
}
|
|
1022
|
+
addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
if (cfg.ADD_ATTR) {
|
|
1026
|
+
if (typeof cfg.ADD_ATTR === 'function') {
|
|
1027
|
+
EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;
|
|
1028
|
+
} else {
|
|
1029
|
+
if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
|
|
1030
|
+
ALLOWED_ATTR = clone(ALLOWED_ATTR);
|
|
1031
|
+
}
|
|
1032
|
+
addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
if (cfg.ADD_URI_SAFE_ATTR) {
|
|
1036
|
+
addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);
|
|
1037
|
+
}
|
|
1038
|
+
if (cfg.FORBID_CONTENTS) {
|
|
1039
|
+
if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
|
|
1040
|
+
FORBID_CONTENTS = clone(FORBID_CONTENTS);
|
|
1041
|
+
}
|
|
1042
|
+
addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);
|
|
1043
|
+
}
|
|
1044
|
+
if (cfg.ADD_FORBID_CONTENTS) {
|
|
1045
|
+
if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {
|
|
1046
|
+
FORBID_CONTENTS = clone(FORBID_CONTENTS);
|
|
1047
|
+
}
|
|
1048
|
+
addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);
|
|
1049
|
+
}
|
|
1050
|
+
/* Add #text in case KEEP_CONTENT is set to true */
|
|
1051
|
+
if (KEEP_CONTENT) {
|
|
1052
|
+
ALLOWED_TAGS['#text'] = true;
|
|
1053
|
+
}
|
|
1054
|
+
/* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */
|
|
1055
|
+
if (WHOLE_DOCUMENT) {
|
|
1056
|
+
addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);
|
|
1057
|
+
}
|
|
1058
|
+
/* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */
|
|
1059
|
+
if (ALLOWED_TAGS.table) {
|
|
1060
|
+
addToSet(ALLOWED_TAGS, ['tbody']);
|
|
1061
|
+
delete FORBID_TAGS.tbody;
|
|
1062
|
+
}
|
|
1063
|
+
if (cfg.TRUSTED_TYPES_POLICY) {
|
|
1064
|
+
if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {
|
|
1065
|
+
throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');
|
|
1066
|
+
}
|
|
1067
|
+
if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {
|
|
1068
|
+
throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');
|
|
1069
|
+
}
|
|
1070
|
+
// Overwrite existing TrustedTypes policy.
|
|
1071
|
+
trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;
|
|
1072
|
+
// Sign local variables required by `sanitize`.
|
|
1073
|
+
emptyHTML = trustedTypesPolicy.createHTML('');
|
|
1074
|
+
} else {
|
|
1075
|
+
// Uninitialized policy, attempt to initialize the internal dompurify policy.
|
|
1076
|
+
if (trustedTypesPolicy === undefined) {
|
|
1077
|
+
trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);
|
|
1078
|
+
}
|
|
1079
|
+
// If creating the internal policy succeeded sign internal variables.
|
|
1080
|
+
if (trustedTypesPolicy !== null && typeof emptyHTML === 'string') {
|
|
1081
|
+
emptyHTML = trustedTypesPolicy.createHTML('');
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
// Prevent further manipulation of configuration.
|
|
1085
|
+
// Not available in IE8, Safari 5, etc.
|
|
1086
|
+
if (freeze) {
|
|
1087
|
+
freeze(cfg);
|
|
1088
|
+
}
|
|
1089
|
+
CONFIG = cfg;
|
|
1090
|
+
};
|
|
1091
|
+
/* Keep track of all possible SVG and MathML tags
|
|
1092
|
+
* so that we can perform the namespace checks
|
|
1093
|
+
* correctly. */
|
|
1094
|
+
const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);
|
|
1095
|
+
const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);
|
|
1096
|
+
/**
|
|
1097
|
+
* @param element a DOM element whose namespace is being checked
|
|
1098
|
+
* @returns Return false if the element has a
|
|
1099
|
+
* namespace that a spec-compliant parser would never
|
|
1100
|
+
* return. Return true otherwise.
|
|
1101
|
+
*/
|
|
1102
|
+
const _checkValidNamespace = function _checkValidNamespace(element) {
|
|
1103
|
+
let parent = getParentNode(element);
|
|
1104
|
+
// In JSDOM, if we're inside shadow DOM, then parentNode
|
|
1105
|
+
// can be null. We just simulate parent in this case.
|
|
1106
|
+
if (!parent || !parent.tagName) {
|
|
1107
|
+
parent = {
|
|
1108
|
+
namespaceURI: NAMESPACE,
|
|
1109
|
+
tagName: 'template'
|
|
1110
|
+
};
|
|
1111
|
+
}
|
|
1112
|
+
const tagName = stringToLowerCase(element.tagName);
|
|
1113
|
+
const parentTagName = stringToLowerCase(parent.tagName);
|
|
1114
|
+
if (!ALLOWED_NAMESPACES[element.namespaceURI]) {
|
|
1115
|
+
return false;
|
|
1116
|
+
}
|
|
1117
|
+
if (element.namespaceURI === SVG_NAMESPACE) {
|
|
1118
|
+
// The only way to switch from HTML namespace to SVG
|
|
1119
|
+
// is via <svg>. If it happens via any other tag, then
|
|
1120
|
+
// it should be killed.
|
|
1121
|
+
if (parent.namespaceURI === HTML_NAMESPACE) {
|
|
1122
|
+
return tagName === 'svg';
|
|
1123
|
+
}
|
|
1124
|
+
// The only way to switch from MathML to SVG is via`
|
|
1125
|
+
// svg if parent is either <annotation-xml> or MathML
|
|
1126
|
+
// text integration points.
|
|
1127
|
+
if (parent.namespaceURI === MATHML_NAMESPACE) {
|
|
1128
|
+
return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);
|
|
1129
|
+
}
|
|
1130
|
+
// We only allow elements that are defined in SVG
|
|
1131
|
+
// spec. All others are disallowed in SVG namespace.
|
|
1132
|
+
return Boolean(ALL_SVG_TAGS[tagName]);
|
|
1133
|
+
}
|
|
1134
|
+
if (element.namespaceURI === MATHML_NAMESPACE) {
|
|
1135
|
+
// The only way to switch from HTML namespace to MathML
|
|
1136
|
+
// is via <math>. If it happens via any other tag, then
|
|
1137
|
+
// it should be killed.
|
|
1138
|
+
if (parent.namespaceURI === HTML_NAMESPACE) {
|
|
1139
|
+
return tagName === 'math';
|
|
1140
|
+
}
|
|
1141
|
+
// The only way to switch from SVG to MathML is via
|
|
1142
|
+
// <math> and HTML integration points
|
|
1143
|
+
if (parent.namespaceURI === SVG_NAMESPACE) {
|
|
1144
|
+
return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];
|
|
1145
|
+
}
|
|
1146
|
+
// We only allow elements that are defined in MathML
|
|
1147
|
+
// spec. All others are disallowed in MathML namespace.
|
|
1148
|
+
return Boolean(ALL_MATHML_TAGS[tagName]);
|
|
1149
|
+
}
|
|
1150
|
+
if (element.namespaceURI === HTML_NAMESPACE) {
|
|
1151
|
+
// The only way to switch from SVG to HTML is via
|
|
1152
|
+
// HTML integration points, and from MathML to HTML
|
|
1153
|
+
// is via MathML text integration points
|
|
1154
|
+
if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {
|
|
1155
|
+
return false;
|
|
1156
|
+
}
|
|
1157
|
+
if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {
|
|
1158
|
+
return false;
|
|
1159
|
+
}
|
|
1160
|
+
// We disallow tags that are specific for MathML
|
|
1161
|
+
// or SVG and should never appear in HTML namespace
|
|
1162
|
+
return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);
|
|
1163
|
+
}
|
|
1164
|
+
// For XHTML and XML documents that support custom namespaces
|
|
1165
|
+
if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {
|
|
1166
|
+
return true;
|
|
1167
|
+
}
|
|
1168
|
+
// The code should never reach this place (this means
|
|
1169
|
+
// that the element somehow got namespace that is not
|
|
1170
|
+
// HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).
|
|
1171
|
+
// Return false just in case.
|
|
1172
|
+
return false;
|
|
1173
|
+
};
|
|
1174
|
+
/**
|
|
1175
|
+
* _forceRemove
|
|
1176
|
+
*
|
|
1177
|
+
* @param node a DOM node
|
|
1178
|
+
*/
|
|
1179
|
+
const _forceRemove = function _forceRemove(node) {
|
|
1180
|
+
arrayPush(DOMPurify.removed, {
|
|
1181
|
+
element: node
|
|
1182
|
+
});
|
|
1183
|
+
try {
|
|
1184
|
+
// eslint-disable-next-line unicorn/prefer-dom-node-remove
|
|
1185
|
+
getParentNode(node).removeChild(node);
|
|
1186
|
+
} catch (_) {
|
|
1187
|
+
remove(node);
|
|
1188
|
+
}
|
|
1189
|
+
};
|
|
1190
|
+
/**
|
|
1191
|
+
* _removeAttribute
|
|
1192
|
+
*
|
|
1193
|
+
* @param name an Attribute name
|
|
1194
|
+
* @param element a DOM node
|
|
1195
|
+
*/
|
|
1196
|
+
const _removeAttribute = function _removeAttribute(name, element) {
|
|
1197
|
+
try {
|
|
1198
|
+
arrayPush(DOMPurify.removed, {
|
|
1199
|
+
attribute: element.getAttributeNode(name),
|
|
1200
|
+
from: element
|
|
1201
|
+
});
|
|
1202
|
+
} catch (_) {
|
|
1203
|
+
arrayPush(DOMPurify.removed, {
|
|
1204
|
+
attribute: null,
|
|
1205
|
+
from: element
|
|
1206
|
+
});
|
|
1207
|
+
}
|
|
1208
|
+
element.removeAttribute(name);
|
|
1209
|
+
// We void attribute values for unremovable "is" attributes
|
|
1210
|
+
if (name === 'is') {
|
|
1211
|
+
if (RETURN_DOM || RETURN_DOM_FRAGMENT) {
|
|
1212
|
+
try {
|
|
1213
|
+
_forceRemove(element);
|
|
1214
|
+
} catch (_) {}
|
|
1215
|
+
} else {
|
|
1216
|
+
try {
|
|
1217
|
+
element.setAttribute(name, '');
|
|
1218
|
+
} catch (_) {}
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
};
|
|
1222
|
+
/**
|
|
1223
|
+
* _initDocument
|
|
1224
|
+
*
|
|
1225
|
+
* @param dirty - a string of dirty markup
|
|
1226
|
+
* @return a DOM, filled with the dirty markup
|
|
1227
|
+
*/
|
|
1228
|
+
const _initDocument = function _initDocument(dirty) {
|
|
1229
|
+
/* Create a HTML document */
|
|
1230
|
+
let doc = null;
|
|
1231
|
+
let leadingWhitespace = null;
|
|
1232
|
+
if (FORCE_BODY) {
|
|
1233
|
+
dirty = '<remove></remove>' + dirty;
|
|
1234
|
+
} else {
|
|
1235
|
+
/* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */
|
|
1236
|
+
const matches = stringMatch(dirty, /^[\r\n\t ]+/);
|
|
1237
|
+
leadingWhitespace = matches && matches[0];
|
|
1238
|
+
}
|
|
1239
|
+
if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {
|
|
1240
|
+
// Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)
|
|
1241
|
+
dirty = '<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>' + dirty + '</body></html>';
|
|
1242
|
+
}
|
|
1243
|
+
const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
|
|
1244
|
+
/*
|
|
1245
|
+
* Use the DOMParser API by default, fallback later if needs be
|
|
1246
|
+
* DOMParser not work for svg when has multiple root element.
|
|
1247
|
+
*/
|
|
1248
|
+
if (NAMESPACE === HTML_NAMESPACE) {
|
|
1249
|
+
try {
|
|
1250
|
+
doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);
|
|
1251
|
+
} catch (_) {}
|
|
1252
|
+
}
|
|
1253
|
+
/* Use createHTMLDocument in case DOMParser is not available */
|
|
1254
|
+
if (!doc || !doc.documentElement) {
|
|
1255
|
+
doc = implementation.createDocument(NAMESPACE, 'template', null);
|
|
1256
|
+
try {
|
|
1257
|
+
doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;
|
|
1258
|
+
} catch (_) {
|
|
1259
|
+
// Syntax error if dirtyPayload is invalid xml
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
const body = doc.body || doc.documentElement;
|
|
1263
|
+
if (dirty && leadingWhitespace) {
|
|
1264
|
+
body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);
|
|
1265
|
+
}
|
|
1266
|
+
/* Work on whole document or just its body */
|
|
1267
|
+
if (NAMESPACE === HTML_NAMESPACE) {
|
|
1268
|
+
return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];
|
|
1269
|
+
}
|
|
1270
|
+
return WHOLE_DOCUMENT ? doc.documentElement : body;
|
|
1271
|
+
};
|
|
1272
|
+
/**
|
|
1273
|
+
* Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.
|
|
1274
|
+
*
|
|
1275
|
+
* @param root The root element or node to start traversing on.
|
|
1276
|
+
* @return The created NodeIterator
|
|
1277
|
+
*/
|
|
1278
|
+
const _createNodeIterator = function _createNodeIterator(root) {
|
|
1279
|
+
return createNodeIterator.call(root.ownerDocument || root, root,
|
|
1280
|
+
// eslint-disable-next-line no-bitwise
|
|
1281
|
+
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
|
|
1282
|
+
};
|
|
1283
|
+
/**
|
|
1284
|
+
* _isClobbered
|
|
1285
|
+
*
|
|
1286
|
+
* @param element element to check for clobbering attacks
|
|
1287
|
+
* @return true if clobbered, false if safe
|
|
1288
|
+
*/
|
|
1289
|
+
const _isClobbered = function _isClobbered(element) {
|
|
1290
|
+
return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function');
|
|
1291
|
+
};
|
|
1292
|
+
/**
|
|
1293
|
+
* Checks whether the given object is a DOM node.
|
|
1294
|
+
*
|
|
1295
|
+
* @param value object to check whether it's a DOM node
|
|
1296
|
+
* @return true is object is a DOM node
|
|
1297
|
+
*/
|
|
1298
|
+
const _isNode = function _isNode(value) {
|
|
1299
|
+
return typeof Node === 'function' && value instanceof Node;
|
|
1300
|
+
};
|
|
1301
|
+
function _executeHooks(hooks, currentNode, data) {
|
|
1302
|
+
arrayForEach(hooks, hook => {
|
|
1303
|
+
hook.call(DOMPurify, currentNode, data, CONFIG);
|
|
1304
|
+
});
|
|
1305
|
+
}
|
|
1306
|
+
/**
|
|
1307
|
+
* _sanitizeElements
|
|
1308
|
+
*
|
|
1309
|
+
* @protect nodeName
|
|
1310
|
+
* @protect textContent
|
|
1311
|
+
* @protect removeChild
|
|
1312
|
+
* @param currentNode to check for permission to exist
|
|
1313
|
+
* @return true if node was killed, false if left alive
|
|
1314
|
+
*/
|
|
1315
|
+
const _sanitizeElements = function _sanitizeElements(currentNode) {
|
|
1316
|
+
let content = null;
|
|
1317
|
+
/* Execute a hook if present */
|
|
1318
|
+
_executeHooks(hooks.beforeSanitizeElements, currentNode, null);
|
|
1319
|
+
/* Check if element is clobbered or can clobber */
|
|
1320
|
+
if (_isClobbered(currentNode)) {
|
|
1321
|
+
_forceRemove(currentNode);
|
|
1322
|
+
return true;
|
|
1323
|
+
}
|
|
1324
|
+
/* Now let's check the element's type and name */
|
|
1325
|
+
const tagName = transformCaseFunc(currentNode.nodeName);
|
|
1326
|
+
/* Execute a hook if present */
|
|
1327
|
+
_executeHooks(hooks.uponSanitizeElement, currentNode, {
|
|
1328
|
+
tagName,
|
|
1329
|
+
allowedTags: ALLOWED_TAGS
|
|
1330
|
+
});
|
|
1331
|
+
/* Detect mXSS attempts abusing namespace confusion */
|
|
1332
|
+
if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(/<[/\w!]/g, currentNode.innerHTML) && regExpTest(/<[/\w!]/g, currentNode.textContent)) {
|
|
1333
|
+
_forceRemove(currentNode);
|
|
1334
|
+
return true;
|
|
1335
|
+
}
|
|
1336
|
+
/* Remove any occurrence of processing instructions */
|
|
1337
|
+
if (currentNode.nodeType === NODE_TYPE.progressingInstruction) {
|
|
1338
|
+
_forceRemove(currentNode);
|
|
1339
|
+
return true;
|
|
1340
|
+
}
|
|
1341
|
+
/* Remove any kind of possibly harmful comments */
|
|
1342
|
+
if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(/<[/\w]/g, currentNode.data)) {
|
|
1343
|
+
_forceRemove(currentNode);
|
|
1344
|
+
return true;
|
|
1345
|
+
}
|
|
1346
|
+
/* Remove element if anything forbids its presence */
|
|
1347
|
+
if (!(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName])) {
|
|
1348
|
+
/* Check if we have a custom element to handle */
|
|
1349
|
+
if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
|
|
1350
|
+
if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
|
|
1351
|
+
return false;
|
|
1352
|
+
}
|
|
1353
|
+
if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
|
|
1354
|
+
return false;
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
/* Keep content except for bad-listed elements */
|
|
1358
|
+
if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
|
|
1359
|
+
const parentNode = getParentNode(currentNode) || currentNode.parentNode;
|
|
1360
|
+
const childNodes = getChildNodes(currentNode) || currentNode.childNodes;
|
|
1361
|
+
if (childNodes && parentNode) {
|
|
1362
|
+
const childCount = childNodes.length;
|
|
1363
|
+
for (let i = childCount - 1; i >= 0; --i) {
|
|
1364
|
+
const childClone = cloneNode(childNodes[i], true);
|
|
1365
|
+
childClone.__removalCount = (currentNode.__removalCount || 0) + 1;
|
|
1366
|
+
parentNode.insertBefore(childClone, getNextSibling(currentNode));
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
_forceRemove(currentNode);
|
|
1371
|
+
return true;
|
|
1372
|
+
}
|
|
1373
|
+
/* Check whether element has a valid namespace */
|
|
1374
|
+
if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {
|
|
1375
|
+
_forceRemove(currentNode);
|
|
1376
|
+
return true;
|
|
1377
|
+
}
|
|
1378
|
+
/* Make sure that older browsers don't get fallback-tag mXSS */
|
|
1379
|
+
if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(/<\/no(script|embed|frames)/i, currentNode.innerHTML)) {
|
|
1380
|
+
_forceRemove(currentNode);
|
|
1381
|
+
return true;
|
|
1382
|
+
}
|
|
1383
|
+
/* Sanitize element content to be template-safe */
|
|
1384
|
+
if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {
|
|
1385
|
+
/* Get the element's text content */
|
|
1386
|
+
content = currentNode.textContent;
|
|
1387
|
+
arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
|
|
1388
|
+
content = stringReplace(content, expr, ' ');
|
|
1389
|
+
});
|
|
1390
|
+
if (currentNode.textContent !== content) {
|
|
1391
|
+
arrayPush(DOMPurify.removed, {
|
|
1392
|
+
element: currentNode.cloneNode()
|
|
1393
|
+
});
|
|
1394
|
+
currentNode.textContent = content;
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
/* Execute a hook if present */
|
|
1398
|
+
_executeHooks(hooks.afterSanitizeElements, currentNode, null);
|
|
1399
|
+
return false;
|
|
1400
|
+
};
|
|
1401
|
+
/**
|
|
1402
|
+
* _isValidAttribute
|
|
1403
|
+
*
|
|
1404
|
+
* @param lcTag Lowercase tag name of containing element.
|
|
1405
|
+
* @param lcName Lowercase attribute name.
|
|
1406
|
+
* @param value Attribute value.
|
|
1407
|
+
* @return Returns true if `value` is valid, otherwise false.
|
|
1408
|
+
*/
|
|
1409
|
+
// eslint-disable-next-line complexity
|
|
1410
|
+
const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {
|
|
1411
|
+
/* Make sure attribute cannot clobber */
|
|
1412
|
+
if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {
|
|
1413
|
+
return false;
|
|
1414
|
+
}
|
|
1415
|
+
/* Allow valid data-* attributes: At least one character after "-"
|
|
1416
|
+
(https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
|
|
1417
|
+
XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
|
|
1418
|
+
We don't need to check the value; it's always URI safe. */
|
|
1419
|
+
if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR, lcName)) ; else if (EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
|
|
1420
|
+
if (
|
|
1421
|
+
// First condition does a very basic check if a) it's basically a valid custom element tagname AND
|
|
1422
|
+
// b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
|
|
1423
|
+
// and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck
|
|
1424
|
+
_isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)) ||
|
|
1425
|
+
// Alternative, second condition checks if it's an `is`-attribute, AND
|
|
1426
|
+
// the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck
|
|
1427
|
+
lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {
|
|
1428
|
+
return false;
|
|
1429
|
+
}
|
|
1430
|
+
/* Check value is safe. First, is attr inert? If so, is safe */
|
|
1431
|
+
} else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA, stringReplace(value, ATTR_WHITESPACE, ''))) ; else if (value) {
|
|
1432
|
+
return false;
|
|
1433
|
+
} else ;
|
|
1434
|
+
return true;
|
|
1435
|
+
};
|
|
1436
|
+
/**
|
|
1437
|
+
* _isBasicCustomElement
|
|
1438
|
+
* checks if at least one dash is included in tagName, and it's not the first char
|
|
1439
|
+
* for more sophisticated checking see https://github.com/sindresorhus/validate-element-name
|
|
1440
|
+
*
|
|
1441
|
+
* @param tagName name of the tag of the node to sanitize
|
|
1442
|
+
* @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.
|
|
1443
|
+
*/
|
|
1444
|
+
const _isBasicCustomElement = function _isBasicCustomElement(tagName) {
|
|
1445
|
+
return tagName !== 'annotation-xml' && stringMatch(tagName, CUSTOM_ELEMENT);
|
|
1446
|
+
};
|
|
1447
|
+
/**
|
|
1448
|
+
* _sanitizeAttributes
|
|
1449
|
+
*
|
|
1450
|
+
* @protect attributes
|
|
1451
|
+
* @protect nodeName
|
|
1452
|
+
* @protect removeAttribute
|
|
1453
|
+
* @protect setAttribute
|
|
1454
|
+
*
|
|
1455
|
+
* @param currentNode to sanitize
|
|
1456
|
+
*/
|
|
1457
|
+
const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {
|
|
1458
|
+
/* Execute a hook if present */
|
|
1459
|
+
_executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);
|
|
1460
|
+
const {
|
|
1461
|
+
attributes
|
|
1462
|
+
} = currentNode;
|
|
1463
|
+
/* Check if we have attributes; if not we might have a text node */
|
|
1464
|
+
if (!attributes || _isClobbered(currentNode)) {
|
|
1465
|
+
return;
|
|
1466
|
+
}
|
|
1467
|
+
const hookEvent = {
|
|
1468
|
+
attrName: '',
|
|
1469
|
+
attrValue: '',
|
|
1470
|
+
keepAttr: true,
|
|
1471
|
+
allowedAttributes: ALLOWED_ATTR,
|
|
1472
|
+
forceKeepAttr: undefined
|
|
1473
|
+
};
|
|
1474
|
+
let l = attributes.length;
|
|
1475
|
+
/* Go backwards over all attributes; safely remove bad ones */
|
|
1476
|
+
while (l--) {
|
|
1477
|
+
const attr = attributes[l];
|
|
1478
|
+
const {
|
|
1479
|
+
name,
|
|
1480
|
+
namespaceURI,
|
|
1481
|
+
value: attrValue
|
|
1482
|
+
} = attr;
|
|
1483
|
+
const lcName = transformCaseFunc(name);
|
|
1484
|
+
const initValue = attrValue;
|
|
1485
|
+
let value = name === 'value' ? initValue : stringTrim(initValue);
|
|
1486
|
+
/* Execute a hook if present */
|
|
1487
|
+
hookEvent.attrName = lcName;
|
|
1488
|
+
hookEvent.attrValue = value;
|
|
1489
|
+
hookEvent.keepAttr = true;
|
|
1490
|
+
hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set
|
|
1491
|
+
_executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);
|
|
1492
|
+
value = hookEvent.attrValue;
|
|
1493
|
+
/* Full DOM Clobbering protection via namespace isolation,
|
|
1494
|
+
* Prefix id and name attributes with `user-content-`
|
|
1495
|
+
*/
|
|
1496
|
+
if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name')) {
|
|
1497
|
+
// Remove the attribute with this value
|
|
1498
|
+
_removeAttribute(name, currentNode);
|
|
1499
|
+
// Prefix the value and later re-create the attribute with the sanitized value
|
|
1500
|
+
value = SANITIZE_NAMED_PROPS_PREFIX + value;
|
|
1501
|
+
}
|
|
1502
|
+
/* Work around a security issue with comments inside attributes */
|
|
1503
|
+
if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\/(style|title|textarea)/i, value)) {
|
|
1504
|
+
_removeAttribute(name, currentNode);
|
|
1505
|
+
continue;
|
|
1506
|
+
}
|
|
1507
|
+
/* Make sure we cannot easily use animated hrefs, even if animations are allowed */
|
|
1508
|
+
if (lcName === 'attributename' && stringMatch(value, 'href')) {
|
|
1509
|
+
_removeAttribute(name, currentNode);
|
|
1510
|
+
continue;
|
|
1511
|
+
}
|
|
1512
|
+
/* Did the hooks approve of the attribute? */
|
|
1513
|
+
if (hookEvent.forceKeepAttr) {
|
|
1514
|
+
continue;
|
|
1515
|
+
}
|
|
1516
|
+
/* Did the hooks approve of the attribute? */
|
|
1517
|
+
if (!hookEvent.keepAttr) {
|
|
1518
|
+
_removeAttribute(name, currentNode);
|
|
1519
|
+
continue;
|
|
1520
|
+
}
|
|
1521
|
+
/* Work around a security issue in jQuery 3.0 */
|
|
1522
|
+
if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(/\/>/i, value)) {
|
|
1523
|
+
_removeAttribute(name, currentNode);
|
|
1524
|
+
continue;
|
|
1525
|
+
}
|
|
1526
|
+
/* Sanitize attribute content to be template-safe */
|
|
1527
|
+
if (SAFE_FOR_TEMPLATES) {
|
|
1528
|
+
arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
|
|
1529
|
+
value = stringReplace(value, expr, ' ');
|
|
1530
|
+
});
|
|
1531
|
+
}
|
|
1532
|
+
/* Is `value` valid for this attribute? */
|
|
1533
|
+
const lcTag = transformCaseFunc(currentNode.nodeName);
|
|
1534
|
+
if (!_isValidAttribute(lcTag, lcName, value)) {
|
|
1535
|
+
_removeAttribute(name, currentNode);
|
|
1536
|
+
continue;
|
|
1537
|
+
}
|
|
1538
|
+
/* Handle attributes that require Trusted Types */
|
|
1539
|
+
if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function') {
|
|
1540
|
+
if (namespaceURI) ; else {
|
|
1541
|
+
switch (trustedTypes.getAttributeType(lcTag, lcName)) {
|
|
1542
|
+
case 'TrustedHTML':
|
|
1543
|
+
{
|
|
1544
|
+
value = trustedTypesPolicy.createHTML(value);
|
|
1545
|
+
break;
|
|
1546
|
+
}
|
|
1547
|
+
case 'TrustedScriptURL':
|
|
1548
|
+
{
|
|
1549
|
+
value = trustedTypesPolicy.createScriptURL(value);
|
|
1550
|
+
break;
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
/* Handle invalid data-* attribute set by try-catching it */
|
|
1556
|
+
if (value !== initValue) {
|
|
1557
|
+
try {
|
|
1558
|
+
if (namespaceURI) {
|
|
1559
|
+
currentNode.setAttributeNS(namespaceURI, name, value);
|
|
1560
|
+
} else {
|
|
1561
|
+
/* Fallback to setAttribute() for browser-unrecognized namespaces e.g. "x-schema". */
|
|
1562
|
+
currentNode.setAttribute(name, value);
|
|
1563
|
+
}
|
|
1564
|
+
if (_isClobbered(currentNode)) {
|
|
1565
|
+
_forceRemove(currentNode);
|
|
1566
|
+
} else {
|
|
1567
|
+
arrayPop(DOMPurify.removed);
|
|
1568
|
+
}
|
|
1569
|
+
} catch (_) {
|
|
1570
|
+
_removeAttribute(name, currentNode);
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
/* Execute a hook if present */
|
|
1575
|
+
_executeHooks(hooks.afterSanitizeAttributes, currentNode, null);
|
|
1576
|
+
};
|
|
1577
|
+
/**
|
|
1578
|
+
* _sanitizeShadowDOM
|
|
1579
|
+
*
|
|
1580
|
+
* @param fragment to iterate over recursively
|
|
1581
|
+
*/
|
|
1582
|
+
const _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {
|
|
1583
|
+
let shadowNode = null;
|
|
1584
|
+
const shadowIterator = _createNodeIterator(fragment);
|
|
1585
|
+
/* Execute a hook if present */
|
|
1586
|
+
_executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);
|
|
1587
|
+
while (shadowNode = shadowIterator.nextNode()) {
|
|
1588
|
+
/* Execute a hook if present */
|
|
1589
|
+
_executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);
|
|
1590
|
+
/* Sanitize tags and elements */
|
|
1591
|
+
_sanitizeElements(shadowNode);
|
|
1592
|
+
/* Check attributes next */
|
|
1593
|
+
_sanitizeAttributes(shadowNode);
|
|
1594
|
+
/* Deep shadow DOM detected */
|
|
1595
|
+
if (shadowNode.content instanceof DocumentFragment) {
|
|
1596
|
+
_sanitizeShadowDOM(shadowNode.content);
|
|
1597
|
+
}
|
|
1598
|
+
}
|
|
1599
|
+
/* Execute a hook if present */
|
|
1600
|
+
_executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);
|
|
1601
|
+
};
|
|
1602
|
+
// eslint-disable-next-line complexity
|
|
1603
|
+
DOMPurify.sanitize = function (dirty) {
|
|
1604
|
+
let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
|
1605
|
+
let body = null;
|
|
1606
|
+
let importedNode = null;
|
|
1607
|
+
let currentNode = null;
|
|
1608
|
+
let returnNode = null;
|
|
1609
|
+
/* Make sure we have a string to sanitize.
|
|
1610
|
+
DO NOT return early, as this will return the wrong type if
|
|
1611
|
+
the user has requested a DOM object rather than a string */
|
|
1612
|
+
IS_EMPTY_INPUT = !dirty;
|
|
1613
|
+
if (IS_EMPTY_INPUT) {
|
|
1614
|
+
dirty = '<!-->';
|
|
1615
|
+
}
|
|
1616
|
+
/* Stringify, in case dirty is an object */
|
|
1617
|
+
if (typeof dirty !== 'string' && !_isNode(dirty)) {
|
|
1618
|
+
if (typeof dirty.toString === 'function') {
|
|
1619
|
+
dirty = dirty.toString();
|
|
1620
|
+
if (typeof dirty !== 'string') {
|
|
1621
|
+
throw typeErrorCreate('dirty is not a string, aborting');
|
|
1622
|
+
}
|
|
1623
|
+
} else {
|
|
1624
|
+
throw typeErrorCreate('toString is not a function');
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
/* Return dirty HTML if DOMPurify cannot run */
|
|
1628
|
+
if (!DOMPurify.isSupported) {
|
|
1629
|
+
return dirty;
|
|
1630
|
+
}
|
|
1631
|
+
/* Assign config vars */
|
|
1632
|
+
if (!SET_CONFIG) {
|
|
1633
|
+
_parseConfig(cfg);
|
|
1634
|
+
}
|
|
1635
|
+
/* Clean up removed elements */
|
|
1636
|
+
DOMPurify.removed = [];
|
|
1637
|
+
/* Check if dirty is correctly typed for IN_PLACE */
|
|
1638
|
+
if (typeof dirty === 'string') {
|
|
1639
|
+
IN_PLACE = false;
|
|
1640
|
+
}
|
|
1641
|
+
if (IN_PLACE) {
|
|
1642
|
+
/* Do some early pre-sanitization to avoid unsafe root nodes */
|
|
1643
|
+
if (dirty.nodeName) {
|
|
1644
|
+
const tagName = transformCaseFunc(dirty.nodeName);
|
|
1645
|
+
if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
|
|
1646
|
+
throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
} else if (dirty instanceof Node) {
|
|
1650
|
+
/* If dirty is a DOM element, append to an empty document to avoid
|
|
1651
|
+
elements being stripped by the parser */
|
|
1652
|
+
body = _initDocument('<!---->');
|
|
1653
|
+
importedNode = body.ownerDocument.importNode(dirty, true);
|
|
1654
|
+
if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {
|
|
1655
|
+
/* Node is already a body, use as is */
|
|
1656
|
+
body = importedNode;
|
|
1657
|
+
} else if (importedNode.nodeName === 'HTML') {
|
|
1658
|
+
body = importedNode;
|
|
1659
|
+
} else {
|
|
1660
|
+
// eslint-disable-next-line unicorn/prefer-dom-node-append
|
|
1661
|
+
body.appendChild(importedNode);
|
|
1662
|
+
}
|
|
1663
|
+
} else {
|
|
1664
|
+
/* Exit directly if we have nothing to do */
|
|
1665
|
+
if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&
|
|
1666
|
+
// eslint-disable-next-line unicorn/prefer-includes
|
|
1667
|
+
dirty.indexOf('<') === -1) {
|
|
1668
|
+
return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;
|
|
1669
|
+
}
|
|
1670
|
+
/* Initialize the document to work on */
|
|
1671
|
+
body = _initDocument(dirty);
|
|
1672
|
+
/* Check we have a DOM node from the data */
|
|
1673
|
+
if (!body) {
|
|
1674
|
+
return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
/* Remove first element node (ours) if FORCE_BODY is set */
|
|
1678
|
+
if (body && FORCE_BODY) {
|
|
1679
|
+
_forceRemove(body.firstChild);
|
|
1680
|
+
}
|
|
1681
|
+
/* Get node iterator */
|
|
1682
|
+
const nodeIterator = _createNodeIterator(IN_PLACE ? dirty : body);
|
|
1683
|
+
/* Now start iterating over the created document */
|
|
1684
|
+
while (currentNode = nodeIterator.nextNode()) {
|
|
1685
|
+
/* Sanitize tags and elements */
|
|
1686
|
+
_sanitizeElements(currentNode);
|
|
1687
|
+
/* Check attributes next */
|
|
1688
|
+
_sanitizeAttributes(currentNode);
|
|
1689
|
+
/* Shadow DOM detected, sanitize it */
|
|
1690
|
+
if (currentNode.content instanceof DocumentFragment) {
|
|
1691
|
+
_sanitizeShadowDOM(currentNode.content);
|
|
1692
|
+
}
|
|
1693
|
+
}
|
|
1694
|
+
/* If we sanitized `dirty` in-place, return it. */
|
|
1695
|
+
if (IN_PLACE) {
|
|
1696
|
+
return dirty;
|
|
1697
|
+
}
|
|
1698
|
+
/* Return sanitized string or DOM */
|
|
1699
|
+
if (RETURN_DOM) {
|
|
1700
|
+
if (RETURN_DOM_FRAGMENT) {
|
|
1701
|
+
returnNode = createDocumentFragment.call(body.ownerDocument);
|
|
1702
|
+
while (body.firstChild) {
|
|
1703
|
+
// eslint-disable-next-line unicorn/prefer-dom-node-append
|
|
1704
|
+
returnNode.appendChild(body.firstChild);
|
|
1705
|
+
}
|
|
1706
|
+
} else {
|
|
1707
|
+
returnNode = body;
|
|
1708
|
+
}
|
|
1709
|
+
if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {
|
|
1710
|
+
/*
|
|
1711
|
+
AdoptNode() is not used because internal state is not reset
|
|
1712
|
+
(e.g. the past names map of a HTMLFormElement), this is safe
|
|
1713
|
+
in theory but we would rather not risk another attack vector.
|
|
1714
|
+
The state that is cloned by importNode() is explicitly defined
|
|
1715
|
+
by the specs.
|
|
1716
|
+
*/
|
|
1717
|
+
returnNode = importNode.call(originalDocument, returnNode, true);
|
|
1718
|
+
}
|
|
1719
|
+
return returnNode;
|
|
1720
|
+
}
|
|
1721
|
+
let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
|
|
1722
|
+
/* Serialize doctype if allowed */
|
|
1723
|
+
if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {
|
|
1724
|
+
serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\n' + serializedHTML;
|
|
1725
|
+
}
|
|
1726
|
+
/* Sanitize final string template-safe */
|
|
1727
|
+
if (SAFE_FOR_TEMPLATES) {
|
|
1728
|
+
arrayForEach([MUSTACHE_EXPR, ERB_EXPR, TMPLIT_EXPR], expr => {
|
|
1729
|
+
serializedHTML = stringReplace(serializedHTML, expr, ' ');
|
|
1730
|
+
});
|
|
1731
|
+
}
|
|
1732
|
+
return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;
|
|
1733
|
+
};
|
|
1734
|
+
DOMPurify.setConfig = function () {
|
|
1735
|
+
let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
|
|
1736
|
+
_parseConfig(cfg);
|
|
1737
|
+
SET_CONFIG = true;
|
|
1738
|
+
};
|
|
1739
|
+
DOMPurify.clearConfig = function () {
|
|
1740
|
+
CONFIG = null;
|
|
1741
|
+
SET_CONFIG = false;
|
|
1742
|
+
};
|
|
1743
|
+
DOMPurify.isValidAttribute = function (tag, attr, value) {
|
|
1744
|
+
/* Initialize shared config vars if necessary. */
|
|
1745
|
+
if (!CONFIG) {
|
|
1746
|
+
_parseConfig({});
|
|
1747
|
+
}
|
|
1748
|
+
const lcTag = transformCaseFunc(tag);
|
|
1749
|
+
const lcName = transformCaseFunc(attr);
|
|
1750
|
+
return _isValidAttribute(lcTag, lcName, value);
|
|
1751
|
+
};
|
|
1752
|
+
DOMPurify.addHook = function (entryPoint, hookFunction) {
|
|
1753
|
+
if (typeof hookFunction !== 'function') {
|
|
1754
|
+
return;
|
|
1755
|
+
}
|
|
1756
|
+
arrayPush(hooks[entryPoint], hookFunction);
|
|
1757
|
+
};
|
|
1758
|
+
DOMPurify.removeHook = function (entryPoint, hookFunction) {
|
|
1759
|
+
if (hookFunction !== undefined) {
|
|
1760
|
+
const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);
|
|
1761
|
+
return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];
|
|
1762
|
+
}
|
|
1763
|
+
return arrayPop(hooks[entryPoint]);
|
|
1764
|
+
};
|
|
1765
|
+
DOMPurify.removeHooks = function (entryPoint) {
|
|
1766
|
+
hooks[entryPoint] = [];
|
|
1767
|
+
};
|
|
1768
|
+
DOMPurify.removeAllHooks = function () {
|
|
1769
|
+
hooks = _createHooksMap();
|
|
1770
|
+
};
|
|
1771
|
+
return DOMPurify;
|
|
1772
|
+
}
|
|
1773
|
+
var purify = createDOMPurify();
|
|
1774
|
+
|
|
1775
|
+
function sanitizeHtml(html) {
|
|
1776
|
+
return purify.sanitize(html, {
|
|
1777
|
+
ALLOWED_TAGS: [
|
|
1778
|
+
// Text formatting
|
|
1779
|
+
'a', 'b', 'i', 'em', 'strong', 'u', 's', 'strike', 'del',
|
|
1780
|
+
// Paragraphs and breaks
|
|
1781
|
+
'p', 'br', 'div', 'span',
|
|
1782
|
+
// Headings
|
|
1783
|
+
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
|
|
1784
|
+
// Lists
|
|
1785
|
+
'ul', 'ol', 'li', 'dl', 'dt', 'dd',
|
|
1786
|
+
// Code
|
|
1787
|
+
'code', 'pre', 'kbd', 'samp',
|
|
1788
|
+
// Blockquotes
|
|
1789
|
+
'blockquote', 'q',
|
|
1790
|
+
// Tables
|
|
1791
|
+
'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td',
|
|
1792
|
+
// Other
|
|
1793
|
+
'hr', 'sub', 'sup', 'small', 'mark', 'abbr', 'cite', 'time'
|
|
1794
|
+
],
|
|
1795
|
+
ALLOWED_ATTR: ['href', 'target', 'rel', 'title', 'class', 'id', 'style'],
|
|
1796
|
+
ALLOW_DATA_ATTR: false,
|
|
1797
|
+
// Allow style attribute but sanitize it
|
|
1798
|
+
ALLOW_UNKNOWN_PROTOCOLS: false,
|
|
1799
|
+
});
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
/**
|
|
1803
|
+
* Formats an ISO timestamp string to a human-readable format.
|
|
1804
|
+
* Example output: "Mar 11, 2026 at 2:30 PM"
|
|
1805
|
+
*/
|
|
1806
|
+
function formatTimestamp(isoString) {
|
|
1807
|
+
const date = new Date(isoString);
|
|
1808
|
+
if (isNaN(date.getTime())) {
|
|
1809
|
+
return '';
|
|
1810
|
+
}
|
|
1811
|
+
const months = [
|
|
1812
|
+
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
|
|
1813
|
+
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
|
|
1814
|
+
];
|
|
1815
|
+
const month = months[date.getMonth()];
|
|
1816
|
+
const day = date.getDate();
|
|
1817
|
+
const year = date.getFullYear();
|
|
1818
|
+
let hours = date.getHours();
|
|
1819
|
+
const minutes = date.getMinutes();
|
|
1820
|
+
const ampm = hours >= 12 ? 'PM' : 'AM';
|
|
1821
|
+
hours = hours % 12 || 12;
|
|
1822
|
+
const minutesStr = minutes < 10 ? `0${minutes}` : `${minutes}`;
|
|
1823
|
+
return `${month} ${day}, ${year} at ${hours}:${minutesStr} ${ampm}`;
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
const MessagePopup = ({ message, onClose, onLinkClick, }) => {
|
|
1827
|
+
const [isVisible, setIsVisible] = useState(false);
|
|
1828
|
+
useEffect(() => {
|
|
1829
|
+
// Trigger animation
|
|
1830
|
+
setTimeout(() => setIsVisible(true), 10);
|
|
1831
|
+
}, []);
|
|
1832
|
+
const handleLinkClick = (e) => {
|
|
1833
|
+
e.preventDefault();
|
|
1834
|
+
const url = e.currentTarget.href;
|
|
1835
|
+
onLinkClick(url);
|
|
1836
|
+
};
|
|
1837
|
+
const sanitizedContent = sanitizeHtml(message.message);
|
|
1838
|
+
const messageType = message.received ? 'viewed' : 'info';
|
|
1839
|
+
return (React.createElement("div", { className: `journy-message-overlay ${isVisible ? 'journy-message-visible' : ''}` },
|
|
1840
|
+
React.createElement("div", { className: `journy-message-popup journy-message-${messageType}` },
|
|
1841
|
+
React.createElement("button", { className: "journy-message-close", onClick: onClose, "aria-label": "Close message" }, "\u00D7"),
|
|
1842
|
+
message.createdAt && (React.createElement("div", { className: "journy-message-timestamp" }, formatTimestamp(message.createdAt))),
|
|
1843
|
+
React.createElement("div", { className: "journy-message-content", dangerouslySetInnerHTML: { __html: sanitizedContent }, onClick: (e) => {
|
|
1844
|
+
const target = e.target;
|
|
1845
|
+
if (target.tagName === 'A') {
|
|
1846
|
+
handleLinkClick(e);
|
|
1847
|
+
}
|
|
1848
|
+
} }))));
|
|
1849
|
+
};
|
|
1850
|
+
|
|
1851
|
+
const POLLING_OPTIONS = [
|
|
1852
|
+
{ label: '15 seconds', value: 15000 },
|
|
1853
|
+
{ label: '30 seconds', value: 30000 },
|
|
1854
|
+
{ label: '60 seconds', value: 60000 },
|
|
1855
|
+
{ label: '120 seconds', value: 120000 },
|
|
1856
|
+
];
|
|
1857
|
+
const DISPLAY_MODE_OPTIONS = [
|
|
1858
|
+
{ label: 'Widget', value: 'widget' },
|
|
1859
|
+
{ label: 'List', value: 'list' },
|
|
1860
|
+
];
|
|
1861
|
+
const STYLES_OPTIONS = [
|
|
1862
|
+
{ label: 'Default', value: 'default' },
|
|
1863
|
+
{ label: 'None (custom)', value: 'none' },
|
|
1864
|
+
];
|
|
1865
|
+
function getStylesKey(styles) {
|
|
1866
|
+
if (styles === 'default' || styles === 'none')
|
|
1867
|
+
return styles;
|
|
1868
|
+
if (typeof styles === 'object' && 'url' in styles)
|
|
1869
|
+
return 'custom-url';
|
|
1870
|
+
if (typeof styles === 'object' && 'css' in styles)
|
|
1871
|
+
return 'custom-css';
|
|
1872
|
+
return 'default';
|
|
1873
|
+
}
|
|
1874
|
+
const SettingsPanel = ({ isOpen, onClose, settings, onSettingsChange, configInfo, }) => {
|
|
1875
|
+
const [showAdvanced, setShowAdvanced] = useState(false);
|
|
1876
|
+
const update = (partial) => {
|
|
1877
|
+
onSettingsChange({ ...settings, ...partial });
|
|
1878
|
+
};
|
|
1879
|
+
const handleToggle = (key) => {
|
|
1880
|
+
update({ [key]: !settings[key] });
|
|
1881
|
+
};
|
|
1882
|
+
const stylesKey = getStylesKey(settings.styles);
|
|
1883
|
+
return (React.createElement("div", { className: `journy-settings-panel ${isOpen ? 'journy-settings-panel-open' : 'journy-settings-panel-closed'}`, onClick: (e) => e.stopPropagation() },
|
|
1884
|
+
React.createElement("div", { className: "journy-settings-header" },
|
|
1885
|
+
React.createElement("span", { className: "journy-settings-title" }, "Settings"),
|
|
1886
|
+
React.createElement("button", { type: "button", className: "journy-settings-close", onClick: onClose, title: "Close settings", "aria-label": "Close settings" }, "\u00D7")),
|
|
1887
|
+
React.createElement("div", { className: "journy-settings-body" },
|
|
1888
|
+
React.createElement("div", { className: "journy-settings-item" },
|
|
1889
|
+
React.createElement("label", { className: "journy-settings-label" }, "Display mode"),
|
|
1890
|
+
React.createElement("select", { className: "journy-settings-select", value: settings.displayMode, onChange: (e) => update({ displayMode: e.target.value }) }, DISPLAY_MODE_OPTIONS.map((opt) => (React.createElement("option", { key: opt.value, value: opt.value }, opt.label))))),
|
|
1891
|
+
React.createElement("div", { className: "journy-settings-item" },
|
|
1892
|
+
React.createElement("label", { className: "journy-settings-label" }, "Polling interval"),
|
|
1893
|
+
React.createElement("select", { className: "journy-settings-select", value: settings.pollingInterval, onChange: (e) => update({ pollingInterval: Number(e.target.value) }) }, POLLING_OPTIONS.map((opt) => (React.createElement("option", { key: opt.value, value: opt.value }, opt.label))))),
|
|
1894
|
+
React.createElement("div", { className: "journy-settings-item" },
|
|
1895
|
+
React.createElement("label", { className: "journy-settings-label" }, "Show read messages"),
|
|
1896
|
+
React.createElement("button", { type: "button", className: `journy-settings-toggle ${settings.showReadMessages ? 'journy-settings-toggle-on' : ''}`, onClick: () => handleToggle('showReadMessages'), role: "switch", "aria-checked": settings.showReadMessages },
|
|
1897
|
+
React.createElement("span", { className: "journy-settings-toggle-knob" }))),
|
|
1898
|
+
React.createElement("div", { className: "journy-settings-item" },
|
|
1899
|
+
React.createElement("label", { className: "journy-settings-label" }, "Auto-expand on new messages"),
|
|
1900
|
+
React.createElement("button", { type: "button", className: `journy-settings-toggle ${settings.autoExpandOnNew ? 'journy-settings-toggle-on' : ''}`, onClick: () => handleToggle('autoExpandOnNew'), role: "switch", "aria-checked": settings.autoExpandOnNew },
|
|
1901
|
+
React.createElement("span", { className: "journy-settings-toggle-knob" }))),
|
|
1902
|
+
React.createElement("div", { className: "journy-settings-item" },
|
|
1903
|
+
React.createElement("label", { className: "journy-settings-label" }, "Styles"),
|
|
1904
|
+
React.createElement("select", { className: "journy-settings-select", value: stylesKey, onChange: (e) => {
|
|
1905
|
+
const val = e.target.value;
|
|
1906
|
+
if (val === 'default' || val === 'none') {
|
|
1907
|
+
update({ styles: val });
|
|
1908
|
+
}
|
|
1909
|
+
} },
|
|
1910
|
+
STYLES_OPTIONS.map((opt) => (React.createElement("option", { key: opt.value, value: opt.value }, opt.label))),
|
|
1911
|
+
stylesKey === 'custom-url' && (React.createElement("option", { value: "custom-url", disabled: true }, "Custom URL")),
|
|
1912
|
+
stylesKey === 'custom-css' && (React.createElement("option", { value: "custom-css", disabled: true }, "Custom CSS")))),
|
|
1913
|
+
React.createElement("div", { className: "journy-settings-item" },
|
|
1914
|
+
React.createElement("button", { type: "button", className: "journy-settings-advanced-btn", onClick: () => setShowAdvanced(!showAdvanced) }, showAdvanced ? '▾ Advanced' : '▸ Advanced')),
|
|
1915
|
+
showAdvanced && (React.createElement(React.Fragment, null,
|
|
1916
|
+
React.createElement("div", { className: "journy-settings-item journy-settings-item-vertical" },
|
|
1917
|
+
React.createElement("label", { className: "journy-settings-label" }, "API endpoint"),
|
|
1918
|
+
React.createElement("input", { type: "text", className: "journy-settings-input", value: settings.apiEndpoint, onChange: (e) => update({ apiEndpoint: e.target.value }), placeholder: "https://jtm.journy.io" })),
|
|
1919
|
+
configInfo && (React.createElement(React.Fragment, null,
|
|
1920
|
+
React.createElement("div", { className: "journy-settings-item" },
|
|
1921
|
+
React.createElement("label", { className: "journy-settings-label" }, "Entity type"),
|
|
1922
|
+
React.createElement("span", { className: "journy-settings-value" }, configInfo.entityType)),
|
|
1923
|
+
configInfo.userId && (React.createElement("div", { className: "journy-settings-item" },
|
|
1924
|
+
React.createElement("label", { className: "journy-settings-label" }, "User ID"),
|
|
1925
|
+
React.createElement("span", { className: "journy-settings-value" }, configInfo.userId))),
|
|
1926
|
+
configInfo.accountId && (React.createElement("div", { className: "journy-settings-item" },
|
|
1927
|
+
React.createElement("label", { className: "journy-settings-label" }, "Account ID"),
|
|
1928
|
+
React.createElement("span", { className: "journy-settings-value" }, configInfo.accountId))))))))));
|
|
1929
|
+
};
|
|
1930
|
+
|
|
1931
|
+
const ICON_SIZE$1 = 12;
|
|
1932
|
+
const DOT_FIRST = 2;
|
|
1933
|
+
const DOT_SECOND = 6;
|
|
1934
|
+
const DOT_THIRD = 10;
|
|
1935
|
+
const DOT_RADIUS = 1;
|
|
1936
|
+
const DragHandle = ({ onMouseDown, title = 'Drag to move', className = 'journy-message-widget-drag-handle', }) => (React.createElement("div", { className: className, onMouseDown: onMouseDown, title: title },
|
|
1937
|
+
React.createElement("svg", { width: ICON_SIZE$1, height: ICON_SIZE$1, viewBox: `0 0 ${ICON_SIZE$1} ${ICON_SIZE$1}`, fill: "none", xmlns: "http://www.w3.org/2000/svg" },
|
|
1938
|
+
React.createElement("circle", { cx: DOT_FIRST, cy: DOT_FIRST, r: DOT_RADIUS, fill: "#9ca3af" }),
|
|
1939
|
+
React.createElement("circle", { cx: DOT_SECOND, cy: DOT_FIRST, r: DOT_RADIUS, fill: "#9ca3af" }),
|
|
1940
|
+
React.createElement("circle", { cx: DOT_THIRD, cy: DOT_FIRST, r: DOT_RADIUS, fill: "#9ca3af" }),
|
|
1941
|
+
React.createElement("circle", { cx: DOT_FIRST, cy: DOT_SECOND, r: DOT_RADIUS, fill: "#9ca3af" }),
|
|
1942
|
+
React.createElement("circle", { cx: DOT_SECOND, cy: DOT_SECOND, r: DOT_RADIUS, fill: "#9ca3af" }),
|
|
1943
|
+
React.createElement("circle", { cx: DOT_THIRD, cy: DOT_SECOND, r: DOT_RADIUS, fill: "#9ca3af" }),
|
|
1944
|
+
React.createElement("circle", { cx: DOT_FIRST, cy: DOT_THIRD, r: DOT_RADIUS, fill: "#9ca3af" }),
|
|
1945
|
+
React.createElement("circle", { cx: DOT_SECOND, cy: DOT_THIRD, r: DOT_RADIUS, fill: "#9ca3af" }),
|
|
1946
|
+
React.createElement("circle", { cx: DOT_THIRD, cy: DOT_THIRD, r: DOT_RADIUS, fill: "#9ca3af" }))));
|
|
1947
|
+
|
|
1948
|
+
const ICON_SIZE = 16;
|
|
1949
|
+
const STROKE_WIDTH = 1.5;
|
|
1950
|
+
/** Diagonal from top-right to bottom-left (resize corner). */
|
|
1951
|
+
const PATH_MAIN = 'M16 0 L0 16';
|
|
1952
|
+
const PATH_INNER = 'M13 3 L3 13';
|
|
1953
|
+
const ResizeHandle = ({ onMouseDown, title = 'Resize', className = 'journy-message-widget-resize-handle', }) => (React.createElement("div", { className: className, onMouseDown: onMouseDown, title: title },
|
|
1954
|
+
React.createElement("svg", { width: ICON_SIZE, height: ICON_SIZE, viewBox: `0 0 ${ICON_SIZE} ${ICON_SIZE}`, fill: "none", xmlns: "http://www.w3.org/2000/svg" },
|
|
1955
|
+
React.createElement("path", { d: `${PATH_MAIN} ${PATH_INNER}`, stroke: "#9ca3af", strokeWidth: STROKE_WIDTH, strokeLinecap: "round" }))));
|
|
1956
|
+
|
|
1957
|
+
const COLLAPSED_WIDTH = 300;
|
|
1958
|
+
const COLLAPSED_HEIGHT = 80;
|
|
1959
|
+
const WIDGET_MODE_EXPANDED_WIDTH = 340;
|
|
1960
|
+
const WIDGET_MODE_EXPANDED_HEIGHT = 280;
|
|
1961
|
+
const LIST_MODE_DEFAULT_WIDTH = 600;
|
|
1962
|
+
const LIST_MODE_DEFAULT_HEIGHT = 800;
|
|
1963
|
+
const DEFAULT_EDGE_OFFSET = 20;
|
|
1964
|
+
const VIEWPORT_PADDING = 40;
|
|
1965
|
+
const MIN_LIST_WIDTH = 300;
|
|
1966
|
+
const MIN_LIST_HEIGHT = 200;
|
|
1967
|
+
const MIN_POSITION_THRESHOLD = 0;
|
|
1968
|
+
function useWidgetDragResize({ isCollapsed, isListMode }) {
|
|
1969
|
+
const [position, setPosition] = useState(() => {
|
|
1970
|
+
const saved = getItem('widget_position');
|
|
1971
|
+
if (saved && typeof saved.left === 'number' && typeof saved.top === 'number') {
|
|
1972
|
+
return {
|
|
1973
|
+
left: Math.max(0, Math.min(saved.left, window.innerWidth - COLLAPSED_WIDTH)),
|
|
1974
|
+
top: Math.max(0, Math.min(saved.top, window.innerHeight - COLLAPSED_HEIGHT)),
|
|
1975
|
+
};
|
|
1976
|
+
}
|
|
1977
|
+
if (saved && typeof saved.x === 'number' && typeof saved.y === 'number') {
|
|
1978
|
+
return {
|
|
1979
|
+
left: Math.max(0, saved.x - COLLAPSED_WIDTH),
|
|
1980
|
+
top: Math.max(0, saved.y - COLLAPSED_HEIGHT),
|
|
1981
|
+
};
|
|
1982
|
+
}
|
|
1983
|
+
return {
|
|
1984
|
+
left: window.innerWidth - DEFAULT_EDGE_OFFSET - COLLAPSED_WIDTH,
|
|
1985
|
+
top: window.innerHeight - DEFAULT_EDGE_OFFSET - COLLAPSED_HEIGHT,
|
|
1986
|
+
};
|
|
1987
|
+
});
|
|
1988
|
+
const [size, setSize] = useState({ width: LIST_MODE_DEFAULT_WIDTH, height: LIST_MODE_DEFAULT_HEIGHT });
|
|
1989
|
+
const [isDragging, setIsDragging] = useState(false);
|
|
1990
|
+
const [isResizing, setIsResizing] = useState(false);
|
|
1991
|
+
const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
|
|
1992
|
+
const [resizeStart, setResizeStart] = useState(null);
|
|
1993
|
+
const widgetRef = useRef(null);
|
|
1994
|
+
const hasDraggedThisSession = useRef(false);
|
|
1995
|
+
const justFinishedDragging = useRef(false);
|
|
1996
|
+
const currentWidth = isCollapsed
|
|
1997
|
+
? COLLAPSED_WIDTH
|
|
1998
|
+
: isListMode
|
|
1999
|
+
? size.width
|
|
2000
|
+
: WIDGET_MODE_EXPANDED_WIDTH;
|
|
2001
|
+
const currentHeight = isCollapsed
|
|
2002
|
+
? COLLAPSED_HEIGHT
|
|
2003
|
+
: isListMode
|
|
2004
|
+
? size.height
|
|
2005
|
+
: WIDGET_MODE_EXPANDED_HEIGHT;
|
|
2006
|
+
// Load saved size from localStorage on mount
|
|
2007
|
+
useEffect(() => {
|
|
2008
|
+
const savedSize = getItem('widget_size');
|
|
2009
|
+
if (savedSize) {
|
|
2010
|
+
setSize({
|
|
2011
|
+
width: Math.max(MIN_LIST_WIDTH, Math.min(savedSize.width, window.innerWidth - VIEWPORT_PADDING)),
|
|
2012
|
+
height: Math.max(MIN_LIST_HEIGHT, Math.min(savedSize.height, window.innerHeight - VIEWPORT_PADDING)),
|
|
2013
|
+
});
|
|
2014
|
+
}
|
|
2015
|
+
}, []);
|
|
2016
|
+
// Clamp position so widget stays on screen
|
|
2017
|
+
useEffect(() => {
|
|
2018
|
+
setPosition(prev => ({
|
|
2019
|
+
left: Math.max(0, Math.min(prev.left, window.innerWidth - currentWidth)),
|
|
2020
|
+
top: Math.max(0, Math.min(prev.top, window.innerHeight - currentHeight)),
|
|
2021
|
+
}));
|
|
2022
|
+
}, [currentWidth, currentHeight]);
|
|
2023
|
+
// Save position when it changes
|
|
2024
|
+
useEffect(() => {
|
|
2025
|
+
if (position.left > MIN_POSITION_THRESHOLD || position.top > MIN_POSITION_THRESHOLD) {
|
|
2026
|
+
setItem('widget_position', position);
|
|
2027
|
+
}
|
|
2028
|
+
}, [position]);
|
|
2029
|
+
// Save size when it changes (list mode expanded only)
|
|
2030
|
+
useEffect(() => {
|
|
2031
|
+
if (isListMode && !isCollapsed && size.width > MIN_POSITION_THRESHOLD && size.height > MIN_POSITION_THRESHOLD) {
|
|
2032
|
+
setItem('widget_size', size);
|
|
2033
|
+
}
|
|
2034
|
+
}, [size, isCollapsed, isListMode]);
|
|
2035
|
+
// Constrain position when window resizes
|
|
2036
|
+
useEffect(() => {
|
|
2037
|
+
const handleResize = () => {
|
|
2038
|
+
setPosition(prev => ({
|
|
2039
|
+
left: Math.max(0, Math.min(prev.left, window.innerWidth - currentWidth)),
|
|
2040
|
+
top: Math.max(0, Math.min(prev.top, window.innerHeight - currentHeight)),
|
|
2041
|
+
}));
|
|
2042
|
+
};
|
|
2043
|
+
window.addEventListener('resize', handleResize);
|
|
2044
|
+
return () => window.removeEventListener('resize', handleResize);
|
|
2045
|
+
}, [currentWidth, currentHeight]);
|
|
2046
|
+
const handleMouseDown = (e) => {
|
|
2047
|
+
const target = e.target;
|
|
2048
|
+
if (!target.closest('.journy-message-widget-drag-handle'))
|
|
2049
|
+
return;
|
|
2050
|
+
if (!widgetRef.current)
|
|
2051
|
+
return;
|
|
2052
|
+
hasDraggedThisSession.current = false;
|
|
2053
|
+
const rect = widgetRef.current.getBoundingClientRect();
|
|
2054
|
+
setDragOffset({
|
|
2055
|
+
x: e.clientX - rect.left,
|
|
2056
|
+
y: e.clientY - rect.top,
|
|
2057
|
+
});
|
|
2058
|
+
setIsDragging(true);
|
|
2059
|
+
};
|
|
2060
|
+
// Global mousemove/mouseup for drag and resize
|
|
2061
|
+
useEffect(() => {
|
|
2062
|
+
if (!isDragging && !isResizing)
|
|
2063
|
+
return;
|
|
2064
|
+
const handleMouseMove = (e) => {
|
|
2065
|
+
if (isDragging) {
|
|
2066
|
+
hasDraggedThisSession.current = true;
|
|
2067
|
+
const newLeft = e.clientX - dragOffset.x;
|
|
2068
|
+
const newTop = e.clientY - dragOffset.y;
|
|
2069
|
+
setPosition({
|
|
2070
|
+
left: Math.max(0, Math.min(newLeft, window.innerWidth - currentWidth)),
|
|
2071
|
+
top: Math.max(0, Math.min(newTop, window.innerHeight - currentHeight)),
|
|
2072
|
+
});
|
|
2073
|
+
}
|
|
2074
|
+
else if (isResizing && resizeStart) {
|
|
2075
|
+
const deltaX = e.clientX - resizeStart.x;
|
|
2076
|
+
const deltaY = e.clientY - resizeStart.y;
|
|
2077
|
+
const maxWidth = window.innerWidth - position.left;
|
|
2078
|
+
const maxHeight = window.innerHeight - position.top;
|
|
2079
|
+
const newWidth = Math.max(MIN_LIST_WIDTH, Math.min(resizeStart.width + deltaX, maxWidth));
|
|
2080
|
+
const newHeight = Math.max(MIN_LIST_HEIGHT, Math.min(resizeStart.height + deltaY, maxHeight));
|
|
2081
|
+
setSize({ width: newWidth, height: newHeight });
|
|
2082
|
+
}
|
|
2083
|
+
};
|
|
2084
|
+
const handleMouseUp = () => {
|
|
2085
|
+
if (isDragging && hasDraggedThisSession.current) {
|
|
2086
|
+
justFinishedDragging.current = true;
|
|
2087
|
+
setTimeout(() => {
|
|
2088
|
+
justFinishedDragging.current = false;
|
|
2089
|
+
}, 100);
|
|
2090
|
+
}
|
|
2091
|
+
setIsDragging(false);
|
|
2092
|
+
setIsResizing(false);
|
|
2093
|
+
setResizeStart(null);
|
|
2094
|
+
};
|
|
2095
|
+
document.addEventListener('mousemove', handleMouseMove);
|
|
2096
|
+
document.addEventListener('mouseup', handleMouseUp);
|
|
2097
|
+
return () => {
|
|
2098
|
+
document.removeEventListener('mousemove', handleMouseMove);
|
|
2099
|
+
document.removeEventListener('mouseup', handleMouseUp);
|
|
2100
|
+
};
|
|
2101
|
+
}, [isDragging, isResizing, dragOffset, resizeStart, position, currentWidth, currentHeight]);
|
|
2102
|
+
const handleResizeStart = (e) => {
|
|
2103
|
+
e.stopPropagation();
|
|
2104
|
+
if (!widgetRef.current)
|
|
2105
|
+
return;
|
|
2106
|
+
const rect = widgetRef.current.getBoundingClientRect();
|
|
2107
|
+
setResizeStart({
|
|
2108
|
+
x: e.clientX,
|
|
2109
|
+
y: e.clientY,
|
|
2110
|
+
width: rect.width,
|
|
2111
|
+
height: rect.height,
|
|
2112
|
+
});
|
|
2113
|
+
setIsResizing(true);
|
|
2114
|
+
};
|
|
2115
|
+
return {
|
|
2116
|
+
position,
|
|
2117
|
+
size,
|
|
2118
|
+
isDragging,
|
|
2119
|
+
isResizing,
|
|
2120
|
+
widgetRef,
|
|
2121
|
+
justFinishedDragging,
|
|
2122
|
+
currentWidth,
|
|
2123
|
+
currentHeight,
|
|
2124
|
+
handleMouseDown,
|
|
2125
|
+
handleResizeStart,
|
|
2126
|
+
};
|
|
2127
|
+
}
|
|
2128
|
+
const TRANSITION_DURATION_S = 0.25;
|
|
2129
|
+
|
|
2130
|
+
const SETTINGS_STORAGE_KEY = 'widget_settings';
|
|
2131
|
+
/** Mark message as received when its element is visible in the viewport. */
|
|
2132
|
+
function useMessageVisibility(ref, messageId, received, onMessageReceived) {
|
|
2133
|
+
const hasFiredRef = useRef(false);
|
|
2134
|
+
useEffect(() => {
|
|
2135
|
+
if (received) {
|
|
2136
|
+
hasFiredRef.current = true;
|
|
2137
|
+
return;
|
|
2138
|
+
}
|
|
2139
|
+
hasFiredRef.current = false;
|
|
2140
|
+
const el = ref.current;
|
|
2141
|
+
if (!el || !onMessageReceived)
|
|
2142
|
+
return;
|
|
2143
|
+
const observer = new IntersectionObserver((entries) => {
|
|
2144
|
+
const [entry] = entries;
|
|
2145
|
+
if (entry?.isIntersecting && !hasFiredRef.current) {
|
|
2146
|
+
hasFiredRef.current = true;
|
|
2147
|
+
onMessageReceived([messageId]);
|
|
2148
|
+
observer.disconnect();
|
|
2149
|
+
}
|
|
2150
|
+
}, { threshold: 0.1, root: null });
|
|
2151
|
+
observer.observe(el);
|
|
2152
|
+
return () => observer.disconnect();
|
|
2153
|
+
}, [messageId, received, onMessageReceived]);
|
|
2154
|
+
}
|
|
2155
|
+
/** Wraps a message row with a ref and viewport visibility observer to mark as received when visible. */
|
|
2156
|
+
const MessageRow = ({ message, isSeparated, onMessageReceived, onDismissMessage, children }) => {
|
|
2157
|
+
const ref = useRef(null);
|
|
2158
|
+
useMessageVisibility(ref, message.id, message.received, onMessageReceived);
|
|
2159
|
+
return (React.createElement("div", { ref: ref, className: `journy-message-widget-message journy-message-${message.received ? 'viewed' : 'info'} ${isSeparated ? 'journy-message-widget-message-separated' : ''}` },
|
|
2160
|
+
onDismissMessage && (React.createElement("button", { type: "button", className: "journy-message-widget-message-close", onClick: (e) => {
|
|
2161
|
+
e.stopPropagation();
|
|
2162
|
+
e.preventDefault();
|
|
2163
|
+
onDismissMessage(message.id);
|
|
2164
|
+
}, title: "Dismiss message", "aria-label": "Dismiss" }, "\u00D7")),
|
|
2165
|
+
children));
|
|
2166
|
+
};
|
|
2167
|
+
/** Derives total, unread, and read counts from the messages array. */
|
|
2168
|
+
function useMessageCounts(messages) {
|
|
2169
|
+
return useMemo(() => {
|
|
2170
|
+
const unreadCount = messages.filter((m) => !m.received).length;
|
|
2171
|
+
const readCount = messages.filter((m) => m.received).length;
|
|
2172
|
+
return {
|
|
2173
|
+
totalCount: messages.length,
|
|
2174
|
+
unreadCount,
|
|
2175
|
+
readCount,
|
|
2176
|
+
};
|
|
2177
|
+
}, [messages]);
|
|
2178
|
+
}
|
|
2179
|
+
const MessageWidget = ({ store, onClose, onCloseWidget, onLinkClick, onToggleExpand, onMessageReceived, onDismissMessage, onNextMessage, onPrevMessage, onSettingsChange, configInfo, }) => {
|
|
2180
|
+
const { messages, currentMessage, isCollapsed, displayMode, widgetVisible } = useMessagingStore(store);
|
|
2181
|
+
const { totalCount, unreadCount, readCount } = useMessageCounts(messages);
|
|
2182
|
+
const [modalMessage, setModalMessage] = useState(null);
|
|
2183
|
+
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
|
|
2184
|
+
const [settings, setSettings] = useState(() => {
|
|
2185
|
+
const saved = getItem(SETTINGS_STORAGE_KEY);
|
|
2186
|
+
return saved
|
|
2187
|
+
? { ...DEFAULT_WIDGET_SETTINGS, ...saved, displayMode }
|
|
2188
|
+
: { ...DEFAULT_WIDGET_SETTINGS, displayMode };
|
|
2189
|
+
});
|
|
2190
|
+
const isListMode = displayMode === 'list';
|
|
2191
|
+
const { position, isDragging, isResizing, widgetRef, justFinishedDragging, currentWidth, currentHeight, handleMouseDown, handleResizeStart, } = useWidgetDragResize({ isCollapsed, isListMode });
|
|
2192
|
+
const contentRef = useRef(null);
|
|
2193
|
+
const scrollTimerRef = useRef(null);
|
|
2194
|
+
// Persist scroll position on scroll (debounced), restore on mount/expand
|
|
2195
|
+
useEffect(() => {
|
|
2196
|
+
if (isCollapsed || !isListMode)
|
|
2197
|
+
return;
|
|
2198
|
+
const el = contentRef.current;
|
|
2199
|
+
if (!el)
|
|
2200
|
+
return;
|
|
2201
|
+
// Restore saved scroll position
|
|
2202
|
+
const savedScroll = getItem('widget_scroll_position');
|
|
2203
|
+
if (savedScroll != null) {
|
|
2204
|
+
el.scrollTop = savedScroll;
|
|
2205
|
+
}
|
|
2206
|
+
const handleScroll = () => {
|
|
2207
|
+
if (scrollTimerRef.current)
|
|
2208
|
+
clearTimeout(scrollTimerRef.current);
|
|
2209
|
+
scrollTimerRef.current = setTimeout(() => {
|
|
2210
|
+
setItem('widget_scroll_position', el.scrollTop);
|
|
2211
|
+
}, 150);
|
|
2212
|
+
};
|
|
2213
|
+
el.addEventListener('scroll', handleScroll, { passive: true });
|
|
2214
|
+
return () => {
|
|
2215
|
+
el.removeEventListener('scroll', handleScroll);
|
|
2216
|
+
if (scrollTimerRef.current)
|
|
2217
|
+
clearTimeout(scrollTimerRef.current);
|
|
2218
|
+
};
|
|
2219
|
+
}, [isCollapsed, isListMode]);
|
|
2220
|
+
const handleSettingsChange = useCallback((newSettings) => {
|
|
2221
|
+
setSettings(newSettings);
|
|
2222
|
+
setItem(SETTINGS_STORAGE_KEY, newSettings);
|
|
2223
|
+
onSettingsChange?.(newSettings);
|
|
2224
|
+
}, [onSettingsChange]);
|
|
2225
|
+
if (!widgetVisible) {
|
|
2226
|
+
return null;
|
|
2227
|
+
}
|
|
2228
|
+
const handleLinkClick = (e) => {
|
|
2229
|
+
e.preventDefault();
|
|
2230
|
+
const url = e.currentTarget.href;
|
|
2231
|
+
onLinkClick(url);
|
|
2232
|
+
};
|
|
2233
|
+
const handleContentClick = (message, e) => {
|
|
2234
|
+
const target = e.target;
|
|
2235
|
+
if (target.tagName === 'A') {
|
|
2236
|
+
handleLinkClick(e);
|
|
2237
|
+
}
|
|
2238
|
+
else {
|
|
2239
|
+
if (onMessageReceived && !message.received) {
|
|
2240
|
+
onMessageReceived([message.id]);
|
|
2241
|
+
}
|
|
2242
|
+
setModalMessage(message);
|
|
2243
|
+
}
|
|
2244
|
+
};
|
|
2245
|
+
// Get messages for display: widget mode shows all messages for consistent navigation;
|
|
2246
|
+
// list mode prioritises unread messages when available.
|
|
2247
|
+
// Apply showReadMessages setting: when disabled, filter out read messages in list mode.
|
|
2248
|
+
const unreadMessages = messages.filter(msg => !msg.received);
|
|
2249
|
+
const filteredMessages = isListMode && !settings.showReadMessages
|
|
2250
|
+
? unreadMessages
|
|
2251
|
+
: messages;
|
|
2252
|
+
const allMessagesToShow = isListMode
|
|
2253
|
+
? (unreadMessages.length > 0 && settings.showReadMessages ? filteredMessages : (filteredMessages.length > 0 ? filteredMessages : messages))
|
|
2254
|
+
: messages;
|
|
2255
|
+
const displayMessage = currentMessage || (!isCollapsed && allMessagesToShow.length > 0 ? allMessagesToShow[0] : null);
|
|
2256
|
+
const currentMessageIndex = displayMessage
|
|
2257
|
+
? Math.max(0, allMessagesToShow.findIndex((m) => m.id === displayMessage.id))
|
|
2258
|
+
: 0;
|
|
2259
|
+
const canGoPrev = !isListMode && allMessagesToShow.length > 1 && currentMessageIndex > 0;
|
|
2260
|
+
const canGoNext = !isListMode && allMessagesToShow.length > 1 && currentMessageIndex < allMessagesToShow.length - 1;
|
|
2261
|
+
// Extract title from HTML if no title field exists
|
|
2262
|
+
const getMessageTitle = (msg) => {
|
|
2263
|
+
if (!msg)
|
|
2264
|
+
return 'Messages';
|
|
2265
|
+
// Try to extract from HTML (first h1, h2, or h3)
|
|
2266
|
+
const match = msg.message.match(/<h[1-3][^>]*>(.*?)<\/h[1-3]>/i);
|
|
2267
|
+
return match ? match[1].replace(/<[^>]+>/g, '') : 'Messages';
|
|
2268
|
+
};
|
|
2269
|
+
return (React.createElement("div", { ref: widgetRef, className: `journy-message-widget ${!isCollapsed ? 'journy-message-widget-expanded' : 'journy-message-widget-collapsed'} ${isDragging ? 'journy-message-widget-dragging' : ''} ${isResizing ? 'journy-message-widget-resizing' : ''}`, style: {
|
|
2270
|
+
left: `${position.left}px`,
|
|
2271
|
+
top: `${position.top}px`,
|
|
2272
|
+
width: `${currentWidth}px`,
|
|
2273
|
+
height: `${currentHeight}px`,
|
|
2274
|
+
transition: isDragging || isResizing ? 'none' : `height ${TRANSITION_DURATION_S}s ease-out, top ${TRANSITION_DURATION_S}s ease-out`,
|
|
2275
|
+
}, onClick: (e) => {
|
|
2276
|
+
// Don't toggle if this click was right after a drag (avoids expand when releasing drag at bottom edge)
|
|
2277
|
+
if (justFinishedDragging.current) {
|
|
2278
|
+
e.preventDefault();
|
|
2279
|
+
e.stopPropagation();
|
|
2280
|
+
return;
|
|
2281
|
+
}
|
|
2282
|
+
// Toggle on click when collapsed, but not if clicking on buttons, drag handle, or content area
|
|
2283
|
+
if (!isCollapsed)
|
|
2284
|
+
return; // Don't toggle when expanded
|
|
2285
|
+
const target = e.target;
|
|
2286
|
+
const isButton = target.closest('button');
|
|
2287
|
+
const isDragHandle = target.closest('.journy-message-widget-drag-handle');
|
|
2288
|
+
const isLink = target.tagName === 'A' || target.closest('a');
|
|
2289
|
+
// Only toggle when clicking on header (but not buttons, drag handle, or links)
|
|
2290
|
+
if (!isButton && !isDragHandle && !isLink) {
|
|
2291
|
+
onToggleExpand();
|
|
2292
|
+
}
|
|
2293
|
+
} },
|
|
2294
|
+
React.createElement("div", { className: "journy-message-widget-header" },
|
|
2295
|
+
React.createElement(DragHandle, { onMouseDown: handleMouseDown }),
|
|
2296
|
+
React.createElement("div", { className: "journy-message-widget-header-content" }, isCollapsed ? (React.createElement(React.Fragment, null,
|
|
2297
|
+
React.createElement("span", { className: "journy-message-widget-badge" }, unreadCount),
|
|
2298
|
+
React.createElement("span", { className: "journy-message-widget-title" }, unreadCount > 0 ? 'New Messages' : 'Messages'),
|
|
2299
|
+
readCount > 0 && (React.createElement("span", { className: "journy-message-widget-read-count" },
|
|
2300
|
+
"(",
|
|
2301
|
+
readCount,
|
|
2302
|
+
" read)")))) : (React.createElement(React.Fragment, null,
|
|
2303
|
+
unreadCount > 0 && (React.createElement("span", { className: "journy-message-widget-badge" }, unreadCount)),
|
|
2304
|
+
React.createElement("span", { className: "journy-message-widget-title" }, displayMessage ? getMessageTitle(displayMessage) : allMessagesToShow.length > 0 ? getMessageTitle(allMessagesToShow[0]) : 'Messages'),
|
|
2305
|
+
isListMode && allMessagesToShow.length > 1 && (React.createElement("span", { className: "journy-message-widget-message-count" },
|
|
2306
|
+
"(",
|
|
2307
|
+
allMessagesToShow.length,
|
|
2308
|
+
" messages)"))))),
|
|
2309
|
+
React.createElement("div", { className: "journy-message-widget-controls" },
|
|
2310
|
+
!isCollapsed && (React.createElement("button", { className: "journy-message-widget-settings-btn", onClick: (e) => {
|
|
2311
|
+
e.stopPropagation();
|
|
2312
|
+
e.preventDefault();
|
|
2313
|
+
setIsSettingsOpen(true);
|
|
2314
|
+
}, onMouseDown: (e) => e.stopPropagation(), title: "Settings", "aria-label": "Settings" },
|
|
2315
|
+
React.createElement("svg", { width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
|
|
2316
|
+
React.createElement("path", { d: "M6.5 1L6.2 2.6C5.8 2.8 5.5 3 5.2 3.2L3.6 2.7L2.1 5.3L3.4 6.3C3.4 6.5 3.3 6.8 3.3 7C3.3 7.2 3.4 7.5 3.4 7.7L2.1 8.7L3.6 11.3L5.2 10.8C5.5 11 5.8 11.2 6.2 11.4L6.5 13H9.5L9.8 11.4C10.2 11.2 10.5 11 10.8 10.8L12.4 11.3L13.9 8.7L12.6 7.7C12.6 7.5 12.7 7.2 12.7 7C12.7 6.8 12.6 6.5 12.6 6.3L13.9 5.3L12.4 2.7L10.8 3.2C10.5 3 10.2 2.8 9.8 2.6L9.5 1H6.5ZM8 5C9.1 5 10 5.9 10 7C10 8.1 9.1 9 8 9C6.9 9 6 8.1 6 7C6 5.9 6.9 5 8 5Z", fill: "currentColor" })))),
|
|
2317
|
+
React.createElement("button", { className: "journy-message-widget-toggle", onClick: (e) => {
|
|
2318
|
+
e.stopPropagation();
|
|
2319
|
+
e.preventDefault();
|
|
2320
|
+
onToggleExpand();
|
|
2321
|
+
}, onMouseDown: (e) => {
|
|
2322
|
+
e.stopPropagation(); // Prevent drag from starting
|
|
2323
|
+
}, title: !isCollapsed ? 'Collapse' : 'Expand', "aria-label": !isCollapsed ? 'Collapse' : 'Expand' }, !isCollapsed ? '−' : '+'),
|
|
2324
|
+
isCollapsed && (React.createElement("button", { className: "journy-message-widget-close", onClick: (e) => {
|
|
2325
|
+
e.stopPropagation();
|
|
2326
|
+
e.preventDefault();
|
|
2327
|
+
onCloseWidget ? onCloseWidget() : onClose();
|
|
2328
|
+
}, onMouseDown: (e) => {
|
|
2329
|
+
e.stopPropagation();
|
|
2330
|
+
}, title: "Close widget", "aria-label": "Close" }, "\u00D7")),
|
|
2331
|
+
!isCollapsed && isListMode === false && allMessagesToShow.length > 1 && (React.createElement(React.Fragment, null,
|
|
2332
|
+
React.createElement("button", { className: "journy-message-widget-nav", onClick: (e) => {
|
|
2333
|
+
e.stopPropagation();
|
|
2334
|
+
e.preventDefault();
|
|
2335
|
+
onPrevMessage?.();
|
|
2336
|
+
}, onMouseDown: (e) => e.stopPropagation(), title: "Previous message", "aria-label": "Previous", disabled: !canGoPrev }, "\u2039"),
|
|
2337
|
+
React.createElement("button", { className: "journy-message-widget-nav", onClick: (e) => {
|
|
2338
|
+
e.stopPropagation();
|
|
2339
|
+
e.preventDefault();
|
|
2340
|
+
onNextMessage?.();
|
|
2341
|
+
}, onMouseDown: (e) => e.stopPropagation(), title: "Next message", "aria-label": "Next", disabled: !canGoNext }, "\u203A"))))),
|
|
2342
|
+
!isCollapsed && allMessagesToShow.length > 0 && (React.createElement(React.Fragment, null,
|
|
2343
|
+
React.createElement("div", { ref: contentRef, className: `journy-message-widget-content ${!isListMode ? 'journy-message-widget-content--single' : ''}` }, isListMode ? (allMessagesToShow.map((message, index) => (React.createElement(MessageRow, { key: message.id, message: message, isSeparated: index < allMessagesToShow.length - 1, onMessageReceived: onMessageReceived, onDismissMessage: onDismissMessage },
|
|
2344
|
+
React.createElement("div", { className: "journy-message-content journy-message-content-clickable", dangerouslySetInnerHTML: { __html: sanitizeHtml(message.message) }, onClick: (e) => handleContentClick(message, e) }),
|
|
2345
|
+
message.createdAt && (React.createElement("div", { className: "journy-message-timestamp" }, formatTimestamp(message.createdAt))))))) : displayMessage ? (React.createElement(MessageRow, { message: displayMessage, isSeparated: false, onMessageReceived: onMessageReceived, onDismissMessage: onDismissMessage },
|
|
2346
|
+
React.createElement("div", { className: "journy-message-content journy-message-content-clickable", dangerouslySetInnerHTML: { __html: sanitizeHtml(displayMessage.message) }, onClick: (e) => handleContentClick(displayMessage, e) }),
|
|
2347
|
+
displayMessage.createdAt && (React.createElement("div", { className: "journy-message-timestamp" }, formatTimestamp(displayMessage.createdAt))))) : null),
|
|
2348
|
+
!isListMode && allMessagesToShow.length > 1 && (React.createElement("div", { className: "journy-message-widget-position" },
|
|
2349
|
+
currentMessageIndex + 1,
|
|
2350
|
+
" / ",
|
|
2351
|
+
allMessagesToShow.length)),
|
|
2352
|
+
isListMode && React.createElement(ResizeHandle, { onMouseDown: handleResizeStart }))),
|
|
2353
|
+
!isCollapsed && allMessagesToShow.length === 0 && (React.createElement(React.Fragment, null,
|
|
2354
|
+
React.createElement("div", { className: "journy-message-widget-content journy-message-widget-empty" },
|
|
2355
|
+
React.createElement("p", null, "No unread messages")),
|
|
2356
|
+
isListMode && React.createElement(ResizeHandle, { onMouseDown: handleResizeStart }))),
|
|
2357
|
+
!isCollapsed && (React.createElement(SettingsPanel, { isOpen: isSettingsOpen, onClose: () => setIsSettingsOpen(false), settings: settings, onSettingsChange: handleSettingsChange, configInfo: configInfo })),
|
|
2358
|
+
modalMessage && (React.createElement(MessagePopup, { message: modalMessage, onClose: () => setModalMessage(null), onLinkClick: onLinkClick }))));
|
|
2359
|
+
};
|
|
2360
|
+
|
|
2361
|
+
var MessageWidgetModule = /*#__PURE__*/Object.freeze({
|
|
2362
|
+
__proto__: null,
|
|
2363
|
+
MessageWidget: MessageWidget,
|
|
2364
|
+
default: MessageWidget
|
|
2365
|
+
});
|
|
2366
|
+
|
|
2367
|
+
/**
|
|
2368
|
+
* Builds a generic track batch item for any SDK event type.
|
|
2369
|
+
*/
|
|
2370
|
+
function buildTrackEventPayload(scope, identity, event, properties) {
|
|
2371
|
+
const base = {
|
|
2372
|
+
type: "track",
|
|
2373
|
+
event: event,
|
|
2374
|
+
properties,
|
|
2375
|
+
};
|
|
2376
|
+
if (scope === "account" && identity.accountId) {
|
|
2377
|
+
return {
|
|
2378
|
+
...base,
|
|
2379
|
+
anonymousId: identity.accountId,
|
|
2380
|
+
context: { groupId: identity.accountId },
|
|
2381
|
+
};
|
|
2382
|
+
}
|
|
2383
|
+
if (identity.userId) {
|
|
2384
|
+
return { ...base, userId: identity.userId };
|
|
2385
|
+
}
|
|
2386
|
+
if (identity.anonymousId) {
|
|
2387
|
+
return { ...base, anonymousId: identity.anonymousId };
|
|
2388
|
+
}
|
|
2389
|
+
throw new Error("User scope requires userId or anonymousId; account scope requires accountId.");
|
|
2390
|
+
}
|
|
2391
|
+
|
|
2392
|
+
const SEND_ANALYTICS_PATH = "/frontend/v1/b";
|
|
2393
|
+
class AnalyticsClient {
|
|
2394
|
+
constructor(config) {
|
|
2395
|
+
this.config = config;
|
|
2396
|
+
this.analyticsHost = config.apiEndpoint || "https://jtm.journy.io";
|
|
2397
|
+
}
|
|
2398
|
+
get trackIdentity() {
|
|
2399
|
+
return {
|
|
2400
|
+
userId: this.config.userId,
|
|
2401
|
+
accountId: this.config.accountId,
|
|
2402
|
+
};
|
|
2403
|
+
}
|
|
2404
|
+
/**
|
|
2405
|
+
* General-purpose method: send an array of SDK events in a single batch.
|
|
2406
|
+
*/
|
|
2407
|
+
async trackEvents(events) {
|
|
2408
|
+
if (events.length === 0)
|
|
2409
|
+
return true;
|
|
2410
|
+
const batch = events.map(({ event, properties }) => buildTrackEventPayload(this.config.entityType, this.trackIdentity, event, properties));
|
|
2411
|
+
await fetch(this.analyticsHost + SEND_ANALYTICS_PATH, {
|
|
2412
|
+
method: "POST",
|
|
2413
|
+
headers: { "Content-Type": "application/json" },
|
|
2414
|
+
body: JSON.stringify({ writeKey: this.config.writeKey, batch }),
|
|
2415
|
+
});
|
|
2416
|
+
return true;
|
|
2417
|
+
}
|
|
2418
|
+
/**
|
|
2419
|
+
* Convenience method for "message received" events. Calls trackEvents internally.
|
|
2420
|
+
*/
|
|
2421
|
+
async sendAnalyticsEvents(messageIds) {
|
|
2422
|
+
return this.trackEvents(messageIds.map(messageId => ({
|
|
2423
|
+
event: SDKEventType.MessageReceived,
|
|
2424
|
+
properties: { messageId },
|
|
2425
|
+
})));
|
|
2426
|
+
}
|
|
2427
|
+
}
|
|
2428
|
+
|
|
2429
|
+
const DEFAULT_API_ENDPOINT = 'https://jtm.journy.io';
|
|
2430
|
+
const DEFAULT_POLLING_INTERVAL = 30000;
|
|
2431
|
+
const ROOT_ELEMENT_ID = 'journy-messages-root';
|
|
2432
|
+
const DEFAULT_STYLE_ID = 'journy-messages-default';
|
|
2433
|
+
const REACT_CHECK_INTERVAL = 100;
|
|
2434
|
+
const REACT_WAIT_TIMEOUT = 10000;
|
|
2435
|
+
const MESSAGE_CLOSE_DELAY = 300;
|
|
2436
|
+
const STORAGE_KEYS = {
|
|
2437
|
+
WIDGET_SETTINGS: 'widget_settings',
|
|
2438
|
+
WIDGET_VISIBLE: 'widget_visible',
|
|
2439
|
+
WIDGET_COLLAPSED: 'widget_collapsed',
|
|
2440
|
+
CURRENT_MESSAGE_ID: 'current_message_id',
|
|
2441
|
+
};
|
|
2442
|
+
class JournyMessaging {
|
|
2443
|
+
constructor(config) {
|
|
2444
|
+
this.initialized = false;
|
|
2445
|
+
this.pollingInterval = null;
|
|
2446
|
+
this.reactRoot = null;
|
|
2447
|
+
this.reactRootContainer = null;
|
|
2448
|
+
this.rootElementId = ROOT_ELEMENT_ID;
|
|
2449
|
+
this.unsubscribePersistence = null;
|
|
2450
|
+
this.config = {
|
|
2451
|
+
apiEndpoint: DEFAULT_API_ENDPOINT,
|
|
2452
|
+
pollingInterval: DEFAULT_POLLING_INTERVAL,
|
|
2453
|
+
...config,
|
|
2454
|
+
};
|
|
2455
|
+
if (!this.config.writeKey) {
|
|
2456
|
+
throw new Error('writeKey is required');
|
|
2457
|
+
}
|
|
2458
|
+
if (!this.config.entityType) {
|
|
2459
|
+
throw new Error('entityType is required');
|
|
2460
|
+
}
|
|
2461
|
+
this.apiClient = new ApiClient(this.config);
|
|
2462
|
+
this.messageQueue = new MessageQueue();
|
|
2463
|
+
this.analyticsClient = new AnalyticsClient(this.config);
|
|
2464
|
+
this.eventTracker = new EventTracker(this.analyticsClient);
|
|
2465
|
+
// Build default settings from config, then overlay any saved settings
|
|
2466
|
+
const configDefaults = {
|
|
2467
|
+
...DEFAULT_WIDGET_SETTINGS,
|
|
2468
|
+
pollingInterval: this.config.pollingInterval || DEFAULT_WIDGET_SETTINGS.pollingInterval,
|
|
2469
|
+
displayMode: this.config.displayMode || DEFAULT_WIDGET_SETTINGS.displayMode,
|
|
2470
|
+
apiEndpoint: this.config.apiEndpoint || DEFAULT_WIDGET_SETTINGS.apiEndpoint,
|
|
2471
|
+
styles: this.config.styles || DEFAULT_WIDGET_SETTINGS.styles,
|
|
2472
|
+
};
|
|
2473
|
+
const savedSettings = getItem(STORAGE_KEYS.WIDGET_SETTINGS);
|
|
2474
|
+
this.widgetSettings = savedSettings
|
|
2475
|
+
? { ...configDefaults, ...savedSettings }
|
|
2476
|
+
: configDefaults;
|
|
2477
|
+
// Apply settings back to config so they take effect
|
|
2478
|
+
this.config.pollingInterval = this.widgetSettings.pollingInterval;
|
|
2479
|
+
this.config.apiEndpoint = this.widgetSettings.apiEndpoint;
|
|
2480
|
+
this.config.displayMode = this.widgetSettings.displayMode;
|
|
2481
|
+
const savedVisible = getItem(STORAGE_KEYS.WIDGET_VISIBLE);
|
|
2482
|
+
const savedCollapsed = getItem(STORAGE_KEYS.WIDGET_COLLAPSED);
|
|
2483
|
+
this.store = new MessagingStore({
|
|
2484
|
+
messages: [],
|
|
2485
|
+
currentMessage: null,
|
|
2486
|
+
isCollapsed: savedCollapsed ?? this.config.isCollapsed ?? true,
|
|
2487
|
+
widgetVisible: savedVisible ?? true,
|
|
2488
|
+
displayMode: this.widgetSettings.displayMode,
|
|
2489
|
+
});
|
|
2490
|
+
this.unsubscribePersistence = this.store.subscribe(() => {
|
|
2491
|
+
const state = this.store.getState();
|
|
2492
|
+
setItem(STORAGE_KEYS.WIDGET_VISIBLE, state.widgetVisible);
|
|
2493
|
+
setItem(STORAGE_KEYS.WIDGET_COLLAPSED, state.isCollapsed);
|
|
2494
|
+
if (state.currentMessage) {
|
|
2495
|
+
setItem(STORAGE_KEYS.CURRENT_MESSAGE_ID, state.currentMessage.id);
|
|
2496
|
+
}
|
|
2497
|
+
else {
|
|
2498
|
+
removeItem(STORAGE_KEYS.CURRENT_MESSAGE_ID);
|
|
2499
|
+
}
|
|
2500
|
+
});
|
|
2501
|
+
this.init();
|
|
2502
|
+
}
|
|
2503
|
+
get uiState() {
|
|
2504
|
+
return this.store.getState();
|
|
2505
|
+
}
|
|
2506
|
+
async init() {
|
|
2507
|
+
if (this.initialized)
|
|
2508
|
+
return;
|
|
2509
|
+
// Load existing messages
|
|
2510
|
+
await this.loadMessages();
|
|
2511
|
+
// Set up polling or WebSocket connection
|
|
2512
|
+
this.startPolling();
|
|
2513
|
+
// Initialize UI
|
|
2514
|
+
this.initializeUI();
|
|
2515
|
+
this.initialized = true;
|
|
2516
|
+
}
|
|
2517
|
+
async loadMessages() {
|
|
2518
|
+
try {
|
|
2519
|
+
const messages = await this.apiClient.getUnreadMessages();
|
|
2520
|
+
const previousActiveCount = this.messageQueue.getActiveCount();
|
|
2521
|
+
this.messageQueue.addMessages(messages);
|
|
2522
|
+
const newActiveCount = this.messageQueue.getActiveCount();
|
|
2523
|
+
let updates = {
|
|
2524
|
+
messages: this.messageQueue.getAllMessages(),
|
|
2525
|
+
};
|
|
2526
|
+
if (newActiveCount > previousActiveCount) {
|
|
2527
|
+
updates.widgetVisible = true;
|
|
2528
|
+
if (this.widgetSettings.autoExpandOnNew) {
|
|
2529
|
+
updates.isCollapsed = false;
|
|
2530
|
+
}
|
|
2531
|
+
}
|
|
2532
|
+
this.store.setState(updates);
|
|
2533
|
+
if (!this.uiState.currentMessage && newActiveCount > 0) {
|
|
2534
|
+
const savedMessageId = getItem(STORAGE_KEYS.CURRENT_MESSAGE_ID);
|
|
2535
|
+
const allMessages = this.messageQueue.getAllMessages();
|
|
2536
|
+
const savedMessage = savedMessageId ? allMessages.find(m => m.id === savedMessageId) : null;
|
|
2537
|
+
if (savedMessage) {
|
|
2538
|
+
this.store.setState({ currentMessage: savedMessage });
|
|
2539
|
+
}
|
|
2540
|
+
else {
|
|
2541
|
+
this.displayNextMessage();
|
|
2542
|
+
}
|
|
2543
|
+
}
|
|
2544
|
+
// Auto-mark current message as received when widget is expanded
|
|
2545
|
+
if (!this.uiState.isCollapsed && this.uiState.currentMessage && !this.uiState.currentMessage.received) {
|
|
2546
|
+
this.handleMessageReceived([this.uiState.currentMessage.id]);
|
|
2547
|
+
}
|
|
2548
|
+
}
|
|
2549
|
+
catch (error) {
|
|
2550
|
+
console.error('Failed to load messages:', error);
|
|
2551
|
+
}
|
|
2552
|
+
}
|
|
2553
|
+
startPolling() {
|
|
2554
|
+
if (this.pollingInterval !== null) {
|
|
2555
|
+
clearInterval(this.pollingInterval);
|
|
2556
|
+
}
|
|
2557
|
+
this.pollingInterval = window.setInterval(() => {
|
|
2558
|
+
this.loadMessages();
|
|
2559
|
+
}, this.config.pollingInterval || DEFAULT_POLLING_INTERVAL);
|
|
2560
|
+
}
|
|
2561
|
+
applyStyles(stylesConfig) {
|
|
2562
|
+
removeInjectedStyles();
|
|
2563
|
+
if (stylesConfig === 'none') ;
|
|
2564
|
+
else if (stylesConfig && stylesConfig !== 'default') {
|
|
2565
|
+
if ('url' in stylesConfig && stylesConfig.url) {
|
|
2566
|
+
injectStyleLink(stylesConfig.url);
|
|
2567
|
+
}
|
|
2568
|
+
else if ('css' in stylesConfig && stylesConfig.css) {
|
|
2569
|
+
injectStyleTag(stylesConfig.css);
|
|
2570
|
+
}
|
|
2571
|
+
}
|
|
2572
|
+
else {
|
|
2573
|
+
injectStyleTag(defaultStyles, DEFAULT_STYLE_ID);
|
|
2574
|
+
}
|
|
2575
|
+
}
|
|
2576
|
+
initializeUI() {
|
|
2577
|
+
// Create root element for React
|
|
2578
|
+
const rootElement = createRootElement(this.rootElementId);
|
|
2579
|
+
this.applyStyles(this.widgetSettings.styles);
|
|
2580
|
+
// Always render UI (even if no messages) so widget can show/hide itself
|
|
2581
|
+
// Dynamically import React and render component
|
|
2582
|
+
// This will be handled when React is available
|
|
2583
|
+
if (typeof window !== 'undefined' && window.React && window.ReactDOM) {
|
|
2584
|
+
this.renderUI(rootElement);
|
|
2585
|
+
}
|
|
2586
|
+
else {
|
|
2587
|
+
this.waitForReact(rootElement);
|
|
2588
|
+
}
|
|
2589
|
+
}
|
|
2590
|
+
waitForReact(rootElement) {
|
|
2591
|
+
const checkInterval = setInterval(() => {
|
|
2592
|
+
if (typeof window !== 'undefined' && window.React && window.ReactDOM) {
|
|
2593
|
+
clearInterval(checkInterval);
|
|
2594
|
+
this.renderUI(rootElement);
|
|
2595
|
+
}
|
|
2596
|
+
}, REACT_CHECK_INTERVAL);
|
|
2597
|
+
setTimeout(() => {
|
|
2598
|
+
clearInterval(checkInterval);
|
|
2599
|
+
}, REACT_WAIT_TIMEOUT);
|
|
2600
|
+
}
|
|
2601
|
+
renderUI(rootElement) {
|
|
2602
|
+
try {
|
|
2603
|
+
const React = window.React;
|
|
2604
|
+
const ReactDOM = window.ReactDOM;
|
|
2605
|
+
if (!React || !ReactDOM) {
|
|
2606
|
+
throw new Error('React or ReactDOM not found in window');
|
|
2607
|
+
}
|
|
2608
|
+
// If the container was replaced (e.g. root removed and re-created), create a new React root
|
|
2609
|
+
if (this.reactRoot && this.reactRootContainer !== rootElement) {
|
|
2610
|
+
this.reactRoot = null;
|
|
2611
|
+
this.reactRootContainer = null;
|
|
2612
|
+
}
|
|
2613
|
+
// Access MessageWidget from the statically imported module
|
|
2614
|
+
const MessageWidget$1 = MessageWidget || MessageWidget;
|
|
2615
|
+
if (!MessageWidget$1) {
|
|
2616
|
+
console.error('MessageWidget not found in module:', MessageWidgetModule);
|
|
2617
|
+
throw new Error('MessageWidget not found in module');
|
|
2618
|
+
}
|
|
2619
|
+
const props = {
|
|
2620
|
+
store: this.store,
|
|
2621
|
+
onClose: () => this.handleMessageClose(),
|
|
2622
|
+
onCloseWidget: () => this.handleCloseWidget(),
|
|
2623
|
+
onLinkClick: (url) => this.handleLinkClick(url),
|
|
2624
|
+
onToggleExpand: () => this.handleToggleExpand(),
|
|
2625
|
+
onMessageReceived: (messageIds) => this.handleMessageReceived(messageIds),
|
|
2626
|
+
onDismissMessage: (messageId) => this.handleDismissMessage(messageId),
|
|
2627
|
+
onNextMessage: () => this.handleNextMessage(),
|
|
2628
|
+
onPrevMessage: () => this.handlePrevMessage(),
|
|
2629
|
+
onSettingsChange: (settings) => this.handleSettingsChange(settings),
|
|
2630
|
+
configInfo: {
|
|
2631
|
+
entityType: this.config.entityType,
|
|
2632
|
+
userId: this.config.userId,
|
|
2633
|
+
accountId: this.config.accountId,
|
|
2634
|
+
},
|
|
2635
|
+
};
|
|
2636
|
+
const element = React.createElement(MessageWidget$1, props);
|
|
2637
|
+
// Use React 18 createRoot if available, otherwise fall back to render
|
|
2638
|
+
if (ReactDOM.createRoot) {
|
|
2639
|
+
if (!this.reactRoot) {
|
|
2640
|
+
rootElement.innerHTML = '';
|
|
2641
|
+
this.reactRoot = ReactDOM.createRoot(rootElement);
|
|
2642
|
+
this.reactRootContainer = rootElement;
|
|
2643
|
+
}
|
|
2644
|
+
this.reactRoot.render(element);
|
|
2645
|
+
}
|
|
2646
|
+
else {
|
|
2647
|
+
rootElement.innerHTML = '';
|
|
2648
|
+
ReactDOM.render(element, rootElement);
|
|
2649
|
+
}
|
|
2650
|
+
}
|
|
2651
|
+
catch (error) {
|
|
2652
|
+
console.error('Failed to render UI:', error);
|
|
2653
|
+
}
|
|
2654
|
+
}
|
|
2655
|
+
handleSettingsChange(newSettings) {
|
|
2656
|
+
const prev = this.widgetSettings;
|
|
2657
|
+
this.widgetSettings = newSettings;
|
|
2658
|
+
setItem(STORAGE_KEYS.WIDGET_SETTINGS, newSettings);
|
|
2659
|
+
// Sync config
|
|
2660
|
+
this.config.pollingInterval = newSettings.pollingInterval;
|
|
2661
|
+
this.config.apiEndpoint = newSettings.apiEndpoint;
|
|
2662
|
+
// Restart polling if interval changed
|
|
2663
|
+
if (newSettings.pollingInterval !== prev.pollingInterval) {
|
|
2664
|
+
this.startPolling();
|
|
2665
|
+
}
|
|
2666
|
+
// Switch display mode
|
|
2667
|
+
if (newSettings.displayMode !== prev.displayMode) {
|
|
2668
|
+
this.store.setState({ displayMode: newSettings.displayMode });
|
|
2669
|
+
}
|
|
2670
|
+
// Re-apply styles if changed
|
|
2671
|
+
if (JSON.stringify(newSettings.styles) !== JSON.stringify(prev.styles)) {
|
|
2672
|
+
this.applyStyles(newSettings.styles);
|
|
2673
|
+
}
|
|
2674
|
+
// Rebuild API client if endpoint or proxy changed
|
|
2675
|
+
if (newSettings.apiEndpoint !== prev.apiEndpoint) {
|
|
2676
|
+
this.apiClient = new ApiClient(this.config);
|
|
2677
|
+
}
|
|
2678
|
+
}
|
|
2679
|
+
handleToggleExpand() {
|
|
2680
|
+
this.store.setState({ isCollapsed: !this.uiState.isCollapsed });
|
|
2681
|
+
}
|
|
2682
|
+
displayNextMessage() {
|
|
2683
|
+
const nextMessage = this.messageQueue.getNextMessage();
|
|
2684
|
+
if (nextMessage && nextMessage.id !== this.uiState.currentMessage?.id) {
|
|
2685
|
+
this.showMessage(nextMessage);
|
|
2686
|
+
return;
|
|
2687
|
+
}
|
|
2688
|
+
this.store.setState({
|
|
2689
|
+
currentMessage: nextMessage || null,
|
|
2690
|
+
messages: this.messageQueue.getAllMessages(),
|
|
2691
|
+
});
|
|
2692
|
+
}
|
|
2693
|
+
showMessage(message) {
|
|
2694
|
+
this.store.setState({
|
|
2695
|
+
currentMessage: message,
|
|
2696
|
+
messages: this.messageQueue.getAllMessages(),
|
|
2697
|
+
});
|
|
2698
|
+
this.eventTracker.track(SDKEventType.MessageOpened, {
|
|
2699
|
+
messageId: message.id,
|
|
2700
|
+
});
|
|
2701
|
+
}
|
|
2702
|
+
handleMessageClose() {
|
|
2703
|
+
const { currentMessage } = this.uiState;
|
|
2704
|
+
if (currentMessage) {
|
|
2705
|
+
this.eventTracker.track(SDKEventType.MessageClosed, {
|
|
2706
|
+
messageId: currentMessage.id,
|
|
2707
|
+
});
|
|
2708
|
+
this.markAsRead([currentMessage.id]);
|
|
2709
|
+
this.store.setState({ currentMessage: null, isCollapsed: false });
|
|
2710
|
+
setTimeout(() => {
|
|
2711
|
+
this.displayNextMessage();
|
|
2712
|
+
}, MESSAGE_CLOSE_DELAY);
|
|
2713
|
+
}
|
|
2714
|
+
}
|
|
2715
|
+
handleCloseWidget() {
|
|
2716
|
+
this.store.setState({ widgetVisible: false });
|
|
2717
|
+
}
|
|
2718
|
+
async handleDismissMessage(messageId) {
|
|
2719
|
+
this.eventTracker.track(SDKEventType.MessageClosed, { messageId });
|
|
2720
|
+
await this.markAsRead([messageId]);
|
|
2721
|
+
if (this.uiState.currentMessage?.id === messageId) {
|
|
2722
|
+
this.store.setState({ currentMessage: null });
|
|
2723
|
+
this.displayNextMessage();
|
|
2724
|
+
}
|
|
2725
|
+
}
|
|
2726
|
+
navigateMessage(direction) {
|
|
2727
|
+
const list = this.messageQueue.getAllMessages();
|
|
2728
|
+
const idx = list.findIndex((m) => m.id === this.uiState.currentMessage?.id);
|
|
2729
|
+
const targetIdx = idx + direction;
|
|
2730
|
+
if (targetIdx < 0 || targetIdx >= list.length)
|
|
2731
|
+
return;
|
|
2732
|
+
const targetMessage = list[targetIdx];
|
|
2733
|
+
if (!targetMessage.received) {
|
|
2734
|
+
this.store.setState({ currentMessage: targetMessage });
|
|
2735
|
+
this.handleMessageReceived([targetMessage.id]);
|
|
2736
|
+
}
|
|
2737
|
+
else {
|
|
2738
|
+
this.store.setState({ currentMessage: targetMessage });
|
|
2739
|
+
}
|
|
2740
|
+
}
|
|
2741
|
+
handleNextMessage() {
|
|
2742
|
+
this.navigateMessage(1);
|
|
2743
|
+
}
|
|
2744
|
+
handlePrevMessage() {
|
|
2745
|
+
this.navigateMessage(-1);
|
|
2746
|
+
}
|
|
2747
|
+
handleLinkClick(url) {
|
|
2748
|
+
const { currentMessage } = this.uiState;
|
|
2749
|
+
if (currentMessage) {
|
|
2750
|
+
this.eventTracker.track(SDKEventType.MessageLinkClicked, {
|
|
2751
|
+
messageId: currentMessage.id,
|
|
2752
|
+
linkUrl: url,
|
|
2753
|
+
});
|
|
2754
|
+
}
|
|
2755
|
+
}
|
|
2756
|
+
async markAsRead(messageIds) {
|
|
2757
|
+
const ids = Array.isArray(messageIds) ? messageIds : [messageIds];
|
|
2758
|
+
await this.handleMessageReceived(ids);
|
|
2759
|
+
this.messageQueue.removeMessage(ids);
|
|
2760
|
+
this.store.setState({ messages: this.messageQueue.getAllMessages() });
|
|
2761
|
+
}
|
|
2762
|
+
async handleMessageReceived(messageIds) {
|
|
2763
|
+
const ids = (Array.isArray(messageIds) ? messageIds : [messageIds]);
|
|
2764
|
+
const alreadyReceivedIds = this.messageQueue.getAlreadyReceivedIds(ids);
|
|
2765
|
+
if (alreadyReceivedIds.length === ids.length)
|
|
2766
|
+
return;
|
|
2767
|
+
// Track locally first to prevent duplicate sends
|
|
2768
|
+
this.messageQueue.markMessageAsReceived(ids);
|
|
2769
|
+
// Update currentMessage so re-render reflects received status immediately
|
|
2770
|
+
const { currentMessage } = this.uiState;
|
|
2771
|
+
const updates = {
|
|
2772
|
+
messages: this.messageQueue.getAllMessages(),
|
|
2773
|
+
};
|
|
2774
|
+
if (currentMessage && ids.includes(currentMessage.id)) {
|
|
2775
|
+
updates.currentMessage = { ...currentMessage, received: true };
|
|
2776
|
+
}
|
|
2777
|
+
this.store.setState(updates);
|
|
2778
|
+
await this.apiClient.markAsRead(ids);
|
|
2779
|
+
await this.analyticsClient.sendAnalyticsEvents(ids);
|
|
2780
|
+
}
|
|
2781
|
+
/** Track a link click event for analytics. Called by host apps when a user clicks a link inside a message. */
|
|
2782
|
+
trackLinkClick(messageId, linkUrl) {
|
|
2783
|
+
this.eventTracker.track(SDKEventType.MessageLinkClicked, {
|
|
2784
|
+
messageId,
|
|
2785
|
+
linkUrl,
|
|
2786
|
+
});
|
|
2787
|
+
}
|
|
2788
|
+
/** Track a message closed event. Called by host apps when a user dismisses a message. */
|
|
2789
|
+
trackMessageClosed(messageId) {
|
|
2790
|
+
this.eventTracker.track(SDKEventType.MessageClosed, {
|
|
2791
|
+
messageId,
|
|
2792
|
+
});
|
|
2793
|
+
}
|
|
2794
|
+
/** Track a message opened event. Called by host apps when a user views a message. */
|
|
2795
|
+
trackMessageOpened(messageId) {
|
|
2796
|
+
this.eventTracker.track(SDKEventType.MessageOpened, {
|
|
2797
|
+
messageId,
|
|
2798
|
+
});
|
|
2799
|
+
}
|
|
2800
|
+
destroy() {
|
|
2801
|
+
if (this.pollingInterval !== null) {
|
|
2802
|
+
clearInterval(this.pollingInterval);
|
|
2803
|
+
this.pollingInterval = null;
|
|
2804
|
+
}
|
|
2805
|
+
if (this.unsubscribePersistence) {
|
|
2806
|
+
this.unsubscribePersistence();
|
|
2807
|
+
this.unsubscribePersistence = null;
|
|
2808
|
+
}
|
|
2809
|
+
this.eventTracker.destroy();
|
|
2810
|
+
this.store.destroy();
|
|
2811
|
+
// Unmount React root before removing element
|
|
2812
|
+
if (this.reactRoot) {
|
|
2813
|
+
try {
|
|
2814
|
+
this.reactRoot.unmount();
|
|
2815
|
+
}
|
|
2816
|
+
catch (error) {
|
|
2817
|
+
console.error('Error unmounting React root:', error);
|
|
2818
|
+
}
|
|
2819
|
+
this.reactRoot = null;
|
|
2820
|
+
this.reactRootContainer = null;
|
|
2821
|
+
}
|
|
2822
|
+
removeRootElement(this.rootElementId);
|
|
2823
|
+
removeInjectedStyles();
|
|
2824
|
+
}
|
|
2825
|
+
}
|
|
2826
|
+
|
|
2827
|
+
// For UMD/global usage
|
|
2828
|
+
if (typeof window !== 'undefined') {
|
|
2829
|
+
window.JournyMessages = JournyMessaging;
|
|
2830
|
+
}
|
|
2831
|
+
|
|
2832
|
+
export { JournyMessaging, JournyMessaging as default };
|
|
2833
|
+
//# sourceMappingURL=journy-messages.esm.js.map
|