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,26 @@
/* global __webpack_dev_server_client__ */
const url = require('native-url');
const getSocketUrlParts = require('./utils/getSocketUrlParts');
/**
* Initializes a socket server for HMR for webpack-dev-server.
* @param {function(*): void} messageHandler A handler to consume Webpack compilation messages.
* @param {string} [resourceQuery] Webpack's `__resourceQuery` string.
* @returns {void}
*/
function initWDSSocket(messageHandler, resourceQuery) {
if (typeof __webpack_dev_server_client__ !== 'undefined') {
const SocketClient = __webpack_dev_server_client__;
const urlParts = getSocketUrlParts(resourceQuery);
const connection = new SocketClient(url.format(urlParts));
connection.onMessage(function onSocketMessage(data) {
const message = JSON.parse(data);
messageHandler(message);
});
}
}
module.exports = initWDSSocket;

View file

@ -0,0 +1,31 @@
/**
* The hard-coded singleton key for webpack-hot-middleware's client instance.
*
* [Ref](https://github.com/webpack-contrib/webpack-hot-middleware/blob/cb29abb9dde435a1ac8e9b19f82d7d36b1093198/client.js#L152)
*/
const singletonKey = '__webpack_hot_middleware_reporter__';
/**
* Initializes a socket server for HMR for webpack-hot-middleware.
* @param {function(*): void} messageHandler A handler to consume Webpack compilation messages.
* @returns {void}
*/
function initWHMEventSource(messageHandler) {
const client = window[singletonKey] || require('webpack-hot-middleware/client');
client.useCustomOverlay({
showProblems: function showProblems(type, data) {
const error = {
type,
data,
};
messageHandler(error);
},
clear: function clear() {
messageHandler({ type: 'ok' });
},
});
}
module.exports = initWHMEventSource;

View file

@ -0,0 +1,51 @@
/* global ʎɐɹɔosǝʌɹǝs */
/**
* Initializes a socket server for HMR for webpack-plugin-serve.
* @param {function(*): void} messageHandler A handler to consume Webpack compilation messages.
* @returns {void}
*/
function initWPSSocket(messageHandler) {
/**
* The hard-coded options injection key from webpack-plugin-serve.
*
* [Ref](https://github.com/shellscape/webpack-plugin-serve/blob/aeb49f14e900802c98df4a4607a76bc67b1cffdf/lib/index.js#L258)
* @type {Object | undefined}
*/
let options;
try {
options = ʎɐɹɔosǝʌɹǝs;
} catch (e) {
// Bail out because this indicates the plugin is not included
return;
}
const { ClientSocket } = require('webpack-plugin-serve/lib/client/ClientSocket');
const { address, client = {}, secure } = options;
const protocol = secure ? 'wss' : 'ws';
const socket = new ClientSocket(client, protocol + '://' + (client.address || address) + '/wps');
socket.addEventListener('message', function listener(message) {
const { action, data } = JSON.parse(message.data);
switch (action) {
case 'done': {
messageHandler({ type: 'ok' });
break;
}
case 'problems': {
if (data.errors.length) {
messageHandler({ type: 'errors', data: data.errors });
} else if (data.warnings.length) {
messageHandler({ type: 'warnings', data: data.warnings });
}
break;
}
default: {
// Do nothing
}
}
});
}
module.exports = initWPSSocket;

View file

@ -0,0 +1,22 @@
/**
* Gets the source (i.e. host) of the script currently running.
* @returns {string}
*/
function getCurrentScriptSource() {
// `document.currentScript` is the most accurate way to get the current running script,
// but is not supported in all browsers (most notably, IE).
if (document.currentScript) {
return document.currentScript.getAttribute('src');
}
// Fallback to getting all scripts running in the document.
const scriptElements = document.scripts || [];
const currentScript = scriptElements[scriptElements.length - 1];
if (currentScript) {
return currentScript.getAttribute('src');
}
throw new Error('[React Refresh] Failed to get current script source!');
}
module.exports = getCurrentScriptSource;

View file

