@scalar/mock-server 0.18.0 → 0.19.0

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.
Files changed (39) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/create-asyncapi-mock-server.d.ts +4 -55
  3. package/dist/create-asyncapi-mock-server.d.ts.map +1 -1
  4. package/dist/create-asyncapi-mock-server.js +16 -22
  5. package/dist/create-mock-server.d.ts +4 -3
  6. package/dist/create-mock-server.d.ts.map +1 -1
  7. package/dist/create-mock-server.js +11 -227
  8. package/dist/create-openapi-mock-server.d.ts +10 -0
  9. package/dist/create-openapi-mock-server.d.ts.map +1 -0
  10. package/dist/create-openapi-mock-server.js +227 -0
  11. package/dist/index.d.ts +0 -2
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +0 -2
  14. package/dist/routes/respond-with-openapi-document.d.ts +1 -1
  15. package/dist/transports/types.d.ts +2 -2
  16. package/dist/types.d.ts +20 -8
  17. package/dist/types.d.ts.map +1 -1
  18. package/dist/utils/get-asyncapi-document.d.ts +4 -0
  19. package/dist/utils/get-asyncapi-document.d.ts.map +1 -0
  20. package/dist/utils/get-asyncapi-document.js +47 -0
  21. package/dist/utils/get-asyncapi-security-schemes.d.ts +4 -0
  22. package/dist/utils/get-asyncapi-security-schemes.d.ts.map +1 -0
  23. package/dist/utils/get-asyncapi-security-schemes.js +17 -0
  24. package/dist/utils/process-document.d.ts +13 -0
  25. package/dist/utils/process-document.d.ts.map +1 -0
  26. package/dist/utils/{process-openapi-document.js → process-document.js} +18 -26
  27. package/dist/utils/resolve-channels.d.ts.map +1 -1
  28. package/dist/utils/resolve-channels.js +32 -19
  29. package/dist/utils/resolve-server-pathnames.d.ts +4 -0
  30. package/dist/utils/resolve-server-pathnames.d.ts.map +1 -0
  31. package/dist/utils/resolve-server-pathnames.js +14 -0
  32. package/dist/utils/set-up-asyncapi-authentication-routes.d.ts.map +1 -1
  33. package/dist/utils/set-up-asyncapi-authentication-routes.js +2 -14
  34. package/package.json +7 -7
  35. package/dist/utils/process-asyncapi-document.d.ts +0 -24
  36. package/dist/utils/process-asyncapi-document.d.ts.map +0 -1
  37. package/dist/utils/process-asyncapi-document.js +0 -64
  38. package/dist/utils/process-openapi-document.d.ts +0 -19
  39. package/dist/utils/process-openapi-document.d.ts.map +0 -1
