source: trip-planner-front/node_modules/@angular-devkit/build-angular/src/utils/index-file/inline-fonts.js@ 59329aa

Last change on this file since 59329aa was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 9.1 KB
Line 
1"use strict";
2/**
3 * @license
4 * Copyright Google LLC All Rights Reserved.
5 *
6 * Use of this source code is governed by an MIT-style license that can be
7 * found in the LICENSE file at https://angular.io/license
8 */
9var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10 if (k2 === undefined) k2 = k;
11 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
12}) : (function(o, m, k, k2) {
13 if (k2 === undefined) k2 = k;
14 o[k2] = m[k];
15}));
16var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
17 Object.defineProperty(o, "default", { enumerable: true, value: v });
18}) : function(o, v) {
19 o["default"] = v;
20});
21var __importStar = (this && this.__importStar) || function (mod) {
22 if (mod && mod.__esModule) return mod;
23 var result = {};
24 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
25 __setModuleDefault(result, mod);
26 return result;
27};
28var __importDefault = (this && this.__importDefault) || function (mod) {
29 return (mod && mod.__esModule) ? mod : { "default": mod };
30};
31Object.defineProperty(exports, "__esModule", { value: true });
32exports.InlineFontsProcessor = void 0;
33const cacache = __importStar(require("cacache"));
34const fs = __importStar(require("fs"));
35const https = __importStar(require("https"));
36const https_proxy_agent_1 = __importDefault(require("https-proxy-agent"));
37const url_1 = require("url");
38const cache_path_1 = require("../cache-path");
39const environment_options_1 = require("../environment-options");
40const html_rewriting_stream_1 = require("./html-rewriting-stream");
41const cacheFontsPath = environment_options_1.cachingDisabled
42 ? undefined
43 : cache_path_1.findCachePath('angular-build-fonts');
44const packageVersion = require('../../../package.json').version;
45const SUPPORTED_PROVIDERS = {
46 'fonts.googleapis.com': {
47 seperateRequestForWOFF: true,
48 preconnectUrl: 'https://fonts.gstatic.com',
49 },
50 'use.typekit.net': {
51 seperateRequestForWOFF: false,
52 preconnectUrl: 'https://use.typekit.net',
53 },
54};
55class InlineFontsProcessor {
56 constructor(options) {
57 this.options = options;
58 }
59 async process(content) {
60 var _a;
61 const hrefList = [];
62 const existingPreconnect = new Set();
63 // Collector link tags with href
64 const { rewriter: collectorStream } = await html_rewriting_stream_1.htmlRewritingStream(content);
65 collectorStream.on('startTag', (tag) => {
66 const { tagName, attrs } = tag;
67 if (tagName !== 'link') {
68 return;
69 }
70 let hrefValue;
71 let relValue;
72 for (const { name, value } of attrs) {
73 switch (name) {
74 case 'rel':
75 relValue = value;
76 break;
77 case 'href':
78 hrefValue = value;
79 break;
80 }
81 if (hrefValue && relValue) {
82 switch (relValue) {
83 case 'stylesheet':
84 // <link rel="stylesheet" href="https://example.com/main.css">
85 hrefList.push(hrefValue);
86 break;
87 case 'preconnect':
88 // <link rel="preconnect" href="https://example.com">
89 existingPreconnect.add(hrefValue.replace(/\/$/, ''));
90 break;
91 }
92 return;
93 }
94 }
95 });
96 await new Promise((resolve) => collectorStream.on('finish', resolve));
97 // Download stylesheets
98 const hrefsContent = new Map();
99 const newPreconnectUrls = new Set();
100 for (const hrefItem of hrefList) {
101 const url = this.createNormalizedUrl(hrefItem);
102 if (!url) {
103 continue;
104 }
105 const content = await this.processHref(url);
106 if (content === undefined) {
107 continue;
108 }
109 hrefsContent.set(hrefItem, content);
110 // Add preconnect
111 const preconnectUrl = (_a = this.getFontProviderDetails(url)) === null || _a === void 0 ? void 0 : _a.preconnectUrl;
112 if (preconnectUrl && !existingPreconnect.has(preconnectUrl)) {
113 newPreconnectUrls.add(preconnectUrl);
114 }
115 }
116 if (hrefsContent.size === 0) {
117 return content;
118 }
119 // Replace link with style tag.
120 const { rewriter, transformedContent } = await html_rewriting_stream_1.htmlRewritingStream(content);
121 rewriter.on('startTag', (tag) => {
122 const { tagName, attrs } = tag;
123 switch (tagName) {
124 case 'head':
125 rewriter.emitStartTag(tag);
126 for (const url of newPreconnectUrls) {
127 rewriter.emitRaw(`<link rel="preconnect" href="${url}" crossorigin>`);
128 }
129 break;
130 case 'link':
131 const hrefAttr = attrs.some(({ name, value }) => name === 'rel' && value === 'stylesheet') &&
132 attrs.find(({ name, value }) => name === 'href' && hrefsContent.has(value));
133 if (hrefAttr) {
134 const href = hrefAttr.value;
135 const cssContent = hrefsContent.get(href);
136 rewriter.emitRaw(`<style type="text/css">${cssContent}</style>`);
137 }
138 else {
139 rewriter.emitStartTag(tag);
140 }
141 break;
142 default:
143 rewriter.emitStartTag(tag);
144 break;
145 }
146 });
147 return transformedContent;
148 }
149 async getResponse(url, userAgent) {
150 var _a;
151 const key = `${packageVersion}|${url}|${userAgent}`;
152 if (cacheFontsPath) {
153 const entry = await cacache.get.info(cacheFontsPath, key);
154 if (entry) {
155 return fs.promises.readFile(entry.path, 'utf8');
156 }
157 }
158 let agent;
159 const httpsProxy = (_a = process.env.HTTPS_PROXY) !== null && _a !== void 0 ? _a : process.env.https_proxy;
160 if (httpsProxy) {
161 agent = https_proxy_agent_1.default(httpsProxy);
162 }
163 const data = await new Promise((resolve, reject) => {
164 let rawResponse = '';
165 https
166 .get(url, {
167 agent,
168 rejectUnauthorized: false,
169 headers: {
170 'user-agent': userAgent,
171 },
172 }, (res) => {
173 if (res.statusCode !== 200) {
174 reject(new Error(`Inlining of fonts failed. ${url} returned status code: ${res.statusCode}.`));
175 return;
176 }
177 res.on('data', (chunk) => (rawResponse += chunk)).on('end', () => resolve(rawResponse));
178 })
179 .on('error', (e) => reject(new Error(`Inlining of fonts failed. An error has occurred while retrieving ${url} over the internet.\n` +
180 e.message)));
181 });
182 if (cacheFontsPath) {
183 await cacache.put(cacheFontsPath, key, data);
184 }
185 return data;
186 }
187 async processHref(url) {
188 const provider = this.getFontProviderDetails(url);
189 if (!provider) {
190 return undefined;
191 }
192 // The order IE -> Chrome is important as otherwise Chrome will load woff1.
193 let cssContent = '';
194 if (this.options.WOFFSupportNeeded && provider.seperateRequestForWOFF) {
195 cssContent += await this.getResponse(url, "Mozilla/5.0 (Windows NT 10.0; Trident/7.0; rv:11. 0) like Gecko" /* IE */);
196 }
197 cssContent += await this.getResponse(url, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36" /* Chrome */);
198 if (this.options.minify) {
199 cssContent = cssContent
200 // Comments.
201 .replace(/\/\*([\s\S]*?)\*\//g, '')
202 // New lines.
203 .replace(/\n/g, '')
204 // Safe spaces.
205 .replace(/\s?[\{\:\;]\s+/g, (s) => s.trim());
206 }
207 return cssContent;
208 }
209 getFontProviderDetails(url) {
210 return SUPPORTED_PROVIDERS[url.hostname];
211 }
212 createNormalizedUrl(value) {
213 // Need to convert '//' to 'https://' because the URL parser will fail with '//'.
214 const normalizedHref = value.startsWith('//') ? `https:${value}` : value;
215 if (!normalizedHref.startsWith('http')) {
216 // Non valid URL.
217 // Example: relative path styles.css.
218 return undefined;
219 }
220 const url = new url_1.URL(normalizedHref);
221 // Force HTTPS protocol
222 url.protocol = 'https:';
223 return url;
224 }
225}
226exports.InlineFontsProcessor = InlineFontsProcessor;
Note: See TracBrowser for help on using the repository browser.