@scalar/mock-server 0.20.3 → 0.21.1
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 +41 -0
- package/dist/create-openapi-mock-server.d.ts.map +1 -1
- package/dist/create-openapi-mock-server.js +78 -19
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/libs/store.d.ts.map +1 -1
- package/dist/libs/store.js +13 -11
- package/dist/routes/mock-any-response.d.ts.map +1 -1
- package/dist/routes/mock-any-response.js +34 -9
- 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/drop-read-only-required.d.ts +8 -0
- package/dist/utils/drop-read-only-required.d.ts.map +1 -0
- package/dist/utils/drop-read-only-required.js +72 -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 +23 -6
- package/dist/utils/hono-route-from-path.d.ts.map +1 -1
- package/dist/utils/hono-route-from-path.js +82 -20
- package/dist/utils/is-settable-response-header.d.ts +3 -0
- package/dist/utils/is-settable-response-header.d.ts.map +1 -0
- package/dist/utils/is-settable-response-header.js +6 -0
- package/dist/utils/mocked-operation.d.ts +21 -0
- package/dist/utils/mocked-operation.d.ts.map +1 -0
- package/dist/utils/mocked-operation.js +13 -0
- package/dist/utils/path-parameters.d.ts +3 -1
- package/dist/utils/path-parameters.d.ts.map +1 -1
- package/dist/utils/path-parameters.js +24 -3
- 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 +47 -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/dist/utils/sandbox.d.ts.map +1 -1
- package/dist/utils/sandbox.js +23 -0
- package/dist/utils/validate-request.d.ts.map +1 -1
- package/dist/utils/validate-request.js +10 -2
- package/package.json +8 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,46 @@
|
|
|
1
1
|
# @scalar/mock-server
|
|
2
2
|
|
|
3
|
+
## 0.21.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#10951](https://github.com/scalar/scalar/pull/10951): Use shortest round-trip decimal values consistently for multipleOf checks, including large JSON integers and positive exponents. Fast-path safe integers and share keyword registration across validators.
|
|
8
|
+
- [#10951](https://github.com/scalar/scalar/pull/10951): Validate decimal `multipleOf` constraints with exact decimal arithmetic, accepting values such as `19.99` and `1000000.19` for `multipleOf: 0.01` while rejecting nonmultiples without a floating-point tolerance.
|
|
9
|
+
- [#10813](https://github.com/scalar/scalar/pull/10813): fix: keep the required properties of an object that the example depth cap truncates, so a deeply nested mock response no longer serves `{}` where its schema requires keys, including keys required through `allOf` members or the selected `oneOf`/`anyOf` variant
|
|
10
|
+
|
|
11
|
+
Preserve explicit values equal to the depth marker and exclude requirements from unselected union branches.
|
|
12
|
+
|
|
13
|
+
Keep required primitive compositions on the normal traversal and collect discriminator requirements from the branch rendered after depth truncation.
|
|
14
|
+
|
|
15
|
+
Reuse evaluated discriminator values for required-property collection and keep inferred tuple arrays empty past the depth cap.
|
|
16
|
+
|
|
17
|
+
Preserve shared requirements and required primitive values through dynamic references, including requirements declared in dynamically referenced composition members.
|
|
18
|
+
|
|
19
|
+
Collect requirements separately when composition branches reuse a shared template under different dynamic bindings.
|
|
20
|
+
|
|
21
|
+
Exclude requirements from composition members omitted by the request or response mode.
|
|
22
|
+
|
|
23
|
+
- [#10950](https://github.com/scalar/scalar/pull/10950): Ignore declared Content-Length, Content-Encoding, and Content-Type response headers so generated bodies remain readable and empty responses do not inherit a declared content type.
|
|
24
|
+
|
|
25
|
+
Ignore other transport-managed headers, including Transfer-Encoding and Trailer. Skip and warn about malformed declared header names and values instead of failing the response.
|
|
26
|
+
|
|
27
|
+
- [#10938](https://github.com/scalar/scalar/pull/10938): fix: merge array items whose `allOf` describes an object without `type: object` on the first member into one example instead of one partial object per member
|
|
28
|
+
- [#10940](https://github.com/scalar/scalar/pull/10940): Route path segments that mix parameters with literal text, such as `{id}.json`, `{id}:cancel` and `v{version}`, only to requests that carry the literal text, and pass their parameters to request validation, `x-handler` and `x-variable`.
|
|
29
|
+
- [#10930](https://github.com/scalar/scalar/pull/10930): Accept request bodies that leave out required `readOnly` properties during request validation.
|
|
30
|
+
- [#10875](https://github.com/scalar/scalar/pull/10875): Keep mock store collections and item IDs isolated from inherited host properties, and validate keys passed through the script sandbox.
|
|
31
|
+
|
|
32
|
+
## 0.21.0
|
|
33
|
+
|
|
34
|
+
### Minor Changes
|
|
35
|
+
|
|
36
|
+
- [#10809](https://github.com/scalar/scalar/pull/10809): feat: add an `onResponse` hook to observe or replace the response for each request
|
|
37
|
+
|
|
38
|
+
### Patch Changes
|
|
39
|
+
|
|
40
|
+
- [#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
|
|
41
|
+
- [#10810](https://github.com/scalar/scalar/pull/10810): fix: leave an object document passed to `createMockServer` unchanged instead of bundling it in place
|
|
42
|
+
- [#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
|
|
43
|
+
|
|
3
44
|
## 0.20.3
|
|
4
45
|
|
|
5
46
|
## 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":"AAGA,OAAO,EAAgB,IAAI,EAA0B,MAAM,MAAM,CAAA;AAIjE,OAAO,KAAK,EAAE,iBAAiB,
|
|
1
|
+
{"version":3,"file":"create-openapi-mock-server.d.ts","sourceRoot":"","sources":["../src/create-openapi-mock-server.ts"],"names":[],"mappings":"AAGA,OAAO,EAAgB,IAAI,EAA0B,MAAM,MAAM,CAAA;AAIjE,OAAO,KAAK,EAAE,iBAAiB,EAA0B,MAAM,SAAS,CAAA;AAexE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAA;AAgFjE;;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,8 @@ 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 { getMatchedOperation, getMockedOperation, setMockedOperation, } from './utils/mocked-operation.js';
|
|
15
|
+
import { comparePathSpecificity, getPathSpecificity } from './utils/path-specificity.js';
|
|
14
16
|
import { requestMatchesPinnedQuery } from './utils/request-matches-pinned-query.js';
|
|
15
17
|
import { resolveLogger } from './utils/resolve-logger.js';
|
|
16
18
|
import { setUpAuthenticationRoutes } from './utils/set-up-authentication-routes.js';
|
|
@@ -20,13 +22,56 @@ import { store } from './libs/store.js';
|
|
|
20
22
|
import { mockAnyResponse } from './routes/mock-any-response.js';
|
|
21
23
|
import { mockHandlerResponse } from './routes/mock-handler-response.js';
|
|
22
24
|
import { respondWithOpenApiDocument } from './routes/respond-with-openapi-document.js';
|
|
23
|
-
/**
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
25
|
+
/**
|
|
26
|
+
* Make `response` the response of the request, keeping only the headers that were staged before the
|
|
27
|
+
* request was handled — the CORS headers — where `response` does not set them itself.
|
|
28
|
+
*
|
|
29
|
+
* Assigning `c.res` directly would merge every header of the response it replaces into the new one,
|
|
30
|
+
* overriding the new one's values, so the mock response's own headers (an `ETag`, a declared
|
|
31
|
+
* `X-Rate-Limit`) would leak into a replacement that deliberately sets different ones.
|
|
32
|
+
*/
|
|
33
|
+
const replaceResponse = (c, response, stagedHeaders) => {
|
|
34
|
+
// Rebuilt so the headers are mutable even when the caller passed a response with immutable ones,
|
|
35
|
+
// such as one returned by `fetch()`. The body stream is handed over as is, never read.
|
|
36
|
+
const replacement = new Response(response.body, response);
|
|
37
|
+
stagedHeaders.forEach((value, name) => {
|
|
38
|
+
if (!replacement.headers.has(name)) {
|
|
39
|
+
replacement.headers.set(name, value);
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
// Clearing it first is what stops Hono from merging the replaced response's headers in.
|
|
43
|
+
c.res = undefined;
|
|
44
|
+
c.res = replacement;
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* Run `onResponse` once the rest of the app has answered a request, sending its replacement when it
|
|
48
|
+
* returns one.
|
|
49
|
+
*
|
|
50
|
+
* Registered as the first middleware after CORS, so it sees every response the app produces —
|
|
51
|
+
* mocked operations, authentication failures, validation errors, the document exports, `404`s and
|
|
52
|
+
* the error handler's `500`s (the error handler runs where the error is thrown, deeper down, before
|
|
53
|
+
* this middleware resumes) — while CORS preflight requests are still answered before it runs.
|
|
54
|
+
*/
|
|
55
|
+
const runResponseHook = (onResponse) => async (c, next) => {
|
|
56
|
+
// The CORS middleware stages its headers on the response before the request is handled. Copied
|
|
57
|
+
// now, before the mock response is merged over them, so a replacement can be given just these.
|
|
58
|
+
const stagedHeaders = new Headers(c.res.headers);
|
|
59
|
+
await next();
|
|
60
|
+
const response = c.res;
|
|
61
|
+
let replacement;
|
|
62
|
+
try {
|
|
63
|
+
replacement = await onResponse({ context: c, operation: getMatchedOperation(c), response });
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
// The error handler answers through the context, which would otherwise build the `500` on top
|
|
67
|
+
// of the mock response and carry all of its headers. Start it from the staged headers instead.
|
|
68
|
+
replaceResponse(c, new Response(null), stagedHeaders);
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
if (replacement && replacement !== response) {
|
|
72
|
+
replaceResponse(c, replacement, stagedHeaders);
|
|
73
|
+
}
|
|
27
74
|
};
|
|
28
|
-
/** Read back the operation a request matched, or `undefined` when it reached no mocked route */
|
|
29
|
-
const getMockedOperation = (c) => c.get('mockedOperation');
|
|
30
75
|
/**
|
|
31
76
|
* Whether an error carries its own response, the way Hono's `HTTPException` does.
|
|
32
77
|
*
|
|
@@ -108,6 +153,11 @@ export const createOpenApiMockServer = async (configuration, schema) => {
|
|
|
108
153
|
}
|
|
109
154
|
}
|
|
110
155
|
app.use(cors({ origin: '*', allowMethods: [...allowedMethods], exposeHeaders: ['X-Scalar-XML-Error'] }));
|
|
156
|
+
// Registered right after CORS and before every route, so it also wraps the routes a caller adds to
|
|
157
|
+
// the returned app.
|
|
158
|
+
if (configuration.onResponse) {
|
|
159
|
+
app.use(runResponseHook(configuration.onResponse));
|
|
160
|
+
}
|
|
111
161
|
/** Authentication methods defined in the OpenAPI document */
|
|
112
162
|
setUpAuthenticationRoutes(app, schema);
|
|
113
163
|
// Only the instructions honor `logger` (on by default); the util still prints warnings and errors
|
|
@@ -115,13 +165,24 @@ export const createOpenApiMockServer = async (configuration, schema) => {
|
|
|
115
165
|
logAuthenticationInstructions(schema?.components?.securitySchemes || {}, resolveLogger(configuration.logger, true));
|
|
116
166
|
/** Paths specified in the OpenAPI document */
|
|
117
167
|
const paths = schema?.paths ?? {};
|
|
118
|
-
//
|
|
119
|
-
//
|
|
120
|
-
//
|
|
121
|
-
//
|
|
168
|
+
// Hono runs every matching route in registration order and the first one that answers wins, so
|
|
169
|
+
// the order routes are registered in decides which operation serves a request that more than one
|
|
170
|
+
// path key matches. Two things set that order.
|
|
171
|
+
//
|
|
172
|
+
// First, concrete paths come before templated ones, as the OpenAPI Paths Object asks: `/pets/mine`
|
|
173
|
+
// answers its own requests even when the document declares `/pets/{petId}` first. Segments are
|
|
174
|
+
// compared from the left and the first one that differs decides; a segment mixing a template with
|
|
175
|
+
// literal text (`{jobId}:cancel`) ranks between a literal and a bare `{param}`. Path keys that rank
|
|
176
|
+
// the same keep the order the document declares them in. See `comparePathSpecificity`.
|
|
177
|
+
//
|
|
178
|
+
// Second, a path key may pin query parameters to describe a variant of an operation, for example
|
|
179
|
+
// `/v1/messages?beta=true` next to `/v1/messages`. A variant has to come before the sibling it shares
|
|
180
|
+
// a path with — otherwise the sibling answers its requests too — so the keys that share a path are
|
|
181
|
+
// grouped where the first of them appears, and the more pinned parameters a key has the earlier it
|
|
182
|
+
// goes. A variant that a request does not satisfy hands it on to the next matching route.
|
|
122
183
|
const pathKeys = Object.keys(paths).map((path) => {
|
|
123
184
|
const { path: pathname, query } = splitPathKey(path);
|
|
124
|
-
return { path, pathname, query };
|
|
185
|
+
return { path, pathname, query, specificity: getPathSpecificity(pathname) };
|
|
125
186
|
});
|
|
126
187
|
/** Where each path first shows up in the document, so its variants stay with it */
|
|
127
188
|
const documentOrder = new Map();
|
|
@@ -130,13 +191,11 @@ export const createOpenApiMockServer = async (configuration, schema) => {
|
|
|
130
191
|
documentOrder.set(pathname, index);
|
|
131
192
|
}
|
|
132
193
|
});
|
|
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);
|
|
194
|
+
// Paths that cannot match the same request may change places here, which is harmless: only the
|
|
195
|
+
// relative order of overlapping routes decides which operation answers.
|
|
196
|
+
const orderedPathKeys = [...pathKeys].sort((a, b) => comparePathSpecificity(a.specificity, b.specificity) ||
|
|
197
|
+
(documentOrder.get(a.pathname) ?? 0) - (documentOrder.get(b.pathname) ?? 0) ||
|
|
198
|
+
b.query.length - a.query.length);
|
|
140
199
|
orderedPathKeys.forEach(({ path, query }) => {
|
|
141
200
|
// A path item may itself be a `$ref`, so resolve it before reading its operations.
|
|
142
201
|
const pathItem = getResolvedRef(paths[path]);
|
|
@@ -160,7 +219,7 @@ export const createOpenApiMockServer = async (configuration, schema) => {
|
|
|
160
219
|
// path key that pins a query it is part of the guarded chain below, so it only fires once the
|
|
161
220
|
// request actually matches the variant rather than for one that is handed on to the sibling.
|
|
162
221
|
handlers.push(async (c, next) => {
|
|
163
|
-
setMockedOperation(c, mockedOperation);
|
|
222
|
+
setMockedOperation(c, mockedOperation, operation);
|
|
164
223
|
await next();
|
|
165
224
|
});
|
|
166
225
|
// 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"}
|
package/dist/libs/store.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/libs/store.ts"],"names":[],"mappings":"AAMA,qBAAa,KAAK;
|
|
1
|
+
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/libs/store.ts"],"names":[],"mappings":"AAMA,qBAAa,KAAK;IAEhB,OAAO,CAAC,IAAI,CAAiC;IAE7C;;OAEG;IACH,IAAI,CAAC,UAAU,EAAE,MAAM,GAAG,GAAG,EAAE;IAK/B;;OAEG;IACH,GAAG,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,GAAG,GAAG,SAAS;IAIpD;;;OAGG;IACH,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,GAAG,GAAG;IAc1C;;;OAGG;IACH,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,GAAG,GAAG,GAAG,IAAI;IAc7D;;;OAGG;IACH,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,GAAG,IAAI;IAWtD;;OAEG;IACH,KAAK,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI;CAOjC;AAED;;GAEG;AACH,eAAO,MAAM,KAAK,OAAc,CAAA"}
|
package/dist/libs/store.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export class Store {
|
|
2
|
-
|
|
2
|
+
// Collection names and item IDs come from guest code, so neither lookup may inherit host properties.
|
|
3
|
+
data = Object.create(null);
|
|
3
4
|
/**
|
|
4
5
|
* Get all items in a collection.
|
|
5
6
|
*/
|
|
@@ -18,14 +19,13 @@ export class Store {
|
|
|
18
19
|
* Auto-generates an ID if not provided.
|
|
19
20
|
*/
|
|
20
21
|
create(collection, data) {
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
}
|
|
22
|
+
const items = this.data[collection] ?? Object.create(null);
|
|
23
|
+
this.data[collection] = items;
|
|
24
24
|
// Handle null/undefined data by defaulting to empty object
|
|
25
25
|
const safeData = data ?? {};
|
|
26
26
|
const id = safeData.id ?? crypto.randomUUID();
|
|
27
27
|
const item = { ...safeData, id };
|
|
28
|
-
|
|
28
|
+
items[id] = item;
|
|
29
29
|
return item;
|
|
30
30
|
}
|
|
31
31
|
/**
|
|
@@ -33,13 +33,14 @@ export class Store {
|
|
|
33
33
|
* Returns null if the item is not found.
|
|
34
34
|
*/
|
|
35
35
|
update(collection, id, data) {
|
|
36
|
-
|
|
36
|
+
const items = this.data[collection];
|
|
37
|
+
if (!items || !(id in items)) {
|
|
37
38
|
return null;
|
|
38
39
|
}
|
|
39
40
|
// Handle null/undefined data by defaulting to empty object
|
|
40
41
|
const safeData = data ?? {};
|
|
41
|
-
const updated = { ...
|
|
42
|
-
|
|
42
|
+
const updated = { ...items[id], ...safeData, id };
|
|
43
|
+
items[id] = updated;
|
|
43
44
|
return updated;
|
|
44
45
|
}
|
|
45
46
|
/**
|
|
@@ -47,10 +48,11 @@ export class Store {
|
|
|
47
48
|
* Returns null if the item is not found.
|
|
48
49
|
*/
|
|
49
50
|
delete(collection, id) {
|
|
50
|
-
|
|
51
|
+
const items = this.data[collection];
|
|
52
|
+
if (!items || !(id in items)) {
|
|
51
53
|
return null;
|
|
52
54
|
}
|
|
53
|
-
delete
|
|
55
|
+
delete items[id];
|
|
54
56
|
return true;
|
|
55
57
|
}
|
|
56
58
|
/**
|
|
@@ -61,7 +63,7 @@ export class Store {
|
|
|
61
63
|
delete this.data[collection];
|
|
62
64
|
}
|
|
63
65
|
else {
|
|
64
|
-
this.data =
|
|
66
|
+
this.data = Object.create(null);
|
|
65
67
|
}
|
|
66
68
|
}
|
|
67
69
|
}
|
|
@@ -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;
|
|
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;AA8BnC;;GAEG;AACH,wBAAgB,eAAe,CAAC,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,WAAW,CAAC,eAAe,EAAE,cAAc,CAAC,EAAE,MAAM,YAuK1G"}
|
|
@@ -6,6 +6,7 @@ import { streamSSE } from 'hono/streaming';
|
|
|
6
6
|
import { collectSseEvents, isEventStreamContentType } from '../utils/collect-sse-events.js';
|
|
7
7
|
import { findPreferredResponseKey } from '../utils/find-preferred-response-key.js';
|
|
8
8
|
import { generateResponseExample } from '../utils/generate-response-example.js';
|
|
9
|
+
import { isSettableResponseHeader } from '../utils/is-settable-response-header.js';
|
|
9
10
|
import { negotiateContentType } from '../utils/negotiate-content-type.js';
|
|
10
11
|
import { normalizeResponseBody } from '../utils/normalize-response-body.js';
|
|
11
12
|
import { parsePreferHeader } from '../utils/parse-prefer-header.js';
|
|
@@ -13,6 +14,19 @@ import { pathParameters } from '../utils/path-parameters.js';
|
|
|
13
14
|
import { selectResponseExample } from '../utils/select-response-example.js';
|
|
14
15
|
import { serializeResponseBody } from '../utils/serialize-response-body.js';
|
|
15
16
|
import { getStreamingResponse, sendStreamingResponse } from '../utils/streaming-response.js';
|
|
17
|
+
/** These fields are owned by the response serializer and transport, never the API description. */
|
|
18
|
+
const IGNORED_RESPONSE_HEADERS = new Set([
|
|
19
|
+
'content-length',
|
|
20
|
+
'content-encoding',
|
|
21
|
+
'content-type',
|
|
22
|
+
'transfer-encoding',
|
|
23
|
+
'trailer',
|
|
24
|
+
'connection',
|
|
25
|
+
'keep-alive',
|
|
26
|
+
'upgrade',
|
|
27
|
+
'te',
|
|
28
|
+
'proxy-connection',
|
|
29
|
+
]);
|
|
16
30
|
/**
|
|
17
31
|
* Mock any response
|
|
18
32
|
*/
|
|
@@ -38,17 +52,29 @@ export function mockAnyResponse(c, operation, openapiVersion) {
|
|
|
38
52
|
// Headers
|
|
39
53
|
const headers = selectedResponse?.headers ?? {};
|
|
40
54
|
Object.keys(headers).forEach((header) => {
|
|
55
|
+
// The body and transport determine these headers. Generated values can truncate a response or
|
|
56
|
+
// make clients decode uncompressed data; OpenAPI also requires ignoring declared Content-Type.
|
|
57
|
+
if (IGNORED_RESPONSE_HEADERS.has(header.toLowerCase())) {
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
41
60
|
const headerObject = getResolvedRef(headers[header]);
|
|
42
|
-
// Headers
|
|
43
|
-
|
|
44
|
-
const value = headerObject?.schema
|
|
45
|
-
? getExampleFromSchema(getResolvedRefDeep(headerObject.schema), { includeDeprecated: true })
|
|
46
|
-
: null;
|
|
61
|
+
// Headers use the generator defaults to preserve their declared values.
|
|
62
|
+
const value = headerObject?.schema ? getExampleFromSchema(getResolvedRefDeep(headerObject.schema)) : null;
|
|
47
63
|
// Loose check on purpose: Hono *deletes* a header when handed `undefined`. This loop is the first
|
|
48
64
|
// thing to set the declared headers, so in practice a delete removes a header set earlier by
|
|
49
65
|
// middleware — `cors()` sets `Access-Control-Allow-Origin` before the handler runs.
|
|
50
66
|
if (value != null) {
|
|
51
|
-
|
|
67
|
+
try {
|
|
68
|
+
const text = String(value);
|
|
69
|
+
if (isSettableResponseHeader(header, text)) {
|
|
70
|
+
c.header(header, text);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
// An authored object can also shadow toString and prevent string conversion.
|
|
76
|
+
}
|
|
77
|
+
console.warn(`Skipping invalid response header ${JSON.stringify(header)} from the API description.`);
|
|
52
78
|
}
|
|
53
79
|
});
|
|
54
80
|
// For 204 No Content responses, we should not set Content-Type and should return null body
|
|
@@ -86,9 +112,8 @@ export function mockAnyResponse(c, operation, openapiVersion) {
|
|
|
86
112
|
generate: generateFromSchema,
|
|
87
113
|
});
|
|
88
114
|
c.status(statusCode);
|
|
89
|
-
//
|
|
90
|
-
//
|
|
91
|
-
// they are what makes the stream readable. Every other declared header set above survives.
|
|
115
|
+
// Transport headers are never copied from the API description. `streamSSE` adds the framing
|
|
116
|
+
// and cache policy needed for an event stream; ordinary custom headers survive.
|
|
92
117
|
return streamSSE(c, async (stream) => {
|
|
93
118
|
for (const event of events) {
|
|
94
119
|
if (event.framed) {
|
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());
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Remove `readOnly` properties from `required` throughout a request body schema.
|
|
3
|
+
*
|
|
4
|
+
* OpenAPI only enforces `required` for a `readOnly` property on responses, so a client creating a
|
|
5
|
+
* resource must be able to leave out server-assigned fields such as `id` or `createdAt`.
|
|
6
|
+
*/
|
|
7
|
+
export declare const dropReadOnlyRequired: (schema: unknown, readOnlyNames?: ReadonlySet<string>) => unknown;
|
|
8
|
+
//# sourceMappingURL=drop-read-only-required.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"drop-read-only-required.d.ts","sourceRoot":"","sources":["../../src/utils/drop-read-only-required.ts"],"names":[],"mappings":"AAqCA;;;;;GAKG;AACH,eAAO,MAAM,oBAAoB,GAAI,QAAQ,OAAO,EAAE,gBAAe,WAAW,CAAC,MAAM,CAAa,KAAG,OAyCtG,CAAA"}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { isObject } from '@scalar/helpers/object/is-object';
|
|
2
|
+
/** Keywords whose subschemas describe the same instance, so a read-only property declared beside them still applies */
|
|
3
|
+
const SAME_INSTANCE_KEYWORDS = new Set(['allOf', 'anyOf', 'oneOf', 'then', 'else']);
|
|
4
|
+
/** Keywords whose subschemas describe a different instance (an item, a property value, …) */
|
|
5
|
+
const NESTED_INSTANCE_KEYWORDS = new Set([
|
|
6
|
+
'additionalItems',
|
|
7
|
+
'additionalProperties',
|
|
8
|
+
'contains',
|
|
9
|
+
'items',
|
|
10
|
+
'prefixItems',
|
|
11
|
+
'unevaluatedItems',
|
|
12
|
+
'unevaluatedProperties',
|
|
13
|
+
]);
|
|
14
|
+
/** Keywords whose value maps author-chosen names to schemas */
|
|
15
|
+
const SCHEMA_MAP_KEYWORDS = new Set(['$defs', 'definitions', 'dependentSchemas', 'patternProperties', 'properties']);
|
|
16
|
+
/** Only unconditional annotations apply when a property is omitted, so union and conditional branches are excluded. */
|
|
17
|
+
const isReadOnlyProperty = (schema) => isObject(schema) &&
|
|
18
|
+
(schema.readOnly === true || (Array.isArray(schema.allOf) && schema.allOf.some(isReadOnlyProperty)));
|
|
19
|
+
/** Names of the properties a schema, or any `allOf` member of it, marks as `readOnly` */
|
|
20
|
+
const getReadOnlyPropertyNames = (schema) => {
|
|
21
|
+
const own = isObject(schema.properties)
|
|
22
|
+
? Object.entries(schema.properties)
|
|
23
|
+
.filter(([, property]) => isReadOnlyProperty(property))
|
|
24
|
+
.map(([name]) => name)
|
|
25
|
+
: [];
|
|
26
|
+
const inherited = Array.isArray(schema.allOf)
|
|
27
|
+
? schema.allOf.filter(isObject).flatMap((member) => getReadOnlyPropertyNames(member))
|
|
28
|
+
: [];
|
|
29
|
+
return [...own, ...inherited];
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Remove `readOnly` properties from `required` throughout a request body schema.
|
|
33
|
+
*
|
|
34
|
+
* OpenAPI only enforces `required` for a `readOnly` property on responses, so a client creating a
|
|
35
|
+
* resource must be able to leave out server-assigned fields such as `id` or `createdAt`.
|
|
36
|
+
*/
|
|
37
|
+
export const dropReadOnlyRequired = (schema, readOnlyNames = new Set()) => {
|
|
38
|
+
if (Array.isArray(schema)) {
|
|
39
|
+
return schema.map((item) => dropReadOnlyRequired(item));
|
|
40
|
+
}
|
|
41
|
+
if (!isObject(schema)) {
|
|
42
|
+
return schema;
|
|
43
|
+
}
|
|
44
|
+
const names = new Set([...readOnlyNames, ...getReadOnlyPropertyNames(schema)]);
|
|
45
|
+
return Object.fromEntries(Object.entries(schema).map(([keyword, value]) => {
|
|
46
|
+
// These schemas test predicates rather than require fields in the request.
|
|
47
|
+
// Relaxing them could select a different branch or make a negation reject a valid body.
|
|
48
|
+
if (keyword === 'if' || keyword === 'not') {
|
|
49
|
+
return [keyword, value];
|
|
50
|
+
}
|
|
51
|
+
if (keyword === 'required' && Array.isArray(value)) {
|
|
52
|
+
return [keyword, value.filter((name) => !names.has(name))];
|
|
53
|
+
}
|
|
54
|
+
if (SAME_INSTANCE_KEYWORDS.has(keyword)) {
|
|
55
|
+
const relax = (member) => dropReadOnlyRequired(member, names);
|
|
56
|
+
return [keyword, Array.isArray(value) ? value.map(relax) : relax(value)];
|
|
57
|
+
}
|
|
58
|
+
if (NESTED_INSTANCE_KEYWORDS.has(keyword)) {
|
|
59
|
+
return [keyword, dropReadOnlyRequired(value)];
|
|
60
|
+
}
|
|
61
|
+
if (SCHEMA_MAP_KEYWORDS.has(keyword) && isObject(value)) {
|
|
62
|
+
return [
|
|
63
|
+
keyword,
|
|
64
|
+
Object.fromEntries(Object.entries(value).map(([name, member]) => [
|
|
65
|
+
name,
|
|
66
|
+
dropReadOnlyRequired(member, keyword === 'dependentSchemas' ? names : undefined),
|
|
67
|
+
])),
|
|
68
|
+
];
|
|
69
|
+
}
|
|
70
|
+
return [keyword, value];
|
|
71
|
+
}));
|
|
72
|
+
};
|
|
@@ -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"}
|