@@ -0,0 +1,227 @@
1
+ import { normalize } from '@scalar/json-magic/helpers/normalize';
2
+ import { getRaw } from '@scalar/json-magic/magic-proxy';
3
+ import { getResolvedRef, mergeSiblingReferences } from '@scalar/workspace-store/helpers/get-resolved-ref';
4
+ import { Hono } from 'hono';
5
+ import { every } from 'hono/combine';
6
+ import { cors } from 'hono/cors';
7
+ import { buildSeedContext } from './utils/build-seed-context.js';
8
+ import { executeSeed } from './utils/execute-seed.js';
9
+ import { getOperations } from './utils/get-operation.js';
10
+ import { handleAuthentication } from './utils/handle-authentication.js';
11
+ import { honoRouteFromPath } from './utils/hono-route-from-path.js';
12
+ import { isAuthenticationRequired } from './utils/is-authentication-required.js';
13
+ import { logAuthenticationInstructions } from './utils/log-authentication-instructions.js';
14
+ import { requestMatchesPinnedQuery } from './utils/request-matches-pinned-query.js';
15
+ import { resolveLogger } from './utils/resolve-logger.js';
16
+ import { setUpAuthenticationRoutes } from './utils/set-up-authentication-routes.js';
17
+ import { splitPathKey } from './utils/split-path-key.js';
18
+ import { validateRequest } from './utils/validate-request.js';
19
+ import { store } from './libs/store.js';
20
+ import { mockAnyResponse } from './routes/mock-any-response.js';
21
+ import { mockHandlerResponse } from './routes/mock-handler-response.js';
22
+ import { respondWithOpenApiDocument } from './routes/respond-with-openapi-document.js';
23
+ /** Record which operation a request matched, so an error escaping it can be named */
24
+ const setMockedOperation = (c, operation) => {
25
+ ;
26
+ c.set('mockedOperation', operation);
27
+ };
28
+ /** Read back the operation a request matched, or `undefined` when it reached no mocked route */
29
+ const getMockedOperation = (c) => c.get('mockedOperation');
30
+ /**
31
+ * Whether an error carries its own response, the way Hono's `HTTPException` does.
32
+ *
33
+ * Checked structurally rather than with `instanceof`, exactly like Hono's own default handler, so an
34
+ * `HTTPException` thrown from a second copy of Hono is still recognized.
35
+ */
36
+ const carriesResponse = (error) => 'getResponse' in error && typeof error.getResponse === 'function';
37
+ /**
38
+ * Create a mock server instance
39
+ */
40
+ export const createOpenApiMockServer = async (configuration, schema) => {
41
+ const app = new Hono();
42
+ // Unhandled errors would otherwise reach Hono's default handler, which answers with a plain-text
43
+ // `Internal Server Error` that says nothing about what broke. A mock server fails for mundane,
44
+ // document-shaped reasons — a response header name the runtime rejects, an example that cannot be
45
+ // serialized — so answer with JSON that names the failing operation and repeats the message,
46
+ // which makes the failure readable in the response instead of something to go reproduce.
47
+ app.onError((error, c) => {
48
+ // The status and body such an error chose are deliberate, not an internal failure, so answer
49
+ // with them. Unlike Hono's default handler, which returns the response directly, it is rebuilt
50
+ // through the context so headers already staged on the response — those from the CORS
51
+ // middleware, most of all — still apply.
52
+ if (carriesResponse(error)) {
53
+ const response = error.getResponse();
54
+ return c.newResponse(response.body, response);
55
+ }
56
+ const operation = getMockedOperation(c);
57
+ // Keep logging the error, as Hono's default handler does, so the stack trace is not lost. Routes
58
+ // added to the returned app are not mocked operations, so name the concrete request instead —
59
+ // the log always points somewhere.
60
+ console.error(operation
61
+ ? `Error while mocking ${operation.method} ${operation.path}:`
62
+ : `Error handling ${c.req.method} ${c.req.path}:`, error);
63
+ return c.json({
64
+ error: 'Internal Server Error',
65
+ message: error.message,
66
+ // Left out entirely rather than sent as `null`, so a client can test for the key.
67
+ ...(operation ? { operation } : {}),
68
+ }, 500);
69
+ });
70
+ const input = configuration?.document ?? configuration?.specification;
71
+ const sourceDocument = typeof input === 'string' ? normalize(input) : input;
72
+ // Source locations need a bundled export so relative references remain usable outside the server.
73
+ const exportDocument = configuration?.origin ||
74
+ (typeof input === 'string' && (sourceDocument === null || typeof sourceDocument !== 'object'))
75
+ ? getRaw(schema)
76
+ : input;
77
+ // Seed data from schemas with x-seed extension
78
+ // This happens before routes are set up so data is available immediately
79
+ const schemas = schema?.components?.schemas;
80
+ if (schemas) {
81
+ for (const [schemaName, schemaObject] of Object.entries(schemas)) {
82
+ // Merge `$ref` siblings so an `x-seed` placed next to a `$ref` is preserved (OpenAPI 3.1 semantics)
83
+ const seedCode = getResolvedRef(schemaObject, mergeSiblingReferences)?.['x-seed'];
84
+ if (seedCode && typeof seedCode === 'string') {
85
+ try {
86
+ // Check if collection is empty (idempotent seeding)
87
+ // Use the schema key directly as the collection name
88
+ const existingItems = store.list(schemaName);
89
+ if (existingItems.length === 0) {
90
+ // Build seed context with schema key (used as collection name)
91
+ const seedContext = buildSeedContext(schemaName);
92
+ // Execute seed code
93
+ await executeSeed(seedCode, seedContext);
94
+ }
95
+ }
96
+ catch (error) {
97
+ // Log error but don't fail server startup
98
+ console.error(`Error seeding schema "${schemaName}":`, error);
99
+ }
100
+ }
101
+ }
102
+ }
103
+ // CORS headers
104
+ const allowedMethods = new Set(['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH', 'QUERY']);
105
+ for (const pathItem of Object.values(schema?.paths ?? {})) {
106
+ for (const method of Object.keys(getOperations(getResolvedRef(pathItem)))) {
107
+ allowedMethods.add(method);
108
+ }
109
+ }
110
+ app.use(cors({ origin: '*', allowMethods: [...allowedMethods], exposeHeaders: ['X-Scalar-XML-Error'] }));
111
+ /** Authentication methods defined in the OpenAPI document */
112
+ setUpAuthenticationRoutes(app, schema);
113
+ // Only the instructions honor `logger` (on by default); the util still prints warnings and errors
114
+ // about security schemes the mock server cannot handle, which a silenced startup should surface.
115
+ logAuthenticationInstructions(schema?.components?.securitySchemes || {}, resolveLogger(configuration.logger, true));
116
+ /** Paths specified in the OpenAPI document */
117
+ const paths = schema?.paths ?? {};
118
+ // A path key may pin query parameters to describe a variant of an operation, for example
119
+ // `/v1/messages?beta=true` next to `/v1/messages`. Hono runs every matching route in registration
120
+ // order, so a variant has to come before the sibling it shares a path with — otherwise the sibling
121
+ // answers its requests too, and the more pinned parameters a key has the more specific it is.
122
+ const pathKeys = Object.keys(paths).map((path) => {
123
+ const { path: pathname, query } = splitPathKey(path);
124
+ return { path, pathname, query };
125
+ });
126
+ /** Where each path first shows up in the document, so its variants stay with it */
127
+ const documentOrder = new Map();
128
+ pathKeys.forEach(({ pathname }, index) => {
129
+ if (!documentOrder.has(pathname)) {
130
+ documentOrder.set(pathname, index);
131
+ }
132
+ });
133
+ // Keys that share a path are grouped where the first of them appears and the most specific one
134
+ // leads the group; a key with a path of its own never moves. So the only keys that change places
135
+ // with anything unrelated are the variants of a path that is described more than once. When two
136
+ // distinct paths overlap — a literal and a parameterized one that pins a query — neither is moved,
137
+ // so whichever the document declares first is matched first, the same as any pair of overlapping
138
+ // Hono routes.
139
+ const orderedPathKeys = [...pathKeys].sort((a, b) => (documentOrder.get(a.pathname) ?? 0) - (documentOrder.get(b.pathname) ?? 0) || b.query.length - a.query.length);
140
+ orderedPathKeys.forEach(({ path, query }) => {
141
+ // A path item may itself be a `$ref`, so resolve it before reading its operations.
142
+ const pathItem = getResolvedRef(paths[path]);
143
+ const operations = getOperations(pathItem);
144
+ /** Keys for all operations of a specified path */
145
+ Object.entries(operations).forEach(([method, operation]) => {
146
+ const route = honoRouteFromPath(path);
147
+ // Remember which operation this route mocks, so the error handler can name it when something
148
+ // fails downstream. Recorded on the context rather than mapped back from the request path,
149
+ // which would not survive the app being mounted under a base path. Registered before the rest
150
+ // of the route so a failure in request validation is named too. The OpenAPI path key is kept
151
+ // (rather than the Hono route) because that is what the document author reads.
152
+ const mockedOperation = {
153
+ method,
154
+ path,
155
+ ...(operation?.operationId ? { operationId: operation.operationId } : {}),
156
+ };
157
+ /** Middleware chain answering this operation, in the order it runs */
158
+ const handlers = [];
159
+ // Runs first, so the error handler can name the operation even when validation fails. For a
160
+ // path key that pins a query it is part of the guarded chain below, so it only fires once the
161
+ // request actually matches the variant rather than for one that is handed on to the sibling.
162
+ handlers.push(async (c, next) => {
163
+ setMockedOperation(c, mockedOperation);
164
+ await next();
165
+ });
166
+ // Operation-level security overrides the global requirement, so fall back to the
167
+ // document-wide `security` when the operation does not define its own.
168
+ const effectiveSecurity = operation.security ?? schema?.security;
169
+ // Check if authentication is required for this operation
170
+ if (isAuthenticationRequired(effectiveSecurity)) {
171
+ handlers.push(handleAuthentication(schema, operation));
172
+ }
173
+ // Notify the `onRequest` callback before validation runs, so it fires for every request —
174
+ // including ones the validation middleware rejects with a `422`.
175
+ if (configuration.onRequest) {
176
+ handlers.push(async (c, next) => {
177
+ configuration.onRequest?.({ context: c, operation });
178
+ await next();
179
+ });
180
+ }
181
+ // Validate the incoming request against the operation contract (on by default;
182
+ // opt out with `validateRequest: false`). Runs after authentication but before the
183
+ // mock handler. Validators are compiled once here, so there is no per-request recompilation.
184
+ if (configuration.validateRequest !== false) {
185
+ handlers.push(validateRequest(operation, pathItem?.parameters));
186
+ }
187
+ // Check if operation has x-handler extension
188
+ // Validate that it's a non-empty string (consistent with x-seed validation)
189
+ const handlerCode = operation?.['x-handler'];
190
+ const hasHandler = handlerCode && typeof handlerCode === 'string' && handlerCode.trim().length > 0;
191
+ // Route to appropriate handler
192
+ if (hasHandler) {
193
+ handlers.push(async (c) => await mockHandlerResponse(c, operation, pathItem?.parameters, schema.openapi));
194
+ }
195
+ else {
196
+ handlers.push(async (c) => await mockAnyResponse(c, operation, schema.openapi));
197
+ }
198
+ // The pinned query parameters are not part of the route, so they are checked here. A request
199
+ // that does not carry them is handed on to the next matching route — usually the sibling path
200
+ // key without the query string.
201
+ const operationChain = every(...handlers);
202
+ // Hono uppercases methods during registration. Match the original method ourselves so
203
+ // additional operations such as COPY and copy remain distinct.
204
+ const register = (handler) => {
205
+ if (method === method.toUpperCase()) {
206
+ app.on(method, route, handler);
207
+ }
208
+ else {
209
+ app.all(route, handler);
210
+ }
211
+ };
212
+ register(async (c, next) => {
213
+ if ((c.req.method !== method && !(method === 'GET' && c.req.method === 'HEAD')) ||
214
+ !requestMatchesPinnedQuery(c, query)) {
215
+ await next();
216
+ return;
217
+ }
218
+ await operationChain(c, next);
219
+ });
220
+ });
221
+ });
222
+ // OpenAPI JSON file
223
+ app.get('/openapi.json', (c) => respondWithOpenApiDocument(c, exportDocument, 'json'));
224
+ // OpenAPI YAML file
225
+ app.get('/openapi.yaml', (c) => respondWithOpenApiDocument(c, exportDocument, 'yaml'));
226
+ return app;
227
+ };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,5 @@
1
- export { type AsyncApiMockServer, type AsyncApiMockServerOptions, createAsyncApiMockServer, } from './create-asyncapi-mock-server.js';
2
1
  export { createMockServer } from './create-mock-server.js';
