vite-plugin-mock-dev-server
Advanced tools
Comparing version 1.1.7 to 1.1.8
@@ -1,4 +0,4 @@ | ||
import Fe from"fs";import Q from"fs/promises";import L from"path";import{build as $e}from"esbuild";import He from"fast-glob";import _e from"is-core-module";import{createFilter as Ue,normalizePath as Ne}from"vite";var re="vite-plugin-mock-dev-server",ne="1.1.7";import se from"fs/promises";import Re from"path";import Ce from"json5";var q={name:"externalize-deps",setup(t){t.onResolve({filter:/.*/},({path:o})=>{if(o[0]!=="."&&!Re.isAbsolute(o))return{external:!0}})}},A={name:"json5-loader",setup(t){t.onLoad({filter:/\.json5$/},async({path:o})=>{let e=await se.readFile(o,"utf-8");return{contents:`export default ${JSON.stringify(Ce.parse(e))}`,loader:"js"}})}},B={name:"json-loader",setup(t){t.onLoad({filter:/\.json$/},async({path:o})=>({contents:`export default ${await se.readFile(o,"utf-8")}`,loader:"js"}))}},J=t=>({name:"alias-plugin",setup(o){o.onResolve({filter:/.*/},async({path:e})=>{let r=t.find(({find:c})=>De(c,e));if(!r)return null;let{find:s,replacement:n}=r;return{path:(await o.resolve(e.replace(s,n),{kind:"import-statement",resolveDir:n,namespace:"file"})).path,external:!1}})}});function De(t,o){return t instanceof RegExp?t.test(o):o.length<t.length?!1:o===t?!0:o.startsWith(`${t}/`)}import K from"fs";import V from"path";import{fileURLToPath as We}from"url";import Ee from"debug";import{match as Ie}from"path-to-regexp";import ie from"picocolors";var S=t=>Array.isArray(t),C=t=>typeof t=="function",Le=t=>Object.prototype.toString.call(t)==="[object Object]",ce=t=>Le(t)&&Object.keys(t).length===0,Te=t=>t!==null&&typeof t=="object"&&typeof t.pipe=="function",ae=t=>Te(t)&&t.readable!==!1&&typeof t._read=="function"&&typeof t._readableState=="object";function pe(t){return new Promise(o=>setTimeout(o,t))}function ue(t){return V.dirname(We(t))}var D=Ee("vite:plugin-mock-dev-server"),P=t=>S(t)?t:t==null?[]:[t],I={info(...t){console.info(ie.cyan("mock-dev-server: "),...t)},error(...t){console.error(` | ||
`,ie.cyan("mock-dev-server: "),...t,` | ||
`)}};function F(t,o,e){for(let s of o){let n=V.join(t,s);if(K.existsSync(n)&&K.statSync(n).isFile()){let i=e!=null&&e.pathOnly?n:K.readFileSync(n,"utf-8");if(!(e!=null&&e.predicate)||e.predicate(i))return i}}let r=V.dirname(t);if(r!==t&&(!(e!=null&&e.rootDir)||r.startsWith(e==null?void 0:e.rootDir)))return F(r,o,e)}var z=(t={})=>{let o=[],e=[];return Object.keys(t).forEach(r=>{var n,i;let s=t[r];typeof s=="string"||!s.ws&&!((n=s.target)!=null&&n.toString().startsWith("ws:"))&&!((i=s.target)!=null&&i.toString().startsWith("wss:"))?o.push(r):e.push(r)}),{httpProxies:o,wsProxies:e}};function G(t,o){return t[0]==="^"&&new RegExp(t).test(o)||o.startsWith(t)}function $(t,o){return(Ie(t,{decode:decodeURIComponent})(o)||{params:{}}).params||{}}async function le(t,o,e){let r=P(e.include),s=P(e.exclude),n={};if(o.define)for(let f in o.define){let l=o.define[f];n[f]=typeof l=="string"?l:JSON.stringify(l)}let{httpProxies:i}=z(o.server.proxy||{});i.push(...P(e.prefix));let c=P(e.wsPrefix),a={};try{let f=F(o.root,["package.json"]);f&&(a=JSON.parse(f))}catch{}let p=e.build.dist,m=await Je(process.cwd(),r,s),u=L.join(o.root,`mock-data-${Date.now()}.js`);await Q.writeFile(u,m,"utf-8");let{code:b,deps:h}=await ze(u,n,o.resolve.alias),k=qe(h);await Q.unlink(u);let g=[{filename:L.join(p,"mock-data.js"),source:b},{filename:L.join(p,"index.js"),source:Be(i,c,e.cookiesOptions,e.build.serverPort)},{filename:L.join(p,"package.json"),source:Ae(a,k)}];try{if(L.isAbsolute(p)){await Q.rm(p,{recursive:!0}),Fe.mkdirSync(p,{recursive:!0});for(let{filename:f,source:l}of g)await Q.writeFile(f,l,"utf-8")}else for(let{filename:f,source:l}of g)t.emitFile({type:"asset",fileName:f,source:l})}catch{}}function qe(t){let o=new Set,e=[re,"connect","cors"];return Object.keys(t).forEach(r=>{t[r].imports.filter(n=>n.external).map(n=>n.path).forEach(n=>{!e.includes(n)&&!_e(n)&&o.add(n)})}),Array.from(o)}function Ae(t,o){let{dependencies:e={},devDependencies:r={}}=t,s={...e,...r},n={name:"mock-server",type:"module",scripts:{start:"node index.js"},dependencies:{connect:"^3.7.0","vite-plugin-mock-dev-server":`^${ne}`,cors:"^2.8.5"},pnpm:{peerDependencyRules:{ignoreMissing:["vite"]}}};return o.forEach(i=>{n.dependencies[i]=s[i]||"latest"}),JSON.stringify(n,null,2)}function Be(t,o,e={},r=8080){return`import { createServer } from 'node:http'; | ||
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(` | ||
`,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'; | ||
@@ -27,4 +27,4 @@ import corsMiddleware from 'cors'; | ||
console.log('listen: http://localhost:${r}'); | ||
`}async function Je(t,o,e){let r=await He(o,{cwd:t}),s=Ue(o,e,{resolve:!1}),n=r.filter(s),i="",c="";return n.forEach((a,p)=>{let m=Ne(L.join(t,a));i+=`import * as m${p} from '${m}'; | ||
`,c+=`m${p}, `}),`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((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'; | ||
${i} | ||
@@ -37,7 +37,8 @@ const exporters = [${c}]; | ||
export default transformMockData(mockList); | ||
`}async function ze(t,o,e){var r;try{let s=await $e({entryPoints:[t],outfile:"out.js",write:!1,target:["node14.18","node16"],platform:"node",bundle:!0,metafile:!0,format:"esm",define:o,plugins:[J(e),q,A,B]});return{code:s.outputFiles[0].text,deps:((r=s.metafile)==null?void 0:r.inputs)||{}}}catch(s){console.error(s)}return{code:"",deps:{}}}import{Buffer as fe}from"buffer";import{parse as ke}from"url";import Xe from"cookies";import Ke from"http-status";import*as H from"mime-types";import{pathToRegexp as ye}from"path-to-regexp";import _ from"picocolors";import Y from"co-body";import Ge from"formidable";async function me(t,o){var s;let e=t.method.toUpperCase();if(["GET","DELETE","HEAD"].includes(e))return;let r=((s=t.headers["content-type"])==null?void 0:s.toLocaleLowerCase())||"";try{if(r.startsWith("application/json"))return await Y.json(t);if(r.startsWith("application/x-www-form-urlencoded"))return await Y.form(t);if(r.startsWith("text/plain"))return await Y.text(t);if(r.startsWith("multipart/form-data"))return await Qe(t,o)}catch(n){console.error(n)}}async function Qe(t,o){let e=Ge(o);return new Promise((r,s)=>{e.parse(t,(n,i,c)=>{if(n){s(n);return}r({...i,...c})})})}function de(t,o){return W(t.headers,o.headers)&&W(t.body,o.body)&&W(t.params,o.params)&&W(t.query,o.query)&&W(t.refererQuery,o.refererQuery)}function W(t,o){if(!o)return!0;for(let e in o)if(o[e]!==t[e])return!1;return!0}function he(t,{formidableOptions:o={},proxies:e,cookiesOptions:r}){return async function(s,n,i){let c=Date.now(),{query:a,pathname:p}=ke(s.url,!0);if(!p||e.length===0||!e.some(j=>G(j,s.url)))return i();let m=t.mockData,u=Object.keys(m).find(j=>ye(j).test(p));if(!u)return i();let{query:b}=ke(s.headers.referer||"",!0),h=await me(s,o),k=new Xe(s,n,r),g=k.get.bind(k),f=s.method.toUpperCase(),l=Ve(m[u],{pathname:p,method:f,request:{query:a,refererQuery:b,body:h,headers:s.headers,getCookie:g}});if(!l)return i();D("middleware: ",f,s.url);let v=s,y=n;v.body=h,v.query=a,v.refererQuery=b,v.params=$(l.url,p),v.getCookie=g,y.setCookie=k.set.bind(k);let{body:M,delay:d,type:x="json",response:R,status:T=200,statusText:je}=l;if(Z(y,T,je),await Ye(v,y,l),await Ze(v,y,l),M){try{let j=C(M)?await M(v):M;await ge(c,d),et(y,j,x)}catch(j){I.error(`${_.red("[body error]")} ${s.url} | ||
`,j),Z(y,500),n.end("")}return}if(R){try{await ge(c,d),await R(v,y,i)}catch(j){I.error(`${_.red("[response error]")} ${s.url} | ||
`,j),Z(y,500),n.end("")}return}n.end("")}}function Ve(t,{pathname:o,method:e,request:r}){return t.find(s=>{if(!o||!s||!s.url||s.ws===!0||!(s.method?S(s.method)?s.method:[s.method]:["GET","POST"]).includes(e))return!1;let i=ye(s.url).test(o);if(i&&s.validator){let c=$(s.url,o);if(C(s.validator))return s.validator({params:c,...r});try{return de({params:c,...r},s.validator)}catch(a){return I.error(`${_.red("[validator error]")} ${o} | ||
`,a),!1}}return i})}function Z(t,o=200,e){t.statusCode=o,t.statusMessage=e||tt(o)}async function Ye(t,o,{headers:e,type:r="json"}){let s=H.contentType(r)||H.contentType(H.lookup(r)||"");if(s&&o.setHeader("Content-Type",s),o.setHeader("Cache-Control","no-cache,max-age=0"),o.setHeader("X-Mock","generate by vite:plugin-mock-dev-server"),!!e)try{let n=C(e)?await e(t):e;Object.keys(n).forEach(i=>{o.setHeader(i,n[i])})}catch(n){I.error(`${_.red("[headers error]")} ${t.url} | ||
`,n)}}async function Ze(t,o,{cookies:e}){if(e)try{let r=C(e)?await e(t):e;Object.keys(r).forEach(s=>{let n=r[s];if(S(n)){let[i,c]=n;o.setCookie(s,i,c)}else o.setCookie(s,n)})}catch(r){I.error(`${_.red("[cookies error]")} ${t.url} | ||
`,r)}}function et(t,o,e){if(ae(o))o.pipe(t);else if(fe.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"?fe.from(r):r)}}async function ge(t,o){if(!o||o<=0)return;let e=Date.now()-t,r=o-e;r>0&&await pe(r)}function tt(t){return Ke[t]||"Unknown"}import nt from"events";import ee from"fs";import{createRequire as st}from"module";import Me from"path";import{pathToFileURL as it}from"url";import be from"chokidar";import{build as ct}from"esbuild";import at from"fast-glob";import{createFilter as pt,normalizePath as N}from"vite";import{parse as ot}from"url";import rt from"lodash.sortby";function ve(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:s,query:n}=ot(r.url,!0),i=e[s]??(e[s]=[]),c={...r,url:s};if(c.ws!==!0){let a=c.validator;ce(n)||(C(a)?c.validator=function(p){return W(p.query,n)&&a(p)}:a?(c.validator={...a},c.validator.query=c.validator.query?{...n,...c.validator.query}:n):c.validator={query:n})}i.push(c)}),Object.keys(e).forEach(r=>{e[r]=rt(e[r],s=>{if(s.ws===!0)return 0;let{validator:n}=s;if(!n)return 1;if(C(n))return 0;let{query:i,params:c,headers:a,body:p,refererQuery:m}=n;return 1/(U(i)+U(c)+U(a)+U(p)+U(m))})}),e}function U(t){return t?Object.keys(t).length:0}var ut=ue(import.meta.url),E=st(ut),X=class extends nt{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=F(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,s=await at(e,{cwd:this.cwd}),n=pt(e,r,{resolve:!1});this.watchMockEntry(),this.watchDeps();for(let c of s.filter(n))await this.loadMock(c);this.updateMockList();let i=null;this.on("mock:update",async c=>{n(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=>{n(c)&&(this.moduleCache.delete(c),this.updateMockList(),this.emit("mock:update-end",c))})}watchMockEntry(){let{include:e}=this.options,[r,...s]=e,n=be.watch(r,{ignoreInitial:!0,cwd:this.cwd});s.length>0&&s.forEach(i=>n.add(i)),n.on("add",async i=>{i=N(i),this.emit("mock:update",i),D("watcher:add",i)}),n.on("change",async i=>{i=N(i),this.emit("mock:update",i),D("watcher:change",i)}),n.on("unlink",async i=>{i=N(i),this.emit("mock:unlink",i),D("watcher:unlink",i)}),this.mockWatcher=n}watchDeps(){let e=[];this.depsWatcher=be.watch([],{ignoreInitial:!0,cwd:this.cwd}),this.depsWatcher.on("change",r=>{r=N(r);let s=this.moduleDeps.get(r);s&&s.forEach(n=>{this.emit("mock:update",n)})}),this.depsWatcher.on("unlink",r=>{r=N(r),this.moduleDeps.delete(r)}),this.on("update:deps",()=>{let r=[];for(let[n]of this.moduleDeps.entries())r.push(n);let s=r.filter(n=>!e.includes(n));s.length>0&&this.depsWatcher.add(s)})}close(){var e,r;(e=this.mockWatcher)==null||e.close(),(r=this.depsWatcher)==null||r.close()}updateMockList(){this._mockData=ve(this.moduleCache)}updateModuleDeps(e,r){Object.keys(r).forEach(s=>{r[s].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:s,deps:n}=await this.transformWithEsbuild(e,r);try{let i=await this.loadFromCode(e,s,r),c=i&&i.default?i.default:Object.keys(i||{}).map(a=>i[a]);S(c)?c.forEach(a=>a.__filepath__=e):c.__filepath__=e,this.moduleCache.set(e,c),this.updateModuleDeps(e,n)}catch(i){console.error(i)}}async loadFromCode(e,r,s){if(s){let n=`${e}.timestamp-${Date.now()}`,i=`${n}.mjs`,c=`${it(n)}.mjs`;await ee.promises.writeFile(i,r,"utf8");try{return await import(c)}finally{try{ee.unlinkSync(i)}catch{}}}else{e=Me.resolve(this.cwd,e);let n=Me.extname(e),i=ee.realpathSync(e),c=n in E.extensions?n:".js",a=E.extensions[c];E.extensions[c]=(m,u)=>{u===i?m._compile(r,u):a(m,u)},delete E.cache[E.resolve(e)];let p=E(e);return E.extensions[c]=a,p.__esModule?p:{default:p}}}async transformWithEsbuild(e,r){var s;try{let n=await ct({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:[J(this.options.alias),q,B,A]});return{code:n.outputFiles[0].text,deps:((s=n.metafile)==null?void 0:s.inputs)||{}}}catch(n){console.error(n)}return{code:"",deps:{}}}};import{parse as xe}from"url";import lt from"cookies";import{pathToRegexp as we}from"path-to-regexp";import{WebSocketServer as mt}from"ws";function Se(t,o,e,r){var c;let s=new Set,n=new Map,i=new Map;(c=t.on)==null||c.call(t,"mock:update-end",a=>{if(!s.has(a))return;let p={};for(let[m,u]of i.entries())t.mockData[m].forEach(b=>{b.ws&&b.__filepath__===a&&u.forEach(({pathname:h,req:k,ws:g})=>{p[h]??(p[h]={mock:b,list:[],mockUrl:m}),p[h].list.push({req:k,ws:g})})});Object.keys(p).forEach(m=>{var l;let{wss:u,cleanupList:b,context:h}=n.get(m),{mock:k,list:g,mockUrl:f}=p[m];Oe(b),u.removeAllListeners(),(l=k.setup)==null||l.call(k,u,h),u.on("close",()=>n.delete(m)),g.forEach(({req:v,ws:y})=>{y.removeAllListeners(),u.emit("connection",y,v),y.on("close",()=>{let M=i.get(f),d=(M==null?void 0:M.findIndex(x=>x.ws===y))||-1;d!==-1&&(M==null||M.splice(d,1))})})})}),o==null||o.on("upgrade",(a,p,m)=>{var M;let{pathname:u,query:b}=xe(a.url,!0);if(!u||e.length===0||!e.some(d=>G(d,a.url)))return;let h=t.mockData,k=Object.keys(h).find(d=>we(d).test(u));if(!k)return;let g=h[k].find(d=>d.url&&d.ws&&we(d.url).test(u));if(!g)return;s.add(g.__filepath__);let f=n.get(u);if(!f){let d=new mt({noServer:!0}),x=[],R={onCleanup:T=>x.push(T)};(M=g.setup)==null||M.call(g,d,R),d.on("close",()=>n.delete(u)),n.set(u,f={wss:d,cleanupList:x,context:R})}let l=a,v=new lt(a,a,r),{query:y}=xe(a.headers.referer||"",!0);l.query=b,l.refererQuery=y,l.params=$(k,u),l.getCookie=v.get.bind(v),f.wss.handleUpgrade(l,p,m,d=>{D(`websocket-mock: ${a.url} connected`),f.wss.emit("connection",d,l);let x=i.get(k);x||i.set(k,x=[]),x.push({req:l,ws:d,pathname:u}),d.on("close",()=>{let R=x.findIndex(T=>T.ws===d);R!==-1&&x.splice(R,1)})})}),o==null||o.on("close",()=>{n.forEach(({wss:a,cleanupList:p})=>{Oe(p),a.close()}),n.clear(),i.clear(),s.clear()})}function Oe(t){let o;for(;o=t.shift();)o==null||o()}async function te(t,o,e,r){let s=P(o.include),n=P(o.exclude),i={};if(t.define)for(let m in t.define){let u=t.define[m];i[m]=typeof u=="string"?u:JSON.stringify(u)}let c=new X({include:s,exclude:n,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:a}=z(t.server.proxy||{}),p=P(o.prefix);return Se(c,e,P(o.wsPrefix),o.cookiesOptions),he(c,{formidableOptions:o.formidableOptions,proxies:[...p,...a],cookiesOptions:o.cookiesOptions})}function Pe({prefix:t=[],wsPrefix:o=[],include:e=["mock/**/*.mock.{js,ts,cjs,mjs,json,json5}"],exclude:r=["**/node_modules/**","**/.vscode/**","**/.git/**"],reload:s=!1,formidableOptions:n={},build:i=!1,cookiesOptions:c={}}={}){let a={prefix:t,wsPrefix:o,include:e,exclude:r,reload:s,cookiesOptions:c,formidableOptions:{multiples:!0,...n},build:i?Object.assign({serverPort:8080,dist:"mockServer"},typeof i=="object"?i:{}):!1},p=[ft(a)];return a.build&&p.push(dt(a)),p}function dt(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 le(this,o,t)}}}function ft(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:s,ws:n}){let i=await te(r,t,s,n);e.use(i)},async configurePreviewServer({middlewares:e,httpServer:r}){let s=await te(o,t,r);e.use(s)}}}function Ao(t){return t}function Bo(t){return e=>(S(e)?e=e.map(r=>t(r)||r):e=t(e)||e,e)}var Qo=Pe;export{he as baseMiddleware,Bo as createDefineMock,Qo as default,Ao as defineMock,Pe as mockDevServerPlugin,Se as mockWebSocket,ve as transformMockData}; | ||
`}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}; |
{ | ||
"name": "vite-plugin-mock-dev-server", | ||
"version": "1.1.7", | ||
"version": "1.1.8", | ||
"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
100371
656