UNPKG

1.61 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra
4*/
5
6"use strict";
7
8const { URL } = require("url");
9const NormalModule = require("../NormalModule");
10
11/** @typedef {import("../Compiler")} Compiler */
12
13class HttpsUriPlugin {
14 /**
15 * Apply the plugin
16 * @param {Compiler} compiler the compiler instance
17 * @returns {void}
18 */
19 apply(compiler) {
20 compiler.hooks.compilation.tap(
21 "HttpsUriPlugin",
22 (compilation, { normalModuleFactory }) => {
23 normalModuleFactory.hooks.resolveForScheme
24 .for("https")
25 .tap("HttpsUriPlugin", resourceData => {
26 const url = new URL(resourceData.resource);
27 resourceData.path = url.origin + url.pathname;
28 resourceData.query = url.search;
29 resourceData.fragment = url.hash;
30 return /** @type {true} */ (true);
31 });
32 NormalModule.getCompilationHooks(compilation)
33 .readResourceForScheme.for("https")
34 .tapAsync("HttpsUriPlugin", (resource, module, callback) => {
35 return require("https").get(new URL(resource), res => {
36 if (res.statusCode !== 200) {
37 res.destroy();
38 return callback(
39 new Error(`https request status code = ${res.statusCode}`)
40 );
41 }
42
43 const bufferArr = [];
44
45 res.on("data", chunk => {
46 bufferArr.push(chunk);
47 });
48
49 res.on("end", () => {
50 if (!res.complete) {
51 return callback(new Error("https request was terminated"));
52 }
53
54 callback(null, Buffer.concat(bufferArr));
55 });
56 });
57 });
58 }
59 );
60 }
61}
62
63module.exports = HttpsUriPlugin;