@scalar/blocks 0.1.16 → 0.1.17
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 +17 -0
- package/dist/code-example/components/CodeExample.vue.d.ts +1 -1
- package/dist/code-example/components/CodeExample.vue.js +1 -1
- package/dist/code-example/components/CodeExample.vue.js.map +1 -1
- package/dist/code-example/components/CodeExample.vue.script.js.map +1 -1
- package/dist/code-example/components/ExamplePicker.vue.d.ts +1 -1
- package/dist/code-example/components/ExamplePicker.vue.js.map +1 -1
- package/dist/code-example/components/ExamplePicker.vue.script.js.map +1 -1
- package/dist/code-example/helpers/generate-client-options.js.map +1 -1
- package/dist/code-example/helpers/generate-code-snippet.d.ts +1 -1
- package/dist/code-example/helpers/generate-code-snippet.js.map +1 -1
- package/dist/code-example/helpers/get-custom-code-samples.d.ts +1 -1
- package/dist/code-example/helpers/get-custom-code-samples.js.map +1 -1
- package/dist/code-example/helpers/get-snippet.js.map +1 -1
- package/dist/code-example/helpers/operation-to-har/operation-to-har.d.ts +1 -1
- package/dist/code-example/helpers/operation-to-har/operation-to-har.js.map +1 -1
- package/dist/code-example/helpers/operation-to-har/process-body.d.ts +1 -1
- package/dist/code-example/helpers/operation-to-har/process-body.d.ts.map +1 -1
- package/dist/code-example/helpers/operation-to-har/process-body.js +79 -73
- package/dist/code-example/helpers/operation-to-har/process-body.js.map +1 -1
- package/dist/code-example/helpers/operation-to-har/process-parameters.d.ts +1 -1
- package/dist/code-example/helpers/operation-to-har/process-parameters.d.ts.map +1 -1
- package/dist/code-example/helpers/operation-to-har/process-parameters.js +50 -48
- package/dist/code-example/helpers/operation-to-har/process-parameters.js.map +1 -1
- package/dist/code-example/helpers/operation-to-har/process-server-url.d.ts +1 -1
- package/dist/code-example/helpers/operation-to-har/process-server-url.js.map +1 -1
- package/dist/code-example/mount.d.ts +1 -1
- package/dist/code-example/mount.js.map +1 -1
- package/dist/constants.js +1 -1
- package/dist/style.css +18 -2
- package/dist/vue-styles.css +1 -1
- package/package.json +7 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# @scalar/blocks
|
|
2
2
|
|
|
3
|
+
## 0.1.17
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#9851](https://github.com/scalar/scalar/pull/9851): Serialize OpenAPI 3.2 `querystring` parameters when generating code snippets, so their values land in the request query string instead of being silently dropped.
|
|
8
|
+
- [#10140](https://github.com/scalar/scalar/pull/10140): Replace redundant type assertions with compiler-checked annotations, typed accumulators, and existing guards across helpers, API conversion, request handling, and schema rendering.
|
|
9
|
+
|
|
10
|
+
Narrow DOM elements and caught errors before accessing their properties. Correct header lookup to include missing values and handle them during PowerShell snippet generation.
|
|
11
|
+
|
|
12
|
+
Validate release-note provider responses, represent unresolved references and absent groups in helper return types, and require narrowing merged object values. Preserve AsyncAPI broker credentials separately from HTTP authentication schemes.
|
|
13
|
+
|
|
14
|
+
- [#10142](https://github.com/scalar/scalar/pull/10142): Send multipart array properties as separate parts with the same field name, applying encoding to each item. Preserve JSON item content types, uploaded files, and array values after form edits, and generate matching code snippets.
|
|
15
|
+
|
|
16
|
+
Send JSON form fields without an upload filename and preserve fields and files in request history.
|
|
17
|
+
|
|
18
|
+
Rename the RestSharp snippet's internal `getMethod` helper so it no longer clashes with the `getMethod` that Nitro bundles into server builds (the new multipart imports shifted chunking and surfaced the collision).
|
|
19
|
+
|
|
3
20
|
## 0.1.16
|
|
4
21
|
|
|
5
22
|
## 0.1.15
|
|
@@ -2,7 +2,7 @@ import type { HttpMethod as HttpMethodType } from '@scalar/helpers/http/http-met
|
|
|
2
2
|
import { type WorkspaceEventBus } from '@scalar/workspace-store/events';
|
|
3
3
|
import type { SecuritySchemeObjectSecret } from '@scalar/workspace-store/request-example';
|
|
4
4
|
import type { XScalarCookie } from '@scalar/workspace-store/schemas/extensions/general/x-scalar-cookies';
|
|
5
|
-
import type { OperationObject, ServerObject } from '@scalar/workspace-store/schemas/v3.
|
|
5
|
+
import type { OperationObject, ServerObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document';
|
|
6
6
|
import type { ClientOptionGroup } from '../types';
|
|
7
7
|
export type CodeExampleProps = {
|
|
8
8
|
/**
|
|
@@ -2,7 +2,7 @@ import e from "./CodeExample.vue.script.js";
|
|
|
2
2
|
/* empty css */
|
|
3
3
|
import t from "../../_virtual/_plugin-vue_export-helper.js";
|
|
4
4
|
//#region src/code-example/components/CodeExample.vue
|
|
5
|
-
var n = /*#__PURE__*/ t(e, [["__scopeId", "data-v-
|
|
5
|
+
var n = /*#__PURE__*/ t(e, [["__scopeId", "data-v-82b2d155"]]);
|
|
6
6
|
//#endregion
|
|
7
7
|
export { n as default };
|
|
8
8
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CodeExample.vue.js","names":[],"sources":["../../../src/code-example/components/CodeExample.vue"],"sourcesContent":["<script lang=\"ts\">\nexport type CodeExampleProps = {\n /**\n * Integration type: determines if the code sample is displayed in a client environment\n * or in an API reference environment.\n */\n integration?: 'client' | 'reference'\n /**\n * List of all http clients formatted into option groups for the client selector\n */\n clientOptions: ClientOptionGroup[]\n /**\n * Pre-selected client, this will determine which client is initially selected in the dropdown.\n * Either a built-in client id (e.g. `js/fetch`) or a custom sample id (e.g. `custom/python`).\n *\n * Typed as a plain string: unioning the (large) client-id union with the `custom/...`\n * ids overflows TypeScript's union-complexity limit inside this component's `defineProps`.\n *\n * @defaults to a custom sample if one is available, otherwise shell/curl\n */\n selectedClient?: string\n /**\n * Which server from the spec to use for the code example\n */\n selectedServer?: ServerObject | null\n /**\n * The selected content type from the requestBody.content, this will determine which examples are available\n * as well as the content type of the code example\n *\n * @defaults to the first content type if not provided\n */\n selectedContentType?: string\n /**\n * Example name to use for resolving example values for parameters AND requestBody.\n *\n * This is the document-wide selection: it is honored only when this operation defines an example\n * with the same key, so picking an example on one operation syncs the rest without blanking out\n * operations that do not share that key.\n *\n * @example \"limited\"\n * ```ts\n * parameters: {\n * name: 'foobar',\n * in: 'query',\n * examples: {\n * limited: {\n * dataValue: 10,\n * }\n * }\n * },\n * body: {\n * content: {\n * 'application/json': {\n * examples: {\n * limited: {\n * dataValue: { foo: 'bar' },\n * }\n * }\n * }\n * }\n * }\n *\n * ```\n */\n selectedExample?: string\n /**\n * Event bus\n */\n eventBus: WorkspaceEventBus\n /**\n * The security schemes which are applicable to this operation\n */\n securitySchemes: SecuritySchemeObjectSecret[]\n /**\n * HTTP method of the operation\n */\n method: HttpMethodType\n /**\n * Path of the operation\n */\n path: string\n /**\n * De-referenced OpenAPI Operation object\n */\n operation: OperationObject\n /**\n * If true and there's no example, we will display a small card with the method and path only\n */\n fallback?: boolean\n /**\n * A method to generate the label of the block, should return an html string\n */\n generateLabel?: () => string\n /**\n * If true, render this as a webhook request example\n */\n isWebhook?: boolean\n /**\n * Workspace + document cookies\n */\n globalCookies?: XScalarCookie[]\n /**\n * When the request body schema uses oneOf/anyOf, use these selected variants\n * for the example snippet (e.g. from the schema dropdowns in the API reference).\n */\n requestBodyCompositionSelection?: Record<string, number>\n}\n\n/**\n * Request Example\n *\n * The core component for rendering a request example block,\n * this component does not have much of its own state but operates on props and custom events\n *\n * @event workspace:update:selected-client - Emitted when the selected client changes\n * @event workspace:update:selected-example - Emitted when the selected example changes, so other operations can sync\n */\nexport default {}\n</script>\n\n<script setup lang=\"ts\">\nimport { ScalarButton } from '@scalar/components/button'\nimport {\n ScalarCard,\n ScalarCardFooter,\n ScalarCardHeader,\n ScalarCardSection,\n} from '@scalar/components/card'\nimport { ScalarCodeBlock } from '@scalar/components/code-block'\nimport { ScalarCombobox } from '@scalar/components/combobox'\nimport { ScalarVirtualText } from '@scalar/components/virtual-text'\nimport { freezeElement } from '@scalar/helpers/dom/freeze-element'\nimport type { HttpMethod as HttpMethodType } from '@scalar/helpers/http/http-methods'\nimport { ScalarIconCaretDown } from '@scalar/icons'\nimport { type WorkspaceEventBus } from '@scalar/workspace-store/events'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport type { SecuritySchemeObjectSecret } from '@scalar/workspace-store/request-example'\nimport type { XScalarCookie } from '@scalar/workspace-store/schemas/extensions/general/x-scalar-cookies'\nimport type {\n OperationObject,\n ServerObject,\n} from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\nimport {\n computed,\n onBeforeMount,\n ref,\n useId,\n watch,\n watchEffect,\n type ComponentPublicInstance,\n} from 'vue'\n\nimport { filterClientsByQuery } from '../helpers/filter-clients-by-query'\nimport { findClient } from '../helpers/find-client'\nimport { generateCodeSnippet } from '../helpers/generate-code-snippet'\nimport { getClients } from '../helpers/get-clients'\nimport { getCustomCodeSamples } from '../helpers/get-custom-code-samples'\nimport { getSecrets } from '../helpers/get-secrets'\nimport { operationToHar } from '../helpers/operation-to-har/operation-to-har'\nimport type {\n ClientOption,\n ClientOptionGroup,\n CustomClientOption,\n} from '../types'\nimport ExamplePicker from './ExamplePicker.vue'\nimport HttpMethod from './HttpMethod.vue'\n\nconst {\n integration,\n clientOptions,\n selectedClient,\n selectedServer = null,\n selectedContentType,\n selectedExample,\n securitySchemes = [],\n method,\n eventBus,\n path,\n operation,\n isWebhook,\n generateLabel,\n globalCookies,\n requestBodyCompositionSelection,\n} = defineProps<CodeExampleProps>()\n\nconst emit = defineEmits<{\n /**\n * Emitted whenever the example key actually shown for this operation changes.\n *\n * This is the resolved local key (not the raw document-wide selection), so layouts that render\n * the test-request button outside this component can open the client with the same example the\n * snippet displays.\n */\n (e: 'update:exampleKey', value: string): void\n}>()\n\ndefineSlots<{\n header: () => unknown\n footer: ({ exampleName }: { exampleName: string }) => unknown\n}>()\n\n/** Grab the examples for the given content type */\nconst requestBodyExamples = computed(() => {\n const content = getResolvedRef(operation.requestBody)?.content ?? {}\n const contentType = selectedContentType || Object.keys(content)[0]\n if (!contentType) return {}\n\n const examples = content[contentType]?.examples ?? {}\n\n return examples\n})\n\n/**\n * The example key actually shown for this operation.\n *\n * `selectedExample` is the document-wide selection that syncs across operations. We honor it only\n * when this operation actually defines that key, otherwise we keep the local example: a selection\n * on one operation should never blank out an operation that does not share the same example.\n */\nconst localExampleKey = ref('')\n\n/** Resolve the key to display, preferring the document-wide selection when this operation has it */\nconst resolveExampleKey = (preferred: string | undefined): string => {\n const keys = Object.keys(requestBodyExamples.value)\n if (preferred && keys.includes(preferred)) {\n return preferred\n }\n // Keep the current local example when it is still valid, otherwise fall back to the first one\n if (localExampleKey.value && keys.includes(localExampleKey.value)) {\n return localExampleKey.value\n }\n return keys[0] ?? ''\n}\n\n// Set the initial example from the document-wide selection, falling back to the first example\nonBeforeMount(() => {\n localExampleKey.value = resolveExampleKey(selectedExample)\n})\n\n// Follow the document-wide selection when it changes and this operation has that example\nwatch(\n () => selectedExample,\n (preferred) => {\n localExampleKey.value = resolveExampleKey(preferred)\n },\n)\n\n/** Reset the selected example key if the content type changes and the new content type doesn't have the previously selected example */\nwatch(\n () => selectedContentType,\n () => {\n if (\n !Object.keys(requestBodyExamples.value).includes(localExampleKey.value)\n ) {\n // Re-resolve so the new content type still follows the document-wide selection when it has\n // that key, instead of always snapping back to the first example\n localExampleKey.value = resolveExampleKey(selectedExample)\n }\n },\n)\n\n// Keep the parent informed of the resolved key so a test-request button rendered outside this\n// component (e.g. the classic layout header) opens the client with the example the snippet shows\nwatchEffect(() => {\n emit('update:exampleKey', localExampleKey.value)\n})\n\n/** Select an example locally and sync the choice across the document */\nconst selectExample = (key: string) => {\n localExampleKey.value = key\n eventBus.emit('workspace:update:selected-example', key)\n}\n\n/** Grab any custom code samples from the operation */\nconst customCodeSamples = computed(() => getCustomCodeSamples(operation))\n\n/** Merge custom code samples with the client options */\nconst clients = computed(() =>\n getClients(\n customCodeSamples.value.samples,\n clientOptions,\n customCodeSamples.value.label,\n ),\n)\n\n/** Total number of available clients across all option groups */\nconst clientCount = computed(() =>\n clients.value.reduce((total, group) => total + group.options.length, 0),\n)\n\n/** The locally selected client which would include code samples from this operation only */\nconst localSelectedClient = ref<ClientOption | CustomClientOption | undefined>(\n findClient(clients.value, selectedClient),\n)\n\n/**\n * Re-resolve the local client whenever the global selection or the available\n * clients change. Watching `clients` matters when navigating between operations:\n * the stored id stays the same, but the matching option (e.g. a custom sample)\n * differs per operation, so without this the snippet could go stale.\n */\nwatch([() => selectedClient, clients], ([newClient]) => {\n const client = findClient(clients.value, newClient)\n if (client) {\n localSelectedClient.value = client\n }\n})\n\n/** Generate HAR data for webhook requests */\nconst webhookHar = computed(() => {\n if (!isWebhook) return null\n\n try {\n return operationToHar({\n operation,\n method,\n path,\n example: localExampleKey.value,\n requestBodyCompositionSelection,\n // Only required parameters are shown in code examples; optional parameters\n // are omitted unless explicitly enabled via `x-disabled: false`.\n defaultDisabledParameters: true,\n })\n } catch (error) {\n console.error('[webhookHar]', error)\n return null\n }\n})\n\n/** Generate the code snippet for the selected example */\nconst generatedCode = computed<string>(() => {\n if (isWebhook) {\n return webhookHar.value?.postData?.text ?? ''\n }\n\n return generateCodeSnippet({\n // Only required parameters are shown in code examples; optional parameters\n // are omitted unless explicitly enabled via `x-disabled: false`.\n defaultDisabledParameters: true,\n includeDefaultHeaders: integration === 'client',\n clientId: localSelectedClient.value?.id,\n customCodeSamples: customCodeSamples.value.samples,\n operation,\n method,\n path,\n contentType: selectedContentType,\n server: selectedServer,\n securitySchemes,\n example: localExampleKey.value,\n globalCookies,\n requestBodyCompositionSelection,\n })\n})\n\n/** The language for the code block, used for syntax highlighting */\nconst codeBlockLanguage = computed(() => {\n if (isWebhook) {\n return webhookLanguage.value\n }\n\n return localSelectedClient.value?.lang\n})\n\n/** Determine the language for webhook content based on MIME type */\nconst webhookLanguage = computed<string>(() => {\n if (!webhookHar.value?.postData) return 'json'\n\n const contentType = webhookHar.value.postData.mimeType\n if (contentType?.includes('json')) return 'json'\n if (contentType?.includes('xml')) return 'xml'\n if (contentType?.includes('yaml') || contentType?.includes('yml'))\n return 'yaml'\n if (contentType?.includes('text/plain')) return 'text'\n\n return 'json'\n})\n\n/** Block secrets from being shown in the code block */\nconst secretCredentials = computed(() => getSecrets(securitySchemes))\n\n/** Grab the ref to freeze the ui as the clients change so there's no jump as the size of the dom changes */\nconst elem = ref<ComponentPublicInstance | null>(null)\n\n/** Set custom example, or update the selected HTTP client globally */\nconst selectClient = (option: ClientOption) => {\n // We need to freeze the ui to prevent scrolling as the clients change\n if (elem.value) {\n const unfreeze = freezeElement(elem.value.$el)\n setTimeout(() => {\n unfreeze()\n }, 300)\n }\n // Update to the local example\n localSelectedClient.value = option\n\n // Sync the selection globally so other operations follow along. Custom samples\n // sync too (keyed by language), so picking e.g. the Python SDK example here\n // shows the Python example on every operation that ships one.\n if (option) {\n eventBus.emit('workspace:update:selected-client', option.id)\n }\n}\n\n// Virtualize the code block if it's too large\n// This prevents the entire app from freezing up if there's a massive example\n// We set a lower threshold here as code examples can get quite large\nconst VIRTUALIZATION_THRESHOLD = 20_000\n\nconst shouldVirtualize = computed(\n () => (generatedCode.value.length ?? 0) > VIRTUALIZATION_THRESHOLD,\n)\n\nconst id = useId()\n</script>\n<template>\n <ScalarCard\n v-if=\"generatedCode\"\n ref=\"elem\"\n class=\"request-card dark-mode\">\n <!-- Header -->\n <ScalarCardHeader class=\"pr-2.5\">\n <span class=\"sr-only\">Request Example for</span>\n <HttpMethod\n as=\"span\"\n class=\"request-method\"\n :method=\"method\" />\n <span\n v-if=\"generateLabel\"\n v-html=\"generateLabel()\" />\n <slot name=\"header\" />\n <!-- Client picker -->\n <template\n v-if=\"!isWebhook && clientCount\"\n #actions>\n <!-- Multiple clients: render a dropdown to switch between them -->\n <ScalarCombobox\n v-if=\"clientCount > 1\"\n class=\"max-h-80\"\n :filterFn=\"filterClientsByQuery\"\n :modelValue=\"localSelectedClient\"\n :options=\"clients\"\n placement=\"bottom-end\"\n teleport\n @update:modelValue=\"selectClient($event as ClientOption)\">\n <ScalarButton\n class=\"text-c-2 hover:text-c-1 flex h-full w-fit gap-1.5 px-0.5 py-0 text-base font-normal\"\n data-testid=\"client-picker\"\n variant=\"ghost\">\n {{ localSelectedClient?.title }}\n <ScalarIconCaretDown\n class=\"ui-open:rotate-180 mt-px size-3 transition-transform duration-100\"\n weight=\"bold\" />\n </ScalarButton>\n </ScalarCombobox>\n <!-- Single client: just show its label, no need for a dropdown -->\n <span\n v-else\n class=\"text-c-2 flex h-full w-fit items-center px-0.5 py-0 text-base font-normal\"\n data-testid=\"client-picker\">\n {{ localSelectedClient?.title }}\n </span>\n </template>\n </ScalarCardHeader>\n\n <!-- Code snippet -->\n <ScalarCardSection class=\"request-editor-section custom-scroll p-0\">\n <div\n :id=\"`${id}-example`\"\n class=\"code-snippet\">\n <ScalarCodeBlock\n v-if=\"!shouldVirtualize\"\n class=\"bg-b-2 h-full\"\n :content=\"generatedCode\"\n :hideCredentials=\"secretCredentials\"\n :lang=\"codeBlockLanguage\"\n lineNumbers />\n <ScalarVirtualText\n v-else\n containerClass=\"custom-scroll scalar-code-block border rounded-b flex flex-1 max-h-screen\"\n contentClass=\"language-plaintext whitespace-pre font-code text-base p-2\"\n :lineHeight=\"20\"\n :text=\"generatedCode\" />\n </div>\n </ScalarCardSection>\n\n <!-- Footer -->\n <ScalarCardFooter\n v-if=\"Object.keys(requestBodyExamples).length > 1 || $slots.footer\"\n class=\"request-card-footer bg-b-3\">\n <!-- Example picker -->\n <div\n v-if=\"Object.keys(requestBodyExamples).length > 1\"\n class=\"request-card-footer-addon\">\n <template v-if=\"Object.keys(requestBodyExamples).length\">\n <ExamplePicker\n :examples=\"requestBodyExamples\"\n :modelValue=\"localExampleKey\"\n @update:modelValue=\"selectExample\" />\n </template>\n </div>\n\n <!-- Footer -->\n <slot\n :exampleName=\"localExampleKey\"\n name=\"footer\" />\n </ScalarCardFooter>\n </ScalarCard>\n\n <!-- Fallback card with just method and path in the case of no examples -->\n <ScalarCard\n v-else-if=\"fallback\"\n class=\"request-card dark-mode\">\n <ScalarCardSection class=\"request-card-simple\">\n <div class=\"request-header\">\n <HttpMethod\n as=\"span\"\n class=\"request-method\"\n :method=\"method\" />\n <slot name=\"header\" />\n </div>\n <slot\n :exampleName=\"localExampleKey\"\n name=\"footer\" />\n </ScalarCardSection>\n </ScalarCard>\n</template>\n<style scoped>\n.request-card {\n color: var(--scalar-color-1);\n font-size: var(--scalar-font-size-3);\n}\n.request-method {\n font-family: var(--scalar-font-code);\n text-transform: uppercase;\n margin-right: 6px;\n}\n.request-card-footer {\n display: flex;\n justify-content: flex-end;\n padding: 6px;\n flex-shrink: 0;\n position: relative;\n}\n.request-card-footer-addon {\n display: flex;\n align-items: center;\n\n flex: 1;\n min-width: 0;\n}\n.request-editor-section {\n display: flex;\n flex: 1;\n}\n.request-card-simple {\n display: flex;\n align-items: center;\n justify-content: space-between;\n\n padding: 8px 8px 8px 12px;\n\n font-size: var(--scalar-small);\n}\n.code-snippet {\n display: flex;\n flex-direction: column;\n width: 100%;\n}\n</style>\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"CodeExample.vue.js","names":[],"sources":["../../../src/code-example/components/CodeExample.vue"],"sourcesContent":["<script lang=\"ts\">\nexport type CodeExampleProps = {\n /**\n * Integration type: determines if the code sample is displayed in a client environment\n * or in an API reference environment.\n */\n integration?: 'client' | 'reference'\n /**\n * List of all http clients formatted into option groups for the client selector\n */\n clientOptions: ClientOptionGroup[]\n /**\n * Pre-selected client, this will determine which client is initially selected in the dropdown.\n * Either a built-in client id (e.g. `js/fetch`) or a custom sample id (e.g. `custom/python`).\n *\n * Typed as a plain string: unioning the (large) client-id union with the `custom/...`\n * ids overflows TypeScript's union-complexity limit inside this component's `defineProps`.\n *\n * @defaults to a custom sample if one is available, otherwise shell/curl\n */\n selectedClient?: string\n /**\n * Which server from the spec to use for the code example\n */\n selectedServer?: ServerObject | null\n /**\n * The selected content type from the requestBody.content, this will determine which examples are available\n * as well as the content type of the code example\n *\n * @defaults to the first content type if not provided\n */\n selectedContentType?: string\n /**\n * Example name to use for resolving example values for parameters AND requestBody.\n *\n * This is the document-wide selection: it is honored only when this operation defines an example\n * with the same key, so picking an example on one operation syncs the rest without blanking out\n * operations that do not share that key.\n *\n * @example \"limited\"\n * ```ts\n * parameters: {\n * name: 'foobar',\n * in: 'query',\n * examples: {\n * limited: {\n * dataValue: 10,\n * }\n * }\n * },\n * body: {\n * content: {\n * 'application/json': {\n * examples: {\n * limited: {\n * dataValue: { foo: 'bar' },\n * }\n * }\n * }\n * }\n * }\n *\n * ```\n */\n selectedExample?: string\n /**\n * Event bus\n */\n eventBus: WorkspaceEventBus\n /**\n * The security schemes which are applicable to this operation\n */\n securitySchemes: SecuritySchemeObjectSecret[]\n /**\n * HTTP method of the operation\n */\n method: HttpMethodType\n /**\n * Path of the operation\n */\n path: string\n /**\n * De-referenced OpenAPI Operation object\n */\n operation: OperationObject\n /**\n * If true and there's no example, we will display a small card with the method and path only\n */\n fallback?: boolean\n /**\n * A method to generate the label of the block, should return an html string\n */\n generateLabel?: () => string\n /**\n * If true, render this as a webhook request example\n */\n isWebhook?: boolean\n /**\n * Workspace + document cookies\n */\n globalCookies?: XScalarCookie[]\n /**\n * When the request body schema uses oneOf/anyOf, use these selected variants\n * for the example snippet (e.g. from the schema dropdowns in the API reference).\n */\n requestBodyCompositionSelection?: Record<string, number>\n}\n\n/**\n * Request Example\n *\n * The core component for rendering a request example block,\n * this component does not have much of its own state but operates on props and custom events\n *\n * @event workspace:update:selected-client - Emitted when the selected client changes\n * @event workspace:update:selected-example - Emitted when the selected example changes, so other operations can sync\n */\nexport default {}\n</script>\n\n<script setup lang=\"ts\">\nimport { ScalarButton } from '@scalar/components/button'\nimport {\n ScalarCard,\n ScalarCardFooter,\n ScalarCardHeader,\n ScalarCardSection,\n} from '@scalar/components/card'\nimport { ScalarCodeBlock } from '@scalar/components/code-block'\nimport { ScalarCombobox } from '@scalar/components/combobox'\nimport { ScalarVirtualText } from '@scalar/components/virtual-text'\nimport { freezeElement } from '@scalar/helpers/dom/freeze-element'\nimport type { HttpMethod as HttpMethodType } from '@scalar/helpers/http/http-methods'\nimport { ScalarIconCaretDown } from '@scalar/icons'\nimport { type WorkspaceEventBus } from '@scalar/workspace-store/events'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport type { SecuritySchemeObjectSecret } from '@scalar/workspace-store/request-example'\nimport type { XScalarCookie } from '@scalar/workspace-store/schemas/extensions/general/x-scalar-cookies'\nimport type {\n OperationObject,\n ServerObject,\n} from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport {\n computed,\n onBeforeMount,\n ref,\n useId,\n watch,\n watchEffect,\n type ComponentPublicInstance,\n} from 'vue'\n\nimport { filterClientsByQuery } from '../helpers/filter-clients-by-query'\nimport { findClient } from '../helpers/find-client'\nimport { generateCodeSnippet } from '../helpers/generate-code-snippet'\nimport { getClients } from '../helpers/get-clients'\nimport { getCustomCodeSamples } from '../helpers/get-custom-code-samples'\nimport { getSecrets } from '../helpers/get-secrets'\nimport { operationToHar } from '../helpers/operation-to-har/operation-to-har'\nimport type {\n ClientOption,\n ClientOptionGroup,\n CustomClientOption,\n} from '../types'\nimport ExamplePicker from './ExamplePicker.vue'\nimport HttpMethod from './HttpMethod.vue'\n\nconst {\n integration,\n clientOptions,\n selectedClient,\n selectedServer = null,\n selectedContentType,\n selectedExample,\n securitySchemes = [],\n method,\n eventBus,\n path,\n operation,\n isWebhook,\n generateLabel,\n globalCookies,\n requestBodyCompositionSelection,\n} = defineProps<CodeExampleProps>()\n\nconst emit = defineEmits<{\n /**\n * Emitted whenever the example key actually shown for this operation changes.\n *\n * This is the resolved local key (not the raw document-wide selection), so layouts that render\n * the test-request button outside this component can open the client with the same example the\n * snippet displays.\n */\n (e: 'update:exampleKey', value: string): void\n}>()\n\ndefineSlots<{\n header: () => unknown\n footer: ({ exampleName }: { exampleName: string }) => unknown\n}>()\n\n/** Grab the examples for the given content type */\nconst requestBodyExamples = computed(() => {\n const content = getResolvedRef(operation.requestBody)?.content ?? {}\n const contentType = selectedContentType || Object.keys(content)[0]\n if (!contentType) return {}\n\n const examples = content[contentType]?.examples ?? {}\n\n return examples\n})\n\n/**\n * The example key actually shown for this operation.\n *\n * `selectedExample` is the document-wide selection that syncs across operations. We honor it only\n * when this operation actually defines that key, otherwise we keep the local example: a selection\n * on one operation should never blank out an operation that does not share the same example.\n */\nconst localExampleKey = ref('')\n\n/** Resolve the key to display, preferring the document-wide selection when this operation has it */\nconst resolveExampleKey = (preferred: string | undefined): string => {\n const keys = Object.keys(requestBodyExamples.value)\n if (preferred && keys.includes(preferred)) {\n return preferred\n }\n // Keep the current local example when it is still valid, otherwise fall back to the first one\n if (localExampleKey.value && keys.includes(localExampleKey.value)) {\n return localExampleKey.value\n }\n return keys[0] ?? ''\n}\n\n// Set the initial example from the document-wide selection, falling back to the first example\nonBeforeMount(() => {\n localExampleKey.value = resolveExampleKey(selectedExample)\n})\n\n// Follow the document-wide selection when it changes and this operation has that example\nwatch(\n () => selectedExample,\n (preferred) => {\n localExampleKey.value = resolveExampleKey(preferred)\n },\n)\n\n/** Reset the selected example key if the content type changes and the new content type doesn't have the previously selected example */\nwatch(\n () => selectedContentType,\n () => {\n if (\n !Object.keys(requestBodyExamples.value).includes(localExampleKey.value)\n ) {\n // Re-resolve so the new content type still follows the document-wide selection when it has\n // that key, instead of always snapping back to the first example\n localExampleKey.value = resolveExampleKey(selectedExample)\n }\n },\n)\n\n// Keep the parent informed of the resolved key so a test-request button rendered outside this\n// component (e.g. the classic layout header) opens the client with the example the snippet shows\nwatchEffect(() => {\n emit('update:exampleKey', localExampleKey.value)\n})\n\n/** Select an example locally and sync the choice across the document */\nconst selectExample = (key: string) => {\n localExampleKey.value = key\n eventBus.emit('workspace:update:selected-example', key)\n}\n\n/** Grab any custom code samples from the operation */\nconst customCodeSamples = computed(() => getCustomCodeSamples(operation))\n\n/** Merge custom code samples with the client options */\nconst clients = computed(() =>\n getClients(\n customCodeSamples.value.samples,\n clientOptions,\n customCodeSamples.value.label,\n ),\n)\n\n/** Total number of available clients across all option groups */\nconst clientCount = computed(() =>\n clients.value.reduce((total, group) => total + group.options.length, 0),\n)\n\n/** The locally selected client which would include code samples from this operation only */\nconst localSelectedClient = ref<ClientOption | CustomClientOption | undefined>(\n findClient(clients.value, selectedClient),\n)\n\n/**\n * Re-resolve the local client whenever the global selection or the available\n * clients change. Watching `clients` matters when navigating between operations:\n * the stored id stays the same, but the matching option (e.g. a custom sample)\n * differs per operation, so without this the snippet could go stale.\n */\nwatch([() => selectedClient, clients], ([newClient]) => {\n const client = findClient(clients.value, newClient)\n if (client) {\n localSelectedClient.value = client\n }\n})\n\n/** Generate HAR data for webhook requests */\nconst webhookHar = computed(() => {\n if (!isWebhook) return null\n\n try {\n return operationToHar({\n operation,\n method,\n path,\n example: localExampleKey.value,\n requestBodyCompositionSelection,\n // Only required parameters are shown in code examples; optional parameters\n // are omitted unless explicitly enabled via `x-disabled: false`.\n defaultDisabledParameters: true,\n })\n } catch (error) {\n console.error('[webhookHar]', error)\n return null\n }\n})\n\n/** Generate the code snippet for the selected example */\nconst generatedCode = computed<string>(() => {\n if (isWebhook) {\n return webhookHar.value?.postData?.text ?? ''\n }\n\n return generateCodeSnippet({\n // Only required parameters are shown in code examples; optional parameters\n // are omitted unless explicitly enabled via `x-disabled: false`.\n defaultDisabledParameters: true,\n includeDefaultHeaders: integration === 'client',\n clientId: localSelectedClient.value?.id,\n customCodeSamples: customCodeSamples.value.samples,\n operation,\n method,\n path,\n contentType: selectedContentType,\n server: selectedServer,\n securitySchemes,\n example: localExampleKey.value,\n globalCookies,\n requestBodyCompositionSelection,\n })\n})\n\n/** The language for the code block, used for syntax highlighting */\nconst codeBlockLanguage = computed(() => {\n if (isWebhook) {\n return webhookLanguage.value\n }\n\n return localSelectedClient.value?.lang\n})\n\n/** Determine the language for webhook content based on MIME type */\nconst webhookLanguage = computed<string>(() => {\n if (!webhookHar.value?.postData) return 'json'\n\n const contentType = webhookHar.value.postData.mimeType\n if (contentType?.includes('json')) return 'json'\n if (contentType?.includes('xml')) return 'xml'\n if (contentType?.includes('yaml') || contentType?.includes('yml'))\n return 'yaml'\n if (contentType?.includes('text/plain')) return 'text'\n\n return 'json'\n})\n\n/** Block secrets from being shown in the code block */\nconst secretCredentials = computed(() => getSecrets(securitySchemes))\n\n/** Grab the ref to freeze the ui as the clients change so there's no jump as the size of the dom changes */\nconst elem = ref<ComponentPublicInstance | null>(null)\n\n/** Set custom example, or update the selected HTTP client globally */\nconst selectClient = (option: ClientOption) => {\n // We need to freeze the ui to prevent scrolling as the clients change\n if (elem.value) {\n const unfreeze = freezeElement(elem.value.$el)\n setTimeout(() => {\n unfreeze()\n }, 300)\n }\n // Update to the local example\n localSelectedClient.value = option\n\n // Sync the selection globally so other operations follow along. Custom samples\n // sync too (keyed by language), so picking e.g. the Python SDK example here\n // shows the Python example on every operation that ships one.\n if (option) {\n eventBus.emit('workspace:update:selected-client', option.id)\n }\n}\n\n// Virtualize the code block if it's too large\n// This prevents the entire app from freezing up if there's a massive example\n// We set a lower threshold here as code examples can get quite large\nconst VIRTUALIZATION_THRESHOLD = 20_000\n\nconst shouldVirtualize = computed(\n () => (generatedCode.value.length ?? 0) > VIRTUALIZATION_THRESHOLD,\n)\n\nconst id = useId()\n</script>\n<template>\n <ScalarCard\n v-if=\"generatedCode\"\n ref=\"elem\"\n class=\"request-card dark-mode\">\n <!-- Header -->\n <ScalarCardHeader class=\"pr-2.5\">\n <span class=\"sr-only\">Request Example for</span>\n <HttpMethod\n as=\"span\"\n class=\"request-method\"\n :method=\"method\" />\n <span\n v-if=\"generateLabel\"\n v-html=\"generateLabel()\" />\n <slot name=\"header\" />\n <!-- Client picker -->\n <template\n v-if=\"!isWebhook && clientCount\"\n #actions>\n <!-- Multiple clients: render a dropdown to switch between them -->\n <ScalarCombobox\n v-if=\"clientCount > 1\"\n class=\"max-h-80\"\n :filterFn=\"filterClientsByQuery\"\n :modelValue=\"localSelectedClient\"\n :options=\"clients\"\n placement=\"bottom-end\"\n teleport\n @update:modelValue=\"selectClient($event as ClientOption)\">\n <ScalarButton\n class=\"text-c-2 hover:text-c-1 flex h-full w-fit gap-1.5 px-0.5 py-0 text-base font-normal\"\n data-testid=\"client-picker\"\n variant=\"ghost\">\n {{ localSelectedClient?.title }}\n <ScalarIconCaretDown\n class=\"ui-open:rotate-180 mt-px size-3 transition-transform duration-100\"\n weight=\"bold\" />\n </ScalarButton>\n </ScalarCombobox>\n <!-- Single client: just show its label, no need for a dropdown -->\n <span\n v-else\n class=\"text-c-2 flex h-full w-fit items-center px-0.5 py-0 text-base font-normal\"\n data-testid=\"client-picker\">\n {{ localSelectedClient?.title }}\n </span>\n </template>\n </ScalarCardHeader>\n\n <!-- Code snippet -->\n <ScalarCardSection class=\"request-editor-section custom-scroll p-0\">\n <div\n :id=\"`${id}-example`\"\n class=\"code-snippet\">\n <ScalarCodeBlock\n v-if=\"!shouldVirtualize\"\n class=\"bg-b-2 h-full\"\n :content=\"generatedCode\"\n :hideCredentials=\"secretCredentials\"\n :lang=\"codeBlockLanguage\"\n lineNumbers />\n <ScalarVirtualText\n v-else\n containerClass=\"custom-scroll scalar-code-block border rounded-b flex flex-1 max-h-screen\"\n contentClass=\"language-plaintext whitespace-pre font-code text-base p-2\"\n :lineHeight=\"20\"\n :text=\"generatedCode\" />\n </div>\n </ScalarCardSection>\n\n <!-- Footer -->\n <ScalarCardFooter\n v-if=\"Object.keys(requestBodyExamples).length > 1 || $slots.footer\"\n class=\"request-card-footer bg-b-3\">\n <!-- Example picker -->\n <div\n v-if=\"Object.keys(requestBodyExamples).length > 1\"\n class=\"request-card-footer-addon\">\n <template v-if=\"Object.keys(requestBodyExamples).length\">\n <ExamplePicker\n :examples=\"requestBodyExamples\"\n :modelValue=\"localExampleKey\"\n @update:modelValue=\"selectExample\" />\n </template>\n </div>\n\n <!-- Footer -->\n <slot\n :exampleName=\"localExampleKey\"\n name=\"footer\" />\n </ScalarCardFooter>\n </ScalarCard>\n\n <!-- Fallback card with just method and path in the case of no examples -->\n <ScalarCard\n v-else-if=\"fallback\"\n class=\"request-card dark-mode\">\n <ScalarCardSection class=\"request-card-simple\">\n <div class=\"request-header\">\n <HttpMethod\n as=\"span\"\n class=\"request-method\"\n :method=\"method\" />\n <slot name=\"header\" />\n </div>\n <slot\n :exampleName=\"localExampleKey\"\n name=\"footer\" />\n </ScalarCardSection>\n </ScalarCard>\n</template>\n<style scoped>\n.request-card {\n color: var(--scalar-color-1);\n font-size: var(--scalar-font-size-3);\n}\n.request-method {\n font-family: var(--scalar-font-code);\n text-transform: uppercase;\n margin-right: 6px;\n}\n.request-card-footer {\n display: flex;\n justify-content: flex-end;\n padding: 6px;\n flex-shrink: 0;\n position: relative;\n}\n.request-card-footer-addon {\n display: flex;\n align-items: center;\n\n flex: 1;\n min-width: 0;\n}\n.request-editor-section {\n display: flex;\n flex: 1;\n}\n.request-card-simple {\n display: flex;\n align-items: center;\n justify-content: space-between;\n\n padding: 8px 8px 8px 12px;\n\n font-size: var(--scalar-small);\n}\n.code-snippet {\n display: flex;\n flex-direction: column;\n width: 100%;\n}\n</style>\n"],"mappings":""}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CodeExample.vue.script.js","names":["$slots"],"sources":["../../../src/code-example/components/CodeExample.vue"],"sourcesContent":["<script lang=\"ts\">\nexport type CodeExampleProps = {\n /**\n * Integration type: determines if the code sample is displayed in a client environment\n * or in an API reference environment.\n */\n integration?: 'client' | 'reference'\n /**\n * List of all http clients formatted into option groups for the client selector\n */\n clientOptions: ClientOptionGroup[]\n /**\n * Pre-selected client, this will determine which client is initially selected in the dropdown.\n * Either a built-in client id (e.g. `js/fetch`) or a custom sample id (e.g. `custom/python`).\n *\n * Typed as a plain string: unioning the (large) client-id union with the `custom/...`\n * ids overflows TypeScript's union-complexity limit inside this component's `defineProps`.\n *\n * @defaults to a custom sample if one is available, otherwise shell/curl\n */\n selectedClient?: string\n /**\n * Which server from the spec to use for the code example\n */\n selectedServer?: ServerObject | null\n /**\n * The selected content type from the requestBody.content, this will determine which examples are available\n * as well as the content type of the code example\n *\n * @defaults to the first content type if not provided\n */\n selectedContentType?: string\n /**\n * Example name to use for resolving example values for parameters AND requestBody.\n *\n * This is the document-wide selection: it is honored only when this operation defines an example\n * with the same key, so picking an example on one operation syncs the rest without blanking out\n * operations that do not share that key.\n *\n * @example \"limited\"\n * ```ts\n * parameters: {\n * name: 'foobar',\n * in: 'query',\n * examples: {\n * limited: {\n * dataValue: 10,\n * }\n * }\n * },\n * body: {\n * content: {\n * 'application/json': {\n * examples: {\n * limited: {\n * dataValue: { foo: 'bar' },\n * }\n * }\n * }\n * }\n * }\n *\n * ```\n */\n selectedExample?: string\n /**\n * Event bus\n */\n eventBus: WorkspaceEventBus\n /**\n * The security schemes which are applicable to this operation\n */\n securitySchemes: SecuritySchemeObjectSecret[]\n /**\n * HTTP method of the operation\n */\n method: HttpMethodType\n /**\n * Path of the operation\n */\n path: string\n /**\n * De-referenced OpenAPI Operation object\n */\n operation: OperationObject\n /**\n * If true and there's no example, we will display a small card with the method and path only\n */\n fallback?: boolean\n /**\n * A method to generate the label of the block, should return an html string\n */\n generateLabel?: () => string\n /**\n * If true, render this as a webhook request example\n */\n isWebhook?: boolean\n /**\n * Workspace + document cookies\n */\n globalCookies?: XScalarCookie[]\n /**\n * When the request body schema uses oneOf/anyOf, use these selected variants\n * for the example snippet (e.g. from the schema dropdowns in the API reference).\n */\n requestBodyCompositionSelection?: Record<string, number>\n}\n\n/**\n * Request Example\n *\n * The core component for rendering a request example block,\n * this component does not have much of its own state but operates on props and custom events\n *\n * @event workspace:update:selected-client - Emitted when the selected client changes\n * @event workspace:update:selected-example - Emitted when the selected example changes, so other operations can sync\n */\nexport default {}\n</script>\n\n<script setup lang=\"ts\">\nimport { ScalarButton } from '@scalar/components/button'\nimport {\n ScalarCard,\n ScalarCardFooter,\n ScalarCardHeader,\n ScalarCardSection,\n} from '@scalar/components/card'\nimport { ScalarCodeBlock } from '@scalar/components/code-block'\nimport { ScalarCombobox } from '@scalar/components/combobox'\nimport { ScalarVirtualText } from '@scalar/components/virtual-text'\nimport { freezeElement } from '@scalar/helpers/dom/freeze-element'\nimport type { HttpMethod as HttpMethodType } from '@scalar/helpers/http/http-methods'\nimport { ScalarIconCaretDown } from '@scalar/icons'\nimport { type WorkspaceEventBus } from '@scalar/workspace-store/events'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport type { SecuritySchemeObjectSecret } from '@scalar/workspace-store/request-example'\nimport type { XScalarCookie } from '@scalar/workspace-store/schemas/extensions/general/x-scalar-cookies'\nimport type {\n OperationObject,\n ServerObject,\n} from '@scalar/workspace-store/schemas/v3.1/strict/openapi-document'\nimport {\n computed,\n onBeforeMount,\n ref,\n useId,\n watch,\n watchEffect,\n type ComponentPublicInstance,\n} from 'vue'\n\nimport { filterClientsByQuery } from '../helpers/filter-clients-by-query'\nimport { findClient } from '../helpers/find-client'\nimport { generateCodeSnippet } from '../helpers/generate-code-snippet'\nimport { getClients } from '../helpers/get-clients'\nimport { getCustomCodeSamples } from '../helpers/get-custom-code-samples'\nimport { getSecrets } from '../helpers/get-secrets'\nimport { operationToHar } from '../helpers/operation-to-har/operation-to-har'\nimport type {\n ClientOption,\n ClientOptionGroup,\n CustomClientOption,\n} from '../types'\nimport ExamplePicker from './ExamplePicker.vue'\nimport HttpMethod from './HttpMethod.vue'\n\nconst {\n integration,\n clientOptions,\n selectedClient,\n selectedServer = null,\n selectedContentType,\n selectedExample,\n securitySchemes = [],\n method,\n eventBus,\n path,\n operation,\n isWebhook,\n generateLabel,\n globalCookies,\n requestBodyCompositionSelection,\n} = defineProps<CodeExampleProps>()\n\nconst emit = defineEmits<{\n /**\n * Emitted whenever the example key actually shown for this operation changes.\n *\n * This is the resolved local key (not the raw document-wide selection), so layouts that render\n * the test-request button outside this component can open the client with the same example the\n * snippet displays.\n */\n (e: 'update:exampleKey', value: string): void\n}>()\n\ndefineSlots<{\n header: () => unknown\n footer: ({ exampleName }: { exampleName: string }) => unknown\n}>()\n\n/** Grab the examples for the given content type */\nconst requestBodyExamples = computed(() => {\n const content = getResolvedRef(operation.requestBody)?.content ?? {}\n const contentType = selectedContentType || Object.keys(content)[0]\n if (!contentType) return {}\n\n const examples = content[contentType]?.examples ?? {}\n\n return examples\n})\n\n/**\n * The example key actually shown for this operation.\n *\n * `selectedExample` is the document-wide selection that syncs across operations. We honor it only\n * when this operation actually defines that key, otherwise we keep the local example: a selection\n * on one operation should never blank out an operation that does not share the same example.\n */\nconst localExampleKey = ref('')\n\n/** Resolve the key to display, preferring the document-wide selection when this operation has it */\nconst resolveExampleKey = (preferred: string | undefined): string => {\n const keys = Object.keys(requestBodyExamples.value)\n if (preferred && keys.includes(preferred)) {\n return preferred\n }\n // Keep the current local example when it is still valid, otherwise fall back to the first one\n if (localExampleKey.value && keys.includes(localExampleKey.value)) {\n return localExampleKey.value\n }\n return keys[0] ?? ''\n}\n\n// Set the initial example from the document-wide selection, falling back to the first example\nonBeforeMount(() => {\n localExampleKey.value = resolveExampleKey(selectedExample)\n})\n\n// Follow the document-wide selection when it changes and this operation has that example\nwatch(\n () => selectedExample,\n (preferred) => {\n localExampleKey.value = resolveExampleKey(preferred)\n },\n)\n\n/** Reset the selected example key if the content type changes and the new content type doesn't have the previously selected example */\nwatch(\n () => selectedContentType,\n () => {\n if (\n !Object.keys(requestBodyExamples.value).includes(localExampleKey.value)\n ) {\n // Re-resolve so the new content type still follows the document-wide selection when it has\n // that key, instead of always snapping back to the first example\n localExampleKey.value = resolveExampleKey(selectedExample)\n }\n },\n)\n\n// Keep the parent informed of the resolved key so a test-request button rendered outside this\n// component (e.g. the classic layout header) opens the client with the example the snippet shows\nwatchEffect(() => {\n emit('update:exampleKey', localExampleKey.value)\n})\n\n/** Select an example locally and sync the choice across the document */\nconst selectExample = (key: string) => {\n localExampleKey.value = key\n eventBus.emit('workspace:update:selected-example', key)\n}\n\n/** Grab any custom code samples from the operation */\nconst customCodeSamples = computed(() => getCustomCodeSamples(operation))\n\n/** Merge custom code samples with the client options */\nconst clients = computed(() =>\n getClients(\n customCodeSamples.value.samples,\n clientOptions,\n customCodeSamples.value.label,\n ),\n)\n\n/** Total number of available clients across all option groups */\nconst clientCount = computed(() =>\n clients.value.reduce((total, group) => total + group.options.length, 0),\n)\n\n/** The locally selected client which would include code samples from this operation only */\nconst localSelectedClient = ref<ClientOption | CustomClientOption | undefined>(\n findClient(clients.value, selectedClient),\n)\n\n/**\n * Re-resolve the local client whenever the global selection or the available\n * clients change. Watching `clients` matters when navigating between operations:\n * the stored id stays the same, but the matching option (e.g. a custom sample)\n * differs per operation, so without this the snippet could go stale.\n */\nwatch([() => selectedClient, clients], ([newClient]) => {\n const client = findClient(clients.value, newClient)\n if (client) {\n localSelectedClient.value = client\n }\n})\n\n/** Generate HAR data for webhook requests */\nconst webhookHar = computed(() => {\n if (!isWebhook) return null\n\n try {\n return operationToHar({\n operation,\n method,\n path,\n example: localExampleKey.value,\n requestBodyCompositionSelection,\n // Only required parameters are shown in code examples; optional parameters\n // are omitted unless explicitly enabled via `x-disabled: false`.\n defaultDisabledParameters: true,\n })\n } catch (error) {\n console.error('[webhookHar]', error)\n return null\n }\n})\n\n/** Generate the code snippet for the selected example */\nconst generatedCode = computed<string>(() => {\n if (isWebhook) {\n return webhookHar.value?.postData?.text ?? ''\n }\n\n return generateCodeSnippet({\n // Only required parameters are shown in code examples; optional parameters\n // are omitted unless explicitly enabled via `x-disabled: false`.\n defaultDisabledParameters: true,\n includeDefaultHeaders: integration === 'client',\n clientId: localSelectedClient.value?.id,\n customCodeSamples: customCodeSamples.value.samples,\n operation,\n method,\n path,\n contentType: selectedContentType,\n server: selectedServer,\n securitySchemes,\n example: localExampleKey.value,\n globalCookies,\n requestBodyCompositionSelection,\n })\n})\n\n/** The language for the code block, used for syntax highlighting */\nconst codeBlockLanguage = computed(() => {\n if (isWebhook) {\n return webhookLanguage.value\n }\n\n return localSelectedClient.value?.lang\n})\n\n/** Determine the language for webhook content based on MIME type */\nconst webhookLanguage = computed<string>(() => {\n if (!webhookHar.value?.postData) return 'json'\n\n const contentType = webhookHar.value.postData.mimeType\n if (contentType?.includes('json')) return 'json'\n if (contentType?.includes('xml')) return 'xml'\n if (contentType?.includes('yaml') || contentType?.includes('yml'))\n return 'yaml'\n if (contentType?.includes('text/plain')) return 'text'\n\n return 'json'\n})\n\n/** Block secrets from being shown in the code block */\nconst secretCredentials = computed(() => getSecrets(securitySchemes))\n\n/** Grab the ref to freeze the ui as the clients change so there's no jump as the size of the dom changes */\nconst elem = ref<ComponentPublicInstance | null>(null)\n\n/** Set custom example, or update the selected HTTP client globally */\nconst selectClient = (option: ClientOption) => {\n // We need to freeze the ui to prevent scrolling as the clients change\n if (elem.value) {\n const unfreeze = freezeElement(elem.value.$el)\n setTimeout(() => {\n unfreeze()\n }, 300)\n }\n // Update to the local example\n localSelectedClient.value = option\n\n // Sync the selection globally so other operations follow along. Custom samples\n // sync too (keyed by language), so picking e.g. the Python SDK example here\n // shows the Python example on every operation that ships one.\n if (option) {\n eventBus.emit('workspace:update:selected-client', option.id)\n }\n}\n\n// Virtualize the code block if it's too large\n// This prevents the entire app from freezing up if there's a massive example\n// We set a lower threshold here as code examples can get quite large\nconst VIRTUALIZATION_THRESHOLD = 20_000\n\nconst shouldVirtualize = computed(\n () => (generatedCode.value.length ?? 0) > VIRTUALIZATION_THRESHOLD,\n)\n\nconst id = useId()\n</script>\n<template>\n <ScalarCard\n v-if=\"generatedCode\"\n ref=\"elem\"\n class=\"request-card dark-mode\">\n <!-- Header -->\n <ScalarCardHeader class=\"pr-2.5\">\n <span class=\"sr-only\">Request Example for</span>\n <HttpMethod\n as=\"span\"\n class=\"request-method\"\n :method=\"method\" />\n <span\n v-if=\"generateLabel\"\n v-html=\"generateLabel()\" />\n <slot name=\"header\" />\n <!-- Client picker -->\n <template\n v-if=\"!isWebhook && clientCount\"\n #actions>\n <!-- Multiple clients: render a dropdown to switch between them -->\n <ScalarCombobox\n v-if=\"clientCount > 1\"\n class=\"max-h-80\"\n :filterFn=\"filterClientsByQuery\"\n :modelValue=\"localSelectedClient\"\n :options=\"clients\"\n placement=\"bottom-end\"\n teleport\n @update:modelValue=\"selectClient($event as ClientOption)\">\n <ScalarButton\n class=\"text-c-2 hover:text-c-1 flex h-full w-fit gap-1.5 px-0.5 py-0 text-base font-normal\"\n data-testid=\"client-picker\"\n variant=\"ghost\">\n {{ localSelectedClient?.title }}\n <ScalarIconCaretDown\n class=\"ui-open:rotate-180 mt-px size-3 transition-transform duration-100\"\n weight=\"bold\" />\n </ScalarButton>\n </ScalarCombobox>\n <!-- Single client: just show its label, no need for a dropdown -->\n <span\n v-else\n class=\"text-c-2 flex h-full w-fit items-center px-0.5 py-0 text-base font-normal\"\n data-testid=\"client-picker\">\n {{ localSelectedClient?.title }}\n </span>\n </template>\n </ScalarCardHeader>\n\n <!-- Code snippet -->\n <ScalarCardSection class=\"request-editor-section custom-scroll p-0\">\n <div\n :id=\"`${id}-example`\"\n class=\"code-snippet\">\n <ScalarCodeBlock\n v-if=\"!shouldVirtualize\"\n class=\"bg-b-2 h-full\"\n :content=\"generatedCode\"\n :hideCredentials=\"secretCredentials\"\n :lang=\"codeBlockLanguage\"\n lineNumbers />\n <ScalarVirtualText\n v-else\n containerClass=\"custom-scroll scalar-code-block border rounded-b flex flex-1 max-h-screen\"\n contentClass=\"language-plaintext whitespace-pre font-code text-base p-2\"\n :lineHeight=\"20\"\n :text=\"generatedCode\" />\n </div>\n </ScalarCardSection>\n\n <!-- Footer -->\n <ScalarCardFooter\n v-if=\"Object.keys(requestBodyExamples).length > 1 || $slots.footer\"\n class=\"request-card-footer bg-b-3\">\n <!-- Example picker -->\n <div\n v-if=\"Object.keys(requestBodyExamples).length > 1\"\n class=\"request-card-footer-addon\">\n <template v-if=\"Object.keys(requestBodyExamples).length\">\n <ExamplePicker\n :examples=\"requestBodyExamples\"\n :modelValue=\"localExampleKey\"\n @update:modelValue=\"selectExample\" />\n </template>\n </div>\n\n <!-- Footer -->\n <slot\n :exampleName=\"localExampleKey\"\n name=\"footer\" />\n </ScalarCardFooter>\n </ScalarCard>\n\n <!-- Fallback card with just method and path in the case of no examples -->\n <ScalarCard\n v-else-if=\"fallback\"\n class=\"request-card dark-mode\">\n <ScalarCardSection class=\"request-card-simple\">\n <div class=\"request-header\">\n <HttpMethod\n as=\"span\"\n class=\"request-method\"\n :method=\"method\" />\n <slot name=\"header\" />\n </div>\n <slot\n :exampleName=\"localExampleKey\"\n name=\"footer\" />\n </ScalarCardSection>\n </ScalarCard>\n</template>\n<style scoped>\n.request-card {\n color: var(--scalar-color-1);\n font-size: var(--scalar-font-size-3);\n}\n.request-method {\n font-family: var(--scalar-font-code);\n text-transform: uppercase;\n margin-right: 6px;\n}\n.request-card-footer {\n display: flex;\n justify-content: flex-end;\n padding: 6px;\n flex-shrink: 0;\n position: relative;\n}\n.request-card-footer-addon {\n display: flex;\n align-items: center;\n\n flex: 1;\n min-width: 0;\n}\n.request-editor-section {\n display: flex;\n flex: 1;\n}\n.request-card-simple {\n display: flex;\n align-items: center;\n justify-content: space-between;\n\n padding: 8px 8px 8px 12px;\n\n font-size: var(--scalar-small);\n}\n.code-snippet {\n display: flex;\n flex-direction: column;\n width: 100%;\n}\n</style>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyLA,IAAM,IAAO,GAiBP,IAAsB,QAAe;GACzC,IAAM,IAAU,EAAe,EAAA,UAAU,WAAW,CAAC,EAAE,WAAW,CAAC,GAC7D,IAAc,EAAA,uBAAuB,OAAO,KAAK,CAAO,CAAC,CAAC;GAKhE,OAJK,IAEY,EAAQ,EAAY,EAAE,YAAY,CAAC,IAF3B,CAAC;EAK5B,CAAC,GASK,IAAkB,EAAI,EAAE,GAGxB,KAAqB,MAA0C;GACnE,IAAM,IAAO,OAAO,KAAK,EAAoB,KAAK;GAQlD,OAPI,KAAa,EAAK,SAAS,CAAS,IAC/B,IAGL,EAAgB,SAAS,EAAK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AjBjB,OAAM;;sBAWA,CARE,OAAO,KAAK,EAAA,KAAmB,CAAA,CAAE,SAAM,KAAA,EAAA,GAD/C,EASM,OATN,GASM,CANY,OAAO,KAAK,EAAA,KAAmB,CAAA,CAAE,UAAA,EAAA,GAC/C,EAGuC,GAAA;;MAFpC,UAAU,EAAA;MACV,YAAY,EAAA;MACZ,uBAAmB;0EAK1B,EAEkB,EAAA,QAAA,UAAA,EADf,aAAa,EAAA,MAAe,GAAA,KAAA,GAAA,EAAA,CAAA,CAAA;;;;;aAOtB,EAAA,YAAA,EAAA,GADb,EAea,EAAA,CAAA,GAAA;;GAbX,OAAM;;oBAYc,CAXpB,EAWoB,EAAA,CAAA,GAAA,EAXD,OAAM,sBAAqB,GAAA;qBAOtC,CANN,EAMM,OANN,GAMM,CALJ,EAGqB,GAAA;KAFnB,IAAG;KACH,OAAM;KACL,QAAQ,EAAA;6BACX,EAAsB,EAAA,QAAA,UAAA,CAAA,GAAA,KAAA,GAAA,EAAA,CAAA,CAAA,GAExB,EAEkB,EAAA,QAAA,UAAA,EADf,aAAa,EAAA,MAAe,GAAA,KAAA,GAAA,EAAA,CAAA,CAAA"}
|
|
1
|
+
{"version":3,"file":"CodeExample.vue.script.js","names":["$slots"],"sources":["../../../src/code-example/components/CodeExample.vue"],"sourcesContent":["<script lang=\"ts\">\nexport type CodeExampleProps = {\n /**\n * Integration type: determines if the code sample is displayed in a client environment\n * or in an API reference environment.\n */\n integration?: 'client' | 'reference'\n /**\n * List of all http clients formatted into option groups for the client selector\n */\n clientOptions: ClientOptionGroup[]\n /**\n * Pre-selected client, this will determine which client is initially selected in the dropdown.\n * Either a built-in client id (e.g. `js/fetch`) or a custom sample id (e.g. `custom/python`).\n *\n * Typed as a plain string: unioning the (large) client-id union with the `custom/...`\n * ids overflows TypeScript's union-complexity limit inside this component's `defineProps`.\n *\n * @defaults to a custom sample if one is available, otherwise shell/curl\n */\n selectedClient?: string\n /**\n * Which server from the spec to use for the code example\n */\n selectedServer?: ServerObject | null\n /**\n * The selected content type from the requestBody.content, this will determine which examples are available\n * as well as the content type of the code example\n *\n * @defaults to the first content type if not provided\n */\n selectedContentType?: string\n /**\n * Example name to use for resolving example values for parameters AND requestBody.\n *\n * This is the document-wide selection: it is honored only when this operation defines an example\n * with the same key, so picking an example on one operation syncs the rest without blanking out\n * operations that do not share that key.\n *\n * @example \"limited\"\n * ```ts\n * parameters: {\n * name: 'foobar',\n * in: 'query',\n * examples: {\n * limited: {\n * dataValue: 10,\n * }\n * }\n * },\n * body: {\n * content: {\n * 'application/json': {\n * examples: {\n * limited: {\n * dataValue: { foo: 'bar' },\n * }\n * }\n * }\n * }\n * }\n *\n * ```\n */\n selectedExample?: string\n /**\n * Event bus\n */\n eventBus: WorkspaceEventBus\n /**\n * The security schemes which are applicable to this operation\n */\n securitySchemes: SecuritySchemeObjectSecret[]\n /**\n * HTTP method of the operation\n */\n method: HttpMethodType\n /**\n * Path of the operation\n */\n path: string\n /**\n * De-referenced OpenAPI Operation object\n */\n operation: OperationObject\n /**\n * If true and there's no example, we will display a small card with the method and path only\n */\n fallback?: boolean\n /**\n * A method to generate the label of the block, should return an html string\n */\n generateLabel?: () => string\n /**\n * If true, render this as a webhook request example\n */\n isWebhook?: boolean\n /**\n * Workspace + document cookies\n */\n globalCookies?: XScalarCookie[]\n /**\n * When the request body schema uses oneOf/anyOf, use these selected variants\n * for the example snippet (e.g. from the schema dropdowns in the API reference).\n */\n requestBodyCompositionSelection?: Record<string, number>\n}\n\n/**\n * Request Example\n *\n * The core component for rendering a request example block,\n * this component does not have much of its own state but operates on props and custom events\n *\n * @event workspace:update:selected-client - Emitted when the selected client changes\n * @event workspace:update:selected-example - Emitted when the selected example changes, so other operations can sync\n */\nexport default {}\n</script>\n\n<script setup lang=\"ts\">\nimport { ScalarButton } from '@scalar/components/button'\nimport {\n ScalarCard,\n ScalarCardFooter,\n ScalarCardHeader,\n ScalarCardSection,\n} from '@scalar/components/card'\nimport { ScalarCodeBlock } from '@scalar/components/code-block'\nimport { ScalarCombobox } from '@scalar/components/combobox'\nimport { ScalarVirtualText } from '@scalar/components/virtual-text'\nimport { freezeElement } from '@scalar/helpers/dom/freeze-element'\nimport type { HttpMethod as HttpMethodType } from '@scalar/helpers/http/http-methods'\nimport { ScalarIconCaretDown } from '@scalar/icons'\nimport { type WorkspaceEventBus } from '@scalar/workspace-store/events'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport type { SecuritySchemeObjectSecret } from '@scalar/workspace-store/request-example'\nimport type { XScalarCookie } from '@scalar/workspace-store/schemas/extensions/general/x-scalar-cookies'\nimport type {\n OperationObject,\n ServerObject,\n} from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport {\n computed,\n onBeforeMount,\n ref,\n useId,\n watch,\n watchEffect,\n type ComponentPublicInstance,\n} from 'vue'\n\nimport { filterClientsByQuery } from '../helpers/filter-clients-by-query'\nimport { findClient } from '../helpers/find-client'\nimport { generateCodeSnippet } from '../helpers/generate-code-snippet'\nimport { getClients } from '../helpers/get-clients'\nimport { getCustomCodeSamples } from '../helpers/get-custom-code-samples'\nimport { getSecrets } from '../helpers/get-secrets'\nimport { operationToHar } from '../helpers/operation-to-har/operation-to-har'\nimport type {\n ClientOption,\n ClientOptionGroup,\n CustomClientOption,\n} from '../types'\nimport ExamplePicker from './ExamplePicker.vue'\nimport HttpMethod from './HttpMethod.vue'\n\nconst {\n integration,\n clientOptions,\n selectedClient,\n selectedServer = null,\n selectedContentType,\n selectedExample,\n securitySchemes = [],\n method,\n eventBus,\n path,\n operation,\n isWebhook,\n generateLabel,\n globalCookies,\n requestBodyCompositionSelection,\n} = defineProps<CodeExampleProps>()\n\nconst emit = defineEmits<{\n /**\n * Emitted whenever the example key actually shown for this operation changes.\n *\n * This is the resolved local key (not the raw document-wide selection), so layouts that render\n * the test-request button outside this component can open the client with the same example the\n * snippet displays.\n */\n (e: 'update:exampleKey', value: string): void\n}>()\n\ndefineSlots<{\n header: () => unknown\n footer: ({ exampleName }: { exampleName: string }) => unknown\n}>()\n\n/** Grab the examples for the given content type */\nconst requestBodyExamples = computed(() => {\n const content = getResolvedRef(operation.requestBody)?.content ?? {}\n const contentType = selectedContentType || Object.keys(content)[0]\n if (!contentType) return {}\n\n const examples = content[contentType]?.examples ?? {}\n\n return examples\n})\n\n/**\n * The example key actually shown for this operation.\n *\n * `selectedExample` is the document-wide selection that syncs across operations. We honor it only\n * when this operation actually defines that key, otherwise we keep the local example: a selection\n * on one operation should never blank out an operation that does not share the same example.\n */\nconst localExampleKey = ref('')\n\n/** Resolve the key to display, preferring the document-wide selection when this operation has it */\nconst resolveExampleKey = (preferred: string | undefined): string => {\n const keys = Object.keys(requestBodyExamples.value)\n if (preferred && keys.includes(preferred)) {\n return preferred\n }\n // Keep the current local example when it is still valid, otherwise fall back to the first one\n if (localExampleKey.value && keys.includes(localExampleKey.value)) {\n return localExampleKey.value\n }\n return keys[0] ?? ''\n}\n\n// Set the initial example from the document-wide selection, falling back to the first example\nonBeforeMount(() => {\n localExampleKey.value = resolveExampleKey(selectedExample)\n})\n\n// Follow the document-wide selection when it changes and this operation has that example\nwatch(\n () => selectedExample,\n (preferred) => {\n localExampleKey.value = resolveExampleKey(preferred)\n },\n)\n\n/** Reset the selected example key if the content type changes and the new content type doesn't have the previously selected example */\nwatch(\n () => selectedContentType,\n () => {\n if (\n !Object.keys(requestBodyExamples.value).includes(localExampleKey.value)\n ) {\n // Re-resolve so the new content type still follows the document-wide selection when it has\n // that key, instead of always snapping back to the first example\n localExampleKey.value = resolveExampleKey(selectedExample)\n }\n },\n)\n\n// Keep the parent informed of the resolved key so a test-request button rendered outside this\n// component (e.g. the classic layout header) opens the client with the example the snippet shows\nwatchEffect(() => {\n emit('update:exampleKey', localExampleKey.value)\n})\n\n/** Select an example locally and sync the choice across the document */\nconst selectExample = (key: string) => {\n localExampleKey.value = key\n eventBus.emit('workspace:update:selected-example', key)\n}\n\n/** Grab any custom code samples from the operation */\nconst customCodeSamples = computed(() => getCustomCodeSamples(operation))\n\n/** Merge custom code samples with the client options */\nconst clients = computed(() =>\n getClients(\n customCodeSamples.value.samples,\n clientOptions,\n customCodeSamples.value.label,\n ),\n)\n\n/** Total number of available clients across all option groups */\nconst clientCount = computed(() =>\n clients.value.reduce((total, group) => total + group.options.length, 0),\n)\n\n/** The locally selected client which would include code samples from this operation only */\nconst localSelectedClient = ref<ClientOption | CustomClientOption | undefined>(\n findClient(clients.value, selectedClient),\n)\n\n/**\n * Re-resolve the local client whenever the global selection or the available\n * clients change. Watching `clients` matters when navigating between operations:\n * the stored id stays the same, but the matching option (e.g. a custom sample)\n * differs per operation, so without this the snippet could go stale.\n */\nwatch([() => selectedClient, clients], ([newClient]) => {\n const client = findClient(clients.value, newClient)\n if (client) {\n localSelectedClient.value = client\n }\n})\n\n/** Generate HAR data for webhook requests */\nconst webhookHar = computed(() => {\n if (!isWebhook) return null\n\n try {\n return operationToHar({\n operation,\n method,\n path,\n example: localExampleKey.value,\n requestBodyCompositionSelection,\n // Only required parameters are shown in code examples; optional parameters\n // are omitted unless explicitly enabled via `x-disabled: false`.\n defaultDisabledParameters: true,\n })\n } catch (error) {\n console.error('[webhookHar]', error)\n return null\n }\n})\n\n/** Generate the code snippet for the selected example */\nconst generatedCode = computed<string>(() => {\n if (isWebhook) {\n return webhookHar.value?.postData?.text ?? ''\n }\n\n return generateCodeSnippet({\n // Only required parameters are shown in code examples; optional parameters\n // are omitted unless explicitly enabled via `x-disabled: false`.\n defaultDisabledParameters: true,\n includeDefaultHeaders: integration === 'client',\n clientId: localSelectedClient.value?.id,\n customCodeSamples: customCodeSamples.value.samples,\n operation,\n method,\n path,\n contentType: selectedContentType,\n server: selectedServer,\n securitySchemes,\n example: localExampleKey.value,\n globalCookies,\n requestBodyCompositionSelection,\n })\n})\n\n/** The language for the code block, used for syntax highlighting */\nconst codeBlockLanguage = computed(() => {\n if (isWebhook) {\n return webhookLanguage.value\n }\n\n return localSelectedClient.value?.lang\n})\n\n/** Determine the language for webhook content based on MIME type */\nconst webhookLanguage = computed<string>(() => {\n if (!webhookHar.value?.postData) return 'json'\n\n const contentType = webhookHar.value.postData.mimeType\n if (contentType?.includes('json')) return 'json'\n if (contentType?.includes('xml')) return 'xml'\n if (contentType?.includes('yaml') || contentType?.includes('yml'))\n return 'yaml'\n if (contentType?.includes('text/plain')) return 'text'\n\n return 'json'\n})\n\n/** Block secrets from being shown in the code block */\nconst secretCredentials = computed(() => getSecrets(securitySchemes))\n\n/** Grab the ref to freeze the ui as the clients change so there's no jump as the size of the dom changes */\nconst elem = ref<ComponentPublicInstance | null>(null)\n\n/** Set custom example, or update the selected HTTP client globally */\nconst selectClient = (option: ClientOption) => {\n // We need to freeze the ui to prevent scrolling as the clients change\n if (elem.value) {\n const unfreeze = freezeElement(elem.value.$el)\n setTimeout(() => {\n unfreeze()\n }, 300)\n }\n // Update to the local example\n localSelectedClient.value = option\n\n // Sync the selection globally so other operations follow along. Custom samples\n // sync too (keyed by language), so picking e.g. the Python SDK example here\n // shows the Python example on every operation that ships one.\n if (option) {\n eventBus.emit('workspace:update:selected-client', option.id)\n }\n}\n\n// Virtualize the code block if it's too large\n// This prevents the entire app from freezing up if there's a massive example\n// We set a lower threshold here as code examples can get quite large\nconst VIRTUALIZATION_THRESHOLD = 20_000\n\nconst shouldVirtualize = computed(\n () => (generatedCode.value.length ?? 0) > VIRTUALIZATION_THRESHOLD,\n)\n\nconst id = useId()\n</script>\n<template>\n <ScalarCard\n v-if=\"generatedCode\"\n ref=\"elem\"\n class=\"request-card dark-mode\">\n <!-- Header -->\n <ScalarCardHeader class=\"pr-2.5\">\n <span class=\"sr-only\">Request Example for</span>\n <HttpMethod\n as=\"span\"\n class=\"request-method\"\n :method=\"method\" />\n <span\n v-if=\"generateLabel\"\n v-html=\"generateLabel()\" />\n <slot name=\"header\" />\n <!-- Client picker -->\n <template\n v-if=\"!isWebhook && clientCount\"\n #actions>\n <!-- Multiple clients: render a dropdown to switch between them -->\n <ScalarCombobox\n v-if=\"clientCount > 1\"\n class=\"max-h-80\"\n :filterFn=\"filterClientsByQuery\"\n :modelValue=\"localSelectedClient\"\n :options=\"clients\"\n placement=\"bottom-end\"\n teleport\n @update:modelValue=\"selectClient($event as ClientOption)\">\n <ScalarButton\n class=\"text-c-2 hover:text-c-1 flex h-full w-fit gap-1.5 px-0.5 py-0 text-base font-normal\"\n data-testid=\"client-picker\"\n variant=\"ghost\">\n {{ localSelectedClient?.title }}\n <ScalarIconCaretDown\n class=\"ui-open:rotate-180 mt-px size-3 transition-transform duration-100\"\n weight=\"bold\" />\n </ScalarButton>\n </ScalarCombobox>\n <!-- Single client: just show its label, no need for a dropdown -->\n <span\n v-else\n class=\"text-c-2 flex h-full w-fit items-center px-0.5 py-0 text-base font-normal\"\n data-testid=\"client-picker\">\n {{ localSelectedClient?.title }}\n </span>\n </template>\n </ScalarCardHeader>\n\n <!-- Code snippet -->\n <ScalarCardSection class=\"request-editor-section custom-scroll p-0\">\n <div\n :id=\"`${id}-example`\"\n class=\"code-snippet\">\n <ScalarCodeBlock\n v-if=\"!shouldVirtualize\"\n class=\"bg-b-2 h-full\"\n :content=\"generatedCode\"\n :hideCredentials=\"secretCredentials\"\n :lang=\"codeBlockLanguage\"\n lineNumbers />\n <ScalarVirtualText\n v-else\n containerClass=\"custom-scroll scalar-code-block border rounded-b flex flex-1 max-h-screen\"\n contentClass=\"language-plaintext whitespace-pre font-code text-base p-2\"\n :lineHeight=\"20\"\n :text=\"generatedCode\" />\n </div>\n </ScalarCardSection>\n\n <!-- Footer -->\n <ScalarCardFooter\n v-if=\"Object.keys(requestBodyExamples).length > 1 || $slots.footer\"\n class=\"request-card-footer bg-b-3\">\n <!-- Example picker -->\n <div\n v-if=\"Object.keys(requestBodyExamples).length > 1\"\n class=\"request-card-footer-addon\">\n <template v-if=\"Object.keys(requestBodyExamples).length\">\n <ExamplePicker\n :examples=\"requestBodyExamples\"\n :modelValue=\"localExampleKey\"\n @update:modelValue=\"selectExample\" />\n </template>\n </div>\n\n <!-- Footer -->\n <slot\n :exampleName=\"localExampleKey\"\n name=\"footer\" />\n </ScalarCardFooter>\n </ScalarCard>\n\n <!-- Fallback card with just method and path in the case of no examples -->\n <ScalarCard\n v-else-if=\"fallback\"\n class=\"request-card dark-mode\">\n <ScalarCardSection class=\"request-card-simple\">\n <div class=\"request-header\">\n <HttpMethod\n as=\"span\"\n class=\"request-method\"\n :method=\"method\" />\n <slot name=\"header\" />\n </div>\n <slot\n :exampleName=\"localExampleKey\"\n name=\"footer\" />\n </ScalarCardSection>\n </ScalarCard>\n</template>\n<style scoped>\n.request-card {\n color: var(--scalar-color-1);\n font-size: var(--scalar-font-size-3);\n}\n.request-method {\n font-family: var(--scalar-font-code);\n text-transform: uppercase;\n margin-right: 6px;\n}\n.request-card-footer {\n display: flex;\n justify-content: flex-end;\n padding: 6px;\n flex-shrink: 0;\n position: relative;\n}\n.request-card-footer-addon {\n display: flex;\n align-items: center;\n\n flex: 1;\n min-width: 0;\n}\n.request-editor-section {\n display: flex;\n flex: 1;\n}\n.request-card-simple {\n display: flex;\n align-items: center;\n justify-content: space-between;\n\n padding: 8px 8px 8px 12px;\n\n font-size: var(--scalar-small);\n}\n.code-snippet {\n display: flex;\n flex-direction: column;\n width: 100%;\n}\n</style>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyLA,IAAM,IAAO,GAiBP,IAAsB,QAAe;GACzC,IAAM,IAAU,EAAe,EAAA,UAAU,WAAW,CAAC,EAAE,WAAW,CAAC,GAC7D,IAAc,EAAA,uBAAuB,OAAO,KAAK,CAAO,CAAC,CAAC;GAKhE,OAJK,IAEY,EAAQ,EAAY,EAAE,YAAY,CAAC,IAF3B,CAAC;EAK5B,CAAC,GASK,IAAkB,EAAI,EAAE,GAGxB,KAAqB,MAA0C;GACnE,IAAM,IAAO,OAAO,KAAK,EAAoB,KAAK;GAQlD,OAPI,KAAa,EAAK,SAAS,CAAS,IAC/B,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mB,EAAA,EAAA,GAAA;;KAjBjB,OAAM;;sBAWA,CARE,OAAO,KAAK,EAAA,KAAmB,CAAA,CAAE,SAAM,KAAA,EAAA,GAD/C,EASM,OATN,GASM,CANY,OAAO,KAAK,EAAA,KAAmB,CAAA,CAAE,UAAA,EAAA,GAC/C,EAGuC,GAAA;;MAFpC,UAAU,EAAA;MACV,YAAY,EAAA;MACZ,uBAAmB;0EAK1B,EAEkB,EAAA,QAAA,UAAA,EADf,aAAa,EAAA,MAAe,GAAA,KAAA,GAAA,EAAA,CAAA,CAAA;;;;;aAOtB,EAAA,YAAA,EAAA,GADb,EAea,EAAA,CAAA,GAAA;;GAbX,OAAM;;oBAYc,CAXpB,EAWoB,EAAA,CAAA,GAAA,EAXD,OAAM,sBAAqB,GAAA;qBAOtC,CANN,EAMM,OANN,GAMM,CALJ,EAGqB,GAAA;KAFnB,IAAG;KACH,OAAM;KACL,QAAQ,EAAA;6BACX,EAAsB,EAAA,QAAA,UAAA,CAAA,GAAA,KAAA,GAAA,EAAA,CAAA,CAAA,GAExB,EAEkB,EAAA,QAAA,UAAA,EADf,aAAa,EAAA,MAAe,GAAA,KAAA,GAAA,EAAA,CAAA,CAAA"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { MediaTypeObject } from '@scalar/workspace-store/schemas/v3.
|
|
1
|
+
import type { MediaTypeObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document';
|
|
2
2
|
type __VLS_Props = {
|
|
3
3
|
examples?: MediaTypeObject['examples'] | Record<string, string>;
|
|
4
4
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ExamplePicker.vue.js","names":[],"sources":["../../../src/code-example/components/ExamplePicker.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { ScalarButton } from '@scalar/components/button'\nimport {\n ScalarListbox,\n type ScalarListboxOption,\n} from '@scalar/components/listbox'\nimport { ScalarIconCaretDown } from '@scalar/icons'\nimport type { MediaTypeObject } from '@scalar/workspace-store/schemas/v3.
|
|
1
|
+
{"version":3,"file":"ExamplePicker.vue.js","names":[],"sources":["../../../src/code-example/components/ExamplePicker.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { ScalarButton } from '@scalar/components/button'\nimport {\n ScalarListbox,\n type ScalarListboxOption,\n} from '@scalar/components/listbox'\nimport { ScalarIconCaretDown } from '@scalar/icons'\nimport type { MediaTypeObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport { computed } from 'vue'\n\nconst { examples = {} } = defineProps<{\n examples?: MediaTypeObject['examples'] | Record<string, string>\n}>()\n\nconst selectedExampleKey = defineModel<string>({\n required: true,\n})\n\ndefineOptions({ inheritAttrs: false })\n\nconst exampleOptions = computed<ScalarListboxOption[]>(() =>\n Object.entries(examples).map(([key, example]) => ({\n id: key,\n label: example?.summary ?? key,\n })),\n)\n\nconst selectedExample = computed<ScalarListboxOption | undefined>({\n get: () =>\n exampleOptions.value.find(({ id }) => id === selectedExampleKey.value),\n set: (v) => (selectedExampleKey.value = v?.id ?? ''),\n})\n</script>\n\n<template>\n <ScalarListbox\n v-model=\"selectedExample\"\n class=\"w-fit min-w-32\"\n :options=\"exampleOptions\"\n placement=\"bottom-start\"\n teleport>\n <ScalarButton\n class=\"text-c-2 hover:text-c-1 flex h-full w-fit min-w-0 gap-1.5 px-1.5 py-0.75 text-base font-normal\"\n data-testid=\"example-picker\"\n variant=\"ghost\"\n v-bind=\"$attrs\">\n <div class=\"min-w-0 flex-1 truncate\">\n {{ selectedExample?.label ?? 'Select an example' }}\n </div>\n <ScalarIconCaretDown\n class=\"ui-open:rotate-180 mt-0.25 size-3 transition-transform duration-100\"\n weight=\"bold\" />\n </ScalarButton>\n </ScalarListbox>\n</template>\n"],"mappings":""}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ExamplePicker.vue.script.js","names":["$attrs"],"sources":["../../../src/code-example/components/ExamplePicker.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { ScalarButton } from '@scalar/components/button'\nimport {\n ScalarListbox,\n type ScalarListboxOption,\n} from '@scalar/components/listbox'\nimport { ScalarIconCaretDown } from '@scalar/icons'\nimport type { MediaTypeObject } from '@scalar/workspace-store/schemas/v3.
|
|
1
|
+
{"version":3,"file":"ExamplePicker.vue.script.js","names":["$attrs"],"sources":["../../../src/code-example/components/ExamplePicker.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { ScalarButton } from '@scalar/components/button'\nimport {\n ScalarListbox,\n type ScalarListboxOption,\n} from '@scalar/components/listbox'\nimport { ScalarIconCaretDown } from '@scalar/icons'\nimport type { MediaTypeObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport { computed } from 'vue'\n\nconst { examples = {} } = defineProps<{\n examples?: MediaTypeObject['examples'] | Record<string, string>\n}>()\n\nconst selectedExampleKey = defineModel<string>({\n required: true,\n})\n\ndefineOptions({ inheritAttrs: false })\n\nconst exampleOptions = computed<ScalarListboxOption[]>(() =>\n Object.entries(examples).map(([key, example]) => ({\n id: key,\n label: example?.summary ?? key,\n })),\n)\n\nconst selectedExample = computed<ScalarListboxOption | undefined>({\n get: () =>\n exampleOptions.value.find(({ id }) => id === selectedExampleKey.value),\n set: (v) => (selectedExampleKey.value = v?.id ?? ''),\n})\n</script>\n\n<template>\n <ScalarListbox\n v-model=\"selectedExample\"\n class=\"w-fit min-w-32\"\n :options=\"exampleOptions\"\n placement=\"bottom-start\"\n teleport>\n <ScalarButton\n class=\"text-c-2 hover:text-c-1 flex h-full w-fit min-w-0 gap-1.5 px-1.5 py-0.75 text-base font-normal\"\n data-testid=\"example-picker\"\n variant=\"ghost\"\n v-bind=\"$attrs\">\n <div class=\"min-w-0 flex-1 truncate\">\n {{ selectedExample?.label ?? 'Select an example' }}\n </div>\n <ScalarIconCaretDown\n class=\"ui-open:rotate-180 mt-0.25 size-3 transition-transform duration-100\"\n weight=\"bold\" />\n </ScalarButton>\n </ScalarListbox>\n</template>\n"],"mappings":";;;;;;;;;;;;;;EAcA,IAAM,IAAqB,EAAmB,GAAA,YAE7C,GAIK,IAAiB,QACrB,OAAO,QAAQ,EAAA,QAAQ,CAAC,CAAC,KAAK,CAAC,GAAK,QAAc;GAChD,IAAI;GACJ,OAAO,GAAS,WAAW;EAC7B,EAAE,CACJ,GAEM,IAAkB,EAA0C;GAChE,WACE,EAAe,MAAM,MAAM,EAAE,YAAS,MAAO,EAAmB,KAAK;GACvE,MAAM,MAAO,EAAmB,QAAQ,GAAG,MAAM;EACnD,CAAC;yBAIC,EAkBgB,EAAA,CAAA,GAAA;eAjBL,EAAA;4CAAe,QAAA;GACxB,OAAM;GACL,SAAS,EAAA;GACV,WAAU;GACV,UAAA;;oBAYe,CAXf,EAWe,EAAA,CAAA,GAXf,EAWe;IAVb,OAAM;IACN,eAAY;IACZ,SAAQ;MACAA,EAAAA,MAAM,GAAA;qBAGR,CAFN,EAEM,OAFN,GAEM,EADD,EAAA,OAAiB,SAAK,mBAAA,GAAA,CAAA,GAE3B,EAEkB,EAAA,CAAA,GAAA;KADhB,OAAM;KACN,QAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate-client-options.js","names":[],"sources":["../../../src/code-example/helpers/generate-client-options.ts"],"sourcesContent":["import { AVAILABLE_CLIENTS, type AvailableClients, snippetz } from '@scalar/snippetz'\nimport type { XCodeSample } from '@scalar/workspace-store/schemas/extensions/operation'\nimport { capitalize } from 'vue'\n\nimport type { ClientOptionGroup } from '../types'\n\n/** Type of custom code sample IDs */\nexport type CustomCodeSampleId = `custom/${string}`\n\n/**\n * Build stable, language-keyed ids for an operation's custom code samples.\n *\n * Custom samples are defined per operation, but a selection (e.g. the Python SDK\n * example) should sync across every operation that ships the same language. So we\n * key the id by language rather than by position: the first sample of a language\n * becomes `custom/<lang>`, and any further samples that repeat a language fall back\n * to `custom/<lang>/<n>` so they stay individually selectable within the operation.\n *\n * The language is lower-cased so a selection still matches when operations (or\n * extensions) spell the same language with different casing (e.g. `Python` vs\n * `python`).\n *\n * @param samples - The custom code samples for a single operation\n * @returns A list of ids aligned by index with the input samples\n */\nexport const getCustomClientIds = (samples: XCodeSample[]): CustomCodeSampleId[] => {\n const countByLang = new Map<string, number>()\n\n return samples.map((sample): CustomCodeSampleId => {\n const lang = (sample.lang || 'plaintext').toLowerCase()\n const seen = countByLang.get(lang) ?? 0\n countByLang.set(lang, seen + 1)\n\n return seen === 0 ? `custom/${lang}` : `custom/${lang}/${seen}`\n })\n}\n\n/**\n * Generate client options for the request example block by filtering by allowed clients\n *\n * @param allowedClients - The list of allowed clients to include in the options\n * @returns A list of client option groups\n */\nexport const generateClientOptions = (allowedClients: AvailableClients = AVAILABLE_CLIENTS): ClientOptionGroup[] => {\n /** Create set of allowlist for quicker lookups */\n const allowedClientsSet = new Set(allowedClients)\n\n const options = snippetz()\n .clients()\n .flatMap((group) => {\n const options = group.clients.flatMap((plugin) => {\n const id = `${group.key}/${plugin.client}
|
|
1
|
+
{"version":3,"file":"generate-client-options.js","names":[],"sources":["../../../src/code-example/helpers/generate-client-options.ts"],"sourcesContent":["import { AVAILABLE_CLIENTS, type AvailableClients, snippetz } from '@scalar/snippetz'\nimport type { XCodeSample } from '@scalar/workspace-store/schemas/extensions/operation'\nimport { capitalize } from 'vue'\n\nimport type { ClientOptionGroup } from '../types'\n\n/** Type of custom code sample IDs */\nexport type CustomCodeSampleId = `custom/${string}`\n\n/**\n * Build stable, language-keyed ids for an operation's custom code samples.\n *\n * Custom samples are defined per operation, but a selection (e.g. the Python SDK\n * example) should sync across every operation that ships the same language. So we\n * key the id by language rather than by position: the first sample of a language\n * becomes `custom/<lang>`, and any further samples that repeat a language fall back\n * to `custom/<lang>/<n>` so they stay individually selectable within the operation.\n *\n * The language is lower-cased so a selection still matches when operations (or\n * extensions) spell the same language with different casing (e.g. `Python` vs\n * `python`).\n *\n * @param samples - The custom code samples for a single operation\n * @returns A list of ids aligned by index with the input samples\n */\nexport const getCustomClientIds = (samples: XCodeSample[]): CustomCodeSampleId[] => {\n const countByLang = new Map<string, number>()\n\n return samples.map((sample): CustomCodeSampleId => {\n const lang = (sample.lang || 'plaintext').toLowerCase()\n const seen = countByLang.get(lang) ?? 0\n countByLang.set(lang, seen + 1)\n\n return seen === 0 ? `custom/${lang}` : `custom/${lang}/${seen}`\n })\n}\n\n/**\n * Generate client options for the request example block by filtering by allowed clients\n *\n * @param allowedClients - The list of allowed clients to include in the options\n * @returns A list of client option groups\n */\nexport const generateClientOptions = (allowedClients: AvailableClients = AVAILABLE_CLIENTS): ClientOptionGroup[] => {\n /** Create set of allowlist for quicker lookups */\n const allowedClientsSet = new Set(allowedClients)\n\n const options = snippetz()\n .clients()\n .flatMap((group) => {\n const options = group.clients.flatMap((plugin) => {\n const id: AvailableClients[number] = `${group.key}/${plugin.client}`\n\n // If the client is not allowed, skip it\n if (!allowedClientsSet.has(id)) {\n return []\n }\n\n return {\n id,\n lang: plugin.client === 'curl' ? ('curl' as const) : group.key,\n title: `${capitalize(group.title)} ${plugin.title}`,\n label: plugin.title,\n targetKey: group.key,\n targetTitle: group.title,\n clientKey: plugin.client,\n }\n })\n\n // If no clients are allowed, skip this group\n if (options.length === 0) {\n return []\n }\n\n return {\n label: group.title,\n key: group.key,\n options,\n }\n })\n\n return options\n}\n"],"mappings":";;;AAyBA,IAAa,KAAsB,MAAiD;CAClF,IAAM,oBAAc,IAAI,IAAoB;CAE5C,OAAO,EAAQ,KAAK,MAA+B;EACjD,IAAM,KAAQ,EAAO,QAAQ,YAAA,CAAa,YAAY,GAChD,IAAO,EAAY,IAAI,CAAI,KAAK;EAGtC,OAFA,EAAY,IAAI,GAAM,IAAO,CAAC,GAEvB,MAAS,IAAI,UAAU,MAAS,UAAU,EAAK,GAAG;CAC3D,CAAC;AACH,GAQa,KAAyB,IAAmC,MAA2C;CAElH,IAAM,IAAoB,IAAI,IAAI,CAAc;CAoChD,OAlCgB,EAAS,CAAC,CACvB,QAAQ,CAAC,CACT,SAAS,MAAU;EAClB,IAAM,IAAU,EAAM,QAAQ,SAAS,MAAW;GAChD,IAAM,IAA+B,GAAG,EAAM,IAAI,GAAG,EAAO;GAO5D,OAJK,EAAkB,IAAI,CAAE,IAItB;IACL;IACA,MAAM,EAAO,WAAW,SAAU,SAAmB,EAAM;IAC3D,OAAO,GAAG,EAAW,EAAM,KAAK,EAAE,GAAG,EAAO;IAC5C,OAAO,EAAO;IACd,WAAW,EAAM;IACjB,aAAa,EAAM;IACnB,WAAW,EAAO;GACpB,IAXS,CAAC;EAYZ,CAAC;EAOD,OAJI,EAAQ,WAAW,IACd,CAAC,IAGH;GACL,OAAO,EAAM;GACb,KAAK,EAAM;GACX;EACF;CACF,CAEK;AACT"}
|
|
@@ -3,7 +3,7 @@ import type { AvailableClient } from '@scalar/snippetz';
|
|
|
3
3
|
import type { SecuritySchemeObjectSecret } from '@scalar/workspace-store/request-example';
|
|
4
4
|
import type { XScalarCookie } from '@scalar/workspace-store/schemas/extensions/general/x-scalar-cookies';
|
|
5
5
|
import type { XCodeSample } from '@scalar/workspace-store/schemas/extensions/operation';
|
|
6
|
-
import type { OperationObject, ServerObject } from '@scalar/workspace-store/schemas/v3.
|
|
6
|
+
import type { OperationObject, ServerObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document';
|
|
7
7
|
import { type CustomCodeSampleId } from './generate-client-options';
|
|
8
8
|
type GenerateCodeSnippetProps = {
|
|
9
9
|
/** The selected client/language for code generation (e.g., 'node/fetch') or a custom code sample ID. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate-code-snippet.js","names":[],"sources":["../../../src/code-example/helpers/generate-code-snippet.ts"],"sourcesContent":["import type { HttpMethod } from '@scalar/helpers/http/http-methods'\nimport type { AvailableClient, ClientId, TargetId } from '@scalar/snippetz'\nimport type { SecuritySchemeObjectSecret } from '@scalar/workspace-store/request-example'\nimport type { XScalarCookie } from '@scalar/workspace-store/schemas/extensions/general/x-scalar-cookies'\nimport type { XCodeSample } from '@scalar/workspace-store/schemas/extensions/operation'\nimport type { OperationObject, ServerObject } from '@scalar/workspace-store/schemas/v3.
|
|
1
|
+
{"version":3,"file":"generate-code-snippet.js","names":[],"sources":["../../../src/code-example/helpers/generate-code-snippet.ts"],"sourcesContent":["import type { HttpMethod } from '@scalar/helpers/http/http-methods'\nimport type { AvailableClient, ClientId, TargetId } from '@scalar/snippetz'\nimport type { SecuritySchemeObjectSecret } from '@scalar/workspace-store/request-example'\nimport type { XScalarCookie } from '@scalar/workspace-store/schemas/extensions/general/x-scalar-cookies'\nimport type { XCodeSample } from '@scalar/workspace-store/schemas/extensions/operation'\nimport type { OperationObject, ServerObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\n\nimport { type CustomCodeSampleId, getCustomClientIds } from './generate-client-options'\nimport { getSnippet } from './get-snippet'\nimport { operationToHar } from './operation-to-har/operation-to-har'\n\ntype GenerateCodeSnippetProps = {\n /** The selected client/language for code generation (e.g., 'node/fetch') or a custom code sample ID. */\n clientId: AvailableClient | CustomCodeSampleId | undefined\n /** The Content-Type header value for the request body (e.g., 'application/json'). */\n contentType: string | undefined\n /** Array of custom code samples defined in the OpenAPI x-codeSamples extension. */\n customCodeSamples: XCodeSample[]\n /** The specific example value to use when generating the code snippet. */\n example: string | undefined\n /** The HTTP method for the operation (e.g., GET, POST, PUT). */\n method: HttpMethod\n /** The OpenAPI operation object containing request/response details. */\n operation: OperationObject\n /** The API endpoint path (e.g., '/users/{id}'). */\n path: string\n /** Array of security schemes to apply to the request (e.g., API keys, OAuth). */\n securitySchemes: SecuritySchemeObjectSecret[]\n /** The server object defining the base URL for the API request. */\n server: ServerObject | null\n /** Workspace + document cookies */\n globalCookies?: XScalarCookie[]\n /** Whether to include default headers (e.g., Accept, Content-Type) automatically. */\n includeDefaultHeaders?: boolean\n /** Selected oneOf/anyOf variants for nested request body example generation. */\n requestBodyCompositionSelection?: Record<string, number>\n /** Whether to disable parameters by default. */\n defaultDisabledParameters?: boolean\n}\n\n/** Generate the code snippet for the selected example OR operation */\nexport const generateCodeSnippet = ({\n clientId,\n customCodeSamples,\n includeDefaultHeaders = false,\n operation,\n method,\n path,\n example,\n contentType,\n server,\n securitySchemes,\n globalCookies,\n requestBodyCompositionSelection,\n defaultDisabledParameters,\n}: GenerateCodeSnippetProps): string => {\n try {\n if (!clientId) {\n return ''\n }\n\n // Use the selected custom example, matched by its language-keyed id\n if (clientId.startsWith('custom')) {\n const ids = getCustomClientIds(customCodeSamples)\n const index = ids.indexOf(clientId as CustomCodeSampleId)\n\n return customCodeSamples[index]?.source ?? 'Custom example not found'\n }\n\n const harRequest = operationToHar({\n operation,\n contentType,\n method,\n path,\n server,\n securitySchemes,\n example,\n globalCookies,\n includeDefaultHeaders,\n requestBodyCompositionSelection,\n defaultDisabledParameters,\n })\n\n const [targetKey, clientKey] = clientId.split('/') as [TargetId, ClientId<TargetId>]\n\n const [error, payload] = getSnippet(targetKey, clientKey, harRequest)\n if (error) {\n console.error('[generateCodeSnippet]', error)\n return error.message ?? 'Error generating code snippet'\n }\n\n return payload\n } catch (error) {\n console.error('[generateCodeSnippet]', error)\n return 'Error generating code snippet'\n }\n}\n"],"mappings":";;;;AAyCA,IAAa,KAAuB,EAClC,aACA,sBACA,2BAAwB,IACxB,cACA,WACA,SACA,YACA,gBACA,WACA,oBACA,kBACA,oCACA,mCACsC;CACtC,IAAI;EACF,IAAI,CAAC,GACH,OAAO;EAIT,IAAI,EAAS,WAAW,QAAQ,GAI9B,OAAO,EAHK,EAAmB,CACjB,CAAA,CAAI,QAAQ,CAED,EAAM,EAAE,UAAU;EAG7C,IAAM,IAAa,EAAe;GAChC;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;EACF,CAAC,GAEK,CAAC,GAAW,KAAa,EAAS,MAAM,GAAG,GAE3C,CAAC,GAAO,KAAW,EAAW,GAAW,GAAW,CAAU;EAMpE,OALI,KACF,QAAQ,MAAM,yBAAyB,CAAK,GACrC,EAAM,WAAW,mCAGnB;CACT,SAAS,GAAO;EAEd,OADA,QAAQ,MAAM,yBAAyB,CAAK,GACrC;CACT;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { XCodeSample } from '@scalar/workspace-store/schemas/extensions/operation';
|
|
2
|
-
import type { OperationObject } from '@scalar/workspace-store/schemas/v3.
|
|
2
|
+
import type { OperationObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document';
|
|
3
3
|
/** Picker group label for samples generated by an SDK provider (Scalar, Stainless, …). */
|
|
4
4
|
declare const SDK_GROUP_LABEL = "SDK";
|
|
5
5
|
/** Picker group label for generic or docs-platform samples (the standard `x-codeSamples` family, ReadMe, …). */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"get-custom-code-samples.js","names":[],"sources":["../../../src/code-example/helpers/get-custom-code-samples.ts"],"sourcesContent":["import type {\n XCodeSample,\n XLanguageExample,\n XReadmeCodeSample,\n} from '@scalar/workspace-store/schemas/extensions/operation'\nimport type { OperationObject } from '@scalar/workspace-store/schemas/v3.
|
|
1
|
+
{"version":3,"file":"get-custom-code-samples.js","names":[],"sources":["../../../src/code-example/helpers/get-custom-code-samples.ts"],"sourcesContent":["import type {\n XCodeSample,\n XLanguageExample,\n XReadmeCodeSample,\n} from '@scalar/workspace-store/schemas/extensions/operation'\nimport type { OperationObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\n\n/** Turns a `{ language: source }` map (x-stainless-snippets) into code samples. */\nconst fromSnippetMap = (snippets: Record<string, string> | undefined, label?: string): XCodeSample[] =>\n Object.entries(snippets ?? {}).map(([lang, source]) => ({ lang, source, ...(label ? { label } : {}) }))\n\n/**\n * Turns `x-stainless-examples` / `x-scalar-examples` into code samples.\n *\n * Each example carries per-language request snippets and an optional title that\n * we surface as the picker label. The response is only used for documentation,\n * so it is ignored here.\n */\nconst fromLanguageExamples = (examples: XLanguageExample | XLanguageExample[] | undefined): XCodeSample[] => {\n if (!examples) {\n return []\n }\n\n return (Array.isArray(examples) ? examples : [examples]).flatMap((example) =>\n fromSnippetMap(example.request, example.title),\n )\n}\n\n/** Turns ReadMe's `x-readme.code-samples` into code samples. */\nconst fromReadmeSamples = (samples: XReadmeCodeSample[] | undefined): XCodeSample[] =>\n (samples ?? []).map((sample) => ({\n lang: sample.language,\n source: sample.code,\n ...(sample.name ? { label: sample.name } : {}),\n }))\n\n/** Picker group label for samples generated by an SDK provider (Scalar, Stainless, …). */\nconst SDK_GROUP_LABEL = 'SDK'\n\n/** Picker group label for generic or docs-platform samples (the standard `x-codeSamples` family, ReadMe, …). */\nexport const CODE_EXAMPLES_GROUP_LABEL = 'Code Examples'\n\ntype CustomCodeSampleGroupLabel = typeof SDK_GROUP_LABEL | typeof CODE_EXAMPLES_GROUP_LABEL\n\ntype CustomCodeSamples = {\n /**\n * Group label for the code sample picker.\n *\n * Samples that come from an SDK provider extension (`x-scalar-examples`,\n * `x-stainless-snippets`, `x-stainless-examples`) surface under \"SDK\". Generic\n * or docs-platform samples (`x-readme`, the `x-codeSamples` family) surface\n * under \"Code Examples\".\n */\n label: CustomCodeSampleGroupLabel\n /** The custom code samples, in picker order. */\n samples: XCodeSample[]\n}\n\n/**\n * Grabs any custom code samples from the operation.\n *\n * Several tools write code samples into OpenAPI under different extensions. When\n * more than one is present we use the highest-priority source only, rather than\n * showing duplicates from every tool. Priority, highest first:\n *\n * 1. `x-scalar-examples` (SDK)\n * 2. `x-stainless-snippets` (SDK, overrides `x-stainless-examples`)\n * 3. `x-stainless-examples` (SDK)\n * 4. `x-readme.code-samples` (Code Examples)\n * 5. `x-codeSamples` / `x-code-samples` / `x-custom-examples` (Code Examples)\n *\n * The winning source also determines the picker group label: SDK-provider\n * extensions surface under \"SDK\", everything else under \"Code Examples\".\n *\n * Note that Speakeasy does not have its own extension — it writes into the\n * standard `x-codeSamples`, so its snippets surface under \"Code Examples\".\n *\n * @param operation - The operation to get the custom code samples from\n * @returns The picker group label and the custom code samples which exist in the operation\n */\nexport const getCustomCodeSamples = (operation: OperationObject): CustomCodeSamples => {\n const scalarExamples = operation['x-scalar-examples'] ?? []\n if (scalarExamples.length) {\n return { label: SDK_GROUP_LABEL, samples: scalarExamples }\n }\n\n const stainlessSnippets = fromSnippetMap(operation['x-stainless-snippets'])\n if (stainlessSnippets.length) {\n return { label: SDK_GROUP_LABEL, samples: stainlessSnippets }\n }\n\n const stainlessExamples = fromLanguageExamples(operation['x-stainless-examples'])\n if (stainlessExamples.length) {\n return { label: SDK_GROUP_LABEL, samples: stainlessExamples }\n }\n\n const readmeSamples = fromReadmeSamples(operation['x-readme']?.['code-samples'])\n if (readmeSamples.length) {\n return { label: CODE_EXAMPLES_GROUP_LABEL, samples: readmeSamples }\n }\n\n const customCodeKeys = ['x-custom-examples', 'x-codeSamples', 'x-code-samples'] as const\n return { label: CODE_EXAMPLES_GROUP_LABEL, samples: customCodeKeys.flatMap((key) => operation[key] ?? []) }\n}\n"],"mappings":";AAQA,IAAM,KAAkB,GAA8C,MACpE,OAAO,QAAQ,KAAY,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAM,QAAa;CAAE;CAAM;CAAQ,GAAI,IAAQ,EAAE,SAAM,IAAI,CAAC;AAAG,EAAE,GASlG,KAAwB,MACvB,KAIG,MAAM,QAAQ,CAAQ,IAAI,IAAW,CAAC,CAAQ,EAAA,CAAG,SAAS,MAChE,EAAe,EAAQ,SAAS,EAAQ,KAAK,CAC/C,IALS,CAAC,GASN,KAAqB,OACxB,KAAW,CAAC,EAAA,CAAG,KAAK,OAAY;CAC/B,MAAM,EAAO;CACb,QAAQ,EAAO;CACf,GAAI,EAAO,OAAO,EAAE,OAAO,EAAO,KAAK,IAAI,CAAC;AAC9C,EAAE,GAGE,IAAkB,OAGX,IAA4B,iBAwC5B,KAAwB,MAAkD;CACrF,IAAM,IAAiB,EAAU,wBAAwB,CAAC;CAC1D,IAAI,EAAe,QACjB,OAAO;EAAE,OAAO;EAAiB,SAAS;CAAe;CAG3D,IAAM,IAAoB,EAAe,EAAU,uBAAuB;CAC1E,IAAI,EAAkB,QACpB,OAAO;EAAE,OAAO;EAAiB,SAAS;CAAkB;CAG9D,IAAM,IAAoB,EAAqB,EAAU,uBAAuB;CAChF,IAAI,EAAkB,QACpB,OAAO;EAAE,OAAO;EAAiB,SAAS;CAAkB;CAG9D,IAAM,IAAgB,EAAkB,EAAU,WAAW,GAAG,eAAe;CAM/E,OALI,EAAc,SACT;EAAE,OAAO;EAA2B,SAAS;CAAc,IAI7D;EAAE,OAAO;EAA2B,SAAS;GAD5B;GAAqB;GAAiB;EACV,CAAA,CAAe,SAAS,MAAQ,EAAU,MAAQ,CAAC,CAAC;CAAE;AAC5G"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"get-snippet.js","names":[],"sources":["../../../src/code-example/helpers/get-snippet.ts"],"sourcesContent":["import type { ErrorResponse } from '@scalar/helpers/errors/normalize-error'\nimport { type ClientId, type TargetId, snippetz } from '@scalar/snippetz'\nimport type { Request as HarRequest } from 'har-format'\n\n/** Key used to hack around the invalid urls */\nconst INVALID_URLS_PREFIX = 'ws://replace.me'\n\n/**\n * Returns a code example for given operation\n */\nexport const getSnippet = <T extends TargetId>(\n target: T | 'javascript',\n client: ClientId<T>,\n harRequest: HarRequest,\n): ErrorResponse<string> => {\n try {\n if (!harRequest.url) {\n return [new Error('Please enter a URL to see a code snippet'), null]\n }\n\n const separator = harRequest.url.startsWith('/') ? '' : '/'\n\n // Hack to get around invalid URLS until we update the snippets lib\n try {\n new URL(harRequest.url)\n } catch {\n harRequest.url = `${INVALID_URLS_PREFIX}${separator}${harRequest.url}`\n }\n\n // Ensure we have valid JSON\n if (harRequest.postData?.mimeType === 'application/json') {\n try {\n JSON.parse(harRequest.postData.text || '{}')\n } catch (error) {\n console.error('[getSnippet] Invalid JSON body', error)\n return [new Error('Invalid JSON body'), null]\n }\n }\n // TODO: Fix this, use js (instead of javascript) everywhere\n const snippetzTargetKey = target.replace('javascript', 'js') as TargetId\n\n if (snippetz().hasPlugin(snippetzTargetKey, client)) {\n const payload = snippetz().print(snippetzTargetKey, client
|
|
1
|
+
{"version":3,"file":"get-snippet.js","names":[],"sources":["../../../src/code-example/helpers/get-snippet.ts"],"sourcesContent":["import type { ErrorResponse } from '@scalar/helpers/errors/normalize-error'\nimport { type ClientId, type TargetId, snippetz } from '@scalar/snippetz'\nimport type { Request as HarRequest } from 'har-format'\n\n/** Key used to hack around the invalid urls */\nconst INVALID_URLS_PREFIX = 'ws://replace.me'\n\n/**\n * Returns a code example for given operation\n */\nexport const getSnippet = <T extends TargetId>(\n target: T | 'javascript',\n client: ClientId<T>,\n harRequest: HarRequest,\n): ErrorResponse<string> => {\n try {\n if (!harRequest.url) {\n return [new Error('Please enter a URL to see a code snippet'), null]\n }\n\n const separator = harRequest.url.startsWith('/') ? '' : '/'\n\n // Hack to get around invalid URLS until we update the snippets lib\n try {\n new URL(harRequest.url)\n } catch {\n harRequest.url = `${INVALID_URLS_PREFIX}${separator}${harRequest.url}`\n }\n\n // Ensure we have valid JSON\n if (harRequest.postData?.mimeType === 'application/json') {\n try {\n JSON.parse(harRequest.postData.text || '{}')\n } catch (error) {\n console.error('[getSnippet] Invalid JSON body', error)\n return [new Error('Invalid JSON body'), null]\n }\n }\n // TODO: Fix this, use js (instead of javascript) everywhere\n const snippetzTargetKey = target.replace('javascript', 'js') as TargetId\n\n if (snippetz().hasPlugin(snippetzTargetKey, client)) {\n const payload = snippetz().print(snippetzTargetKey, client, harRequest)\n if (!payload) {\n return [new Error('Error generating snippet'), null]\n }\n\n return [null, payload.replace(`${INVALID_URLS_PREFIX}${separator}`, '')]\n }\n } catch (error) {\n console.error('[getSnippet] Error generating snippet', error)\n return [new Error('Error generating snippet'), null]\n }\n\n return [new Error('No snippet found'), null]\n}\n"],"mappings":";;AAKA,IAAM,IAAsB,mBAKf,KACX,GACA,GACA,MAC0B;CAC1B,IAAI;EACF,IAAI,CAAC,EAAW,KACd,OAAO,CAAC,gBAAI,MAAM,0CAA0C,GAAG,IAAI;EAGrE,IAAM,IAAY,EAAW,IAAI,WAAW,GAAG,IAAI,KAAK;EAGxD,IAAI;GACF,IAAI,IAAI,EAAW,GAAG;EACxB,QAAQ;GACN,EAAW,MAAM,GAAG,IAAsB,IAAY,EAAW;EACnE;EAGA,IAAI,EAAW,UAAU,aAAa,oBACpC,IAAI;GACF,KAAK,MAAM,EAAW,SAAS,QAAQ,IAAI;EAC7C,SAAS,GAAO;GAEd,OADA,QAAQ,MAAM,kCAAkC,CAAK,GAC9C,CAAC,gBAAI,MAAM,mBAAmB,GAAG,IAAI;EAC9C;EAGF,IAAM,IAAoB,EAAO,QAAQ,cAAc,IAAI;EAE3D,IAAI,EAAS,CAAC,CAAC,UAAU,GAAmB,CAAM,GAAG;GACnD,IAAM,IAAU,EAAS,CAAC,CAAC,MAAM,GAAmB,GAAQ,CAAU;GAKtE,OAJK,IAIE,CAAC,MAAM,EAAQ,QAAQ,GAAG,IAAsB,KAAa,EAAE,CAAC,IAH9D,CAAC,gBAAI,MAAM,0BAA0B,GAAG,IAAI;EAIvD;CACF,SAAS,GAAO;EAEd,OADA,QAAQ,MAAM,yCAAyC,CAAK,GACrD,CAAC,gBAAI,MAAM,0BAA0B,GAAG,IAAI;CACrD;CAEA,OAAO,CAAC,gBAAI,MAAM,kBAAkB,GAAG,IAAI;AAC7C"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { HttpMethod } from '@scalar/helpers/http/http-methods';
|
|
2
2
|
import { type SecuritySchemeObjectSecret } from '@scalar/workspace-store/request-example';
|
|
3
3
|
import type { XScalarCookie } from '@scalar/workspace-store/schemas/extensions/general/x-scalar-cookies';
|
|
4
|
-
import type { OperationObject, ServerObject } from '@scalar/workspace-store/schemas/v3.
|
|
4
|
+
import type { OperationObject, ServerObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document';
|
|
5
5
|
import type { Request as HarRequest } from 'har-format';
|
|
6
6
|
export type OperationToHarProps = {
|
|
7
7
|
/** OpenAPI Operation object */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"operation-to-har.js","names":[],"sources":["../../../../src/code-example/helpers/operation-to-har/operation-to-har.ts"],"sourcesContent":["import { isElectron } from '@scalar/helpers/general/is-electron'\nimport type { HttpMethod } from '@scalar/helpers/http/http-methods'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport {\n type SecuritySchemeObjectSecret,\n filterGlobalCookie,\n getDefaultHeaders,\n restoreConventionalDefaultHeaderNames,\n} from '@scalar/workspace-store/request-example'\nimport type { XScalarCookie } from '@scalar/workspace-store/schemas/extensions/general/x-scalar-cookies'\nimport type { OperationObject, ServerObject } from '@scalar/workspace-store/schemas/v3.
|
|
1
|
+
{"version":3,"file":"operation-to-har.js","names":[],"sources":["../../../../src/code-example/helpers/operation-to-har/operation-to-har.ts"],"sourcesContent":["import { isElectron } from '@scalar/helpers/general/is-electron'\nimport type { HttpMethod } from '@scalar/helpers/http/http-methods'\nimport { getResolvedRef } from '@scalar/workspace-store/helpers/get-resolved-ref'\nimport {\n type SecuritySchemeObjectSecret,\n filterGlobalCookie,\n getDefaultHeaders,\n restoreConventionalDefaultHeaderNames,\n} from '@scalar/workspace-store/request-example'\nimport type { XScalarCookie } from '@scalar/workspace-store/schemas/extensions/general/x-scalar-cookies'\nimport type { OperationObject, ServerObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document'\nimport type { Request as HarRequest } from 'har-format'\n\nimport { APP_VERSION } from '@/constants'\n\nimport { processBody } from './process-body'\nimport { processParameters } from './process-parameters'\nimport { processSecuritySchemes } from './process-security-schemes'\nimport { processServerUrl } from './process-server-url'\n\nexport type OperationToHarProps = {\n /** OpenAPI Operation object */\n operation: OperationObject\n /** HTTP method of the operation */\n method: HttpMethod\n /** Path of the operation */\n path: string\n /**\n * Name of the currently selected operation example\n *\n * Applies to both the body and the parameters\n */\n example?: string\n /**\n * Content type of the operation\n *\n * Applies to both the body and the parameters (if applicable)\n * @defaults to the first content type in the MediaTypeObject\n */\n contentType?: string\n /** OpenAPI Server object */\n server?: ServerObject | null\n /** OpenAPI SecurityScheme objects which are applicable to the operation */\n securitySchemes?: SecuritySchemeObjectSecret[]\n /** Workspace + document cookies */\n globalCookies?: XScalarCookie[]\n /**\n * Whether to include default headers (e.g., Accept, Content-Type) automatically.\n * If false, default headers will be omitted from the HAR request.\n * @default true\n */\n includeDefaultHeaders?: boolean\n /**\n * Selected oneOf/anyOf variants for nested request body example generation\n * (e.g. from the schema dropdowns in the API reference).\n */\n requestBodyCompositionSelection?: Record<string, number>\n /**\n * Whether to disable parameters by default.\n * @default false\n */\n defaultDisabledParameters?: boolean\n}\n\n/**\n * Converts an OpenAPI Operation to a HarRequest format for generating HTTP request snippets.\n *\n * This function transforms OpenAPI 3.1 operation objects into HAR (HTTP Archive) format requests,\n * which can be used to generate code snippets for various programming languages and HTTP clients.\n *\n * The conversion handles:\n * - Server URL processing and path parameter substitution\n * - Query parameter formatting based on OpenAPI parameter styles\n * - Request body processing with content type handling\n * - Security scheme integration (API keys, etc.)\n *\n * The resulting HarRequest object follows the HAR specification and includes:\n * - HTTP method and URL\n * - Headers and query parameters\n * - Request body (if present)\n * - Cookie information\n * - Size calculations for headers and body\n *\n * @see https://w3c.github.io/web-performance/specs/HAR/Overview.html\n * @see https://spec.openapis.org/oas/v3.1.0#operation-object\n */\nexport const operationToHar = ({\n includeDefaultHeaders = false,\n operation,\n contentType,\n method,\n path,\n server = null,\n example,\n securitySchemes,\n globalCookies,\n requestBodyCompositionSelection,\n defaultDisabledParameters = false,\n}: OperationToHarProps): HarRequest => {\n const defaultHeaders = includeDefaultHeaders\n ? getDefaultHeaders({\n method,\n operation,\n exampleName: example ?? 'default',\n hideDisabledHeaders: true,\n hideOverriddenHeaders: true,\n options: { isElectron: isElectron(), appVersion: APP_VERSION },\n })\n : {}\n const defaultHeadersWithConventionalNames = restoreConventionalDefaultHeaderNames(defaultHeaders)\n\n const disabledGlobalCookies =\n operation['x-scalar-disable-parameters']?.['global-cookies']?.[example ?? 'default'] ?? {}\n\n const serverUrl = processServerUrl(server, path)\n\n // Initialize the HAR request with basic properties\n const harRequest: HarRequest = {\n method,\n url: serverUrl,\n headers: Object.entries(defaultHeadersWithConventionalNames).map(([name, value]) => ({ name, value })),\n queryString: [],\n postData: undefined,\n httpVersion: 'HTTP/1.1',\n cookies: [],\n headersSize: -1,\n bodySize: -1,\n }\n\n // Handle parameters\n if (operation.parameters) {\n const { url, headers, queryString, cookies } = processParameters({\n harRequest,\n parameters: operation.parameters,\n example,\n defaultDisabled: defaultDisabledParameters,\n })\n\n // Correctly filter the global cookies by the processed url\n const filteredGlobalCookies =\n globalCookies\n ?.filter((cookie) => filterGlobalCookie({ cookie, url, disabledGlobalCookies }))\n ?.map((cookie) => ({ name: cookie.name, value: cookie.value })) ?? []\n\n harRequest.url = url\n harRequest.headers = headers\n harRequest.queryString = queryString\n harRequest.cookies = [...filteredGlobalCookies, ...cookies]\n }\n\n const body = getResolvedRef(operation.requestBody)\n\n // Handle request body\n if (body?.content) {\n const postData = processBody({\n requestBody: body,\n contentType,\n example,\n requestBodyCompositionSelection,\n })\n\n if (postData) {\n harRequest.postData = postData\n harRequest.bodySize = postData.text?.length ?? -1\n\n // Add or update Content-Type header\n if (postData.mimeType) {\n const existingContentTypeHeader = harRequest.headers.find(\n (header) => header.name.toLowerCase() === 'content-type',\n )\n // Update existing header if it has an empty value\n if (existingContentTypeHeader && !existingContentTypeHeader.value) {\n existingContentTypeHeader.value = postData.mimeType\n }\n // Add new header if none exists\n else if (!existingContentTypeHeader) {\n harRequest.headers.push({\n name: 'Content-Type',\n value: postData.mimeType,\n })\n }\n }\n }\n }\n\n // Handle security schemes\n if (securitySchemes) {\n const { headers, queryString, cookies } = processSecuritySchemes(securitySchemes)\n harRequest.headers.push(...headers)\n harRequest.queryString.push(...queryString)\n harRequest.cookies.push(...cookies)\n }\n\n // Calculate headers size without allocating a large joined string\n let headersSize = 0\n for (const h of harRequest.headers) {\n // name + \": \" + value + \"\\r\\n\"\n headersSize += (h.name?.length ?? 0) + 2 + (h.value?.length ?? 0) + 2\n }\n harRequest.headersSize = headersSize\n\n return harRequest\n}\n"],"mappings":";;;;;;;;;AAsFA,IAAa,KAAkB,EAC7B,2BAAwB,IACxB,cACA,gBACA,WACA,SACA,YAAS,MACT,YACA,oBACA,kBACA,oCACA,+BAA4B,SACS;CAWrC,IAAM,IAAsC,EAVrB,IACnB,EAAkB;EAChB;EACA;EACA,aAAa,KAAW;EACxB,qBAAqB;EACrB,uBAAuB;EACvB,SAAS;GAAE,YAAY,EAAW;GAAG,YAAY;EAAY;CAC/D,CAAC,IACD,CAAC,CAC2F,GAE1F,IACJ,EAAU,8BAA8B,GAAG,iBAAiB,GAAG,KAAW,cAAc,CAAC,GAKrF,IAAyB;EAC7B;EACA,KALgB,EAAiB,GAAQ,CAKpC;EACL,SAAS,OAAO,QAAQ,CAAmC,CAAC,CAAC,KAAK,CAAC,GAAM,QAAY;GAAE;GAAM;EAAM,EAAE;EACrG,aAAa,CAAC;EACd,UAAU,KAAA;EACV,aAAa;EACb,SAAS,CAAC;EACV,aAAa;EACb,UAAU;CACZ;CAGA,IAAI,EAAU,YAAY;EACxB,IAAM,EAAE,QAAK,YAAS,gBAAa,eAAY,EAAkB;GAC/D;GACA,YAAY,EAAU;GACtB;GACA,iBAAiB;EACnB,CAAC,GAGK,IACJ,GACI,QAAQ,MAAW,EAAmB;GAAE;GAAQ;GAAK;EAAsB,CAAC,CAAC,CAAC,EAC9E,KAAK,OAAY;GAAE,MAAM,EAAO;GAAM,OAAO,EAAO;EAAM,EAAE,KAAK,CAAC;EAKxE,AAHA,EAAW,MAAM,GACjB,EAAW,UAAU,GACrB,EAAW,cAAc,GACzB,EAAW,UAAU,CAAC,GAAG,GAAuB,GAAG,CAAO;CAC5D;CAEA,IAAM,IAAO,EAAe,EAAU,WAAW;CAGjD,IAAI,GAAM,SAAS;EACjB,IAAM,IAAW,EAAY;GAC3B,aAAa;GACb;GACA;GACA;EACF,CAAC;EAED,IAAI,MACF,EAAW,WAAW,GACtB,EAAW,WAAW,EAAS,MAAM,UAAU,IAG3C,EAAS,WAAU;GACrB,IAAM,IAA4B,EAAW,QAAQ,MAClD,MAAW,EAAO,KAAK,YAAY,MAAM,cAC5C;GAEA,AAAI,KAA6B,CAAC,EAA0B,QAC1D,EAA0B,QAAQ,EAAS,WAGnC,KACR,EAAW,QAAQ,KAAK;IACtB,MAAM;IACN,OAAO,EAAS;GAClB,CAAC;EAEL;CAEJ;CAGA,IAAI,GAAiB;EACnB,IAAM,EAAE,YAAS,gBAAa,eAAY,EAAuB,CAAe;EAGhF,AAFA,EAAW,QAAQ,KAAK,GAAG,CAAO,GAClC,EAAW,YAAY,KAAK,GAAG,CAAW,GAC1C,EAAW,QAAQ,KAAK,GAAG,CAAO;CACpC;CAGA,IAAI,IAAc;CAClB,KAAK,IAAM,KAAK,EAAW,SAEzB,MAAgB,EAAE,MAAM,UAAU,KAAK,KAAK,EAAE,OAAO,UAAU,KAAK;CAItE,OAFA,EAAW,cAAc,GAElB;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { RequestBodyObject } from '@scalar/workspace-store/schemas/v3.
|
|
1
|
+
import type { RequestBodyObject } from '@scalar/workspace-store/schemas/v3.2/strict/openapi-document';
|
|
2
2
|
import type { PostData } from 'har-format';
|
|
3
3
|
import type { OperationToHarProps } from './operation-to-har';
|
|
4
4
|
type ProcessBodyProps = Pick<OperationToHarProps, 'contentType' | 'example' | 'requestBodyCompositionSelection'> & {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"process-body.d.ts","sourceRoot":"","sources":["../../../../src/code-example/helpers/operation-to-har/process-body.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"process-body.d.ts","sourceRoot":"","sources":["../../../../src/code-example/helpers/operation-to-har/process-body.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAEV,iBAAiB,EAElB,MAAM,8DAA8D,CAAA;AACrE,OAAO,KAAK,EAAS,QAAQ,EAAE,MAAM,YAAY,CAAA;AAEjD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAA;AAE7D,KAAK,gBAAgB,GAAG,IAAI,CAAC,mBAAmB,EAAE,aAAa,GAAG,SAAS,GAAG,iCAAiC,CAAC,GAAG;IACjH,WAAW,EAAE,iBAAiB,CAAA;CAC/B,CAAA;AA8JD;;;GAGG;AACH,eAAO,MAAM,WAAW,GAAI,yEAKzB,gBAAgB,KAAG,QAAQ,GAAG,SA+FhC,CAAA"}
|