3
2
  export { defaultTransports, sseTransport, websocketTransport } from './transports/index.js';
4
3
  export type { MessageDirection, MockMessage, MockTransport, ResolvedChannel, ResolvedMessage, ResolvedOperation, TransportContext, } from './transports/types.js';
5
4
  export type { MockServerLogger, MockServerOptions } from './types.js';
6
- export { isAsyncApiDocument } from './utils/process-asyncapi-document.js';
7
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,kBAAkB,EACvB,KAAK,yBAAyB,EAC9B,wBAAwB,GACzB,MAAM,+BAA+B,CAAA;AACtC,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAA;AACvD,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAA;AAClF,YAAY,EACV,gBAAgB,EAChB,WAAW,EACX,aAAa,EACb,eAAe,EACf,eAAe,EACf,iBAAiB,EACjB,gBAAgB,GACjB,MAAM,oBAAoB,CAAA;AAC3B,YAAY,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAA;AAClE,OAAO,EAAE,kBAAkB,EAAE,MAAM,mCAAmC,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAA;AACvD,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAA;AAClF,YAAY,EACV,gBAAgB,EAChB,WAAW,EACX,aAAa,EACb,eAAe,EACf,eAAe,EACf,iBAAiB,EACjB,gBAAgB,GACjB,MAAM,oBAAoB,CAAA;AAC3B,YAAY,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAA"}
package/dist/index.js CHANGED
@@ -1,4 +1,2 @@
1
- export { createAsyncApiMockServer, } from './create-asyncapi-mock-server.js';
2
1
  export { createMockServer } from './create-mock-server.js';
