@scalar/api-client 3.19.0 → 3.19.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 +20 -0
- package/dist/style.css +55 -25
- package/dist/v2/blocks/request-block/RequestBlock.vue.script.js.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestBody.vue.d.ts.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestBody.vue.js +1 -1
- package/dist/v2/blocks/request-block/components/RequestBody.vue.js.map +1 -1
- package/dist/v2/blocks/request-block/components/RequestBody.vue.script.js +21 -5
- package/dist/v2/blocks/request-block/components/RequestBody.vue.script.js.map +1 -1
- package/dist/v2/blocks/response-block/components/ResponseBodyRaw.vue.d.ts.map +1 -1
- package/dist/v2/blocks/response-block/components/ResponseBodyRaw.vue.js +1 -1
- package/dist/v2/blocks/response-block/components/ResponseBodyRaw.vue.js.map +1 -1
- package/dist/v2/blocks/response-block/components/ResponseBodyRaw.vue.script.js +42 -16
- package/dist/v2/blocks/response-block/components/ResponseBodyRaw.vue.script.js.map +1 -1
- package/dist/v2/blocks/response-block/helpers/media-types.d.ts.map +1 -1
- package/dist/v2/blocks/response-block/helpers/media-types.js +5 -0
- package/dist/v2/blocks/response-block/helpers/media-types.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/AuthSelector.vue.script.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2Metadata.vue.d.ts +16 -0
- package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2Metadata.vue.d.ts.map +1 -0
- package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2Metadata.vue.js +7 -0
- package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2Metadata.vue.js.map +1 -0
- package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2Metadata.vue.script.js +86 -0
- package/dist/v2/blocks/scalar-auth-selector-block/components/OAuth2Metadata.vue.script.js.map +1 -0
- package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue.d.ts.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue.script.js +19 -2
- package/dist/v2/blocks/scalar-auth-selector-block/components/RequestAuthTab.vue.script.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-oauth2-metadata.d.ts +6 -0
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-oauth2-metadata.d.ts.map +1 -0
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-oauth2-metadata.js +25 -0
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-oauth2-metadata.js.map +1 -0
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-openid-connect-discovery.d.ts +1 -2
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-openid-connect-discovery.d.ts.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-openid-connect-discovery.js +2 -2
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/fetch-openid-connect-discovery.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth.d.ts.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth.js +13 -9
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth.js.map +1 -1
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth2-metadata-to-flows.d.ts +9 -0
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth2-metadata-to-flows.d.ts.map +1 -0
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth2-metadata-to-flows.js +36 -0
- package/dist/v2/blocks/scalar-auth-selector-block/helpers/oauth2-metadata-to-flows.js.map +1 -0
- package/dist/v2/components/code-input/CodeInput.vue.d.ts +2 -2
- package/dist/v2/components/code-input/CodeInput.vue.d.ts.map +1 -1
- package/dist/v2/components/code-input/CodeInput.vue.js +1 -1
- package/dist/v2/components/code-input/CodeInput.vue.js.map +1 -1
- package/dist/v2/components/code-input/CodeInput.vue.script.js +40 -9
- package/dist/v2/components/code-input/CodeInput.vue.script.js.map +1 -1
- package/dist/v2/components/server/ServerDropdown.vue.d.ts.map +1 -1
- package/dist/v2/components/server/ServerDropdown.vue.js.map +1 -1
- package/dist/v2/components/server/ServerDropdown.vue.script.js +1 -1
- package/dist/v2/components/server/ServerDropdown.vue.script.js.map +1 -1
- package/dist/v2/constants.js +1 -1
- package/dist/v2/features/modal/helpers/resolve-route-parameters.d.ts +9 -3
- package/dist/v2/features/modal/helpers/resolve-route-parameters.d.ts.map +1 -1
- package/dist/v2/features/modal/helpers/resolve-route-parameters.js.map +1 -1
- package/dist/vue-styles.css +33 -23
- package/package.json +16 -16
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oauth.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/oauth.ts"],"sourcesContent":["import type { ErrorResponse } from '@scalar/helpers/errors/normalize-error'\nimport { replaceEnvVariables, replacePathVariables } from '@scalar/helpers/regex/replace-variables'\nimport { isRelativePath } from '@scalar/helpers/url/is-relative-path'\nimport { makeUrlAbsolute } from '@scalar/helpers/url/make-url-absolute'\nimport { shouldUseProxy } from '@scalar/helpers/url/redirect-to-proxy'\nimport type { OAuthFlowsObjectSecret } from '@scalar/workspace-store/request-example'\nimport { getServerVariables } from '@scalar/workspace-store/request-example'\nimport type { ServerObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport { encode, fromUint8Array } from 'js-base64'\n\nimport type { CustomFetch } from '@/v2/blocks/operation-block/helpers/send-request'\n\nimport { getOAuthCallbackData } from './oauth-callback'\n\n/** Oauth2 security schemes which are not implicit */\ntype NonImplicitFlows = Omit<OAuthFlowsObjectSecret, 'implicit'>\n\ntype PKCEState = {\n codeVerifier: string\n codeChallenge: string\n codeChallengeMethod: string\n}\n\ntype ActiveServerBase = { basePath: string } | { baseUrl: string } | Record<string, never>\n\nexport type OAuth2Tokens = {\n accessToken: string\n refreshToken?: string\n}\n\n/**\n * Captures the OAuth2 redirect for environments where the browser-popup polling\n * approach cannot work (notably the Electron desktop app, where the renderer\n * runs on `file://` and providers reject `file://` redirect URIs).\n *\n * The implementation opens the authorization URL in the system browser and\n * resolves once the provider redirects back. Because the redirect target (for\n * example an ephemeral loopback port) is only known to the host environment, the\n * implementation appends the `redirect_uri` itself and reports back the exact\n * value it used so the token exchange can send the matching `redirect_uri`.\n */\nexport type CaptureOAuth2Callback = (params: {\n /** The fully built authorization URL, without a `redirect_uri` parameter. */\n authorizationUrl: string\n}) => Promise<\n ErrorResponse<{\n /** The full callback URL the provider redirected to, including query and/or hash params. */\n callbackUrl: string\n /** The `redirect_uri` the host environment used, so the token exchange can match it. */\n redirectUri: string\n }>\n>\n\n/** Flow types that support token refresh (all except implicit) */\ntype RefreshableFlows = Exclude<keyof OAuthFlowsObjectSecret, 'implicit'>\n\n/**\n * Resolves the active server URL using OpenAPI server variables first, then\n * Scalar environment variables.\n */\nexport const getServerUrl = (\n activeServer: ServerObject | null,\n environmentVariables: Record<string, string> = {},\n): string =>\n replaceEnvVariables(\n replacePathVariables(activeServer?.url ?? '', getServerVariables(activeServer)),\n environmentVariables,\n )\n\n/**\n * Builds the base option used when OAuth URLs are relative to the active server.\n *\n * Relative server URLs become browser-only base paths because they need the\n * current window location to resolve correctly.\n */\nexport const getActiveServerBase = (\n activeServer: ServerObject | null,\n environmentVariables: Record<string, string> = {},\n): ActiveServerBase => {\n const serverUrl = getServerUrl(activeServer, environmentVariables)\n if (!serverUrl) {\n return {}\n }\n\n if (isRelativePath(serverUrl)) {\n return typeof window === 'undefined' ? {} : { basePath: serverUrl }\n }\n\n return { baseUrl: serverUrl }\n}\n\n/**\n * Generates a random string for PKCE code verifier\n *\n * @see https://www.rfc-editor.org/rfc/rfc7636#page-8\n */\nconst generateCodeVerifier = (): string => {\n // Generate 32 random bytes\n const buffer = new Uint8Array(32)\n crypto.getRandomValues(buffer)\n\n // Base64URL encode the bytes\n return fromUint8Array(buffer, true)\n}\n\n/**\n * Creates a code challenge from the code verifier\n */\nconst generateCodeChallenge = async (verifier: string, encoding: 'SHA-256' | 'plain'): Promise<string> => {\n if (encoding === 'plain') {\n return verifier\n }\n\n // If crypto.subtle.digest is not a function, we cannot use SHA-256\n if (typeof crypto?.subtle?.digest !== 'function') {\n console.warn('SHA-256 is only supported when using https, using a plain text code challenge instead.')\n return verifier\n }\n\n // ASCII encoding is just taking the lower 8 bits of each character\n const encoder = new TextEncoder()\n const data = encoder.encode(verifier)\n const digest = await crypto.subtle.digest('SHA-256', data)\n\n // Base64URL encode the bytes\n return fromUint8Array(new Uint8Array(digest), true)\n}\n\n/**\n * Authorize oauth2 flow\n *\n * @returns the resolved oauth2 tokens\n */\nexport const authorizeOauth2 = async (\n flows: OAuthFlowsObjectSecret,\n type: keyof OAuthFlowsObjectSecret,\n selectedScopes: string[],\n /** We use the active server to set a base for relative redirect uris */\n activeServer: ServerObject | null,\n /** If we want to use the proxy */\n proxyUrl: string,\n /** Flattened environment variables used to resolve server URL templates like `{protocol}` */\n environmentVariables: Record<string, string> = {},\n /** Fetch used for the token request; the desktop app passes an IPC-backed fetch (see {@link authorizeServers}). */\n customFetch?: CustomFetch,\n /**\n * Optional redirect capture for interactive flows (authorization code and implicit).\n * When provided, the system browser plus a host-owned redirect target replaces the\n * default popup-polling approach. Required for the Electron desktop app.\n */\n captureCallback?: CaptureOAuth2Callback,\n): Promise<ErrorResponse<OAuth2Tokens>> => {\n const flow = flows[type]\n\n try {\n if (!flow) {\n return [new Error('Flow not found'), null]\n }\n\n const scopes = selectedScopes.join(' ')\n\n // Client Credentials or Password Flow\n if (type === 'clientCredentials' || type === 'password') {\n return authorizeServers(\n flows,\n type,\n scopes,\n {\n proxyUrl,\n customFetch,\n },\n activeServer,\n environmentVariables,\n )\n }\n\n // Generate a random state string with the length of 8 characters\n const state = (Math.random() + 1).toString(36).substring(2, 10)\n\n const authorizationUrl = makeUrlAbsolute(\n flows[type]!['x-scalar-secret-auth-url'] ?? flows[type]!.authorizationUrl,\n getActiveServerBase(activeServer, environmentVariables),\n )\n\n const url = new URL(authorizationUrl)\n\n /** Special PKCE state */\n let pkce: PKCEState | null = null\n\n // Params unique to the flows\n if (type === 'implicit') {\n url.searchParams.set('response_type', 'token')\n } else if (type === 'authorizationCode') {\n const typedFlow = flows[type]! // Safe to assert due to earlier check\n\n url.searchParams.set('response_type', 'code')\n\n // PKCE\n if (typedFlow['x-usePkce'] !== 'no') {\n const codeVerifier = generateCodeVerifier()\n const codeChallenge = await generateCodeChallenge(codeVerifier, typedFlow['x-usePkce'])\n\n // Set state for later verification\n pkce = {\n codeVerifier,\n codeChallenge,\n codeChallengeMethod: typedFlow['x-usePkce'] === 'SHA-256' ? 'S256' : 'plain',\n }\n\n // Set the code challenge and method on the url\n url.searchParams.set('code_challenge', codeChallenge)\n url.searchParams.set('code_challenge_method', pkce.codeChallengeMethod)\n }\n }\n\n const typedFlow = flows[type]! // Safe to assert due to earlier check\n\n // The capture path appends its own `redirect_uri` (it owns the target, for\n // example an ephemeral loopback port), so we only set it here for the popup path.\n if (!captureCallback) {\n // Handle relative redirect uris\n if (typedFlow['x-scalar-secret-redirect-uri'].startsWith('/')) {\n const baseUrl =\n getServerUrl(activeServer, environmentVariables) || window.location.origin + window.location.pathname\n const redirectUri = new URL(typedFlow['x-scalar-secret-redirect-uri'], baseUrl).toString()\n\n url.searchParams.set('redirect_uri', redirectUri)\n } else {\n url.searchParams.set('redirect_uri', typedFlow['x-scalar-secret-redirect-uri'])\n }\n }\n\n if (flow['x-scalar-security-query']) {\n Object.keys(flow['x-scalar-security-query']).forEach((key: string): void => {\n const value = flow['x-scalar-security-query']?.[key]\n if (!value) {\n return\n }\n url.searchParams.set(key, value)\n })\n }\n\n // Common to all flows\n url.searchParams.set('client_id', flow['x-scalar-secret-client-id'])\n url.searchParams.set('state', state)\n if (scopes) {\n url.searchParams.set('scope', scopes)\n }\n\n // Capture path: open the system browser and let the host environment catch\n // the redirect (used by the desktop app, where popup polling cannot work).\n if (captureCallback) {\n const [captureError, capture] = await captureCallback({ authorizationUrl: url.toString() })\n\n if (captureError || !capture) {\n return [captureError ?? new Error('Failed to capture the OAuth2 redirect'), null]\n }\n\n const { accessToken, accessTokenParams, code, codeParams, error, errorDescription, refreshToken } =\n getOAuthCallbackData(() => capture.callbackUrl, flow['x-tokenName'] || 'access_token')\n\n if (error) {\n return [new Error(`OAuth error: ${error}${errorDescription ? ` (${errorDescription})` : ''}`), null]\n }\n\n // Implicit Flow\n if (accessToken) {\n if ((accessTokenParams?.get('state') ?? null) !== state) {\n return [new Error('State mismatch'), null]\n }\n return [null, { accessToken, ...(refreshToken ? { refreshToken } : {}) }]\n }\n\n // Authorization Code Server Flow\n if (code && type === 'authorizationCode') {\n if ((codeParams?.get('state') ?? null) !== state) {\n return [new Error('State mismatch'), null]\n }\n return authorizeServers(\n flows,\n type,\n scopes,\n {\n code,\n pkce,\n proxyUrl,\n customFetch,\n // The token request must echo the exact redirect_uri used in the authorization request.\n redirectUri: capture.redirectUri,\n },\n activeServer,\n environmentVariables,\n )\n }\n\n return [new Error('No authorization code or access token was returned'), null]\n }\n\n const windowFeatures = 'left=100,top=100,width=800,height=600'\n const authWindow = window.open(url, 'openAuth2Window', windowFeatures)\n\n // Open up a window and poll until closed or we have the data we want\n if (authWindow) {\n // We need to return a promise here due to the setInterval\n return new Promise<ErrorResponse<OAuth2Tokens>>((resolve) => {\n const checkWindowClosed = setInterval(() => {\n const { accessToken, accessTokenParams, code, codeParams, error, errorDescription, refreshToken } =\n getOAuthCallbackData(() => authWindow.location.href, flow['x-tokenName'] || 'access_token')\n\n // The window has closed OR we have what we are looking for so we stop polling\n if (authWindow.closed || accessToken || code || error) {\n clearInterval(checkWindowClosed)\n authWindow.close()\n\n if (error) {\n resolve([new Error(`OAuth error: ${error}${errorDescription ? ` (${errorDescription})` : ''}`), null])\n return\n }\n\n // Implicit Flow\n if (accessToken) {\n const _state = accessTokenParams?.get('state') ?? null\n\n if (_state === state) {\n resolve([null, { accessToken, ...(refreshToken ? { refreshToken } : {}) }])\n } else {\n resolve([new Error('State mismatch'), null])\n }\n return\n }\n\n // Authorization Code Server Flow\n if (code && type === 'authorizationCode') {\n const _state = codeParams?.get('state') ?? null\n\n if (_state === state) {\n void authorizeServers(\n flows,\n type,\n scopes,\n {\n code,\n pkce,\n proxyUrl,\n customFetch,\n },\n activeServer,\n environmentVariables,\n )\n .then(resolve)\n .catch((error: unknown) => {\n resolve([\n error instanceof Error ? error : new Error('Failed to get an access token', { cause: error }),\n null,\n ])\n })\n } else {\n resolve([new Error('State mismatch'), null])\n }\n return\n }\n\n // User closed window without authorizing\n resolve([new Error('Window was closed without granting authorization'), null])\n }\n }, 200)\n })\n }\n return [new Error('Failed to open auth window'), null]\n } catch (error) {\n return [error instanceof Error ? error : new Error('Failed to authorize oauth2 flow', { cause: error }), null]\n }\n}\n\n/**\n * Makes the BE authorization call to grab the token server to server\n * Used for clientCredentials and authorizationCode\n */\nconst authorizeServers = async (\n flows: NonImplicitFlows,\n type: keyof NonImplicitFlows,\n scopes: string,\n {\n code,\n pkce,\n proxyUrl,\n customFetch = fetch,\n redirectUri,\n }: {\n code?: string\n pkce?: PKCEState | null\n proxyUrl?: string\n customFetch?: CustomFetch\n /** Overrides the stored redirect_uri (the capture path owns the real target). */\n redirectUri?: string\n } = {},\n activeServer: ServerObject | null,\n environmentVariables: Record<string, string> = {},\n): Promise<ErrorResponse<OAuth2Tokens>> => {\n const flow = flows[type]\n\n if (!flow) {\n return [new Error('OAuth2 flow was not defined'), null]\n }\n\n const formData = new URLSearchParams()\n\n // Only client credentials and password flows support scopes in the token request\n if (scopes && (type === 'clientCredentials' || type === 'password')) {\n formData.set('scope', scopes)\n }\n\n /** Where to add the credentials */\n const addCredentialsToBody = flow['x-scalar-credentials-location'] === 'body'\n /**\n * PKCE and client authentication are independent: a confidential client may use both.\n * We send the client_secret whenever one is set, regardless of PKCE (see RFC 9700 Section 2.1.1).\n */\n const hasClientSecret = Boolean(flow['x-scalar-secret-client-secret'])\n /**\n * Public authorization-code clients still need client_id in the token body.\n * We only send it implicitly for that case to avoid conflicting with Basic auth.\n */\n const shouldSendClientIdInBody = addCredentialsToBody || (type === 'authorizationCode' && !hasClientSecret)\n\n if (shouldSendClientIdInBody) {\n formData.set('client_id', flow['x-scalar-secret-client-id'])\n }\n if (addCredentialsToBody && hasClientSecret) {\n formData.set('client_secret', flow['x-scalar-secret-client-secret'])\n }\n if (redirectUri) {\n formData.set('redirect_uri', redirectUri)\n } else if ('x-scalar-secret-redirect-uri' in flow && flow['x-scalar-secret-redirect-uri']) {\n formData.set('redirect_uri', flow['x-scalar-secret-redirect-uri'])\n }\n\n // Authorization Code\n if (code) {\n formData.set('code', code)\n formData.set('grant_type', 'authorization_code')\n\n // PKCE\n if (pkce) {\n formData.set('code_verifier', pkce.codeVerifier)\n }\n }\n // Password\n else if (type === 'password') {\n const typedFlow = flows[type]! // Safe to assert due to earlier check\n formData.set('grant_type', 'password')\n formData.set('username', typedFlow['x-scalar-secret-username'])\n formData.set('password', typedFlow['x-scalar-secret-password'])\n }\n // Client Credentials\n else {\n formData.set('grant_type', 'client_credentials')\n }\n\n // Additional request body parameters\n if (flow['x-scalar-security-body']) {\n Object.entries(flow['x-scalar-security-body']).forEach(([key, value]) => {\n if (value !== undefined && value !== null) {\n formData.set(key, String(value))\n }\n })\n }\n\n try {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n }\n\n // Add client id + secret to headers for confidential clients.\n if (!addCredentialsToBody && hasClientSecret) {\n headers.Authorization = `Basic ${encode(`${flow['x-scalar-secret-client-id']}:${flow['x-scalar-secret-client-secret']}`)}`\n }\n\n // Check if we should use the proxy\n const tokenUrl = makeUrlAbsolute(\n flow['x-scalar-secret-token-url'] ?? flow.tokenUrl,\n getActiveServerBase(activeServer, environmentVariables),\n )\n const url = shouldUseProxy(proxyUrl, tokenUrl)\n ? `${proxyUrl}?${new URLSearchParams([['scalar_url', tokenUrl]]).toString()}`\n : tokenUrl\n\n // Make the call\n const resp = await customFetch(url, {\n method: 'POST',\n headers,\n body: formData,\n })\n const responseData = await resp.json()\n\n // Use custom token name if specified, otherwise default to access_token\n const tokenName = flow['x-tokenName'] || 'access_token'\n const accessToken = responseData[tokenName]\n const refreshToken = responseData.refresh_token\n\n if (!accessToken) {\n return [new Error(responseData.error_description ?? responseData.error ?? 'Failed to get an access token'), null]\n }\n\n return [null, { accessToken, ...(typeof refreshToken === 'string' ? { refreshToken } : {}) }]\n } catch (error) {\n return [\n error instanceof Error\n ? error\n : new Error('Failed to get an access token. Please check your credentials.', { cause: error }),\n null,\n ]\n }\n}\n\n/**\n * Exchange a refresh token for a new access token using the `grant_type=refresh_token` flow.\n *\n * Uses the stored refresh token, client credentials, and the token URL (or refreshUrl when available)\n * to request fresh tokens from the authorization server per RFC 6749 Section 6.\n */\nexport const refreshOauth2Token = async (\n flows: OAuthFlowsObjectSecret,\n type: RefreshableFlows,\n /** If we want to use the proxy */\n proxyUrl: string,\n /** We use the active server to set a base for relative URLs */\n activeServer: ServerObject | null,\n /** Flattened environment variables used to resolve server URL templates */\n environmentVariables: Record<string, string> = {},\n /** Fetch used for the refresh request; the desktop app passes an IPC-backed fetch so it leaves the renderer's network stack. */\n customFetch: CustomFetch = fetch,\n): Promise<ErrorResponse<OAuth2Tokens>> => {\n const flow = flows[type]\n\n if (!flow) {\n return [new Error('OAuth2 flow was not defined'), null]\n }\n\n const refreshToken = flow['x-scalar-secret-refresh-token']\n if (!refreshToken) {\n return [new Error('No refresh token available'), null]\n }\n\n const formData = new URLSearchParams()\n formData.set('grant_type', 'refresh_token')\n formData.set('refresh_token', refreshToken)\n\n const addCredentialsToBody = flow['x-scalar-credentials-location'] === 'body'\n /** A confidential client keeps using its secret on refresh, even when PKCE is enabled. */\n const hasClientSecret = Boolean(flow['x-scalar-secret-client-secret'])\n /**\n * Public authorization-code clients still need client_id in the refresh body per RFC 6749 Section 6.\n * We only send it implicitly for that case to avoid conflicting with Basic auth.\n */\n const shouldSendClientIdInBody = addCredentialsToBody || (type === 'authorizationCode' && !hasClientSecret)\n\n if (shouldSendClientIdInBody) {\n formData.set('client_id', flow['x-scalar-secret-client-id'])\n }\n if (addCredentialsToBody && hasClientSecret) {\n formData.set('client_secret', flow['x-scalar-secret-client-secret'])\n }\n\n if (flow['x-scalar-security-body']) {\n Object.entries(flow['x-scalar-security-body']).forEach(([key, value]) => {\n if (value !== undefined && value !== null) {\n formData.set(key, String(value))\n }\n })\n }\n\n try {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n }\n\n if (!addCredentialsToBody && hasClientSecret) {\n headers.Authorization = `Basic ${encode(`${flow['x-scalar-secret-client-id']}:${flow['x-scalar-secret-client-secret']}`)}`\n }\n\n const refreshUrl = flow.refreshUrl || flow['x-scalar-secret-token-url'] || flow.tokenUrl\n const absoluteRefreshUrl = makeUrlAbsolute(refreshUrl, getActiveServerBase(activeServer, environmentVariables))\n const url = shouldUseProxy(proxyUrl, absoluteRefreshUrl)\n ? `${proxyUrl}?${new URLSearchParams([['scalar_url', absoluteRefreshUrl]]).toString()}`\n : absoluteRefreshUrl\n\n const resp = await customFetch(url, {\n method: 'POST',\n headers,\n body: formData,\n })\n const responseData = await resp.json()\n\n const tokenName = flow['x-tokenName'] || 'access_token'\n const accessToken = responseData[tokenName]\n const newRefreshToken = responseData.refresh_token\n\n if (!accessToken) {\n return [new Error(responseData.error_description ?? responseData.error ?? 'Token refresh failed'), null]\n }\n\n return [\n null,\n {\n accessToken,\n ...(typeof newRefreshToken === 'string' ? { refreshToken: newRefreshToken } : { refreshToken }),\n },\n ]\n } catch (error) {\n return [\n error instanceof Error\n ? error\n : new Error('Failed to refresh the access token. Please re-authorize.', { cause: error }),\n null,\n ]\n }\n}\n"],"mappings":";;;;;;;;;;;;AA4DA,IAAa,gBAC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AAC,KAAK,WAAW;EACvE,IAAI,UAAU,KAAA,KAAa,UAAU,MACnC,SAAS,IAAI,KAAK,OAAO,KAAK,CAAC;CAEnC,CAAC;CAGH,IAAI;EACF,MAAM,UAAkC,EACtC,gBAAgB,oCAClB;EAEA,IAAI,CAAC,wBAAwB,iBAC3B,QAAQ,gBAAgB,SAAS,OAAO,GAAG,KAAK,6BAA6B,GAAG,KAAK,kCAAkC;EAIzH,MAAM,qBAAqB,gBADR,KAAK,cAAc,KAAK,gCAAgC,KAAK,UACzB,oBAAoB,cAAc,oBAAoB,CAAC;EAU9G,MAAM,eAAe,OAAM,MALR,YAJP,eAAe,UAAU,kBAAkB,IACnD,GAAG,SAAS,GAAG,IAAI,gBAAgB,CAAC,CAAC,cAAc,kBAAkB,CAAC,CAAC,CAAC,CAAC,SAAS,MAClF,oBAEgC;GAClC,QAAQ;GACR;GACA,MAAM;EACR,CAAC,EAAA,CAC+B,KAAK;EAGrC,MAAM,cAAc,aADF,KAAK,kBAAkB;EAEzC,MAAM,kBAAkB,aAAa;EAErC,IAAI,CAAC,aACH,OAAO,CAAC,IAAI,MAAM,aAAa,qBAAqB,aAAa,SAAS,sBAAsB,GAAG,IAAI;EAGzG,OAAO,CACL,MACA;GACE;GACA,GAAI,OAAO,oBAAoB,WAAW,EAAE,cAAc,gBAAgB,IAAI,EAAE,aAAa;EAC/F,CACF;CACF,SAAS,OAAO;EACd,OAAO,CACL,iBAAiB,QACb,QACA,IAAI,MAAM,4DAA4D,EAAE,OAAO,MAAM,CAAC,GAC1F,IACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"oauth.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/oauth.ts"],"sourcesContent":["import type { ErrorResponse } from '@scalar/helpers/errors/normalize-error'\nimport { replaceEnvVariables, replacePathVariables } from '@scalar/helpers/regex/replace-variables'\nimport { isRelativePath } from '@scalar/helpers/url/is-relative-path'\nimport { makeUrlAbsolute } from '@scalar/helpers/url/make-url-absolute'\nimport { shouldUseProxy } from '@scalar/helpers/url/redirect-to-proxy'\nimport type { OAuthFlowsObjectSecret } from '@scalar/workspace-store/request-example'\nimport { getServerVariables } from '@scalar/workspace-store/request-example'\nimport type { ServerObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport { encode, fromUint8Array } from 'js-base64'\n\nimport type { CustomFetch } from '@/v2/blocks/operation-block/helpers/send-request'\n\nimport { getOAuthCallbackData } from './oauth-callback'\n\n/** Oauth2 security schemes which are not implicit */\ntype NonImplicitFlows = Omit<OAuthFlowsObjectSecret, 'implicit'>\n\ntype PKCEState = {\n codeVerifier: string\n codeChallenge: string\n codeChallengeMethod: string\n}\n\ntype ActiveServerBase = { basePath: string } | { baseUrl: string } | Record<string, never>\n\nexport type OAuth2Tokens = {\n accessToken: string\n refreshToken?: string\n}\n\n/**\n * Captures the OAuth2 redirect for environments where the browser-popup polling\n * approach cannot work (notably the Electron desktop app, where the renderer\n * runs on `file://` and providers reject `file://` redirect URIs).\n *\n * The implementation opens the authorization URL in the system browser and\n * resolves once the provider redirects back. Because the redirect target (for\n * example an ephemeral loopback port) is only known to the host environment, the\n * implementation appends the `redirect_uri` itself and reports back the exact\n * value it used so the token exchange can send the matching `redirect_uri`.\n */\nexport type CaptureOAuth2Callback = (params: {\n /** The fully built authorization URL, without a `redirect_uri` parameter. */\n authorizationUrl: string\n}) => Promise<\n ErrorResponse<{\n /** The full callback URL the provider redirected to, including query and/or hash params. */\n callbackUrl: string\n /** The `redirect_uri` the host environment used, so the token exchange can match it. */\n redirectUri: string\n }>\n>\n\n/** Flow types that support token refresh (all except implicit) */\ntype RefreshableFlows = Exclude<keyof OAuthFlowsObjectSecret, 'implicit'>\n\n/**\n * Resolves the active server URL using OpenAPI server variables first, then\n * Scalar environment variables.\n */\nexport const getServerUrl = (\n activeServer: ServerObject | null,\n environmentVariables: Record<string, string> = {},\n): string =>\n replaceEnvVariables(\n replacePathVariables(activeServer?.url ?? '', getServerVariables(activeServer)),\n environmentVariables,\n )\n\n/**\n * Builds the base option used when OAuth URLs are relative to the active server.\n *\n * Relative server URLs become browser-only base paths because they need the\n * current window location to resolve correctly.\n */\nexport const getActiveServerBase = (\n activeServer: ServerObject | null,\n environmentVariables: Record<string, string> = {},\n): ActiveServerBase => {\n const serverUrl = getServerUrl(activeServer, environmentVariables)\n if (!serverUrl) {\n return {}\n }\n\n if (isRelativePath(serverUrl)) {\n return typeof window === 'undefined' ? {} : { basePath: serverUrl }\n }\n\n return { baseUrl: serverUrl }\n}\n\n/**\n * Generates a random string for PKCE code verifier\n *\n * @see https://www.rfc-editor.org/rfc/rfc7636#page-8\n */\nconst generateCodeVerifier = (): string => {\n // Generate 32 random bytes\n const buffer = new Uint8Array(32)\n crypto.getRandomValues(buffer)\n\n // Base64URL encode the bytes\n return fromUint8Array(buffer, true)\n}\n\n/**\n * Creates a code challenge from the code verifier\n */\nconst generateCodeChallenge = async (verifier: string, encoding: 'SHA-256' | 'plain'): Promise<string> => {\n if (encoding === 'plain') {\n return verifier\n }\n\n // If crypto.subtle.digest is not a function, we cannot use SHA-256\n if (typeof crypto?.subtle?.digest !== 'function') {\n console.warn('SHA-256 is only supported when using https, using a plain text code challenge instead.')\n return verifier\n }\n\n // ASCII encoding is just taking the lower 8 bits of each character\n const encoder = new TextEncoder()\n const data = encoder.encode(verifier)\n const digest = await crypto.subtle.digest('SHA-256', data)\n\n // Base64URL encode the bytes\n return fromUint8Array(new Uint8Array(digest), true)\n}\n\n/**\n * Authorize oauth2 flow\n *\n * @returns the resolved oauth2 tokens\n */\nexport const authorizeOauth2 = async (\n flows: OAuthFlowsObjectSecret,\n type: keyof OAuthFlowsObjectSecret,\n selectedScopes: string[],\n /** We use the active server to set a base for relative redirect uris */\n activeServer: ServerObject | null,\n /** If we want to use the proxy */\n proxyUrl: string,\n /** Flattened environment variables used to resolve server URL templates like `{protocol}` */\n environmentVariables: Record<string, string> = {},\n /** Fetch used for the token request; the desktop app passes an IPC-backed fetch (see {@link authorizeServers}). */\n customFetch?: CustomFetch,\n /**\n * Optional redirect capture for interactive flows (authorization code and implicit).\n * When provided, the system browser plus a host-owned redirect target replaces the\n * default popup-polling approach. Required for the Electron desktop app.\n */\n captureCallback?: CaptureOAuth2Callback,\n): Promise<ErrorResponse<OAuth2Tokens>> => {\n const flow = flows[type]\n\n try {\n if (!flow) {\n return [new Error('Flow not found'), null]\n }\n\n const scopes = selectedScopes.join(' ')\n\n // Client Credentials or Password Flow\n if (type === 'clientCredentials' || type === 'password') {\n return authorizeServers(\n flows,\n type,\n scopes,\n {\n proxyUrl,\n customFetch,\n },\n activeServer,\n environmentVariables,\n )\n }\n\n // Generate a random state string with the length of 8 characters\n const state = (Math.random() + 1).toString(36).substring(2, 10)\n\n const authorizationUrl = makeUrlAbsolute(\n flows[type]!['x-scalar-secret-auth-url'] ?? flows[type]!.authorizationUrl,\n getActiveServerBase(activeServer, environmentVariables),\n )\n\n const url = new URL(authorizationUrl)\n\n /** Special PKCE state */\n let pkce: PKCEState | null = null\n\n // Params unique to the flows\n if (type === 'implicit') {\n url.searchParams.set('response_type', 'token')\n } else if (type === 'authorizationCode') {\n const typedFlow = flows[type]! // Safe to assert due to earlier check\n\n url.searchParams.set('response_type', 'code')\n\n // PKCE\n if (typedFlow['x-usePkce'] !== 'no') {\n const codeVerifier = generateCodeVerifier()\n const codeChallenge = await generateCodeChallenge(codeVerifier, typedFlow['x-usePkce'])\n\n // Set state for later verification\n pkce = {\n codeVerifier,\n codeChallenge,\n codeChallengeMethod: typedFlow['x-usePkce'] === 'SHA-256' ? 'S256' : 'plain',\n }\n\n // Set the code challenge and method on the url\n url.searchParams.set('code_challenge', codeChallenge)\n url.searchParams.set('code_challenge_method', pkce.codeChallengeMethod)\n }\n }\n\n const typedFlow = flows[type]! // Safe to assert due to earlier check\n\n // The capture path appends its own `redirect_uri` (it owns the target, for\n // example an ephemeral loopback port), so we only set it here for the popup path.\n if (!captureCallback) {\n // Handle relative redirect uris\n if (typedFlow['x-scalar-secret-redirect-uri'].startsWith('/')) {\n const baseUrl =\n getServerUrl(activeServer, environmentVariables) || window.location.origin + window.location.pathname\n const redirectUri = new URL(typedFlow['x-scalar-secret-redirect-uri'], baseUrl).toString()\n\n url.searchParams.set('redirect_uri', redirectUri)\n } else {\n url.searchParams.set('redirect_uri', typedFlow['x-scalar-secret-redirect-uri'])\n }\n }\n\n if (flow['x-scalar-security-query']) {\n Object.keys(flow['x-scalar-security-query']).forEach((key: string): void => {\n const value = flow['x-scalar-security-query']?.[key]\n if (!value) {\n return\n }\n url.searchParams.set(key, value)\n })\n }\n\n // Common to all flows\n url.searchParams.set('client_id', flow['x-scalar-secret-client-id'].trim())\n url.searchParams.set('state', state)\n if (scopes) {\n url.searchParams.set('scope', scopes)\n }\n\n // Capture path: open the system browser and let the host environment catch\n // the redirect (used by the desktop app, where popup polling cannot work).\n if (captureCallback) {\n const [captureError, capture] = await captureCallback({ authorizationUrl: url.toString() })\n\n if (captureError || !capture) {\n return [captureError ?? new Error('Failed to capture the OAuth2 redirect'), null]\n }\n\n const { accessToken, accessTokenParams, code, codeParams, error, errorDescription, refreshToken } =\n getOAuthCallbackData(() => capture.callbackUrl, flow['x-tokenName'] || 'access_token')\n\n if (error) {\n return [new Error(`OAuth error: ${error}${errorDescription ? ` (${errorDescription})` : ''}`), null]\n }\n\n // Implicit Flow\n if (accessToken) {\n if ((accessTokenParams?.get('state') ?? null) !== state) {\n return [new Error('State mismatch'), null]\n }\n return [null, { accessToken, ...(refreshToken ? { refreshToken } : {}) }]\n }\n\n // Authorization Code Server Flow\n if (code && type === 'authorizationCode') {\n if ((codeParams?.get('state') ?? null) !== state) {\n return [new Error('State mismatch'), null]\n }\n return authorizeServers(\n flows,\n type,\n scopes,\n {\n code,\n pkce,\n proxyUrl,\n customFetch,\n // The token request must echo the exact redirect_uri used in the authorization request.\n redirectUri: capture.redirectUri,\n },\n activeServer,\n environmentVariables,\n )\n }\n\n return [new Error('No authorization code or access token was returned'), null]\n }\n\n const windowFeatures = 'left=100,top=100,width=800,height=600'\n const authWindow = window.open(url, 'openAuth2Window', windowFeatures)\n\n // Open up a window and poll until closed or we have the data we want\n if (authWindow) {\n // We need to return a promise here due to the setInterval\n return new Promise<ErrorResponse<OAuth2Tokens>>((resolve) => {\n const checkWindowClosed = setInterval(() => {\n const { accessToken, accessTokenParams, code, codeParams, error, errorDescription, refreshToken } =\n getOAuthCallbackData(() => authWindow.location.href, flow['x-tokenName'] || 'access_token')\n\n // The window has closed OR we have what we are looking for so we stop polling\n if (authWindow.closed || accessToken || code || error) {\n clearInterval(checkWindowClosed)\n authWindow.close()\n\n if (error) {\n resolve([new Error(`OAuth error: ${error}${errorDescription ? ` (${errorDescription})` : ''}`), null])\n return\n }\n\n // Implicit Flow\n if (accessToken) {\n const _state = accessTokenParams?.get('state') ?? null\n\n if (_state === state) {\n resolve([null, { accessToken, ...(refreshToken ? { refreshToken } : {}) }])\n } else {\n resolve([new Error('State mismatch'), null])\n }\n return\n }\n\n // Authorization Code Server Flow\n if (code && type === 'authorizationCode') {\n const _state = codeParams?.get('state') ?? null\n\n if (_state === state) {\n void authorizeServers(\n flows,\n type,\n scopes,\n {\n code,\n pkce,\n proxyUrl,\n customFetch,\n },\n activeServer,\n environmentVariables,\n )\n .then(resolve)\n .catch((error: unknown) => {\n resolve([\n error instanceof Error ? error : new Error('Failed to get an access token', { cause: error }),\n null,\n ])\n })\n } else {\n resolve([new Error('State mismatch'), null])\n }\n return\n }\n\n // User closed window without authorizing\n resolve([new Error('Window was closed without granting authorization'), null])\n }\n }, 200)\n })\n }\n return [new Error('Failed to open auth window'), null]\n } catch (error) {\n return [error instanceof Error ? error : new Error('Failed to authorize oauth2 flow', { cause: error }), null]\n }\n}\n\n/**\n * Makes the BE authorization call to grab the token server to server\n * Used for clientCredentials and authorizationCode\n */\nconst authorizeServers = async (\n flows: NonImplicitFlows,\n type: keyof NonImplicitFlows,\n scopes: string,\n {\n code,\n pkce,\n proxyUrl,\n customFetch = fetch,\n redirectUri,\n }: {\n code?: string\n pkce?: PKCEState | null\n proxyUrl?: string\n customFetch?: CustomFetch\n /** Overrides the stored redirect_uri (the capture path owns the real target). */\n redirectUri?: string\n } = {},\n activeServer: ServerObject | null,\n environmentVariables: Record<string, string> = {},\n): Promise<ErrorResponse<OAuth2Tokens>> => {\n const flow = flows[type]\n\n if (!flow) {\n return [new Error('OAuth2 flow was not defined'), null]\n }\n\n const formData = new URLSearchParams()\n\n // Only client credentials and password flows support scopes in the token request\n if (scopes && (type === 'clientCredentials' || type === 'password')) {\n formData.set('scope', scopes)\n }\n\n // Ignore surrounding copy/paste whitespace without changing stored credentials or other secrets.\n const clientId = flow['x-scalar-secret-client-id'].trim()\n const clientSecret = flow['x-scalar-secret-client-secret'].trim()\n /** Where to add the credentials */\n const addCredentialsToBody = flow['x-scalar-credentials-location'] === 'body'\n /**\n * PKCE and client authentication are independent: a confidential client may use both.\n * We send the client_secret whenever one is set, regardless of PKCE (see RFC 9700 Section 2.1.1).\n */\n const hasClientSecret = Boolean(clientSecret)\n /**\n * Public authorization-code clients still need client_id in the token body.\n * We only send it implicitly for that case to avoid conflicting with Basic auth.\n */\n const shouldSendClientIdInBody = addCredentialsToBody || (type === 'authorizationCode' && !hasClientSecret)\n\n if (shouldSendClientIdInBody) {\n formData.set('client_id', clientId)\n }\n if (addCredentialsToBody && hasClientSecret) {\n formData.set('client_secret', clientSecret)\n }\n if (redirectUri) {\n formData.set('redirect_uri', redirectUri)\n } else if ('x-scalar-secret-redirect-uri' in flow && flow['x-scalar-secret-redirect-uri']) {\n formData.set('redirect_uri', flow['x-scalar-secret-redirect-uri'])\n }\n\n // Authorization Code\n if (code) {\n formData.set('code', code)\n formData.set('grant_type', 'authorization_code')\n\n // PKCE\n if (pkce) {\n formData.set('code_verifier', pkce.codeVerifier)\n }\n }\n // Password\n else if (type === 'password') {\n const typedFlow = flows[type]! // Safe to assert due to earlier check\n formData.set('grant_type', 'password')\n formData.set('username', typedFlow['x-scalar-secret-username'])\n formData.set('password', typedFlow['x-scalar-secret-password'])\n }\n // Client Credentials\n else {\n formData.set('grant_type', 'client_credentials')\n }\n\n // Additional request body parameters\n if (flow['x-scalar-security-body']) {\n Object.entries(flow['x-scalar-security-body']).forEach(([key, value]) => {\n if (value !== undefined && value !== null) {\n formData.set(key, String(value))\n }\n })\n }\n\n try {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n }\n\n // Add client id + secret to headers for confidential clients.\n if (!addCredentialsToBody && hasClientSecret) {\n headers.Authorization = `Basic ${encode(`${clientId}:${clientSecret}`)}`\n }\n\n // Check if we should use the proxy\n const tokenUrl = makeUrlAbsolute(\n flow['x-scalar-secret-token-url'] ?? flow.tokenUrl,\n getActiveServerBase(activeServer, environmentVariables),\n )\n const url = shouldUseProxy(proxyUrl, tokenUrl)\n ? `${proxyUrl}?${new URLSearchParams([['scalar_url', tokenUrl]]).toString()}`\n : tokenUrl\n\n // Make the call\n const resp = await customFetch(url, {\n method: 'POST',\n headers,\n body: formData,\n })\n const responseData = await resp.json()\n\n // Use custom token name if specified, otherwise default to access_token\n const tokenName = flow['x-tokenName'] || 'access_token'\n const accessToken = responseData[tokenName]\n const refreshToken = responseData.refresh_token\n\n if (!accessToken) {\n return [new Error(responseData.error_description ?? responseData.error ?? 'Failed to get an access token'), null]\n }\n\n return [null, { accessToken, ...(typeof refreshToken === 'string' ? { refreshToken } : {}) }]\n } catch (error) {\n return [\n error instanceof Error\n ? error\n : new Error('Failed to get an access token. Please check your credentials.', { cause: error }),\n null,\n ]\n }\n}\n\n/**\n * Exchange a refresh token for a new access token using the `grant_type=refresh_token` flow.\n *\n * Uses the stored refresh token, client credentials, and the token URL (or refreshUrl when available)\n * to request fresh tokens from the authorization server per RFC 6749 Section 6.\n */\nexport const refreshOauth2Token = async (\n flows: OAuthFlowsObjectSecret,\n type: RefreshableFlows,\n /** If we want to use the proxy */\n proxyUrl: string,\n /** We use the active server to set a base for relative URLs */\n activeServer: ServerObject | null,\n /** Flattened environment variables used to resolve server URL templates */\n environmentVariables: Record<string, string> = {},\n /** Fetch used for the refresh request; the desktop app passes an IPC-backed fetch so it leaves the renderer's network stack. */\n customFetch: CustomFetch = fetch,\n): Promise<ErrorResponse<OAuth2Tokens>> => {\n const flow = flows[type]\n\n if (!flow) {\n return [new Error('OAuth2 flow was not defined'), null]\n }\n\n const refreshToken = flow['x-scalar-secret-refresh-token']\n if (!refreshToken) {\n return [new Error('No refresh token available'), null]\n }\n\n const formData = new URLSearchParams()\n formData.set('grant_type', 'refresh_token')\n formData.set('refresh_token', refreshToken)\n\n // Ignore surrounding copy/paste whitespace without changing stored credentials or other secrets.\n const clientId = flow['x-scalar-secret-client-id'].trim()\n const clientSecret = flow['x-scalar-secret-client-secret'].trim()\n const addCredentialsToBody = flow['x-scalar-credentials-location'] === 'body'\n /** A confidential client keeps using its secret on refresh, even when PKCE is enabled. */\n const hasClientSecret = Boolean(clientSecret)\n /**\n * Public authorization-code clients still need client_id in the refresh body per RFC 6749 Section 6.\n * We only send it implicitly for that case to avoid conflicting with Basic auth.\n */\n const shouldSendClientIdInBody = addCredentialsToBody || (type === 'authorizationCode' && !hasClientSecret)\n\n if (shouldSendClientIdInBody) {\n formData.set('client_id', clientId)\n }\n if (addCredentialsToBody && hasClientSecret) {\n formData.set('client_secret', clientSecret)\n }\n\n if (flow['x-scalar-security-body']) {\n Object.entries(flow['x-scalar-security-body']).forEach(([key, value]) => {\n if (value !== undefined && value !== null) {\n formData.set(key, String(value))\n }\n })\n }\n\n try {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n }\n\n if (!addCredentialsToBody && hasClientSecret) {\n headers.Authorization = `Basic ${encode(`${clientId}:${clientSecret}`)}`\n }\n\n const refreshUrl = flow.refreshUrl || flow['x-scalar-secret-token-url'] || flow.tokenUrl\n const absoluteRefreshUrl = makeUrlAbsolute(refreshUrl, getActiveServerBase(activeServer, environmentVariables))\n const url = shouldUseProxy(proxyUrl, absoluteRefreshUrl)\n ? `${proxyUrl}?${new URLSearchParams([['scalar_url', absoluteRefreshUrl]]).toString()}`\n : absoluteRefreshUrl\n\n const resp = await customFetch(url, {\n method: 'POST',\n headers,\n body: formData,\n })\n const responseData = await resp.json()\n\n const tokenName = flow['x-tokenName'] || 'access_token'\n const accessToken = responseData[tokenName]\n const newRefreshToken = responseData.refresh_token\n\n if (!accessToken) {\n return [new Error(responseData.error_description ?? responseData.error ?? 'Token refresh failed'), null]\n }\n\n return [\n null,\n {\n accessToken,\n ...(typeof newRefreshToken === 'string' ? { refreshToken: newRefreshToken } : { refreshToken }),\n },\n ]\n } catch (error) {\n return [\n error instanceof Error\n ? error\n : new Error('Failed to refresh the access token. Please re-authorize.', { cause: error }),\n null,\n ]\n }\n}\n"],"mappings":";;;;;;;;;;;;AA4DA,IAAa,gBACX,cACA,uBAA+C,CAAC,MAEhD,oBACE,qBAAqB,cAAc,OAAO,IAAI,mBAAmB,YAAY,CAAC,GAC9E,oBACF;;;;;;;AAQF,IAAa,uBACX,cACA,uBAA+C,CAAC,MAC3B;CACrB,MAAM,YAAY,aAAa,cAAc,oBAAoB;CACjE,IAAI,CAAC,WACH,OAAO,CAAC;CAGV,IAAI,eAAe,SAAS,GAC1B,OAAO,OAAO,WAAW,cAAc,CAAC,IAAI,EAAE,UAAU,UAAU;CAGpE,OAAO,EAAE,SAAS,UAAU;AAC9B;;;;;;AAOA,IAAM,6BAAqC;CAEzC,MAAM,yBAAS,IAAI,WAAW,EAAE;CAChC,OAAO,gBAAgB,MAAM;CAG7B,OAAO,eAAe,QAAQ,IAAI;AACpC;;;;AAKA,IAAM,wBAAwB,OAAO,UAAkB,aAAmD;CACxG,IAAI,aAAa,SACf,OAAO;CAIT,IAAI,OAAO,QAAQ,QAAQ,WAAW,YAAY;EAChD,QAAQ,KAAK,wFAAwF;EACrG,OAAO;CACT;CAIA,MAAM,OAAO,IADO,YACP,CAAA,CAAQ,OAAO,QAAQ;CACpC,MAAM,SAAS,M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AAM,cAAc,aADF,KAAK,kBAAkB;EAEzC,MAAM,kBAAkB,aAAa;EAErC,IAAI,CAAC,aACH,OAAO,CAAC,IAAI,MAAM,aAAa,qBAAqB,aAAa,SAAS,sBAAsB,GAAG,IAAI;EAGzG,OAAO,CACL,MACA;GACE;GACA,GAAI,OAAO,oBAAoB,WAAW,EAAE,cAAc,gBAAgB,IAAI,EAAE,aAAa;EAC/F,CACF;CACF,SAAS,OAAO;EACd,OAAO,CACL,iBAAiB,QACb,QACA,IAAI,MAAM,4DAA4D,EAAE,OAAO,MAAM,CAAC,GAC1F,IACF;CACF;AACF"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { OAuthFlowsObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document';
|
|
2
|
+
import type { OpenIDConnectDiscovery } from './fetch-openid-connect-discovery.js';
|
|
3
|
+
type FlowUpdates = {
|
|
4
|
+
[Key in keyof OAuthFlowsObject]?: Partial<NonNullable<OAuthFlowsObject[Key]>>;
|
|
5
|
+
};
|
|
6
|
+
/** Supplements endpoints in declared flows. Explicit scopes, including an empty scope set, remain authoritative. */
|
|
7
|
+
export declare const oauth2MetadataToFlows: (metadata: OpenIDConnectDiscovery, flows: OAuthFlowsObject) => FlowUpdates;
|
|
8
|
+
export {};
|
|
9
|
+
//# sourceMappingURL=oauth2-metadata-to-flows.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth2-metadata-to-flows.d.ts","sourceRoot":"","sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/oauth2-metadata-to-flows.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8DAA8D,CAAA;AAEpG,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,kCAAkC,CAAA;AAE9E,KAAK,WAAW,GAAG;KAAG,GAAG,IAAI,MAAM,gBAAgB,CAAC,CAAC,EAAE,OAAO,CAAC,WAAW,CAAC,gBAAgB,CAAC,GAAG,CAAC,CAAC,CAAC;CAAE,CAAA;AAEpG,oHAAoH;AACpH,eAAO,MAAM,qBAAqB,GAAI,UAAU,sBAAsB,EAAE,OAAO,gBAAgB,KAAG,WA6BjG,CAAA"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
//#region src/v2/blocks/scalar-auth-selector-block/helpers/oauth2-metadata-to-flows.ts
|
|
2
|
+
/** Supplements endpoints in declared flows. Explicit scopes, including an empty scope set, remain authoritative. */
|
|
3
|
+
var oauth2MetadataToFlows = (metadata, flows) => {
|
|
4
|
+
const scopes = Object.fromEntries((metadata.scopes_supported ?? []).map((scope) => [scope, ""]));
|
|
5
|
+
const grants = new Set(metadata.grant_types_supported ?? ["authorization_code", "implicit"]);
|
|
6
|
+
const authorizationUrl = metadata.authorization_endpoint;
|
|
7
|
+
const tokenUrl = metadata.token_endpoint;
|
|
8
|
+
const discovered = {
|
|
9
|
+
...grants.has("implicit") && authorizationUrl ? { implicit: {
|
|
10
|
+
authorizationUrl,
|
|
11
|
+
scopes
|
|
12
|
+
} } : {},
|
|
13
|
+
...grants.has("password") && tokenUrl ? { password: {
|
|
14
|
+
tokenUrl,
|
|
15
|
+
scopes
|
|
16
|
+
} } : {},
|
|
17
|
+
...grants.has("client_credentials") && tokenUrl ? { clientCredentials: {
|
|
18
|
+
tokenUrl,
|
|
19
|
+
scopes
|
|
20
|
+
} } : {},
|
|
21
|
+
...grants.has("authorization_code") && authorizationUrl && tokenUrl ? { authorizationCode: {
|
|
22
|
+
authorizationUrl,
|
|
23
|
+
tokenUrl,
|
|
24
|
+
scopes
|
|
25
|
+
} } : {}
|
|
26
|
+
};
|
|
27
|
+
if (!Object.keys(flows).length) return discovered;
|
|
28
|
+
return Object.fromEntries(Object.entries(flows).filter(([, flow]) => flow).map(([key, flow]) => [key, {
|
|
29
|
+
..."authorizationUrl" in flow && !flow.authorizationUrl && authorizationUrl ? { authorizationUrl } : {},
|
|
30
|
+
..."tokenUrl" in flow && !flow.tokenUrl && tokenUrl ? { tokenUrl } : {}
|
|
31
|
+
}]).filter(([, update]) => Object.keys(update).length > 0));
|
|
32
|
+
};
|
|
33
|
+
//#endregion
|
|
34
|
+
export { oauth2MetadataToFlows };
|
|
35
|
+
|
|
36
|
+
//# sourceMappingURL=oauth2-metadata-to-flows.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth2-metadata-to-flows.js","names":[],"sources":["../../../../../src/v2/blocks/scalar-auth-selector-block/helpers/oauth2-metadata-to-flows.ts"],"sourcesContent":["import type { OAuthFlowsObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\n\nimport type { OpenIDConnectDiscovery } from './fetch-openid-connect-discovery'\n\ntype FlowUpdates = { [Key in keyof OAuthFlowsObject]?: Partial<NonNullable<OAuthFlowsObject[Key]>> }\n\n/** Supplements endpoints in declared flows. Explicit scopes, including an empty scope set, remain authoritative. */\nexport const oauth2MetadataToFlows = (metadata: OpenIDConnectDiscovery, flows: OAuthFlowsObject): FlowUpdates => {\n const scopes = Object.fromEntries((metadata.scopes_supported ?? []).map((scope) => [scope, '']))\n const grants = new Set(metadata.grant_types_supported ?? ['authorization_code', 'implicit'])\n const authorizationUrl = metadata.authorization_endpoint\n const tokenUrl = metadata.token_endpoint\n const discovered: FlowUpdates = {\n ...(grants.has('implicit') && authorizationUrl ? { implicit: { authorizationUrl, scopes } } : {}),\n ...(grants.has('password') && tokenUrl ? { password: { tokenUrl, scopes } } : {}),\n ...(grants.has('client_credentials') && tokenUrl ? { clientCredentials: { tokenUrl, scopes } } : {}),\n ...(grants.has('authorization_code') && authorizationUrl && tokenUrl\n ? { authorizationCode: { authorizationUrl, tokenUrl, scopes } }\n : {}),\n }\n // An empty Flows Object can discover supported grants. Otherwise the API description controls the allowed flows.\n if (!Object.keys(flows).length) {\n return discovered\n }\n return Object.fromEntries(\n Object.entries(flows)\n .filter(([, flow]) => flow)\n .map(([key, flow]): [string, Record<string, string>] => [\n key,\n {\n ...('authorizationUrl' in flow && !flow.authorizationUrl && authorizationUrl ? { authorizationUrl } : {}),\n ...('tokenUrl' in flow && !flow.tokenUrl && tokenUrl ? { tokenUrl } : {}),\n },\n ])\n .filter(([, update]) => Object.keys(update).length > 0),\n )\n}\n"],"mappings":";;AAOA,IAAa,yBAAyB,UAAkC,UAAyC;CAC/G,MAAM,SAAS,OAAO,aAAa,SAAS,oBAAoB,CAAC,EAAA,CAAG,KAAK,UAAU,CAAC,OAAO,EAAE,CAAC,CAAC;CAC/F,MAAM,SAAS,IAAI,IAAI,SAAS,yBAAyB,CAAC,sBAAsB,UAAU,CAAC;CAC3F,MAAM,mBAAmB,SAAS;CAClC,MAAM,WAAW,SAAS;CAC1B,MAAM,aAA0B;EAC9B,GAAI,OAAO,IAAI,UAAU,KAAK,mBAAmB,EAAE,UAAU;GAAE;GAAkB;EAAO,EAAE,IAAI,CAAC;EAC/F,GAAI,OAAO,IAAI,UAAU,KAAK,WAAW,EAAE,UAAU;GAAE;GAAU;EAAO,EAAE,IAAI,CAAC;EAC/E,GAAI,OAAO,IAAI,oBAAoB,KAAK,WAAW,EAAE,mBAAmB;GAAE;GAAU;EAAO,EAAE,IAAI,CAAC;EAClG,GAAI,OAAO,IAAI,oBAAoB,KAAK,oBAAoB,WACxD,EAAE,mBAAmB;GAAE;GAAkB;GAAU;EAAO,EAAE,IAC5D,CAAC;CACP;CAEA,IAAI,CAAC,OAAO,KAAK,KAAK,CAAC,CAAC,QACtB,OAAO;CAET,OAAO,OAAO,YACZ,OAAO,QAAQ,KAAK,CAAC,CAClB,QAAQ,GAAG,UAAU,IAAI,CAAC,CAC1B,KAAK,CAAC,KAAK,UAA4C,CACtD,KACA;EACE,GAAI,sBAAsB,QAAQ,CAAC,KAAK,oBAAoB,mBAAmB,EAAE,iBAAiB,IAAI,CAAC;EACvG,GAAI,cAAc,QAAQ,CAAC,KAAK,YAAY,WAAW,EAAE,SAAS,IAAI,CAAC;CACzE,CACF,CAAC,CAAC,CACD,QAAQ,GAAG,YAAY,OAAO,KAAK,MAAM,CAAC,CAAC,SAAS,CAAC,CAC1D;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type CodeMirrorLanguage, type Extension } from '@scalar/use-codemirror';
|
|
1
|
+
import { EditorView, type CodeMirrorLanguage, type Extension } from '@scalar/use-codemirror';
|
|
2
2
|
import type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments';
|
|
3
3
|
import { type Ref } from 'vue';
|
|
4
4
|
import type { ClientLayout } from '../../../v2/types/layout';
|
|
@@ -98,7 +98,7 @@ declare const __VLS_export: __VLS_WithSlots<import("vue").DefineComponent<{
|
|
|
98
98
|
handleSubmit: (value: string, event: KeyboardEvent | FocusEvent) => void;
|
|
99
99
|
handleBlur: (value: string, event: FocusEvent) => void;
|
|
100
100
|
booleanOptions: import("vue").ComputedRef<string[]>;
|
|
101
|
-
codeMirror: Ref<
|
|
101
|
+
codeMirror: Ref<EditorView | null, EditorView | null>;
|
|
102
102
|
codeMirrorRef: Ref<HTMLDivElement | null, HTMLDivElement | null>;
|
|
103
103
|
modelValue: CodeInputModelValue;
|
|
104
104
|
setCodeMirrorContent: (content?: string) => void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CodeInput.vue.d.ts","sourceRoot":"","sources":["../../../../src/v2/components/code-input/CodeInput.vue"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"CodeInput.vue.d.ts","sourceRoot":"","sources":["../../../../src/v2/components/code-input/CodeInput.vue"],"names":[],"mappings":"AAwvBA,OAAO,EAEL,UAAU,EAGV,KAAK,kBAAkB,EACvB,KAAK,SAAS,EACf,MAAM,wBAAwB,CAAA;AAM/B,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2EAA2E,CAAA;AAEnH,OAAO,EAAyC,KAAK,GAAG,EAAE,MAAM,KAAK,CAAA;AAIrE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBA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MAAM,EAAE,CAAC,CAAC;KACV,CAAA;CACD,CAAC"}
|
|
@@ -3,7 +3,7 @@ import CodeInput_vue_vue_type_script_setup_true_lang_default from "./CodeInput.v
|
|
|
3
3
|
/* empty css */
|
|
4
4
|
/* empty css */
|
|
5
5
|
//#region src/v2/components/code-input/CodeInput.vue
|
|
6
|
-
var CodeInput_default = /*#__PURE__*/ _plugin_vue_export_helper_default(CodeInput_vue_vue_type_script_setup_true_lang_default, [["__scopeId", "data-v-
|
|
6
|
+
var CodeInput_default = /*#__PURE__*/ _plugin_vue_export_helper_default(CodeInput_vue_vue_type_script_setup_true_lang_default, [["__scopeId", "data-v-dbc85839"]]);
|
|
7
7
|
//#endregion
|
|
8
8
|
export { CodeInput_default as default };
|
|
9
9
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CodeInput.vue.js","names":[],"sources":["../../../../src/v2/components/code-input/CodeInput.vue"],"sourcesContent":["<script lang=\"ts\">\nexport type CodeInputModelValue =\n | string\n | number\n | boolean\n | Array<string | number | boolean>\n | Record<string, unknown>\n\n/**\n * CodeInput\n *\n * A versatile input component that adapts its rendering based on props:\n * - Disabled mode: Read-only text display\n * - Select mode: Dropdown for enums, booleans, or examples\n * - Editor mode: CodeMirror with environment variable support\n *\n * Type `{{` to trigger autocomplete for environment variables and runtime context functions\n * (for example `{{$guid}}`) when an environment is provided.\n * It takes in any data but always will emit a string value,\n * this string should then be parsed in accordance to the schema or content type.\n *\n * @example\n * ```vue\n * <!-- Basic input with environment variables -->\n * <CodeInput v-model=\"value\" :environment=\"env\" />\n *\n * <!-- Boolean select -->\n * <CodeInput v-model=\"flag\" type=\"boolean\" />\n *\n * <!-- JSON editor with linting -->\n * <CodeInput v-model=\"data\" language=\"json\" :lint=\"true\" />\n * ```\n */\nexport default {\n inheritAttrs: false,\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { isDefined } from '@scalar/helpers/array/is-defined'\nimport {\n colorPicker as colorPickerExtension,\n useCodeMirror,\n useDropdown,\n type CodeMirrorLanguage,\n type Extension,\n} from '@scalar/use-codemirror'\nimport {\n CONTEXT_FUNCTION_NAMES,\n getContextFunctionComment,\n isContextFunctionName,\n} from '@scalar/workspace-store/request-example'\nimport type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments'\nimport { nanoid } from 'nanoid'\nimport { computed, ref, toRef, useAttrs, watch, type Ref } from 'vue'\n\nimport DataTableInputSelect from '@/v2/components/data-table/DataTableInputSelect.vue'\nimport EnvironmentVariableDropdown from '@/v2/features/environments/components/EnvironmentVariablesDropdown.vue'\nimport type { ClientLayout } from '@/v2/types/layout'\n\nimport { backspaceCommand, pillPlugin } from './code-variable-widget'\n\ntype Props = {\n modelValue: CodeInputModelValue\n /** Environment for variable substitution. Pass undefined to disable environment variables */\n environment: XScalarEnvironment | undefined\n /** Type of the input value, affects rendering mode for booleans */\n type?: string | string[]\n /** Render as disabled text display */\n disabled?: boolean\n /** Show error styling */\n error?: boolean\n /** Layout context affects styling and behavior */\n layout?: ClientLayout\n /** Predefined enum values, triggers select mode */\n enum?: string[]\n /** Example values, triggers select mode */\n examples?: string[]\n /** Default value to show in select mode */\n default?: Props['modelValue']\n /** Allow null in boolean select options */\n nullable?: boolean\n /** Placeholder text for empty input */\n placeholder?: string\n /** Show required indicator */\n required?: boolean\n /** Enable color picker extension */\n colorPicker?: boolean\n /** Show line numbers in editor */\n lineNumbers?: boolean\n /** Enable linting */\n lint?: boolean\n /** Enable line wrapping */\n lineWrapping?: boolean\n /** CodeMirror language mode */\n language?: CodeMirrorLanguage\n /** Additional CodeMirror extensions */\n extensions?: Extension[]\n /** Disable tab key for indentation */\n disableTabIndent?: boolean\n /** Disable enter key */\n disableEnter?: boolean\n /** Disable automatic bracket closing */\n disableCloseBrackets?: boolean\n /** Emit submit event on blur */\n emitOnBlur?: boolean\n /** Enable environment variable pills */\n withVariables?: boolean\n /** Enable fake data suggestions like $guid, $timestamp, etc. Should only be enabled for parameters and request bodies */\n withFakeData?: boolean\n /** Emit change event even if the value is the same */\n alwaysEmitChange?: boolean\n /** Custom change handler, prevents default emit */\n handleFieldChange?: (value: string) => void\n /** Custom submit handler, prevents default emit */\n handleFieldSubmit?: (value: string) => void\n /** Put a linethrough on the input text */\n linethrough?: boolean\n}\n\nconst {\n modelValue,\n environment,\n type,\n disabled = false,\n error = false,\n layout = 'desktop',\n enum: enumProp,\n examples,\n default: defaultProp,\n nullable = false,\n placeholder,\n required,\n colorPicker = false,\n lineNumbers = false,\n lint = false,\n lineWrapping = false,\n language,\n extensions = [],\n disableTabIndent = false,\n disableEnter = false,\n disableCloseBrackets = false,\n emitOnBlur = true,\n alwaysEmitChange = false,\n withVariables = true,\n withFakeData = false,\n handleFieldChange,\n handleFieldSubmit,\n} = defineProps<Props>()\n\nconst emit = defineEmits<{\n 'update:modelValue': [value: string]\n 'submit': [value: string, event: KeyboardEvent | FocusEvent]\n 'navigate': [route: { page: 'document'; path: 'environment' }]\n 'blur': [value: string, event: FocusEvent]\n}>()\n\n// ---------------------------------------------------------------------------\n// Component identity and focus state\n\nconst attrs = useAttrs()\nconst componentId =\n (typeof attrs.id === 'string' && attrs.id) || `id-${nanoid()}`\nconst isFocused = ref(false)\n\n// ---------------------------------------------------------------------------\n// Rendering mode detection\n\n/**\n * Determines if we should render a select dropdown for boolean types.\n */\nconst isBooleanMode = computed((): boolean => {\n if (enumProp?.length) {\n return false\n }\n return type === 'boolean' || (Array.isArray(type) && type.includes('boolean'))\n})\n\n/**\n * Options for boolean select mode.\n */\nconst booleanOptions = computed((): string[] =>\n nullable ? ['true', 'false', 'null'] : ['true', 'false'],\n)\n\n/**\n * Default type when dealing with type arrays.\n * Finds the first non-null type.\n */\nconst defaultType = computed((): string | undefined => {\n if (Array.isArray(type)) {\n return type.find((t) => t !== 'null') ?? 'string'\n }\n return type\n})\n\n// ---------------------------------------------------------------------------\n// Event handlers\n\n/**\n * Handles value changes during typing.\n */\nconst handleChange = (value: string): void => {\n if (!alwaysEmitChange && value === serializeValue(modelValue)) {\n return\n }\n\n // Use custom handler or emit update\n if (handleFieldChange) {\n handleFieldChange(value)\n } else {\n emit('update:modelValue', value)\n }\n}\n\n/**\n * Handles form submission (enter key or blur with emitOnBlur).\n */\nconst handleSubmit = (\n value: string,\n event: KeyboardEvent | FocusEvent,\n): void => {\n if (handleFieldSubmit) {\n handleFieldSubmit(value)\n } else {\n emit('submit', value, event)\n }\n}\n\n/**\n * Handles input blur event.\n */\nconst handleBlur = (value: string, event: FocusEvent): void => {\n isFocused.value = false\n\n if (emitOnBlur && modelValue) {\n handleSubmit(value, event)\n }\n\n emit('blur', value, event)\n}\n\n/**\n * Handles model value updates from select components.\n */\nconst handleSelectChange = (value: string): void =>\n emit('update:modelValue', value)\n\n// ---------------------------------------------------------------------------\n// CodeMirror setup\n\n/**\n * Build extensions array.\n * Note: Extensions are not reactive after initialization.\n */\nconst buildExtensions = (): Extension[] => {\n const extensionsList: Extension[] = [...extensions]\n\n if (colorPicker) {\n extensionsList.push(colorPickerExtension)\n }\n\n return extensionsList\n}\n\n/**\n * Reactive pill plugin for environment variable visualization.\n */\nconst contextFunctionDropdownItems = computed(() =>\n withFakeData\n ? CONTEXT_FUNCTION_NAMES.map((key) => ({\n key,\n description: getContextFunctionComment(key),\n }))\n : [],\n)\n\nconst pillPluginExtension = computed(() =>\n pillPlugin({\n environment,\n isContextFunctionName,\n isReadOnly: layout === 'modal',\n }),\n)\n\n/**\n * Combined extensions for CodeMirror.\n */\nconst codeMirrorExtensions = computed((): Extension[] => [\n ...buildExtensions(),\n pillPluginExtension.value,\n backspaceCommand,\n])\n\nconst codeMirrorRef: Ref<HTMLDivElement | null> = ref(null)\n\n/** Converts the model value to a string for CodeMirror */\nconst serializeValue = (value: CodeInputModelValue): string => {\n if (typeof value === 'string') {\n return value\n }\n return JSON.stringify(value)\n}\n\nconst { codeMirror, setCodeMirrorContent } = useCodeMirror({\n content: toRef(() => serializeValue(modelValue)),\n onChange: (value) => {\n handleChange(value)\n updateDropdownVisibility()\n },\n onFocus: () => {\n isFocused.value = true\n },\n onBlur: handleBlur,\n codeMirrorRef,\n disableTabIndent: toRef(() => disableTabIndent),\n disableEnter: toRef(() => disableEnter),\n disableCloseBrackets: toRef(() => disableCloseBrackets),\n lineNumbers: toRef(() => lineNumbers),\n language: toRef(() => language),\n lint: toRef(() => lint),\n extensions: codeMirrorExtensions,\n placeholder: toRef(() => placeholder),\n})\n\n/**\n * Handle autofocus attribute.\n */\nwatch(codeMirror, () => {\n if (codeMirror.value && Object.hasOwn(attrs, 'autofocus')) {\n codeMirror.value.focus()\n }\n})\n\n// ---------------------------------------------------------------------------\n// Environment variable dropdown\n\nconst showDropdown = ref(false)\nconst dropdownQuery = ref('')\nconst dropdownPosition = ref({ left: 0, top: 0 })\nconst dropdownRef = ref<InstanceType<\n typeof EnvironmentVariableDropdown\n> | null>(null)\n\nconst { handleDropdownSelect, updateDropdownVisibility } = useDropdown({\n codeMirror,\n query: dropdownQuery,\n showDropdown,\n dropdownPosition,\n})\n\n/**\n * Determines if the environment variable dropdown should be visible.\n * Shows when environment is defined (for env vars) or withFakeData is true (for context functions)\n */\nconst displayVariablesDropdown = computed((): boolean => {\n return (\n showDropdown.value &&\n withVariables &&\n layout !== 'modal' &&\n (Boolean(environment) || withFakeData)\n )\n})\n\n// ---------------------------------------------------------------------------\n// Keyboard event handling\n\n/**\n * Handles keyboard navigation for dropdown and form submission.\n */\nconst handleKeyDown = (key: string, event: KeyboardEvent): void => {\n if (showDropdown.value) {\n if (key === 'down' || key === 'up') {\n event.preventDefault()\n dropdownRef.value?.handleArrowKey(key)\n } else if (key === 'enter') {\n event.preventDefault()\n dropdownRef.value?.handleSelect()\n }\n return\n }\n\n if (key === 'escape' && !disableTabIndent) {\n event.stopPropagation()\n }\n\n if (key === 'enter' && event.target instanceof HTMLDivElement) {\n handleSubmit(codeMirror.value?.state.doc.toString() ?? '', event)\n }\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n\ndefineExpose({\n /**\n * Focus the codemirror element\n *\n * @param cursorAtEnd boolean place the cursor at the end of the input\n */\n focus: (position?: 'start' | 'end' | number) => {\n if (!codeMirror.value) {\n return\n }\n codeMirror.value.focus()\n\n if (!isDefined(position)) {\n return\n }\n\n const anchor = (() => {\n if (position === 'start') {\n return 0\n }\n if (position === 'end') {\n return codeMirror.value.state.doc.length\n }\n return position\n })()\n\n // Move the cursor to the specified position\n codeMirror.value.dispatch({\n selection: { anchor },\n scrollIntoView: true,\n })\n },\n isFocused,\n handleChange,\n handleSubmit,\n handleBlur,\n booleanOptions,\n codeMirror,\n codeMirrorRef,\n modelValue,\n setCodeMirrorContent,\n cursorPosition: () => codeMirror.value?.state.selection.main.head,\n serializeValue,\n})\n</script>\n\n<template>\n <!-- Disabled mode: read-only text display -->\n <div\n v-if=\"disabled\"\n class=\"text-c-2 flex cursor-default items-center justify-center\"\n :class=\"{\n 'font-code pr-2 pl-1 text-base': layout === 'modal',\n 'px-2': layout !== 'modal',\n 'line-through': linethrough,\n }\"\n data-testid=\"code-input-disabled\">\n <span class=\"whitespace-nowrap\">{{ modelValue }}</span>\n </div>\n\n <!-- Enum mode: select dropdown with predefined values -->\n <DataTableInputSelect\n v-else-if=\"enumProp?.length\"\n :default=\"defaultProp\"\n :modelValue=\"modelValue\"\n :type=\"defaultType\"\n :value=\"enumProp\"\n @update:modelValue=\"handleSelectChange\" />\n\n <!-- Boolean mode: select dropdown with true/false (and optionally null) -->\n <DataTableInputSelect\n v-else-if=\"isBooleanMode\"\n :default=\"defaultProp\"\n :modelValue=\"modelValue\"\n :value=\"booleanOptions\"\n @update:modelValue=\"handleSelectChange\" />\n\n <!-- Examples mode: select dropdown with example values -->\n <DataTableInputSelect\n v-else-if=\"examples?.length\"\n :default=\"defaultProp\"\n :modelValue=\"modelValue\"\n :value=\"examples\"\n @update:modelValue=\"handleSelectChange\" />\n\n <!-- Editor mode: CodeMirror with environment variable support -->\n <div\n v-else\n :id=\"componentId\"\n v-bind=\"$attrs\"\n ref=\"codeMirrorRef\"\n class=\"group/input group-[.alert]:outline-orange group-[.error]:outline-red font-code peer relative w-full overflow-hidden text-xs leading-[1.44] whitespace-nowrap -outline-offset-1 has-[:focus-visible]:rounded-[4px] has-[:focus-visible]:outline\"\n :class=\"{\n 'line-wrapping has-[:focus-visible]:bg-b-1 has-[:focus-visible]:absolute has-[:focus-visible]:z-1':\n lineWrapping,\n 'flow-code-input--error': error,\n 'line-through': linethrough,\n }\"\n @keydown.down.stop=\"handleKeyDown('down', $event)\"\n @keydown.enter=\"handleKeyDown('enter', $event)\"\n @keydown.escape=\"handleKeyDown('escape', $event)\"\n @keydown.up.stop=\"handleKeyDown('up', $event)\">\n <!-- Tab exit hint (shown when focused) -->\n <div\n v-if=\"!disableTabIndent\"\n class=\"z-context text-c-2 absolute right-1.5 bottom-1 hidden font-sans group-has-[:focus-visible]/input:block\"\n role=\"alert\">\n Press\n <kbd class=\"-mx-0.25 rounded border px-0.5 font-mono\">Esc</kbd> then\n <kbd class=\"-mx-0.25 rounded border px-0.5 font-mono\">Tab</kbd> to exit\n </div>\n </div>\n\n <!-- Warning slot (positioned absolutely) -->\n <div\n v-if=\"$slots.warning\"\n class=\"centered-y text-orange absolute right-7 text-xs\">\n <slot name=\"warning\" />\n </div>\n\n <!-- Icon slot (positioned absolutely) -->\n <div\n v-if=\"$slots.icon\"\n class=\"centered-y absolute right-0 flex h-full items-center p-1.5 group-has-[.cm-focused]:z-1\">\n <slot name=\"icon\" />\n </div>\n\n <!-- Required indicator -->\n <div\n v-if=\"required\"\n class=\"required centered-y text-xxs text-c-3 group-[.error]:text-red bg-b-1 pointer-events-none absolute right-0 mr-0.5 pt-px pr-2 opacity-100 shadow-[-8px_0_4px_var(--scalar-background-1)] transition-opacity duration-150 group-[.alert]:bg-transparent group-[.alert]:shadow-none group-[.error]:bg-transparent group-[.error]:shadow-none peer-has-[.cm-focused]:opacity-0\">\n Required\n </div>\n\n <!-- Environment variable autocomplete dropdown -->\n <EnvironmentVariableDropdown\n v-if=\"displayVariablesDropdown\"\n ref=\"dropdownRef\"\n :contextFunctionItems=\"contextFunctionDropdownItems\"\n :dropdownPosition=\"dropdownPosition\"\n :environment=\"environment\"\n :query=\"dropdownQuery\"\n @close=\"showDropdown = false\"\n @redirect=\"emit('navigate', { page: 'document', path: 'environment' })\"\n @select=\"handleDropdownSelect\" />\n</template>\n<style scoped>\n/*\n Deep styling for customizing Codemirror\n */\n:deep(.cm-editor) {\n height: 100%;\n outline: none;\n padding: 0;\n background: transparent;\n}\n:deep(.cm-placeholder) {\n color: var(--scalar-color-3);\n}\n:deep(.cm-content) {\n font-family: var(--scalar-font-code);\n font-size: var(--scalar-small);\n max-height: 20px;\n padding: 8px 0;\n}\n/* Tooltip helper */\n:deep(.cm-tooltip) {\n background: transparent !important;\n filter: brightness(var(--scalar-lifted-brightness));\n border-radius: var(--scalar-radius);\n box-shadow: var(--scalar-shadow-2);\n border: none !important;\n outline: none !important;\n overflow: hidden !important;\n}\n:deep(.cm-tooltip-autocomplete ul li) {\n padding: 3px 6px !important;\n}\n:deep(.cm-completionIcon-type:after) {\n color: var(--scalar-color-3) !important;\n}\n:deep(.cm-tooltip-autocomplete ul li[aria-selected]) {\n background: var(--scalar-background-2) !important;\n color: var(--scalar-color-1) !important;\n}\n:deep(.cm-tooltip-autocomplete ul) {\n padding: 6px !important;\n position: relative;\n}\n:deep(.cm-tooltip-autocomplete ul li:hover) {\n border-radius: 3px;\n color: var(--scalar-color-1) !important;\n background: var(--scalar-background-3) !important;\n}\n/* Disable active line highlighting */\n:deep(.cm-activeLine),\n:deep(.cm-activeLineGutter) {\n background-color: transparent;\n}\n/* Color selection matching */\n:deep(.cm-selectionMatch),\n:deep(.cm-matchingBracket) {\n border-radius: var(--scalar-radius);\n background: var(--scalar-background-4) !important;\n}\n/* Color Picker Swatches */\n:deep(.cm-css-color-picker-wrapper) {\n display: inline-flex;\n outline: 1px solid var(--scalar-background-3);\n border-radius: 3px;\n overflow: hidden;\n}\n/* Number gutter */\n:deep(.cm-gutters) {\n background-color: transparent;\n border-right: none;\n color: var(--scalar-color-3);\n font-size: var(--scalar-small);\n line-height: 22px;\n border-radius: 0 0 0 3px;\n}\n:deep(.cm-gutters:before) {\n content: '';\n position: absolute;\n top: 2px;\n left: 2px;\n width: calc(100% - 2px);\n height: calc(100% - 4px);\n border-radius: var(--scalar-radius) 0 0 var(--scalar-radius);\n background-color: var(--scalar-background-1);\n}\n:deep(.cm-gutterElement) {\n font-family: var(--scalar-font-code) !important;\n padding-left: 0px !important;\n padding-right: 6px !important;\n display: flex;\n align-items: center;\n justify-content: flex-end;\n position: relative;\n}\n:deep(.cm-lineNumbers .cm-gutterElement) {\n min-width: fit-content;\n}\n:deep(.cm-gutter + .cm-gutter :not(.cm-foldGutter) .cm-gutterElement) {\n padding-left: 0 !important;\n}\n:deep(.cm-scroller) {\n overflow: auto;\n}\n.line-wrapping:focus-within :deep(.cm-content) {\n display: inline-table;\n min-height: fit-content;\n padding: 3px 6px;\n white-space: break-spaces;\n word-break: break-all;\n}\n</style>\n<style>\n.cm-pill {\n color: var(--scalar-color-1) !important;\n padding: 0px 9px;\n display: inline-block;\n border-radius: var(--scalar-radius-full);\n font-size: var(--scalar-small);\n}\n.light-mode .cm-pill {\n background: var(--scalar-background-3) !important;\n}\n.dark-mode .cm-pill {\n background: color-mix(in srgb, var(--tw-bg-base), transparent 90%) !important;\n}\n.cm-pill--context-fn {\n border: 1px dashed color-mix(in srgb, var(--scalar-color-3), transparent 35%);\n padding: 0px 8px;\n}\n.light-mode .cm-pill--context-fn {\n background: color-mix(\n in srgb,\n var(--scalar-background-3),\n transparent 40%\n ) !important;\n}\n.dark-mode .cm-pill--context-fn {\n background: color-mix(\n in srgb,\n var(--scalar-background-3),\n transparent 55%\n ) !important;\n}\n.cm-pill:first-of-type {\n margin-left: 0;\n}\n.cm-editor .cm-widgetBuffer {\n display: none;\n}\n.cm-foldPlaceholder:hover {\n color: var(--scalar-color-1);\n}\n.cm-foldGutter .cm-gutterElement {\n font-size: var(--scalar-heading-4);\n padding: 2px !important;\n}\n.cm-foldGutter .cm-gutterElement:first-of-type {\n display: none;\n}\n.cm-foldGutter .cm-gutterElement .cm-foldMarker {\n padding: 2px;\n padding-top: 2px;\n}\n.cm-foldGutter .cm-gutterElement:hover .cm-foldMarker {\n background: var(--scalar-background-2);\n border-radius: var(--scalar-radius);\n color: var(--scalar-color-1);\n}\n</style>\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"CodeInput.vue.js","names":[],"sources":["../../../../src/v2/components/code-input/CodeInput.vue"],"sourcesContent":["<script lang=\"ts\">\nexport type CodeInputModelValue =\n | string\n | number\n | boolean\n | Array<string | number | boolean>\n | Record<string, unknown>\n\n/**\n * CodeInput\n *\n * A versatile input component that adapts its rendering based on props:\n * - Disabled mode: Read-only text display\n * - Select mode: Dropdown for enums, booleans, or examples\n * - Editor mode: CodeMirror with environment variable support\n *\n * Type `{{` to trigger autocomplete for environment variables and runtime context functions\n * (for example `{{$guid}}`) when an environment is provided.\n * It takes in any data but always will emit a string value,\n * this string should then be parsed in accordance to the schema or content type.\n *\n * @example\n * ```vue\n * <!-- Basic input with environment variables -->\n * <CodeInput v-model=\"value\" :environment=\"env\" />\n *\n * <!-- Boolean select -->\n * <CodeInput v-model=\"flag\" type=\"boolean\" />\n *\n * <!-- JSON editor with linting -->\n * <CodeInput v-model=\"data\" language=\"json\" :lint=\"true\" />\n * ```\n */\nexport default {\n inheritAttrs: false,\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { ScalarIconButton } from '@scalar/components/icon-button'\nimport { isDefined } from '@scalar/helpers/array/is-defined'\nimport { ScalarIconArrowElbowDownLeft } from '@scalar/icons'\nimport {\n colorPicker as colorPickerExtension,\n EditorView,\n useCodeMirror,\n useDropdown,\n type CodeMirrorLanguage,\n type Extension,\n} from '@scalar/use-codemirror'\nimport {\n CONTEXT_FUNCTION_NAMES,\n getContextFunctionComment,\n isContextFunctionName,\n} from '@scalar/workspace-store/request-example'\nimport type { XScalarEnvironment } from '@scalar/workspace-store/schemas/extensions/document/x-scalar-environments'\nimport { nanoid } from 'nanoid'\nimport { computed, ref, toRef, useAttrs, watch, type Ref } from 'vue'\n\nimport DataTableInputSelect from '@/v2/components/data-table/DataTableInputSelect.vue'\nimport EnvironmentVariableDropdown from '@/v2/features/environments/components/EnvironmentVariablesDropdown.vue'\nimport type { ClientLayout } from '@/v2/types/layout'\n\nimport { backspaceCommand, pillPlugin } from './code-variable-widget'\n\ntype Props = {\n modelValue: CodeInputModelValue\n /** Environment for variable substitution. Pass undefined to disable environment variables */\n environment: XScalarEnvironment | undefined\n /** Type of the input value, affects rendering mode for booleans */\n type?: string | string[]\n /** Render as disabled text display */\n disabled?: boolean\n /** Show error styling */\n error?: boolean\n /** Layout context affects styling and behavior */\n layout?: ClientLayout\n /** Predefined enum values, triggers select mode */\n enum?: string[]\n /** Example values, triggers select mode */\n examples?: string[]\n /** Default value to show in select mode */\n default?: Props['modelValue']\n /** Allow null in boolean select options */\n nullable?: boolean\n /** Placeholder text for empty input */\n placeholder?: string\n /** Show required indicator */\n required?: boolean\n /** Enable color picker extension */\n colorPicker?: boolean\n /** Show line numbers in editor */\n lineNumbers?: boolean\n /** Enable linting */\n lint?: boolean\n /** Enable line wrapping */\n lineWrapping?: boolean\n /** CodeMirror language mode */\n language?: CodeMirrorLanguage\n /** Additional CodeMirror extensions */\n extensions?: Extension[]\n /** Disable tab key for indentation */\n disableTabIndent?: boolean\n /** Disable enter key */\n disableEnter?: boolean\n /** Disable automatic bracket closing */\n disableCloseBrackets?: boolean\n /** Emit submit event on blur */\n emitOnBlur?: boolean\n /** Enable environment variable pills */\n withVariables?: boolean\n /** Enable fake data suggestions like $guid, $timestamp, etc. Should only be enabled for parameters and request bodies */\n withFakeData?: boolean\n /** Emit change event even if the value is the same */\n alwaysEmitChange?: boolean\n /** Custom change handler, prevents default emit */\n handleFieldChange?: (value: string) => void\n /** Custom submit handler, prevents default emit */\n handleFieldSubmit?: (value: string) => void\n /** Put a linethrough on the input text */\n linethrough?: boolean\n}\n\nconst {\n modelValue,\n environment,\n type,\n disabled = false,\n error = false,\n layout = 'desktop',\n enum: enumProp,\n examples,\n default: defaultProp,\n nullable = false,\n placeholder,\n required,\n colorPicker = false,\n lineNumbers = false,\n lint = false,\n lineWrapping = false,\n language,\n extensions = [],\n disableTabIndent = false,\n disableEnter = false,\n disableCloseBrackets = false,\n emitOnBlur = true,\n alwaysEmitChange = false,\n withVariables = true,\n withFakeData = false,\n handleFieldChange,\n handleFieldSubmit,\n} = defineProps<Props>()\n\nconst emit = defineEmits<{\n 'update:modelValue': [value: string]\n 'submit': [value: string, event: KeyboardEvent | FocusEvent]\n 'navigate': [route: { page: 'document'; path: 'environment' }]\n 'blur': [value: string, event: FocusEvent]\n}>()\n\n// ---------------------------------------------------------------------------\n// Component identity and focus state\n\nconst attrs = useAttrs()\nconst componentId =\n (typeof attrs.id === 'string' && attrs.id) || `id-${nanoid()}`\nconst isFocused = ref(false)\n\n// ---------------------------------------------------------------------------\n// Rendering mode detection\n\n/**\n * Determines if we should render a select dropdown for boolean types.\n */\nconst isBooleanMode = computed((): boolean => {\n if (enumProp?.length) {\n return false\n }\n return type === 'boolean' || (Array.isArray(type) && type.includes('boolean'))\n})\n\n/**\n * Options for boolean select mode.\n */\nconst booleanOptions = computed((): string[] =>\n nullable ? ['true', 'false', 'null'] : ['true', 'false'],\n)\n\n/**\n * Default type when dealing with type arrays.\n * Finds the first non-null type.\n */\nconst defaultType = computed((): string | undefined => {\n if (Array.isArray(type)) {\n return type.find((t) => t !== 'null') ?? 'string'\n }\n return type\n})\n\n// ---------------------------------------------------------------------------\n// Event handlers\n\n/**\n * Handles value changes during typing.\n */\nconst handleChange = (value: string): void => {\n if (!alwaysEmitChange && value === serializeValue(modelValue)) {\n return\n }\n\n // Use custom handler or emit update\n if (handleFieldChange) {\n handleFieldChange(value)\n } else {\n emit('update:modelValue', value)\n }\n}\n\n/**\n * Handles form submission (enter key or blur with emitOnBlur).\n */\nconst handleSubmit = (\n value: string,\n event: KeyboardEvent | FocusEvent,\n): void => {\n if (handleFieldSubmit) {\n handleFieldSubmit(value)\n } else {\n emit('submit', value, event)\n }\n}\n\n/**\n * Handles input blur event.\n */\nconst handleBlur = (value: string, event: FocusEvent): void => {\n isFocused.value = false\n\n if (emitOnBlur && modelValue) {\n handleSubmit(value, event)\n }\n\n emit('blur', value, event)\n}\n\n/**\n * Handles model value updates from select components.\n */\nconst handleSelectChange = (value: string): void =>\n emit('update:modelValue', value)\n\n// ---------------------------------------------------------------------------\n// CodeMirror setup\n\n/**\n * Build extensions array.\n * Note: Extensions are not reactive after initialization.\n */\nconst buildExtensions = (): Extension[] => {\n const extensionsList: Extension[] = [...extensions]\n\n if (colorPicker) {\n extensionsList.push(colorPickerExtension)\n }\n\n return extensionsList\n}\n\n/**\n * Reactive pill plugin for environment variable visualization.\n */\nconst contextFunctionDropdownItems = computed(() =>\n withFakeData\n ? CONTEXT_FUNCTION_NAMES.map((key) => ({\n key,\n description: getContextFunctionComment(key),\n }))\n : [],\n)\n\nconst pillPluginExtension = computed(() =>\n pillPlugin({\n environment,\n isContextFunctionName,\n isReadOnly: layout === 'modal',\n }),\n)\n\nconst isLineWrapping = ref(lineWrapping)\n\nwatch(\n () => lineWrapping,\n (val) => {\n isLineWrapping.value = val\n },\n)\n\nconst toggleLineWrapping = (): void => {\n isLineWrapping.value = !isLineWrapping.value\n}\n\nconst lineWrappingExtension = computed(() =>\n isLineWrapping.value ? [EditorView.lineWrapping] : [],\n)\n\n/**\n * Combined extensions for CodeMirror.\n */\nconst codeMirrorExtensions = computed((): Extension[] => [\n ...buildExtensions(),\n ...lineWrappingExtension.value,\n pillPluginExtension.value,\n backspaceCommand,\n])\n\nconst codeMirrorRef: Ref<HTMLDivElement | null> = ref(null)\n\n/** Converts the model value to a string for CodeMirror */\nconst serializeValue = (value: CodeInputModelValue): string => {\n if (typeof value === 'string') {\n return value\n }\n return JSON.stringify(value)\n}\n\nconst { codeMirror, setCodeMirrorContent } = useCodeMirror({\n content: toRef(() => serializeValue(modelValue)),\n onChange: (value) => {\n handleChange(value)\n updateDropdownVisibility()\n },\n onFocus: () => {\n isFocused.value = true\n },\n onBlur: handleBlur,\n codeMirrorRef,\n disableTabIndent: toRef(() => disableTabIndent),\n disableEnter: toRef(() => disableEnter),\n disableCloseBrackets: toRef(() => disableCloseBrackets),\n lineNumbers: toRef(() => lineNumbers),\n language: toRef(() => language),\n lint: toRef(() => lint),\n extensions: codeMirrorExtensions,\n placeholder: toRef(() => placeholder),\n})\n\n/**\n * Handle autofocus attribute.\n */\nwatch(codeMirror, () => {\n if (codeMirror.value && Object.hasOwn(attrs, 'autofocus')) {\n codeMirror.value.focus()\n }\n})\n\n// ---------------------------------------------------------------------------\n// Environment variable dropdown\n\nconst showDropdown = ref(false)\nconst dropdownQuery = ref('')\nconst dropdownPosition = ref({ left: 0, top: 0 })\nconst dropdownRef = ref<InstanceType<\n typeof EnvironmentVariableDropdown\n> | null>(null)\n\nconst { handleDropdownSelect, updateDropdownVisibility } = useDropdown({\n codeMirror,\n query: dropdownQuery,\n showDropdown,\n dropdownPosition,\n})\n\n/**\n * Determines if the environment variable dropdown should be visible.\n * Shows when environment is defined (for env vars) or withFakeData is true (for context functions)\n */\nconst displayVariablesDropdown = computed((): boolean => {\n return (\n showDropdown.value &&\n withVariables &&\n layout !== 'modal' &&\n (Boolean(environment) || withFakeData)\n )\n})\n\n// ---------------------------------------------------------------------------\n// Keyboard event handling\n\n/**\n * Handles keyboard navigation for dropdown and form submission.\n */\nconst handleKeyDown = (key: string, event: KeyboardEvent): void => {\n if (showDropdown.value) {\n if (key === 'down' || key === 'up') {\n event.preventDefault()\n dropdownRef.value?.handleArrowKey(key)\n } else if (key === 'enter') {\n event.preventDefault()\n dropdownRef.value?.handleSelect()\n }\n return\n }\n\n if (key === 'escape' && !disableTabIndent) {\n event.stopPropagation()\n }\n\n if (key === 'enter' && event.target instanceof HTMLDivElement) {\n handleSubmit(codeMirror.value?.state.doc.toString() ?? '', event)\n }\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n\ndefineExpose({\n /**\n * Focus the codemirror element\n *\n * @param cursorAtEnd boolean place the cursor at the end of the input\n */\n focus: (position?: 'start' | 'end' | number) => {\n if (!codeMirror.value) {\n return\n }\n codeMirror.value.focus()\n\n if (!isDefined(position)) {\n return\n }\n\n const anchor = (() => {\n if (position === 'start') {\n return 0\n }\n if (position === 'end') {\n return codeMirror.value.state.doc.length\n }\n return position\n })()\n\n // Move the cursor to the specified position\n codeMirror.value.dispatch({\n selection: { anchor },\n scrollIntoView: true,\n })\n },\n isFocused,\n handleChange,\n handleSubmit,\n handleBlur,\n booleanOptions,\n codeMirror,\n codeMirrorRef,\n modelValue,\n setCodeMirrorContent,\n cursorPosition: () => codeMirror.value?.state.selection.main.head,\n serializeValue,\n})\n</script>\n\n<template>\n <!-- Disabled mode: read-only text display -->\n <div\n v-if=\"disabled\"\n class=\"text-c-2 flex cursor-default items-center justify-center\"\n :class=\"{\n 'font-code pr-2 pl-1 text-base': layout === 'modal',\n 'px-2': layout !== 'modal',\n 'line-through': linethrough,\n }\"\n data-testid=\"code-input-disabled\">\n <span class=\"whitespace-nowrap\">{{ modelValue }}</span>\n </div>\n\n <!-- Enum mode: select dropdown with predefined values -->\n <DataTableInputSelect\n v-else-if=\"enumProp?.length\"\n :default=\"defaultProp\"\n :modelValue=\"modelValue\"\n :type=\"defaultType\"\n :value=\"enumProp\"\n @update:modelValue=\"handleSelectChange\" />\n\n <!-- Boolean mode: select dropdown with true/false (and optionally null) -->\n <DataTableInputSelect\n v-else-if=\"isBooleanMode\"\n :default=\"defaultProp\"\n :modelValue=\"modelValue\"\n :value=\"booleanOptions\"\n @update:modelValue=\"handleSelectChange\" />\n\n <!-- Examples mode: select dropdown with example values -->\n <DataTableInputSelect\n v-else-if=\"examples?.length\"\n :default=\"defaultProp\"\n :modelValue=\"modelValue\"\n :value=\"examples\"\n @update:modelValue=\"handleSelectChange\" />\n\n <!-- Editor mode: CodeMirror with environment variable support -->\n <div\n v-else\n :id=\"componentId\"\n v-bind=\"$attrs\"\n ref=\"codeMirrorRef\"\n class=\"group/input group-[.alert]:outline-orange group-[.error]:outline-red font-code peer relative w-full overflow-hidden text-xs leading-[1.44] whitespace-nowrap -outline-offset-1 has-[:focus-visible]:rounded-[4px] has-[:focus-visible]:outline\"\n :class=\"{\n 'line-wrapping has-[:focus-visible]:bg-b-1 has-[:focus-visible]:absolute has-[:focus-visible]:z-1':\n lineWrapping,\n 'flow-code-input--error': error,\n 'line-through': linethrough,\n }\"\n @keydown.down.stop=\"handleKeyDown('down', $event)\"\n @keydown.enter=\"handleKeyDown('enter', $event)\"\n @keydown.escape=\"handleKeyDown('escape', $event)\"\n @keydown.up.stop=\"handleKeyDown('up', $event)\">\n <!-- Wrap toggle button for multi-line editor (e.g. Request Body) -->\n <div\n v-if=\"lineNumbers\"\n class=\"absolute top-2 right-2 z-10 flex items-center opacity-0 transition-opacity duration-150 group-hover/input:opacity-100 group-has-focus-visible/input:opacity-100\">\n <ScalarIconButton\n class=\"bg-b-2 text-c-2 hover:text-c-1\"\n :class=\"{ '!bg-b-3 !text-c-1': isLineWrapping }\"\n :icon=\"ScalarIconArrowElbowDownLeft\"\n :aria-pressed=\"isLineWrapping\"\n :aria-label=\"isLineWrapping ? 'Disable line wrap' : 'Wrap lines'\"\n :label=\"isLineWrapping ? 'Disable line wrap' : 'Wrap lines'\"\n size=\"sm\"\n tooltip\n variant=\"ghost\"\n @click.stop=\"toggleLineWrapping\" />\n </div>\n\n <!-- Tab exit hint (shown when focused) -->\n <div\n v-if=\"!disableTabIndent\"\n class=\"z-context text-c-2 absolute right-1.5 bottom-1 hidden font-sans group-has-[:focus-visible]/input:block\"\n role=\"alert\">\n Press\n <kbd class=\"-mx-0.25 rounded border px-0.5 font-mono\">Esc</kbd> then\n <kbd class=\"-mx-0.25 rounded border px-0.5 font-mono\">Tab</kbd> to exit\n </div>\n </div>\n\n <!-- Warning slot (positioned absolutely) -->\n <div\n v-if=\"$slots.warning\"\n class=\"centered-y text-orange absolute right-7 text-xs\">\n <slot name=\"warning\" />\n </div>\n\n <!-- Icon slot (positioned absolutely) -->\n <div\n v-if=\"$slots.icon\"\n class=\"centered-y absolute right-0 flex h-full items-center p-1.5 group-has-[.cm-focused]:z-1\">\n <slot name=\"icon\" />\n </div>\n\n <!-- Required indicator -->\n <div\n v-if=\"required\"\n class=\"required centered-y text-xxs text-c-3 group-[.error]:text-red bg-b-1 pointer-events-none absolute right-0 mr-0.5 pt-px pr-2 opacity-100 shadow-[-8px_0_4px_var(--scalar-background-1)] transition-opacity duration-150 group-[.alert]:bg-transparent group-[.alert]:shadow-none group-[.error]:bg-transparent group-[.error]:shadow-none peer-has-[.cm-focused]:opacity-0\">\n Required\n </div>\n\n <!-- Environment variable autocomplete dropdown -->\n <EnvironmentVariableDropdown\n v-if=\"displayVariablesDropdown\"\n ref=\"dropdownRef\"\n :contextFunctionItems=\"contextFunctionDropdownItems\"\n :dropdownPosition=\"dropdownPosition\"\n :environment=\"environment\"\n :query=\"dropdownQuery\"\n @close=\"showDropdown = false\"\n @redirect=\"emit('navigate', { page: 'document', path: 'environment' })\"\n @select=\"handleDropdownSelect\" />\n</template>\n<style scoped>\n/*\n Deep styling for customizing Codemirror\n */\n:deep(.cm-editor) {\n height: 100%;\n outline: none;\n padding: 0;\n background: transparent;\n}\n:deep(.cm-placeholder) {\n color: var(--scalar-color-3);\n}\n:deep(.cm-content) {\n font-family: var(--scalar-font-code);\n font-size: var(--scalar-small);\n max-height: 20px;\n padding: 8px 0;\n}\n/* Tooltip helper */\n:deep(.cm-tooltip) {\n background: transparent !important;\n filter: brightness(var(--scalar-lifted-brightness));\n border-radius: var(--scalar-radius);\n box-shadow: var(--scalar-shadow-2);\n border: none !important;\n outline: none !important;\n overflow: hidden !important;\n}\n:deep(.cm-tooltip-autocomplete ul li) {\n padding: 3px 6px !important;\n}\n:deep(.cm-completionIcon-type:after) {\n color: var(--scalar-color-3) !important;\n}\n:deep(.cm-tooltip-autocomplete ul li[aria-selected]) {\n background: var(--scalar-background-2) !important;\n color: var(--scalar-color-1) !important;\n}\n:deep(.cm-tooltip-autocomplete ul) {\n padding: 6px !important;\n position: relative;\n}\n:deep(.cm-tooltip-autocomplete ul li:hover) {\n border-radius: 3px;\n color: var(--scalar-color-1) !important;\n background: var(--scalar-background-3) !important;\n}\n/* Disable active line highlighting */\n:deep(.cm-activeLine),\n:deep(.cm-activeLineGutter) {\n background-color: transparent;\n}\n/* Color selection matching */\n:deep(.cm-selectionMatch),\n:deep(.cm-matchingBracket) {\n border-radius: var(--scalar-radius);\n background: var(--scalar-background-4) !important;\n}\n/* Color Picker Swatches */\n:deep(.cm-css-color-picker-wrapper) {\n display: inline-flex;\n outline: 1px solid var(--scalar-background-3);\n border-radius: 3px;\n overflow: hidden;\n}\n/* Number gutter */\n:deep(.cm-gutters) {\n background-color: transparent;\n border-right: none;\n color: var(--scalar-color-3);\n font-size: var(--scalar-small);\n line-height: 22px;\n border-radius: 0 0 0 3px;\n}\n:deep(.cm-gutters:before) {\n content: '';\n position: absolute;\n top: 2px;\n left: 2px;\n width: calc(100% - 2px);\n height: calc(100% - 4px);\n border-radius: var(--scalar-radius) 0 0 var(--scalar-radius);\n background-color: var(--scalar-background-1);\n}\n:deep(.cm-gutterElement) {\n font-family: var(--scalar-font-code) !important;\n padding-left: 0px !important;\n padding-right: 6px !important;\n display: flex;\n align-items: center;\n justify-content: flex-end;\n position: relative;\n}\n:deep(.cm-lineNumbers .cm-gutterElement) {\n min-width: fit-content;\n}\n:deep(.cm-gutter + .cm-gutter :not(.cm-foldGutter) .cm-gutterElement) {\n padding-left: 0 !important;\n}\n:deep(.cm-scroller) {\n overflow: auto;\n}\n:deep(.cm-lineWrapping .cm-line) {\n word-break: break-all;\n}\n:deep(.cm-lineWrapping .cm-content) {\n white-space: pre-wrap;\n max-height: none;\n}\n.line-wrapping:focus-within :deep(.cm-content) {\n display: inline-table;\n min-height: fit-content;\n padding: 3px 6px;\n white-space: break-spaces;\n word-break: break-all;\n}\n</style>\n<style>\n.cm-pill {\n color: var(--scalar-color-1) !important;\n padding: 0px 9px;\n display: inline-block;\n border-radius: var(--scalar-radius-full);\n font-size: var(--scalar-small);\n}\n.light-mode .cm-pill {\n background: var(--scalar-background-3) !important;\n}\n.dark-mode .cm-pill {\n background: color-mix(in srgb, var(--tw-bg-base), transparent 90%) !important;\n}\n.cm-pill--context-fn {\n border: 1px dashed color-mix(in srgb, var(--scalar-color-3), transparent 35%);\n padding: 0px 8px;\n}\n.light-mode .cm-pill--context-fn {\n background: color-mix(\n in srgb,\n var(--scalar-background-3),\n transparent 40%\n ) !important;\n}\n.dark-mode .cm-pill--context-fn {\n background: color-mix(\n in srgb,\n var(--scalar-background-3),\n transparent 55%\n ) !important;\n}\n.cm-pill:first-of-type {\n margin-left: 0;\n}\n.cm-editor .cm-widgetBuffer {\n display: none;\n}\n.cm-foldPlaceholder:hover {\n color: var(--scalar-color-1);\n}\n.cm-foldGutter .cm-gutterElement {\n font-size: var(--scalar-heading-4);\n padding: 2px !important;\n}\n.cm-foldGutter .cm-gutterElement:first-of-type {\n display: none;\n}\n.cm-foldGutter .cm-gutterElement .cm-foldMarker {\n padding: 2px;\n padding-top: 2px;\n}\n.cm-foldGutter .cm-gutterElement:hover .cm-foldMarker {\n background: var(--scalar-background-2);\n border-radius: var(--scalar-radius);\n color: var(--scalar-color-1);\n}\n</style>\n"],"mappings":""}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import DataTableInputSelect_default from "../data-table/DataTableInputSelect.vue.js";
|
|
2
2
|
import EnvironmentVariablesDropdown_default from "../../features/environments/components/EnvironmentVariablesDropdown.vue.js";
|
|
3
3
|
import { backspaceCommand, pillPlugin } from "./code-variable-widget.js";
|
|
4
|
-
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createTextVNode, defineComponent, mergeProps, normalizeClass, openBlock, ref, renderSlot, toDisplayString, toRef, unref, useAttrs, watch, withKeys, withModifiers } from "vue";
|
|
4
|
+
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createTextVNode, createVNode, defineComponent, mergeProps, normalizeClass, openBlock, ref, renderSlot, toDisplayString, toRef, unref, useAttrs, watch, withKeys, withModifiers } from "vue";
|
|
5
|
+
import { ScalarIconArrowElbowDownLeft } from "@scalar/icons";
|
|
6
|
+
import { ScalarIconButton } from "@scalar/components/icon-button";
|
|
5
7
|
import { isDefined } from "@scalar/helpers/array/is-defined";
|
|
6
|
-
import { colorPicker, useCodeMirror, useDropdown } from "@scalar/use-codemirror";
|
|
8
|
+
import { EditorView, colorPicker, useCodeMirror, useDropdown } from "@scalar/use-codemirror";
|
|
7
9
|
import { CONTEXT_FUNCTION_NAMES, getContextFunctionComment, isContextFunctionName } from "@scalar/workspace-store/request-example";
|
|
8
10
|
import { nanoid } from "nanoid";
|
|
9
11
|
//#region src/v2/components/code-input/CodeInput.vue?vue&type=script&setup=true&lang.ts
|
|
@@ -11,18 +13,22 @@ var _hoisted_1 = { class: "whitespace-nowrap" };
|
|
|
11
13
|
var _hoisted_2 = ["id"];
|
|
12
14
|
var _hoisted_3 = {
|
|
13
15
|
key: 0,
|
|
16
|
+
class: "absolute top-2 right-2 z-10 flex items-center opacity-0 transition-opacity duration-150 group-hover/input:opacity-100 group-has-focus-visible/input:opacity-100"
|
|
17
|
+
};
|
|
18
|
+
var _hoisted_4 = {
|
|
19
|
+
key: 1,
|
|
14
20
|
class: "z-context text-c-2 absolute right-1.5 bottom-1 hidden font-sans group-has-[:focus-visible]/input:block",
|
|
15
21
|
role: "alert"
|
|
16
22
|
};
|
|
17
|
-
var
|
|
23
|
+
var _hoisted_5 = {
|
|
18
24
|
key: 5,
|
|
19
25
|
class: "centered-y text-orange absolute right-7 text-xs"
|
|
20
26
|
};
|
|
21
|
-
var
|
|
27
|
+
var _hoisted_6 = {
|
|
22
28
|
key: 6,
|
|
23
29
|
class: "centered-y absolute right-0 flex h-full items-center p-1.5 group-has-[.cm-focused]:z-1"
|
|
24
30
|
};
|
|
25
|
-
var
|
|
31
|
+
var _hoisted_7 = {
|
|
26
32
|
key: 7,
|
|
27
33
|
class: "required centered-y text-xxs text-c-3 group-[.error]:text-red bg-b-1 pointer-events-none absolute right-0 mr-0.5 pt-px pr-2 opacity-100 shadow-[-8px_0_4px_var(--scalar-background-1)] transition-opacity duration-150 group-[.alert]:bg-transparent group-[.alert]:shadow-none group-[.error]:bg-transparent group-[.error]:shadow-none peer-has-[.cm-focused]:opacity-0"
|
|
28
34
|
};
|
|
@@ -195,11 +201,20 @@ var CodeInput_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
|
|
|
195
201
|
isContextFunctionName,
|
|
196
202
|
isReadOnly: __props.layout === "modal"
|
|
197
203
|
}));
|
|
204
|
+
const isLineWrapping = ref(__props.lineWrapping);
|
|
205
|
+
watch(() => __props.lineWrapping, (val) => {
|
|
206
|
+
isLineWrapping.value = val;
|
|
207
|
+
});
|
|
208
|
+
const toggleLineWrapping = () => {
|
|
209
|
+
isLineWrapping.value = !isLineWrapping.value;
|
|
210
|
+
};
|
|
211
|
+
const lineWrappingExtension = computed(() => isLineWrapping.value ? [EditorView.lineWrapping] : []);
|
|
198
212
|
/**
|
|
199
213
|
* Combined extensions for CodeMirror.
|
|
200
214
|
*/
|
|
201
215
|
const codeMirrorExtensions = computed(() => [
|
|
202
216
|
...buildExtensions(),
|
|
217
|
+
...lineWrappingExtension.value,
|
|
203
218
|
pillPluginExtension.value,
|
|
204
219
|
backspaceCommand
|
|
205
220
|
]);
|
|
@@ -363,16 +378,32 @@ var CodeInput_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ define
|
|
|
363
378
|
_cache[2] || (_cache[2] = withKeys(($event) => handleKeyDown("escape", $event), ["escape"])),
|
|
364
379
|
_cache[3] || (_cache[3] = withKeys(withModifiers(($event) => handleKeyDown("up", $event), ["stop"]), ["up"]))
|
|
365
380
|
]
|
|
366
|
-
}), [
|
|
381
|
+
}), [__props.lineNumbers ? (openBlock(), createElementBlock("div", _hoisted_3, [createVNode(unref(ScalarIconButton), {
|
|
382
|
+
class: normalizeClass(["bg-b-2 text-c-2 hover:text-c-1", { "!bg-b-3 !text-c-1": isLineWrapping.value }]),
|
|
383
|
+
icon: unref(ScalarIconArrowElbowDownLeft),
|
|
384
|
+
"aria-pressed": isLineWrapping.value,
|
|
385
|
+
"aria-label": isLineWrapping.value ? "Disable line wrap" : "Wrap lines",
|
|
386
|
+
label: isLineWrapping.value ? "Disable line wrap" : "Wrap lines",
|
|
387
|
+
size: "sm",
|
|
388
|
+
tooltip: "",
|
|
389
|
+
variant: "ghost",
|
|
390
|
+
onClick: withModifiers(toggleLineWrapping, ["stop"])
|
|
391
|
+
}, null, 8, [
|
|
392
|
+
"class",
|
|
393
|
+
"icon",
|
|
394
|
+
"aria-pressed",
|
|
395
|
+
"aria-label",
|
|
396
|
+
"label"
|
|
397
|
+
])])) : createCommentVNode("", true), !__props.disableTabIndent ? (openBlock(), createElementBlock("div", _hoisted_4, [..._cache[6] || (_cache[6] = [
|
|
367
398
|
createTextVNode(" Press ", -1),
|
|
368
399
|
createElementVNode("kbd", { class: "-mx-0.25 rounded border px-0.5 font-mono" }, "Esc", -1),
|
|
369
400
|
createTextVNode(" then ", -1),
|
|
370
401
|
createElementVNode("kbd", { class: "-mx-0.25 rounded border px-0.5 font-mono" }, "Tab", -1),
|
|
371
402
|
createTextVNode(" to exit ", -1)
|
|
372
403
|
])])) : createCommentVNode("", true)], 16, _hoisted_2)),
|
|
373
|
-
_ctx.$slots.warning ? (openBlock(), createElementBlock("div",
|
|
374
|
-
_ctx.$slots.icon ? (openBlock(), createElementBlock("div",
|
|
375
|
-
__props.required ? (openBlock(), createElementBlock("div",
|
|
404
|
+
_ctx.$slots.warning ? (openBlock(), createElementBlock("div", _hoisted_5, [renderSlot(_ctx.$slots, "warning", {}, void 0, true)])) : createCommentVNode("", true),
|
|
405
|
+
_ctx.$slots.icon ? (openBlock(), createElementBlock("div", _hoisted_6, [renderSlot(_ctx.$slots, "icon", {}, void 0, true)])) : createCommentVNode("", true),
|
|
406
|
+
__props.required ? (openBlock(), createElementBlock("div", _hoisted_7, " Required ")) : createCommentVNode("", true),
|
|
376
407
|
displayVariablesDropdown.value ? (openBlock(), createBlock(EnvironmentVariablesDropdown_default, {
|
|
377
408
|
key: 8,
|
|
378
409
|
ref_key: "dropdownRef",
|