vite-plugin-mock-dev-server
Advanced tools
Comparing version 1.1.8 to 1.1.9
@@ -445,3 +445,3 @@ import { Connect, Plugin, ResolvedConfig } from 'vite'; | ||
get mockData(): Record<string, MockOptions>; | ||
load(): Promise<void>; | ||
load(): void; | ||
private watchMockEntry; | ||
@@ -448,0 +448,0 @@ /** |
@@ -1,5 +0,5 @@ | ||
import Ne from"fs";import X from"fs/promises";import F from"path";import{build as qe}from"esbuild";import Ae from"fast-glob";import Ue from"is-core-module";import{createFilter as Be,normalizePath as Je}from"vite";var ie="vite-plugin-mock-dev-server",ce="1.1.8";import ae from"fs/promises";import Ee from"path";import Le from"json5";var U={name:"externalize-deps",setup(t){t.onResolve({filter:/.*/},({path:o})=>{if(o[0]!=="."&&!Ee.isAbsolute(o))return{external:!0}})}},B={name:"json5-loader",setup(t){t.onLoad({filter:/\.json5$/},async({path:o})=>{let e=await ae.readFile(o,"utf-8");return{contents:`export default ${JSON.stringify(Le.parse(e))}`,loader:"js"}})}},J={name:"json-loader",setup(t){t.onLoad({filter:/\.json$/},async({path:o})=>({contents:`export default ${await ae.readFile(o,"utf-8")}`,loader:"js"}))}},z=t=>({name:"alias-plugin",setup(o){o.onResolve({filter:/.*/},async({path:e})=>{let r=t.find(({find:c})=>Ie(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 Ie(t,o){return t instanceof RegExp?t.test(o):o.length<t.length?!1:o===t?!0:o.startsWith(`${t}/`)}import V from"fs";import Y from"path";import{fileURLToPath as Te}from"url";import $e from"debug";import{match as _e}from"path-to-regexp";import pe from"picocolors";var S=t=>Array.isArray(t),P=t=>typeof t=="function",Fe=t=>Object.prototype.toString.call(t)==="[object Object]",ue=t=>Fe(t)&&Object.keys(t).length===0,He=t=>t!==null&&typeof t=="object"&&typeof t.pipe=="function",le=t=>He(t)&&t.readable!==!1&&typeof t._read=="function"&&typeof t._readableState=="object";function de(t){return new Promise(o=>setTimeout(o,t))}function me(t){return Y.dirname(Te(t))}var j=$e("vite:plugin-mock-dev-server"),O=t=>S(t)?t:t==null?[]:[t],C={info(...t){console.info(pe.cyan("mock-dev-server: "),...t)},error(...t){console.error(` | ||
import Ne from"fs";import X from"fs/promises";import T from"path";import{build as qe}from"esbuild";import Ae from"fast-glob";import Ue from"is-core-module";import{createFilter as Be,normalizePath as Je}from"vite";var ie="vite-plugin-mock-dev-server",ce="1.1.9";import ae from"fs/promises";import Ee from"path";import Ie from"json5";var U={name:"externalize-deps",setup(t){t.onResolve({filter:/.*/},({path:o})=>{if(o[0]!=="."&&!Ee.isAbsolute(o))return{external:!0}})}},B={name:"json5-loader",setup(t){t.onLoad({filter:/\.json5$/},async({path:o})=>{let e=await ae.readFile(o,"utf-8");return{contents:`export default ${JSON.stringify(Ie.parse(e))}`,loader:"js"}})}},J={name:"json-loader",setup(t){t.onLoad({filter:/\.json$/},async({path:o})=>({contents:`export default ${await ae.readFile(o,"utf-8")}`,loader:"js"}))}},z=t=>({name:"alias-plugin",setup(o){o.onResolve({filter:/.*/},async({path:e})=>{let r=t.find(({find:c})=>Le(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 Le(t,o){return t instanceof RegExp?t.test(o):o.length<t.length?!1:o===t?!0:o.startsWith(`${t}/`)}import V from"fs";import Y from"path";import{fileURLToPath as _e}from"url";import $e from"debug";import{match as Fe}from"path-to-regexp";import pe from"picocolors";var S=t=>Array.isArray(t),j=t=>typeof t=="function",Te=t=>Object.prototype.toString.call(t)==="[object Object]",le=t=>Te(t)&&Object.keys(t).length===0,He=t=>t!==null&&typeof t=="object"&&typeof t.pipe=="function",ue=t=>He(t)&&t.readable!==!1&&typeof t._read=="function"&&typeof t._readableState=="object";function me(t){return new Promise(o=>setTimeout(o,t))}function de(t){return Y.dirname(_e(t))}var C=$e("vite:plugin-mock-dev-server"),O=t=>S(t)?t:t==null?[]:[t],W={info(...t){console.info(pe.cyan("mock-dev-server: "),...t)},error(...t){console.error(` | ||
`,pe.cyan("mock-dev-server: "),...t,` | ||
`)}};function H(t,o,e){for(let n of o){let s=Y.join(t,n);if(V.existsSync(s)&&V.statSync(s).isFile()){let i=e!=null&&e.pathOnly?s:V.readFileSync(s,"utf-8");if(!(e!=null&&e.predicate)||e.predicate(i))return i}}let r=Y.dirname(t);if(r!==t&&(!(e!=null&&e.rootDir)||r.startsWith(e==null?void 0:e.rootDir)))return H(r,o,e)}var G=(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 Q(t,o){return t[0]==="^"&&new RegExp(t).test(o)||o.startsWith(t)}function N(t,o){return(_e(t,{decode:decodeURIComponent})(o)||{params:{}}).params||{}}async function fe(t,o,e){let r=O(e.include),n=O(e.exclude),s={};if(o.define)for(let p in o.define){let l=o.define[p];s[p]=typeof l=="string"?l:JSON.stringify(l)}let{httpProxies:i}=G(o.server.proxy||{});i.push(...O(e.prefix));let c=O(e.wsPrefix),d={};try{let p=H(o.root,["package.json"]);p&&(d=JSON.parse(p))}catch{}let m=e.build.dist,v=await Xe(process.cwd(),r,n),y=F.join(o.root,`mock-data-${Date.now()}.js`);await X.writeFile(y,v,"utf-8");let{code:_,deps:R}=await Ke(y,s,o.resolve.alias),a=ze(R);await X.unlink(y);let u=[{filename:F.join(m,"mock-data.js"),source:_},{filename:F.join(m,"index.js"),source:Qe(i,c,e.cookiesOptions,e.build.serverPort)},{filename:F.join(m,"package.json"),source:Ge(d,a)}];try{if(F.isAbsolute(m)){await X.rm(m,{recursive:!0}),Ne.mkdirSync(m,{recursive:!0});for(let{filename:p,source:l}of u)await X.writeFile(p,l,"utf-8")}else for(let{filename:p,source:l}of u)t.emitFile({type:"asset",fileName:p,source:l})}catch{}}function ze(t){let o=new Set,e=[ie,"connect","cors"];return Object.keys(t).forEach(r=>{t[r].imports.filter(s=>s.external).map(s=>s.path).forEach(s=>{!e.includes(s)&&!Ue(s)&&o.add(s)})}),Array.from(o)}function Ge(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":`^${ce}`,cors:"^2.8.5"},pnpm:{peerDependencyRules:{ignoreMissing:["vite"]}}};return o.forEach(i=>{s.dependencies[i]=n[i]||"latest"}),JSON.stringify(s,null,2)}function Qe(t,o,e={},r=8080){return`import { createServer } from 'node:http'; | ||
import connect from 'connect'; | ||
`)}};function H(t,o,e){for(let n of o){let s=Y.join(t,n);if(V.existsSync(s)&&V.statSync(s).isFile()){let i=e!=null&&e.pathOnly?s:V.readFileSync(s,"utf-8");if(!(e!=null&&e.predicate)||e.predicate(i))return i}}let r=Y.dirname(t);if(r!==t&&(!(e!=null&&e.rootDir)||r.startsWith(e==null?void 0:e.rootDir)))return H(r,o,e)}var G=(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 Q(t,o){return t[0]==="^"&&new RegExp(t).test(o)||o.startsWith(t)}function N(t,o){return(Fe(t,{decode:decodeURIComponent})(o)||{params:{}}).params||{}}async function fe(t,o,e){let r=O(e.include),n=O(e.exclude),s={};if(o.define)for(let p in o.define){let u=o.define[p];s[p]=typeof u=="string"?u:JSON.stringify(u)}let{httpProxies:i}=G(o.server.proxy||{});i.push(...O(e.prefix));let c=O(e.wsPrefix),m={};try{let p=H(o.root,["package.json"]);p&&(m=JSON.parse(p))}catch{}let d=e.build.dist,v=await Xe(process.cwd(),r,n),y=T.join(o.root,`mock-data-${Date.now()}.js`);await X.writeFile(y,v,"utf-8");let{code:F,deps:D}=await Ke(y,s,o.resolve.alias),a=ze(D);await X.unlink(y);let l=[{filename:T.join(d,"mock-data.js"),source:F},{filename:T.join(d,"index.js"),source:Qe(i,c,e.cookiesOptions,e.build.serverPort)},{filename:T.join(d,"package.json"),source:Ge(m,a)}];try{if(T.isAbsolute(d)){await X.rm(d,{recursive:!0}),Ne.mkdirSync(d,{recursive:!0});for(let{filename:p,source:u}of l)await X.writeFile(p,u,"utf-8")}else for(let{filename:p,source:u}of l)t.emitFile({type:"asset",fileName:p,source:u})}catch{}}function ze(t){let o=new Set,e=[ie,"connect","cors"];return Object.keys(t).forEach(r=>{t[r].imports.filter(s=>s.external).map(s=>s.path).forEach(s=>{!e.includes(s)&&!Ue(s)&&o.add(s)})}),Array.from(o)}function Ge(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":`^${ce}`,cors:"^2.8.5"},pnpm:{peerDependencyRules:{ignoreMissing:["vite"]}}};return o.forEach(i=>{s.dependencies[i]=n[i]||"latest"}),JSON.stringify(s,null,2)}function Qe(t,o,e={},r=8080){return`import { createServer } from 'node:http'; | ||
import connect from 'connect'; | ||
import corsMiddleware from 'cors'; | ||
@@ -27,4 +27,4 @@ import { baseMiddleware, mockWebSocket } from 'vite-plugin-mock-dev-server'; | ||
console.log('listen: http://localhost:${r}'); | ||
`}async function Xe(t,o,e){let r=await Ae(o,{cwd:t}),n=Be(o,e,{resolve:!1}),s=r.filter(n),i="",c="";return s.forEach((d,m)=>{let v=Je(F.join(t,d));i+=`import * as m${m} from '${v}'; | ||
`,c+=`m${m}, `}),`import { transformMockData } from 'vite-plugin-mock-dev-server'; | ||
`}async function Xe(t,o,e){let r=await Ae(o,{cwd:t}),n=Be(o,e,{resolve:!1}),s=r.filter(n),i="",c="";return s.forEach((m,d)=>{let v=Je(T.join(t,m));i+=`import * as m${d} from '${v}'; | ||
`,c+=`m${d}, `}),`import { transformMockData } from 'vite-plugin-mock-dev-server'; | ||
${i} | ||
@@ -35,10 +35,9 @@ const exporters = [${c}]; | ||
: Object.keys(raw || {}).map((key) => raw[key]) | ||
) | ||
export default transformMockData(mockList); | ||
`}async function Ke(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:[z(e),U,B,J]});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 ye}from"buffer";import{parse as he}from"url";import Ze from"cookies";import et from"http-status";import*as q from"mime-types";import{pathToRegexp as Me}from"path-to-regexp";import W from"picocolors";import Z from"co-body";import Ve 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 Z.json(t);if(r.startsWith("application/x-www-form-urlencoded"))return await Z.form(t);if(r.startsWith("text/plain"))return await Z.text(t);if(r.startsWith("multipart/form-data"))return await Ye(t,o)}catch(s){console.error(s)}}async function Ye(t,o){let e=Ve(o);return new Promise((r,n)=>{e.parse(t,(s,i,c)=>{if(s){n(s);return}r({...i,...c})})})}function ge(t,o){return T(t.headers,o.headers)&&T(t.body,o.body)&&T(t.params,o.params)&&T(t.query,o.query)&&T(t.refererQuery,o.refererQuery)}function T(t,o){if(!o)return!0;for(let e in o)if(o[e]!==t[e])return!1;return!0}function be(t,{formidableOptions:o={},proxies:e,cookiesOptions:r}){return async function(n,s,i){let c=Date.now(),{query:d,pathname:m}=he(n.url,!0);if(!m||e.length===0||!e.some(h=>Q(h,n.url)))return i();let v=t.mockData,y=Object.keys(v).find(h=>Me(h).test(m));if(!y)return i();let{query:_}=he(n.headers.referer||"",!0),R=await ke(n,o),a=new Ze(n,s,r),u=a.get.bind(a),p=n.method.toUpperCase(),l=tt(v[y],{pathname:m,method:p,request:{query:d,refererQuery:_,body:R,headers:n.headers,getCookie:u}});if(!l)return i();j("middleware: ",p,n.url);let f=n,k=s;f.body=R,f.query=d,f.refererQuery=_,f.params=N(l.url,m),f.getCookie=u,k.setCookie=a.set.bind(a);let{body:g,delay:w,type:D="json",response:E,status:L=200,statusText:I}=l;if(ee(k,L,I),await ot(f,k,l),await rt(f,k,l),g){try{let h=P(g)?await g(f):g;await ve(c,w),nt(k,h,D)}catch(h){C.error(`${W.red("[body error]")} ${n.url} | ||
`,`file: ${W.cyan(l.__filepath__)}`,h),ee(k,500),s.end("")}return}if(E){try{await ve(c,w),await E(f,k,i)}catch(h){C.error(`${W.red("[response error]")} ${n.url} | ||
`,`file: ${W.cyan(l.__filepath__)}`,h),ee(k,500),s.end("")}return}s.end("")}}function tt(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=Me(n.url).test(o);if(i&&n.validator){let c=N(n.url,o);if(P(n.validator))return n.validator({params:c,...r});try{return ge({params:c,...r},n.validator)}catch(d){return C.error(`${W.red("[validator error]")} ${o} | ||
`,`file: ${W.cyan(n.__filepath__)}`,d),!1}}return i})}function ee(t,o=200,e){t.statusCode=o,t.statusMessage=e||st(o)}async function ot(t,o,{headers:e,type:r="json"}){let n=q.contentType(r)||q.contentType(q.lookup(r)||"");if(n&&o.setHeader("Content-Type",n),o.setHeader("Cache-Control","no-cache,max-age=0"),o.setHeader("X-Mock","generate by vite:plugin-mock-dev-server"),!!e)try{let s=P(e)?await e(t):e;Object.keys(s).forEach(i=>{o.setHeader(i,s[i])})}catch(s){C.error(`${W.red("[headers error]")} ${t.url} | ||
`,s)}}async function rt(t,o,{cookies:e}){if(e)try{let r=P(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){C.error(`${W.red("[cookies error]")} ${t.url} | ||
`,r)}}function nt(t,o,e){if(le(o))o.pipe(t);else if(ye.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"?ye.from(r):r)}}async function ve(t,o){if(!o||o<=0)return;let e=Date.now()-t,r=o-e;r>0&&await de(r)}function st(t){return et[t]||"Unknown"}import pt from"events";import te from"fs";import{createRequire as ut}from"module";import we from"path";import{pathToFileURL as lt}from"url";import Se from"chokidar";import{build as dt}from"esbuild";import mt from"fast-glob";import{createFilter as ft,normalizePath as A}from"vite";import{parse as it}from"url";import ct from"lodash.sortby";function xe(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}=it(r.url,!0),i=e[n]??(e[n]=[]),c={...r,url:n};if(c.ws!==!0){let d=c.validator;ue(s)||(P(d)?c.validator=function(m){return T(m.query,s)&&d(m)}:d?(c.validator={...d},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]=ct(e[r],n=>{if(n.ws===!0)return 0;let{validator:s}=n;return s?P(s)?0:1/Object.keys(s).reduce((c,d)=>c+at(s[d]),0):1})}),e}function at(t){return t?Object.keys(t).length:0}var kt=me(import.meta.url),$=ut(kt),K=class extends pt{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}async load(){let{include:e,exclude:r}=this.options,n=await mt(e,{cwd:this.cwd}),s=ft(e,r,{resolve:!1});this.watchMockEntry(),this.watchDeps();for(let c of n.filter(s))await this.loadMock(c);this.updateMockList();let i=null;this.on("mock:update",async c=>{s(c)&&(await this.loadMock(c),i&&clearTimeout(i),i=setTimeout(()=>{this.updateMockList(),this.emit("mock:update-end",c),i=null},0))}),this.on("mock:unlink",async c=>{s(c)&&(this.moduleCache.delete(c),this.updateMockList(),this.emit("mock:update-end",c))})}watchMockEntry(){let{include:e}=this.options,[r,...n]=e,s=Se.watch(r,{ignoreInitial:!0,cwd:this.cwd});n.length>0&&n.forEach(i=>s.add(i)),s.on("add",async i=>{i=A(i),this.emit("mock:update",i),j("watcher:add",i)}),s.on("change",async i=>{i=A(i),this.emit("mock:update",i),j("watcher:change",i)}),s.on("unlink",async i=>{i=A(i),this.emit("mock:unlink",i),j("watcher:unlink",i)}),this.mockWatcher=s}watchDeps(){let e=[];this.depsWatcher=Se.watch([],{ignoreInitial:!0,cwd:this.cwd}),this.depsWatcher.on("change",r=>{r=A(r);let n=this.moduleDeps.get(r);n&&n.forEach(s=>{this.emit("mock:update",s)})}),this.depsWatcher.on("unlink",r=>{r=A(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=xe(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&&i.default?i.default:Object.keys(i||{}).map(d=>i[d]);S(c)?c.forEach(d=>d.__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=`${lt(s)}.mjs`;await te.promises.writeFile(i,r,"utf8");try{return await import(c)}finally{try{te.unlinkSync(i)}catch{}}}else{e=we.resolve(this.cwd,e);let s=we.extname(e),i=te.realpathSync(e),c=s in $.extensions?s:".js",d=$.extensions[c];$.extensions[c]=(v,y)=>{y===i?v._compile(r,y):d(v,y)},delete $.cache[$.resolve(e)];let m=$(e);return $.extensions[c]=d,m.__esModule?m:{default:m}}}async transformWithEsbuild(e,r){var n;try{let s=await dt({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:[z(this.options.alias),U,J,B]});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 Oe}from"url";import gt from"cookies";import{pathToRegexp as Pe}from"path-to-regexp";import yt from"picocolors";import{WebSocketServer as ht}from"ws";function Ce(t,o,e,r){var R;let n=new Map,s=new Map,i=new WeakMap,c=a=>{let u=s.get(a);return!u&&s.set(a,u=new Map),u},d=(a,u)=>{let p=a.get(u);return!p&&a.set(u,p=new ht({noServer:!0})),p},m=(a,u)=>{let p=n.get(a);!p&&n.set(a,p=new Set),p.add(u)},v=(a,u,p,l,f,k)=>{var g;try{(g=p.setup)==null||g.call(p,u,l),u.on("close",()=>{a.delete(f)})}catch(w){C.error(`${yt.red("[websocket server error]")} ${k} | ||
`,w)}},y=(a,u,p,l)=>{a.emit("connection",u,p),u.on("close",()=>{let f=l.findIndex(k=>k.ws===u);f!==-1&&l.splice(f,1)})},_=(a,u,p,l,f)=>{let{cleanupList:k,connectionList:g,context:w}=i.get(u);je(k),u.removeAllListeners(),v(a,u,p,w,l,f),g.forEach(({ws:D,req:E})=>{D.removeAllListeners(),y(u,D,E,g)})};(R=t.on)==null||R.call(t,"mock:update-end",a=>{if(!n.has(a))return;let u=n.get(a);for(let p of u.values())for(let l of t.mockData[p]){if(!l.ws||l.__filepath!==a)return;let f=c(p);for(let[k,g]of f.entries())_(f,g,l,k,a)}}),o==null||o.on("upgrade",(a,u,p)=>{let{pathname:l,query:f}=Oe(a.url,!0);if(!l||e.length===0||!e.some(M=>Q(M,a.url)))return;let k=t.mockData,g=Object.keys(k).find(M=>Pe(M).test(l));if(!g)return;let w=k[g].find(M=>M.url&&M.ws&&Pe(M.url).test(l));if(!w)return;let D=w.__filepath__;m(D,g);let E=c(g),L=d(E,l),I=i.get(L);if(!I){let M=[],ne={onCleanup:De=>M.push(De)};I={cleanupList:M,context:ne,connectionList:[]},i.set(L,I),v(E,L,w,ne,l,D)}let h=a,re=new gt(a,a,r),{query:Re}=Oe(a.headers.referer||"",!0);h.query=f,h.refererQuery=Re,h.params=N(g,l),h.getCookie=re.get.bind(re),L.handleUpgrade(h,u,p,M=>{j(`websocket-mock: ${a.url} connected`),I.connectionList.push({req:h,ws:M}),y(L,M,h,I.connectionList)})}),o==null||o.on("close",()=>{for(let a of s.values()){for(let u of a.values()){let p=i.get(u);je(p.cleanupList),u.close()}a.clear()}s.clear(),n.clear()})}function je(t){let o;for(;o=t.shift();)o==null||o()}async function oe(t,o,e,r){let n=O(o.include),s=O(o.exclude),i={};if(t.define)for(let v in t.define){let y=t.define[v];i[v]=typeof y=="string"?y:JSON.stringify(y)}let c=new K({include:n,exclude:s,define:i,alias:t.resolve.alias});await c.load(),c.on("mock:update-end",()=>{o.reload&&(r==null||r.send({type:"full-reload"}))}),e==null||e.on("close",()=>c.close());let{httpProxies:d}=G(t.server.proxy||{}),m=O(o.prefix);return Ce(c,e,O(o.wsPrefix),o.cookiesOptions),be(c,{formidableOptions:o.formidableOptions,proxies:[...m,...d],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 d={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=[Mt(d)];return d.build&&m.push(vt(d)),m}function vt(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 fe(this,o,t)}}}function Mt(t){let o={};return{name:"vite-plugin-mock-dev-server",enforce:"pre",apply:"serve",configResolved(e){o=e,e.logger.warn("")},async configureServer({middlewares:e,config:r,httpServer:n,ws:s}){let i=await oe(r,t,n,s);e.use(i)},async configurePreviewServer({middlewares:e,httpServer:r}){let n=await oe(o,t,r);e.use(n)}}}function Ko(t){return t}function Vo(t){return e=>(S(e)?e=e.map(r=>t(r)||r):e=t(e)||e,e)}var tr=We;export{be as baseMiddleware,Vo as createDefineMock,tr as default,Ko as defineMock,We as mockDevServerPlugin,Ce as mockWebSocket,xe as transformMockData}; | ||
); | ||
export default transformMockData(mockList);`}async function Ke(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:[z(e),U,B,J]});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 ye}from"buffer";import{parse as he}from"url";import Ze from"cookies";import et from"http-status";import*as q from"mime-types";import{pathToRegexp as Me}from"path-to-regexp";import R from"picocolors";import Z from"co-body";import Ve 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 Z.json(t);if(r.startsWith("application/x-www-form-urlencoded"))return await Z.form(t);if(r.startsWith("text/plain"))return await Z.text(t);if(r.startsWith("multipart/form-data"))return await Ye(t,o)}catch(s){console.error(s)}}async function Ye(t,o){let e=Ve(o);return new Promise((r,n)=>{e.parse(t,(s,i,c)=>{if(s){n(s);return}r({...i,...c})})})}function ge(t,o){return _(t.headers,o.headers)&&_(t.body,o.body)&&_(t.params,o.params)&&_(t.query,o.query)&&_(t.refererQuery,o.refererQuery)}function _(t,o){if(!o)return!0;for(let e in o)if(o[e]!==t[e])return!1;return!0}function be(t,{formidableOptions:o={},proxies:e,cookiesOptions:r}){return async function(n,s,i){let c=Date.now(),{query:m,pathname:d}=he(n.url,!0);if(!d||e.length===0||!e.some(h=>Q(h,n.url)))return i();let v=t.mockData,y=Object.keys(v).find(h=>Me(h).test(d));if(!y)return i();let{query:F}=he(n.headers.referer||"",!0),D=await ke(n,o),a=new Ze(n,s,r),l=a.get.bind(a),p=n.method.toUpperCase(),u=tt(v[y],{pathname:d,method:p,request:{query:m,refererQuery:F,body:D,headers:n.headers,getCookie:l}});if(!u)return i();C("middleware: ",p,n.url);let f=n,k=s;f.body=D,f.query=m,f.refererQuery=F,f.params=N(u.url,d),f.getCookie=l,k.setCookie=a.set.bind(a);let{body:g,delay:w,type:P="json",response:E,status:I=200,statusText:L}=u;if(ee(k,I,L),await ot(f,k,u),await rt(f,k,u),g){try{let h=j(g)?await g(f):g;await ve(c,w),nt(k,h,P)}catch(h){W.error(`${R.red("[body error]")} ${n.url} | ||
`,`file: ${R.cyan(u.__filepath__)}`,h),ee(k,500),s.end("")}return}if(E){try{await ve(c,w),await E(f,k,i)}catch(h){W.error(`${R.red("[response error]")} ${n.url} | ||
`,`file: ${R.cyan(u.__filepath__)}`,h),ee(k,500),s.end("")}return}s.end("")}}function tt(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=Me(n.url).test(o);if(i&&n.validator){let c=N(n.url,o);if(j(n.validator))return n.validator({params:c,...r});try{return ge({params:c,...r},n.validator)}catch(m){return W.error(`${R.red("[validator error]")} ${o} | ||
`,`file: ${R.cyan(n.__filepath__)}`,m),!1}}return i})}function ee(t,o=200,e){t.statusCode=o,t.statusMessage=e||st(o)}async function ot(t,o,{headers:e,type:r="json"}){let n=q.contentType(r)||q.contentType(q.lookup(r)||"");if(n&&o.setHeader("Content-Type",n),o.setHeader("Cache-Control","no-cache,max-age=0"),o.setHeader("X-Mock","generate by vite:plugin-mock-dev-server"),!!e)try{let s=j(e)?await e(t):e;Object.keys(s).forEach(i=>{o.setHeader(i,s[i])})}catch(s){W.error(`${R.red("[headers error]")} ${t.url} | ||
`,s)}}async function rt(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){W.error(`${R.red("[cookies error]")} ${t.url} | ||
`,r)}}function nt(t,o,e){if(ue(o))o.pipe(t);else if(ye.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"?ye.from(r):r)}}async function ve(t,o){if(!o||o<=0)return;let e=Date.now()-t,r=o-e;r>0&&await me(r)}function st(t){return et[t]||"Unknown"}import pt from"events";import te from"fs";import{createRequire as lt}from"module";import we from"path";import{pathToFileURL as ut}from"url";import Se from"chokidar";import{build as mt}from"esbuild";import dt from"fast-glob";import{createFilter as ft,normalizePath as A}from"vite";import{parse as it}from"url";import ct from"lodash.sortby";function xe(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}=it(r.url,!0),i=e[n]??(e[n]=[]),c={...r,url:n};if(c.ws!==!0){let m=c.validator;le(s)||(j(m)?c.validator=function(d){return _(d.query,s)&&m(d)}:m?(c.validator={...m},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]=ct(e[r],n=>{if(n.ws===!0)return 0;let{validator:s}=n;return s?j(s)?0:1/Object.keys(s).reduce((c,m)=>c+at(s[m]),0):1})}),e}function at(t){return t?Object.keys(t).length:0}var kt=de(import.meta.url),$=lt(kt),K=class extends pt{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=ft(e,r,{resolve:!1});dt(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=Se.watch(r,{ignoreInitial:!0,cwd:this.cwd});n.length>0&&n.forEach(i=>s.add(i)),s.on("add",async i=>{i=A(i),this.emit("mock:update",i),C("watcher:add",i)}),s.on("change",async i=>{i=A(i),this.emit("mock:update",i),C("watcher:change",i)}),s.on("unlink",async i=>{i=A(i),this.emit("mock:unlink",i),C("watcher:unlink",i)}),this.mockWatcher=s}watchDeps(){let e=[];this.depsWatcher=Se.watch([],{ignoreInitial:!0,cwd:this.cwd}),this.depsWatcher.on("change",r=>{r=A(r);let n=this.moduleDeps.get(r);n&&n.forEach(s=>{this.emit("mock:update",s)})}),this.depsWatcher.on("unlink",r=>{r=A(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=xe(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&&i.default?i.default:Object.keys(i||{}).map(m=>i[m]);S(c)?c.forEach(m=>m.__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=`${ut(s)}.mjs`;await te.promises.writeFile(i,r,"utf8");try{return await import(c)}finally{try{te.unlinkSync(i)}catch{}}}else{e=we.resolve(this.cwd,e);let s=we.extname(e),i=te.realpathSync(e),c=s in $.extensions?s:".js",m=$.extensions[c];$.extensions[c]=(v,y)=>{y===i?v._compile(r,y):m(v,y)},delete $.cache[$.resolve(e)];let d=$(e);return $.extensions[c]=m,d.__esModule?d:{default:d}}}async transformWithEsbuild(e,r){var n;try{let s=await mt({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:[z(this.options.alias),U,J,B]});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 Oe}from"url";import gt from"cookies";import{pathToRegexp as Pe}from"path-to-regexp";import yt from"picocolors";import{WebSocketServer as ht}from"ws";function Ce(t,o,e,r){var D;let n=new Map,s=new Map,i=new WeakMap,c=a=>{let l=s.get(a);return!l&&s.set(a,l=new Map),l},m=(a,l)=>{let p=a.get(l);return!p&&a.set(l,p=new ht({noServer:!0})),p},d=(a,l)=>{let p=n.get(a);!p&&n.set(a,p=new Set),p.add(l)},v=(a,l,p,u,f,k)=>{var g;try{(g=p.setup)==null||g.call(p,l,u),l.on("close",()=>{a.delete(f)})}catch(w){W.error(`${yt.red("[websocket server error]")} ${k} | ||
`,w)}},y=(a,l,p,u)=>{a.emit("connection",l,p),l.on("close",()=>{let f=u.findIndex(k=>k.ws===l);f!==-1&&u.splice(f,1)})},F=(a,l,p,u,f)=>{let{cleanupList:k,connectionList:g,context:w}=i.get(l);je(k),g.forEach(({ws:P})=>P.removeAllListeners()),l.removeAllListeners(),v(a,l,p,w,u,f),g.forEach(({ws:P,req:E})=>y(l,P,E,g))};(D=t.on)==null||D.call(t,"mock:update-end",a=>{if(!n.has(a))return;let l=n.get(a);if(l)for(let p of l.values())for(let u of t.mockData[p]){if(!u.ws||u.__filepath__!==a)return;let f=c(p);for(let[k,g]of f.entries())F(f,g,u,k,a)}}),o==null||o.on("upgrade",(a,l,p)=>{let{pathname:u,query:f}=Oe(a.url,!0);if(!u||e.length===0||!e.some(M=>Q(M,a.url)))return;let k=t.mockData,g=Object.keys(k).find(M=>Pe(M).test(u));if(!g)return;let w=k[g].find(M=>M.url&&M.ws&&Pe(M.url).test(u));if(!w)return;let P=w.__filepath__;d(P,g);let E=c(g),I=m(E,u),L=i.get(I);if(!L){let M=[],ne={onCleanup:De=>M.push(De)};L={cleanupList:M,context:ne,connectionList:[]},i.set(I,L),v(E,I,w,ne,u,P)}let h=a,re=new gt(a,a,r),{query:Re}=Oe(a.headers.referer||"",!0);h.query=f,h.refererQuery=Re,h.params=N(g,u),h.getCookie=re.get.bind(re),I.handleUpgrade(h,l,p,M=>{C(`websocket-mock: ${a.url} connected`),L.connectionList.push({req:h,ws:M}),y(I,M,h,L.connectionList)})}),o==null||o.on("close",()=>{for(let a of s.values()){for(let l of a.values()){let p=i.get(l);je(p.cleanupList),l.close()}a.clear()}s.clear(),n.clear()})}function je(t){let o;for(;o=t.shift();)o==null||o()}async function oe(t,o,e,r){let n=O(o.include),s=O(o.exclude),i={};if(t.define)for(let v in t.define){let y=t.define[v];i[v]=typeof y=="string"?y:JSON.stringify(y)}let c=new K({include:n,exclude:s,define:i,alias:t.resolve.alias});c.load(),c.on("mock:update-end",()=>{o.reload&&(r==null||r.send({type:"full-reload"}))}),e==null||e.on("close",()=>c.close());let{httpProxies:m}=G(t.server.proxy||{}),d=O(o.prefix);return Ce(c,e,O(o.wsPrefix),o.cookiesOptions),be(c,{formidableOptions:o.formidableOptions,proxies:[...d,...m],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 m={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},d=[Mt(m)];return m.build&&d.push(vt(m)),d}function vt(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 fe(this,o,t)}}}function Mt(t){let o={};return{name:"vite-plugin-mock-dev-server",enforce:"pre",apply:"serve",configResolved(e){o=e,e.logger.warn("")},async configureServer({middlewares:e,config:r,httpServer:n,ws:s}){let i=await oe(r,t,n,s);e.use(i)},async configurePreviewServer({middlewares:e,httpServer:r}){let n=await oe(o,t,r);e.use(n)}}}function Ko(t){return t}function Vo(t){return e=>(S(e)?e=e.map(r=>t(r)||r):e=t(e)||e,e)}var tr=We;export{be as baseMiddleware,Vo as createDefineMock,tr as default,Ko as defineMock,We as mockDevServerPlugin,Ce as mockWebSocket,xe as transformMockData}; |
{ | ||
"name": "vite-plugin-mock-dev-server", | ||
"version": "1.1.8", | ||
"version": "1.1.9", | ||
"keywords": [ | ||
@@ -5,0 +5,0 @@ "vite", |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
100417
654