0.2.0 - Mid migration

This commit is contained in:
Daniel Mason 2022-04-25 14:47:15 +12:00
parent 139e6a915e
commit 7e38fdbd7d
42393 changed files with 5358157 additions and 62 deletions

View file

@ -0,0 +1,3 @@
'use strict';
module.exports = class DevMiddlewareError extends Error {};

106
web/node_modules/webpack-dev-middleware/lib/context.js generated vendored Normal file
View file

@ -0,0 +1,106 @@
'use strict';
const weblog = require('webpack-log');
module.exports = function ctx(compiler, options) {
const context = {
state: false,
webpackStats: null,
callbacks: [],
options,
compiler,
watching: null,
forceRebuild: false,
};
if (options.logger) {
context.log = options.logger;
} else {
context.log = weblog({
level: options.logLevel || 'info',
name: 'wdm',
timestamp: options.logTime,
});
}
const { log } = context;
function done(stats) {
// We are now on valid state
context.state = true;
context.webpackStats = stats;
// Do the stuff in nextTick, because bundle may be invalidated
// if a change happened while compiling
process.nextTick(() => {
// check if still in valid state
if (!context.state) {
return;
}
// print webpack output
context.options.reporter(context.options, {
log,
state: true,
stats,
});
// execute callback that are delayed
const cbs = context.callbacks;
context.callbacks = [];
cbs.forEach((cb) => {
cb(stats);
});
});
// In lazy mode, we may issue another rebuild
if (context.forceRebuild) {
context.forceRebuild = false;
rebuild();
}
}
function invalid(callback) {
if (context.state) {
context.options.reporter(context.options, {
log,
state: false,
});
}
// We are now in invalid state
context.state = false;
if (typeof callback === 'function') {
callback();
}
}
function rebuild() {
if (context.state) {
context.state = false;
context.compiler.run((err) => {
if (err) {
log.error(err.stack || err);
if (err.details) {
log.error(err.details);
}
}
});
} else {
context.forceRebuild = true;
}
}
context.rebuild = rebuild;
context.compiler.hooks.invalid.tap('WebpackDevMiddleware', invalid);
context.compiler.hooks.run.tap('WebpackDevMiddleware', invalid);
context.compiler.hooks.done.tap('WebpackDevMiddleware', done);
context.compiler.hooks.watchRun.tap(
'WebpackDevMiddleware',
(comp, callback) => {
invalid(callback);
}
);
return context;
};

140
web/node_modules/webpack-dev-middleware/lib/fs.js generated vendored Normal file
View file

@ -0,0 +1,140 @@
'use strict';
const fs = require('fs');
const path = require('path');
const MemoryFileSystem = require('memory-fs');
const mkdirp = require('mkdirp');
const { colors } = require('webpack-log');
const DevMiddlewareError = require('./DevMiddlewareError');
module.exports = {
toDisk(context) {
const compilers = context.compiler.compilers || [context.compiler];
for (const compiler of compilers) {
compiler.hooks.emit.tap('WebpackDevMiddleware', (compilation) => {
if (compiler.hasWebpackDevMiddlewareAssetEmittedCallback) {
return;
}
compiler.hooks.assetEmitted.tapAsync(
'WebpackDevMiddleware',
(file, info, callback) => {
let targetPath = null;
let content = null;
// webpack@5
if (info.compilation) {
({ targetPath, content } = info);
} else {
let targetFile = file;
const queryStringIdx = targetFile.indexOf('?');
if (queryStringIdx >= 0) {
targetFile = targetFile.substr(0, queryStringIdx);
}
let { outputPath } = compiler;
// TODO Why? Need remove in future major release
if (outputPath === '/') {
outputPath = compiler.context;
}
outputPath = compilation.getPath(outputPath, {});
content = info;
targetPath = path.join(outputPath, targetFile);
}
const { writeToDisk: filter } = context.options;
const allowWrite =
filter && typeof filter === 'function'
? filter(targetPath)
: true;
if (!allowWrite) {
return callback();
}
const { log } = context;
const dir = path.dirname(targetPath);
return mkdirp(dir, (mkdirpError) => {
if (mkdirpError) {
return callback(mkdirpError);
}
return fs.writeFile(targetPath, content, (writeFileError) => {
if (writeFileError) {
return callback(writeFileError);
}
log.debug(
colors.cyan(
`Asset written to disk: ${path.relative(
process.cwd(),
targetPath
)}`
)
);
return callback();
});
});
}
);
compiler.hasWebpackDevMiddlewareAssetEmittedCallback = true;
});
}
},
setFs(context, compiler) {
if (
typeof compiler.outputPath === 'string' &&
!path.posix.isAbsolute(compiler.outputPath) &&
!path.win32.isAbsolute(compiler.outputPath)
) {
throw new DevMiddlewareError(
'`output.path` needs to be an absolute path or `/`.'
);
}
let fileSystem;
// store our files in memory
const isConfiguredFs = context.options.fs;
const isMemoryFs =
!isConfiguredFs &&
!compiler.compilers &&
compiler.outputFileSystem instanceof MemoryFileSystem;
if (isConfiguredFs) {
// eslint-disable-next-line no-shadow
const { fs } = context.options;
if (typeof fs.join !== 'function') {
// very shallow check
throw new Error(
'Invalid options: options.fs.join() method is expected'
);
}
// eslint-disable-next-line no-param-reassign
compiler.outputFileSystem = fs;
fileSystem = fs;
} else if (isMemoryFs) {
fileSystem = compiler.outputFileSystem;
} else {
fileSystem = new MemoryFileSystem();
// eslint-disable-next-line no-param-reassign
compiler.outputFileSystem = fileSystem;
}
// eslint-disable-next-line no-param-reassign
context.fs = fileSystem;
},
};

