vite-plugin-mock-dev-server 1.8.4 → 1.8.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.
package/dist/index.js CHANGED
@@ -1,293 +1,252 @@
1
- import {
2
- createDefineMock,
3
- createSSEStream,
4
- defineMock,
5
- defineMockData
6
- } from "./chunk-4RQVTS77.js";
7
- import {
8
- baseMiddleware,
9
- createLogger,
10
- debug,
11
- doesProxyContextMatchUrl,
12
- ensureProxies,
13
- logLevels,
14
- lookupFile,
15
- mockWebSocket,
16
- normalizePath,
17
- recoverRequest,
18
- sortByValidator,
19
- transformMockData,
20
- transformRawData,
21
- urlParse
22
- } from "./chunk-YZXX2W2L.js";
23
-
24
- // src/plugin.ts
25
- import { toArray as toArray4 } from "@pengzhanbo/utils";
26
-
27
- // src/core/build.ts
28
- import fs2 from "node:fs";
29
- import fsp2 from "node:fs/promises";
30
- import path2 from "node:path";
31
- import process2 from "node:process";
32
- import { toArray } from "@pengzhanbo/utils";
1
+ import { createDefineMock, createSSEStream, defineMock, defineMockData } from "./helper-L9yYYkP2.js";
2
+ import { baseMiddleware, createLogger, debug, doesProxyContextMatchUrl, ensureProxies, logLevels, lookupFile, mockWebSocket, normalizePath, recoverRequest, sortByValidator, transformMockData, transformRawData, urlParse } from "./server-BKiEqtZe.js";
3
+ import { isArray, isBoolean, promiseParallel, toArray, uniq } from "@pengzhanbo/utils";
4
+ import fs, { promises } from "node:fs";
5
+ import fsp from "node:fs/promises";
6
+ import path from "node:path";
7
+ import process from "node:process";
33
8
  import { createFilter } from "@rollup/pluginutils";
34
9
  import fg from "fast-glob";
35
10
  import isCore from "is-core-module";
36
- import c from "picocolors";
37
-
38
- // src/core/compiler.ts
39
- import fs, { promises as fsp } from "node:fs";
40
- import path from "node:path";
41
- import process from "node:process";
11
+ import colors from "picocolors";
42
12
  import { pathToFileURL } from "node:url";
43
13
  import { build } from "esbuild";
44
14
  import JSON5 from "json5";
