vite-plugin-mock-dev-server 1.4.5 → 1.4.6

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.
Files changed (3) hide show
  1. package/dist/index.cjs +159 -144
  2. package/dist/index.js +121 -106
  3. package/package.json +7 -7
package/dist/index.cjs CHANGED
@@ -56,11 +56,11 @@ var import_node_fs3 = __toESM(require("fs"), 1);
56
56
  var import_promises = __toESM(require("fs/promises"), 1);
57
57
  var import_node_path3 = __toESM(require("path"), 1);
58
58
  var import_node_process2 = __toESM(require("process"), 1);
59
- var import_utils3 = require("@pengzhanbo/utils");
59
+ var import_utils2 = require("@pengzhanbo/utils");
60
60
  var import_fast_glob = __toESM(require("fast-glob"), 1);
61
61
  var import_is_core_module = __toESM(require("is-core-module"), 1);
62
62
  var import_pluginutils = require("@rollup/pluginutils");
63
- var import_picocolors3 = __toESM(require("picocolors"), 1);
63
+ var import_picocolors = __toESM(require("picocolors"), 1);
64
64
 
65
65
  // src/compiler.ts
66
66
  var import_node_fs2 = __toESM(require("fs"), 1);
@@ -267,117 +267,91 @@ async function loadFromCode(filepath, code, isESM, cwd) {
267
267
 
268
268
  // src/define.ts
269
269
  var import_node_process = __toESM(require("process"), 1);
270
- var import_picocolors2 = __toESM(require("picocolors"), 1);
271
-
272
- // src/logger.ts
273
- var import_utils2 = require("@pengzhanbo/utils");
274
- var import_picocolors = __toESM(require("picocolors"), 1);
275
- var logLevels = {
276
- silent: 0,
277
- error: 1,
278
- warn: 2,
279
- info: 3,
280
- debug: 4
281
- };
282
- function createLogger(prefix, defaultLevel = "info") {
283
- prefix = `[${prefix}]`;
284
- function output(type, msg, level) {
285
- level = (0, import_utils2.isBoolean)(level) ? level ? defaultLevel : "error" : level;
286
- const thresh = logLevels[level];
287
- if (thresh >= logLevels[type]) {
288
- const method = type === "info" || type === "debug" ? "log" : type;
289
- const tag = type === "debug" ? import_picocolors.default.magenta(import_picocolors.default.bold(prefix)) : type === "info" ? import_picocolors.default.cyan(import_picocolors.default.bold(prefix)) : type === "warn" ? import_picocolors.default.yellow(import_picocolors.default.bold(prefix)) : import_picocolors.default.red(import_picocolors.default.bold(prefix));
290
- const format = `${import_picocolors.default.dim(
291
- (/* @__PURE__ */ new Date()).toLocaleTimeString()
292
- )} ${tag} ${msg}`;
293
- console[method](format);
294
- }
295
- }
296
- const logger = {
297
- debug(msg, level = defaultLevel) {
298
- output("debug", msg, level);
299
- },
300
- info(msg, level = defaultLevel) {
301
- output("info", msg, level);
302
- },
303
- warn(msg, level = defaultLevel) {
304
- output("warn", msg, level);
305
- },
306
- error(msg, level = defaultLevel) {
307
- output("error", msg, level);
308
- }
309
- };
310
- return logger;
311
- }
312
-
313
- // src/define.ts
314
- var metaEnvRe = /import\.meta\.env\.(.+)/;
315
270
  function viteDefine(config) {
316
- const logger = createLogger("vite:mock-dev-server", "warn");
317
271
  const processNodeEnv = {};
318
272
  const nodeEnv = import_node_process.default.env.NODE_ENV || config.mode;
319
273
  Object.assign(processNodeEnv, {
320
274
  "process.env.NODE_ENV": JSON.stringify(nodeEnv),
321
275
  "global.process.env.NODE_ENV": JSON.stringify(nodeEnv),
322
- "globalThis.process.env.NODE_ENV": JSON.stringify(nodeEnv),
323
- "__vite_process_env_NODE_ENV": JSON.stringify(nodeEnv)
276
+ "globalThis.process.env.NODE_ENV": JSON.stringify(nodeEnv)
324
277
  });
325
278
  const userDefine = {};
326
279
  const userDefineEnv = {};
327
- const defineErrorKeys = [];
328
280
  for (const key in config.define) {
329
281
  const val = config.define[key];
282
+ const isMetaEnv = key.startsWith("import.meta.env.");
330
283
  if (typeof val === "string") {
331
- try {
332
- JSON.parse(val);
284
+ if (canJsonParse(val)) {
333
285
  userDefine[key] = val;
334
- } catch {
335
- defineErrorKeys.push(key);
286
+ isMetaEnv && (userDefineEnv[key.slice(16)] = val);
336
287
  }
337
288
  } else {
338
- userDefine[key] = JSON.stringify(val);
289
+ userDefine[key] = handleDefineValue(val);
290
+ isMetaEnv && (userDefineEnv[key.slice(16)] = val);
339
291
  }
340
- const match2 = key.match(metaEnvRe);
341
- if (match2 && userDefine[key])
342
- userDefineEnv[match2[1]] = `__vite__define__${userDefine[key]}`;
343
- }
344
- if (defineErrorKeys.length) {
345
- logger.warn(
346
- `The following keys: ${import_picocolors2.default.yellow(
347
- import_picocolors2.default.underline(defineErrorKeys.join(", "))
348
- )} declared in 'define' cannot be parsed as regular code snippets.`
349
- );
350
292
  }
351
293
  const importMetaKeys = {};
294
+ const importMetaEnvKeys = {};
352
295
  const importMetaFallbackKeys = {};
353
- importMetaKeys["import.meta.hot"] = "undefined";
354
- for (const key in config.env)
355
- importMetaKeys[`import.meta.env.${key}`] = JSON.stringify(config.env[key]);
356
- Object.assign(importMetaFallbackKeys, {
357
- "import.meta.env": JSON.stringify({
358
- ...config.env,
359
- ...userDefineEnv
360
- }).replace(
361
- /"__vite__define__(.+?)"([,}])/g,
362
- (_, val, suffix) => `${val.replace(/(^\\")|(\\"$)/g, '"')}${suffix}`
363
- )
364
- });
365
- return {
296
+ importMetaKeys["import.meta.hot"] = `undefined`;
297
+ for (const key in config.env) {
298
+ const val = JSON.stringify(config.env[key]);
299
+ importMetaKeys[`import.meta.env.${key}`] = val;
300
+ importMetaEnvKeys[key] = val;
301
+ }
302
+ importMetaFallbackKeys["import.meta.env"] = `undefined`;
303
+ const define = {
304
+ ...processNodeEnv,
366
305
  ...importMetaKeys,
367
306
  ...userDefine,
368
- ...importMetaFallbackKeys,
369
- ...processNodeEnv
307
+ ...importMetaFallbackKeys
370
308
  };
309
+ if ("import.meta.env" in define) {
310
+ define["import.meta.env"] = serializeDefine({
311
+ ...importMetaEnvKeys,
312
+ ...userDefineEnv
313
+ });
314
+ }
315
+ return define;
316
+ }
317
+ function serializeDefine(define) {
318
+ let res = `{`;
319
+ const keys = Object.keys(define);
320
+ for (let i = 0; i < keys.length; i++) {
321
+ const key = keys[i];
322
+ const val = define[key];
323
+ res += `${JSON.stringify(key)}: ${handleDefineValue(val)}`;
324
+ if (i !== keys.length - 1)
325
+ res += `, `;
326
+ }
327
+ return `${res}}`;
328
+ }
329
+ function handleDefineValue(value) {
330
+ if (typeof value === "undefined")
331
+ return "undefined";
332
+ if (typeof value === "string")
333
+ return value;
334
+ return JSON.stringify(value);
335
+ }
336
+ function canJsonParse(value) {
337
+ try {
338
+ JSON.parse(value);
339
+ return true;
340
+ } catch {
341
+ return false;
342
+ }
371
343
  }
372
344
 
373
345
  // src/build.ts
346
+ var packageName = true ? "vite-plugin-mock-dev-server" : "vite-plugin-mock-dev-server";
347
+ var packageVersion = true ? "1.4.6" : "latest";
374
348
  async function generateMockServer(ctx, config, options) {
375
- const include = (0, import_utils3.toArray)(options.include);
376
- const exclude = (0, import_utils3.toArray)(options.exclude);
349
+ const include = (0, import_utils2.toArray)(options.include);
350
+ const exclude = (0, import_utils2.toArray)(options.exclude);
377
351
  const define = viteDefine(config);
378
352
  const { httpProxies } = ensureProxies(config.server.proxy || {});
379
- httpProxies.push(...(0, import_utils3.toArray)(options.prefix));
380
- const wsProxies = (0, import_utils3.toArray)(options.wsPrefix);
353
+ httpProxies.push(...(0, import_utils2.toArray)(options.prefix));
354
+ const wsProxies = (0, import_utils2.toArray)(options.wsPrefix);
381
355
  let pkg = {};
382
356
  try {
383
357
  const pkgStr = lookupFile(config.root, ["package.json"]);
@@ -421,14 +395,14 @@ async function generateMockServer(ctx, config, options) {
421
395
  if (import_node_fs3.default.existsSync(filename))
422
396
  await import_promises.default.rm(filename);
423
397
  }
424
- config.logger.info(`${import_picocolors3.default.green("\u2713")} generate mock server in ${import_picocolors3.default.cyan(outputDir)}`);
398
+ config.logger.info(`${import_picocolors.default.green("\u2713")} generate mock server in ${import_picocolors.default.cyan(outputDir)}`);
425
399
  for (const { filename, source } of outputList) {
426
400
  import_node_fs3.default.mkdirSync(import_node_path3.default.dirname(filename), { recursive: true });
427
401
  await import_promises.default.writeFile(filename, source, "utf-8");
428
402
  const sourceSize = (source.length / 1024).toFixed(2);
429
403
  const name = import_node_path3.default.relative(outputDir, filename);
430
404
  const space = name.length < 30 ? " ".repeat(30 - name.length) : "";
431
- config.logger.info(` ${import_picocolors3.default.green(name)}${space}${import_picocolors3.default.bold(import_picocolors3.default.dim(`${sourceSize} kB`))}`);
405
+ config.logger.info(` ${import_picocolors.default.green(name)}${space}${import_picocolors.default.bold(import_picocolors.default.dim(`${sourceSize} kB`))}`);
432
406
  }
433
407
  } else {
434
408
  for (const { filename, source } of outputList) {
@@ -445,7 +419,7 @@ async function generateMockServer(ctx, config, options) {
445
419
  }
446
420
  function getMockDependencies(deps, alias) {
447
421
  const list = /* @__PURE__ */ new Set();
448
- const excludeDeps = ["vite-plugin-mock-dev-server", "connect", "cors"];
422
+ const excludeDeps = [packageName, "connect", "cors"];
449
423
  const isAlias = (p) => alias.find(({ find }) => aliasMatches(find, p));
450
424
  Object.keys(deps).forEach((mPath) => {
451
425
  const imports = deps[mPath].imports.filter((_) => _.external && !_.path.startsWith("<define:") && !isAlias(_.path)).map((_) => _.path);
@@ -467,7 +441,7 @@ function generatePackageJson(pkg, mockDeps) {
467
441
  },
468
442
  dependencies: {
469
443
  "connect": "^3.7.0",
470
- "vite-plugin-mock-dev-server": `^${"1.4.5"}`,
444
+ "vite-plugin-mock-dev-server": `^${packageVersion}`,
471
445
  "cors": "^2.8.5"
472
446
  },
473
447
  pnpm: { peerDependencyRules: { ignoreMissing: ["vite"] } }
@@ -553,19 +527,19 @@ export default transformMockData(mockList);`;
553
527
  var import_utils14 = require("@pengzhanbo/utils");
554
528
  var import_cors = __toESM(require("cors"), 1);
555
529
  var import_path_to_regexp5 = require("path-to-regexp");
556
- var import_picocolors6 = __toESM(require("picocolors"), 1);
530
+ var import_picocolors5 = __toESM(require("picocolors"), 1);
557
531
 
558
532
  // src/baseMiddleware.ts
559
533
  var import_node_buffer2 = require("buffer");
560
- var import_utils7 = require("@pengzhanbo/utils");
534
+ var import_utils6 = require("@pengzhanbo/utils");
561
535
  var import_cookies = __toESM(require("cookies"), 1);
562
536
  var import_http_status = __toESM(require("http-status"), 1);
563
537
  var mime = __toESM(require("mime-types"), 1);
564
538
  var import_path_to_regexp3 = require("path-to-regexp");
565
- var import_picocolors4 = __toESM(require("picocolors"), 1);
539
+ var import_picocolors2 = __toESM(require("picocolors"), 1);
566
540
 
567
541
  // src/matchingWeight.ts
568
- var import_utils5 = require("@pengzhanbo/utils");
542
+ var import_utils4 = require("@pengzhanbo/utils");
569
543
  var import_path_to_regexp2 = require("path-to-regexp");
570
544
  var tokensCache = {};
571
545
  function getTokens(rule) {
@@ -574,7 +548,7 @@ function getTokens(rule) {
574
548
  const tks = (0, import_path_to_regexp2.parse)(rule);
575
549
  const tokens = [];
576
550
  for (const tk of tks) {
577
- if (!(0, import_utils5.isString)(tk)) {
551
+ if (!(0, import_utils4.isString)(tk)) {
578
552
  tokens.push(tk);
579
553
  } else {
580
554
  const hasPrefix = tk[0] === "/";
@@ -598,7 +572,7 @@ function sortFn(rule) {
598
572
  let w = 0;
599
573
  for (let i = 0; i < tokens.length; i++) {
600
574
  const token = tokens[i];
601
- if (!(0, import_utils5.isString)(token))
575
+ if (!(0, import_utils4.isString)(token))
602
576
  w += 10 ** (i + 1);
603
577
  w += 10 ** (i + 1);
604
578
  }
@@ -615,12 +589,12 @@ function preSort(rules) {
615
589
  preMatch[len].push(rule);
616
590
  }
617
591
  for (const match2 of preMatch.filter((v) => v && v.length > 0))
618
- matched = [...matched, ...(0, import_utils5.sortBy)(match2, sortFn).reverse()];
592
+ matched = [...matched, ...(0, import_utils4.sortBy)(match2, sortFn).reverse()];
619
593
  return matched;
620
594
  }
621
595
  function defaultPriority(rules) {
622
596
  const highest = getHighest(rules);
623
- return (0, import_utils5.sortBy)(rules, (rule) => {
597
+ return (0, import_utils4.sortBy)(rules, (rule) => {
624
598
  const tokens = getTokens(rule);
625
599
  const dym = tokens.filter((token) => typeof token !== "string");
626
600
  if (dym.length === 0)
@@ -629,7 +603,7 @@ function defaultPriority(rules) {
629
603
  let exp = 0;
630
604
  for (let i = 0; i < tokens.length; i++) {
631
605
  const token = tokens[i];
632
- const isDynamic = !(0, import_utils5.isString)(token);
606
+ const isDynamic = !(0, import_utils4.isString)(token);
633
607
  const {
634
608
  pattern = "",
635
609
  modifier,
@@ -638,7 +612,7 @@ function defaultPriority(rules) {
638
612
  } = isDynamic ? token : {};
639
613
  const isGlob = pattern && pattern.includes(".*");
640
614
  const isSlash = prefix === "/";
641
- const isNamed = (0, import_utils5.isString)(name);
615
+ const isNamed = (0, import_utils4.isString)(name);
642
616
  exp += isDynamic && isSlash ? 1 : 0;
643
617
  if (i === tokens.length - 1 && isGlob) {
644
618
  weight += 5 * 10 ** (tokens.length === 1 ? highest + 1 : highest);
@@ -668,14 +642,14 @@ function matchingWeight(rules, url, priority) {
668
642
  preSort(rules.filter((rule) => (0, import_path_to_regexp2.pathToRegexp)(rule).test(url)))
669
643
  );
670
644
  const { global = [], special = {} } = priority;
671
- if (global.length === 0 && (0, import_utils5.isEmptyObject)(special) || matched.length === 0)
645
+ if (global.length === 0 && (0, import_utils4.isEmptyObject)(special) || matched.length === 0)
672
646
  return matched;
673
647
  const [statics, dynamics] = twoPartMatch(matched);
674
648
  const globalMatch = global.filter((rule) => dynamics.includes(rule));
675
649
  if (globalMatch.length > 0) {
676
- matched = (0, import_utils5.uniq)([...statics, ...globalMatch, ...dynamics]);
650
+ matched = (0, import_utils4.uniq)([...statics, ...globalMatch, ...dynamics]);
677
651
  }
678
- if ((0, import_utils5.isEmptyObject)(special))
652
+ if ((0, import_utils4.isEmptyObject)(special))
679
653
  return matched;
680
654
  const specialRule = Object.keys(special).filter(
681
655
  (rule) => matched.includes(rule)
@@ -683,10 +657,10 @@ function matchingWeight(rules, url, priority) {
683
657
  if (!specialRule)
684
658
  return matched;
685
659
  const options = special[specialRule];
686
- const { rules: lowerRules, when } = (0, import_utils5.isArray)(options) ? { rules: options, when: [] } : options;
660
+ const { rules: lowerRules, when } = (0, import_utils4.isArray)(options) ? { rules: options, when: [] } : options;
687
661
  if (lowerRules.includes(matched[0])) {
688
662
  if (when.length === 0 || when.some((path4) => (0, import_path_to_regexp2.pathToRegexp)(path4).test(url))) {
689
- matched = (0, import_utils5.uniq)([specialRule, ...matched]);
663
+ matched = (0, import_utils4.uniq)([specialRule, ...matched]);
690
664
  }
691
665
  }
692
666
  return matched;
@@ -784,7 +758,7 @@ function recoverRequest(config) {
784
758
  }
785
759
 
786
760
  // src/validator.ts
787
- var import_utils6 = require("@pengzhanbo/utils");
761
+ var import_utils5 = require("@pengzhanbo/utils");
788
762
  function validate(request, validator) {
789
763
  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);
790
764
  }
@@ -798,7 +772,7 @@ function isObjectSubset(source, target) {
798
772
  return true;
799
773
  }
800
774
  function isIncluded(source, target) {
801
- if ((0, import_utils6.isArray)(source) && (0, import_utils6.isArray)(target)) {
775
+ if ((0, import_utils5.isArray)(source) && (0, import_utils5.isArray)(target)) {
802
776
  const seen = /* @__PURE__ */ new Set();
803
777
  return target.every(
804
778
  (ti) => source.some((si, i) => {
@@ -811,7 +785,7 @@ function isIncluded(source, target) {
811
785
  })
812
786
  );
813
787
  }
814
- if ((0, import_utils6.isObject)(source) && (0, import_utils6.isObject)(target))
788
+ if ((0, import_utils5.isObject)(source) && (0, import_utils5.isObject)(target))
815
789
  return isObjectSubset(source, target);
816
790
  return Object.is(source, target);
817
791
  }
@@ -825,7 +799,7 @@ function baseMiddleware(mockLoader, {
825
799
  priority = {}
826
800
  }) {
827
801
  return async function(req, res, next) {
828
- const startTime = (0, import_utils7.timestamp)();
802
+ const startTime = (0, import_utils6.timestamp)();
829
803
  const { query, pathname } = urlParse(req.url);
830
804
  if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url)))
831
805
  return next();
@@ -860,10 +834,10 @@ function baseMiddleware(mockLoader, {
860
834
  }
861
835
  if (!mock) {
862
836
  const matched = mockUrls.map(
863
- (m) => m === _mockUrl ? import_picocolors4.default.underline(import_picocolors4.default.bold(m)) : import_picocolors4.default.dim(m)
837
+ (m) => m === _mockUrl ? import_picocolors2.default.underline(import_picocolors2.default.bold(m)) : import_picocolors2.default.dim(m)
864
838
  ).join(", ");
865
839
  logger.warn(
866
- `${import_picocolors4.default.green(
840
+ `${import_picocolors2.default.green(
867
841
  pathname
868
842
  )} matches ${matched} , but mock data is not found.`
869
843
  );
@@ -892,25 +866,25 @@ function baseMiddleware(mockLoader, {
892
866
  await provideCookies(request, response, mock, logger);
893
867
  logger.info(requestLog(request, filepath), logLevel);
894
868
  logger.debug(
895
- `${import_picocolors4.default.magenta("DEBUG")} ${import_picocolors4.default.underline(
869
+ `${import_picocolors2.default.magenta("DEBUG")} ${import_picocolors2.default.underline(
896
870
  pathname
897
871
  )} matches: [ ${mockUrls.map(
898
- (m) => m === _mockUrl ? import_picocolors4.default.underline(import_picocolors4.default.bold(m)) : import_picocolors4.default.dim(m)
872
+ (m) => m === _mockUrl ? import_picocolors2.default.underline(import_picocolors2.default.bold(m)) : import_picocolors2.default.dim(m)
899
873
  ).join(", ")} ]
900
874
  `
901
875
  );
902
876
  if (body) {
903
877
  try {
904
- const content = (0, import_utils7.isFunction)(body) ? await body(request) : body;
878
+ const content = (0, import_utils6.isFunction)(body) ? await body(request) : body;
905
879
  await realDelay(startTime, delay);
906
880
  sendData(response, content, type);
907
881
  } catch (e) {
908
882
  logger.error(
909
- `${import_picocolors4.default.red(
883
+ `${import_picocolors2.default.red(
910
884
  `mock error at ${pathname}`
911
885
  )}
912
886
  ${e}
913
- at body (${import_picocolors4.default.underline(filepath)})`,
887
+ at body (${import_picocolors2.default.underline(filepath)})`,
914
888
  logLevel
915
889
  );
916
890
  responseStatus(response, 500);
@@ -924,11 +898,11 @@ ${e}
924
898
  await responseFn(request, response, next);
925
899
  } catch (e) {
926
900
  logger.error(
927
- `${import_picocolors4.default.red(
901
+ `${import_picocolors2.default.red(
928
902
  `mock error at ${pathname}`
929
903
  )}
930
904
  ${e}
931
- at response (${import_picocolors4.default.underline(filepath)})`,
905
+ at response (${import_picocolors2.default.underline(filepath)})`,
932
906
  logLevel
933
907
  );
934
908
  responseStatus(response, 500);
@@ -947,13 +921,13 @@ function fineMock(mockList, logger, {
947
921
  return mockList.find((mock) => {
948
922
  if (!pathname || !mock || !mock.url || mock.ws === true)
949
923
  return false;
950
- const methods = mock.method ? (0, import_utils7.isArray)(mock.method) ? mock.method : [mock.method] : ["GET", "POST"];
924
+ const methods = mock.method ? (0, import_utils6.isArray)(mock.method) ? mock.method : [mock.method] : ["GET", "POST"];
951
925
  if (!methods.includes(method))
952
926
  return false;
953
927
  const hasMock = (0, import_path_to_regexp3.pathToRegexp)(mock.url).test(pathname);
954
928
  if (hasMock && mock.validator) {
955
929
  const params = parseParams(mock.url, pathname);
956
- if ((0, import_utils7.isFunction)(mock.validator)) {
930
+ if ((0, import_utils6.isFunction)(mock.validator)) {
957
931
  return mock.validator({ params, ...request });
958
932
  } else {
959
933
  try {
@@ -961,11 +935,11 @@ function fineMock(mockList, logger, {
961
935
  } catch (e) {
962
936
  const file = mock.__filepath__;
963
937
  logger.error(
964
- `${import_picocolors4.default.red(
938
+ `${import_picocolors2.default.red(
965
939
  `mock error at ${pathname}`
966
940
  )}
967
941
  ${e}
968
- at validator (${import_picocolors4.default.underline(file)})`,
942
+ at validator (${import_picocolors2.default.underline(file)})`,
969
943
  mock.log
970
944
  );
971
945
  return false;
@@ -990,17 +964,17 @@ async function provideHeaders(req, res, mock, logger) {
990
964
  if (!headers)
991
965
  return;
992
966
  try {
993
- const raw = (0, import_utils7.isFunction)(headers) ? await headers(req) : headers;
967
+ const raw = (0, import_utils6.isFunction)(headers) ? await headers(req) : headers;
994
968
  Object.keys(raw).forEach((key) => {
995
969
  res.setHeader(key, raw[key]);
996
970
  });
997
971
  } catch (e) {
998
972
  logger.error(
999
- `${import_picocolors4.default.red(
973
+ `${import_picocolors2.default.red(
1000
974
  `mock error at ${req.url.split("?")[0]}`
1001
975
  )}
1002
976
  ${e}
1003
- at headers (${import_picocolors4.default.underline(filepath)})`,
977
+ at headers (${import_picocolors2.default.underline(filepath)})`,
1004
978
  mock.log
1005
979
  );
1006
980
  }
@@ -1011,10 +985,10 @@ async function provideCookies(req, res, mock, logger) {
1011
985
  if (!cookies)
1012
986
  return;
1013
987
  try {
1014
- const raw = (0, import_utils7.isFunction)(cookies) ? await cookies(req) : cookies;
988
+ const raw = (0, import_utils6.isFunction)(cookies) ? await cookies(req) : cookies;
1015
989
  Object.keys(raw).forEach((key) => {
1016
990
  const cookie = raw[key];
1017
- if ((0, import_utils7.isArray)(cookie)) {
991
+ if ((0, import_utils6.isArray)(cookie)) {
1018
992
  const [value, options] = cookie;
1019
993
  res.setCookie(key, value, options);
1020
994
  } else {
@@ -1023,11 +997,11 @@ async function provideCookies(req, res, mock, logger) {
1023
997
  });
1024
998
  } catch (e) {
1025
999
  logger.error(
1026
- `${import_picocolors4.default.red(
1000
+ `${import_picocolors2.default.red(
1027
1001
  `mock error at ${req.url.split("?")[0]}`
1028
1002
  )}
1029
1003
  ${e}
1030
- at cookies (${import_picocolors4.default.underline(filepath)})`,
1004
+ at cookies (${import_picocolors2.default.underline(filepath)})`,
1031
1005
  mock.log
1032
1006
  );
1033
1007
  }
@@ -1043,17 +1017,17 @@ function sendData(res, raw, type) {
1043
1017
  }
1044
1018
  }
1045
1019
  async function realDelay(startTime, delay) {
1046
- if (!delay || typeof delay === "number" && delay <= 0 || (0, import_utils7.isArray)(delay) && delay.length !== 2)
1020
+ if (!delay || typeof delay === "number" && delay <= 0 || (0, import_utils6.isArray)(delay) && delay.length !== 2)
1047
1021
  return;
1048
1022
  let realDelay2 = 0;
1049
- if ((0, import_utils7.isArray)(delay)) {
1023
+ if ((0, import_utils6.isArray)(delay)) {
1050
1024
  const [min, max] = delay;
1051
- realDelay2 = (0, import_utils7.random)(min, max);
1025
+ realDelay2 = (0, import_utils6.random)(min, max);
1052
1026
  } else {
1053
- realDelay2 = delay - ((0, import_utils7.timestamp)() - startTime);
1027
+ realDelay2 = delay - ((0, import_utils6.timestamp)() - startTime);
1054
1028
  }
1055
1029
  if (realDelay2 > 0)
1056
- await (0, import_utils7.sleep)(realDelay2);
1030
+ await (0, import_utils6.sleep)(realDelay2);
1057
1031
  }
1058
1032
  function getHTTPStatusText(status) {
1059
1033
  return import_http_status.default[status] || "Unknown";
@@ -1061,18 +1035,59 @@ function getHTTPStatusText(status) {
1061
1035
  function requestLog(request, filepath) {
1062
1036
  const { url, method, query, params, body } = request;
1063
1037
  let { pathname } = new URL(url, "http://example.com");
1064
- pathname = import_picocolors4.default.green(decodeURIComponent(pathname));
1038
+ pathname = import_picocolors2.default.green(decodeURIComponent(pathname));
1065
1039
  const format = (prefix, data) => {
1066
- return !data || (0, import_utils7.isEmptyObject)(data) ? "" : ` ${import_picocolors4.default.gray(`${prefix}:`)}${JSON.stringify(data)}`;
1040
+ return !data || (0, import_utils6.isEmptyObject)(data) ? "" : ` ${import_picocolors2.default.gray(`${prefix}:`)}${JSON.stringify(data)}`;
1067
1041
  };
1068
- const ms = import_picocolors4.default.magenta(import_picocolors4.default.bold(method));
1042
+ const ms = import_picocolors2.default.magenta(import_picocolors2.default.bold(method));
1069
1043
  const qs = format("query", query);
1070
1044
  const ps = format("params", params);
1071
1045
  const bs = format("body", body);
1072
- const file = ` ${import_picocolors4.default.dim(import_picocolors4.default.underline(`(${filepath})`))}`;
1046
+ const file = ` ${import_picocolors2.default.dim(import_picocolors2.default.underline(`(${filepath})`))}`;
1073
1047
  return `${ms} ${pathname}${qs}${ps}${bs}${file}`;
1074
1048
  }
1075
1049
 
1050
+ // src/logger.ts
1051
+ var import_utils8 = require("@pengzhanbo/utils");
1052
+ var import_picocolors3 = __toESM(require("picocolors"), 1);
1053
+ var logLevels = {
1054
+ silent: 0,
1055
+ error: 1,
1056
+ warn: 2,
1057
+ info: 3,
1058
+ debug: 4
1059
+ };
1060
+ function createLogger(prefix, defaultLevel = "info") {
1061
+ prefix = `[${prefix}]`;
1062
+ function output(type, msg, level) {
1063
+ level = (0, import_utils8.isBoolean)(level) ? level ? defaultLevel : "error" : level;
1064
+ const thresh = logLevels[level];
1065
+ if (thresh >= logLevels[type]) {
1066
+ const method = type === "info" || type === "debug" ? "log" : type;
1067
+ const tag = type === "debug" ? import_picocolors3.default.magenta(import_picocolors3.default.bold(prefix)) : type === "info" ? import_picocolors3.default.cyan(import_picocolors3.default.bold(prefix)) : type === "warn" ? import_picocolors3.default.yellow(import_picocolors3.default.bold(prefix)) : import_picocolors3.default.red(import_picocolors3.default.bold(prefix));
1068
+ const format = `${import_picocolors3.default.dim(
1069
+ (/* @__PURE__ */ new Date()).toLocaleTimeString()
1070
+ )} ${tag} ${msg}`;
1071
+ console[method](format);
1072
+ }
1073
+ }
1074
+ const logger = {
1075
+ debug(msg, level = defaultLevel) {
1076
+ output("debug", msg, level);
1077
+ },
1078
+ info(msg, level = defaultLevel) {
1079
+ output("info", msg, level);
1080
+ },
1081
+ warn(msg, level = defaultLevel) {
1082
+ output("warn", msg, level);
1083
+ },
1084
+ error(msg, level = defaultLevel) {
1085
+ output("error", msg, level);
1086
+ }
1087
+ };
1088
+ return logger;
1089
+ }
1090
+
1076
1091
  // src/MockLoader.ts
1077
1092
  var import_node_events = __toESM(require("events"), 1);
1078
1093
  var import_node_process3 = __toESM(require("process"), 1);
@@ -1312,7 +1327,7 @@ var MockLoader = class extends import_node_events.default {
1312
1327
  // src/ws.ts
1313
1328
  var import_cookies2 = __toESM(require("cookies"), 1);
1314
1329
  var import_path_to_regexp4 = require("path-to-regexp");
1315
- var import_picocolors5 = __toESM(require("picocolors"), 1);
1330
+ var import_picocolors4 = __toESM(require("picocolors"), 1);
1316
1331
  var import_ws = require("ws");
1317
1332
  function mockWebSocket({
1318
1333
  loader,
@@ -1347,7 +1362,7 @@ function mockWebSocket({
1347
1362
  wss.on("close", () => wssMap.delete(pathname));
1348
1363
  wss.on("error", (e) => {
1349
1364
  logger.error(
1350
- `${import_picocolors5.default.red(
1365
+ `${import_picocolors4.default.red(
1351
1366
  `WebSocket mock error at ${wss.path}`
1352
1367
  )}
1353
1368
  ${e}
@@ -1357,7 +1372,7 @@ ${e}
1357
1372
  });
1358
1373
  } catch (e) {
1359
1374
  logger.error(
1360
- `${import_picocolors5.default.red(
1375
+ `${import_picocolors4.default.red(
1361
1376
  `WebSocket mock error at ${wss.path}`
1362
1377
  )}
1363
1378
  ${e}
@@ -1438,9 +1453,9 @@ ${e}
1438
1453
  request.getCookie = cookies.get.bind(cookies);
1439
1454
  wss.handleUpgrade(request, socket, head, (ws) => {
1440
1455
  logger.info(
1441
- `${import_picocolors5.default.magenta(import_picocolors5.default.bold("WebSocket"))} ${import_picocolors5.default.green(
1456
+ `${import_picocolors4.default.magenta(import_picocolors4.default.bold("WebSocket"))} ${import_picocolors4.default.green(
1442
1457
  req.url
1443
- )} connected ${import_picocolors5.default.dim(`(${filepath})`)}`,
1458
+ )} connected ${import_picocolors4.default.dim(`(${filepath})`)}`,
1444
1459
  mock.log
1445
1460
  );
1446
1461
  wssContext.connectionList.push({ req: request, ws });
@@ -1487,8 +1502,8 @@ function mockServerMiddleware(config, options, httpServer, ws) {
1487
1502
  const { httpProxies } = ensureProxies(config.server.proxy || {});
1488
1503
  const prefix = (0, import_utils14.toArray)(options.prefix);
1489
1504
  const proxies = (0, import_utils14.uniq)([...prefix, ...httpProxies]);
1490
- if (!proxies.length)
1491
- logger.warn(`No proxy was configured, mock server will not work. See ${import_picocolors6.default.cyan("https://vite-plugin-mock-dev-server.netlify.app/guide/usage")}`);
1505
+ if (!proxies.length || !(0, import_utils14.toArray)(options.wsPrefix).length)
1506
+ logger.warn(`No proxy was configured, mock server will not work. See ${import_picocolors5.default.cyan("https://vite-plugin-mock-dev-server.netlify.app/guide/usage")}`);
1492
1507
  mockWebSocket({
1493
1508
  loader,
1494
1509
  httpServer,
package/dist/index.js CHANGED
@@ -217,110 +217,84 @@ async function loadFromCode(filepath, code, isESM, cwd) {
217
217
 
218
218
  // src/define.ts
219
219
  import process from "node:process";
220
- import colors2 from "picocolors";
221
-
222
- // src/logger.ts
223
- import { isBoolean } from "@pengzhanbo/utils";
224
- import colors from "picocolors";
225
- var logLevels = {
226
- silent: 0,
227
- error: 1,
228
- warn: 2,
229
- info: 3,
230
- debug: 4
231
- };
232
- function createLogger(prefix, defaultLevel = "info") {
233
- prefix = `[${prefix}]`;
234
- function output(type, msg, level) {
235
- level = isBoolean(level) ? level ? defaultLevel : "error" : level;
236
- const thresh = logLevels[level];
237
- if (thresh >= logLevels[type]) {
238
- const method = type === "info" || type === "debug" ? "log" : type;
239
- const tag = type === "debug" ? colors.magenta(colors.bold(prefix)) : type === "info" ? colors.cyan(colors.bold(prefix)) : type === "warn" ? colors.yellow(colors.bold(prefix)) : colors.red(colors.bold(prefix));
240
- const format = `${colors.dim(
241
- (/* @__PURE__ */ new Date()).toLocaleTimeString()
242
- )} ${tag} ${msg}`;
243
- console[method](format);
244
- }
245
- }
246
- const logger = {
247
- debug(msg, level = defaultLevel) {
248
- output("debug", msg, level);
249
- },
250
- info(msg, level = defaultLevel) {
251
- output("info", msg, level);
252
- },
253
- warn(msg, level = defaultLevel) {
254
- output("warn", msg, level);
255
- },
256
- error(msg, level = defaultLevel) {
257
- output("error", msg, level);
258
- }
259
- };
260
- return logger;
261
- }
262
-
263
- // src/define.ts
264
- var metaEnvRe = /import\.meta\.env\.(.+)/;
265
220
  function viteDefine(config) {
266
- const logger = createLogger("vite:mock-dev-server", "warn");
267
221
  const processNodeEnv = {};
268
222
  const nodeEnv = process.env.NODE_ENV || config.mode;
269
223
  Object.assign(processNodeEnv, {
270
224
  "process.env.NODE_ENV": JSON.stringify(nodeEnv),
271
225
  "global.process.env.NODE_ENV": JSON.stringify(nodeEnv),
272
- "globalThis.process.env.NODE_ENV": JSON.stringify(nodeEnv),
273
- "__vite_process_env_NODE_ENV": JSON.stringify(nodeEnv)
226
+ "globalThis.process.env.NODE_ENV": JSON.stringify(nodeEnv)
274
227
  });
275
228
  const userDefine = {};
276
229
  const userDefineEnv = {};
277
- const defineErrorKeys = [];
278
230
  for (const key in config.define) {
279
231
  const val = config.define[key];
232
+ const isMetaEnv = key.startsWith("import.meta.env.");
280
233
  if (typeof val === "string") {
281
- try {
282
- JSON.parse(val);
234
+ if (canJsonParse(val)) {
283
235
  userDefine[key] = val;
284
- } catch {
285
- defineErrorKeys.push(key);
236
+ isMetaEnv && (userDefineEnv[key.slice(16)] = val);
286
237
  }
287
238
  } else {
288
- userDefine[key] = JSON.stringify(val);
239
+ userDefine[key] = handleDefineValue(val);
240
+ isMetaEnv && (userDefineEnv[key.slice(16)] = val);
289
241
  }
290
- const match2 = key.match(metaEnvRe);
291
- if (match2 && userDefine[key])
292
- userDefineEnv[match2[1]] = `__vite__define__${userDefine[key]}`;
293
- }
294
- if (defineErrorKeys.length) {
295
- logger.warn(
296
- `The following keys: ${colors2.yellow(
297
- colors2.underline(defineErrorKeys.join(", "))
298
- )} declared in 'define' cannot be parsed as regular code snippets.`
299
- );
300
242
  }
301
243
  const importMetaKeys = {};
244
+ const importMetaEnvKeys = {};
302
245
  const importMetaFallbackKeys = {};
303
- importMetaKeys["import.meta.hot"] = "undefined";
304
- for (const key in config.env)
305
- importMetaKeys[`import.meta.env.${key}`] = JSON.stringify(config.env[key]);
306
- Object.assign(importMetaFallbackKeys, {
307
- "import.meta.env": JSON.stringify({
308
- ...config.env,
309
- ...userDefineEnv
310
- }).replace(
311
- /"__vite__define__(.+?)"([,}])/g,
312
- (_, val, suffix) => `${val.replace(/(^\\")|(\\"$)/g, '"')}${suffix}`
313
- )
314
- });
315
- return {
246
+ importMetaKeys["import.meta.hot"] = `undefined`;
247
+ for (const key in config.env) {
248
+ const val = JSON.stringify(config.env[key]);
249
+ importMetaKeys[`import.meta.env.${key}`] = val;
250
+ importMetaEnvKeys[key] = val;
251
+ }
252
+ importMetaFallbackKeys["import.meta.env"] = `undefined`;
253
+ const define = {
254
+ ...processNodeEnv,
316
255
  ...importMetaKeys,
317
256
  ...userDefine,
318
- ...importMetaFallbackKeys,
319
- ...processNodeEnv
257
+ ...importMetaFallbackKeys
320
258
  };
259
+ if ("import.meta.env" in define) {
260
+ define["import.meta.env"] = serializeDefine({
261
+ ...importMetaEnvKeys,
262
+ ...userDefineEnv
263
+ });
264
+ }
265
+ return define;
266
+ }
267
+ function serializeDefine(define) {
268
+ let res = `{`;
269
+ const keys = Object.keys(define);
270
+ for (let i = 0; i < keys.length; i++) {
271
+ const key = keys[i];
272
+ const val = define[key];
273
+ res += `${JSON.stringify(key)}: ${handleDefineValue(val)}`;
274
+ if (i !== keys.length - 1)
275
+ res += `, `;
276
+ }
277
+ return `${res}}`;
278
+ }
279
+ function handleDefineValue(value) {
280
+ if (typeof value === "undefined")
281
+ return "undefined";
282
+ if (typeof value === "string")
283
+ return value;
284
+ return JSON.stringify(value);
285
+ }
286
+ function canJsonParse(value) {
287
+ try {
288
+ JSON.parse(value);
289
+ return true;
290
+ } catch {
291
+ return false;
292
+ }
321
293
  }
322
294
 
323
295
  // src/build.ts
296
+ var packageName = true ? "vite-plugin-mock-dev-server" : "vite-plugin-mock-dev-server";
297
+ var packageVersion = true ? "1.4.6" : "latest";
324
298
  async function generateMockServer(ctx, config, options) {
325
299
  const include = toArray(options.include);
326
300
  const exclude = toArray(options.exclude);
@@ -395,7 +369,7 @@ async function generateMockServer(ctx, config, options) {
395
369
  }
396
370
  function getMockDependencies(deps, alias) {
397
371
  const list = /* @__PURE__ */ new Set();
398
- const excludeDeps = ["vite-plugin-mock-dev-server", "connect", "cors"];
372
+ const excludeDeps = [packageName, "connect", "cors"];
399
373
  const isAlias = (p) => alias.find(({ find }) => aliasMatches(find, p));
400
374
  Object.keys(deps).forEach((mPath) => {
401
375
  const imports = deps[mPath].imports.filter((_) => _.external && !_.path.startsWith("<define:") && !isAlias(_.path)).map((_) => _.path);
@@ -417,7 +391,7 @@ function generatePackageJson(pkg, mockDeps) {
417
391
  },
418
392
  dependencies: {
419
393
  "connect": "^3.7.0",
420
- "vite-plugin-mock-dev-server": `^${"1.4.5"}`,
394
+ "vite-plugin-mock-dev-server": `^${packageVersion}`,
421
395
  "cors": "^2.8.5"
422
396
  },
423
397
  pnpm: { peerDependencyRules: { ignoreMissing: ["vite"] } }
@@ -519,7 +493,7 @@ import Cookies from "cookies";
519
493
  import HTTP_STATUS from "http-status";
520
494
  import * as mime from "mime-types";
521
495
  import { pathToRegexp as pathToRegexp2 } from "path-to-regexp";
522
- import colors3 from "picocolors";
496
+ import colors from "picocolors";
523
497
 
524
498
  // src/matchingWeight.ts
525
499
  import {
@@ -823,10 +797,10 @@ function baseMiddleware(mockLoader, {
823
797
  }
824
798
  if (!mock) {
825
799
  const matched = mockUrls.map(
826
- (m) => m === _mockUrl ? colors3.underline(colors3.bold(m)) : colors3.dim(m)
800
+ (m) => m === _mockUrl ? colors.underline(colors.bold(m)) : colors.dim(m)
827
801
  ).join(", ");
828
802
  logger.warn(
829
- `${colors3.green(
803
+ `${colors.green(
830
804
  pathname
831
805
  )} matches ${matched} , but mock data is not found.`
832
806
  );
@@ -855,10 +829,10 @@ function baseMiddleware(mockLoader, {
855
829
  await provideCookies(request, response, mock, logger);
856
830
  logger.info(requestLog(request, filepath), logLevel);
857
831
  logger.debug(
858
- `${colors3.magenta("DEBUG")} ${colors3.underline(
832
+ `${colors.magenta("DEBUG")} ${colors.underline(
859
833
  pathname
860
834
  )} matches: [ ${mockUrls.map(
861
- (m) => m === _mockUrl ? colors3.underline(colors3.bold(m)) : colors3.dim(m)
835
+ (m) => m === _mockUrl ? colors.underline(colors.bold(m)) : colors.dim(m)
862
836
  ).join(", ")} ]
863
837
  `
864
838
  );
@@ -869,11 +843,11 @@ function baseMiddleware(mockLoader, {
869
843
  sendData(response, content, type);
870
844
  } catch (e) {
871
845
  logger.error(
872
- `${colors3.red(
846
+ `${colors.red(
873
847
  `mock error at ${pathname}`
874
848
  )}
875
849
  ${e}
876
- at body (${colors3.underline(filepath)})`,
850
+ at body (${colors.underline(filepath)})`,
877
851
  logLevel
878
852
  );
879
853
  responseStatus(response, 500);
@@ -887,11 +861,11 @@ ${e}
887
861
  await responseFn(request, response, next);
888
862
  } catch (e) {
889
863
  logger.error(
890
- `${colors3.red(
864
+ `${colors.red(
891
865
  `mock error at ${pathname}`
892
866
  )}
893
867
  ${e}
894
- at response (${colors3.underline(filepath)})`,
868
+ at response (${colors.underline(filepath)})`,
895
869
  logLevel
896
870
  );
897
871
  responseStatus(response, 500);
@@ -924,11 +898,11 @@ function fineMock(mockList, logger, {
924
898
  } catch (e) {
925
899
  const file = mock.__filepath__;
926
900
  logger.error(
927
- `${colors3.red(
901
+ `${colors.red(
928
902
  `mock error at ${pathname}`
929
903
  )}
930
904
  ${e}
931
- at validator (${colors3.underline(file)})`,
905
+ at validator (${colors.underline(file)})`,
932
906
  mock.log
933
907
  );
934
908
  return false;
@@ -959,11 +933,11 @@ async function provideHeaders(req, res, mock, logger) {
959
933
  });
960
934
  } catch (e) {
961
935
  logger.error(
962
- `${colors3.red(
936
+ `${colors.red(
963
937
  `mock error at ${req.url.split("?")[0]}`
964
938
  )}
965
939
  ${e}
966
- at headers (${colors3.underline(filepath)})`,
940
+ at headers (${colors.underline(filepath)})`,
967
941
  mock.log
968
942
  );
969
943
  }
@@ -986,11 +960,11 @@ async function provideCookies(req, res, mock, logger) {
986
960
  });
987
961
  } catch (e) {
988
962
  logger.error(
989
- `${colors3.red(
963
+ `${colors.red(
990
964
  `mock error at ${req.url.split("?")[0]}`
991
965
  )}
992
966
  ${e}
993
- at cookies (${colors3.underline(filepath)})`,
967
+ at cookies (${colors.underline(filepath)})`,
994
968
  mock.log
995
969
  );
996
970
  }
@@ -1024,18 +998,59 @@ function getHTTPStatusText(status) {
1024
998
  function requestLog(request, filepath) {
1025
999
  const { url, method, query, params, body } = request;
1026
1000
  let { pathname } = new URL(url, "http://example.com");
1027
- pathname = colors3.green(decodeURIComponent(pathname));
1001
+ pathname = colors.green(decodeURIComponent(pathname));
1028
1002
  const format = (prefix, data) => {
1029
- return !data || isEmptyObject2(data) ? "" : ` ${colors3.gray(`${prefix}:`)}${JSON.stringify(data)}`;
1003
+ return !data || isEmptyObject2(data) ? "" : ` ${colors.gray(`${prefix}:`)}${JSON.stringify(data)}`;
1030
1004
  };
1031
- const ms = colors3.magenta(colors3.bold(method));
1005
+ const ms = colors.magenta(colors.bold(method));
1032
1006
  const qs = format("query", query);
1033
1007
  const ps = format("params", params);
1034
1008
  const bs = format("body", body);
1035
- const file = ` ${colors3.dim(colors3.underline(`(${filepath})`))}`;
1009
+ const file = ` ${colors.dim(colors.underline(`(${filepath})`))}`;
1036
1010
  return `${ms} ${pathname}${qs}${ps}${bs}${file}`;
1037
1011
  }
1038
1012
 
1013
+ // src/logger.ts
1014
+ import { isBoolean } from "@pengzhanbo/utils";
1015
+ import colors2 from "picocolors";
1016
+ var logLevels = {
1017
+ silent: 0,
1018
+ error: 1,
1019
+ warn: 2,
1020
+ info: 3,
1021
+ debug: 4
1022
+ };
1023
+ function createLogger(prefix, defaultLevel = "info") {
1024
+ prefix = `[${prefix}]`;
1025
+ function output(type, msg, level) {
1026
+ level = isBoolean(level) ? level ? defaultLevel : "error" : level;
1027
+ const thresh = logLevels[level];
1028
+ if (thresh >= logLevels[type]) {
1029
+ const method = type === "info" || type === "debug" ? "log" : type;
1030
+ const tag = type === "debug" ? colors2.magenta(colors2.bold(prefix)) : type === "info" ? colors2.cyan(colors2.bold(prefix)) : type === "warn" ? colors2.yellow(colors2.bold(prefix)) : colors2.red(colors2.bold(prefix));
1031
+ const format = `${colors2.dim(
1032
+ (/* @__PURE__ */ new Date()).toLocaleTimeString()
1033
+ )} ${tag} ${msg}`;
1034
+ console[method](format);
1035
+ }
1036
+ }
1037
+ const logger = {
1038
+ debug(msg, level = defaultLevel) {
1039
+ output("debug", msg, level);
1040
+ },
1041
+ info(msg, level = defaultLevel) {
1042
+ output("info", msg, level);
1043
+ },
1044
+ warn(msg, level = defaultLevel) {
1045
+ output("warn", msg, level);
1046
+ },
1047
+ error(msg, level = defaultLevel) {
1048
+ output("error", msg, level);
1049
+ }
1050
+ };
1051
+ return logger;
1052
+ }
1053
+
1039
1054
  // src/MockLoader.ts
1040
1055
  import EventEmitter from "node:events";
1041
1056
  import process3 from "node:process";
@@ -1281,7 +1296,7 @@ var MockLoader = class extends EventEmitter {
1281
1296
  // src/ws.ts
1282
1297
  import Cookies2 from "cookies";
1283
1298
  import { pathToRegexp as pathToRegexp3 } from "path-to-regexp";
1284
- import colors4 from "picocolors";
1299
+ import colors3 from "picocolors";
1285
1300
  import { WebSocketServer } from "ws";
1286
1301
  function mockWebSocket({
1287
1302
  loader,
@@ -1316,7 +1331,7 @@ function mockWebSocket({
1316
1331
  wss.on("close", () => wssMap.delete(pathname));
1317
1332
  wss.on("error", (e) => {
1318
1333
  logger.error(
1319
- `${colors4.red(
1334
+ `${colors3.red(
1320
1335
  `WebSocket mock error at ${wss.path}`
1321
1336
  )}
1322
1337
  ${e}
@@ -1326,7 +1341,7 @@ ${e}
1326
1341
  });
1327
1342
  } catch (e) {
1328
1343
  logger.error(
1329
- `${colors4.red(
1344
+ `${colors3.red(
1330
1345
  `WebSocket mock error at ${wss.path}`
1331
1346
  )}
1332
1347
  ${e}
@@ -1407,9 +1422,9 @@ ${e}
1407
1422
  request.getCookie = cookies.get.bind(cookies);
1408
1423
  wss.handleUpgrade(request, socket, head, (ws) => {
1409
1424
  logger.info(
1410
- `${colors4.magenta(colors4.bold("WebSocket"))} ${colors4.green(
1425
+ `${colors3.magenta(colors3.bold("WebSocket"))} ${colors3.green(
1411
1426
  req.url
1412
- )} connected ${colors4.dim(`(${filepath})`)}`,
1427
+ )} connected ${colors3.dim(`(${filepath})`)}`,
1413
1428
  mock.log
1414
1429
  );
1415
1430
  wssContext.connectionList.push({ req: request, ws });
@@ -1456,7 +1471,7 @@ function mockServerMiddleware(config, options, httpServer, ws) {
1456
1471
  const { httpProxies } = ensureProxies(config.server.proxy || {});
1457
1472
  const prefix = toArray3(options.prefix);
1458
1473
  const proxies = uniq2([...prefix, ...httpProxies]);
1459
- if (!proxies.length)
1474
+ if (!proxies.length || !toArray3(options.wsPrefix).length)
1460
1475
  logger.warn(`No proxy was configured, mock server will not work. See ${c2.cyan("https://vite-plugin-mock-dev-server.netlify.app/guide/usage")}`);
1461
1476
  mockWebSocket({
1462
1477
  loader,
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "vite-plugin-mock-dev-server",
3
3
  "type": "module",
4
- "version": "1.4.5",
5
- "packageManager": "pnpm@8.14.0",
4
+ "version": "1.4.6",
5
+ "packageManager": "pnpm@8.14.1",
6
6
  "author": "pengzhanbo <q942450674@outlook.com> (https://github.com/pengzhanbo)",
7
7
  "license": "MIT",
8
8
  "homepage": "https://vite-plugin-mock-dev-server.netlify.app",
@@ -62,7 +62,7 @@
62
62
  "ws": "^8.16.0"
63
63
  },
64
64
  "devDependencies": {
65
- "@pengzhanbo/eslint-config": "^1.5.1",
65
+ "@pengzhanbo/eslint-config": "^1.5.3",
66
66
  "@types/co-body": "^6.1.3",
67
67
  "@types/cookies": "^0.7.10",
68
68
  "@types/cors": "^2.8.17",
@@ -70,17 +70,17 @@
70
70
  "@types/formidable": "2.0.6",
71
71
  "@types/is-core-module": "^2.2.2",
72
72
  "@types/mime-types": "^2.1.4",
73
- "@types/node": "^20.10.8",
73
+ "@types/node": "^20.11.5",
74
74
  "@types/ws": "^8.5.10",
75
- "bumpp": "^9.2.1",
75
+ "bumpp": "^9.3.0",
76
76
  "conventional-changelog-cli": "^4.1.0",
77
77
  "eslint": "^8.56.0",
78
78
  "mockjs": "^1.1.0",
79
79
  "tsup": "^8.0.1",
80
80
  "typescript": "^5.3.3",
81
81
  "vite": "^5.0.11",
82
- "vitepress": "^1.0.0-rc.36",
83
- "vitest": "^1.1.3"
82
+ "vitepress": "^1.0.0-rc.39",
83
+ "vitest": "^1.2.1"
84
84
  },
85
85
  "scripts": {
86
86
  "build": "tsup && node ./deprecate.mjs",