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.
package/index.js ADDED
@@ -0,0 +1,86 @@
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 processors from "./processors/index.js";
27
+ import * as vendor from "./vendor/index.js";
28
+ import * as modules from "./modules/index.js";
29
+ import * as core from "./single-file-core.js";
30
+ import * as helper from "./single-file-helper.js";
31
+ import * as util from "./single-file-util.js";
32
+
33
+ let SingleFile;
34
+ export {
35
+ init,
36
+ getPageData,
37
+ processors,
38
+ vendor,
39
+ modules,
40
+ helper,
41
+ SingleFile
42
+ };
43
+
44
+ function init(initOptions) {
45
+ SingleFile = core.getClass(util.getInstance(initOptions), vendor.cssTree);
46
+ }
47
+
48
+ async function getPageData(options = {}, initOptions, doc = globalThis.document, win = globalThis) {
49
+ const frames = processors.frameTree;
50
+ let framesSessionId;
51
+ init(initOptions);
52
+ if (doc && win) {
53
+ helper.initDoc(doc);
54
+ const preInitializationPromises = [];
55
+ if (!options.saveRawPage) {
56
+ if (!options.removeFrames && frames && globalThis.frames && globalThis.frames.length) {
57
+ let frameTreePromise;
58
+ if (options.loadDeferredImages) {
59
+ frameTreePromise = new Promise(resolve => globalThis.setTimeout(() => resolve(frames.getAsync(options)), options.loadDeferredImagesMaxIdleTime - frames.TIMEOUT_INIT_REQUEST_MESSAGE));
60
+ } else {
61
+ frameTreePromise = frames.getAsync(options);
62
+ }
63
+ preInitializationPromises.push(frameTreePromise);
64
+ }
65
+ if (options.loadDeferredImages) {
66
+ preInitializationPromises.push(processors.lazy.process(options));
67
+ }
68
+ }
69
+ [options.frames] = await Promise.all(preInitializationPromises);
70
+ framesSessionId = options.frames && options.frames.sessionId;
71
+ }
72
+ options.doc = doc;
73
+ options.win = win;
74
+ options.insertCanonicalLink = true;
75
+ options.onprogress = event => {
76
+ if (event.type === event.RESOURCES_INITIALIZED && doc && win && options.loadDeferredImages) {
77
+ processors.lazy.resetZoomLevel(options);
78
+ }
79
+ };
80
+ const processor = new SingleFile(options);
81
+ await processor.run();
82
+ if (framesSessionId) {
83
+ frames.cleanup(framesSessionId);
84
+ }
85
+ return await processor.getPageData();
86
+ }
@@ -0,0 +1,340 @@
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 cssTree from "./../vendor/css-tree.js";
27
+ import {
28
+ normalizeFontFamily,
29
+ getFontWeight
30
+ } from "./../single-file-helper.js";
31
+
32
+ const helper = {
33
+ normalizeFontFamily,
34
+ getFontWeight
35
+ };
36
+
37
+ const FontFace = globalThis.FontFace;
38
+
39
+ const REGEXP_URL_SIMPLE_QUOTES_FN = /url\s*\(\s*'(.*?)'\s*\)/i;
40
+ const REGEXP_URL_DOUBLE_QUOTES_FN = /url\s*\(\s*"(.*?)"\s*\)/i;
41
+ const REGEXP_URL_NO_QUOTES_FN = /url\s*\(\s*(.*?)\s*\)/i;
42
+ const REGEXP_URL_FUNCTION = /(url|local|-sf-url-original)\(.*?\)\s*(,|$)/g;
43
+ const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
44
+ const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;
45
+ const REGEXP_URL_FUNCTION_WOFF = /^url\(\s*["']?data:font\/(woff2?)/;
46
+ const REGEXP_URL_FUNCTION_WOFF_ALT = /^url\(\s*["']?data:application\/x-font-(woff)/;
47
+ const REGEXP_FONT_FORMAT = /\.([^.?#]+)((\?|#).*?)?$/;
48
+ const REGEXP_FONT_FORMAT_VALUE = /format\((.*?)\)\s*,?$/;
49
+ const REGEXP_FONT_SRC = /(.*?)\s*,?$/;
50
+ const EMPTY_URL_SOURCE = /^url\(["']?data:[^,]*,?["']?\)/;
51
+ const LOCAL_SOURCE = "local(";
52
+ const MEDIA_ALL = "all";
53
+ const FONT_STRETCHES = {
54
+ "ultra-condensed": "50%",
55
+ "extra-condensed": "62.5%",
56
+ "condensed": "75%",
57
+ "semi-condensed": "87.5%",
58
+ "normal": "100%",
59
+ "semi-expanded": "112.5%",
60
+ "expanded": "125%",
61
+ "extra-expanded": "150%",
62
+ "ultra-expanded": "200%"
63
+ };
64
+ const FONT_MAX_LOAD_DELAY = 5000;
65
+
66
+ export {
67
+ process
68
+ };
69
+
70
+ async function process(doc, stylesheets, fontDeclarations, fontTests) {
71
+ const fontsDetails = {
72
+ fonts: new Map(),
73
+ medias: new Map(),
74
+ supports: new Map()
75
+ };
76
+ const stats = { rules: { processed: 0, discarded: 0 }, fonts: { processed: 0, discarded: 0 } };
77
+ let sheetIndex = 0;
78
+ stylesheets.forEach(stylesheetInfo => {
79
+ const cssRules = stylesheetInfo.stylesheet.children;
80
+ if (cssRules) {
81
+ stats.rules.processed += cssRules.size;
82
+ stats.rules.discarded += cssRules.size;
83
+ if (stylesheetInfo.mediaText && stylesheetInfo.mediaText != MEDIA_ALL) {
84
+ const mediaFontsDetails = createFontsDetailsInfo();
85
+ fontsDetails.medias.set("media-" + sheetIndex + "-" + stylesheetInfo.mediaText, mediaFontsDetails);
86
+ getFontsDetails(doc, cssRules, sheetIndex, mediaFontsDetails);
87
+ } else {
88
+ getFontsDetails(doc, cssRules, sheetIndex, fontsDetails);
89
+ }
90
+ }
91
+ sheetIndex++;
92
+ });
93
+ processFontDetails(fontsDetails);
94
+ await Promise.all([...stylesheets].map(async ([, stylesheetInfo], sheetIndex) => {
95
+ const cssRules = stylesheetInfo.stylesheet.children;
96
+ const media = stylesheetInfo.mediaText;
97
+ if (cssRules) {
98
+ if (media && media != MEDIA_ALL) {
99
+ await processFontFaceRules(cssRules, sheetIndex, fontsDetails.medias.get("media-" + sheetIndex + "-" + media), fontDeclarations, fontTests, stats);
100
+ } else {
101
+ await processFontFaceRules(cssRules, sheetIndex, fontsDetails, fontDeclarations, fontTests, stats);
102
+ }
103
+ stats.rules.discarded -= cssRules.size;
104
+ }
105
+ }));
106
+ return stats;
107
+ }
108
+
109
+ function getFontsDetails(doc, cssRules, sheetIndex, mediaFontsDetails) {
110
+ let mediaIndex = 0, supportsIndex = 0;
111
+ cssRules.forEach(ruleData => {
112
+ if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.block.children && ruleData.prelude) {
113
+ const mediaText = cssTree.generate(ruleData.prelude);
114
+ const fontsDetails = createFontsDetailsInfo();
115
+ mediaFontsDetails.medias.set("media-" + sheetIndex + "-" + mediaIndex + "-" + mediaText, fontsDetails);
116
+ mediaIndex++;
117
+ getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails);
118
+ } else if (ruleData.type == "Atrule" && ruleData.name == "supports" && ruleData.block && ruleData.block.children && ruleData.prelude) {
119
+ const supportsText = cssTree.generate(ruleData.prelude);
120
+ const fontsDetails = createFontsDetailsInfo();
121
+ mediaFontsDetails.supports.set("supports-" + sheetIndex + "-" + supportsIndex + "-" + supportsText, fontsDetails);
122
+ supportsIndex++;
123
+ getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails);
124
+ } else if (ruleData.type == "Atrule" && ruleData.name == "font-face" && ruleData.block && ruleData.block.children) {
125
+ const fontKey = getFontKey(ruleData);
126
+ let fontInfo = mediaFontsDetails.fonts.get(fontKey);
127
+ if (!fontInfo) {
128
+ fontInfo = [];
129
+ mediaFontsDetails.fonts.set(fontKey, fontInfo);
130
+ }
131
+ const src = getPropertyValue(ruleData, "src");
132
+ if (src) {
133
+ const fontSources = src.match(REGEXP_URL_FUNCTION);
134
+ if (fontSources) {
135
+ fontSources.forEach(source => fontInfo.unshift(source));
136
+ }
137
+ }
138
+ }
139
+ });
140
+ }
141
+
142
+ function processFontDetails(fontsDetails) {
143
+ fontsDetails.fonts.forEach((fontInfo, fontKey) => {
144
+ fontsDetails.fonts.set(fontKey, fontInfo.map(fontSource => {
145
+ const fontFormatMatch = fontSource.match(REGEXP_FONT_FORMAT_VALUE);
146
+ let fontFormat;
147
+ const fontUrl = getURL(fontSource);
148
+ if (fontFormatMatch && fontFormatMatch[1]) {
149
+ fontFormat = fontFormatMatch[1].replace(REGEXP_SIMPLE_QUOTES_STRING, "$1").replace(REGEXP_DOUBLE_QUOTES_STRING, "$1").toLowerCase();
150
+ }
151
+ if (!fontFormat) {
152
+ const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF);
153
+ if (fontFormatMatch && fontFormatMatch[1]) {
154
+ fontFormat = fontFormatMatch[1];
155
+ } else {
156
+ const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF_ALT);
157
+ if (fontFormatMatch && fontFormatMatch[1]) {
158
+ fontFormat = fontFormatMatch[1];
159
+ }
160
+ }
161
+ }
162
+ if (!fontFormat && fontUrl) {
163
+ const fontFormatMatch = fontUrl.match(REGEXP_FONT_FORMAT);
164
+ if (fontFormatMatch && fontFormatMatch[1]) {
165
+ fontFormat = fontFormatMatch[1];
166
+ }
167
+ }
168
+ return { src: fontSource.match(REGEXP_FONT_SRC)[1], fontUrl, format: fontFormat };
169
+ }));
170
+ });
171
+ fontsDetails.medias.forEach(mediaFontsDetails => processFontDetails(mediaFontsDetails));
172
+ fontsDetails.supports.forEach(supportsFontsDetails => processFontDetails(supportsFontsDetails));
173
+ }
174
+
175
+ async function processFontFaceRules(cssRules, sheetIndex, fontsDetails, fontDeclarations, fontTests, stats) {
176
+ const removedRules = [];
177
+ let mediaIndex = 0, supportsIndex = 0;
178
+ for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
179
+ const ruleData = cssRule.data;
180
+ if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.block.children && ruleData.prelude) {
181
+ const mediaText = cssTree.generate(ruleData.prelude);
182
+ await processFontFaceRules(ruleData.block.children, sheetIndex, fontsDetails.medias.get("media-" + sheetIndex + "-" + mediaIndex + "-" + mediaText), fontDeclarations, fontTests, stats);
183
+ mediaIndex++;
184
+ } else if (ruleData.type == "Atrule" && ruleData.name == "supports" && ruleData.block && ruleData.block.children && ruleData.prelude) {
185
+ const supportsText = cssTree.generate(ruleData.prelude);
186
+ await processFontFaceRules(ruleData.block.children, sheetIndex, fontsDetails.supports.get("supports-" + sheetIndex + "-" + supportsIndex + "-" + supportsText), fontDeclarations, fontTests, stats);
187
+ supportsIndex++;
188
+ } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
189
+ const key = getFontKey(ruleData);
190
+ const fontInfo = fontsDetails.fonts.get(key);
191
+ if (fontInfo) {
192
+ const processed = await processFontFaceRule(ruleData, fontInfo, fontDeclarations, fontTests, stats);
193
+ if (processed) {
194
+ fontsDetails.fonts.delete(key);
195
+ }
196
+ } else {
197
+ removedRules.push(cssRule);
198
+ }
199
+ }
200
+ }
201
+ removedRules.forEach(cssRule => cssRules.remove(cssRule));
202
+ }
203
+
204
+ async function processFontFaceRule(ruleData, fontInfo, fontDeclarations, fontTests, stats) {
205
+ const removedNodes = [];
206
+ for (let node = ruleData.block.children.head; node; node = node.next) {
207
+ if (node.data.property == "src") {
208
+ removedNodes.push(node);
209
+ }
210
+ }
211
+ removedNodes.pop();
212
+ removedNodes.forEach(node => ruleData.block.children.remove(node));
213
+ const srcDeclaration = ruleData.block.children.filter(node => node.property == "src").tail;
214
+ if (srcDeclaration) {
215
+ await Promise.all(fontInfo.map(async (source, sourceIndex) => {
216
+ if (fontTests.has(source.src)) {
217
+ source.valid = fontTests.get(source.src);
218
+ } else {
219
+ if (FontFace) {
220
+ const fontFace = new FontFace("test-font", source.src);
221
+ try {
222
+ let timeout;
223
+ await Promise.race([
224
+ fontFace.load().then(() => fontFace.loaded).then(() => { source.valid = true; globalThis.clearTimeout(timeout); }),
225
+ new Promise(resolve => timeout = globalThis.setTimeout(() => { source.valid = true; resolve(); }, FONT_MAX_LOAD_DELAY))
226
+ ]);
227
+ } catch (error) {
228
+ const declarationFontURLs = fontDeclarations.get(srcDeclaration.data);
229
+ if (declarationFontURLs) {
230
+ const fontURL = declarationFontURLs[declarationFontURLs.length - sourceIndex - 1];
231
+ if (fontURL) {
232
+ const fontFace = new FontFace("test-font", "url(" + fontURL + ")");
233
+ try {
234
+ let timeout;
235
+ await Promise.race([
236
+ fontFace.load().then(() => fontFace.loaded).then(() => { source.valid = true; globalThis.clearTimeout(timeout); }),
237
+ new Promise(resolve => timeout = globalThis.setTimeout(() => { source.valid = true; resolve(); }, FONT_MAX_LOAD_DELAY))
238
+ ]);
239
+ } catch (error) {
240
+ // ignored
241
+ }
242
+ }
243
+ } else {
244
+ source.valid = true;
245
+ }
246
+ }
247
+ } else {
248
+ source.valid = true;
249
+ }
250
+ fontTests.set(source.src, source.valid);
251
+ }
252
+ }));
253
+ const findSourceByFormat = (fontFormat, testValidity) => fontInfo.find(source => !source.src.match(EMPTY_URL_SOURCE) && source.format == fontFormat && (!testValidity || source.valid));
254
+ const filterSources = fontSource => fontInfo.filter(source => source == fontSource || source.src.startsWith(LOCAL_SOURCE));
255
+ stats.fonts.processed += fontInfo.length;
256
+ stats.fonts.discarded += fontInfo.length;
257
+ const woffFontFound =
258
+ findSourceByFormat("woff2-variations", true) || findSourceByFormat("woff2", true) || findSourceByFormat("woff", true);
259
+ if (woffFontFound) {
260
+ fontInfo = filterSources(woffFontFound);
261
+ } else {
262
+ const ttfFontFound =
263
+ findSourceByFormat("truetype-variations", true) || findSourceByFormat("truetype", true);
264
+ if (ttfFontFound) {
265
+ fontInfo = filterSources(ttfFontFound);
266
+ } else {
267
+ const otfFontFound =
268
+ findSourceByFormat("opentype") || findSourceByFormat("embedded-opentype");
269
+ if (otfFontFound) {
270
+ fontInfo = filterSources(otfFontFound);
271
+ } else {
272
+ fontInfo = fontInfo.filter(source => !source.src.match(EMPTY_URL_SOURCE) && (source.valid) || source.src.startsWith(LOCAL_SOURCE));
273
+ }
274
+ }
275
+ }
276
+ stats.fonts.discarded -= fontInfo.length;
277
+ fontInfo.reverse();
278
+ try {
279
+ srcDeclaration.data.value = cssTree.parse(fontInfo.map(fontSource => fontSource.src).join(","), { context: "value" });
280
+ }
281
+ catch (error) {
282
+ // ignored
283
+ }
284
+ return true;
285
+ } else {
286
+ return false;
287
+ }
288
+ }
289
+
290
+ function getPropertyValue(ruleData, propertyName) {
291
+ let property;
292
+ if (ruleData.block.children) {
293
+ property = ruleData.block.children.filter(node => {
294
+ try {
295
+ return node.property == propertyName && !cssTree.generate(node.value).match(/\\9$/);
296
+ } catch (error) {
297
+ return node.property == propertyName;
298
+ }
299
+ }).tail;
300
+ }
301
+ if (property) {
302
+ try {
303
+ return cssTree.generate(property.data.value);
304
+ } catch (error) {
305
+ // ignored
306
+ }
307
+ }
308
+ }
309
+
310
+ function getFontKey(ruleData) {
311
+ return JSON.stringify([
312
+ helper.normalizeFontFamily(getPropertyValue(ruleData, "font-family")),
313
+ helper.getFontWeight(getPropertyValue(ruleData, "font-weight") || "400"),
314
+ getPropertyValue(ruleData, "font-style") || "normal",
315
+ getPropertyValue(ruleData, "unicode-range"),
316
+ getFontStretch(getPropertyValue(ruleData, "font-stretch")),
317
+ getPropertyValue(ruleData, "font-variant") || "normal",
318
+ getPropertyValue(ruleData, "font-feature-settings"),
319
+ getPropertyValue(ruleData, "font-variation-settings")
320
+ ]);
321
+ }
322
+
323
+ function getFontStretch(stretch) {
324
+ return FONT_STRETCHES[stretch] || stretch;
325
+ }
326
+
327
+ function createFontsDetailsInfo() {
328
+ return {
329
+ fonts: new Map(),
330
+ medias: new Map(),
331
+ supports: new Map()
332
+ };
333
+ }
334
+
335
+ function getURL(urlFunction) {
336
+ const urlMatch = urlFunction.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
337
+ urlFunction.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
338
+ urlFunction.match(REGEXP_URL_NO_QUOTES_FN);
339
+ return urlMatch && urlMatch[1];
340
+ }