View file

@ -0,0 +1,136 @@
'use strict';
const path = require('path');
const mime = require('mime');
const DevMiddlewareError = require('./DevMiddlewareError');
const {
getFilenameFromUrl,
handleRangeHeaders,
handleRequest,
ready,
} = require('./util');
// Do not add a charset to the Content-Type header of these file types
// otherwise the client will fail to render them correctly.
const NonCharsetFileTypes = /\.(wasm|usdz)$/;
module.exports = function wrapper(context) {
return function middleware(req, res, next) {
// fixes #282. credit @cexoso. in certain edge situations res.locals is
// undefined.
// eslint-disable-next-line no-param-reassign
res.locals = res.locals || {};
function goNext() {
if (!context.options.serverSideRender) {
return next();
}
return new Promise((resolve) => {
ready(
context,
() => {
// eslint-disable-next-line no-param-reassign
res.locals.webpackStats = context.webpackStats;
// eslint-disable-next-line no-param-reassign
res.locals.fs = context.fs;
resolve(next());
},
req
);
});
}
const acceptedMethods = context.options.methods || ['GET', 'HEAD'];
if (acceptedMethods.indexOf(req.method) === -1) {
return goNext();
}
let filename = getFilenameFromUrl(
context.options.publicPath,
context.compiler,
req.url
);
if (filename === false) {
return goNext();
}
return new Promise((resolve) => {
handleRequest(context, filename, processRequest, req);
// eslint-disable-next-line consistent-return
function processRequest() {
try {
let stat = context.fs.statSync(filename);
if (!stat.isFile()) {
if (stat.isDirectory()) {
let { index } = context.options;
// eslint-disable-next-line no-undefined
if (index === undefined || index === true) {
index = 'index.html';
} else if (!index) {
throw new DevMiddlewareError('next');
}
filename = path.posix.join(filename, index);
stat = context.fs.statSync(filename);
if (!stat.isFile()) {
throw new DevMiddlewareError('next');
}
} else {
throw new DevMiddlewareError('next');
}
}
} catch (e) {
return resolve(goNext());
}
// server content
let content = context.fs.readFileSync(filename);
content = handleRangeHeaders(content, req, res);
let contentType = mime.getType(filename) || '';
if (!NonCharsetFileTypes.test(filename)) {
contentType += '; charset=UTF-8';
}
if (!res.getHeader || !res.getHeader('Content-Type')) {
res.setHeader('Content-Type', contentType);
}
res.setHeader('Content-Length', content.length);
const { headers } = context.options;
if (headers) {
for (const name in headers) {
if ({}.hasOwnProperty.call(headers, name)) {
res.setHeader(name, context.options.headers[name]);
}
}
}
// Express automatically sets the statusCode to 200, but not all servers do (Koa).
// eslint-disable-next-line no-param-reassign
res.statusCode = res.statusCode || 200;
if (res.send) {
res.send(content);
} else {
res.end(content);
}
resolve();
}
});
};
};

View file

@ -0,0 +1,32 @@
'use strict';
module.exports = function reporter(middlewareOptions, options) {
const { log, state, stats } = options;
if (state) {
const displayStats = middlewareOptions.stats !== false;
const statsString = stats.toString(middlewareOptions.stats);
// displayStats only logged
if (displayStats && statsString.trim().length) {
if (stats.hasErrors()) {
log.error(statsString);
} else if (stats.hasWarnings()) {
log.warn(statsString);
} else {
log.info(statsString);
}
}
let message = 'Compiled successfully.';
if (stats.hasErrors()) {
message = 'Failed to compile.';
} else if (stats.hasWarnings()) {
message = 'Compiled with warnings.';
}
log.info(message);
} else {
log.info('Compiling...');
}
};

