UNPKG

@farmfe/runtime-plugin-hmr

Version:

Runtime hmr plugin of Farm

94 lines 3.26 kB
import { logger } from './logger.js'; export class HotModuleState { constructor(id, hmrClient) { this.acceptCallbacks = []; this.data = {}; this.id = id; this.hmrClient = hmrClient; } // the same as vite's hot.accept accept(deps, callback) { if (typeof deps === 'function' || !deps) { // self-accept hot.accept(() => {}) this.acceptCallbacks.push({ deps: [this.id], fn: ([mod]) => deps?.(mod) }); } else if (typeof deps === 'string') { // accept a single dependency hot.accept('./dep.js', () => {}) this.acceptCallbacks.push({ deps: [deps], fn: ([mod]) => callback?.(mod) }); } else if (Array.isArray(deps)) { // accept multiple dependencies hot.accept(['./dep1.js', './dep2.js'], () => {}) this.acceptCallbacks.push({ deps, fn: callback }); } else { throw new Error('invalid hot.accept call'); } } dispose(callback) { this.hmrClient.disposeMap.set(this.id, callback); } prune(callback) { this.hmrClient.pruneMap.set(this.id, callback); } acceptExports(_, _callback) { logger.debug('acceptExports is not supported for now'); } decline() { /** does no thing */ } invalidate(message) { this.hmrClient.notifyListeners('vite:invalidate', { path: this.id, message }); // notify the server to find the boundary starting from the parents of this module this.send('vite:invalidate', { path: this.id, message }); this.send('farm:invalidate', { path: this.id, message }); logger.debug(`invalidate ${this.id}${message ? `: ${message}` : ''}`); } on(event, cb) { const addToMap = (map) => { const existing = map.get(event) || []; existing.push(cb); map.set(event, existing); }; addToMap(this.hmrClient.customListenersMap); } off(event, cb) { const removeFromMap = (map) => { const existing = map.get(event); if (existing === undefined) { return; } const pruned = existing.filter((l) => l !== cb); if (pruned.length === 0) { map.delete(event); return; } map.set(event, pruned); }; removeFromMap(this.hmrClient.customListenersMap); } send(event, data) { if (this.hmrClient.socket.readyState === WebSocket.OPEN) { this.hmrClient.socket.send(JSON.stringify({ type: 'custom', event, data })); } } } export function createHotContext(id, hmrClient) { if (hmrClient.registeredHotModulesMap.has(id)) { const hotModuleState = hmrClient.registeredHotModulesMap.get(id); hotModuleState.acceptCallbacks = []; // clear the accept callbacks when hot reloading return hotModuleState; } const state = new HotModuleState(id, hmrClient); hmrClient.registeredHotModulesMap.set(id, state); return state; } //# sourceMappingURL=hot-module-state.js.map