@schmock/express 2.1.6 → 2.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire as a}from"node:module";var o=a(import.meta.url);var y=["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"];function g(V){return y.includes(V)}function j(V){let $=V.toUpperCase();if(!g($))throw Error(`Invalid HTTP method: "${V}"`);return $}function x(V){return V.endsWith("/")&&V!=="/"?V.slice(0,-1):V}function H(V){let{status:$,body:J}=V;return $===404&&J!==null&&typeof J==="object"&&"code"in J&&J.code==="ROUTE_NOT_FOUND"}function b(V){return Array.isArray(V)&&(V.length===2||V.length===3)&&typeof V[0]==="number"&&V[0]>=100&&V[0]<=599}function D(V){return V instanceof Error?V.message:"Unknown error"}class T extends Error{code;context;constructor(V,$,J){super(V);this.code=$;this.context=J;if(this.name="SchmockError",typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor)}}class P extends T{constructor(V,$){super(`Route not found: ${V} ${$}`,"ROUTE_NOT_FOUND",{method:V,path:$});this.name="RouteNotFoundError"}}class E extends T{constructor(V,$){super(`Invalid route key format: "${V}". ${$}`,"ROUTE_PARSE_ERROR",{routeKey:V,reason:$});this.name="RouteParseError"}}class C extends T{constructor(V,$){super(`Plugin "${V}" failed: ${$.message}`,"PLUGIN_ERROR",{pluginName:V,originalError:$});this.name="PluginError"}}class S extends T{constructor(V,$){super(`Invalid route definition for "${V}": ${$}`,"ROUTE_DEFINITION_ERROR",{routeKey:V,reason:$});this.name="RouteDefinitionError"}}function f(V){let $={};for(let[J,X]of Object.entries(V.headers))if(typeof X==="string")$[J]=X;return $}function R(V){let $={};return V.searchParams.forEach((J,X)=>{$[X]=J}),$}var s=10485760;function k(V,$,J=s){return new Promise((X,Y)=>{let G=[],L=0;V.on("error",Y),V.on("data",(Z)=>{if(L+=Z.length,L>J){V.destroy(),Y(Object.assign(Error("Request body too large"),{status:413}));return}G.push(Z)}),V.on("end",()=>{let Z=Buffer.concat(G).toString();if(!Z){X(void 0);return}if(($["content-type"]??"").includes("json"))try{X(JSON.parse(Z))}catch{X(Z)}else X(Z)})})}function v(V,$,J){let X={...$.headers,...J};if(!X["content-type"]&&$.body!==void 0&&typeof $.body!=="string")X["content-type"]="application/json";let Y=$.body===void 0?void 0:typeof $.body==="string"?$.body:JSON.stringify($.body);V.writeHead($.status,X),V.end(Y)}function t(V){let $=V.indexOf("?"),J=$===-1?V:V.slice(0,$);if(J.includes("://"))try{return new URL(J).pathname}catch{}if(!J.startsWith("/"))return`/${J}`;return J}function r(V){if(!V.includes("://"))return null;try{return new URL(V).origin}catch{return null}}function e(V){if(V.includes("://"))try{let $=new URL(V),J=$.pathname,X=J==="/"?"":J.replace(/\/$/,"");return{origin:$.origin,path:X}}catch{}return{origin:null,path:V.replace(/\/$/,"")}}function V0(V){let $=V.indexOf("?");if($===-1)return{};let J=new URLSearchParams(V.slice($+1)),X={};return J.forEach((Y,G)=>{X[G]=Y}),X}function $0(V,$){let J={},X=$?.headers??(V instanceof Request?V.headers:void 0);if(!X)return J;if(X instanceof Headers)X.forEach((Y,G)=>{J[G]=Y});else if(Array.isArray(X))for(let[Y,G]of X)J[Y.toLowerCase()]=G;else for(let Y of Object.keys(X))J[Y.toLowerCase()]=X[Y];return J}async function J0(V,$){let J=$?.body??(V instanceof Request?V.body:null);if(J===null||J===void 0)return;if(typeof J==="string")try{return JSON.parse(J)}catch{return J}if(J instanceof URLSearchParams){let X={};return J.forEach((Y,G)=>{X[G]=Y}),X}if(V instanceof Request&&!$?.body&&V.body)try{return await V.clone().json()}catch{try{return await V.clone().text()}catch{return}}return}function q(V,$={}){let{baseUrl:J,passthrough:X=!0,beforeRequest:Y,beforeResponse:G,errorFormatter:L}=$,Z=globalThis.fetch,_=!0;return globalThis.fetch=async(A,W)=>{let z=A instanceof Request?A.url:A instanceof URL?A.href:A,B=t(z);if(J){let{origin:K,path:U}=e(J);if(K){if(r(z)!==K)return Z(A,W)}if(U){if(!(B===U||B.startsWith(`${U}/`)))return Z(A,W)}}let O=A instanceof Request?A.method:W?.method??"GET",Q=$0(A,W),N=V0(z),F=await J0(A,W),M={method:O,path:B,headers:Q,body:F,query:N};try{if(Y){let I=await Y(M);if(I)M=I}let K=await V(j(M.method),M.path,{headers:M.headers,body:M.body,query:M.query});if(H(K)){if(X)return Z(A,W);return new Response(JSON.stringify({error:"No matching mock route found",code:"ROUTE_NOT_FOUND"}),{status:404,headers:{"content-type":"application/json"}})}let U=K;if(G){let I=await G(U,M);if(I)U=I}let w=new Headers(U.headers);if(!w.has("content-type")&&U.body!==null&&U.body!==void 0)w.set("content-type","application/json");let n=U.body===null||U.body===void 0?null:typeof U.body==="string"?U.body:JSON.stringify(U.body);return new Response(n,{status:U.status,headers:w})}catch(K){if(L){let U=L(K instanceof Error?K:Error(String(K)));return new Response(JSON.stringify(U),{status:500,headers:{"content-type":"application/json"}})}throw K}},{restore(){if(_)globalThis.fetch=Z,_=!1},get active(){return _}}}function d(V){let $=V.match(/^(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS) (.+)$/);if(!$)throw new E(V,'Expected format: "METHOD /path" (e.g., "GET /users")');let[,J,X]=$,Y=[],G=X.split(/(:[a-zA-Z0-9_-]+)/g).map((Z)=>{let _=Z.match(/^:([a-zA-Z0-9_-]+)$/);if(_)return Y.push(_[1]),"([^/]+)";return Z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}).join(""),L=new RegExp(`^${G}$`);return{method:j(J),path:X,pattern:L,params:Y}}async function m(V,$,J,X){let Y=$,G=J;X.log("pipeline",`Running plugin pipeline for ${V.length} plugins`);for(let L of V){X.log("pipeline",`Processing plugin: ${L.name}`);try{let Z=await L.process(Y,G);if(!Z?.context)throw Error(`Plugin ${L.name} didn't return valid result`);if(Y=Z.context,Z.response!==void 0&&(G===void 0||G===null))X.log("pipeline",`Plugin ${L.name} generated response`),G=Z.response;else if(Z.response!==void 0&&G!==void 0)X.log("pipeline",`Plugin ${L.name} transformed response`),G=Z.response}catch(Z){if(X.log("pipeline",`Plugin ${L.name} failed: ${D(Z)}`),L.onError)try{let A=Z instanceof Error?Z:Error(D(Z)),W=await L.onError(A,Y);if(W){if(X.log("pipeline",`Plugin ${L.name} handled error`),W instanceof Error)throw new C(L.name,W);if(typeof W==="object"&&W!==null&&"status"in W){G=W;break}}}catch(A){if(A instanceof C)throw A;X.log("pipeline",`Plugin ${L.name} error handler failed: ${D(A)}`)}let _=Z instanceof Error?Z:Error(D(Z));throw new C(L.name,_)}}return{context:Y,response:G}}function X0(V){return typeof V==="object"&&V!==null&&"status"in V&&"body"in V}function c(V,$){let J=200,X=V,Y={},G=!1;if(X0(V))return{status:V.status,body:V.body,headers:V.headers||{}};if(b(V))[J,X,Y={}]=V,G=!0;if(X===null||X===void 0){if(!G)J=J===200?204:J;X=void 0}if(!Y["content-type"]&&$.contentType&&!G){if(Y["content-type"]=$.contentType,$.contentType==="text/plain"&&X!==void 0){if(typeof X==="object"&&!Buffer.isBuffer(X))X=JSON.stringify(X);else if(typeof X!=="string")X=String(X)}}return{status:J,body:X,headers:Y}}function l(V){return typeof V==="function"}function h(V,$,J,X){let Y=J.get(`${V} ${x($)}`);if(Y)return Y;for(let G of X)if(G.method===V&&G.params.length>0&&G.pattern.test($))return G;return}function i(V,$){let J=$.match(V.pattern);if(!J)return{};let X={};return V.params.forEach((Y,G)=>{X[Y]=J[G+1]}),X}class u{enabled;constructor(V=!1){this.enabled=V}log(V,$,J){if(!this.enabled)return;let Y=`[${new Date().toISOString()}] [SCHMOCK:${V.toUpperCase()}]`;if(J)console.log(`${Y} ${$}`,J);else console.log(`${Y} ${$}`)}time(V){if(!this.enabled)return;console.time(`[SCHMOCK] ${V}`)}timeEnd(V){if(!this.enabled)return;console.timeEnd(`[SCHMOCK] ${V}`)}}class p{globalConfig;routes=[];staticRoutes=new Map;plugins=[];logger;requestHistory=[];callableRef;server;serverInfo;interceptHandle=null;listeners=new Map;constructor(V={}){this.globalConfig=V;if(this.logger=new u(V.debug||!1),V.debug)this.logger.log("config","Debug mode enabled");this.logger.log("config","Callable mock instance created",{debug:V.debug,namespace:V.namespace,delay:V.delay})}defineRoute(V,$,J){if(!J.contentType)if(typeof $==="function")J.contentType="application/json";else if(typeof $==="string"||typeof $==="number"||typeof $==="boolean")J.contentType="text/plain";else if(Buffer.isBuffer($))J.contentType="application/octet-stream";else J.contentType="application/json";if(typeof $!=="function"&&J.contentType==="application/json")try{JSON.stringify($)}catch(L){throw new S(V,"Generator data is not valid JSON but contentType is application/json")}let X=d(V);if(this.routes.find((L)=>L.method===X.method&&L.path===X.path))return this.logger.log("warning",`Duplicate route: ${V} — first registration wins`),this;let G={pattern:X.pattern,params:X.params,method:X.method,path:X.path,generator:$,config:J};if(this.routes.push(G),X.params.length===0){let L=`${X.method} ${x(X.path)}`;this.staticRoutes.set(L,G)}return this.logger.log("route",`Route defined: ${V}`,{contentType:J.contentType,generatorType:typeof $,hasParams:X.params.length>0}),this}setCallableRef(V){this.callableRef=V}pipe(V){if(this.plugins.push(V),this.logger.log("plugin",`Registered plugin: ${V.name}@${V.version||"unknown"}`,{name:V.name,version:V.version,hasProcess:typeof V.process==="function",hasOnError:typeof V.onError==="function"}),V.install&&this.callableRef)V.install(this.callableRef);return this}history(V,$){if(V||$)return this.requestHistory.filter((J)=>(!V||J.method===V)&&(!$||J.path===$));return[...this.requestHistory]}called(V,$){if(V||$)return this.requestHistory.some((J)=>(!V||J.method===V)&&(!$||J.path===$));return this.requestHistory.length>0}callCount(V,$){if(V||$)return this.requestHistory.filter((J)=>(!V||J.method===V)&&(!$||J.path===$)).length;return this.requestHistory.length}lastRequest(V,$){if(V||$){let J=this.requestHistory.filter((X)=>(!V||X.method===V)&&(!$||X.path===$));return J[J.length-1]}return this.requestHistory[this.requestHistory.length-1]}getRoutes(){return this.routes.map((V)=>({method:V.method,path:V.path,hasParams:V.params.length>0}))}getState(){return{...this.globalConfig.state||{}}}on(V,$){let J=this.listeners.get(V);if(!J)J=new Set,this.listeners.set(V,J);return J.add($),this}off(V,$){return this.listeners.get(V)?.delete($),this}emit(V,$){let J=this.listeners.get(V);if(J)for(let X of J)X($)}reset(){if(this.interceptHandle?.restore(),this.interceptHandle=null,this.close(),this.routes=[],this.staticRoutes.clear(),this.plugins=[],this.requestHistory=[],this.listeners.clear(),this.globalConfig.state)for(let V of Object.keys(this.globalConfig.state))delete this.globalConfig.state[V];this.logger.log("lifecycle","Mock fully reset")}resetHistory(){this.requestHistory=[],this.logger.log("lifecycle","Request history cleared")}resetState(){if(this.globalConfig.state)for(let V of Object.keys(this.globalConfig.state))delete this.globalConfig.state[V];this.logger.log("lifecycle","State cleared")}listen(V=0,$="127.0.0.1"){if(this.server)throw new T("Server is already running","SERVER_ALREADY_RUNNING");return import("node:http").then(({createServer:J})=>this.#V(J,V,$))}#V(V,$,J){let X=V((Y,G)=>{(async()=>{let Z=new URL(Y.url??"/",`http://${Y.headers.host}`),_=j(Y.method??"GET"),A=Z.pathname,W=f(Y),z=R(Z),B=await k(Y,W),O=await this.handle(_,A,{headers:W,body:B,query:z});v(G,O)})().catch((Z)=>{if(!G.headersSent)G.writeHead(500,{"content-type":"application/json"});G.end(JSON.stringify({error:Z instanceof Error?Z.message:"Internal Server Error",code:"SERVER_ERROR"}))})});return this.server=X,new Promise((Y,G)=>{X.on("error",G),X.listen($,J,()=>{let L=X.address(),Z=L!==null&&typeof L==="object"?L.port:$;this.serverInfo={port:Z,hostname:J},this.logger.log("server",`Listening on ${J}:${Z}`),Y(this.serverInfo)})})}close(){if(!this.server)return;this.server.closeAllConnections(),this.server.close(),this.server=void 0,this.serverInfo=void 0,this.logger.log("server","Server stopped")}intercept(V){if(this.interceptHandle?.active)throw new T("Already intercepting. Call restore() first.","ALREADY_INTERCEPTING");return this.interceptHandle=q(($,J,X)=>this.handle($,J,X),V),this.interceptHandle}async handle(V,$,J){let X=performance.now(),Y=this.globalConfig.debug?crypto.randomUUID():"",G=J?.query||{},L=J?.headers||{};this.logger.log("request",`[${Y}] ${V} ${$}`,{headers:L,query:G,bodyType:J?.body?typeof J.body:"none"}),this.logger.time(`request-${Y}`),this.emit("request:start",{method:V,path:$,headers:L});try{let Z=$;if(this.globalConfig.namespace&&this.globalConfig.namespace!=="/"){let N=this.globalConfig.namespace.startsWith("/")?this.globalConfig.namespace:`/${this.globalConfig.namespace}`,F=$.startsWith("/")?$:`/${$}`;if(!(F===N||F.startsWith(N.endsWith("/")?N:`${N}/`))){this.logger.log("route",`[${Y}] Path doesn't match namespace ${N}`);let U=new P(V,$),w={status:404,body:{error:U.message,code:U.code},headers:{}};return this.emit("request:end",{method:V,path:$,status:404,duration:performance.now()-X}),this.logger.timeEnd(`request-${Y}`),w}let K=F.slice(N.length);Z=K.startsWith("/")?K:`/${K}`}let _=h(V,Z,this.staticRoutes,this.routes);if(!_){this.logger.log("route",`[${Y}] No route found for ${V} ${Z}`),this.emit("request:notfound",{method:V,path:Z});let N=new P(V,$),F={status:404,body:{error:N.message,code:N.code},headers:{}};return this.emit("request:end",{method:V,path:Z,status:404,duration:performance.now()-X}),this.logger.timeEnd(`request-${Y}`),F}this.logger.log("route",`[${Y}] Matched route: ${V} ${_.path}`);let A=i(_,Z);this.emit("request:match",{method:V,path:Z,routePath:_.path,params:A});let W={method:V,path:Z,params:A,query:G,headers:L,body:J?.body,state:this.globalConfig.state||{}},z;if(l(_.generator))z=await _.generator(W);else z=_.generator;let B={path:Z,route:_.config,method:V,params:A,query:G,headers:L,body:J?.body,state:new Map,routeState:this.globalConfig.state||{}};try{let N=await m(this.plugins,B,z,this.logger);B=N.context,z=N.response}catch(N){throw this.logger.log("error",`[${Y}] Plugin pipeline error: ${D(N)}`),N}let O=c(z,_.config);await this.applyDelay(_.config.delay),this.requestHistory.push({method:V,path:Z,params:A,query:G,headers:L,body:J?.body,timestamp:Date.now(),response:{status:O.status,body:O.body}});let Q=this.globalConfig.maxHistorySize;if(typeof Q==="number"&&Q>=0&&this.requestHistory.length>Q)this.requestHistory.splice(0,this.requestHistory.length-Q);return this.emit("request:end",{method:V,path:Z,status:O.status,duration:performance.now()-X}),this.logger.log("response",`[${Y}] Sending response ${O.status}`,{status:O.status,headers:O.headers,bodyType:typeof O.body}),this.logger.timeEnd(`request-${Y}`),O}catch(Z){this.logger.log("error",`[${Y}] Error processing request: ${D(Z)}`,Z);let _={status:500,body:{error:D(Z),code:Z instanceof T?Z.code:"INTERNAL_ERROR"},headers:{}};return await this.applyDelay(),this.emit("request:end",{method:V,path:$,status:500,duration:performance.now()-X}),this.logger.log("error",`[${Y}] Returning error response 500`),this.logger.timeEnd(`request-${Y}`),_}}async applyDelay(V){let $=V??this.globalConfig.delay;if(!$)return;let J=Array.isArray($)?Math.random()*($[1]-$[0])+$[0]:$;await new Promise((X)=>setTimeout(X,J))}}function Y0(V,$){if(V.status!=null)$.status(V.status);if(V.headers)Object.entries(V.headers).forEach(([J,X])=>{if(typeof X==="string")$.set(J,X)});if(V.body!==void 0)if(typeof V.body==="string")$.send(V.body);else $.json(V.body);else $.end()}function Z0(V){return Object.fromEntries(Object.entries(V).map(([$,J])=>[$,Array.isArray(J)?J[0]:J]).filter(($)=>typeof $[1]==="string"))}function G0(V){let $={};for(let[J,X]of Object.entries(V))if(typeof X==="string")$[J]=X;else if(Array.isArray(X))$[J]=X[0]?String(X[0]):"";else if(X!=null)$[J]=String(X);return $}function $1(V,$={}){let{errorFormatter:J,passErrorsToNext:X=!0,transformHeaders:Y=Z0,transformQuery:G=G0,beforeRequest:L,beforeResponse:Z}=$;return async(_,A,W)=>{try{let z;try{z=j(_.method)}catch{return W()}let B={method:z,path:_.path,headers:Y(_.headers),body:_.body,query:G(_.query)};if(L){let Q=await L(_,A);if(Q)B={...B,...Q,method:j(Q.method||B.method)}}let O=await V.handle(B.method,B.path,{headers:B.headers,body:B.body,query:B.query});if(H(O)){W();return}if(Z){let Q=await Z(O,_,A);if(Q)O=Q}if(J&&O.status===500&&O.body!==null&&typeof O.body==="object"&&"error"in O.body&&"code"in O.body){let Q=O.body,N=typeof Q.error==="string"?Q.error:"Unknown error",F=J(Error(N),_);A.status(500).json(F);return}Y0(O,A)}catch(z){if(J){let B=z instanceof Error?z:Error(String(z)),O=J(B,_);A.status(500).json(O)}else if(X)W(z);else A.status(500).json({error:z instanceof Error?z.message:"Internal Server Error",code:z instanceof T?z.code:"INTERNAL_ERROR"})}}}export{$1 as toExpress};
|
|
1
|
+
import{createRequire as a}from"node:module";var o=a(import.meta.url);var y=["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"];function g(V){return y.includes(V)}function F(V){let $=V.toUpperCase();if(!g($))throw Error(`Invalid HTTP method: "${V}"`);return $}function I(V){return V.endsWith("/")&&V!=="/"?V.slice(0,-1):V}function x(V){let{status:$,body:J}=V;return $===404&&J!==null&&typeof J==="object"&&"code"in J&&J.code==="ROUTE_NOT_FOUND"}function E(V){return Array.isArray(V)&&(V.length===2||V.length===3)&&typeof V[0]==="number"&&V[0]>=100&&V[0]<=599}function D(V){return V instanceof Error?V.message:"Unknown error"}class T extends Error{code;context;constructor(V,$,J){super(V);this.code=$;this.context=J;if(this.name="SchmockError",typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor)}}class P extends T{constructor(V,$){super(`Route not found: ${V} ${$}`,"ROUTE_NOT_FOUND",{method:V,path:$});this.name="RouteNotFoundError"}}class b extends T{constructor(V,$){super(`Invalid route key format: "${V}". ${$}`,"ROUTE_PARSE_ERROR",{routeKey:V,reason:$});this.name="RouteParseError"}}class H extends T{constructor(V,$){super(`Plugin "${V}" failed: ${$.message}`,"PLUGIN_ERROR",{pluginName:V,originalError:$});this.name="PluginError"}}class S extends T{constructor(V,$){super(`Invalid route definition for "${V}": ${$}`,"ROUTE_DEFINITION_ERROR",{routeKey:V,reason:$});this.name="RouteDefinitionError"}}function f(V){let $={};for(let[J,X]of Object.entries(V.headers))if(typeof X==="string")$[J]=X;return $}function k(V){let $={};return V.searchParams.forEach((J,X)=>{$[X]=J}),$}var s=10485760;function R(V,$,J=s){return new Promise((X,Y)=>{let G=[],_=0;V.on("error",Y),V.on("data",(Z)=>{if(_+=Z.length,_>J){V.destroy(),Y(Object.assign(Error("Request body too large"),{status:413}));return}G.push(Z)}),V.on("end",()=>{let Z=Buffer.concat(G).toString();if(!Z){X(void 0);return}if(($["content-type"]??"").includes("json"))try{X(JSON.parse(Z))}catch{X(Z)}else X(Z)})})}function v(V,$,J){let X={...$.headers,...J};if(!X["content-type"]&&$.body!==void 0&&typeof $.body!=="string")X["content-type"]="application/json";let Y=$.body===void 0?void 0:typeof $.body==="string"?$.body:JSON.stringify($.body);V.writeHead($.status,X),V.end(Y)}function t(V){let $=V.indexOf("?"),J=$===-1?V:V.slice(0,$);if(J.includes("://"))try{return new URL(J).pathname}catch{}if(!J.startsWith("/"))return`/${J}`;return J}function r(V){if(!V.includes("://"))return null;try{return new URL(V).origin}catch{return null}}function e(V){if(V.includes("://"))try{let $=new URL(V),J=$.pathname,X=J==="/"?"":J.replace(/\/$/,"");return{origin:$.origin,path:X}}catch{}return{origin:null,path:V.replace(/\/$/,"")}}function V0(V){let $=V.indexOf("?");if($===-1)return{};let J=new URLSearchParams(V.slice($+1)),X={};return J.forEach((Y,G)=>{X[G]=Y}),X}function $0(V,$){let J={},X=$?.headers??(V instanceof Request?V.headers:void 0);if(!X)return J;if(X instanceof Headers)X.forEach((Y,G)=>{J[G.toLowerCase()]=Y});else if(Array.isArray(X))for(let[Y,G]of X)J[Y.toLowerCase()]=G;else for(let Y of Object.keys(X))J[Y.toLowerCase()]=X[Y];return J}async function J0(V,$){let J=$?.body??(V instanceof Request?V.body:null);if(J===null||J===void 0)return;if(typeof J==="string")try{return JSON.parse(J)}catch{return J}if(J instanceof URLSearchParams){let X={};return J.forEach((Y,G)=>{X[G]=Y}),X}if(V instanceof Request&&!$?.body&&V.body)try{return await V.clone().json()}catch{try{return await V.clone().text()}catch{return}}return}function q(V,$={}){let{baseUrl:J,passthrough:X=!0,beforeRequest:Y,beforeResponse:G,errorFormatter:_}=$,Z=globalThis.fetch,L=!0;return globalThis.fetch=async(A,W)=>{let U=A instanceof Request?A.url:A instanceof URL?A.href:A,B=t(U);if(J){let{origin:K,path:z}=e(J);if(K){if(r(U)!==K)return Z(A,W)}if(z){if(!(B===z||B.startsWith(`${z}/`)))return Z(A,W)}}let O=A instanceof Request?A.method:W?.method??"GET",Q=$0(A,W),N=V0(U),j=await J0(A,W),M={method:O,path:B,headers:Q,body:j,query:N};try{if(Y){let C=await Y(M);if(C)M=C}let K=await V(F(M.method),M.path,{headers:M.headers,body:M.body,query:M.query});if(x(K)){if(X)return Z(A,W);return new Response(JSON.stringify({error:"No matching mock route found",code:"ROUTE_NOT_FOUND"}),{status:404,headers:{"content-type":"application/json"}})}let z=K;if(G){let C=await G(z,M);if(C)z=C}let w=new Headers(z.headers);if(!w.has("content-type")&&z.body!==null&&z.body!==void 0)w.set("content-type","application/json");let n=z.body===null||z.body===void 0?null:typeof z.body==="string"?z.body:JSON.stringify(z.body);return new Response(n,{status:z.status,headers:w})}catch(K){if(_){let z=_(K instanceof Error?K:Error(String(K)));return new Response(JSON.stringify(z),{status:500,headers:{"content-type":"application/json"}})}throw K}},{restore(){if(L)globalThis.fetch=Z,L=!1},get active(){return L}}}function d(V){let $=V.match(/^(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS) (.+)$/);if(!$)throw new b(V,'Expected format: "METHOD /path" (e.g., "GET /users")');let[,J,X]=$,Y=[],G=X.split(/(:[a-zA-Z0-9_-]+)/g).map((Z)=>{let L=Z.match(/^:([a-zA-Z0-9_-]+)$/);if(L)return Y.push(L[1]),"([^/]+)";return Z.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}).join(""),_=new RegExp(`^${G}$`);return{method:F(J),path:X,pattern:_,params:Y}}async function m(V,$,J,X){let Y=$,G=J;X.log("pipeline",`Running plugin pipeline for ${V.length} plugins`);for(let _ of V){X.log("pipeline",`Processing plugin: ${_.name}`);try{let Z=await _.process(Y,G);if(!Z?.context)throw Error(`Plugin ${_.name} didn't return valid result`);if(Y=Z.context,Z.response!==void 0&&(G===void 0||G===null))X.log("pipeline",`Plugin ${_.name} generated response`),G=Z.response;else if(Z.response!==void 0&&G!==void 0)X.log("pipeline",`Plugin ${_.name} transformed response`),G=Z.response}catch(Z){if(X.log("pipeline",`Plugin ${_.name} failed: ${D(Z)}`),_.onError)try{let A=Z instanceof Error?Z:Error(D(Z)),W=await _.onError(A,Y);if(W){if(X.log("pipeline",`Plugin ${_.name} handled error`),W instanceof Error)throw new H(_.name,W);if(E(W)||typeof W==="object"&&W!==null&&"status"in W){G=W;break}}}catch(A){if(A instanceof H)throw A;X.log("pipeline",`Plugin ${_.name} error handler failed: ${D(A)}`)}let L=Z instanceof Error?Z:Error(D(Z));throw new H(_.name,L)}}return{context:Y,response:G}}function X0(V){return typeof V==="object"&&V!==null&&"status"in V&&typeof V.status==="number"&&"body"in V}function c(V,$){let J=200,X=V,Y={},G=!1;if(X0(V))return{status:V.status,body:V.body,headers:V.headers||{}};if(E(V))[J,X,Y={}]=V,G=!0;if(X===null||X===void 0){if(!G)J=J===200?204:J;X=void 0}if(!Y["content-type"]&&$.contentType&&!G){if(Y["content-type"]=$.contentType,$.contentType==="text/plain"&&X!==void 0){if(typeof X==="object"&&!Buffer.isBuffer(X))X=JSON.stringify(X);else if(typeof X!=="string")X=String(X)}}return{status:J,body:X,headers:Y}}function l(V){return typeof V==="function"}function h(V,$,J,X){let Y=J.get(`${V} ${I($)}`);if(Y)return Y;for(let G of X)if(G.method===V&&G.params.length>0&&G.pattern.test($))return G;return}function i(V,$){let J=$.match(V.pattern);if(!J)return{};let X={};return V.params.forEach((Y,G)=>{X[Y]=J[G+1]}),X}class p{enabled;constructor(V=!1){this.enabled=V}log(V,$,J){if(!this.enabled)return;let Y=`[${new Date().toISOString()}] [SCHMOCK:${V.toUpperCase()}]`;if(J)console.log(`${Y} ${$}`,J);else console.log(`${Y} ${$}`)}time(V){if(!this.enabled)return;console.time(`[SCHMOCK] ${V}`)}timeEnd(V){if(!this.enabled)return;console.timeEnd(`[SCHMOCK] ${V}`)}}class u{globalConfig;routes=[];staticRoutes=new Map;plugins=[];logger;requestHistory=[];callableRef;server;serverInfo;interceptHandle=null;listeners=new Map;constructor(V={}){this.globalConfig=V;if(this.logger=new p(V.debug||!1),V.debug)this.logger.log("config","Debug mode enabled");this.logger.log("config","Callable mock instance created",{debug:V.debug,namespace:V.namespace,delay:V.delay})}defineRoute(V,$,J){let X={...J};if(!X.contentType)if(typeof $==="function")X.contentType="application/json";else if(typeof $==="string"||typeof $==="number"||typeof $==="boolean")X.contentType="text/plain";else if(Buffer.isBuffer($))X.contentType="application/octet-stream";else X.contentType="application/json";if(typeof $!=="function"&&X.contentType==="application/json")try{JSON.stringify($)}catch(L){throw new S(V,"Generator data is not valid JSON but contentType is application/json")}let Y=d(V),G=I(Y.path);if(this.routes.find((L)=>L.method===Y.method&&I(L.path)===G))return this.logger.log("warning",`Duplicate route: ${V} — first registration wins`),this;let Z={pattern:Y.pattern,params:Y.params,method:Y.method,path:Y.path,generator:$,config:X};if(this.routes.push(Z),Y.params.length===0){let L=`${Y.method} ${I(Y.path)}`;this.staticRoutes.set(L,Z)}return this.logger.log("route",`Route defined: ${V}`,{contentType:X.contentType,generatorType:typeof $,hasParams:Y.params.length>0}),this}setCallableRef(V){this.callableRef=V}pipe(V){if(this.plugins.push(V),this.logger.log("plugin",`Registered plugin: ${V.name}@${V.version||"unknown"}`,{name:V.name,version:V.version,hasProcess:typeof V.process==="function",hasOnError:typeof V.onError==="function"}),V.install&&this.callableRef)V.install(this.callableRef);return this}cloneRecord(V){try{return structuredClone(V)}catch{return{...V,response:{...V.response}}}}history(V,$){if(V||$)return this.requestHistory.filter((J)=>(!V||J.method===V)&&(!$||J.path===$)).map((J)=>this.cloneRecord(J));return this.requestHistory.map((J)=>this.cloneRecord(J))}called(V,$){if(V||$)return this.requestHistory.some((J)=>(!V||J.method===V)&&(!$||J.path===$));return this.requestHistory.length>0}callCount(V,$){if(V||$)return this.requestHistory.filter((J)=>(!V||J.method===V)&&(!$||J.path===$)).length;return this.requestHistory.length}lastRequest(V,$){if(V||$){let X=this.requestHistory.filter((G)=>(!V||G.method===V)&&(!$||G.path===$)),Y=X[X.length-1];return Y?this.cloneRecord(Y):void 0}let J=this.requestHistory[this.requestHistory.length-1];return J?this.cloneRecord(J):void 0}getRoutes(){return this.routes.map((V)=>({method:V.method,path:V.path,hasParams:V.params.length>0}))}getState(){return{...this.globalConfig.state||{}}}on(V,$){let J=this.listeners.get(V);if(!J)J=new Set,this.listeners.set(V,J);return J.add($),this}off(V,$){return this.listeners.get(V)?.delete($),this}emit(V,$){let J=this.listeners.get(V);if(J)for(let X of J)X($)}reset(){if(this.interceptHandle?.restore(),this.interceptHandle=null,this.close(),this.routes=[],this.staticRoutes.clear(),this.plugins=[],this.requestHistory=[],this.listeners.clear(),this.globalConfig.state)this.globalConfig.state={};this.logger.log("lifecycle","Mock fully reset")}resetHistory(){this.requestHistory=[],this.logger.log("lifecycle","Request history cleared")}resetState(){if(this.globalConfig.state)this.globalConfig.state={};this.logger.log("lifecycle","State cleared")}listen(V=0,$="127.0.0.1"){if(this.server)throw new T("Server is already running","SERVER_ALREADY_RUNNING");return import("node:http").then(({createServer:J})=>this.#V(J,V,$))}#V(V,$,J){let X=V((Y,G)=>{(async()=>{let Z=new URL(Y.url??"/",`http://${Y.headers.host}`),L=F(Y.method??"GET"),A=Z.pathname,W=f(Y),U=k(Z),B=await R(Y,W),O=await this.handle(L,A,{headers:W,body:B,query:U});v(G,O)})().catch((Z)=>{if(!G.headersSent)G.writeHead(500,{"content-type":"application/json"});G.end(JSON.stringify({error:Z instanceof Error?Z.message:"Internal Server Error",code:"SERVER_ERROR"}))})});return this.server=X,new Promise((Y,G)=>{X.on("error",G),X.listen($,J,()=>{let _=X.address(),Z=_!==null&&typeof _==="object"?_.port:$;this.serverInfo={port:Z,hostname:J},this.logger.log("server",`Listening on ${J}:${Z}`),Y(this.serverInfo)})})}close(){if(!this.server)return;this.server.closeAllConnections(),this.server.close(),this.server=void 0,this.serverInfo=void 0,this.logger.log("server","Server stopped")}intercept(V){if(this.interceptHandle?.active)throw new T("Already intercepting. Call restore() first.","ALREADY_INTERCEPTING");return this.interceptHandle=q(($,J,X)=>this.handle($,J,X),V),this.interceptHandle}async handle(V,$,J){let X=performance.now(),Y=this.globalConfig.debug?crypto.randomUUID():"",G=J?.query||{},_=J?.headers||{};this.logger.log("request",`[${Y}] ${V} ${$}`,{headers:_,query:G,bodyType:J?.body?typeof J.body:"none"}),this.logger.time(`request-${Y}`),this.emit("request:start",{method:V,path:$,headers:_});try{let Z=$;if(this.globalConfig.namespace&&this.globalConfig.namespace!=="/"){let N=this.globalConfig.namespace.startsWith("/")?this.globalConfig.namespace:`/${this.globalConfig.namespace}`,j=$.startsWith("/")?$:`/${$}`;if(!(j===N||j.startsWith(N.endsWith("/")?N:`${N}/`))){this.logger.log("route",`[${Y}] Path doesn't match namespace ${N}`);let z=new P(V,$),w={status:404,body:{error:z.message,code:z.code},headers:{}};return this.emit("request:end",{method:V,path:$,status:404,duration:performance.now()-X}),this.logger.timeEnd(`request-${Y}`),w}let K=j.slice(N.length);Z=K.startsWith("/")?K:`/${K}`}let L=h(V,Z,this.staticRoutes,this.routes);if(!L){this.logger.log("route",`[${Y}] No route found for ${V} ${Z}`),this.emit("request:notfound",{method:V,path:Z});let N=new P(V,$),j={status:404,body:{error:N.message,code:N.code},headers:{}};return this.emit("request:end",{method:V,path:Z,status:404,duration:performance.now()-X}),this.logger.timeEnd(`request-${Y}`),j}this.logger.log("route",`[${Y}] Matched route: ${V} ${L.path}`);let A=i(L,Z);this.emit("request:match",{method:V,path:Z,routePath:L.path,params:A});let W={method:V,path:Z,params:A,query:G,headers:_,body:J?.body,state:this.globalConfig.state||{}},U;if(l(L.generator))U=await L.generator(W);else U=L.generator;let B={path:Z,route:L.config,method:V,params:A,query:G,headers:_,body:J?.body,state:new Map,routeState:this.globalConfig.state||{}};try{let N=await m(this.plugins,B,U,this.logger);B=N.context,U=N.response}catch(N){throw this.logger.log("error",`[${Y}] Plugin pipeline error: ${D(N)}`),N}let O=c(U,L.config);await this.applyDelay(L.config.delay),this.requestHistory.push({method:V,path:Z,params:A,query:G,headers:_,body:J?.body,timestamp:Date.now(),response:{status:O.status,body:O.body}});let Q=this.globalConfig.maxHistorySize;if(typeof Q==="number"&&Q>=0&&this.requestHistory.length>Q)this.requestHistory.splice(0,this.requestHistory.length-Q);return this.emit("request:end",{method:V,path:Z,status:O.status,duration:performance.now()-X}),this.logger.log("response",`[${Y}] Sending response ${O.status}`,{status:O.status,headers:O.headers,bodyType:typeof O.body}),this.logger.timeEnd(`request-${Y}`),O}catch(Z){this.logger.log("error",`[${Y}] Error processing request: ${D(Z)}`,Z);let L={status:500,body:{error:D(Z),code:Z instanceof T?Z.code:"INTERNAL_ERROR"},headers:{}};return await this.applyDelay(),this.emit("request:end",{method:V,path:$,status:500,duration:performance.now()-X}),this.logger.log("error",`[${Y}] Returning error response 500`),this.logger.timeEnd(`request-${Y}`),L}}async applyDelay(V){let $=V??this.globalConfig.delay;if(!$)return;let J=Array.isArray($)?Math.random()*($[1]-$[0])+$[0]:$;await new Promise((X)=>setTimeout(X,J))}}function Y0(V,$){if(V.status!=null)$.status(V.status);if(V.headers)Object.entries(V.headers).forEach(([J,X])=>{if(typeof X==="string")$.set(J,X)});if(V.body!==void 0)if(typeof V.body==="string")$.send(V.body);else $.json(V.body);else $.end()}function Z0(V){return Object.fromEntries(Object.entries(V).map(([$,J])=>[$,Array.isArray(J)?J[0]:J]).filter(($)=>typeof $[1]==="string"))}function G0(V){let $={};for(let[J,X]of Object.entries(V))if(typeof X==="string")$[J]=X;else if(Array.isArray(X))$[J]=X[0]?String(X[0]):"";else if(X!=null)$[J]=String(X);return $}function J1(V,$={}){let{errorFormatter:J,passErrorsToNext:X=!0,transformHeaders:Y=Z0,transformQuery:G=G0,beforeRequest:_,beforeResponse:Z}=$;return async(L,A,W)=>{try{let U;try{U=F(L.method)}catch{return W()}let B={method:U,path:L.path,headers:Y(L.headers),body:L.body,query:G(L.query)};if(_){let Q=await _(L,A);if(Q)B={...B,...Q,method:F(Q.method||B.method)}}let O=await V.handle(B.method,B.path,{headers:B.headers,body:B.body,query:B.query});if(x(O)){W();return}if(Z){let Q=await Z(O,L,A);if(Q)O=Q}if(J&&O.status===500&&O.body!==null&&typeof O.body==="object"&&"error"in O.body&&"code"in O.body){let Q=O.body,N=typeof Q.error==="string"?Q.error:"Unknown error",j=J(Error(N),L);A.status(500).json(j);return}Y0(O,A)}catch(U){if(J){let B=U instanceof Error?U:Error(String(U)),O=J(B,L);A.status(500).json(O)}else if(X)W(U);else A.status(500).json({error:U instanceof Error?U.message:"Internal Server Error",code:U instanceof T?U.code:"INTERNAL_ERROR"})}}}export{J1 as toExpress};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@schmock/express",
|
|
3
|
-
"version": "2.1
|
|
3
|
+
"version": "2.2.1",
|
|
4
4
|
"description": "Express adapter for Schmock mock API generator",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
"vitest": "^4.1.7"
|
|
37
37
|
},
|
|
38
38
|
"peerDependencies": {
|
|
39
|
-
"@schmock/core": "^2.1
|
|
39
|
+
"@schmock/core": "^2.2.1",
|
|
40
40
|
"express": "^4.18.0 || ^5.0.0"
|
|
41
41
|
},
|
|
42
42
|
"keywords": [
|