45
- var externalizeDeps = {
46
- name: "externalize-deps",
47
- setup(build2) {
48
- build2.onResolve({ filter: /.*/ }, ({ path: id }) => {
49
- if (id[0] !== "." && !path.isAbsolute(id))
50
- return { external: true };
51
- });
52
- }
15
+ import { pathToRegexp } from "path-to-regexp";
16
+ import cors from "cors";
17
+ import EventEmitter from "node:events";
18
+ import chokidar from "chokidar";
19
+
20
+ //#region src/core/compiler.ts
21
+ const externalizeDeps = {
22
+ name: "externalize-deps",
23
+ setup(build$1) {
24
+ build$1.onResolve({ filter: /.*/ }, ({ path: id }) => {
25
+ if (id[0] !== "." && !path.isAbsolute(id)) return { external: true };
26
+ });
27
+ }
53
28
  };
54
- var json5Loader = {
55
- name: "json5-loader",
56
- setup(build2) {
57
- build2.onLoad({ filter: /\.json5$/ }, async ({ path: path3 }) => {
58
- const content = await fsp.readFile(path3, "utf-8");
59
- return {
60
- contents: `export default ${JSON.stringify(JSON5.parse(content))}`,
61
- loader: "js"
62
- };
63
- });
64
- }
29
+ const json5Loader = {
30
+ name: "json5-loader",
31
+ setup(build$1) {
32
+ build$1.onLoad({ filter: /\.json5$/ }, async ({ path: path$1 }) => {
33
+ const content = await promises.readFile(path$1, "utf-8");
34
+ return {
35
+ contents: `export default ${JSON.stringify(JSON5.parse(content))}`,
36
+ loader: "js"
37
+ };
38
+ });
39
+ }
65
40
  };
66
- var jsonLoader = {
67
- name: "json-loader",
68
- setup(build2) {
69
- build2.onLoad({ filter: /\.json$/ }, async ({ path: path3 }) => {
70
- const content = await fsp.readFile(path3, "utf-8");
71
- return {
72
- contents: `export default ${content}`,
73
- loader: "js"
74
- };
75
- });
76
- }
41
+ const jsonLoader = {
42
+ name: "json-loader",
43
+ setup(build$1) {
44
+ build$1.onLoad({ filter: /\.json$/ }, async ({ path: path$1 }) => {
45
+ const content = await promises.readFile(path$1, "utf-8");
46
+ return {
47
+ contents: `export default ${content}`,
48
+ loader: "js"
49
+ };
50
+ });
51
+ }
77
52
  };
78
- var renamePlugin = {
79
- name: "rename-plugin",
80
- setup(build2) {
81
- build2.onResolve({ filter: /.*/ }, ({ path: id }) => {
82
- if (id === "vite-plugin-mock-dev-server") {
83
- return {
84
- path: "vite-plugin-mock-dev-server/helper",
85
- external: true
86
- };
87
- }
88
- return null;
89
- });
90
- }
53
+ const renamePlugin = {
54
+ name: "rename-plugin",
55
+ setup(build$1) {
56
+ build$1.onResolve({ filter: /.*/ }, ({ path: id }) => {
57
+ if (id === "vite-plugin-mock-dev-server") return {
58
+ path: "vite-plugin-mock-dev-server/helper",
59
+ external: true
60
+ };
61
+ return null;
62
+ });
63
+ }
91
64
  };
92
65
  function aliasPlugin(alias) {
93
- return {
94
- name: "alias-plugin",
95
- setup(build2) {
96
- build2.onResolve({ filter: /.*/ }, async ({ path: id }) => {
97
- const matchedEntry = alias.find(({ find: find2 }) => aliasMatches(find2, id));
98
- if (!matchedEntry)
99
- return null;
100
- const { find, replacement } = matchedEntry;
101
- const result = await build2.resolve(id.replace(find, replacement), {
102
- kind: "import-statement",
103
- resolveDir: replacement,
104
- namespace: "file"
105
- });
106
- return {
107
- path: result.path,
108
- external: false
109
- };
110
- });
111
- }
112
- };
66
+ return {
67
+ name: "alias-plugin",
68
+ setup(build$1) {
69
+ build$1.onResolve({ filter: /.*/ }, async ({ path: id }) => {
70
+ const matchedEntry = alias.find(({ find: find$1 }) => aliasMatches(find$1, id));
71
+ if (!matchedEntry) return null;
72
+ const { find, replacement } = matchedEntry;
73
+ const result = await build$1.resolve(id.replace(find, replacement), {
74
+ kind: "import-statement",
75
+ resolveDir: replacement,
76
+ namespace: "file"
77
+ });
78
+ return {
79
+ path: result.path,
80
+ external: false
81
+ };
82
+ });
83
+ }
84
+ };
113
85
  }
114
86
  function aliasMatches(pattern, importee) {
115
- if (pattern instanceof RegExp)
116
- return pattern.test(importee);
117
- if (importee.length < pattern.length)
118
- return false;
119
- if (importee === pattern)
120
- return true;
121
- return importee.startsWith(`${pattern}/`);
87
+ if (pattern instanceof RegExp) return pattern.test(importee);
88
+ if (importee.length < pattern.length) return false;
89
+ if (importee === pattern) return true;
90
+ return importee.startsWith(`${pattern}/`);
122
91
  }
123
92
  async function transformWithEsbuild(entryPoint, options) {
124
- const { isESM = true, define, alias, cwd = process.cwd() } = options;
125
- const filepath = path.resolve(cwd, entryPoint);
126
- const filename = path.basename(entryPoint);
127
- const dirname = path.dirname(filepath);
128
- try {
129
- const result = await build({
130
- entryPoints: [entryPoint],
131
- outfile: "out.js",
132
- write: false,
133
- target: ["node18"],
134
- platform: "node",
135
- bundle: true,
136
- metafile: true,
137
- format: isESM ? "esm" : "cjs",
138
- define: {
139
- ...define,
140
- __dirname: JSON.stringify(dirname),
141
- __filename: JSON.stringify(filename),
142
- ...isESM ? {} : { "import.meta.url": JSON.stringify(pathToFileURL(filepath)) }
143
- },
144
- plugins: [aliasPlugin(alias), renamePlugin, externalizeDeps, jsonLoader, json5Loader],
145
- absWorkingDir: cwd
146
- });
147
- return {
148
- code: result.outputFiles[0].text,
149
- deps: result.metafile?.inputs || {}
150
- };
151
- } catch (e) {
152
- console.error(e);
153
- }
154
- return { code: "", deps: {} };
93
+ const { isESM = true, define, alias, cwd = process.cwd() } = options;
94
+ const filepath = path.resolve(cwd, entryPoint);
95
+ const filename = path.basename(entryPoint);
96
+ const dirname = path.dirname(filepath);
97
+ try {
98
+ const result = await build({
99
+ entryPoints: [entryPoint],
100
+ outfile: "out.js",
101
+ write: false,
102
+ target: ["node18"],
103
+ platform: "node",
104
+ bundle: true,
105
+ metafile: true,
106
+ format: isESM ? "esm" : "cjs",
107
+ define: {
108
+ ...define,
109
+ __dirname: JSON.stringify(dirname),
110
+ __filename: JSON.stringify(filename),
111
+ ...isESM ? {} : { "import.meta.url": JSON.stringify(pathToFileURL(filepath)) }
112
+ },
113
+ plugins: [
114
+ aliasPlugin(alias),
115
+ renamePlugin,
116
+ externalizeDeps,
117
+ jsonLoader,
118
+ json5Loader
119
+ ],
120
+ absWorkingDir: cwd
121
+ });
122
+ return {
123
+ code: result.outputFiles[0].text,
124
+ deps: result.metafile?.inputs || {}
125
+ };
126
+ } catch (e) {
127
+ console.error(e);
128
+ }
129
+ return {
130
+ code: "",
131
+ deps: {}
132
+ };
155
133
  }
156
- async function loadFromCode({
157
- filepath,
158
- code,
159
- isESM,
160
- cwd
161
- }) {
162
- filepath = path.resolve(cwd, filepath);
163
- const ext = isESM ? ".mjs" : ".cjs";
164
- const filepathTmp = `${filepath}.timestamp-${Date.now()}${ext}`;
165
- const file = pathToFileURL(filepathTmp).toString();
166
- await fsp.writeFile(filepathTmp, code, "utf8");
167
- try {
168
- const mod = await import(file);
169
- return mod.default || mod;
170
- } finally {
171
- try {
172
- fs.unlinkSync(filepathTmp);
173
- } catch {
174
- }
175
- }
134
+ async function loadFromCode({ filepath, code, isESM, cwd }) {
135
+ filepath = path.resolve(cwd, filepath);
136
+ const ext = isESM ? ".mjs" : ".cjs";
137
+ const filepathTmp = `${filepath}.timestamp-${Date.now()}${ext}`;
138
+ const file = pathToFileURL(filepathTmp).toString();
139
+ await promises.writeFile(filepathTmp, code, "utf8");
140
+ try {
141
+ const mod = await import(file);
142
+ return mod.default || mod;
143
+ } finally {
144
+ try {
145
+ fs.unlinkSync(filepathTmp);
146
+ } catch {}
147
+ }
176
148
  }
177
149
 
178
- // src/core/build.ts
150
+ //#endregion
151
+ //#region src/core/build.ts
179
152
  async function generateMockServer(ctx, options) {
180
- const include = toArray(options.include);
181
- const exclude = toArray(options.exclude);
182
- const cwd = options.cwd || process2.cwd();
183
- let pkg = {};
184
- try {
185
- const pkgStr = lookupFile(options.context, ["package.json"]);
186
- if (pkgStr)
187
- pkg = JSON.parse(pkgStr);
188
- } catch {
189
- }
190
- const outputDir = options.build.dist;
191
- const content = await generateMockEntryCode(cwd, include, exclude);
192
- const mockEntry = path2.join(cwd, `mock-data-${Date.now()}.js`);
193
- await fsp2.writeFile(mockEntry, content, "utf-8");
194
- const { code, deps } = await transformWithEsbuild(mockEntry, options);
195
- const mockDeps = getMockDependencies(deps, options.alias);
196
- await fsp2.unlink(mockEntry);
197
- const outputList = [
198
- {
199
- filename: path2.join(outputDir, "mock-data.js"),
200
- source: code
201
- },
202
- {
203
- filename: path2.join(outputDir, "index.js"),
204
- source: generatorServerEntryCode(options)
205
- },
206
- {
207
- filename: path2.join(outputDir, "package.json"),
208
- source: generatePackageJson(pkg, mockDeps)
209
- }
210
- ];
211
- try {
212
- if (path2.isAbsolute(outputDir)) {
213
- for (const { filename } of outputList) {
214
- if (fs2.existsSync(filename))
215
- await fsp2.rm(filename);
216
- }
217
- options.logger.info(`${c.green("\u2713")} generate mock server in ${c.cyan(outputDir)}`);
218
- for (const { filename, source } of outputList) {
219
- fs2.mkdirSync(path2.dirname(filename), { recursive: true });
220
- await fsp2.writeFile(filename, source, "utf-8");
221
- const sourceSize = (source.length / 1024).toFixed(2);
222
- const name = path2.relative(outputDir, filename);
223
- const space = name.length < 30 ? " ".repeat(30 - name.length) : "";
224
- options.logger.info(` ${c.green(name)}${space}${c.bold(c.dim(`${sourceSize} kB`))}`);
225
- }
226
- } else {
227
- for (const { filename, source } of outputList) {
228
- ctx.emitFile({
229
- type: "asset",
230
- fileName: filename,
231
- source
232
- });
233
- }
234
- }
235
- } catch (e) {
236
- console.error(e);
237
- }
153
+ const include = toArray(options.include);
154
+ const exclude = toArray(options.exclude);
155
+ const cwd = options.cwd || process.cwd();
156
+ let pkg = {};
157
+ try {
158
+ const pkgStr = lookupFile(options.context, ["package.json"]);
159
+ if (pkgStr) pkg = JSON.parse(pkgStr);
160
+ } catch {}
161
+ const outputDir = options.build.dist;
162
+ const content = await generateMockEntryCode(cwd, include, exclude);
163
+ const mockEntry = path.join(cwd, `mock-data-${Date.now()}.js`);
164
+ await fsp.writeFile(mockEntry, content, "utf-8");
165
+ const { code, deps } = await transformWithEsbuild(mockEntry, options);
166
+ const mockDeps = getMockDependencies(deps, options.alias);
167
+ await fsp.unlink(mockEntry);
168
+ const outputList = [
169
+ {
170
+ filename: path.join(outputDir, "mock-data.js"),
171
+ source: code
172
+ },
173
+ {
174
+ filename: path.join(outputDir, "index.js"),
175
+ source: generatorServerEntryCode(options)
176
+ },
177
+ {
178
+ filename: path.join(outputDir, "package.json"),
179
+ source: generatePackageJson(pkg, mockDeps)
180
+ }
181
+ ];
182
+ try {
183
+ if (path.isAbsolute(outputDir)) {
184
+ for (const { filename } of outputList) if (fs.existsSync(filename)) await fsp.rm(filename);
185
+ options.logger.info(`${colors.green("✓")} generate mock server in ${colors.cyan(outputDir)}`);
186
+ for (const { filename, source } of outputList) {
187
+ fs.mkdirSync(path.dirname(filename), { recursive: true });
188
+ await fsp.writeFile(filename, source, "utf-8");
189
+ const sourceSize = (source.length / 1024).toFixed(2);
190
+ const name = path.relative(outputDir, filename);
191
+ const space = name.length < 30 ? " ".repeat(30 - name.length) : "";
192
+ options.logger.info(` ${colors.green(name)}${space}${colors.bold(colors.dim(`${sourceSize} kB`))}`);
193
+ }
194
+ } else for (const { filename, source } of outputList) ctx.emitFile({
195
+ type: "asset",
196
+ fileName: filename,
197
+ source
198
+ });
199
+ } catch (e) {
200
+ console.error(e);
201
+ }
238
202
  }
239
203
  function getMockDependencies(deps, alias) {
240
- const list = /* @__PURE__ */ new Set();
241
- const excludeDeps = ["vite-plugin-mock-dev-server", "connect", "cors"];
242
- const isAlias = (p) => alias.find(({ find }) => aliasMatches(find, p));
243
- Object.keys(deps).forEach((mPath) => {
244
- const imports = deps[mPath].imports.filter((_) => _.external && !_.path.startsWith("<define:") && !isAlias(_.path)).map((_) => _.path);
245
- imports.forEach((dep) => {
246
- const name = normalizePackageName(dep);
247
- if (!excludeDeps.includes(name) && !isCore(name))
248
- list.add(name);
249
- });
250
- });
251
- return Array.from(list);
204
+ const list = new Set();
205
+ const excludeDeps = [
206
+ "vite-plugin-mock-dev-server",
207
+ "connect",
208
+ "cors"
209
+ ];
210
+ const isAlias = (p) => alias.find(({ find }) => aliasMatches(find, p));
211
+ Object.keys(deps).forEach((mPath) => {
212
+ const imports = deps[mPath].imports.filter((_) => _.external && !_.path.startsWith("<define:") && !isAlias(_.path)).map((_) => _.path);
213
+ imports.forEach((dep) => {
214
+ const name = normalizePackageName(dep);
215
+ if (!excludeDeps.includes(name) && !isCore(name)) list.add(name);
216
+ });
217
+ });
218
+ return Array.from(list);
252
219
  }
253
220
  function normalizePackageName(dep) {
254
- const [scope, name] = dep.split("/");
255
- if (scope[0] === "@") {
256
- return `${scope}/${name}`;
257
- }
258
- return scope;
221
+ const [scope, name] = dep.split("/");
222
+ if (scope[0] === "@") return `${scope}/${name}`;
223
+ return scope;
259
224
  }
260
225
  function generatePackageJson(pkg, mockDeps) {
261
- const { dependencies = {}, devDependencies = {} } = pkg;
262
- const dependents = { ...dependencies, ...devDependencies };
263
- const mockPkg = {
264
- name: "mock-server",
265
- type: "module",
266
- scripts: {
267
- start: "node index.js"
268
- },
269
- dependencies: {
270
- connect: "^3.7.0",
271
- ["vite-plugin-mock-dev-server"]: `^${"1.8.3"}`,
272
- cors: "^2.8.5"
273
- },
274
- pnpm: { peerDependencyRules: { ignoreMissing: ["vite"] } }
275
- };
276
- mockDeps.forEach((dep) => {
277
- mockPkg.dependencies[dep] = dependents[dep] || "latest";
278
- });
279
- return JSON.stringify(mockPkg, null, 2);
226
+ const { dependencies = {}, devDependencies = {} } = pkg;
227
+ const dependents = {
228
+ ...dependencies,
229
+ ...devDependencies
230
+ };
231
+ const mockPkg = {
232
+ name: "mock-server",
233
+ type: "module",
234
+ scripts: { start: "node index.js" },
235
+ dependencies: {
236
+ connect: "^3.7.0",
237
+ ["vite-plugin-mock-dev-server"]: `^1.8.5`,
238
+ cors: "^2.8.5"
239
+ },
240
+ pnpm: { peerDependencyRules: { ignoreMissing: ["vite"] } }
241
+ };
242
+ mockDeps.forEach((dep) => {
243
+ mockPkg.dependencies[dep] = dependents[dep] || "latest";
244
+ });
245
+ return JSON.stringify(mockPkg, null, 2);
280
246
  }
281
- function generatorServerEntryCode({
282
- proxies,
283
- wsProxies,
284
- cookiesOptions,
285
- bodyParserOptions,
286
- priority,
287
- build: build2
288
- }) {
289
- const { serverPort, log } = build2;
290
- return `import { createServer } from 'node:http';
247
+ function generatorServerEntryCode({ proxies, wsProxies, cookiesOptions, bodyParserOptions, priority, build: build$1 }) {
248
+ const { serverPort, log } = build$1;
249
+ return `import { createServer } from 'node:http';
291
250
  import connect from 'connect';
292
251
  import corsMiddleware from 'cors';
293
252
  import { baseMiddleware, createLogger, mockWebSocket } from 'vite-plugin-mock-dev-server/server';
@@ -321,24 +280,19 @@ console.log('listen: http://localhost:${serverPort}');
321
280
  `;
322
281
  }
323
282
  async function generateMockEntryCode(cwd, include, exclude) {
324
- const includePaths = await fg(include, { cwd });
325
- const includeFilter = createFilter(include, exclude, {
326
- resolve: false
327
- });
328
- const mockFiles = includePaths.filter(includeFilter);
329
- let importers = "";
330
- const exporters = [];
331
- mockFiles.forEach((filepath, index) => {
332
- const file = normalizePath(path2.join(cwd, filepath));
333
- importers += `import * as m${index} from '${file}';
334
- `;
335
- exporters.push(`[m${index}, '${filepath}']`);
336
- });
337
- return `import { transformMockData, transformRawData } from 'vite-plugin-mock-dev-server/server';
283
+ const includePaths = await fg(include, { cwd });
284
+ const includeFilter = createFilter(include, exclude, { resolve: false });
285
+ const mockFiles = includePaths.filter(includeFilter);
286
+ let importers = "";
287
+ const exporters = [];
288
+ mockFiles.forEach((filepath, index) => {
289
+ const file = normalizePath(path.join(cwd, filepath));
290
+ importers += `import * as m${index} from '${file}';\n`;
291
+ exporters.push(`[m${index}, '${filepath}']`);
292
+ });
293
+ return `import { transformMockData, transformRawData } from 'vite-plugin-mock-dev-server/server';
338
294
  ${importers}
339
- const exporters = [
340
- ${exporters.join(",\n ")}
341
- ];
295
+ const exporters = [\n ${exporters.join(",\n ")}\n];
342
296
  const mockList = exporters.map(([mod, filepath]) => {
343
297
  const raw = mod.default || mod;
344
298
  return transformRawData(raw, filepath);
@@ -346,446 +300,405 @@ const mockList = exporters.map(([mod, filepath]) => {
346
300
  export default transformMockData(mockList);`;
347
301
  }
348
302
 
349
- // src/core/mockMiddleware.ts
350
- import cors from "cors";
351
- import { pathToRegexp } from "path-to-regexp";
352
-
353
- // src/core/mockCompiler.ts
354
- import EventEmitter from "node:events";
355
- import process3 from "node:process";
356
- import { promiseParallel, toArray as toArray2 } from "@pengzhanbo/utils";
357
- import { createFilter as createFilter2 } from "@rollup/pluginutils";
358
- import chokidar from "chokidar";
359
- import fastGlob from "fast-glob";
303
+ //#endregion
304
+ //#region src/core/mockCompiler.ts
360
305
  function createMockCompiler(options) {
361
- return new MockCompiler(options);
306
+ return new MockCompiler(options);
362
307
  }
308
+ /**
309
+ * mock配置加载器
310
+ */
363
311
  var MockCompiler = class extends EventEmitter {
364
- constructor(options) {
365
- super();
366
- this.options = options;
367
- this.cwd = options.cwd || process3.cwd();
368
- try {
369
- const pkg = lookupFile(this.cwd, ["package.json"]);
370
- this.moduleType = !!pkg && JSON.parse(pkg).type === "module" ? "esm" : "cjs";
371
- } catch {
372
- }
373
- }
374
- moduleCache = /* @__PURE__ */ new Map();
375
- moduleDeps = /* @__PURE__ */ new Map();
376
- cwd;
377
- mockWatcher;
378
- depsWatcher;
379
- moduleType = "cjs";
380
- _mockData = {};
381
- get mockData() {
382
- return this._mockData;
383
- }
384
- run() {
385
- const { include, exclude } = this.options;
386
- const includeFilter = createFilter2(include, exclude, { resolve: false });
387
- fastGlob(include, { cwd: this.cwd }).then(
388
- (files) => files.filter(includeFilter).map((file) => () => this.loadMock(file))
389
- ).then((loadList) => promiseParallel(loadList, 10)).then(() => this.updateMockList());
390
- this.watchMockEntry();
391
- this.watchDeps();
392
- let timer = null;
393
- this.on("mock:update", async (filepath) => {
394
- if (!includeFilter(filepath))
395
- return;
396
- await this.loadMock(filepath);
397
- if (timer)
398
- clearImmediate(timer);
399
- timer = setImmediate(() => {
400
- this.updateMockList();
401
- this.emit("mock:update-end", filepath);
402
- timer = null;
403
- });
404
- });
405
- this.on("mock:unlink", async (filepath) => {
406
- if (!includeFilter(filepath))
407
- return;
408
- this.moduleCache.delete(filepath);
409
- this.updateMockList();
410
- this.emit("mock:update-end", filepath);
411
- });
412
- }
413
- watchMockEntry() {
414
- const { include } = this.options;
415
- const [firstGlob, ...otherGlob] = toArray2(include);
416
- const watcher = this.mockWatcher = chokidar.watch(firstGlob, {
417
- ignoreInitial: true,
418
- cwd: this.cwd
419
- });
420
- if (otherGlob.length > 0)
421
- otherGlob.forEach((glob) => watcher.add(glob));
422
- watcher.on("add", async (filepath) => {
423
- filepath = normalizePath(filepath);
424
- this.emit("mock:update", filepath);
425
- debug("watcher:add", filepath);
426
- });
427
- watcher.on("change", async (filepath) => {
428
- filepath = normalizePath(filepath);
429
- this.emit("mock:update", filepath);
430
- debug("watcher:change", filepath);
431
- });
432
- watcher.on("unlink", async (filepath) => {
433
- filepath = normalizePath(filepath);
434
- this.emit("mock:unlink", filepath);
435
- debug("watcher:unlink", filepath);
436
- });
437
- }
438
- /**
439
- * 监听 mock文件依赖的本地文件变动,
440
- * mock依赖文件更新,mock文件也一并更新
441
- */
442
- watchDeps() {
443
- const oldDeps = [];
444
- this.depsWatcher = chokidar.watch([], {
445
- ignoreInitial: true,
446
- cwd: this.cwd
447
- });
448
- this.depsWatcher.on("change", (filepath) => {
449
- filepath = normalizePath(filepath);
450
- const mockFiles = this.moduleDeps.get(filepath);
451
- mockFiles?.forEach((file) => {
452
- this.emit("mock:update", file);
453
- });
454
- });
455
- this.depsWatcher.on("unlink", (filepath) => {
456
- filepath = normalizePath(filepath);
457
- this.moduleDeps.delete(filepath);
458
- });
459
- this.on("update:deps", () => {
460
- const deps = [];
461
- for (const [dep] of this.moduleDeps.entries())
462
- deps.push(dep);
463
- const exactDeps = deps.filter((dep) => !oldDeps.includes(dep));
464
- if (exactDeps.length > 0)
465
- this.depsWatcher.add(exactDeps);
466
- });
467
- }
468
- close() {
469
- this.mockWatcher?.close();
470
- this.depsWatcher?.close();
471
- }
472
- updateMockList() {
473
- this._mockData = transformMockData(this.moduleCache);
474
- }
475
- updateModuleDeps(filepath, deps) {
476
- Object.keys(deps).forEach((mPath) => {
477
- const imports = deps[mPath].imports.map((_) => _.path);
478
- imports.forEach((dep) => {
479
- if (!this.moduleDeps.has(dep))
480
- this.moduleDeps.set(dep, /* @__PURE__ */ new Set());
481
- const cur = this.moduleDeps.get(dep);
482
- cur.add(filepath);
483
- });
484
- });
485
- this.emit("update:deps");
486
- }
487
- async loadMock(filepath) {
488
- if (!filepath)
489
- return;
490
- let isESM = false;
491
- if (/\.m[jt]s$/.test(filepath))
492
- isESM = true;
493
- else if (/\.c[jt]s$/.test(filepath))
494
- isESM = false;
495
- else
496
- isESM = this.moduleType === "esm";
497
- const { define, alias } = this.options;
498
- const { code, deps } = await transformWithEsbuild(
499
- filepath,
500
- { isESM, define, alias, cwd: this.cwd }
501
- );
502
- try {
503
- const raw = await loadFromCode({ filepath, code, isESM, cwd: this.cwd }) || {};
504
- this.moduleCache.set(filepath, transformRawData(raw, filepath));
505
- this.updateModuleDeps(filepath, deps);
506
- } catch (e) {
507
- console.error(e);
508
- }
509
- }
312
+ moduleCache = new Map();
313
+ moduleDeps = new Map();
314
+ moduleType = "cjs";
315
+ _mockData = {};
316
+ constructor(options) {
317
+ super();
318
+ this.options = options;
319
+ this.cwd = options.cwd || process.cwd();
320
+ try {
321
+ const pkg = lookupFile(this.cwd, ["package.json"]);
322
+ this.moduleType = !!pkg && JSON.parse(pkg).type === "module" ? "esm" : "cjs";
323
+ } catch {}
324
+ }
325
+ get mockData() {
326
+ return this._mockData;
327
+ }
328
+ run() {
329
+ const { include, exclude } = this.options;
330
+ /**
331
+ * 使用 rollup 提供的 include/exclude 规则,
332
+ * 过滤包含文件
333
+ */
334
+ const includeFilter = createFilter(include, exclude, { resolve: false });
335
+ fg(include, { cwd: this.cwd }).then((files) => files.filter(includeFilter).map((file) => () => this.loadMock(file))).then((loadList) => promiseParallel(loadList, 10)).then(() => this.updateMockList());
336
+ this.watchMockEntry();
337
+ this.watchDeps();
338
+ let timer = null;
339
+ this.on("mock:update", async (filepath) => {
340
+ if (!includeFilter(filepath)) return;
341
+ await this.loadMock(filepath);
342
+ if (timer) clearImmediate(timer);
343
+ timer = setImmediate(() => {
344
+ this.updateMockList();
345
+ this.emit("mock:update-end", filepath);
346
+ timer = null;
347
+ });
348
+ });
349
+ this.on("mock:unlink", async (filepath) => {
350
+ if (!includeFilter(filepath)) return;
351
+ this.moduleCache.delete(filepath);
352
+ this.updateMockList();
353
+ this.emit("mock:update-end", filepath);
354
+ });
355
+ }
356
+ watchMockEntry() {
357
+ const { include } = this.options;
358
+ const [firstGlob, ...otherGlob] = toArray(include);
359
+ const watcher = this.mockWatcher = chokidar.watch(firstGlob, {
360
+ ignoreInitial: true,
361
+ cwd: this.cwd
362
+ });
363
+ if (otherGlob.length > 0) otherGlob.forEach((glob) => watcher.add(glob));
364
+ watcher.on("add", async (filepath) => {
365
+ filepath = normalizePath(filepath);
366
+ this.emit("mock:update", filepath);
367
+ debug("watcher:add", filepath);
368
+ });
369
+ watcher.on("change", async (filepath) => {
370
+ filepath = normalizePath(filepath);
371
+ this.emit("mock:update", filepath);
372
+ debug("watcher:change", filepath);
373
+ });
374
+ watcher.on("unlink", async (filepath) => {
375
+ filepath = normalizePath(filepath);
376
+ this.emit("mock:unlink", filepath);
377
+ debug("watcher:unlink", filepath);
378
+ });
379
+ }
380
+ /**
381
+ * 监听 mock文件依赖的本地文件变动,
382
+ * mock依赖文件更新,mock文件也一并更新
383
+ */
384
+ watchDeps() {
385
+ const oldDeps = [];
386
+ this.depsWatcher = chokidar.watch([], {
387
+ ignoreInitial: true,
388
+ cwd: this.cwd
389
+ });
390
+ this.depsWatcher.on("change", (filepath) => {
391
+ filepath = normalizePath(filepath);
392
+ const mockFiles = this.moduleDeps.get(filepath);
393
+ mockFiles?.forEach((file) => {
394
+ this.emit("mock:update", file);
395
+ });
396
+ });
397
+ this.depsWatcher.on("unlink", (filepath) => {
398
+ filepath = normalizePath(filepath);
399
+ this.moduleDeps.delete(filepath);
400
+ });
401
+ this.on("update:deps", () => {
402
+ const deps = [];
403
+ for (const [dep] of this.moduleDeps.entries()) deps.push(dep);
404
+ const exactDeps = deps.filter((dep) => !oldDeps.includes(dep));
405
+ if (exactDeps.length > 0) this.depsWatcher.add(exactDeps);
406
+ });
407
+ }
408
+ close() {
409
+ this.mockWatcher?.close();
410
+ this.depsWatcher?.close();
411
+ }
412
+ updateMockList() {
413
+ this._mockData = transformMockData(this.moduleCache);
414
+ }
415
+ updateModuleDeps(filepath, deps) {
416
+ Object.keys(deps).forEach((mPath) => {
417
+ const imports = deps[mPath].imports.map((_) => _.path);
418
+ imports.forEach((dep) => {
419
+ if (!this.moduleDeps.has(dep)) this.moduleDeps.set(dep, new Set());
420
+ const cur = this.moduleDeps.get(dep);
421
+ cur.add(filepath);
422
+ });
423
+ });
424
+ this.emit("update:deps");
425
+ }
426
+ async loadMock(filepath) {
427
+ if (!filepath) return;
428
+ let isESM = false;
429
+ if (/\.m[jt]s$/.test(filepath)) isESM = true;
430
+ else if (/\.c[jt]s$/.test(filepath)) isESM = false;
431
+ else isESM = this.moduleType === "esm";
432
+ const { define, alias } = this.options;
433
+ const { code, deps } = await transformWithEsbuild(filepath, {
434
+ isESM,
435
+ define,
436
+ alias,
437
+ cwd: this.cwd
438
+ });
439
+ try {
440
+ const raw = await loadFromCode({
441
+ filepath,
442
+ code,
443
+ isESM,
444
+ cwd: this.cwd
445
+ }) || {};
446
+ this.moduleCache.set(filepath, transformRawData(raw, filepath));
447
+ this.updateModuleDeps(filepath, deps);
448
+ } catch (e) {
449
+ console.error(e);
450
+ }
451
+ }
510
452
  };
511
453
 
512
- // src/core/mockMiddleware.ts
454
+ //#endregion
455
+ //#region src/core/mockMiddleware.ts
513
456
  function mockServerMiddleware(options, server, ws) {
514
- const compiler = createMockCompiler(options);
515
- compiler.run();
516
- compiler.on("mock:update-end", () => {
517
- if (options.reload)
518
- ws?.send({ type: "full-reload" });
519
- });
520
- server?.on("close", () => compiler.close());
521
- mockWebSocket(compiler, server, options);
522
- const middlewares = [];
523
- middlewares.push(
524
- /**
525
- * vite 的开发服务中,由于插件 enforce 为 `pre`,
526
- * mock 中间件的执行顺序 早于 vite 内部的 cors 中间件执行,
527
- * 这导致了 vite 默认开启的 cors 对 mock 请求不生效。
528
- * 在一些比如 微前端项目、或者联合项目中,会由于端口不一致而导致跨域问题。
529
- * 所以在这里,使用 cors 中间件 来解决这个问题。
530
- *
531
- * 同时为了使 插件内的 cors vite cors 不产生冲突,并拥有一致的默认行为,
532
- * 也会使用 viteConfig.server.cors 配置,并支持 用户可以对 mock 中的 cors 中间件进行配置。
533
- * 而用户的配置也仅对 mock 的接口生效。
534
- */
535
- corsMiddleware(compiler, options),
536
- baseMiddleware(compiler, options)
537
- );
538
- return middlewares.filter(Boolean);
457
+ /**
458
+ * 加载 mock 文件, 包括监听 mock 文件的依赖文件变化,
459
+ * 并注入 vite `define` / `alias`
460
+ */
461
+ const compiler = createMockCompiler(options);
462
+ compiler.run();
463
+ /**
464
+ * 监听 mock 文件是否发生变更,如何配置了 reload 为 true,
465
+ * 当发生变更时,通知当前页面进行重新加载
466
+ */
467
+ compiler.on("mock:update-end", () => {
468
+ if (options.reload) ws?.send({ type: "full-reload" });
469
+ });
470
+ server?.on("close", () => compiler.close());
471
+ /**
472
+ * 虽然 config.server.proxy 中有关于 ws 的代理配置,
473
+ * 但是由于 vite 内部在启动时,直接对 ws相关的请求,通过 upgrade 事件,发送给 http-proxy
474
+ * ws 代理方法。如果插件直接使用 config.server.proxy 中的 ws 配置,
475
+ * 就会导致两次 upgrade 事件 wss 实例的冲突。
476
+ * 由于 vite 内部并没有提供其他的方式跳过 内部 upgrade 的方式,(个人认为也没有必要提供此类方式)
477
+ * 所以插件选择了通过插件的配置项 `wsPrefix` 来做 判断的首要条件。
478
+ * 当前插件默认会将已配置在 wsPrefix 的值,从 config.server.proxy 的删除,避免发生冲突问题。
479
+ */
480
+ mockWebSocket(compiler, server, options);
481
+ const middlewares = [];
482
+ middlewares.push(
483
+ /**
484
+ * 在 vite 的开发服务中,由于插件 的 enforce 为 `pre`,
485
+ * mock 中间件的执行顺序 早于 vite 内部的 cors 中间件执行,
486
+ * 这导致了 vite 默认开启的 cors 对 mock 请求不生效。
487
+ * 在一些比如 微前端项目、或者联合项目中,会由于端口不一致而导致跨域问题。
488
+ * 所以在这里,使用 cors 中间件 来解决这个问题。
489
+ *
490
+ * 同时为了使 插件内的 cors 和 vite 的 cors 不产生冲突,并拥有一致的默认行为,
491
+ * 也会使用 viteConfig.server.cors 配置,并支持 用户可以对 mock 中的 cors 中间件进行配置。
492
+ * 而用户的配置也仅对 mock 的接口生效。
493
+ */
494
+ corsMiddleware(compiler, options),
495
+ baseMiddleware(compiler, options)
496
+ );
497
+ return middlewares.filter(Boolean);
539
498
  }
540
499
  function corsMiddleware(compiler, { proxies, cors: corsOptions }) {
541
- return !corsOptions ? void 0 : function(req, res, next) {
542
- const { pathname } = urlParse(req.url);
543
- if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url))) {
544
- return next();
545
- }
546
- const mockData = compiler.mockData;
547
- const mockUrl = Object.keys(mockData).find(
548
- (key) => pathToRegexp(key).test(pathname)
549
- );
550
- if (!mockUrl)
551
- return next();
552
- cors(corsOptions)(req, res, next);
553
- };
500
+ return !corsOptions ? void 0 : function(req, res, next) {
501
+ const { pathname } = urlParse(req.url);
502
+ if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url))) return next();
503
+ const mockData = compiler.mockData;
504
+ const mockUrl = Object.keys(mockData).find((key) => pathToRegexp(key).test(pathname));
505
+ if (!mockUrl) return next();
506
+ cors(corsOptions)(req, res, next);
507
+ };
554
508
  }
