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.3.2 to 1.3.3

4

dist/index.js

@@ -1,2 +0,2 @@

import{toArray as co}from"@pengzhanbo/utils";import ft from"node:fs";import Z from"node:fs/promises";import N from"node:path";import{toArray as ee}from"@pengzhanbo/utils";import gt from"fast-glob";import kt from"is-core-module";import{createFilter as ht,normalizePath as yt}from"vite";var ye="vite-plugin-mock-dev-server",ve="1.3.2";import xe,{promises as pe}from"node:fs";import{createRequire as ot}from"node:module";import ae from"node:path";import{pathToFileURL as rt}from"node:url";import{build as nt}from"esbuild";import st from"json5";import ie from"node:fs";import ce from"node:path";import{parse as Ke}from"node:querystring";import{URL as Xe,fileURLToPath as Ye}from"node:url";import Ze from"debug";import{match as et}from"path-to-regexp";var tt=o=>o!==null&&typeof o=="object"&&typeof o.pipe=="function",Me=o=>tt(o)&&o.readable!==!1&&typeof o._read=="function"&&typeof o._readableState=="object";function be(o){return ce.dirname(Ye(o))}var Q=Ze("vite:mock-dev-server");function q(o,t,e){for(let s of t){let n=ce.join(o,s);if(ie.existsSync(n)&&ie.statSync(n).isFile()){let i=e!=null&&e.pathOnly?n:ie.readFileSync(n,"utf-8");if(!(e!=null&&e.predicate)||e.predicate(i))return i}}let r=ce.dirname(o);if(r!==o&&(!(e!=null&&e.rootDir)||r.startsWith(e==null?void 0:e.rootDir)))return q(r,t,e)}var V=(o={})=>{let t=[],e=[];return Object.keys(o).forEach(r=>{var n,i;let s=o[r];typeof s=="string"||!s.ws&&!((n=s.target)!=null&&n.toString().startsWith("ws:"))&&!((i=s.target)!=null&&i.toString().startsWith("wss:"))?t.push(r):e.push(r)}),{httpProxies:t,wsProxies:e}};function I(o,t){return o[0]==="^"&&new RegExp(o).test(t)||t.startsWith(o)}function B(o,t){return(et(o,{decode:decodeURIComponent})(t)||{params:{}}).params||{}}function W(o){let t=new Xe(o,"http://example.com"),e=decodeURIComponent(t.pathname),r=Ke(t.search.replace(/^\?/,""));return{pathname:e,query:r}}var it={name:"externalize-deps",setup(o){o.onResolve({filter:/.*/},({path:t})=>{if(t[0]!=="."&&!ae.isAbsolute(t))return{external:!0}})}},ct={name:"json5-loader",setup(o){o.onLoad({filter:/\.json5$/},async({path:t})=>{let e=await pe.readFile(t,"utf-8");return{contents:`export default ${JSON.stringify(st.parse(e))}`,loader:"js"}})}},at={name:"json-loader",setup(o){o.onLoad({filter:/\.json$/},async({path:t})=>({contents:`export default ${await pe.readFile(t,"utf-8")}`,loader:"js"}))}},pt=o=>({name:"alias-plugin",setup(t){t.onResolve({filter:/.*/},async({path:e})=>{let r=o.find(({find:c})=>lt(c,e));if(!r)return null;let{find:s,replacement:n}=r;return{path:(await t.resolve(e.replace(s,n),{kind:"import-statement",resolveDir:n,namespace:"file"})).path,external:!1}})}});function lt(o,t){return o instanceof RegExp?o.test(t):t.length<o.length?!1:t===o?!0:t.startsWith(`${o}/`)}async function K(o,t){var n;let{isESM:e=!0,define:r,alias:s}=t;try{let i=await nt({entryPoints:[o],outfile:"out.js",write:!1,target:["node14.18","node16"],platform:"node",bundle:!0,metafile:!0,format:e?"esm":"cjs",define:r,plugins:[pt(s),it,at,ct]});return{code:i.outputFiles[0].text,deps:((n=i.metafile)==null?void 0:n.inputs)||{}}}catch(i){console.error(i)}return{code:"",deps:{}}}var ut=be(import.meta.url),T=ot(ut);async function we(o,t,e,r){if(e){let s=`${o}.timestamp-${Date.now()}`,n=`${s}.mjs`,i=`${rt(s)}.mjs`;await pe.writeFile(n,t,"utf8");try{return await import(i)}finally{try{xe.unlinkSync(n)}catch{}}}else{o=ae.resolve(r,o);let s=ae.extname(o),n=xe.realpathSync(o),i=s in T.extensions?s:".js",c=T.extensions[i];T.extensions[i]=(p,m)=>{m===n?p._compile(t,m):c(p,m)},delete T.cache[T.resolve(o)];let a=T(o);return T.extensions[i]=c,a.__esModule?a:{default:a}}}import Oe from"picocolors";import{isBoolean as mt}from"@pengzhanbo/utils";import $ from"picocolors";var Se={silent:0,error:1,warn:2,info:3,debug:4};function X(o,t="info"){o=`[${o}]`;function e(s,n,i){if(i=mt(i)?i?t:"error":i,Se[i]>=Se[s]){let a=s==="info"||s==="debug"?"log":s,p=s==="debug"?$.magenta($.bold(o)):s==="info"?$.cyan($.bold(o)):s==="warn"?$.yellow($.bold(o)):$.red($.bold(o)),m=`${$.dim(new Date().toLocaleTimeString())} ${p} ${n}`;console[a](m)}}return{debug(s,n=t){e("debug",s,n)},info(s,n=t){e("info",s,n)},warn(s,n=t){e("warn",s,n)},error(s,n=t){e("error",s,n)}}}var dt=/import\.meta\.env\.(.+)/;function Y(o){let t=X("vite:mock-dev-server","warn"),e={},r=process.env.NODE_ENV||o.mode;Object.assign(e,{"process.env.NODE_ENV":JSON.stringify(r),"global.process.env.NODE_ENV":JSON.stringify(r),"globalThis.process.env.NODE_ENV":JSON.stringify(r),__vite_process_env_NODE_ENV:JSON.stringify(r)});let s={},n={},i=[];for(let p in o.define){let m=o.define[p];if(typeof m=="string")try{JSON.parse(m),s[p]=m}catch{i.push(p)}else s[p]=JSON.stringify(m);let d=p.match(dt);d&&s[p]&&(n[d[1]]=`__vite__define__${s[p]}`)}i.length&&t.warn(`The following keys: ${Oe.yellow(Oe.underline(i.join(", ")))} declared in 'define' cannot be parsed as regular code snippets.`);let c={},a={};c["import.meta.hot"]="undefined";for(let p in o.env)c[`import.meta.env.${p}`]=JSON.stringify(o.env[p]);return Object.assign(a,{"import.meta.env":JSON.stringify({...o.env,...n}).replace(/"__vite__define__(.+?)"([,}])/g,(p,m,d)=>`${m.replace(/(^\\")|(\\"$)/g,'"')}${d}`)}),{...c,...s,...a,...e}}async function Ce(o,t,e){let r=ee(e.include),s=ee(e.exclude),n=Y(t),{httpProxies:i}=V(t.server.proxy||{});i.push(...ee(e.prefix));let c=ee(e.wsPrefix),a={};try{let l=q(t.root,["package.json"]);l&&(a=JSON.parse(l))}catch{}let p=e.build.dist,m=await xt(process.cwd(),r,s),d=N.join(t.root,`mock-data-${Date.now()}.js`);await Z.writeFile(d,m,"utf-8");let{code:h,deps:y}=await K(d,{define:n,alias:t.resolve.alias}),P=vt(y);await Z.unlink(d);let u=[{filename:N.join(p,"mock-data.js"),source:h},{filename:N.join(p,"index.js"),source:bt(i,c,e.cookiesOptions,e.priority,e.build.serverPort)},{filename:N.join(p,"package.json"),source:Mt(a,P)}];try{if(N.isAbsolute(p)){await Z.rm(p,{recursive:!0}),ft.mkdirSync(p,{recursive:!0});for(let{filename:l,source:f}of u)await Z.writeFile(l,f,"utf-8")}else for(let{filename:l,source:f}of u)o.emitFile({type:"asset",fileName:l,source:f})}catch{}}function vt(o){let t=new Set,e=[ye,"connect","cors"];return Object.keys(o).forEach(r=>{o[r].imports.filter(n=>n.external&&!n.path.startsWith("<define:")).map(n=>n.path).forEach(n=>{!e.includes(n)&&!kt(n)&&t.add(n)})}),Array.from(t)}function Mt(o,t){let{dependencies:e={},devDependencies:r={}}=o,s={...e,...r},n={name:"mock-server",type:"module",scripts:{start:"node index.js"},dependencies:{connect:"^3.7.0","vite-plugin-mock-dev-server":`^${ve}`,cors:"^2.8.5"},pnpm:{peerDependencyRules:{ignoreMissing:["vite"]}}};return t.forEach(i=>{n.dependencies[i]=s[i]||"latest"}),JSON.stringify(n,null,2)}function bt(o,t,e={},r={},s=8080){return`import { createServer } from 'node:http';
import{toArray as co}from"@pengzhanbo/utils";import ft from"node:fs";import Z from"node:fs/promises";import N from"node:path";import{toArray as ee}from"@pengzhanbo/utils";import gt from"fast-glob";import kt from"is-core-module";import{createFilter as ht,normalizePath as yt}from"vite";var ye="vite-plugin-mock-dev-server",ve="1.3.3";import xe,{promises as pe}from"node:fs";import{createRequire as ot}from"node:module";import ae from"node:path";import{pathToFileURL as rt}from"node:url";import{build as nt}from"esbuild";import st from"json5";import ie from"node:fs";import ce from"node:path";import{parse as Ke}from"node:querystring";import{URL as Xe,fileURLToPath as Ye}from"node:url";import Ze from"debug";import{match as et}from"path-to-regexp";var tt=o=>o!==null&&typeof o=="object"&&typeof o.pipe=="function",Me=o=>tt(o)&&o.readable!==!1&&typeof o._read=="function"&&typeof o._readableState=="object";function be(o){return ce.dirname(Ye(o))}var Q=Ze("vite:mock-dev-server");function q(o,t,e){for(let s of t){let n=ce.join(o,s);if(ie.existsSync(n)&&ie.statSync(n).isFile()){let i=e!=null&&e.pathOnly?n:ie.readFileSync(n,"utf-8");if(!(e!=null&&e.predicate)||e.predicate(i))return i}}let r=ce.dirname(o);if(r!==o&&(!(e!=null&&e.rootDir)||r.startsWith(e==null?void 0:e.rootDir)))return q(r,t,e)}var V=(o={})=>{let t=[],e=[];return Object.keys(o).forEach(r=>{var n,i;let s=o[r];typeof s=="string"||!s.ws&&!((n=s.target)!=null&&n.toString().startsWith("ws:"))&&!((i=s.target)!=null&&i.toString().startsWith("wss:"))?t.push(r):e.push(r)}),{httpProxies:t,wsProxies:e}};function I(o,t){return o[0]==="^"&&new RegExp(o).test(t)||t.startsWith(o)}function B(o,t){return(et(o,{decode:decodeURIComponent})(t)||{params:{}}).params||{}}function W(o){let t=new Xe(o,"http://example.com"),e=decodeURIComponent(t.pathname),r=Ke(t.search.replace(/^\?/,""));return{pathname:e,query:r}}var it={name:"externalize-deps",setup(o){o.onResolve({filter:/.*/},({path:t})=>{if(t[0]!=="."&&!ae.isAbsolute(t))return{external:!0}})}},ct={name:"json5-loader",setup(o){o.onLoad({filter:/\.json5$/},async({path:t})=>{let e=await pe.readFile(t,"utf-8");return{contents:`export default ${JSON.stringify(st.parse(e))}`,loader:"js"}})}},at={name:"json-loader",setup(o){o.onLoad({filter:/\.json$/},async({path:t})=>({contents:`export default ${await pe.readFile(t,"utf-8")}`,loader:"js"}))}},pt=o=>({name:"alias-plugin",setup(t){t.onResolve({filter:/.*/},async({path:e})=>{let r=o.find(({find:c})=>lt(c,e));if(!r)return null;let{find:s,replacement:n}=r;return{path:(await t.resolve(e.replace(s,n),{kind:"import-statement",resolveDir:n,namespace:"file"})).path,external:!1}})}});function lt(o,t){return o instanceof RegExp?o.test(t):t.length<o.length?!1:t===o?!0:t.startsWith(`${o}/`)}async function K(o,t){var n;let{isESM:e=!0,define:r,alias:s}=t;try{let i=await nt({entryPoints:[o],outfile:"out.js",write:!1,target:["node14.18","node16"],platform:"node",bundle:!0,metafile:!0,format:e?"esm":"cjs",define:r,plugins:[pt(s),it,at,ct]});return{code:i.outputFiles[0].text,deps:((n=i.metafile)==null?void 0:n.inputs)||{}}}catch(i){console.error(i)}return{code:"",deps:{}}}var ut=be(import.meta.url),T=ot(ut);async function we(o,t,e,r){if(e){let s=`${o}.timestamp-${Date.now()}`,n=`${s}.mjs`,i=`${rt(s)}.mjs`;await pe.writeFile(n,t,"utf8");try{return await import(i)}finally{try{xe.unlinkSync(n)}catch{}}}else{o=ae.resolve(r,o);let s=ae.extname(o),n=xe.realpathSync(o),i=s in T.extensions?s:".js",c=T.extensions[i];T.extensions[i]=(p,m)=>{m===n?p._compile(t,m):c(p,m)},delete T.cache[T.resolve(o)];let a=T(o);return T.extensions[i]=c,a.__esModule?a:{default:a}}}import Oe from"picocolors";import{isBoolean as mt}from"@pengzhanbo/utils";import $ from"picocolors";var Se={silent:0,error:1,warn:2,info:3,debug:4};function X(o,t="info"){o=`[${o}]`;function e(s,n,i){if(i=mt(i)?i?t:"error":i,Se[i]>=Se[s]){let a=s==="info"||s==="debug"?"log":s,p=s==="debug"?$.magenta($.bold(o)):s==="info"?$.cyan($.bold(o)):s==="warn"?$.yellow($.bold(o)):$.red($.bold(o)),m=`${$.dim(new Date().toLocaleTimeString())} ${p} ${n}`;console[a](m)}}return{debug(s,n=t){e("debug",s,n)},info(s,n=t){e("info",s,n)},warn(s,n=t){e("warn",s,n)},error(s,n=t){e("error",s,n)}}}var dt=/import\.meta\.env\.(.+)/;function Y(o){let t=X("vite:mock-dev-server","warn"),e={},r=process.env.NODE_ENV||o.mode;Object.assign(e,{"process.env.NODE_ENV":JSON.stringify(r),"global.process.env.NODE_ENV":JSON.stringify(r),"globalThis.process.env.NODE_ENV":JSON.stringify(r),__vite_process_env_NODE_ENV:JSON.stringify(r)});let s={},n={},i=[];for(let p in o.define){let m=o.define[p];if(typeof m=="string")try{JSON.parse(m),s[p]=m}catch{i.push(p)}else s[p]=JSON.stringify(m);let d=p.match(dt);d&&s[p]&&(n[d[1]]=`__vite__define__${s[p]}`)}i.length&&t.warn(`The following keys: ${Oe.yellow(Oe.underline(i.join(", ")))} declared in 'define' cannot be parsed as regular code snippets.`);let c={},a={};c["import.meta.hot"]="undefined";for(let p in o.env)c[`import.meta.env.${p}`]=JSON.stringify(o.env[p]);return Object.assign(a,{"import.meta.env":JSON.stringify({...o.env,...n}).replace(/"__vite__define__(.+?)"([,}])/g,(p,m,d)=>`${m.replace(/(^\\")|(\\"$)/g,'"')}${d}`)}),{...c,...s,...a,...e}}async function Ce(o,t,e){let r=ee(e.include),s=ee(e.exclude),n=Y(t),{httpProxies:i}=V(t.server.proxy||{});i.push(...ee(e.prefix));let c=ee(e.wsPrefix),a={};try{let l=q(t.root,["package.json"]);l&&(a=JSON.parse(l))}catch{}let p=e.build.dist,m=await xt(process.cwd(),r,s),d=N.join(t.root,`mock-data-${Date.now()}.js`);await Z.writeFile(d,m,"utf-8");let{code:h,deps:y}=await K(d,{define:n,alias:t.resolve.alias}),P=vt(y);await Z.unlink(d);let u=[{filename:N.join(p,"mock-data.js"),source:h},{filename:N.join(p,"index.js"),source:bt(i,c,e.cookiesOptions,e.priority,e.build.serverPort)},{filename:N.join(p,"package.json"),source:Mt(a,P)}];try{if(N.isAbsolute(p)){await Z.rm(p,{recursive:!0}),ft.mkdirSync(p,{recursive:!0});for(let{filename:l,source:f}of u)await Z.writeFile(l,f,"utf-8")}else for(let{filename:l,source:f}of u)o.emitFile({type:"asset",fileName:l,source:f})}catch{}}function vt(o){let t=new Set,e=[ye,"connect","cors"];return Object.keys(o).forEach(r=>{o[r].imports.filter(n=>n.external&&!n.path.startsWith("<define:")).map(n=>n.path).forEach(n=>{!e.includes(n)&&!kt(n)&&t.add(n)})}),Array.from(t)}function Mt(o,t){let{dependencies:e={},devDependencies:r={}}=o,s={...e,...r},n={name:"mock-server",type:"module",scripts:{start:"node index.js"},dependencies:{connect:"^3.7.0","vite-plugin-mock-dev-server":`^${ve}`,cors:"^2.8.5"},pnpm:{peerDependencyRules:{ignoreMissing:["vite"]}}};return t.forEach(i=>{n.dependencies[i]=s[i]||"latest"}),JSON.stringify(n,null,2)}function bt(o,t,e={},r={},s=8080){return`import { createServer } from 'node:http';
import connect from 'connect';

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

});
export default transformMockData(mockList);`}import{isBoolean as ro,toArray as se}from"@pengzhanbo/utils";import no from"cors";import{pathToRegexp as so}from"path-to-regexp";import{Buffer as Ie}from"node:buffer";import{isArray as oe,isEmptyObject as Dt,isFunction as re,random as Et,sleep as Lt,timestamp as He}from"@pengzhanbo/utils";import _t from"cookies";import Tt from"http-status";import*as A from"mime-types";import{pathToRegexp as It}from"path-to-regexp";import k from"picocolors";import{isArray as wt,isEmptyObject as Pe,isString as te,sortBy as je,uniq as Re}from"@pengzhanbo/utils";import{parse as St,pathToRegexp as We}from"path-to-regexp";var le={};function J(o){if(le[o])return le[o];let t=St(o),e=[];for(let r of t)if(!te(r))e.push(r);else{let s=r[0]==="/",n=s?r.slice(1).split("/"):r.split("/");e.push(`${s?"/":""}${n[0]}`,...n.slice(1).map(i=>`/${i}`))}return le[o]=e,e}function Ot(o){let t=o.map(e=>J(e).length);return t=t.length===0?[1]:t,Math.max(...t)+2}function Ct(o){let t=J(o),e=0;for(let r=0;r<t.length;r++){let s=t[r];te(s)||(e+=10**(r+1)),e+=10**(r+1)}return e}function Pt(o){let t=[],e=[];for(let r of o){let n=J(r).filter(i=>typeof i!="string").length;e[n]||(e[n]=[]),e[n].push(r)}for(let r of e.filter(s=>s&&s.length>0))t=[...t,...je(r,Ct)];return t}function Rt(o){let t=Ot(o);return je(o,e=>{let r=J(e),s=r.filter(c=>typeof c!="string");if(s.length===0)return 0;let n=s.length,i=0;for(let c=0;c<r.length;c++){let a=r[c],p=!te(a),{pattern:m="",modifier:d,prefix:h,name:y}=p?a:{},P=m&&m.includes(".*"),u=h==="/",l=te(y);i+=p&&u?1:0,c===r.length-1&&P?n+=5*10**t:P?n+=3*10**(t-1):m&&(u?n+=(l?2:1)*10**(i+1):n-=1*10**i),d==="+"&&(n+=1*10**(t-1)),d==="*"&&(n+=1*10**(t-1)+1),d==="?"&&(n+=1*10**(i+(u?1:0)))}return n})}function $e(o,t,e){let r=Rt(Pt(o.filter(y=>We(y).test(t)))),{global:s=[],special:n={}}=e;if(s.length===0&&Pe(n)||r.length===0)return r;let[i,c]=Wt(r),a=s.filter(y=>c.includes(y));if(a.length>0&&(r=Re([...i,...a,...c])),Pe(n))return r;let p=Object.keys(n).filter(y=>r.includes(y))[0];if(!p)return r;let m=n[p],{rules:d,when:h}=wt(m)?{rules:m,when:[]}:m;return d.includes(r[0])&&(h.length===0||h.some(y=>We(y).test(t)))&&(r=Re([p,...r])),r}function Wt(o){let t=[],e=[];for(let r of o)J(r).filter(i=>typeof i!="string").length>0?e.push(r):t.push(r);return[t,e]}import ue from"co-body";import jt from"formidable";async function De(o,t){var s;let e=o.method.toUpperCase();if(["GET","DELETE","HEAD"].includes(e))return;let r=((s=o.headers["content-type"])==null?void 0:s.toLocaleLowerCase())||"";try{if(r.startsWith("application/json"))return await ue.json(o);if(r.startsWith("application/x-www-form-urlencoded"))return await ue.form(o);if(r.startsWith("text/plain"))return await ue.text(o);if(r.startsWith("multipart/form-data"))return await $t(o,t)}catch(n){console.error(n)}}async function $t(o,t){let e=jt(t);return new Promise((r,s)=>{e.parse(o,(n,i,c)=>{if(n){s(n);return}r({...i,...c})})})}import{isArray as Ee,isObject as Le}from"@pengzhanbo/utils";function _e(o,t){return E(o.headers,t.headers)&&E(o.body,t.body)&&E(o.params,t.params)&&E(o.query,t.query)&&E(o.refererQuery,t.refererQuery)}function E(o,t){if(!t)return!0;for(let e in t)if(!Te(o[e],t[e]))return!1;return!0}function Te(o,t){if(Ee(o)&&Ee(t)){let e=new Set;return t.every(r=>o.some((s,n)=>{if(e.has(n))return!1;let i=Te(s,r);return i&&e.add(n),i}))}return Le(o)&&Le(t)?E(o,t):Object.is(o,t)}function Fe(o,{formidableOptions:t={},proxies:e,cookiesOptions:r,logger:s,priority:n={}}){return async function(i,c,a){let p=He(),{query:m,pathname:d}=W(i.url);if(!d||e.length===0||!e.some(x=>I(x,i.url)))return a();let h=o.mockData,y=$e(Object.keys(h),d,n);if(y.length===0)return a();let{query:P}=W(i.headers.referer||""),u=await De(i,t),l=new _t(i,c,r),f=l.get.bind(l),v=i.method.toUpperCase(),M,C;for(let x of y)if(M=Nt(h[x],s,{pathname:d,method:v,request:{query:m,refererQuery:P,body:u,headers:i.headers,getCookie:f}}),M){C=x;break}if(!M){let x=y.map(U=>U===C?k.underline(k.bold(U)):k.dim(U)).join(", ");return s.warn(`${k.green(d)} matches ${x} , but mock data is not found.`),a()}let g=i,b=c;g.body=u,g.query=m,g.refererQuery=P,g.params=B(M.url,d),g.getCookie=f,b.setCookie=l.set.bind(l);let{body:R,delay:L,type:_="json",response:D,status:j=200,statusText:G,log:F,__filepath__:w}=M;if(me(b,j,G),await Ht(g,b,M,s),await Ft(g,b,M,s),s.info(Bt(g,w),F),s.debug(`${k.magenta("DEBUG")} ${k.underline(d)} matches: [ ${y.map(x=>x===C?k.underline(k.bold(x)):k.dim(x)).join(", ")} ]
export default transformMockData(mockList);`}import{isBoolean as ro,toArray as se}from"@pengzhanbo/utils";import no from"cors";import{pathToRegexp as so}from"path-to-regexp";import{Buffer as Ie}from"node:buffer";import{isArray as oe,isEmptyObject as Dt,isFunction as re,random as Et,sleep as Lt,timestamp as He}from"@pengzhanbo/utils";import _t from"cookies";import Tt from"http-status";import*as A from"mime-types";import{pathToRegexp as It}from"path-to-regexp";import k from"picocolors";import{isArray as wt,isEmptyObject as Pe,isString as te,sortBy as je,uniq as Re}from"@pengzhanbo/utils";import{parse as St,pathToRegexp as We}from"path-to-regexp";var le={};function J(o){if(le[o])return le[o];let t=St(o),e=[];for(let r of t)if(!te(r))e.push(r);else{let s=r[0]==="/",n=s?r.slice(1).split("/"):r.split("/");e.push(`${s?"/":""}${n[0]}`,...n.slice(1).map(i=>`/${i}`))}return le[o]=e,e}function Ot(o){let t=o.map(e=>J(e).length);return t=t.length===0?[1]:t,Math.max(...t)+2}function Ct(o){let t=J(o),e=0;for(let r=0;r<t.length;r++){let s=t[r];te(s)||(e+=10**(r+1)),e+=10**(r+1)}return e}function Pt(o){let t=[],e=[];for(let r of o){let n=J(r).filter(i=>typeof i!="string").length;e[n]||(e[n]=[]),e[n].push(r)}for(let r of e.filter(s=>s&&s.length>0))t=[...t,...je(r,Ct).reverse()];return t}function Rt(o){let t=Ot(o);return je(o,e=>{let r=J(e),s=r.filter(c=>typeof c!="string");if(s.length===0)return 0;let n=s.length,i=0;for(let c=0;c<r.length;c++){let a=r[c],p=!te(a),{pattern:m="",modifier:d,prefix:h,name:y}=p?a:{},P=m&&m.includes(".*"),u=h==="/",l=te(y);i+=p&&u?1:0,c===r.length-1&&P?n+=5*10**(r.length===1?t+1:t):P?n+=3*10**(t-1):m&&(u?n+=(l?2:1)*10**(i+1):n-=1*10**i),d==="+"&&(n+=1*10**(t-1)),d==="*"&&(n+=1*10**(t-1)+1),d==="?"&&(n+=1*10**(i+(u?1:0)))}return n})}function $e(o,t,e){let r=Rt(Pt(o.filter(y=>We(y).test(t)))),{global:s=[],special:n={}}=e;if(s.length===0&&Pe(n)||r.length===0)return r;let[i,c]=Wt(r),a=s.filter(y=>c.includes(y));if(a.length>0&&(r=Re([...i,...a,...c])),Pe(n))return r;let p=Object.keys(n).filter(y=>r.includes(y))[0];if(!p)return r;let m=n[p],{rules:d,when:h}=wt(m)?{rules:m,when:[]}:m;return d.includes(r[0])&&(h.length===0||h.some(y=>We(y).test(t)))&&(r=Re([p,...r])),r}function Wt(o){let t=[],e=[];for(let r of o)J(r).filter(i=>typeof i!="string").length>0?e.push(r):t.push(r);return[t,e]}import ue from"co-body";import jt from"formidable";async function De(o,t){var s;let e=o.method.toUpperCase();if(["GET","DELETE","HEAD"].includes(e))return;let r=((s=o.headers["content-type"])==null?void 0:s.toLocaleLowerCase())||"";try{if(r.startsWith("application/json"))return await ue.json(o);if(r.startsWith("application/x-www-form-urlencoded"))return await ue.form(o);if(r.startsWith("text/plain"))return await ue.text(o);if(r.startsWith("multipart/form-data"))return await $t(o,t)}catch(n){console.error(n)}}async function $t(o,t){let e=jt(t);return new Promise((r,s)=>{e.parse(o,(n,i,c)=>{if(n){s(n);return}r({...i,...c})})})}import{isArray as Ee,isObject as Le}from"@pengzhanbo/utils";function _e(o,t){return E(o.headers,t.headers)&&E(o.body,t.body)&&E(o.params,t.params)&&E(o.query,t.query)&&E(o.refererQuery,t.refererQuery)}function E(o,t){if(!t)return!0;for(let e in t)if(!Te(o[e],t[e]))return!1;return!0}function Te(o,t){if(Ee(o)&&Ee(t)){let e=new Set;return t.every(r=>o.some((s,n)=>{if(e.has(n))return!1;let i=Te(s,r);return i&&e.add(n),i}))}return Le(o)&&Le(t)?E(o,t):Object.is(o,t)}function Fe(o,{formidableOptions:t={},proxies:e,cookiesOptions:r,logger:s,priority:n={}}){return async function(i,c,a){let p=He(),{query:m,pathname:d}=W(i.url);if(!d||e.length===0||!e.some(x=>I(x,i.url)))return a();let h=o.mockData,y=$e(Object.keys(h),d,n);if(y.length===0)return a();let{query:P}=W(i.headers.referer||""),u=await De(i,t),l=new _t(i,c,r),f=l.get.bind(l),v=i.method.toUpperCase(),M,C;for(let x of y)if(M=Nt(h[x],s,{pathname:d,method:v,request:{query:m,refererQuery:P,body:u,headers:i.headers,getCookie:f}}),M){C=x;break}if(!M){let x=y.map(U=>U===C?k.underline(k.bold(U)):k.dim(U)).join(", ");return s.warn(`${k.green(d)} matches ${x} , but mock data is not found.`),a()}let g=i,b=c;g.body=u,g.query=m,g.refererQuery=P,g.params=B(M.url,d),g.getCookie=f,b.setCookie=l.set.bind(l);let{body:R,delay:L,type:_="json",response:D,status:j=200,statusText:G,log:F,__filepath__:w}=M;if(me(b,j,G),await Ht(g,b,M,s),await Ft(g,b,M,s),s.info(Bt(g,w),F),s.debug(`${k.magenta("DEBUG")} ${k.underline(d)} matches: [ ${y.map(x=>x===C?k.underline(k.bold(x)):k.dim(x)).join(", ")} ]
`),R){try{let x=re(R)?await R(g):R;await Ne(p,L),Ut(b,x,_)}catch(x){s.error(`${k.red(`mock error at ${d}`)}

@@ -48,0 +48,0 @@ ${x}

{
"name": "vite-plugin-mock-dev-server",
"version": "1.3.2",
"version": "1.3.3",
"keywords": [

@@ -5,0 +5,0 @@ "vite",

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