🎥 Make videos programmatically with React
start inlining hot middleware
Jonny Burger47d6790aa948
diff --git a/packages/bundler/patches/webpack-hot-middleware+2.25.0.patch b/packages/bundler/patches/webpack-hot-middleware+2.25.0.patchdeleted file mode 100644index 5c569a6832..0000000000--- a/packages/bundler/patches/webpack-hot-middleware+2.25.0.patch+++ /dev/null@@ -1,44 +0,0 @@-diff --git a/node_modules/webpack-hot-middleware/client-overlay.js b/node_modules/webpack-hot-middleware/client-overlay.js-index 73e40c6..be4ced2 100644---- a/node_modules/webpack-hot-middleware/client-overlay.js-+++ b/node_modules/webpack-hot-middleware/client-overlay.js-@@ -40,7 +40,9 @@ var entities = new Entities();-- function showProblems(type, lines) {- clientOverlay.innerHTML = '';-- lines.forEach(function(msg) {-+ lines.forEach(function(line) {-+ var isNested = typeof line === 'object';-+ var msg = isNested ? line.moduleName + '\n\n' + line.message : line;- msg = ansiHTML(entities.encode(msg));- var div = document.createElement('div');- div.style.marginBottom = '26px';-diff --git a/node_modules/webpack-hot-middleware/client.js b/node_modules/webpack-hot-middleware/client.js-index abc95ed..b04b429 100644---- a/node_modules/webpack-hot-middleware/client.js-+++ b/node_modules/webpack-hot-middleware/client.js-@@ -176,8 +176,10 @@ function createReporter() {- var previousProblems = null;- function log(type, obj) {- var newProblems = obj[type]-- .map(function(msg) {-- return strip(msg);-+ .map(function(problem) {-+ var isNested = typeof problem === 'object';-+ var message = isNested ? problem.message : problem;-+ return strip(message);- })- .join('\n');- if (previousProblems == newProblems) {-diff --git a/node_modules/webpack-hot-middleware/middleware.js b/node_modules/webpack-hot-middleware/middleware.js-index a5d7384..261a21a 100644---- a/node_modules/webpack-hot-middleware/middleware.js-+++ b/node_modules/webpack-hot-middleware/middleware.js-@@ -122,6 +122,7 @@ function publishStats(action, statsResult, eventStream, log) {- modules: true,- timings: true,- hash: true,-+ errors: true- });- // For multi-compiler, stats will be an object with a 'children' array of stats- var bundles = extractBundles(stats);diff --git a/packages/bundler/src/hot-middleware/client.ts b/packages/bundler/src/hot-middleware/client.tsnew file mode 100644index 0000000000..50b696cb0d--- /dev/null+++ b/packages/bundler/src/hot-middleware/client.ts@@ -0,0 +1,268 @@+import {processUpdate} from './process-update';++const options = {+ path: '/__webpack_hmr',+ timeout: 20 * 1000,+ overlay: true,+ reload: false,+ log: true,+ warn: true,+ name: '',+ autoConnect: true,+ overlayStyles: {},+ overlayWarnings: false,+ ansiColors: {},+};++if (typeof window === 'undefined') {+ // do nothing+} else if (typeof window.EventSource === 'undefined') {+ console.warn(+ 'Unsupported browser: You need a browser that supports EventSource '+ );+} else if (options.autoConnect) {+ connect();+}++function setOptionsAndConnect() {+ connect();+}++function EventSourceWrapper() {+ let source: EventSource;+ let lastActivity = Date.now();+ const listeners = [];++ init();+ const timer = setInterval(() => {+ if (Date.now() - lastActivity > options.timeout) {+ handleDisconnect();+ }+ }, options.timeout / 2);++ function init() {+ source = new window.EventSource(options.path);+ source.onopen = handleOnline;+ source.onerror = handleDisconnect;+ source.onmessage = handleMessage;+ }++ function handleOnline() {+ if (options.log) console.log('[HMR] connected');+ lastActivity = Date.now();+ }++ function handleMessage(event) {+ lastActivity = Date.now();+ for (let i = 0; i < listeners.length; i++) {+ listeners[i](event);+ }+ }++ function handleDisconnect() {+ clearInterval(timer);+ source.close();+ setTimeout(init, options.timeout);+ }++ return {+ addMessageListener(fn) {+ listeners.push(fn);+ },+ };+}++function getEventSourceWrapper() {+ if (!window.__whmEventSourceWrapper) {+ window.__whmEventSourceWrapper = {};+ }++ if (!window.__whmEventSourceWrapper[options.path]) {+ // cache the wrapper for other entries loaded on+ // the same page with the same options.path+ window.__whmEventSourceWrapper[options.path] = EventSourceWrapper();+ }++ return window.__whmEventSourceWrapper[options.path];+}++function connect() {+ getEventSourceWrapper().addMessageListener(handleMessage);++ function handleMessage(event) {+ if (event.data === '\uD83D\uDC93') {+ return;+ }++ try {+ processMessage(JSON.parse(event.data));+ } catch (ex) {+ if (options.warn) {+ console.warn('Invalid HMR message: ' + event.data + '\n' + ex);+ }+ }+ }+}++// the reporter needs to be a singleton on the page+// in case the client is being used by multiple bundles+// we only want to report once.+// all the errors will go to all clients+const singletonKey = '__webpack_hot_middleware_reporter__';+let reporter;+if (typeof window !== 'undefined') {+ if (!window[singletonKey]) {+ window[singletonKey] = createReporter();+ }++ reporter = window[singletonKey];+}++function createReporter() {+ const strip = require('strip-ansi');++ let overlay;+ if (typeof document !== 'undefined' && options.overlay) {+ overlay = require('./client-overlay')({+ ansiColors: options.ansiColors,+ overlayStyles: options.overlayStyles,+ });+ }++ const styles = {+ errors: 'color: #ff0000;',+ warnings: 'color: #999933;',+ };+ let previousProblems = null;++ function log(type, obj) {+ const newProblems = obj[type]+ .map((msg) => {+ return strip(msg);+ })+ .join('\n');+ if (previousProblems == newProblems) {+ return;+ }++ previousProblems = newProblems;++ const style = styles[type];+ const name = obj.name ? "'" + obj.name + "' " : '';+ const title =+ '[HMR] bundle ' + name + 'has ' + obj[type].length + ' ' + type;+ // NOTE: console.warn or console.error will print the stack trace+ // which isn't helpful here, so using console.log to escape it.+ if (console.group && console.groupEnd) {+ console.group('%c' + title, style);+ console.log('%c' + newProblems, style);+ console.groupEnd();+ } else {+ console.log(+ '%c' + title + '\n\t%c' + newProblems.replace(/\n/g, '\n\t'),+ style + 'font-weight: bold;',+ style + 'font-weight: normal;'+ );+ }+ }++ return {+ cleanProblemsCache() {+ previousProblems = null;+ },+ problems(type, obj) {+ if (options.warn) {+ log(type, obj);+ }++ if (overlay) {+ if (options.overlayWarnings || type === 'errors') {+ overlay.showProblems(type, obj[type]);+ return false;+ }++ overlay.clear();+ }++ return true;+ },+ success() {+ if (overlay) overlay.clear();+ },+ useCustomOverlay(customOverlay) {+ overlay = customOverlay;+ },+ };+}++let customHandler;+let subscribeAllHandler;++function processMessage(obj) {+ switch (obj.action) {+ case 'building':+ if (options.log) {+ console.log(+ '[HMR] bundle ' ++ (obj.name ? "'" + obj.name + "' " : '') ++ 'rebuilding'+ );+ }++ break;+ case 'built':+ if (options.log) {+ console.log(+ '[HMR] bundle ' ++ (obj.name ? "'" + obj.name + "' " : '') ++ 'rebuilt in ' ++ obj.time ++ 'ms'+ );+ }++ // fall through+ case 'sync':+ if (obj.name && options.name && obj.name !== options.name) {+ return;+ }++ var applyUpdate = true;+ if (obj.errors.length > 0) {+ if (reporter) reporter.problems('errors', obj);+ applyUpdate = false;+ } else if (obj.warnings.length > 0) {+ if (reporter) {+ const overlayShown = reporter.problems('warnings', obj);+ applyUpdate = overlayShown;+ }+ } else if (reporter) {+ reporter.cleanProblemsCache();+ reporter.success();+ }++ if (applyUpdate) {+ processUpdate(obj.hash, obj.modules, options);+ }++ break;+ default:+ if (customHandler) {+ customHandler(obj);+ }+ }++ if (subscribeAllHandler) {+ subscribeAllHandler(obj);+ }+}++module.exports = {+ subscribeAll(handler) {+ subscribeAllHandler = handler;+ },+ subscribe(handler) {+ customHandler = handler;+ },+ setOptionsAndConnect,+};diff --git a/packages/bundler/src/hot-middleware/index.tsx b/packages/bundler/src/hot-middleware/index.tsxnew file mode 100644index 0000000000..1590510b7c--- /dev/null+++ b/packages/bundler/src/hot-middleware/index.tsx@@ -0,0 +1,188 @@+import webpack from 'webpack';++const {parse} = require('url');++exports.pathMatch = function (url, path) {+ try {+ return parse(url).pathname === path;+ } catch (e) {+ return false;+ }+};++export function webpackHotMiddleware(compiler: webpack.Compiler, opts) {+ opts = opts || {};+ opts.log =+ typeof opts.log === 'undefined' ? console.log.bind(console) : opts.log;+ opts.path = opts.path || '/__webpack_hmr';+ opts.heartbeat = opts.heartbeat || 10 * 1000;++ let eventStream = createEventStream(opts.heartbeat);+ let latestStats = null;+ let closed = false;++ compiler.hooks.invalid.tap('webpack-hot-middleware', onInvalid);+ compiler.hooks.done.tap('webpack-hot-middleware', onDone);++ function onInvalid() {+ if (closed) return;+ latestStats = null;+ if (opts.log) opts.log('webpack building...');+ eventStream.publish({+ action: 'building',+ });+ }++ function onDone(statsResult) {+ if (closed) return;+ // Keep hold of latest stats so they can be propagated to new clients+ latestStats = statsResult;+ publishStats('built', latestStats, eventStream, opts.log);+ }++ const middleware = function (req, res, next) {+ if (closed) return next();+ if (!pathMatch(req.url, opts.path)) return next();+ eventStream.handler(req, res);+ if (latestStats) {+ // Explicitly not passing in `log` fn as we don't want to log again on+ // the server+ publishStats('sync', latestStats, eventStream);+ }+ };++ middleware.publish = function (payload) {+ if (closed) return;+ eventStream.publish(payload);+ };++ middleware.close = function () {+ if (closed) return;+ // Can't remove compiler plugins, so we just set a flag and noop if closed+ // https://github.com/webpack/tapable/issues/32#issuecomment-350644466+ closed = true;+ eventStream.close();+ eventStream = null;+ };++ return middleware;+}++function createEventStream(heartbeat) {+ let clientId = 0;+ let clients = {};++ function everyClient(fn) {+ Object.keys(clients).forEach((id) => {+ fn(clients[id]);+ });+ }++ const interval = setInterval(function heartbeatTick() {+ everyClient((client) => {+ client.write('data: \uD83D\uDC93\n\n');+ });+ }, heartbeat).unref();+ return {+ close() {+ clearInterval(interval);+ everyClient((client) => {+ if (!client.finished) client.end();+ });+ clients = {};+ },+ handler(req, res) {+ const headers = {+ 'Access-Control-Allow-Origin': '*',+ 'Content-Type': 'text/event-stream;charset=utf-8',+ 'Cache-Control': 'no-cache, no-transform',+ // While behind nginx, event stream should not be buffered:+ // http://nginx.org/docs/http/ngx_http_proxy_module.html#proxy_buffering+ 'X-Accel-Buffering': 'no',+ };++ const isHttp1 = !(parseInt(req.httpVersion) >= 2);+ if (isHttp1) {+ req.socket.setKeepAlive(true);+ Object.assign(headers, {+ Connection: 'keep-alive',+ });+ }++ res.writeHead(200, headers);+ res.write('\n');+ const id = clientId++;+ clients[id] = res;+ req.on('close', () => {+ if (!res.finished) res.end();+ delete clients[id];+ });+ },+ publish(payload) {+ everyClient((client) => {+ client.write('data: ' + JSON.stringify(payload) + '\n\n');+ });+ },+ };+}++function publishStats(action, statsResult, eventStream, log) {+ const stats = statsResult.toJson({+ all: false,+ cached: true,+ children: true,+ modules: true,+ timings: true,+ hash: true,+ });+ // For multi-compiler, stats will be an object with a 'children' array of stats+ const bundles = extractBundles(stats);+ bundles.forEach((stats) => {+ let name = stats.name || '';++ // Fallback to compilation name in case of 1 bundle (if it exists)+ if (bundles.length === 1 && !name && statsResult.compilation) {+ name = statsResult.compilation.name || '';+ }++ if (log) {+ log(+ 'webpack built ' ++ (name ? name + ' ' : '') ++ stats.hash ++ ' in ' ++ stats.time ++ 'ms'+ );+ }++ eventStream.publish({+ name,+ action,+ time: stats.time,+ hash: stats.hash,+ warnings: stats.warnings || [],+ errors: stats.errors || [],+ modules: buildModuleMap(stats.modules),+ });+ });+}++function extractBundles(stats) {+ // Stats has modules, single bundle+ if (stats.modules) return [stats];++ // Stats has children, multiple bundles+ if (stats.children && stats.children.length) return stats.children;++ // Not sure, assume single+ return [stats];+}++function buildModuleMap(modules) {+ const map = {};+ modules.forEach((module) => {+ map[module.id] = module.name;+ });+ return map;+}diff --git a/packages/bundler/src/hot-middleware/process-update.ts b/packages/bundler/src/hot-middleware/process-update.tsnew file mode 100644index 0000000000..171046ffb0--- /dev/null+++ b/packages/bundler/src/hot-middleware/process-update.ts@@ -0,0 +1,161 @@+/**+ * Based heavily on https://github.com/webpack/webpack/blob/+ * c0afdf9c6abc1dd70707c594e473802a566f7b6e/hot/only-dev-server.js+ * Original copyright Tobias Koppers @sokra (MIT license)+ */++/* global __webpack_hash__ */++if (!module.hot) {+ throw new Error('[HMR] Hot Module Replacement is disabled.');+}++const hmrDocsUrl = 'https://webpack.js.org/concepts/hot-module-replacement/'; // eslint-disable-line max-len++let lastHash;+const failureStatuses = {abort: 1, fail: 1};+const applyOptions = {+ ignoreUnaccepted: true,+ ignoreDeclined: true,+ ignoreErrored: true,+ onUnaccepted(data) {+ console.warn(+ 'Ignored an update to unaccepted module ' + data.chain.join(' -> ')+ );+ },+ onDeclined(data) {+ console.warn(+ 'Ignored an update to declined module ' + data.chain.join(' -> ')+ );+ },+ onErrored(data) {+ console.error(data.error);+ console.warn(+ 'Ignored an error while updating module ' ++ data.moduleId ++ ' (' ++ data.type ++ ')'+ );+ },+};++function upToDate(hash) {+ if (hash) lastHash = hash;+ return lastHash == __webpack_hash__;+}++export const processUpdate = function (hash: string, moduleMap, options) {+ const {reload} = options;+ if (!upToDate(hash) && module.hot.status() == 'idle') {+ if (options.log) console.log('[HMR] Checking for updates on the server...');+ check();+ }++ function check() {+ const cb = function (err, updatedModules) {+ if (err) return handleError(err);++ if (!updatedModules) {+ if (options.warn) {+ console.warn('[HMR] Cannot find update (Full reload needed)');+ console.warn('[HMR] (Probably because of restarting the server)');+ }++ performReload();+ return null;+ }++ const applyCallback = function (applyErr, renewedModules) {+ if (applyErr) return handleError(applyErr);++ if (!upToDate()) check();++ logUpdates(updatedModules, renewedModules);+ };++ const applyResult = module.hot.apply(applyOptions, applyCallback);+ // webpack 2 promise+ if (applyResult && applyResult.then) {+ // HotModuleReplacement.runtime.js refers to the result as `outdatedModules`+ applyResult.then((outdatedModules) => {+ applyCallback(null, outdatedModules);+ });+ applyResult.catch(applyCallback);+ }+ };++ const result = module.hot.check(false, cb);+ // webpack 2 promise+ if (result && result.then) {+ result.then((updatedModules) => {+ cb(null, updatedModules);+ });+ result.catch(cb);+ }+ }++ function logUpdates(updatedModules, renewedModules) {+ const unacceptedModules = updatedModules.filter((moduleId) => {+ return renewedModules && renewedModules.indexOf(moduleId) < 0;+ });++ if (unacceptedModules.length > 0) {+ if (options.warn) {+ console.warn(+ "[HMR] The following modules couldn't be hot updated: " ++ '(Full reload needed)\n' ++ 'This is usually because the modules which have changed ' ++ '(and their parents) do not know how to hot reload themselves. ' ++ 'See ' ++ hmrDocsUrl ++ ' for more details.'+ );+ unacceptedModules.forEach((moduleId) => {+ console.warn('[HMR] - ' + (moduleMap[moduleId] || moduleId));+ });+ }++ performReload();+ return;+ }++ if (options.log) {+ if (!renewedModules || renewedModules.length === 0) {+ console.log('[HMR] Nothing hot updated.');+ } else {+ console.log('[HMR] Updated modules:');+ renewedModules.forEach((moduleId) => {+ console.log('[HMR] - ' + (moduleMap[moduleId] || moduleId));+ });+ }++ if (upToDate()) {+ console.log('[HMR] App is up to date.');+ }+ }+ }++ function handleError(err) {+ if (module.hot.status() in failureStatuses) {+ if (options.warn) {+ console.warn('[HMR] Cannot check for update (Full reload needed)');+ console.warn('[HMR] ' + (err.stack || err.message));+ }++ performReload();+ return;+ }++ if (options.warn) {+ console.warn('[HMR] Update check failed: ' + (err.stack || err.message));+ }+ }++ function performReload() {+ if (reload) {+ if (options.warn) console.warn('[HMR] Reloading page');+ window.location.reload();+ }+ }+};