UNPKG

11.4 kBJavaScriptView Raw
1"use strict";
2/**
3 * @license
4 * Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
5 * This code may only be used under the BSD style license found at
6 * http://polymer.github.io/LICENSE.txt
7 * The complete set of authors may be found at
8 * http://polymer.github.io/AUTHORS.txt
9 * The complete set of contributors may be found at
10 * http://polymer.github.io/CONTRIBUTORS.txt
11 * Code distributed by Google as part of the polymer project is also
12 * subject to an additional IP rights grant found at
13 * http://polymer.github.io/PATENTS.txt
14 */
15var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
16 return new (P || (P = Promise))(function (resolve, reject) {
17 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
18 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
19 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
20 step((generator = generator.apply(thisArg, _arguments || [])).next());
21 });
22};
23var __asyncValues = (this && this.__asyncValues) || function (o) {
24 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
25 var m = o[Symbol.asyncIterator], i;
26 return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
27 function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
28 function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
29};
30var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
31var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
32 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
33 var g = generator.apply(thisArg, _arguments || []), i, q = [];
34 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
35 function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
36 function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
37 function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
38 function fulfill(value) { resume("next", value); }
39 function reject(value) { resume("throw", value); }
40 function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
41};
42Object.defineProperty(exports, "__esModule", { value: true });
43const path = require("path");
44const polymer_analyzer_1 = require("polymer-analyzer");
45const deps_index_1 = require("polymer-bundler/lib/deps-index");
46const File = require("vinyl");
47const path_transformers_1 = require("./path-transformers");
48const file_map_url_loader_1 = require("./file-map-url-loader");
49const streams_1 = require("./streams");
50/**
51 * A mapping of file extensions and their default resource type.
52 */
53const extensionToTypeMapping = new Map([
54 ['.css', 'style'],
55 ['.gif', 'image'],
56 ['.html', 'document'],
57 ['.png', 'image'],
58 ['.jpg', 'image'],
59 ['.js', 'script'],
60 ['.json', 'script'],
61 ['.svg', 'image'],
62 ['.webp', 'image'],
63 ['.woff', 'font'],
64 ['.woff2', 'font'],
65]);
66/**
67 * Get the default resource type for a file based on its extension.
68 */
69function getResourceTypeFromUrl(url) {
70 return extensionToTypeMapping.get(path.extname(url));
71}
72/**
73 * Get the resource type for an import, handling special import types and
74 * falling back to getResourceTypeFromUrl() if the resource type can't be
75 * detected directly from importFeature.
76 */
77function getResourceTypeFromImport(importFeature) {
78 const importKinds = importFeature.kinds;
79 if (importKinds.has('css-import') || importKinds.has('html-style')) {
80 return 'style';
81 }
82 if (importKinds.has('html-import')) {
83 return 'document';
84 }
85 if (importKinds.has('html-script')) {
86 return 'script';
87 }
88 // @NOTE(fks) 04-07-2017: A js-import can actually import multiple types of
89 // resources, so we can't guarentee that it's a script and should instead rely
90 // on the default file-extension mapping.
91 return getResourceTypeFromUrl(importFeature.url);
92}
93/**
94 * Create a PushManifestEntry from an analyzer Import.
95 */
96function createPushEntryFromImport(importFeature) {
97 return {
98 type: getResourceTypeFromImport(importFeature),
99 weight: 1,
100 };
101}
102/**
103 * Analyze the given URL and resolve with a collection of push manifest entries
104 * to be added to the overall push manifest.
105 */
106function generatePushManifestEntryForUrl(analyzer, url) {
107 return __awaiter(this, void 0, void 0, function* () {
108 const analysis = yield analyzer.analyze([url]);
109 const result = analysis.getDocument(url);
110 if (result.successful === false) {
111 const message = result.error && result.error.message || 'unknown';
112 throw new Error(`Unable to get document ${url}: ${message}`);
113 }
114 const analyzedDocument = result.value;
115 const rawImports = [...analyzedDocument.getFeatures({
116 kind: 'import',
117 externalPackages: true,
118 imported: true,
119 noLazyImports: true,
120 })];
121 const importsToPush = rawImports.filter((i) => !(i.type === 'html-import' && i.lazy) &&
122 !(i.kinds.has('html-script-back-reference')));
123 const pushManifestEntries = {};
124 for (const analyzedImport of importsToPush) {
125 // TODO This import URL does not respect the document's base tag.
126 // Probably an issue more generally with all URLs analyzed out of
127 // documents, but base tags are somewhat rare.
128 const analyzedImportUrl = analyzedImport.url;
129 const relativeImportUrl = analyzer.urlResolver.relative(analyzedImportUrl);
130 const analyzedImportEntry = pushManifestEntries[relativeImportUrl];
131 if (!analyzedImportEntry) {
132 pushManifestEntries[relativeImportUrl] =
133 createPushEntryFromImport(analyzedImport);
134 }
135 }
136 return pushManifestEntries;
137 });
138}
139/**
140 * A stream that reads in files from an application to generate an HTTP2/Push
141 * manifest that gets injected into the stream.
142 */
143class AddPushManifest extends streams_1.AsyncTransformStream {
144 constructor(config, outPath, basePath) {
145 super({ objectMode: true });
146 this.files = new Map();
147 this.config = config;
148 this.analyzer = new polymer_analyzer_1.Analyzer({
149 urlLoader: new file_map_url_loader_1.FileMapUrlLoader(this.files),
150 urlResolver: new polymer_analyzer_1.FsUrlResolver(config.root),
151 });
152 this.outPath =
153 path.join(this.config.root, outPath || 'push-manifest.json');
154 this.basePath = (basePath || '');
155 }
156 _transformIter(files) {
157 return __asyncGenerator(this, arguments, function* _transformIter_1() {
158 var e_1, _a;
159 try {
160 for (var files_1 = __asyncValues(files), files_1_1; files_1_1 = yield __await(files_1.next()), !files_1_1.done;) {
161 const file = files_1_1.value;
162 this.files.set(this.analyzer.resolveUrl(path_transformers_1.urlFromPath(this.config.root, file.path)), file);
163 yield yield __await(file);
164 }
165 }
166 catch (e_1_1) { e_1 = { error: e_1_1 }; }
167 finally {
168 try {
169 if (files_1_1 && !files_1_1.done && (_a = files_1.return)) yield __await(_a.call(files_1));
170 }
171 finally { if (e_1) throw e_1.error; }
172 }
173 // Generate a push manifest, and propagate any errors up.
174 const pushManifest = yield __await(this.generatePushManifest());
175 const pushManifestContents = JSON.stringify(pushManifest, undefined, ' ');
176 // Push the new push manifest into the stream.
177 yield yield __await(new File({
178 path: this.outPath,
179 contents: Buffer.from(pushManifestContents),
180 }));
181 });
182 }
183 generatePushManifest() {
184 return __awaiter(this, void 0, void 0, function* () {
185 // Bundler's buildDepsIndex code generates an index with all fragments and
186 // all lazy-imports encountered are the keys, so we'll use that function to
187 // produce the set of all fragments to generate push-manifest entries for.
188 const depsIndex = yield deps_index_1.buildDepsIndex(this.config.allFragments.map((path) => this.analyzer.resolveUrl(path_transformers_1.urlFromPath(this.config.root, path))), this.analyzer);
189 // Don't include bundler's fake "sub-bundle" URLs (e.g.
190 // "foo.html>external#1>bar.js").
191 const allFragments = new Set([...depsIndex.keys()].filter((url) => !url.includes('>')));
192 // If an app-shell exists, use that as our main push URL because it has a
193 // reliable URL. Otherwise, support the single entrypoint URL.
194 const mainPushEntrypointUrl = this.analyzer.resolveUrl(path_transformers_1.urlFromPath(this.config.root, this.config.shell ||
195 this.config.entrypoint));
196 allFragments.add(mainPushEntrypointUrl);
197 // Generate the dependencies to push for each fragment.
198 const pushManifest = {};
199 for (const fragment of allFragments) {
200 const absoluteFragmentUrl = '/' + this.analyzer.urlResolver.relative(fragment);
201 pushManifest[absoluteFragmentUrl] =
202 yield generatePushManifestEntryForUrl(this.analyzer, fragment);
203 }
204 // The URLs we got may be absolute or relative depending on how they were
205 // declared in the source. This will normalize them to relative by stripping
206 // any leading slash.
207 //
208 // TODO Decide whether they should really be relative or absolute. Relative
209 // was chosen here only because most links were already relative so it was
210 // a smaller change, but
211 // https://github.com/GoogleChrome/http2-push-manifest actually shows
212 // relative for the keys and absolute for the values.
213 const normalize = (p) => path.posix.join(this.basePath, p).replace(/^\/+/, '');
214 const normalized = {};
215 for (const source of Object.keys(pushManifest)) {
216 const targets = {};
217 for (const target of Object.keys(pushManifest[source])) {
218 targets[normalize(target)] = pushManifest[source][target];
219 }
220 normalized[normalize(source)] = targets;
221 }
222 return normalized;
223 });
224 }
225}
226exports.AddPushManifest = AddPushManifest;
227//# sourceMappingURL=push-manifest.js.map
\No newline at end of file