single-file-core 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.
@@ -0,0 +1,418 @@
1
+ /*
2
+ * Copyright 2010-2020 Gildas Lormeau
3
+ * contact : gildas.lormeau <at> gmail.com
4
+ *
5
+ * This file is part of SingleFile.
6
+ *
7
+ * The code in this file is free software: you can redistribute it and/or
8
+ * modify it under the terms of the GNU Affero General Public License
9
+ * (GNU AGPL) as published by the Free Software Foundation, either version 3
10
+ * of the License, or (at your option) any later version.
11
+ *
12
+ * The code in this file is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
15
+ * General Public License for more details.
16
+ *
17
+ * As additional permission under GNU AGPL version 3 section 7, you may
18
+ * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
19
+ * AGPL normally required by section 4, provided you include this license
20
+ * notice and a URL through which recipients can access the Corresponding
21
+ * Source.
22
+ */
23
+
24
+ /* global globalThis */
25
+
26
+ import * as lazy from "./../../lazy/content/content-lazy-loader.js";
27
+ import {
28
+ ON_BEFORE_CAPTURE_EVENT_NAME,
29
+ ON_AFTER_CAPTURE_EVENT_NAME,
30
+ WIN_ID_ATTRIBUTE_NAME,
31
+ preProcessDoc,
32
+ serialize,
33
+ postProcessDoc,
34
+ getShadowRoot
35
+ } from "./../../../single-file-helper.js";
36
+
37
+ const helper = {
38
+ ON_BEFORE_CAPTURE_EVENT_NAME,
39
+ ON_AFTER_CAPTURE_EVENT_NAME,
40
+ WIN_ID_ATTRIBUTE_NAME,
41
+ preProcessDoc,
42
+ serialize,
43
+ postProcessDoc,
44
+ getShadowRoot
45
+ };
46
+
47
+ const MESSAGE_PREFIX = "__frameTree__::";
48
+ const FRAMES_CSS_SELECTOR = "iframe, frame, object[type=\"text/html\"][data]";
49
+ const ALL_ELEMENTS_CSS_SELECTOR = "*";
50
+ const INIT_REQUEST_MESSAGE = "singlefile.frameTree.initRequest";
51
+ const ACK_INIT_REQUEST_MESSAGE = "singlefile.frameTree.ackInitRequest";
52
+ const CLEANUP_REQUEST_MESSAGE = "singlefile.frameTree.cleanupRequest";
53
+ const INIT_RESPONSE_MESSAGE = "singlefile.frameTree.initResponse";
54
+ const TARGET_ORIGIN = "*";
55
+ const TIMEOUT_INIT_REQUEST_MESSAGE = 5000;
56
+ const TIMEOUT_INIT_RESPONSE_MESSAGE = 10000;
57
+ const TOP_WINDOW_ID = "0";
58
+ const WINDOW_ID_SEPARATOR = ".";
59
+ const TOP_WINDOW = globalThis.window == globalThis.top;
60
+
61
+ const browser = globalThis.browser;
62
+ const addEventListener = (type, listener, options) => globalThis.addEventListener(type, listener, options);
63
+ const top = globalThis.top;
64
+ const MessageChannel = globalThis.MessageChannel;
65
+ const document = globalThis.document;
66
+
67
+ let sessions = globalThis.sessions;
68
+ if (!sessions) {
69
+ sessions = globalThis.sessions = new Map();
70
+ }
71
+ let windowId;
72
+ if (TOP_WINDOW) {
73
+ windowId = TOP_WINDOW_ID;
74
+ if (browser && browser.runtime && browser.runtime.onMessage && browser.runtime.onMessage.addListener) {
75
+ browser.runtime.onMessage.addListener(message => {
76
+ if (message.method == INIT_RESPONSE_MESSAGE) {
77
+ initResponse(message);
78
+ return Promise.resolve({});
79
+ } else if (message.method == ACK_INIT_REQUEST_MESSAGE) {
80
+ clearFrameTimeout("requestTimeouts", message.sessionId, message.windowId);
81
+ createFrameResponseTimeout(message.sessionId, message.windowId);
82
+ return Promise.resolve({});
83
+ }
84
+ });
85
+ }
86
+ }
87
+ addEventListener("message", async event => {
88
+ if (typeof event.data == "string" && event.data.startsWith(MESSAGE_PREFIX)) {
89
+ event.preventDefault();
90
+ event.stopPropagation();
91
+ const message = JSON.parse(event.data.substring(MESSAGE_PREFIX.length));
92
+ if (message.method == INIT_REQUEST_MESSAGE) {
93
+ if (event.source) {
94
+ sendMessage(event.source, { method: ACK_INIT_REQUEST_MESSAGE, windowId: message.windowId, sessionId: message.sessionId });
95
+ }
96
+ if (!TOP_WINDOW) {
97
+ globalThis.stop();
98
+ if (message.options.loadDeferredImages) {
99
+ lazy.process(message.options);
100
+ }
101
+ await initRequestAsync(message);
102
+ }
103
+ } else if (message.method == ACK_INIT_REQUEST_MESSAGE) {
104
+ clearFrameTimeout("requestTimeouts", message.sessionId, message.windowId);
105
+ createFrameResponseTimeout(message.sessionId, message.windowId);
106
+ } else if (message.method == CLEANUP_REQUEST_MESSAGE) {
107
+ cleanupRequest(message);
108
+ } else if (message.method == INIT_RESPONSE_MESSAGE && sessions.get(message.sessionId)) {
109
+ const port = event.ports[0];
110
+ port.onmessage = event => initResponse(event.data);
111
+ }
112
+ }
113
+ }, true);
114
+
115
+ export {
116
+ getAsync,
117
+ getSync,
118
+ cleanup,
119
+ initResponse,
120
+ TIMEOUT_INIT_REQUEST_MESSAGE
121
+ };
122
+
123
+ function getAsync(options) {
124
+ const sessionId = getNewSessionId();
125
+ options = JSON.parse(JSON.stringify(options));
126
+ return new Promise(resolve => {
127
+ sessions.set(sessionId, {
128
+ frames: [],
129
+ requestTimeouts: {},
130
+ responseTimeouts: {},
131
+ resolve: frames => {
132
+ frames.sessionId = sessionId;
133
+ resolve(frames);
134
+ }
135
+ });
136
+ initRequestAsync({ windowId, sessionId, options });
137
+ });
138
+ }
139
+
140
+ function getSync(options) {
141
+ const sessionId = getNewSessionId();
142
+ options = JSON.parse(JSON.stringify(options));
143
+ sessions.set(sessionId, {
144
+ frames: [],
145
+ requestTimeouts: {},
146
+ responseTimeouts: {}
147
+ });
148
+ initRequestSync({ windowId, sessionId, options });
149
+ const frames = sessions.get(sessionId).frames;
150
+ frames.sessionId = sessionId;
151
+ return frames;
152
+ }
153
+
154
+ function cleanup(sessionId) {
155
+ sessions.delete(sessionId);
156
+ cleanupRequest({ windowId, sessionId, options: { sessionId } });
157
+ }
158
+
159
+ function getNewSessionId() {
160
+ return globalThis.crypto.getRandomValues(new Uint32Array(32)).join("");
161
+ }
162
+
163
+ function initRequestSync(message) {
164
+ const sessionId = message.sessionId;
165
+ const waitForUserScript = globalThis._singleFile_waitForUserScript;
166
+ delete globalThis._singleFile_cleaningUp;
167
+ if (!TOP_WINDOW) {
168
+ windowId = globalThis.frameId = message.windowId;
169
+ }
170
+ processFrames(document, message.options, windowId, sessionId);
171
+ if (!TOP_WINDOW) {
172
+ if (message.options.userScriptEnabled && waitForUserScript) {
173
+ waitForUserScript(helper.ON_BEFORE_CAPTURE_EVENT_NAME);
174
+ }
175
+ sendInitResponse({ frames: [getFrameData(document, globalThis, windowId, message.options)], sessionId, requestedFrameId: document.documentElement.dataset.requestedFrameId && windowId });
176
+ if (message.options.userScriptEnabled && waitForUserScript) {
177
+ waitForUserScript(helper.ON_AFTER_CAPTURE_EVENT_NAME);
178
+ }
179
+ delete document.documentElement.dataset.requestedFrameId;
180
+ }
181
+ }
182
+
183
+ async function initRequestAsync(message) {
184
+ const sessionId = message.sessionId;
185
+ const waitForUserScript = globalThis._singleFile_waitForUserScript;
186
+ delete globalThis._singleFile_cleaningUp;
187
+ if (!TOP_WINDOW) {
188
+ windowId = globalThis.frameId = message.windowId;
189
+ }
190
+ processFrames(document, message.options, windowId, sessionId);
191
+ if (!TOP_WINDOW) {
192
+ if (message.options.userScriptEnabled && waitForUserScript) {
193
+ await waitForUserScript(helper.ON_BEFORE_CAPTURE_EVENT_NAME);
194
+ }
195
+ sendInitResponse({ frames: [getFrameData(document, globalThis, windowId, message.options)], sessionId, requestedFrameId: document.documentElement.dataset.requestedFrameId && windowId });
196
+ if (message.options.userScriptEnabled && waitForUserScript) {
197
+ await waitForUserScript(helper.ON_AFTER_CAPTURE_EVENT_NAME);
198
+ }
199
+ delete document.documentElement.dataset.requestedFrameId;
200
+ }
201
+ }
202
+
203
+ function cleanupRequest(message) {
204
+ if (!globalThis._singleFile_cleaningUp) {
205
+ globalThis._singleFile_cleaningUp = true;
206
+ const sessionId = message.sessionId;
207
+ cleanupFrames(getFrames(document), message.windowId, sessionId);
208
+ }
209
+ }
210
+
211
+ function initResponse(message) {
212
+ message.frames.forEach(frameData => clearFrameTimeout("responseTimeouts", message.sessionId, frameData.windowId));
213
+ const windowData = sessions.get(message.sessionId);
214
+ if (windowData) {
215
+ if (message.requestedFrameId) {
216
+ windowData.requestedFrameId = message.requestedFrameId;
217
+ }
218
+ message.frames.forEach(messageFrameData => {
219
+ let frameData = windowData.frames.find(frameData => messageFrameData.windowId == frameData.windowId);
220
+ if (!frameData) {
221
+ frameData = { windowId: messageFrameData.windowId };
222
+ windowData.frames.push(frameData);
223
+ }
224
+ if (!frameData.processed) {
225
+ frameData.content = messageFrameData.content;
226
+ frameData.baseURI = messageFrameData.baseURI;
227
+ frameData.title = messageFrameData.title;
228
+ frameData.canvases = messageFrameData.canvases;
229
+ frameData.fonts = messageFrameData.fonts;
230
+ frameData.stylesheets = messageFrameData.stylesheets;
231
+ frameData.images = messageFrameData.images;
232
+ frameData.posters = messageFrameData.posters;
233
+ frameData.videos = messageFrameData.videos;
234
+ frameData.usedFonts = messageFrameData.usedFonts;
235
+ frameData.shadowRoots = messageFrameData.shadowRoots;
236
+ frameData.imports = messageFrameData.imports;
237
+ frameData.processed = messageFrameData.processed;
238
+ }
239
+ });
240
+ const remainingFrames = windowData.frames.filter(frameData => !frameData.processed).length;
241
+ if (!remainingFrames) {
242
+ windowData.frames = windowData.frames.sort((frame1, frame2) => frame2.windowId.split(WINDOW_ID_SEPARATOR).length - frame1.windowId.split(WINDOW_ID_SEPARATOR).length);
243
+ if (windowData.resolve) {
244
+ if (windowData.requestedFrameId) {
245
+ windowData.frames.forEach(frameData => {
246
+ if (frameData.windowId == windowData.requestedFrameId) {
247
+ frameData.requestedFrame = true;
248
+ }
249
+ });
250
+ }
251
+ windowData.resolve(windowData.frames);
252
+ }
253
+ }
254
+ }
255
+ }
256
+ function processFrames(doc, options, parentWindowId, sessionId) {
257
+ const frameElements = getFrames(doc);
258
+ processFramesAsync(doc, frameElements, options, parentWindowId, sessionId);
259
+ if (frameElements.length) {
260
+ processFramesSync(doc, frameElements, options, parentWindowId, sessionId);
261
+ }
262
+ }
263
+
264
+ function processFramesAsync(doc, frameElements, options, parentWindowId, sessionId) {
265
+ const frames = [];
266
+ let requestTimeouts;
267
+ if (sessions.get(sessionId)) {
268
+ requestTimeouts = sessions.get(sessionId).requestTimeouts;
269
+ } else {
270
+ requestTimeouts = {};
271
+ sessions.set(sessionId, { requestTimeouts });
272
+ }
273
+ frameElements.forEach((frameElement, frameIndex) => {
274
+ const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
275
+ frameElement.setAttribute(helper.WIN_ID_ATTRIBUTE_NAME, windowId);
276
+ frames.push({ windowId });
277
+ });
278
+ sendInitResponse({ frames, sessionId, requestedFrameId: doc.documentElement.dataset.requestedFrameId && parentWindowId });
279
+ frameElements.forEach((frameElement, frameIndex) => {
280
+ const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
281
+ try {
282
+ sendMessage(frameElement.contentWindow, { method: INIT_REQUEST_MESSAGE, windowId, sessionId, options });
283
+ } catch (error) {
284
+ // ignored
285
+ }
286
+ requestTimeouts[windowId] = globalThis.setTimeout(() => sendInitResponse({ frames: [{ windowId, processed: true }], sessionId }), TIMEOUT_INIT_REQUEST_MESSAGE);
287
+ });
288
+ delete doc.documentElement.dataset.requestedFrameId;
289
+ }
290
+
291
+ function processFramesSync(doc, frameElements, options, parentWindowId, sessionId) {
292
+ const frames = [];
293
+ frameElements.forEach((frameElement, frameIndex) => {
294
+ const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
295
+ let frameDoc;
296
+ try {
297
+ frameDoc = frameElement.contentDocument;
298
+ } catch (error) {
299
+ // ignored
300
+ }
301
+ if (frameDoc) {
302
+ try {
303
+ const frameWindow = frameElement.contentWindow;
304
+ frameWindow.stop();
305
+ clearFrameTimeout("requestTimeouts", sessionId, windowId);
306
+ processFrames(frameDoc, options, windowId, sessionId);
307
+ frames.push(getFrameData(frameDoc, frameWindow, windowId, options));
308
+ } catch (error) {
309
+ frames.push({ windowId, processed: true });
310
+ }
311
+ }
312
+ });
313
+ sendInitResponse({ frames, sessionId, requestedFrameId: doc.documentElement.dataset.requestedFrameId && parentWindowId });
314
+ delete doc.documentElement.dataset.requestedFrameId;
315
+ }
316
+
317
+ function clearFrameTimeout(type, sessionId, windowId) {
318
+ const session = sessions.get(sessionId);
319
+ if (session && session[type]) {
320
+ const timeout = session[type][windowId];
321
+ if (timeout) {
322
+ globalThis.clearTimeout(timeout);
323
+ delete session[type][windowId];
324
+ }
325
+ }
326
+ }
327
+
328
+ function createFrameResponseTimeout(sessionId, windowId) {
329
+ const session = sessions.get(sessionId);
330
+ if (session && session.responseTimeouts) {
331
+ session.responseTimeouts[windowId] = globalThis.setTimeout(() => sendInitResponse({ frames: [{ windowId: windowId, processed: true }], sessionId: sessionId }), TIMEOUT_INIT_RESPONSE_MESSAGE);
332
+ }
333
+ }
334
+
335
+ function cleanupFrames(frameElements, parentWindowId, sessionId) {
336
+ frameElements.forEach((frameElement, frameIndex) => {
337
+ const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
338
+ frameElement.removeAttribute(helper.WIN_ID_ATTRIBUTE_NAME);
339
+ try {
340
+ sendMessage(frameElement.contentWindow, { method: CLEANUP_REQUEST_MESSAGE, windowId, sessionId });
341
+ } catch (error) {
342
+ // ignored
343
+ }
344
+ });
345
+ frameElements.forEach((frameElement, frameIndex) => {
346
+ const windowId = parentWindowId + WINDOW_ID_SEPARATOR + frameIndex;
347
+ let frameDoc;
348
+ try {
349
+ frameDoc = frameElement.contentDocument;
350
+ } catch (error) {
351
+ // ignored
352
+ }
353
+ if (frameDoc) {
354
+ try {
355
+ cleanupFrames(getFrames(frameDoc), windowId, sessionId);
356
+ } catch (error) {
357
+ // ignored
358
+ }
359
+ }
360
+ });
361
+ }
362
+
363
+ function sendInitResponse(message) {
364
+ message.method = INIT_RESPONSE_MESSAGE;
365
+ try {
366
+ top.singlefile.processors.frameTree.initResponse(message);
367
+ } catch (error) {
368
+ sendMessage(top, message, true);
369
+ }
370
+ }
371
+
372
+ function sendMessage(targetWindow, message, useChannel) {
373
+ if (targetWindow == top && browser && browser.runtime && browser.runtime.sendMessage) {
374
+ browser.runtime.sendMessage(message);
375
+ } else {
376
+ if (useChannel) {
377
+ const channel = new MessageChannel();
378
+ targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify({ method: message.method, sessionId: message.sessionId }), TARGET_ORIGIN, [channel.port2]);
379
+ channel.port1.postMessage(message);
380
+ } else {
381
+ targetWindow.postMessage(MESSAGE_PREFIX + JSON.stringify(message), TARGET_ORIGIN);
382
+ }
383
+ }
384
+ }
385
+
386
+ function getFrameData(document, globalThis, windowId, options) {
387
+ const docData = helper.preProcessDoc(document, globalThis, options);
388
+ const content = helper.serialize(document);
389
+ helper.postProcessDoc(document, docData.markedElements, docData.invalidElements);
390
+ const baseURI = document.baseURI.split("#")[0];
391
+ return {
392
+ windowId,
393
+ content,
394
+ baseURI,
395
+ title: document.title,
396
+ canvases: docData.canvases,
397
+ fonts: docData.fonts,
398
+ stylesheets: docData.stylesheets,
399
+ images: docData.images,
400
+ posters: docData.posters,
401
+ videos: docData.videos,
402
+ usedFonts: docData.usedFonts,
403
+ shadowRoots: docData.shadowRoots,
404
+ imports: docData.imports,
405
+ processed: true
406
+ };
407
+ }
408
+
409
+ function getFrames(document) {
410
+ let frames = Array.from(document.querySelectorAll(FRAMES_CSS_SELECTOR));
411
+ document.querySelectorAll(ALL_ELEMENTS_CSS_SELECTOR).forEach(element => {
412
+ const shadowRoot = helper.getShadowRoot(element);
413
+ if (shadowRoot) {
414
+ frames = frames.concat(...shadowRoot.querySelectorAll(FRAMES_CSS_SELECTOR));
415
+ }
416
+ });
417
+ return frames;
418
+ }