vite-plugin-mock-dev-server 1.1.4 → 1.1.5

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 +17 -993
  2. package/dist/index.js +17 -948
  3. package/package.json +6 -2
package/dist/index.js CHANGED
@@ -1,260 +1,6 @@
1
- // src/build.ts
2
- import fs2 from "fs";
3
- import fsp2 from "fs/promises";
4
- import path3 from "path";
5
- import { build } from "esbuild";
6
- import fg from "fast-glob";
7
- import isCore from "is-core-module";
8
- import { createFilter, normalizePath } from "vite";
9
-
10
- // package.json
11
- var name = "vite-plugin-mock-dev-server";
12
- var version = "1.1.4";
13
-
14
- // src/esbuildPlugin.ts
15
- import fsp from "fs/promises";
16
- import path from "path";
17
- import JSON5 from "json5";
18
- var externalizeDeps = {
19
- name: "externalize-deps",
20
- setup(build3) {
21
- build3.onResolve({ filter: /.*/ }, ({ path: id }) => {
22
- if (id[0] !== "." && !path.isAbsolute(id)) {
23
- return {
24
- external: true
25
- };
26
- }
27
- });
28
- }
29
- };
30
- var json5Loader = {
31
- name: "json5-loader",
32
- setup(build3) {
33
- build3.onLoad({ filter: /\.json5$/ }, async ({ path: path5 }) => {
34
- const content = await fsp.readFile(path5, "utf-8");
35
- return {
36
- contents: `export default ${JSON.stringify(JSON5.parse(content))}`,
37
- loader: "js"
38
- };
39
- });
40
- }
41
- };
42
- var jsonLoader = {
43
- name: "json-loader",
44
- setup(build3) {
45
- build3.onLoad({ filter: /\.json$/ }, async ({ path: path5 }) => {
46
- const content = await fsp.readFile(path5, "utf-8");
47
- return {
48
- contents: `export default ${content}`,
49
- loader: "js"
50
- };
51
- });
52
- }
53
- };
54
- var aliasPlugin = (alias) => {
55
- return {
56
- name: "alias-plugin",
57
- setup(build3) {
58
- build3.onResolve({ filter: /.*/ }, async ({ path: id }) => {
59
- const matchedEntry = alias.find(({ find: find2 }) => matches(find2, id));
60
- if (!matchedEntry) {
61
- return null;
62
- }
63
- const { find, replacement } = matchedEntry;
64
- const result = await build3.resolve(id.replace(find, replacement), {
65
- kind: "import-statement",
66
- resolveDir: replacement,
67
- namespace: "file"
68
- });
69
- return {
70
- path: result.path,
71
- external: false
72
- };
73
- });
74
- }
75
- };
76
- };
77
- function matches(pattern, importee) {
78
- if (pattern instanceof RegExp) {
79
- return pattern.test(importee);
80
- }
81
- if (importee.length < pattern.length) {
82
- return false;
83
- }
84
- if (importee === pattern) {
85
- return true;
86
- }
87
- return importee.startsWith(`${pattern}/`);
88
- }
89
-
90
- // src/utils.ts
91
- import fs from "fs";
92
- import path2 from "path";
93
- import { fileURLToPath } from "url";
94
- import Debug from "debug";
95
- import { match } from "path-to-regexp";
96
- import colors from "picocolors";
97
- var isArray = (val) => Array.isArray(val);
98
- var isFunction = (val) => typeof val === "function";
99
- var isStream = (stream) => stream !== null && typeof stream === "object" && typeof stream.pipe === "function";
100
- var isReadableStream = (stream) => isStream(stream) && stream.readable !== false && typeof stream._read === "function" && typeof stream._readableState === "object";
101
- function sleep(timeout) {
102
- return new Promise((resolve) => setTimeout(resolve, timeout));
103
- }
104
- function getDirname(importMetaUrl) {
105
- return path2.dirname(fileURLToPath(importMetaUrl));
106
- }
107
- var debug = Debug("vite:plugin-mock-dev-server");
108
- var ensureArray = (thing) => {
109
- if (isArray(thing))
110
- return thing;
111
- if (thing === null || thing === void 0)
112
- return [];
113
- return [thing];
114
- };
115
- var log = {
116
- info(...args) {
117
- console.info(colors.cyan("mock-dev-server: "), ...args);
118
- },
119
- error(...args) {
120
- console.error("\n", colors.cyan("mock-dev-server: "), ...args, "\n");
121
- }
122
- };
123
- function lookupFile(dir, formats, options) {
124
- for (const format of formats) {
125
- const fullPath = path2.join(dir, format);
126
- if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {
127
- const result = (options == null ? void 0 : options.pathOnly) ? fullPath : fs.readFileSync(fullPath, "utf-8");
128
- if (!(options == null ? void 0 : options.predicate) || options.predicate(result)) {
129
- return result;
130
- }
131
- }
132
- }
133
- const parentDir = path2.dirname(dir);
134
- if (parentDir !== dir && (!(options == null ? void 0 : options.rootDir) || parentDir.startsWith(options == null ? void 0 : options.rootDir))) {
135
- return lookupFile(parentDir, formats, options);
136
- }
137
- }
138
- var ensureProxies = (serverProxy = {}) => {
139
- const proxies = Object.keys(serverProxy).map((key) => {
140
- var _a, _b;
141
- const value = serverProxy[key];
142
- return typeof value === "string" ? key : value.ws || ((_a = value.target) == null ? void 0 : _a.toString().startsWith("ws:")) || ((_b = value.target) == null ? void 0 : _b.toString().startsWith("wss:")) ? "" : key;
143
- }).filter(Boolean);
144
- return proxies;
145
- };
146
- function parseParams(pattern, url) {
147
- const urlMatch = match(pattern, { decode: decodeURIComponent })(url) || {
148
- params: {}
149
- };
150
- return urlMatch.params || {};
151
- }
152
-
153
- // src/build.ts
154
- async function generateMockServer(ctx, config, options) {
155
- const include = ensureArray(options.include);
156
- const exclude = ensureArray(options.exclude);
157
- const define = {};
158
- if (config.define) {
159
- for (const key in config.define) {
160
- const val = config.define[key];
161
- define[key] = typeof val === "string" ? val : JSON.stringify(val);
162
- }
163
- }
164
- const proxies = ensureProxies(config.server.proxy || {});
165
- const prefix = ensureArray(options.prefix);
166
- let pkg = {};
167
- try {
168
- const pkgStr = lookupFile(config.root, ["package.json"]);
169
- if (pkgStr) {
170
- pkg = JSON.parse(pkgStr);
171
- }
172
- } catch {
173
- }
174
- const outputDir = options.build.dist;
175
- const content = await generateMockEntryCode(process.cwd(), include, exclude);
176
- const mockEntry = path3.join(config.root, `mock-data-${Date.now()}.js`);
177
- await fsp2.writeFile(mockEntry, content, "utf-8");
178
- const { code, deps } = await buildMockEntry(
179
- mockEntry,
180
- define,
181
- config.resolve.alias
182
- );
183
- const mockDeps = getMockDependencies(deps);
184
- await fsp2.unlink(mockEntry);
185
- const outputList = [
186
- {
187
- filename: path3.join(outputDir, "mock-data.js"),
188
- source: code
189
- },
190
- {
191
- filename: path3.join(outputDir, "index.js"),
192
- source: generatorServerEntryCode(
193
- [...prefix, ...proxies],
194
- options.cookiesOptions,
195
- options.build.serverPort
196
- )
197
- },
198
- {
199
- filename: path3.join(outputDir, "package.json"),
200
- source: generatePackageJson(pkg, mockDeps)
201
- }
202
- ];
203
- try {
204
- if (path3.isAbsolute(outputDir)) {
205
- await fsp2.rm(outputDir, { recursive: true });
206
- fs2.mkdirSync(outputDir, { recursive: true });
207
- for (const { filename, source } of outputList) {
208
- await fsp2.writeFile(filename, source, "utf-8");
209
- }
210
- } else {
211
- for (const { filename, source } of outputList) {
212
- ctx.emitFile({
213
- type: "asset",
214
- fileName: filename,
215
- source
216
- });
217
- }
218
- }
219
- } catch {
220
- }
221
- }
222
- function getMockDependencies(deps) {
223
- const list = /* @__PURE__ */ new Set();
224
- const excludeDeps = [name, "connect", "cors"];
225
- Object.keys(deps).forEach((mPath) => {
226
- const imports = deps[mPath].imports.filter((_) => _.external).map((_) => _.path);
227
- imports.forEach((dep) => {
228
- if (!excludeDeps.includes(dep) && !isCore(dep)) {
229
- list.add(dep);
230
- }
231
- });
232
- });
233
- return Array.from(list);
234
- }
235
- function generatePackageJson(pkg, mockDeps) {
236
- const { dependencies = {}, devDependencies = {} } = pkg;
237
- const dependents = { ...dependencies, ...devDependencies };
238
- const mockPkg = {
239
- name: "mock-server",
240
- type: "module",
241
- scripts: {
242
- start: "node index.js"
243
- },
244
- dependencies: {
245
- "connect": "^3.7.0",
246
- "vite-plugin-mock-dev-server": `^${version}`,
247
- "cors": "^2.8.5"
248
- },
249
- pnpm: { peerDependencyRules: { ignoreMissing: ["vite"] } }
250
- };
251
- mockDeps.forEach((dep) => {
252
- mockPkg.dependencies[dep] = dependents[dep] || "latest";
253
- });
254
- return JSON.stringify(mockPkg, null, 2);
255
- }
256
- function generatorServerEntryCode(proxies, cookiesOptions = {}, port = 8080) {
257
- return `import connect from 'connect';
1
+ import Fe from"fs";import A from"fs/promises";import R from"path";import{build as Te}from"esbuild";import $e from"fast-glob";import Le from"is-core-module";import{createFilter as Ie,normalizePath as We}from"vite";var Z="vite-plugin-mock-dev-server",ee="1.1.5";import te from"fs/promises";import Oe from"path";import je from"json5";var N={name:"externalize-deps",setup(t){t.onResolve({filter:/.*/},({path:r})=>{if(r[0]!=="."&&!Oe.isAbsolute(r))return{external:!0}})}},oe={name:"json5-loader",setup(t){t.onLoad({filter:/\.json5$/},async({path:r})=>{let e=await te.readFile(r,"utf-8");return{contents:`export default ${JSON.stringify(je.parse(e))}`,loader:"js"}})}},re={name:"json-loader",setup(t){t.onLoad({filter:/\.json$/},async({path:r})=>({contents:`export default ${await te.readFile(r,"utf-8")}`,loader:"js"}))}},B=t=>({name:"alias-plugin",setup(r){r.onResolve({filter:/.*/},async({path:e})=>{let o=t.find(({find:a})=>Se(a,e));if(!o)return null;let{find:n,replacement:s}=o;return{path:(await r.resolve(e.replace(n,s),{kind:"import-statement",resolveDir:s,namespace:"file"})).path,external:!1}})}});function Se(t,r){return t instanceof RegExp?t.test(r):r.length<t.length?!1:r===t?!0:r.startsWith(`${t}/`)}import _ from"fs";import z from"path";import{fileURLToPath as Re}from"url";import Pe from"debug";import{match as De}from"path-to-regexp";import ne from"picocolors";var v=t=>Array.isArray(t),b=t=>typeof t=="function",Ce=t=>Object.prototype.toString.call(t)==="[object Object]",se=t=>Ce(t)&&Object.keys(t).length===0,Ee=t=>t!==null&&typeof t=="object"&&typeof t.pipe=="function",ie=t=>Ee(t)&&t.readable!==!1&&typeof t._read=="function"&&typeof t._readableState=="object";function ae(t){return new Promise(r=>setTimeout(r,t))}function ce(t){return z.dirname(Re(t))}var j=Pe("vite:plugin-mock-dev-server"),M=t=>v(t)?t:t==null?[]:[t],S={info(...t){console.info(ne.cyan("mock-dev-server: "),...t)},error(...t){console.error(`
2
+ `,ne.cyan("mock-dev-server: "),...t,`
3
+ `)}};function D(t,r,e){for(let n of r){let s=z.join(t,n);if(_.existsSync(s)&&_.statSync(s).isFile()){let i=e!=null&&e.pathOnly?s:_.readFileSync(s,"utf-8");if(!(e!=null&&e.predicate)||e.predicate(i))return i}}let o=z.dirname(t);if(o!==t&&(!(e!=null&&e.rootDir)||o.startsWith(e==null?void 0:e.rootDir)))return D(o,r,e)}var J=(t={})=>Object.keys(t).map(e=>{var n,s;let o=t[e];return typeof o=="string"?e:o.ws||(n=o.target)!=null&&n.toString().startsWith("ws:")||(s=o.target)!=null&&s.toString().startsWith("wss:")?"":e}).filter(Boolean);function U(t,r){return(De(t,{decode:decodeURIComponent})(r)||{params:{}}).params||{}}async function pe(t,r,e){let o=M(e.include),n=M(e.exclude),s={};if(r.define)for(let m in r.define){let d=r.define[m];s[m]=typeof d=="string"?d:JSON.stringify(d)}let i=J(r.server.proxy||{}),a=M(e.prefix),c={};try{let m=D(r.root,["package.json"]);m&&(c=JSON.parse(m))}catch{}let p=e.build.dist,u=await Ae(process.cwd(),o,n),l=R.join(r.root,`mock-data-${Date.now()}.js`);await A.writeFile(l,u,"utf-8");let{code:L,deps:I}=await qe(l,s,r.resolve.alias),O=Ne(I);await A.unlink(l);let P=[{filename:R.join(p,"mock-data.js"),source:L},{filename:R.join(p,"index.js"),source:Je([...a,...i],e.cookiesOptions,e.build.serverPort)},{filename:R.join(p,"package.json"),source:Be(c,O)}];try{if(R.isAbsolute(p)){await A.rm(p,{recursive:!0}),Fe.mkdirSync(p,{recursive:!0});for(let{filename:m,source:d}of P)await A.writeFile(m,d,"utf-8")}else for(let{filename:m,source:d}of P)t.emitFile({type:"asset",fileName:m,source:d})}catch{}}function Ne(t){let r=new Set,e=[Z,"connect","cors"];return Object.keys(t).forEach(o=>{t[o].imports.filter(s=>s.external).map(s=>s.path).forEach(s=>{!e.includes(s)&&!Le(s)&&r.add(s)})}),Array.from(r)}function Be(t,r){let{dependencies:e={},devDependencies:o={}}=t,n={...e,...o},s={name:"mock-server",type:"module",scripts:{start:"node index.js"},dependencies:{connect:"^3.7.0","vite-plugin-mock-dev-server":`^${ee}`,cors:"^2.8.5"},pnpm:{peerDependencyRules:{ignoreMissing:["vite"]}}};return r.forEach(i=>{s.dependencies[i]=n[i]||"latest"}),JSON.stringify(s,null,2)}function Je(t,r={},e=8080){return`import connect from 'connect';
258
4
  import corsMiddleware from 'cors';
259
5
  import { baseMiddleware } from 'vite-plugin-mock-dev-server';
260
6
  import mockData from './mock-data.js';
@@ -263,701 +9,24 @@ const app = connect();
263
9
  app.use(corsMiddleware());
264
10
  app.use(baseMiddleware({ mockData }, {
265
11
  formidableOptions: { multiples: true },
266
- proxies: ${JSON.stringify(proxies)}
267
- cookiesOptions: ${JSON.stringify(cookiesOptions)}
12
+ proxies: ${JSON.stringify(t)}
13
+ cookiesOptions: ${JSON.stringify(r)}
268
14
  }));
269
- app.listen(${port});
15
+ app.listen(${e});
270
16
 
271
- console.log('listen: http://localhost:${port}');
272
- `;
273
- }
274
- async function generateMockEntryCode(cwd, include, exclude) {
275
- const includePaths = await fg(include, { cwd });
276
- const includeFilter = createFilter(include, exclude, {
277
- resolve: false
278
- });
279
- const mockFiles = includePaths.filter(includeFilter);
280
- let importers = "";
281
- let exporters = "";
282
- mockFiles.forEach((filepath, index) => {
283
- const file = normalizePath(path3.join(cwd, filepath));
284
- importers += `import * as m${index} from '${file}';
285
- `;
286
- exporters += `m${index}, `;
287
- });
288
- return `import { transformMockData } from 'vite-plugin-mock-dev-server';
289
- ${importers}
290
- const exporters = [${exporters}];
17
+ console.log('listen: http://localhost:${e}');
18
+ `}async function Ae(t,r,e){let o=await $e(r,{cwd:t}),n=Ie(r,e,{resolve:!1}),s=o.filter(n),i="",a="";return s.forEach((c,p)=>{let u=We(R.join(t,c));i+=`import * as m${p} from '${u}';
19
+ `,a+=`m${p}, `}),`import { transformMockData } from 'vite-plugin-mock-dev-server';
20
+ ${i}
21
+ const exporters = [${a}];
291
22
  const mockList = exporters.map((raw) => raw && raw.default
292
23
  ? raw.default
293
24
  : Object.keys(raw || {}).map((key) => raw[key])
294
25
  )
295
26
  export default transformMockData(mockList);
296
- `;
297
- }
298
- async function buildMockEntry(inputFile, define, alias) {
299
- var _a;
300
- try {
301
- const result = await build({
302
- entryPoints: [inputFile],
303
- outfile: "out.js",
304
- write: false,
305
- target: ["node14.18", "node16"],
306
- platform: "node",
307
- bundle: true,
308
- metafile: true,
309
- format: "esm",
310
- define,
311
- plugins: [aliasPlugin(alias), externalizeDeps, json5Loader, jsonLoader]
312
- });
313
- return {
314
- code: result.outputFiles[0].text,
315
- deps: ((_a = result.metafile) == null ? void 0 : _a.inputs) || {}
316
- };
317
- } catch (e) {
318
- console.error(e);
319
- }
320
- return { code: "", deps: {} };
321
- }
322
-
323
- // src/baseMiddleware.ts
324
- import { Buffer } from "buffer";
325
- import { parse as urlParse } from "url";
326
- import Cookies from "cookies";
327
- import HTTP_STATUS from "http-status";
328
- import * as mime from "mime-types";
329
- import { pathToRegexp } from "path-to-regexp";
330
- import colors2 from "picocolors";
331
-
332
- // src/parseReqBody.ts
333
- import bodyParser from "co-body";
334
- import formidable from "formidable";
335
- async function parseReqBody(req, options) {
336
- var _a;
337
- const method = req.method.toUpperCase();
338
- if (["GET", "DELETE", "HEAD"].includes(method))
339
- return void 0;
340
- const type = ((_a = req.headers["content-type"]) == null ? void 0 : _a.toLocaleLowerCase()) || "";
341
- try {
342
- if (type.startsWith("application/json")) {
343
- return await bodyParser.json(req);
344
- }
345
- if (type.startsWith("application/x-www-form-urlencoded")) {
346
- return await bodyParser.form(req);
347
- }
348
- if (type.startsWith("text/plain")) {
349
- return await bodyParser.text(req);
350
- }
351
- if (type.startsWith("multipart/form-data")) {
352
- return await parseMultipart(req, options);
353
- }
354
- } catch (e) {
355
- console.error(e);
356
- }
357
- return void 0;
358
- }
359
- async function parseMultipart(req, options) {
360
- const form = formidable(options);
361
- return new Promise((resolve, reject) => {
362
- form.parse(req, (error, fields, files) => {
363
- if (error) {
364
- reject(error);
365
- return;
366
- }
367
- resolve({ ...fields, ...files });
368
- });
369
- });
370
- }
371
-
372
- // src/validator.ts
373
- function validate(request, validator) {
374
- return equalObj(request.headers, validator.headers) && equalObj(request.body, validator.body) && equalObj(request.params, validator.params) && equalObj(request.query, validator.query) && equalObj(request.refererQuery, validator.refererQuery);
375
- }
376
- function equalObj(left, right) {
377
- if (!right)
378
- return true;
379
- for (const key in right) {
380
- if (right[key] !== left[key])
381
- return false;
382
- }
383
- return true;
384
- }
385
-
386
- // src/baseMiddleware.ts
387
- function baseMiddleware(mockLoader, { formidableOptions = {}, proxies, cookiesOptions }) {
388
- return async function(req, res, next) {
389
- const startTime = Date.now();
390
- const { query, pathname } = urlParse(req.url, true);
391
- if (!pathname || proxies.length === 0 || !proxies.some((context) => doesProxyContextMatchUrl(context, req.url))) {
392
- return next();
393
- }
394
- const mockData = mockLoader.mockData;
395
- const mockUrl = Object.keys(mockData).find((key) => {
396
- return pathToRegexp(key).test(pathname);
397
- });
398
- if (!mockUrl)
399
- return next();
400
- const { query: refererQuery } = urlParse(req.headers.referer || "", true);
401
- const reqBody = await parseReqBody(req, formidableOptions);
402
- const cookies = new Cookies(req, res, cookiesOptions);
403
- const getCookie = cookies.get.bind(cookies);
404
- const method = req.method.toUpperCase();
405
- const mock = fineMock(mockData[mockUrl], {
406
- pathname,
407
- method,
408
- request: {
409
- query,
410
- refererQuery,
411
- body: reqBody,
412
- headers: req.headers,
413
- getCookie
414
- }
415
- });
416
- if (!mock)
417
- return next();
418
- debug("middleware: ", method, pathname);
419
- const request = req;
420
- const response = res;
421
- request.body = reqBody;
422
- request.query = query;
423
- request.refererQuery = refererQuery;
424
- request.params = parseParams(mock.url, pathname);
425
- request.getCookie = getCookie;
426
- response.setCookie = cookies.set.bind(cookies);
427
- const {
428
- body,
429
- delay,
430
- type = "json",
431
- response: responseFn,
432
- status = 200,
433
- statusText
434
- } = mock;
435
- responseStatus(response, status, statusText);
436
- await provideHeaders(request, response, mock);
437
- await provideCookies(request, response, mock);
438
- if (body) {
439
- try {
440
- const content = isFunction(body) ? await body(request) : body;
441
- await realDelay(startTime, delay);
442
- sendData(response, content, type);
443
- } catch (e) {
444
- log.error(`${colors2.red("[body error]")} ${req.url}
445
- `, e);
446
- responseStatus(response, 500);
447
- res.end("");
448
- }
449
- return;
450
- }
451
- if (responseFn) {
452
- try {
453
- await realDelay(startTime, delay);
454
- await responseFn(request, response, next);
455
- } catch (e) {
456
- log.error(`${colors2.red("[response error]")} ${req.url}
457
- `, e);
458
- responseStatus(response, 500);
459
- res.end("");
460
- }
461
- return;
462
- }
463
- res.end("");
464
- };
465
- }
466
- function fineMock(mockList, {
467
- pathname,
468
- method,
469
- request
470
- }) {
471
- return mockList.find((mock) => {
472
- if (!pathname || !mock || !mock.url)
473
- return false;
474
- const methods = mock.method ? isArray(mock.method) ? mock.method : [mock.method] : ["GET", "POST"];
475
- if (!methods.includes(method))
476
- return false;
477
- const hasMock = pathToRegexp(mock.url).test(pathname);
478
- if (hasMock && mock.validator) {
479
- const params = parseParams(mock.url, pathname);
480
- if (isFunction(mock.validator)) {
481
- return mock.validator({ params, ...request });
482
- } else {
483
- return validate({ params, ...request }, mock.validator);
484
- }
485
- }
486
- return hasMock;
487
- });
488
- }
489
- function responseStatus(response, status = 200, statusText) {
490
- response.statusCode = status;
491
- response.statusMessage = statusText || getHTTPStatusText(status);
492
- }
493
- async function provideHeaders(req, res, { headers, type = "json" }) {
494
- const contentType2 = mime.contentType(type) || mime.contentType(mime.lookup(type) || "");
495
- contentType2 && res.setHeader("Content-Type", contentType2);
496
- res.setHeader("Cache-Control", "no-cache,max-age=0");
497
- res.setHeader("X-Mock", "generate by vite:plugin-mock-dev-server");
498
- if (!headers)
499
- return;
500
- try {
501
- const raw = isFunction(headers) ? await headers(req) : headers;
502
- Object.keys(raw).forEach((key) => {
503
- res.setHeader(key, raw[key]);
504
- });
505
- } catch (e) {
506
- log.error(`${colors2.red("[headers error]")} ${req.url}
507
- `, e);
508
- }
509
- }
510
- async function provideCookies(req, res, { cookies }) {
511
- if (!cookies)
512
- return;
513
- try {
514
- const raw = isFunction(cookies) ? await cookies(req) : cookies;
515
- Object.keys(raw).forEach((key) => {
516
- const cookie = raw[key];
517
- if (isArray(cookie)) {
518
- const [value, options] = cookie;
519
- res.setCookie(key, value, options);
520
- } else {
521
- res.setCookie(key, cookie);
522
- }
523
- });
524
- } catch (e) {
525
- log.error(`${colors2.red("[cookies error]")} ${req.url}
526
- `, e);
527
- }
528
- }
529
- function sendData(res, raw, type) {
530
- if (isReadableStream(raw)) {
531
- raw.pipe(res);
532
- } else if (Buffer.isBuffer(raw)) {
533
- res.end(type === "text" || type === "json" ? raw.toString("utf-8") : raw);
534
- } else {
535
- const content = typeof raw === "string" ? raw : JSON.stringify(raw);
536
- res.end(type === "buffer" ? Buffer.from(content) : content);
537
- }
538
- }
539
- async function realDelay(startTime, delay) {
540
- if (!delay || delay <= 0)
541
- return;
542
- const diff = Date.now() - startTime;
543
- const realDelay2 = delay - diff;
544
- if (realDelay2 > 0)
545
- await sleep(realDelay2);
546
- }
547
- function doesProxyContextMatchUrl(context, url) {
548
- return context.startsWith("^") && new RegExp(context).test(url) || url.startsWith(context);
549
- }
550
- function getHTTPStatusText(status) {
551
- return HTTP_STATUS[status] || "Unknown";
552
- }
553
-
554
- // src/MockLoader.ts
555
- import EventEmitter from "events";
556
- import fs3 from "fs";
557
- import { createRequire } from "module";
558
- import path4 from "path";
559
- import { pathToFileURL } from "url";
560
- import chokidar from "chokidar";
561
- import { build as build2 } from "esbuild";
562
- import fastGlob from "fast-glob";
563
- import JSON52 from "json5";
564
- import { createFilter as createFilter2, normalizePath as normalizePath2 } from "vite";
565
-
566
- // src/transform.ts
567
- import { parse as urlParse2 } from "url";
568
- function transformMockData(mockList) {
569
- const list = [];
570
- for (const [, handle] of mockList.entries()) {
571
- if (handle) {
572
- isArray(handle) ? list.push(...handle) : list.push(handle);
573
- }
574
- }
575
- const mocks = {};
576
- list.filter(
577
- (mock) => (mock.enabled || typeof mock.enabled === "undefined") && mock.url
578
- ).forEach((mock) => {
579
- const { pathname, query } = urlParse2(mock.url, true);
580
- const list2 = mocks[pathname] ?? (mocks[pathname] = []);
581
- const current = Object.assign({}, mock, { url: pathname });
582
- if (query && !isFunction(current.validator)) {
583
- current.validator = Object.assign({}, current.validator || {});
584
- current.validator.query = Object.assign(
585
- query,
586
- current.validator.query || {}
587
- );
588
- }
589
- current.validator ? list2.unshift(current) : list2.push(current);
590
- });
591
- return mocks;
592
- }
593
-
594
- // src/MockLoader.ts
595
- var _dirname = getDirname(import.meta.url);
596
- var _require = createRequire(_dirname);
597
- var _MockLoader = class extends EventEmitter {
598
- constructor(options) {
599
- super();
600
- this.options = options;
601
- this.moduleCache = /* @__PURE__ */ new Map();
602
- this.moduleDeps = /* @__PURE__ */ new Map();
603
- this.moduleType = "cjs";
604
- this._mockData = {};
605
- this.cwd = options.cwd || process.cwd();
606
- try {
607
- const pkg = lookupFile(this.cwd, ["package.json"]);
608
- this.moduleType = !!pkg && JSON.parse(pkg).type === "module" ? "esm" : "cjs";
609
- } catch (e) {
610
- }
611
- }
612
- get mockData() {
613
- return this._mockData;
614
- }
615
- async load() {
616
- const { include, exclude } = this.options;
617
- const includePaths = await fastGlob(include, {
618
- cwd: this.cwd
619
- });
620
- const includeFilter = createFilter2(include, exclude, {
621
- resolve: false
622
- });
623
- this.watchMockEntry();
624
- this.watchDeps();
625
- for (const filepath of includePaths.filter(includeFilter)) {
626
- await this.loadMock(filepath);
627
- }
628
- this.updateMockList();
629
- this.on("mock:update", async (filepath) => {
630
- if (!includeFilter(filepath))
631
- return;
632
- await this.loadMock(filepath);
633
- this.updateMockList();
634
- this.emit("mock:update-end");
635
- });
636
- this.on("mock:unlink", async (filepath) => {
637
- if (!includeFilter(filepath))
638
- return;
639
- this.moduleCache.delete(filepath);
640
- this.updateMockList();
641
- this.emit("mock:update-end");
642
- });
643
- }
644
- watchMockEntry() {
645
- const { include } = this.options;
646
- const [firstGlob, ...otherGlob] = include;
647
- const watcher = chokidar.watch(firstGlob, {
648
- ignoreInitial: true,
649
- cwd: this.cwd
650
- });
651
- otherGlob.length > 0 && otherGlob.forEach((glob) => watcher.add(glob));
652
- watcher.on("add", async (filepath) => {
653
- filepath = normalizePath2(filepath);
654
- this.emit("mock:update", filepath);
655
- debug("watcher:add", filepath);
656
- });
657
- watcher.on("change", async (filepath) => {
658
- filepath = normalizePath2(filepath);
659
- this.emit("mock:update", filepath);
660
- debug("watcher:change", filepath);
661
- });
662
- watcher.on("unlink", async (filepath) => {
663
- filepath = normalizePath2(filepath);
664
- this.emit("mock:unlink", filepath);
665
- debug("watcher:unlink", filepath);
666
- });
667
- this.mockWatcher = watcher;
668
- }
669
- /**
670
- * 监听 mock文件依赖的本地文件变动,
671
- * mock依赖文件更新,mock文件也一并更新
672
- */
673
- watchDeps() {
674
- const oldDeps = [];
675
- this.depsWatcher = chokidar.watch([], {
676
- ignoreInitial: true,
677
- cwd: this.cwd
678
- });
679
- this.depsWatcher.on("change", (filepath) => {
680
- filepath = normalizePath2(filepath);
681
- const mockFiles = this.moduleDeps.get(filepath);
682
- mockFiles && mockFiles.forEach((file) => {
683
- this.emit("mock:update", file);
684
- });
685
- });
686
- this.depsWatcher.on("unlink", (filepath) => {
687
- filepath = normalizePath2(filepath);
688
- this.moduleDeps.delete(filepath);
689
- });
690
- this.on("update:deps", () => {
691
- const deps = [];
692
- for (const [dep] of this.moduleDeps.entries()) {
693
- deps.push(dep);
694
- }
695
- const exactDeps = deps.filter((dep) => !oldDeps.includes(dep));
696
- exactDeps.length > 0 && this.depsWatcher.add(exactDeps);
697
- });
698
- }
699
- close() {
700
- var _a, _b;
701
- (_a = this.mockWatcher) == null ? void 0 : _a.close();
702
- (_b = this.depsWatcher) == null ? void 0 : _b.close();
703
- }
704
- updateMockList() {
705
- this._mockData = transformMockData(this.moduleCache);
706
- }
707
- updateModuleDeps(filepath, deps) {
708
- Object.keys(deps).forEach((mPath) => {
709
- const imports = deps[mPath].imports.map((_) => _.path);
710
- imports.forEach((dep) => {
711
- if (!this.moduleDeps.has(dep)) {
712
- this.moduleDeps.set(dep, /* @__PURE__ */ new Set());
713
- }
714
- const cur = this.moduleDeps.get(dep);
715
- cur.add(filepath);
716
- });
717
- });
718
- this.emit("update:deps");
719
- }
720
- async loadMock(filepath) {
721
- if (!filepath)
722
- return;
723
- if (_MockLoader.EXT_JSON.test(filepath)) {
724
- await this.loadJson(filepath);
725
- } else {
726
- await this.loadModule(filepath);
727
- }
728
- }
729
- async loadJson(filepath) {
730
- const content = await fs3.promises.readFile(filepath, "utf-8");
731
- try {
732
- const mockConfig = JSON52.parse(content);
733
- this.moduleCache.set(filepath, mockConfig);
734
- } catch (e) {
735
- }
736
- }
737
- async loadModule(filepath) {
738
- if (!filepath)
739
- return;
740
- let isESM = false;
741
- if (/\.m[jt]s$/.test(filepath)) {
742
- isESM = true;
743
- } else if (/\.c[jt]s$/.test(filepath)) {
744
- isESM = false;
745
- } else {
746
- isESM = this.moduleType === "esm";
747
- }
748
- const { code, deps } = await this.transformWithEsbuild(filepath, isESM);
749
- try {
750
- const raw = await this.loadFromCode(filepath, code, isESM);
751
- const mockConfig = raw && raw.default ? raw.default : Object.keys(raw || {}).map((key) => raw[key]);
752
- this.moduleCache.set(filepath, mockConfig);
753
- this.updateModuleDeps(filepath, deps);
754
- } catch (e) {
755
- console.error(e);
756
- }
757
- }
758
- async loadFromCode(filepath, code, isESM) {
759
- if (isESM) {
760
- const fileBase = `${filepath}.timestamp-${Date.now()}`;
761
- const fileNameTmp = `${fileBase}.mjs`;
762
- const fileUrl = `${pathToFileURL(fileBase)}.mjs`;
763
- await fs3.promises.writeFile(fileNameTmp, code, "utf8");
764
- try {
765
- return await import(fileUrl);
766
- } finally {
767
- try {
768
- fs3.unlinkSync(fileNameTmp);
769
- } catch {
770
- }
771
- }
772
- } else {
773
- filepath = path4.resolve(this.cwd, filepath);
774
- const extension = path4.extname(filepath);
775
- const realFileName = fs3.realpathSync(filepath);
776
- const loaderExt = extension in _require.extensions ? extension : ".js";
777
- const defaultLoader = _require.extensions[loaderExt];
778
- _require.extensions[loaderExt] = (module, filename) => {
779
- if (filename === realFileName) {
780
- ;
781
- module._compile(code, filename);
782
- } else {
783
- defaultLoader(module, filename);
784
- }
785
- };
786
- delete _require.cache[_require.resolve(filepath)];
787
- const raw = _require(filepath);
788
- _require.extensions[loaderExt] = defaultLoader;
789
- return raw.__esModule ? raw : { default: raw };
790
- }
791
- }
792
- async transformWithEsbuild(filepath, isESM) {
793
- var _a;
794
- try {
795
- const result = await build2({
796
- entryPoints: [filepath],
797
- outfile: "out.js",
798
- write: false,
799
- target: ["node14.18", "node16"],
800
- platform: "node",
801
- bundle: true,
802
- metafile: true,
803
- format: isESM ? "esm" : "cjs",
804
- define: this.options.define,
805
- plugins: [aliasPlugin(this.options.alias), externalizeDeps]
806
- });
807
- return {
808
- code: result.outputFiles[0].text,
809
- deps: ((_a = result.metafile) == null ? void 0 : _a.inputs) || {}
810
- };
811
- } catch (e) {
812
- }
813
- return {
814
- code: "",
815
- deps: {}
816
- };
817
- }
818
- };
819
- var MockLoader = _MockLoader;
820
- MockLoader.EXT_JSON = /\.json5?$/;
821
-
822
- // src/mockMiddleware.ts
823
- async function mockServerMiddleware(config, options, httpServer, ws) {
824
- const include = ensureArray(options.include);
825
- const exclude = ensureArray(options.exclude);
826
- const define = {};
827
- if (config.define) {
828
- for (const key in config.define) {
829
- const val = config.define[key];
830
- define[key] = typeof val === "string" ? val : JSON.stringify(val);
831
- }
832
- }
833
- const loader = new MockLoader({
834
- include,
835
- exclude,
836
- define,
837
- alias: config.resolve.alias
838
- });
839
- await loader.load();
840
- httpServer == null ? void 0 : httpServer.on("close", () => loader.close());
841
- loader.on("mock:update-end", () => {
842
- if (options.reload) {
843
- ws == null ? void 0 : ws.send({ type: "full-reload" });
844
- }
845
- });
846
- const proxies = ensureProxies(config.server.proxy || {});
847
- const prefix = ensureArray(options.prefix);
848
- return baseMiddleware(loader, {
849
- formidableOptions: options.formidableOptions,
850
- proxies: [...prefix, ...proxies],
851
- cookiesOptions: options.cookiesOptions
852
- });
853
- }
854
-
855
- // src/plugin.ts
856
- function mockDevServerPlugin({
857
- prefix = [],
858
- include = ["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],
859
- exclude = ["**/node_modules/**", "**/.vscode/**", "**/.git/**"],
860
- reload = false,
861
- formidableOptions = {},
862
- build: build3 = false,
863
- cookiesOptions = {}
864
- } = {}) {
865
- const pluginOptions = {
866
- prefix,
867
- include,
868
- exclude,
869
- reload,
870
- cookiesOptions,
871
- formidableOptions: {
872
- multiples: true,
873
- ...formidableOptions
874
- },
875
- build: build3 ? Object.assign(
876
- {
877
- serverPort: 8080,
878
- dist: "mockServer"
879
- },
880
- typeof build3 === "object" ? build3 : {}
881
- ) : false
882
- };
883
- const plugins = [serverPlugin(pluginOptions)];
884
- if (pluginOptions.build) {
885
- plugins.push(buildPlugin(pluginOptions));
886
- }
887
- return plugins;
888
- }
889
- function buildPlugin(pluginOptions) {
890
- let viteConfig = {};
891
- return {
892
- name: "vite-plugin-mock-dev-server-generator",
893
- enforce: "post",
894
- apply: "build",
895
- configResolved(config) {
896
- viteConfig = config;
897
- config.logger.warn("");
898
- },
899
- async buildEnd(error) {
900
- if (error)
901
- return;
902
- if (viteConfig.command !== "build")
903
- return;
904
- await generateMockServer(this, viteConfig, pluginOptions);
905
- }
906
- };
907
- }
908
- function serverPlugin(pluginOptions) {
909
- let viteConfig = {};
910
- return {
911
- name: "vite-plugin-mock-dev-server",
912
- enforce: "pre",
913
- apply: "serve",
914
- configResolved(config) {
915
- viteConfig = config;
916
- config.logger.warn("");
917
- },
918
- async configureServer({ middlewares, config, httpServer, ws }) {
919
- const middleware = await mockServerMiddleware(
920
- config,
921
- pluginOptions,
922
- httpServer,
923
- ws
924
- );
925
- middlewares.use(middleware);
926
- },
927
- async configurePreviewServer({ middlewares, httpServer }) {
928
- const middleware = await mockServerMiddleware(
929
- viteConfig,
930
- pluginOptions,
931
- httpServer
932
- );
933
- middlewares.use(middleware);
934
- }
935
- };
936
- }
937
-
938
- // src/define.ts
939
- function defineMock(config) {
940
- return config;
941
- }
942
- function createDefineMock(transformer) {
943
- const define = (config) => {
944
- if (isArray(config)) {
945
- config = config.map((item) => transformer(item) || item);
946
- } else {
947
- config = transformer(config) || config;
948
- }
949
- return config;
950
- };
951
- return define;
952
- }
953
-
954
- // src/index.ts
955
- var src_default = mockDevServerPlugin;
956
- export {
957
- baseMiddleware,
958
- createDefineMock,
959
- src_default as default,
960
- defineMock,
961
- mockDevServerPlugin,
962
- transformMockData
963
- };
27
+ `}async function qe(t,r,e){var o;try{let n=await Te({entryPoints:[t],outfile:"out.js",write:!1,target:["node14.18","node16"],platform:"node",bundle:!0,metafile:!0,format:"esm",define:r,plugins:[B(e),N,oe,re]});return{code:n.outputFiles[0].text,deps:((o=n.metafile)==null?void 0:o.inputs)||{}}}catch(n){console.error(n)}return{code:"",deps:{}}}import{Buffer as de}from"buffer";import{parse as me}from"url";import Ue from"cookies";import He from"http-status";import*as C from"mime-types";import{pathToRegexp as ge}from"path-to-regexp";import E from"picocolors";import H from"co-body";import _e from"formidable";async function le(t,r){var n;let e=t.method.toUpperCase();if(["GET","DELETE","HEAD"].includes(e))return;let o=((n=t.headers["content-type"])==null?void 0:n.toLocaleLowerCase())||"";try{if(o.startsWith("application/json"))return await H.json(t);if(o.startsWith("application/x-www-form-urlencoded"))return await H.form(t);if(o.startsWith("text/plain"))return await H.text(t);if(o.startsWith("multipart/form-data"))return await ze(t,r)}catch(s){console.error(s)}}async function ze(t,r){let e=_e(r);return new Promise((o,n)=>{e.parse(t,(s,i,a)=>{if(s){n(s);return}o({...i,...a})})})}function ue(t,r){return x(t.headers,r.headers)&&x(t.body,r.body)&&x(t.params,r.params)&&x(t.query,r.query)&&x(t.refererQuery,r.refererQuery)}function x(t,r){if(!r)return!0;for(let e in r)if(r[e]!==t[e])return!1;return!0}function ye(t,{formidableOptions:r={},proxies:e,cookiesOptions:o}){return async function(n,s,i){let a=Date.now(),{query:c,pathname:p}=me(n.url,!0);if(!p||e.length===0||!e.some(k=>Ve(k,n.url)))return i();let u=t.mockData,l=Object.keys(u).find(k=>ge(k).test(p));if(!l)return i();let{query:L}=me(n.headers.referer||"",!0),I=await le(n,r),O=new Ue(n,s,o),P=O.get.bind(O),m=n.method.toUpperCase(),d=Ge(u[l],{pathname:p,method:m,request:{query:c,refererQuery:L,body:I,headers:n.headers,getCookie:P}});if(!d)return i();j("middleware: ",m,n.url);let y=n,h=s;y.body=I,y.query=c,y.refererQuery=L,y.params=U(d.url,p),y.getCookie=P,h.setCookie=O.set.bind(O);let{body:W,delay:K,type:Me="json",response:V,status:xe=200,statusText:we}=d;if(G(h,xe,we),await Qe(y,h,d),await Xe(y,h,d),W){try{let k=b(W)?await W(y):W;await fe(a,K),Ke(h,k,Me)}catch(k){S.error(`${E.red("[body error]")} ${n.url}
28
+ `,k),G(h,500),s.end("")}return}if(V){try{await fe(a,K),await V(y,h,i)}catch(k){S.error(`${E.red("[response error]")} ${n.url}
29
+ `,k),G(h,500),s.end("")}return}s.end("")}}function Ge(t,{pathname:r,method:e,request:o}){return t.find(n=>{if(!r||!n||!n.url||!(n.method?v(n.method)?n.method:[n.method]:["GET","POST"]).includes(e))return!1;let i=ge(n.url).test(r);if(i&&n.validator){let a=U(n.url,r);if(b(n.validator))return n.validator({params:a,...o});try{return ue({params:a,...o},n.validator)}catch(c){return S.error(`${E.red("[validator error]")} ${r}
30
+ `,c),!1}}return i})}function G(t,r=200,e){t.statusCode=r,t.statusMessage=e||Ye(r)}async function Qe(t,r,{headers:e,type:o="json"}){let n=C.contentType(o)||C.contentType(C.lookup(o)||"");if(n&&r.setHeader("Content-Type",n),r.setHeader("Cache-Control","no-cache,max-age=0"),r.setHeader("X-Mock","generate by vite:plugin-mock-dev-server"),!!e)try{let s=b(e)?await e(t):e;Object.keys(s).forEach(i=>{r.setHeader(i,s[i])})}catch(s){S.error(`${E.red("[headers error]")} ${t.url}
31
+ `,s)}}async function Xe(t,r,{cookies:e}){if(e)try{let o=b(e)?await e(t):e;Object.keys(o).forEach(n=>{let s=o[n];if(v(s)){let[i,a]=s;r.setCookie(n,i,a)}else r.setCookie(n,s)})}catch(o){S.error(`${E.red("[cookies error]")} ${t.url}
32
+ `,o)}}function Ke(t,r,e){if(ie(r))r.pipe(t);else if(de.isBuffer(r))t.end(e==="text"||e==="json"?r.toString("utf-8"):r);else{let o=typeof r=="string"?r:JSON.stringify(r);t.end(e==="buffer"?de.from(o):o)}}async function fe(t,r){if(!r||r<=0)return;let e=Date.now()-t,o=r-e;o>0&&await ae(o)}function Ve(t,r){return t[0]==="^"&&new RegExp(t).test(r)||r.startsWith(t)}function Ye(t){return He[t]||"Unknown"}import tt from"events";import q from"fs";import{createRequire as ot}from"module";import he from"path";import{pathToFileURL as rt}from"url";import ve from"chokidar";import{build as nt}from"esbuild";import st from"fast-glob";import it from"json5";import{createFilter as at,normalizePath as T}from"vite";import{parse as Ze}from"url";import et from"lodash.sortby";function ke(t){let r=[];for(let[,o]of t.entries())o&&(v(o)?r.push(...o):r.push(o));let e={};return r.filter(o=>(o.enabled||typeof o.enabled>"u")&&o.url).forEach(o=>{let{pathname:n,query:s}=Ze(o.url,!0),i=e[n]??(e[n]=[]),a={...o,url:n},c=a.validator;se(s)||(b(c)?a.validator=function(p){return x(p.query,s)&&c(p)}:c?(a.validator={...c},a.validator.query=a.validator.query?{...s,...a.validator.query}:s):a.validator={query:s}),i.push(a)}),Object.keys(e).forEach(o=>{e[o]=et(e[o],({validator:n})=>{if(!n)return 2;if(b(n))return 0;let{query:s,params:i,headers:a,body:c,refererQuery:p}=n;return 1/(F(s)+F(i)+F(a)+F(c)+F(p))})}),e}function F(t){return t?Object.keys(t).length:0}var ct=ce(import.meta.url),w=ot(ct),Q=class extends tt{constructor(e){super();this.options=e;this.moduleCache=new Map;this.moduleDeps=new Map;this.moduleType="cjs";this._mockData={};this.cwd=e.cwd||process.cwd();try{let o=D(this.cwd,["package.json"]);this.moduleType=o&&JSON.parse(o).type==="module"?"esm":"cjs"}catch{}}get mockData(){return this._mockData}async load(){let{include:e,exclude:o}=this.options,n=await st(e,{cwd:this.cwd}),s=at(e,o,{resolve:!1});this.watchMockEntry(),this.watchDeps();for(let i of n.filter(s))await this.loadMock(i);this.updateMockList(),this.on("mock:update",async i=>{s(i)&&(await this.loadMock(i),this.updateMockList(),this.emit("mock:update-end"))}),this.on("mock:unlink",async i=>{s(i)&&(this.moduleCache.delete(i),this.updateMockList(),this.emit("mock:update-end"))})}watchMockEntry(){let{include:e}=this.options,[o,...n]=e,s=ve.watch(o,{ignoreInitial:!0,cwd:this.cwd});n.length>0&&n.forEach(i=>s.add(i)),s.on("add",async i=>{i=T(i),this.emit("mock:update",i),j("watcher:add",i)}),s.on("change",async i=>{i=T(i),this.emit("mock:update",i),j("watcher:change",i)}),s.on("unlink",async i=>{i=T(i),this.emit("mock:unlink",i),j("watcher:unlink",i)}),this.mockWatcher=s}watchDeps(){let e=[];this.depsWatcher=ve.watch([],{ignoreInitial:!0,cwd:this.cwd}),this.depsWatcher.on("change",o=>{o=T(o);let n=this.moduleDeps.get(o);n&&n.forEach(s=>{this.emit("mock:update",s)})}),this.depsWatcher.on("unlink",o=>{o=T(o),this.moduleDeps.delete(o)}),this.on("update:deps",()=>{let o=[];for(let[s]of this.moduleDeps.entries())o.push(s);let n=o.filter(s=>!e.includes(s));n.length>0&&this.depsWatcher.add(n)})}close(){var e,o;(e=this.mockWatcher)==null||e.close(),(o=this.depsWatcher)==null||o.close()}updateMockList(){this._mockData=ke(this.moduleCache)}updateModuleDeps(e,o){Object.keys(o).forEach(n=>{o[n].imports.map(i=>i.path).forEach(i=>{this.moduleDeps.has(i)||this.moduleDeps.set(i,new Set),this.moduleDeps.get(i).add(e)})}),this.emit("update:deps")}async loadMock(e){e&&(Q.EXT_JSON.test(e)?await this.loadJson(e):await this.loadModule(e))}async loadJson(e){let o=await q.promises.readFile(e,"utf-8");try{let n=it.parse(o);this.moduleCache.set(e,n)}catch{}}async loadModule(e){if(!e)return;let o=!1;/\.m[jt]s$/.test(e)?o=!0:/\.c[jt]s$/.test(e)?o=!1:o=this.moduleType==="esm";let{code:n,deps:s}=await this.transformWithEsbuild(e,o);try{let i=await this.loadFromCode(e,n,o),a=i&&i.default?i.default:Object.keys(i||{}).map(c=>i[c]);this.moduleCache.set(e,a),this.updateModuleDeps(e,s)}catch(i){console.error(i)}}async loadFromCode(e,o,n){if(n){let s=`${e}.timestamp-${Date.now()}`,i=`${s}.mjs`,a=`${rt(s)}.mjs`;await q.promises.writeFile(i,o,"utf8");try{return await import(a)}finally{try{q.unlinkSync(i)}catch{}}}else{e=he.resolve(this.cwd,e);let s=he.extname(e),i=q.realpathSync(e),a=s in w.extensions?s:".js",c=w.extensions[a];w.extensions[a]=(u,l)=>{l===i?u._compile(o,l):c(u,l)},delete w.cache[w.resolve(e)];let p=w(e);return w.extensions[a]=c,p.__esModule?p:{default:p}}}async transformWithEsbuild(e,o){var n;try{let s=await nt({entryPoints:[e],outfile:"out.js",write:!1,target:["node14.18","node16"],platform:"node",bundle:!0,metafile:!0,format:o?"esm":"cjs",define:this.options.define,plugins:[B(this.options.alias),N]});return{code:s.outputFiles[0].text,deps:((n=s.metafile)==null?void 0:n.inputs)||{}}}catch{}return{code:"",deps:{}}}},$=Q;$.EXT_JSON=/\.json5?$/;async function X(t,r,e,o){let n=M(r.include),s=M(r.exclude),i={};if(t.define)for(let u in t.define){let l=t.define[u];i[u]=typeof l=="string"?l:JSON.stringify(l)}let a=new $({include:n,exclude:s,define:i,alias:t.resolve.alias});await a.load(),e==null||e.on("close",()=>a.close()),a.on("mock:update-end",()=>{r.reload&&(o==null||o.send({type:"full-reload"}))});let c=J(t.server.proxy||{}),p=M(r.prefix);return ye(a,{formidableOptions:r.formidableOptions,proxies:[...p,...c],cookiesOptions:r.cookiesOptions})}function be({prefix:t=[],include:r=["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],exclude:e=["**/node_modules/**","**/.vscode/**","**/.git/**"],reload:o=!1,formidableOptions:n={},build:s=!1,cookiesOptions:i={}}={}){let a={prefix:t,include:r,exclude:e,reload:o,cookiesOptions:i,formidableOptions:{multiples:!0,...n},build:s?Object.assign({serverPort:8080,dist:"mockServer"},typeof s=="object"?s:{}):!1},c=[lt(a)];return a.build&&c.push(pt(a)),c}function pt(t){let r={};return{name:"vite-plugin-mock-dev-server-generator",enforce:"post",apply:"build",configResolved(e){r=e,e.logger.warn("")},async buildEnd(e){e||r.command==="build"&&await pe(this,r,t)}}}function lt(t){let r={};return{name:"vite-plugin-mock-dev-server",enforce:"pre",apply:"serve",configResolved(e){r=e,e.logger.warn("")},async configureServer({middlewares:e,config:o,httpServer:n,ws:s}){let i=await X(o,t,n,s);e.use(i)},async configurePreviewServer({middlewares:e,httpServer:o}){let n=await X(r,t,o);e.use(n)}}}function Fo(t){return t}function To(t){return e=>(v(e)?e=e.map(o=>t(o)||o):e=t(e)||e,e)}var Wo=be;export{ye as baseMiddleware,To as createDefineMock,Wo as default,Fo as defineMock,be as mockDevServerPlugin,ke as transformMockData};