188
web/node_modules/webpack-dev-middleware/lib/util.js generated vendored Normal file
View file

@ -0,0 +1,188 @@
'use strict';
const path = require('path');
const { parse } = require('url');
const querystring = require('querystring');
const parseRange = require('range-parser');
const HASH_REGEXP = /[0-9a-f]{10,}/;
// support for multi-compiler configuration
// see: https://github.com/webpack/webpack-dev-server/issues/641
function getPaths(publicPath, compiler, url) {
const compilers = compiler && compiler.compilers;
if (Array.isArray(compilers)) {
let compilerPublicPath;
// the path portion of compilerPublicPath
let compilerPublicPathBase;
for (let i = 0; i < compilers.length; i++) {
compilerPublicPath =
compilers[i].options &&
compilers[i].options.output &&
compilers[i].options.output.publicPath;
if (compilerPublicPath) {
compilerPublicPathBase =
compilerPublicPath.indexOf('/') === 0
? compilerPublicPath // eslint-disable-next-line
: // handle the case where compilerPublicPath is a URL with hostname
parse(compilerPublicPath).pathname;
// check the url vs the path part of the compilerPublicPath
if (url.indexOf(compilerPublicPathBase) === 0) {
return {
publicPath: compilerPublicPath,
outputPath: compilers[i].outputPath,
};
}
}
}
}
return {
publicPath,
outputPath: compiler.outputPath,
};
}
// eslint-disable-next-line consistent-return
function ready(context, fn, req) {
if (context.state) {
return fn(context.webpackStats);
}
context.log.info(`wait until bundle finished: ${req.url || fn.name}`);
context.callbacks.push(fn);
}
module.exports = {
getFilenameFromUrl(pubPath, compiler, url) {
const { outputPath, publicPath } = getPaths(pubPath, compiler, url);
// localPrefix is the folder our bundle should be in
const localPrefix = parse(publicPath || '/', false, true);
const urlObject = parse(url);
let filename;
const hostNameIsTheSame = localPrefix.hostname === urlObject.hostname;
// publicPath has the hostname that is not the same as request url's, should fail
if (
localPrefix.hostname !== null &&
urlObject.hostname !== null &&
!hostNameIsTheSame
) {
return false;
}
// publicPath is not in url, so it should fail
if (publicPath && hostNameIsTheSame && url.indexOf(publicPath) !== 0) {
return false;
}
// strip localPrefix from the start of url
if (urlObject.pathname.indexOf(localPrefix.pathname) === 0) {
filename = urlObject.pathname.substr(localPrefix.pathname.length);
}
if (
!urlObject.hostname &&
localPrefix.hostname &&
url.indexOf(localPrefix.path) !== 0
) {
return false;
}
let uri = outputPath;
/* istanbul ignore if */
if (process.platform === 'win32') {
// Path Handling for Microsoft Windows
if (filename) {
uri = path.posix.join(outputPath || '', querystring.unescape(filename));
if (!path.win32.isAbsolute(uri)) {
uri = `/${uri}`;
}
}
return uri;
}
// Path Handling for all other operating systems
if (filename) {
uri = path.posix.join(outputPath || '', filename);
if (!path.posix.isAbsolute(uri)) {
uri = `/${uri}`;
}
}
// if no matches, use outputPath as filename
return querystring.unescape(uri);
},
handleRangeHeaders(content, req, res) {
// assumes express API. For other servers, need to add logic to access
// alternative header APIs
res.setHeader('Accept-Ranges', 'bytes');
if (req.headers.range) {
const ranges = parseRange(content.length, req.headers.range);
// unsatisfiable
if (ranges === -1) {
res.setHeader('Content-Range', `bytes */${content.length}`);
// eslint-disable-next-line no-param-reassign
res.statusCode = 416;
}
// valid (syntactically invalid/multiple ranges are treated as a
// regular response)
if (ranges !== -2 && ranges.length === 1) {
const { length } = content;
// Content-Range
// eslint-disable-next-line no-param-reassign
res.statusCode = 206;
res.setHeader(
'Content-Range',
`bytes ${ranges[0].start}-${ranges[0].end}/${length}`
);
// eslint-disable-next-line no-param-reassign
content = content.slice(ranges[0].start, ranges[0].end + 1);
}
}
return content;
},
handleRequest(context, filename, processRequest, req) {
// in lazy mode, rebuild on bundle request
if (
context.options.lazy &&
(!context.options.filename || context.options.filename.test(filename))
) {
context.rebuild();
}
if (HASH_REGEXP.test(filename)) {
try {
if (context.fs.statSync(filename).isFile()) {
processRequest();
return;
}
} catch (e) {
// eslint-disable-line
}
}
ready(context, processRequest, req);
},
noop: () => {},
ready,
};