vite-plugin-entry-shaking-debugger
Version:
Debugger for vite-plugin-entry-shaking
210 lines (190 loc) • 7.5 kB
JavaScript
import { dirname, resolve as resolve$1 } from 'node:path';
import { fileURLToPath } from 'node:url';
import sirv from 'sirv';
import { readFileSync } from 'fs';
import { createRequire } from 'module';
import { resolve } from 'path';
import { readFile } from 'node:fs/promises';
import { normalizePath } from 'vite';
function getDefaultExportFromCjs (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var picocolors = {exports: {}};
let p = process || {}, argv = p.argv || [], env = p.env || {};
let isColorSupported =
!(!!env.NO_COLOR || argv.includes("--no-color")) &&
(!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI);
let formatter = (open, close, replace = open) =>
input => {
let string = "" + input, index = string.indexOf(close, open.length);
return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close
};
let replaceClose = (string, close, replace, index) => {
let result = "", cursor = 0;
do {
result += string.substring(cursor, index) + replace;
cursor = index + close.length;
index = string.indexOf(close, cursor);
} while (~index)
return result + string.substring(cursor)
};
let createColors = (enabled = isColorSupported) => {
let f = enabled ? formatter : () => String;
return {
isColorSupported: enabled,
reset: f("\x1b[0m", "\x1b[0m"),
bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
italic: f("\x1b[3m", "\x1b[23m"),
underline: f("\x1b[4m", "\x1b[24m"),
inverse: f("\x1b[7m", "\x1b[27m"),
hidden: f("\x1b[8m", "\x1b[28m"),
strikethrough: f("\x1b[9m", "\x1b[29m"),
black: f("\x1b[30m", "\x1b[39m"),
red: f("\x1b[31m", "\x1b[39m"),
green: f("\x1b[32m", "\x1b[39m"),
yellow: f("\x1b[33m", "\x1b[39m"),
blue: f("\x1b[34m", "\x1b[39m"),
magenta: f("\x1b[35m", "\x1b[39m"),
cyan: f("\x1b[36m", "\x1b[39m"),
white: f("\x1b[37m", "\x1b[39m"),
gray: f("\x1b[90m", "\x1b[39m"),
bgBlack: f("\x1b[40m", "\x1b[49m"),
bgRed: f("\x1b[41m", "\x1b[49m"),
bgGreen: f("\x1b[42m", "\x1b[49m"),
bgYellow: f("\x1b[43m", "\x1b[49m"),
bgBlue: f("\x1b[44m", "\x1b[49m"),
bgMagenta: f("\x1b[45m", "\x1b[49m"),
bgCyan: f("\x1b[46m", "\x1b[49m"),
bgWhite: f("\x1b[47m", "\x1b[49m"),
blackBright: f("\x1b[90m", "\x1b[39m"),
redBright: f("\x1b[91m", "\x1b[39m"),
greenBright: f("\x1b[92m", "\x1b[39m"),
yellowBright: f("\x1b[93m", "\x1b[39m"),
blueBright: f("\x1b[94m", "\x1b[39m"),
magentaBright: f("\x1b[95m", "\x1b[39m"),
cyanBright: f("\x1b[96m", "\x1b[39m"),
whiteBright: f("\x1b[97m", "\x1b[39m"),
bgBlackBright: f("\x1b[100m", "\x1b[49m"),
bgRedBright: f("\x1b[101m", "\x1b[49m"),
bgGreenBright: f("\x1b[102m", "\x1b[49m"),
bgYellowBright: f("\x1b[103m", "\x1b[49m"),
bgBlueBright: f("\x1b[104m", "\x1b[49m"),
bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
bgCyanBright: f("\x1b[106m", "\x1b[49m"),
bgWhiteBright: f("\x1b[107m", "\x1b[49m"),
}
};
picocolors.exports = createColors();
picocolors.exports.createColors = createColors;
var picocolorsExports = picocolors.exports;
const colors = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
const require = createRequire(import.meta.url);
const packageMainPath = require.resolve("vite-plugin-entry-shaking");
const packageJsonPath = resolve(packageMainPath, "../../package.json");
const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8"));
const { name, version } = packageJson;
const VERSION = version;
const PLUGIN_NAME = name;
const PLUGIN_MESSAGE_PREFIX = "vpes";
const wsMessageName = (name) => `${PLUGIN_MESSAGE_PREFIX}:${name}`;
const READY = wsMessageName("getInitialState");
const TYPE = "t";
const MAP = "m";
const SET = "s";
const VAL = "v";
const stringify = (v) => JSON.stringify(v, replacer);
const parse = (v) => JSON.parse(v, reviver);
const isObject = (v) => typeof v === "object" && v !== null;
const replacer = (_, v) => v instanceof Map ? { [TYPE]: MAP, [VAL]: [...v] } : v instanceof Set ? { [TYPE]: SET, [VAL]: [...v] } : v;
const reviver = (_, v) => isObject(v) && v[TYPE] === MAP ? new Map(v[VAL]) : isObject(v) && v[TYPE] === SET ? new Set(v[VAL]) : v;
const JSONMap = { stringify, parse };
const _ = wsMessageName;
function createChannel({ hot, config }, ctx, consumer) {
subscribeToEventBus(hot, ctx);
const { root } = config;
hot.on(READY, () => {
hot.send(
READY,
JSONMap.stringify({
root,
consumer,
entries: ctx.entries,
metrics: ctx.metrics,
logs: ctx.logger.logs,
options: {
diagnostics: ctx.options.diagnostics,
debug: ctx.options.debug
},
diagnostics: {
list: ctx.diagnostics.list,
listPerPath: ctx.diagnostics.listPerPath
}
})
);
});
}
function subscribeToEventBus(hot, ctx) {
ctx.eventBus?.subscribe((event, data) => {
hot.send(_(event), JSONMap.stringify(data.length > 1 ? [...data] : data[0]));
});
}
const CURR_DIR = dirname(fileURLToPath(import.meta.url));
resolve$1(CURR_DIR, "../dist/client");
const PATH_TO_CONSUMER_PACKAGE = normalizePath(resolve$1(process.cwd(), "package.json"));
async function getConsumerPackageInfo() {
try {
const packageJsonContent = await readFile(PATH_TO_CONSUMER_PACKAGE, "utf-8");
const { name, version } = JSON.parse(packageJsonContent);
return { name, version };
} catch {
return { name: "Debugger" };
}
}
const PATH_TO_CLIENT = resolve$1(dirname(fileURLToPath(import.meta.url)), "../dist/client");
async function attachDebugger(server, ctx) {
const { base } = server.config;
const debuggerPath = `${base}__debugger`;
const sirvConfig = { dev: true, single: true };
server.middlewares.use(debuggerPath, sirv(PATH_TO_CLIENT, sirvConfig));
const consumer = await getConsumerPackageInfo();
createChannel(server, ctx, consumer);
printUrls(server, debuggerPath, consumer);
}
function printUrls(server, debuggerRoute, consumer) {
const printViteUrls = server.printUrls;
server.printUrls = () => {
printViteUrls();
const resolvedLocalUrls = server.resolvedUrls?.local ?? [];
const pluginHeader = colors.green(`${colors.bold(PLUGIN_NAME)} v${VERSION}`);
const pluginName = colors.dim("debugger");
server.config.logger.info(`
${pluginHeader} ${pluginName}
`);
resolvedLocalUrls.forEach((url, i) => {
const baseUrl = url.endsWith("/") && debuggerRoute.startsWith("/") ? url.slice(0, -1) : url;
const debugPath = debuggerRoute.endsWith("/") ? debuggerRoute : `${debuggerRoute}/`;
const debugUrl = `${baseUrl}${debugPath}`;
if (!i) {
openBrowser(baseUrl);
openBrowser(debugUrl, 300);
}
server.config.logger.info(
colors.dim(colors.green(" \u279C")) + colors.dim(` ${colors.bold("Local:")} ${colors.cyan(debugUrl)}`)
);
if (consumer.name && consumer.version) {
const debuggee = `${consumer.name}@${consumer.version}`;
server.config.logger.info(
colors.dim(colors.green(" \u279C")) + colors.dim(` Debugging ${colors.bold(debuggee)}`)
);
}
});
};
}
function openBrowser(address, delay = 0) {
setTimeout(() => {
import('open').then((r) => r.default(address, { newInstance: true })).catch(() => {
});
}, delay);
}
export { attachDebugger, attachDebugger as default };