@scalar/mock-server 0.20.3 → 0.21.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.
- package/CHANGELOG.md +12 -0
- package/dist/create-openapi-mock-server.d.ts.map +1 -1
- package/dist/create-openapi-mock-server.js +87 -16
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/routes/mock-any-response.d.ts.map +1 -1
- package/dist/routes/mock-any-response.js +2 -3
- package/dist/types.d.ts +39 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/clone-document.d.ts +13 -0
- package/dist/utils/clone-document.d.ts.map +1 -0
- package/dist/utils/clone-document.js +56 -0
- package/dist/utils/generate-response-example.d.ts +2 -18
- package/dist/utils/generate-response-example.d.ts.map +1 -1
- package/dist/utils/generate-response-example.js +2 -19
- package/dist/utils/hono-route-from-path.d.ts +9 -0
- package/dist/utils/hono-route-from-path.d.ts.map +1 -1
- package/dist/utils/hono-route-from-path.js +23 -14
- package/dist/utils/path-specificity.d.ts +32 -0
- package/dist/utils/path-specificity.d.ts.map +1 -0
- package/dist/utils/path-specificity.js +58 -0
- package/dist/utils/process-document.d.ts +5 -1
- package/dist/utils/process-document.d.ts.map +1 -1
- package/dist/utils/process-document.js +9 -2
- package/package.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# @scalar/mock-server
|
|
2
2
|
|
|
3
|
+
## 0.21.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#10809](https://github.com/scalar/scalar/pull/10809): feat: add an `onResponse` hook to observe or replace the response for each request
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- [#10808](https://github.com/scalar/scalar/pull/10808): fix: match concrete paths before templated ones, so `/pets/mine` is answered by its own operation even when the document declares `/pets/{petId}` first
|
|
12
|
+
- [#10810](https://github.com/scalar/scalar/pull/10810): fix: leave an object document passed to `createMockServer` unchanged instead of bundling it in place
|
|
13
|
+
- [#10812](https://github.com/scalar/scalar/pull/10812): fix(mock-server): include deprecated schemas in XML responses, so a response whose schema is deprecated no longer comes back with an empty XML body
|
|
14
|
+
|
|
3
15
|
## 0.20.3
|
|
4
16
|
|
|
5
17
|
## 0.20.2
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-openapi-mock-server.d.ts","sourceRoot":"","sources":["../src/create-openapi-mock-server.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"create-openapi-mock-server.d.ts","sourceRoot":"","sources":["../src/create-openapi-mock-server.ts"],"names":[],"mappings":"AAIA,OAAO,EAAgB,IAAI,EAA0B,MAAM,MAAM,CAAA;AAIjE,OAAO,KAAK,EAAE,iBAAiB,EAA0B,MAAM,SAAS,CAAA;AASxE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAA;AAyHjE;;GAEG;AACH,eAAO,MAAM,uBAAuB,GAClC,eAAe,iBAAiB,EAChC,QAAQ,OAAO,CAAC,iBAAiB,EAAE;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,CAAC,CAAC,UAAU,CAAC,KAClE,OAAO,CAAC,IAAI,CAsPd,CAAA"}
|
|
@@ -11,6 +11,7 @@ import { handleAuthentication } from './utils/handle-authentication.js';
|
|
|
11
11
|
import { honoRouteFromPath } from './utils/hono-route-from-path.js';
|
|
12
12
|
import { isAuthenticationRequired } from './utils/is-authentication-required.js';
|
|
13
13
|
import { logAuthenticationInstructions } from './utils/log-authentication-instructions.js';
|
|
14
|
+
import { comparePathSpecificity, getPathSpecificity } from './utils/path-specificity.js';
|
|
14
15
|
import { requestMatchesPinnedQuery } from './utils/request-matches-pinned-query.js';
|
|
15
16
|
import { resolveLogger } from './utils/resolve-logger.js';
|
|
16
17
|
import { setUpAuthenticationRoutes } from './utils/set-up-authentication-routes.js';
|
|
@@ -20,13 +21,69 @@ import { store } from './libs/store.js';
|
|
|
20
21
|
import { mockAnyResponse } from './routes/mock-any-response.js';
|
|
21
22
|
import { mockHandlerResponse } from './routes/mock-handler-response.js';
|
|
22
23
|
import { respondWithOpenApiDocument } from './routes/respond-with-openapi-document.js';
|
|
23
|
-
/**
|
|
24
|
-
|
|
24
|
+
/**
|
|
25
|
+
* Record which operation a request matched, so an error escaping it can be named and `onResponse`
|
|
26
|
+
* receives the operation object itself.
|
|
27
|
+
*/
|
|
28
|
+
const setMockedOperation = (c, mockedOperation, operation) => {
|
|
25
29
|
;
|
|
26
|
-
c.set('mockedOperation',
|
|
30
|
+
c.set('mockedOperation', mockedOperation);
|
|
31
|
+
c.set('matchedOperation', operation);
|
|
27
32
|
};
|
|
28
33
|
/** Read back the operation a request matched, or `undefined` when it reached no mocked route */
|
|
29
34
|
const getMockedOperation = (c) => c.get('mockedOperation');
|
|
35
|
+
/** Read back the operation object a request matched, or `undefined` when it reached no mocked route */
|
|
36
|
+
const getMatchedOperation = (c) => c.get('matchedOperation');
|
|
37
|
+
/**
|
|
38
|
+
* Make `response` the response of the request, keeping only the headers that were staged before the
|
|
39
|
+
* request was handled — the CORS headers — where `response` does not set them itself.
|
|
40
|
+
*
|
|
41
|
+
* Assigning `c.res` directly would merge every header of the response it replaces into the new one,
|
|
42
|
+
* overriding the new one's values, so the mock response's own headers (an `ETag`, a declared
|
|
43
|
+
* `X-Rate-Limit`) would leak into a replacement that deliberately sets different ones.
|
|
44
|
+
*/
|
|
45
|
+
const replaceResponse = (c, response, stagedHeaders) => {
|
|
46
|
+
// Rebuilt so the headers are mutable even when the caller passed a response with immutable ones,
|
|
47
|
+
// such as one returned by `fetch()`. The body stream is handed over as is, never read.
|
|
48
|
+
const replacement = new Response(response.body, response);
|
|
49
|
+
stagedHeaders.forEach((value, name) => {
|
|
50
|
+
if (!replacement.headers.has(name)) {
|
|
51
|
+
replacement.headers.set(name, value);
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
// Clearing it first is what stops Hono from merging the replaced response's headers in.
|
|
55
|
+
c.res = undefined;
|
|
56
|
+
c.res = replacement;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Run `onResponse` once the rest of the app has answered a request, sending its replacement when it
|
|
60
|
+
* returns one.
|
|
61
|
+
*
|
|
62
|
+
* Registered as the first middleware after CORS, so it sees every response the app produces —
|
|
63
|
+
* mocked operations, authentication failures, validation errors, the document exports, `404`s and
|
|
64
|
+
* the error handler's `500`s (the error handler runs where the error is thrown, deeper down, before
|
|
65
|
+
* this middleware resumes) — while CORS preflight requests are still answered before it runs.
|
|
66
|
+
*/
|
|
67
|
+
const runResponseHook = (onResponse) => async (c, next) => {
|
|
68
|
+
// The CORS middleware stages its headers on the response before the request is handled. Copied
|
|
69
|
+
// now, before the mock response is merged over them, so a replacement can be given just these.
|
|
70
|
+
const stagedHeaders = new Headers(c.res.headers);
|
|
71
|
+
await next();
|
|
72
|
+
const response = c.res;
|
|
73
|
+
let replacement;
|
|
74
|
+
try {
|
|
75
|
+
replacement = await onResponse({ context: c, operation: getMatchedOperation(c), response });
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
// The error handler answers through the context, which would otherwise build the `500` on top
|
|
79
|
+
// of the mock response and carry all of its headers. Start it from the staged headers instead.
|
|
80
|
+
replaceResponse(c, new Response(null), stagedHeaders);
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
if (replacement && replacement !== response) {
|
|
84
|
+
replaceResponse(c, replacement, stagedHeaders);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
30
87
|
/**
|
|
31
88
|
* Whether an error carries its own response, the way Hono's `HTTPException` does.
|
|
32
89
|
*
|
|
@@ -108,6 +165,11 @@ export const createOpenApiMockServer = async (configuration, schema) => {
|
|
|
108
165
|
}
|
|
109
166
|
}
|
|
110
167
|
app.use(cors({ origin: '*', allowMethods: [...allowedMethods], exposeHeaders: ['X-Scalar-XML-Error'] }));
|
|
168
|
+
// Registered right after CORS and before every route, so it also wraps the routes a caller adds to
|
|
169
|
+
// the returned app.
|
|
170
|
+
if (configuration.onResponse) {
|
|
171
|
+
app.use(runResponseHook(configuration.onResponse));
|
|
172
|
+
}
|
|
111
173
|
/** Authentication methods defined in the OpenAPI document */
|
|
112
174
|
setUpAuthenticationRoutes(app, schema);
|
|
113
175
|
// Only the instructions honor `logger` (on by default); the util still prints warnings and errors
|
|
@@ -115,13 +177,24 @@ export const createOpenApiMockServer = async (configuration, schema) => {
|
|
|
115
177
|
logAuthenticationInstructions(schema?.components?.securitySchemes || {}, resolveLogger(configuration.logger, true));
|
|
116
178
|
/** Paths specified in the OpenAPI document */
|
|
117
179
|
const paths = schema?.paths ?? {};
|
|
118
|
-
//
|
|
119
|
-
//
|
|
120
|
-
//
|
|
121
|
-
//
|
|
180
|
+
// Hono runs every matching route in registration order and the first one that answers wins, so
|
|
181
|
+
// the order routes are registered in decides which operation serves a request that more than one
|
|
182
|
+
// path key matches. Two things set that order.
|
|
183
|
+
//
|
|
184
|
+
// First, concrete paths come before templated ones, as the OpenAPI Paths Object asks: `/pets/mine`
|
|
185
|
+
// answers its own requests even when the document declares `/pets/{petId}` first. Segments are
|
|
186
|
+
// compared from the left and the first one that differs decides; a segment mixing a template with
|
|
187
|
+
// literal text (`{jobId}:cancel`) ranks between a literal and a bare `{param}`. Path keys that rank
|
|
188
|
+
// the same keep the order the document declares them in. See `comparePathSpecificity`.
|
|
189
|
+
//
|
|
190
|
+
// Second, a path key may pin query parameters to describe a variant of an operation, for example
|
|
191
|
+
// `/v1/messages?beta=true` next to `/v1/messages`. A variant has to come before the sibling it shares
|
|
192
|
+
// a path with — otherwise the sibling answers its requests too — so the keys that share a path are
|
|
193
|
+
// grouped where the first of them appears, and the more pinned parameters a key has the earlier it
|
|
194
|
+
// goes. A variant that a request does not satisfy hands it on to the next matching route.
|
|
122
195
|
const pathKeys = Object.keys(paths).map((path) => {
|
|
123
196
|
const { path: pathname, query } = splitPathKey(path);
|
|
124
|
-
return { path, pathname, query };
|
|
197
|
+
return { path, pathname, query, specificity: getPathSpecificity(pathname) };
|
|
125
198
|
});
|
|
126
199
|
/** Where each path first shows up in the document, so its variants stay with it */
|
|
127
200
|
const documentOrder = new Map();
|
|
@@ -130,13 +203,11 @@ export const createOpenApiMockServer = async (configuration, schema) => {
|
|
|
130
203
|
documentOrder.set(pathname, index);
|
|
131
204
|
}
|
|
132
205
|
});
|
|
133
|
-
//
|
|
134
|
-
//
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
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);
|
|
206
|
+
// Paths that cannot match the same request may change places here, which is harmless: only the
|
|
207
|
+
// relative order of overlapping routes decides which operation answers.
|
|
208
|
+
const orderedPathKeys = [...pathKeys].sort((a, b) => comparePathSpecificity(a.specificity, b.specificity) ||
|
|
209
|
+
(documentOrder.get(a.pathname) ?? 0) - (documentOrder.get(b.pathname) ?? 0) ||
|
|
210
|
+
b.query.length - a.query.length);
|
|
140
211
|
orderedPathKeys.forEach(({ path, query }) => {
|
|
141
212
|
// A path item may itself be a `$ref`, so resolve it before reading its operations.
|
|
142
213
|
const pathItem = getResolvedRef(paths[path]);
|
|
@@ -160,7 +231,7 @@ export const createOpenApiMockServer = async (configuration, schema) => {
|
|
|
160
231
|
// path key that pins a query it is part of the guarded chain below, so it only fires once the
|
|
161
232
|
// request actually matches the variant rather than for one that is handed on to the sibling.
|
|
162
233
|
handlers.push(async (c, next) => {
|
|
163
|
-
setMockedOperation(c, mockedOperation);
|
|
234
|
+
setMockedOperation(c, mockedOperation, operation);
|
|
164
235
|
await next();
|
|
165
236
|
});
|
|
166
237
|
// Operation-level security overrides the global requirement, so fall back to the
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { createMockServer } from './create-mock-server.js';
|
|
2
2
|
export { defaultTransports, sseTransport, websocketTransport } from './transports/index.js';
|
|
3
3
|
export type { MessageDirection, MockMessage, MockTransport, ResolvedChannel, ResolvedMessage, ResolvedOperation, TransportContext, } from './transports/types.js';
|
|
4
|
-
export type { MockServerLogger, MockServerOptions } from './types.js';
|
|
4
|
+
export type { MockServerLogger, MockServerOptions, MockServerResponseHook, MockServerResponseHookData, } from './types.js';
|
|
5
5
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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,
|
|
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,EACV,gBAAgB,EAChB,iBAAiB,EACjB,sBAAsB,EACtB,0BAA0B,GAC3B,MAAM,SAAS,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mock-any-response.d.ts","sourceRoot":"","sources":["../../src/routes/mock-any-response.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AAKxD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAenC;;GAEG;AACH,wBAAgB,eAAe,CAAC,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,WAAW,CAAC,eAAe,EAAE,cAAc,CAAC,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"mock-any-response.d.ts","sourceRoot":"","sources":["../../src/routes/mock-any-response.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AAKxD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAA;AAenC;;GAEG;AACH,wBAAgB,eAAe,CAAC,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,WAAW,CAAC,eAAe,EAAE,cAAc,CAAC,EAAE,MAAM,YA2J1G"}
|
|
@@ -39,10 +39,9 @@ export function mockAnyResponse(c, operation, openapiVersion) {
|
|
|
39
39
|
const headers = selectedResponse?.headers ?? {};
|
|
40
40
|
Object.keys(headers).forEach((header) => {
|
|
41
41
|
const headerObject = getResolvedRef(headers[header]);
|
|
42
|
-
// Headers
|
|
43
|
-
// the note on that helper for why passing them would change what declared headers emit.
|
|
42
|
+
// Headers use the generator defaults to preserve their declared values.
|
|
44
43
|
const value = headerObject?.schema
|
|
45
|
-
? getExampleFromSchema(getResolvedRefDeep(headerObject.schema)
|
|
44
|
+
? getExampleFromSchema(getResolvedRefDeep(headerObject.schema))
|
|
46
45
|
: null;
|
|
47
46
|
// Loose check on purpose: Hono *deletes* a header when handed `undefined`. This loop is the first
|
|
48
47
|
// thing to set the declared headers, so in practice a delete removes a header set earlier by
|
package/dist/types.d.ts
CHANGED
|
@@ -12,6 +12,37 @@ type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<T, Exclude<keyo
|
|
|
12
12
|
}[Keys];
|
|
13
13
|
/** A sink for the informational log lines the mock servers print while starting up. */
|
|
14
14
|
export type MockServerLogger = (line: string) => void;
|
|
15
|
+
/** What the `onResponse` callback receives for one request. */
|
|
16
|
+
export type MockServerResponseHookData = {
|
|
17
|
+
/** The Hono context of the request, the same one `onRequest` receives */
|
|
18
|
+
context: Context;
|
|
19
|
+
/**
|
|
20
|
+
* The OpenAPI operation that answered the request, or `undefined` when the request matched no
|
|
21
|
+
* operation: the `/openapi.json` and `/openapi.yaml` exports, the authentication routes, routes
|
|
22
|
+
* added to the returned app, and requests answered with `404 Not Found`.
|
|
23
|
+
*/
|
|
24
|
+
operation: OpenAPIV3_1.OperationObject | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* The response the mock server is about to send. Its body is left unread, so a streaming response
|
|
27
|
+
* (`text/event-stream`, JSON Lines) is still streaming. Reading it consumes it, so a callback that
|
|
28
|
+
* reads the body has to return a replacement — `response.clone()` gives it a copy to read instead.
|
|
29
|
+
*/
|
|
30
|
+
response: Response;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Observe or replace the response the OpenAPI mock server sends for a request.
|
|
34
|
+
*
|
|
35
|
+
* It runs once per request, after the mock server has produced its response — including
|
|
36
|
+
* authentication failures, `422` request validation responses, and `500` responses from the error
|
|
37
|
+
* handler. CORS preflight requests are answered before it runs, so they never reach it.
|
|
38
|
+
*
|
|
39
|
+
* Return a `Response` to send it instead of the mock response. The CORS headers the server adds are
|
|
40
|
+
* carried over onto it, unless it sets them itself. Return nothing to keep the mock response.
|
|
41
|
+
*
|
|
42
|
+
* An error thrown (or a promise rejected) by the callback is answered like any other failure while
|
|
43
|
+
* mocking: a `500` response naming the matched operation, which does not reach the callback again.
|
|
44
|
+
*/
|
|
45
|
+
export type MockServerResponseHook = (data: MockServerResponseHookData) => Response | void | Promise<Response | void>;
|
|
15
46
|
type BaseMockServerOptions = {
|
|
16
47
|
/** Runtime adapter for AsyncAPI WebSocket channels. It must invoke onOpen after accepting a connection. */
|
|
17
48
|
upgradeWebSocket?: UpgradeWebSocket;
|
|
@@ -44,6 +75,14 @@ type BaseMockServerOptions = {
|
|
|
44
75
|
context: Context;
|
|
45
76
|
operation: OpenAPIV3_1.OperationObject;
|
|
46
77
|
}) => void;
|
|
78
|
+
/**
|
|
79
|
+
* Callback function called once per OpenAPI request, after the mock server has produced its
|
|
80
|
+
* response and before it is sent. Return a `Response` (or a promise of one) to send that instead,
|
|
81
|
+
* or nothing to keep the mock response.
|
|
82
|
+
*
|
|
83
|
+
* See {@link MockServerResponseHook} for what reaches it.
|
|
84
|
+
*/
|
|
85
|
+
onResponse?: MockServerResponseHook;
|
|
47
86
|
/**
|
|
48
87
|
* Validate the incoming OpenAPI request against the matched operation's schema. When the request
|
|
49
88
|
* violates the contract, the server responds with `422` and a `application/problem+json`
|
package/dist/types.d.ts.map
CHANGED
|
@@ -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;AACnC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAE/C,OAAO,KAAK,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAEzE,6CAA6C;AAC7C,eAAO,MAAM,WAAW,+DAAgE,CAAA;AAExF;;GAEG;AACH,KAAK,iBAAiB,CAAC,CAAC,EAAE,IAAI,SAAS,MAAM,CAAC,GAAG,MAAM,CAAC,IAAI,IAAI,CAAC,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC,GACzF;KACG,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;CACzE,CAAC,IAAI,CAAC,CAAA;AAET,uFAAuF;AACvF,MAAM,MAAM,gBAAgB,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAA;AAErD,KAAK,qBAAqB,GAAG;IAC3B,2GAA2G;IAC3G,gBAAgB,CAAC,EAAE,gBAAgB,CAAA;IAEnC,6FAA6F;IAC7F,UAAU,CAAC,EAAE,aAAa,EAAE,CAAA;IAE5B,0DAA0D;IAC1D,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,gBAAgB,CAAC;QAAC,OAAO,EAAE,OAAO,CAAA;KAAE,KAAK,IAAI,CAAA;IAE/F,iGAAiG;IACjG,MAAM,CAAC,EAAE,MAAM,CAAA;IAEf;;;;;OAKG;IACH,aAAa,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAE5C;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,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"}
|
|
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;AACnC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AAE/C,OAAO,KAAK,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA;AAEzE,6CAA6C;AAC7C,eAAO,MAAM,WAAW,+DAAgE,CAAA;AAExF;;GAEG;AACH,KAAK,iBAAiB,CAAC,CAAC,EAAE,IAAI,SAAS,MAAM,CAAC,GAAG,MAAM,CAAC,IAAI,IAAI,CAAC,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,CAAC,GACzF;KACG,CAAC,IAAI,IAAI,CAAC,CAAC,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;CACzE,CAAC,IAAI,CAAC,CAAA;AAET,uFAAuF;AACvF,MAAM,MAAM,gBAAgB,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAA;AAErD,+DAA+D;AAC/D,MAAM,MAAM,0BAA0B,GAAG;IACvC,yEAAyE;IACzE,OAAO,EAAE,OAAO,CAAA;IAChB;;;;OAIG;IACH,SAAS,EAAE,WAAW,CAAC,eAAe,GAAG,SAAS,CAAA;IAClD;;;;OAIG;IACH,QAAQ,EAAE,QAAQ,CAAA;CACnB,CAAA;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,sBAAsB,GAAG,CAAC,IAAI,EAAE,0BAA0B,KAAK,QAAQ,GAAG,IAAI,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAAA;AAErH,KAAK,qBAAqB,GAAG;IAC3B,2GAA2G;IAC3G,gBAAgB,CAAC,EAAE,gBAAgB,CAAA;IAEnC,6FAA6F;IAC7F,UAAU,CAAC,EAAE,aAAa,EAAE,CAAA;IAE5B,0DAA0D;IAC1D,SAAS,CAAC,EAAE,CAAC,KAAK,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,gBAAgB,CAAC;QAAC,OAAO,EAAE,OAAO,CAAA;KAAE,KAAK,IAAI,CAAA;IAE/F,iGAAiG;IACjG,MAAM,CAAC,EAAE,MAAM,CAAA;IAEf;;;;;OAKG;IACH,aAAa,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAE5C;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,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;;;;;;OAMG;IACH,UAAU,CAAC,EAAE,sBAAsB,CAAA;IAEnC;;;;;;;;;;;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,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deep copy an API description passed as an object, so processing it never edits the caller's object.
|
|
3
|
+
*
|
|
4
|
+
* Bundling writes into the document it is handed — it records external documents under `x-ext` and
|
|
5
|
+
* removes `x-ext-urls` — and that must not leak back into an object the caller still holds.
|
|
6
|
+
*
|
|
7
|
+
* Not `structuredClone`: it throws on values a caller can reasonably pass, such as a `Proxy` (a
|
|
8
|
+
* reactive or lazily resolved document) or a function somewhere in the tree. Copying only arrays and
|
|
9
|
+
* plain objects handles those, keeps shared and circular references intact, and leaves anything
|
|
10
|
+
* else in the tree shared with the caller.
|
|
11
|
+
*/
|
|
12
|
+
export declare const cloneDocument: <T extends object>(document: T) => T;
|
|
13
|
+
//# sourceMappingURL=clone-document.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"clone-document.d.ts","sourceRoot":"","sources":["../../src/utils/clone-document.ts"],"names":[],"mappings":"AAqDA;;;;;;;;;;GAUG;AACH,eAAO,MAAM,aAAa,GAAI,CAAC,SAAS,MAAM,EAAE,UAAU,CAAC,KAAG,CAAmC,CAAA"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { isObject } from '@scalar/helpers/object/is-object';
|
|
2
|
+
/**
|
|
3
|
+
* Copy the JSON-shaped part of a value: arrays and plain objects are copied, everything else is
|
|
4
|
+
* kept as is.
|
|
5
|
+
*
|
|
6
|
+
* `seen` maps each source object to its copy, so a shared object stays shared and a cycle stays a
|
|
7
|
+
* cycle, the way they were in the source.
|
|
8
|
+
*/
|
|
9
|
+
const copy = (value, seen) => {
|
|
10
|
+
if (typeof value !== 'object' || value === null) {
|
|
11
|
+
return value;
|
|
12
|
+
}
|
|
13
|
+
const existing = seen.get(value);
|
|
14
|
+
if (existing !== undefined) {
|
|
15
|
+
return existing;
|
|
16
|
+
}
|
|
17
|
+
if (Array.isArray(value)) {
|
|
18
|
+
const result = new Array(value.length);
|
|
19
|
+
seen.set(value, result);
|
|
20
|
+
// `forEach` skips holes, so a sparse array stays sparse.
|
|
21
|
+
value.forEach((item, index) => {
|
|
22
|
+
result[index] = copy(item, seen);
|
|
23
|
+
});
|
|
24
|
+
return result;
|
|
25
|
+
}
|
|
26
|
+
// A `Date`, a `Map` or any other instance is not something bundling walks into, so it is shared
|
|
27
|
+
// with the source rather than rebuilt without its prototype.
|
|
28
|
+
if (!isObject(value)) {
|
|
29
|
+
return value;
|
|
30
|
+
}
|
|
31
|
+
const result = {};
|
|
32
|
+
seen.set(value, result);
|
|
33
|
+
for (const [key, item] of Object.entries(value)) {
|
|
34
|
+
// Defined rather than assigned, so a `__proto__` key in parsed JSON stays an ordinary key
|
|
35
|
+
// instead of replacing the copy's prototype.
|
|
36
|
+
Object.defineProperty(result, key, {
|
|
37
|
+
value: copy(item, seen),
|
|
38
|
+
enumerable: true,
|
|
39
|
+
writable: true,
|
|
40
|
+
configurable: true,
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
return result;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Deep copy an API description passed as an object, so processing it never edits the caller's object.
|
|
47
|
+
*
|
|
48
|
+
* Bundling writes into the document it is handed — it records external documents under `x-ext` and
|
|
49
|
+
* removes `x-ext-urls` — and that must not leak back into an object the caller still holds.
|
|
50
|
+
*
|
|
51
|
+
* Not `structuredClone`: it throws on values a caller can reasonably pass, such as a `Proxy` (a
|
|
52
|
+
* reactive or lazily resolved document) or a function somewhere in the tree. Copying only arrays and
|
|
53
|
+
* plain objects handles those, keeps shared and circular references intact, and leaves anything
|
|
54
|
+
* else in the tree shared with the caller.
|
|
55
|
+
*/
|
|
56
|
+
export const cloneDocument = (document) => copy(document, new Map());
|
|
@@ -2,24 +2,8 @@ import { getExampleFromSchema } from '@scalar/workspace-store/request-example';
|
|
|
2
2
|
/** The schema shape `getExampleFromSchema` accepts, so callers do not have to name it themselves. */
|
|
3
3
|
export type ExampleSchema = Parameters<typeof getExampleFromSchema>[0];
|
|
4
4
|
/**
|
|
5
|
-
* Generate
|
|
6
|
-
*
|
|
7
|
-
* Every value the mock puts on the wire — an HTTP body, an SSE frame, a channel message — has to
|
|
8
|
-
* satisfy the schema it was declared with, which is why this passes `includeDeprecated: true`:
|
|
9
|
-
* `deprecated` marks a field as discouraged, not absent, so omitting it answered a declared JSON
|
|
10
|
-
* response with zero bytes and dropped required properties. Owning the option set in one place keeps
|
|
11
|
-
* a newly added response path from quietly missing that.
|
|
12
|
-
*
|
|
13
|
-
* Not for response headers. Two of the options here would change what an already-declared header
|
|
14
|
-
* emits: `emptyString` yields the literal `string` for a bare `type: 'string'` and switches on
|
|
15
|
-
* format-based generation (a `format: 'date-time'` header would emit a fabricated timestamp), and
|
|
16
|
-
* `mode: 'read'` drops a `writeOnly` header entirely. Headers set `includeDeprecated` on their own
|
|
17
|
-
* call instead.
|
|
18
|
-
*
|
|
19
|
-
* @param schema - The resolved schema to generate a value for.
|
|
20
|
-
* @param variables - Values for `x-variable` substitution, usually a request's path parameters.
|
|
21
|
-
* Omitted by callers that have no request in scope, such as channel messages.
|
|
22
|
-
* @returns The generated value, or `undefined` when the schema yields nothing.
|
|
5
|
+
* Generate response bodies and message payloads with response-mode defaults.
|
|
6
|
+
* Headers use the generator directly to preserve empty strings and write-only values.
|
|
23
7
|
*/
|
|
24
8
|
export declare const generateResponseExample: (schema: ExampleSchema, variables?: Record<string, unknown>) => unknown;
|
|
25
9
|
//# sourceMappingURL=generate-response-example.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate-response-example.d.ts","sourceRoot":"","sources":["../../src/utils/generate-response-example.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,yCAAyC,CAAA;AAE9E,qGAAqG;AACrG,MAAM,MAAM,aAAa,GAAG,UAAU,CAAC,OAAO,oBAAoB,CAAC,CAAC,CAAC,CAAC,CAAA;AAEtE
|
|
1
|
+
{"version":3,"file":"generate-response-example.d.ts","sourceRoot":"","sources":["../../src/utils/generate-response-example.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,yCAAyC,CAAA;AAE9E,qGAAqG;AACrG,MAAM,MAAM,aAAa,GAAG,UAAU,CAAC,OAAO,oBAAoB,CAAC,CAAC,CAAC,CAAC,CAAA;AAEtE;;;GAGG;AACH,eAAO,MAAM,uBAAuB,GAAI,QAAQ,aAAa,EAAE,YAAY,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAG,OAKjG,CAAA"}
|
|
@@ -1,27 +1,10 @@
|
|
|
1
1
|
import { getExampleFromSchema } from '@scalar/workspace-store/request-example';
|
|
2
2
|
/**
|
|
3
|
-
* Generate
|
|
4
|
-
*
|
|
5
|
-
* Every value the mock puts on the wire — an HTTP body, an SSE frame, a channel message — has to
|
|
6
|
-
* satisfy the schema it was declared with, which is why this passes `includeDeprecated: true`:
|
|
7
|
-
* `deprecated` marks a field as discouraged, not absent, so omitting it answered a declared JSON
|
|
8
|
-
* response with zero bytes and dropped required properties. Owning the option set in one place keeps
|
|
9
|
-
* a newly added response path from quietly missing that.
|
|
10
|
-
*
|
|
11
|
-
* Not for response headers. Two of the options here would change what an already-declared header
|
|
12
|
-
* emits: `emptyString` yields the literal `string` for a bare `type: 'string'` and switches on
|
|
13
|
-
* format-based generation (a `format: 'date-time'` header would emit a fabricated timestamp), and
|
|
14
|
-
* `mode: 'read'` drops a `writeOnly` header entirely. Headers set `includeDeprecated` on their own
|
|
15
|
-
* call instead.
|
|
16
|
-
*
|
|
17
|
-
* @param schema - The resolved schema to generate a value for.
|
|
18
|
-
* @param variables - Values for `x-variable` substitution, usually a request's path parameters.
|
|
19
|
-
* Omitted by callers that have no request in scope, such as channel messages.
|
|
20
|
-
* @returns The generated value, or `undefined` when the schema yields nothing.
|
|
3
|
+
* Generate response bodies and message payloads with response-mode defaults.
|
|
4
|
+
* Headers use the generator directly to preserve empty strings and write-only values.
|
|
21
5
|
*/
|
|
22
6
|
export const generateResponseExample = (schema, variables) => getExampleFromSchema(schema, {
|
|
23
7
|
emptyString: 'string',
|
|
24
8
|
variables,
|
|
25
9
|
mode: 'read',
|
|
26
|
-
includeDeprecated: true,
|
|
27
10
|
});
|
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
/** Prefix for the parameters we synthesize to match a literal path segment verbatim. */
|
|
2
2
|
export declare const LITERAL_PARAMETER_PREFIX = "__scalar_literal_";
|
|
3
|
+
/**
|
|
4
|
+
* Convert an OpenAPI path key into the segments of a Hono route, one entry per `/`-separated segment
|
|
5
|
+
* of the path portion of the key.
|
|
6
|
+
*
|
|
7
|
+
* The segments are returned on their own, rather than as a route string, because an escaped segment
|
|
8
|
+
* carries a regular expression with a `/` in it (`[^/]+`), so the joined route cannot be split back
|
|
9
|
+
* into segments. Everything else about the conversion is described on `honoRouteFromPath`.
|
|
10
|
+
*/
|
|
11
|
+
export declare const honoRouteSegmentsFromPath: (path: string) => string[];
|
|
3
12
|
/**
|
|
4
13
|
* Convert an OpenAPI path key into a Hono route.
|
|
5
14
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hono-route-from-path.d.ts","sourceRoot":"","sources":["../../src/utils/hono-route-from-path.ts"],"names":[],"mappings":"AAaA,wFAAwF;AACxF,eAAO,MAAM,wBAAwB,sBAAsB,CAAA;AA2D3D;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,iBAAiB,GAAI,MAAM,MAAM,KAAG,
|
|
1
|
+
{"version":3,"file":"hono-route-from-path.d.ts","sourceRoot":"","sources":["../../src/utils/hono-route-from-path.ts"],"names":[],"mappings":"AAaA,wFAAwF;AACxF,eAAO,MAAM,wBAAwB,sBAAsB,CAAA;AA2D3D;;;;;;;GAOG;AACH,eAAO,MAAM,yBAAyB,GAAI,MAAM,MAAM,KAAG,MAAM,EAiC9D,CAAA;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,iBAAiB,GAAI,MAAM,MAAM,KAAG,MAAmD,CAAA"}
|
|
@@ -57,21 +57,14 @@ const patternFromSegment = (segment) => {
|
|
|
57
57
|
return pattern;
|
|
58
58
|
};
|
|
59
59
|
/**
|
|
60
|
-
* Convert an OpenAPI path key into a Hono route
|
|
61
|
-
*
|
|
62
|
-
* Example: `/posts/{id}` → `/posts/:id`
|
|
63
|
-
*
|
|
64
|
-
* A segment whose literal text would be read as routing syntax is registered as a single parameter
|
|
65
|
-
* with an explicit pattern instead, because Hono allows only one parameter per segment and that is
|
|
66
|
-
* the only way to make it match such a segment verbatim. The request then routes to the right
|
|
67
|
-
* operation, but the path parameters of that one segment are no longer bound by name: they surface
|
|
68
|
-
* as the synthesized parameter, and a required path parameter in it reads as missing to request
|
|
69
|
-
* validation. Hono cannot express both at once, and matching the wrong operation is worse.
|
|
60
|
+
* Convert an OpenAPI path key into the segments of a Hono route, one entry per `/`-separated segment
|
|
61
|
+
* of the path portion of the key.
|
|
70
62
|
*
|
|
71
|
-
*
|
|
72
|
-
*
|
|
63
|
+
* The segments are returned on their own, rather than as a route string, because an escaped segment
|
|
64
|
+
* carries a regular expression with a `/` in it (`[^/]+`), so the joined route cannot be split back
|
|
65
|
+
* into segments. Everything else about the conversion is described on `honoRouteFromPath`.
|
|
73
66
|
*/
|
|
74
|
-
export const
|
|
67
|
+
export const honoRouteSegmentsFromPath = (path) => {
|
|
75
68
|
const { path: pathname } = splitPathKey(path);
|
|
76
69
|
const route = [];
|
|
77
70
|
let literalIndex = 0;
|
|
@@ -96,5 +89,21 @@ export const honoRouteFromPath = (path) => {
|
|
|
96
89
|
}
|
|
97
90
|
previousIsPattern = needsPattern;
|
|
98
91
|
}
|
|
99
|
-
return route
|
|
92
|
+
return route;
|
|
100
93
|
};
|
|
94
|
+
/**
|
|
95
|
+
* Convert an OpenAPI path key into a Hono route.
|
|
96
|
+
*
|
|
97
|
+
* Example: `/posts/{id}` → `/posts/:id`
|
|
98
|
+
*
|
|
99
|
+
* A segment whose literal text would be read as routing syntax is registered as a single parameter
|
|
100
|
+
* with an explicit pattern instead, because Hono allows only one parameter per segment and that is
|
|
101
|
+
* the only way to make it match such a segment verbatim. The request then routes to the right
|
|
102
|
+
* operation, but the path parameters of that one segment are no longer bound by name: they surface
|
|
103
|
+
* as the synthesized parameter, and a required path parameter in it reads as missing to request
|
|
104
|
+
* validation. Hono cannot express both at once, and matching the wrong operation is worse.
|
|
105
|
+
*
|
|
106
|
+
* A query string in the key (`/v1/messages?beta=true`) is dropped here — it is matched against the
|
|
107
|
+
* incoming request separately, see `splitPathKey`.
|
|
108
|
+
*/
|
|
109
|
+
export const honoRouteFromPath = (path) => honoRouteSegmentsFromPath(path).join('/');
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How specific one path segment is, lower being more specific:
|
|
3
|
+
*
|
|
4
|
+
* - `0` — literal text only (`messages`, `users:batchGet`), which matches one value
|
|
5
|
+
* - `1` — a template mixed with literal text (`{jobId}:cancel`), which matches a subset of values
|
|
6
|
+
* - `2` — nothing but templates (`{id}`, `{a}{b}`), which matches any value
|
|
7
|
+
*/
|
|
8
|
+
type SegmentSpecificity = 0 | 1 | 2;
|
|
9
|
+
/**
|
|
10
|
+
* Describe how specific a path key is, one rank per `/`-separated segment of its path portion.
|
|
11
|
+
*
|
|
12
|
+
* The query string of the key is ignored: it does not take part in routing, and variants of one path
|
|
13
|
+
* are ordered among themselves by how many query parameters they pin.
|
|
14
|
+
*/
|
|
15
|
+
export declare const getPathSpecificity: (pathKey: string) => readonly SegmentSpecificity[];
|
|
16
|
+
/**
|
|
17
|
+
* Order two paths so the more concrete one is matched first, as the OpenAPI Paths Object asks:
|
|
18
|
+
* "When matching URLs, concrete (non-templated) paths would be matched before their templated
|
|
19
|
+
* counterparts."
|
|
20
|
+
*
|
|
21
|
+
* Segments are compared position by position and the first one that differs decides, so
|
|
22
|
+
* `/pets/mine` comes before `/pets/{petId}`, and `/a/literal/{y}` before `/a/{x}/b`. The specification
|
|
23
|
+
* leaves pairs like `/{entity}/me` and `/books/{id}` ambiguous and up to the tooling; reading from
|
|
24
|
+
* the left, the way a path is resolved one segment at a time, settles them toward `/books/{id}`.
|
|
25
|
+
*
|
|
26
|
+
* Paths with a different number of segments can never match the same request, because a path
|
|
27
|
+
* parameter never matches a `/`, so the shorter one simply goes first to keep the order total. Paths
|
|
28
|
+
* that rank the same return `0` and keep their relative order in a stable sort.
|
|
29
|
+
*/
|
|
30
|
+
export declare const comparePathSpecificity: (left: readonly SegmentSpecificity[], right: readonly SegmentSpecificity[]) => number;
|
|
31
|
+
export {};
|
|
32
|
+
//# sourceMappingURL=path-specificity.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"path-specificity.d.ts","sourceRoot":"","sources":["../../src/utils/path-specificity.ts"],"names":[],"mappings":"AAGA;;;;;;GAMG;AACH,KAAK,kBAAkB,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;AA8BnC;;;;;GAKG;AACH,eAAO,MAAM,kBAAkB,GAAI,SAAS,MAAM,KAAG,SAAS,kBAAkB,EAK/E,CAAA;AAED;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,sBAAsB,GACjC,MAAM,SAAS,kBAAkB,EAAE,EACnC,OAAO,SAAS,kBAAkB,EAAE,KACnC,MAUF,CAAA"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { LITERAL_PARAMETER_PREFIX, honoRouteSegmentsFromPath } from './hono-route-from-path.js';
|
|
2
|
+
import { PATH_KEY_TEMPLATE, splitPathKey } from './split-path-key.js';
|
|
3
|
+
/** Matches a segment the route compiler turned into a parameter with an explicit pattern. */
|
|
4
|
+
const PATTERN_SEGMENT = new RegExp(`^:${LITERAL_PARAMETER_PREFIX}\\d+\\{`);
|
|
5
|
+
/**
|
|
6
|
+
* Rank one segment of a path key, given the Hono route segment it compiles to.
|
|
7
|
+
*
|
|
8
|
+
* A segment that mixes a template with literal text ranks between the two, as long as the router
|
|
9
|
+
* actually enforces that literal text. Not every mixed segment compiles that way: `{name}.json`
|
|
10
|
+
* becomes the whole-segment parameter `:name.json`, which Hono matches against any value. Such a
|
|
11
|
+
* segment ranks like a bare template, because ranking it higher would let it answer requests meant
|
|
12
|
+
* for a plain `{id}` sibling that the document may well have declared first.
|
|
13
|
+
*/
|
|
14
|
+
const segmentSpecificity = (segment, routeSegment) => {
|
|
15
|
+
const literalText = segment.replace(PATH_KEY_TEMPLATE, '');
|
|
16
|
+
if (literalText === segment) {
|
|
17
|
+
return 0;
|
|
18
|
+
}
|
|
19
|
+
if (literalText === '') {
|
|
20
|
+
return 2;
|
|
21
|
+
}
|
|
22
|
+
const matchesAnyValue = routeSegment.startsWith(':') && !PATTERN_SEGMENT.test(routeSegment);
|
|
23
|
+
return matchesAnyValue ? 2 : 1;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Describe how specific a path key is, one rank per `/`-separated segment of its path portion.
|
|
27
|
+
*
|
|
28
|
+
* The query string of the key is ignored: it does not take part in routing, and variants of one path
|
|
29
|
+
* are ordered among themselves by how many query parameters they pin.
|
|
30
|
+
*/
|
|
31
|
+
export const getPathSpecificity = (pathKey) => {
|
|
32
|
+
const { path: pathname } = splitPathKey(pathKey);
|
|
33
|
+
const routeSegments = honoRouteSegmentsFromPath(pathname);
|
|
34
|
+
return pathname.split('/').map((segment, index) => segmentSpecificity(segment, routeSegments[index] ?? ''));
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* Order two paths so the more concrete one is matched first, as the OpenAPI Paths Object asks:
|
|
38
|
+
* "When matching URLs, concrete (non-templated) paths would be matched before their templated
|
|
39
|
+
* counterparts."
|
|
40
|
+
*
|
|
41
|
+
* Segments are compared position by position and the first one that differs decides, so
|
|
42
|
+
* `/pets/mine` comes before `/pets/{petId}`, and `/a/literal/{y}` before `/a/{x}/b`. The specification
|
|
43
|
+
* leaves pairs like `/{entity}/me` and `/books/{id}` ambiguous and up to the tooling; reading from
|
|
44
|
+
* the left, the way a path is resolved one segment at a time, settles them toward `/books/{id}`.
|
|
45
|
+
*
|
|
46
|
+
* Paths with a different number of segments can never match the same request, because a path
|
|
47
|
+
* parameter never matches a `/`, so the shorter one simply goes first to keep the order total. Paths
|
|
48
|
+
* that rank the same return `0` and keep their relative order in a stable sort.
|
|
49
|
+
*/
|
|
50
|
+
export const comparePathSpecificity = (left, right) => {
|
|
51
|
+
for (let index = 0; index < Math.min(left.length, right.length); index++) {
|
|
52
|
+
const difference = (left[index] ?? 0) - (right[index] ?? 0);
|
|
53
|
+
if (difference !== 0) {
|
|
54
|
+
return difference;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return left.length - right.length;
|
|
58
|
+
};
|
|
@@ -8,6 +8,10 @@ export type ProcessedDocument = {
|
|
|
8
8
|
type: 'asyncapi';
|
|
9
9
|
document: AsyncApiDocument;
|
|
10
10
|
};
|
|
11
|
-
/**
|
|
11
|
+
/**
|
|
12
|
+
* Bundle API descriptions once, retaining AsyncAPI and upgrading compatible OpenAPI input.
|
|
13
|
+
*
|
|
14
|
+
* An object input is never modified; the returned document is built from a copy of it.
|
|
15
|
+
*/
|
|
12
16
|
export declare const processDocument: (document: string | Record<string, unknown> | undefined, origin?: string) => Promise<ProcessedDocument>;
|
|
13
17
|
//# sourceMappingURL=process-document.d.ts.map
|
|
@@ -1 +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;
|
|
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;AAKlE,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;;;;GAIG;AACH,eAAO,MAAM,eAAe,GAC1B,UAAU,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EACtD,SAAS,MAAM,KACd,OAAO,CAAC,iBAAiB,CA2E3B,CAAA"}
|
|
@@ -8,7 +8,12 @@ import { isHttpUrl } from '@scalar/json-magic/helpers/is-http-url';
|
|
|
8
8
|
import { createMagicProxy } from '@scalar/json-magic/magic-proxy';
|
|
9
9
|
import { upgrade } from '@scalar/openapi-upgrader';
|
|
10
10
|
import { openApiDocument, resolveOpenApiDocument } from '@scalar/workspace-store/plugins/bundler';
|
|
11
|
-
|
|
11
|
+
import { cloneDocument } from './clone-document.js';
|
|
12
|
+
/**
|
|
13
|
+
* Bundle API descriptions once, retaining AsyncAPI and upgrading compatible OpenAPI input.
|
|
14
|
+
*
|
|
15
|
+
* An object input is never modified; the returned document is built from a copy of it.
|
|
16
|
+
*/
|
|
12
17
|
export const processDocument = async (document, origin) => {
|
|
13
18
|
// Handle empty/undefined input gracefully
|
|
14
19
|
if (!document || (typeof document === 'object' && Object.keys(document).length === 0)) {
|
|
@@ -34,7 +39,9 @@ export const processDocument = async (document, origin) => {
|
|
|
34
39
|
try {
|
|
35
40
|
// Bundle external references with Node.js plugins
|
|
36
41
|
// Include parseJson and parseYaml to handle string inputs
|
|
37
|
-
|
|
42
|
+
// `bundle` edits the object it is handed — it records external documents under `x-ext` and drops
|
|
43
|
+
// `x-ext-urls` — so an object input is copied first and the caller's document is left as passed.
|
|
44
|
+
bundled = await bundle(typeof document === 'string' ? document : cloneDocument(document), {
|
|
38
45
|
origin,
|
|
39
46
|
plugins: [
|
|
40
47
|
openApiDocument(),
|
package/package.json
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"swagger",
|
|
17
17
|
"cli"
|
|
18
18
|
],
|
|
19
|
-
"version": "0.
|
|
19
|
+
"version": "0.21.0",
|
|
20
20
|
"engines": {
|
|
21
21
|
"node": ">=22.19.0"
|
|
22
22
|
},
|
|
@@ -52,12 +52,12 @@
|
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
54
|
"@faker-js/faker": "10.6.0",
|
|
55
|
-
"@scalar/helpers": "0.
|
|
56
|
-
"@scalar/json-magic": "0.
|
|
55
|
+
"@scalar/helpers": "0.17.0",
|
|
56
|
+
"@scalar/json-magic": "0.18.0",
|
|
57
57
|
"@scalar/openapi-types": "0.9.8",
|
|
58
|
-
"@scalar/openapi-upgrader": "0.4.
|
|
59
|
-
"@scalar/types": "0.
|
|
60
|
-
"@scalar/workspace-store": "0.
|
|
58
|
+
"@scalar/openapi-upgrader": "0.4.7",
|
|
59
|
+
"@scalar/types": "0.27.0",
|
|
60
|
+
"@scalar/workspace-store": "0.70.0",
|
|
61
61
|
"ajv": "^8.20.0",
|
|
62
62
|
"ajv-formats": "^3.0.1",
|
|
63
63
|
"hono": "^4.13.13",
|