555
509
 
556
- // src/core/resolvePluginOptions.ts
557
- import process5 from "node:process";
558
- import { isArray, isBoolean, toArray as toArray3, uniq } from "@pengzhanbo/utils";
559
- import color from "picocolors";
560
-
561
- // src/core/define.ts
562
- import process4 from "node:process";
510
+ //#endregion
511
+ //#region src/core/define.ts
563
512
  function viteDefine(config) {
564
- const processNodeEnv = {};
565
- const nodeEnv = process4.env.NODE_ENV || config.mode;
566
- Object.assign(processNodeEnv, {
567
- "process.env.NODE_ENV": JSON.stringify(nodeEnv),
568
- "global.process.env.NODE_ENV": JSON.stringify(nodeEnv),
569
- "globalThis.process.env.NODE_ENV": JSON.stringify(nodeEnv)
570
- });
571
- const userDefine = {};
572
- const userDefineEnv = {};
573
- for (const key in config.define) {
574
- const val = config.define[key];
575
- const isMetaEnv = key.startsWith("import.meta.env.");
576
- if (typeof val === "string") {
577
- if (canJsonParse(val)) {
578
- userDefine[key] = val;
579
- if (isMetaEnv)
580
- userDefineEnv[key.slice(16)] = val;
581
- }
582
- } else {
583
- userDefine[key] = handleDefineValue(val);
584
- if (isMetaEnv)
585
- userDefineEnv[key.slice(16)] = val;
586
- }
587
- }
588
- const importMetaKeys = {};
589
- const importMetaEnvKeys = {};
590
- const importMetaFallbackKeys = {};
591
- importMetaKeys["import.meta.hot"] = `undefined`;
592
- for (const key in config.env) {
593
- const val = JSON.stringify(config.env[key]);
594
- importMetaKeys[`import.meta.env.${key}`] = val;
595
- importMetaEnvKeys[key] = val;
596
- }
597
- importMetaFallbackKeys["import.meta.env"] = `undefined`;
598
- const define = {
599
- ...processNodeEnv,
600
- ...importMetaKeys,
601
- ...userDefine,
602
- ...importMetaFallbackKeys
603
- };
604
- if ("import.meta.env" in define) {
605
- define["import.meta.env"] = serializeDefine({
606
- ...importMetaEnvKeys,
607
- ...userDefineEnv
608
- });
609
- }
610
- return define;
513
+ const processNodeEnv = {};
514
+ const nodeEnv = process.env.NODE_ENV || config.mode;
515
+ Object.assign(processNodeEnv, {
516
+ "process.env.NODE_ENV": JSON.stringify(nodeEnv),
517
+ "global.process.env.NODE_ENV": JSON.stringify(nodeEnv),
518
+ "globalThis.process.env.NODE_ENV": JSON.stringify(nodeEnv)
519
+ });
520
+ const userDefine = {};
521
+ const userDefineEnv = {};
522
+ for (const key in config.define) {
523
+ const val = config.define[key];
524
+ const isMetaEnv = key.startsWith("import.meta.env.");
525
+ if (typeof val === "string") {
526
+ if (canJsonParse(val)) {
527
+ userDefine[key] = val;
528
+ if (isMetaEnv) userDefineEnv[key.slice(16)] = val;
529
+ }
530
+ } else {
531
+ userDefine[key] = handleDefineValue(val);
532
+ if (isMetaEnv) userDefineEnv[key.slice(16)] = val;
533
+ }
534
+ }
535
+ const importMetaKeys = {};
536
+ const importMetaEnvKeys = {};
537
+ const importMetaFallbackKeys = {};
538
+ importMetaKeys["import.meta.hot"] = `undefined`;
539
+ for (const key in config.env) {
540
+ const val = JSON.stringify(config.env[key]);
541
+ importMetaKeys[`import.meta.env.${key}`] = val;
542
+ importMetaEnvKeys[key] = val;
543
+ }
544
+ importMetaFallbackKeys["import.meta.env"] = `undefined`;
545
+ const define = {
546
+ ...processNodeEnv,
547
+ ...importMetaKeys,
548
+ ...userDefine,
549
+ ...importMetaFallbackKeys
550
+ };
551
+ if ("import.meta.env" in define) define["import.meta.env"] = serializeDefine({
552
+ ...importMetaEnvKeys,
553
+ ...userDefineEnv
554
+ });
555
+ return define;
611
556
  }