@ -0,0 +1,94 @@
const url = require('native-url');
const getCurrentScriptSource = require('./getCurrentScriptSource');
const parseQuery = require('./parseQuery');
/**
* @typedef {Object} SocketUrlParts
* @property {string} [auth]
* @property {string} [hostname]
* @property {string} [protocol]
* @property {string} [pathname]
* @property {string} [port]
*/
/**
* Parse current location and Webpack's `__resourceQuery` into parts that can create a valid socket URL.
* @param {string} [resourceQuery] The Webpack `__resourceQuery` string.
* @returns {SocketUrlParts} The parsed URL parts.
* @see https://webpack.js.org/api/module-variables/#__resourcequery-webpack-specific
*/
function getSocketUrlParts(resourceQuery) {
const scriptSource = getCurrentScriptSource();
const urlParts = url.parse(scriptSource);
/** @type {string | undefined} */
let auth;
let hostname = urlParts.hostname;
let protocol = urlParts.protocol;
let pathname = '/sockjs-node'; // This is hard-coded in WDS
let port = urlParts.port;
// FIXME:
// This is a hack to work-around `native-url`'s parse method,
// which filters out falsy values when concatenating the `auth` string.
// In reality, we need to check for both values to correctly inject them.
// Ref: GoogleChromeLabs/native-url#32
// The placeholder `baseURL` is to allow parsing of relative paths,
// and will have no effect if `scriptSource` is a proper URL.
const authUrlParts = new URL(scriptSource, 'http://foo.bar');
// Parse authentication credentials in case we need them
if (authUrlParts.username) {
auth = authUrlParts.username;
// Since HTTP basic authentication does not allow empty username,
// we only include password if the username is not empty.
if (authUrlParts.password) {
// Result: <username>:<password>
auth = auth.concat(':', authUrlParts.password);
}
}
// Check for IPv4 and IPv6 host addresses that corresponds to `any`/`empty`.
// This is important because `hostname` can be empty for some hosts,
// such as `about:blank` or `file://` URLs.
const isEmptyHostname =
urlParts.hostname === '0.0.0.0' || urlParts.hostname === '::' || urlParts.hostname === null;
// We only re-assign the hostname if we are using HTTP/HTTPS protocols
if (
isEmptyHostname &&
window.location.hostname &&
window.location.protocol.indexOf('http') !== -1
) {
hostname = window.location.hostname;
}
// We only re-assign `protocol` when `hostname` is available and is empty,
// since otherwise we risk creating an invalid URL.
// We also do this when `https` is used as it mandates the use of secure sockets.
if (hostname && (isEmptyHostname || window.location.protocol === 'https:')) {
protocol = window.location.protocol;
}
// We only re-assign port when it is not available or `empty`
if (!port || port === '0') {
port = window.location.port;
}
// If the resource query is available,
// parse it and overwrite everything we received from the script host.
const parsedQuery = parseQuery(resourceQuery || '');
hostname = parsedQuery.sockHost || hostname;
pathname = parsedQuery.sockPath || pathname;
port = parsedQuery.sockPort || port;
return {
auth: auth,
hostname: hostname,
pathname: pathname,
protocol: protocol,
port: port,
};
}
module.exports = getSocketUrlParts;

View file

@ -0,0 +1,33 @@
/**
* Parse a query string into an object.
* @param {string} [querystring] The query string.
* @returns {Record<string, string>} The parsed query object.
*/
function parseQuery(querystring) {
let query = '';
if (typeof querystring === 'string') {
query = querystring;
}
/**
* Transform query strings such as `?foo1=bar1&foo2=bar2`:
* - remove `?` from the start
* - split with `&`
* - split pairs with `=`
* The resulting format will be { foo1: 'bar1', foo2: 'bar2' }
*/
return query
.replace(/^\?/, '')
.split('&')
.reduce(function (acc, entry) {
const pair = entry.split('=');
// Add all non-empty entries to the accumulated object
if (pair[0]) {
acc[pair[0]] = pair[1];
}
return acc;
}, {});
}
module.exports = parseQuery;