vite-plugin-mock-dev-server 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -152,6 +152,14 @@ export default defineConfig({
152
152
  > Different from using `viteConfig.server.proxy` by default for http mock, `websocket mock` does not use the ws-related configuration in `viteConfig.server.proxy`. Also, rules configured in `wsPrefix` cannot be configured simultaneously in `viteConfig.server.proxy`, as it will cause conflicts when starting the vite server because multiple instances of WebSocketServer cannot be implemented for the same request.
153
153
  > This conflict is neither a problem with Vite nor with the plugin; it belongs to a reasonable error type. When switching between WebSocket Mock and WebSocket Proxy, please pay attention to avoid duplicate configurations that may cause conflicts.
154
154
 
155
+ - `option.cwd`
156
+
157
+ **Type:** `string`
158
+
159
+ Configure the matching context for `include` and `exclude`.
160
+
161
+ **Default:** `process.cwd()`
162
+
155
163
  - `option.include`
156
164
 
157
165
  **Type:** `string | string[]`
@@ -939,7 +947,7 @@ You can access related `mock` interfaces through `localhost:8080/`.
939
947
  ## Contributors
940
948
 
941
949
  <!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
942
- [![All Contributors](https://img.shields.io/badge/all_contributors-4-orange.svg?style=flat-square)](#contributors)
950
+ [![All Contributors](https://img.shields.io/badge/all_contributors-5-orange.svg?style=flat-square)](#contributors)
943
951
  <!-- ALL-CONTRIBUTORS-BADGE:END -->
944
952
 
945
953
  <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
@@ -952,6 +960,7 @@ You can access related `mock` interfaces through `localhost:8080/`.
952
960
  <td align="center" valign="top" width="14.28%"><a href="https://github.com/jiadesen"><img src="https://avatars.githubusercontent.com/u/22772994?v=4?s=100" width="100px;" alt="jiadesen"/><br /><sub><b>jiadesen</b></sub></a><br /><a href="#ideas-jiadesen" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/pengzhanbo/vite-plugin-mock-dev-server/issues?q=author%3Ajiadesen" title="Bug reports">🐛</a></td>
953
961
  <td align="center" valign="top" width="14.28%"><a href="https://github.com/yogibaba"><img src="https://avatars.githubusercontent.com/u/152670?v=4?s=100" width="100px;" alt="yogibaba"/><br /><sub><b>yogibaba</b></sub></a><br /><a href="https://github.com/pengzhanbo/vite-plugin-mock-dev-server/commits?author=yogibaba" title="Code">💻</a></td>
954
962
  <td align="center" valign="top" width="14.28%"><a href="https://github.com/pfdgithub"><img src="https://avatars.githubusercontent.com/u/3262762?v=4?s=100" width="100px;" alt="pfdgithub"/><br /><sub><b>pfdgithub</b></sub></a><br /><a href="https://github.com/pengzhanbo/vite-plugin-mock-dev-server/commits?author=pfdgithub" title="Code">💻</a> <a href="https://github.com/pengzhanbo/vite-plugin-mock-dev-server/issues?q=author%3Apfdgithub" title="Bug reports">🐛</a></td>
963
+ <td align="center" valign="top" width="14.28%"><a href="https://github.com/chuyuandu"><img src="https://avatars.githubusercontent.com/u/6959138?v=4?s=100" width="100px;" alt="chuyuan du"/><br /><sub><b>chuyuan du</b></sub></a><br /><a href="https://github.com/pengzhanbo/vite-plugin-mock-dev-server/commits?author=chuyuandu" title="Code">💻</a></td>
955
964
  </tr>
956
965
  </tbody>
957
966
  </table>
package/README.zh-CN.md CHANGED
@@ -151,6 +151,14 @@ export default defineConfig({
151
151
  > 与 http mock 默认使用 `viteConfig.server.proxy` 不同的是,`websocket mock` 不会使用 `viteConfig.server.proxy` 中的 ws 相关的配置,且配置在 `wsPrefix` 中的规则,不能同时配置在 `viteConfig.server.proxy`中,因为会导致在 vite 在启动服务时产生冲突,因为不能对同一个请求实现多个的 `WebSocketServer`实例。
152
152
  > 该冲突既不是 `vite` 的问题,也不是插件的问题,这属于合理的错误类型。在进行 `WebSocket Mock`和 `WebSocket Proxy` 切换时,请注意配置不要出现重复导致冲突。
153
153
 
154
+ - `option.cwd`
155
+
156
+ **类型:** `string`
157
+
158
+ 配置 `include` 和 `exclude` 的匹配上下文
159
+
160
+ **默认值:** `process.cwd()`
161
+
154
162
  - `option.include`
155
163
 
156
164
  **类型:** `string | string[]`
package/dist/index.cjs CHANGED
@@ -44,11 +44,12 @@ __export(src_exports, {
44
44
  });
45
45
  module.exports = __toCommonJS(src_exports);
46
46
 
47
- // node_modules/.pnpm/tsup@8.0.2_typescript@5.4.3/node_modules/tsup/assets/cjs_shims.js
48
- var getImportMetaUrl = () => typeof document === "undefined" ? new URL("file:" + __filename).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
47
+ // node_modules/.pnpm/tsup@8.2.3_jiti@1.21.0_postcss@8.4.40_typescript@5.5.4/node_modules/tsup/assets/cjs_shims.js
48
+ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.src || new URL("main.js", document.baseURI).href;
49
49
  var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
50
50
 
51
51
  // src/plugin.ts
52
+ var import_node_process4 = __toESM(require("process"), 1);
52
53
  var import_utils16 = require("@pengzhanbo/utils");
53
54
 
54
55
  // src/build.ts
@@ -98,8 +99,9 @@ function lookupFile(dir, formats, options) {
98
99
  }
99
100
  }
100
101
  const parentDir = import_node_path.default.dirname(dir);
101
- if (parentDir !== dir && (!(options == null ? void 0 : options.rootDir) || parentDir.startsWith(options == null ? void 0 : options.rootDir)))
102
+ if (parentDir !== dir && (!(options == null ? void 0 : options.rootDir) || parentDir.startsWith(options == null ? void 0 : options.rootDir))) {
102
103
  return lookupFile(parentDir, formats, options);
104
+ }
103
105
  }
104
106
  function ensureProxies(serverProxy = {}) {
105
107
  const httpProxies = [];
@@ -107,10 +109,11 @@ function ensureProxies(serverProxy = {}) {
107
109
  Object.keys(serverProxy).forEach((key) => {
108
110
  var _a, _b;
109
111
  const value = serverProxy[key];
110
- if (typeof value === "string" || !value.ws && !((_a = value.target) == null ? void 0 : _a.toString().startsWith("ws:")) && !((_b = value.target) == null ? void 0 : _b.toString().startsWith("wss:")))
112
+ if (typeof value === "string" || !value.ws && !((_a = value.target) == null ? void 0 : _a.toString().startsWith("ws:")) && !((_b = value.target) == null ? void 0 : _b.toString().startsWith("wss:"))) {
111
113
  httpProxies.push(key);
112
- else
114
+ } else {
113
115
  wsProxies.push(key);
116
+ }
114
117
  });
115
118
  return { httpProxies, wsProxies };
116
119
  }
@@ -230,7 +233,12 @@ async function transformWithEsbuild(entryPoint, options) {
230
233
  }
231
234
  var _dirname = getDirname(importMetaUrl);
232
235
  var _require = (0, import_node_module.createRequire)(_dirname);
233
- async function loadFromCode(filepath, code, isESM, cwd) {
236
+ async function loadFromCode({
237
+ filepath,
238
+ code,
239
+ isESM,
240
+ cwd
241
+ }) {
234
242
  if (isESM) {
235
243
  const fileBase = `${filepath}.timestamp-${Date.now()}`;
236
244
  const fileNameTmp = `${fileBase}.mjs`;
@@ -283,11 +291,13 @@ function viteDefine(config) {
283
291
  if (typeof val === "string") {
284
292
  if (canJsonParse(val)) {
285
293
  userDefine[key] = val;
286
- isMetaEnv && (userDefineEnv[key.slice(16)] = val);
294
+ if (isMetaEnv)
295
+ userDefineEnv[key.slice(16)] = val;
287
296
  }
288
297
  } else {
289
298
  userDefine[key] = handleDefineValue(val);
290
- isMetaEnv && (userDefineEnv[key.slice(16)] = val);
299
+ if (isMetaEnv)
300
+ userDefineEnv[key.slice(16)] = val;
291
301
  }
292
302
  }
293
303
  const importMetaKeys = {};
@@ -344,11 +354,12 @@ function canJsonParse(value) {
344
354
 
345
355
  // src/build.ts
346
356
  var packageName = true ? "vite-plugin-mock-dev-server" : "vite-plugin-mock-dev-server";
347
- var packageVersion = true ? "1.5.0" : "latest";
357
+ var packageVersion = true ? "1.6.0" : "latest";
348
358
  async function generateMockServer(ctx, config, options) {
349
359
  const include = (0, import_utils2.toArray)(options.include);
350
360
  const exclude = (0, import_utils2.toArray)(options.exclude);
351
361
  const define = viteDefine(config);
362
+ const cwd = options.cwd || import_node_process2.default.cwd();
352
363
  const { httpProxies } = ensureProxies(config.server.proxy || {});
353
364
  httpProxies.push(...(0, import_utils2.toArray)(options.prefix));
354
365
  const wsProxies = (0, import_utils2.toArray)(options.wsPrefix);
@@ -360,8 +371,8 @@ async function generateMockServer(ctx, config, options) {
360
371
  } catch {
361
372
  }
362
373
  const outputDir = options.build.dist;
363
- const content = await generateMockEntryCode(import_node_process2.default.cwd(), include, exclude);
364
- const mockEntry = import_node_path3.default.join(config.root, `mock-data-${Date.now()}.js`);
374
+ const content = await generateMockEntryCode(cwd, include, exclude);
375
+ const mockEntry = import_node_path3.default.join(cwd, `mock-data-${Date.now()}.js`);
365
376
  await import_promises.default.writeFile(mockEntry, content, "utf-8");
366
377
  const { code, deps } = await transformWithEsbuild(mockEntry, {
367
378
  define,
@@ -676,8 +687,7 @@ function twoPartMatch(rules) {
676
687
  const dym = tokens.filter((token) => typeof token !== "string");
677
688
  if (dym.length > 0)
678
689
  dynamics.push(rule);
679
- else
680
- statics.push(rule);
690
+ else statics.push(rule);
681
691
  }
682
692
  return [statics, dynamics];
683
693
  }
@@ -818,12 +828,14 @@ function baseMiddleware(mockLoader, {
818
828
  return async function(req, res, next) {
819
829
  const startTime = (0, import_utils6.timestamp)();
820
830
  const { query, pathname } = urlParse(req.url);
821
- if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url)))
831
+ if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url))) {
822
832
  return next();
833
+ }
823
834
  const mockData = mockLoader.mockData;
824
835
  const mockUrls = matchingWeight(Object.keys(mockData), pathname, priority);
825
- if (mockUrls.length === 0)
836
+ if (mockUrls.length === 0) {
826
837
  return next();
838
+ }
827
839
  collectRequest(req);
828
840
  const { query: refererQuery } = urlParse(req.headers.referer || "");
829
841
  const reqBody = await parseReqBody(req, formidableOptions, bodyParserOptions);
@@ -974,10 +986,12 @@ async function provideHeaders(req, res, mock, logger) {
974
986
  const { headers, type = "json" } = mock;
975
987
  const filepath = mock.__filepath__;
976
988
  const contentType2 = mime.contentType(type) || mime.contentType(mime.lookup(type) || "");
977
- contentType2 && res.setHeader("Content-Type", contentType2);
989
+ if (contentType2)
990
+ res.setHeader("Content-Type", contentType2);
978
991
  res.setHeader("Cache-Control", "no-cache,max-age=0");
979
992
  res.setHeader("X-Mock-Power-By", "vite-plugin-mock-dev-server");
980
- filepath && res.setHeader("X-File-Path", filepath);
993
+ if (filepath)
994
+ res.setHeader("X-File-Path", filepath);
981
995
  if (!headers)
982
996
  return;
983
997
  try {
@@ -1034,8 +1048,9 @@ function sendData(res, raw, type) {
1034
1048
  }
1035
1049
  }
1036
1050
  async function realDelay(startTime, delay) {
1037
- if (!delay || typeof delay === "number" && delay <= 0 || (0, import_utils6.isArray)(delay) && delay.length !== 2)
1051
+ if (!delay || typeof delay === "number" && delay <= 0 || (0, import_utils6.isArray)(delay) && delay.length !== 2) {
1038
1052
  return;
1053
+ }
1039
1054
  let realDelay2 = 0;
1040
1055
  if ((0, import_utils6.isArray)(delay)) {
1041
1056
  const [min, max] = delay;
@@ -1119,7 +1134,7 @@ function transformMockData(mockList) {
1119
1134
  const list = [];
1120
1135
  for (const [, handle] of mockList.entries()) {
1121
1136
  if (handle)
1122
- (0, import_utils9.isArray)(handle) ? list.push(...handle) : list.push(handle);
1137
+ list.push(...(0, import_utils9.toArray)(handle));
1123
1138
  }
1124
1139
  const mocks = {};
1125
1140
  list.filter((mock) => (0, import_utils9.isObject)(mock) && mock.enabled !== false && mock.url).forEach((mock) => {
@@ -1179,7 +1194,7 @@ var MockLoader = class extends import_node_events.default {
1179
1194
  try {
1180
1195
  const pkg = lookupFile(this.cwd, ["package.json"]);
1181
1196
  this.moduleType = !!pkg && JSON.parse(pkg).type === "module" ? "esm" : "cjs";
1182
- } catch (e) {
1197
+ } catch {
1183
1198
  }
1184
1199
  }
1185
1200
  moduleCache = /* @__PURE__ */ new Map();
@@ -1207,7 +1222,8 @@ var MockLoader = class extends import_node_events.default {
1207
1222
  if (!includeFilter(filepath))
1208
1223
  return;
1209
1224
  await this.loadMock(filepath);
1210
- timer && clearImmediate(timer);
1225
+ if (timer)
1226
+ clearImmediate(timer);
1211
1227
  timer = setImmediate(() => {
1212
1228
  this.updateMockList();
1213
1229
  this.emit("mock:update-end", filepath);
@@ -1229,7 +1245,8 @@ var MockLoader = class extends import_node_events.default {
1229
1245
  ignoreInitial: true,
1230
1246
  cwd: this.cwd
1231
1247
  });
1232
- otherGlob.length > 0 && otherGlob.forEach((glob) => watcher.add(glob));
1248
+ if (otherGlob.length > 0)
1249
+ otherGlob.forEach((glob) => watcher.add(glob));
1233
1250
  watcher.on("add", async (filepath) => {
1234
1251
  filepath = normalizePath(filepath);
1235
1252
  this.emit("mock:update", filepath);
@@ -1259,7 +1276,7 @@ var MockLoader = class extends import_node_events.default {
1259
1276
  this.depsWatcher.on("change", (filepath) => {
1260
1277
  filepath = normalizePath(filepath);
1261
1278
  const mockFiles = this.moduleDeps.get(filepath);
1262
- mockFiles && mockFiles.forEach((file) => {
1279
+ mockFiles == null ? void 0 : mockFiles.forEach((file) => {
1263
1280
  this.emit("mock:update", file);
1264
1281
  });
1265
1282
  });
@@ -1272,7 +1289,8 @@ var MockLoader = class extends import_node_events.default {
1272
1289
  for (const [dep] of this.moduleDeps.entries())
1273
1290
  deps.push(dep);
1274
1291
  const exactDeps = deps.filter((dep) => !oldDeps.includes(dep));
1275
- exactDeps.length > 0 && this.depsWatcher.add(exactDeps);
1292
+ if (exactDeps.length > 0)
1293
+ this.depsWatcher.add(exactDeps);
1276
1294
  });
1277
1295
  }
1278
1296
  close() {
@@ -1311,12 +1329,12 @@ var MockLoader = class extends import_node_events.default {
1311
1329
  { isESM, define, alias }
1312
1330
  );
1313
1331
  try {
1314
- const raw = await loadFromCode(
1332
+ const raw = await loadFromCode({
1315
1333
  filepath,
1316
1334
  code,
1317
1335
  isESM,
1318
- this.cwd
1319
- ) || {};
1336
+ cwd: this.cwd
1337
+ }) || {};
1320
1338
  let mockConfig;
1321
1339
  if ((0, import_utils11.hasOwn)(raw, "default")) {
1322
1340
  mockConfig = raw.default;
@@ -1358,17 +1376,20 @@ function mockWebSocket({
1358
1376
  const wssContextMap = /* @__PURE__ */ new WeakMap();
1359
1377
  const getWssMap = (mockUrl) => {
1360
1378
  let wssMap = poolMap.get(mockUrl);
1361
- !wssMap && poolMap.set(mockUrl, wssMap = /* @__PURE__ */ new Map());
1379
+ if (!wssMap)
1380
+ poolMap.set(mockUrl, wssMap = /* @__PURE__ */ new Map());
1362
1381
  return wssMap;
1363
1382
  };
1364
1383
  const getWss = (wssMap, pathname) => {
1365
1384
  let wss = wssMap.get(pathname);
1366
- !wss && wssMap.set(pathname, wss = new import_ws.WebSocketServer({ noServer: true }));
1385
+ if (!wss)
1386
+ wssMap.set(pathname, wss = new import_ws.WebSocketServer({ noServer: true }));
1367
1387
  return wss;
1368
1388
  };
1369
1389
  const addHmr = (filepath, mockUrl) => {
1370
1390
  let urlList = hmrMap.get(filepath);
1371
- !urlList && hmrMap.set(filepath, urlList = /* @__PURE__ */ new Set());
1391
+ if (!urlList)
1392
+ hmrMap.set(filepath, urlList = /* @__PURE__ */ new Set());
1372
1393
  urlList.add(mockUrl);
1373
1394
  };
1374
1395
  const setupWss = (wssMap, wss, mock, context, pathname, filepath) => {
@@ -1433,8 +1454,9 @@ ${e}
1433
1454
  });
1434
1455
  httpServer == null ? void 0 : httpServer.on("upgrade", (req, socket, head) => {
1435
1456
  const { pathname, query } = urlParse(req.url);
1436
- if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url)))
1457
+ if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url))) {
1437
1458
  return;
1459
+ }
1438
1460
  const mockData = loader.mockData;
1439
1461
  const mockUrl = Object.keys(mockData).find((key) => {
1440
1462
  return (0, import_path_to_regexp4.pathToRegexp)(key).test(pathname);
@@ -1504,6 +1526,7 @@ function mockServerMiddleware(config, options, httpServer, ws) {
1504
1526
  (0, import_utils14.isBoolean)(options.log) ? options.log ? "info" : "error" : options.log
1505
1527
  );
1506
1528
  const loader = new MockLoader({
1529
+ cwd: options.cwd,
1507
1530
  include: (0, import_utils14.toArray)(options.include),
1508
1531
  exclude: (0, import_utils14.toArray)(options.exclude),
1509
1532
  define: viteDefine(config),
@@ -1571,8 +1594,9 @@ function corsMiddleware(mockLoader, proxies, config, options) {
1571
1594
  const { pathname } = urlParse(req.url);
1572
1595
  if (!pathname || proxies.length === 0 || !proxies.some(
1573
1596
  (context) => doesProxyContextMatchUrl(context, req.url)
1574
- ))
1597
+ )) {
1575
1598
  return next();
1599
+ }
1576
1600
  const mockData = mockLoader.mockData;
1577
1601
  const mockUrl = Object.keys(mockData).find(
1578
1602
  (key) => (0, import_path_to_regexp5.pathToRegexp)(key).test(pathname)
@@ -1587,6 +1611,7 @@ function corsMiddleware(mockLoader, proxies, config, options) {
1587
1611
  function mockDevServerPlugin({
1588
1612
  prefix = [],
1589
1613
  wsPrefix = [],
1614
+ cwd = import_node_process4.default.cwd(),
1590
1615
  include = ["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],
1591
1616
  exclude = ["**/node_modules/**", "**/.vscode/**", "**/.git/**"],
1592
1617
  reload = false,
@@ -1601,6 +1626,7 @@ function mockDevServerPlugin({
1601
1626
  const pluginOptions = {
1602
1627
  prefix,
1603
1628
  wsPrefix,
1629
+ cwd,
1604
1630
  include,
1605
1631
  exclude,
1606
1632
  reload,
package/dist/index.d.cts CHANGED
@@ -41,6 +41,14 @@ interface MockServerPluginOptions {
41
41
  * @example ['/socket.io']
42
42
  */
43
43
  wsPrefix?: string | string[];
44
+ /**
45
+ * Configure the matching context for `include` and `exclude`.
46
+ *
47
+ * 配置 `include` 和 `exclude` 的匹配上下文
48
+ *
49
+ * @default process.cwd()
50
+ */
51
+ cwd?: string;
44
52
  /**
45
53
  * glob string matching mock includes files
46
54
  *
@@ -564,7 +572,7 @@ type LogType = 'info' | 'warn' | 'error' | 'debug';
564
572
  type LogLevel = LogType | 'silent';
565
573
 
566
574
  /** @deprecated The CJS build of vite-plugin-mock-dev-server's Node API is deprecated. See https://vitejs.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details. */
567
- declare function mockDevServerPlugin({ prefix, wsPrefix, include, exclude, reload, log, cors, formidableOptions, build, cookiesOptions, bodyParserOptions, priority, }?: MockServerPluginOptions): Plugin[];
575
+ declare function mockDevServerPlugin({ prefix, wsPrefix, cwd, include, exclude, reload, log, cors, formidableOptions, build, cookiesOptions, bodyParserOptions, priority, }?: MockServerPluginOptions): Plugin[];
568
576
 
569
577
  /**
570
578
  * mock config Type helper
package/dist/index.d.ts CHANGED
@@ -41,6 +41,14 @@ interface MockServerPluginOptions {
41
41
  * @example ['/socket.io']
42
42
  */
43
43
  wsPrefix?: string | string[];
44
+ /**
45
+ * Configure the matching context for `include` and `exclude`.
46
+ *
47
+ * 配置 `include` 和 `exclude` 的匹配上下文
48
+ *
49
+ * @default process.cwd()
50
+ */
51
+ cwd?: string;
44
52
  /**
45
53
  * glob string matching mock includes files
46
54
  *
@@ -563,7 +571,7 @@ type FormidableFile = formidable.File | formidable.File[];
563
571
  type LogType = 'info' | 'warn' | 'error' | 'debug';
564
572
  type LogLevel = LogType | 'silent';
565
573
 
566
- declare function mockDevServerPlugin({ prefix, wsPrefix, include, exclude, reload, log, cors, formidableOptions, build, cookiesOptions, bodyParserOptions, priority, }?: MockServerPluginOptions): Plugin[];
574
+ declare function mockDevServerPlugin({ prefix, wsPrefix, cwd, include, exclude, reload, log, cors, formidableOptions, build, cookiesOptions, bodyParserOptions, priority, }?: MockServerPluginOptions): Plugin[];
567
575
 
568
576
  /**
569
577
  * mock config Type helper
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // src/plugin.ts
2
- import { toArray as toArray4 } from "@pengzhanbo/utils";
2
+ import process4 from "node:process";
3
+ import { toArray as toArray5 } from "@pengzhanbo/utils";
3
4
 
4
5
  // src/build.ts
5
6
  import fs3 from "node:fs";
@@ -48,8 +49,9 @@ function lookupFile(dir, formats, options) {
48
49
  }
49
50
  }
50
51
  const parentDir = path.dirname(dir);
51
- if (parentDir !== dir && (!(options == null ? void 0 : options.rootDir) || parentDir.startsWith(options == null ? void 0 : options.rootDir)))
52
+ if (parentDir !== dir && (!(options == null ? void 0 : options.rootDir) || parentDir.startsWith(options == null ? void 0 : options.rootDir))) {
52
53
  return lookupFile(parentDir, formats, options);
54
+ }
53
55
  }
54
56
  function ensureProxies(serverProxy = {}) {
55
57
  const httpProxies = [];
@@ -57,10 +59,11 @@ function ensureProxies(serverProxy = {}) {
57
59
  Object.keys(serverProxy).forEach((key) => {
58
60
  var _a, _b;
59
61
  const value = serverProxy[key];
60
- if (typeof value === "string" || !value.ws && !((_a = value.target) == null ? void 0 : _a.toString().startsWith("ws:")) && !((_b = value.target) == null ? void 0 : _b.toString().startsWith("wss:")))
62
+ if (typeof value === "string" || !value.ws && !((_a = value.target) == null ? void 0 : _a.toString().startsWith("ws:")) && !((_b = value.target) == null ? void 0 : _b.toString().startsWith("wss:"))) {
61
63
  httpProxies.push(key);
62
- else
64
+ } else {
63
65
  wsProxies.push(key);
66
+ }
64
67
  });
65
68
  return { httpProxies, wsProxies };
66
69
  }
@@ -180,7 +183,12 @@ async function transformWithEsbuild(entryPoint, options) {
180
183
  }
181
184
  var _dirname = getDirname(import.meta.url);
182
185
  var _require = createRequire(_dirname);
183
- async function loadFromCode(filepath, code, isESM, cwd) {
186
+ async function loadFromCode({
187
+ filepath,
188
+ code,
189
+ isESM,
190
+ cwd
191
+ }) {
184
192
  if (isESM) {
185
193
  const fileBase = `${filepath}.timestamp-${Date.now()}`;
186
194
  const fileNameTmp = `${fileBase}.mjs`;
@@ -233,11 +241,13 @@ function viteDefine(config) {
233
241
  if (typeof val === "string") {
234
242
  if (canJsonParse(val)) {
235
243
  userDefine[key] = val;
236
- isMetaEnv && (userDefineEnv[key.slice(16)] = val);
244
+ if (isMetaEnv)
245
+ userDefineEnv[key.slice(16)] = val;
237
246
  }
238
247
  } else {
239
248
  userDefine[key] = handleDefineValue(val);
240
- isMetaEnv && (userDefineEnv[key.slice(16)] = val);
249
+ if (isMetaEnv)
250
+ userDefineEnv[key.slice(16)] = val;
241
251
  }
242
252
  }
243
253
  const importMetaKeys = {};
@@ -294,11 +304,12 @@ function canJsonParse(value) {
294
304
 
295
305
  // src/build.ts
296
306
  var packageName = true ? "vite-plugin-mock-dev-server" : "vite-plugin-mock-dev-server";
297
- var packageVersion = true ? "1.5.0" : "latest";
307
+ var packageVersion = true ? "1.6.0" : "latest";
298
308
  async function generateMockServer(ctx, config, options) {
299
309
  const include = toArray(options.include);
300
310
  const exclude = toArray(options.exclude);
301
311
  const define = viteDefine(config);
312
+ const cwd = options.cwd || process2.cwd();
302
313
  const { httpProxies } = ensureProxies(config.server.proxy || {});
303
314
  httpProxies.push(...toArray(options.prefix));
304
315
  const wsProxies = toArray(options.wsPrefix);
@@ -310,8 +321,8 @@ async function generateMockServer(ctx, config, options) {
310
321
  } catch {
311
322
  }
312
323
  const outputDir = options.build.dist;
313
- const content = await generateMockEntryCode(process2.cwd(), include, exclude);
314
- const mockEntry = path3.join(config.root, `mock-data-${Date.now()}.js`);
324
+ const content = await generateMockEntryCode(cwd, include, exclude);
325
+ const mockEntry = path3.join(cwd, `mock-data-${Date.now()}.js`);
315
326
  await fsp2.writeFile(mockEntry, content, "utf-8");
316
327
  const { code, deps } = await transformWithEsbuild(mockEntry, {
317
328
  define,
@@ -477,7 +488,7 @@ export default transformMockData(mockList);`;
477
488
  }
478
489
 
479
490
  // src/mockMiddleware.ts
480
- import { isBoolean as isBoolean2, toArray as toArray3, uniq as uniq2 } from "@pengzhanbo/utils";
491
+ import { isBoolean as isBoolean2, toArray as toArray4, uniq as uniq2 } from "@pengzhanbo/utils";
481
492
  import cors from "cors";
482
493
  import { pathToRegexp as pathToRegexp4 } from "path-to-regexp";
483
494
  import c2 from "picocolors";
@@ -639,8 +650,7 @@ function twoPartMatch(rules) {
639
650
  const dym = tokens.filter((token) => typeof token !== "string");
640
651
  if (dym.length > 0)
641
652
  dynamics.push(rule);
642
- else
643
- statics.push(rule);
653
+ else statics.push(rule);
644
654
  }
645
655
  return [statics, dynamics];
646
656
  }
@@ -781,12 +791,14 @@ function baseMiddleware(mockLoader, {
781
791
  return async function(req, res, next) {
782
792
  const startTime = timestamp();
783
793
  const { query, pathname } = urlParse(req.url);
784
- if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url)))
794
+ if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url))) {
785
795
  return next();
796
+ }
786
797
  const mockData = mockLoader.mockData;
787
798
  const mockUrls = matchingWeight(Object.keys(mockData), pathname, priority);
788
- if (mockUrls.length === 0)
799
+ if (mockUrls.length === 0) {
789
800
  return next();
801
+ }
790
802
  collectRequest(req);
791
803
  const { query: refererQuery } = urlParse(req.headers.referer || "");
792
804
  const reqBody = await parseReqBody(req, formidableOptions, bodyParserOptions);
@@ -937,10 +949,12 @@ async function provideHeaders(req, res, mock, logger) {
937
949
  const { headers, type = "json" } = mock;
938
950
  const filepath = mock.__filepath__;
939
951
  const contentType2 = mime.contentType(type) || mime.contentType(mime.lookup(type) || "");
940
- contentType2 && res.setHeader("Content-Type", contentType2);
952
+ if (contentType2)
953
+ res.setHeader("Content-Type", contentType2);
941
954
  res.setHeader("Cache-Control", "no-cache,max-age=0");
942
955
  res.setHeader("X-Mock-Power-By", "vite-plugin-mock-dev-server");
943
- filepath && res.setHeader("X-File-Path", filepath);
956
+ if (filepath)
957
+ res.setHeader("X-File-Path", filepath);
944
958
  if (!headers)
945
959
  return;
946
960
  try {
@@ -997,8 +1011,9 @@ function sendData(res, raw, type) {
997
1011
  }
998
1012
  }
999
1013
  async function realDelay(startTime, delay) {
1000
- if (!delay || typeof delay === "number" && delay <= 0 || isArray3(delay) && delay.length !== 2)
1014
+ if (!delay || typeof delay === "number" && delay <= 0 || isArray3(delay) && delay.length !== 2) {
1001
1015
  return;
1016
+ }
1002
1017
  let realDelay2 = 0;
1003
1018
  if (isArray3(delay)) {
1004
1019
  const [min, max] = delay;
@@ -1071,24 +1086,24 @@ function createLogger(prefix, defaultLevel = "info") {
1071
1086
  // src/MockLoader.ts
1072
1087
  import EventEmitter from "node:events";
1073
1088
  import process3 from "node:process";
1074
- import { hasOwn, isArray as isArray5, promiseParallel, toArray as toArray2 } from "@pengzhanbo/utils";
1089
+ import { hasOwn, isArray as isArray4, promiseParallel, toArray as toArray3 } from "@pengzhanbo/utils";
1075
1090
  import chokidar from "chokidar";
1076
1091
  import fastGlob from "fast-glob";
1077
1092
  import { createFilter as createFilter2 } from "@rollup/pluginutils";
1078
1093
 
1079
1094
  // src/transform.ts
1080
1095
  import {
1081
- isArray as isArray4,
1082
1096
  isEmptyObject as isEmptyObject3,
1083
1097
  isFunction as isFunction2,
1084
1098
  isObject as isObject2,
1085
- sortBy as sortBy2
1099
+ sortBy as sortBy2,
1100
+ toArray as toArray2
1086
1101
  } from "@pengzhanbo/utils";
1087
1102
  function transformMockData(mockList) {
1088
1103
  const list = [];
1089
1104
  for (const [, handle] of mockList.entries()) {
1090
1105
  if (handle)
1091
- isArray4(handle) ? list.push(...handle) : list.push(handle);
1106
+ list.push(...toArray2(handle));
1092
1107
  }
1093
1108
  const mocks = {};
1094
1109
  list.filter((mock) => isObject2(mock) && mock.enabled !== false && mock.url).forEach((mock) => {
@@ -1148,7 +1163,7 @@ var MockLoader = class extends EventEmitter {
1148
1163
  try {
1149
1164
  const pkg = lookupFile(this.cwd, ["package.json"]);
1150
1165
  this.moduleType = !!pkg && JSON.parse(pkg).type === "module" ? "esm" : "cjs";
1151
- } catch (e) {
1166
+ } catch {
1152
1167
  }
1153
1168
  }
1154
1169
  moduleCache = /* @__PURE__ */ new Map();
@@ -1176,7 +1191,8 @@ var MockLoader = class extends EventEmitter {
1176
1191
  if (!includeFilter(filepath))
1177
1192
  return;
1178
1193
  await this.loadMock(filepath);
1179
- timer && clearImmediate(timer);
1194
+ if (timer)
1195
+ clearImmediate(timer);
1180
1196
  timer = setImmediate(() => {
1181
1197
  this.updateMockList();
1182
1198
  this.emit("mock:update-end", filepath);
@@ -1198,7 +1214,8 @@ var MockLoader = class extends EventEmitter {
1198
1214
  ignoreInitial: true,
1199
1215
  cwd: this.cwd
1200
1216
  });
1201
- otherGlob.length > 0 && otherGlob.forEach((glob) => watcher.add(glob));
1217
+ if (otherGlob.length > 0)
1218
+ otherGlob.forEach((glob) => watcher.add(glob));
1202
1219
  watcher.on("add", async (filepath) => {
1203
1220
  filepath = normalizePath(filepath);
1204
1221
  this.emit("mock:update", filepath);
@@ -1228,7 +1245,7 @@ var MockLoader = class extends EventEmitter {
1228
1245
  this.depsWatcher.on("change", (filepath) => {
1229
1246
  filepath = normalizePath(filepath);
1230
1247
  const mockFiles = this.moduleDeps.get(filepath);
1231
- mockFiles && mockFiles.forEach((file) => {
1248
+ mockFiles == null ? void 0 : mockFiles.forEach((file) => {
1232
1249
  this.emit("mock:update", file);
1233
1250
  });
1234
1251
  });
@@ -1241,7 +1258,8 @@ var MockLoader = class extends EventEmitter {
1241
1258
  for (const [dep] of this.moduleDeps.entries())
1242
1259
  deps.push(dep);
1243
1260
  const exactDeps = deps.filter((dep) => !oldDeps.includes(dep));
1244
- exactDeps.length > 0 && this.depsWatcher.add(exactDeps);
1261
+ if (exactDeps.length > 0)
1262
+ this.depsWatcher.add(exactDeps);
1245
1263
  });
1246
1264
  }
1247
1265
  close() {
@@ -1280,22 +1298,22 @@ var MockLoader = class extends EventEmitter {
1280
1298
  { isESM, define, alias }
1281
1299
  );
1282
1300
  try {
1283
- const raw = await loadFromCode(
1301
+ const raw = await loadFromCode({
1284
1302
  filepath,
1285
1303
  code,
1286
1304
  isESM,
1287
- this.cwd
1288
- ) || {};
1305
+ cwd: this.cwd
1306
+ }) || {};
1289
1307
  let mockConfig;
1290
1308
  if (hasOwn(raw, "default")) {
1291
1309
  mockConfig = raw.default;
1292
1310
  } else {
1293
1311
  mockConfig = [];
1294
1312
  Object.keys(raw).forEach(
1295
- (key) => mockConfig.push(...toArray2(raw[key]))
1313
+ (key) => mockConfig.push(...toArray3(raw[key]))
1296
1314
  );
1297
1315
  }
1298
- if (isArray5(mockConfig)) {
1316
+ if (isArray4(mockConfig)) {
1299
1317
  mockConfig.forEach((mock) => mock.__filepath__ = filepath);
1300
1318
  } else {
1301
1319
  ;
@@ -1327,17 +1345,20 @@ function mockWebSocket({
1327
1345
  const wssContextMap = /* @__PURE__ */ new WeakMap();
1328
1346
  const getWssMap = (mockUrl) => {
1329
1347
  let wssMap = poolMap.get(mockUrl);
1330
- !wssMap && poolMap.set(mockUrl, wssMap = /* @__PURE__ */ new Map());
1348
+ if (!wssMap)
1349
+ poolMap.set(mockUrl, wssMap = /* @__PURE__ */ new Map());
1331
1350
  return wssMap;
1332
1351
  };
1333
1352
  const getWss = (wssMap, pathname) => {
1334
1353
  let wss = wssMap.get(pathname);
1335
- !wss && wssMap.set(pathname, wss = new WebSocketServer({ noServer: true }));
1354
+ if (!wss)
1355
+ wssMap.set(pathname, wss = new WebSocketServer({ noServer: true }));
1336
1356
  return wss;
1337
1357
  };
1338
1358
  const addHmr = (filepath, mockUrl) => {
1339
1359
  let urlList = hmrMap.get(filepath);
1340
- !urlList && hmrMap.set(filepath, urlList = /* @__PURE__ */ new Set());
1360
+ if (!urlList)
1361
+ hmrMap.set(filepath, urlList = /* @__PURE__ */ new Set());
1341
1362
  urlList.add(mockUrl);
1342
1363
  };
1343
1364
  const setupWss = (wssMap, wss, mock, context, pathname, filepath) => {
@@ -1402,8 +1423,9 @@ ${e}
1402
1423
  });
1403
1424
  httpServer == null ? void 0 : httpServer.on("upgrade", (req, socket, head) => {
1404
1425
  const { pathname, query } = urlParse(req.url);
1405
- if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url)))
1426
+ if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url))) {
1406
1427
  return;
1428
+ }
1407
1429
  const mockData = loader.mockData;
1408
1430
  const mockUrl = Object.keys(mockData).find((key) => {
1409
1431
  return pathToRegexp3(key).test(pathname);
@@ -1473,8 +1495,9 @@ function mockServerMiddleware(config, options, httpServer, ws) {
1473
1495
  isBoolean2(options.log) ? options.log ? "info" : "error" : options.log
1474
1496
  );
1475
1497
  const loader = new MockLoader({
1476
- include: toArray3(options.include),
1477
- exclude: toArray3(options.exclude),
1498
+ cwd: options.cwd,
1499
+ include: toArray4(options.include),
1500
+ exclude: toArray4(options.exclude),
1478
1501
  define: viteDefine(config),
1479
1502
  alias: config.resolve.alias
1480
1503
  });
@@ -1485,14 +1508,14 @@ function mockServerMiddleware(config, options, httpServer, ws) {
1485
1508
  });
1486
1509
  httpServer == null ? void 0 : httpServer.on("close", () => loader.close());
1487
1510
  const { httpProxies } = ensureProxies(config.server.proxy || {});
1488
- const prefix = toArray3(options.prefix);
1511
+ const prefix = toArray4(options.prefix);
1489
1512
  const proxies = uniq2([...prefix, ...httpProxies]);
1490
- if (!proxies.length && !toArray3(options.wsPrefix).length)
1513
+ if (!proxies.length && !toArray4(options.wsPrefix).length)
1491
1514
  logger.warn(`No proxy was configured, mock server will not work. See ${c2.cyan("https://vite-plugin-mock-dev-server.netlify.app/guide/usage")}`);
1492
1515
  mockWebSocket({
1493
1516
  loader,
1494
1517
  httpServer,
1495
- proxies: toArray3(options.wsPrefix),
1518
+ proxies: toArray4(options.wsPrefix),
1496
1519
  cookiesOptions: options.cookiesOptions,
1497
1520
  logger
1498
1521
  });
@@ -1540,8 +1563,9 @@ function corsMiddleware(mockLoader, proxies, config, options) {
1540
1563
  const { pathname } = urlParse(req.url);
1541
1564
  if (!pathname || proxies.length === 0 || !proxies.some(
1542
1565
  (context) => doesProxyContextMatchUrl(context, req.url)
1543
- ))
1566
+ )) {
1544
1567
  return next();
1568
+ }
1545
1569
  const mockData = mockLoader.mockData;
1546
1570
  const mockUrl = Object.keys(mockData).find(
1547
1571
  (key) => pathToRegexp4(key).test(pathname)
@@ -1556,6 +1580,7 @@ function corsMiddleware(mockLoader, proxies, config, options) {
1556
1580
  function mockDevServerPlugin({
1557
1581
  prefix = [],
1558
1582
  wsPrefix = [],
1583
+ cwd = process4.cwd(),
1559
1584
  include = ["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],
1560
1585
  exclude = ["**/node_modules/**", "**/.vscode/**", "**/.git/**"],
1561
1586
  reload = false,
@@ -1570,6 +1595,7 @@ function mockDevServerPlugin({
1570
1595
  const pluginOptions = {
1571
1596
  prefix,
1572
1597
  wsPrefix,
1598
+ cwd,
1573
1599
  include,
1574
1600
  exclude,
1575
1601
  reload,
@@ -1623,7 +1649,7 @@ function serverPlugin(pluginOptions) {
1623
1649
  apply: "serve",
1624
1650
  config(config) {
1625
1651
  var _a;
1626
- const wsPrefix = toArray4(pluginOptions.wsPrefix);
1652
+ const wsPrefix = toArray5(pluginOptions.wsPrefix);
1627
1653
  if (wsPrefix.length && ((_a = config.server) == null ? void 0 : _a.proxy)) {
1628
1654
  const proxy = {};
1629
1655
  Object.keys(config.server.proxy).forEach((key) => {
@@ -1659,13 +1685,13 @@ function serverPlugin(pluginOptions) {
1659
1685
  }
1660
1686
 
1661
1687
  // src/defineMock.ts
1662
- import { isArray as isArray6 } from "@pengzhanbo/utils";
1688
+ import { isArray as isArray5 } from "@pengzhanbo/utils";
1663
1689
  function defineMock(config) {
1664
1690
  return config;
1665
1691
  }
1666
1692
  function createDefineMock(transformer) {
1667
1693
  const define = (config) => {
1668
- if (isArray6(config))
1694
+ if (isArray5(config))
1669
1695
  config = config.map((item) => transformer(item) || item);
1670
1696
  else
1671
1697
  config = transformer(config) || config;
package/package.json CHANGED
@@ -1,8 +1,7 @@
1
1
  {
2
2
  "name": "vite-plugin-mock-dev-server",
3
3
  "type": "module",
4
- "version": "1.5.0",
5
- "packageManager": "pnpm@8.15.5",
4
+ "version": "1.6.0",
6
5
  "author": "pengzhanbo <q942450674@outlook.com> (https://github.com/pengzhanbo)",
7
6
  "license": "MIT",
8
7
  "homepage": "https://vite-plugin-mock-dev-server.netlify.app",
@@ -46,23 +45,23 @@
46
45
  "@pengzhanbo/utils": "^1.1.2",
47
46
  "@rollup/pluginutils": "^5.1.0",
48
47
  "chokidar": "^3.6.0",
49
- "co-body": "^6.1.0",
48
+ "co-body": "^6.2.0",
50
49
  "cookies": "^0.9.1",
51
50
  "cors": "^2.8.5",
52
- "debug": "^4.3.4",
53
- "esbuild": "^0.20.2",
51
+ "debug": "^4.3.5",
52
+ "esbuild": "^0.23.0",
54
53
  "fast-glob": "^3.3.2",
55
54
  "formidable": "2.1.2",
56
55
  "http-status": "^1.7.4",
57
- "is-core-module": "^2.13.1",
56
+ "is-core-module": "^2.15.0",
58
57
  "json5": "^2.2.3",
59
58
  "mime-types": "^2.1.35",
60
- "path-to-regexp": "^6.2.1",
61
- "picocolors": "^1.0.0",
62
- "ws": "^8.16.0"
59
+ "path-to-regexp": "6.2.2",
60
+ "picocolors": "^1.0.1",
61
+ "ws": "^8.18.0"
63
62
  },
64
63
  "devDependencies": {
65
- "@pengzhanbo/eslint-config": "^1.7.0",
64
+ "@pengzhanbo/eslint-config": "^1.12.0",
66
65
  "@types/co-body": "^6.1.3",
67
66
  "@types/cookies": "^0.9.0",
68
67
  "@types/cors": "^2.8.17",
@@ -70,17 +69,17 @@
70
69
  "@types/formidable": "2.0.6",
71
70
  "@types/is-core-module": "^2.2.2",
72
71
  "@types/mime-types": "^2.1.4",
73
- "@types/node": "^20.11.30",
74
- "@types/ws": "^8.5.10",
75
- "bumpp": "^9.4.0",
76
- "conventional-changelog-cli": "^4.1.0",
77
- "eslint": "^8.57.0",
72
+ "@types/node": "^20.14.12",
73
+ "@types/ws": "^8.5.11",
74
+ "bumpp": "^9.4.1",
75
+ "conventional-changelog-cli": "^5.0.0",
76
+ "eslint": "^9.7.0",
78
77
  "mockjs": "^1.1.0",
79
- "tsup": "^8.0.2",
80
- "typescript": "^5.4.3",
81
- "vite": "^5.2.6",
82
- "vitepress": "^1.0.1",
83
- "vitest": "^1.4.0"
78
+ "tsup": "^8.2.3",
79
+ "typescript": "^5.5.4",
80
+ "vite": "^5.3.4",
81
+ "vitepress": "^1.3.1",
82
+ "vitest": "^2.0.4"
84
83
  },
85
84
  "scripts": {
86
85
  "build": "tsup && node ./deprecate.mjs",