557
+ /**
558
+ * Like `JSON.stringify` but keeps raw string values as a literal
559
+ * in the generated code. For example: `"window"` would refer to
560
+ * the global `window` object directly.
561
+ */
612
562
  function serializeDefine(define) {
613
- let res = `{`;
614
- const keys = Object.keys(define);
615
- for (let i = 0; i < keys.length; i++) {
616
- const key = keys[i];
617
- const val = define[key];
618
- res += `${JSON.stringify(key)}: ${handleDefineValue(val)}`;
619
- if (i !== keys.length - 1)
620
- res += `, `;
621
- }
622
- return `${res}}`;
563
+ let res = `{`;
564
+ const keys = Object.keys(define);
565
+ for (let i = 0; i < keys.length; i++) {
566
+ const key = keys[i];
567
+ const val = define[key];
568
+ res += `${JSON.stringify(key)}: ${handleDefineValue(val)}`;
569
+ if (i !== keys.length - 1) res += `, `;
570
+ }
571
+ return `${res}}`;
623
572
  }
624
573
  function handleDefineValue(value) {
625
- if (typeof value === "undefined")
626
- return "undefined";
627
- if (typeof value === "string")
628
- return value;
629
- return JSON.stringify(value);
574
+ if (typeof value === "undefined") return "undefined";
575
+ if (typeof value === "string") return value;
576
+ return JSON.stringify(value);
630
577
  }
