@visulima/api-platform 1.2.7 → 1.2.8
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 +13 -0
- package/README.md +8 -11
- package/dist/{chunk-A2BQLJ5W.mjs → chunk-2BDDP26Z.mjs} +1 -1
- package/dist/{chunk-BIZOICFF.js.map → chunk-2BDDP26Z.mjs.map} +1 -1
- package/dist/{chunk-BIZOICFF.js → chunk-5B2CCUEK.js} +1 -1
- package/dist/{chunk-A2BQLJ5W.mjs.map → chunk-5B2CCUEK.js.map} +1 -1
- package/dist/{chunk-NH4B62H7.js → chunk-JC55W6OX.js} +1 -1
- package/dist/{chunk-NH4B62H7.js.map → chunk-JC55W6OX.js.map} +1 -1
- package/dist/{chunk-4GBB2H25.mjs → chunk-MAUWX6TE.mjs} +1 -1
- package/dist/{chunk-4GBB2H25.mjs.map → chunk-MAUWX6TE.mjs.map} +1 -1
- package/dist/{chunk-T5VHDOUW.js → chunk-RK2WQGNS.js} +1 -1
- package/dist/chunk-RK2WQGNS.js.map +1 -0
- package/dist/{chunk-DEQMZAAH.mjs → chunk-S2NV4N4L.mjs} +1 -1
- package/dist/chunk-S2NV4N4L.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/dist/framework/next/index-browser.d.ts +5 -2
- package/dist/framework/next/index-browser.js +2 -2
- package/dist/framework/next/index-browser.mjs +1 -1
- package/dist/framework/next/index-server.d.ts +1 -1
- package/dist/framework/next/index-server.js +4 -4
- package/dist/framework/next/index-server.js.map +1 -1
- package/dist/framework/next/index-server.mjs +2 -2
- package/dist/framework/next/index-server.mjs.map +1 -1
- package/dist/framework/next/routes/pages/redoc/index.d.ts +1 -1
- package/dist/framework/next/routes/pages/swagger/index.d.ts +1 -1
- package/dist/index-browser.d.ts +1 -1
- package/dist/index-server.d.ts +1 -1
- package/dist/index-server.js +4 -4
- package/dist/index-server.js.map +1 -1
- package/dist/index-server.mjs +2 -2
- package/dist/index-server.mjs.map +1 -1
- package/package.json +6 -6
- package/dist/chunk-DEQMZAAH.mjs.map +0 -1
- package/dist/chunk-T5VHDOUW.js.map +0 -1
- package/dist/get-static-properties-swagger-546ee3ba.d.ts +0 -5
- /package/dist/{index-bd61921e.d.ts → index-browser-bd61921e.d.ts} +0 -0
|
@@ -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","../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":["colors","execSync","existsSync","rmSync","statSync","extname","join","process","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","jsDocumentCommentsToOpenApi","parseFile","swaggerJsDocumentCommentsToOpenApi","readFileSync","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","packageJSON","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":"AACA,OAAOA,MAAY,QACnB,OAAS,YAAAC,OAAgB,gBACzB,OAAS,cAAAC,EAAY,UAAAC,EAAQ,YAAAC,OAAgB,KAC7C,OAAS,WAAAC,EAAS,QAAAC,MAAY,OAC9B,OAAOC,MAAa,UCKpB,IAAMC,EAAgB,CAACC,EAA8BC,IAAwB,CACzE,GAAIA,EAAK,SAAW,EAChB,MAAM,IAAI,MAAM,qCAAqC,EAGzD,IAAIC,EAAmBF,EAAe,SAAS,EAE/C,OAAAC,EAAK,QAASE,GAAQ,CAClBD,EAAmBC,EAAI,SACjBD,EAAiB,QAAQ,uBAAwB,KAAKC,EAAI,OAAO,EACjED,EAAiB,QAAQ,iBAAkB,IAAIC,EAAI,MAAM,CACnE,CAAC,EAEMD,EACF,QAAQ,gBAAiB,EAAE,EAC3B,QAAQ,KAAM,EAAE,EAChB,WAAW,OAAQ,EAAE,EACrB,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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AAAA,WAAcvI,EAAO,YAAY,OAAO2B,EAAO,MAAM,CAAC,UAAUA,EAAO,SAAW,EAAI,QAAU;AAAA,CAAa,CAC7H,EAEO6G,GAAQhB","sourcesContent":["// eslint-disable-next-line import/no-extraneous-dependencies\nimport colors from \"chalk\";\nimport { execSync } from \"node:child_process\";\nimport { existsSync, rmSync, statSync } from \"node:fs\";\nimport { extname, join } from \"node:path\";\nimport process from \"node:process\";\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.d\";\nimport {\n ALLOWED_EXTENSIONS, getApp, getAppWorkingDirectoryPath, getFrameworkName,\n} from \"./utils\";\n\ntype RenderOptions = {\n includePaths: string[];\n excludePaths: string[];\n methods: string[];\n group: string;\n};\n\nconst listCommand = async (\n framework: \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | undefined,\n path: string,\n options: Partial<\n RenderOptions & {\n verbose: boolean;\n }\n > = {},\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 // eslint-disable-next-line sonarjs/no-duplicate-string\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 // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-return\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 // eslint-disable-next-line no-console\n console.log(dots + colors.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 ${colors.greenBright(String(routes.length))} HTTP ${routes.length === 1 ? \"route\" : \"routes\"}.\\n`);\n};\n\nexport default listCommand;\n","import type { ExpressRegex, Key } from \"./types.d\";\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 atleast 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(/\\\\/gi, \"\")\n .replaceAll(/\\/{2,}/gi, \"/\");\n};\n\nexport default mapKeysToPath;\n","import mapKeysToPath from \"./map-keys-to-path\";\nimport type { ExpressRegex, Key } from \"./types.d\";\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 = /^\\/\\^((?:\\\\[$()*+./?[\\\\\\]^{|}]|[^$()*+./?[\\\\\\]^{|}])*)\\$\\//.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(/\\\\(.)/g, \"$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","// eslint-disable-next-line import/no-extraneous-dependencies\nimport type { Express, Router } from \"express\";\n\nimport pathRegexParser from \"./path-regex-parser\";\nimport type {\n Key, Layer, Parameter, Route, RouteMetaData,\n} from \"./types.d\";\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 { name: key.name, in: \"path\", required: !key.optional };\n });\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\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,}/gi, \"/\");\n\n if (filtered.length === 0) {\n return { path, pathParams: pathParameters, method: lastRequestHandler.method };\n }\n\n return {\n path,\n pathParams: pathParameters,\n method: lastRequestHandler.method,\n metadata: ((filtered[0] as Layer).handle as Route).metadata,\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","// eslint-disable-next-line import/no-extraneous-dependencies\nimport 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 path: route.path,\n method: route.method.toUpperCase(),\n tags: [],\n file: \"unknown\",\n });\n });\n\n return routes;\n};\n\nexport default expressRoutes;\n","// eslint-disable-next-line import/no-extraneous-dependencies\nimport type { FastifyInstance } from \"fastify\";\n\nimport type { Route } from \"./types\";\n\n// \"<spaces> activity (GET)\" -> \"activity\"\nconst getSegment = (line: string) => line.replaceAll(/ \\(.*\\)/g, \"\").trim();\n\n// \"<spaces> activity (GET)\" -> \"GET\"\nconst getMethod = (line: string) => (line.trim().split(\" \")[1] as string).slice(1, -1);\n\ntype Segment = { index: number; segment: string; methods: string[] | null; depth: number; isRoute: boolean };\n\nconst fastifyRoutes = (app: FastifyInstance): Route[] => {\n const printedRoutes = app\n .printRoutes()\n .replaceAll(/[─│└├]/g, \" \")\n .trimEnd();\n\n const lines = printedRoutes.split(\"\\n\");\n\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(/ \\(.*\\)/g, \"\").match(/ /g);\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 segment,\n index,\n depth,\n isRoute,\n methods,\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 path: route,\n method: method.toUpperCase(),\n tags: [],\n file: \"unknown\",\n });\n });\n });\n\n return routes;\n};\n\nexport default fastifyRoutes;\n","// eslint-disable-next-line import/no-extraneous-dependencies\nimport type { Server } from \"@hapi/hapi\";\n\nimport type { Route } from \"./types\";\n\nconst hapiRoutes = (app: Server): Route[] => {\n // @ts-expect-error\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 path: route.path,\n method: route.route.method.toUpperCase(),\n tags: [],\n file: \"unknown\",\n });\n });\n });\n\n return routes;\n};\n\nexport default hapiRoutes;\n","// eslint-disable-next-line import/no-extraneous-dependencies\nimport 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 // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n .flatMap((middlewareFunction) => (middlewareFunction as any).router.stack)\n .forEach((route) => {\n routes.push({\n path: route.path,\n method: route.methods.join(\"|\").toUpperCase(),\n tags: [],\n file: \"unknown\",\n });\n });\n\n return routes;\n};\n\nexport default koaRoutes;\n","import type { OpenApiObject } from \"@visulima/jsdoc-open-api\";\nimport { jsDocumentCommentsToOpenApi, parseFile, swaggerJsDocumentCommentsToOpenApi } from \"@visulima/jsdoc-open-api\";\nimport { readFileSync } from \"node:fs\";\nimport process from \"node:process\";\n\nimport type { Route } from \"../types.d\";\n\nconst extensionRegex = /\\.(js|ts|mjs|cjs)$/;\n\n// eslint-disable-next-line sonarjs/cognitive-complexity\nconst apiRouteFileParser = (apiRouteFile: string, cwdPath: string, verbose: boolean = 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/).forEach((line) => {\n const match = /[=aces|]+\\s[\"'|](GET|POST|PUT|PATCH|HEAD|DELETE|OPTIONS)[\"'|]/.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 method: method as string,\n path: apiRouteFile.replace(cwdPath, \"\").replace(extensionRegex, \"\").replaceAll(\"\\\\\", \"/\"),\n tags: [],\n file: apiRouteFile.replace(`${process.cwd()}${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`, \"\"),\n });\n }\n });\n\n if (routes.length === 0) {\n routes.push({\n method: \"GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS\",\n path: apiRouteFile.replace(cwdPath, \"\").replace(extensionRegex, \"\").replaceAll(\"\\\\\", \"/\"),\n tags: [],\n file: apiRouteFile.replace(`${process.cwd()}${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`, \"\"),\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 path: path.replaceAll(\"\\\\\", \"/\"),\n method: method.toUpperCase(),\n tags: methodSpec.tags,\n file: apiRouteFile.replace(`${process.cwd()}${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`, \"\"),\n });\n });\n });\n });\n\n return routes;\n};\n\nexport default apiRouteFileParser;\n","// eslint-disable-next-line import/no-extraneous-dependencies\nimport { collect } from \"@visulima/readdir\";\nimport { statSync } from \"node:fs\";\nimport { join } from \"node:path\";\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: string = \"\", verbose: boolean = 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\ntype AppExport = { [key: string]: any; app?: string | { app?: string } };\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 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 const packageJSON = JSON.parse(readFileSync(packageJSONFilePath).toString());\n const { dependencies } = packageJSON;\n\n if (dependencies.express) {\n return \"express\";\n }\n\n if (dependencies.koa && (dependencies[\"@koa/router\"] || dependencies[\"koa-router\"])) {\n return \"koa\";\n }\n\n if (dependencies.next) {\n return \"next\";\n }\n\n if (dependencies[\"@hapi/hapi\"]) {\n return \"hapi\";\n }\n\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 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\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","// eslint-disable-next-line import/no-extraneous-dependencies\nimport type { Server } from \"@hapi/hapi\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport type { Express } from \"express\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport type { FastifyInstance } from \"fastify\";\n// eslint-disable-next-line import/no-extraneous-dependencies\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.d\";\n\nexport type FrameworkName = \"express\" | \"fastify\" | \"hapi\" | \"koa\" | \"next\" | \"unknown\";\nexport async function getRoutes(\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 colors from \"chalk\";\n\nimport type { Route } from \"./types\";\n\nconst renderRoute = (method: string, routePath: string): string => {\n const colorMap = {\n GET: colors.blue,\n POST: colors.yellow,\n PATCH: colors.yellow,\n PUT: colors.yellow,\n DELETE: colors.redBright,\n OPTIONS: colors.hex(\"#6C7280\"),\n ANY: colors.redBright,\n HEAD: colors.hex(\"#6C7280\"),\n };\n\n let methodText: string;\n\n if (method === \"GET|HEAD\") {\n methodText = `${colors.blue(\"GET\")}${colors.grey(\"|HEAD\")}`;\n } else {\n const coloredMethod = colorMap[method as keyof typeof colorMap](method);\n\n methodText = method === \"GET\" ? `${coloredMethod}${colors.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 ? colors.yellowBright(segment) : segment;\n })\n .join(\"/\");\n\n return ` ${methodText}${spaces}${routeText}${colors.grey(dots)}`;\n};\n\nconst routesRender = (routesMap: Route[], options: { methods?: string[] } = {}): (string | undefined)[] => 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 chunkRK2WQGNS_js = require('../../../chunk-RK2WQGNS.js');
|
|
4
4
|
require('../../../chunk-DELU3TYG.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(e=>{try{
|
|
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(e=>{try{chunkRK2WQGNS_js.a(e.framework,e.path,{verbose:e.verbose,group:e.group,includePaths:e.includePath,excludePaths:e.excludePaths});}catch(n){console.log(),console.error(n),process.exit(1);}});},p=i;
|
|
8
8
|
|
|
9
9
|
exports.listCommand = p;
|
|
10
10
|
//# sourceMappingURL=out.js.map
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkRK2WQGNS_js = require('../../chunk-RK2WQGNS.js');
|
|
4
4
|
require('../../chunk-DELU3TYG.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 chunkRK2WQGNS_js.a; }
|
|
11
11
|
});
|
|
12
12
|
//# sourceMappingURL=out.js.map
|
|
13
13
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,2 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import { GetStaticProps } from 'next';
|
|
2
|
+
|
|
3
|
+
declare const getStaticProps: (swaggerUrl: string) => GetStaticProps;
|
|
4
|
+
|
|
5
|
+
export { getStaticProps as getSwaggerStaticProps };
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunk5B2CCUEK_js = require('../../chunk-5B2CCUEK.js');
|
|
4
4
|
require('../../chunk-DELU3TYG.js');
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
|
|
8
8
|
Object.defineProperty(exports, 'getSwaggerStaticProps', {
|
|
9
9
|
enumerable: true,
|
|
10
|
-
get: function () { return
|
|
10
|
+
get: function () { return chunk5B2CCUEK_js.a; }
|
|
11
11
|
});
|
|
12
12
|
//# sourceMappingURL=out.js.map
|
|
13
13
|
//# sourceMappingURL=index-browser.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { getSwaggerStaticProps } from './index-browser.js';
|
|
2
2
|
import { BaseDefinition } from '@visulima/jsdoc-open-api';
|
|
3
3
|
import { NextConfig } from 'next';
|
|
4
4
|
import { S as SwaggerHandlerOptions } from '../../swagger-handler-8947e0f1.js';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
4
|
-
var
|
|
3
|
+
var chunkJC55W6OX_js = require('../../chunk-JC55W6OX.js');
|
|
4
|
+
var chunk5B2CCUEK_js = require('../../chunk-5B2CCUEK.js');
|
|
5
5
|
require('../../chunk-DELU3TYG.js');
|
|
6
6
|
var jsdocOpenApi = require('@visulima/jsdoc-open-api');
|
|
7
7
|
var m = require('fs');
|
|
@@ -12,11 +12,11 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
|
12
12
|
var m__default = /*#__PURE__*/_interopDefault(m);
|
|
13
13
|
var l__default = /*#__PURE__*/_interopDefault(l);
|
|
14
14
|
|
|
15
|
-
var d=({definition:t,sources:s,verbose:p,output:r="swagger/swagger.json"})=>o=>({...o,webpack:(e,i)=>{if(!i.isServer)return e;if(r.startsWith("/")&&(r=r.slice(1)),!r.endsWith(".json"))throw new Error("The output path must end with .json");return e={...e,plugins:[...e.plugins,new jsdocOpenApi.SwaggerCompilerPlugin(`${i.dir}/${r}`,s.map(g=>{let a=l__default.default.join(i.dir,g.replace("./",""));return m__default.default.lstatSync(a).isDirectory(),a}),{openapi:"3.0.0",...t},{verbose:p})]},typeof o.webpack=="function"?o.webpack(e,i):e}}),w=d;var u=(t={})=>
|
|
15
|
+
var d=({definition:t,sources:s,verbose:p,output:r="swagger/swagger.json"})=>o=>({...o,webpack:(e,i)=>{if(!i.isServer)return e;if(r.startsWith("/")&&(r=r.slice(1)),!r.endsWith(".json"))throw new Error("The output path must end with .json");return e={...e,plugins:[...e.plugins,new jsdocOpenApi.SwaggerCompilerPlugin(`${i.dir}/${r}`,s.map(g=>{let a=l__default.default.join(i.dir,g.replace("./",""));return m__default.default.lstatSync(a).isDirectory(),a}),{openapi:"3.0.0",...t},{verbose:p})]},typeof o.webpack=="function"?o.webpack(e,i):e}}),w=d;var u=(t={})=>chunkJC55W6OX_js.c(t),c=u;
|
|
16
16
|
|
|
17
17
|
Object.defineProperty(exports, 'getSwaggerStaticProps', {
|
|
18
18
|
enumerable: true,
|
|
19
|
-
get: function () { return
|
|
19
|
+
get: function () { return chunk5B2CCUEK_js.a; }
|
|
20
20
|
});
|
|
21
21
|
exports.swaggerApiRoute = c;
|
|
22
22
|
exports.withOpenApi = w;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/framework/next/webpack/with-open-api.ts","../../../src/framework/next/routes/api/swagger.ts"],"names":["SwaggerCompilerPlugin","fs","path","withOpenApi","definition","sources","verbose","output","nextConfig","config","options","source","combinedPath","with_open_api_default","swaggerApiRoute","swagger_handler_default","swagger_default"],"mappings":"wHACA,OAAS,yBAAAA,MAA6B,2BAKtC,OAAOC,MAAQ,KACf,OAAOC,MAAU,OAGjB,IAAMC,EAAc,CAAC,CACjB,WAAAC,
|
|
1
|
+
{"version":3,"sources":["../../../src/framework/next/webpack/with-open-api.ts","../../../src/framework/next/routes/api/swagger.ts"],"names":["SwaggerCompilerPlugin","fs","path","withOpenApi","definition","sources","verbose","output","nextConfig","config","options","source","combinedPath","with_open_api_default","swaggerApiRoute","swagger_handler_default","swagger_default"],"mappings":"wHACA,OAAS,yBAAAA,MAA6B,2BAKtC,OAAOC,MAAQ,KACf,OAAOC,MAAU,OAGjB,IAAMC,EAAc,CAAC,CACjB,WAAAC,EACA,QAAAC,EACA,QAAAC,EACA,OAAAC,EAAS,sBACb,IAMOC,IAAwC,CAC3C,GAAGA,EACH,QAAS,CAACC,EAAuBC,IAAiB,CAC9C,GAAI,CAACA,EAAQ,SACT,OAAOD,EAQX,GALIF,EAAO,WAAW,GAAG,IAErBA,EAASA,EAAO,MAAM,CAAC,GAGvB,CAACA,EAAO,SAAS,OAAO,EACxB,MAAM,IAAI,MAAM,qCAAqC,EA6BzD,OAzBAE,EAAS,CACL,GAAGA,EACH,QAAS,CAEL,GAAGA,EAAO,QACV,IAAIT,EACA,GAAGU,EAAQ,OAAOH,IAClBF,EAAQ,IAAKM,GAAW,CACpB,IAAMC,EAAeV,EAAK,KAAKQ,EAAQ,IAAeC,EAAO,QAAQ,KAAM,EAAE,CAAC,EAG9E,OAAAV,EAAG,UAAUW,CAAY,EAAE,YAAY,EAEhCA,CACX,CAAC,EACD,CAEI,QAAS,QACT,GAAGR,CACP,EACA,CAAE,QAAAE,CAAQ,CACd,CACJ,CACJ,EAEI,OAAOE,EAAW,SAAY,WACvBA,EAAW,QAAQC,EAAQC,CAAO,EAGtCD,CACX,CACJ,GAEOI,EAAQV,EChEf,IAAMW,EAAsH,CAACJ,EAAU,CAAC,IAAMK,EAAeL,CAAO,EAE7JM,EAAQF","sourcesContent":["import type { BaseDefinition } from \"@visulima/jsdoc-open-api\";\nimport { SwaggerCompilerPlugin } from \"@visulima/jsdoc-open-api\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport type { NextConfig } from \"next\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport type { NextJsWebpackConfig } from \"next/dist/server/config-shared\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { Configuration } from \"webpack\";\n\nconst withOpenApi = ({\n definition,\n sources,\n verbose,\n output = \"swagger/swagger.json\",\n}: // eslint-disable-next-line max-len\n{\n definition: Exclude<BaseDefinition, \"openapi\"> & { openapi?: string };\n sources: string[];\n verbose?: boolean;\n output: string;\n}) => (nextConfig: NextConfig): NextConfig => ({\n ...nextConfig,\n webpack: (config: Configuration, options: any) => {\n if (!options.isServer) {\n return config;\n }\n\n if (output.startsWith(\"/\")) {\n // eslint-disable-next-line no-param-reassign\n output = output.slice(1);\n }\n\n if (!output.endsWith(\".json\")) {\n throw new Error(\"The output path must end with .json\");\n }\n\n // eslint-disable-next-line no-param-reassign\n config = {\n ...config,\n plugins: [\n // @ts-expect-error\n ...config.plugins,\n new SwaggerCompilerPlugin(\n `${options.dir}/${output}`,\n sources.map((source) => {\n const combinedPath = path.join(options.dir as string, source.replace(\"./\", \"\"));\n\n // Check if the path is a directory\n fs.lstatSync(combinedPath).isDirectory();\n\n return combinedPath;\n }),\n {\n // @ts-expect-error\n openapi: \"3.0.0\",\n ...definition,\n },\n { verbose },\n ),\n ],\n };\n\n if (typeof nextConfig.webpack === \"function\") {\n return nextConfig.webpack(config, options) as NextJsWebpackConfig;\n }\n\n return config as NextJsWebpackConfig;\n },\n} as NextConfig);\n\nexport default withOpenApi;\n","import type { SwaggerHandlerOptions } from \"../../../../swagger/api/swagger-handler\";\nimport swaggerHandler from \"../../../../swagger/api/swagger-handler\";\n\n/**\n * @deprecated Use `import { swaggerHandler } from \"@visulima/api-platform\"` instead.\n */\n// eslint-disable-next-line max-len\nconst swaggerApiRoute: <M extends string, PrismaClient>(options: Partial<SwaggerHandlerOptions<M, PrismaClient>>) => void = (options = {}) => swaggerHandler(options);\n\nexport default swaggerApiRoute;\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { c as c$1 } from '../../chunk-
|
|
2
|
-
export { a as getSwaggerStaticProps } from '../../chunk-
|
|
1
|
+
import { c as c$1 } from '../../chunk-MAUWX6TE.mjs';
|
|
2
|
+
export { a as getSwaggerStaticProps } from '../../chunk-2BDDP26Z.mjs';
|
|
3
3
|
import '../../chunk-2ZMPKWQQ.mjs';
|
|
4
4
|
import { SwaggerCompilerPlugin } from '@visulima/jsdoc-open-api';
|
|
5
5
|
import m from 'fs';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/framework/next/webpack/with-open-api.ts","../../../src/framework/next/routes/api/swagger.ts"],"names":["SwaggerCompilerPlugin","fs","path","withOpenApi","definition","sources","verbose","output","nextConfig","config","options","source","combinedPath","with_open_api_default","swaggerApiRoute","swagger_handler_default","swagger_default"],"mappings":"2HACA,OAAS,yBAAAA,MAA6B,2BAKtC,OAAOC,MAAQ,KACf,OAAOC,MAAU,OAGjB,IAAMC,EAAc,CAAC,CACjB,WAAAC,
|
|
1
|
+
{"version":3,"sources":["../../../src/framework/next/webpack/with-open-api.ts","../../../src/framework/next/routes/api/swagger.ts"],"names":["SwaggerCompilerPlugin","fs","path","withOpenApi","definition","sources","verbose","output","nextConfig","config","options","source","combinedPath","with_open_api_default","swaggerApiRoute","swagger_handler_default","swagger_default"],"mappings":"2HACA,OAAS,yBAAAA,MAA6B,2BAKtC,OAAOC,MAAQ,KACf,OAAOC,MAAU,OAGjB,IAAMC,EAAc,CAAC,CACjB,WAAAC,EACA,QAAAC,EACA,QAAAC,EACA,OAAAC,EAAS,sBACb,IAMOC,IAAwC,CAC3C,GAAGA,EACH,QAAS,CAACC,EAAuBC,IAAiB,CAC9C,GAAI,CAACA,EAAQ,SACT,OAAOD,EAQX,GALIF,EAAO,WAAW,GAAG,IAErBA,EAASA,EAAO,MAAM,CAAC,GAGvB,CAACA,EAAO,SAAS,OAAO,EACxB,MAAM,IAAI,MAAM,qCAAqC,EA6BzD,OAzBAE,EAAS,CACL,GAAGA,EACH,QAAS,CAEL,GAAGA,EAAO,QACV,IAAIT,EACA,GAAGU,EAAQ,OAAOH,IAClBF,EAAQ,IAAKM,GAAW,CACpB,IAAMC,EAAeV,EAAK,KAAKQ,EAAQ,IAAeC,EAAO,QAAQ,KAAM,EAAE,CAAC,EAG9E,OAAAV,EAAG,UAAUW,CAAY,EAAE,YAAY,EAEhCA,CACX,CAAC,EACD,CAEI,QAAS,QACT,GAAGR,CACP,EACA,CAAE,QAAAE,CAAQ,CACd,CACJ,CACJ,EAEI,OAAOE,EAAW,SAAY,WACvBA,EAAW,QAAQC,EAAQC,CAAO,EAGtCD,CACX,CACJ,GAEOI,EAAQV,EChEf,IAAMW,EAAsH,CAACJ,EAAU,CAAC,IAAMK,EAAeL,CAAO,EAE7JM,EAAQF","sourcesContent":["import type { BaseDefinition } from \"@visulima/jsdoc-open-api\";\nimport { SwaggerCompilerPlugin } from \"@visulima/jsdoc-open-api\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport type { NextConfig } from \"next\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport type { NextJsWebpackConfig } from \"next/dist/server/config-shared\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { Configuration } from \"webpack\";\n\nconst withOpenApi = ({\n definition,\n sources,\n verbose,\n output = \"swagger/swagger.json\",\n}: // eslint-disable-next-line max-len\n{\n definition: Exclude<BaseDefinition, \"openapi\"> & { openapi?: string };\n sources: string[];\n verbose?: boolean;\n output: string;\n}) => (nextConfig: NextConfig): NextConfig => ({\n ...nextConfig,\n webpack: (config: Configuration, options: any) => {\n if (!options.isServer) {\n return config;\n }\n\n if (output.startsWith(\"/\")) {\n // eslint-disable-next-line no-param-reassign\n output = output.slice(1);\n }\n\n if (!output.endsWith(\".json\")) {\n throw new Error(\"The output path must end with .json\");\n }\n\n // eslint-disable-next-line no-param-reassign\n config = {\n ...config,\n plugins: [\n // @ts-expect-error\n ...config.plugins,\n new SwaggerCompilerPlugin(\n `${options.dir}/${output}`,\n sources.map((source) => {\n const combinedPath = path.join(options.dir as string, source.replace(\"./\", \"\"));\n\n // Check if the path is a directory\n fs.lstatSync(combinedPath).isDirectory();\n\n return combinedPath;\n }),\n {\n // @ts-expect-error\n openapi: \"3.0.0\",\n ...definition,\n },\n { verbose },\n ),\n ],\n };\n\n if (typeof nextConfig.webpack === \"function\") {\n return nextConfig.webpack(config, options) as NextJsWebpackConfig;\n }\n\n return config as NextJsWebpackConfig;\n },\n} as NextConfig);\n\nexport default withOpenApi;\n","import type { SwaggerHandlerOptions } from \"../../../../swagger/api/swagger-handler\";\nimport swaggerHandler from \"../../../../swagger/api/swagger-handler\";\n\n/**\n * @deprecated Use `import { swaggerHandler } from \"@visulima/api-platform\"` instead.\n */\n// eslint-disable-next-line max-len\nconst swaggerApiRoute: <M extends string, PrismaClient>(options: Partial<SwaggerHandlerOptions<M, PrismaClient>>) => void = (options = {}) => swaggerHandler(options);\n\nexport default swaggerApiRoute;\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { NextPage, InferGetStaticPropsType } from 'next';
|
|
2
2
|
import { RedocStandaloneProps } from 'redoc';
|
|
3
|
-
import {
|
|
3
|
+
import { getSwaggerStaticProps as getStaticProps } from '../../../index-browser.js';
|
|
4
4
|
|
|
5
5
|
declare const RedocApiDocument: (name: string, swagger?: Exclude<RedocStandaloneProps, "spec">) => NextPage<InferGetStaticPropsType<typeof getStaticProps>>;
|
|
6
6
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { NextPage, InferGetStaticPropsType } from 'next';
|
|
2
2
|
import { SwaggerUIProps } from 'swagger-ui-react';
|
|
3
|
-
import {
|
|
3
|
+
import { getSwaggerStaticProps as getStaticProps } from '../../../index-browser.js';
|
|
4
4
|
|
|
5
5
|
declare const SwaggerApiDocument: (name: string, swagger?: Exclude<SwaggerUIProps, "spec">) => NextPage<InferGetStaticPropsType<typeof getStaticProps>>;
|
|
6
6
|
|
package/dist/index-browser.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { i as zod } from './index-bd61921e.js';
|
|
1
|
+
export { i as zod } from './index-browser-bd61921e.js';
|
|
2
2
|
import 'zod';
|
package/dist/index-server.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { d as dateIn, a as dateOut, i as zod } from './index-bd61921e.js';
|
|
1
|
+
export { d as dateIn, a as dateOut, i as zod } from './index-browser-bd61921e.js';
|
|
2
2
|
export { BadGateway, BadRequest, BandwidthLimitExceeded, Conflict, ExpectationFailed, FailedDependency, Forbidden, GatewayTimeout, Gone, HTTPVersionNotSupported, ImATeapot, InsufficientStorage, InternalServerError, LengthRequired, Locked, LoopDetected, MethodNotAllowed, MisdirectedRequest, NetworkAuthenticationRequire, NotAcceptable, NotExtended, NotFound, NotImplemented, PayloadTooLarge, PaymentRequired, PreconditionFailed, PreconditionRequired, ProxyAuthenticationRequired, RangeNotSatisfiable, RequestHeaderFieldsTooLarge, RequestTimeout, ServiceUnavailable, TooManyRequests, URITooLong, Unauthorized, UnavailableForLegalReasons, UnprocessableEntity, UnsupportedMediaType, UpgradeRequired, VariantAlsoNegotiates, default as createHttpError } from 'http-errors';
|
|
3
3
|
import * as zod from 'zod';
|
|
4
4
|
import { AnyZodObject, ZodObject } from 'zod';
|
package/dist/index-server.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var chunkQJNODCPR_js = require('./chunk-QJNODCPR.js');
|
|
4
|
-
var
|
|
4
|
+
var chunkJC55W6OX_js = require('./chunk-JC55W6OX.js');
|
|
5
5
|
require('./chunk-DELU3TYG.js');
|
|
6
6
|
var k = require('http-errors');
|
|
7
7
|
var connect = require('@visulima/connect');
|
|
@@ -21,7 +21,7 @@ var $__default = /*#__PURE__*/_interopDefault($);
|
|
|
21
21
|
var G__default = /*#__PURE__*/_interopDefault(G);
|
|
22
22
|
var pe__default = /*#__PURE__*/_interopDefault(pe);
|
|
23
23
|
|
|
24
|
-
var f=(e,o)=>{let t=o.headers??{};Object.keys(t).forEach(r=>{e.setHeader(r,t[r]);});},p=(e,o)=>{e.setHeader("content-type","application/json; charset=utf-8"),e.end(JSON.stringify(o));},u=(e,o)=>{o.statusCode!==void 0&&(e.statusCode=o.statusCode),o.status!==void 0&&(e.statusCode=o.status),e.statusCode<400&&(e.statusCode=httpStatusCodes.StatusCodes.INTERNAL_SERVER_ERROR);};var v="An error occurred",J=(e,o,t)=>{if(u(t,e),f(t,e),e instanceof g__default.default.JapiError||g__default.default.JapiError.isLikeJapiError(e)){let r=new g__default.default.ErrorSerializer;p(t,r.serialize(e));}else if(e instanceof k.HttpError){let{statusCode:r,title:a,message:n}=e;p(t,{errors:[{code:r,title:a||httpStatusCodes.getReasonPhrase(r)||v,detail:n}]});}else {let{message:r}=e;p(t,{errors:[{code:"500",title:httpStatusCodes.getReasonPhrase(t.statusCode)||v,detail:r}]});}},z=J;var A="https://tools.ietf.org/html/rfc2616#section-10",M="An error occurred",W=(e,o,t)=>{let{stack:r,message:a}=e;if(e instanceof k.HttpError){let{statusCode:n,expose:s,title:i,type:d}=e;t.statusCode=n,f(t,e),p(t,{type:d||A,title:i||httpStatusCodes.getReasonPhrase(n)||M,details:a,...s?{trace:r}:{}});}else u(t,e),p(t,{type:A,title:httpStatusCodes.getReasonPhrase(t.statusCode)||M,details:a,...e.expose?{trace:r}:{}});},C=W;var x=(e,o)=>async(t,r,a)=>{let n=r.headers.accept,s=C;n==="application/vnd.api+json"&&(s=z);for(let{regex:i,handler:d}of e)if(i.test(n)){s=d;break}t.expose=o,s(t,r,a);},h=async(e,o,t)=>{let r=[...new Set(t.map(a=>a.method))].join(", ");throw o.setHeader("Allow",r),o.statusCode=405,k__default.default(405,`No route with [${e.method}] method found.`)};var I={alpn:"ALPN","c-pep":"C-PEP","c-pep-info":"C-PEP-Info","caldav-timezones":"CalDAV-Timezones","content-id":"Content-ID","content-md5":"Content-MD5",dasl:"DASL",dav:"DAV",dnt:"DNT",etag:"ETag",getprofile:"GetProfile","http2-settings":"HTTP2-Settings","last-event-id":"Last-Event-ID","mime-version":"MIME-Version","optional-www-authenticate":"Optional-WWW-Authenticate","sec-websocket-accept":"Sec-WebSocket-Accept","sec-websocket-extensions":"Sec-WebSocket-Extensions","sec-webSocket-key":"Sec-WebSocket-Key","sec-webSocket-protocol":"Sec-WebSocket-Protocol","sec-webSocket-version":"Sec-WebSocket-Version",slug:"SLUG",tcn:"TCN",te:"TE",ttl:"TTL","www-authenticate":"WWW-Authenticate","x-att-deviceid":"X-ATT-DeviceId","x-dnsprefetch-control":"X-DNSPrefetch-Control","x-uidh":"X-UIDH"},X=(e,o)=>{let t=e.toLowerCase();return o?I[t]?I[t]:t.split("-").map(r=>r[0]?.toUpperCase()+r.slice(1)).join("-"):t},K={canonical:!1,normalizeHeaderKey:X},Z=e=>{let o={...K,...e};return async(t,r,a)=>{let n={},s={};return Object.keys(t.headers).forEach(i=>{n[i]=t.headers[i];let d=o.normalizeHeaderKey(i,o.canonical);d&&(s[d]=t.headers[i]);}),t.headers=s,t.rawHeaders=n,a()}},H=Z;var B=e=>{if(typeof e!="string")return !1;try{let o=JSON.parse(e),t=Object.prototype.toString.call(o);return t==="[object Object]"||t==="[object Array]"}catch{return !1}},S=B;var _=e=>G__default.default.toXML(e,{header:!0,indent:" "}),R=_;var y="Content-Type",Q=(e,o,t,r,a)=>{if(typeof t.getHeader(y)=="string")return r;let i=[...$__default.default(o).types(),a.defaultContentType],d=r,w=!1;return i.forEach(l=>{e.forEach(({regex:O,serializer:q})=>{O.test(l)&&(t.setHeader(y,l),d=q(d),w=!0);}),w||(/yaml|yml/.test(l)?(t.setHeader(y,l),d=
|
|
24
|
+
var f=(e,o)=>{let t=o.headers??{};Object.keys(t).forEach(r=>{e.setHeader(r,t[r]);});},p=(e,o)=>{e.setHeader("content-type","application/json; charset=utf-8"),e.end(JSON.stringify(o));},u=(e,o)=>{o.statusCode!==void 0&&(e.statusCode=o.statusCode),o.status!==void 0&&(e.statusCode=o.status),e.statusCode<400&&(e.statusCode=httpStatusCodes.StatusCodes.INTERNAL_SERVER_ERROR);};var v="An error occurred",J=(e,o,t)=>{if(u(t,e),f(t,e),e instanceof g__default.default.JapiError||g__default.default.JapiError.isLikeJapiError(e)){let r=new g__default.default.ErrorSerializer;p(t,r.serialize(e));}else if(e instanceof k.HttpError){let{statusCode:r,title:a,message:n}=e;p(t,{errors:[{code:r,title:a||httpStatusCodes.getReasonPhrase(r)||v,detail:n}]});}else {let{message:r}=e;p(t,{errors:[{code:"500",title:httpStatusCodes.getReasonPhrase(t.statusCode)||v,detail:r}]});}},z=J;var A="https://tools.ietf.org/html/rfc2616#section-10",M="An error occurred",W=(e,o,t)=>{let{stack:r,message:a}=e;if(e instanceof k.HttpError){let{statusCode:n,expose:s,title:i,type:d}=e;t.statusCode=n,f(t,e),p(t,{type:d||A,title:i||httpStatusCodes.getReasonPhrase(n)||M,details:a,...s?{trace:r}:{}});}else u(t,e),p(t,{type:A,title:httpStatusCodes.getReasonPhrase(t.statusCode)||M,details:a,...e.expose?{trace:r}:{}});},C=W;var x=(e,o)=>async(t,r,a)=>{let n=r.headers.accept,s=C;n==="application/vnd.api+json"&&(s=z);for(let{regex:i,handler:d}of e)if(i.test(n)){s=d;break}t.expose=o,s(t,r,a);},h=async(e,o,t)=>{let r=[...new Set(t.map(a=>a.method))].join(", ");throw o.setHeader("Allow",r),o.statusCode=405,k__default.default(405,`No route with [${e.method}] method found.`)};var I={alpn:"ALPN","c-pep":"C-PEP","c-pep-info":"C-PEP-Info","caldav-timezones":"CalDAV-Timezones","content-id":"Content-ID","content-md5":"Content-MD5",dasl:"DASL",dav:"DAV",dnt:"DNT",etag:"ETag",getprofile:"GetProfile","http2-settings":"HTTP2-Settings","last-event-id":"Last-Event-ID","mime-version":"MIME-Version","optional-www-authenticate":"Optional-WWW-Authenticate","sec-websocket-accept":"Sec-WebSocket-Accept","sec-websocket-extensions":"Sec-WebSocket-Extensions","sec-webSocket-key":"Sec-WebSocket-Key","sec-webSocket-protocol":"Sec-WebSocket-Protocol","sec-webSocket-version":"Sec-WebSocket-Version",slug:"SLUG",tcn:"TCN",te:"TE",ttl:"TTL","www-authenticate":"WWW-Authenticate","x-att-deviceid":"X-ATT-DeviceId","x-dnsprefetch-control":"X-DNSPrefetch-Control","x-uidh":"X-UIDH"},X=(e,o)=>{let t=e.toLowerCase();return o?I[t]?I[t]:t.split("-").map(r=>r[0]?.toUpperCase()+r.slice(1)).join("-"):t},K={canonical:!1,normalizeHeaderKey:X},Z=e=>{let o={...K,...e};return async(t,r,a)=>{let n={},s={};return Object.keys(t.headers).forEach(i=>{n[i]=t.headers[i];let d=o.normalizeHeaderKey(i,o.canonical);d&&(s[d]=t.headers[i]);}),t.headers=s,t.rawHeaders=n,a()}},H=Z;var B=e=>{if(typeof e!="string")return !1;try{let o=JSON.parse(e),t=Object.prototype.toString.call(o);return t==="[object Object]"||t==="[object Array]"}catch{return !1}},S=B;var _=e=>G__default.default.toXML(e,{header:!0,indent:" "}),R=_;var y="Content-Type",Q=(e,o,t,r,a)=>{if(typeof t.getHeader(y)=="string")return r;let i=[...$__default.default(o).types(),a.defaultContentType],d=r,w=!1;return i.forEach(l=>{e.forEach(({regex:O,serializer:q})=>{O.test(l)&&(t.setHeader(y,l),d=q(d),w=!0);}),w||(/yaml|yml/.test(l)?(t.setHeader(y,l),d=chunkJC55W6OX_js.b(S(r)?JSON.parse(r):r)):l.includes("xml")&&(t.setHeader(y,l),d=R({[chunkJC55W6OX_js.a(`${o.url?.replace("/api/","")}`.trim())]:S(r)?JSON.parse(r):r})));}),d},m=Q;var ee=Y__default.default("api-platform:connect:serializers-middleware"),te=(e=[],o="application/json; charset=utf-8")=>async(t,r,a)=>{if(typeof r.send=="function"){let n=r.send;r.send=s=>(r.send=n,s=m(e,t,r,s,{defaultContentType:o}),r.send(s));}else if(typeof r.json=="function")ee("response.json() is not supported by @visulima/api-platform serializer. Use response.send() or response.end() instead.");else {let n=r.end;r.end=(s,...i)=>(r.end=n,s=m(e,t,r,s,{defaultContentType:o}),r.end(s,...i));}return a()},E=te;var oe=(e={})=>new connect.NodeRouter({onNoMatch:h,onError:x(e.errorHandlers??[],e.showTrace??!1)}).use(H(e.middlewares?.["http-header-normalizer"]??{})).use(E(e.middlewares?.serializers?.serializers??[],e.middlewares?.serializers?.defaultContentType??"application/json; charset=utf-8")),se=oe;var ne=e=>e.ip??e.headers["x-forwarded-for"]??e.headers["x-real-ip"]??e.connection.remoteAddress,ae=(e,o)=>async(t,r,a)=>{let n=ne(t);if(n===void 0)throw k__default.default(400,"Missing IP");try{let s=await e.consume(n),i={"Retry-After":Math.round(s.msBeforeNext/1e3)||1,"X-RateLimit-Remaining":s.remainingPoints,"X-RateLimit-Reset":new Date(Date.now()+s.msBeforeNext).toISOString(),...o};Object.keys(i).forEach(d=>{r.setHeader(d,i[d]);}),await a();}catch{throw k__default.default(429,"Too Many Requests")}},ie=ae;var le=e=>connect.expressWrapper(pe__default.default(e)),me=le;
|
|
25
25
|
|
|
26
26
|
Object.defineProperty(exports, 'dateIn', {
|
|
27
27
|
enumerable: true,
|
|
@@ -37,11 +37,11 @@ Object.defineProperty(exports, 'zod', {
|
|
|
37
37
|
});
|
|
38
38
|
Object.defineProperty(exports, 'swaggerHandler', {
|
|
39
39
|
enumerable: true,
|
|
40
|
-
get: function () { return
|
|
40
|
+
get: function () { return chunkJC55W6OX_js.c; }
|
|
41
41
|
});
|
|
42
42
|
Object.defineProperty(exports, 'yamlTransformer', {
|
|
43
43
|
enumerable: true,
|
|
44
|
-
get: function () { return
|
|
44
|
+
get: function () { return chunkJC55W6OX_js.b; }
|
|
45
45
|
});
|
|
46
46
|
Object.defineProperty(exports, 'BadGateway', {
|
|
47
47
|
enumerable: true,
|
package/dist/index-server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index-server.ts","../src/connect/create-node-router.ts","../src/connect/handler.ts","../src/error-handler/jsonapi-error-handler.ts","../src/error-handler/utils.ts","../src/error-handler/problem-error-handler.ts","../src/connect/middleware/http-header-normalizer.ts","../src/connect/middleware/serializers-middleware.ts","../src/serializers/serialize.ts","../src/serializers/has-json-structure.ts","../src/serializers/transformer/xml.ts","../src/connect/middleware/rate-limiter-middleware.ts","../src/connect/middleware/cors-middleware.ts"],"names":["default","BadRequest","Forbidden","BadGateway","BandwidthLimitExceeded","Conflict","ExpectationFailed","FailedDependency","GatewayTimeout","Gone","HTTPVersionNotSupported","ImATeapot","InsufficientStorage","InternalServerError","VariantAlsoNegotiates","ProxyAuthenticationRequired","NetworkAuthenticationRequire","LengthRequired","LoopDetected","Locked","MethodNotAllowed","MisdirectedRequest","NotAcceptable","NotExtended","NotFound","NotImplemented","PayloadTooLarge","RequestHeaderFieldsTooLarge","PaymentRequired","PreconditionFailed","PreconditionRequired","RangeNotSatisfiable","RequestTimeout","ServiceUnavailable","TooManyRequests","Unauthorized","UnprocessableEntity","UnavailableForLegalReasons","UnsupportedMediaType","UpgradeRequired","URITooLong","NodeRouter","createHttpError","HttpError","getReasonPhrase","tsJapi","StatusCodes","setErrorHeaders","response","error","headers","header","sendJson","jsonBody","addStatusCodeToResponse","defaultTitle","jsonapiErrorHandler","_request","serializer","statusCode","title","message","jsonapi_error_handler_default","defaultType","problemErrorHandler","stack","expose","type","problem_error_handler_default","onError","errorHandlers","showTrace","request","apiFormat","errorHandler","regex","handler","onNoMatch","routes","uniqueMethods","route","exceptions","normalizeHeaderKey","key","canonical","lowerCaseKey","text","defaults","httpHeaderNormalizerMiddleware","options_","options","_","next","rawHeaders","normalizedKey","http_header_normalizer_default","debug","accepts","hasJsonStructure","data","result","has_json_structure_default","xml","xmlTransformer","xml_default","contentTypeKey","serialize","serializers","types","serializedData","breakTypes","yaml_default","toHeaderCase","serialize_default","log","serializersMiddleware","defaultContentType","oldSend","oldEnd","arguments_","serializers_middleware_default","createNodeRouter","create_node_router_default","createEdgeRouter","EdgeRouter","expressWrapper","Router","withZod","getIP","rateLimiterMiddleware","rateLimiter","ip","limiter","mergedHeaders","rate_limiter_middleware_default","cors","corsMiddleware","cors_middleware_default"],"mappings":"yIAEA,OACe,WAAXA,GACA,cAAAC,GACA,aAAAC,GACA,cAAAC,GACA,0BAAAC,GACA,YAAAC,GACA,qBAAAC,GACA,oBAAAC,GACA,kBAAAC,GACA,QAAAC,GACA,2BAAAC,GACA,aAAAC,GACA,uBAAAC,GACA,uBAAAC,GACA,yBAAAC,GACA,+BAAAC,GACA,gCAAAC,GACA,kBAAAC,GACA,gBAAAC,GACA,UAAAC,GACA,oBAAAC,GACA,sBAAAC,GACA,iBAAAC,GACA,eAAAC,GACA,YAAAC,GACA,kBAAAC,GACA,mBAAAC,GACA,+BAAAC,GACA,mBAAAC,GACA,sBAAAC,GACA,wBAAAC,GACA,uBAAAC,GACA,kBAAAC,GACA,sBAAAC,GACA,mBAAAC,GACA,gBAAAC,GACA,uBAAAC,GACA,8BAAAC,GACA,wBAAAC,GACA,mBAAAC,GACA,cAAAC,OACG,cC5CP,OAAS,cAAAC,OAAkB,oBCG3B,OAAOC,MAAqB,cCH5B,OAAS,aAAAC,MAAiB,cAC1B,OAAS,mBAAAC,MAAuB,oBAChC,OAAOC,MAAY,UCDnB,OAAS,eAAAC,MAAmB,oBAGrB,IAAMC,EAAkB,CAACC,EAA0BC,IAAyB,CAC/E,IAAMC,EAAuED,EAAoB,SAAW,CAAC,EAE7G,OAAO,KAAKC,CAAO,EAAE,QAASC,GAAmB,CAC7CH,EAAS,UAAUG,EAAQD,EAAQC,CAAM,CAA4C,CACzF,CAAC,CACL,EAOaC,EAAW,CAACJ,EAA0BK,IAA4B,CAE3EL,EAAS,UAAU,eAAgB,iCAAiC,EAEpEA,EAAS,IAAI,KAAK,UAAUK,CAAQ,CAAC,CACzC,EAEaC,EAA0B,CAACN,EAA0BC,IAAyB,CAGlFA,EAAoB,aAAe,SACpCD,EAA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,CAAE,EAEtCE,EAAgD,CAClD,cAAe,KAAK,MAAMD,EAAQ,aAAe,GAAI,GAAK,EAC1D,wBAAyBA,EAAQ,gBACjC,oBAAqB,IAAI,KAAK,KAAK,IAAI,EAAIA,EAAQ,YAAY,EAAE,YAAY,EAC7E,GAAGlF,CACP,EAEA,OAAO,KAAKmF,CAAa,EAAE,QAASlD,GAAQ,CACxCnC,EAAS,UAAUmC,EAAKkD,EAAclD,CAAG,CAAgB,CAC7D,CAAC,EAED,MAAMS,EAAK,CACf,MAAE,CACE,MAAMlD,EAAgB,IAAK,mBAAmB,CAClD,CACJ,EAEO4F,GAAQL,GC1Cf,OAAS,kBAAAJ,OAAsB,oBAI/B,OAAOU,OAAU,OAIjB,IAAMC,GAAoF9C,GAAgDmC,GAAkCU,GAAK7C,CAAO,CAAC,EAElL+C,GAAQD","sourcesContent":["export * from \"./index-browser\";\n\nexport {\n default as createHttpError,\n BadRequest,\n Forbidden,\n BadGateway,\n BandwidthLimitExceeded,\n Conflict,\n ExpectationFailed,\n FailedDependency,\n GatewayTimeout,\n Gone,\n HTTPVersionNotSupported,\n ImATeapot,\n InsufficientStorage,\n InternalServerError,\n VariantAlsoNegotiates,\n ProxyAuthenticationRequired,\n NetworkAuthenticationRequire,\n LengthRequired,\n LoopDetected,\n Locked,\n MethodNotAllowed,\n MisdirectedRequest,\n NotAcceptable,\n NotExtended,\n NotFound,\n NotImplemented,\n PayloadTooLarge,\n RequestHeaderFieldsTooLarge,\n PaymentRequired,\n PreconditionFailed,\n PreconditionRequired,\n RangeNotSatisfiable,\n RequestTimeout,\n ServiceUnavailable,\n TooManyRequests,\n Unauthorized,\n UnprocessableEntity,\n UnavailableForLegalReasons,\n UnsupportedMediaType,\n UpgradeRequired,\n URITooLong,\n} from \"http-errors\";\n\nexport { default as createNodeRouter } from \"./connect/create-node-router\";\nexport { onError, onNoMatch } from \"./connect/handler\";\nexport type {\n EdgeRequestHandler,\n ExpressRequestHandler,\n NodeRequestHandler,\n Route,\n HandlerOptions,\n NextHandler,\n FunctionLike,\n Nextable,\n ValueOrPromise,\n FindResult,\n RouteShortcutMethod,\n HttpMethod,\n} from \"@visulima/connect\";\nexport {\n createEdgeRouter, EdgeRouter, expressWrapper, NodeRouter, Router, withZod, sendJson,\n} from \"@visulima/connect\";\n\nexport type { Serializers, Serializer } from \"./serializers\";\nexport { serialize, yamlTransformer, xmlTransformer } from \"./serializers\";\n\nexport { default as rateLimiterMiddleware } from \"./connect/middleware/rate-limiter-middleware\";\nexport { default as corsMiddleware } from \"./connect/middleware/cors-middleware\";\nexport { default as serializersMiddleware } from \"./connect/middleware/serializers-middleware\";\nexport { default as httpHeaderNormalizerMiddleware } from \"./connect/middleware/http-header-normalizer\";\n\nexport { default as swaggerHandler } from \"./swagger/api/swagger-handler\";\n\nexport { dateIn, dateOut } from \"./zod\";\n","import { NodeRouter } from \"@visulima/connect\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { AnyZodObject, ZodObject } from \"zod\";\n\nimport type { ErrorHandlers } from \"../error-handler/types\";\nimport type { Serializers } from \"../serializers\";\nimport { onError, onNoMatch } from \"./handler\";\nimport httpHeaderNormalizerMiddleware from \"./middleware/http-header-normalizer\";\nimport serializersMiddleware from \"./middleware/serializers-middleware\";\n\nconst createNodeRouter = <\n Request extends IncomingMessage,\n Response extends ServerResponse,\n Schema extends AnyZodObject = ZodObject<{ body?: AnyZodObject; headers?: AnyZodObject; query?: AnyZodObject }>,\n>(\n options: {\n middlewares?: {\n \"http-header-normalizer\"?: { canonical?: boolean; normalizeHeaderKey?: (key: string, canonical: boolean) => string };\n serializers?: {\n serializers?: Serializers;\n defaultContentType?: string;\n };\n };\n errorHandlers?: ErrorHandlers;\n showTrace?: boolean;\n } = {},\n ): NodeRouter<Request, Response, Schema> => {\n const router = new NodeRouter<Request, Response, Schema>({\n onNoMatch,\n onError: onError(options.errorHandlers ?? [], options.showTrace ?? false),\n });\n\n return router\n .use(httpHeaderNormalizerMiddleware(options.middlewares?.[\"http-header-normalizer\"] ?? {}))\n .use(\n serializersMiddleware(\n options.middlewares?.serializers?.serializers ?? [],\n options.middlewares?.serializers?.defaultContentType ?? \"application/json; charset=utf-8\",\n ),\n );\n};\n\nexport default createNodeRouter;\n","import type {\n FunctionLike, Nextable, Route, ValueOrPromise,\n} from \"@visulima/connect\";\nimport createHttpError from \"http-errors\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport JsonapiErrorHandler from \"../error-handler/jsonapi-error-handler\";\nimport ProblemErrorHandler from \"../error-handler/problem-error-handler\";\nimport type { ErrorHandler, ErrorHandlers } from \"../error-handler/types\";\n\n// eslint-disable-next-line unicorn/consistent-function-scoping,max-len\nexport const onError = <Request extends IncomingMessage, Response extends ServerResponse>(errorHandlers: ErrorHandlers, showTrace: boolean) => async (error: unknown, request: Request, response: Response): Promise<void> => {\n const apiFormat: string = request.headers.accept as string;\n\n let errorHandler: ErrorHandler = ProblemErrorHandler;\n\n if (apiFormat === \"application/vnd.api+json\") {\n errorHandler = JsonapiErrorHandler;\n }\n\n // eslint-disable-next-line no-restricted-syntax\n for (const { regex, handler } of errorHandlers) {\n if (regex.test(apiFormat)) {\n errorHandler = handler;\n break;\n }\n }\n\n // eslint-disable-next-line no-param-reassign\n (error as Error & { expose: boolean }).expose = showTrace;\n\n errorHandler(error, request, response);\n};\n\nexport const onNoMatch: <Request extends IncomingMessage, Response extends ServerResponse>(\n request: Request,\n response: Response,\n routes: Route<Nextable<FunctionLike>>[],\n) => ValueOrPromise<void> = async (request, response, routes) => {\n const uniqueMethods = [...new Set(routes.map((route) => route.method))].join(\", \");\n\n response.setHeader(\"Allow\", uniqueMethods);\n response.statusCode = 405;\n\n throw createHttpError(405, `No route with [${request.method}] method found.`);\n};\n","import { HttpError } from \"http-errors\";\nimport { getReasonPhrase } from \"http-status-codes\";\nimport tsJapi from \"ts-japi\";\n\nimport type { ErrorHandler } from \"./types\";\nimport { addStatusCodeToResponse, sendJson, setErrorHeaders } from \"./utils\";\n\nconst defaultTitle = \"An error occurred\";\n\nconst jsonapiErrorHandler: ErrorHandler = (error: Error | HttpError | tsJapi.JapiError, _request, response) => {\n addStatusCodeToResponse(response, error);\n\n setErrorHeaders(response, error);\n\n if (error instanceof tsJapi.JapiError || tsJapi.JapiError.isLikeJapiError(error)) {\n const serializer = new tsJapi.ErrorSerializer();\n\n sendJson(response, serializer.serialize(error));\n } else if (error instanceof HttpError) {\n const { statusCode, title, message } = error;\n\n sendJson(response, {\n errors: [\n {\n code: statusCode,\n title: title || getReasonPhrase(statusCode) || defaultTitle,\n detail: message,\n },\n ],\n });\n } else {\n const { message } = error;\n\n sendJson(response, {\n errors: [\n {\n code: \"500\",\n title: getReasonPhrase(response.statusCode) || defaultTitle,\n detail: message,\n },\n ],\n });\n }\n};\n\nexport default jsonapiErrorHandler;\n","import type { HttpError } from \"http-errors\";\nimport { StatusCodes } from \"http-status-codes\";\nimport type { ServerResponse } from \"node:http\";\n\nexport const setErrorHeaders = (response: ServerResponse, error: unknown): void => {\n const headers: { [key: string]: ReadonlyArray<string> | number | string } = (error as HttpError).headers ?? {};\n\n Object.keys(headers).forEach((header: string) => {\n response.setHeader(header, headers[header] as ReadonlyArray<string> | number | string);\n });\n};\n\n/**\n * Send `JSON` object\n * @param response response object\n * @param jsonBody of data\n */\nexport const sendJson = (response: ServerResponse, jsonBody: unknown): void => {\n // Set header to application/json\n response.setHeader(\"content-type\", \"application/json; charset=utf-8\");\n\n response.end(JSON.stringify(jsonBody));\n};\n\nexport const addStatusCodeToResponse = (response: ServerResponse, error: unknown): void => {\n // respect err.statusCode\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if ((error as HttpError).statusCode !== undefined) {\n response.statusCode = (error as HttpError).statusCode;\n }\n\n // respect err.status\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if ((error as HttpError).status !== undefined) {\n response.statusCode = (error as HttpError).status;\n }\n\n // default status code to 500\n if (response.statusCode < 400) {\n response.statusCode = StatusCodes.INTERNAL_SERVER_ERROR;\n }\n};\n","import { HttpError } from \"http-errors\";\nimport { getReasonPhrase } from \"http-status-codes\";\n\nimport type { ErrorHandler } from \"./types\";\nimport { addStatusCodeToResponse, sendJson, setErrorHeaders } from \"./utils\";\n\nconst defaultType = \"https://tools.ietf.org/html/rfc2616#section-10\";\nconst defaultTitle = \"An error occurred\";\n/**\n * Normalizes errors according to the API Problem spec (RFC 7807).\n *\n * @see https://tools.ietf.org/html/rfc7807\n */\nconst problemErrorHandler: ErrorHandler = (error: Error | HttpError, _request, response) => {\n const { stack, message } = error;\n\n if (error instanceof HttpError) {\n const {\n statusCode, expose, title, type,\n } = error;\n\n response.statusCode = statusCode;\n\n setErrorHeaders(response, error);\n\n sendJson(response, {\n type: type || defaultType,\n title: title || getReasonPhrase(statusCode) || defaultTitle,\n details: message,\n ...(expose ? { trace: stack } : {}),\n });\n } else {\n addStatusCodeToResponse(response, error);\n\n sendJson(response, {\n type: defaultType,\n title: getReasonPhrase(response.statusCode) || defaultTitle,\n details: message,\n ...((error as Error & { expose: boolean }).expose ? { trace: stack } : {}),\n });\n }\n};\n\nexport default problemErrorHandler;\n","import type { NextHandler, ValueOrPromise } from \"@visulima/connect\";\nimport type { IncomingHttpHeaders, IncomingMessage, ServerResponse } from \"node:http\";\n\nconst exceptions = {\n alpn: \"ALPN\",\n \"c-pep\": \"C-PEP\",\n \"c-pep-info\": \"C-PEP-Info\",\n \"caldav-timezones\": \"CalDAV-Timezones\",\n \"content-id\": \"Content-ID\",\n \"content-md5\": \"Content-MD5\",\n dasl: \"DASL\",\n dav: \"DAV\",\n dnt: \"DNT\",\n etag: \"ETag\",\n getprofile: \"GetProfile\",\n \"http2-settings\": \"HTTP2-Settings\",\n \"last-event-id\": \"Last-Event-ID\",\n \"mime-version\": \"MIME-Version\",\n \"optional-www-authenticate\": \"Optional-WWW-Authenticate\",\n \"sec-websocket-accept\": \"Sec-WebSocket-Accept\",\n \"sec-websocket-extensions\": \"Sec-WebSocket-Extensions\",\n \"sec-webSocket-key\": \"Sec-WebSocket-Key\",\n \"sec-webSocket-protocol\": \"Sec-WebSocket-Protocol\",\n \"sec-webSocket-version\": \"Sec-WebSocket-Version\",\n slug: \"SLUG\",\n tcn: \"TCN\",\n te: \"TE\",\n ttl: \"TTL\",\n \"www-authenticate\": \"WWW-Authenticate\",\n \"x-att-deviceid\": \"X-ATT-DeviceId\",\n \"x-dnsprefetch-control\": \"X-DNSPrefetch-Control\",\n \"x-uidh\": \"X-UIDH\",\n};\n\nconst normalizeHeaderKey = (key: string, canonical: boolean) => {\n const lowerCaseKey = key.toLowerCase();\n\n if (!canonical) {\n return lowerCaseKey;\n }\n\n if (exceptions[lowerCaseKey as keyof typeof exceptions]) {\n return exceptions[lowerCaseKey as keyof typeof exceptions];\n }\n\n return (\n lowerCaseKey\n .split(\"-\")\n // eslint-disable-next-line no-unsafe-optional-chaining\n .map((text) => text[0]?.toUpperCase() + text.slice(1))\n .join(\"-\")\n );\n};\n\nconst defaults = {\n canonical: false,\n normalizeHeaderKey,\n};\n\n/**\n * HTTP headers are case-insensitive.\n * That's why NodeJS makes them lower case by default.\n * While sensible, sometimes, for example for compatibility reasons, you might need them in their more common form.\n */\nconst httpHeaderNormalizerMiddleware = (options_?: {\n canonical?: boolean;\n normalizeHeaderKey?: (key: string, canonical: boolean) => string;\n}): ((request: IncomingMessage, response: ServerResponse, next: NextHandler) => ValueOrPromise<void>) => {\n const options = { ...defaults, ...options_ };\n\n return async <Request extends IncomingMessage>(request: Request, _: any, next: NextHandler) => {\n const rawHeaders: IncomingHttpHeaders = {};\n const headers: IncomingHttpHeaders = {};\n\n Object.keys(request.headers).forEach((key) => {\n rawHeaders[key] = request.headers[key];\n\n const normalizedKey = options.normalizeHeaderKey(key, options.canonical);\n\n if (normalizedKey) {\n headers[normalizedKey] = request.headers[key];\n }\n });\n\n request.headers = headers;\n // @TODO at type `request.rawHeaders` to global scope\n // @ts-expect-error\n request.rawHeaders = rawHeaders;\n\n return next();\n };\n};\n\nexport default httpHeaderNormalizerMiddleware;\n","import type { NextHandler, ValueOrPromise } from \"@visulima/connect\";\nimport debug from \"debug\";\nimport type { NextApiResponse } from \"next\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { Serializers } from \"../../serializers\";\nimport { serialize } from \"../../serializers\";\n\n// eslint-disable-next-line testing-library/no-debugging-utils\nconst log = debug(\"api-platform:connect:serializers-middleware\");\n\n// eslint-disable-next-line max-len\nconst serializersMiddleware = (serializers: Serializers = [], defaultContentType: string = \"application/json; charset=utf-8\") => async <Request extends IncomingMessage, Response extends ServerResponse>(request: Request, response: NextApiResponse | Response, next: NextHandler): Promise<ValueOrPromise<void>> => {\n if (typeof (response as NextApiResponse).send === \"function\") {\n const oldSend = (response as NextApiResponse).send;\n\n (response as NextApiResponse).send = (data) => {\n (response as NextApiResponse).send = oldSend;\n\n // eslint-disable-next-line no-param-reassign\n data = serialize<Request, NextApiResponse | Response>(serializers, request, response, data, { defaultContentType });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return (response as NextApiResponse).send(data);\n };\n } else if (typeof (response as NextApiResponse).json === \"function\") {\n log(\"response.json() is not supported by @visulima/api-platform serializer. Use response.send() or response.end() instead.\");\n } else {\n const oldEnd = response.end;\n\n // @ts-expect-error\n response.end = (data, ...arguments_) => {\n response.end = oldEnd;\n\n // eslint-disable-next-line no-param-reassign\n data = serialize<Request, NextApiResponse | Response>(serializers, request, response, data, { defaultContentType });\n\n // @ts-expect-error TS2345: Argument of type 'unknown' is not assignable to parameter of type 'BufferEncoding'.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return response.end(data, ...arguments_);\n };\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return next();\n};\n\nexport default serializersMiddleware;\n","import accepts from \"accepts\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { toHeaderCase } from \"../utils\";\nimport hasJsonStructure from \"./has-json-structure\";\nimport xmlTransformer from \"./transformer/xml\";\nimport yamlTransformer from \"./transformer/yaml\";\nimport type { Serializers } from \"./types\";\n\nconst contentTypeKey = \"Content-Type\";\n\n// eslint-disable-next-line max-len\nconst serialize = <Request extends IncomingMessage, Response extends ServerResponse>(\n serializers: Serializers,\n request: Request,\n response: Response,\n data: unknown,\n options: {\n defaultContentType: string;\n },\n // eslint-disable-next-line sonarjs/cognitive-complexity\n): Buffer | Uint8Array | string => {\n const contentType = response.getHeader(contentTypeKey) as string | undefined;\n\n // skip serialization when Content-Type is already set\n if (typeof contentType === \"string\") {\n return data as string;\n }\n\n const accept = accepts(request);\n const types: string[] = [...(accept.types() as string[]), options.defaultContentType];\n\n let serializedData = data;\n let breakTypes = false;\n\n // eslint-disable-next-line no-restricted-syntax\n types.forEach((type) => {\n serializers.forEach(({ regex, serializer }) => {\n if (regex.test(type)) {\n response.setHeader(contentTypeKey, type);\n\n serializedData = serializer(serializedData);\n breakTypes = true;\n }\n });\n\n if (!breakTypes) {\n if (/yaml|yml/.test(type)) {\n response.setHeader(contentTypeKey, type);\n\n serializedData = yamlTransformer(hasJsonStructure(data) ? JSON.parse(data as string) : data);\n } else if (type.includes(\"xml\")) {\n response.setHeader(contentTypeKey, type);\n\n serializedData = xmlTransformer({\n [toHeaderCase(`${request.url?.replace(\"/api/\", \"\")}`.trim())]: hasJsonStructure(data) ? JSON.parse(data as string) : data,\n });\n }\n }\n });\n\n return serializedData as Buffer | Uint8Array | string;\n};\n\nexport default serialize;\n","const hasJsonStructure = (data: unknown): boolean => {\n if (typeof data !== \"string\") {\n return false;\n }\n\n try {\n const result = JSON.parse(data);\n const type = Object.prototype.toString.call(result);\n\n return type === \"[object Object]\" || type === \"[object Array]\";\n } catch {\n return false;\n }\n};\n\nexport default hasJsonStructure;\n","import type { XmlElement } from \"jstoxml\";\nimport xml from \"jstoxml\";\n\nimport type { Serializer } from \"../types\";\n\nconst xmlTransformer: Serializer = (data?: XmlElement | XmlElement[]) => xml.toXML(data, {\n header: true,\n indent: \" \",\n});\n\nexport default xmlTransformer;\n","import type { NextHandler } from \"@visulima/connect\";\nimport createHttpError from \"http-errors\";\nimport type { NextApiResponse } from \"next\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { RateLimiterAbstract, RateLimiterRes } from \"rate-limiter-flexible\";\n\n// eslint-disable-next-line max-len\nconst getIP: (request: IncomingMessage & { ip?: string }) => string | undefined = (request) => request.ip\n ?? (request.headers[\"x-forwarded-for\"] as string | undefined)\n ?? (request.headers[\"x-real-ip\"] as string | undefined)\n ?? request.connection.remoteAddress;\n\ntype HeaderValue = ReadonlyArray<string> | number | string;\n\n// eslint-disable-next-line max-len\nconst rateLimiterMiddleware = (rateLimiter: RateLimiterAbstract, headers?: (limiterResponse: RateLimiterRes) => { [key: string]: HeaderValue }) => async <Request extends IncomingMessage, Response extends ServerResponse>(request: Request, response: NextApiResponse | Response, next: NextHandler): Promise<void> => {\n const ip = getIP(request);\n\n if (ip === undefined) {\n throw createHttpError(400, \"Missing IP\");\n }\n\n try {\n const limiter = await rateLimiter.consume(ip);\n\n const mergedHeaders: { [key: string]: HeaderValue } = {\n \"Retry-After\": Math.round(limiter.msBeforeNext / 1000) || 1,\n \"X-RateLimit-Remaining\": limiter.remainingPoints,\n \"X-RateLimit-Reset\": new Date(Date.now() + limiter.msBeforeNext).toISOString(),\n ...headers,\n };\n\n Object.keys(mergedHeaders).forEach((key) => {\n response.setHeader(key, mergedHeaders[key] as HeaderValue);\n });\n\n await next();\n } catch {\n throw createHttpError(429, \"Too Many Requests\");\n }\n};\n\nexport default rateLimiterMiddleware;\n","import { expressWrapper } from \"@visulima/connect\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport type { CorsOptions, CorsOptionsDelegate } from \"cors\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport cors from \"cors\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\n// eslint-disable-next-line max-len,@typescript-eslint/explicit-module-boundary-types\nconst corsMiddleware = <Request extends IncomingMessage, Response extends ServerResponse>(options?: CorsOptions | CorsOptionsDelegate) => expressWrapper<Request, Response>(cors(options));\n\nexport default corsMiddleware;\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index-server.ts","../src/connect/create-node-router.ts","../src/connect/handler.ts","../src/error-handler/jsonapi-error-handler.ts","../src/error-handler/utils.ts","../src/error-handler/problem-error-handler.ts","../src/connect/middleware/http-header-normalizer.ts","../src/connect/middleware/serializers-middleware.ts","../src/serializers/serialize.ts","../src/serializers/has-json-structure.ts","../src/serializers/transformer/xml.ts","../src/connect/middleware/rate-limiter-middleware.ts","../src/connect/middleware/cors-middleware.ts"],"names":["default","BadRequest","Forbidden","BadGateway","BandwidthLimitExceeded","Conflict","ExpectationFailed","FailedDependency","GatewayTimeout","Gone","HTTPVersionNotSupported","ImATeapot","InsufficientStorage","InternalServerError","VariantAlsoNegotiates","ProxyAuthenticationRequired","NetworkAuthenticationRequire","LengthRequired","LoopDetected","Locked","MethodNotAllowed","MisdirectedRequest","NotAcceptable","NotExtended","NotFound","NotImplemented","PayloadTooLarge","RequestHeaderFieldsTooLarge","PaymentRequired","PreconditionFailed","PreconditionRequired","RangeNotSatisfiable","RequestTimeout","ServiceUnavailable","TooManyRequests","Unauthorized","UnprocessableEntity","UnavailableForLegalReasons","UnsupportedMediaType","UpgradeRequired","URITooLong","NodeRouter","createHttpError","HttpError","getReasonPhrase","tsJapi","StatusCodes","setErrorHeaders","response","error","headers","header","sendJson","jsonBody","addStatusCodeToResponse","defaultTitle","jsonapiErrorHandler","_request","serializer","statusCode","title","message","jsonapi_error_handler_default","defaultType","problemErrorHandler","stack","expose","type","problem_error_handler_default","onError","errorHandlers","showTrace","request","apiFormat","errorHandler","regex","handler","onNoMatch","routes","uniqueMethods","route","exceptions","normalizeHeaderKey","key","canonical","lowerCaseKey","text","defaults","httpHeaderNormalizerMiddleware","options_","options","_","next","rawHeaders","normalizedKey","http_header_normalizer_default","debug","accepts","hasJsonStructure","data","result","has_json_structure_default","xml","xmlTransformer","xml_default","contentTypeKey","serialize","serializers","types","serializedData","breakTypes","yaml_default","toHeaderCase","serialize_default","log","serializersMiddleware","defaultContentType","oldSend","oldEnd","arguments_","serializers_middleware_default","createNodeRouter","create_node_router_default","createEdgeRouter","EdgeRouter","expressWrapper","Router","withZod","getIP","rateLimiterMiddleware","rateLimiter","ip","limiter","mergedHeaders","rate_limiter_middleware_default","cors","corsMiddleware","cors_middleware_default"],"mappings":"yIAEA,OACe,WAAXA,GACA,cAAAC,GACA,aAAAC,GACA,cAAAC,GACA,0BAAAC,GACA,YAAAC,GACA,qBAAAC,GACA,oBAAAC,GACA,kBAAAC,GACA,QAAAC,GACA,2BAAAC,GACA,aAAAC,GACA,uBAAAC,GACA,uBAAAC,GACA,yBAAAC,GACA,+BAAAC,GACA,gCAAAC,GACA,kBAAAC,GACA,gBAAAC,GACA,UAAAC,GACA,oBAAAC,GACA,sBAAAC,GACA,iBAAAC,GACA,eAAAC,GACA,YAAAC,GACA,kBAAAC,GACA,mBAAAC,GACA,+BAAAC,GACA,mBAAAC,GACA,sBAAAC,GACA,wBAAAC,GACA,uBAAAC,GACA,kBAAAC,GACA,sBAAAC,GACA,mBAAAC,GACA,gBAAAC,GACA,uBAAAC,GACA,8BAAAC,GACA,wBAAAC,GACA,mBAAAC,GACA,cAAAC,OACG,cC5CP,OAAS,cAAAC,OAAkB,oBCG3B,OAAOC,MAAqB,cCH5B,OAAS,aAAAC,MAAiB,cAC1B,OAAS,mBAAAC,MAAuB,oBAChC,OAAOC,MAAY,UCDnB,OAAS,eAAAC,MAAmB,oBAGrB,IAAMC,EAAkB,CAACC,EAA0BC,IAAyB,CAC/E,IAAMC,EAAuED,EAAoB,SAAW,CAAC,EAE7G,OAAO,KAAKC,CAAO,EAAE,QAASC,GAAmB,CAC7CH,EAAS,UAAUG,EAAQD,EAAQC,CAAM,CAA4C,CACzF,CAAC,CACL,EAOaC,EAAW,CAACJ,EAA0BK,IAA4B,CAE3EL,EAAS,UAAU,e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AKH,GAAMxD,CAAO,EAExB,GAAI2D,IAAO,OACP,MAAMzF,EAAgB,IAAK,YAAY,EAG3C,GAAI,CACA,IAAM0F,EAAU,MAAMF,EAAY,QAAQC,CAAE,EAEtCE,EAAgD,CAClD,cAAe,KAAK,MAAMD,EAAQ,aAAe,GAAI,GAAK,EAC1D,wBAAyBA,EAAQ,gBACjC,oBAAqB,IAAI,KAAK,KAAK,IAAI,EAAIA,EAAQ,YAAY,EAAE,YAAY,EAC7E,GAAGlF,CACP,EAEA,OAAO,KAAKmF,CAAa,EAAE,QAASlD,GAAQ,CACxCnC,EAAS,UAAUmC,EAAKkD,EAAclD,CAAG,CAAgB,CAC7D,CAAC,EAED,MAAMS,EAAK,CACf,MAAE,CACE,MAAMlD,EAAgB,IAAK,mBAAmB,CAClD,CACJ,EAEO4F,GAAQL,GC9Cf,OAAS,kBAAAJ,OAAsB,oBAI/B,OAAOU,OAAU,OAIjB,IAAMC,GAAoF9C,GAAgDmC,GAAkCU,GAAK7C,CAAO,CAAC,EAElL+C,GAAQD","sourcesContent":["export * from \"./index-browser\";\n\nexport {\n default as createHttpError,\n BadRequest,\n Forbidden,\n BadGateway,\n BandwidthLimitExceeded,\n Conflict,\n ExpectationFailed,\n FailedDependency,\n GatewayTimeout,\n Gone,\n HTTPVersionNotSupported,\n ImATeapot,\n InsufficientStorage,\n InternalServerError,\n VariantAlsoNegotiates,\n ProxyAuthenticationRequired,\n NetworkAuthenticationRequire,\n LengthRequired,\n LoopDetected,\n Locked,\n MethodNotAllowed,\n MisdirectedRequest,\n NotAcceptable,\n NotExtended,\n NotFound,\n NotImplemented,\n PayloadTooLarge,\n RequestHeaderFieldsTooLarge,\n PaymentRequired,\n PreconditionFailed,\n PreconditionRequired,\n RangeNotSatisfiable,\n RequestTimeout,\n ServiceUnavailable,\n TooManyRequests,\n Unauthorized,\n UnprocessableEntity,\n UnavailableForLegalReasons,\n UnsupportedMediaType,\n UpgradeRequired,\n URITooLong,\n} from \"http-errors\";\n\nexport { default as createNodeRouter } from \"./connect/create-node-router\";\nexport { onError, onNoMatch } from \"./connect/handler\";\nexport type {\n EdgeRequestHandler,\n ExpressRequestHandler,\n NodeRequestHandler,\n Route,\n HandlerOptions,\n NextHandler,\n FunctionLike,\n Nextable,\n ValueOrPromise,\n FindResult,\n RouteShortcutMethod,\n HttpMethod,\n} from \"@visulima/connect\";\nexport {\n createEdgeRouter, EdgeRouter, expressWrapper, NodeRouter, Router, withZod, sendJson,\n} from \"@visulima/connect\";\n\nexport type { Serializers, Serializer } from \"./serializers\";\nexport { serialize, yamlTransformer, xmlTransformer } from \"./serializers\";\n\nexport { default as rateLimiterMiddleware } from \"./connect/middleware/rate-limiter-middleware\";\nexport { default as corsMiddleware } from \"./connect/middleware/cors-middleware\";\nexport { default as serializersMiddleware } from \"./connect/middleware/serializers-middleware\";\nexport { default as httpHeaderNormalizerMiddleware } from \"./connect/middleware/http-header-normalizer\";\n\nexport { default as swaggerHandler } from \"./swagger/api/swagger-handler\";\n\nexport { dateIn, dateOut } from \"./zod\";\n","import { NodeRouter } from \"@visulima/connect\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { AnyZodObject, ZodObject } from \"zod\";\n\nimport type { ErrorHandlers } from \"../error-handler/types\";\nimport type { Serializers } from \"../serializers\";\nimport { onError, onNoMatch } from \"./handler\";\nimport httpHeaderNormalizerMiddleware from \"./middleware/http-header-normalizer\";\nimport serializersMiddleware from \"./middleware/serializers-middleware\";\n\nconst createNodeRouter = <\n Request extends IncomingMessage,\n Response extends ServerResponse,\n Schema extends AnyZodObject = ZodObject<{ body?: AnyZodObject; headers?: AnyZodObject; query?: AnyZodObject }>,\n>(\n options: {\n middlewares?: {\n \"http-header-normalizer\"?: { canonical?: boolean; normalizeHeaderKey?: (key: string, canonical: boolean) => string };\n serializers?: {\n serializers?: Serializers;\n defaultContentType?: string;\n };\n };\n errorHandlers?: ErrorHandlers;\n showTrace?: boolean;\n } = {},\n ): NodeRouter<Request, Response, Schema> => {\n const router = new NodeRouter<Request, Response, Schema>({\n onNoMatch,\n onError: onError(options.errorHandlers ?? [], options.showTrace ?? false),\n });\n\n return router\n .use(httpHeaderNormalizerMiddleware(options.middlewares?.[\"http-header-normalizer\"] ?? {}))\n .use(\n serializersMiddleware(\n options.middlewares?.serializers?.serializers ?? [],\n options.middlewares?.serializers?.defaultContentType ?? \"application/json; charset=utf-8\",\n ),\n );\n};\n\nexport default createNodeRouter;\n","import type {\n FunctionLike, Nextable, Route, ValueOrPromise,\n} from \"@visulima/connect\";\nimport createHttpError from \"http-errors\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport JsonapiErrorHandler from \"../error-handler/jsonapi-error-handler\";\nimport ProblemErrorHandler from \"../error-handler/problem-error-handler\";\nimport type { ErrorHandler, ErrorHandlers } from \"../error-handler/types\";\n\n// eslint-disable-next-line unicorn/consistent-function-scoping,max-len\nexport const onError = <Request extends IncomingMessage, Response extends ServerResponse>(errorHandlers: ErrorHandlers, showTrace: boolean) => async (error: unknown, request: Request, response: Response): Promise<void> => {\n const apiFormat: string = request.headers.accept as string;\n\n let errorHandler: ErrorHandler = ProblemErrorHandler;\n\n if (apiFormat === \"application/vnd.api+json\") {\n errorHandler = JsonapiErrorHandler;\n }\n\n // eslint-disable-next-line no-restricted-syntax\n for (const { regex, handler } of errorHandlers) {\n if (regex.test(apiFormat)) {\n errorHandler = handler;\n break;\n }\n }\n\n // eslint-disable-next-line no-param-reassign\n (error as Error & { expose: boolean }).expose = showTrace;\n\n errorHandler(error, request, response);\n};\n\nexport const onNoMatch: <Request extends IncomingMessage, Response extends ServerResponse>(\n request: Request,\n response: Response,\n routes: Route<Nextable<FunctionLike>>[],\n) => ValueOrPromise<void> = async (request, response, routes) => {\n const uniqueMethods = [...new Set(routes.map((route) => route.method))].join(\", \");\n\n response.setHeader(\"Allow\", uniqueMethods);\n response.statusCode = 405;\n\n throw createHttpError(405, `No route with [${request.method}] method found.`);\n};\n","import { HttpError } from \"http-errors\";\nimport { getReasonPhrase } from \"http-status-codes\";\nimport tsJapi from \"ts-japi\";\n\nimport type { ErrorHandler } from \"./types\";\nimport { addStatusCodeToResponse, sendJson, setErrorHeaders } from \"./utils\";\n\nconst defaultTitle = \"An error occurred\";\n\nconst jsonapiErrorHandler: ErrorHandler = (error: Error | HttpError | tsJapi.JapiError, _request, response) => {\n addStatusCodeToResponse(response, error);\n\n setErrorHeaders(response, error);\n\n if (error instanceof tsJapi.JapiError || tsJapi.JapiError.isLikeJapiError(error)) {\n const serializer = new tsJapi.ErrorSerializer();\n\n sendJson(response, serializer.serialize(error));\n } else if (error instanceof HttpError) {\n const { statusCode, title, message } = error;\n\n sendJson(response, {\n errors: [\n {\n code: statusCode,\n title: title || getReasonPhrase(statusCode) || defaultTitle,\n detail: message,\n },\n ],\n });\n } else {\n const { message } = error;\n\n sendJson(response, {\n errors: [\n {\n code: \"500\",\n title: getReasonPhrase(response.statusCode) || defaultTitle,\n detail: message,\n },\n ],\n });\n }\n};\n\nexport default jsonapiErrorHandler;\n","import type { HttpError } from \"http-errors\";\nimport { StatusCodes } from \"http-status-codes\";\nimport type { ServerResponse } from \"node:http\";\n\nexport const setErrorHeaders = (response: ServerResponse, error: unknown): void => {\n const headers: { [key: string]: ReadonlyArray<string> | number | string } = (error as HttpError).headers ?? {};\n\n Object.keys(headers).forEach((header: string) => {\n response.setHeader(header, headers[header] as ReadonlyArray<string> | number | string);\n });\n};\n\n/**\n * Send `JSON` object\n * @param response response object\n * @param jsonBody of data\n */\nexport const sendJson = (response: ServerResponse, jsonBody: unknown): void => {\n // Set header to application/json\n response.setHeader(\"content-type\", \"application/json; charset=utf-8\");\n\n response.end(JSON.stringify(jsonBody));\n};\n\nexport const addStatusCodeToResponse = (response: ServerResponse, error: unknown): void => {\n // respect err.statusCode\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if ((error as HttpError).statusCode !== undefined) {\n response.statusCode = (error as HttpError).statusCode;\n }\n\n // respect err.status\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if ((error as HttpError).status !== undefined) {\n response.statusCode = (error as HttpError).status;\n }\n\n // default status code to 500\n if (response.statusCode < 400) {\n response.statusCode = StatusCodes.INTERNAL_SERVER_ERROR;\n }\n};\n","import { HttpError } from \"http-errors\";\nimport { getReasonPhrase } from \"http-status-codes\";\n\nimport type { ErrorHandler } from \"./types\";\nimport { addStatusCodeToResponse, sendJson, setErrorHeaders } from \"./utils\";\n\nconst defaultType = \"https://tools.ietf.org/html/rfc2616#section-10\";\nconst defaultTitle = \"An error occurred\";\n/**\n * Normalizes errors according to the API Problem spec (RFC 7807).\n *\n * @see https://tools.ietf.org/html/rfc7807\n */\nconst problemErrorHandler: ErrorHandler = (error: Error | HttpError, _request, response) => {\n const { stack, message } = error;\n\n if (error instanceof HttpError) {\n const {\n statusCode, expose, title, type,\n } = error;\n\n response.statusCode = statusCode;\n\n setErrorHeaders(response, error);\n\n sendJson(response, {\n type: type || defaultType,\n title: title || getReasonPhrase(statusCode) || defaultTitle,\n details: message,\n ...(expose ? { trace: stack } : {}),\n });\n } else {\n addStatusCodeToResponse(response, error);\n\n sendJson(response, {\n type: defaultType,\n title: getReasonPhrase(response.statusCode) || defaultTitle,\n details: message,\n ...((error as Error & { expose: boolean }).expose ? { trace: stack } : {}),\n });\n }\n};\n\nexport default problemErrorHandler;\n","import type { NextHandler, ValueOrPromise } from \"@visulima/connect\";\nimport type { IncomingHttpHeaders, IncomingMessage, ServerResponse } from \"node:http\";\n\nconst exceptions = {\n alpn: \"ALPN\",\n \"c-pep\": \"C-PEP\",\n \"c-pep-info\": \"C-PEP-Info\",\n \"caldav-timezones\": \"CalDAV-Timezones\",\n \"content-id\": \"Content-ID\",\n \"content-md5\": \"Content-MD5\",\n dasl: \"DASL\",\n dav: \"DAV\",\n dnt: \"DNT\",\n etag: \"ETag\",\n getprofile: \"GetProfile\",\n \"http2-settings\": \"HTTP2-Settings\",\n \"last-event-id\": \"Last-Event-ID\",\n \"mime-version\": \"MIME-Version\",\n \"optional-www-authenticate\": \"Optional-WWW-Authenticate\",\n \"sec-websocket-accept\": \"Sec-WebSocket-Accept\",\n \"sec-websocket-extensions\": \"Sec-WebSocket-Extensions\",\n \"sec-webSocket-key\": \"Sec-WebSocket-Key\",\n \"sec-webSocket-protocol\": \"Sec-WebSocket-Protocol\",\n \"sec-webSocket-version\": \"Sec-WebSocket-Version\",\n slug: \"SLUG\",\n tcn: \"TCN\",\n te: \"TE\",\n ttl: \"TTL\",\n \"www-authenticate\": \"WWW-Authenticate\",\n \"x-att-deviceid\": \"X-ATT-DeviceId\",\n \"x-dnsprefetch-control\": \"X-DNSPrefetch-Control\",\n \"x-uidh\": \"X-UIDH\",\n};\n\nconst normalizeHeaderKey = (key: string, canonical: boolean) => {\n const lowerCaseKey = key.toLowerCase();\n\n if (!canonical) {\n return lowerCaseKey;\n }\n\n if (exceptions[lowerCaseKey as keyof typeof exceptions]) {\n return exceptions[lowerCaseKey as keyof typeof exceptions];\n }\n\n return (\n lowerCaseKey\n .split(\"-\")\n // eslint-disable-next-line no-unsafe-optional-chaining\n .map((text) => text[0]?.toUpperCase() + text.slice(1))\n .join(\"-\")\n );\n};\n\nconst defaults = {\n canonical: false,\n normalizeHeaderKey,\n};\n\n/**\n * HTTP headers are case-insensitive.\n * That's why NodeJS makes them lower case by default.\n * While sensible, sometimes, for example for compatibility reasons, you might need them in their more common form.\n */\nconst httpHeaderNormalizerMiddleware = (options_?: {\n canonical?: boolean;\n normalizeHeaderKey?: (key: string, canonical: boolean) => string;\n}): ((request: IncomingMessage, response: ServerResponse, next: NextHandler) => ValueOrPromise<void>) => {\n const options = { ...defaults, ...options_ };\n\n return async <Request extends IncomingMessage>(request: Request, _: any, next: NextHandler) => {\n const rawHeaders: IncomingHttpHeaders = {};\n const headers: IncomingHttpHeaders = {};\n\n Object.keys(request.headers).forEach((key) => {\n rawHeaders[key] = request.headers[key];\n\n const normalizedKey = options.normalizeHeaderKey(key, options.canonical);\n\n if (normalizedKey) {\n headers[normalizedKey] = request.headers[key];\n }\n });\n\n request.headers = headers;\n // @TODO at type `request.rawHeaders` to global scope\n // @ts-expect-error\n request.rawHeaders = rawHeaders;\n\n return next();\n };\n};\n\nexport default httpHeaderNormalizerMiddleware;\n","import type { NextHandler, ValueOrPromise } from \"@visulima/connect\";\nimport debug from \"debug\";\nimport type { NextApiResponse } from \"next\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport type { Serializers } from \"../../serializers\";\nimport { serialize } from \"../../serializers\";\n\n// eslint-disable-next-line testing-library/no-debugging-utils\nconst log = debug(\"api-platform:connect:serializers-middleware\");\n\n// eslint-disable-next-line max-len\nconst serializersMiddleware = (serializers: Serializers = [], defaultContentType: string = \"application/json; charset=utf-8\") => async <Request extends IncomingMessage, Response extends ServerResponse>(\n request: Request,\n response: NextApiResponse | Response,\n next: NextHandler,\n): Promise<ValueOrPromise<void>> => {\n if (typeof (response as NextApiResponse).send === \"function\") {\n const oldSend = (response as NextApiResponse).send;\n\n (response as NextApiResponse).send = (data) => {\n (response as NextApiResponse).send = oldSend;\n\n // eslint-disable-next-line no-param-reassign\n data = serialize<Request, NextApiResponse | Response>(serializers, request, response, data, { defaultContentType });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return (response as NextApiResponse).send(data);\n };\n } else if (typeof (response as NextApiResponse).json === \"function\") {\n log(\"response.json() is not supported by @visulima/api-platform serializer. Use response.send() or response.end() instead.\");\n } else {\n const oldEnd = response.end;\n\n // @ts-expect-error\n response.end = (data, ...arguments_) => {\n response.end = oldEnd;\n\n // eslint-disable-next-line no-param-reassign\n data = serialize<Request, NextApiResponse | Response>(serializers, request, response, data, { defaultContentType });\n\n // @ts-expect-error TS2345: Argument of type 'unknown' is not assignable to parameter of type 'BufferEncoding'.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return response.end(data, ...arguments_);\n };\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return next();\n};\n\nexport default serializersMiddleware;\n","import accepts from \"accepts\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\nimport { toHeaderCase } from \"../utils\";\nimport hasJsonStructure from \"./has-json-structure\";\nimport xmlTransformer from \"./transformer/xml\";\nimport yamlTransformer from \"./transformer/yaml\";\nimport type { Serializers } from \"./types\";\n\nconst contentTypeKey = \"Content-Type\";\n\n// eslint-disable-next-line max-len\nconst serialize = <Request extends IncomingMessage, Response extends ServerResponse>(\n serializers: Serializers,\n request: Request,\n response: Response,\n data: unknown,\n options: {\n defaultContentType: string;\n },\n // eslint-disable-next-line sonarjs/cognitive-complexity\n): Buffer | Uint8Array | string => {\n const contentType = response.getHeader(contentTypeKey) as string | undefined;\n\n // skip serialization when Content-Type is already set\n if (typeof contentType === \"string\") {\n return data as string;\n }\n\n const accept = accepts(request);\n const types: string[] = [...(accept.types() as string[]), options.defaultContentType];\n\n let serializedData = data;\n let breakTypes = false;\n\n // eslint-disable-next-line no-restricted-syntax\n types.forEach((type) => {\n serializers.forEach(({ regex, serializer }) => {\n if (regex.test(type)) {\n response.setHeader(contentTypeKey, type);\n\n serializedData = serializer(serializedData);\n breakTypes = true;\n }\n });\n\n if (!breakTypes) {\n if (/yaml|yml/.test(type)) {\n response.setHeader(contentTypeKey, type);\n\n serializedData = yamlTransformer(hasJsonStructure(data) ? JSON.parse(data as string) : data);\n } else if (type.includes(\"xml\")) {\n response.setHeader(contentTypeKey, type);\n\n serializedData = xmlTransformer({\n [toHeaderCase(`${request.url?.replace(\"/api/\", \"\")}`.trim())]: hasJsonStructure(data) ? JSON.parse(data as string) : data,\n });\n }\n }\n });\n\n return serializedData as Buffer | Uint8Array | string;\n};\n\nexport default serialize;\n","const hasJsonStructure = (data: unknown): boolean => {\n if (typeof data !== \"string\") {\n return false;\n }\n\n try {\n const result = JSON.parse(data);\n const type = Object.prototype.toString.call(result);\n\n return type === \"[object Object]\" || type === \"[object Array]\";\n } catch {\n return false;\n }\n};\n\nexport default hasJsonStructure;\n","import type { XmlElement } from \"jstoxml\";\nimport xml from \"jstoxml\";\n\nimport type { Serializer } from \"../types\";\n\nconst xmlTransformer: Serializer = (data?: XmlElement | XmlElement[]) => xml.toXML(data, {\n header: true,\n indent: \" \",\n});\n\nexport default xmlTransformer;\n","import type { NextHandler } from \"@visulima/connect\";\nimport createHttpError from \"http-errors\";\nimport type { NextApiResponse } from \"next\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type { RateLimiterAbstract, RateLimiterRes } from \"rate-limiter-flexible\";\n\n// eslint-disable-next-line max-len\nconst getIP: (request: IncomingMessage & { ip?: string }) => string | undefined = (request) => request.ip\n ?? (request.headers[\"x-forwarded-for\"] as string | undefined)\n ?? (request.headers[\"x-real-ip\"] as string | undefined)\n ?? request.connection.remoteAddress;\n\ntype HeaderValue = ReadonlyArray<string> | number | string;\n\n// eslint-disable-next-line max-len\nconst rateLimiterMiddleware = (rateLimiter: RateLimiterAbstract, headers?: (limiterResponse: RateLimiterRes) => { [key: string]: HeaderValue }) => async <Request extends IncomingMessage, Response extends ServerResponse>(\n request: Request,\n response: NextApiResponse | Response,\n next: NextHandler,\n): Promise<void> => {\n const ip = getIP(request);\n\n if (ip === undefined) {\n throw createHttpError(400, \"Missing IP\");\n }\n\n try {\n const limiter = await rateLimiter.consume(ip);\n\n const mergedHeaders: { [key: string]: HeaderValue } = {\n \"Retry-After\": Math.round(limiter.msBeforeNext / 1000) || 1,\n \"X-RateLimit-Remaining\": limiter.remainingPoints,\n \"X-RateLimit-Reset\": new Date(Date.now() + limiter.msBeforeNext).toISOString(),\n ...headers,\n };\n\n Object.keys(mergedHeaders).forEach((key) => {\n response.setHeader(key, mergedHeaders[key] as HeaderValue);\n });\n\n await next();\n } catch {\n throw createHttpError(429, \"Too Many Requests\");\n }\n};\n\nexport default rateLimiterMiddleware;\n","import { expressWrapper } from \"@visulima/connect\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport type { CorsOptions, CorsOptionsDelegate } from \"cors\";\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport cors from \"cors\";\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\n\n// eslint-disable-next-line max-len,@typescript-eslint/explicit-module-boundary-types\nconst corsMiddleware = <Request extends IncomingMessage, Response extends ServerResponse>(options?: CorsOptions | CorsOptionsDelegate) => expressWrapper<Request, Response>(cors(options));\n\nexport default corsMiddleware;\n"]}
|
package/dist/index-server.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { a as dateIn, b as dateOut, c as zod } from './chunk-4ZTB2SHJ.mjs';
|
|
2
|
-
import { b, a } from './chunk-
|
|
3
|
-
export { c as swaggerHandler, b as yamlTransformer } from './chunk-
|
|
2
|
+
import { b, a } from './chunk-MAUWX6TE.mjs';
|
|
3
|
+
export { c as swaggerHandler, b as yamlTransformer } from './chunk-MAUWX6TE.mjs';
|
|
4
4
|
import './chunk-2ZMPKWQQ.mjs';
|
|
5
5
|
import k, { HttpError } from 'http-errors';
|
|
6
6
|
export { BadGateway, BadRequest, BandwidthLimitExceeded, Conflict, ExpectationFailed, FailedDependency, Forbidden, GatewayTimeout, Gone, HTTPVersionNotSupported, ImATeapot, InsufficientStorage, InternalServerError, LengthRequired, Locked, LoopDetected, MethodNotAllowed, MisdirectedRequest, NetworkAuthenticationRequire, NotAcceptable, NotExtended, NotFound, NotImplemented, PayloadTooLarge, PaymentRequired, PreconditionFailed, PreconditionRequired, ProxyAuthenticationRequired, RangeNotSatisfiable, RequestHeaderFieldsTooLarge, RequestTimeout, ServiceUnavailable, TooManyRequests, URITooLong, Unauthorized, UnavailableForLegalReasons, UnprocessableEntity, UnsupportedMediaType, UpgradeRequired, VariantAlsoNegotiates, default as createHttpError } from 'http-errors';
|