@scalar/nextjs-openapi 0.0.2

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 ADDED
@@ -0,0 +1,20 @@
1
+ # @scalar/nextjs-openapi
2
+
3
+ ## 0.0.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 48d7ad5: fix: repository URL in package.json
8
+ - @scalar/nextjs-api-reference@0.4.84
9
+
10
+ ## 0.0.1
11
+
12
+ ### Patch Changes
13
+
14
+ - cec10d5: fix(nextjs-openapi): convert next config back to js from ts
15
+ - 44e7e75: feat(nextjs-openapi): added next.js openapi generation integration
16
+ - Updated dependencies [44e7e75]
17
+ - Updated dependencies [89adf75]
18
+ - @scalar/nextjs-api-reference@0.4.84
19
+ - @scalar/ts-to-openapi@0.0.1
20
+ - @scalar/types@0.0.6
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023-present Scalar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,35 @@
1
+ # [PRE-ALPHA] Scalar Next.js API Reference Handler
2
+
3
+ [![Version](https://img.shields.io/npm/v/%40scalar/nextjs-openapi)](https://www.npmjs.com/package/@scalar/nextjs-openapi)
4
+ [![Downloads](https://img.shields.io/npm/dm/%40scalar/nextjs-openapi)](https://www.npmjs.com/package/@scalar/nextjs-openapi)
5
+ [![License](https://img.shields.io/npm/l/%40scalar%2fnextjs-openapi)](https://www.npmjs.com/package/@scalar/nextjs-openapi)
6
+ [![Discord](https://img.shields.io/discord/1135330207960678410?style=flat&color=5865F2)](https://discord.gg/scalar)
7
+
8
+ This plugin automatically generates an OpenAPI schema file based on a Next.js API.
9
+
10
+ <picture>
11
+ <source media="(prefers-color-scheme: dark)" srcset="https://github.com/scalar/scalar/assets/2039539/5837adad-a605-4edb-90ec-b929ff2b803b">
12
+ <source media="(prefers-color-scheme: light)" srcset="https://github.com/scalar/scalar/assets/2039539/4f58202d-f40f-47b3-aeaa-44681b424a45">
13
+ <img alt="Screenshot of an API Reference" src="https://github.com/scalar/scalar/assets/2039539/4f58202d-f40f-47b3-aeaa-44681b424a45">
14
+ </picture>
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm install @scalar/nextjs-openapi
20
+ ```
21
+
22
+ ## Usage
23
+
24
+ Currently this plugin is strictly for the app router with typescript. Currently we generate the spec from the Request/Context types as well as the returns in the HTTP method. You can find a simple example in the `playground` folder.
25
+
26
+ Also is currently under heavy development, all API's are likely to change. However we are looking for feedback! If you have an open API OR would like to share a private one, let us know so we can test the integration with it.
27
+
28
+ You just need to drop this file into the `app/api/openapi/[[...openapi]]` folder. You can rename the openapi folder to whatever you like but the dynamic folder must be catch-all as we will be serving two endpoints.
29
+
30
+ ```ts
31
+ // app/api/openapi/[[...slug]]/route.ts
32
+ import { OpenAPI } from '@scalar/nextjs-openapi'
33
+
34
+ export const GET = OpenAPI()
35
+ ```
@@ -0,0 +1,2 @@
1
+ export * from './openapi.js';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { OpenAPI } from './openapi.js';
@@ -0,0 +1,26 @@
1
+ import type { ReferenceConfiguration } from '@scalar/types/legacy';
2
+ import type { NextRequest } from 'next/server';
3
+ /**
4
+ * Scalar OpenAPI config
5
+ */
6
+ export type OpenAPIConfig = {
7
+ /**
8
+ * The base directory for your API files
9
+ * @default 'app/api'
10
+ */
11
+ apiDirectory?: string;
12
+ } & ReferenceConfiguration;
13
+ /**
14
+ * Scalar Next.js OpenAPI schema generation
15
+ *
16
+ * Handles both the schema generation as well as the references
17
+ *
18
+ * TODO:
19
+ * - Docs
20
+ * - file watcher
21
+ * - caching
22
+ */
23
+ export declare const OpenAPI: (config?: OpenAPIConfig) => {
24
+ GET: (req: NextRequest) => Promise<Response>;
25
+ };
26
+ //# sourceMappingURL=openapi.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openapi.d.ts","sourceRoot":"","sources":["../src/openapi.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAA;AAGlE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAa9C;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG;IAC1B;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAA;CACtB,GAAG,sBAAsB,CAAA;AAqC1B;;;;;;;;;GASG;AACH,eAAO,MAAM,OAAO,YAAY,aAAa;eAmCxB,WAAW;CAkB/B,CAAA"}
@@ -0,0 +1,86 @@
1
+ import { ApiReference } from '@scalar/nextjs-api-reference';
2
+ import { sync } from 'fast-glob';
3
+ import { readFileSync } from 'fs';
4
+ import { createSourceFile, ScriptTarget, ScriptKind, JSDocParsingMode, createProgram } from 'typescript';
5
+ import { getPathSchema } from './path.js';
6
+
7
+ // TODO switch to watcher
8
+ // @see https://github.com/microsoft/TypeScript-wiki/blob/main/Using-the-Compiler-API.md#writing-an-incremental-program-watcher
9
+ const compilerHost = {
10
+ fileExists: () => true,
11
+ getCanonicalFileName: (filename) => filename,
12
+ getCurrentDirectory: () => '',
13
+ getDefaultLibFileName: () => '',
14
+ getNewLine: () => '\n',
15
+ getSourceFile: (filename) => createSourceFile(filename, readFileSync(filename).toString(), ScriptTarget.Latest, false, ScriptKind.TS),
16
+ jsDocParsingMode: JSDocParsingMode.ParseAll,
17
+ readFile: () => undefined,
18
+ useCaseSensitiveFileNames: () => true,
19
+ writeFile: () => null,
20
+ };
21
+ /** OpenAPI 3.1.0 Spec */
22
+ const spec = {
23
+ openapi: '3.1.0',
24
+ info: {
25
+ title: `${process.env.npm_package_name} - Next.js OpenAPI Spec by Scalar`,
26
+ description: process.env.npm_package_description ||
27
+ 'This file has been autogenerated, check out the docs to see how to customize these options',
28
+ version: process.env.npm_package_version || '0.0.0',
29
+ },
30
+ paths: {},
31
+ };
32
+ /**
33
+ * Scalar Next.js OpenAPI schema generation
34
+ *
35
+ * Handles both the schema generation as well as the references
36
+ *
37
+ * TODO:
38
+ * - Docs
39
+ * - file watcher
40
+ * - caching
41
+ */
42
+ const OpenAPI = (config = {}) => {
43
+ const apiDirectory = config.apiDirectory ?? 'app/api';
44
+ /** All ts files required for the schema */
45
+ const programFileNames = sync(apiDirectory + '/**/*.ts');
46
+ /** Specific route files to generate paths */
47
+ const routeFileNames = sync(apiDirectory + '/**/route.ts');
48
+ const program = createProgram(programFileNames, {
49
+ noResolve: true,
50
+ target: ScriptTarget.Latest,
51
+ }, compilerHost);
52
+ // Loop over all non scalar files to extract openapi data using AST
53
+ routeFileNames.forEach((fileName) => {
54
+ const sourceFile = program.getSourceFile(fileName);
55
+ if (sourceFile) {
56
+ const resp = getPathSchema(sourceFile, program);
57
+ // Grab the path from the fileName
58
+ const rawPath = fileName
59
+ .replace(/^app|\/route\.ts$/g, '')
60
+ .replace(/\[/g, '{')
61
+ .replace(/]/g, '}');
62
+ const path = rawPath.startsWith('/') ? rawPath : '/' + rawPath;
63
+ spec.paths[path] = resp;
64
+ }
65
+ });
66
+ return {
67
+ GET: async (req) => {
68
+ // OpenAPI Schema JSON
69
+ if (req.nextUrl.pathname.endsWith('.json')) {
70
+ // Just grabbing the origin here but we can be smarter and look for the greatest common few segments
71
+ spec.servers = [{ url: req.nextUrl.origin }];
72
+ return Response.json(spec);
73
+ }
74
+ // References
75
+ else {
76
+ return await ApiReference({
77
+ spec: {
78
+ url: req.nextUrl.pathname + '/schema.json',
79
+ },
80
+ })();
81
+ }
82
+ },
83
+ };
84
+ };
85
+
86
+ export { OpenAPI };
package/dist/path.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import type { OpenAPIV3_1 } from 'openapi-types';
2
+ import { type Program, type SourceFile } from 'typescript';
3
+ /**
4
+ * Traverse the typescript file and extract as much info as we can for the openapi spec
5
+ */
6
+ export declare const getPathSchema: (sourceFile: SourceFile, program: Program) => OpenAPIV3_1.PathsObject<{}, {}>;
7
+ //# sourceMappingURL=path.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"path.d.ts","sourceRoot":"","sources":["../src/path.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAA;AAEhD,OAAO,EAGL,KAAK,OAAO,EACZ,KAAK,UAAU,EAOhB,MAAM,YAAY,CAAA;AAsDnB;;GAEG;AACH,eAAO,MAAM,aAAa,eAAgB,UAAU,WAAW,OAAO,oCAwCrE,CAAA"}
package/dist/path.js ADDED
@@ -0,0 +1,84 @@
1
+ import { getJSDocFromNode, generateResponses, getSchemaFromTypeNode } from '@scalar/ts-to-openapi';
2
+ import { extname, join } from 'path';
3
+ import { isFunctionDeclaration, isVariableStatement, isParameter, isTypeLiteralNode, isPropertySignature, isIdentifier } from 'typescript';
4
+
5
+ /** Check if identifier is a supported http method */
6
+ const checkForMethod = (identifier) => {
7
+ const method = identifier?.escapedText?.toLowerCase();
8
+ return method?.match(/^(get|post|put|patch|delete|head|options)$/)
9
+ ? method
10
+ : null;
11
+ };
12
+ const fileNameResolver = (source, target) => {
13
+ const sourceExt = extname(source);
14
+ const targetExt = extname(target);
15
+ const targetRelative = target + (targetExt ? '' : sourceExt);
16
+ const targetPath = join(source.replace(/\/([^/]+)$/, ''), targetRelative);
17
+ return targetPath;
18
+ };
19
+ /**
20
+ * Takes a parameter node and returns a path parameter schema
21
+ */
22
+ const extractPathParams = (node, program) => {
23
+ // Traverse to the params with type guards
24
+ if (node &&
25
+ isParameter(node) &&
26
+ node.type &&
27
+ isTypeLiteralNode(node.type) &&
28
+ node.type.members[0] &&
29
+ isPropertySignature(node.type.members[0]) &&
30
+ isIdentifier(node.type.members[0].name) &&
31
+ node.type.members[0].name.escapedText === 'params' &&
32
+ node.type.members[0].type &&
33
+ isTypeLiteralNode(node.type.members[0].type))
34
+ return node.type.members[0].type?.members.flatMap((member) => {
35
+ if (!isPropertySignature(member) || !member.type)
36
+ return [];
37
+ return {
38
+ name: member.name?.getText(),
39
+ schema: getSchemaFromTypeNode(member.type, program, fileNameResolver),
40
+ in: 'path',
41
+ };
42
+ });
43
+ return [];
44
+ };
45
+ /**
46
+ * Traverse the typescript file and extract as much info as we can for the openapi spec
47
+ */
48
+ const getPathSchema = (sourceFile, program) => {
49
+ const path = {};
50
+ const typeChecker = program.getTypeChecker();
51
+ sourceFile.statements.forEach((statement) => {
52
+ // Function
53
+ if (isFunctionDeclaration(statement) && statement.name) {
54
+ const method = checkForMethod(statement.name);
55
+ if (method) {
56
+ const { title, description } = getJSDocFromNode(statement);
57
+ const parameters = extractPathParams(statement.parameters[1], program);
58
+ const responses = generateResponses(statement.body, typeChecker);
59
+ path[method] = {
60
+ summary: title,
61
+ description,
62
+ parameters,
63
+ responses,
64
+ };
65
+ }
66
+ }
67
+ // TODO: variables
68
+ else if (isVariableStatement(statement)) {
69
+ const method = checkForMethod(statement.declarationList.declarations[0].name);
70
+ if (method) {
71
+ const { title, description } = getJSDocFromNode(statement);
72
+ const responses = generateResponses(statement, typeChecker);
73
+ path[method] = {
74
+ summary: title,
75
+ description,
76
+ responses,
77
+ };
78
+ }
79
+ }
80
+ });
81
+ return path;
82
+ };
83
+
84
+ export { getPathSchema };
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@scalar/nextjs-openapi",
3
+ "description": "Automatically generate an OpenAPI schema from a Nextjs API",
4
+ "license": "MIT",
5
+ "author": "Scalar (https://github.com/scalar)",
6
+ "homepage": "https://github.com/scalar/scalar",
7
+ "bugs": "https://github.com/scalar/scalar/issues/new/choose",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/scalar/scalar.git",
11
+ "directory": "packages/nextjs-openapi"
12
+ },
13
+ "keywords": [
14
+ "typescript",
15
+ "types",
16
+ "scalar",
17
+ "references"
18
+ ],
19
+ "version": "0.0.2",
20
+ "engines": {
21
+ "node": ">=18"
22
+ },
23
+ "type": "module",
24
+ "exports": {
25
+ ".": {
26
+ "import": "./dist/index.js",
27
+ "types": "./dist/index.d.ts"
28
+ }
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "CHANGELOG.md"
33
+ ],
34
+ "dependencies": {
35
+ "fast-glob": "^3.3.2",
36
+ "@scalar/nextjs-api-reference": "0.4.84",
37
+ "@scalar/types": "0.0.6",
38
+ "@scalar/ts-to-openapi": "0.0.1"
39
+ },
40
+ "devDependencies": {
41
+ "@types/node": "^20.14.10",
42
+ "@types/react": "^18.2.60",
43
+ "@types/react-dom": "^18.2.19",
44
+ "next": "^14.2.5",
45
+ "openapi-types": "^12.1.3",
46
+ "typescript": "^5.5.2",
47
+ "@scalar/build-tooling": "0.1.10"
48
+ },
49
+ "scripts": {
50
+ "build": "scalar-build-rollup",
51
+ "dev": "next dev playground -p 5066",
52
+ "lint:check": "eslint .",
53
+ "lint:fix": "eslint . --fix",
54
+ "types:build": "scalar-types-build",
55
+ "types:check": "scalar-types-check"
56
+ }
57
+ }