631
578
  function canJsonParse(value) {
632
- try {
633
- JSON.parse(value);
634
- return true;
635
- } catch {
636
- return false;
637
- }
579
+ try {
580
+ JSON.parse(value);
581
+ return true;
582
+ } catch {
583
+ return false;
584
+ }
638
585
  }
639
586
 
640
- // src/core/resolvePluginOptions.ts
641
- function resolvePluginOptions({
642
- prefix = [],
643
- wsPrefix = [],
644
- cwd,
645
- include = ["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],
646
- exclude = ["**/node_modules/**", "**/.vscode/**", "**/.git/**"],
647
- reload = false,
648
- log = "info",
649
- cors: cors2 = true,
650
- formidableOptions = {},
651
- build: build2 = false,
652
- cookiesOptions = {},
653
- bodyParserOptions = {},
654
- priority = {}
655
- }, config) {
656
- const logger = createLogger("vite:mock", isBoolean(log) ? log ? "info" : "error" : log);
657
- const { httpProxies } = ensureProxies(config.server.proxy || {});
658
- const proxies = uniq([...toArray3(prefix), ...httpProxies]);
659
- const wsProxies = toArray3(wsPrefix);
660
- if (!proxies.length && !wsProxies.length)
661
- logger.warn(`No proxy was configured, mock server will not work. See ${color.cyan("https://vite-plugin-mock-dev-server.netlify.app/guide/usage")}`);
662
- const enabled = cors2 === false ? false : config.server.cors !== false;
663
- let corsOptions = {};
664
- if (enabled && config.server.cors !== false) {
665
- corsOptions = {
666
- ...corsOptions,
667
- ...typeof config.server.cors === "boolean" ? {} : config.server.cors
668
- };
669
- }
670
- if (enabled && cors2 !== false) {
671
- corsOptions = {
672
- ...corsOptions,
673
- ...typeof cors2 === "boolean" ? {} : cors2
674
- };
675
- }
676
- const alias = [];
677
- const aliasConfig = config.resolve.alias || [];
678
- if (isArray(aliasConfig)) {
679
- alias.push(...aliasConfig);
680
- } else {
681
- Object.entries(aliasConfig).forEach(([find, replacement]) => {
682
- alias.push({ find, replacement });
683
- });
684
- }
685
- return {
686
- cwd: cwd || process5.cwd(),
687
- include,
688
- exclude,
689
- context: config.root,
690
- reload,
691
- cors: enabled ? corsOptions : false,
692
- cookiesOptions,
693
- log,
694
- formidableOptions: {
695
- multiples: true,
696
- ...formidableOptions
697
- },
698
- bodyParserOptions,
699
- priority,
700
- build: build2 ? Object.assign(
701
- {
702
- serverPort: 8080,
703
- dist: "mockServer",
704
- log: "error"
705
- },
706
- typeof build2 === "object" ? build2 : {}
707
- ) : false,
708
- proxies,
709
- wsProxies,
710
- logger,
711
- alias,
712
- define: viteDefine(config)
713
- };
587
+ //#endregion
588
+ //#region src/core/resolvePluginOptions.ts
589
+ function resolvePluginOptions({ prefix = [], wsPrefix = [], cwd, include = ["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"], exclude = [
590
+ "**/node_modules/**",
591
+ "**/.vscode/**",
592
+ "**/.git/**"
593
+ ], reload = false, log = "info", cors: cors$1 = true, formidableOptions = {}, build: build$1 = false, cookiesOptions = {}, bodyParserOptions = {}, priority = {} }, config) {
594
+ const logger = createLogger("vite:mock", isBoolean(log) ? log ? "info" : "error" : log);
595
+ const { httpProxies } = ensureProxies(config.server.proxy || {});
596
+ const proxies = uniq([...toArray(prefix), ...httpProxies]);
597
+ const wsProxies = toArray(wsPrefix);
598
+ if (!proxies.length && !wsProxies.length) logger.warn(`No proxy was configured, mock server will not work. See ${colors.cyan("https://vite-plugin-mock-dev-server.netlify.app/guide/usage")}`);
599
+ const enabled = cors$1 === false ? false : config.server.cors !== false;
600
+ let corsOptions = {};
601
+ if (enabled && config.server.cors !== false) corsOptions = {
602
+ ...corsOptions,
603
+ ...typeof config.server.cors === "boolean" ? {} : config.server.cors
604
+ };
605
+ if (enabled && cors$1 !== false) corsOptions = {
606
+ ...corsOptions,
607
+ ...typeof cors$1 === "boolean" ? {} : cors$1
608
+ };
609
+ const alias = [];
610
+ const aliasConfig = config.resolve.alias || [];
611
+ if (isArray(aliasConfig)) alias.push(...aliasConfig);
612
+ else Object.entries(aliasConfig).forEach(([find, replacement]) => {
613
+ alias.push({
614
+ find,
615
+ replacement
616
+ });
617
+ });
618
+ return {
619
+ cwd: cwd || process.cwd(),
620
+ include,
621
+ exclude,
622
+ context: config.root,
623
+ reload,
624
+ cors: enabled ? corsOptions : false,
625
+ cookiesOptions,
626
+ log,
627
+ formidableOptions: {
628
+ multiples: true,
629
+ ...formidableOptions
630
+ },
631
+ bodyParserOptions,
632
+ priority,
633
+ build: build$1 ? Object.assign({
634
+ serverPort: 8080,
635
+ dist: "mockServer",
636
+ log: "error"
637
+ }, typeof build$1 === "object" ? build$1 : {}) : false,
638
+ proxies,
639
+ wsProxies,
640
+ logger,
641
+ alias,
642
+ define: viteDefine(config)
643
+ };
714
644
  }
715
645
 
716
- // src/plugin.ts
646
+ //#endregion
647
+ //#region src/plugin.ts
717
648
  function mockDevServerPlugin(options = {}) {
718
- const plugins = [serverPlugin(options)];
719
- if (options.build)
720
- plugins.push(buildPlugin(options));
721
- return plugins;
649
+ const plugins = [serverPlugin(options)];
650
+ if (options.build) plugins.push(buildPlugin(options));
651
+ return plugins;
722
652
  }
723
653
  function buildPlugin(options) {
724
- let viteConfig = {};
725
- let resolvedOptions;
726
- return {
727
- name: "vite-plugin-mock-dev-server-generator",
728
- enforce: "post",
729
- apply: "build",
730
- configResolved(config) {
731
- viteConfig = config;
732
- resolvedOptions = resolvePluginOptions(options, config);
733
- config.logger.warn("");
734
- },
735
- async buildEnd(error) {
736
- if (error || viteConfig.command !== "build")
737
- return;
738
- await generateMockServer(this, resolvedOptions);
739
- }
740
- };
654
+ let viteConfig = {};
655
+ let resolvedOptions;
656
+ return {
657
+ name: "vite-plugin-mock-dev-server-generator",
658
+ enforce: "post",
659
+ apply: "build",
660
+ configResolved(config) {
661
+ viteConfig = config;
662
+ resolvedOptions = resolvePluginOptions(options, config);
663
+ config.logger.warn("");
664
+ },
665
+ async buildEnd(error) {
666
+ if (error || viteConfig.command !== "build") return;
667
+ await generateMockServer(this, resolvedOptions);
668
+ }
669
+ };
741
670
  }
742
671
  function serverPlugin(options) {
743
- let resolvedOptions;
744
- return {
745
- name: "vite-plugin-mock-dev-server",
746
- enforce: "pre",
747
- apply: "serve",
748
- config(config) {
749
- const wsPrefix = toArray4(options.wsPrefix);
750
- if (wsPrefix.length && config.server?.proxy) {
751
- const proxy = {};
752
- Object.keys(config.server.proxy).forEach((key) => {
753
- if (!wsPrefix.includes(key))
754
- proxy[key] = config.server.proxy[key];
755
- });
756
- config.server.proxy = proxy;
757
- }
758
- recoverRequest(config);
759
- },
760
- configResolved(config) {
761
- resolvedOptions = resolvePluginOptions(options, config);
762
- config.logger.warn("");
763
- },
764
- configureServer({ middlewares, httpServer, ws }) {
765
- const middlewareList = mockServerMiddleware(resolvedOptions, httpServer, ws);
766
- middlewareList.forEach((middleware) => middlewares.use(middleware));
767
- },
768
- configurePreviewServer({ middlewares, httpServer }) {
769
- const middlewareList = mockServerMiddleware(resolvedOptions, httpServer);
770
- middlewareList.forEach((middleware) => middlewares.use(middleware));
771
- }
772
- };
672
+ let resolvedOptions;
673
+ return {
674
+ name: "vite-plugin-mock-dev-server",
675
+ enforce: "pre",
676
+ apply: "serve",
677
+ config(config) {
678
+ const wsPrefix = toArray(options.wsPrefix);
679
+ if (wsPrefix.length && config.server?.proxy) {
680
+ const proxy = {};
681
+ Object.keys(config.server.proxy).forEach((key) => {
682
+ if (!wsPrefix.includes(key)) proxy[key] = config.server.proxy[key];
683
+ });
684
+ config.server.proxy = proxy;
685
+ }
686
+ recoverRequest(config);
687
+ },
688
+ configResolved(config) {
689
+ resolvedOptions = resolvePluginOptions(options, config);
690
+ config.logger.warn("");
691
+ },
692
+ configureServer({ middlewares, httpServer, ws }) {
693
+ const middlewareList = mockServerMiddleware(resolvedOptions, httpServer, ws);
694
+ middlewareList.forEach((middleware) => middlewares.use(middleware));
695
+ },
696
+ configurePreviewServer({ middlewares, httpServer }) {
697
+ const middlewareList = mockServerMiddleware(resolvedOptions, httpServer);
698
+ middlewareList.forEach((middleware) => middlewares.use(middleware));
699
+ }
700
+ };
773
701
  }
774
702
 
775
- // src/index.ts
776
- var index_default = mockDevServerPlugin;
777
- export {
778
- baseMiddleware,
779
- createDefineMock,
780
- createLogger,
781
- createSSEStream,
782
- index_default as default,
783
- defineMock,
784
- defineMockData,
785
- logLevels,
786
- mockDevServerPlugin,
787
- mockWebSocket,
788
- sortByValidator,
789
- transformMockData,
790
- transformRawData
791
- };
703
+ //#endregion
704
+ export { baseMiddleware, createDefineMock, createLogger, createSSEStream, defineMock, defineMockData, logLevels, mockDevServerPlugin, mockWebSocket, sortByValidator, transformMockData, transformRawData };