@scalar/mock-server 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 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,62 @@
1
+ # Scalar Mock Server
2
+
3
+ A server returning fake data based on an OpenAPI specification
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @scalar/mock-server
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```ts
14
+ import { serve } from '@hono/node-server'
15
+ import { createMockServer } from '@scalar/mock-server'
16
+
17
+ // Your OpenAPI specification
18
+ const openapi = {
19
+ openapi: '3.1.0',
20
+ info: {
21
+ title: 'Hello World',
22
+ version: '1.0.0',
23
+ },
24
+ paths: {
25
+ '/foobar': {
26
+ get: {
27
+ responses: {
28
+ '200': {
29
+ description: 'OK',
30
+ content: {
31
+ 'application/json': {
32
+ example: {
33
+ foo: 'bar',
34
+ },
35
+ },
36
+ },
37
+ },
38
+ },
39
+ },
40
+ },
41
+ },
42
+ }
43
+
44
+ // Create the mocked routes
45
+ const app = await createMockServer({
46
+ openapi,
47
+ onRequest({ context, operation }) {
48
+ console.log(context.req.method, context.req.path)
49
+ },
50
+ })
51
+
52
+ // Start the server
53
+ serve(
54
+ {
55
+ fetch: app.fetch,
56
+ port: 3000,
57
+ },
58
+ (info) => {
59
+ console.log(`Listening on http://localhost:${info.port}`)
60
+ },
61
+ )
62
+ ```
package/dist/index.js ADDED
@@ -0,0 +1,143 @@
1
+ import { getExampleFromSchema } from '@scalar/api-reference';
2
+ import { parse } from '@scalar/openapi-parser';
3
+ import { Hono } from 'hono';
4
+
5
+ /******************************************************************************
6
+ Copyright (c) Microsoft Corporation.
7
+
8
+ Permission to use, copy, modify, and/or distribute this software for any
9
+ purpose with or without fee is hereby granted.
10
+
11
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
12
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
14
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
16
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17
+ PERFORMANCE OF THIS SOFTWARE.
18
+ ***************************************************************************** */
19
+ /* global Reflect, Promise, SuppressedError, Symbol */
20
+
21
+
22
+ function __awaiter(thisArg, _arguments, P, generator) {
23
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
24
+ return new (P || (P = Promise))(function (resolve, reject) {
25
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
26
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
27
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
28
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
29
+ });
30
+ }
31
+
32
+ function __generator(thisArg, body) {
33
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
34
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
35
+ function verb(n) { return function (v) { return step([n, v]); }; }
36
+ function step(op) {
37
+ if (f) throw new TypeError("Generator is already executing.");
38
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
39
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
40
+ if (y = 0, t) op = [op[0] & 2, t.value];
41
+ switch (op[0]) {
42
+ case 0: case 1: t = op; break;
43
+ case 4: _.label++; return { value: op[1], done: false };
44
+ case 5: _.label++; y = op[1]; op = [0]; continue;
45
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
46
+ default:
47
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
48
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
49
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
50
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
51
+ if (t[2]) _.ops.pop();
52
+ _.trys.pop(); continue;
53
+ }
54
+ op = body.call(thisArg, _);
55
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
56
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
57
+ }
58
+ }
59
+
60
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
61
+ var e = new Error(message);
62
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
63
+ };
64
+
65
+ /**
66
+ * Normalize OpenAPI JSON string, YAML string … to object
67
+ */
68
+ function normalize(openapi) {
69
+ if (typeof openapi === 'string') {
70
+ openapi = JSON.parse(openapi);
71
+ }
72
+ return openapi;
73
+ }
74
+
75
+ /**
76
+ * Convert path to route
77
+ * Example: /posts/{id} -> /posts/:id
78
+ */
79
+ function routeFromPath(path) {
80
+ return path.replace(/{/g, ':').replace(/}/g, '');
81
+ }
82
+
83
+ /**
84
+ * Create a mock server instance
85
+ */
86
+ function createMockServer(options) {
87
+ var _a;
88
+ return __awaiter(this, void 0, void 0, function () {
89
+ var app, specification;
90
+ return __generator(this, function (_b) {
91
+ switch (_b.label) {
92
+ case 0:
93
+ app = new Hono();
94
+ // Normalize input
95
+ options.openapi = normalize(options.openapi);
96
+ return [4 /*yield*/, parse(options.openapi)
97
+ // OpenAPI file
98
+ ];
99
+ case 1:
100
+ specification = _b.sent();
101
+ // OpenAPI file
102
+ app.get('/openapi.json', function (c) {
103
+ if (!(options === null || options === void 0 ? void 0 : options.openapi)) {
104
+ return c.text('Not found', 404);
105
+ }
106
+ return c.json(options.openapi);
107
+ });
108
+ // Paths
109
+ Object.keys((_a = specification.document.paths) !== null && _a !== void 0 ? _a : {}).forEach(function (path) {
110
+ // Request methods
111
+ Object.keys(specification.document.paths[path]).forEach(function (method) {
112
+ var route = routeFromPath(path);
113
+ // Route
114
+ app[method](route, function (c) {
115
+ var _a, _b;
116
+ // Call onRequest callback
117
+ if (options === null || options === void 0 ? void 0 : options.onRequest) {
118
+ options.onRequest({
119
+ context: c,
120
+ operation: specification.document.paths[path][method],
121
+ });
122
+ }
123
+ // Response
124
+ var operation = specification.document.paths[path][method];
125
+ var jsonResponseConfiguration = (_b = (_a = operation.responses) === null || _a === void 0 ? void 0 : _a['200']) === null || _b === void 0 ? void 0 : _b.content['application/json'];
126
+ var response = (jsonResponseConfiguration === null || jsonResponseConfiguration === void 0 ? void 0 : jsonResponseConfiguration.example)
127
+ ? jsonResponseConfiguration.example
128
+ : (jsonResponseConfiguration === null || jsonResponseConfiguration === void 0 ? void 0 : jsonResponseConfiguration.schema)
129
+ ? getExampleFromSchema(jsonResponseConfiguration.schema, {
130
+ emptyString: '…',
131
+ })
132
+ : null;
133
+ return c.json(response);
134
+ });
135
+ });
136
+ });
137
+ return [2 /*return*/, app];
138
+ }
139
+ });
140
+ });
141
+ }
142
+
143
+ export { createMockServer, normalize, routeFromPath };
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@scalar/mock-server",
3
+ "description": "OpenAPI mock server server",
4
+ "license": "MIT",
5
+ "author": "Scalar (https://github.com/scalar)",
6
+ "homepage": "https://github.com/scalar/cli",
7
+ "bugs": "https://github.com/scalar/cli/issues/new/choose",
8
+ "keywords": [
9
+ "scalar",
10
+ "openapi",
11
+ "swagger",
12
+ "cli"
13
+ ],
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://github.com/scalar/cli.git",
17
+ "directory": "packages/mock-server"
18
+ },
19
+ "engines": {
20
+ "node": ">=18"
21
+ },
22
+ "main": "./dist/index.js",
23
+ "types": "dist/src/index.d.ts",
24
+ "exports": {
25
+ "import": "./dist/index.js"
26
+ },
27
+ "scripts": {
28
+ "test": "vitest",
29
+ "cli:link": "pnpm run build && npm unlink -g && npm link",
30
+ "types:check": "tsc --noEmit --skipLibCheck",
31
+ "build": "rm -Rf dist/ && tsc && rollup -c"
32
+ },
33
+ "type": "module",
34
+ "version": "0.0.2",
35
+ "files": [
36
+ "./dist"
37
+ ],
38
+ "dependencies": {
39
+ "@hono/node-server": "^1.7.0",
40
+ "@scalar/api-reference": "^1.16.1",
41
+ "@scalar/openapi-parser": "^0.1.0",
42
+ "hono": "^4.0.2",
43
+ "vite-node": "^1.2.2"
44
+ },
45
+ "devDependencies": {
46
+ "@rollup/plugin-json": "^6.1.0",
47
+ "@rollup/plugin-typescript": "^11.1.6",
48
+ "@types/node": "^20.11.17",
49
+ "execa": "^8.0.1",
50
+ "rollup": "^4.10.0",
51
+ "rollup-plugin-delete": "^2.0.0",
52
+ "strip-ansi": "^7.1.0",
53
+ "tslib": "^2.6.2",
54
+ "typescript": "^5.3.3"
55
+ }
56
+ }
@@ -0,0 +1,2 @@
1
+ export * from './lib';
2
+ export * from './utils';
@@ -0,0 +1,2 @@
1
+ export * from './lib';
2
+ export * from './utils';
@@ -0,0 +1,12 @@
1
+ import { OpenAPI } from '@scalar/openapi-parser';
2
+ import { type Context, Hono } from 'hono';
3
+ /**
4
+ * Create a mock server instance
5
+ */
6
+ export declare function createMockServer(options?: {
7
+ openapi: string | Record<string, any>;
8
+ onRequest?: (data: {
9
+ context: Context;
10
+ operation: OpenAPI.Operation;
11
+ }) => void;
12
+ }): Promise<Hono<import("hono").Env, import("hono/types").BlankSchema, "/">>;
@@ -0,0 +1,99 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ var __generator = (this && this.__generator) || function (thisArg, body) {
11
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
12
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
13
+ function verb(n) { return function (v) { return step([n, v]); }; }
14
+ function step(op) {
15
+ if (f) throw new TypeError("Generator is already executing.");
16
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
17
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
18
+ if (y = 0, t) op = [op[0] & 2, t.value];
19
+ switch (op[0]) {
20
+ case 0: case 1: t = op; break;
21
+ case 4: _.label++; return { value: op[1], done: false };
22
+ case 5: _.label++; y = op[1]; op = [0]; continue;
23
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
24
+ default:
25
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
26
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
27
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
28
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
29
+ if (t[2]) _.ops.pop();
30
+ _.trys.pop(); continue;
31
+ }
32
+ op = body.call(thisArg, _);
33
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
34
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
35
+ }
36
+ };
37
+ import { getExampleFromSchema } from '@scalar/api-reference';
38
+ import { parse } from '@scalar/openapi-parser';
39
+ import { Hono } from 'hono';
40
+ import { normalize, routeFromPath } from '../utils';
41
+ /**
42
+ * Create a mock server instance
43
+ */
44
+ export function createMockServer(options) {
45
+ var _a;
46
+ return __awaiter(this, void 0, void 0, function () {
47
+ var app, specification;
48
+ return __generator(this, function (_b) {
49
+ switch (_b.label) {
50
+ case 0:
51
+ app = new Hono();
52
+ // Normalize input
53
+ options.openapi = normalize(options.openapi);
54
+ return [4 /*yield*/, parse(options.openapi)
55
+ // OpenAPI file
56
+ ];
57
+ case 1:
58
+ specification = _b.sent();
59
+ // OpenAPI file
60
+ app.get('/openapi.json', function (c) {
61
+ if (!(options === null || options === void 0 ? void 0 : options.openapi)) {
62
+ return c.text('Not found', 404);
63
+ }
64
+ return c.json(options.openapi);
65
+ });
66
+ // Paths
67
+ Object.keys((_a = specification.document.paths) !== null && _a !== void 0 ? _a : {}).forEach(function (path) {
68
+ // Request methods
69
+ Object.keys(specification.document.paths[path]).forEach(function (method) {
70
+ var route = routeFromPath(path);
71
+ // Route
72
+ app[method](route, function (c) {
73
+ var _a, _b;
74
+ // Call onRequest callback
75
+ if (options === null || options === void 0 ? void 0 : options.onRequest) {
76
+ options.onRequest({
77
+ context: c,
78
+ operation: specification.document.paths[path][method],
79
+ });
80
+ }
81
+ // Response
82
+ var operation = specification.document.paths[path][method];
83
+ var jsonResponseConfiguration = (_b = (_a = operation.responses) === null || _a === void 0 ? void 0 : _a['200']) === null || _b === void 0 ? void 0 : _b.content['application/json'];
84
+ var response = (jsonResponseConfiguration === null || jsonResponseConfiguration === void 0 ? void 0 : jsonResponseConfiguration.example)
85
+ ? jsonResponseConfiguration.example
86
+ : (jsonResponseConfiguration === null || jsonResponseConfiguration === void 0 ? void 0 : jsonResponseConfiguration.schema)
87
+ ? getExampleFromSchema(jsonResponseConfiguration.schema, {
88
+ emptyString: '…',
89
+ })
90
+ : null;
91
+ return c.json(response);
92
+ });
93
+ });
94
+ });
95
+ return [2 /*return*/, app];
96
+ }
97
+ });
98
+ });
99
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,82 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ var __generator = (this && this.__generator) || function (thisArg, body) {
11
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
12
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
13
+ function verb(n) { return function (v) { return step([n, v]); }; }
14
+ function step(op) {
15
+ if (f) throw new TypeError("Generator is already executing.");
16
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
17
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
18
+ if (y = 0, t) op = [op[0] & 2, t.value];
19
+ switch (op[0]) {
20
+ case 0: case 1: t = op; break;
21
+ case 4: _.label++; return { value: op[1], done: false };
22
+ case 5: _.label++; y = op[1]; op = [0]; continue;
23
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
24
+ default:
25
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
26
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
27
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
28
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
29
+ if (t[2]) _.ops.pop();
30
+ _.trys.pop(); continue;
31
+ }
32
+ op = body.call(thisArg, _);
33
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
34
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
35
+ }
36
+ };
37
+ import { describe, expect, it } from 'vitest';
38
+ import { createMockServer } from './createMockServer';
39
+ describe('onRequest', function () {
40
+ it('call custom onRequest hook', function () { return __awaiter(void 0, void 0, void 0, function () {
41
+ return __generator(this, function (_a) {
42
+ return [2 /*return*/, new Promise(function (resolve) { return __awaiter(void 0, void 0, void 0, function () {
43
+ var openapi, server;
44
+ return __generator(this, function (_a) {
45
+ switch (_a.label) {
46
+ case 0:
47
+ openapi = {
48
+ openapi: '3.1.0',
49
+ info: {
50
+ title: 'Hello World',
51
+ version: '1.0.0',
52
+ },
53
+ paths: {
54
+ '/foobar': {
55
+ get: {
56
+ operationId: 'foobar',
57
+ },
58
+ },
59
+ },
60
+ };
61
+ return [4 /*yield*/, createMockServer({
62
+ openapi: openapi,
63
+ onRequest: function (_a) {
64
+ var context = _a.context, operation = _a.operation;
65
+ expect(context.req.method).toBe('GET');
66
+ expect(context.req.path).toBe('/foobar');
67
+ expect(operation.operationId).toBe('foobar');
68
+ resolve(null);
69
+ },
70
+ })];
71
+ case 1:
72
+ server = _a.sent();
73
+ return [4 /*yield*/, server.request('/foobar')];
74
+ case 2:
75
+ _a.sent();
76
+ return [2 /*return*/];
77
+ }
78
+ });
79
+ }); })];
80
+ });
81
+ }); });
82
+ });
@@ -0,0 +1 @@
1
+ export {};