vite-plugin-mock-dev-server 2.0.5 → 2.0.7

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