Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

vite-plugin-mock-dev-server

Package Overview
Dependencies
Maintainers
1
Versions
84
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

vite-plugin-mock-dev-server - npm Package Compare versions

Comparing version 1.1.13 to 1.1.14

9

dist/index.d.ts

@@ -228,8 +228,11 @@ import { Connect, Plugin, ResolvedConfig } from 'vite';

/**
* Configure response delay time, unit: `ms`
* Configure response delay time,
* If an array is passed in, it represents the range of delay time.
* unit: `ms`
*
* 配置响应延迟时间, 单位: `ms`
* 配置响应延迟时间, 如果传入的是一个数组,则代表延迟时间的范围
* 单位: `ms`
* @default 0
*/
delay?: number;
delay?: number | [number, number];
/**

@@ -236,0 +239,0 @@ * Configure response body cookies

@@ -1,4 +0,4 @@

import Ue from"fs";import X from"fs/promises";import T from"path";import{build as qe}from"esbuild";import Be from"fast-glob";import Je from"is-core-module";import{createFilter as ze,normalizePath as Ge}from"vite";var ae="vite-plugin-mock-dev-server",pe="1.1.13";var Ee=/import\.meta\.env\.(.+)/;function B(t){let o={},e=process.env.NODE_ENV||t.mode;Object.assign(o,{"process.env.NODE_ENV":JSON.stringify(e),"global.process.env.NODE_ENV":JSON.stringify(e),"globalThis.process.env.NODE_ENV":JSON.stringify(e),__vite_process_env_NODE_ENV:JSON.stringify(e)});let r={},n={};for(let c in t.define){let a=t.define[c];r[c]=typeof a=="string"?a:JSON.stringify(a);let m=c.match(Ee);m&&(n[m[1]]=`__vite__define__${r[c]}`)}let s={},i={};s["import.meta.hot"]="undefined";for(let c in t.env)s[`import.meta.env.${c}`]=JSON.stringify(t.env[c]);return Object.assign(i,{"import.meta.env":JSON.stringify({...t.env,...n}).replace(/"__vite__define__(.+?)"([,}])/g,(c,a,m)=>`${a.replace(/(^\\")|(\\"$)/g,'"')}${m}`)}),{...s,...r,...i,...o}}import le from"fs/promises";import Ie from"path";import Le from"json5";var J={name:"externalize-deps",setup(t){t.onResolve({filter:/.*/},({path:o})=>{if(o[0]!=="."&&!Ie.isAbsolute(o))return{external:!0}})}},z={name:"json5-loader",setup(t){t.onLoad({filter:/\.json5$/},async({path:o})=>{let e=await le.readFile(o,"utf-8");return{contents:`export default ${JSON.stringify(Le.parse(e))}`,loader:"js"}})}},G={name:"json-loader",setup(t){t.onLoad({filter:/\.json$/},async({path:o})=>({contents:`export default ${await le.readFile(o,"utf-8")}`,loader:"js"}))}},Q=t=>({name:"alias-plugin",setup(o){o.onResolve({filter:/.*/},async({path:e})=>{let r=t.find(({find:c})=>$e(c,e));if(!r)return null;let{find:n,replacement:s}=r;return{path:(await o.resolve(e.replace(n,s),{kind:"import-statement",resolveDir:s,namespace:"file"})).path,external:!1}})}});function $e(t,o){return t instanceof RegExp?t.test(o):o.length<t.length?!1:o===t?!0:o.startsWith(`${t}/`)}import Z from"fs";import ee from"path";import{fileURLToPath as Fe}from"url";import Te from"debug";import{match as Ne}from"path-to-regexp";import ue from"picocolors";var S=t=>Array.isArray(t),j=t=>typeof t=="function",He=t=>Object.prototype.toString.call(t)==="[object Object]",te=t=>He(t)&&Object.keys(t).length===0,Ae=t=>t!==null&&typeof t=="object"&&typeof t.pipe=="function",me=t=>Ae(t)&&t.readable!==!1&&typeof t._read=="function"&&typeof t._readableState=="object";function de(t){return new Promise(o=>setTimeout(o,t))}function fe(t){return ee.dirname(Fe(t))}var C=Te("vite:plugin-mock-dev-server"),w=t=>S(t)?t:t==null?[]:[t],R={info(...t){console.info(ue.cyan("mock-dev-server: "),...t)},error(...t){console.error(`
`,ue.cyan("mock-dev-server: "),...t,`
`)}};function H(t,o,e){for(let n of o){let s=ee.join(t,n);if(Z.existsSync(s)&&Z.statSync(s).isFile()){let i=e!=null&&e.pathOnly?s:Z.readFileSync(s,"utf-8");if(!(e!=null&&e.predicate)||e.predicate(i))return i}}let r=ee.dirname(t);if(r!==t&&(!(e!=null&&e.rootDir)||r.startsWith(e==null?void 0:e.rootDir)))return H(r,o,e)}var V=(t={})=>{let o=[],e=[];return Object.keys(t).forEach(r=>{var s,i;let n=t[r];typeof n=="string"||!n.ws&&!((s=n.target)!=null&&s.toString().startsWith("ws:"))&&!((i=n.target)!=null&&i.toString().startsWith("wss:"))?o.push(r):e.push(r)}),{httpProxies:o,wsProxies:e}};function K(t,o){return t[0]==="^"&&new RegExp(t).test(o)||o.startsWith(t)}function A(t,o){return(Ne(t,{decode:decodeURIComponent})(o)||{params:{}}).params||{}}async function ge(t,o,e){let r=w(e.include),n=w(e.exclude),s=B(o),{httpProxies:i}=V(o.server.proxy||{});i.push(...w(e.prefix));let c=w(e.wsPrefix),a={};try{let u=H(o.root,["package.json"]);u&&(a=JSON.parse(u))}catch{}let m=e.build.dist,x=await Xe(process.cwd(),r,n),v=T.join(o.root,`mock-data-${Date.now()}.js`);await X.writeFile(v,x,"utf-8");let{code:F,deps:D}=await Ye(v,s,o.resolve.alias),p=Qe(D);await X.unlink(v);let l=[{filename:T.join(m,"mock-data.js"),source:F},{filename:T.join(m,"index.js"),source:Ke(i,c,e.cookiesOptions,e.build.serverPort)},{filename:T.join(m,"package.json"),source:Ve(a,p)}];try{if(T.isAbsolute(m)){await X.rm(m,{recursive:!0}),Ue.mkdirSync(m,{recursive:!0});for(let{filename:u,source:d}of l)await X.writeFile(u,d,"utf-8")}else for(let{filename:u,source:d}of l)t.emitFile({type:"asset",fileName:u,source:d})}catch{}}function Qe(t){let o=new Set,e=[ae,"connect","cors"];return Object.keys(t).forEach(r=>{t[r].imports.filter(s=>s.external).map(s=>s.path).forEach(s=>{!e.includes(s)&&!Je(s)&&o.add(s)})}),Array.from(o)}function Ve(t,o){let{dependencies:e={},devDependencies:r={}}=t,n={...e,...r},s={name:"mock-server",type:"module",scripts:{start:"node index.js"},dependencies:{connect:"^3.7.0","vite-plugin-mock-dev-server":`^${pe}`,cors:"^2.8.5"},pnpm:{peerDependencyRules:{ignoreMissing:["vite"]}}};return o.forEach(i=>{s.dependencies[i]=n[i]||"latest"}),JSON.stringify(s,null,2)}function Ke(t,o,e={},r=8080){return`import { createServer } from 'node:http';
import Be from"fs";import Z from"fs/promises";import N from"path";import{build as Je}from"esbuild";import ze from"fast-glob";import Ge from"is-core-module";import{createFilter as Qe,normalizePath as Ve}from"vite";var le="vite-plugin-mock-dev-server",ue="1.1.14";var Ie=/import\.meta\.env\.(.+)/;function J(t){let o={},e=process.env.NODE_ENV||t.mode;Object.assign(o,{"process.env.NODE_ENV":JSON.stringify(e),"global.process.env.NODE_ENV":JSON.stringify(e),"globalThis.process.env.NODE_ENV":JSON.stringify(e),__vite_process_env_NODE_ENV:JSON.stringify(e)});let r={},n={};for(let c in t.define){let a=t.define[c];r[c]=typeof a=="string"?a:JSON.stringify(a);let m=c.match(Ie);m&&(n[m[1]]=`__vite__define__${r[c]}`)}let s={},i={};s["import.meta.hot"]="undefined";for(let c in t.env)s[`import.meta.env.${c}`]=JSON.stringify(t.env[c]);return Object.assign(i,{"import.meta.env":JSON.stringify({...t.env,...n}).replace(/"__vite__define__(.+?)"([,}])/g,(c,a,m)=>`${a.replace(/(^\\")|(\\"$)/g,'"')}${m}`)}),{...s,...r,...i,...o}}import me from"fs/promises";import Le from"path";import $e from"json5";var z={name:"externalize-deps",setup(t){t.onResolve({filter:/.*/},({path:o})=>{if(o[0]!=="."&&!Le.isAbsolute(o))return{external:!0}})}},G={name:"json5-loader",setup(t){t.onLoad({filter:/\.json5$/},async({path:o})=>{let e=await me.readFile(o,"utf-8");return{contents:`export default ${JSON.stringify($e.parse(e))}`,loader:"js"}})}},Q={name:"json-loader",setup(t){t.onLoad({filter:/\.json$/},async({path:o})=>({contents:`export default ${await me.readFile(o,"utf-8")}`,loader:"js"}))}},V=t=>({name:"alias-plugin",setup(o){o.onResolve({filter:/.*/},async({path:e})=>{let r=t.find(({find:c})=>Te(c,e));if(!r)return null;let{find:n,replacement:s}=r;return{path:(await o.resolve(e.replace(n,s),{kind:"import-statement",resolveDir:s,namespace:"file"})).path,external:!1}})}});function Te(t,o){return t instanceof RegExp?t.test(o):o.length<t.length?!1:o===t?!0:o.startsWith(`${t}/`)}import te from"fs";import oe from"path";import{parse as Fe}from"querystring";import{URL as Ne,fileURLToPath as He}from"url";import Ae from"debug";import{match as Ue}from"path-to-regexp";import de from"picocolors";var h=t=>Array.isArray(t),j=t=>typeof t=="function",K=t=>Object.prototype.toString.call(t)==="[object Object]",re=t=>K(t)&&Object.keys(t).length===0,qe=t=>t!==null&&typeof t=="object"&&typeof t.pipe=="function",fe=t=>qe(t)&&t.readable!==!1&&typeof t._read=="function"&&typeof t._readableState=="object";function ke(t){return new Promise(o=>setTimeout(o,t))}function ge(t){return oe.dirname(He(t))}var C=Ae("vite:plugin-mock-dev-server"),S=t=>h(t)?t:t==null?[]:[t],R={info(...t){console.info(de.cyan("mock-dev-server: "),...t)},error(...t){console.error(`
`,de.cyan("mock-dev-server: "),...t,`
`)}};function A(t,o,e){for(let n of o){let s=oe.join(t,n);if(te.existsSync(s)&&te.statSync(s).isFile()){let i=e!=null&&e.pathOnly?s:te.readFileSync(s,"utf-8");if(!(e!=null&&e.predicate)||e.predicate(i))return i}}let r=oe.dirname(t);if(r!==t&&(!(e!=null&&e.rootDir)||r.startsWith(e==null?void 0:e.rootDir)))return A(r,o,e)}var X=(t={})=>{let o=[],e=[];return Object.keys(t).forEach(r=>{var s,i;let n=t[r];typeof n=="string"||!n.ws&&!((s=n.target)!=null&&s.toString().startsWith("ws:"))&&!((i=n.target)!=null&&i.toString().startsWith("wss:"))?o.push(r):e.push(r)}),{httpProxies:o,wsProxies:e}};function Y(t,o){return t[0]==="^"&&new RegExp(t).test(o)||o.startsWith(t)}function U(t,o){return(Ue(t,{decode:decodeURIComponent})(o)||{params:{}}).params||{}}function W(t){let o=new Ne(t,"http://example.com"),e=decodeURIComponent(o.pathname),r=Fe(o.search.replace(/^\?/,""));return{pathname:e,query:r}}async function ye(t,o,e){let r=S(e.include),n=S(e.exclude),s=J(o),{httpProxies:i}=X(o.server.proxy||{});i.push(...S(e.prefix));let c=S(e.wsPrefix),a={};try{let u=A(o.root,["package.json"]);u&&(a=JSON.parse(u))}catch{}let m=e.build.dist,w=await Ze(process.cwd(),r,n),v=N.join(o.root,`mock-data-${Date.now()}.js`);await Z.writeFile(v,w,"utf-8");let{code:F,deps:E}=await et(v,s,o.resolve.alias),p=Ke(E);await Z.unlink(v);let l=[{filename:N.join(m,"mock-data.js"),source:F},{filename:N.join(m,"index.js"),source:Ye(i,c,e.cookiesOptions,e.build.serverPort)},{filename:N.join(m,"package.json"),source:Xe(a,p)}];try{if(N.isAbsolute(m)){await Z.rm(m,{recursive:!0}),Be.mkdirSync(m,{recursive:!0});for(let{filename:u,source:d}of l)await Z.writeFile(u,d,"utf-8")}else for(let{filename:u,source:d}of l)t.emitFile({type:"asset",fileName:u,source:d})}catch{}}function Ke(t){let o=new Set,e=[le,"connect","cors"];return Object.keys(t).forEach(r=>{t[r].imports.filter(s=>s.external).map(s=>s.path).forEach(s=>{!e.includes(s)&&!Ge(s)&&o.add(s)})}),Array.from(o)}function Xe(t,o){let{dependencies:e={},devDependencies:r={}}=t,n={...e,...r},s={name:"mock-server",type:"module",scripts:{start:"node index.js"},dependencies:{connect:"^3.7.0","vite-plugin-mock-dev-server":`^${ue}`,cors:"^2.8.5"},pnpm:{peerDependencyRules:{ignoreMissing:["vite"]}}};return o.forEach(i=>{s.dependencies[i]=n[i]||"latest"}),JSON.stringify(s,null,2)}function Ye(t,o,e={},r=8080){return`import { createServer } from 'node:http';
import connect from 'connect';

@@ -27,3 +27,3 @@ import corsMiddleware from 'cors';

console.log('listen: http://localhost:${r}');
`}async function Xe(t,o,e){let r=await Be(o,{cwd:t}),n=ze(o,e,{resolve:!1}),s=r.filter(n),i="",c="";return s.forEach((a,m)=>{let x=Ge(T.join(t,a));i+=`import * as m${m} from '${x}';
`}async function Ze(t,o,e){let r=await ze(o,{cwd:t}),n=Qe(o,e,{resolve:!1}),s=r.filter(n),i="",c="";return s.forEach((a,m)=>{let w=Ve(N.join(t,a));i+=`import * as m${m} from '${w}';
`,c+=`m${m}, `}),`import { transformMockData } from 'vite-plugin-mock-dev-server';

@@ -46,8 +46,8 @@ ${i}

});
export default transformMockData(mockList);`}async function Ye(t,o,e){var r;try{let n=await qe({entryPoints:[t],outfile:"out.js",write:!1,target:["node14.18","node16"],platform:"node",bundle:!0,metafile:!0,format:"esm",define:o,plugins:[Q(e),J,z,G]});return{code:n.outputFiles[0].text,deps:((r=n.metafile)==null?void 0:r.inputs)||{}}}catch(n){console.error(n)}return{code:"",deps:{}}}import{Buffer as ve}from"buffer";import{parse as he}from"url";import tt from"cookies";import ot from"http-status";import rt from"lodash.sortby";import*as U from"mime-types";import{pathToRegexp as be}from"path-to-regexp";import W from"picocolors";import oe from"co-body";import Ze from"formidable";async function ke(t,o){var n;let e=t.method.toUpperCase();if(["GET","DELETE","HEAD"].includes(e))return;let r=((n=t.headers["content-type"])==null?void 0:n.toLocaleLowerCase())||"";try{if(r.startsWith("application/json"))return await oe.json(t);if(r.startsWith("application/x-www-form-urlencoded"))return await oe.form(t);if(r.startsWith("text/plain"))return await oe.text(t);if(r.startsWith("multipart/form-data"))return await et(t,o)}catch(s){console.error(s)}}async function et(t,o){let e=Ze(o);return new Promise((r,n)=>{e.parse(t,(s,i,c)=>{if(s){n(s);return}r({...i,...c})})})}function ye(t,o){return L(t.headers,o.headers)&&L(t.body,o.body)&&L(t.params,o.params)&&L(t.query,o.query)&&L(t.refererQuery,o.refererQuery)}function L(t,o){if(!o)return!0;for(let e in o)if(o[e]!==t[e])return!1;return!0}var nt=/:/g;function xe(t,{formidableOptions:o={},proxies:e,cookiesOptions:r}){return async function(n,s,i){let c=Date.now(),{query:a,pathname:m}=he(n.url,!0);if(!m||e.length===0||!e.some(y=>K(y,n.url)))return i();let x=t.mockData,v=rt(Object.keys(x),y=>{var N;return((N=y.match(nt))==null?void 0:N.length)||0}).find(y=>be(y).test(m));if(!v)return i();let{query:F}=he(n.headers.referer||"",!0),D=await ke(n,o),p=new tt(n,s,r),l=p.get.bind(p),u=n.method.toUpperCase(),d=st(x[v],{pathname:m,method:u,request:{query:a,refererQuery:F,body:D,headers:n.headers,getCookie:l}});if(!d)return i();C("middleware: ",u,n.url);let f=n,g=s;f.body=D,f.query=a,f.refererQuery=F,f.params=A(d.url,m),f.getCookie=l,g.setCookie=p.set.bind(p);let{body:k,delay:O,type:P="json",response:_,status:E=200,statusText:I}=d;if(re(g,E,I),await it(f,g,d),await ct(f,g,d),k){try{let y=j(k)?await k(f):k;await Me(c,O),at(g,y,P)}catch(y){R.error(`${W.red("[body error]")} ${n.url}
`,`file: ${W.cyan(d.__filepath__)}`,y),re(g,500),s.end("")}return}if(_){try{await Me(c,O),await _(f,g,i)}catch(y){R.error(`${W.red("[response error]")} ${n.url}
`,`file: ${W.cyan(d.__filepath__)}`,y),re(g,500),s.end("")}return}s.end("")}}function st(t,{pathname:o,method:e,request:r}){return t.find(n=>{if(!o||!n||!n.url||n.ws===!0||!(n.method?S(n.method)?n.method:[n.method]:["GET","POST"]).includes(e))return!1;let i=be(n.url).test(o);if(i&&n.validator){let c=A(n.url,o);if(j(n.validator))return n.validator({params:c,...r});try{return ye({params:c,...r},n.validator)}catch(a){return R.error(`${W.red("[validator error]")} ${o}
`,`file: ${W.cyan(n.__filepath__)}`,a),!1}}return i})}function re(t,o=200,e){t.statusCode=o,t.statusMessage=e||pt(o)}async function it(t,o,e){let{headers:r,type:n="json"}=e,s=e.__filepath__,i=U.contentType(n)||U.contentType(U.lookup(n)||"");if(i&&o.setHeader("Content-Type",i),o.setHeader("Cache-Control","no-cache,max-age=0"),o.setHeader("X-Mock-Power-By","vite-plugin-mock-dev-server"),o.setHeader("X-File-Path",s),!!r)try{let c=j(r)?await r(t):r;Object.keys(c).forEach(a=>{o.setHeader(a,c[a])})}catch(c){R.error(`${W.red("[headers error]")} ${t.url}
`,c)}}async function ct(t,o,{cookies:e}){if(e)try{let r=j(e)?await e(t):e;Object.keys(r).forEach(n=>{let s=r[n];if(S(s)){let[i,c]=s;o.setCookie(n,i,c)}else o.setCookie(n,s)})}catch(r){R.error(`${W.red("[cookies error]")} ${t.url}
`,r)}}function at(t,o,e){if(me(o))o.pipe(t);else if(ve.isBuffer(o))t.end(e==="text"||e==="json"?o.toString("utf-8"):o);else{let r=typeof o=="string"?o:JSON.stringify(o);t.end(e==="buffer"?ve.from(r):r)}}async function Me(t,o){if(!o||o<=0)return;let e=Date.now()-t,r=o-e;r>0&&await de(r)}function pt(t){return ot[t]||"Unknown"}import dt from"events";import ne from"fs";import{createRequire as ft}from"module";import Se from"path";import{pathToFileURL as gt}from"url";import Oe from"chokidar";import{build as kt}from"esbuild";import yt from"fast-glob";import{createFilter as vt,normalizePath as q}from"vite";import{parse as lt}from"url";import ut from"lodash.sortby";function we(t){let o=[];for(let[,r]of t.entries())r&&(S(r)?o.push(...r):o.push(r));let e={};return o.filter(r=>(r.enabled||typeof r.enabled>"u")&&r.url).forEach(r=>{let{pathname:n,query:s}=lt(r.url,!0),i=e[n]??(e[n]=[]),c={...r,url:n};if(c.ws!==!0){let a=c.validator;te(s)||(j(a)?c.validator=function(m){return L(m.query,s)&&a(m)}:a?(c.validator={...a},c.validator.query=c.validator.query?{...s,...c.validator.query}:s):c.validator={query:s})}i.push(c)}),Object.keys(e).forEach(r=>{e[r]=ut(e[r],n=>{if(n.ws===!0)return 0;let{validator:s}=n;return!s||te(s)?2:j(s)?0:1/Object.keys(s).reduce((c,a)=>c+mt(s[a]),0)})}),e}function mt(t){return t?Object.keys(t).length:0}var ht=fe(import.meta.url),$=ft(ht),Y=class extends dt{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 r=H(this.cwd,["package.json"]);this.moduleType=r&&JSON.parse(r).type==="module"?"esm":"cjs"}catch{}}get mockData(){return this._mockData}load(){let{include:e,exclude:r}=this.options,n=vt(e,r,{resolve:!1});yt(e,{cwd:this.cwd}).then(i=>Promise.all(i.filter(n).map(c=>this.loadMock(c)))).then(()=>this.updateMockList()),this.watchMockEntry(),this.watchDeps();let s=null;this.on("mock:update",async i=>{n(i)&&(await this.loadMock(i),s&&clearImmediate(s),s=setImmediate(()=>{this.updateMockList(),this.emit("mock:update-end",i),s=null}))}),this.on("mock:unlink",async i=>{n(i)&&(this.moduleCache.delete(i),this.updateMockList(),this.emit("mock:update-end",i))})}watchMockEntry(){let{include:e}=this.options,[r,...n]=e,s=Oe.watch(r,{ignoreInitial:!0,cwd:this.cwd});n.length>0&&n.forEach(i=>s.add(i)),s.on("add",async i=>{i=q(i),this.emit("mock:update",i),C("watcher:add",i)}),s.on("change",async i=>{i=q(i),this.emit("mock:update",i),C("watcher:change",i)}),s.on("unlink",async i=>{i=q(i),this.emit("mock:unlink",i),C("watcher:unlink",i)}),this.mockWatcher=s}watchDeps(){let e=[];this.depsWatcher=Oe.watch([],{ignoreInitial:!0,cwd:this.cwd}),this.depsWatcher.on("change",r=>{r=q(r);let n=this.moduleDeps.get(r);n&&n.forEach(s=>{this.emit("mock:update",s)})}),this.depsWatcher.on("unlink",r=>{r=q(r),this.moduleDeps.delete(r)}),this.on("update:deps",()=>{let r=[];for(let[s]of this.moduleDeps.entries())r.push(s);let n=r.filter(s=>!e.includes(s));n.length>0&&this.depsWatcher.add(n)})}close(){var e,r;(e=this.mockWatcher)==null||e.close(),(r=this.depsWatcher)==null||r.close()}updateMockList(){this._mockData=we(this.moduleCache)}updateModuleDeps(e,r){Object.keys(r).forEach(n=>{r[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){if(!e)return;let r=!1;/\.m[jt]s$/.test(e)?r=!0:/\.c[jt]s$/.test(e)?r=!1:r=this.moduleType==="esm";let{code:n,deps:s}=await this.transformWithEsbuild(e,r);try{let i=await this.loadFromCode(e,n,r)||{},c;i.default?c=i.default:(c=[],Object.keys(i).forEach(a=>{S(i[a])?c.push(...i[a]):c.push(i[a])})),S(c)?c.forEach(a=>a.__filepath__=e):c.__filepath__=e,this.moduleCache.set(e,c),this.updateModuleDeps(e,s)}catch(i){console.error(i)}}async loadFromCode(e,r,n){if(n){let s=`${e}.timestamp-${Date.now()}`,i=`${s}.mjs`,c=`${gt(s)}.mjs`;await ne.promises.writeFile(i,r,"utf8");try{return await import(c)}finally{try{ne.unlinkSync(i)}catch{}}}else{e=Se.resolve(this.cwd,e);let s=Se.extname(e),i=ne.realpathSync(e),c=s in $.extensions?s:".js",a=$.extensions[c];$.extensions[c]=(x,v)=>{v===i?x._compile(r,v):a(x,v)},delete $.cache[$.resolve(e)];let m=$(e);return $.extensions[c]=a,m.__esModule?m:{default:m}}}async transformWithEsbuild(e,r){var n;try{let s=await kt({entryPoints:[e],outfile:"out.js",write:!1,target:["node14.18","node16"],platform:"node",bundle:!0,metafile:!0,format:r?"esm":"cjs",define:this.options.define,plugins:[Q(this.options.alias),J,G,z]});return{code:s.outputFiles[0].text,deps:((n=s.metafile)==null?void 0:n.inputs)||{}}}catch(s){console.error(s)}return{code:"",deps:{}}}};import{parse as Pe}from"url";import Mt from"cookies";import{pathToRegexp as je}from"path-to-regexp";import bt from"picocolors";import{WebSocketServer as xt}from"ws";function Re(t,o,e,r){var D;let n=new Map,s=new Map,i=new WeakMap,c=p=>{let l=s.get(p);return!l&&s.set(p,l=new Map),l},a=(p,l)=>{let u=p.get(l);return!u&&p.set(l,u=new xt({noServer:!0})),u},m=(p,l)=>{let u=n.get(p);!u&&n.set(p,u=new Set),u.add(l)},x=(p,l,u,d,f,g)=>{var k;try{(k=u.setup)==null||k.call(u,l,d),l.on("close",()=>p.delete(f))}catch(O){R.error(`${bt.red("[websocket server error]")} ${g}
`,O)}},v=(p,l,u,d)=>{p.emit("connection",l,u),l.on("close",()=>{let f=d.findIndex(g=>g.ws===l);f!==-1&&d.splice(f,1)})},F=(p,l,u,d,f)=>{let{cleanupList:g,connectionList:k,context:O}=i.get(l);Ce(g),k.forEach(({ws:P})=>P.removeAllListeners()),l.removeAllListeners(),x(p,l,u,O,d,f),k.forEach(({ws:P,req:_})=>v(l,P,_,k))};(D=t.on)==null||D.call(t,"mock:update-end",p=>{if(!n.has(p))return;let l=n.get(p);if(l)for(let u of l.values())for(let d of t.mockData[u]){if(!d.ws||d.__filepath__!==p)return;let f=c(u);for(let[g,k]of f.entries())F(f,k,d,g,p)}}),o==null||o.on("upgrade",(p,l,u)=>{let{pathname:d,query:f}=Pe(p.url,!0);if(!d||e.length===0||!e.some(h=>K(h,p.url)))return;let g=t.mockData,k=Object.keys(g).find(h=>je(h).test(d));if(!k)return;let O=g[k].find(h=>h.url&&h.ws&&je(h.url).test(d));if(!O)return;let P=O.__filepath__;m(P,k);let _=c(k),E=a(_,d),I=i.get(E);if(!I){let h=[],ie={onCleanup:_e=>h.push(_e)};I={cleanupList:h,context:ie,connectionList:[]},i.set(E,I),x(_,E,O,ie,d,P)}let y=p,N=new Mt(p,p,r),{query:De}=Pe(p.headers.referer||"",!0);y.query=f,y.refererQuery=De,y.params=A(k,d),y.getCookie=N.get.bind(N),E.handleUpgrade(y,l,u,h=>{C(`websocket-mock: ${p.url} connected`),I.connectionList.push({req:y,ws:h}),v(E,h,y,I.connectionList)})}),o==null||o.on("close",()=>{for(let p of s.values()){for(let l of p.values()){let u=i.get(l);Ce(u.cleanupList),l.close()}p.clear()}s.clear(),n.clear()})}function Ce(t){let o;for(;o=t.shift();)o==null||o()}async function se(t,o,e,r){let n=new Y({include:w(o.include),exclude:w(o.exclude),define:B(t),alias:t.resolve.alias});n.load(),n.on("mock:update-end",()=>{o.reload&&(r==null||r.send({type:"full-reload"}))}),e==null||e.on("close",()=>n.close());let{httpProxies:s}=V(t.server.proxy||{}),i=w(o.prefix);return Re(n,e,w(o.wsPrefix),o.cookiesOptions),xe(n,{formidableOptions:o.formidableOptions,proxies:[...i,...s],cookiesOptions:o.cookiesOptions})}function We({prefix:t=[],wsPrefix:o=[],include:e=["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],exclude:r=["**/node_modules/**","**/.vscode/**","**/.git/**"],reload:n=!1,formidableOptions:s={},build:i=!1,cookiesOptions:c={}}={}){let a={prefix:t,wsPrefix:o,include:e,exclude:r,reload:n,cookiesOptions:c,formidableOptions:{multiples:!0,...s},build:i?Object.assign({serverPort:8080,dist:"mockServer"},typeof i=="object"?i:{}):!1},m=[St(a)];return a.build&&m.push(wt(a)),m}function wt(t){let o={};return{name:"vite-plugin-mock-dev-server-generator",enforce:"post",apply:"build",configResolved(e){o=e,e.logger.warn("")},async buildEnd(e){e||o.command==="build"&&await ge(this,o,t)}}}function St(t){let o={};return{name:"vite-plugin-mock-dev-server",enforce:"pre",apply:"serve",config(e){var s;let r=w(t.wsPrefix);if(r.length===0||!((s=e.server)!=null&&s.proxy)||Object.keys(e.server.proxy).length===0)return;let n={};Object.keys(e.server.proxy).forEach(i=>{r.includes(i)||(n[i]=e.server.proxy[i])}),e.server.proxy=n},configResolved(e){o=e,e.logger.warn("")},async configureServer({middlewares:e,config:r,httpServer:n,ws:s}){let i=await se(r,t,n,s);e.use(i)},async configurePreviewServer({middlewares:e,httpServer:r}){let n=await se(o,t,r);e.use(n)}}}function ir(t){return t}function cr(t){return e=>(S(e)?e=e.map(r=>t(r)||r):e=t(e)||e,e)}var ur=We;export{xe as baseMiddleware,cr as createDefineMock,ur as default,ir as defineMock,We as mockDevServerPlugin,Re as mockWebSocket,we as transformMockData};
export default transformMockData(mockList);`}async function et(t,o,e){var r;try{let n=await Je({entryPoints:[t],outfile:"out.js",write:!1,target:["node14.18","node16"],platform:"node",bundle:!0,metafile:!0,format:"esm",define:o,plugins:[V(e),z,G,Q]});return{code:n.outputFiles[0].text,deps:((r=n.metafile)==null?void 0:r.inputs)||{}}}catch(n){console.error(n)}return{code:"",deps:{}}}import{Buffer as be}from"buffer";import rt from"cookies";import nt from"http-status";import st from"lodash.sortby";import*as q from"mime-types";import{pathToRegexp as we}from"path-to-regexp";import _ from"picocolors";import ne from"co-body";import tt from"formidable";async function he(t,o){var n;let e=t.method.toUpperCase();if(["GET","DELETE","HEAD"].includes(e))return;let r=((n=t.headers["content-type"])==null?void 0:n.toLocaleLowerCase())||"";try{if(r.startsWith("application/json"))return await ne.json(t);if(r.startsWith("application/x-www-form-urlencoded"))return await ne.form(t);if(r.startsWith("text/plain"))return await ne.text(t);if(r.startsWith("multipart/form-data"))return await ot(t,o)}catch(s){console.error(s)}}async function ot(t,o){let e=tt(o);return new Promise((r,n)=>{e.parse(t,(s,i,c)=>{if(s){n(s);return}r({...i,...c})})})}function ve(t,o){return D(t.headers,o.headers)&&D(t.body,o.body)&&D(t.params,o.params)&&D(t.query,o.query)&&D(t.refererQuery,o.refererQuery)}function D(t,o){if(!o)return!0;for(let e in o)if(!Me(t[e],o[e]))return!1;return!0}function Me(t,o){if(h(t)&&h(o)){let e=new Set;return o.every(r=>t.some((n,s)=>{if(e.has(s))return!1;let i=Me(n,r);return i&&e.add(s),i}))}return K(t)&&K(o)?D(t,o):t===o}var it=/:/g;function Se(t,{formidableOptions:o={},proxies:e,cookiesOptions:r}){return async function(n,s,i){let c=Date.now(),{query:a,pathname:m}=W(n.url);if(!m||e.length===0||!e.some(y=>Y(y,n.url)))return i();let w=t.mockData,v=st(Object.keys(w),y=>{var H;return((H=y.match(it))==null?void 0:H.length)||0}).find(y=>we(y).test(m));if(!v)return i();let{query:F}=W(n.headers.referer||""),E=await he(n,o),p=new rt(n,s,r),l=p.get.bind(p),u=n.method.toUpperCase(),d=ct(w[v],{pathname:m,method:u,request:{query:a,refererQuery:F,body:E,headers:n.headers,getCookie:l}});if(!d)return i();C("middleware: ",u,n.url);let f=n,k=s;f.body=E,f.query=a,f.refererQuery=F,f.params=U(d.url,m),f.getCookie=l,k.setCookie=p.set.bind(p);let{body:g,delay:O,type:P="json",response:I,status:L=200,statusText:$}=d;if(se(k,L,$),await at(f,k,d),await pt(f,k,d),g){try{let y=j(g)?await g(f):g;await xe(c,O),lt(k,y,P)}catch(y){R.error(`${_.red("[body error]")} ${n.url}
`,`file: ${_.cyan(d.__filepath__)}`,y),se(k,500),s.end("")}return}if(I){try{await xe(c,O),await I(f,k,i)}catch(y){R.error(`${_.red("[response error]")} ${n.url}
`,`file: ${_.cyan(d.__filepath__)}`,y),se(k,500),s.end("")}return}s.end("")}}function ct(t,{pathname:o,method:e,request:r}){return t.find(n=>{if(!o||!n||!n.url||n.ws===!0||!(n.method?h(n.method)?n.method:[n.method]:["GET","POST"]).includes(e))return!1;let i=we(n.url).test(o);if(i&&n.validator){let c=U(n.url,o);if(j(n.validator))return n.validator({params:c,...r});try{return ve({params:c,...r},n.validator)}catch(a){return R.error(`${_.red("[validator error]")} ${o}
`,`file: ${_.cyan(n.__filepath__)}`,a),!1}}return i})}function se(t,o=200,e){t.statusCode=o,t.statusMessage=e||ut(o)}async function at(t,o,e){let{headers:r,type:n="json"}=e,s=e.__filepath__,i=q.contentType(n)||q.contentType(q.lookup(n)||"");if(i&&o.setHeader("Content-Type",i),o.setHeader("Cache-Control","no-cache,max-age=0"),o.setHeader("X-Mock-Power-By","vite-plugin-mock-dev-server"),o.setHeader("X-File-Path",s),!!r)try{let c=j(r)?await r(t):r;Object.keys(c).forEach(a=>{o.setHeader(a,c[a])})}catch(c){R.error(`${_.red("[headers error]")} ${t.url}
`,c)}}async function pt(t,o,{cookies:e}){if(e)try{let r=j(e)?await e(t):e;Object.keys(r).forEach(n=>{let s=r[n];if(h(s)){let[i,c]=s;o.setCookie(n,i,c)}else o.setCookie(n,s)})}catch(r){R.error(`${_.red("[cookies error]")} ${t.url}
`,r)}}function lt(t,o,e){if(fe(o))o.pipe(t);else if(be.isBuffer(o))t.end(e==="text"||e==="json"?o.toString("utf-8"):o);else{let r=typeof o=="string"?o:JSON.stringify(o);t.end(e==="buffer"?be.from(r):r)}}async function xe(t,o){if(!o||typeof o=="number"&&o<=0||h(o)&&o.length!==2)return;let e=0;if(h(o)){let[r,n]=o;e=Math.floor(Math.random()*(n-r+1))+r}else e=o-(Date.now()-t);e>0&&await ke(e)}function ut(t){return nt[t]||"Unknown"}import ft from"events";import ie from"fs";import{createRequire as kt}from"module";import Pe from"path";import{pathToFileURL as gt}from"url";import je from"chokidar";import{build as yt}from"esbuild";import ht from"fast-glob";import{createFilter as vt,normalizePath as B}from"vite";import mt from"lodash.sortby";function Oe(t){let o=[];for(let[,r]of t.entries())r&&(h(r)?o.push(...r):o.push(r));let e={};return o.filter(r=>(r.enabled||typeof r.enabled>"u")&&r.url).forEach(r=>{let{pathname:n,query:s}=W(r.url),i=e[n]??(e[n]=[]),c={...r,url:n};if(c.ws!==!0){let a=c.validator;re(s)||(j(a)?c.validator=function(m){return D(m.query,s)&&a(m)}:a?(c.validator={...a},c.validator.query=c.validator.query?{...s,...c.validator.query}:s):c.validator={query:s})}i.push(c)}),Object.keys(e).forEach(r=>{e[r]=mt(e[r],n=>{if(n.ws===!0)return 0;let{validator:s}=n;return!s||re(s)?2:j(s)?0:1/Object.keys(s).reduce((c,a)=>c+dt(s[a]),0)})}),e}function dt(t){return t?Object.keys(t).length:0}var Mt=ge(import.meta.url),T=kt(Mt),ee=class extends ft{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 r=A(this.cwd,["package.json"]);this.moduleType=r&&JSON.parse(r).type==="module"?"esm":"cjs"}catch{}}get mockData(){return this._mockData}load(){let{include:e,exclude:r}=this.options,n=vt(e,r,{resolve:!1});ht(e,{cwd:this.cwd}).then(i=>Promise.all(i.filter(n).map(c=>this.loadMock(c)))).then(()=>this.updateMockList()),this.watchMockEntry(),this.watchDeps();let s=null;this.on("mock:update",async i=>{n(i)&&(await this.loadMock(i),s&&clearImmediate(s),s=setImmediate(()=>{this.updateMockList(),this.emit("mock:update-end",i),s=null}))}),this.on("mock:unlink",async i=>{n(i)&&(this.moduleCache.delete(i),this.updateMockList(),this.emit("mock:update-end",i))})}watchMockEntry(){let{include:e}=this.options,[r,...n]=e,s=je.watch(r,{ignoreInitial:!0,cwd:this.cwd});n.length>0&&n.forEach(i=>s.add(i)),s.on("add",async i=>{i=B(i),this.emit("mock:update",i),C("watcher:add",i)}),s.on("change",async i=>{i=B(i),this.emit("mock:update",i),C("watcher:change",i)}),s.on("unlink",async i=>{i=B(i),this.emit("mock:unlink",i),C("watcher:unlink",i)}),this.mockWatcher=s}watchDeps(){let e=[];this.depsWatcher=je.watch([],{ignoreInitial:!0,cwd:this.cwd}),this.depsWatcher.on("change",r=>{r=B(r);let n=this.moduleDeps.get(r);n&&n.forEach(s=>{this.emit("mock:update",s)})}),this.depsWatcher.on("unlink",r=>{r=B(r),this.moduleDeps.delete(r)}),this.on("update:deps",()=>{let r=[];for(let[s]of this.moduleDeps.entries())r.push(s);let n=r.filter(s=>!e.includes(s));n.length>0&&this.depsWatcher.add(n)})}close(){var e,r;(e=this.mockWatcher)==null||e.close(),(r=this.depsWatcher)==null||r.close()}updateMockList(){this._mockData=Oe(this.moduleCache)}updateModuleDeps(e,r){Object.keys(r).forEach(n=>{r[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){if(!e)return;let r=!1;/\.m[jt]s$/.test(e)?r=!0:/\.c[jt]s$/.test(e)?r=!1:r=this.moduleType==="esm";let{code:n,deps:s}=await this.transformWithEsbuild(e,r);try{let i=await this.loadFromCode(e,n,r)||{},c;i.default?c=i.default:(c=[],Object.keys(i).forEach(a=>{h(i[a])?c.push(...i[a]):c.push(i[a])})),h(c)?c.forEach(a=>a.__filepath__=e):c.__filepath__=e,this.moduleCache.set(e,c),this.updateModuleDeps(e,s)}catch(i){console.error(i)}}async loadFromCode(e,r,n){if(n){let s=`${e}.timestamp-${Date.now()}`,i=`${s}.mjs`,c=`${gt(s)}.mjs`;await ie.promises.writeFile(i,r,"utf8");try{return await import(c)}finally{try{ie.unlinkSync(i)}catch{}}}else{e=Pe.resolve(this.cwd,e);let s=Pe.extname(e),i=ie.realpathSync(e),c=s in T.extensions?s:".js",a=T.extensions[c];T.extensions[c]=(w,v)=>{v===i?w._compile(r,v):a(w,v)},delete T.cache[T.resolve(e)];let m=T(e);return T.extensions[c]=a,m.__esModule?m:{default:m}}}async transformWithEsbuild(e,r){var n;try{let s=await yt({entryPoints:[e],outfile:"out.js",write:!1,target:["node14.18","node16"],platform:"node",bundle:!0,metafile:!0,format:r?"esm":"cjs",define:this.options.define,plugins:[V(this.options.alias),z,Q,G]});return{code:s.outputFiles[0].text,deps:((n=s.metafile)==null?void 0:n.inputs)||{}}}catch(s){console.error(s)}return{code:"",deps:{}}}};import bt from"cookies";import{pathToRegexp as Ce}from"path-to-regexp";import xt from"picocolors";import{WebSocketServer as wt}from"ws";function We(t,o,e,r){var E;let n=new Map,s=new Map,i=new WeakMap,c=p=>{let l=s.get(p);return!l&&s.set(p,l=new Map),l},a=(p,l)=>{let u=p.get(l);return!u&&p.set(l,u=new wt({noServer:!0})),u},m=(p,l)=>{let u=n.get(p);!u&&n.set(p,u=new Set),u.add(l)},w=(p,l,u,d,f,k)=>{var g;try{(g=u.setup)==null||g.call(u,l,d),l.on("close",()=>p.delete(f))}catch(O){R.error(`${xt.red("[websocket server error]")} ${k}
`,O)}},v=(p,l,u,d)=>{p.emit("connection",l,u),l.on("close",()=>{let f=d.findIndex(k=>k.ws===l);f!==-1&&d.splice(f,1)})},F=(p,l,u,d,f)=>{let{cleanupList:k,connectionList:g,context:O}=i.get(l);Re(k),g.forEach(({ws:P})=>P.removeAllListeners()),l.removeAllListeners(),w(p,l,u,O,d,f),g.forEach(({ws:P,req:I})=>v(l,P,I,g))};(E=t.on)==null||E.call(t,"mock:update-end",p=>{if(!n.has(p))return;let l=n.get(p);if(l)for(let u of l.values())for(let d of t.mockData[u]){if(!d.ws||d.__filepath__!==p)return;let f=c(u);for(let[k,g]of f.entries())F(f,g,d,k,p)}}),o==null||o.on("upgrade",(p,l,u)=>{let{pathname:d,query:f}=W(p.url);if(!d||e.length===0||!e.some(M=>Y(M,p.url)))return;let k=t.mockData,g=Object.keys(k).find(M=>Ce(M).test(d));if(!g)return;let O=k[g].find(M=>M.url&&M.ws&&Ce(M.url).test(d));if(!O)return;let P=O.__filepath__;m(P,g);let I=c(g),L=a(I,d),$=i.get(L);if(!$){let M=[],ae={onCleanup:Ee=>M.push(Ee)};$={cleanupList:M,context:ae,connectionList:[]},i.set(L,$),w(I,L,O,ae,d,P)}let y=p,H=new bt(p,p,r),{query:_e}=W(p.headers.referer||"");y.query=f,y.refererQuery=_e,y.params=U(g,d),y.getCookie=H.get.bind(H),L.handleUpgrade(y,l,u,M=>{C(`websocket-mock: ${p.url} connected`),$.connectionList.push({req:y,ws:M}),v(L,M,y,$.connectionList)})}),o==null||o.on("close",()=>{for(let p of s.values()){for(let l of p.values()){let u=i.get(l);Re(u.cleanupList),l.close()}p.clear()}s.clear(),n.clear()})}function Re(t){let o;for(;o=t.shift();)o==null||o()}async function ce(t,o,e,r){let n=new ee({include:S(o.include),exclude:S(o.exclude),define:J(t),alias:t.resolve.alias});n.load(),n.on("mock:update-end",()=>{o.reload&&(r==null||r.send({type:"full-reload"}))}),e==null||e.on("close",()=>n.close());let{httpProxies:s}=X(t.server.proxy||{}),i=S(o.prefix);return We(n,e,S(o.wsPrefix),o.cookiesOptions),Se(n,{formidableOptions:o.formidableOptions,proxies:[...i,...s],cookiesOptions:o.cookiesOptions})}function De({prefix:t=[],wsPrefix:o=[],include:e=["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],exclude:r=["**/node_modules/**","**/.vscode/**","**/.git/**"],reload:n=!1,formidableOptions:s={},build:i=!1,cookiesOptions:c={}}={}){let a={prefix:t,wsPrefix:o,include:e,exclude:r,reload:n,cookiesOptions:c,formidableOptions:{multiples:!0,...s},build:i?Object.assign({serverPort:8080,dist:"mockServer"},typeof i=="object"?i:{}):!1},m=[Ot(a)];return a.build&&m.push(St(a)),m}function St(t){let o={};return{name:"vite-plugin-mock-dev-server-generator",enforce:"post",apply:"build",configResolved(e){o=e,e.logger.warn("")},async buildEnd(e){e||o.command==="build"&&await ye(this,o,t)}}}function Ot(t){let o={};return{name:"vite-plugin-mock-dev-server",enforce:"pre",apply:"serve",config(e){var s;let r=S(t.wsPrefix);if(r.length===0||!((s=e.server)!=null&&s.proxy)||Object.keys(e.server.proxy).length===0)return;let n={};Object.keys(e.server.proxy).forEach(i=>{r.includes(i)||(n[i]=e.server.proxy[i])}),e.server.proxy=n},configResolved(e){o=e,e.logger.warn("")},async configureServer({middlewares:e,config:r,httpServer:n,ws:s}){let i=await ce(r,t,n,s);e.use(i)},async configurePreviewServer({middlewares:e,httpServer:r}){let n=await ce(o,t,r);e.use(n)}}}function ir(t){return t}function cr(t){return e=>(h(e)?e=e.map(r=>t(r)||r):e=t(e)||e,e)}var ur=De;export{Se as baseMiddleware,cr as createDefineMock,ur as default,ir as defineMock,De as mockDevServerPlugin,We as mockWebSocket,Oe as transformMockData};
{
"name": "vite-plugin-mock-dev-server",
"version": "1.1.13",
"version": "1.1.14",
"keywords": [

@@ -21,5 +21,7 @@ "vite",

".": {
"types": "./dist/index.d.ts",
"require": "./dist/index.cjs",
"import": "./dist/index.js"
}
},
"./package.json": "./package.json"
},

@@ -38,7 +40,7 @@ "main": "dist/index.cjs",

"debug": "^4.3.4",
"esbuild": "^0.17.18",
"esbuild": "^0.17.19",
"fast-glob": "^3.2.12",
"formidable": "^2.1.1",
"http-status": "^1.6.2",
"is-core-module": "^2.12.0",
"is-core-module": "^2.12.1",
"json5": "^2.2.3",

@@ -52,16 +54,16 @@ "lodash.sortby": "^4.7.0",

"devDependencies": {
"@pengzhanbo/eslint-config": "^0.3.11",
"@pengzhanbo/prettier-config": "^0.3.11",
"@pengzhanbo/eslint-config": "^0.3.12",
"@pengzhanbo/prettier-config": "^0.3.12",
"@types/co-body": "^6.1.0",
"@types/cookies": "^0.7.7",
"@types/debug": "^4.1.7",
"@types/formidable": "^2.0.5",
"@types/formidable": "^2.0.6",
"@types/is-core-module": "^2.2.0",
"@types/lodash.sortby": "^4.7.7",
"@types/mime-types": "^2.1.1",
"@types/node": "^18.16.5",
"@types/node": "^18.16.13",
"@types/ws": "^8.5.4",
"bumpp": "^9.1.0",
"conventional-changelog-cli": "^2.2.2",
"eslint": "^8.40.0",
"eslint": "^8.41.0",
"mockjs": "^1.1.0",

@@ -71,4 +73,4 @@ "prettier": "^2.8.8",

"typescript": "^5.0.4",
"vite": "^4.3.5",
"vitepress": "1.0.0-alpha.75"
"vite": "^4.3.8",
"vitepress": "1.0.0-alpha.76"
},

@@ -78,21 +80,6 @@ "peerDependencies": {

},
"packageManager": "pnpm@8.3.1",
"packageManager": "pnpm@8.5.0",
"engines": {
"node": "^14.18.0 || >=16"
},
"tsup": {
"entry": [
"src/index.ts"
],
"shims": true,
"sourcemap": false,
"dts": true,
"splitting": false,
"clean": true,
"minify": true,
"format": [
"esm",
"cjs"
]
},
"scripts": {

@@ -99,0 +86,0 @@ "build": "tsup",

@@ -84,5 +84,3 @@ # vite-plugin-mock-dev-server

proxy: {
'^/api': {
target: 'http://example.com'
}
'^/api': { target: 'http://example.com' }
}

@@ -110,6 +108,3 @@ }

url: '/api/test',
body: {
a: 1,
b: 2,
}
body: { a: 1, b: 2 }
})

@@ -225,3 +220,3 @@ ```

* build output dir
@default 'mockServer'
* @default 'mockServer'
*/

@@ -292,3 +287,5 @@ dist?: string

/**
* Set interface response delay, unit: ms.
* Set interface response delay, if an array is passed in,
* it represents the range of delay time.
* unit: ms.
* @default 0

@@ -307,34 +304,2 @@ */

/**
* Request validator, return mock data if validated, otherwise do not use current mock.
* This is useful in scenarios where an interface needs to return different data based
* on different input parameters.
* Validators can solve this type of problem well by dividing the same URL into multiple
* mock configurations and determining which one is effective based on the validator.
*
* @type { headers?: object; body?: object; query?: object; params?: object; refererQuery?: object }
*
* If the validator passes in an object,
* then the validation method is to strictly compare whether the `value`
* of each `key` in headers/body/query/params in the request interface is exactly equal.
* If they are all equal, then the validation passes.
* @type ({ headers: object; body: object; query: object; params: object; refererQuery: object }) => boolean
*
* If the validator passed in is a function,
* then the data related to the requested interface will be provided as input parameters
* for users to perform custom validation and return a boolean.
*
*/
validator: {
headers: {},
body: {},
query: {},
params: {},
/**
* refererQuery validates the query parameters in the URL of the request source page,
* which allows for direct modification of parameters in the browser address bar
* to obtain different simulated data.
*/
refererQuery: {}
},
/**
* response headers

@@ -389,3 +354,34 @@ * @type Record<string, any>

res.end()
}
},
/**
* Request validator, return mock data if validated, otherwise do not use current mock.
* This is useful in scenarios where an interface needs to return different data based
* on different input parameters.
* Validators can solve this type of problem well by dividing the same URL into multiple
* mock configurations and determining which one is effective based on the validator.
*
* @type { headers, body, query, params, refererQuery }
* If the validator passed in is an object,
* then the validation method is to deeply compare whether
* `headers/body/query/params/refererQuery` of the requested interface contain
* the `key-value` of the validator.
*
* @type (request) => boolean
* If the validator passed in is a function,
* then the data related to the requested interface will be provided as input parameters
* for users to perform custom validation and return a boolean.
*
*/
validator: {
headers: {},
body: {},
query: {},
params: {},
/**
* refererQuery validates the query parameters in the URL of the request source page,
* which allows for direct modification of parameters in the browser address bar
* to obtain different simulated data.
*/
refererQuery: {}
},
})

@@ -542,2 +538,9 @@ ```

body: { message: 'query.a == 3' }
},
// Hitting the POST /api/test request, and in the request body,
// field a is an array that contains items with values of 1 and 2.
{
url: '/api/test',
method: ['POST'],
validator: { body: { a: [1, 2] } }
}

@@ -544,0 +547,0 @@ ])

@@ -85,5 +85,3 @@ # vite-plugin-mock-dev-server

proxy: {
'^/api': {
target: 'http://example.com'
}
'^/api': { target: 'http://example.com' }
}

@@ -110,6 +108,3 @@ }

url: '/api/test',
body: {
a: 1,
b: 2,
}
body: { a: 1, b: 2 }
})

@@ -220,3 +215,3 @@ ```

* 构建输出目录
@default 'mockServer'
* @default 'mockServer'
*/

@@ -285,3 +280,4 @@ dist?: string

/**
* 设置接口响应延迟, 单位:ms
* 设置接口响应延迟,如果传入的是一个数组,则代表延迟时间的范围
* 单位:ms
* @default 0

@@ -300,29 +296,2 @@ */

/**
* 请求验证器,通过验证器则返回 mock数据,否则不使用当前mock。
* 这对于一些场景中,某个接口需要通过不同的入参来返回不同的数据,
* 验证器可以很好的解决这一类问题,将同个 url 分为多个 mock配置,
* 根据 验证器来判断哪个mock配置生效。
*
* @type { headers?: object; body?: object; query?: object; params?: object; refererQuery?: object }
*
* 如果 validator 传入的是一个对象,那么验证方式是严格比较 请求的接口
* 中,headers/body/query/params 的各个`key`的`value`是否全等,
* 全等则校验通过
*
* @type ({ headers: object; body: object; query: object; params: object; refererQuery: object }) => boolean
* 如果 validator 传入的是一个函数,那么会讲 请求的接口相关数据作为入参,提供给使用者进行自定义校验,并返回一个 boolean
*
*/
validator: {
headers: {},
body: {},
query: {},
params: {},
/**
* refererQuery 验证了请求来源页面 URL 中的查询参数,
* 这使得可以直接在浏览器地址栏中修改参数以获取不同的模拟数据。
*/
refererQuery: {}
},
/**
* 响应状态 headers

@@ -371,3 +340,3 @@ * @type Record<string, any>

*/
body: {},
body: '',

@@ -385,3 +354,28 @@ /**

res.end()
}
},
/**
* 请求验证器,通过验证器则返回 mock数据,否则不使用当前mock。
* 这对于一些场景中,某个接口需要通过不同的入参来返回不同的数据,验证器可以很好的解决这一类问题,
* 将同个 url 分为多个 mock配置,根据 验证器来判断哪个mock配置生效。
*
* @type { headers, body, query, params, refererQuery }
* 如果 validator 传入的是一个对象,那么验证方式是 深度比较 请求的接口
* 中 headers/body/query/params/refererQuery 是否包含 validator 的 key-value。
*
* @type (request) => boolean
* 如果 validator 传入的是一个函数,那么会将 请求的接口相关数据作为入参,
* 提供给使用者进行自定义校验,并返回一个 boolean
*
*/
validator: {
headers: {},
body: {},
query: {},
params: {},
/**
* refererQuery 验证了请求来源页面 URL 中的查询参数,
* 这使得可以直接在浏览器地址栏中修改参数以获取不同的模拟数据。
*/
refererQuery: {}
},
})

@@ -538,2 +532,8 @@ ```

body: { message: 'query.a == 3' },
},
// 命中 POST /api/test 请求,且 请求体中,字段 a 为数组,且数组包含值为 1, 2 的项
{
url: '/api/test',
method: ['POST'],
validator: { body: { a: [1, 2] } }
}

@@ -540,0 +540,0 @@ ])

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc