@scalar/mock-server 0.17.6 → 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 (69) hide show
  1. package/CHANGELOG.md +25 -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 +24 -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-authorize-page.d.ts +1 -1
  15. package/dist/routes/respond-with-authorize-page.d.ts.map +1 -1
  16. package/dist/routes/respond-with-authorize-page.js +9 -6
  17. package/dist/routes/respond-with-openapi-document.d.ts +1 -1
  18. package/dist/routes/respond-with-token.d.ts +1 -10
  19. package/dist/routes/respond-with-token.d.ts.map +1 -1
  20. package/dist/routes/respond-with-token.js +8 -5
  21. package/dist/transports/sse.d.ts.map +1 -1
  22. package/dist/transports/sse.js +17 -13
  23. package/dist/transports/types.d.ts +12 -2
  24. package/dist/transports/types.d.ts.map +1 -1
  25. package/dist/transports/websocket.d.ts.map +1 -1
  26. package/dist/transports/websocket.js +38 -30
  27. package/dist/types.d.ts +20 -8
  28. package/dist/types.d.ts.map +1 -1
  29. package/dist/utils/authenticate-asyncapi-channel.d.ts +9 -0
  30. package/dist/utils/authenticate-asyncapi-channel.d.ts.map +1 -0
  31. package/dist/utils/authenticate-asyncapi-channel.js +49 -0
  32. package/dist/utils/digest-authentication.d.ts +6 -0
  33. package/dist/utils/digest-authentication.d.ts.map +1 -0
  34. package/dist/utils/digest-authentication.js +35 -0
  35. package/dist/utils/get-asyncapi-document.d.ts +4 -0
  36. package/dist/utils/get-asyncapi-document.d.ts.map +1 -0
  37. package/dist/utils/get-asyncapi-document.js +47 -0
  38. package/dist/utils/get-asyncapi-security-schemes.d.ts +4 -0
  39. package/dist/utils/get-asyncapi-security-schemes.d.ts.map +1 -0
  40. package/dist/utils/get-asyncapi-security-schemes.js +17 -0
  41. package/dist/utils/handle-authentication.d.ts +14 -0
  42. package/dist/utils/handle-authentication.d.ts.map +1 -1
  43. package/dist/utils/handle-authentication.js +21 -6
  44. package/dist/utils/log-authentication-instructions.d.ts +3 -1
  45. package/dist/utils/log-authentication-instructions.d.ts.map +1 -1
  46. package/dist/utils/log-authentication-instructions.js +10 -2
  47. package/dist/utils/process-document.d.ts +13 -0
  48. package/dist/utils/process-document.d.ts.map +1 -0
  49. package/dist/utils/{process-openapi-document.js → process-document.js} +18 -26
  50. package/dist/utils/resolve-channels.d.ts.map +1 -1
  51. package/dist/utils/resolve-channels.js +39 -11
  52. package/dist/utils/resolve-server-pathnames.d.ts +4 -0
  53. package/dist/utils/resolve-server-pathnames.d.ts.map +1 -0
  54. package/dist/utils/resolve-server-pathnames.js +14 -0
  55. package/dist/utils/set-up-asyncapi-authentication-routes.d.ts +5 -0
  56. package/dist/utils/set-up-asyncapi-authentication-routes.d.ts.map +1 -0
  57. package/dist/utils/set-up-asyncapi-authentication-routes.js +37 -0
  58. package/dist/utils/set-up-authentication-routes.d.ts.map +1 -1
  59. package/dist/utils/set-up-authentication-routes.js +9 -18
  60. package/dist/utils/set-up-device-authorization.js +1 -1
  61. package/dist/utils/set-up-openid-connect.d.ts +4 -0
  62. package/dist/utils/set-up-openid-connect.d.ts.map +1 -0
  63. package/dist/utils/set-up-openid-connect.js +196 -0
  64. package/package.json +10 -10
  65. package/dist/utils/process-asyncapi-document.d.ts +0 -24
  66. package/dist/utils/process-asyncapi-document.d.ts.map +0 -1
  67. package/dist/utils/process-asyncapi-document.js +0 -64
  68. package/dist/utils/process-openapi-document.d.ts +0 -19
  69. package/dist/utils/process-openapi-document.d.ts.map +0 -1
