diff options
Diffstat (limited to 'node_modules/vuepress-html-webpack-plugin/lib')
4 files changed, 322 insertions, 0 deletions
diff --git a/node_modules/vuepress-html-webpack-plugin/lib/chunksorter.js b/node_modules/vuepress-html-webpack-plugin/lib/chunksorter.js new file mode 100644 index 00000000..36b5c9a9 --- /dev/null +++ b/node_modules/vuepress-html-webpack-plugin/lib/chunksorter.js @@ -0,0 +1,139 @@ +'use strict'; + +const toposort = require('toposort'); +const _ = require('lodash'); + +/** + Sorts dependencies between chunks by their "parents" attribute. + + This function sorts chunks based on their dependencies with each other. + The parent relation between chunks as generated by Webpack for each chunk + is used to define a directed (and hopefully acyclic) graph, which is then + topologically sorted in order to retrieve the correct order in which + chunks need to be embedded into HTML. A directed edge in this graph is + describing a "is parent of" relationship from a chunk to another (distinct) + chunk. Thus topological sorting orders chunks from bottom-layer chunks to + highest level chunks that use the lower-level chunks. + + @param {Array} chunks an array of chunks as generated by the html-webpack-plugin. + - For webpack < 4, It is assumed that each entry contains at least the properties + "id" (containing the chunk id) and "parents" (array containing the ids of the + parent chunks). + - For webpack 4+ the see the chunkGroups param for parent-child relationships + + @param {Array} chunks an array of ChunkGroups that has a getParents method. + Each ChunkGroup contains a list of chunks in order. + + @return {Array} A topologically sorted version of the input chunks +*/ +module.exports.dependency = (chunks, options, compilation) => { + const chunkGroups = compilation.chunkGroups; + if (!chunks) { + return chunks; + } + + // We build a map (chunk-id -> chunk) for faster access during graph building. + const nodeMap = {}; + + chunks.forEach(chunk => { + nodeMap[chunk.id] = chunk; + }); + + // Next, we add an edge for each parent relationship into the graph + let edges = []; + + if (chunkGroups) { + // Add an edge for each parent (parent -> child) + edges = chunkGroups.reduce((result, chunkGroup) => result.concat( + Array.from(chunkGroup.parentsIterable, parentGroup => [parentGroup, chunkGroup]) + ), []); + const sortedGroups = toposort.array(chunkGroups, edges); + // flatten chunkGroup into chunks + const sortedChunks = sortedGroups + .reduce((result, chunkGroup) => result.concat(chunkGroup.chunks), []) + .map(chunk => // use the chunk from the list passed in, since it may be a filtered list + nodeMap[chunk.id]) + .filter((chunk, index, self) => { + // make sure exists (ie excluded chunks not in nodeMap) + const exists = !!chunk; + // make sure we have a unique list + const unique = self.indexOf(chunk) === index; + return exists && unique; + }); + return sortedChunks; + } else { + // before webpack 4 there was no chunkGroups + chunks.forEach(chunk => { + if (chunk.parents) { + // Add an edge for each parent (parent -> child) + chunk.parents.forEach(parentId => { + // webpack2 chunk.parents are chunks instead of string id(s) + const parentChunk = _.isObject(parentId) ? parentId : nodeMap[parentId]; + // If the parent chunk does not exist (e.g. because of an excluded chunk) + // we ignore that parent + if (parentChunk) { + edges.push([parentChunk, chunk]); + } + }); + } + }); + // We now perform a topological sorting on the input chunks and built edges + return toposort.array(chunks, edges); + } +}; + +/** + * Sorts the chunks based on the chunk id. + * + * @param {Array} chunks the list of chunks to sort + * @return {Array} The sorted list of chunks + */ +module.exports.id = chunks => chunks.sort(function orderEntryLast (a, b) { + if (a.entry !== b.entry) { + return b.entry ? 1 : -1; + } else { + return b.id - a.id; + } +}); + +/** + * Performs identity mapping (no-sort). + * @param {Array} chunks the chunks to sort + * @return {Array} The sorted chunks + */ +module.exports.none = chunks => chunks; + +/** + * Sort manually by the chunks + * @param {Array} chunks the chunks to sort + * @return {Array} The sorted chunks + */ +module.exports.manual = (chunks, options) => { + const specifyChunks = options.chunks; + const chunksResult = []; + let filterResult = []; + if (Array.isArray(specifyChunks)) { + for (var i = 0; i < specifyChunks.length; i++) { + filterResult = chunks.filter(chunk => { + if (chunk.names[0] && chunk.names[0] === specifyChunks[i]) { + return true; + } + return false; + }); + filterResult.length > 0 && chunksResult.push(filterResult[0]); + } + } + return chunksResult; +}; + +/** + * Defines the default sorter. + */ +module.exports.auto = module.exports.id; + +// In webpack 2 the ids have been flipped. +// Therefore the id sort doesn't work the same way as it did for webpack 1 +// Luckily the dependency sort is working as expected +if (Number(require('webpack/package.json').version.split('.')[0]) > 1) { + module.exports.auto = module.exports.dependency; +} diff --git a/node_modules/vuepress-html-webpack-plugin/lib/compiler.js b/node_modules/vuepress-html-webpack-plugin/lib/compiler.js new file mode 100644 index 00000000..d5c91b6c --- /dev/null +++ b/node_modules/vuepress-html-webpack-plugin/lib/compiler.js @@ -0,0 +1,125 @@ +/* + * This file uses webpack to compile a template with a child compiler. + * + * [TEMPLATE] -> [JAVASCRIPT] + * + */ +'use strict'; +const path = require('path'); +const NodeTemplatePlugin = require('webpack/lib/node/NodeTemplatePlugin'); +const NodeTargetPlugin = require('webpack/lib/node/NodeTargetPlugin'); +const LoaderTargetPlugin = require('webpack/lib/LoaderTargetPlugin'); +const LibraryTemplatePlugin = require('webpack/lib/LibraryTemplatePlugin'); +const SingleEntryPlugin = require('webpack/lib/SingleEntryPlugin'); + +/** + * Compiles the template into a nodejs factory, adds its to the compilation.assets + * and returns a promise of the result asset object. + * + * @param template relative path to the template file + * @param context path context + * @param outputFilename the file name + * @param compilation The webpack compilation object + * + * Returns an object: + * { + * hash: {String} - Base64 hash of the file + * content: {String} - Javascript executable code of the template + * } + * + */ +module.exports.compileTemplate = function compileTemplate (template, context, outputFilename, compilation) { + // The entry file is just an empty helper as the dynamic template + // require is added in "loader.js" + const outputOptions = { + filename: outputFilename, + publicPath: compilation.outputOptions.publicPath + }; + // Store the result of the parent compilation before we start the child compilation + const assetsBeforeCompilation = Object.assign({}, compilation.assets[outputOptions.filename]); + // Create an additional child compiler which takes the template + // and turns it into an Node.JS html factory. + // This allows us to use loaders during the compilation + const compilerName = getCompilerName(context, outputFilename); + const childCompiler = compilation.createChildCompiler(compilerName, outputOptions); + childCompiler.context = context; + new NodeTemplatePlugin(outputOptions).apply(childCompiler); + new NodeTargetPlugin().apply(childCompiler); + new LibraryTemplatePlugin('HTML_WEBPACK_PLUGIN_RESULT', 'var').apply(childCompiler); + + // Using undefined as name for the SingleEntryPlugin causes a unexpected output as described in + // https://github.com/jantimon/html-webpack-plugin/issues/895 + // Using a string as a name for the SingleEntryPlugin causes problems with HMR as described in + // https://github.com/jantimon/html-webpack-plugin/issues/900 + // Until the HMR issue is fixed we keep the ugly output: + new SingleEntryPlugin(this.context, template, undefined).apply(childCompiler); + + new LoaderTargetPlugin('node').apply(childCompiler); + + // Fix for "Uncaught TypeError: __webpack_require__(...) is not a function" + // Hot module replacement requires that every child compiler has its own + // cache. @see https://github.com/ampedandwired/html-webpack-plugin/pull/179 + + // Backwards compatible version of: childCompiler.hooks.compilation + (childCompiler.hooks ? childCompiler.hooks.compilation.tap.bind(childCompiler.hooks.compilation, 'HtmlWebpackPlugin') : childCompiler.plugin.bind(childCompiler, 'compilation'))(compilation => { + if (compilation.cache) { + if (!compilation.cache[compilerName]) { + compilation.cache[compilerName] = {}; + } + compilation.cache = compilation.cache[compilerName]; + } + }); + + // Compile and return a promise + return new Promise((resolve, reject) => { + childCompiler.runAsChild((err, entries, childCompilation) => { + // Resolve / reject the promise + if (childCompilation && childCompilation.errors && childCompilation.errors.length) { + const errorDetails = childCompilation.errors.map(error => error.message + (error.error ? ':\n' + error.error : '')).join('\n'); + reject(new Error('Child compilation failed:\n' + errorDetails)); + } else if (err) { + reject(err); + } else { + // Replace [hash] placeholders in filename + // In webpack 4 the plugin interface changed, so check for available fns + const outputName = compilation.mainTemplate.getAssetPath + ? compilation.mainTemplate.hooks.assetPath.call(outputOptions.filename, { + hash: childCompilation.hash, + chunk: entries[0] + }) + : compilation.mainTemplate.applyPluginsWaterfall( + 'asset-path', + outputOptions.filename, + { + hash: childCompilation.hash, + chunk: entries[0] + }); + + // Restore the parent compilation to the state like it + // was before the child compilation + compilation.assets[outputName] = assetsBeforeCompilation[outputName]; + if (assetsBeforeCompilation[outputName] === undefined) { + // If it wasn't there - delete it + delete compilation.assets[outputName]; + } + resolve({ + // Hash of the template entry point + hash: entries[0].hash, + // Output name + outputName: outputName, + // Compiled code + content: childCompilation.assets[outputName].source() + }); + } + }); + }); +}; + +/** + * Returns the child compiler name e.g. 'html-webpack-plugin for "index.html"' + */ +function getCompilerName (context, filename) { + const absolutePath = path.resolve(context, filename); + const relativePath = path.relative(context, absolutePath); + return 'html-webpack-plugin for "' + (absolutePath.length < relativePath.length ? absolutePath : relativePath) + '"'; +} diff --git a/node_modules/vuepress-html-webpack-plugin/lib/errors.js b/node_modules/vuepress-html-webpack-plugin/lib/errors.js new file mode 100644 index 00000000..2b946dad --- /dev/null +++ b/node_modules/vuepress-html-webpack-plugin/lib/errors.js @@ -0,0 +1,23 @@ +'use strict'; +const PrettyError = require('pretty-error'); +const prettyError = new PrettyError(); +prettyError.withoutColors(); +prettyError.skipPackage(['html-plugin-evaluation']); +prettyError.skipNodeFiles(); +prettyError.skip(function (traceLine) { + return traceLine.path === 'html-plugin-evaluation'; +}); + +module.exports = function (err, context) { + return { + toHtml: function () { + return 'Html Webpack Plugin:\n<pre>\n' + this.toString() + '</pre>'; + }, + toJsonHtml: function () { + return JSON.stringify(this.toHtml()); + }, + toString: function () { + return prettyError.render(err).replace(/webpack:\/\/\/\./g, context); + } + }; +}; diff --git a/node_modules/vuepress-html-webpack-plugin/lib/loader.js b/node_modules/vuepress-html-webpack-plugin/lib/loader.js new file mode 100644 index 00000000..c1062d1f --- /dev/null +++ b/node_modules/vuepress-html-webpack-plugin/lib/loader.js @@ -0,0 +1,35 @@ +/* This loader renders the template with underscore if no other loader was found */ +'use strict'; + +const _ = require('lodash'); +const loaderUtils = require('loader-utils'); + +module.exports = function (source) { + if (this.cacheable) { + this.cacheable(); + } + const allLoadersButThisOne = this.loaders.filter(function (loader) { + // Loader API changed from `loader.module` to `loader.normal` in Webpack 2. + return (loader.module || loader.normal) !== module.exports; + }); + // This loader shouldn't kick in if there is any other loader + if (allLoadersButThisOne.length > 0) { + return source; + } + // Skip .js files + if (/\.js$/.test(this.resourcePath)) { + return source; + } + + // The following part renders the tempalte with lodash as aminimalistic loader + // + // Get templating options + const options = this.query !== '' ? loaderUtils.parseQuery(this.query) : {}; + const template = _.template(source, _.defaults(options, { variable: 'data' })); + // Require !!lodash - using !! will disable all loaders (e.g. babel) + return 'var _ = require(' + loaderUtils.stringifyRequest(this, '!!' + require.resolve('lodash')) + ');' + + 'module.exports = function (templateParams) { with(templateParams) {' + + // Execute the lodash template + 'return (' + template.source + ')();' + + '}}'; +}; |
