rspack-plugin-mock
Version:
inject api mock server to development server
1,563 lines • 51.9 kB
JavaScript
import path from "node:path";
import { attempt, attemptAsync, deepEqual, hasOwn, isArray, isBoolean, isEmptyObject, isFunction, isPlainObject, isString, kebabCase, objectKeys, partition, random, sleep, sortBy, timestamp, toArray, uniq } from "@pengzhanbo/utils";
import fs, { promises } from "node:fs";
import ansis from "ansis";
import picomatch from "picomatch";
import { loadPackageJSONSync } from "local-pkg";
import { match, parse, pathToRegexp } from "path-to-regexp";
import os from "node:os";
import { fileURLToPath } from "node:url";
import Debug from "debug";
import { Volume, createFsFromVolume } from "memfs";
import { parse as parse$1 } from "node:querystring";
import crypto from "node:crypto";
import cors from "cors";
import bodyParser from "co-body";
import formidable from "formidable";
import http from "node:http";
import { Buffer } from "node:buffer";
import zlib from "node:zlib";
import HTTP_STATUS from "http-status";
import * as mime from "mime-types";
import { WebSocketServer } from "ws";
//#region src/utils/createMatcher.ts
function createMatcher(include, exclude, defaultIgnore = true) {
const pattern = [];
const ignore = [...defaultIgnore ? ["**/node_modules/**"] : [], ...toArray(exclude)];
toArray(include).forEach((item) => {
if (item[0] === "!") ignore.push(item.slice(1));
else pattern.push(item);
});
return {
pattern,
ignore,
isMatch: picomatch(pattern, { ignore })
};
}
//#endregion
//#region src/utils/doesProxyContextMatchUrl.ts
const PATTERN_CACHE = /* @__PURE__ */ new Map();
function doesProxyContextMatchUrl(context, req) {
const url = req.url;
if (typeof context === "function") return context(url, req);
if (context[0] === "^") {
let pattern = PATTERN_CACHE.get(context);
if (!pattern) PATTERN_CACHE.set(context, pattern = new RegExp(context));
return pattern.test(url);
}
return url.startsWith(context);
}
//#endregion
//#region src/utils/getDeps.ts
function getPackageDeps(cwd) {
const { dependencies, devDependencies, peerDependencies, optionalDependencies } = loadPackageJSONSync(cwd) || {};
return {
...dependencies,
...devDependencies,
...peerDependencies,
...optionalDependencies
};
}
function getPackageDepList(cwd) {
return uniq(objectKeys(getPackageDeps(cwd)));
}
//#endregion
//#region src/utils/is.ts
function isStream(stream) {
return stream !== null && typeof stream === "object" && typeof stream.pipe === "function";
}
function isReadableStream(stream) {
return isStream(stream) && stream.readable !== false && typeof stream._read === "function" && typeof stream._readableState === "object";
}
/**
* 判断内容类型是否为文本类型
*
* @param contentType 内容类型
* @returns 是否为文本类型
*/
function isTextContent(contentType) {
return [
"text",
"json",
"xml"
].some((type) => contentType.includes(type));
}
//#endregion
//#region src/utils/isObjectSubset.ts
/**
* Checks if target object is a subset of source object.
* That is, all properties and their corresponding values in target exist in source.
*
* 深度比较两个对象之间,target 是否属于 source 的子集,
* 即 target 的所有属性和对应的值,都在 source 中,
*/
function isObjectSubset(source, target) {
if (!target) return true;
for (const key in target) if (!isIncluded(source[key], target[key])) return false;
return true;
}
function isIncluded(source, target) {
if (isArray(source) && isArray(target)) {
const seen = /* @__PURE__ */ new Set();
return target.every((ti) => source.some((si, i) => {
if (seen.has(i)) return false;
const included = isIncluded(si, ti);
if (included) seen.add(i);
return included;
}));
}
if (isPlainObject(source) && isPlainObject(target)) return isObjectSubset(source, target);
return Object.is(source, target);
}
//#endregion
//#region src/utils/isPathMatch.ts
const cache = /* @__PURE__ */ new Map();
/**
* 判断 path 是否匹配 pattern
*/
function isPathMatch(pattern, path) {
let regexp = cache.get(pattern);
if (!regexp) {
regexp = pathToRegexp(pattern).regexp;
cache.set(pattern, regexp);
}
return regexp.test(path);
}
//#endregion
//#region src/utils/matchScene.ts
function matchScene(activeScene, mockScene) {
if (!mockScene) return true;
const scenes = toArray(mockScene);
if (activeScene.length === 0 && scenes.length > 0) return false;
if (scenes.length === 0) return true;
return scenes.some((s) => activeScene.includes(s));
}
getDirname(import.meta.url);
const vfs = createFsFromVolume(new Volume());
function getDirname(importMetaUrl) {
return path.dirname(fileURLToPath(importMetaUrl));
}
Debug("vite:mock-dev-server");
const windowsSlashRE = /\\/g;
const isWindows = os.platform() === "win32";
function slash(p) {
return p.replace(windowsSlashRE, "/");
}
function normalizePath(id) {
return path.posix.normalize(isWindows ? slash(id) : id);
}
//#endregion
//#region src/utils/urlParse.ts
/**
* nodejs 从 19.0.0 开始 弃用 url.parse,因此使用 url.parse 来解析 可能会报错,
* 使用 URL 来解析
*/
function urlParse(input) {
const url = new URL(input, "http://example.com");
return {
pathname: decodeURIComponent(url.pathname),
query: parse$1(url.search.replace(/^\?/, ""))
};
}
//#endregion
//#region src/utils/waitingFor.ts
function waitingFor(onSuccess, maxRetry = 5) {
return function wait(getter, retry = 0) {
const value = getter();
if (value) onSuccess(value);
else if (retry < maxRetry) setTimeout(() => wait(getter, retry + 1), 100);
};
}
//#endregion
//#region src/compiler/processData.ts
function processRawData(rawData) {
return rawData.filter((item) => item[0]).map(([raw, __filepath__]) => {
let mockConfig;
if (raw.default) if (isArray(raw.default)) mockConfig = raw.default.map((item) => ({
...item,
__filepath__
}));
else mockConfig = {
...raw.default,
__filepath__
};
else if ("url" in raw) mockConfig = {
...raw,
__filepath__
};
else {
mockConfig = [];
objectKeys(raw || {}).forEach((key) => {
const data = raw[key];
if (isArray(data)) mockConfig.push(...data.map((item) => ({
...item,
__filepath__
})));
else mockConfig.push({
...data,
__filepath__
});
});
}
return mockConfig;
});
}
function processMockData(mockList) {
const list = [];
for (const [, handle] of mockList.entries()) if (handle) list.push(...toArray(handle));
const mocks = {};
list.filter((mock) => isPlainObject(mock) && mock.enabled !== false && mock.url).forEach((mock) => {
const { pathname, query } = urlParse(mock.url);
const list = mocks[pathname] ??= [];
const current = {
...mock,
url: pathname
};
if (current.ws !== true) {
const validator = current.validator;
if (!isEmptyObject(query)) if (isFunction(validator)) current.validator = function(request) {
return isObjectSubset(request.query, query) && validator(request);
};
else if (validator) {
current.validator = { ...validator };
current.validator.query = current.validator.query ? {
...query,
...current.validator.query
} : query;
} else current.validator = { query };
}
list.push(current);
});
objectKeys(mocks).forEach((key) => {
mocks[key] = sortByValidator(mocks[key]);
});
return mocks;
}
function sortByValidator(mocks) {
return sortBy(mocks, (item) => {
if (item.ws === true) return 0;
const { validator } = item;
if (!validator || isEmptyObject(validator)) return 2;
if (isFunction(validator)) return 0;
return 1 / Object.keys(validator).reduce((prev, key) => prev + keysCount(validator[key]), 0);
});
}
function keysCount(obj) {
if (!obj) return 0;
return objectKeys(obj).length;
}
//#endregion
//#region src/mockHttp/cors.ts
/**
* Create CORS middleware
*
* 创建 CORS 中间件
*
* @param corsOptions - CORS options / CORS 配置项
* @returns CORS middleware function or undefined / CORS 中间件函数或未定义
*/
function createCors(corsOptions) {
const corsMiddleware = corsOptions ? cors(corsOptions) : void 0;
return corsMiddleware ? (req, res) => new Promise((resolve, reject) => corsMiddleware(req, res, (err) => {
err ? reject(err) : resolve();
})) : void 0;
}
//#endregion
//#region src/mockHttp/request.ts
/**
* Parse request body
*
* 解析请求体 request.body
*
* @param req - Incoming message object / 入站消息对象
* @param logger - Logger instance / 日志实例
* @param formidableOptions - Formidable options for multipart form data / 用于 multipart 表单数据的 Formidable 配置项
* @param bodyParserOptions - Body parser options / 请求体解析配置项
* @returns Parsed request body / 解析后的请求体
*/
async function parseRequestBody(req, logger, formidableOptions, bodyParserOptions = {}) {
const method = req.method.toUpperCase();
if (["HEAD", "OPTIONS"].includes(method)) return void 0;
const type = req.headers["content-type"]?.toLocaleLowerCase() || "";
const { limit, formLimit, jsonLimit, textLimit, ...rest } = bodyParserOptions;
try {
if (type.startsWith("application/json")) return await bodyParser.json(req, {
limit: jsonLimit || limit,
...rest
});
if (type.startsWith("application/x-www-form-urlencoded")) return await bodyParser.form(req, {
limit: formLimit || limit,
...rest
});
if (type.startsWith("text/plain")) return await bodyParser.text(req, {
limit: textLimit || limit,
...rest
});
if (type.startsWith("multipart/form-data")) return await parseRequestBodyWithMultipart(req, formidableOptions);
} catch (e) {
logger.error(e);
}
}
/**
* Default formidable options
*
* 默认的 formidable 配置项
*/
const DEFAULT_FORMIDABLE_OPTIONS = {
keepExtensions: true,
filename(name, ext, part) {
return part?.originalFilename || `${name}.${Date.now()}${ext ? `.${ext}` : ""}`;
}
};
/**
* Parse request body with multipart form data
*
* 解析 request form multipart body
*
* @param req - Incoming message object / 入站消息对象
* @param options - Formidable options / Formidable 配置项
* @returns Parsed request body / 解析后的请求体
*/
async function parseRequestBodyWithMultipart(req, options) {
const form = formidable({
...DEFAULT_FORMIDABLE_OPTIONS,
...options
});
return new Promise((resolve, reject) => {
form.parse(req, (error, fields, files) => {
if (error) {
reject(error);
return;
}
resolve({
...fields,
...files
});
});
});
}
/**
* Cache for path-to-regexp match functions
*
* path-to-regexp 匹配函数缓存
*/
const matcherCache = /* @__PURE__ */ new Map();
/**
* Parse request URL dynamic parameters
*
* 解析请求 url 中的动态参数 params
*
* @param pattern - URL pattern / URL 模式
* @param url - Request URL / 请求 URL
* @returns Parsed parameters / 解析后的参数
*/
function parseRequestParams(pattern, url) {
let matcher = matcherCache.get(pattern);
if (!matcher) {
matcher = match(pattern, { decode: decodeURIComponent });
matcherCache.set(pattern, matcher);
}
const matched = matcher(url);
return matched ? matched.params : {};
}
/**
* Validate request against validator
*
* 验证请求是否符合 validator
*
* @param request - Request object / 请求对象
* @param validator - Validator object / 验证器对象
* @returns Whether the request is valid / 请求是否有效
*/
function requestValidate(request, validator) {
return isObjectSubset(request.headers, validator.headers) && isObjectSubset(request.body, validator.body) && isObjectSubset(request.params, validator.params) && isObjectSubset(request.query, validator.query) && isObjectSubset(request.refererQuery, validator.refererQuery);
}
/**
* Format log data
*
* 格式化日志数据
*
* @param prefix - Log prefix / 日志前缀
* @param data - Data to format / 要格式化的数据
* @returns Formatted log string / 格式化后的日志字符串
*/
function formatLog(prefix, data) {
return !data || isEmptyObject(data) ? "" : ` ${ansis.gray(`${prefix}:`)}${JSON.stringify(data)}`;
}
/**
* Generate request log
*
* 生成请求日志
*
* @param request - Request object / 请求对象
* @param filepath - Mock file path / Mock 文件路径
* @param shouldSimulateError - Whether to simulate error / 是否模拟错误
* @returns Formatted log string / 格式化后的日志字符串
*/
function requestLog(request, filepath, shouldSimulateError) {
const { url, method, query, params, body } = request;
let { pathname } = new URL(url, "http://example.com");
pathname = ansis.green(decodeURIComponent(pathname));
const ms = ansis.magenta.bold(method);
const qs = formatLog("query", query);
const ps = formatLog("params", params);
const bs = formatLog("body", body);
const es = shouldSimulateError ? ` 🎲 ${ansis.bgYellow("ERR")}` : "";
const file = ` ${ansis.dim.underline(`(${filepath})`)}`;
return `${ms}${es} ${pathname}${qs}${ps}${bs}${file}`;
}
//#endregion
//#region src/mockHttp/matcher.ts
/**
* Find matching mock data
*
* 查找匹配的 mock data
*
* @param mockList - Mock options list / Mock 配置列表
* @param logger - Logger instance / 日志实例
* @param options - Find options / 查找选项
* @param options.pathname - Request pathname / 请求路径
* @param options.method - HTTP method / HTTP 方法
* @param options.request - Request object / 请求对象
* @param options.activeScene - Active scene / 当前场景
* @returns Matched mock HTTP item or undefined / 匹配的 Mock HTTP 项或未定义
*/
function findMockData(mockList, logger, { pathname, method, request, activeScene }) {
return mockList.find((mock) => {
if (!pathname || !mock || !mock.url || mock.ws) return false;
if (!(mock.method ? isArray(mock.method) ? mock.method : [mock.method] : ["GET", "POST"]).includes(method)) return false;
if (!matchScene(activeScene, mock.scene)) return false;
const hasMock = isPathMatch(mock.url, pathname);
if (hasMock && mock.validator) {
const params = parseRequestParams(mock.url, pathname);
if (isFunction(mock.validator)) return mock.validator({
params,
...request
});
else {
const [error, validated] = attempt(requestValidate, {
params,
...request
}, mock.validator);
if (error) {
const file = mock.__filepath__;
logger.error(`${ansis.red(`mock error at ${pathname}`)}\n${error}\n at validator (${ansis.underline(file)})`, mock.log);
return false;
}
return validated;
}
}
return hasMock;
});
}
//#endregion
//#region src/cookies/constants.ts
/**
* RegExp to match field-content in RFC 7230 sec 3.2
*
* field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
* field-vchar = VCHAR / obs-text
* obs-text = %x80-FF
*/
const fieldContentRegExp = /^[\t\u0020-\u007E\u0080-\u00FF]+$/;
/**
* RegExp to match Priority cookie attribute value.
*/
const PRIORITY_REGEXP = /^(?:low|medium|high)$/i;
/**
* Cache for generated name regular expressions.
*/
const REGEXP_CACHE = Object.create(null);
/**
* RegExp to match all characters to escape in a RegExp.
*/
const REGEXP_ESCAPE_CHARS_REGEXP = /[\^$\\.*+?()[\]{}|]/g;
/**
* RegExp to match basic restricted name characters for loose validation.
*/
const RESTRICTED_NAME_CHARS_REGEXP = /[;=]/;
/**
* RegExp to match basic restricted value characters for loose validation.
*/
const RESTRICTED_VALUE_CHARS_REGEXP = /;/;
/**
* RegExp to match Same-Site cookie attribute value.
*/
const SAME_SITE_REGEXP = /^(?:lax|none|strict)$/i;
//#endregion
//#region src/cookies/Cookie.ts
var Cookie = class {
name;
value;
maxAge;
expires;
path = "/";
domain;
secure = false;
httpOnly = true;
sameSite = false;
overwrite = false;
priority;
partitioned;
constructor(name, value, options = {}) {
if (!fieldContentRegExp.test(name) || RESTRICTED_NAME_CHARS_REGEXP.test(name)) throw new TypeError("argument name is invalid");
if (value && (!fieldContentRegExp.test(value) || RESTRICTED_VALUE_CHARS_REGEXP.test(value))) throw new TypeError("argument value is invalid");
this.name = name;
this.value = value;
Object.assign(this, options);
if (!this.value) {
this.expires = /* @__PURE__ */ new Date(0);
this.maxAge = void 0;
}
if (this.path && !fieldContentRegExp.test(this.path)) throw new TypeError("[Cookie] option path is invalid");
if (this.domain && !fieldContentRegExp.test(this.domain)) throw new TypeError("[Cookie] option domain is invalid");
if (typeof this.maxAge === "number" ? Number.isNaN(this.maxAge) || !Number.isFinite(this.maxAge) : this.maxAge) throw new TypeError("[Cookie] option maxAge is invalid");
if (this.priority && !PRIORITY_REGEXP.test(this.priority)) throw new TypeError("[Cookie] option priority is invalid");
if (this.sameSite && this.sameSite !== true && !SAME_SITE_REGEXP.test(this.sameSite)) throw new TypeError("[Cookie] option sameSite is invalid");
}
toString() {
return `${this.name}=${this.value}`;
}
toHeader() {
let header = this.toString();
if (this.maxAge) this.expires = new Date(Date.now() + this.maxAge);
if (this.path) header += `; path=${this.path}`;
if (this.expires) header += `; expires=${this.expires.toUTCString()}`;
if (this.domain) header += `; domain=${this.domain}`;
if (this.priority) header += `; priority=${this.priority.toLowerCase()}`;
if (this.sameSite) header += `; samesite=${this.sameSite === true ? "strict" : this.sameSite.toLowerCase()}`;
if (this.secure) header += "; secure";
if (this.httpOnly) header += "; httponly";
if (this.partitioned) header += "; partitioned";
return header;
}
};
//#endregion
//#region src/cookies/timeSafeCompare.ts
function bufferEqual(a, b) {
if (a.length !== b.length) return false;
if (crypto.timingSafeEqual) return crypto.timingSafeEqual(a, b);
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
return true;
}
function createHmac(key, data) {
return crypto.createHmac("sha256", key).update(data).digest();
}
function timeSafeCompare(a, b) {
const sa = String(a);
const sb = String(b);
const key = crypto.randomBytes(32);
return bufferEqual(createHmac(key, sa), createHmac(key, sb)) && a === b;
}
//#endregion
//#region src/cookies/Keygrip.ts
const SLASH_PATTERN = /[/+=]/g;
const REPLACE_MAP = {
"/": "_",
"+": "-",
"=": ""
};
var Keygrip = class {
algorithm;
encoding;
keys = [];
constructor(keys, algorithm, encoding) {
this.keys = keys;
this.algorithm = algorithm || "sha256";
this.encoding = encoding || "base64";
}
sign(data, key = this.keys[0]) {
return crypto.createHmac(this.algorithm, key).update(data).digest(this.encoding).replace(SLASH_PATTERN, (m) => REPLACE_MAP[m]);
}
index(data, digest) {
for (let i = 0, l = this.keys.length; i < l; i++) if (timeSafeCompare(digest, this.sign(data, this.keys[i]))) return i;
return -1;
}
verify(data, digest) {
return this.index(data, digest) > -1;
}
};
//#endregion
//#region src/cookies/Cookies.ts
var Cookies = class {
request;
response;
secure;
keys;
constructor(req, res, options = {}) {
this.request = req;
this.response = res;
this.secure = options.secure;
if (options.keys instanceof Keygrip) this.keys = options.keys;
else if (isArray(options.keys)) this.keys = new Keygrip(options.keys);
}
set(name, value, options) {
const req = this.request;
const res = this.response;
const headers = toArray(res.getHeader("Set-Cookie"));
const cookie = new Cookie(name, value, options);
const signed = options?.signed ?? !!this.keys;
const secure = this.secure === void 0 ? req.protocol === "https" || isRequestEncrypted(req) : Boolean(this.secure);
if (!secure && options?.secure) throw new Error("Cannot send secure cookie over unencrypted connection");
cookie.secure = options?.secure ?? secure;
pushCookie(headers, cookie);
if (signed && options) {
if (!this.keys) throw new Error(".keys required for signed cookies");
cookie.value = this.keys.sign(cookie.toString());
cookie.name += ".sig";
pushCookie(headers, cookie);
}
(res.set ? http.OutgoingMessage.prototype.setHeader : res.setHeader).call(res, "Set-Cookie", headers);
return this;
}
get(name, options) {
const signName = `${name}.sig`;
const signed = options?.signed ?? !!this.keys;
const header = this.request.headers.cookie;
if (!header) return;
const match = header.match(getPattern(name));
if (!match) return;
let value = match[1];
if (value[0] === "\"") value = value.slice(1, -1);
if (!options || !signed) return value;
const remote = this.get(signName);
if (!remote) return;
const data = `${name}=${value}`;
if (!this.keys) throw new Error(".keys required for signed cookies");
const index = this.keys.index(data, remote);
if (index < 0) this.set(signName, null, {
path: "/",
signed: false
});
else {
index && this.set(signName, this.keys.sign(data), { signed: false });
return value;
}
}
};
/**
* Get the pattern to search for a cookie in a string.
*/
function getPattern(name) {
if (!REGEXP_CACHE[name]) REGEXP_CACHE[name] = new RegExp(`(?:^|;) *${name.replace(REGEXP_ESCAPE_CHARS_REGEXP, "\\$&")}=([^;]*)`);
return REGEXP_CACHE[name];
}
/**
* Get the encrypted status for a request.
*/
function isRequestEncrypted(req) {
return Boolean(req.socket ? req.socket.encrypted : req.connection.encrypted);
}
function pushCookie(headers, cookie) {
if (cookie.overwrite) {
for (let i = headers.length - 1; i >= 0; i--) if (headers[i].indexOf(`${cookie.name}=`) === 0) headers.splice(i, 1);
}
headers.push(cookie.toHeader());
}
//#endregion
//#region src/recorder/constants.ts
const FILTERED_RESPONSE_HEADERS = [
"date",
"expires",
"last-modified",
"server",
"x-powered-by",
"x-aspnet-version",
"x-nginx-version",
"via",
"cache-control",
"etag",
"age",
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"proxy-connection",
"trailer",
"access-control-allow-origin",
"access-control-allow-credentials",
"access-control-allow-methods",
"access-control-allow-headers",
"access-control-expose-headers",
"access-control-max-age",
"origin",
"p3p",
"pragma",
"x-request-id",
"x-correlation-id",
"x-trace-id",
"x-varnish",
"x-cache",
"x-cache-hits",
"x-cache-status",
"cf-cache-status",
"cf-ray",
"cf-request-id",
"server-timing",
"x-dns-prefetch-control"
];
//#endregion
//#region src/recorder/decompress.ts
/**
* Decode response body according to encoding
*
* 根据编码解码响应体
*
* @param rawBody 原始响应体
* @param encoding 编码
* @returns 解码后的响应体
*/
async function decompressBody(rawBody, encoding) {
try {
switch (encoding.toLowerCase()) {
case "gzip":
case "x-gzip": return {
body: await gunzip(rawBody),
encoding: "identity"
};
case "deflate":
case "x-deflate": return {
body: await deflate(rawBody),
encoding: "identity"
};
case "br": return {
body: await brotli(rawBody),
encoding: "identity"
};
case "zstd": return {
body: await zstd(rawBody),
encoding: "identity"
};
}
} catch {}
return {
body: rawBody,
encoding
};
}
let zstdStreaming = null;
/**
* Decompress zstd compressed data
*
* 解压缩 zstd 压缩数据
*
* zlib.zstdDecompress 从 v22.15.0 开始支持,对于旧版本 Node.js 可以使用 zstd-codec 库
*
* @param rawBody 压缩数据
* @returns 解压缩后的数据
*/
async function zstd(rawBody) {
if (zlib.zstdDecompress) return new Promise((resolve, reject) => {
zlib.zstdDecompress(rawBody, (err, data) => {
err ? reject(err) : resolve(data);
});
});
if (!zstdStreaming) {
const { ZstdCodec } = await import("zstd-codec");
zstdStreaming = await new Promise((resolve) => {
ZstdCodec.run((binding) => {
resolve(new binding.Streaming());
});
});
}
return zstdStreaming.decompress(rawBody, rawBody.length);
}
/**
* Decompress brotli compressed data
*
* 解压缩 brotli 压缩数据
*
* @param rawBody 压缩数据
* @returns 解压缩后的数据
*/
async function brotli(rawBody) {
return new Promise((resolve, reject) => {
zlib.brotliDecompress(rawBody, (err, data) => {
err ? reject(err) : resolve(data);
});
});
}
async function gunzip(rawBody) {
return new Promise((resolve, reject) => {
zlib.gunzip(rawBody, (err, data) => {
err ? reject(err) : resolve(data);
});
});
}
async function deflate(rawBody) {
return new Promise((resolve, reject) => {
zlib.inflate(rawBody, (err, data) => {
err ? reject(err) : resolve(data);
});
});
}
//#endregion
//#region src/recorder/helper.ts
const timeFormatter = new Intl.DateTimeFormat("en-US", {
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
hour12: false
});
/**
* 处理记录的请求
*
* @param req 原始请求对象
* @param pathname 请求路径
* @param body 请求体
* @returns 处理后的请求记录
*/
function processRecordReq(req, pathname, body) {
const { query } = urlParse(req.url);
const method = req.method.toUpperCase();
let bodyType = (req.headers["content-type"] || "").split(";")[0].trim();
if (bodyType.startsWith("multipart/form-data") && isPlainObject(body)) {
body = { ...body };
objectKeys(body).forEach((key) => {
const value = body[key];
if (isPlainObject(value) && hasOwn(value, "filepath") && hasOwn(value, "mimetype")) delete body[key];
});
}
if (Buffer.isBuffer(body)) {
body = body.toString();
bodyType = "buffer";
}
return {
method,
pathname,
query,
bodyType,
body
};
}
/**
* 处理记录的响应
*
* @param res 原始响应对象
* @param body 响应体
* @returns 处理后的响应记录
*/
async function processRecordRes(res, body) {
const status = res.statusCode || 200;
const statusText = res.statusMessage || "OK";
const headers = {};
for (const [key, value] of Object.entries(res.headers)) {
const lowerKey = key.toLowerCase();
if (value !== void 0 && !FILTERED_RESPONSE_HEADERS.includes(lowerKey)) headers[key] = String(value);
}
const isText = isTextContent(headers["content-type"] || "");
if (isText) {
const { body: decodedBody, encoding } = await decompressBody(body, headers["content-encoding"] || "");
body = Buffer.from(decodedBody);
headers["content-encoding"] = encoding;
}
return {
status,
statusText,
headers,
body: body.toString(isText ? "utf-8" : "base64")
};
}
/**
* 判断两个请求是否是同一个请求
*
* @param prev 上一个请求
* @param current 当前请求
* @returns 是否是同一个请求
*/
function isSameRecord(prev, current) {
if (prev.pathname !== current.pathname || prev.method !== current.method) return false;
if (prev.bodyType !== current.bodyType) return false;
if (!deepEqual(prev.query, current.query)) return false;
if (current.bodyType === "buffer" && prev.bodyType === "buffer") {
const currentBody = Buffer.from(current.body);
const prevBody = Buffer.from(prev.body);
if (currentBody.length !== prevBody.length || !currentBody.equals(prevBody)) return false;
}
if (!deepEqual(prev.body, current.body)) return false;
return true;
}
/**
* 创建请求记录过滤器
*
* @param filter 记录过滤选项
* @returns 请求匹配函数
*/
function createRecordMatcher(filter) {
if (isFunction(filter)) return filter;
const { mode = "glob" } = filter;
const include = toArray(filter.include);
const exclude = toArray(filter.exclude);
if (mode === "glob") {
const { isMatch } = createMatcher(include, exclude);
return (req) => isMatch(req.pathname);
}
return (req) => {
return include.some((pattern) => isPathMatch(pattern, req.pathname)) && exclude.every((pattern) => !isPathMatch(pattern, req.pathname));
};
}
/**
* 生成记录文件路径
*
* @param pathname 请求路径
* @param dir 记录目录
* @returns 记录文件路径
*/
function getFilepath(pathname, dir) {
return path.join(dir, `${kebabCase(pathname)}.json`);
}
//#endregion
//#region src/recorder/storage.ts
const storage = /* @__PURE__ */ new Map();
/**
* 读取记录文件
*
* @param filepath 记录文件路径
* @returns 记录的请求数组
*/
async function readRecordStorage(filepath) {
if (storage.has(filepath)) return storage.get(filepath);
try {
if (!fs.existsSync(filepath)) return [];
const content = await fs.promises.readFile(filepath, "utf-8") || "[]";
const data = JSON.parse(content);
storage.set(filepath, data);
return data;
} catch (error) {
console.error(`Error reading record file ${filepath}:`, error);
return [];
}
}
/**
* 写入记录文件
*
* @param filepath 记录文件路径
* @param records 记录的请求数组
*/
async function writeRecordStorage(filepath, records) {
try {
storage.set(filepath, records);
await fs.promises.mkdir(path.dirname(filepath), { recursive: true });
await fs.promises.writeFile(filepath, JSON.stringify(records, null, 2), "utf-8");
} catch (error) {
console.error(`Error writing record file ${filepath}:`, error);
}
}
const originalReqCache = /* @__PURE__ */ new WeakMap();
/**
* Record a request with the raw request object.
*
* 记录原始请求对象的请求
*
* @param req The original request object / 原始请求对象
* @param pathname The request pathname / 请求路径名
* @param body The request body / 请求体
*/
function recordRequestWithRawReq(req, pathname, body) {
originalReqCache.set(req, {
body,
pathname,
timestamp: Date.now()
});
}
//#endregion
//#region src/recorder/Recorder.ts
/**
* 请求记录器
*/
var Recorder = class {
options;
filter;
constructor(options) {
this.options = options;
this.filter = createRecordMatcher(options.filter);
this.addGitignore();
}
getPlugin() {
return (proxyServer) => {
proxyServer.on("proxyRes", (proxyRes, req) => {
let chunks = [];
proxyRes.on("data", (chunk) => chunk && chunks.push(chunk));
proxyRes.on("end", () => {
this.record(req, proxyRes, Buffer.concat(chunks));
chunks = null;
});
});
};
}
async record(req, res, resBody) {
if (!originalReqCache.has(req)) return;
const { body, pathname, timestamp } = originalReqCache.get(req);
originalReqCache.delete(req);
if (!pathname) return;
const recordReq = processRecordReq(req, pathname, body);
if (!this.filter(recordReq)) return;
const { cwd, dir, status, expires, overwrite } = this.options;
if (status.length !== 0 && !status.includes(res.statusCode || 200)) return;
const record = {
meta: {
timestamp,
filepath: "",
createAt: timeFormatter.format(timestamp),
referer: req.headers.referer || "unknown"
},
req: recordReq,
res: await processRecordRes(res, resBody)
};
const filepath = getFilepath(pathname, dir);
record.meta.filepath = filepath;
const absoluteFilepath = path.join(cwd, filepath);
const records = (await readRecordStorage(absoluteFilepath)).filter((item) => timestamp - item.meta.timestamp <= expires);
const index = records.findIndex((item) => isSameRecord(item.req, record.req) && item.res.status === record.res.status);
if (index === -1) records.push(record);
else if (overwrite || timestamp - records[index].meta.timestamp > expires) records[index] = record;
await writeRecordStorage(absoluteFilepath, records);
}
async addGitignore() {
const options = this.options;
if (!options.gitignore) return;
const dirname = path.join(options.cwd, options.dir);
await promises.mkdir(dirname, { recursive: true });
if (!fs.existsSync(path.join(dirname, ".gitignore"))) await promises.writeFile(path.join(dirname, ".gitignore"), "*\n", "utf-8");
}
};
//#endregion
//#region src/recorder/replay.ts
/**
* Replay a recorded request.
*
* 重放已记录的请求
*
* @param rawReq The original request object / 原始请求对象
* @param pathname The request pathname / 请求路径名
* @param body The request body / 请求体
* @param options Record options / 录制配置项
* @returns The recorded request object if found, otherwise undefined / 如果找到记录的请求对象,则返回该对象,否则返回 undefined
*/
async function replayRecordedRequest(rawReq, pathname, body, options) {
const req = processRecordReq(rawReq, pathname, body);
const filepath = path.join(options.cwd, getFilepath(req.pathname, options.dir));
const timestamp = Date.now();
const records = await readRecordStorage(filepath);
const matchedList = records.filter((item) => timestamp - item.meta.timestamp < options.expires && isSameRecord(item.req, req));
let matched;
if (options.status.length === 0) matched = matchedList.find((item) => item.res.status === 200) || records[0];
else matched = matchedList.find((item) => options.status.includes(item.res.status));
if (matched) {
const isText = isTextContent(matched.res.headers["content-type"] || "");
return {
url: matched.req.pathname,
status: matched.res.status,
statusText: matched.res.statusText,
headers: matched.res.headers,
body: Buffer.from(matched.res.body, isText ? "utf-8" : "base64"),
type: "buffer",
__filepath__: matched.meta.filepath
};
}
}
//#endregion
//#region src/mockHttp/matchingWeight.ts
const tokensCache = {};
function getTokens(rule) {
if (tokensCache[rule]) return tokensCache[rule];
const res = [];
const flatten = (tokens, group = false) => {
for (const token of tokens) if (token.type === "text") {
const sub = token.value.split("/").filter(Boolean);
sub.length && res.push(...sub.map((v) => ({
type: "text",
value: v
})));
} else if (token.type === "group") flatten(token.tokens, true);
else {
if (group) token.optional = true;
res.push(token);
}
};
flatten(parse(rule).tokens);
tokensCache[rule] = res;
return res;
}
function getHighest(rules) {
let weights = rules.map((rule) => getTokens(rule).length);
weights = weights.length === 0 ? [1] : weights;
return Math.max(...weights) + 2;
}
function computedWeight(rule, highest) {
const tokens = getTokens(rule);
const dym = tokens.filter((token) => token.type !== "text");
if (dym.length === 0) return 0;
let weight = dym.length;
let exp = 0;
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i];
const isDynamic = token.type !== "text";
const isWildcard = token.type === "wildcard";
const isOptional = !!token.optional;
exp += isDynamic ? 1 : 0;
if (i === tokens.length - 1 && isWildcard) weight += (isOptional ? 5 : 4) * 10 ** (tokens.length === 1 ? highest + 1 : highest);
else {
if (isWildcard) weight += 3 * 10 ** (highest - 1);
else weight += 2 * 10 ** exp;
if (isOptional) weight += 10 ** exp;
}
}
return weight;
}
function defaultPriority(rules) {
const highest = getHighest(rules);
return rules.sort((a, b) => computedWeight(a, highest) - computedWeight(b, highest));
}
/**
* Calculate matching weight for mock URLs
*
* 计算 Mock URL 的匹配权重
*
* @param rules - Array of URL patterns / URL 模式数组
* @param url - Request URL / 请求 URL
* @param priority - Priority configuration / 优先级配置
* @returns Sorted array of matched rules / 排序后的匹配规则数组
*/
function matchingWeight(rules, url, priority) {
let matched = defaultPriority(rules.filter((rule) => isPathMatch(rule, url)));
const { global = [], special = {} } = priority;
if (global.length === 0 && isEmptyObject(special) || matched.length === 0) return matched;
const [dynamics, statics] = partition(matched, (rule) => getTokens(rule).filter((token) => token.type !== "text").length > 0);
const globalMatch = global.filter((rule) => dynamics.includes(rule));
if (globalMatch.length > 0) matched = uniq([
...statics,
...globalMatch,
...dynamics
]);
if (isEmptyObject(special)) return matched;
const specialRule = Object.keys(special).filter((rule) => matched.includes(rule))[0];
if (!specialRule) return matched;
const options = special[specialRule];
const { rules: lowerRules, when } = isArray(options) ? {
rules: options,
when: []
} : options;
if (lowerRules.includes(matched[0])) {
if (when.length === 0 || when.some((path) => pathToRegexp(path).regexp.test(url))) matched = uniq([specialRule, ...matched]);
}
return matched;
}
//#endregion
//#region src/mockHttp/requestRecovery.ts
/**
* 请求复原
*
* 由于 parseReqBody 在解析请求时,会将请求流消费,
* 导致当接口不需要被 mock,继而由 vite http-proxy 转发时,请求流无法继续。
* 为此,我们在请求流中记录请求数据,当当前请求无法继续时,可以从备份中恢复请求流
*/
const requestCollectCache = /* @__PURE__ */ new WeakMap();
function collectRequest(req) {
const chunks = [];
req.on("data", (chunk) => {
chunks.push(Buffer.from(chunk));
});
req.on("end", () => {
if (chunks.length) requestCollectCache.set(req, Buffer.concat(chunks));
});
}
function rewriteRequest(proxyReq, req) {
const buffer = requestCollectCache.get(req);
if (buffer) {
requestCollectCache.delete(req);
if (!proxyReq.headersSent) proxyReq.setHeader("Content-Length", buffer.byteLength);
if (!proxyReq.writableEnded) proxyReq.write(buffer);
}
}
//#endregion
//#region src/mockHttp/response.ts
/**
* Get HTTP status text by status code
*
* 根据状态码获取状态文本
*
* @param status - HTTP status code / HTTP 状态码
* @returns HTTP status text / HTTP 状态文本
*/
function getHTTPStatusText(status) {
return HTTP_STATUS[status] || "Unknown";
}
/**
* Set response status
*
* 设置响应状态
*
* @param response - Response object / 响应对象
* @param status - HTTP status code / HTTP 状态码
* @param statusText - HTTP status text / HTTP 状态文本
*/
function provideResponseStatus(response, status = 200, statusText) {
response.statusCode = status;
response.statusMessage = statusText || getHTTPStatusText(status);
}
/**
* Set response headers
*
* 设置响应头
*
* @param req - Request object / 请求对象
* @param res - Response object / 响应对象
* @param mock - Mock HTTP item / Mock HTTP 配置项
* @param logger - Logger instance / 日志实例
*/
async function provideResponseHeaders(req, res, mock, logger) {
const { headers, type = "json" } = mock;
const filepath = mock.__filepath__;
const contentType = mime.contentType(type) || mime.contentType(mime.lookup(type) || "");
if (contentType) res.setHeader("Content-Type", contentType);
res.setHeader("Cache-Control", "no-cache,max-age=0");
res.setHeader("X-Mock-Power-By", "vite-plugin-mock-dev-server");
if (filepath) res.setHeader("X-File-Path", filepath);
if (!headers) return;
const [error, data] = await attemptAsync(async () => isFunction(headers) ? await headers(req) : headers);
if (error) {
logger.error(`${ansis.red(`mock error at ${req.url.split("?")[0]}`)}\n${error}\n at headers (${ansis.underline(filepath)})`, mock.log);
return;
}
objectKeys(data).forEach((key) => res.setHeader(key, data[key]));
}
/**
* Set response cookies
*
* 设置响应cookie
*
* @param req - Request object / 请求对象
* @param res - Response object / 响应对象
* @param mock - Mock HTTP item / Mock HTTP 配置项
* @param logger - Logger instance / 日志实例
*/
async function provideResponseCookies(req, res, mock, logger) {
const { cookies } = mock;
if (!cookies) return;
const [error, data] = await attemptAsync(async () => isFunction(cookies) ? await cookies(req) : cookies);
if (error) {
const filepath = mock.__filepath__;
logger.error(`${ansis.red(`mock error at ${req.url.split("?")[0]}`)}\n${error}\n at cookies (${ansis.underline(filepath)})`, mock.log);
return;
}
objectKeys(data).forEach((key) => {
const cookie = data[key];
const [value, options] = isArray(cookie) ? cookie : [cookie];
res.setCookie(key, value, options);
});
}
/**
* Send response data
*
* 设置响应数据
*
* @param res - Response object / 响应对象
* @param raw - Response body data / 响应体数据
* @param type - Response data type / 响应数据类型
*/
function sendResponseData(res, raw, type) {
if (isReadableStream(raw)) raw.pipe(res);
else if (Buffer.isBuffer(raw)) res.end(type === "text" || type === "json" ? raw.toString("utf-8") : raw);
else {
const content = typeof raw === "string" ? raw : JSON.stringify(raw);
res.end(type === "buffer" ? Buffer.from(content) : content);
}
}
/**
* Apply real response delay
*
* 实际响应延迟
*
* @param startTime - Request start time / 请求开始时间
* @param delay - Delay configuration / 延迟配置
*/
async function responseRealDelay(startTime, delay) {
if (!delay || typeof delay === "number" && delay <= 0 || isArray(delay) && delay.length !== 2) return;
let realDelay = 0;
if (isArray(delay)) {
const [min, max] = delay;
realDelay = random(min, max);
} else realDelay = delay - (timestamp() - startTime);
if (realDelay > 0) await sleep(realDelay);
}
//#endregion
//#region src/mockHttp/middleware.ts
/**
* Create mock middleware
*
* 创建 Mock 中间件
*
* @param compiler - Compiler instance / 编译器实例
* @param options - Middleware options / 中间件配置项
* @param options.formidableOptions - Formidable options / Formidable 配置项
* @param options.bodyParserOptions - Body parser options / 请求体解析配置项
* @param options.proxies - Proxy paths / 代理路径
* @param options.cookiesOptions - Cookies options / Cookies 配置项
* @param options.logger - Logger instance / 日志实例
* @param options.priority - Path matching priority / 路径匹配优先级
* @param options.cors - CORS options / CORS 配置项
* @param options.record - Record options / 录制配置项
* @param options.replay - Replay options / 回放配置项
* @param options.activeScene - Active scene / 活动场景
*
* @returns Connect middleware function / Connect 中间件函数
*/
function createMockMiddleware(compiler, { formidableOptions = {}, bodyParserOptions = {}, proxies, cookiesOptions, logger, priority = {}, cors: corsOptions, record, replay, activeScene }) {
const cors = createCors(corsOptions);
const [globFilter, contextFilter] = partition(proxies, (item) => isString(item) && item.includes("*"));
const { isMatch: isGlobProxiesMatch } = createMatcher(globFilter, [], false);
return async function(req, res, next) {
const startTime = timestamp();
const { query, pathname } = urlParse(req.url);
if (!pathname || proxies.length === 0) return next();
if (contextFilter.length && !contextFilter.some((context) => doesProxyContextMatchUrl(context, req))) return next();
if (globFilter.length && !isGlobProxiesMatch(pathname)) return next();
const mockData = compiler.mockData;
const mockUrls = matchingWeight(Object.keys(mockData), pathname, priority);
if (mockUrls.length === 0 && !record.enabled) return next();
collectRequest(req);
const cookies = new Cookies(req, res, cookiesOptions);
let mock;
let _mockUrl;
const method = req.method.toUpperCase();
const extraReq = {
query,
refererQuery: urlParse(req.headers.referer || "").query,
body: await parseRequestBody(req, logger, formidableOptions, bodyParserOptions),
headers: req.headers,
getCookie: cookies.get.bind(cookies)
};
const headerScene = req.headers["x-mock-scene"];
const effectiveScene = headerScene ? toArray(headerScene).map((item) => item.split(",").map((s) => s.trim())).flat().filter(Boolean) : activeScene;
for (const mockUrl of mockUrls) {
mock = findMockData(mockData[mockUrl], logger, {
pathname,
method,
request: extraReq,
activeScene: effectiveScene
});
if (mock) {
_mockUrl = mockUrl;
break;
}
}
if (replay && !mock) mock = await replayRecordedRequest(req, pathname, extraReq.body, record);
if (!mock) {
record.enabled && recordRequestWithRawReq(req, pathname, extraReq.body);
const matched = mockUrls.map((m) => m === _mockUrl ? ansis.underline.bold(m) : ansis.dim(m)).join(", ");
matched.length && logger.warn(`${ansis.green(pathname)} matches ${matched}, but mock data is not found.`);
return next();
}
if (cors) {
const [error] = await attemptAsync(cors, req, res);
if (error) {
logger.error(`CORS error: ${error}`);
return next(error);
}
}
const request = req;
const response = res;
Object.assign(request, extraReq);
request.params = parseRequestParams(mock.url, pathname);
response.setCookie = cookies.set.bind(cookies);
const { delay, type = "json", response: responseFn, log: logLevel, error: errorConfig, __filepath__: filepath } = mock;
let { body, status = 200, statusText } = mock;
const shouldSimulateError = errorConfig && (errorConfig.probability ?? .5) > Math.random();
if (shouldSimulateError) {
status = errorConfig.status ?? 500;
statusText = errorConfig.statusText;
body = errorConfig.body;
}
provideResponseStatus(response, status, statusText);
await provideResponseHeaders(request, response, mock, logger);
await provideResponseCookies(request, response, mock, logger);
logger.info(requestLog(request, filepath, shouldSimulateError), logLevel);
logger.debug(`${ansis.magenta("DEBUG")} ${ansis.underline(pathname)} matches: [ ${mockUrls.map((m) => m === _mockUrl ? ansis.underline.bold(m) : ansis.dim(m)).join(", ")} ]\n`);
if (body) {
const [error] = await attemptAsync(async () => {
const content = isFunction(body) ? await body(request) : body;
await responseRealDelay(startTime, delay);
sendResponseData(response, content, type);
});
if (error) {
logger.error(`${ansis.red(`mock error at ${pathname}`)}\n ${error}\n at body (${ansis.underline.gray(filepath)})`, logLevel);
provideResponseStatus(response, 500);
res.end("");
}
return;
}
if (responseFn) {
const [error] = await attemptAsync(async () => {
await responseRealDelay(startTime, delay);
await responseFn(request, response, next);
});
if (error) {
logger.error(`${ansis.red(`mock error at ${pathname}`)}\n ${error}\n at response (${ansis.underline.gray(filepath)})`, logLevel);
provideResponseStatus(response, 500);
res.end("");
}
return;
}
res.end("");
};
}
//#endregion
//#region src/mockWebsocket/server.ts
function mockWebSocket(compiler, httpServer, { wsProxies: proxies, cookiesOptions, logger }) {
const hmrMap = /* @__PURE__ */ new Map();
const poolMap = /* @__PURE__ */ new Map();
const wssContextMap = /* @__PURE__ */ new WeakMap();
const getWssMap = (mockUrl) => {
let wssMap = poolMap.get(mockUrl);
if (!wssMap) poolMap.set(mockUrl, wssMap = /* @__PURE__ */ new Map());
return wssMap;
};
const addHmr = (filepath, mockUrl) => {
let urlList = hmrMap.get(filepath);
if (!urlList) hmrMap.set(filepath, urlList = /* @__PURE__ */ new Set());
urlList.add(mockUrl);
};
const setupWss = (wssMap, wss, mock, context, pathname, filepath) => {
try {
mock.setup?.(wss, context);
wss.on("close", () => wssMap.delete(pathname));
wss.on("error", (e) => {
logger.error(`${ansis.red(`WebSocket mock error at ${wss.path}`)}\n${e}\n at setup (${filepath})`, mock.log);
});
} catch (e) {
logger.error(`${ansis.red(`WebSocket mock error at ${wss.path}`)}\n${e}\n at setup (${filepath})`, mock.log);
}
};
const restartWss = (wssMap, wss, mock, pathname, filepath) => {
const { cleanupList, connectionList, context } = wssContextMap.get(wss);
cleanupRunner(cleanupList);
connectionList.forEach(({ ws }) => ws.removeAllListeners());
wss.removeAllListeners();
setupWss(wssMap, wss, mock, context, pathname, filepath);
connectionList.forEach(({ ws, req }) => emitConnection(wss, ws, req, connectionList));
};
compiler.on("update", ({ filepath }) => {
if (!hmrMap.has(filepath)) return;
const mockUrlList = hmrMap.get(filepath);
if (!mockUrlList) return;
for (const mockUrl of mockUrlList.values()) for (const mock of compiler.mockData[mockUrl]) {
if (!mock.ws || mock.__filepath__ !== filepath) return;
const wssMap = getWssMap(mockUrl);
for (const [pathname, wss] of wssMap.entries()) restartWss(wssMap, wss, mock, pathname, filepath);
}
});
const [globFilter, contextFilter] = partition(proxies, (item) => isString(item) && item.includes("*"));
const { isMatch: isGlobProxiesMatch } = createMatcher(globFilter, [], false);
httpServer?.on("upgrade", (req, socket, head) => {
const { pathname, query } = urlParse(req.url);
if (!pathname || proxies.length === 0) return;
if (contextFilter.length && !contextFilter.some((context) => doesProxyContextMatchUrl(context, req))) return;
if (globFilter.length && !isGlobProxiesMatch(pathname)) return;
const mockData = compiler.mockData;
const mockUrl = objectKeys(mockData).find((key) => isPathMatch(key, pathname));
if (!mockUrl) return;
const mock = mockData[mockUrl].find((mock) => {
return mock.url && mock.ws && isPathMatch(mock.url, pathname);
});
if (!mock) return;
const filepath = mock.__filepath__;
addHmr(filepath, mockUrl);
const wssMap = getWssMap(mockUrl);
const wss = getWss(wssMap, pathname);
let wssContext = wssContextMap.get(wss);
if (!wssContext) {
const cleanupList = [];
const context = { onCleanup: (cleanup) => cleanupList.push(cleanup) };
wssContext = {
cleanupList,
context,
connectionList: []
};
wssContextMap.set(wss, wssContext);
setupWss(wssMap, wss, mock, context, pathname, filepath);
}
const request = req;
const cookies = new Cookies(req, req, cookiesOptions);
const { query: refererQuery } = urlParse(req.headers.referer || "");
request.query = query;
request.refererQuery = refererQuery;
request.params = parseRequestParams(mockUrl, pathname);
request.getCookie = cookies.get.bind(cookies);
wss.handleUpgrade(request, socket, head, (ws) => {
logger.info(`${ansis.magenta(ansis.bold("WebSocket"))} ${ansis.green(req.url)} connected ${ansis.dim(`(${filepath})`)}`, mock.log);
wssContext.connectionList.push({
req: request,
ws
});
emitConnection(wss, ws, request, wssContext.connectionList);
});
});
httpServer?.on("close", () => {
for (const wssMap of poolMap.values()) {
for (const wss of wssMap.values()) {
cleanupRunner(wssContextMap.get(wss).cleanupList);
wss.close();
}
wssMap.clear();
}
poolMap.clear();
hmrMap.clear();
});
}
function getWss(wssMap, pathname) {
let wss = wssMap.get(pathname);
if (!wss) wssMap.set(pathname, wss = new WebSocketServer({ noServer: true }));
return wss;
}
function emitConnection(wss, ws, req, connectionList) {
wss.emit("connection", ws, req);
ws.on("close", () => {
const i = connectionList.findIndex((item) => item.ws === ws);
if (i !== -1) connectionList.splice(i, 1);
});
}
function cleanupRunner(cleanupList) {
let cleanup;
while (cleanup = cleanupList.shift()) cleanup?.();
}
//#endregion
//#region src/core/logger.ts
const logLevels = {
silent: 0,
error: 1,
warn: 2,
info: 3,
debug: 4
};
function createLogger(prefix, defaultLevel = "info") {
prefix = `[${prefix}]`;
function output(type, msg, level) {
level = isBoolean(level) ? level ? defaultLevel : "error" : level;
if (logLevels[level] >= logLevels[type]) {
const method = type === "info" || type === "debug" ? "log" : type;
const tag = type === "debug" ? ansis.magenta.bold(prefix) : type === "info" ? ansis.cyan.bold(prefix) : type === "warn" ? ansis.yellow.bold(prefix) : ansis.red.bold(prefix);
const format = `${ansis.dim((/* @__PURE__ */ new Date()).toLocaleTimeString())} ${tag} ${msg}`;
console[method](format);
}
}
return {
debug(msg, level = defaultLevel) {
output("debug", msg, level);
},
info(msg, level = defaultLevel) {
output("info", msg, level);
},
warn(msg, level = defaultLevel) {
output("warn", msg, level);
},
error(msg, level = defaultLevel) {
output("error", msg, level);
}
};
}
//#endregion
export { rewriteRequest as a, processRawData as c, normalizePath as d, vfs as f, createMatcher as h, createMockMiddleware as i, sortByValidator as l, getPackageDeps as m, logLevels as n, Recorder as o, getPackageDepList as p, mockWebSocket as r, processMockData as s, createLogger as t, waitingFor as