@@ -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
+ };
@@ -0,0 +1,5 @@
1
+ import type { AsyncApiDocument } from '@scalar/types/asyncapi/3.1';
2
+ import type { Hono } from 'hono';
3
+ /** Adapt AsyncAPI OAuth and OpenID Connect schemes to the shared mock authorization and token handlers. */
4
+ export declare const setUpAsyncApiAuthenticationRoutes: (app: Hono, document: AsyncApiDocument) => void;
5
+ //# sourceMappingURL=set-up-asyncapi-authentication-routes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"set-up-asyncapi-authentication-routes.d.ts","sourceRoot":"","sources":["../../src/utils/set-up-asyncapi-authentication-routes.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAA;AAElE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAA;AAKhC,2GAA2G;AAC3G,eAAO,MAAM,iCAAiC,GAAI,KAAK,IAAI,EAAE,UAAU,gBAAgB,KAAG,IAmCzF,CAAA"}
@@ -0,0 +1,37 @@
1
+ import { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref';
2
+ import { getAsyncApiSecuritySchemes } from './get-asyncapi-security-schemes.js';
3
+ import { setUpAuthenticationRoutes } from './set-up-authentication-routes.js';
4
+ /** Adapt AsyncAPI OAuth and OpenID Connect schemes to the shared mock authorization and token handlers. */
5
+ export const setUpAsyncApiAuthenticationRoutes = (app, document) => {
6
+ const securitySchemes = {};
7
+ for (const [index, rawScheme] of getAsyncApiSecuritySchemes(document).entries()) {
8
+ const scheme = getResolvedRef(rawScheme);
9
+ if (scheme?.type === 'openIdConnect') {
10
+ securitySchemes[index] = { type: 'openIdConnect', openIdConnectUrl: scheme.openIdConnectUrl };
11
+ continue;
12
+ }
13
+ if (scheme?.type !== 'oauth2') {
14
+ continue;
15
+ }
16
+ const sourceFlows = getResolvedRef(scheme.flows);
17
+ const flows = {};
18
+ for (const name of ['authorizationCode', 'implicit', 'password', 'clientCredentials']) {
19
+ const flow = getResolvedRef(sourceFlows?.[name]);
20
+ if (flow) {
21
+ flows[name] = {
22
+ authorizationUrl: flow.authorizationUrl,
23
+ tokenUrl: flow.tokenUrl,
24
+ refreshUrl: flow.refreshUrl,
25
+ scopes: flow.availableScopes,
26
+ };
27
+ }
28
+ }
29
+ securitySchemes[index] = { type: 'oauth2', flows };
30
+ }
31
+ // Only OAuth and OpenID Connect schemes are adapted; broker authentication has no OpenAPI equivalent.
32
+ setUpAuthenticationRoutes(app, {
33
+ openapi: '3.1.0',
34
+ info: { title: document.info.title, version: document.info.version },
35
+ components: { securitySchemes },
36
+ });
37
+ };
@@ -1 +1 @@
1
- {"version":3,"file":"set-up-authentication-routes.d.ts","sourceRoot":"","sources":["../../src/utils/set-up-authentication-routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAA0B,MAAM,uBAAuB,CAAA;AAE5E,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAA;AAShC;;GAEG;AACH,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,IAAI,EAAE,MAAM,CAAC,EAAE,OAAO,CAAC,QAAQ,QAiH7E"}
1
+ {"version":3,"file":"set-up-authentication-routes.d.ts","sourceRoot":"","sources":["../../src/utils/set-up-authentication-routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAA0B,MAAM,uBAAuB,CAAA;AAE5E,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAA;AAUhC;;GAEG;AACH,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,IAAI,EAAE,MAAM,CAAC,EAAE,OAAO,CAAC,QAAQ,QA0G7E"}
@@ -4,11 +4,17 @@ import { respondWithToken } from '../routes/respond-with-token.js';
4
4
  import { getOAuth2Metadata } from './get-oauth2-metadata.js';
5
5
  import { getOpenAuthTokenUrls, getPathFromUrl } from './get-open-auth-token-urls.js';
6
6
  import { setUpDeviceAuthorization } from './set-up-device-authorization.js';
7
+ import { setUpOpenIdConnect } from './set-up-openid-connect.js';
7
8
  /**
8
9
  * Helper function to set up authentication routes for OAuth 2.0 flows
9
10
  */
10
11
  export function setUpAuthenticationRoutes(app, schema) {
11
12
  const securitySchemes = schema?.components?.securitySchemes || {};
13
+ const discoveryUrls = Object.values(securitySchemes).flatMap((rawScheme) => {
14
+ const scheme = getResolvedRef(rawScheme);
15
+ return scheme?.type === 'openIdConnect' && scheme.openIdConnectUrl ? [scheme.openIdConnectUrl] : [];
16
+ });
17
+ setUpOpenIdConnect(app, discoveryUrls, schema?.info?.title ?? '', Object.values(securitySchemes).some((scheme) => getResolvedRef(scheme)?.type === 'oauth2'));
12
18
  setUpDeviceAuthorization(app, schema);
13
19
  // Set up authentication routes for OAuth 2.0 flows
14
20
  getOpenAuthTokenUrls(schema).forEach((tokenUrl) => {
@@ -68,25 +74,10 @@ export function setUpAuthenticationRoutes(app, schema) {
68
74
  }
69
75
  }
70
76
  else if (scheme.type === 'openIdConnect') {
71
- // Handle OpenID Connect configuration
77
+ // Non-OIDC OAuth requests still use the permissive shared mock handlers.
72
78
  if (scheme.openIdConnectUrl) {
73
- const configPath = getPathFromUrl(scheme.openIdConnectUrl ?? '/.well-known/openid-configuration');
74
- // Add route for OpenID Connect configuration
75
- app.get(configPath, (c) => {
76
- return c.json({
77
- issuer: 'https://example.com',
78
- authorization_endpoint: '/oauth/authorize',
79
- token_endpoint: '/oauth/token',
80
- response_types_supported: ['code', 'token', 'id_token'],
81
- subject_types_supported: ['public'],
82
- id_token_signing_alg_values_supported: ['RS256'],
83
- });
84
- });
85
- // Add standard endpoints
86
- const authorizeRoute = '/oauth/authorize';
87
- const tokenRoute = '/oauth/token';
88
- authorizeUrls.add(getPathFromUrl(authorizeRoute));
89
- tokenUrls.add(getPathFromUrl(tokenRoute));
79
+ authorizeUrls.add('/oauth/authorize');
80
+ tokenUrls.add('/oauth/token');
90
81
  }
91
82
  }
92
83
  });
@@ -6,7 +6,7 @@ const getClientId = (clientId, authorization) => {
6
6
  if (typeof clientId === 'string') {
7
7
  return clientId;
8
8
  }
9
- if (!authorization?.startsWith('Basic ')) {
9
+ if (!authorization || !/^Basic /i.test(authorization)) {
10
10
  return '';
11
11
  }
12
12
  const credentials = Buffer.from(authorization.slice(6), 'base64').toString();
@@ -0,0 +1,4 @@
1
+ import type { Hono } from 'hono';
2
+ /** Serve a small OIDC code-flow provider with verifiable ID tokens and a stable mock identity. */
3
+ export declare const setUpOpenIdConnect: (app: Hono, discoveryUrls: string[], title: string, allowOAuthFallback?: boolean) => void;
4
+ //# sourceMappingURL=set-up-openid-connect.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"set-up-openid-connect.d.ts","sourceRoot":"","sources":["../../src/utils/set-up-openid-connect.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAW,IAAI,EAAE,MAAM,MAAM,CAAA;AA0CzC,kGAAkG;AAClG,eAAO,MAAM,kBAAkB,GAC7B,KAAK,IAAI,EACT,eAAe,MAAM,EAAE,EACvB,OAAO,MAAM,EACb,4BAA0B,KACzB,IA+LF,CAAA"}
@@ -0,0 +1,196 @@
1
+ import { respondWithAuthorizePage } from '../routes/respond-with-authorize-page.js';
2
+ import { getPathFromUrl } from './get-open-auth-token-urls.js';
3
+ const SUBJECT = 'scalar-mock-user';
4
+ const encode = (bytes) => btoa(String.fromCharCode(...bytes))
5
+ .replace(/\+/g, '-')
6
+ .replace(/\//g, '_')
7
+ .replace(/=+$/, '');
8
+ const encodeJson = (value) => encode(new TextEncoder().encode(JSON.stringify(value)));
9
+ const now = () => Math.floor(Date.now() / 1000);
10
+ /** Expiring, bounded state keeps this development provider safe to leave running. */
11
+ const remember = (store, key, value) => {
12
+ for (const [existing, authorization] of store) {
13
+ if (authorization.expiresAt <= now()) {
14
+ store.delete(existing);
15
+ }
16
+ }
17
+ if (store.size >= 1000) {
18
+ const oldest = store.keys().next().value;
19
+ if (oldest) {
20
+ store.delete(oldest);
21
+ }
22
+ }
23
+ store.set(key, value);
24
+ };
25
+ /** Serve a small OIDC code-flow provider with verifiable ID tokens and a stable mock identity. */
26
+ export const setUpOpenIdConnect = (app, discoveryUrls, title, allowOAuthFallback = false) => {
27
+ if (discoveryUrls.length === 0) {
28
+ return;
29
+ }
30
+ // Workers forbid random number generation until a request handler runs.
31
+ let keyId;
32
+ const getKeyId = () => (keyId ??= crypto.randomUUID());
33
+ const codes = new Map();
34
+ const refreshTokens = new Map();
35
+ const accessTokens = new Map();
36
+ let keys;
37
+ const getKeys = () => {
38
+ keys ??= crypto.subtle.generateKey({ name: 'RSASSA-PKCS1-v1_5', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' }, true, ['sign', 'verify']);
39
+ return keys;
40
+ };
41
+ const tokenError = (c, error, description) => {
42
+ c.header('Cache-Control', 'no-store');
43
+ return c.json({ error, error_description: description }, 400);
44
+ };
45
+ for (const path of new Set(discoveryUrls.map((url) => getPathFromUrl(url, { preserveTrailingSlash: true })))) {
46
+ app.get(path, (c) => {
47
+ const origin = new URL(c.req.url).origin;
48
+ return c.json({
49
+ issuer: origin,
50
+ authorization_endpoint: `${origin}/oauth/authorize`,
51
+ token_endpoint: `${origin}/oauth/token`,
52
+ jwks_uri: `${origin}/oauth/jwks`,
53
+ userinfo_endpoint: `${origin}/oauth/userinfo`,
54
+ response_types_supported: ['code'],
55
+ grant_types_supported: ['authorization_code', 'refresh_token'],
56
+ subject_types_supported: ['public'],
57
+ id_token_signing_alg_values_supported: ['RS256'],
58
+ token_endpoint_auth_methods_supported: ['none'],
59
+ code_challenge_methods_supported: ['S256'],
60
+ scopes_supported: ['openid', 'profile', 'email'],
61
+ });
62
+ });
63
+ }
64
+ app.get('/oauth/jwks', async (c) => {
65
+ const key = await crypto.subtle.exportKey('jwk', (await getKeys()).publicKey);
66
+ return c.json({ keys: [{ ...key, kid: getKeyId(), use: 'sig', alg: 'RS256' }] });
67
+ });
68
+ app.get('/oauth/authorize', (c, next) => {
69
+ const scope = c.req.query('scope') ?? '';
70
+ if (!scope.split(/\s+/).includes('openid')) {
71
+ return next();
72
+ }
73
+ const clientId = c.req.query('client_id');
74
+ const redirectUri = c.req.query('redirect_uri');
75
+ if (!clientId || !redirectUri || c.req.query('response_type') !== 'code') {
76
+ return tokenError(c, 'invalid_request', 'OpenID Connect requires client_id, redirect_uri, and response_type=code');
77
+ }
78
+ try {
79
+ if (!['http:', 'https:'].includes(new URL(redirectUri).protocol)) {
80
+ throw new Error('Invalid redirect');
81
+ }
82
+ }
83
+ catch {
84
+ return tokenError(c, 'invalid_request', 'redirect_uri must be an HTTP or HTTPS URL');
85
+ }
86
+ const codeChallenge = c.req.query('code_challenge');
87
+ if (codeChallenge && (c.req.query('code_challenge_method') !== 'S256' || !/^[\w-]{43}$/.test(codeChallenge))) {
88
+ return tokenError(c, 'invalid_request', 'Only S256 PKCE challenges are supported');
89
+ }
90
+ const code = `oidc-code-${crypto.randomUUID()}`;
91
+ remember(codes, code, {
92
+ clientId,
93
+ redirectUri,
94
+ scope,
95
+ nonce: c.req.query('nonce'),
96
+ codeChallenge,
97
+ issuer: new URL(c.req.url).origin,
98
+ expiresAt: now() + 300,
99
+ });
100
+ return respondWithAuthorizePage(c, title, code);
101
+ });
102
+ app.post('/oauth/token', async (c, next) => {
103
+ const body = await c.req.parseBody();
104
+ const parameter = (name) => typeof body[name] === 'string' ? body[name] : c.req.query(name);
105
+ const code = parameter('code') ?? '';
106
+ const refresh = parameter('refresh_token') ?? '';
107
+ const scope = parameter('scope');
108
+ const authorization = codes.get(code) ?? refreshTokens.get(refresh);
109
+ // Ordinary OAuth mocks share this path. Claim only OIDC requests or tokens this provider issued.
110
+ if (allowOAuthFallback &&
111
+ !authorization &&
112
+ !code.startsWith('oidc-code-') &&
113
+ !refresh.startsWith('oidc-refresh-') &&
114
+ !scope?.split(/\s+/).includes('openid')) {
115
+ return next();
116
+ }
117
+ const grant = parameter('grant_type');
118
+ if (grant !== 'authorization_code' && grant !== 'refresh_token') {
119
+ return tokenError(c, 'unsupported_grant_type', 'OpenID Connect supports authorization_code and refresh_token');
120
+ }
121
+ const source = grant === 'authorization_code' ? codes : refreshTokens;
122
+ const credential = grant === 'authorization_code' ? code : refresh;
123
+ const session = source.get(credential);
124
+ if (!session ||
125
+ session.expiresAt <= now() ||
126
+ session.issuer !== new URL(c.req.url).origin ||
127
+ parameter('client_id') !== session.clientId) {
128
+ return tokenError(c, 'invalid_grant', 'Invalid or expired authorization for this client');
129
+ }
130
+ if (grant === 'authorization_code') {
131
+ if (parameter('redirect_uri') !== session.redirectUri) {
132
+ return tokenError(c, 'invalid_grant', 'redirect_uri does not match');
133
+ }
134
+ if (session.codeChallenge) {
135
+ const verifier = parameter('code_verifier') ?? '';
136
+ const challenge = encode(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
137
+ if (!/^[\w.~-]{43,128}$/.test(verifier) || challenge !== session.codeChallenge) {
138
+ return tokenError(c, 'invalid_grant', 'Invalid PKCE verifier');
139
+ }
140
+ }
141
+ }
142
+ const effectiveScope = scope ?? session.scope;
143
+ if (effectiveScope.split(/\s+/).some((value) => !session.scope.split(/\s+/).includes(value))) {
144
+ return tokenError(c, 'invalid_scope', 'Requested scope exceeds the authorization');
145
+ }
146
+ // PKCE hashing yields; another exchange may consume this code while it runs.
147
+ if (source.get(credential) !== session) {
148
+ return tokenError(c, 'invalid_grant', 'Authorization has already been used');
149
+ }
150
+ source.delete(credential);
151
+ const issuedAt = now();
152
+ const header = encodeJson({ alg: 'RS256', typ: 'JWT', kid: getKeyId() });
153
+ const claims = encodeJson({
154
+ iss: session.issuer,
155
+ sub: SUBJECT,
156
+ aud: session.clientId,
157
+ iat: issuedAt,
158
+ exp: issuedAt + 3600,
159
+ ...(session.nonce ? { nonce: session.nonce } : {}),
160
+ });
161
+ const signingInput = `${header}.${claims}`;
162
+ const signature = await crypto.subtle.sign('RSASSA-PKCS1-v1_5', (await getKeys()).privateKey, new TextEncoder().encode(signingInput));
163
+ const accessToken = crypto.randomUUID();
164
+ const refreshToken = `oidc-refresh-${crypto.randomUUID()}`;
165
+ remember(accessTokens, accessToken, { ...session, scope: effectiveScope, expiresAt: issuedAt + 3600 });
166
+ remember(refreshTokens, refreshToken, { ...session, scope: effectiveScope, expiresAt: issuedAt + 86400 });
167
+ c.header('Cache-Control', 'no-store');
168
+ c.header('Pragma', 'no-cache');
169
+ return c.json({
170
+ access_token: accessToken,
171
+ token_type: 'Bearer',
172
+ expires_in: 3600,
173
+ refresh_token: refreshToken,
174
+ scope: effectiveScope,
175
+ id_token: `${signingInput}.${encode(new Uint8Array(signature))}`,
176
+ });
177
+ });
178
+ app.on(['GET', 'POST'], '/oauth/userinfo', (c) => {
179
+ const token = c.req.header('Authorization')?.match(/^Bearer\s+(\S+)$/i)?.[1];
180
+ const session = token ? accessTokens.get(token) : undefined;
181
+ c.header('Cache-Control', 'no-store');
182
+ if (!session ||
183
+ session.expiresAt <= now() ||
184
+ session.issuer !== new URL(c.req.url).origin ||
185
+ !session.scope.split(/\s+/).includes('openid')) {
186
+ c.header('WWW-Authenticate', 'Bearer error="invalid_token"');
187
+ return c.json({ error: 'invalid_token' }, 401);
188
+ }
189
+ const scopes = session.scope.split(/\s+/);
190
+ return c.json({
191
+ sub: SUBJECT,
192
+ ...(scopes.includes('profile') ? { name: 'Scalar Mock User', preferred_username: 'scalar' } : {}),
193
+ ...(scopes.includes('email') ? { email: 'mock@example.com', email_verified: true } : {}),
194
+ });
195
+ });
196
+ };
package/package.json CHANGED
@@ -16,7 +16,7 @@
16
16
  "swagger",
17
17
  "cli"
18
18
  ],
19
- "version": "0.17.6",
19
+ "version": "0.19.0",
20
20
  "engines": {
21
21
  "node": ">=22"
22
22
  },
@@ -52,25 +52,25 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "@faker-js/faker": "10.6.0",
55
- "@hono/node-server": "^2.1.1",
56
- "@scalar/helpers": "0.16.3",
57
- "@scalar/json-magic": "0.15.7",
55
+ "@scalar/helpers": "0.16.4",
56
+ "@scalar/json-magic": "0.16.1",
58
57
  "@scalar/openapi-types": "0.9.8",
59
- "@scalar/openapi-upgrader": "0.4.4",
60
- "@scalar/types": "0.23.2",
61
- "@scalar/workspace-store": "0.68.3",
58
+ "@scalar/openapi-upgrader": "0.4.5",
59
+ "@scalar/types": "0.24.0",
60
+ "@scalar/workspace-store": "0.68.5",
62
61
  "ajv": "^8.20.0",
63
62
  "ajv-formats": "^3.0.1",
64
63
  "hono": "^4.13.8",
65
64
  "quickjs-emscripten": "0.32.0",
66
- "ws": "8.21.3",
67
65
  "yaml": "^2.9.0"
68
66
  },
69
67
  "devDependencies": {
68
+ "@hono/node-server": "^2.1.1",
70
69
  "@types/node": "^24.1.0",
71
70
  "@types/ws": "8.18.1",
72
- "undici": "7.29.1",
73
- "vite": "8.1.5"
71
+ "undici": "7.30.1",
72
+ "vite": "8.1.5",
73
+ "ws": "8.21.3"
74
74
  },
75
75
  "scripts": {
76
76
  "build": "tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json",
@@ -1,24 +0,0 @@
1
- import type { AsyncApiDocument } from '@scalar/types/asyncapi/3.1';
2
- /**
3
- * Processes an AsyncAPI document by bundling external references and wrapping it so internal
4
- * references stay intact but resolve lazily — the AsyncAPI counterpart of
5
- * {@link processOpenApiDocument}.
6
- *
7
- * Unlike a full dereference, the returned document keeps `$ref` nodes in place. Consumers resolve
8
- * them on demand with `getResolvedRef` from `@scalar/workspace-store`, which reads the `$ref-value`
9
- * exposed by the magic proxy. This avoids eagerly flattening (and duplicating) the whole document.
10
- *
11
- * Only AsyncAPI 3.1 is supported; 2.x documents should be upgraded before being passed in.
12
- *
13
- * @param document - The AsyncAPI document to process. Can be a string (URL/path) or an object.
14
- * @param origin - Source file path or URL for resolving references in an already loaded document.
15
- * @returns A promise that resolves to the AsyncAPI document with lazily resolvable references.
16
- * @throws Error if the document cannot be processed or is invalid.
17
- */
18
- export declare function processAsyncApiDocument(document: string | Record<string, any> | undefined, origin?: string): Promise<AsyncApiDocument>;
19
- /**
20
- * Detects whether a loaded document describes an AsyncAPI API (rather than OpenAPI/Swagger).
21
- * Used to route an incoming document to the right mock engine.
22
- */
23
- export declare function isAsyncApiDocument(document: unknown): boolean;
24
- //# sourceMappingURL=process-asyncapi-document.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"process-asyncapi-document.d.ts","sourceRoot":"","sources":["../../src/utils/process-asyncapi-document.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAA;AAElE;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,uBAAuB,CAC3C,QAAQ,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,SAAS,EAClD,MAAM,CAAC,EAAE,MAAM,GACd,OAAO,CAAC,gBAAgB,CAAC,CAsC3B;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,OAAO,GAAG,OAAO,CAE7D"}
@@ -1,64 +0,0 @@
1
- import path from 'node:path';
2
- import { cwd } from 'node:process';
3
- import { bundle } from '@scalar/json-magic/bundle';
4
- import { fetchUrls, parseJson, parseYaml, readFiles } from '@scalar/json-magic/bundle/plugins/node';
5
- import { isFilePath } from '@scalar/json-magic/helpers/is-file-path';
6
- import { createMagicProxy } from '@scalar/json-magic/magic-proxy';
7
- /**
8
- * Processes an AsyncAPI document by bundling external references and wrapping it so internal
9
- * references stay intact but resolve lazily — the AsyncAPI counterpart of
10
- * {@link processOpenApiDocument}.
11
- *
12
- * Unlike a full dereference, the returned document keeps `$ref` nodes in place. Consumers resolve
13
- * them on demand with `getResolvedRef` from `@scalar/workspace-store`, which reads the `$ref-value`
14
- * exposed by the magic proxy. This avoids eagerly flattening (and duplicating) the whole document.
15
- *
16
- * Only AsyncAPI 3.1 is supported; 2.x documents should be upgraded before being passed in.
17
- *
18
- * @param document - The AsyncAPI document to process. Can be a string (URL/path) or an object.
19
- * @param origin - Source file path or URL for resolving references in an already loaded document.
20
- * @returns A promise that resolves to the AsyncAPI document with lazily resolvable references.
21
- * @throws Error if the document cannot be processed or is invalid.
22
- */
23
- export async function processAsyncApiDocument(document, origin) {
24
- // Handle empty/undefined input gracefully with a minimal valid document.
25
- if (!document || (typeof document === 'object' && Object.keys(document).length === 0)) {
26
- return {
27
- asyncapi: '3.1.0',
28
- info: {
29
- title: 'Mock API',
30
- version: '1.0.0',
31
- },
32
- channels: {},
33
- operations: {},
34
- };
35
- }
36
- let bundled;
37
- // Keep references inside the source directory and prevent access to internal services.
38
- const source = origin ?? document;
39
- const basePath = typeof source === 'string' && isFilePath(source) ? path.dirname(path.resolve(source)) : cwd();
40
- try {
41
- // Bundle external references; parse string inputs (JSON or YAML) along the way.
42
- bundled = await bundle(document, {
43
- origin,
44
- plugins: [parseJson(), parseYaml(), readFiles({ basePath }), fetchUrls({ blockPrivateNetworks: true })],
45
- treeShake: false,
46
- });
47
- }
48
- catch (error) {
49
- throw new Error(`Failed to bundle AsyncAPI document: ${error instanceof Error ? error.message : String(error)}`);
50
- }
51
- if (!bundled || typeof bundled !== 'object') {
52
- throw new Error('Bundled document is invalid: expected an object');
53
- }
54
- // Wrap the document in a magic proxy so internal references resolve lazily via `$ref-value`.
55
- // External references were already pulled inline by `bundle` above, so only local `$ref`s remain.
56
- return createMagicProxy(bundled);
57
- }
58
- /**
59
- * Detects whether a loaded document describes an AsyncAPI API (rather than OpenAPI/Swagger).
60
- * Used to route an incoming document to the right mock engine.
61
- */
62
- export function isAsyncApiDocument(document) {
63
- return typeof document === 'object' && document !== null && 'asyncapi' in document;
64
- }
@@ -1,19 +0,0 @@
1
- import type { OpenAPIV3_1, OpenAPIV3_2 } from '@scalar/openapi-types';
2
- /**
3
- * Processes an OpenAPI document by bundling external references, upgrading compatible input to OpenAPI 3.2,
4
- * and wrapping it so internal references stay intact but resolve lazily.
5
- *
6
- * Unlike a full dereference, the returned document keeps `$ref` nodes in place. Consumers
7
- * resolve them on demand with `getResolvedRef` from `@scalar/workspace-store`, which reads the
8
- * `$ref-value` exposed by the magic proxy. This avoids eagerly flattening (and duplicating)
9
- * the whole document up front.
10
- *
11
- * Compatibility failures retain the OpenAPI 3.1 document and its version, without applying partial migrations.
12
- *
13
- * @param document - The OpenAPI document to process. Can be a string (URL/path) or an object.
14
- * @param origin - Source file path or URL for resolving references in an already loaded document.
15
- * @returns A promise that resolves to the document with lazily resolvable references.
16
- * @throws Error if the document cannot be processed or is invalid.
17
- */
18
- export declare function processOpenApiDocument(document: string | Record<string, any> | undefined, origin?: string): Promise<OpenAPIV3_1.Document | OpenAPIV3_2.Document>;
19
- //# sourceMappingURL=process-openapi-document.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"process-openapi-document.d.ts","sourceRoot":"","sources":["../../src/utils/process-openapi-document.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAA;AAIrE;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,sBAAsB,CAC1C,QAAQ,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,SAAS,EAClD,MAAM,CAAC,EAAE,MAAM,GACd,OAAO,CAAC,WAAW,CAAC,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC,CAkEtD"}