3
2
  export { defaultTransports, sseTransport, websocketTransport } from './transports/index.js';
4
- export { isAsyncApiDocument } from './utils/process-asyncapi-document.js';
@@ -2,7 +2,7 @@ import type { Context } from 'hono';
2
2
  /**
3
3
  * OpenAPI endpoints
4
4
  */
5
- export declare function respondWithOpenApiDocument(c: Context, input?: string | Record<string, any>, format?: 'json' | 'yaml'): (Response & import("hono").TypedResponse<"Not found", 404, "text">) | (Response & import("hono").TypedResponse<import("hono/utils/types").JSONValue, import("hono/utils/http-status").ContentfulStatusCode, "json">) | (Response & import("hono").TypedResponse<string, 200, "text">) | (Response & import("hono").TypedResponse<{
5
+ export declare function respondWithOpenApiDocument(c: Context, input?: string | Record<string, any>, format?: 'json' | 'yaml'): (Response & import("hono").TypedResponse<string, 200, "text">) | (Response & import("hono").TypedResponse<"Not found", 404, "text">) | (Response & import("hono").TypedResponse<import("hono/utils/types").JSONValue, import("hono/utils/http-status").ContentfulStatusCode, "json">) | (Response & import("hono").TypedResponse<{
6
6
  error: string;
7
7
  message: string;
8
8
  }, 500, "json">) | (Response & import("hono").TypedResponse<{
@@ -70,7 +70,7 @@ export type TransportContext = {
70
70
  /** The Hono app. HTTP-based transports (SSE, SignalR negotiate) register routes here. */
71
71
  app: Hono;
72
72
  /**
73
- * Hono's WebSocket upgrade helper, bound to the Node adapter. Upgrade-based transports
73
+ * Hono's WebSocket upgrade helper, bound to the host runtime. Upgrade-based transports
74
74
  * (WebSocket, SignalR) register sockets via `app.get(route, upgradeWebSocket(...))`.
75
75
  */
76
76
  upgradeWebSocket: UpgradeWebSocket;
@@ -91,7 +91,7 @@ export type TransportContext = {
91
91
  /**
92
92
  * A pluggable transport that knows how to serve a class of AsyncAPI channels (by protocol).
93
93
  * Built-in transports cover WebSocket and SSE; consumers can append their own (e.g. SignalR)
94
- * via {@link AsyncApiMockServerOptions.transports} without changing the core.
94
+ * via {@link MockServerOptions.transports} without changing the core.
95
95
  */
96
96
  export type MockTransport = {
97
97
  /** Unique transport id, e.g. `websocket`, `sse`. */
package/dist/types.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import type { OpenAPIV3_1 } from '@scalar/openapi-types';
2
2
  import type { Context } from 'hono';
3
+ import type { UpgradeWebSocket } from 'hono/ws';
4
+ import type { MessageDirection, MockTransport } from './transports/types.js';
3
5
  /** Available HTTP methods for Hono routes */
4
6
  export declare const httpMethods: readonly ["get", "put", "post", "delete", "options", "patch"];
5
7
  /**
@@ -11,29 +13,39 @@ type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<T, Exclude<keyo
11
13
  /** A sink for the informational log lines the mock servers print while starting up. */
12
14
  export type MockServerLogger = (line: string) => void;
13
15
  type BaseMockServerOptions = {
16
+ /** Runtime adapter for AsyncAPI WebSocket channels. It must invoke onOpen after accepting a connection. */
17
+ upgradeWebSocket?: UpgradeWebSocket;
18
+ /** Additional AsyncAPI transports, tried after the built-in WebSocket and SSE transports. */
19
+ transports?: MockTransport[];
20
+ /** Observe messages flowing through AsyncAPI channels. */
21
+ onMessage?: (event: {
22
+ channel: string;
23
+ direction: MessageDirection;
24
+ payload: unknown;
25
+ }) => void;
14
26
  /** Source file path or URL used to resolve relative references in an already loaded document. */
15
27
  origin?: string;
16
28
  /**
17
- * The OpenAPI document to use for mocking.
18
- * Can be a string (URL or file path) or an object.
29
+ * The OpenAPI or AsyncAPI document to use for mocking.
30
+ * Can be an object, inline JSON/YAML, a URL, or a file path.
19
31
  *
20
32
  * @deprecated Use `document` instead
21
33
  */
22
34
  specification?: string | Record<string, any>;
23
35
  /**
24
- * The OpenAPI document to use for mocking.
25
- * Can be a string (URL or file path) or an object.
36
+ * The OpenAPI or AsyncAPI document to use for mocking.
37
+ * Can be an object, inline JSON/YAML, a URL, or a file path.
26
38
  */
27
39
  document?: string | Record<string, any>;
28
40
  /**
29
- * Callback function to be called before each request is processed.
41
+ * Callback function called before each OpenAPI request is processed.
30
42
  */
31
43
  onRequest?: (data: {
32
44
  context: Context;
33
45
  operation: OpenAPIV3_1.OperationObject;
34
46
  }) => void;
35
47
  /**
36
- * Validate the incoming request against the matched operation's schema. When the request
48
+ * Validate the incoming OpenAPI request against the matched operation's schema. When the request
37
49
  * violates the contract, the server responds with `422` and a `application/problem+json`
38
50
  * body describing the violations, instead of returning a mock response.
39
51
  *
@@ -47,8 +59,8 @@ type BaseMockServerOptions = {
47
59
  validateRequest?: boolean;
48
60
  /**
49
61
  * Control the informational output the server prints while starting up, which is currently the
50
- * authentication instructions for the security schemes of the document. Defaults to logging to
51
- * the console.
62
+ * authentication instructions for OpenAPI and transport lifecycle lines for AsyncAPI.
63
+ * Defaults to console logging for OpenAPI and silence for AsyncAPI.
52
64
  *
53
65
  * Pass `false` to silence it — handy when the mock server runs inside a test harness or another
54
66
  * program, where the instructions are noise — or a `(line) => void` sink to route the lines
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AACxD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAEnC,6CAA6C;AAC7C,eAAO,MAAM,WAAW,+DAAgE,CAAA;AAExF;;GAEG;AACH,KAAK,iBAAiB,CAAC,CAAC,EAAE,IAAI,S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G,CAAC,CAAA;IAEvC;;OAEG;IACH,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,SAAS,EAAE,WAAW,CAAC,eAAe,CAAA;KAAE,KAAK,IAAI,CAAA;IAExF;;;;;;;;;;;OAWG;IACH,eAAe,CAAC,EAAE,OAAO,CAAA;IAEzB;;;;;;;;;;;OAWG;IACH,MAAM,CAAC,EAAE,OAAO,GAAG,gBAAgB,CAAA;CACpC,CAAA;AAED,MAAM,MAAM,iBAAiB,GAAG,iBAAiB,CAAC,qBAAqB,EAAE,eAAe,GAAG,UAAU,CAAC,CAAA"}
@@ -0,0 +1,4 @@
1
+ import type { AsyncApiDocument } from '@scalar/types/asyncapi/3.1';
2
+ /** Serve a separate document for each mock origin without mutating the loaded API description. */
3
+ export declare const getAsyncApiDocument: (document: AsyncApiDocument, url: string) => AsyncApiDocument;
4
+ //# sourceMappingURL=get-asyncapi-document.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"get-asyncapi-document.d.ts","sourceRoot":"","sources":["../../src/utils/get-asyncapi-document.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAA;AAKlE,kGAAkG;AAClG,eAAO,MAAM,mBAAmB,GAAI,UAAU,gBAAgB,EAAE,KAAK,MAAM,KAAG,gBAmC7E,CAAA"}
@@ -0,0 +1,47 @@
1
+ import { createMagicProxy, getRaw } from '@scalar/json-magic/magic-proxy';
2
+ import { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref';
3
+ import { getAsyncApiSecuritySchemes } from './get-asyncapi-security-schemes.js';
4
+ /** Serve a separate document for each mock origin without mutating the loaded API description. */
5
+ export const getAsyncApiDocument = (document, url) => {
6
+ const origin = new URL(url);
7
+ const copy = createMagicProxy(structuredClone(getRaw(document)));
8
+ for (const rawServer of Object.values(copy.servers ?? {})) {
9
+ const server = getResolvedRef(rawServer);
10
+ if (!server)
11
+ continue;
12
+ const protocol = server.protocol.toLowerCase();
13
+ if (!['ws', 'wss', 'http', 'https', 'sse'].includes(protocol))
14
+ continue;
15
+ server.host = origin.host;
16
+ server.protocol =
17
+ protocol === 'ws' || protocol === 'wss'
18
+ ? origin.protocol === 'https:'
19
+ ? 'wss'
20
+ : 'ws'
21
+ : protocol === 'sse'
22
+ ? 'sse'
23
+ : origin.protocol.slice(0, -1);
24
+ }
25
+ const rebase = (value) => {
26
+ const endpoint = new URL(value, origin);
27
+ return new URL(`${endpoint.pathname}${endpoint.search}${endpoint.hash}`, origin).href;
28
+ };
29
+ for (const scheme of getAsyncApiSecuritySchemes(copy)) {
30
+ if (scheme?.type === 'openIdConnect' && scheme.openIdConnectUrl)
31
+ scheme.openIdConnectUrl = rebase(scheme.openIdConnectUrl);
32
+ if (scheme?.type !== 'oauth2')
33
+ continue;
34
+ for (const rawFlow of Object.values(getResolvedRef(scheme.flows) ?? {})) {
35
+ const flow = getResolvedRef(rawFlow);
36
+ if (!flow)
37
+ continue;
38
+ if (flow.authorizationUrl)
39
+ flow.authorizationUrl = rebase(flow.authorizationUrl);
40
+ if (flow.tokenUrl)
41
+ flow.tokenUrl = rebase(flow.tokenUrl);
42
+ if (flow.refreshUrl)
43
+ flow.refreshUrl = rebase(flow.refreshUrl);
44
+ }
45
+ }
46
+ return getRaw(copy);
47
+ };
@@ -0,0 +1,4 @@
1
+ import type { AsyncApiDocument, AsyncApiSecuritySchemeObject } from '@scalar/types/asyncapi/3.1';
2
+ /** Collect component and inline security schemes, including operation traits. */
3
+ export declare const getAsyncApiSecuritySchemes: (document: AsyncApiDocument) => Array<AsyncApiSecuritySchemeObject | undefined>;
4
+ //# sourceMappingURL=get-asyncapi-security-schemes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"get-asyncapi-security-schemes.d.ts","sourceRoot":"","sources":["../../src/utils/get-asyncapi-security-schemes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,4BAA4B,EAAE,MAAM,4BAA4B,CAAA;AAGhG,iFAAiF;AACjF,eAAO,MAAM,0BAA0B,GACrC,UAAU,gBAAgB,KACzB,KAAK,CAAC,4BAA4B,GAAG,SAAS,CAchD,CAAA"}
@@ -0,0 +1,17 @@
1
+ import { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref';
2
+ /** Collect component and inline security schemes, including operation traits. */
3
+ export const getAsyncApiSecuritySchemes = (document) => {
4
+ const components = getResolvedRef(document.components);
5
+ // AsyncAPI also permits inline schemes on servers, operations, and operation traits.
6
+ return [
7
+ ...Object.values(components?.securitySchemes ?? {}),
8
+ ...Object.values(document.servers ?? {}).flatMap((server) => getResolvedRef(server)?.security ?? []),
9
+ ...Object.values(document.operations ?? {}).flatMap((rawOperation) => {
10
+ const operation = getResolvedRef(rawOperation);
11
+ return [
12
+ ...(operation?.security ?? []),
13
+ ...(operation?.traits ?? []).flatMap((trait) => getResolvedRef(trait)?.security ?? []),
14
+ ];
15
+ }),
16
+ ].map((scheme) => getResolvedRef(scheme));
17
+ };
@@ -0,0 +1,13 @@
1
+ import type { OpenAPIV3_1, OpenAPIV3_2 } from '@scalar/openapi-types';
2
+ import type { AsyncApiDocument } from '@scalar/types/asyncapi/3.1';
3
+ /** A processed API description, tagged so each mock engine receives its own document type. */
4
+ export type ProcessedDocument = {
5
+ type: 'openapi';
6
+ document: OpenAPIV3_1.Document | OpenAPIV3_2.Document;
7
+ } | {
8
+ type: 'asyncapi';
9
+ document: AsyncApiDocument;
10
+ };
11
+ /** Bundle API descriptions once, retaining AsyncAPI and upgrading compatible OpenAPI input. */
12
+ export declare const processDocument: (document: string | Record<string, unknown> | undefined, origin?: string) => Promise<ProcessedDocument>;
13
+ //# sourceMappingURL=process-document.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process-document.d.ts","sourceRoot":"","sources":["../../src/utils/process-document.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AAErE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAA;AAGlE,8FAA8F;AAC9F,MAAM,MAAM,iBAAiB,GACzB;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,QAAQ,EAAE,WAAW,CAAC,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAA;CAAE,GAC1E;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,QAAQ,EAAE,gBAAgB,CAAA;CAAE,CAAA;AAEpD,+FAA+F;AAC/F,eAAO,MAAM,eAAe,GAC1B,UAAU,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EACtD,SAAS,MAAM,KACd,OAAO,CAAC,iBAAiB,CAyE3B,CAAA"}
@@ -1,5 +1,6 @@
1
1
  import path from 'node:path';
2
2
  import { cwd } from 'node:process';
3
+ import { isObjectLike } from '@scalar/helpers/object/is-object';
3
4
  import { bundle } from '@scalar/json-magic/bundle';
4
5
  import { fetchUrls, parseJson, parseYaml, readFiles } from '@scalar/json-magic/bundle/plugins/node';
5
6
  import { isFilePath } from '@scalar/json-magic/helpers/is-file-path';
@@ -7,33 +8,21 @@ import { isHttpUrl } from '@scalar/json-magic/helpers/is-http-url';
7
8
  import { createMagicProxy } from '@scalar/json-magic/magic-proxy';
8
9
  import { upgrade } from '@scalar/openapi-upgrader';
9
10
  import { openApiDocument, resolveOpenApiDocument } from '@scalar/workspace-store/plugins/bundler';
10
- /**
11
- * Processes an OpenAPI document by bundling external references, upgrading compatible input to OpenAPI 3.2,
12
- * and wrapping it so internal references stay intact but resolve lazily.
13
- *
14
- * Unlike a full dereference, the returned document keeps `$ref` nodes in place. Consumers
15
- * resolve them on demand with `getResolvedRef` from `@scalar/workspace-store`, which reads the
16
- * `$ref-value` exposed by the magic proxy. This avoids eagerly flattening (and duplicating)
17
- * the whole document up front.
18
- *
19
- * Compatibility failures retain the OpenAPI 3.1 document and its version, without applying partial migrations.
20
- *
21
- * @param document - The OpenAPI document to process. Can be a string (URL/path) or an object.
22
- * @param origin - Source file path or URL for resolving references in an already loaded document.
23
- * @returns A promise that resolves to the document with lazily resolvable references.
24
- * @throws Error if the document cannot be processed or is invalid.
25
- */
26
- export async function processOpenApiDocument(document, origin) {
11
+ /** Bundle API descriptions once, retaining AsyncAPI and upgrading compatible OpenAPI input. */
12
+ export const processDocument = async (document, origin) => {
27
13
  // Handle empty/undefined input gracefully
28
14
  if (!document || (typeof document === 'object' && Object.keys(document).length === 0)) {
29
15
  // Return a minimal valid OpenAPI 3.2 document
30
16
  return {
31
- openapi: '3.2.0',
32
- info: {
33
- title: 'Mock API',
34
- version: '1.0.0',
17
+ type: 'openapi',
18
+ document: {
19
+ openapi: '3.2.0',
20
+ info: {
21
+ title: 'Mock API',
22
+ version: '1.0.0',
23
+ },
24
+ paths: {},
35
25
  },
36
- paths: {},
37
26
  };
38
27
  }
39
28
  let bundled;
@@ -58,11 +47,14 @@ export async function processOpenApiDocument(document, origin) {
58
47
  });
59
48
  }
60
49
  catch (error) {
61
- throw new Error(`Failed to bundle OpenAPI document: ${error instanceof Error ? error.message : String(error)}`);
50
+ throw new Error(`Failed to bundle API document: ${error instanceof Error ? error.message : String(error)}`);
62
51
  }
63
- if (!bundled || typeof bundled !== 'object') {
52
+ if (!isObjectLike(bundled)) {
64
53
  throw new Error('Bundled document is invalid: expected an object');
65
54
  }
55
+ if ('asyncapi' in bundled) {
56
+ return { type: 'asyncapi', document: createMagicProxy(bundled) };
57
+ }
66
58
  // Upgrading must not activate a $self field authored in an older OpenAPI version.
67
59
  const retrievalUri = origin ?? (typeof document === 'string' && (isFilePath(document) || isHttpUrl(document)) ? document : '/');
68
60
  const documentUri = resolveOpenApiDocument(bundled, retrievalUri)?.baseUri;
@@ -78,5 +70,5 @@ export async function processOpenApiDocument(document, origin) {
78
70
  }
79
71
  // Wrap the document in a magic proxy so internal references resolve lazily via `$ref-value`.
80
72
  // External references were already pulled inline by `bundle` above, so only local `$ref`s remain.
81
- return createMagicProxy(upgraded, { documentUri });
82
- }
73
+ return { type: 'openapi', document: createMagicProxy(upgraded, { documentUri }) };
74
+ };
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-channels.d.ts","sourceRoot":"","sources":["../../src/utils/resolve-channels.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAyB,MAAM,4BAA4B,CAAA;AAWzF,OAAO,KAAK,EAAE,eAAe,EAAsC,MAAM,oBAAoB,CAAA;AAkE7F;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,gBAAgB,GAAG,eAAe,EAAE,CA6D7E"}
1
+ {"version":3,"file":"resolve-channels.d.ts","sourceRoot":"","sources":["../../src/utils/resolve-channels.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAyB,MAAM,4BAA4B,CAAA;AAWzF,OAAO,KAAK,EAAE,eAAe,EAAsC,MAAM,oBAAoB,CAAA;AAoE7F;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,gBAAgB,GAAG,eAAe,EAAE,CAuE7E"}
@@ -1,7 +1,9 @@
1
+ import { combineUrlAndPath } from '@scalar/helpers/url/merge-urls';
1
2
  import { ASYNCAPI_WEBSOCKET_PROTOCOLS, getAllChannelMessages, getAsyncApiServers, getChannelOperations, resolveChannel, } from '@scalar/workspace-store/channel-example';
2
3
  import { getNameFromRef } from '@scalar/workspace-store/helpers/get-name-from-ref';
3
4
  import { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref';
4
5
  import { honoRouteFromPath } from '../utils/hono-route-from-path.js';
6
+ import { resolveServerPathnames } from './resolve-server-pathnames.js';
5
7
  /** Extract a plain JSON Schema from a message `payload`, unwrapping the Multi Format Schema Object. */
6
8
  function extractPayloadSchema(payload) {
7
9
  const resolved = getResolvedRef(payload);
@@ -91,25 +93,36 @@ export function resolveChannels(document) {
91
93
  ...(operation.security ? { security: operation.security.map((scheme) => getResolvedRef(scheme)) } : {}),
92
94
  };
93
95
  });
94
- const servers = getAsyncApiServers(document, { channel, webSocketOnly: false });
95
- const security = servers.map(({ protocol, server }) => ({
96
- protocol,
97
- schemes: (server.security ?? []).map((scheme) => getResolvedRef(scheme)),
98
- }));
99
- // A channel restricted to unresolved servers must not accidentally become public.
100
- if (channel.servers?.length && servers.length === 0) {
101
- security.push({ protocol: '', schemes: [undefined] });
96
+ // An empty server list means all servers, just like an omitted list.
97
+ const serverChannel = channel.servers?.length ? channel : { ...channel, servers: undefined };
98
+ const servers = getAsyncApiServers(document, { channel: serverChannel, webSocketOnly: false });
99
+ const routes = new Map();
100
+ for (const entry of servers.length ? servers : [undefined]) {
101
+ for (const pathname of entry ? resolveServerPathnames(entry.server) : ['']) {
102
+ const route = honoRouteFromPath(combineUrlAndPath(pathname || '/', channelAddress));
103
+ const security = entry
104
+ ? { protocol: entry.protocol, schemes: (entry.server.security ?? []).map((scheme) => getResolvedRef(scheme)) }
105
+ : { protocol: '', schemes: channel.servers?.length ? [undefined] : [] };
106
+ const existing = routes.get(route);
107
+ if (existing) {
108
+ existing.protocols = [...new Set([...existing.protocols, entry.protocol])];
109
+ existing.security.push(security);
110
+ continue;
111
+ }
112
+ routes.set(route, {
113
+ security: [security],
114
+ id: channelName,
115
+ address: channelAddress,
116
+ route: route.startsWith('/') ? route : `/${route}`,
117
+ protocols: entry ? [entry.protocol] : resolveProtocols(document, serverChannel),
118
+ operations,
119
+ messages,
120
+ });
121
+ }
102
122
  }
103
- return [
104
- {
105
- ...(security.some(({ schemes }) => schemes.length) ? { security } : {}),
106
- id: channelName,
107
- address: channelAddress,
108
- route: honoRouteFromPath(`/${channelAddress.replace(/^\//, '')}`),
109
- protocols: resolveProtocols(document, channel),
110
- operations,
111
- messages,
112
- },
113
- ];
123
+ return [...routes.values()].map(({ security, ...channel }) => ({
124
+ ...channel,
125
+ ...(security?.some(({ schemes }) => schemes.length) ? { security } : {}),
126
+ }));
114
127
  });
115
128
  }
@@ -0,0 +1,4 @@
1
+ import type { AsyncApiServerObject } from '@scalar/types/asyncapi/3.1';
2
+ /** Expand server pathname variables without expanding channel parameters or host variables. */
3
+ export declare const resolveServerPathnames: (server: AsyncApiServerObject) => string[];
4
+ //# sourceMappingURL=resolve-server-pathnames.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve-server-pathnames.d.ts","sourceRoot":"","sources":["../../src/utils/resolve-server-pathnames.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAA;AAGtE,+FAA+F;AAC/F,eAAO,MAAM,sBAAsB,GAAI,QAAQ,oBAAoB,KAAG,MAAM,EAa3E,CAAA"}
@@ -0,0 +1,14 @@
1
+ import { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref';
2
+ /** Expand server pathname variables without expanding channel parameters or host variables. */
3
+ export const resolveServerPathnames = (server) => {
4
+ const pathname = server.pathname ?? '';
5
+ const names = [...new Set([...pathname.matchAll(/\{([^{}]+)\}/g)].map((match) => match[1]))];
6
+ return names.reduce((paths, name) => {
7
+ const variable = getResolvedRef(server.variables?.[name]);
8
+ const values = variable?.enum?.length ? variable.enum : variable?.default !== undefined ? [variable.default] : [];
9
+ // Unconstrained variables remain dynamic route parameters.
10
+ if (!values.length)
11
+ return paths;
12
+ return [...new Set(paths.flatMap((path) => values.map((value) => path.replaceAll(`{${name}}`, () => value))))];
13
+ }, [pathname]);
14
+ };