@visulima/api-platform 2.0.20 → 2.0.22
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/CHANGELOG.md +28 -0
- package/README.md +3 -3
- package/dist/chunk-4ITG7UZN.js +25 -0
- package/dist/chunk-4ITG7UZN.js.map +1 -0
- package/dist/chunk-JEDCAOHQ.mjs +18 -0
- package/dist/chunk-JEDCAOHQ.mjs.map +1 -0
- package/dist/framework/cli/commander/index.js +2 -2
- package/dist/framework/cli/commander/index.mjs +1 -1
- package/dist/framework/cli/index.js +2 -2
- package/dist/framework/cli/index.mjs +1 -1
- package/package.json +6 -7
- package/dist/chunk-7VCBFZEZ.js +0 -24
- package/dist/chunk-7VCBFZEZ.js.map +0 -1
- package/dist/chunk-FZUWQEM2.mjs +0 -17
- package/dist/chunk-FZUWQEM2.mjs.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,31 @@
|
|
|
1
|
+
## @visulima/api-platform [2.0.22](https://github.com/visulima/visulima/compare/@visulima/api-platform@2.0.21...@visulima/api-platform@2.0.22) (2024-03-09)
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
### Bug Fixes
|
|
5
|
+
|
|
6
|
+
* migrating readdir to fs package ([8da1572](https://github.com/visulima/visulima/commit/8da157281faddf606ceacfb8e091175be2dd0acf))
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
### Dependencies
|
|
11
|
+
|
|
12
|
+
* **@visulima/jsdoc-open-api:** upgraded to 2.0.16
|
|
13
|
+
* **@visulima/fs:** upgraded to 1.0.0
|
|
14
|
+
|
|
15
|
+
## @visulima/api-platform [2.0.21](https://github.com/visulima/visulima/compare/@visulima/api-platform@2.0.20...@visulima/api-platform@2.0.21) (2024-03-06)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
### Bug Fixes
|
|
19
|
+
|
|
20
|
+
* removed lodash.set ([387d110](https://github.com/visulima/visulima/commit/387d110f715d295457d8cb34f6cbd900856e92a3))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
### Dependencies
|
|
25
|
+
|
|
26
|
+
* **@visulima/connect:** upgraded to 3.0.1
|
|
27
|
+
* **@visulima/crud:** upgraded to 2.0.16
|
|
28
|
+
|
|
1
29
|
## @visulima/api-platform [2.0.20](https://github.com/visulima/visulima/compare/@visulima/api-platform@2.0.19...@visulima/api-platform@2.0.20) (2024-03-06)
|
|
2
30
|
|
|
3
31
|
|
package/README.md
CHANGED
|
@@ -45,7 +45,7 @@ npm install @visulima/api-platform zod
|
|
|
45
45
|
#### Installation for Next.js
|
|
46
46
|
|
|
47
47
|
```sh
|
|
48
|
-
npm install @visulima/api-platform zod @visulima/
|
|
48
|
+
npm install @visulima/api-platform zod @visulima/fs
|
|
49
49
|
```
|
|
50
50
|
|
|
51
51
|
### Yarn
|
|
@@ -57,7 +57,7 @@ yarn add @visulima/api-platform zod
|
|
|
57
57
|
#### Installation for Next.js
|
|
58
58
|
|
|
59
59
|
```sh
|
|
60
|
-
yarn add @visulima/api-platform zod @visulima/
|
|
60
|
+
yarn add @visulima/api-platform zod @visulima/fs
|
|
61
61
|
```
|
|
62
62
|
|
|
63
63
|
### Pnpm
|
|
@@ -69,7 +69,7 @@ pnpm add @visulima/api-platform zod
|
|
|
69
69
|
#### Installation for Next.js
|
|
70
70
|
|
|
71
71
|
```sh
|
|
72
|
-
pnpm add @visulima/api-platform zod @visulima/
|
|
72
|
+
pnpm add @visulima/api-platform zod @visulima/fs
|
|
73
73
|
```
|
|
74
74
|
|
|
75
75
|
### To use the swagger-ui or the redoc-ui you need to install the following packages:
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var child_process = require('child_process');
|
|
4
|
+
var fs = require('fs');
|
|
5
|
+
var path = require('path');
|
|
6
|
+
var h = require('process');
|
|
7
|
+
var d = require('chalk');
|
|
8
|
+
var jsdocOpenApi = require('@visulima/jsdoc-open-api');
|
|
9
|
+
var promises = require('fs/promises');
|
|
10
|
+
var url = require('url');
|
|
11
|
+
|
|
12
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
13
|
+
|
|
14
|
+
var h__default = /*#__PURE__*/_interopDefault(h);
|
|
15
|
+
var d__default = /*#__PURE__*/_interopDefault(d);
|
|
16
|
+
|
|
17
|
+
var te=(e,r)=>{if(r.length===0)throw new Error("must include at least one key to map");let t=e.toString();return r.forEach(o=>{t=o.optional?t.replace("(?:\\/([^\\/]+?))?\\",`/:${o.name}?`):t.replace("(?:([^\\/]+?))",`:${o.name}`);}),t.replace("/?(?=\\/|$)/i","").replace("/^","").replaceAll("\\","").replaceAll(/\/{2,}/gu,"/")},A=te;var re=(e,r)=>{if(typeof e=="string")return e;if(e.fast_slash)return "";if(e.fast_star)return "*";let t="";r.length>0&&(t=A(e,r));let o=/^\/\^((?:\\[$()*+./?[\\\]^{|}]|[^$()*+./?[\\\]^{|}])*)\$\//u.exec(e.toString().replace("\\/?","").replace("(?=\\/|$)","$"));return Array.isArray(o)&&o.length>1?o[1].replaceAll(/\\(.)/gu,"$1").slice(1):t?t.slice(1):e.toString()},P=re;var oe=(e,r,t)=>{let o=e.route.stack.at(-1),s=r.map(a=>({in:"path",name:a.name,required:!a.optional})),i=e.route.stack.filter(a=>a.handle.metadata);if(i.length>1)throw new Error("Only one metadata middleware is allowed per route");let n=(t+e.route.path).replaceAll(/\/{2,}/gu,"/");return i.length===0?{method:o.method,path:n,pathParams:s}:{metadata:i[0].handle.metadata,method:o.method,path:n,pathParams:s}},T=(e,r,t,o)=>{o=[...o,...t.keys],t.name==="router"&&t.handle&&t.handle.stack.forEach(s=>{r=r||"",T(e,`${r}/${P(t.regexp,t.keys)}`,s,o);}),!(!t.route||t.route.stack.length===0)&&e.push(oe(t,o,r));},se=e=>{let r=e._router||e.router,t=[];return r.stack.forEach(o=>{T(t,"",o,[]);}),t},F=se;var ie=e=>{let r=[];return F(e).forEach(t=>{r.push({file:"unknown",method:t.method.toUpperCase(),path:t.path,tags:[]});}),r},v=ie;var b=e=>e.replaceAll(/ \(.*\)/gu,"").trim(),$=e=>e.trim().split(" ")[1].slice(1,-1),ne=e=>{let t=e.printRoutes().replaceAll(/[─│└├]/gu," ").trimEnd().split(`
|
|
18
|
+
`),o=t.reduce((i,n,a)=>{let p=b(n);if(b(t[a-1]??"")===p){let ee=i.filter(D=>D.index<a&&D.segment===p),{methods:R}=ee.at(-1);return R!==null&&R.push($(n)),i}let c=n.replaceAll(/ \(.*\)/gu,"").match(/ /gu);if(c===null)throw new Error("Invalid spaces");let l=c.length/4,m=n.includes("("),x=m?[$(n)]:null;return i.push({depth:l,index:a,isRoute:m,methods:x,segment:p}),i},[]),s=[];return o.filter(i=>i.isRoute).forEach(i=>{let a=[...o.filter(p=>p.index<i.index&&p.depth<i.depth).filter((p,u,c)=>!c.find(l=>l.depth===p.depth&&l.index>p.index)).map(p=>p.segment),i.segment].join("");if(i.methods===null)throw new Error("Invalid methods");i.methods.forEach(p=>{s.push({file:"unknown",method:p.toUpperCase(),path:a,tags:[]});});}),s},L=ne;var ae=e=>{let t=e._core.router.routes,o=[];return [...t.keys()].forEach(s=>{t.get(s).routes.forEach(i=>{o.push({file:"unknown",method:i.route.method.toUpperCase(),path:i.path,tags:[]});});}),o},j=ae;var le=e=>{let r=[];return e.middleware.filter(t=>t.router).flatMap(t=>t.router.stack).forEach(t=>{r.push({file:"unknown",method:t.methods.join("|").toUpperCase(),path:t.path,tags:[]});}),r},O=le;var N=/\.(js|ts|mjs|cjs)$/u,me=(e,r,t=!1)=>{let o=[],s=jsdocOpenApi.parseFile(e,jsdocOpenApi.jsDocumentCommentsToOpenApi,t);o=[...o,...s.map(a=>a.spec)];let i=jsdocOpenApi.parseFile(e,jsdocOpenApi.swaggerJsDocumentCommentsToOpenApi,t);o=[...o,...i.map(a=>a.spec)];let n=[];return o.length===0?(fs.readFileSync(e,"utf8").split(/\r?\n/u).forEach(p=>{let u=/[=aces|]+\s["'|](GET|POST|PUT|PATCH|HEAD|DELETE|OPTIONS)["'|]/u.exec(p);if(u){let[,c]=u;c==="GET"&&(c="GET|HEAD"),n.push({file:e.replace(`${h__default.default.cwd()}${h__default.default.platform==="win32"?"\\":"/"}`,""),method:c,path:e.replace(r,"").replace(N,"").replaceAll("\\","/"),tags:[]});}}),n.length===0&&n.push({file:e.replace(`${h__default.default.cwd()}${h__default.default.platform==="win32"?"\\":"/"}`,""),method:"GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS",path:e.replace(r,"").replace(N,"").replaceAll("\\","/"),tags:[]}),n):(o.forEach(a=>{Object.entries(a?.paths??{}).forEach(([u,c])=>{Object.entries(c).forEach(([m,x])=>{n.push({file:e.replace(`${h__default.default.cwd()}${h__default.default.platform==="win32"?"\\":"/"}`,""),method:m.toUpperCase(),path:u.replaceAll("\\","/"),tags:x.tags});});});}),n)},C=me;var we=class extends Error{root;constructor(e,r){super(`${e instanceof Error?e.message:e} for path "${r}"`),this.cause=e,this.name="WalkError",this.root=r;}},M=we,ke=e=>{let r=e.replace(/\.\*/g,".([^/]*)").replace(/\*\*/g,"(.*)").replace(/(?<!\.)\*(?!\*)/g,"([^/]*)").replace(/\?/g,"[^/]").replace(/\.(?!\*)/g,"\\.").replace(/\{/g,"(").replace(/\}/g,")").replace(/,/g,"|").replace(/\[!(.*?)\]/g,"[^$1]");return new RegExp(`^${r}$`)},H=ke,Re=e=>e instanceof URL?url.fileURLToPath(e):e,De=Re,Ae=(e,r,t,o)=>r&&!r.some(s=>e.endsWith(s))||t&&!t.some(s=>s.test(e))?!1:!(o&&o.some(s=>s.test(e))),g=Ae,Pe=async e=>{let r=path.normalize(e),t=path.basename(r),o=await promises.stat(r);return {isDirectory:o.isDirectory,isFile:o.isFile,isSymbolicLink:o.isSymbolicLink,name:t,path:r}};async function*K(e,{extensions:r,followSymlinks:t=!1,includeDirs:o=!0,includeFiles:s=!0,includeSymlinks:i=!0,match:n,maxDepth:a=Number.POSITIVE_INFINITY,skip:p}={}){if(a<0)return;let u=n?n.map(l=>typeof l=="string"?H(l):l):void 0,c=p?p.map(l=>typeof l=="string"?H(l):l):void 0;if(e=path.resolve(De(e)),o&&g(e,r,u,c)&&(yield await Pe(e)),!(a<1||!g(e,void 0,void 0,c)))try{for await(let l of await promises.readdir(e,{withFileTypes:!0})){let m=path.join(e,l.name);if(l.isSymbolicLink())if(t)m=await promises.realpath(m);else if(i&&g(m,r,u,c))yield {isDirectory:l.isDirectory,isFile:l.isFile,isSymbolicLink:l.isSymbolicLink,name:l.name,path:m};else continue;l.isSymbolicLink()||l.isDirectory()?yield*K(m,{extensions:r,followSymlinks:t,includeDirs:o,includeFiles:s,includeSymlinks:i,match:u,maxDepth:a-1,skip:c}):l.isFile()&&s&&g(m,r,u,c)&&(yield {isDirectory:l.isDirectory,isFile:l.isFile,isSymbolicLink:l.isSymbolicLink,name:l.name,path:m});}}catch(l){throw l instanceof M?l:new M(l,e)}}var Te=async(e,r={})=>{let t={extensions:["js","mjs","cjs","ts"],...r},o=[];for await(let s of K(e,t))o.push(s.path);return o},G=Te;var E=[".js",".ts",".mjs",".cjs"],_=e=>{let r=path.parse(e);for(;r.base&&r.root!==r.dir;){if(fs.readdirSync(r.dir).find(s=>s==="package.json"))return r.dir;r=path.parse(r.dir);}return null},W=e=>{let r=`${e}/package.json`,{dependencies:t}=JSON.parse(fs.readFileSync(r).toString());return t?.express?"express":t?.koa&&(t["@koa/router"]||t["koa-router"])?"koa":t?.next?"next":t?.["@hapi/hapi"]?"hapi":t?.fastify?"fastify":null},J=(e,r)=>Object.keys(e).length===0?null:r==="hapi"?typeof e.app.app=="string"?e.app:e:e.app??e;var q=e=>{try{return fs.statSync(e).isDirectory()}catch{return !1}},$e=async(e="")=>{let r=path.join(e,"pages/api");return !q(r)&&(r=path.join(e,"src/pages/api"),!q(r))?[]:G(r,{extensions:E,includeDirs:!1})},Y=$e;var S=async(e,r,t)=>{if(r==="express")return v(e);if(r==="koa")return O(e);if(r==="hapi")return j(e);if(r==="fastify")return L(e);if(r==="next"){let o=await Y(e);if(o.length===0)throw new Error(`No API routes found, in "${e}".`);return o.flatMap(s=>C(s,e,t))}return null};var Le=(e,r)=>{let t=new Map;return e.forEach(o=>{let s=r(o),i=t.get(s);i?i.push(o):t.set(s,[o]);}),t},X=Le;var je=(e,r)=>{let t={ANY:d__default.default.redBright,DELETE:d__default.default.redBright,GET:d__default.default.blue,HEAD:d__default.default.hex("#6C7280"),OPTIONS:d__default.default.hex("#6C7280"),PATCH:d__default.default.yellow,POST:d__default.default.yellow,PUT:d__default.default.yellow},o;if(e==="GET|HEAD")o=`${d__default.default.blue("GET")}${d__default.default.grey("|HEAD")}`;else {let u=t[e](e);o=e==="GET"?`${u}${d__default.default.grey("|HEAD")}`:u;}let s=e==="GET"?6:14-e.length,i=Array.from({length:s}).fill(" ").join(""),n=process.stdout.columns-16-r.length-4,a=n>0?Array.from({length:n}).fill(".").join(""):"",p=r.split("/").map(u=>[":","["].includes(u[0]??"")?d__default.default.yellowBright(u):u).join("/");return ` ${o}${i}${p}${d__default.default.grey(a)}`},Oe=(e,r={})=>e.map(t=>{if(!(Array.isArray(r.methods)&&r.methods.includes(t.method)))return t.method==="GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS"&&(t.method="ANY"),je(t.method,t.path.replace("/pages",""))}).filter(Boolean),w=Oe;var Ce=async(e,r,t={})=>{let o=path.join(h__default.default.cwd(),r);if(!fs.existsSync(o))throw new Error("No such file, invalid path provided.");let s=_(o);if(!s)throw new Error("Please initialize local package.json.");if(e===void 0){let n=W(s);if(!n)throw new Error("Couldn't detect supported back-end framework.");e=n;}let i=null;if(e==="next")i=await S(o,"next",t.verbose??!1);else {if(!fs.statSync(o).isFile())throw new Error(`${o} is directory, but file expected.`);if(!E.includes(path.extname(o)))throw new Error("Please specify application .ts/.js/.mjs/.cjs file.");let n=`${s}/.env`;fs.existsSync(n)&&(await import(`${s}/node_modules/dotenv/lib/main.js`)).config({path:n});let a=path.extname(o)===".ts",p=path.join(s,"node_modules/.bin/tsc");if(a&&!fs.existsSync(p))throw new Error(`Please install typescript in ${s}`);try{if(a)try{child_process.execSync(`${p} --outDir framework-list >&2`,{cwd:s});}catch(l){console.log(`TSC compilation failed. Please resolve issues in your project.
|
|
19
|
+
`),console.log(l),fs.rmSync(path.join(s,"framework-list"),{recursive:!0});}let u=a?path.join(s,"framework-list",o.replace(s,"").replace(".ts",".js")):o,{default:c}=await import(u);i=await S(["AsyncFunction","Function"].includes(c.constructor.name)?await c():J(c,e),e,t.verbose??!1);}finally{a&&fs.rmSync(path.join(s,"framework-list"),{recursive:!0});}}if(i===null)throw new Error(`Framework "${e}" is not supported.`);if(Array.isArray(t.includePaths)&&t.includePaths.length>0&&(i=t.includePaths.flatMap(n=>i.filter(a=>a.path.startsWith(n)))),Array.isArray(t.excludePaths)&&t.excludePaths.length>0&&(i=t.excludePaths.flatMap(n=>i.filter(a=>!a.path.startsWith(n)))),typeof t.group=="string"&&t.group!==""){console.log();let n=X(i,p=>t.group==="path"?p.path.replace("/pages","").split("/")[1]:p.tags[0]??"unsorted"),a=0;n.forEach((p,u)=>{a>0&&console.log();let c=(h__default.default.stdout.columns-16-u.length)/2,l=c>0?Array.from({length:c}).fill(" ").join(""):"";console.log(l+d__default.default.bold.underline(u)),w(p,t).forEach(m=>{console.log(m);}),a+=1;});}else console.log(),w(i,t).forEach(n=>{console.log(n);});console.log(`
|
|
20
|
+
Listed ${d__default.default.greenBright(String(i.length))} HTTP ${i.length===1?"route":"routes"}.
|
|
21
|
+
`);},Vt=Ce;
|
|
22
|
+
|
|
23
|
+
exports.a = Vt;
|
|
24
|
+
//# sourceMappingURL=out.js.map
|
|
25
|
+
//# sourceMappingURL=chunk-4ITG7UZN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/framework/cli/command/list/list-command.ts","../src/framework/cli/command/list/routes/express/map-keys-to-path.ts","../src/framework/cli/command/list/routes/express/path-regex-parser.ts","../src/framework/cli/command/list/routes/express/express-path-parser.ts","../src/framework/cli/command/list/routes/express-routes.ts","../src/framework/cli/command/list/routes/fastify-routes.ts","../src/framework/cli/command/list/routes/hapi-routes.ts","../src/framework/cli/command/list/routes/koa-routes.ts","../src/framework/cli/command/list/routes/next/api-route-file-parser.ts","../src/framework/cli/command/list/routes/next/collect-api-route-files.ts","../../fs/src/walk.ts","../src/framework/cli/command/list/utils.ts","../src/framework/cli/command/list/get-routes.ts","../src/framework/cli/command/list/routes/routes-group-by.ts","../src/framework/cli/command/list/routes/routes-render.ts"],"names":["execSync","existsSync","rmSync","statSync","extname","join","process","chalk","mapKeysToPath","layerRegexPath","keys","convertedSubPath","key","map_keys_to_path_default","pathRegexParser","mappedPath","match","path_regex_parser_default","parseRouteLayer","layer","basePath","lastRequestHandler","pathParameters","filtered","element","path","traverse","routes","l","expressPathParser","app","router","express_path_parser_default","expressRoutes","route","express_routes_default","getSegment","line","getMethod","fastifyRoutes","lines","segments","allSegments","index","segment","entries","item","methods","spaces","depth","isRoute","seg","_index","previousArray","r","method","fastify_routes_default","hapiRoutes","coreRoutes","hapi_routes_default","koaRoutes","middlewareFunction","koa_routes_default","readFileSync","jsDocumentCommentsToOpenApi","parseFile","swaggerJsDocumentCommentsToOpenApi","extensionRegex","apiRouteFileParser","apiRouteFile","cwdPath","verbose","specs","parsedJsDocumentFile","parsedSwaggerJsDocumentFile","spec","pathSpec","methodSpec","api_route_file_parser_default","readdir","stat","readdirSync","parse","ALLOWED_EXTENSIONS","getAppWorkingDirectoryPath","appFilePath","lastParsedPath","getFrameworkName","directory","packageJSONFilePath","dependencies","getApp","appExport","frameworkName","isDirectory","collectApiRouteFiles","apiFolderPath","$","collect_api_route_files_default","getRoutes","appOrPath","apiRouteFiles","routesGroupBy","list","keyGetter","map","collection","routes_group_by_default","renderRoute","routePath","colorMap","methodText","coloredMethod","spacesCount","dotsCount","dots","routeText","routesRender","routesMap","options","routes_render_default","listCommand","framework","frameworkPath","appWorkingDirectoryPath","environmentFilePath","isTypeScriptApp","tscPath","error","appJsFilePath","defaultExport","ipath","epath","groupedMap","counter","groupedRoutes","renderedRoute","list_command_default"],"mappings":"AAAA,OAAS,YAAAA,OAAgB,gBACzB,OAAS,cAAAC,EAAY,UAAAC,EAAQ,YAAAC,OAAgB,KAC7C,OAAS,WAAAC,EAAS,QAAAC,MAAY,OAC9B,OAAOC,MAAa,UAGpB,OAAOC,MAAW,QCIlB,IAAMC,GAAgB,CAACC,EAA8BC,IAAwB,CACzE,GAAIA,EAAK,SAAW,EAChB,MAAM,IAAI,MAAM,sCAAsC,EAG1D,IAAIC,EAAmBF,EAAe,SAAS,EAE/C,OAAAC,EAAK,QAASE,GAAQ,CAClBD,EAAmBC,EAAI,SACjBD,EAAiB,QAAQ,uBAAwB,KAAKC,EAAI,IAAI,GAAG,EACjED,EAAiB,QAAQ,iBAAkB,IAAIC,EAAI,IAAI,EAAE,CACnE,CAAC,EAEMD,EACF,QAAQ,gBAAiB,EAAE,EAC3B,QAAQ,KAAM,EAAE,EAChB,WAAW,KAAM,EAAE,EACnB,WAAW,WAAY,GAAG,CACnC,EAEOE,EAAQL,GCnBf,IAAMM,GAAkB,CAACL,EAAuCC,IAAwB,CACpF,GAAI,OAAOD,GAAmB,SAC1B,OAAOA,EAGX,GAAIA,EAAe,WACf,MAAO,GAGX,GAAIA,EAAe,UACf,MAAO,IAGX,IAAIM,EAAa,GAEbL,EAAK,OAAS,IACdK,EAAaF,EAAcJ,EAAgBC,CAAI,GAGnD,IAAMM,EAAQ,8DAA8D,KACxEP,EAAe,SAAS,EAAE,QAAQ,OAAQ,EAAE,EAAE,QAAQ,YAAa,GAAG,CAC1E,EAEA,OAAI,MAAM,QAAQO,CAAK,GAAKA,EAAM,OAAS,EAC/BA,EAAM,CAAC,EAAa,WAAW,UAAW,IAAI,EAAE,MAAM,CAAC,EAG/DD,EACOA,EAAW,MAAM,CAAC,EAGtBN,EAAe,SAAS,CACnC,EAEOQ,EAA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AAQ,YAAY,GAAKA,EAAQ,aAAa,OAAS,IACrE5F,EAAS4F,EAAQ,aAAa,QAASa,GAAWzG,EAAmB,OAAQO,GAAU,CAACA,EAAM,KAAK,WAAWkG,CAAK,CAAC,CAAC,GAGrH,OAAOb,EAAQ,OAAU,UAAYA,EAAQ,QAAU,GAAI,CAE3D,QAAQ,IAAI,EAEZ,IAAMc,EAAa1B,EAAchF,EAASO,GAClCqF,EAAQ,QAAU,OACXrF,EAAM,KAAK,QAAQ,SAAU,EAAE,EAAE,MAAM,GAAG,EAAE,CAAC,EAGjDA,EAAM,KAAK,CAAC,GAAK,UAC3B,EAEGoG,EAAU,EAEdD,EAAW,QAAQ,CAACE,EAAe3H,IAAQ,CACnC0H,EAAU,GAEV,QAAQ,IAAI,EAGhB,IAAMpB,GAAa5G,EAAQ,OAAO,QAAU,GAAKM,EAAI,QAAU,EACzDuG,EAAOD,EAAY,EAAI,MAAM,KAAK,CAAE,OAAQA,CAAU,CAAC,EAAE,KAAK,GAAG,EAAE,KAAK,EAAE,EAAI,GAGpF,QAAQ,IAAIC,EAAO5G,EAAM,KAAK,UAAUK,CAAG,CAAC,EAE5C4G,EAAae,EAAehB,CAAO,EAAE,QAASiB,GAAkB,CAE5D,QAAQ,IAAIA,CAAa,CAC7B,CAAC,EAEDF,GAAW,CACf,CAAC,CACL,MAEI,QAAQ,IAAI,EAEZd,EAAa7F,EAAQ4F,CAAO,EAAE,QAASiB,GAAkB,CAErD,QAAQ,IAAIA,CAAa,CAC7B,CAAC,EAIL,QAAQ,IAAI;AAAA,WAAcjI,EAAM,YAAY,OAAOoB,EAAO,MAAM,CAAC,CAAC,SAASA,EAAO,SAAW,EAAI,QAAU,QAAQ;AAAA,CAAK,CAC5H,EAEO8G,GAAQhB","sourcesContent":["import { execSync } from \"node:child_process\";\nimport { existsSync, rmSync, statSync } from \"node:fs\";\nimport { extname, join } from \"node:path\";\nimport process from \"node:process\";\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport chalk from \"chalk\";\n\nimport { getRoutes } from \"./get-routes\";\nimport routesGroupBy from \"./routes/routes-group-by\";\nimport routesRender from \"./routes/routes-render\";\nimport type { Route } from \"./routes/types\";\nimport { ALLOWED_EXTENSIONS, getApp, getAppWorkingDirectoryPath, getFrameworkName } from \"./utils\";\n\ninterface RenderOptions {\n excludePaths: string[];\n group: string;\n includePaths: string[];\n methods: string[];\n verbose: boolean;\n}\n\nconst listCommand = async (\n framework: \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | undefined,\n path: string,\n options: Partial<RenderOptions> = {},\n // eslint-disable-next-line sonarjs/cognitive-complexity\n): Promise<void> => {\n const frameworkPath = join(process.cwd(), path);\n\n if (!existsSync(frameworkPath)) {\n throw new Error(\"No such file, invalid path provided.\");\n }\n\n const appWorkingDirectoryPath = getAppWorkingDirectoryPath(frameworkPath);\n\n if (!appWorkingDirectoryPath) {\n throw new Error(\"Please initialize local package.json.\");\n }\n\n if (framework === undefined) {\n const frameworkName = getFrameworkName(appWorkingDirectoryPath);\n\n if (!frameworkName) {\n throw new Error(\"Couldn't detect supported back-end framework.\");\n }\n\n // eslint-disable-next-line no-param-reassign\n framework = frameworkName;\n }\n\n let routes: Route[] | null = null;\n\n if (framework === \"next\") {\n routes = await getRoutes(frameworkPath, \"next\", options.verbose ?? false);\n } else {\n if (!statSync(frameworkPath).isFile()) {\n throw new Error(`${frameworkPath} is directory, but file expected.`);\n }\n\n if (!ALLOWED_EXTENSIONS.includes(extname(frameworkPath))) {\n throw new Error(\"Please specify application .ts/.js/.mjs/.cjs file.\");\n }\n\n const environmentFilePath = `${appWorkingDirectoryPath}/.env`;\n\n if (existsSync(environmentFilePath)) {\n // Loads environment vars in the current process so application\n // that depends on them can be loaded properly below\n const dotEnvironmentFilePath = `${appWorkingDirectoryPath}/node_modules/dotenv/lib/main.js`;\n const dotenv = await import(dotEnvironmentFilePath);\n\n dotenv.config({ path: environmentFilePath });\n }\n\n const isTypeScriptApp = extname(frameworkPath) === \".ts\";\n const tscPath = join(appWorkingDirectoryPath, \"node_modules/.bin/tsc\");\n\n if (isTypeScriptApp && !existsSync(tscPath)) {\n throw new Error(`Please install typescript in ${appWorkingDirectoryPath}`);\n }\n\n try {\n if (isTypeScriptApp) {\n // || rm -r ./framework-list removes framework-list directory in case tsc fails\n\n try {\n execSync(`${tscPath} --outDir framework-list >&2`, { cwd: appWorkingDirectoryPath });\n } catch (error: any) {\n // eslint-disable-next-line no-console\n console.log(\"TSC compilation failed. Please resolve issues in your project.\\n\");\n // eslint-disable-next-line no-console\n console.log(error);\n\n rmSync(join(appWorkingDirectoryPath, \"framework-list\"), { recursive: true });\n }\n }\n\n const appJsFilePath = isTypeScriptApp\n ? join(appWorkingDirectoryPath, \"framework-list\", frameworkPath.replace(appWorkingDirectoryPath, \"\").replace(\".ts\", \".js\"))\n : frameworkPath;\n\n const { default: defaultExport } = await import(appJsFilePath);\n\n routes = await getRoutes(\n [\"AsyncFunction\", \"Function\"].includes(defaultExport.constructor.name as string) ? await defaultExport() : getApp(defaultExport, framework),\n framework,\n options.verbose ?? false,\n );\n } finally {\n if (isTypeScriptApp) {\n rmSync(join(appWorkingDirectoryPath, \"framework-list\"), { recursive: true });\n }\n }\n }\n\n if (routes === null) {\n throw new Error(`Framework \"${framework}\" is not supported.`);\n }\n\n if (Array.isArray(options.includePaths) && options.includePaths.length > 0) {\n routes = options.includePaths.flatMap((ipath) => (routes as Route[]).filter((route) => route.path.startsWith(ipath)));\n }\n\n if (Array.isArray(options.excludePaths) && options.excludePaths.length > 0) {\n routes = options.excludePaths.flatMap((epath) => (routes as Route[]).filter((route) => !route.path.startsWith(epath)));\n }\n\n if (typeof options.group === \"string\" && options.group !== \"\") {\n // eslint-disable-next-line no-console\n console.log();\n\n const groupedMap = routesGroupBy(routes, (route) => {\n if (options.group === \"path\") {\n return route.path.replace(\"/pages\", \"\").split(\"/\")[1];\n }\n\n return route.tags[0] ?? \"unsorted\";\n });\n\n let counter = 0;\n\n groupedMap.forEach((groupedRoutes, key) => {\n if (counter > 0) {\n // eslint-disable-next-line no-console\n console.log();\n }\n\n const dotsCount = (process.stdout.columns - 16 - key.length) / 2;\n const dots = dotsCount > 0 ? Array.from({ length: dotsCount }).fill(\" \").join(\"\") : \"\";\n\n // eslint-disable-next-line no-console\n console.log(dots + chalk.bold.underline(key));\n\n routesRender(groupedRoutes, options).forEach((renderedRoute) => {\n // eslint-disable-next-line no-console\n console.log(renderedRoute);\n });\n\n counter += 1;\n });\n } else {\n // eslint-disable-next-line no-console\n console.log();\n\n routesRender(routes, options).forEach((renderedRoute) => {\n // eslint-disable-next-line no-console\n console.log(renderedRoute);\n });\n }\n\n // eslint-disable-next-line no-console\n console.log(`\\n Listed ${chalk.greenBright(String(routes.length))} HTTP ${routes.length === 1 ? \"route\" : \"routes\"}.\\n`);\n};\n\nexport default listCommand;\n","import type { ExpressRegex, Key } from \"./types\";\n\n/**\n * Map's the keys/path variables to the regex inside a given path\n *\n * @param layerRegexPath The regex for a router with path parameters\n * @param keys The keys that represent the path parameters\n *\n * @returns The regex for a path variable converted to original string on the express route\n */\nconst mapKeysToPath = (layerRegexPath: ExpressRegex, keys: Key[]): string => {\n if (keys.length === 0) {\n throw new Error(\"must include at least one key to map\");\n }\n\n let convertedSubPath = layerRegexPath.toString();\n\n keys.forEach((key) => {\n convertedSubPath = key.optional\n ? convertedSubPath.replace(\"(?:\\\\/([^\\\\/]+?))?\\\\\", `/:${key.name}?`)\n : convertedSubPath.replace(\"(?:([^\\\\/]+?))\", `:${key.name}`);\n });\n\n return convertedSubPath\n .replace(\"/?(?=\\\\/|$)/i\", \"\")\n .replace(\"/^\", \"\")\n .replaceAll(\"\\\\\", \"\")\n .replaceAll(/\\/{2,}/gu, \"/\");\n};\n\nexport default mapKeysToPath;\n","import mapKeysToPath from \"./map-keys-to-path\";\nimport type { ExpressRegex, Key } from \"./types\";\n\n/** Parses an express layer's regex and converts it to the original format seen in code.\n *\n * @param layerRegexPath The layer's regex pattern\n * @param keys The keys that represent the layer's path parameters\n * @returns The path string for that layer\n * Code inspired and modify from:\n * https://github.com/expressjs/express/issues/3308#issuecomment-300957572\n */\nconst pathRegexParser = (layerRegexPath: ExpressRegex | string, keys: Key[]): string => {\n if (typeof layerRegexPath === \"string\") {\n return layerRegexPath;\n }\n\n if (layerRegexPath.fast_slash) {\n return \"\";\n }\n\n if (layerRegexPath.fast_star) {\n return \"*\";\n }\n\n let mappedPath = \"\";\n\n if (keys.length > 0) {\n mappedPath = mapKeysToPath(layerRegexPath, keys);\n }\n\n const match = /^\\/\\^((?:\\\\[$()*+./?[\\\\\\]^{|}]|[^$()*+./?[\\\\\\]^{|}])*)\\$\\//u.exec(\n layerRegexPath.toString().replace(\"\\\\/?\", \"\").replace(\"(?=\\\\/|$)\", \"$\"),\n ) as string[];\n\n if (Array.isArray(match) && match.length > 1) {\n return (match[1] as string).replaceAll(/\\\\(.)/gu, \"$1\").slice(1);\n }\n\n if (mappedPath) {\n return mappedPath.slice(1);\n }\n\n return layerRegexPath.toString();\n};\n\nexport default pathRegexParser;\n","import type { Express, Router } from \"express\";\n\nimport pathRegexParser from \"./path-regex-parser\";\nimport type { Key, Layer, Parameter, Route, RouteMetaData } from \"./types\";\n\n/**\n * Parses a route object. Route objects are the leafs of an express router tree\n *\n * @param layer The layer of this route object - represents the stack of middleware and other metadata\n * @param keys The full set of keys for this particular route\n * @param basePath The base path as it was initial declared for this route\n * @returns A ExpressPath object holding the metadata for a given route\n */\nconst parseRouteLayer = (layer: Required<Layer>, keys: Key[], basePath: string): RouteMetaData => {\n const lastRequestHandler = layer.route.stack.at(-1) as Layer;\n const pathParameters: Parameter[] = keys.map((key) => {\n return { in: \"path\", name: key.name, required: !key.optional };\n });\n\n const filtered = layer.route.stack.filter((element) => (element.handle as Route).metadata);\n\n if (filtered.length > 1) {\n throw new Error(\"Only one metadata middleware is allowed per route\");\n }\n\n const path = (basePath + layer.route.path).replaceAll(/\\/{2,}/gu, \"/\");\n\n if (filtered.length === 0) {\n return { method: lastRequestHandler.method, path, pathParams: pathParameters };\n }\n\n return {\n metadata: ((filtered[0] as Layer).handle as Route).metadata,\n method: lastRequestHandler.method,\n path,\n pathParams: pathParameters,\n };\n};\n\n/**\n * Recursive traversal method for the express router and middleware tree.\n *\n * @param routes The array of routes to add to\n * @param path The current path segment that we have traversed so far\n * @param layer The current 'layer' of the router tree\n * @param keys The keys for the parameter's in the current path branch of the traversal\n * @returns void - base case saves result to internal object\n */\nconst traverse = (routes: RouteMetaData[], path: string, layer: Layer, keys: Key[]): void => {\n // eslint-disable-next-line no-param-reassign\n keys = [...keys, ...layer.keys];\n\n if (layer.name === \"router\" && layer.handle) {\n layer.handle.stack.forEach((l: Layer) => {\n // eslint-disable-next-line no-param-reassign\n path = path || \"\";\n\n traverse(routes, `${path}/${pathRegexParser(layer.regexp, layer.keys)}`, l, keys);\n });\n }\n\n if (!layer.route || layer.route.stack.length === 0) {\n return;\n }\n\n routes.push(parseRouteLayer(layer as Required<Layer>, keys, path));\n};\n\n// @TODO use this to parse the express swagger\n\n/**\n * Parses an Express app and generates list of routes with metadata.\n *\n * Can Parse:\n * - Nested Routers and Complex Express Projects\n * - Optional parameters e.g. /:name?\n * - Complex Matching routes e.g. /ma*tch, /ex(ab)?mple\n * - Regex routes e.g. /\\/abc|\\/xyz/\n * - Array of paths e.g. app.get(['/abc', '/xyz']) -> /abc,xyz/\n *\n * @param app The Express app reference. Must be used after all routes have been attached\n *\n * @returns List of routes for this express app with meta-data that has been picked up\n */\nconst expressPathParser = (app: Express): RouteMetaData[] => {\n // eslint-disable-next-line no-underscore-dangle\n const router: Router = app._router || app.router;\n const routes: RouteMetaData[] = [];\n\n router.stack.forEach((layer: Layer) => {\n traverse(routes, \"\", layer, []);\n });\n\n return routes;\n};\n\nexport default expressPathParser;\n","import type { Express } from \"express\";\n\nimport expressPathParser from \"./express/express-path-parser\";\nimport type { RouteMetaData } from \"./express/types\";\nimport type { Route } from \"./types\";\n\nconst expressRoutes = (app: Express): Route[] => {\n const routes: Route[] = [];\n\n expressPathParser(app).forEach((route: RouteMetaData) => {\n routes.push({\n file: \"unknown\",\n method: route.method.toUpperCase(),\n path: route.path,\n tags: [],\n });\n });\n\n return routes;\n};\n\nexport default expressRoutes;\n","import type { FastifyInstance } from \"fastify\";\n\nimport type { Route } from \"./types\";\n\n// \"<spaces> activity (GET)\" -> \"activity\"\nconst getSegment = (line: string) => line.replaceAll(/ \\(.*\\)/gu, \"\").trim();\n\n// \"<spaces> activity (GET)\" -> \"GET\"\nconst getMethod = (line: string) => (line.trim().split(\" \")[1] as string).slice(1, -1);\n\ninterface Segment {\n depth: number;\n index: number;\n isRoute: boolean;\n methods: string[] | null;\n segment: string;\n}\n\nconst fastifyRoutes = (app: FastifyInstance): Route[] => {\n const printedRoutes = app\n .printRoutes()\n .replaceAll(/[─│└├]/gu, \" \")\n .trimEnd();\n\n const lines = printedRoutes.split(\"\\n\");\n\n // eslint-disable-next-line unicorn/no-array-reduce\n const segments = lines.reduce((allSegments: Segment[], line, index) => {\n const segment = getSegment(line);\n const previousSegment = getSegment(lines[index - 1] ?? \"\");\n\n if (previousSegment === segment) {\n const entries: Segment[] = allSegments.filter((item) => item.index < index && item.segment === segment);\n\n const { methods } = entries.at(-1) as Segment;\n\n if (methods !== null) {\n methods.push(getMethod(line));\n }\n\n return allSegments;\n }\n\n // spaces preceding segment / not counting single space between segment and (METHOD)\n const spaces = line.replaceAll(/ \\(.*\\)/gu, \"\").match(/ /gu);\n\n if (spaces === null) {\n throw new Error(\"Invalid spaces\");\n }\n\n const depth = spaces.length / 4;\n const isRoute = line.includes(\"(\");\n const methods = isRoute ? [getMethod(line)] : null;\n\n allSegments.push({\n depth,\n index,\n isRoute,\n methods,\n segment,\n });\n\n return allSegments;\n }, []);\n\n const routes: Route[] = [];\n\n segments\n .filter((item) => item.isRoute)\n .forEach((item) => {\n const ancestorSegments = segments\n .filter((seg) => seg.index < item.index && seg.depth < item.depth)\n // eslint-disable-next-line unicorn/prefer-array-some\n .filter((seg, _index, previousArray) => !previousArray.find((segment) => segment.depth === seg.depth && segment.index > seg.index));\n\n const route = [...ancestorSegments.map((r) => r.segment), item.segment].join(\"\");\n\n if (item.methods === null) {\n throw new Error(\"Invalid methods\");\n }\n\n item.methods.forEach((method: string) => {\n routes.push({\n file: \"unknown\",\n method: method.toUpperCase(),\n path: route,\n tags: [],\n });\n });\n });\n\n return routes;\n};\n\nexport default fastifyRoutes;\n","import type { Server } from \"@hapi/hapi\";\n\nimport type { Route } from \"./types\";\n\nconst hapiRoutes = (app: Server): Route[] => {\n // @ts-expect-error TS2339: Property '_core' does not exist on type 'Server'. Internal API.\n // eslint-disable-next-line no-underscore-dangle\n const core = app._core as any;\n const coreRoutes = core.router.routes;\n const routes: Route[] = [];\n\n [...coreRoutes.keys()].forEach((method: string) => {\n coreRoutes.get(method).routes.forEach((route: any) => {\n routes.push({\n file: \"unknown\",\n method: route.route.method.toUpperCase(),\n path: route.path,\n tags: [],\n });\n });\n });\n\n return routes;\n};\n\nexport default hapiRoutes;\n","import type Koa from \"koa\";\n\nimport type { Route } from \"./types\";\n\nconst koaRoutes = (app: Koa): Route[] => {\n const routes: Route[] = [];\n\n app.middleware\n .filter((middlewareFunction) => (middlewareFunction as any).router)\n\n .flatMap((middlewareFunction) => (middlewareFunction as any).router.stack)\n .forEach((route) => {\n routes.push({\n file: \"unknown\",\n method: route.methods.join(\"|\").toUpperCase(),\n path: route.path,\n tags: [],\n });\n });\n\n return routes;\n};\n\nexport default koaRoutes;\n","import { readFileSync } from \"node:fs\";\nimport process from \"node:process\";\n\nimport type { OpenApiObject } from \"@visulima/jsdoc-open-api\";\nimport { jsDocumentCommentsToOpenApi, parseFile, swaggerJsDocumentCommentsToOpenApi } from \"@visulima/jsdoc-open-api\";\n\nimport type { Route } from \"../types\";\n\n// eslint-disable-next-line regexp/no-unused-capturing-group\nconst extensionRegex = /\\.(js|ts|mjs|cjs)$/u;\n\n// eslint-disable-next-line sonarjs/cognitive-complexity\nconst apiRouteFileParser = (apiRouteFile: string, cwdPath: string, verbose = false): Route[] => {\n let specs: OpenApiObject[] = [];\n\n const parsedJsDocumentFile = parseFile(apiRouteFile, jsDocumentCommentsToOpenApi, verbose);\n\n specs = [...specs, ...parsedJsDocumentFile.map((item) => item.spec)];\n\n const parsedSwaggerJsDocumentFile = parseFile(apiRouteFile, swaggerJsDocumentCommentsToOpenApi, verbose);\n\n specs = [...specs, ...parsedSwaggerJsDocumentFile.map((item) => item.spec)];\n\n const routes: Route[] = [];\n\n if (specs.length === 0) {\n const apiRouteFileContent = readFileSync(apiRouteFile, \"utf8\");\n\n apiRouteFileContent.split(/\\r?\\n/u).forEach((line) => {\n const match = /[=aces|]+\\s[\"'|](GET|POST|PUT|PATCH|HEAD|DELETE|OPTIONS)[\"'|]/u.exec(line);\n\n if (match) {\n let [, method] = match;\n\n if (method === \"GET\") {\n method = \"GET|HEAD\";\n }\n\n routes.push({\n file: apiRouteFile.replace(`${process.cwd()}${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`, \"\"),\n method: method as string,\n path: apiRouteFile.replace(cwdPath, \"\").replace(extensionRegex, \"\").replaceAll(\"\\\\\", \"/\"),\n tags: [],\n });\n }\n });\n\n if (routes.length === 0) {\n routes.push({\n file: apiRouteFile.replace(`${process.cwd()}${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`, \"\"),\n method: \"GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS\",\n path: apiRouteFile.replace(cwdPath, \"\").replace(extensionRegex, \"\").replaceAll(\"\\\\\", \"/\"),\n tags: [],\n });\n }\n\n return routes;\n }\n\n specs.forEach((spec) => {\n const paths = Object.entries(spec?.paths ?? {});\n\n paths.forEach(([path, pathSpec]) => {\n const methods = Object.entries(pathSpec);\n\n methods.forEach(([method, methodSpec]) => {\n routes.push({\n file: apiRouteFile.replace(`${process.cwd()}${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`, \"\"),\n method: method.toUpperCase(),\n path: path.replaceAll(\"\\\\\", \"/\"),\n tags: methodSpec.tags,\n });\n });\n });\n });\n\n return routes;\n};\n\nexport default apiRouteFileParser;\n","import { statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { collect } from \"@visulima/fs\";\n\nimport { ALLOWED_EXTENSIONS } from \"../../utils\";\n\nconst isDirectory = (path: string): boolean => {\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n};\n\nconst collectApiRouteFiles = async (path = \"\"): Promise<string[]> => {\n let apiFolderPath = join(path, \"pages/api\");\n\n // src/pages will be ignored if pages is present in the root directory\n if (!isDirectory(apiFolderPath)) {\n apiFolderPath = join(path, \"src/pages/api\");\n\n if (!isDirectory(apiFolderPath)) {\n return [];\n }\n }\n\n return collect(apiFolderPath, {\n extensions: ALLOWED_EXTENSIONS,\n includeDirs: false,\n });\n};\n\nexport default collectApiRouteFiles;\n","// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.\n// Documentation and interface for walk were adapted from Go\n// https://golang.org/pkg/path/filepath/#Walk\n// Copyright 2009 The Go Authors. All rights reserved. BSD license.\n\nimport type { Stats } from \"node:fs\";\nimport { readdir, realpath, stat } from \"node:fs/promises\";\nimport { basename, join, normalize, resolve } from \"node:path\";\n\nimport WalkError from \"./error/walk-error\";\nimport type { WalkEntry, WalkOptions } from \"./types\";\nimport globToRegExp from \"./utils/glob-to-regex\";\nimport toPath from \"./utils/to-path\";\nimport walkInclude from \"./utils/walk-include\";\n\n// eslint-disable-next-line @typescript-eslint/naming-convention,no-underscore-dangle\nconst _createWalkEntry = async (path: string): Promise<WalkEntry> => {\n const normalizePath: string = normalize(path as string);\n\n const name = basename(normalizePath);\n // eslint-disable-next-line security/detect-non-literal-fs-filename\n const info: Stats = await stat(normalizePath);\n\n return {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n isDirectory: info.isDirectory,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n isFile: info.isFile,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n isSymbolicLink: info.isSymbolicLink,\n name,\n path: normalizePath,\n };\n};\n\n/**\n * Walks the file tree rooted at root, yielding each file or directory in the\n * tree filtered according to the given options.\n * Options:\n * - maxDepth?: number = Infinity;\n * - includeFiles?: boolean = true;\n * - includeDirs?: boolean = true;\n * - includeSymlinks?: boolean = true;\n * - followSymlinks?: boolean = false;\n * - extensions?: string[];\n * - match?: string | ReadonlyArray<string>;\n * - skip?: string | ReadonlyArray<string>;\n */\n// eslint-disable-next-line sonarjs/cognitive-complexity\nexport default async function* walk(\n directory: URL | string,\n {\n extensions,\n followSymlinks = false,\n includeDirs: includeDirectories = true,\n includeFiles = true,\n includeSymlinks = true,\n match,\n maxDepth = Number.POSITIVE_INFINITY,\n skip,\n }: WalkOptions = {},\n): AsyncIterableIterator<WalkEntry> {\n if (maxDepth < 0) {\n return;\n }\n\n const mappedMatch = match ? match.map((pattern): RegExp => (typeof pattern === \"string\" ? globToRegExp(pattern) : pattern)) : undefined;\n const mappedSkip = skip ? skip.map((pattern): RegExp => (typeof pattern === \"string\" ? globToRegExp(pattern) : pattern)) : undefined;\n\n // eslint-disable-next-line no-param-reassign\n directory = resolve(toPath(directory));\n\n if (includeDirectories && walkInclude(directory, extensions, mappedMatch, mappedSkip)) {\n yield await _createWalkEntry(directory);\n }\n\n if (maxDepth < 1 || !walkInclude(directory, undefined, undefined, mappedSkip)) {\n return;\n }\n\n try {\n // eslint-disable-next-line no-restricted-syntax,security/detect-non-literal-fs-filename,no-loops/no-loops\n for await (const entry of await readdir(directory, {\n withFileTypes: true,\n })) {\n let path = join(directory, entry.name);\n\n if (entry.isSymbolicLink()) {\n if (followSymlinks) {\n // eslint-disable-next-line security/detect-non-literal-fs-filename\n path = await realpath(path);\n } else if (includeSymlinks && walkInclude(path, extensions, mappedMatch, mappedSkip)) {\n yield {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n isDirectory: entry.isDirectory,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n isFile: entry.isFile,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n isSymbolicLink: entry.isSymbolicLink,\n name: entry.name,\n path,\n };\n } else {\n // eslint-disable-next-line no-continue\n continue;\n }\n }\n\n if (entry.isSymbolicLink() || entry.isDirectory()) {\n yield* walk(path, {\n extensions,\n followSymlinks,\n includeDirs: includeDirectories,\n includeFiles,\n includeSymlinks,\n match: mappedMatch,\n maxDepth: maxDepth - 1,\n skip: mappedSkip,\n } as WalkOptions);\n } else if (entry.isFile() && includeFiles && walkInclude(path, extensions, mappedMatch, mappedSkip)) {\n yield {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n isDirectory: entry.isDirectory,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n isFile: entry.isFile,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n isSymbolicLink: entry.isSymbolicLink,\n name: entry.name,\n path,\n };\n }\n }\n } catch (error) {\n if (error instanceof WalkError) {\n throw error;\n }\n\n throw new WalkError(error, directory);\n }\n}\n","import { readdirSync, readFileSync } from \"node:fs\";\nimport { parse } from \"node:path\";\n\nimport type { PackageJson } from \"type-fest\";\n\ninterface AppExport {\n [key: string]: any;\n app?: string | { app?: string };\n}\n\nexport const ALLOWED_EXTENSIONS = [\".js\", \".ts\", \".mjs\", \".cjs\"];\n\nexport const getAppWorkingDirectoryPath = (appFilePath: string): string | null => {\n let lastParsedPath = parse(appFilePath);\n\n // Once the following condition returns false it means we traversed the whole file system\n // eslint-disable-next-line no-loops/no-loops\n while (lastParsedPath.base && lastParsedPath.root !== lastParsedPath.dir) {\n const parentDirectionItems = readdirSync(lastParsedPath.dir);\n\n const packageJSON = parentDirectionItems.find((item) => item === \"package.json\");\n\n if (packageJSON) {\n return lastParsedPath.dir;\n }\n\n lastParsedPath = parse(lastParsedPath.dir);\n }\n\n return null;\n};\n\nexport const getFrameworkName = (directory: string): \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | null => {\n const packageJSONFilePath = `${directory}/package.json`;\n\n const { dependencies } = JSON.parse(readFileSync(packageJSONFilePath).toString()) as PackageJson;\n\n // eslint-disable-next-line @typescript-eslint/dot-notation\n if (dependencies?.[\"express\"]) {\n return \"express\";\n }\n\n // eslint-disable-next-line @typescript-eslint/dot-notation\n if (dependencies?.[\"koa\"] && (dependencies[\"@koa/router\"] || dependencies[\"koa-router\"])) {\n return \"koa\";\n }\n\n // eslint-disable-next-line @typescript-eslint/dot-notation\n if (dependencies?.[\"next\"]) {\n return \"next\";\n }\n\n if (dependencies?.[\"@hapi/hapi\"]) {\n return \"hapi\";\n }\n\n // eslint-disable-next-line @typescript-eslint/dot-notation\n if (dependencies?.[\"fastify\"]) {\n return \"fastify\";\n }\n\n return null;\n};\n\nexport const getApp = (appExport: AppExport, frameworkName: \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | null): AppExport | string | null => {\n const isExportEmpty = Object.keys(appExport).length === 0;\n\n if (isExportEmpty) {\n return null;\n }\n\n if (frameworkName === \"hapi\") {\n if (typeof (appExport.app as { app?: string }).app === \"string\") {\n return appExport.app as { app: string };\n }\n\n return appExport;\n }\n\n return appExport.app ?? appExport;\n};\n","import type { Server } from \"@hapi/hapi\";\nimport type { Express } from \"express\";\nimport type { FastifyInstance } from \"fastify\";\nimport type Koa from \"koa\";\n\nimport expressRoutes from \"./routes/express-routes\";\nimport fastifyRoutes from \"./routes/fastify-routes\";\nimport hapiRoutes from \"./routes/hapi-routes\";\nimport koaRoutes from \"./routes/koa-routes\";\nimport apiRouteFileParser from \"./routes/next/api-route-file-parser\";\nimport collectApiRouteFiles from \"./routes/next/collect-api-route-files\";\nimport type { Route } from \"./routes/types\";\n\nexport type FrameworkName = \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | \"unknown\";\nexport const getRoutes = async (\n appOrPath: Express | FastifyInstance | Koa | Server | string,\n frameworkName: FrameworkName,\n verbose: boolean,\n): Promise<Route[] | null> => {\n if (frameworkName === \"express\") {\n return expressRoutes(appOrPath as Express);\n }\n\n if (frameworkName === \"koa\") {\n return koaRoutes(appOrPath as Koa);\n }\n\n if (frameworkName === \"hapi\") {\n return hapiRoutes(appOrPath as Server);\n }\n\n if (frameworkName === \"fastify\") {\n return fastifyRoutes(appOrPath as FastifyInstance);\n }\n\n if (frameworkName === \"next\") {\n const apiRouteFiles = await collectApiRouteFiles(appOrPath as string);\n\n if (apiRouteFiles.length === 0) {\n throw new Error(`No API routes found, in \"${appOrPath}\".`);\n }\n\n return apiRouteFiles.flatMap((apiRouteFile) => apiRouteFileParser(apiRouteFile, appOrPath as string, verbose));\n }\n\n return null;\n};\n","import type { Route } from \"./types\";\n\nconst routesGroupBy = (list: Route[], keyGetter: (item: Route) => keyof Route): Map<string, Route[]> => {\n const map = new Map<string, Route[]>();\n\n list.forEach((item) => {\n const key = keyGetter(item);\n const collection = map.get(key);\n\n if (collection) {\n collection.push(item);\n } else {\n map.set(key, [item]);\n }\n });\n\n return map;\n};\n\nexport default routesGroupBy;\n","// eslint-disable-next-line import/no-extraneous-dependencies\nimport chalk from \"chalk\";\n\nimport type { Route } from \"./types\";\n\nconst renderRoute = (method: string, routePath: string): string => {\n const colorMap = {\n ANY: chalk.redBright,\n DELETE: chalk.redBright,\n GET: chalk.blue,\n HEAD: chalk.hex(\"#6C7280\"),\n OPTIONS: chalk.hex(\"#6C7280\"),\n PATCH: chalk.yellow,\n POST: chalk.yellow,\n PUT: chalk.yellow,\n };\n\n let methodText: string;\n\n if (method === \"GET|HEAD\") {\n methodText = `${chalk.blue(\"GET\")}${chalk.grey(\"|HEAD\")}`;\n } else {\n const coloredMethod = colorMap[method as keyof typeof colorMap](method);\n\n methodText = method === \"GET\" ? `${coloredMethod}${chalk.grey(\"|HEAD\")}` : coloredMethod;\n }\n\n const spacesCount = method === \"GET\" ? 6 : 14 - method.length;\n const spaces = Array.from({ length: spacesCount }).fill(\" \").join(\"\");\n\n const dotsCount = process.stdout.columns - 16 - routePath.length - 4;\n const dots = dotsCount > 0 ? Array.from({ length: dotsCount }).fill(\".\").join(\"\") : \"\";\n\n const routeText = routePath\n .split(\"/\")\n .map((segment) => {\n const isDynamicSegment = [\":\", \"[\"].includes(segment[0] ?? \"\");\n\n return isDynamicSegment ? chalk.yellowBright(segment) : segment;\n })\n .join(\"/\");\n\n return ` ${methodText}${spaces}${routeText}${chalk.grey(dots)}`;\n};\n\nconst routesRender = (routesMap: Route[], options: { methods?: string[] } = {}): (string | undefined)[] =>\n routesMap\n .map((route) => {\n if (Array.isArray(options.methods) && options.methods.includes(route.method)) {\n return;\n }\n\n if (route.method === \"GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS\") {\n // eslint-disable-next-line no-param-reassign\n route.method = \"ANY\";\n }\n\n // eslint-disable-next-line consistent-return\n return renderRoute(route.method, route.path.replace(\"/pages\", \"\"));\n })\n .filter(Boolean);\n\nexport default routesRender;\n"]}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { execSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, statSync, rmSync, readdirSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { join, extname, parse, resolve, normalize, basename } from 'node:path';
|
|
4
|
+
import y from 'node:process';
|
|
5
|
+
import h from 'chalk';
|
|
6
|
+
import { parseFile, jsDocumentCommentsToOpenApi, swaggerJsDocumentCommentsToOpenApi } from '@visulima/jsdoc-open-api';
|
|
7
|
+
import { readdir, realpath, stat } from 'node:fs/promises';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
|
|
10
|
+
var re=(e,r)=>{if(r.length===0)throw new Error("must include at least one key to map");let t=e.toString();return r.forEach(o=>{t=o.optional?t.replace("(?:\\/([^\\/]+?))?\\",`/:${o.name}?`):t.replace("(?:([^\\/]+?))",`:${o.name}`);}),t.replace("/?(?=\\/|$)/i","").replace("/^","").replaceAll("\\","").replaceAll(/\/{2,}/gu,"/")},P=re;var oe=(e,r)=>{if(typeof e=="string")return e;if(e.fast_slash)return "";if(e.fast_star)return "*";let t="";r.length>0&&(t=P(e,r));let o=/^\/\^((?:\\[$()*+./?[\\\]^{|}]|[^$()*+./?[\\\]^{|}])*)\$\//u.exec(e.toString().replace("\\/?","").replace("(?=\\/|$)","$"));return Array.isArray(o)&&o.length>1?o[1].replaceAll(/\\(.)/gu,"$1").slice(1):t?t.slice(1):e.toString()},T=oe;var se=(e,r,t)=>{let o=e.route.stack.at(-1),s=r.map(a=>({in:"path",name:a.name,required:!a.optional})),i=e.route.stack.filter(a=>a.handle.metadata);if(i.length>1)throw new Error("Only one metadata middleware is allowed per route");let n=(t+e.route.path).replaceAll(/\/{2,}/gu,"/");return i.length===0?{method:o.method,path:n,pathParams:s}:{metadata:i[0].handle.metadata,method:o.method,path:n,pathParams:s}},F=(e,r,t,o)=>{o=[...o,...t.keys],t.name==="router"&&t.handle&&t.handle.stack.forEach(s=>{r=r||"",F(e,`${r}/${T(t.regexp,t.keys)}`,s,o);}),!(!t.route||t.route.stack.length===0)&&e.push(se(t,o,r));},ie=e=>{let r=e._router||e.router,t=[];return r.stack.forEach(o=>{F(t,"",o,[]);}),t},v=ie;var ne=e=>{let r=[];return v(e).forEach(t=>{r.push({file:"unknown",method:t.method.toUpperCase(),path:t.path,tags:[]});}),r},b=ne;var $=e=>e.replaceAll(/ \(.*\)/gu,"").trim(),L=e=>e.trim().split(" ")[1].slice(1,-1),ae=e=>{let t=e.printRoutes().replaceAll(/[─│└├]/gu," ").trimEnd().split(`
|
|
11
|
+
`),o=t.reduce((i,n,a)=>{let p=$(n);if($(t[a-1]??"")===p){let te=i.filter(A=>A.index<a&&A.segment===p),{methods:D}=te.at(-1);return D!==null&&D.push(L(n)),i}let c=n.replaceAll(/ \(.*\)/gu,"").match(/ /gu);if(c===null)throw new Error("Invalid spaces");let l=c.length/4,m=n.includes("("),S=m?[L(n)]:null;return i.push({depth:l,index:a,isRoute:m,methods:S,segment:p}),i},[]),s=[];return o.filter(i=>i.isRoute).forEach(i=>{let a=[...o.filter(p=>p.index<i.index&&p.depth<i.depth).filter((p,u,c)=>!c.find(l=>l.depth===p.depth&&l.index>p.index)).map(p=>p.segment),i.segment].join("");if(i.methods===null)throw new Error("Invalid methods");i.methods.forEach(p=>{s.push({file:"unknown",method:p.toUpperCase(),path:a,tags:[]});});}),s},j=ae;var le=e=>{let t=e._core.router.routes,o=[];return [...t.keys()].forEach(s=>{t.get(s).routes.forEach(i=>{o.push({file:"unknown",method:i.route.method.toUpperCase(),path:i.path,tags:[]});});}),o},O=le;var pe=e=>{let r=[];return e.middleware.filter(t=>t.router).flatMap(t=>t.router.stack).forEach(t=>{r.push({file:"unknown",method:t.methods.join("|").toUpperCase(),path:t.path,tags:[]});}),r},I=pe;var C=/\.(js|ts|mjs|cjs)$/u,fe=(e,r,t=!1)=>{let o=[],s=parseFile(e,jsDocumentCommentsToOpenApi,t);o=[...o,...s.map(a=>a.spec)];let i=parseFile(e,swaggerJsDocumentCommentsToOpenApi,t);o=[...o,...i.map(a=>a.spec)];let n=[];return o.length===0?(readFileSync(e,"utf8").split(/\r?\n/u).forEach(p=>{let u=/[=aces|]+\s["'|](GET|POST|PUT|PATCH|HEAD|DELETE|OPTIONS)["'|]/u.exec(p);if(u){let[,c]=u;c==="GET"&&(c="GET|HEAD"),n.push({file:e.replace(`${y.cwd()}${y.platform==="win32"?"\\":"/"}`,""),method:c,path:e.replace(r,"").replace(C,"").replaceAll("\\","/"),tags:[]});}}),n.length===0&&n.push({file:e.replace(`${y.cwd()}${y.platform==="win32"?"\\":"/"}`,""),method:"GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS",path:e.replace(r,"").replace(C,"").replaceAll("\\","/"),tags:[]}),n):(o.forEach(a=>{Object.entries(a?.paths??{}).forEach(([u,c])=>{Object.entries(c).forEach(([m,S])=>{n.push({file:e.replace(`${y.cwd()}${y.platform==="win32"?"\\":"/"}`,""),method:m.toUpperCase(),path:u.replaceAll("\\","/"),tags:S.tags});});});}),n)},M=fe;var ke=class extends Error{root;constructor(e,r){super(`${e instanceof Error?e.message:e} for path "${r}"`),this.cause=e,this.name="WalkError",this.root=r;}},H=ke,Re=e=>{let r=e.replace(/\.\*/g,".([^/]*)").replace(/\*\*/g,"(.*)").replace(/(?<!\.)\*(?!\*)/g,"([^/]*)").replace(/\?/g,"[^/]").replace(/\.(?!\*)/g,"\\.").replace(/\{/g,"(").replace(/\}/g,")").replace(/,/g,"|").replace(/\[!(.*?)\]/g,"[^$1]");return new RegExp(`^${r}$`)},K=Re,De=e=>e instanceof URL?fileURLToPath(e):e,Ae=De,Pe=(e,r,t,o)=>r&&!r.some(s=>e.endsWith(s))||t&&!t.some(s=>s.test(e))?!1:!(o&&o.some(s=>s.test(e))),E=Pe,Te=async e=>{let r=normalize(e),t=basename(r),o=await stat(r);return {isDirectory:o.isDirectory,isFile:o.isFile,isSymbolicLink:o.isSymbolicLink,name:t,path:r}};async function*G(e,{extensions:r,followSymlinks:t=!1,includeDirs:o=!0,includeFiles:s=!0,includeSymlinks:i=!0,match:n,maxDepth:a=Number.POSITIVE_INFINITY,skip:p}={}){if(a<0)return;let u=n?n.map(l=>typeof l=="string"?K(l):l):void 0,c=p?p.map(l=>typeof l=="string"?K(l):l):void 0;if(e=resolve(Ae(e)),o&&E(e,r,u,c)&&(yield await Te(e)),!(a<1||!E(e,void 0,void 0,c)))try{for await(let l of await readdir(e,{withFileTypes:!0})){let m=join(e,l.name);if(l.isSymbolicLink())if(t)m=await realpath(m);else if(i&&E(m,r,u,c))yield {isDirectory:l.isDirectory,isFile:l.isFile,isSymbolicLink:l.isSymbolicLink,name:l.name,path:m};else continue;l.isSymbolicLink()||l.isDirectory()?yield*G(m,{extensions:r,followSymlinks:t,includeDirs:o,includeFiles:s,includeSymlinks:i,match:u,maxDepth:a-1,skip:c}):l.isFile()&&s&&E(m,r,u,c)&&(yield {isDirectory:l.isDirectory,isFile:l.isFile,isSymbolicLink:l.isSymbolicLink,name:l.name,path:m});}}catch(l){throw l instanceof H?l:new H(l,e)}}var Fe=async(e,r={})=>{let t={extensions:["js","mjs","cjs","ts"],...r},o=[];for await(let s of G(e,t))o.push(s.path);return o},U=Fe;var x=[".js",".ts",".mjs",".cjs"],W=e=>{let r=parse(e);for(;r.base&&r.root!==r.dir;){if(readdirSync(r.dir).find(s=>s==="package.json"))return r.dir;r=parse(r.dir);}return null},J=e=>{let r=`${e}/package.json`,{dependencies:t}=JSON.parse(readFileSync(r).toString());return t?.express?"express":t?.koa&&(t["@koa/router"]||t["koa-router"])?"koa":t?.next?"next":t?.["@hapi/hapi"]?"hapi":t?.fastify?"fastify":null},B=(e,r)=>Object.keys(e).length===0?null:r==="hapi"?typeof e.app.app=="string"?e.app:e:e.app??e;var Y=e=>{try{return statSync(e).isDirectory()}catch{return !1}},Le=async(e="")=>{let r=join(e,"pages/api");return !Y(r)&&(r=join(e,"src/pages/api"),!Y(r))?[]:U(r,{extensions:x,includeDirs:!1})},X=Le;var w=async(e,r,t)=>{if(r==="express")return b(e);if(r==="koa")return I(e);if(r==="hapi")return O(e);if(r==="fastify")return j(e);if(r==="next"){let o=await X(e);if(o.length===0)throw new Error(`No API routes found, in "${e}".`);return o.flatMap(s=>M(s,e,t))}return null};var je=(e,r)=>{let t=new Map;return e.forEach(o=>{let s=r(o),i=t.get(s);i?i.push(o):t.set(s,[o]);}),t},z=je;var Oe=(e,r)=>{let t={ANY:h.redBright,DELETE:h.redBright,GET:h.blue,HEAD:h.hex("#6C7280"),OPTIONS:h.hex("#6C7280"),PATCH:h.yellow,POST:h.yellow,PUT:h.yellow},o;if(e==="GET|HEAD")o=`${h.blue("GET")}${h.grey("|HEAD")}`;else {let u=t[e](e);o=e==="GET"?`${u}${h.grey("|HEAD")}`:u;}let s=e==="GET"?6:14-e.length,i=Array.from({length:s}).fill(" ").join(""),n=process.stdout.columns-16-r.length-4,a=n>0?Array.from({length:n}).fill(".").join(""):"",p=r.split("/").map(u=>[":","["].includes(u[0]??"")?h.yellowBright(u):u).join("/");return ` ${o}${i}${p}${h.grey(a)}`},Ie=(e,r={})=>e.map(t=>{if(!(Array.isArray(r.methods)&&r.methods.includes(t.method)))return t.method==="GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS"&&(t.method="ANY"),Oe(t.method,t.path.replace("/pages",""))}).filter(Boolean),k=Ie;var Me=async(e,r,t={})=>{let o=join(y.cwd(),r);if(!existsSync(o))throw new Error("No such file, invalid path provided.");let s=W(o);if(!s)throw new Error("Please initialize local package.json.");if(e===void 0){let n=J(s);if(!n)throw new Error("Couldn't detect supported back-end framework.");e=n;}let i=null;if(e==="next")i=await w(o,"next",t.verbose??!1);else {if(!statSync(o).isFile())throw new Error(`${o} is directory, but file expected.`);if(!x.includes(extname(o)))throw new Error("Please specify application .ts/.js/.mjs/.cjs file.");let n=`${s}/.env`;existsSync(n)&&(await import(`${s}/node_modules/dotenv/lib/main.js`)).config({path:n});let a=extname(o)===".ts",p=join(s,"node_modules/.bin/tsc");if(a&&!existsSync(p))throw new Error(`Please install typescript in ${s}`);try{if(a)try{execSync(`${p} --outDir framework-list >&2`,{cwd:s});}catch(l){console.log(`TSC compilation failed. Please resolve issues in your project.
|
|
12
|
+
`),console.log(l),rmSync(join(s,"framework-list"),{recursive:!0});}let u=a?join(s,"framework-list",o.replace(s,"").replace(".ts",".js")):o,{default:c}=await import(u);i=await w(["AsyncFunction","Function"].includes(c.constructor.name)?await c():B(c,e),e,t.verbose??!1);}finally{a&&rmSync(join(s,"framework-list"),{recursive:!0});}}if(i===null)throw new Error(`Framework "${e}" is not supported.`);if(Array.isArray(t.includePaths)&&t.includePaths.length>0&&(i=t.includePaths.flatMap(n=>i.filter(a=>a.path.startsWith(n)))),Array.isArray(t.excludePaths)&&t.excludePaths.length>0&&(i=t.excludePaths.flatMap(n=>i.filter(a=>!a.path.startsWith(n)))),typeof t.group=="string"&&t.group!==""){console.log();let n=z(i,p=>t.group==="path"?p.path.replace("/pages","").split("/")[1]:p.tags[0]??"unsorted"),a=0;n.forEach((p,u)=>{a>0&&console.log();let c=(y.stdout.columns-16-u.length)/2,l=c>0?Array.from({length:c}).fill(" ").join(""):"";console.log(l+h.bold.underline(u)),k(p,t).forEach(m=>{console.log(m);}),a+=1;});}else console.log(),k(i,t).forEach(n=>{console.log(n);});console.log(`
|
|
13
|
+
Listed ${h.greenBright(String(i.length))} HTTP ${i.length===1?"route":"routes"}.
|
|
14
|
+
`);},Yt=Me;
|
|
15
|
+
|
|
16
|
+
export { Yt as a };
|
|
17
|
+
//# sourceMappingURL=out.js.map
|
|
18
|
+
//# sourceMappingURL=chunk-JEDCAOHQ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/framework/cli/command/list/list-command.ts","../src/framework/cli/command/list/routes/express/map-keys-to-path.ts","../src/framework/cli/command/list/routes/express/path-regex-parser.ts","../src/framework/cli/command/list/routes/express/express-path-parser.ts","../src/framework/cli/command/list/routes/express-routes.ts","../src/framework/cli/command/list/routes/fastify-routes.ts","../src/framework/cli/command/list/routes/hapi-routes.ts","../src/framework/cli/command/list/routes/koa-routes.ts","../src/framework/cli/command/list/routes/next/api-route-file-parser.ts","../src/framework/cli/command/list/routes/next/collect-api-route-files.ts","../../fs/src/walk.ts","../src/framework/cli/command/list/utils.ts","../src/framework/cli/command/list/get-routes.ts","../src/framework/cli/command/list/routes/routes-group-by.ts","../src/framework/cli/command/list/routes/routes-render.ts"],"names":["execSync","existsSync","rmSync","statSync","extname","join","process","chalk","mapKeysToPath","layerRegexPath","keys","convertedSubPath","key","map_keys_to_path_default","pathRegexParser","mappedPath","match","path_regex_parser_default","parseRouteLayer","layer","basePath","lastRequestHandler","pathParameters","filtered","element","path","traverse","routes","l","expressPathParser","app","router","express_path_parser_default","expressRoutes","route","express_routes_default","getSegment","line","getMethod","fastifyRoutes","lines","segments","allSegments","index","segment","entries","item","methods","spaces","depth","isRoute","seg","_index","previousArray","r","method","fastify_routes_default","hapiRoutes","coreRoutes","hapi_routes_default","koaRoutes","middlewareFunction","koa_routes_default","readFileSync","jsDocumentCommentsToOpenApi","parseFile","swaggerJsDocumentCommentsToOpenApi","extensionRegex","apiRouteFileParser","apiRouteFile","cwdPath","verbose","specs","parsedJsDocumentFile","parsedSwaggerJsDocumentFile","spec","pathSpec","methodSpec","api_route_file_parser_default","readdir","stat","readdirSync","parse","ALLOWED_EXTENSIONS","getAppWorkingDirectoryPath","appFilePath","lastParsedPath","getFrameworkName","directory","packageJSONFilePath","dependencies","getApp","appExport","frameworkName","isDirectory","collectApiRouteFiles","apiFolderPath","$","collect_api_route_files_default","getRoutes","appOrPath","apiRouteFiles","routesGroupBy","list","keyGetter","map","collection","routes_group_by_default","renderRoute","routePath","colorMap","methodText","coloredMethod","spacesCount","dotsCount","dots","routeText","routesRender","routesMap","options","routes_render_default","listCommand","framework","frameworkPath","appWorkingDirectoryPath","environmentFilePath","isTypeScriptApp","tscPath","error","appJsFilePath","defaultExport","ipath","epath","groupedMap","counter","groupedRoutes","renderedRoute","list_command_default"],"mappings":"AAAA,OAAS,YAAAA,OAAgB,qBACzB,OAAS,cAAAC,EAAY,UAAAC,EAAQ,YAAAC,OAAgB,UAC7C,OAAS,WAAAC,EAAS,QAAAC,MAAY,YAC9B,OAAOC,MAAa,eAGpB,OAAOC,OAAW,QCIlB,IAAMC,GAAgB,CAACC,EAA8BC,IAAwB,CACzE,GAAIA,EAAK,SAAW,EAChB,MAAM,IAAI,MAAM,sCAAsC,EAG1D,IAAIC,EAAmBF,EAAe,SAAS,EAE/C,OAAAC,EAAK,QAASE,GAAQ,CAClBD,EAAmBC,EAAI,SACjBD,EAAiB,QAAQ,uBAAwB,KAAKC,EAAI,IAAI,GAAG,EACjED,EAAiB,QAAQ,iBAAkB,IAAIC,EAAI,IAAI,EAAE,CACnE,CAAC,EAEMD,EACF,QAAQ,gBAAiB,EAAE,EAC3B,QAAQ,KAAM,EAAE,EAChB,WAAW,KAAM,EAAE,EACnB,WAAW,WAAY,GAAG,CACnC,EAEOE,EAAQL,GCnBf,IAAMM,GAAkB,CAACL,EAAuCC,IAAwB,CACpF,GAAI,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AIA,CAAa,CAC7B,CAAC,EAEDF,GAAW,CACf,CAAC,CACL,MAEI,QAAQ,IAAI,EAEZd,EAAa7F,EAAQ4F,CAAO,EAAE,QAASiB,GAAkB,CAErD,QAAQ,IAAIA,CAAa,CAC7B,CAAC,EAIL,QAAQ,IAAI;AAAA,WAAcjI,GAAM,YAAY,OAAOoB,EAAO,MAAM,CAAC,CAAC,SAASA,EAAO,SAAW,EAAI,QAAU,QAAQ;AAAA,CAAK,CAC5H,EAEO8G,GAAQhB","sourcesContent":["import { execSync } from \"node:child_process\";\nimport { existsSync, rmSync, statSync } from \"node:fs\";\nimport { extname, join } from \"node:path\";\nimport process from \"node:process\";\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport chalk from \"chalk\";\n\nimport { getRoutes } from \"./get-routes\";\nimport routesGroupBy from \"./routes/routes-group-by\";\nimport routesRender from \"./routes/routes-render\";\nimport type { Route } from \"./routes/types\";\nimport { ALLOWED_EXTENSIONS, getApp, getAppWorkingDirectoryPath, getFrameworkName } from \"./utils\";\n\ninterface RenderOptions {\n excludePaths: string[];\n group: string;\n includePaths: string[];\n methods: string[];\n verbose: boolean;\n}\n\nconst listCommand = async (\n framework: \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | undefined,\n path: string,\n options: Partial<RenderOptions> = {},\n // eslint-disable-next-line sonarjs/cognitive-complexity\n): Promise<void> => {\n const frameworkPath = join(process.cwd(), path);\n\n if (!existsSync(frameworkPath)) {\n throw new Error(\"No such file, invalid path provided.\");\n }\n\n const appWorkingDirectoryPath = getAppWorkingDirectoryPath(frameworkPath);\n\n if (!appWorkingDirectoryPath) {\n throw new Error(\"Please initialize local package.json.\");\n }\n\n if (framework === undefined) {\n const frameworkName = getFrameworkName(appWorkingDirectoryPath);\n\n if (!frameworkName) {\n throw new Error(\"Couldn't detect supported back-end framework.\");\n }\n\n // eslint-disable-next-line no-param-reassign\n framework = frameworkName;\n }\n\n let routes: Route[] | null = null;\n\n if (framework === \"next\") {\n routes = await getRoutes(frameworkPath, \"next\", options.verbose ?? false);\n } else {\n if (!statSync(frameworkPath).isFile()) {\n throw new Error(`${frameworkPath} is directory, but file expected.`);\n }\n\n if (!ALLOWED_EXTENSIONS.includes(extname(frameworkPath))) {\n throw new Error(\"Please specify application .ts/.js/.mjs/.cjs file.\");\n }\n\n const environmentFilePath = `${appWorkingDirectoryPath}/.env`;\n\n if (existsSync(environmentFilePath)) {\n // Loads environment vars in the current process so application\n // that depends on them can be loaded properly below\n const dotEnvironmentFilePath = `${appWorkingDirectoryPath}/node_modules/dotenv/lib/main.js`;\n const dotenv = await import(dotEnvironmentFilePath);\n\n dotenv.config({ path: environmentFilePath });\n }\n\n const isTypeScriptApp = extname(frameworkPath) === \".ts\";\n const tscPath = join(appWorkingDirectoryPath, \"node_modules/.bin/tsc\");\n\n if (isTypeScriptApp && !existsSync(tscPath)) {\n throw new Error(`Please install typescript in ${appWorkingDirectoryPath}`);\n }\n\n try {\n if (isTypeScriptApp) {\n // || rm -r ./framework-list removes framework-list directory in case tsc fails\n\n try {\n execSync(`${tscPath} --outDir framework-list >&2`, { cwd: appWorkingDirectoryPath });\n } catch (error: any) {\n // eslint-disable-next-line no-console\n console.log(\"TSC compilation failed. Please resolve issues in your project.\\n\");\n // eslint-disable-next-line no-console\n console.log(error);\n\n rmSync(join(appWorkingDirectoryPath, \"framework-list\"), { recursive: true });\n }\n }\n\n const appJsFilePath = isTypeScriptApp\n ? join(appWorkingDirectoryPath, \"framework-list\", frameworkPath.replace(appWorkingDirectoryPath, \"\").replace(\".ts\", \".js\"))\n : frameworkPath;\n\n const { default: defaultExport } = await import(appJsFilePath);\n\n routes = await getRoutes(\n [\"AsyncFunction\", \"Function\"].includes(defaultExport.constructor.name as string) ? await defaultExport() : getApp(defaultExport, framework),\n framework,\n options.verbose ?? false,\n );\n } finally {\n if (isTypeScriptApp) {\n rmSync(join(appWorkingDirectoryPath, \"framework-list\"), { recursive: true });\n }\n }\n }\n\n if (routes === null) {\n throw new Error(`Framework \"${framework}\" is not supported.`);\n }\n\n if (Array.isArray(options.includePaths) && options.includePaths.length > 0) {\n routes = options.includePaths.flatMap((ipath) => (routes as Route[]).filter((route) => route.path.startsWith(ipath)));\n }\n\n if (Array.isArray(options.excludePaths) && options.excludePaths.length > 0) {\n routes = options.excludePaths.flatMap((epath) => (routes as Route[]).filter((route) => !route.path.startsWith(epath)));\n }\n\n if (typeof options.group === \"string\" && options.group !== \"\") {\n // eslint-disable-next-line no-console\n console.log();\n\n const groupedMap = routesGroupBy(routes, (route) => {\n if (options.group === \"path\") {\n return route.path.replace(\"/pages\", \"\").split(\"/\")[1];\n }\n\n return route.tags[0] ?? \"unsorted\";\n });\n\n let counter = 0;\n\n groupedMap.forEach((groupedRoutes, key) => {\n if (counter > 0) {\n // eslint-disable-next-line no-console\n console.log();\n }\n\n const dotsCount = (process.stdout.columns - 16 - key.length) / 2;\n const dots = dotsCount > 0 ? Array.from({ length: dotsCount }).fill(\" \").join(\"\") : \"\";\n\n // eslint-disable-next-line no-console\n console.log(dots + chalk.bold.underline(key));\n\n routesRender(groupedRoutes, options).forEach((renderedRoute) => {\n // eslint-disable-next-line no-console\n console.log(renderedRoute);\n });\n\n counter += 1;\n });\n } else {\n // eslint-disable-next-line no-console\n console.log();\n\n routesRender(routes, options).forEach((renderedRoute) => {\n // eslint-disable-next-line no-console\n console.log(renderedRoute);\n });\n }\n\n // eslint-disable-next-line no-console\n console.log(`\\n Listed ${chalk.greenBright(String(routes.length))} HTTP ${routes.length === 1 ? \"route\" : \"routes\"}.\\n`);\n};\n\nexport default listCommand;\n","import type { ExpressRegex, Key } from \"./types\";\n\n/**\n * Map's the keys/path variables to the regex inside a given path\n *\n * @param layerRegexPath The regex for a router with path parameters\n * @param keys The keys that represent the path parameters\n *\n * @returns The regex for a path variable converted to original string on the express route\n */\nconst mapKeysToPath = (layerRegexPath: ExpressRegex, keys: Key[]): string => {\n if (keys.length === 0) {\n throw new Error(\"must include at least one key to map\");\n }\n\n let convertedSubPath = layerRegexPath.toString();\n\n keys.forEach((key) => {\n convertedSubPath = key.optional\n ? convertedSubPath.replace(\"(?:\\\\/([^\\\\/]+?))?\\\\\", `/:${key.name}?`)\n : convertedSubPath.replace(\"(?:([^\\\\/]+?))\", `:${key.name}`);\n });\n\n return convertedSubPath\n .replace(\"/?(?=\\\\/|$)/i\", \"\")\n .replace(\"/^\", \"\")\n .replaceAll(\"\\\\\", \"\")\n .replaceAll(/\\/{2,}/gu, \"/\");\n};\n\nexport default mapKeysToPath;\n","import mapKeysToPath from \"./map-keys-to-path\";\nimport type { ExpressRegex, Key } from \"./types\";\n\n/** Parses an express layer's regex and converts it to the original format seen in code.\n *\n * @param layerRegexPath The layer's regex pattern\n * @param keys The keys that represent the layer's path parameters\n * @returns The path string for that layer\n * Code inspired and modify from:\n * https://github.com/expressjs/express/issues/3308#issuecomment-300957572\n */\nconst pathRegexParser = (layerRegexPath: ExpressRegex | string, keys: Key[]): string => {\n if (typeof layerRegexPath === \"string\") {\n return layerRegexPath;\n }\n\n if (layerRegexPath.fast_slash) {\n return \"\";\n }\n\n if (layerRegexPath.fast_star) {\n return \"*\";\n }\n\n let mappedPath = \"\";\n\n if (keys.length > 0) {\n mappedPath = mapKeysToPath(layerRegexPath, keys);\n }\n\n const match = /^\\/\\^((?:\\\\[$()*+./?[\\\\\\]^{|}]|[^$()*+./?[\\\\\\]^{|}])*)\\$\\//u.exec(\n layerRegexPath.toString().replace(\"\\\\/?\", \"\").replace(\"(?=\\\\/|$)\", \"$\"),\n ) as string[];\n\n if (Array.isArray(match) && match.length > 1) {\n return (match[1] as string).replaceAll(/\\\\(.)/gu, \"$1\").slice(1);\n }\n\n if (mappedPath) {\n return mappedPath.slice(1);\n }\n\n return layerRegexPath.toString();\n};\n\nexport default pathRegexParser;\n","import type { Express, Router } from \"express\";\n\nimport pathRegexParser from \"./path-regex-parser\";\nimport type { Key, Layer, Parameter, Route, RouteMetaData } from \"./types\";\n\n/**\n * Parses a route object. Route objects are the leafs of an express router tree\n *\n * @param layer The layer of this route object - represents the stack of middleware and other metadata\n * @param keys The full set of keys for this particular route\n * @param basePath The base path as it was initial declared for this route\n * @returns A ExpressPath object holding the metadata for a given route\n */\nconst parseRouteLayer = (layer: Required<Layer>, keys: Key[], basePath: string): RouteMetaData => {\n const lastRequestHandler = layer.route.stack.at(-1) as Layer;\n const pathParameters: Parameter[] = keys.map((key) => {\n return { in: \"path\", name: key.name, required: !key.optional };\n });\n\n const filtered = layer.route.stack.filter((element) => (element.handle as Route).metadata);\n\n if (filtered.length > 1) {\n throw new Error(\"Only one metadata middleware is allowed per route\");\n }\n\n const path = (basePath + layer.route.path).replaceAll(/\\/{2,}/gu, \"/\");\n\n if (filtered.length === 0) {\n return { method: lastRequestHandler.method, path, pathParams: pathParameters };\n }\n\n return {\n metadata: ((filtered[0] as Layer).handle as Route).metadata,\n method: lastRequestHandler.method,\n path,\n pathParams: pathParameters,\n };\n};\n\n/**\n * Recursive traversal method for the express router and middleware tree.\n *\n * @param routes The array of routes to add to\n * @param path The current path segment that we have traversed so far\n * @param layer The current 'layer' of the router tree\n * @param keys The keys for the parameter's in the current path branch of the traversal\n * @returns void - base case saves result to internal object\n */\nconst traverse = (routes: RouteMetaData[], path: string, layer: Layer, keys: Key[]): void => {\n // eslint-disable-next-line no-param-reassign\n keys = [...keys, ...layer.keys];\n\n if (layer.name === \"router\" && layer.handle) {\n layer.handle.stack.forEach((l: Layer) => {\n // eslint-disable-next-line no-param-reassign\n path = path || \"\";\n\n traverse(routes, `${path}/${pathRegexParser(layer.regexp, layer.keys)}`, l, keys);\n });\n }\n\n if (!layer.route || layer.route.stack.length === 0) {\n return;\n }\n\n routes.push(parseRouteLayer(layer as Required<Layer>, keys, path));\n};\n\n// @TODO use this to parse the express swagger\n\n/**\n * Parses an Express app and generates list of routes with metadata.\n *\n * Can Parse:\n * - Nested Routers and Complex Express Projects\n * - Optional parameters e.g. /:name?\n * - Complex Matching routes e.g. /ma*tch, /ex(ab)?mple\n * - Regex routes e.g. /\\/abc|\\/xyz/\n * - Array of paths e.g. app.get(['/abc', '/xyz']) -> /abc,xyz/\n *\n * @param app The Express app reference. Must be used after all routes have been attached\n *\n * @returns List of routes for this express app with meta-data that has been picked up\n */\nconst expressPathParser = (app: Express): RouteMetaData[] => {\n // eslint-disable-next-line no-underscore-dangle\n const router: Router = app._router || app.router;\n const routes: RouteMetaData[] = [];\n\n router.stack.forEach((layer: Layer) => {\n traverse(routes, \"\", layer, []);\n });\n\n return routes;\n};\n\nexport default expressPathParser;\n","import type { Express } from \"express\";\n\nimport expressPathParser from \"./express/express-path-parser\";\nimport type { RouteMetaData } from \"./express/types\";\nimport type { Route } from \"./types\";\n\nconst expressRoutes = (app: Express): Route[] => {\n const routes: Route[] = [];\n\n expressPathParser(app).forEach((route: RouteMetaData) => {\n routes.push({\n file: \"unknown\",\n method: route.method.toUpperCase(),\n path: route.path,\n tags: [],\n });\n });\n\n return routes;\n};\n\nexport default expressRoutes;\n","import type { FastifyInstance } from \"fastify\";\n\nimport type { Route } from \"./types\";\n\n// \"<spaces> activity (GET)\" -> \"activity\"\nconst getSegment = (line: string) => line.replaceAll(/ \\(.*\\)/gu, \"\").trim();\n\n// \"<spaces> activity (GET)\" -> \"GET\"\nconst getMethod = (line: string) => (line.trim().split(\" \")[1] as string).slice(1, -1);\n\ninterface Segment {\n depth: number;\n index: number;\n isRoute: boolean;\n methods: string[] | null;\n segment: string;\n}\n\nconst fastifyRoutes = (app: FastifyInstance): Route[] => {\n const printedRoutes = app\n .printRoutes()\n .replaceAll(/[─│└├]/gu, \" \")\n .trimEnd();\n\n const lines = printedRoutes.split(\"\\n\");\n\n // eslint-disable-next-line unicorn/no-array-reduce\n const segments = lines.reduce((allSegments: Segment[], line, index) => {\n const segment = getSegment(line);\n const previousSegment = getSegment(lines[index - 1] ?? \"\");\n\n if (previousSegment === segment) {\n const entries: Segment[] = allSegments.filter((item) => item.index < index && item.segment === segment);\n\n const { methods } = entries.at(-1) as Segment;\n\n if (methods !== null) {\n methods.push(getMethod(line));\n }\n\n return allSegments;\n }\n\n // spaces preceding segment / not counting single space between segment and (METHOD)\n const spaces = line.replaceAll(/ \\(.*\\)/gu, \"\").match(/ /gu);\n\n if (spaces === null) {\n throw new Error(\"Invalid spaces\");\n }\n\n const depth = spaces.length / 4;\n const isRoute = line.includes(\"(\");\n const methods = isRoute ? [getMethod(line)] : null;\n\n allSegments.push({\n depth,\n index,\n isRoute,\n methods,\n segment,\n });\n\n return allSegments;\n }, []);\n\n const routes: Route[] = [];\n\n segments\n .filter((item) => item.isRoute)\n .forEach((item) => {\n const ancestorSegments = segments\n .filter((seg) => seg.index < item.index && seg.depth < item.depth)\n // eslint-disable-next-line unicorn/prefer-array-some\n .filter((seg, _index, previousArray) => !previousArray.find((segment) => segment.depth === seg.depth && segment.index > seg.index));\n\n const route = [...ancestorSegments.map((r) => r.segment), item.segment].join(\"\");\n\n if (item.methods === null) {\n throw new Error(\"Invalid methods\");\n }\n\n item.methods.forEach((method: string) => {\n routes.push({\n file: \"unknown\",\n method: method.toUpperCase(),\n path: route,\n tags: [],\n });\n });\n });\n\n return routes;\n};\n\nexport default fastifyRoutes;\n","import type { Server } from \"@hapi/hapi\";\n\nimport type { Route } from \"./types\";\n\nconst hapiRoutes = (app: Server): Route[] => {\n // @ts-expect-error TS2339: Property '_core' does not exist on type 'Server'. Internal API.\n // eslint-disable-next-line no-underscore-dangle\n const core = app._core as any;\n const coreRoutes = core.router.routes;\n const routes: Route[] = [];\n\n [...coreRoutes.keys()].forEach((method: string) => {\n coreRoutes.get(method).routes.forEach((route: any) => {\n routes.push({\n file: \"unknown\",\n method: route.route.method.toUpperCase(),\n path: route.path,\n tags: [],\n });\n });\n });\n\n return routes;\n};\n\nexport default hapiRoutes;\n","import type Koa from \"koa\";\n\nimport type { Route } from \"./types\";\n\nconst koaRoutes = (app: Koa): Route[] => {\n const routes: Route[] = [];\n\n app.middleware\n .filter((middlewareFunction) => (middlewareFunction as any).router)\n\n .flatMap((middlewareFunction) => (middlewareFunction as any).router.stack)\n .forEach((route) => {\n routes.push({\n file: \"unknown\",\n method: route.methods.join(\"|\").toUpperCase(),\n path: route.path,\n tags: [],\n });\n });\n\n return routes;\n};\n\nexport default koaRoutes;\n","import { readFileSync } from \"node:fs\";\nimport process from \"node:process\";\n\nimport type { OpenApiObject } from \"@visulima/jsdoc-open-api\";\nimport { jsDocumentCommentsToOpenApi, parseFile, swaggerJsDocumentCommentsToOpenApi } from \"@visulima/jsdoc-open-api\";\n\nimport type { Route } from \"../types\";\n\n// eslint-disable-next-line regexp/no-unused-capturing-group\nconst extensionRegex = /\\.(js|ts|mjs|cjs)$/u;\n\n// eslint-disable-next-line sonarjs/cognitive-complexity\nconst apiRouteFileParser = (apiRouteFile: string, cwdPath: string, verbose = false): Route[] => {\n let specs: OpenApiObject[] = [];\n\n const parsedJsDocumentFile = parseFile(apiRouteFile, jsDocumentCommentsToOpenApi, verbose);\n\n specs = [...specs, ...parsedJsDocumentFile.map((item) => item.spec)];\n\n const parsedSwaggerJsDocumentFile = parseFile(apiRouteFile, swaggerJsDocumentCommentsToOpenApi, verbose);\n\n specs = [...specs, ...parsedSwaggerJsDocumentFile.map((item) => item.spec)];\n\n const routes: Route[] = [];\n\n if (specs.length === 0) {\n const apiRouteFileContent = readFileSync(apiRouteFile, \"utf8\");\n\n apiRouteFileContent.split(/\\r?\\n/u).forEach((line) => {\n const match = /[=aces|]+\\s[\"'|](GET|POST|PUT|PATCH|HEAD|DELETE|OPTIONS)[\"'|]/u.exec(line);\n\n if (match) {\n let [, method] = match;\n\n if (method === \"GET\") {\n method = \"GET|HEAD\";\n }\n\n routes.push({\n file: apiRouteFile.replace(`${process.cwd()}${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`, \"\"),\n method: method as string,\n path: apiRouteFile.replace(cwdPath, \"\").replace(extensionRegex, \"\").replaceAll(\"\\\\\", \"/\"),\n tags: [],\n });\n }\n });\n\n if (routes.length === 0) {\n routes.push({\n file: apiRouteFile.replace(`${process.cwd()}${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`, \"\"),\n method: \"GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS\",\n path: apiRouteFile.replace(cwdPath, \"\").replace(extensionRegex, \"\").replaceAll(\"\\\\\", \"/\"),\n tags: [],\n });\n }\n\n return routes;\n }\n\n specs.forEach((spec) => {\n const paths = Object.entries(spec?.paths ?? {});\n\n paths.forEach(([path, pathSpec]) => {\n const methods = Object.entries(pathSpec);\n\n methods.forEach(([method, methodSpec]) => {\n routes.push({\n file: apiRouteFile.replace(`${process.cwd()}${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`, \"\"),\n method: method.toUpperCase(),\n path: path.replaceAll(\"\\\\\", \"/\"),\n tags: methodSpec.tags,\n });\n });\n });\n });\n\n return routes;\n};\n\nexport default apiRouteFileParser;\n","import { statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { collect } from \"@visulima/fs\";\n\nimport { ALLOWED_EXTENSIONS } from \"../../utils\";\n\nconst isDirectory = (path: string): boolean => {\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n};\n\nconst collectApiRouteFiles = async (path = \"\"): Promise<string[]> => {\n let apiFolderPath = join(path, \"pages/api\");\n\n // src/pages will be ignored if pages is present in the root directory\n if (!isDirectory(apiFolderPath)) {\n apiFolderPath = join(path, \"src/pages/api\");\n\n if (!isDirectory(apiFolderPath)) {\n return [];\n }\n }\n\n return collect(apiFolderPath, {\n extensions: ALLOWED_EXTENSIONS,\n includeDirs: false,\n });\n};\n\nexport default collectApiRouteFiles;\n","// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.\n// Documentation and interface for walk were adapted from Go\n// https://golang.org/pkg/path/filepath/#Walk\n// Copyright 2009 The Go Authors. All rights reserved. BSD license.\n\nimport type { Stats } from \"node:fs\";\nimport { readdir, realpath, stat } from \"node:fs/promises\";\nimport { basename, join, normalize, resolve } from \"node:path\";\n\nimport WalkError from \"./error/walk-error\";\nimport type { WalkEntry, WalkOptions } from \"./types\";\nimport globToRegExp from \"./utils/glob-to-regex\";\nimport toPath from \"./utils/to-path\";\nimport walkInclude from \"./utils/walk-include\";\n\n// eslint-disable-next-line @typescript-eslint/naming-convention,no-underscore-dangle\nconst _createWalkEntry = async (path: string): Promise<WalkEntry> => {\n const normalizePath: string = normalize(path as string);\n\n const name = basename(normalizePath);\n // eslint-disable-next-line security/detect-non-literal-fs-filename\n const info: Stats = await stat(normalizePath);\n\n return {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n isDirectory: info.isDirectory,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n isFile: info.isFile,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n isSymbolicLink: info.isSymbolicLink,\n name,\n path: normalizePath,\n };\n};\n\n/**\n * Walks the file tree rooted at root, yielding each file or directory in the\n * tree filtered according to the given options.\n * Options:\n * - maxDepth?: number = Infinity;\n * - includeFiles?: boolean = true;\n * - includeDirs?: boolean = true;\n * - includeSymlinks?: boolean = true;\n * - followSymlinks?: boolean = false;\n * - extensions?: string[];\n * - match?: string | ReadonlyArray<string>;\n * - skip?: string | ReadonlyArray<string>;\n */\n// eslint-disable-next-line sonarjs/cognitive-complexity\nexport default async function* walk(\n directory: URL | string,\n {\n extensions,\n followSymlinks = false,\n includeDirs: includeDirectories = true,\n includeFiles = true,\n includeSymlinks = true,\n match,\n maxDepth = Number.POSITIVE_INFINITY,\n skip,\n }: WalkOptions = {},\n): AsyncIterableIterator<WalkEntry> {\n if (maxDepth < 0) {\n return;\n }\n\n const mappedMatch = match ? match.map((pattern): RegExp => (typeof pattern === \"string\" ? globToRegExp(pattern) : pattern)) : undefined;\n const mappedSkip = skip ? skip.map((pattern): RegExp => (typeof pattern === \"string\" ? globToRegExp(pattern) : pattern)) : undefined;\n\n // eslint-disable-next-line no-param-reassign\n directory = resolve(toPath(directory));\n\n if (includeDirectories && walkInclude(directory, extensions, mappedMatch, mappedSkip)) {\n yield await _createWalkEntry(directory);\n }\n\n if (maxDepth < 1 || !walkInclude(directory, undefined, undefined, mappedSkip)) {\n return;\n }\n\n try {\n // eslint-disable-next-line no-restricted-syntax,security/detect-non-literal-fs-filename,no-loops/no-loops\n for await (const entry of await readdir(directory, {\n withFileTypes: true,\n })) {\n let path = join(directory, entry.name);\n\n if (entry.isSymbolicLink()) {\n if (followSymlinks) {\n // eslint-disable-next-line security/detect-non-literal-fs-filename\n path = await realpath(path);\n } else if (includeSymlinks && walkInclude(path, extensions, mappedMatch, mappedSkip)) {\n yield {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n isDirectory: entry.isDirectory,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n isFile: entry.isFile,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n isSymbolicLink: entry.isSymbolicLink,\n name: entry.name,\n path,\n };\n } else {\n // eslint-disable-next-line no-continue\n continue;\n }\n }\n\n if (entry.isSymbolicLink() || entry.isDirectory()) {\n yield* walk(path, {\n extensions,\n followSymlinks,\n includeDirs: includeDirectories,\n includeFiles,\n includeSymlinks,\n match: mappedMatch,\n maxDepth: maxDepth - 1,\n skip: mappedSkip,\n } as WalkOptions);\n } else if (entry.isFile() && includeFiles && walkInclude(path, extensions, mappedMatch, mappedSkip)) {\n yield {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n isDirectory: entry.isDirectory,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n isFile: entry.isFile,\n // eslint-disable-next-line @typescript-eslint/unbound-method\n isSymbolicLink: entry.isSymbolicLink,\n name: entry.name,\n path,\n };\n }\n }\n } catch (error) {\n if (error instanceof WalkError) {\n throw error;\n }\n\n throw new WalkError(error, directory);\n }\n}\n","import { readdirSync, readFileSync } from \"node:fs\";\nimport { parse } from \"node:path\";\n\nimport type { PackageJson } from \"type-fest\";\n\ninterface AppExport {\n [key: string]: any;\n app?: string | { app?: string };\n}\n\nexport const ALLOWED_EXTENSIONS = [\".js\", \".ts\", \".mjs\", \".cjs\"];\n\nexport const getAppWorkingDirectoryPath = (appFilePath: string): string | null => {\n let lastParsedPath = parse(appFilePath);\n\n // Once the following condition returns false it means we traversed the whole file system\n // eslint-disable-next-line no-loops/no-loops\n while (lastParsedPath.base && lastParsedPath.root !== lastParsedPath.dir) {\n const parentDirectionItems = readdirSync(lastParsedPath.dir);\n\n const packageJSON = parentDirectionItems.find((item) => item === \"package.json\");\n\n if (packageJSON) {\n return lastParsedPath.dir;\n }\n\n lastParsedPath = parse(lastParsedPath.dir);\n }\n\n return null;\n};\n\nexport const getFrameworkName = (directory: string): \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | null => {\n const packageJSONFilePath = `${directory}/package.json`;\n\n const { dependencies } = JSON.parse(readFileSync(packageJSONFilePath).toString()) as PackageJson;\n\n // eslint-disable-next-line @typescript-eslint/dot-notation\n if (dependencies?.[\"express\"]) {\n return \"express\";\n }\n\n // eslint-disable-next-line @typescript-eslint/dot-notation\n if (dependencies?.[\"koa\"] && (dependencies[\"@koa/router\"] || dependencies[\"koa-router\"])) {\n return \"koa\";\n }\n\n // eslint-disable-next-line @typescript-eslint/dot-notation\n if (dependencies?.[\"next\"]) {\n return \"next\";\n }\n\n if (dependencies?.[\"@hapi/hapi\"]) {\n return \"hapi\";\n }\n\n // eslint-disable-next-line @typescript-eslint/dot-notation\n if (dependencies?.[\"fastify\"]) {\n return \"fastify\";\n }\n\n return null;\n};\n\nexport const getApp = (appExport: AppExport, frameworkName: \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | null): AppExport | string | null => {\n const isExportEmpty = Object.keys(appExport).length === 0;\n\n if (isExportEmpty) {\n return null;\n }\n\n if (frameworkName === \"hapi\") {\n if (typeof (appExport.app as { app?: string }).app === \"string\") {\n return appExport.app as { app: string };\n }\n\n return appExport;\n }\n\n return appExport.app ?? appExport;\n};\n","import type { Server } from \"@hapi/hapi\";\nimport type { Express } from \"express\";\nimport type { FastifyInstance } from \"fastify\";\nimport type Koa from \"koa\";\n\nimport expressRoutes from \"./routes/express-routes\";\nimport fastifyRoutes from \"./routes/fastify-routes\";\nimport hapiRoutes from \"./routes/hapi-routes\";\nimport koaRoutes from \"./routes/koa-routes\";\nimport apiRouteFileParser from \"./routes/next/api-route-file-parser\";\nimport collectApiRouteFiles from \"./routes/next/collect-api-route-files\";\nimport type { Route } from \"./routes/types\";\n\nexport type FrameworkName = \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | \"unknown\";\nexport const getRoutes = async (\n appOrPath: Express | FastifyInstance | Koa | Server | string,\n frameworkName: FrameworkName,\n verbose: boolean,\n): Promise<Route[] | null> => {\n if (frameworkName === \"express\") {\n return expressRoutes(appOrPath as Express);\n }\n\n if (frameworkName === \"koa\") {\n return koaRoutes(appOrPath as Koa);\n }\n\n if (frameworkName === \"hapi\") {\n return hapiRoutes(appOrPath as Server);\n }\n\n if (frameworkName === \"fastify\") {\n return fastifyRoutes(appOrPath as FastifyInstance);\n }\n\n if (frameworkName === \"next\") {\n const apiRouteFiles = await collectApiRouteFiles(appOrPath as string);\n\n if (apiRouteFiles.length === 0) {\n throw new Error(`No API routes found, in \"${appOrPath}\".`);\n }\n\n return apiRouteFiles.flatMap((apiRouteFile) => apiRouteFileParser(apiRouteFile, appOrPath as string, verbose));\n }\n\n return null;\n};\n","import type { Route } from \"./types\";\n\nconst routesGroupBy = (list: Route[], keyGetter: (item: Route) => keyof Route): Map<string, Route[]> => {\n const map = new Map<string, Route[]>();\n\n list.forEach((item) => {\n const key = keyGetter(item);\n const collection = map.get(key);\n\n if (collection) {\n collection.push(item);\n } else {\n map.set(key, [item]);\n }\n });\n\n return map;\n};\n\nexport default routesGroupBy;\n","// eslint-disable-next-line import/no-extraneous-dependencies\nimport chalk from \"chalk\";\n\nimport type { Route } from \"./types\";\n\nconst renderRoute = (method: string, routePath: string): string => {\n const colorMap = {\n ANY: chalk.redBright,\n DELETE: chalk.redBright,\n GET: chalk.blue,\n HEAD: chalk.hex(\"#6C7280\"),\n OPTIONS: chalk.hex(\"#6C7280\"),\n PATCH: chalk.yellow,\n POST: chalk.yellow,\n PUT: chalk.yellow,\n };\n\n let methodText: string;\n\n if (method === \"GET|HEAD\") {\n methodText = `${chalk.blue(\"GET\")}${chalk.grey(\"|HEAD\")}`;\n } else {\n const coloredMethod = colorMap[method as keyof typeof colorMap](method);\n\n methodText = method === \"GET\" ? `${coloredMethod}${chalk.grey(\"|HEAD\")}` : coloredMethod;\n }\n\n const spacesCount = method === \"GET\" ? 6 : 14 - method.length;\n const spaces = Array.from({ length: spacesCount }).fill(\" \").join(\"\");\n\n const dotsCount = process.stdout.columns - 16 - routePath.length - 4;\n const dots = dotsCount > 0 ? Array.from({ length: dotsCount }).fill(\".\").join(\"\") : \"\";\n\n const routeText = routePath\n .split(\"/\")\n .map((segment) => {\n const isDynamicSegment = [\":\", \"[\"].includes(segment[0] ?? \"\");\n\n return isDynamicSegment ? chalk.yellowBright(segment) : segment;\n })\n .join(\"/\");\n\n return ` ${methodText}${spaces}${routeText}${chalk.grey(dots)}`;\n};\n\nconst routesRender = (routesMap: Route[], options: { methods?: string[] } = {}): (string | undefined)[] =>\n routesMap\n .map((route) => {\n if (Array.isArray(options.methods) && options.methods.includes(route.method)) {\n return;\n }\n\n if (route.method === \"GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS\") {\n // eslint-disable-next-line no-param-reassign\n route.method = \"ANY\";\n }\n\n // eslint-disable-next-line consistent-return\n return renderRoute(route.method, route.path.replace(\"/pages\", \"\"));\n })\n .filter(Boolean);\n\nexport default routesRender;\n"]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunk4ITG7UZN_js = require('../../../chunk-4ITG7UZN.js');
|
|
4
4
|
require('../../../chunk-3XT5P2HO.js');
|
|
5
5
|
var process = require('process');
|
|
6
6
|
|
|
7
|
-
var i=(o,t="list",r="List all available API routes; Supported frameworks are next, express, koa, hapi and fastify")=>{o.command(t).description(r).option("--framework <framework>","Framework to use, choose from next, express, koa, hapi and fastify").option("-p, --path [path]","...").option("--group [type]","Groups routes. Supported: path, tag").option("--include-path [path]","Includes only routes which contain a given path element. (comma-separated values)",[]).option("--exclude-path [path]","Excludes routes which contain a given path element. (comma-separated values)",[]).option("-v, --verbose","Verbose output.",!1).action(async e=>{try{await
|
|
7
|
+
var i=(o,t="list",r="List all available API routes; Supported frameworks are next, express, koa, hapi and fastify")=>{o.command(t).description(r).option("--framework <framework>","Framework to use, choose from next, express, koa, hapi and fastify").option("-p, --path [path]","...").option("--group [type]","Groups routes. Supported: path, tag").option("--include-path [path]","Includes only routes which contain a given path element. (comma-separated values)",[]).option("--exclude-path [path]","Excludes routes which contain a given path element. (comma-separated values)",[]).option("-v, --verbose","Verbose output.",!1).action(async e=>{try{await chunk4ITG7UZN_js.a(e.framework,e.path,{excludePaths:e.excludePaths??[],group:e.group,includePaths:e.includePath??[],verbose:e.verbose});}catch(s){console.log(),console.error(s),process.exit(1);}});},m=i;
|
|
8
8
|
|
|
9
9
|
exports.listCommand = m;
|
|
10
10
|
//# sourceMappingURL=out.js.map
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunk4ITG7UZN_js = require('../../chunk-4ITG7UZN.js');
|
|
4
4
|
require('../../chunk-3XT5P2HO.js');
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
|
|
8
8
|
Object.defineProperty(exports, 'listCommand', {
|
|
9
9
|
enumerable: true,
|
|
10
|
-
get: function () { return
|
|
10
|
+
get: function () { return chunk4ITG7UZN_js.a; }
|
|
11
11
|
});
|
|
12
12
|
//# sourceMappingURL=out.js.map
|
|
13
13
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@visulima/api-platform",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.22",
|
|
4
4
|
"description": "Visulima API platform is a set of tools to build and consume web APIs",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"anolilab",
|
|
@@ -141,8 +141,8 @@
|
|
|
141
141
|
"test:watch": "vitest"
|
|
142
142
|
},
|
|
143
143
|
"dependencies": {
|
|
144
|
-
"@visulima/connect": "3.0.
|
|
145
|
-
"@visulima/jsdoc-open-api": "2.0.
|
|
144
|
+
"@visulima/connect": "3.0.1",
|
|
145
|
+
"@visulima/jsdoc-open-api": "2.0.16",
|
|
146
146
|
"accepts": "^1.3.8",
|
|
147
147
|
"debug": "^4.3.4",
|
|
148
148
|
"http-errors": "^2.0.0",
|
|
@@ -175,15 +175,14 @@
|
|
|
175
175
|
"@types/koa": "^2.15.0",
|
|
176
176
|
"@types/koa__router": "^12.0.4",
|
|
177
177
|
"@types/lodash.merge": "^4.6.9",
|
|
178
|
-
"@types/lodash.set": "^4.3.9",
|
|
179
178
|
"@types/node": "18.18.14",
|
|
180
179
|
"@types/qs": "^6.9.12",
|
|
181
180
|
"@types/react": "^18.2.64",
|
|
182
181
|
"@types/react-dom": "^18.2.20",
|
|
183
182
|
"@types/swagger-ui-react": "^4.18.3",
|
|
184
183
|
"@types/webpack": "^5.28.5",
|
|
185
|
-
"@visulima/crud": "2.0.
|
|
186
|
-
"@visulima/
|
|
184
|
+
"@visulima/crud": "2.0.16",
|
|
185
|
+
"@visulima/fs": "1.0.0",
|
|
187
186
|
"@vitest/coverage-v8": "^1.3.1",
|
|
188
187
|
"@vitest/ui": "^1.3.1",
|
|
189
188
|
"chalk": "5.3.0",
|
|
@@ -240,7 +239,7 @@
|
|
|
240
239
|
"optionalDependencies": {
|
|
241
240
|
"@hapi/hapi": "^21.3.3",
|
|
242
241
|
"@koa/router": "^12.0.1",
|
|
243
|
-
"@visulima/crud": "2.0.
|
|
242
|
+
"@visulima/crud": "2.0.16",
|
|
244
243
|
"@visulima/readdir": "2.0.12",
|
|
245
244
|
"chalk": "5.3.0",
|
|
246
245
|
"commander": "^12.0.0",
|
package/dist/chunk-7VCBFZEZ.js
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
var child_process = require('child_process');
|
|
4
|
-
var fs = require('fs');
|
|
5
|
-
var path = require('path');
|
|
6
|
-
var d = require('process');
|
|
7
|
-
var f = require('chalk');
|
|
8
|
-
var jsdocOpenApi = require('@visulima/jsdoc-open-api');
|
|
9
|
-
var readdir = require('@visulima/readdir');
|
|
10
|
-
|
|
11
|
-
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
12
|
-
|
|
13
|
-
var d__default = /*#__PURE__*/_interopDefault(d);
|
|
14
|
-
var f__default = /*#__PURE__*/_interopDefault(f);
|
|
15
|
-
|
|
16
|
-
var z=(t,r)=>{if(r.length===0)throw new Error("must include at least one key to map");let e=t.toString();return r.forEach(o=>{e=o.optional?e.replace("(?:\\/([^\\/]+?))?\\",`/:${o.name}?`):e.replace("(?:([^\\/]+?))",`:${o.name}`);}),e.replace("/?(?=\\/|$)/i","").replace("/^","").replaceAll("\\","").replaceAll(/\/{2,}/gu,"/")},S=z;var Q=(t,r)=>{if(typeof t=="string")return t;if(t.fast_slash)return "";if(t.fast_star)return "*";let e="";r.length>0&&(e=S(t,r));let o=/^\/\^((?:\\[$()*+./?[\\\]^{|}]|[^$()*+./?[\\\]^{|}])*)\$\//u.exec(t.toString().replace("\\/?","").replace("(?=\\/|$)","$"));return Array.isArray(o)&&o.length>1?o[1].replaceAll(/\\(.)/gu,"$1").slice(1):e?e.slice(1):t.toString()},T=Q;var V=(t,r,e)=>{let o=t.route.stack.at(-1),a=r.map(i=>({in:"path",name:i.name,required:!i.optional})),s=t.route.stack.filter(i=>i.handle.metadata);if(s.length>1)throw new Error("Only one metadata middleware is allowed per route");let n=(e+t.route.path).replaceAll(/\/{2,}/gu,"/");return s.length===0?{method:o.method,path:n,pathParams:a}:{metadata:s[0].handle.metadata,method:o.method,path:n,pathParams:a}},k=(t,r,e,o)=>{o=[...o,...e.keys],e.name==="router"&&e.handle&&e.handle.stack.forEach(a=>{r=r||"",k(t,`${r}/${T(e.regexp,e.keys)}`,a,o);}),!(!e.route||e.route.stack.length===0)&&t.push(V(e,o,r));},Z=t=>{let r=t._router||t.router,e=[];return r.stack.forEach(o=>{k(e,"",o,[]);}),e},D=Z;var ee=t=>{let r=[];return D(t).forEach(e=>{r.push({file:"unknown",method:e.method.toUpperCase(),path:e.path,tags:[]});}),r},$=ee;var j=t=>t.replaceAll(/ \(.*\)/gu,"").trim(),O=t=>t.trim().split(" ")[1].slice(1,-1),te=t=>{let e=t.printRoutes().replaceAll(/[─│└├]/gu," ").trimEnd().split(`
|
|
17
|
-
`),o=e.reduce((s,n,i)=>{let p=j(n);if(j(e[i-1]??"")===p){let Y=s.filter(P=>P.index<i&&P.segment===p),{methods:A}=Y.at(-1);return A!==null&&A.push(O(n)),s}let l=n.replaceAll(/ \(.*\)/gu,"").match(/ /gu);if(l===null)throw new Error("Invalid spaces");let m=l.length/4,h=n.includes("("),E=h?[O(n)]:null;return s.push({depth:m,index:i,isRoute:h,methods:E,segment:p}),s},[]),a=[];return o.filter(s=>s.isRoute).forEach(s=>{let i=[...o.filter(p=>p.index<s.index&&p.depth<s.depth).filter((p,c,l)=>!l.find(m=>m.depth===p.depth&&m.index>p.index)).map(p=>p.segment),s.segment].join("");if(s.methods===null)throw new Error("Invalid methods");s.methods.forEach(p=>{a.push({file:"unknown",method:p.toUpperCase(),path:i,tags:[]});});}),a},v=te;var re=t=>{let e=t._core.router.routes,o=[];return [...e.keys()].forEach(a=>{e.get(a).routes.forEach(s=>{o.push({file:"unknown",method:s.route.method.toUpperCase(),path:s.path,tags:[]});});}),o},F=re;var oe=t=>{let r=[];return t.middleware.filter(e=>e.router).flatMap(e=>e.router.stack).forEach(e=>{r.push({file:"unknown",method:e.methods.join("|").toUpperCase(),path:e.path,tags:[]});}),r},b=oe;var L=/\.(js|ts|mjs|cjs)$/u,ie=(t,r,e=!1)=>{let o=[],a=jsdocOpenApi.parseFile(t,jsdocOpenApi.jsDocumentCommentsToOpenApi,e);o=[...o,...a.map(i=>i.spec)];let s=jsdocOpenApi.parseFile(t,jsdocOpenApi.swaggerJsDocumentCommentsToOpenApi,e);o=[...o,...s.map(i=>i.spec)];let n=[];return o.length===0?(fs.readFileSync(t,"utf8").split(/\r?\n/u).forEach(p=>{let c=/[=aces|]+\s["'|](GET|POST|PUT|PATCH|HEAD|DELETE|OPTIONS)["'|]/u.exec(p);if(c){let[,l]=c;l==="GET"&&(l="GET|HEAD"),n.push({file:t.replace(`${d__default.default.cwd()}${d__default.default.platform==="win32"?"\\":"/"}`,""),method:l,path:t.replace(r,"").replace(L,"").replaceAll("\\","/"),tags:[]});}}),n.length===0&&n.push({file:t.replace(`${d__default.default.cwd()}${d__default.default.platform==="win32"?"\\":"/"}`,""),method:"GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS",path:t.replace(r,"").replace(L,"").replaceAll("\\","/"),tags:[]}),n):(o.forEach(i=>{Object.entries(i?.paths??{}).forEach(([c,l])=>{Object.entries(l).forEach(([h,E])=>{n.push({file:t.replace(`${d__default.default.cwd()}${d__default.default.platform==="win32"?"\\":"/"}`,""),method:h.toUpperCase(),path:c.replaceAll("\\","/"),tags:E.tags});});});}),n)},N=ie;var y=[".js",".ts",".mjs",".cjs"],I=t=>{let r=path.parse(t);for(;r.base&&r.root!==r.dir;){if(fs.readdirSync(r.dir).find(a=>a==="package.json"))return r.dir;r=path.parse(r.dir);}return null},H=t=>{let r=`${t}/package.json`,{dependencies:e}=JSON.parse(fs.readFileSync(r).toString());return e?.express?"express":e?.koa&&(e["@koa/router"]||e["koa-router"])?"koa":e?.next?"next":e?.["@hapi/hapi"]?"hapi":e?.fastify?"fastify":null},K=(t,r)=>Object.keys(t).length===0?null:r==="hapi"?typeof t.app.app=="string"?t.app:t:t.app??t;var J=t=>{try{return fs.statSync(t).isDirectory()}catch{return !1}},fe=async(t="",r=!1)=>{let e=path.join(t,"pages/api");return !J(e)&&(e=path.join(t,"src/pages/api"),!J(e))?[]:readdir.collect(e,{extensions:y,includeDirs:!1,minimatchOptions:{match:{debug:r,matchBase:!0},skip:{debug:r,matchBase:!0}}})},_=fe;var x=async(t,r,e)=>{if(r==="express")return $(t);if(r==="koa")return b(t);if(r==="hapi")return F(t);if(r==="fastify")return v(t);if(r==="next"){let o=await _(t,e);if(o.length===0)throw new Error(`No API routes found, in "${t}".`);return o.flatMap(a=>N(a,t,e))}return null};var me=(t,r)=>{let e=new Map;return t.forEach(o=>{let a=r(o),s=e.get(a);s?s.push(o):e.set(a,[o]);}),e},B=me;var he=(t,r)=>{let e={ANY:f__default.default.redBright,DELETE:f__default.default.redBright,GET:f__default.default.blue,HEAD:f__default.default.hex("#6C7280"),OPTIONS:f__default.default.hex("#6C7280"),PATCH:f__default.default.yellow,POST:f__default.default.yellow,PUT:f__default.default.yellow},o;if(t==="GET|HEAD")o=`${f__default.default.blue("GET")}${f__default.default.grey("|HEAD")}`;else {let c=e[t](t);o=t==="GET"?`${c}${f__default.default.grey("|HEAD")}`:c;}let a=t==="GET"?6:14-t.length,s=Array.from({length:a}).fill(" ").join(""),n=process.stdout.columns-16-r.length-4,i=n>0?Array.from({length:n}).fill(".").join(""):"",p=r.split("/").map(c=>[":","["].includes(c[0]??"")?f__default.default.yellowBright(c):c).join("/");return ` ${o}${s}${p}${f__default.default.grey(i)}`},de=(t,r={})=>t.map(e=>{if(!(Array.isArray(r.methods)&&r.methods.includes(e.method)))return e.method==="GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS"&&(e.method="ANY"),he(e.method,e.path.replace("/pages",""))}).filter(Boolean),R=de;var Ee=async(t,r,e={})=>{let o=path.join(d__default.default.cwd(),r);if(!fs.existsSync(o))throw new Error("No such file, invalid path provided.");let a=I(o);if(!a)throw new Error("Please initialize local package.json.");if(t===void 0){let n=H(a);if(!n)throw new Error("Couldn't detect supported back-end framework.");t=n;}let s=null;if(t==="next")s=await x(o,"next",e.verbose??!1);else {if(!fs.statSync(o).isFile())throw new Error(`${o} is directory, but file expected.`);if(!y.includes(path.extname(o)))throw new Error("Please specify application .ts/.js/.mjs/.cjs file.");let n=`${a}/.env`;fs.existsSync(n)&&(await import(`${a}/node_modules/dotenv/lib/main.js`)).config({path:n});let i=path.extname(o)===".ts",p=path.join(a,"node_modules/.bin/tsc");if(i&&!fs.existsSync(p))throw new Error(`Please install typescript in ${a}`);try{if(i)try{child_process.execSync(`${p} --outDir framework-list >&2`,{cwd:a});}catch(m){console.log(`TSC compilation failed. Please resolve issues in your project.
|
|
18
|
-
`),console.log(m),fs.rmSync(path.join(a,"framework-list"),{recursive:!0});}let c=i?path.join(a,"framework-list",o.replace(a,"").replace(".ts",".js")):o,{default:l}=await import(c);s=await x(["AsyncFunction","Function"].includes(l.constructor.name)?await l():K(l,t),t,e.verbose??!1);}finally{i&&fs.rmSync(path.join(a,"framework-list"),{recursive:!0});}}if(s===null)throw new Error(`Framework "${t}" is not supported.`);if(Array.isArray(e.includePaths)&&e.includePaths.length>0&&(s=e.includePaths.flatMap(n=>s.filter(i=>i.path.startsWith(n)))),Array.isArray(e.excludePaths)&&e.excludePaths.length>0&&(s=e.excludePaths.flatMap(n=>s.filter(i=>!i.path.startsWith(n)))),typeof e.group=="string"&&e.group!==""){console.log();let n=B(s,p=>e.group==="path"?p.path.replace("/pages","").split("/")[1]:p.tags[0]??"unsorted"),i=0;n.forEach((p,c)=>{i>0&&console.log();let l=(d__default.default.stdout.columns-16-c.length)/2,m=l>0?Array.from({length:l}).fill(" ").join(""):"";console.log(m+f__default.default.bold.underline(c)),R(p,e).forEach(h=>{console.log(h);}),i+=1;});}else console.log(),R(s,e).forEach(n=>{console.log(n);});console.log(`
|
|
19
|
-
Listed ${f__default.default.greenBright(String(s.length))} HTTP ${s.length===1?"route":"routes"}.
|
|
20
|
-
`);},xt=Ee;
|
|
21
|
-
|
|
22
|
-
exports.a = xt;
|
|
23
|
-
//# sourceMappingURL=out.js.map
|
|
24
|
-
//# sourceMappingURL=chunk-7VCBFZEZ.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/framework/cli/command/list/list-command.ts","../src/framework/cli/command/list/routes/express/map-keys-to-path.ts","../src/framework/cli/command/list/routes/express/path-regex-parser.ts","../src/framework/cli/command/list/routes/express/express-path-parser.ts","../src/framework/cli/command/list/routes/express-routes.ts","../src/framework/cli/command/list/routes/fastify-routes.ts","../src/framework/cli/command/list/routes/hapi-routes.ts","../src/framework/cli/command/list/routes/koa-routes.ts","../src/framework/cli/command/list/routes/next/api-route-file-parser.ts","../src/framework/cli/command/list/routes/next/collect-api-route-files.ts","../src/framework/cli/command/list/utils.ts","../src/framework/cli/command/list/get-routes.ts","../src/framework/cli/command/list/routes/routes-group-by.ts","../src/framework/cli/command/list/routes/routes-render.ts"],"names":["execSync","existsSync","rmSync","statSync","extname","join","process","chalk","mapKeysToPath","layerRegexPath","keys","convertedSubPath","key","map_keys_to_path_default","pathRegexParser","mappedPath","match","path_regex_parser_default","parseRouteLayer","layer","basePath","lastRequestHandler","pathParameters","filtered","element","path","traverse","routes","l","expressPathParser","app","router","express_path_parser_default","expressRoutes","route","express_routes_default","getSegment","line","getMethod","fastifyRoutes","lines","segments","allSegments","index","segment","entries","item","methods","spaces","depth","isRoute","seg","_index","previousArray","r","method","fastify_routes_default","hapiRoutes","coreRoutes","hapi_routes_default","koaRoutes","middlewareFunction","koa_routes_default","readFileSync","jsDocumentCommentsToOpenApi","parseFile","swaggerJsDocumentCommentsToOpenApi","extensionRegex","apiRouteFileParser","apiRouteFile","cwdPath","verbose","specs","parsedJsDocumentFile","parsedSwaggerJsDocumentFile","spec","pathSpec","methodSpec","api_route_file_parser_default","collect","readdirSync","parse","ALLOWED_EXTENSIONS","getAppWorkingDirectoryPath","appFilePath","lastParsedPath","getFrameworkName","directory","packageJSONFilePath","dependencies","getApp","appExport","frameworkName","isDirectory","collectApiRouteFiles","apiFolderPath","collect_api_route_files_default","getRoutes","appOrPath","apiRouteFiles","routesGroupBy","list","keyGetter","map","collection","routes_group_by_default","renderRoute","routePath","colorMap","methodText","coloredMethod","spacesCount","dotsCount","dots","routeText","routesRender","routesMap","options","routes_render_default","listCommand","framework","frameworkPath","appWorkingDirectoryPath","environmentFilePath","isTypeScriptApp","tscPath","error","appJsFilePath","defaultExport","ipath","epath","groupedMap","counter","groupedRoutes","renderedRoute","list_command_default"],"mappings":"AAAA,OAAS,YAAAA,OAAgB,gBACzB,OAAS,cAAAC,EAAY,UAAAC,EAAQ,YAAAC,OAAgB,KAC7C,OAAS,WAAAC,EAAS,QAAAC,MAAY,OAC9B,OAAOC,MAAa,UAGpB,OAAOC,MAAW,QCIlB,IAAMC,EAAgB,CAACC,EAA8BC,IAAwB,CACzE,GAAIA,EAAK,SAAW,EAChB,MAAM,IAAI,MAAM,sCAAsC,EAG1D,IAAIC,EAAmBF,EAAe,SAAS,EAE/C,OAAAC,EAAK,QAASE,GAAQ,CAClBD,EAAmBC,EAAI,SACjBD,EAAiB,QAAQ,uBAAwB,KAAKC,EAAI,IAAI,GAAG,EACjED,EAAiB,QAAQ,iBAAkB,IAAIC,EAAI,IAAI,EAAE,CACnE,CAAC,EAEMD,EACF,QAAQ,gBAAiB,EAAE,EAC3B,QAAQ,KAAM,EAAE,EAChB,WAAW,KAAM,EAAE,EACnB,WAAW,WAAY,GAAG,CACnC,EAEOE,EAAQL,ECnBf,IAAMM,EAAkB,CAACL,EAAuCC,IAAwB,CACpF,GAAI,OAAOD,GAAmB,SAC1B,OAAOA,EAGX,GAAIA,EAAe,WACf,MAAO,GAGX,GAAIA,EAAe,UACf,MAAO,IAGX,IAAIM,EAAa,GAEbL,EAAK,OAAS,IACdK,EAAaF,EAAcJ,EAAgBC,CAAI,GAGnD,IAAMM,EAAQ,8DAA8D,KACxEP,EAAe,SAAS,EAAE,QAAQ,OAAQ,EAAE,EAAE,QAAQ,YAAa,GAAG,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,IAAI;AAAA,WAAc/H,EAAM,YAAY,OAAOoB,EAAO,MAAM,CAAC,CAAC,SAASA,EAAO,SAAW,EAAI,QAAU,QAAQ;AAAA,CAAK,CAC5H,EAEO4G,GAAQhB","sourcesContent":["import { execSync } from \"node:child_process\";\nimport { existsSync, rmSync, statSync } from \"node:fs\";\nimport { extname, join } from \"node:path\";\nimport process from \"node:process\";\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport chalk from \"chalk\";\n\nimport { getRoutes } from \"./get-routes\";\nimport routesGroupBy from \"./routes/routes-group-by\";\nimport routesRender from \"./routes/routes-render\";\nimport type { Route } from \"./routes/types\";\nimport { ALLOWED_EXTENSIONS, getApp, getAppWorkingDirectoryPath, getFrameworkName } from \"./utils\";\n\ninterface RenderOptions {\n excludePaths: string[];\n group: string;\n includePaths: string[];\n methods: string[];\n verbose: boolean;\n}\n\nconst listCommand = async (\n framework: \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | undefined,\n path: string,\n options: Partial<RenderOptions> = {},\n // eslint-disable-next-line sonarjs/cognitive-complexity\n): Promise<void> => {\n const frameworkPath = join(process.cwd(), path);\n\n if (!existsSync(frameworkPath)) {\n throw new Error(\"No such file, invalid path provided.\");\n }\n\n const appWorkingDirectoryPath = getAppWorkingDirectoryPath(frameworkPath);\n\n if (!appWorkingDirectoryPath) {\n throw new Error(\"Please initialize local package.json.\");\n }\n\n if (framework === undefined) {\n const frameworkName = getFrameworkName(appWorkingDirectoryPath);\n\n if (!frameworkName) {\n throw new Error(\"Couldn't detect supported back-end framework.\");\n }\n\n // eslint-disable-next-line no-param-reassign\n framework = frameworkName;\n }\n\n let routes: Route[] | null = null;\n\n if (framework === \"next\") {\n routes = await getRoutes(frameworkPath, \"next\", options.verbose ?? false);\n } else {\n if (!statSync(frameworkPath).isFile()) {\n throw new Error(`${frameworkPath} is directory, but file expected.`);\n }\n\n if (!ALLOWED_EXTENSIONS.includes(extname(frameworkPath))) {\n throw new Error(\"Please specify application .ts/.js/.mjs/.cjs file.\");\n }\n\n const environmentFilePath = `${appWorkingDirectoryPath}/.env`;\n\n if (existsSync(environmentFilePath)) {\n // Loads environment vars in the current process so application\n // that depends on them can be loaded properly below\n const dotEnvironmentFilePath = `${appWorkingDirectoryPath}/node_modules/dotenv/lib/main.js`;\n const dotenv = await import(dotEnvironmentFilePath);\n\n dotenv.config({ path: environmentFilePath });\n }\n\n const isTypeScriptApp = extname(frameworkPath) === \".ts\";\n const tscPath = join(appWorkingDirectoryPath, \"node_modules/.bin/tsc\");\n\n if (isTypeScriptApp && !existsSync(tscPath)) {\n throw new Error(`Please install typescript in ${appWorkingDirectoryPath}`);\n }\n\n try {\n if (isTypeScriptApp) {\n // || rm -r ./framework-list removes framework-list directory in case tsc fails\n\n try {\n execSync(`${tscPath} --outDir framework-list >&2`, { cwd: appWorkingDirectoryPath });\n } catch (error: any) {\n // eslint-disable-next-line no-console\n console.log(\"TSC compilation failed. Please resolve issues in your project.\\n\");\n // eslint-disable-next-line no-console\n console.log(error);\n\n rmSync(join(appWorkingDirectoryPath, \"framework-list\"), { recursive: true });\n }\n }\n\n const appJsFilePath = isTypeScriptApp\n ? join(appWorkingDirectoryPath, \"framework-list\", frameworkPath.replace(appWorkingDirectoryPath, \"\").replace(\".ts\", \".js\"))\n : frameworkPath;\n\n const { default: defaultExport } = await import(appJsFilePath);\n\n routes = await getRoutes(\n [\"AsyncFunction\", \"Function\"].includes(defaultExport.constructor.name as string) ? await defaultExport() : getApp(defaultExport, framework),\n framework,\n options.verbose ?? false,\n );\n } finally {\n if (isTypeScriptApp) {\n rmSync(join(appWorkingDirectoryPath, \"framework-list\"), { recursive: true });\n }\n }\n }\n\n if (routes === null) {\n throw new Error(`Framework \"${framework}\" is not supported.`);\n }\n\n if (Array.isArray(options.includePaths) && options.includePaths.length > 0) {\n routes = options.includePaths.flatMap((ipath) => (routes as Route[]).filter((route) => route.path.startsWith(ipath)));\n }\n\n if (Array.isArray(options.excludePaths) && options.excludePaths.length > 0) {\n routes = options.excludePaths.flatMap((epath) => (routes as Route[]).filter((route) => !route.path.startsWith(epath)));\n }\n\n if (typeof options.group === \"string\" && options.group !== \"\") {\n // eslint-disable-next-line no-console\n console.log();\n\n const groupedMap = routesGroupBy(routes, (route) => {\n if (options.group === \"path\") {\n return route.path.replace(\"/pages\", \"\").split(\"/\")[1];\n }\n\n return route.tags[0] ?? \"unsorted\";\n });\n\n let counter = 0;\n\n groupedMap.forEach((groupedRoutes, key) => {\n if (counter > 0) {\n // eslint-disable-next-line no-console\n console.log();\n }\n\n const dotsCount = (process.stdout.columns - 16 - key.length) / 2;\n const dots = dotsCount > 0 ? Array.from({ length: dotsCount }).fill(\" \").join(\"\") : \"\";\n\n // eslint-disable-next-line no-console\n console.log(dots + chalk.bold.underline(key));\n\n routesRender(groupedRoutes, options).forEach((renderedRoute) => {\n // eslint-disable-next-line no-console\n console.log(renderedRoute);\n });\n\n counter += 1;\n });\n } else {\n // eslint-disable-next-line no-console\n console.log();\n\n routesRender(routes, options).forEach((renderedRoute) => {\n // eslint-disable-next-line no-console\n console.log(renderedRoute);\n });\n }\n\n // eslint-disable-next-line no-console\n console.log(`\\n Listed ${chalk.greenBright(String(routes.length))} HTTP ${routes.length === 1 ? \"route\" : \"routes\"}.\\n`);\n};\n\nexport default listCommand;\n","import type { ExpressRegex, Key } from \"./types\";\n\n/**\n * Map's the keys/path variables to the regex inside a given path\n *\n * @param layerRegexPath The regex for a router with path parameters\n * @param keys The keys that represent the path parameters\n *\n * @returns The regex for a path variable converted to original string on the express route\n */\nconst mapKeysToPath = (layerRegexPath: ExpressRegex, keys: Key[]): string => {\n if (keys.length === 0) {\n throw new Error(\"must include at least one key to map\");\n }\n\n let convertedSubPath = layerRegexPath.toString();\n\n keys.forEach((key) => {\n convertedSubPath = key.optional\n ? convertedSubPath.replace(\"(?:\\\\/([^\\\\/]+?))?\\\\\", `/:${key.name}?`)\n : convertedSubPath.replace(\"(?:([^\\\\/]+?))\", `:${key.name}`);\n });\n\n return convertedSubPath\n .replace(\"/?(?=\\\\/|$)/i\", \"\")\n .replace(\"/^\", \"\")\n .replaceAll(\"\\\\\", \"\")\n .replaceAll(/\\/{2,}/gu, \"/\");\n};\n\nexport default mapKeysToPath;\n","import mapKeysToPath from \"./map-keys-to-path\";\nimport type { ExpressRegex, Key } from \"./types\";\n\n/** Parses an express layer's regex and converts it to the original format seen in code.\n *\n * @param layerRegexPath The layer's regex pattern\n * @param keys The keys that represent the layer's path parameters\n * @returns The path string for that layer\n * Code inspired and modify from:\n * https://github.com/expressjs/express/issues/3308#issuecomment-300957572\n */\nconst pathRegexParser = (layerRegexPath: ExpressRegex | string, keys: Key[]): string => {\n if (typeof layerRegexPath === \"string\") {\n return layerRegexPath;\n }\n\n if (layerRegexPath.fast_slash) {\n return \"\";\n }\n\n if (layerRegexPath.fast_star) {\n return \"*\";\n }\n\n let mappedPath = \"\";\n\n if (keys.length > 0) {\n mappedPath = mapKeysToPath(layerRegexPath, keys);\n }\n\n const match = /^\\/\\^((?:\\\\[$()*+./?[\\\\\\]^{|}]|[^$()*+./?[\\\\\\]^{|}])*)\\$\\//u.exec(\n layerRegexPath.toString().replace(\"\\\\/?\", \"\").replace(\"(?=\\\\/|$)\", \"$\"),\n ) as string[];\n\n if (Array.isArray(match) && match.length > 1) {\n return (match[1] as string).replaceAll(/\\\\(.)/gu, \"$1\").slice(1);\n }\n\n if (mappedPath) {\n return mappedPath.slice(1);\n }\n\n return layerRegexPath.toString();\n};\n\nexport default pathRegexParser;\n","import type { Express, Router } from \"express\";\n\nimport pathRegexParser from \"./path-regex-parser\";\nimport type { Key, Layer, Parameter, Route, RouteMetaData } from \"./types\";\n\n/**\n * Parses a route object. Route objects are the leafs of an express router tree\n *\n * @param layer The layer of this route object - represents the stack of middleware and other metadata\n * @param keys The full set of keys for this particular route\n * @param basePath The base path as it was initial declared for this route\n * @returns A ExpressPath object holding the metadata for a given route\n */\nconst parseRouteLayer = (layer: Required<Layer>, keys: Key[], basePath: string): RouteMetaData => {\n const lastRequestHandler = layer.route.stack.at(-1) as Layer;\n const pathParameters: Parameter[] = keys.map((key) => {\n return { in: \"path\", name: key.name, required: !key.optional };\n });\n\n const filtered = layer.route.stack.filter((element) => (element.handle as Route).metadata);\n\n if (filtered.length > 1) {\n throw new Error(\"Only one metadata middleware is allowed per route\");\n }\n\n const path = (basePath + layer.route.path).replaceAll(/\\/{2,}/gu, \"/\");\n\n if (filtered.length === 0) {\n return { method: lastRequestHandler.method, path, pathParams: pathParameters };\n }\n\n return {\n metadata: ((filtered[0] as Layer).handle as Route).metadata,\n method: lastRequestHandler.method,\n path,\n pathParams: pathParameters,\n };\n};\n\n/**\n * Recursive traversal method for the express router and middleware tree.\n *\n * @param routes The array of routes to add to\n * @param path The current path segment that we have traversed so far\n * @param layer The current 'layer' of the router tree\n * @param keys The keys for the parameter's in the current path branch of the traversal\n * @returns void - base case saves result to internal object\n */\nconst traverse = (routes: RouteMetaData[], path: string, layer: Layer, keys: Key[]): void => {\n // eslint-disable-next-line no-param-reassign\n keys = [...keys, ...layer.keys];\n\n if (layer.name === \"router\" && layer.handle) {\n layer.handle.stack.forEach((l: Layer) => {\n // eslint-disable-next-line no-param-reassign\n path = path || \"\";\n\n traverse(routes, `${path}/${pathRegexParser(layer.regexp, layer.keys)}`, l, keys);\n });\n }\n\n if (!layer.route || layer.route.stack.length === 0) {\n return;\n }\n\n routes.push(parseRouteLayer(layer as Required<Layer>, keys, path));\n};\n\n// @TODO use this to parse the express swagger\n\n/**\n * Parses an Express app and generates list of routes with metadata.\n *\n * Can Parse:\n * - Nested Routers and Complex Express Projects\n * - Optional parameters e.g. /:name?\n * - Complex Matching routes e.g. /ma*tch, /ex(ab)?mple\n * - Regex routes e.g. /\\/abc|\\/xyz/\n * - Array of paths e.g. app.get(['/abc', '/xyz']) -> /abc,xyz/\n *\n * @param app The Express app reference. Must be used after all routes have been attached\n *\n * @returns List of routes for this express app with meta-data that has been picked up\n */\nconst expressPathParser = (app: Express): RouteMetaData[] => {\n // eslint-disable-next-line no-underscore-dangle\n const router: Router = app._router || app.router;\n const routes: RouteMetaData[] = [];\n\n router.stack.forEach((layer: Layer) => {\n traverse(routes, \"\", layer, []);\n });\n\n return routes;\n};\n\nexport default expressPathParser;\n","import type { Express } from \"express\";\n\nimport expressPathParser from \"./express/express-path-parser\";\nimport type { RouteMetaData } from \"./express/types\";\nimport type { Route } from \"./types\";\n\nconst expressRoutes = (app: Express): Route[] => {\n const routes: Route[] = [];\n\n expressPathParser(app).forEach((route: RouteMetaData) => {\n routes.push({\n file: \"unknown\",\n method: route.method.toUpperCase(),\n path: route.path,\n tags: [],\n });\n });\n\n return routes;\n};\n\nexport default expressRoutes;\n","import type { FastifyInstance } from \"fastify\";\n\nimport type { Route } from \"./types\";\n\n// \"<spaces> activity (GET)\" -> \"activity\"\nconst getSegment = (line: string) => line.replaceAll(/ \\(.*\\)/gu, \"\").trim();\n\n// \"<spaces> activity (GET)\" -> \"GET\"\nconst getMethod = (line: string) => (line.trim().split(\" \")[1] as string).slice(1, -1);\n\ninterface Segment {\n depth: number;\n index: number;\n isRoute: boolean;\n methods: string[] | null;\n segment: string;\n}\n\nconst fastifyRoutes = (app: FastifyInstance): Route[] => {\n const printedRoutes = app\n .printRoutes()\n .replaceAll(/[─│└├]/gu, \" \")\n .trimEnd();\n\n const lines = printedRoutes.split(\"\\n\");\n\n // eslint-disable-next-line unicorn/no-array-reduce\n const segments = lines.reduce((allSegments: Segment[], line, index) => {\n const segment = getSegment(line);\n const previousSegment = getSegment(lines[index - 1] ?? \"\");\n\n if (previousSegment === segment) {\n const entries: Segment[] = allSegments.filter((item) => item.index < index && item.segment === segment);\n\n const { methods } = entries.at(-1) as Segment;\n\n if (methods !== null) {\n methods.push(getMethod(line));\n }\n\n return allSegments;\n }\n\n // spaces preceding segment / not counting single space between segment and (METHOD)\n const spaces = line.replaceAll(/ \\(.*\\)/gu, \"\").match(/ /gu);\n\n if (spaces === null) {\n throw new Error(\"Invalid spaces\");\n }\n\n const depth = spaces.length / 4;\n const isRoute = line.includes(\"(\");\n const methods = isRoute ? [getMethod(line)] : null;\n\n allSegments.push({\n depth,\n index,\n isRoute,\n methods,\n segment,\n });\n\n return allSegments;\n }, []);\n\n const routes: Route[] = [];\n\n segments\n .filter((item) => item.isRoute)\n .forEach((item) => {\n const ancestorSegments = segments\n .filter((seg) => seg.index < item.index && seg.depth < item.depth)\n // eslint-disable-next-line unicorn/prefer-array-some\n .filter((seg, _index, previousArray) => !previousArray.find((segment) => segment.depth === seg.depth && segment.index > seg.index));\n\n const route = [...ancestorSegments.map((r) => r.segment), item.segment].join(\"\");\n\n if (item.methods === null) {\n throw new Error(\"Invalid methods\");\n }\n\n item.methods.forEach((method: string) => {\n routes.push({\n file: \"unknown\",\n method: method.toUpperCase(),\n path: route,\n tags: [],\n });\n });\n });\n\n return routes;\n};\n\nexport default fastifyRoutes;\n","import type { Server } from \"@hapi/hapi\";\n\nimport type { Route } from \"./types\";\n\nconst hapiRoutes = (app: Server): Route[] => {\n // @ts-expect-error TS2339: Property '_core' does not exist on type 'Server'. Internal API.\n // eslint-disable-next-line no-underscore-dangle\n const core = app._core as any;\n const coreRoutes = core.router.routes;\n const routes: Route[] = [];\n\n [...coreRoutes.keys()].forEach((method: string) => {\n coreRoutes.get(method).routes.forEach((route: any) => {\n routes.push({\n file: \"unknown\",\n method: route.route.method.toUpperCase(),\n path: route.path,\n tags: [],\n });\n });\n });\n\n return routes;\n};\n\nexport default hapiRoutes;\n","import type Koa from \"koa\";\n\nimport type { Route } from \"./types\";\n\nconst koaRoutes = (app: Koa): Route[] => {\n const routes: Route[] = [];\n\n app.middleware\n .filter((middlewareFunction) => (middlewareFunction as any).router)\n\n .flatMap((middlewareFunction) => (middlewareFunction as any).router.stack)\n .forEach((route) => {\n routes.push({\n file: \"unknown\",\n method: route.methods.join(\"|\").toUpperCase(),\n path: route.path,\n tags: [],\n });\n });\n\n return routes;\n};\n\nexport default koaRoutes;\n","import { readFileSync } from \"node:fs\";\nimport process from \"node:process\";\n\nimport type { OpenApiObject } from \"@visulima/jsdoc-open-api\";\nimport { jsDocumentCommentsToOpenApi, parseFile, swaggerJsDocumentCommentsToOpenApi } from \"@visulima/jsdoc-open-api\";\n\nimport type { Route } from \"../types\";\n\n// eslint-disable-next-line regexp/no-unused-capturing-group\nconst extensionRegex = /\\.(js|ts|mjs|cjs)$/u;\n\n// eslint-disable-next-line sonarjs/cognitive-complexity\nconst apiRouteFileParser = (apiRouteFile: string, cwdPath: string, verbose = false): Route[] => {\n let specs: OpenApiObject[] = [];\n\n const parsedJsDocumentFile = parseFile(apiRouteFile, jsDocumentCommentsToOpenApi, verbose);\n\n specs = [...specs, ...parsedJsDocumentFile.map((item) => item.spec)];\n\n const parsedSwaggerJsDocumentFile = parseFile(apiRouteFile, swaggerJsDocumentCommentsToOpenApi, verbose);\n\n specs = [...specs, ...parsedSwaggerJsDocumentFile.map((item) => item.spec)];\n\n const routes: Route[] = [];\n\n if (specs.length === 0) {\n const apiRouteFileContent = readFileSync(apiRouteFile, \"utf8\");\n\n apiRouteFileContent.split(/\\r?\\n/u).forEach((line) => {\n const match = /[=aces|]+\\s[\"'|](GET|POST|PUT|PATCH|HEAD|DELETE|OPTIONS)[\"'|]/u.exec(line);\n\n if (match) {\n let [, method] = match;\n\n if (method === \"GET\") {\n method = \"GET|HEAD\";\n }\n\n routes.push({\n file: apiRouteFile.replace(`${process.cwd()}${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`, \"\"),\n method: method as string,\n path: apiRouteFile.replace(cwdPath, \"\").replace(extensionRegex, \"\").replaceAll(\"\\\\\", \"/\"),\n tags: [],\n });\n }\n });\n\n if (routes.length === 0) {\n routes.push({\n file: apiRouteFile.replace(`${process.cwd()}${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`, \"\"),\n method: \"GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS\",\n path: apiRouteFile.replace(cwdPath, \"\").replace(extensionRegex, \"\").replaceAll(\"\\\\\", \"/\"),\n tags: [],\n });\n }\n\n return routes;\n }\n\n specs.forEach((spec) => {\n const paths = Object.entries(spec?.paths ?? {});\n\n paths.forEach(([path, pathSpec]) => {\n const methods = Object.entries(pathSpec);\n\n methods.forEach(([method, methodSpec]) => {\n routes.push({\n file: apiRouteFile.replace(`${process.cwd()}${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`, \"\"),\n method: method.toUpperCase(),\n path: path.replaceAll(\"\\\\\", \"/\"),\n tags: methodSpec.tags,\n });\n });\n });\n });\n\n return routes;\n};\n\nexport default apiRouteFileParser;\n","import { statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { collect } from \"@visulima/readdir\";\n\nimport { ALLOWED_EXTENSIONS } from \"../../utils\";\n\nconst isDirectory = (path: string): boolean => {\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n};\n\nconst collectApiRouteFiles = async (path = \"\", verbose = false): Promise<string[]> => {\n let apiFolderPath = join(path, \"pages/api\");\n\n // src/pages will be ignored if pages is present in the root directory\n if (!isDirectory(apiFolderPath)) {\n apiFolderPath = join(path, \"src/pages/api\");\n\n if (!isDirectory(apiFolderPath)) {\n return [];\n }\n }\n\n return collect(apiFolderPath, {\n extensions: ALLOWED_EXTENSIONS,\n includeDirs: false,\n minimatchOptions: {\n match: {\n debug: verbose,\n matchBase: true,\n },\n skip: {\n debug: verbose,\n matchBase: true,\n },\n },\n });\n};\n\nexport default collectApiRouteFiles;\n","import { readdirSync, readFileSync } from \"node:fs\";\nimport { parse } from \"node:path\";\n\nimport type { PackageJson } from \"type-fest\";\n\ninterface AppExport {\n [key: string]: any;\n app?: string | { app?: string };\n}\n\nexport const ALLOWED_EXTENSIONS = [\".js\", \".ts\", \".mjs\", \".cjs\"];\n\nexport const getAppWorkingDirectoryPath = (appFilePath: string): string | null => {\n let lastParsedPath = parse(appFilePath);\n\n // Once the following condition returns false it means we traversed the whole file system\n // eslint-disable-next-line no-loops/no-loops\n while (lastParsedPath.base && lastParsedPath.root !== lastParsedPath.dir) {\n const parentDirectionItems = readdirSync(lastParsedPath.dir);\n\n const packageJSON = parentDirectionItems.find((item) => item === \"package.json\");\n\n if (packageJSON) {\n return lastParsedPath.dir;\n }\n\n lastParsedPath = parse(lastParsedPath.dir);\n }\n\n return null;\n};\n\nexport const getFrameworkName = (directory: string): \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | null => {\n const packageJSONFilePath = `${directory}/package.json`;\n\n const { dependencies } = JSON.parse(readFileSync(packageJSONFilePath).toString()) as PackageJson;\n\n // eslint-disable-next-line @typescript-eslint/dot-notation\n if (dependencies?.[\"express\"]) {\n return \"express\";\n }\n\n // eslint-disable-next-line @typescript-eslint/dot-notation\n if (dependencies?.[\"koa\"] && (dependencies[\"@koa/router\"] || dependencies[\"koa-router\"])) {\n return \"koa\";\n }\n\n // eslint-disable-next-line @typescript-eslint/dot-notation\n if (dependencies?.[\"next\"]) {\n return \"next\";\n }\n\n if (dependencies?.[\"@hapi/hapi\"]) {\n return \"hapi\";\n }\n\n // eslint-disable-next-line @typescript-eslint/dot-notation\n if (dependencies?.[\"fastify\"]) {\n return \"fastify\";\n }\n\n return null;\n};\n\nexport const getApp = (appExport: AppExport, frameworkName: \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | null): AppExport | string | null => {\n const isExportEmpty = Object.keys(appExport).length === 0;\n\n if (isExportEmpty) {\n return null;\n }\n\n if (frameworkName === \"hapi\") {\n if (typeof (appExport.app as { app?: string }).app === \"string\") {\n return appExport.app as { app: string };\n }\n\n return appExport;\n }\n\n return appExport.app ?? appExport;\n};\n","import type { Server } from \"@hapi/hapi\";\nimport type { Express } from \"express\";\nimport type { FastifyInstance } from \"fastify\";\nimport type Koa from \"koa\";\n\nimport expressRoutes from \"./routes/express-routes\";\nimport fastifyRoutes from \"./routes/fastify-routes\";\nimport hapiRoutes from \"./routes/hapi-routes\";\nimport koaRoutes from \"./routes/koa-routes\";\nimport apiRouteFileParser from \"./routes/next/api-route-file-parser\";\nimport collectApiRouteFiles from \"./routes/next/collect-api-route-files\";\nimport type { Route } from \"./routes/types\";\n\nexport type FrameworkName = \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | \"unknown\";\nexport const getRoutes = async (\n appOrPath: Express | FastifyInstance | Koa | Server | string,\n frameworkName: FrameworkName,\n verbose: boolean,\n): Promise<Route[] | null> => {\n if (frameworkName === \"express\") {\n return expressRoutes(appOrPath as Express);\n }\n\n if (frameworkName === \"koa\") {\n return koaRoutes(appOrPath as Koa);\n }\n\n if (frameworkName === \"hapi\") {\n return hapiRoutes(appOrPath as Server);\n }\n\n if (frameworkName === \"fastify\") {\n return fastifyRoutes(appOrPath as FastifyInstance);\n }\n\n if (frameworkName === \"next\") {\n const apiRouteFiles = await collectApiRouteFiles(appOrPath as string, verbose);\n\n if (apiRouteFiles.length === 0) {\n throw new Error(`No API routes found, in \"${appOrPath}\".`);\n }\n\n return apiRouteFiles.flatMap((apiRouteFile) => apiRouteFileParser(apiRouteFile, appOrPath as string, verbose));\n }\n\n return null;\n};\n","import type { Route } from \"./types\";\n\nconst routesGroupBy = (list: Route[], keyGetter: (item: Route) => keyof Route): Map<string, Route[]> => {\n const map = new Map<string, Route[]>();\n\n list.forEach((item) => {\n const key = keyGetter(item);\n const collection = map.get(key);\n\n if (collection) {\n collection.push(item);\n } else {\n map.set(key, [item]);\n }\n });\n\n return map;\n};\n\nexport default routesGroupBy;\n","// eslint-disable-next-line import/no-extraneous-dependencies\nimport chalk from \"chalk\";\n\nimport type { Route } from \"./types\";\n\nconst renderRoute = (method: string, routePath: string): string => {\n const colorMap = {\n ANY: chalk.redBright,\n DELETE: chalk.redBright,\n GET: chalk.blue,\n HEAD: chalk.hex(\"#6C7280\"),\n OPTIONS: chalk.hex(\"#6C7280\"),\n PATCH: chalk.yellow,\n POST: chalk.yellow,\n PUT: chalk.yellow,\n };\n\n let methodText: string;\n\n if (method === \"GET|HEAD\") {\n methodText = `${chalk.blue(\"GET\")}${chalk.grey(\"|HEAD\")}`;\n } else {\n const coloredMethod = colorMap[method as keyof typeof colorMap](method);\n\n methodText = method === \"GET\" ? `${coloredMethod}${chalk.grey(\"|HEAD\")}` : coloredMethod;\n }\n\n const spacesCount = method === \"GET\" ? 6 : 14 - method.length;\n const spaces = Array.from({ length: spacesCount }).fill(\" \").join(\"\");\n\n const dotsCount = process.stdout.columns - 16 - routePath.length - 4;\n const dots = dotsCount > 0 ? Array.from({ length: dotsCount }).fill(\".\").join(\"\") : \"\";\n\n const routeText = routePath\n .split(\"/\")\n .map((segment) => {\n const isDynamicSegment = [\":\", \"[\"].includes(segment[0] ?? \"\");\n\n return isDynamicSegment ? chalk.yellowBright(segment) : segment;\n })\n .join(\"/\");\n\n return ` ${methodText}${spaces}${routeText}${chalk.grey(dots)}`;\n};\n\nconst routesRender = (routesMap: Route[], options: { methods?: string[] } = {}): (string | undefined)[] =>\n routesMap\n .map((route) => {\n if (Array.isArray(options.methods) && options.methods.includes(route.method)) {\n return;\n }\n\n if (route.method === \"GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS\") {\n // eslint-disable-next-line no-param-reassign\n route.method = \"ANY\";\n }\n\n // eslint-disable-next-line consistent-return\n return renderRoute(route.method, route.path.replace(\"/pages\", \"\"));\n })\n .filter(Boolean);\n\nexport default routesRender;\n"]}
|
package/dist/chunk-FZUWQEM2.mjs
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { execSync } from 'node:child_process';
|
|
2
|
-
import { existsSync, statSync, rmSync, readdirSync, readFileSync } from 'node:fs';
|
|
3
|
-
import { join, extname, parse } from 'node:path';
|
|
4
|
-
import g from 'node:process';
|
|
5
|
-
import m from 'chalk';
|
|
6
|
-
import { parseFile, jsDocumentCommentsToOpenApi, swaggerJsDocumentCommentsToOpenApi } from '@visulima/jsdoc-open-api';
|
|
7
|
-
import { collect } from '@visulima/readdir';
|
|
8
|
-
|
|
9
|
-
var Q=(t,r)=>{if(r.length===0)throw new Error("must include at least one key to map");let e=t.toString();return r.forEach(o=>{e=o.optional?e.replace("(?:\\/([^\\/]+?))?\\",`/:${o.name}?`):e.replace("(?:([^\\/]+?))",`:${o.name}`);}),e.replace("/?(?=\\/|$)/i","").replace("/^","").replaceAll("\\","").replaceAll(/\/{2,}/gu,"/")},T=Q;var V=(t,r)=>{if(typeof t=="string")return t;if(t.fast_slash)return "";if(t.fast_star)return "*";let e="";r.length>0&&(e=T(t,r));let o=/^\/\^((?:\\[$()*+./?[\\\]^{|}]|[^$()*+./?[\\\]^{|}])*)\$\//u.exec(t.toString().replace("\\/?","").replace("(?=\\/|$)","$"));return Array.isArray(o)&&o.length>1?o[1].replaceAll(/\\(.)/gu,"$1").slice(1):e?e.slice(1):t.toString()},k=V;var Z=(t,r,e)=>{let o=t.route.stack.at(-1),a=r.map(i=>({in:"path",name:i.name,required:!i.optional})),s=t.route.stack.filter(i=>i.handle.metadata);if(s.length>1)throw new Error("Only one metadata middleware is allowed per route");let n=(e+t.route.path).replaceAll(/\/{2,}/gu,"/");return s.length===0?{method:o.method,path:n,pathParams:a}:{metadata:s[0].handle.metadata,method:o.method,path:n,pathParams:a}},D=(t,r,e,o)=>{o=[...o,...e.keys],e.name==="router"&&e.handle&&e.handle.stack.forEach(a=>{r=r||"",D(t,`${r}/${k(e.regexp,e.keys)}`,a,o);}),!(!e.route||e.route.stack.length===0)&&t.push(Z(e,o,r));},ee=t=>{let r=t._router||t.router,e=[];return r.stack.forEach(o=>{D(e,"",o,[]);}),e},$=ee;var te=t=>{let r=[];return $(t).forEach(e=>{r.push({file:"unknown",method:e.method.toUpperCase(),path:e.path,tags:[]});}),r},j=te;var O=t=>t.replaceAll(/ \(.*\)/gu,"").trim(),v=t=>t.trim().split(" ")[1].slice(1,-1),re=t=>{let e=t.printRoutes().replaceAll(/[─│└├]/gu," ").trimEnd().split(`
|
|
10
|
-
`),o=e.reduce((s,n,i)=>{let p=O(n);if(O(e[i-1]??"")===p){let z=s.filter(S=>S.index<i&&S.segment===p),{methods:P}=z.at(-1);return P!==null&&P.push(v(n)),s}let l=n.replaceAll(/ \(.*\)/gu,"").match(/ /gu);if(l===null)throw new Error("Invalid spaces");let h=l.length/4,d=n.includes("("),x=d?[v(n)]:null;return s.push({depth:h,index:i,isRoute:d,methods:x,segment:p}),s},[]),a=[];return o.filter(s=>s.isRoute).forEach(s=>{let i=[...o.filter(p=>p.index<s.index&&p.depth<s.depth).filter((p,c,l)=>!l.find(h=>h.depth===p.depth&&h.index>p.index)).map(p=>p.segment),s.segment].join("");if(s.methods===null)throw new Error("Invalid methods");s.methods.forEach(p=>{a.push({file:"unknown",method:p.toUpperCase(),path:i,tags:[]});});}),a},F=re;var oe=t=>{let e=t._core.router.routes,o=[];return [...e.keys()].forEach(a=>{e.get(a).routes.forEach(s=>{o.push({file:"unknown",method:s.route.method.toUpperCase(),path:s.path,tags:[]});});}),o},b=oe;var se=t=>{let r=[];return t.middleware.filter(e=>e.router).flatMap(e=>e.router.stack).forEach(e=>{r.push({file:"unknown",method:e.methods.join("|").toUpperCase(),path:e.path,tags:[]});}),r},C=se;var N=/\.(js|ts|mjs|cjs)$/u,pe=(t,r,e=!1)=>{let o=[],a=parseFile(t,jsDocumentCommentsToOpenApi,e);o=[...o,...a.map(i=>i.spec)];let s=parseFile(t,swaggerJsDocumentCommentsToOpenApi,e);o=[...o,...s.map(i=>i.spec)];let n=[];return o.length===0?(readFileSync(t,"utf8").split(/\r?\n/u).forEach(p=>{let c=/[=aces|]+\s["'|](GET|POST|PUT|PATCH|HEAD|DELETE|OPTIONS)["'|]/u.exec(p);if(c){let[,l]=c;l==="GET"&&(l="GET|HEAD"),n.push({file:t.replace(`${g.cwd()}${g.platform==="win32"?"\\":"/"}`,""),method:l,path:t.replace(r,"").replace(N,"").replaceAll("\\","/"),tags:[]});}}),n.length===0&&n.push({file:t.replace(`${g.cwd()}${g.platform==="win32"?"\\":"/"}`,""),method:"GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS",path:t.replace(r,"").replace(N,"").replaceAll("\\","/"),tags:[]}),n):(o.forEach(i=>{Object.entries(i?.paths??{}).forEach(([c,l])=>{Object.entries(l).forEach(([d,x])=>{n.push({file:t.replace(`${g.cwd()}${g.platform==="win32"?"\\":"/"}`,""),method:d.toUpperCase(),path:c.replaceAll("\\","/"),tags:x.tags});});});}),n)},M=pe;var E=[".js",".ts",".mjs",".cjs"],H=t=>{let r=parse(t);for(;r.base&&r.root!==r.dir;){if(readdirSync(r.dir).find(a=>a==="package.json"))return r.dir;r=parse(r.dir);}return null},K=t=>{let r=`${t}/package.json`,{dependencies:e}=JSON.parse(readFileSync(r).toString());return e?.express?"express":e?.koa&&(e["@koa/router"]||e["koa-router"])?"koa":e?.next?"next":e?.["@hapi/hapi"]?"hapi":e?.fastify?"fastify":null},G=(t,r)=>Object.keys(t).length===0?null:r==="hapi"?typeof t.app.app=="string"?t.app:t:t.app??t;var _=t=>{try{return statSync(t).isDirectory()}catch{return !1}},me=async(t="",r=!1)=>{let e=join(t,"pages/api");return !_(e)&&(e=join(t,"src/pages/api"),!_(e))?[]:collect(e,{extensions:E,includeDirs:!1,minimatchOptions:{match:{debug:r,matchBase:!0},skip:{debug:r,matchBase:!0}}})},B=me;var R=async(t,r,e)=>{if(r==="express")return j(t);if(r==="koa")return C(t);if(r==="hapi")return b(t);if(r==="fastify")return F(t);if(r==="next"){let o=await B(t,e);if(o.length===0)throw new Error(`No API routes found, in "${t}".`);return o.flatMap(a=>M(a,t,e))}return null};var he=(t,r)=>{let e=new Map;return t.forEach(o=>{let a=r(o),s=e.get(a);s?s.push(o):e.set(a,[o]);}),e},U=he;var de=(t,r)=>{let e={ANY:m.redBright,DELETE:m.redBright,GET:m.blue,HEAD:m.hex("#6C7280"),OPTIONS:m.hex("#6C7280"),PATCH:m.yellow,POST:m.yellow,PUT:m.yellow},o;if(t==="GET|HEAD")o=`${m.blue("GET")}${m.grey("|HEAD")}`;else {let c=e[t](t);o=t==="GET"?`${c}${m.grey("|HEAD")}`:c;}let a=t==="GET"?6:14-t.length,s=Array.from({length:a}).fill(" ").join(""),n=process.stdout.columns-16-r.length-4,i=n>0?Array.from({length:n}).fill(".").join(""):"",p=r.split("/").map(c=>[":","["].includes(c[0]??"")?m.yellowBright(c):c).join("/");return ` ${o}${s}${p}${m.grey(i)}`},ge=(t,r={})=>t.map(e=>{if(!(Array.isArray(r.methods)&&r.methods.includes(e.method)))return e.method==="GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS"&&(e.method="ANY"),de(e.method,e.path.replace("/pages",""))}).filter(Boolean),w=ge;var xe=async(t,r,e={})=>{let o=join(g.cwd(),r);if(!existsSync(o))throw new Error("No such file, invalid path provided.");let a=H(o);if(!a)throw new Error("Please initialize local package.json.");if(t===void 0){let n=K(a);if(!n)throw new Error("Couldn't detect supported back-end framework.");t=n;}let s=null;if(t==="next")s=await R(o,"next",e.verbose??!1);else {if(!statSync(o).isFile())throw new Error(`${o} is directory, but file expected.`);if(!E.includes(extname(o)))throw new Error("Please specify application .ts/.js/.mjs/.cjs file.");let n=`${a}/.env`;existsSync(n)&&(await import(`${a}/node_modules/dotenv/lib/main.js`)).config({path:n});let i=extname(o)===".ts",p=join(a,"node_modules/.bin/tsc");if(i&&!existsSync(p))throw new Error(`Please install typescript in ${a}`);try{if(i)try{execSync(`${p} --outDir framework-list >&2`,{cwd:a});}catch(h){console.log(`TSC compilation failed. Please resolve issues in your project.
|
|
11
|
-
`),console.log(h),rmSync(join(a,"framework-list"),{recursive:!0});}let c=i?join(a,"framework-list",o.replace(a,"").replace(".ts",".js")):o,{default:l}=await import(c);s=await R(["AsyncFunction","Function"].includes(l.constructor.name)?await l():G(l,t),t,e.verbose??!1);}finally{i&&rmSync(join(a,"framework-list"),{recursive:!0});}}if(s===null)throw new Error(`Framework "${t}" is not supported.`);if(Array.isArray(e.includePaths)&&e.includePaths.length>0&&(s=e.includePaths.flatMap(n=>s.filter(i=>i.path.startsWith(n)))),Array.isArray(e.excludePaths)&&e.excludePaths.length>0&&(s=e.excludePaths.flatMap(n=>s.filter(i=>!i.path.startsWith(n)))),typeof e.group=="string"&&e.group!==""){console.log();let n=U(s,p=>e.group==="path"?p.path.replace("/pages","").split("/")[1]:p.tags[0]??"unsorted"),i=0;n.forEach((p,c)=>{i>0&&console.log();let l=(g.stdout.columns-16-c.length)/2,h=l>0?Array.from({length:l}).fill(" ").join(""):"";console.log(h+m.bold.underline(c)),w(p,e).forEach(d=>{console.log(d);}),i+=1;});}else console.log(),w(s,e).forEach(n=>{console.log(n);});console.log(`
|
|
12
|
-
Listed ${m.greenBright(String(s.length))} HTTP ${s.length===1?"route":"routes"}.
|
|
13
|
-
`);},Rt=xe;
|
|
14
|
-
|
|
15
|
-
export { Rt as a };
|
|
16
|
-
//# sourceMappingURL=out.js.map
|
|
17
|
-
//# sourceMappingURL=chunk-FZUWQEM2.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/framework/cli/command/list/list-command.ts","../src/framework/cli/command/list/routes/express/map-keys-to-path.ts","../src/framework/cli/command/list/routes/express/path-regex-parser.ts","../src/framework/cli/command/list/routes/express/express-path-parser.ts","../src/framework/cli/command/list/routes/express-routes.ts","../src/framework/cli/command/list/routes/fastify-routes.ts","../src/framework/cli/command/list/routes/hapi-routes.ts","../src/framework/cli/command/list/routes/koa-routes.ts","../src/framework/cli/command/list/routes/next/api-route-file-parser.ts","../src/framework/cli/command/list/routes/next/collect-api-route-files.ts","../src/framework/cli/command/list/utils.ts","../src/framework/cli/command/list/get-routes.ts","../src/framework/cli/command/list/routes/routes-group-by.ts","../src/framework/cli/command/list/routes/routes-render.ts"],"names":["execSync","existsSync","rmSync","statSync","extname","join","process","chalk","mapKeysToPath","layerRegexPath","keys","convertedSubPath","key","map_keys_to_path_default","pathRegexParser","mappedPath","match","path_regex_parser_default","parseRouteLayer","layer","basePath","lastRequestHandler","pathParameters","filtered","element","path","traverse","routes","l","expressPathParser","app","router","express_path_parser_default","expressRoutes","route","express_routes_default","getSegment","line","getMethod","fastifyRoutes","lines","segments","allSegments","index","segment","entries","item","methods","spaces","depth","isRoute","seg","_index","previousArray","r","method","fastify_routes_default","hapiRoutes","coreRoutes","hapi_routes_default","koaRoutes","middlewareFunction","koa_routes_default","readFileSync","jsDocumentCommentsToOpenApi","parseFile","swaggerJsDocumentCommentsToOpenApi","extensionRegex","apiRouteFileParser","apiRouteFile","cwdPath","verbose","specs","parsedJsDocumentFile","parsedSwaggerJsDocumentFile","spec","pathSpec","methodSpec","api_route_file_parser_default","collect","readdirSync","parse","ALLOWED_EXTENSIONS","getAppWorkingDirectoryPath","appFilePath","lastParsedPath","getFrameworkName","directory","packageJSONFilePath","dependencies","getApp","appExport","frameworkName","isDirectory","collectApiRouteFiles","apiFolderPath","collect_api_route_files_default","getRoutes","appOrPath","apiRouteFiles","routesGroupBy","list","keyGetter","map","collection","routes_group_by_default","renderRoute","routePath","colorMap","methodText","coloredMethod","spacesCount","dotsCount","dots","routeText","routesRender","routesMap","options","routes_render_default","listCommand","framework","frameworkPath","appWorkingDirectoryPath","environmentFilePath","isTypeScriptApp","tscPath","error","appJsFilePath","defaultExport","ipath","epath","groupedMap","counter","groupedRoutes","renderedRoute","list_command_default"],"mappings":"AAAA,OAAS,YAAAA,OAAgB,qBACzB,OAAS,cAAAC,EAAY,UAAAC,EAAQ,YAAAC,OAAgB,UAC7C,OAAS,WAAAC,EAAS,QAAAC,MAAY,YAC9B,OAAOC,MAAa,eAGpB,OAAOC,MAAW,QCIlB,IAAMC,EAAgB,CAACC,EAA8BC,IAAwB,CACzE,GAAIA,EAAK,SAAW,EAChB,MAAM,IAAI,MAAM,sCAAsC,EAG1D,IAAIC,EAAmBF,EAAe,SAAS,EAE/C,OAAAC,EAAK,QAASE,GAAQ,CAClBD,EAAmBC,EAAI,SACjBD,EAAiB,QAAQ,uBAAwB,KAAKC,EAAI,IAAI,GAAG,EACjED,EAAiB,QAAQ,iBAAkB,IAA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Q,IAAI,EAGhB,IAAMpB,GAAa1G,EAAQ,OAAO,QAAU,GAAKM,EAAI,QAAU,EACzDqG,EAAOD,EAAY,EAAI,MAAM,KAAK,CAAE,OAAQA,CAAU,CAAC,EAAE,KAAK,GAAG,EAAE,KAAK,EAAE,EAAI,GAGpF,QAAQ,IAAIC,EAAO1G,EAAM,KAAK,UAAUK,CAAG,CAAC,EAE5C0G,EAAae,EAAehB,CAAO,EAAE,QAASiB,GAAkB,CAE5D,QAAQ,IAAIA,CAAa,CAC7B,CAAC,EAEDF,GAAW,CACf,CAAC,CACL,MAEI,QAAQ,IAAI,EAEZd,EAAa3F,EAAQ0F,CAAO,EAAE,QAASiB,GAAkB,CAErD,QAAQ,IAAIA,CAAa,CAC7B,CAAC,EAIL,QAAQ,IAAI;AAAA,WAAc/H,EAAM,YAAY,OAAOoB,EAAO,MAAM,CAAC,CAAC,SAASA,EAAO,SAAW,EAAI,QAAU,QAAQ;AAAA,CAAK,CAC5H,EAEO4G,GAAQhB","sourcesContent":["import { execSync } from \"node:child_process\";\nimport { existsSync, rmSync, statSync } from \"node:fs\";\nimport { extname, join } from \"node:path\";\nimport process from \"node:process\";\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport chalk from \"chalk\";\n\nimport { getRoutes } from \"./get-routes\";\nimport routesGroupBy from \"./routes/routes-group-by\";\nimport routesRender from \"./routes/routes-render\";\nimport type { Route } from \"./routes/types\";\nimport { ALLOWED_EXTENSIONS, getApp, getAppWorkingDirectoryPath, getFrameworkName } from \"./utils\";\n\ninterface RenderOptions {\n excludePaths: string[];\n group: string;\n includePaths: string[];\n methods: string[];\n verbose: boolean;\n}\n\nconst listCommand = async (\n framework: \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | undefined,\n path: string,\n options: Partial<RenderOptions> = {},\n // eslint-disable-next-line sonarjs/cognitive-complexity\n): Promise<void> => {\n const frameworkPath = join(process.cwd(), path);\n\n if (!existsSync(frameworkPath)) {\n throw new Error(\"No such file, invalid path provided.\");\n }\n\n const appWorkingDirectoryPath = getAppWorkingDirectoryPath(frameworkPath);\n\n if (!appWorkingDirectoryPath) {\n throw new Error(\"Please initialize local package.json.\");\n }\n\n if (framework === undefined) {\n const frameworkName = getFrameworkName(appWorkingDirectoryPath);\n\n if (!frameworkName) {\n throw new Error(\"Couldn't detect supported back-end framework.\");\n }\n\n // eslint-disable-next-line no-param-reassign\n framework = frameworkName;\n }\n\n let routes: Route[] | null = null;\n\n if (framework === \"next\") {\n routes = await getRoutes(frameworkPath, \"next\", options.verbose ?? false);\n } else {\n if (!statSync(frameworkPath).isFile()) {\n throw new Error(`${frameworkPath} is directory, but file expected.`);\n }\n\n if (!ALLOWED_EXTENSIONS.includes(extname(frameworkPath))) {\n throw new Error(\"Please specify application .ts/.js/.mjs/.cjs file.\");\n }\n\n const environmentFilePath = `${appWorkingDirectoryPath}/.env`;\n\n if (existsSync(environmentFilePath)) {\n // Loads environment vars in the current process so application\n // that depends on them can be loaded properly below\n const dotEnvironmentFilePath = `${appWorkingDirectoryPath}/node_modules/dotenv/lib/main.js`;\n const dotenv = await import(dotEnvironmentFilePath);\n\n dotenv.config({ path: environmentFilePath });\n }\n\n const isTypeScriptApp = extname(frameworkPath) === \".ts\";\n const tscPath = join(appWorkingDirectoryPath, \"node_modules/.bin/tsc\");\n\n if (isTypeScriptApp && !existsSync(tscPath)) {\n throw new Error(`Please install typescript in ${appWorkingDirectoryPath}`);\n }\n\n try {\n if (isTypeScriptApp) {\n // || rm -r ./framework-list removes framework-list directory in case tsc fails\n\n try {\n execSync(`${tscPath} --outDir framework-list >&2`, { cwd: appWorkingDirectoryPath });\n } catch (error: any) {\n // eslint-disable-next-line no-console\n console.log(\"TSC compilation failed. Please resolve issues in your project.\\n\");\n // eslint-disable-next-line no-console\n console.log(error);\n\n rmSync(join(appWorkingDirectoryPath, \"framework-list\"), { recursive: true });\n }\n }\n\n const appJsFilePath = isTypeScriptApp\n ? join(appWorkingDirectoryPath, \"framework-list\", frameworkPath.replace(appWorkingDirectoryPath, \"\").replace(\".ts\", \".js\"))\n : frameworkPath;\n\n const { default: defaultExport } = await import(appJsFilePath);\n\n routes = await getRoutes(\n [\"AsyncFunction\", \"Function\"].includes(defaultExport.constructor.name as string) ? await defaultExport() : getApp(defaultExport, framework),\n framework,\n options.verbose ?? false,\n );\n } finally {\n if (isTypeScriptApp) {\n rmSync(join(appWorkingDirectoryPath, \"framework-list\"), { recursive: true });\n }\n }\n }\n\n if (routes === null) {\n throw new Error(`Framework \"${framework}\" is not supported.`);\n }\n\n if (Array.isArray(options.includePaths) && options.includePaths.length > 0) {\n routes = options.includePaths.flatMap((ipath) => (routes as Route[]).filter((route) => route.path.startsWith(ipath)));\n }\n\n if (Array.isArray(options.excludePaths) && options.excludePaths.length > 0) {\n routes = options.excludePaths.flatMap((epath) => (routes as Route[]).filter((route) => !route.path.startsWith(epath)));\n }\n\n if (typeof options.group === \"string\" && options.group !== \"\") {\n // eslint-disable-next-line no-console\n console.log();\n\n const groupedMap = routesGroupBy(routes, (route) => {\n if (options.group === \"path\") {\n return route.path.replace(\"/pages\", \"\").split(\"/\")[1];\n }\n\n return route.tags[0] ?? \"unsorted\";\n });\n\n let counter = 0;\n\n groupedMap.forEach((groupedRoutes, key) => {\n if (counter > 0) {\n // eslint-disable-next-line no-console\n console.log();\n }\n\n const dotsCount = (process.stdout.columns - 16 - key.length) / 2;\n const dots = dotsCount > 0 ? Array.from({ length: dotsCount }).fill(\" \").join(\"\") : \"\";\n\n // eslint-disable-next-line no-console\n console.log(dots + chalk.bold.underline(key));\n\n routesRender(groupedRoutes, options).forEach((renderedRoute) => {\n // eslint-disable-next-line no-console\n console.log(renderedRoute);\n });\n\n counter += 1;\n });\n } else {\n // eslint-disable-next-line no-console\n console.log();\n\n routesRender(routes, options).forEach((renderedRoute) => {\n // eslint-disable-next-line no-console\n console.log(renderedRoute);\n });\n }\n\n // eslint-disable-next-line no-console\n console.log(`\\n Listed ${chalk.greenBright(String(routes.length))} HTTP ${routes.length === 1 ? \"route\" : \"routes\"}.\\n`);\n};\n\nexport default listCommand;\n","import type { ExpressRegex, Key } from \"./types\";\n\n/**\n * Map's the keys/path variables to the regex inside a given path\n *\n * @param layerRegexPath The regex for a router with path parameters\n * @param keys The keys that represent the path parameters\n *\n * @returns The regex for a path variable converted to original string on the express route\n */\nconst mapKeysToPath = (layerRegexPath: ExpressRegex, keys: Key[]): string => {\n if (keys.length === 0) {\n throw new Error(\"must include at least one key to map\");\n }\n\n let convertedSubPath = layerRegexPath.toString();\n\n keys.forEach((key) => {\n convertedSubPath = key.optional\n ? convertedSubPath.replace(\"(?:\\\\/([^\\\\/]+?))?\\\\\", `/:${key.name}?`)\n : convertedSubPath.replace(\"(?:([^\\\\/]+?))\", `:${key.name}`);\n });\n\n return convertedSubPath\n .replace(\"/?(?=\\\\/|$)/i\", \"\")\n .replace(\"/^\", \"\")\n .replaceAll(\"\\\\\", \"\")\n .replaceAll(/\\/{2,}/gu, \"/\");\n};\n\nexport default mapKeysToPath;\n","import mapKeysToPath from \"./map-keys-to-path\";\nimport type { ExpressRegex, Key } from \"./types\";\n\n/** Parses an express layer's regex and converts it to the original format seen in code.\n *\n * @param layerRegexPath The layer's regex pattern\n * @param keys The keys that represent the layer's path parameters\n * @returns The path string for that layer\n * Code inspired and modify from:\n * https://github.com/expressjs/express/issues/3308#issuecomment-300957572\n */\nconst pathRegexParser = (layerRegexPath: ExpressRegex | string, keys: Key[]): string => {\n if (typeof layerRegexPath === \"string\") {\n return layerRegexPath;\n }\n\n if (layerRegexPath.fast_slash) {\n return \"\";\n }\n\n if (layerRegexPath.fast_star) {\n return \"*\";\n }\n\n let mappedPath = \"\";\n\n if (keys.length > 0) {\n mappedPath = mapKeysToPath(layerRegexPath, keys);\n }\n\n const match = /^\\/\\^((?:\\\\[$()*+./?[\\\\\\]^{|}]|[^$()*+./?[\\\\\\]^{|}])*)\\$\\//u.exec(\n layerRegexPath.toString().replace(\"\\\\/?\", \"\").replace(\"(?=\\\\/|$)\", \"$\"),\n ) as string[];\n\n if (Array.isArray(match) && match.length > 1) {\n return (match[1] as string).replaceAll(/\\\\(.)/gu, \"$1\").slice(1);\n }\n\n if (mappedPath) {\n return mappedPath.slice(1);\n }\n\n return layerRegexPath.toString();\n};\n\nexport default pathRegexParser;\n","import type { Express, Router } from \"express\";\n\nimport pathRegexParser from \"./path-regex-parser\";\nimport type { Key, Layer, Parameter, Route, RouteMetaData } from \"./types\";\n\n/**\n * Parses a route object. Route objects are the leafs of an express router tree\n *\n * @param layer The layer of this route object - represents the stack of middleware and other metadata\n * @param keys The full set of keys for this particular route\n * @param basePath The base path as it was initial declared for this route\n * @returns A ExpressPath object holding the metadata for a given route\n */\nconst parseRouteLayer = (layer: Required<Layer>, keys: Key[], basePath: string): RouteMetaData => {\n const lastRequestHandler = layer.route.stack.at(-1) as Layer;\n const pathParameters: Parameter[] = keys.map((key) => {\n return { in: \"path\", name: key.name, required: !key.optional };\n });\n\n const filtered = layer.route.stack.filter((element) => (element.handle as Route).metadata);\n\n if (filtered.length > 1) {\n throw new Error(\"Only one metadata middleware is allowed per route\");\n }\n\n const path = (basePath + layer.route.path).replaceAll(/\\/{2,}/gu, \"/\");\n\n if (filtered.length === 0) {\n return { method: lastRequestHandler.method, path, pathParams: pathParameters };\n }\n\n return {\n metadata: ((filtered[0] as Layer).handle as Route).metadata,\n method: lastRequestHandler.method,\n path,\n pathParams: pathParameters,\n };\n};\n\n/**\n * Recursive traversal method for the express router and middleware tree.\n *\n * @param routes The array of routes to add to\n * @param path The current path segment that we have traversed so far\n * @param layer The current 'layer' of the router tree\n * @param keys The keys for the parameter's in the current path branch of the traversal\n * @returns void - base case saves result to internal object\n */\nconst traverse = (routes: RouteMetaData[], path: string, layer: Layer, keys: Key[]): void => {\n // eslint-disable-next-line no-param-reassign\n keys = [...keys, ...layer.keys];\n\n if (layer.name === \"router\" && layer.handle) {\n layer.handle.stack.forEach((l: Layer) => {\n // eslint-disable-next-line no-param-reassign\n path = path || \"\";\n\n traverse(routes, `${path}/${pathRegexParser(layer.regexp, layer.keys)}`, l, keys);\n });\n }\n\n if (!layer.route || layer.route.stack.length === 0) {\n return;\n }\n\n routes.push(parseRouteLayer(layer as Required<Layer>, keys, path));\n};\n\n// @TODO use this to parse the express swagger\n\n/**\n * Parses an Express app and generates list of routes with metadata.\n *\n * Can Parse:\n * - Nested Routers and Complex Express Projects\n * - Optional parameters e.g. /:name?\n * - Complex Matching routes e.g. /ma*tch, /ex(ab)?mple\n * - Regex routes e.g. /\\/abc|\\/xyz/\n * - Array of paths e.g. app.get(['/abc', '/xyz']) -> /abc,xyz/\n *\n * @param app The Express app reference. Must be used after all routes have been attached\n *\n * @returns List of routes for this express app with meta-data that has been picked up\n */\nconst expressPathParser = (app: Express): RouteMetaData[] => {\n // eslint-disable-next-line no-underscore-dangle\n const router: Router = app._router || app.router;\n const routes: RouteMetaData[] = [];\n\n router.stack.forEach((layer: Layer) => {\n traverse(routes, \"\", layer, []);\n });\n\n return routes;\n};\n\nexport default expressPathParser;\n","import type { Express } from \"express\";\n\nimport expressPathParser from \"./express/express-path-parser\";\nimport type { RouteMetaData } from \"./express/types\";\nimport type { Route } from \"./types\";\n\nconst expressRoutes = (app: Express): Route[] => {\n const routes: Route[] = [];\n\n expressPathParser(app).forEach((route: RouteMetaData) => {\n routes.push({\n file: \"unknown\",\n method: route.method.toUpperCase(),\n path: route.path,\n tags: [],\n });\n });\n\n return routes;\n};\n\nexport default expressRoutes;\n","import type { FastifyInstance } from \"fastify\";\n\nimport type { Route } from \"./types\";\n\n// \"<spaces> activity (GET)\" -> \"activity\"\nconst getSegment = (line: string) => line.replaceAll(/ \\(.*\\)/gu, \"\").trim();\n\n// \"<spaces> activity (GET)\" -> \"GET\"\nconst getMethod = (line: string) => (line.trim().split(\" \")[1] as string).slice(1, -1);\n\ninterface Segment {\n depth: number;\n index: number;\n isRoute: boolean;\n methods: string[] | null;\n segment: string;\n}\n\nconst fastifyRoutes = (app: FastifyInstance): Route[] => {\n const printedRoutes = app\n .printRoutes()\n .replaceAll(/[─│└├]/gu, \" \")\n .trimEnd();\n\n const lines = printedRoutes.split(\"\\n\");\n\n // eslint-disable-next-line unicorn/no-array-reduce\n const segments = lines.reduce((allSegments: Segment[], line, index) => {\n const segment = getSegment(line);\n const previousSegment = getSegment(lines[index - 1] ?? \"\");\n\n if (previousSegment === segment) {\n const entries: Segment[] = allSegments.filter((item) => item.index < index && item.segment === segment);\n\n const { methods } = entries.at(-1) as Segment;\n\n if (methods !== null) {\n methods.push(getMethod(line));\n }\n\n return allSegments;\n }\n\n // spaces preceding segment / not counting single space between segment and (METHOD)\n const spaces = line.replaceAll(/ \\(.*\\)/gu, \"\").match(/ /gu);\n\n if (spaces === null) {\n throw new Error(\"Invalid spaces\");\n }\n\n const depth = spaces.length / 4;\n const isRoute = line.includes(\"(\");\n const methods = isRoute ? [getMethod(line)] : null;\n\n allSegments.push({\n depth,\n index,\n isRoute,\n methods,\n segment,\n });\n\n return allSegments;\n }, []);\n\n const routes: Route[] = [];\n\n segments\n .filter((item) => item.isRoute)\n .forEach((item) => {\n const ancestorSegments = segments\n .filter((seg) => seg.index < item.index && seg.depth < item.depth)\n // eslint-disable-next-line unicorn/prefer-array-some\n .filter((seg, _index, previousArray) => !previousArray.find((segment) => segment.depth === seg.depth && segment.index > seg.index));\n\n const route = [...ancestorSegments.map((r) => r.segment), item.segment].join(\"\");\n\n if (item.methods === null) {\n throw new Error(\"Invalid methods\");\n }\n\n item.methods.forEach((method: string) => {\n routes.push({\n file: \"unknown\",\n method: method.toUpperCase(),\n path: route,\n tags: [],\n });\n });\n });\n\n return routes;\n};\n\nexport default fastifyRoutes;\n","import type { Server } from \"@hapi/hapi\";\n\nimport type { Route } from \"./types\";\n\nconst hapiRoutes = (app: Server): Route[] => {\n // @ts-expect-error TS2339: Property '_core' does not exist on type 'Server'. Internal API.\n // eslint-disable-next-line no-underscore-dangle\n const core = app._core as any;\n const coreRoutes = core.router.routes;\n const routes: Route[] = [];\n\n [...coreRoutes.keys()].forEach((method: string) => {\n coreRoutes.get(method).routes.forEach((route: any) => {\n routes.push({\n file: \"unknown\",\n method: route.route.method.toUpperCase(),\n path: route.path,\n tags: [],\n });\n });\n });\n\n return routes;\n};\n\nexport default hapiRoutes;\n","import type Koa from \"koa\";\n\nimport type { Route } from \"./types\";\n\nconst koaRoutes = (app: Koa): Route[] => {\n const routes: Route[] = [];\n\n app.middleware\n .filter((middlewareFunction) => (middlewareFunction as any).router)\n\n .flatMap((middlewareFunction) => (middlewareFunction as any).router.stack)\n .forEach((route) => {\n routes.push({\n file: \"unknown\",\n method: route.methods.join(\"|\").toUpperCase(),\n path: route.path,\n tags: [],\n });\n });\n\n return routes;\n};\n\nexport default koaRoutes;\n","import { readFileSync } from \"node:fs\";\nimport process from \"node:process\";\n\nimport type { OpenApiObject } from \"@visulima/jsdoc-open-api\";\nimport { jsDocumentCommentsToOpenApi, parseFile, swaggerJsDocumentCommentsToOpenApi } from \"@visulima/jsdoc-open-api\";\n\nimport type { Route } from \"../types\";\n\n// eslint-disable-next-line regexp/no-unused-capturing-group\nconst extensionRegex = /\\.(js|ts|mjs|cjs)$/u;\n\n// eslint-disable-next-line sonarjs/cognitive-complexity\nconst apiRouteFileParser = (apiRouteFile: string, cwdPath: string, verbose = false): Route[] => {\n let specs: OpenApiObject[] = [];\n\n const parsedJsDocumentFile = parseFile(apiRouteFile, jsDocumentCommentsToOpenApi, verbose);\n\n specs = [...specs, ...parsedJsDocumentFile.map((item) => item.spec)];\n\n const parsedSwaggerJsDocumentFile = parseFile(apiRouteFile, swaggerJsDocumentCommentsToOpenApi, verbose);\n\n specs = [...specs, ...parsedSwaggerJsDocumentFile.map((item) => item.spec)];\n\n const routes: Route[] = [];\n\n if (specs.length === 0) {\n const apiRouteFileContent = readFileSync(apiRouteFile, \"utf8\");\n\n apiRouteFileContent.split(/\\r?\\n/u).forEach((line) => {\n const match = /[=aces|]+\\s[\"'|](GET|POST|PUT|PATCH|HEAD|DELETE|OPTIONS)[\"'|]/u.exec(line);\n\n if (match) {\n let [, method] = match;\n\n if (method === \"GET\") {\n method = \"GET|HEAD\";\n }\n\n routes.push({\n file: apiRouteFile.replace(`${process.cwd()}${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`, \"\"),\n method: method as string,\n path: apiRouteFile.replace(cwdPath, \"\").replace(extensionRegex, \"\").replaceAll(\"\\\\\", \"/\"),\n tags: [],\n });\n }\n });\n\n if (routes.length === 0) {\n routes.push({\n file: apiRouteFile.replace(`${process.cwd()}${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`, \"\"),\n method: \"GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS\",\n path: apiRouteFile.replace(cwdPath, \"\").replace(extensionRegex, \"\").replaceAll(\"\\\\\", \"/\"),\n tags: [],\n });\n }\n\n return routes;\n }\n\n specs.forEach((spec) => {\n const paths = Object.entries(spec?.paths ?? {});\n\n paths.forEach(([path, pathSpec]) => {\n const methods = Object.entries(pathSpec);\n\n methods.forEach(([method, methodSpec]) => {\n routes.push({\n file: apiRouteFile.replace(`${process.cwd()}${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`, \"\"),\n method: method.toUpperCase(),\n path: path.replaceAll(\"\\\\\", \"/\"),\n tags: methodSpec.tags,\n });\n });\n });\n });\n\n return routes;\n};\n\nexport default apiRouteFileParser;\n","import { statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { collect } from \"@visulima/readdir\";\n\nimport { ALLOWED_EXTENSIONS } from \"../../utils\";\n\nconst isDirectory = (path: string): boolean => {\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n};\n\nconst collectApiRouteFiles = async (path = \"\", verbose = false): Promise<string[]> => {\n let apiFolderPath = join(path, \"pages/api\");\n\n // src/pages will be ignored if pages is present in the root directory\n if (!isDirectory(apiFolderPath)) {\n apiFolderPath = join(path, \"src/pages/api\");\n\n if (!isDirectory(apiFolderPath)) {\n return [];\n }\n }\n\n return collect(apiFolderPath, {\n extensions: ALLOWED_EXTENSIONS,\n includeDirs: false,\n minimatchOptions: {\n match: {\n debug: verbose,\n matchBase: true,\n },\n skip: {\n debug: verbose,\n matchBase: true,\n },\n },\n });\n};\n\nexport default collectApiRouteFiles;\n","import { readdirSync, readFileSync } from \"node:fs\";\nimport { parse } from \"node:path\";\n\nimport type { PackageJson } from \"type-fest\";\n\ninterface AppExport {\n [key: string]: any;\n app?: string | { app?: string };\n}\n\nexport const ALLOWED_EXTENSIONS = [\".js\", \".ts\", \".mjs\", \".cjs\"];\n\nexport const getAppWorkingDirectoryPath = (appFilePath: string): string | null => {\n let lastParsedPath = parse(appFilePath);\n\n // Once the following condition returns false it means we traversed the whole file system\n // eslint-disable-next-line no-loops/no-loops\n while (lastParsedPath.base && lastParsedPath.root !== lastParsedPath.dir) {\n const parentDirectionItems = readdirSync(lastParsedPath.dir);\n\n const packageJSON = parentDirectionItems.find((item) => item === \"package.json\");\n\n if (packageJSON) {\n return lastParsedPath.dir;\n }\n\n lastParsedPath = parse(lastParsedPath.dir);\n }\n\n return null;\n};\n\nexport const getFrameworkName = (directory: string): \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | null => {\n const packageJSONFilePath = `${directory}/package.json`;\n\n const { dependencies } = JSON.parse(readFileSync(packageJSONFilePath).toString()) as PackageJson;\n\n // eslint-disable-next-line @typescript-eslint/dot-notation\n if (dependencies?.[\"express\"]) {\n return \"express\";\n }\n\n // eslint-disable-next-line @typescript-eslint/dot-notation\n if (dependencies?.[\"koa\"] && (dependencies[\"@koa/router\"] || dependencies[\"koa-router\"])) {\n return \"koa\";\n }\n\n // eslint-disable-next-line @typescript-eslint/dot-notation\n if (dependencies?.[\"next\"]) {\n return \"next\";\n }\n\n if (dependencies?.[\"@hapi/hapi\"]) {\n return \"hapi\";\n }\n\n // eslint-disable-next-line @typescript-eslint/dot-notation\n if (dependencies?.[\"fastify\"]) {\n return \"fastify\";\n }\n\n return null;\n};\n\nexport const getApp = (appExport: AppExport, frameworkName: \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | null): AppExport | string | null => {\n const isExportEmpty = Object.keys(appExport).length === 0;\n\n if (isExportEmpty) {\n return null;\n }\n\n if (frameworkName === \"hapi\") {\n if (typeof (appExport.app as { app?: string }).app === \"string\") {\n return appExport.app as { app: string };\n }\n\n return appExport;\n }\n\n return appExport.app ?? appExport;\n};\n","import type { Server } from \"@hapi/hapi\";\nimport type { Express } from \"express\";\nimport type { FastifyInstance } from \"fastify\";\nimport type Koa from \"koa\";\n\nimport expressRoutes from \"./routes/express-routes\";\nimport fastifyRoutes from \"./routes/fastify-routes\";\nimport hapiRoutes from \"./routes/hapi-routes\";\nimport koaRoutes from \"./routes/koa-routes\";\nimport apiRouteFileParser from \"./routes/next/api-route-file-parser\";\nimport collectApiRouteFiles from \"./routes/next/collect-api-route-files\";\nimport type { Route } from \"./routes/types\";\n\nexport type FrameworkName = \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | \"unknown\";\nexport const getRoutes = async (\n appOrPath: Express | FastifyInstance | Koa | Server | string,\n frameworkName: FrameworkName,\n verbose: boolean,\n): Promise<Route[] | null> => {\n if (frameworkName === \"express\") {\n return expressRoutes(appOrPath as Express);\n }\n\n if (frameworkName === \"koa\") {\n return koaRoutes(appOrPath as Koa);\n }\n\n if (frameworkName === \"hapi\") {\n return hapiRoutes(appOrPath as Server);\n }\n\n if (frameworkName === \"fastify\") {\n return fastifyRoutes(appOrPath as FastifyInstance);\n }\n\n if (frameworkName === \"next\") {\n const apiRouteFiles = await collectApiRouteFiles(appOrPath as string, verbose);\n\n if (apiRouteFiles.length === 0) {\n throw new Error(`No API routes found, in \"${appOrPath}\".`);\n }\n\n return apiRouteFiles.flatMap((apiRouteFile) => apiRouteFileParser(apiRouteFile, appOrPath as string, verbose));\n }\n\n return null;\n};\n","import type { Route } from \"./types\";\n\nconst routesGroupBy = (list: Route[], keyGetter: (item: Route) => keyof Route): Map<string, Route[]> => {\n const map = new Map<string, Route[]>();\n\n list.forEach((item) => {\n const key = keyGetter(item);\n const collection = map.get(key);\n\n if (collection) {\n collection.push(item);\n } else {\n map.set(key, [item]);\n }\n });\n\n return map;\n};\n\nexport default routesGroupBy;\n","// eslint-disable-next-line import/no-extraneous-dependencies\nimport chalk from \"chalk\";\n\nimport type { Route } from \"./types\";\n\nconst renderRoute = (method: string, routePath: string): string => {\n const colorMap = {\n ANY: chalk.redBright,\n DELETE: chalk.redBright,\n GET: chalk.blue,\n HEAD: chalk.hex(\"#6C7280\"),\n OPTIONS: chalk.hex(\"#6C7280\"),\n PATCH: chalk.yellow,\n POST: chalk.yellow,\n PUT: chalk.yellow,\n };\n\n let methodText: string;\n\n if (method === \"GET|HEAD\") {\n methodText = `${chalk.blue(\"GET\")}${chalk.grey(\"|HEAD\")}`;\n } else {\n const coloredMethod = colorMap[method as keyof typeof colorMap](method);\n\n methodText = method === \"GET\" ? `${coloredMethod}${chalk.grey(\"|HEAD\")}` : coloredMethod;\n }\n\n const spacesCount = method === \"GET\" ? 6 : 14 - method.length;\n const spaces = Array.from({ length: spacesCount }).fill(\" \").join(\"\");\n\n const dotsCount = process.stdout.columns - 16 - routePath.length - 4;\n const dots = dotsCount > 0 ? Array.from({ length: dotsCount }).fill(\".\").join(\"\") : \"\";\n\n const routeText = routePath\n .split(\"/\")\n .map((segment) => {\n const isDynamicSegment = [\":\", \"[\"].includes(segment[0] ?? \"\");\n\n return isDynamicSegment ? chalk.yellowBright(segment) : segment;\n })\n .join(\"/\");\n\n return ` ${methodText}${spaces}${routeText}${chalk.grey(dots)}`;\n};\n\nconst routesRender = (routesMap: Route[], options: { methods?: string[] } = {}): (string | undefined)[] =>\n routesMap\n .map((route) => {\n if (Array.isArray(options.methods) && options.methods.includes(route.method)) {\n return;\n }\n\n if (route.method === \"GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS\") {\n // eslint-disable-next-line no-param-reassign\n route.method = \"ANY\";\n }\n\n // eslint-disable-next-line consistent-return\n return renderRoute(route.method, route.path.replace(\"/pages\", \"\"));\n })\n .filter(Boolean);\n\nexport default routesRender;\n"]}
|