@executor-js/plugin-openapi 1.4.28 → 1.4.30
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/dist/{AddOpenApiSource-FLMNI742.js → AddOpenApiSource-KSOMPQ2R.js} +4 -4
- package/dist/{EditOpenApiSource-I4NIGIIJ.js → EditOpenApiSource-AOA7APR2.js} +301 -192
- package/dist/EditOpenApiSource-AOA7APR2.js.map +1 -0
- package/dist/{OpenApiSourceSummary-CM46DB4L.js → OpenApiSourceSummary-Y3S6ZBOZ.js} +4 -4
- package/dist/OpenApiSourceSummary-Y3S6ZBOZ.js.map +1 -0
- package/dist/api/group.d.ts +124 -118
- package/dist/api/index.d.ts +148 -369
- package/dist/chunk-BB5IAKRG.js +136 -0
- package/dist/chunk-BB5IAKRG.js.map +1 -0
- package/dist/{chunk-E7PZ2QGD.js → chunk-EOXXE5DG.js} +17 -455
- package/dist/chunk-EOXXE5DG.js.map +1 -0
- package/dist/{chunk-OZ67JNID.js → chunk-NIKLYJ3X.js} +830 -319
- package/dist/chunk-NIKLYJ3X.js.map +1 -0
- package/dist/{chunk-TGDT6QCH.js → chunk-YJMXYKYX.js} +178 -117
- package/dist/chunk-YJMXYKYX.js.map +1 -0
- package/dist/{chunk-GFQUEZUW.js → chunk-ZZBTLFTA.js} +78 -93
- package/dist/chunk-ZZBTLFTA.js.map +1 -0
- package/dist/client.js +7 -137
- package/dist/client.js.map +1 -1
- package/dist/core.js +5 -10
- package/dist/index.js +3 -2
- package/dist/react/atoms.d.ts +83 -223
- package/dist/react/client.d.ts +123 -117
- package/dist/sdk/credential-status.d.ts +3 -3
- package/dist/sdk/extract.d.ts +19 -19
- package/dist/sdk/index.d.ts +2 -2
- package/dist/sdk/invoke.d.ts +7 -7
- package/dist/sdk/parse.d.ts +2 -3
- package/dist/sdk/plugin.d.ts +181 -275
- package/dist/sdk/preview.d.ts +12 -12
- package/dist/sdk/source-contracts.d.ts +55 -0
- package/dist/sdk/store.d.ts +6 -269
- package/dist/sdk/types.d.ts +16 -65
- package/dist/testing/index.d.ts +149 -11
- package/dist/testing.js +419 -33
- package/dist/testing.js.map +1 -1
- package/dist/testing.test.d.ts +1 -0
- package/package.json +3 -4
- package/dist/EditOpenApiSource-I4NIGIIJ.js.map +0 -1
- package/dist/OpenApiSourceSummary-CM46DB4L.js.map +0 -1
- package/dist/chunk-E7PZ2QGD.js.map +0 -1
- package/dist/chunk-GFQUEZUW.js.map +0 -1
- package/dist/chunk-OZ67JNID.js.map +0 -1
- package/dist/chunk-TGDT6QCH.js.map +0 -1
- /package/dist/{AddOpenApiSource-FLMNI742.js.map → AddOpenApiSource-KSOMPQ2R.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react/EditOpenApiSource.tsx"],"sourcesContent":["import { useEffect, useMemo, useRef, useState } from \"react\";\nimport { useAtomSet, useAtomValue } from \"@effect/atom-react\";\nimport * as Exit from \"effect/Exit\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as AsyncResult from \"effect/unstable/reactivity/AsyncResult\";\n\nimport { connectionsAtom, sourceAtom, startOAuth } from \"@executor-js/react/api/atoms\";\nimport { useScope, useScopeStack, useUserScope } from \"@executor-js/react/api/scope-context\";\nimport { connectionWriteKeys, sourceWriteKeys } from \"@executor-js/react/api/reactivity-keys\";\nimport { Button } from \"@executor-js/react/components/button\";\nimport { CopyButton } from \"@executor-js/react/components/copy-button\";\nimport {\n CardStack,\n CardStackContent,\n CardStackEntry,\n CardStackEntryContent,\n CardStackEntryDescription,\n CardStackEntryField,\n CardStackEntryTitle,\n} from \"@executor-js/react/components/card-stack\";\nimport { FilterTabs } from \"@executor-js/react/components/filter-tabs\";\nimport { Input } from \"@executor-js/react/components/input\";\nimport { sourceWriteKeys as openApiWriteKeys } from \"@executor-js/react/api/reactivity-keys\";\nimport { ConnectionId, ScopeId, SecretId } from \"@executor-js/sdk/core\";\nimport { useSecretPickerSecrets } from \"@executor-js/react/plugins/use-secret-picker-secrets\";\nimport {\n oauthCallbackUrl,\n useOAuthPopupFlow,\n type OAuthCompletionPayload,\n} from \"@executor-js/react/plugins/oauth-sign-in\";\nimport {\n effectiveCredentialBindingForScope,\n exactCredentialBindingForScope,\n isConnectionCredentialBindingValue,\n isSecretCredentialBindingValue,\n} from \"@executor-js/react/plugins/credential-bindings\";\nimport { SecretCredentialSlotBindings } from \"@executor-js/react/plugins/credential-slot-bindings\";\n\nimport {\n openApiSourceAtom,\n openApiSourceBindingsAtom,\n removeOpenApiSourceBinding,\n setOpenApiSourceBinding,\n updateOpenApiSource,\n} from \"./atoms\";\nimport { OpenApiSourceDetailsFields } from \"./OpenApiSourceDetailsFields\";\nimport {\n OPENAPI_OAUTH_CALLBACK_PATH,\n OPENAPI_OAUTH_POPUP_NAME,\n inferOAuthIssuerUrl,\n resolveOAuthUrl,\n} from \"./AddOpenApiSource\";\nimport { oauth2ClientSecretSlot } from \"../sdk/store\";\nimport {\n OAuth2SourceConfig,\n OpenApiSourceBindingInput,\n type OpenApiSourceBindingRef,\n} from \"../sdk/types\";\n\nconst ErrorMessage = Schema.Struct({ message: Schema.String });\nconst decodeErrorMessage = Schema.decodeUnknownOption(ErrorMessage);\n\nconst errorMessageFromExit = (exit: Exit.Exit<unknown, unknown>, fallback: string): string =>\n Option.match(Option.flatMap(Exit.findErrorOption(exit), decodeErrorMessage), {\n onNone: () => fallback,\n onSome: ({ message }) => message,\n });\n\ntype SlotDef =\n | {\n readonly kind: \"secret\";\n readonly slot: string;\n readonly label: string;\n readonly hint?: string;\n }\n | {\n readonly kind: \"oauth2\";\n readonly slot: string;\n readonly label: string;\n };\n\nconst slugify = (value: string): string =>\n value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\") || \"default\";\n\nconst shortHash = (value: string): string => {\n let hash = 0x811c9dc5;\n for (let i = 0; i < value.length; i++) {\n hash ^= value.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(36).slice(0, 6);\n};\n\nconst openApiOAuthConnectionId = (\n sourceId: string,\n securitySchemeName: string,\n targetScope: ScopeId,\n): ConnectionId =>\n ConnectionId.make(\n `openapi-oauth-${slugify(sourceId)}-${slugify(securitySchemeName)}-${shortHash(targetScope)}`,\n );\n\nconst effectiveClientSecretSlot = (oauth2: {\n readonly securitySchemeName: string;\n readonly clientSecretSlot: string | null;\n}): string => oauth2.clientSecretSlot ?? oauth2ClientSecretSlot(oauth2.securitySchemeName);\n\nexport default function EditOpenApiSource(props: {\n readonly sourceId: string;\n readonly onSave: () => void;\n}) {\n const displayScope = useScope();\n const scopeStack = useScopeStack();\n const userScope = useUserScope();\n const sourceSummaryResult = useAtomValue(sourceAtom(props.sourceId, displayScope));\n const sourceSummary =\n AsyncResult.isSuccess(sourceSummaryResult) && sourceSummaryResult.value\n ? sourceSummaryResult.value\n : null;\n const sourceScopeId = sourceSummary?.scopeId ?? displayScope;\n const sourceScope = ScopeId.make(sourceScopeId);\n const scopeRanks = useMemo(\n () => new Map(scopeStack.map((scope, index) => [scope.id, index] as const)),\n [scopeStack],\n );\n\n const sourceResult = useAtomValue(openApiSourceAtom(sourceScope, props.sourceId));\n const bindingsResult = useAtomValue(\n openApiSourceBindingsAtom(displayScope, props.sourceId, sourceScope),\n );\n const connectionsResult = useAtomValue(connectionsAtom(displayScope));\n const secretList = useSecretPickerSecrets();\n\n const doUpdate = useAtomSet(updateOpenApiSource, { mode: \"promiseExit\" });\n const doSetBinding = useAtomSet(setOpenApiSourceBinding, {\n mode: \"promiseExit\",\n });\n const doRemoveBinding = useAtomSet(removeOpenApiSourceBinding, {\n mode: \"promiseExit\",\n });\n const doStartOAuth = useAtomSet(startOAuth, { mode: \"promiseExit\" });\n const oauth = useOAuthPopupFlow<OAuthCompletionPayload>({\n popupName: OPENAPI_OAUTH_POPUP_NAME,\n popupBlockedMessage: \"OAuth popup was blocked by the browser\",\n startErrorMessage: \"Failed to connect OAuth\",\n });\n\n const source =\n AsyncResult.isSuccess(sourceResult) && sourceResult.value ? sourceResult.value : null;\n const bindingRows: readonly OpenApiSourceBindingRef[] = AsyncResult.isSuccess(bindingsResult)\n ? bindingsResult.value\n : [];\n const connections = AsyncResult.isSuccess(connectionsResult) ? connectionsResult.value : [];\n const oauth2RedirectUrl = oauthCallbackUrl(OPENAPI_OAUTH_CALLBACK_PATH);\n\n const [name, setName] = useState(source?.name ?? \"\");\n const [baseUrl, setBaseUrl] = useState(source?.config.baseUrl ?? \"\");\n const [sourceSaveState, setSourceSaveState] = useState<\"idle\" | \"saving\" | \"saved\">(\"idle\");\n const [error, setError] = useState<string | null>(null);\n const [busyKey, setBusyKey] = useState<string | null>(null);\n const [pendingOAuthConnection, setPendingOAuthConnection] = useState<{\n readonly scopeId: ScopeId;\n readonly slot: string;\n readonly connectionId: string;\n } | null>(null);\n const [loadedSourceKey, setLoadedSourceKey] = useState<string | null>(null);\n const [selectedOAuthTokenScope, setSelectedOAuthTokenScope] = useState<string>(\n userScope !== sourceScopeId ? userScope : sourceScopeId,\n );\n const [oauth2AuthorizationUrl, setOAuth2AuthorizationUrl] = useState(\n source?.config.oauth2?.authorizationUrl ?? \"\",\n );\n const [oauth2TokenUrl, setOAuth2TokenUrl] = useState(source?.config.oauth2?.tokenUrl ?? \"\");\n const [oauth2EndpointsSaveState, setOAuth2EndpointsSaveState] = useState<\n \"idle\" | \"saving\" | \"saved\"\n >(\"idle\");\n const editIdentity = useMemo(\n () => ({\n name,\n namespace: props.sourceId,\n setName,\n setNamespace: () => {},\n reset: () => {},\n }),\n [name, props.sourceId],\n );\n const sourceSaveSeq = useRef(0);\n const oauth2EndpointsSaveSeq = useRef(0);\n\n useEffect(() => {\n setSelectedOAuthTokenScope(userScope !== sourceScopeId ? userScope : sourceScopeId);\n }, [sourceScopeId, userScope]);\n\n useEffect(() => {\n if (!source) return;\n const sourceKey = `${sourceScopeId}:${source.namespace}`;\n if (loadedSourceKey === sourceKey) return;\n setName(source.name);\n setBaseUrl(source.config.baseUrl ?? \"\");\n setOAuth2AuthorizationUrl(source.config.oauth2?.authorizationUrl ?? \"\");\n setOAuth2TokenUrl(source.config.oauth2?.tokenUrl ?? \"\");\n setOAuth2EndpointsSaveState(\"idle\");\n setSourceSaveState(\"idle\");\n setLoadedSourceKey(sourceKey);\n }, [loadedSourceKey, source, sourceScopeId]);\n\n useEffect(() => {\n if (!source) return;\n const sourceKey = `${sourceScopeId}:${source.namespace}`;\n if (loadedSourceKey !== sourceKey) return;\n\n const nextName = name.trim();\n const nextBaseUrl = baseUrl.trim();\n const currentName = source.name;\n const currentBaseUrl = source.config.baseUrl ?? \"\";\n if ((nextName || currentName) === currentName && nextBaseUrl === currentBaseUrl) {\n return;\n }\n\n const timeout = window.setTimeout(() => {\n const seq = ++sourceSaveSeq.current;\n setSourceSaveState(\"saving\");\n setError(null);\n void (async () => {\n const exit = await doUpdate({\n params: { scopeId: displayScope, namespace: props.sourceId },\n payload: {\n sourceScope,\n name: nextName || undefined,\n baseUrl: nextBaseUrl || undefined,\n },\n reactivityKeys: openApiWriteKeys,\n });\n if (sourceSaveSeq.current !== seq) return;\n if (Exit.isFailure(exit)) {\n setSourceSaveState(\"idle\");\n setError(errorMessageFromExit(exit, \"Failed to save source details\"));\n return;\n }\n setSourceSaveState(\"saved\");\n window.setTimeout(() => {\n if (sourceSaveSeq.current === seq) setSourceSaveState(\"idle\");\n }, 1600);\n })();\n }, 600);\n\n return () => window.clearTimeout(timeout);\n }, [\n baseUrl,\n displayScope,\n doUpdate,\n loadedSourceKey,\n name,\n props.sourceId,\n source,\n sourceScope,\n sourceScopeId,\n ]);\n\n const secretSlots = useMemo(() => {\n if (!source) return [] as SlotDef[];\n const slots: SlotDef[] = [];\n for (const [headerName, value] of Object.entries(source.config.headers ?? {})) {\n if (typeof value === \"string\") continue;\n slots.push({\n kind: \"secret\",\n slot: value.slot,\n label: headerName,\n hint: value.prefix ? `Prefix: ${value.prefix}` : undefined,\n });\n }\n if (source.config.oauth2) {\n const clientSecretSlot = effectiveClientSecretSlot(source.config.oauth2);\n slots.push({\n kind: \"secret\",\n slot: source.config.oauth2.clientIdSlot,\n label: \"Client ID\",\n });\n slots.push({\n kind: \"secret\",\n slot: clientSecretSlot,\n label: \"Client Secret\",\n hint:\n source.config.oauth2.flow === \"authorizationCode\"\n ? \"Optional for public PKCE clients\"\n : undefined,\n });\n slots.push({\n kind: \"oauth2\",\n slot: source.config.oauth2.connectionSlot,\n label:\n source.config.oauth2.flow === \"clientCredentials\"\n ? \"OAuth Client Credentials\"\n : \"OAuth Authorization Code\",\n });\n }\n return slots;\n }, [source]);\n\n const credentialScopes = useMemo(() => {\n const entries = [{ scopeId: ScopeId.make(sourceScopeId), label: \"Organization\" }];\n if (userScope !== sourceScopeId) {\n entries.unshift({ scopeId: ScopeId.make(userScope), label: \"Personal\" });\n } else {\n entries[0] = {\n scopeId: ScopeId.make(sourceScopeId),\n label: \"Credentials\",\n };\n }\n return entries;\n }, [sourceScopeId, userScope]);\n const credentialScopeOptions = useMemo(\n () =>\n credentialScopes.map((entry) => ({\n scopeId: entry.scopeId,\n label: entry.label,\n description:\n entry.label === \"Personal\"\n ? \"Saved only for your account.\"\n : \"Shared with everyone who can use this source.\",\n })),\n [credentialScopes],\n );\n const organizationCredentialScope =\n credentialScopes.find((entry) => entry.label === \"Organization\") ?? credentialScopes[0]!;\n const personalCredentialScope =\n credentialScopes.find((entry) => entry.label === \"Personal\") ?? null;\n const secretBindingScopes =\n personalCredentialScope &&\n personalCredentialScope.scopeId !== organizationCredentialScope.scopeId\n ? [organizationCredentialScope, personalCredentialScope]\n : [organizationCredentialScope];\n const activeOAuthTokenScope =\n credentialScopes.find((entry) => entry.scopeId === selectedOAuthTokenScope) ??\n credentialScopes[0]!;\n const activeOAuthTokenScopeId = activeOAuthTokenScope.scopeId;\n const activeOAuthTokenScopeLabel = activeOAuthTokenScope.label;\n\n if (!source) {\n return (\n <div className=\"space-y-3\">\n <h1 className=\"text-xl font-semibold text-foreground\">Edit OpenAPI Source</h1>\n <p className=\"text-sm text-muted-foreground\">Loading configuration…</p>\n </div>\n );\n }\n\n const setSecretBinding = async (\n targetScope: ScopeId,\n slot: string,\n secretId: string,\n secretScope: ScopeId,\n ) => {\n const inputKey = `${targetScope}:${slot}`;\n const trimmed = secretId.trim();\n if (!trimmed) return;\n setBusyKey(inputKey);\n setError(null);\n const exit = await doSetBinding({\n params: { scopeId: displayScope },\n payload: OpenApiSourceBindingInput.make({\n sourceId: props.sourceId,\n sourceScope,\n scope: targetScope,\n slot,\n value: {\n kind: \"secret\",\n secretId: SecretId.make(trimmed),\n secretScopeId: secretScope,\n },\n }),\n reactivityKeys: sourceWriteKeys,\n });\n if (Exit.isFailure(exit)) {\n setError(errorMessageFromExit(exit, \"Failed to save credential binding\"));\n }\n setBusyKey(null);\n };\n\n const clearBinding = async (targetScope: ScopeId, slot: string) => {\n setBusyKey(`${targetScope}:${slot}:clear`);\n setError(null);\n const exit = await doRemoveBinding({\n params: { scopeId: displayScope },\n payload: {\n sourceId: props.sourceId,\n sourceScope,\n slot,\n scope: targetScope,\n },\n reactivityKeys: sourceWriteKeys,\n });\n if (Exit.isFailure(exit)) {\n setError(errorMessageFromExit(exit, \"Failed to clear credential binding\"));\n }\n setBusyKey(null);\n };\n\n const connectOAuth = async (targetScope: ScopeId) => {\n const oauth2 = source.config.oauth2;\n if (!oauth2) return;\n const clientIdBinding = effectiveCredentialBindingForScope(\n bindingRows,\n oauth2.clientIdSlot,\n targetScope,\n scopeRanks,\n );\n const clientSecretSlot = effectiveClientSecretSlot(oauth2);\n const clientSecretBinding = effectiveCredentialBindingForScope(\n bindingRows,\n clientSecretSlot,\n targetScope,\n scopeRanks,\n );\n if (!clientIdBinding || !isSecretCredentialBindingValue(clientIdBinding.value)) {\n setError(\"Client ID must be bound before connecting\");\n return;\n }\n const clientIdSecretId = clientIdBinding.value.secretId;\n if (\n oauth2.flow === \"clientCredentials\" &&\n (!clientSecretBinding || !isSecretCredentialBindingValue(clientSecretBinding.value))\n ) {\n setError(\"Client secret must be bound before connecting\");\n return;\n }\n const clientSecretValue =\n oauth2.flow === \"clientCredentials\" &&\n clientSecretBinding &&\n isSecretCredentialBindingValue(clientSecretBinding.value)\n ? clientSecretBinding.value\n : null;\n\n const existingConnection = exactCredentialBindingForScope(\n bindingRows,\n oauth2.connectionSlot,\n targetScope,\n );\n const connectionId =\n existingConnection && isConnectionCredentialBindingValue(existingConnection.value)\n ? existingConnection.value.connectionId\n : openApiOAuthConnectionId(props.sourceId, oauth2.securitySchemeName, targetScope);\n\n setBusyKey(`${targetScope}:${oauth2.connectionSlot}:connect`);\n setPendingOAuthConnection({\n scopeId: targetScope,\n slot: oauth2.connectionSlot,\n connectionId: connectionId,\n });\n setError(null);\n const failConnect = (message: string) => {\n setError(message);\n setPendingOAuthConnection(null);\n setBusyKey(null);\n };\n const displayName = source.name;\n const tokenUrl = resolveOAuthUrl(oauth2.tokenUrl, source.config.baseUrl ?? \"\");\n if (oauth2.flow === \"clientCredentials\") {\n const startOAuthExit = await doStartOAuth({\n params: { scopeId: targetScope },\n payload: {\n endpoint: tokenUrl,\n redirectUrl: tokenUrl,\n connectionId: connectionId,\n tokenScope: targetScope,\n strategy: {\n kind: \"client-credentials\",\n tokenEndpoint: tokenUrl,\n clientIdSecretId,\n clientSecretSecretId: clientSecretValue!.secretId,\n scopes: [...oauth2.scopes],\n },\n pluginId: \"openapi\",\n identityLabel: `${displayName} OAuth`,\n },\n });\n if (Exit.isFailure(startOAuthExit)) {\n failConnect(errorMessageFromExit(startOAuthExit, \"Failed to connect OAuth\"));\n return;\n }\n const response = startOAuthExit.value;\n if (!response.completedConnection) {\n failConnect(\"Unexpected OAuth response\");\n return;\n }\n const setBindingExit = await doSetBinding({\n params: { scopeId: displayScope },\n payload: OpenApiSourceBindingInput.make({\n sourceId: props.sourceId,\n sourceScope,\n scope: targetScope,\n slot: oauth2.connectionSlot,\n value: {\n kind: \"connection\",\n connectionId: ConnectionId.make(response.completedConnection.connectionId),\n },\n }),\n reactivityKeys: [...sourceWriteKeys, ...connectionWriteKeys],\n });\n if (Exit.isFailure(setBindingExit)) {\n failConnect(errorMessageFromExit(setBindingExit, \"Failed to connect OAuth\"));\n return;\n }\n setPendingOAuthConnection(null);\n setBusyKey(null);\n return;\n }\n\n const authorizationUrl = resolveOAuthUrl(\n oauth2.authorizationUrl ?? \"\",\n source.config.baseUrl ?? \"\",\n );\n const issuerUrl = oauth2.issuerUrl ?? inferOAuthIssuerUrl(authorizationUrl);\n const startOAuthExit = await doStartOAuth({\n params: { scopeId: targetScope },\n payload: {\n endpoint: authorizationUrl,\n connectionId,\n tokenScope: targetScope,\n redirectUrl: oauth2RedirectUrl,\n strategy: {\n kind: \"authorization-code\",\n authorizationEndpoint: authorizationUrl,\n tokenEndpoint: tokenUrl,\n issuerUrl,\n clientIdSecretId,\n clientSecretSecretId:\n clientSecretBinding && isSecretCredentialBindingValue(clientSecretBinding.value)\n ? clientSecretBinding.value.secretId\n : null,\n scopes: [...oauth2.scopes],\n },\n pluginId: \"openapi\",\n identityLabel: `${displayName} OAuth`,\n },\n });\n if (Exit.isFailure(startOAuthExit)) {\n failConnect(errorMessageFromExit(startOAuthExit, \"Failed to connect OAuth\"));\n return;\n }\n const response = startOAuthExit.value;\n if (response.authorizationUrl === null) {\n failConnect(\"Unexpected OAuth response\");\n return;\n }\n\n await oauth.openAuthorization({\n tokenScope: targetScope,\n run: async () => ({\n sessionId: response.sessionId,\n authorizationUrl: response.authorizationUrl,\n }),\n onSuccess: async (result) => {\n const setBindingExit = await doSetBinding({\n params: { scopeId: displayScope },\n payload: OpenApiSourceBindingInput.make({\n sourceId: props.sourceId,\n sourceScope,\n scope: targetScope,\n slot: oauth2.connectionSlot,\n value: {\n kind: \"connection\",\n connectionId: ConnectionId.make(result.connectionId),\n },\n }),\n reactivityKeys: [...sourceWriteKeys, ...connectionWriteKeys],\n });\n if (Exit.isFailure(setBindingExit)) {\n failConnect(errorMessageFromExit(setBindingExit, \"Failed to connect OAuth\"));\n return;\n }\n setPendingOAuthConnection(null);\n setBusyKey(null);\n },\n onError: (message) => {\n setError(message);\n setPendingOAuthConnection(null);\n setBusyKey(null);\n },\n });\n };\n\n return (\n <div className=\"space-y-6\">\n <div>\n <h1 className=\"text-xl font-semibold text-foreground\">OpenAPI Source</h1>\n </div>\n\n <OpenApiSourceDetailsFields\n title=\"Source Details\"\n description=\"Name and base URL save automatically.\"\n identity={editIdentity}\n baseUrl={baseUrl}\n onBaseUrlChange={setBaseUrl}\n specUrl={source.config.sourceUrl ?? \"\"}\n onSpecUrlChange={() => {}}\n specUrlDisabled\n namespaceReadOnly\n saveState={sourceSaveState}\n footer={\n source.config.oauth2\n ? `Authentication Template: OAuth2 ${source.config.oauth2.flow}`\n : Object.keys(source.config.headers ?? {}).length > 0\n ? `Authentication Template: ${Object.keys(source.config.headers ?? {}).length} header binding${\n Object.keys(source.config.headers ?? {}).length === 1 ? \"\" : \"s\"\n }`\n : \"Authentication Template: None\"\n }\n />\n\n <CardStack>\n <CardStackContent className=\"border-t-0\">\n <CardStackEntry>\n <CardStackEntryContent>\n <CardStackEntryTitle>Secrets</CardStackEntryTitle>\n </CardStackEntryContent>\n </CardStackEntry>\n\n <SecretCredentialSlotBindings\n slots={secretSlots.filter((slot) => slot.kind === \"secret\")}\n bindingScopes={secretBindingScopes}\n bindingRows={bindingRows}\n scopeRanks={scopeRanks}\n secrets={secretList}\n sourceId={props.sourceId}\n sourceName={source.name}\n credentialScopeOptions={credentialScopeOptions}\n busyKey={busyKey}\n onSetSecretBinding={setSecretBinding}\n onClearBinding={clearBinding}\n />\n\n {source.config.oauth2 &&\n (() => {\n const oauth2 = source.config.oauth2;\n const trimmedAuthUrl = oauth2AuthorizationUrl.trim();\n const trimmedTokenUrl = oauth2TokenUrl.trim();\n const savedAuthUrl = oauth2.authorizationUrl ?? \"\";\n const isAuthCode = oauth2.flow === \"authorizationCode\";\n const endpointsDirty =\n (isAuthCode && trimmedAuthUrl !== savedAuthUrl) ||\n trimmedTokenUrl !== oauth2.tokenUrl;\n const saving = oauth2EndpointsSaveState === \"saving\";\n const tokenUrlMissing = trimmedTokenUrl.length === 0;\n const authUrlMissing = isAuthCode && trimmedAuthUrl.length === 0;\n const canSave = endpointsDirty && !saving && !tokenUrlMissing && !authUrlMissing;\n\n const saveOAuth2Endpoints = async () => {\n const seq = ++oauth2EndpointsSaveSeq.current;\n setOAuth2EndpointsSaveState(\"saving\");\n setError(null);\n const exit = await doUpdate({\n params: { scopeId: displayScope, namespace: props.sourceId },\n payload: {\n sourceScope,\n oauth2: OAuth2SourceConfig.make({\n kind: \"oauth2\",\n securitySchemeName: oauth2.securitySchemeName,\n flow: oauth2.flow,\n tokenUrl: trimmedTokenUrl,\n authorizationUrl: isAuthCode ? trimmedAuthUrl || null : null,\n issuerUrl: oauth2.issuerUrl ?? null,\n clientIdSlot: oauth2.clientIdSlot,\n clientSecretSlot: oauth2.clientSecretSlot,\n connectionSlot: oauth2.connectionSlot,\n scopes: [...oauth2.scopes],\n }),\n },\n reactivityKeys: openApiWriteKeys,\n });\n if (oauth2EndpointsSaveSeq.current !== seq) return;\n if (Exit.isFailure(exit)) {\n setOAuth2EndpointsSaveState(\"idle\");\n setError(errorMessageFromExit(exit, \"Failed to save OAuth endpoints\"));\n return;\n }\n setOAuth2EndpointsSaveState(\"saved\");\n window.setTimeout(() => {\n if (oauth2EndpointsSaveSeq.current === seq) {\n setOAuth2EndpointsSaveState(\"idle\");\n }\n }, 1600);\n };\n\n const exact = exactCredentialBindingForScope(\n bindingRows,\n oauth2.connectionSlot,\n activeOAuthTokenScopeId,\n );\n const binding =\n exact ??\n effectiveCredentialBindingForScope(\n bindingRows,\n oauth2.connectionSlot,\n activeOAuthTokenScopeId,\n scopeRanks,\n );\n const connectionBinding =\n binding && isConnectionCredentialBindingValue(binding.value) ? binding.value : null;\n const connection = connectionBinding\n ? connections.find((entry) => entry.id === connectionBinding.connectionId)\n : null;\n const bindingScopeId = connectionBinding && binding ? binding.scopeId : null;\n const isConnecting =\n busyKey === `${activeOAuthTokenScopeId}:${oauth2.connectionSlot}:connect`;\n const isPendingOAuthConnection =\n pendingOAuthConnection?.scopeId === activeOAuthTokenScopeId &&\n pendingOAuthConnection !== null &&\n pendingOAuthConnection.slot === oauth2.connectionSlot;\n const isConnected = connection !== null && connection !== undefined;\n const statusText =\n isConnecting || isPendingOAuthConnection\n ? \"Saving OAuth connection...\"\n : connectionBinding && bindingScopeId\n ? connection\n ? bindingScopeId === activeOAuthTokenScopeId\n ? `Connected in ${activeOAuthTokenScopeLabel.toLowerCase()} as ${\n connection.identityLabel ?? connection.id\n }`\n : `Using organization connection ${\n connection.identityLabel ?? connection.id\n }`\n : bindingScopeId === activeOAuthTokenScopeId\n ? `Saved connection is missing in ${activeOAuthTokenScopeLabel.toLowerCase()}`\n : \"Organization connection is missing\"\n : `No ${activeOAuthTokenScopeLabel.toLowerCase()} connection`;\n const connectDisabled = isConnecting || endpointsDirty || saving;\n\n return (\n <>\n <CardStackEntry>\n <CardStackEntryContent>\n <CardStackEntryTitle>OAuth Endpoints</CardStackEntryTitle>\n <CardStackEntryDescription>\n Override the URLs from the OpenAPI spec when a provider publishes the wrong\n values.\n </CardStackEntryDescription>\n </CardStackEntryContent>\n <div className=\"flex items-center gap-2\">\n {oauth2EndpointsSaveState !== \"idle\" && (\n <span className=\"text-xs text-muted-foreground\">\n {saving ? \"Saving…\" : \"Saved\"}\n </span>\n )}\n <Button\n size=\"sm\"\n onClick={() => void saveOAuth2Endpoints()}\n disabled={!canSave}\n >\n Save\n </Button>\n </div>\n </CardStackEntry>\n {isAuthCode && (\n <CardStackEntryField label=\"Authorization URL\">\n <Input\n value={oauth2AuthorizationUrl}\n onChange={(e) =>\n setOAuth2AuthorizationUrl((e.target as HTMLInputElement).value)\n }\n className=\"font-mono text-sm\"\n />\n </CardStackEntryField>\n )}\n <CardStackEntryField label=\"Token URL\">\n <Input\n value={oauth2TokenUrl}\n onChange={(e) => setOAuth2TokenUrl((e.target as HTMLInputElement).value)}\n className=\"font-mono text-sm\"\n />\n </CardStackEntryField>\n <CardStackEntryField label=\"Redirect URL\">\n <div className=\"space-y-1.5\">\n <div className=\"flex items-center gap-1 rounded-md border border-border bg-background/50 px-2.5 py-1.5 font-mono text-[11px]\">\n <span className=\"truncate flex-1 text-foreground\">{oauth2RedirectUrl}</span>\n <CopyButton value={oauth2RedirectUrl} />\n </div>\n <p className=\"text-xs text-muted-foreground\">\n Add this to your OAuth app's allowed redirects.\n </p>\n </div>\n </CardStackEntryField>\n {credentialScopes.length > 1 && (\n <CardStackEntry>\n <CardStackEntryContent>\n <CardStackEntryTitle>OAuth token</CardStackEntryTitle>\n <CardStackEntryDescription>\n Choose where the signed-in OAuth token is saved.\n </CardStackEntryDescription>\n </CardStackEntryContent>\n <FilterTabs\n tabs={credentialScopes.map((entry) => ({\n value: entry.scopeId,\n label: entry.label,\n }))}\n value={activeOAuthTokenScopeId}\n onChange={setSelectedOAuthTokenScope}\n />\n </CardStackEntry>\n )}\n <CardStackEntryField label=\"OAuth Connection\">\n <div className=\"space-y-2\">\n <div className=\"text-sm text-muted-foreground\">{statusText}</div>\n <Button\n size=\"sm\"\n onClick={() => void connectOAuth(activeOAuthTokenScopeId)}\n disabled={connectDisabled}\n >\n {isConnecting ? \"Connecting…\" : isConnected ? \"Reconnect\" : \"Connect\"}\n </Button>\n {endpointsDirty && (\n <p className=\"text-xs text-muted-foreground\">\n Save endpoint changes before reconnecting.\n </p>\n )}\n </div>\n </CardStackEntryField>\n </>\n );\n })()}\n </CardStackContent>\n </CardStack>\n\n {error && (\n <div className=\"rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2\">\n <p className=\"text-sm text-destructive\">{error}</p>\n </div>\n )}\n\n <div className=\"flex items-center justify-start border-t border-border pt-4\">\n <Button variant=\"ghost\" onClick={props.onSave}>\n Back\n </Button>\n </div>\n </div>\n );\n}\n"],"mappings":";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SAAQ,SAAS,MAAM,QAAQ,kBAE/C,GACF;AAAA,KACF;AAEJ;","names":["startOAuthExit","response"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react/OpenApiSourceSummary.tsx","../src/sdk/credential-status.ts"],"sourcesContent":["import { useAtomValue } from \"@effect/atom-react\";\nimport * as AsyncResult from \"effect/unstable/reactivity/AsyncResult\";\n\nimport { connectionsAtom, sourceAtom } from \"@executor-js/react/api/atoms\";\nimport { Badge } from \"@executor-js/react/components/badge\";\nimport { useScope, useScopeStack, useUserScope } from \"@executor-js/react/api/scope-context\";\nimport { ScopeId } from \"@executor-js/sdk/core\";\nimport {\n SourceCredentialNotice,\n SourceCredentialStatusBadge,\n missingSourceCredentialLabels,\n type SourceCredentialSlot,\n} from \"@executor-js/react/plugins/source-credential-status\";\n\nimport { openApiSourceAtom, openApiSourceBindingsAtom } from \"./atoms\";\nimport { effectiveBindingForScope } from \"../sdk/credential-status\";\nimport { oauth2ClientSecretSlot, type StoredSourceSchemaType } from \"../sdk/store\";\n\nfunction OAuthBadge() {\n return <Badge variant=\"secondary\">OAuth</Badge>;\n}\n\nfunction CheckingCredentialsBadge() {\n return (\n <Badge\n variant=\"outline\"\n className=\"border-border bg-muted/50 text-[10px] text-muted-foreground\"\n >\n Checking credentials\n </Badge>\n );\n}\n\nconst effectiveClientSecretSlot = (oauth2: {\n readonly securitySchemeName: string;\n readonly clientSecretSlot: string | null;\n}): string => oauth2.clientSecretSlot ?? oauth2ClientSecretSlot(oauth2.securitySchemeName);\n\nconst sourceCredentialSlots = (source: StoredSourceSchemaType): readonly SourceCredentialSlot[] => {\n const slots: SourceCredentialSlot[] = [];\n for (const [name, value] of Object.entries(source.config.headers ?? {})) {\n if (typeof value !== \"string\") slots.push({ kind: \"secret\", slot: value.slot, label: name });\n }\n for (const [name, value] of Object.entries(source.config.queryParams ?? {})) {\n if (typeof value !== \"string\") slots.push({ kind: \"secret\", slot: value.slot, label: name });\n }\n const oauth2 = source.config.oauth2;\n if (oauth2) {\n slots.push({ kind: \"secret\", slot: oauth2.clientIdSlot, label: \"Client ID\" });\n slots.push({\n kind: \"secret\",\n slot: effectiveClientSecretSlot(oauth2),\n label: \"Client Secret\",\n });\n slots.push({\n kind: \"connection\",\n slot: oauth2.connectionSlot,\n label: oauth2.flow === \"clientCredentials\" ? \"OAuth client connection\" : \"OAuth sign-in\",\n });\n }\n return slots;\n};\n\n// The entry row already renders name + id + kind, so this summary\n// component only contributes extras — specifically, an OAuth status\n// badge when the source has OAuth2 configured. Non-OAuth sources\n// render nothing.\nexport default function OpenApiSourceSummary(props: {\n sourceId: string;\n variant?: \"badge\" | \"panel\";\n onAction?: () => void;\n}) {\n const displayScope = useScope();\n const userScope = useUserScope();\n const scopeStack = useScopeStack();\n const summaryResult = useAtomValue(sourceAtom(props.sourceId, displayScope));\n const sourceScopeId =\n AsyncResult.isSuccess(summaryResult) && summaryResult.value?.scopeId\n ? summaryResult.value.scopeId\n : displayScope;\n const sourceResult = useAtomValue(openApiSourceAtom(ScopeId.make(sourceScopeId), props.sourceId));\n const bindingsResult = useAtomValue(\n openApiSourceBindingsAtom(displayScope, props.sourceId, ScopeId.make(sourceScopeId)),\n );\n const connectionsResult = useAtomValue(connectionsAtom(displayScope));\n\n const source =\n AsyncResult.isSuccess(sourceResult) && sourceResult.value ? sourceResult.value : null;\n\n if (!source) return null;\n const oauth2 = source.config.oauth2;\n const bindingsLoaded = AsyncResult.isSuccess(bindingsResult);\n const connectionsLoaded = AsyncResult.isSuccess(connectionsResult);\n if (!bindingsLoaded) {\n return props.variant === \"panel\" ? null : <CheckingCredentialsBadge />;\n }\n\n const bindings = AsyncResult.isSuccess(bindingsResult) ? bindingsResult.value : [];\n if (oauth2 && !connectionsLoaded) {\n return props.variant === \"panel\" ? null : <CheckingCredentialsBadge />;\n }\n const connections = AsyncResult.isSuccess(connectionsResult) ? connectionsResult.value : [];\n const liveConnectionIds = new Set(connections.map((connection) => connection.id));\n const scopeRanks = new Map(scopeStack.map((scope, index) => [scope.id, index] as const));\n const credentialTargetScope = userScope;\n const missing = missingSourceCredentialLabels({\n slots: sourceCredentialSlots(source),\n bindings,\n targetScope: credentialTargetScope,\n scopeRanks,\n liveConnectionIds,\n });\n\n if (props.variant === \"panel\") {\n return <SourceCredentialNotice missing={missing} onAction={props.onAction} />;\n }\n\n if (missing.length > 0) return <SourceCredentialStatusBadge missing={missing} />;\n\n if (!oauth2) return null;\n const connectionBinding = effectiveBindingForScope(\n bindings,\n oauth2.connectionSlot,\n credentialTargetScope,\n scopeRanks,\n );\n const connectionId =\n connectionBinding && connectionBinding.value.kind === \"connection\"\n ? connectionBinding.value.connectionId\n : null;\n\n if (connectionId && connections.some((connection) => connection.id === connectionId)) {\n return <SourceCredentialStatusBadge missing={[]} />;\n }\n\n return <OAuthBadge />;\n}\n","import type { ConnectionId, ScopeId } from \"@executor-js/sdk/core\";\n\nimport { oauth2ClientSecretSlot } from \"./store\";\nimport type { ConfiguredHeaderValue, OpenApiSourceBindingValue } from \"./types\";\n\nexport type BindingRowForCredentialStatus = {\n readonly slot: string;\n readonly scopeId: ScopeId;\n readonly value: OpenApiSourceBindingValue;\n};\n\nexport type SourceForCredentialStatus = {\n readonly config: {\n readonly headers?: Record<string, ConfiguredHeaderValue>;\n readonly oauth2?: {\n readonly securitySchemeName: string;\n readonly flow: \"authorizationCode\" | \"clientCredentials\";\n readonly clientIdSlot: string;\n readonly clientSecretSlot: string | null;\n readonly connectionSlot: string;\n };\n };\n};\n\nconst scopeRank = (ranks: ReadonlyMap<string, number>, scopeId: ScopeId): number =>\n ranks.get(scopeId) ?? Number.MAX_SAFE_INTEGER;\n\nexport const effectiveBindingForScope = (\n rows: readonly BindingRowForCredentialStatus[],\n slot: string,\n targetScope: ScopeId,\n ranks: ReadonlyMap<string, number>,\n): BindingRowForCredentialStatus | null =>\n rows\n .filter(\n (row) => row.slot === slot && scopeRank(ranks, row.scopeId) >= scopeRank(ranks, targetScope),\n )\n .sort((a, b) => scopeRank(ranks, a.scopeId) - scopeRank(ranks, b.scopeId))[0] ?? null;\n\nconst hasSecretBinding = (\n rows: readonly BindingRowForCredentialStatus[],\n slot: string,\n targetScope: ScopeId,\n ranks: ReadonlyMap<string, number>,\n) => effectiveBindingForScope(rows, slot, targetScope, ranks)?.value.kind === \"secret\";\n\nconst hasConnectionBinding = (\n rows: readonly BindingRowForCredentialStatus[],\n slot: string,\n targetScope: ScopeId,\n ranks: ReadonlyMap<string, number>,\n liveConnectionIds?: ReadonlySet<string>,\n) => {\n const binding = effectiveBindingForScope(rows, slot, targetScope, ranks);\n if (binding?.value.kind !== \"connection\") return false;\n return liveConnectionIds ? liveConnectionIds.has(binding.value.connectionId) : true;\n};\n\nconst effectiveClientSecretSlot = (oauth2: {\n readonly securitySchemeName: string;\n readonly clientSecretSlot: string | null;\n}): string => oauth2.clientSecretSlot ?? oauth2ClientSecretSlot(oauth2.securitySchemeName);\n\nexport function missingCredentialLabels(\n source: SourceForCredentialStatus,\n bindings: readonly BindingRowForCredentialStatus[],\n targetScope: ScopeId,\n ranks: ReadonlyMap<string, number>,\n options?: {\n readonly liveConnectionIds?: ReadonlySet<string> | readonly ConnectionId[];\n },\n): string[] {\n const missing: string[] = [];\n const rawLiveConnectionIds = options?.liveConnectionIds;\n const liveConnectionIds = rawLiveConnectionIds\n ? rawLiveConnectionIds instanceof Set\n ? rawLiveConnectionIds\n : new Set(rawLiveConnectionIds)\n : undefined;\n\n for (const [headerName, value] of Object.entries(source.config.headers ?? {})) {\n if (typeof value === \"string\") continue;\n if (!hasSecretBinding(bindings, value.slot, targetScope, ranks)) {\n missing.push(headerName);\n }\n }\n\n const oauth2 = source.config.oauth2;\n if (!oauth2) return missing;\n\n if (!hasSecretBinding(bindings, oauth2.clientIdSlot, targetScope, ranks)) {\n missing.push(\"Client ID\");\n }\n\n const clientSecretSlot = effectiveClientSecretSlot(oauth2);\n if (!hasSecretBinding(bindings, clientSecretSlot, targetScope, ranks)) {\n missing.push(\"Client Secret\");\n }\n\n if (\n !hasConnectionBinding(bindings, oauth2.connectionSlot, targetScope, ranks, liveConnectionIds)\n ) {\n missing.push(oauth2.flow === \"clientCredentials\" ? \"OAuth client connection\" : \"OAuth sign-in\");\n }\n\n return missing;\n}\n"],"mappings":";;;;;;;;;AAAA,SAAS,oBAAoB;AAC7B,YAAY,iBAAiB;AAE7B,SAAS,iBAAiB,kBAAkB;AAC5C,SAAS,aAAa;AACtB,SAAS,UAAU,eAAe,oBAAoB;AACtD,SAAS,eAAe;AACxB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;;;ACYP,IAAM,YAAY,CAAC,OAAoC,YACrD,MAAM,IAAI,OAAO,KAAK,OAAO;AAExB,IAAM,2BAA2B,CACtC,MACA,MACA,aACA,UAEA,KACG;AAAA,EACC,CAAC,QAAQ,IAAI,SAAS,QAAQ,UAAU,OAAO,IAAI,OAAO,KAAK,UAAU,OAAO,WAAW;AAC7F,EACC,KAAK,CAAC,GAAG,MAAM,UAAU,OAAO,EAAE,OAAO,IAAI,UAAU,OAAO,EAAE,OAAO,CAAC,EAAE,CAAC,KAAK;;;ADlB5E;AADT,SAAS,aAAa;AACpB,SAAO,oBAAC,SAAM,SAAQ,aAAY,mBAAK;AACzC;AAEA,SAAS,2BAA2B;AAClC,SACE;AAAA,IAAC;AAAA;AAAA,MACC,SAAQ;AAAA,MACR,WAAU;AAAA,MACX;AAAA;AAAA,EAED;AAEJ;AAEA,IAAM,4BAA4B,CAAC,WAGrB,OAAO,oBAAoB,uBAAuB,OAAO,kBAAkB;AAEzF,IAAM,wBAAwB,CAAC,WAAoE;AACjG,QAAM,QAAgC,CAAC;AACvC,aAAW,CAAC,MAAM,KAAK,KAAK,OAAO,QAAQ,OAAO,OAAO,WAAW,CAAC,CAAC,GAAG;AACvE,QAAI,OAAO,UAAU,SAAU,OAAM,KAAK,EAAE,MAAM,UAAU,MAAM,MAAM,MAAM,OAAO,KAAK,CAAC;AAAA,EAC7F;AAC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","../src/sdk/extract.ts","../src/sdk/preview.ts","../src/sdk/store.ts"],"sourcesContent":["import { Data, Schema } from \"effect\";\nimport type { Option } from \"effect\";\n\n// HTTP status lives on the class declaration so HttpApiBuilder's error\n// encoder (which reads `ast.annotations` off the schema it stored on\n// `group.addError(...)`) finds it. Applying the annotation post-hoc\n// via `.annotate(...)` in group.ts produced a transform-wrapper AST\n// whose status was not picked up — the error then slipped the typed\n// channel and was captured as a 500 by the observability middleware,\n// spamming Sentry on user misconfig.\nexport class OpenApiParseError extends Schema.TaggedErrorClass<OpenApiParseError>()(\n \"OpenApiParseError\",\n {\n message: Schema.String,\n },\n { httpApiStatus: 400 },\n) {}\n\nexport class OpenApiExtractionError extends Schema.TaggedErrorClass<OpenApiExtractionError>()(\n \"OpenApiExtractionError\",\n {\n message: Schema.String,\n },\n { httpApiStatus: 400 },\n) {}\n\nexport class OpenApiInvocationError extends Data.TaggedError(\"OpenApiInvocationError\")<{\n readonly message: string;\n readonly statusCode: Option.Option<number>;\n readonly cause?: unknown;\n}> {}\n\nexport class OpenApiOAuthError extends Schema.TaggedErrorClass<OpenApiOAuthError>()(\n \"OpenApiOAuthError\",\n {\n message: Schema.String,\n },\n { httpApiStatus: 400 },\n) {}\n","import type { OpenAPI, OpenAPIV3, OpenAPIV3_1 } from \"openapi-types\";\nimport { Duration, Effect, Schema } from \"effect\";\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\";\nimport YAML from \"yaml\";\n\nimport { OpenApiExtractionError, OpenApiParseError } from \"./errors\";\n\nexport type ParsedDocument = OpenAPIV3.Document | OpenAPIV3_1.Document;\n\nexport interface SpecFetchCredentials {\n readonly headers?: Record<string, string>;\n readonly queryParams?: Record<string, string>;\n}\n\n// ExtractionError subclass raised from parse() for non-3.x specs\nclass OpenApiExtractionErrorFromParse extends OpenApiExtractionError {}\n\n/**\n * Fetch an OpenAPI spec URL and return its body text. Uses the Effect\n * HttpClient so the caller chooses the transport via layer — in Cloudflare\n * Workers, `FetchHttpClient.layer` binds to the Workers-native `fetch` and\n * avoids json-schema-ref-parser's Node-polyfill http resolver, which hangs\n * in production. Bounded by a 60s timeout.\n */\nexport const fetchSpecText = Effect.fn(\"OpenApi.fetchSpecText\")(function* (\n url: string,\n credentials?: SpecFetchCredentials,\n) {\n const client = yield* HttpClient.HttpClient;\n const requestUrl = new URL(url);\n for (const [name, value] of Object.entries(credentials?.queryParams ?? {})) {\n requestUrl.searchParams.set(name, value);\n }\n let request = HttpClientRequest.get(requestUrl.toString()).pipe(\n HttpClientRequest.setHeader(\"Accept\", \"application/json, application/yaml, text/yaml, */*\"),\n );\n for (const [name, value] of Object.entries(credentials?.headers ?? {})) {\n request = HttpClientRequest.setHeader(request, name, value);\n }\n const response = yield* client.execute(request).pipe(\n Effect.timeout(Duration.seconds(60)),\n Effect.mapError(\n (_cause) =>\n new OpenApiParseError({\n message: \"Failed to fetch OpenAPI document\",\n }),\n ),\n );\n if (response.status < 200 || response.status >= 300) {\n return yield* new OpenApiParseError({\n message: `Failed to fetch OpenAPI document: HTTP ${response.status}`,\n });\n }\n return yield* response.text.pipe(\n Effect.mapError(\n (_cause) =>\n new OpenApiParseError({\n message: \"Failed to read OpenAPI document body\",\n }),\n ),\n );\n});\n\n/**\n * Resolve an input string to spec text — if it's a URL, fetch it via\n * HttpClient; otherwise return it as-is.\n */\nexport const resolveSpecText = (input: string, credentials?: SpecFetchCredentials) =>\n input.startsWith(\"http://\") || input.startsWith(\"https://\")\n ? fetchSpecText(input, credentials)\n : Effect.succeed(input);\n\n/**\n * Parse an OpenAPI document from spec text and validate it's OpenAPI 3.x.\n *\n * NOTE: does NOT resolve `$ref`s. `DocResolver` + `normalizeOpenApiRefs`\n * downstream work on refs lazily, so inlining them here would just waste\n * memory — and for big specs (e.g. Cloudflare's API) that blows through\n * the 128MB Cloudflare Workers memory cap.\n */\nexport const parse = Effect.fn(\"OpenApi.parse\")(function* (text: string) {\n const api = yield* parseTextToObject(text);\n\n if (!isOpenApi3(api)) {\n return yield* new OpenApiExtractionErrorFromParse({\n message:\n \"Only OpenAPI 3.x documents are supported. Swagger 2.x documents should be converted first.\",\n });\n }\n\n return api as ParsedDocument;\n});\n\n// ---------------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------------\n\nconst isOpenApi3 = (doc: OpenAPI.Document): doc is OpenAPIV3.Document | OpenAPIV3_1.Document =>\n \"openapi\" in doc && typeof doc.openapi === \"string\" && doc.openapi.startsWith(\"3.\");\n\nconst parseTextToObject = (text: string): Effect.Effect<OpenAPI.Document, OpenApiParseError> =>\n Effect.gen(function* () {\n const trimmed = text.trim();\n if (trimmed.length === 0) {\n return yield* new OpenApiParseError({\n message: \"OpenAPI document is empty\",\n });\n }\n\n const parsed = yield* parseJsonLike(trimmed).pipe(\n Effect.mapError(\n () =>\n new OpenApiParseError({\n message: \"Failed to parse OpenAPI document\",\n }),\n ),\n );\n\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n return yield* new OpenApiParseError({\n message: \"OpenAPI document must parse to an object\",\n });\n }\n\n return parsed as OpenAPI.Document;\n });\n\nconst parseJsonText = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));\n\nconst parseJsonLike = (text: string): Effect.Effect<unknown, unknown> => {\n const parseYaml = Effect.try({\n try: () => YAML.parse(text) as unknown,\n catch: () => \"YamlParseFailed\" as const,\n });\n if (!text.startsWith(\"{\") && !text.startsWith(\"[\")) return parseYaml;\n return parseJsonText(text).pipe(Effect.catch(() => parseYaml));\n};\n","// ---------------------------------------------------------------------------\n// OpenAPI type aliases and $ref resolution\n//\n// Wraps the openapi-types V3/V3_1 union mess and provides clean ref resolution.\n// ---------------------------------------------------------------------------\n\nimport { Option } from \"effect\";\nimport type { OpenAPIV3, OpenAPIV3_1 } from \"openapi-types\";\nimport type { ParsedDocument } from \"./parse\";\nimport type { ServerVariable } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Type aliases — collapse V3 / V3_1 unions into single names\n// ---------------------------------------------------------------------------\n\nexport type ParameterObject = OpenAPIV3.ParameterObject | OpenAPIV3_1.ParameterObject;\nexport type OperationObject = OpenAPIV3.OperationObject | OpenAPIV3_1.OperationObject;\nexport type PathItemObject = OpenAPIV3.PathItemObject | OpenAPIV3_1.PathItemObject;\nexport type RequestBodyObject = OpenAPIV3.RequestBodyObject | OpenAPIV3_1.RequestBodyObject;\nexport type ResponseObject = OpenAPIV3.ResponseObject | OpenAPIV3_1.ResponseObject;\nexport type MediaTypeObject = OpenAPIV3.MediaTypeObject | OpenAPIV3_1.MediaTypeObject;\n\n// ---------------------------------------------------------------------------\n// DocResolver — wraps a parsed document for clean $ref resolution\n// ---------------------------------------------------------------------------\n\nexport class DocResolver {\n constructor(readonly doc: ParsedDocument) {}\n\n /** Resolve a value that might be a $ref, returning the resolved object */\n resolve<T>(value: T | OpenAPIV3.ReferenceObject | OpenAPIV3_1.ReferenceObject): T | null {\n if (isRef(value)) {\n const resolved = this.resolvePointer(value.$ref);\n return resolved as T | null;\n }\n return value as T;\n }\n\n private resolvePointer(ref: string): unknown {\n if (!ref.startsWith(\"#/\")) return null;\n const segments = ref.slice(2).split(\"/\");\n let current: unknown = this.doc;\n for (const segment of segments) {\n if (typeof current !== \"object\" || current === null) return null;\n current = (current as Record<string, unknown>)[segment];\n }\n return current;\n }\n}\n\nconst isRef = (value: unknown): value is { $ref: string } =>\n typeof value === \"object\" && value !== null && \"$ref\" in value;\n\n// ---------------------------------------------------------------------------\n// Server URL resolution\n// ---------------------------------------------------------------------------\n\n/** Substitute `{var}` placeholders in a templated URL using a plain map. */\nexport const substituteUrlVariables = (url: string, values: Record<string, string>): string => {\n let out = url;\n for (const [name, value] of Object.entries(values)) {\n out = out.replaceAll(`{${name}}`, value);\n }\n return out;\n};\n\nexport const OPENAPI_MAX_SERVER_VARIABLE_OPTIONS = 64;\n\ntype ServerLike = {\n url: string;\n variables: import(\"effect/Option\").Option<Record<string, ServerVariable | string>>;\n};\n\nexport const expandServerUrlOptions = (\n server: ServerLike,\n limit = OPENAPI_MAX_SERVER_VARIABLE_OPTIONS,\n): readonly string[] => {\n if (!Option.isSome(server.variables)) return [server.url];\n let urls: readonly string[] = [server.url];\n for (const [name, variable] of Object.entries(server.variables.value)) {\n const enumValues =\n typeof variable === \"string\" ? [] : Option.getOrElse(variable.enum, () => []);\n const values =\n enumValues.length > 0\n ? enumValues\n : [typeof variable === \"string\" ? variable : variable.default];\n const next: string[] = [];\n for (const url of urls) {\n for (const value of values) {\n next.push(url.replaceAll(`{${name}}`, value));\n if (next.length >= limit) return next;\n }\n }\n urls = next;\n }\n return urls;\n};\n\nexport const resolveBaseUrl = (servers: readonly ServerLike[]): string => {\n const server = servers[0];\n if (!server) return \"\";\n\n if (!Option.isSome(server.variables)) return server.url;\n\n const values: Record<string, string> = {};\n for (const [name, v] of Object.entries(server.variables.value)) {\n values[name] = typeof v === \"string\" ? v : v.default;\n }\n return substituteUrlVariables(server.url, values);\n};\n\n// ---------------------------------------------------------------------------\n// Content negotiation\n// ---------------------------------------------------------------------------\n\n/**\n * Return all declared media entries in spec order. `Object.entries` on a\n * plain object preserves insertion order in modern engines, which matches\n * spec declaration order as the parser produced it.\n */\nexport const declaredContents = (\n content: Record<string, MediaTypeObject> | undefined,\n): ReadonlyArray<{ mediaType: string; media: MediaTypeObject }> => {\n if (!content) return [];\n return Object.entries(content).map(([mediaType, media]) => ({ mediaType, media }));\n};\n\n/**\n * Pick the default media type for a requestBody or response. Matches\n * swagger-client behaviour: **first declared wins** (not JSON-first). Spec\n * authors order content entries to signal intent (upload-heavy endpoints\n * declare multipart first, JSON second); respecting that order avoids\n * silently downgrading a multipart endpoint to JSON.\n *\n * For response bodies we still want a JSON preference because the server\n * picks the response content type, not the client — the old `application/\n * json` preference is preserved via `preferredResponseContent` below.\n */\nexport const preferredContent = (\n content: Record<string, MediaTypeObject> | undefined,\n): { mediaType: string; media: MediaTypeObject } | undefined => {\n const first = declaredContents(content)[0];\n return first ? first : undefined;\n};\n\n/** Response-side content picker — still JSON-first because the server\n * picks the response media type, so we want to advertise a preference. */\nexport const preferredResponseContent = (\n content: Record<string, MediaTypeObject> | undefined,\n): { mediaType: string; media: MediaTypeObject } | undefined => {\n if (!content) return undefined;\n const entries = Object.entries(content);\n const pick =\n entries.find(([mt]) => mt === \"application/json\") ??\n entries.find(([mt]) => mt.toLowerCase().includes(\"+json\")) ??\n entries.find(([mt]) => mt.toLowerCase().includes(\"json\")) ??\n entries[0];\n return pick ? { mediaType: pick[0], media: pick[1] } : undefined;\n};\n","import { Schema } from \"effect\";\nimport {\n ConnectionId,\n ScopeId,\n ScopedSecretCredentialInput,\n SecretBackedValue,\n SecretId,\n} from \"@executor-js/sdk/core\";\n\n// ---------------------------------------------------------------------------\n// Branded IDs\n// ---------------------------------------------------------------------------\n\nexport const OperationId = Schema.String.pipe(Schema.brand(\"OperationId\"));\nexport type OperationId = typeof OperationId.Type;\n\n// ---------------------------------------------------------------------------\n// HTTP\n// ---------------------------------------------------------------------------\n\nexport const HttpMethod = Schema.Literals([\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"patch\",\n \"head\",\n \"options\",\n \"trace\",\n]);\nexport type HttpMethod = typeof HttpMethod.Type;\n\nexport const ParameterLocation = Schema.Literals([\"path\", \"query\", \"header\", \"cookie\"]);\nexport type ParameterLocation = typeof ParameterLocation.Type;\n\n// ---------------------------------------------------------------------------\n// Extracted operation\n// ---------------------------------------------------------------------------\n\nexport const OperationParameter = Schema.Struct({\n name: Schema.String,\n location: ParameterLocation,\n required: Schema.Boolean,\n schema: Schema.OptionFromOptional(Schema.Unknown),\n style: Schema.OptionFromOptional(Schema.String),\n explode: Schema.OptionFromOptional(Schema.Boolean),\n allowReserved: Schema.OptionFromOptional(Schema.Boolean),\n description: Schema.OptionFromOptional(Schema.String),\n});\nexport type OperationParameter = typeof OperationParameter.Type;\n\n/**\n * OpenAPI 3.x `Encoding Object` (§4.8.15). Declared per-property inside a\n * multipart/form-data or application/x-www-form-urlencoded request body.\n *\n * - `contentType` — for multipart, overrides the per-part `Content-Type`\n * header (e.g. `application/json` for a JSON-encoded metadata part).\n * - `style` / `explode` / `allowReserved` — for form-urlencoded, control\n * array / object serialization the same way parameter-level style does.\n */\nexport const EncodingObject = Schema.Struct({\n contentType: Schema.OptionFromOptional(Schema.String),\n style: Schema.OptionFromOptional(Schema.String),\n explode: Schema.OptionFromOptional(Schema.Boolean),\n allowReserved: Schema.OptionFromOptional(Schema.Boolean),\n});\nexport type EncodingObject = typeof EncodingObject.Type;\n\nexport const MediaBinding = Schema.Struct({\n contentType: Schema.String,\n schema: Schema.OptionFromOptional(Schema.Unknown),\n encoding: Schema.OptionFromOptional(Schema.Record(Schema.String, EncodingObject)),\n});\nexport type MediaBinding = typeof MediaBinding.Type;\n\nexport const OperationRequestBody = Schema.Struct({\n required: Schema.Boolean,\n /** Default media type — first declared in spec order (not JSON-first).\n * Used when the caller does not override via the tool's `contentType` arg. */\n contentType: Schema.String,\n /** Schema of the default media type. Kept for backward compat with stored\n * bindings from before `contents` was added. */\n schema: Schema.OptionFromOptional(Schema.Unknown),\n /** All declared media types in spec order. Populated by `extract.ts`\n * going forward; older persisted bindings may have this unset and will\n * fall back to `{contentType, schema}`. */\n contents: Schema.OptionFromOptional(Schema.Array(MediaBinding)),\n});\nexport type OperationRequestBody = typeof OperationRequestBody.Type;\n\nexport const ExtractedOperation = Schema.Struct({\n operationId: OperationId,\n method: HttpMethod,\n pathTemplate: Schema.String,\n summary: Schema.OptionFromOptional(Schema.String),\n description: Schema.OptionFromOptional(Schema.String),\n tags: Schema.Array(Schema.String),\n parameters: Schema.Array(OperationParameter),\n requestBody: Schema.OptionFromOptional(OperationRequestBody),\n inputSchema: Schema.OptionFromOptional(Schema.Unknown),\n outputSchema: Schema.OptionFromOptional(Schema.Unknown),\n deprecated: Schema.Boolean,\n});\nexport type ExtractedOperation = typeof ExtractedOperation.Type;\n\nexport const ServerVariable = Schema.Struct({\n default: Schema.String,\n enum: Schema.OptionFromOptional(Schema.Array(Schema.String)),\n description: Schema.OptionFromOptional(Schema.String),\n});\nexport type ServerVariable = typeof ServerVariable.Type;\n\nexport const ServerInfo = Schema.Struct({\n url: Schema.String,\n description: Schema.OptionFromOptional(Schema.String),\n variables: Schema.OptionFromOptional(Schema.Record(Schema.String, ServerVariable)),\n});\nexport type ServerInfo = typeof ServerInfo.Type;\n\nexport const ExtractionResult = Schema.Struct({\n title: Schema.OptionFromOptional(Schema.String),\n version: Schema.OptionFromOptional(Schema.String),\n servers: Schema.Array(ServerInfo),\n operations: Schema.Array(ExtractedOperation),\n});\nexport type ExtractionResult = typeof ExtractionResult.Type;\n\n// ---------------------------------------------------------------------------\n// Operation binding — minimal invocation data (no schemas/metadata)\n// ---------------------------------------------------------------------------\n\nexport const OperationBinding = Schema.Struct({\n method: HttpMethod,\n pathTemplate: Schema.String,\n parameters: Schema.Array(OperationParameter),\n requestBody: Schema.OptionFromOptional(OperationRequestBody),\n});\nexport type OperationBinding = typeof OperationBinding.Type;\n\n// ---------------------------------------------------------------------------\n// Invocation\n// ---------------------------------------------------------------------------\n\n/**\n * A header value — either a static string or a reference to a secret.\n * Stored as JSON-serializable data.\n */\nexport const HeaderValue = SecretBackedValue;\nexport type HeaderValue = typeof HeaderValue.Type;\n\nexport const ConfiguredHeaderBinding = Schema.Struct({\n kind: Schema.Literal(\"binding\"),\n slot: Schema.String,\n prefix: Schema.optional(Schema.String),\n}).annotate({ identifier: \"OpenApiConfiguredHeaderBinding\" });\nexport type ConfiguredHeaderBinding = typeof ConfiguredHeaderBinding.Type;\n\nexport const ConfiguredHeaderValue = Schema.Union([Schema.String, ConfiguredHeaderBinding]);\nexport type ConfiguredHeaderValue = typeof ConfiguredHeaderValue.Type;\n\nexport const OpenApiCredentialInput = Schema.Union([\n ScopedSecretCredentialInput,\n HeaderValue,\n ConfiguredHeaderValue,\n]);\nexport type OpenApiCredentialInput = typeof OpenApiCredentialInput.Type;\n\nexport const OpenApiSourceBindingValue = Schema.Union([\n Schema.Struct({\n kind: Schema.Literal(\"secret\"),\n secretId: SecretId,\n secretScopeId: Schema.optional(ScopeId),\n }),\n Schema.Struct({\n kind: Schema.Literal(\"connection\"),\n connectionId: ConnectionId,\n }),\n Schema.Struct({\n kind: Schema.Literal(\"text\"),\n text: Schema.String,\n }),\n]);\nexport type OpenApiSourceBindingValue = typeof OpenApiSourceBindingValue.Type;\n\nexport const OpenApiSourceBindingInput = Schema.Struct({\n sourceId: Schema.String,\n sourceScope: ScopeId,\n scope: ScopeId,\n slot: Schema.String,\n value: OpenApiSourceBindingValue,\n});\nexport type OpenApiSourceBindingInput = typeof OpenApiSourceBindingInput.Type;\n\nexport const OpenApiSourceBindingRef = Schema.Struct({\n sourceId: Schema.String,\n sourceScopeId: ScopeId,\n scopeId: ScopeId,\n slot: Schema.String,\n value: OpenApiSourceBindingValue,\n createdAt: Schema.Date,\n updatedAt: Schema.Date,\n});\nexport type OpenApiSourceBindingRef = typeof OpenApiSourceBindingRef.Type;\n\n// ---------------------------------------------------------------------------\n// OAuth2 source config — carries source-owned slots and API-level config to\n// kick off a fresh sign-in from the source detail UI without needing any\n// one user's live connection to still exist.\n//\n// Split of responsibilities:\n// - The Source owns: the OAuth config (tokenUrl, authorizationUrl,\n// client credential slots, connection slot, scopes, flow,\n// securitySchemeName).\n// Values are a property of the target API, identical for every user\n// signing into this source. Source-owned = reconnect works even if\n// the connection row has been removed.\n// - The Connection owns: live access/refresh tokens, token expiry,\n// provider state the refresh path reads from. The connection's\n// `providerState` caches the refresh-relevant bits of the config\n// so the refresh loop never reaches back into source storage.\n//\n// This is a deliberate small duplication (scopes + tokenUrl and the static\n// client credential ids referenced by slots appear in source bindings and\n// connection providerState). The values are static per source so the two\n// copies can't drift under normal reconnect flows.\n// ---------------------------------------------------------------------------\n\nexport const OAuth2Flow = Schema.Literals([\"authorizationCode\", \"clientCredentials\"]);\nexport type OAuth2Flow = typeof OAuth2Flow.Type;\n\nexport const OAuth2SourceConfig = Schema.Struct({\n kind: Schema.Literal(\"oauth2\"),\n securitySchemeName: Schema.String,\n flow: OAuth2Flow,\n tokenUrl: Schema.String,\n authorizationUrl: Schema.NullOr(Schema.String),\n issuerUrl: Schema.optional(Schema.NullOr(Schema.String)),\n clientIdSlot: Schema.String,\n clientSecretSlot: Schema.NullOr(Schema.String),\n connectionSlot: Schema.String,\n scopes: Schema.Array(Schema.String),\n}).annotate({ identifier: \"OpenApiOAuth2SourceConfig\" });\nexport type OAuth2SourceConfig = typeof OAuth2SourceConfig.Type;\n\nexport const InvocationResult = Schema.Struct({\n status: Schema.Number,\n headers: Schema.Record(Schema.String, Schema.String),\n data: Schema.NullOr(Schema.Unknown),\n error: Schema.NullOr(Schema.Unknown),\n});\nexport type InvocationResult = typeof InvocationResult.Type;\n","import { Effect, Option } from \"effect\";\n\nimport { OpenApiExtractionError } from \"./errors\";\nimport type { ParsedDocument } from \"./parse\";\nimport {\n declaredContents,\n DocResolver,\n preferredResponseContent,\n type OperationObject,\n type ParameterObject,\n type PathItemObject,\n type RequestBodyObject,\n type ResponseObject,\n} from \"./openapi-utils\";\nimport {\n EncodingObject,\n ExtractedOperation,\n ExtractionResult,\n type HttpMethod,\n MediaBinding,\n OperationId,\n OperationParameter,\n OperationRequestBody,\n type ParameterLocation,\n ServerInfo,\n ServerVariable,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst HTTP_METHODS: readonly HttpMethod[] = [\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"patch\",\n \"head\",\n \"options\",\n \"trace\",\n];\n\nconst VALID_PARAM_LOCATIONS = new Set<string>([\"path\", \"query\", \"header\", \"cookie\"]);\n\n// ---------------------------------------------------------------------------\n// Parameter extraction\n// ---------------------------------------------------------------------------\n\nconst extractParameters = (\n pathItem: PathItemObject,\n operation: OperationObject,\n r: DocResolver,\n): OperationParameter[] => {\n const merged = new Map<string, ParameterObject>();\n\n for (const raw of pathItem.parameters ?? []) {\n const p = r.resolve<ParameterObject>(raw);\n if (!p) continue;\n merged.set(`${p.in}:${p.name}`, p);\n }\n for (const raw of operation.parameters ?? []) {\n const p = r.resolve<ParameterObject>(raw);\n if (!p) continue;\n merged.set(`${p.in}:${p.name}`, p);\n }\n\n return [...merged.values()]\n .filter((p) => VALID_PARAM_LOCATIONS.has(p.in))\n .map((p) =>\n OperationParameter.make({\n name: p.name,\n location: p.in as ParameterLocation,\n required: p.in === \"path\" ? true : p.required === true,\n schema: Option.fromNullishOr(p.schema),\n style: Option.fromNullishOr(p.style),\n explode: Option.fromNullishOr(p.explode),\n allowReserved: Option.fromNullishOr(\"allowReserved\" in p ? p.allowReserved : undefined),\n description: Option.fromNullishOr(p.description),\n }),\n );\n};\n\n// ---------------------------------------------------------------------------\n// Request body extraction\n// ---------------------------------------------------------------------------\n\nconst buildEncodingRecord = (\n encoding: Record<string, unknown> | undefined,\n): Record<string, EncodingObject> | undefined => {\n if (!encoding) return undefined;\n const out: Record<string, EncodingObject> = {};\n for (const [prop, raw] of Object.entries(encoding)) {\n if (typeof raw !== \"object\" || raw === null) continue;\n const e = raw as {\n contentType?: string;\n style?: string;\n explode?: boolean;\n allowReserved?: boolean;\n };\n out[prop] = EncodingObject.make({\n contentType: Option.fromNullishOr(e.contentType),\n style: Option.fromNullishOr(e.style),\n explode: Option.fromNullishOr(e.explode),\n allowReserved: Option.fromNullishOr(e.allowReserved),\n });\n }\n return Object.keys(out).length > 0 ? out : undefined;\n};\n\nconst extractRequestBody = (\n operation: OperationObject,\n r: DocResolver,\n): OperationRequestBody | undefined => {\n if (!operation.requestBody) return undefined;\n\n const body = r.resolve<RequestBodyObject>(operation.requestBody);\n if (!body) return undefined;\n\n const contents = declaredContents(body.content).map(({ mediaType, media }) =>\n MediaBinding.make({\n contentType: mediaType,\n schema: Option.fromNullishOr(media.schema),\n encoding: Option.fromNullishOr(\n buildEncodingRecord((media as { encoding?: Record<string, unknown> }).encoding),\n ),\n }),\n );\n if (contents.length === 0) return undefined;\n\n // Default = first declared (spec author's preferred order). Callers can\n // override at invoke time with a `contentType` arg.\n const defaultContent = contents[0]!;\n\n return OperationRequestBody.make({\n required: body.required === true,\n contentType: defaultContent.contentType,\n schema: defaultContent.schema,\n contents: Option.some(contents),\n });\n};\n\n// ---------------------------------------------------------------------------\n// Response schema extraction\n// ---------------------------------------------------------------------------\n\nconst extractOutputSchema = (operation: OperationObject, r: DocResolver): unknown | undefined => {\n if (!operation.responses) return undefined;\n\n const entries = Object.entries(operation.responses);\n const preferred = [\n ...entries.filter(([s]) => /^2\\d\\d$/.test(s)).sort(([a], [b]) => a.localeCompare(b)),\n ...entries.filter(([s]) => s === \"default\"),\n ];\n\n for (const [, ref] of preferred) {\n const resp = r.resolve<ResponseObject>(ref);\n if (!resp) continue;\n const content = preferredResponseContent(resp.content);\n if (content?.media.schema) return content.media.schema;\n }\n\n return undefined;\n};\n\n// ---------------------------------------------------------------------------\n// Input schema builder\n// ---------------------------------------------------------------------------\n\nconst buildInputSchema = (\n parameters: readonly OperationParameter[],\n requestBody: OperationRequestBody | undefined,\n): Record<string, unknown> | undefined => {\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n\n for (const param of parameters) {\n properties[param.name] = Option.getOrElse(param.schema, () => ({ type: \"string\" }));\n if (param.required) required.push(param.name);\n }\n\n if (requestBody) {\n properties.body = Option.getOrElse(requestBody.schema, () => ({ type: \"object\" }));\n if (requestBody.required) required.push(\"body\");\n\n // When the spec declares multiple media types for this requestBody,\n // expose `contentType` so the model can pick. Default = first declared.\n // `body` schema tracks the default; the model is responsible for\n // supplying a body shape that matches whichever contentType it picks.\n const contents = Option.getOrUndefined(requestBody.contents);\n if (contents && contents.length > 1) {\n properties.contentType = {\n type: \"string\",\n enum: contents.map((c) => c.contentType),\n default: requestBody.contentType,\n description:\n \"Content-Type for the request body. Declared media types for this operation, in spec order.\",\n };\n }\n }\n\n if (Object.keys(properties).length === 0) return undefined;\n\n return {\n type: \"object\",\n properties,\n ...(required.length > 0 ? { required } : {}),\n additionalProperties: false,\n };\n};\n\n// ---------------------------------------------------------------------------\n// Operation ID derivation\n// ---------------------------------------------------------------------------\n\nconst deriveOperationId = (\n method: HttpMethod,\n pathTemplate: string,\n operation: OperationObject,\n): string =>\n operation.operationId ??\n (`${method}_${pathTemplate.replace(/[^a-zA-Z0-9]+/g, \"_\")}`.replace(/^_+|_+$/g, \"\") ||\n `${method}_operation`);\n\n// ---------------------------------------------------------------------------\n// Server extraction\n// ---------------------------------------------------------------------------\n\nconst extractServers = (doc: ParsedDocument): ServerInfo[] =>\n (doc.servers ?? []).flatMap((server) => {\n if (!server.url) return [];\n const vars = server.variables\n ? Object.fromEntries(\n Object.entries(server.variables).flatMap(([name, v]) => {\n if (v.default === undefined || v.default === null) return [];\n const enumValues = Array.isArray(v.enum)\n ? v.enum.filter((x): x is string => typeof x === \"string\")\n : undefined;\n return [\n [\n name,\n ServerVariable.make({\n default: String(v.default),\n enum:\n enumValues && enumValues.length > 0 ? Option.some(enumValues) : Option.none(),\n description: Option.fromNullishOr(v.description),\n }),\n ],\n ];\n }),\n )\n : undefined;\n return [\n ServerInfo.make({\n url: server.url,\n description: Option.fromNullishOr(server.description),\n variables: vars && Object.keys(vars).length > 0 ? Option.some(vars) : Option.none(),\n }),\n ];\n });\n\n// ---------------------------------------------------------------------------\n// Main extraction\n// ---------------------------------------------------------------------------\n\n/** Extract all operations from a bundled OpenAPI 3.x document */\nexport const extract = Effect.fn(\"OpenApi.extract\")(function* (doc: ParsedDocument) {\n const paths = doc.paths;\n if (!paths) {\n return yield* new OpenApiExtractionError({\n message: \"OpenAPI document has no paths defined\",\n });\n }\n\n const r = new DocResolver(doc);\n const operations: ExtractedOperation[] = [];\n\n for (const [pathTemplate, pathItem] of Object.entries(paths).sort(([a], [b]) =>\n a.localeCompare(b),\n )) {\n if (!pathItem) continue;\n\n for (const method of HTTP_METHODS) {\n const operation = pathItem[method];\n if (!operation) continue;\n\n const parameters = extractParameters(pathItem, operation, r);\n const requestBody = extractRequestBody(operation, r);\n const inputSchema = buildInputSchema(parameters, requestBody);\n const outputSchema = extractOutputSchema(operation, r);\n const tags = (operation.tags ?? []).filter((t) => t.trim().length > 0);\n\n operations.push(\n ExtractedOperation.make({\n operationId: OperationId.make(deriveOperationId(method, pathTemplate, operation)),\n method,\n pathTemplate,\n summary: Option.fromNullishOr(operation.summary),\n description: Option.fromNullishOr(operation.description),\n tags,\n parameters,\n requestBody: Option.fromNullishOr(requestBody),\n inputSchema: Option.fromNullishOr(inputSchema),\n outputSchema: Option.fromNullishOr(outputSchema),\n deprecated: operation.deprecated === true,\n }),\n );\n }\n }\n\n return ExtractionResult.make({\n title: Option.fromNullishOr(doc.info?.title),\n version: Option.fromNullishOr(doc.info?.version),\n servers: extractServers(doc),\n operations,\n });\n});\n","import { Effect, Option } from \"effect\";\nimport { Schema } from \"effect\";\n\nimport { parse, resolveSpecText, type ParsedDocument } from \"./parse\";\nimport { extract } from \"./extract\";\nimport { DocResolver } from \"./openapi-utils\";\nimport { HttpMethod, ServerInfo, type ExtractionResult } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// OAuth 2.0 flows — one entry per supported grant type\n// ---------------------------------------------------------------------------\n\n/** Scopes declared by a flow: `{ scopeName: description }` */\nconst OAuth2Scopes = Schema.Record(Schema.String, Schema.String);\nconst SecuritySchemeType = Schema.Literals([\"http\", \"apiKey\", \"oauth2\", \"openIdConnect\"]);\ntype SecuritySchemeType = typeof SecuritySchemeType.Type;\n\nconst decodeSecuritySchemeType = Schema.decodeUnknownOption(SecuritySchemeType);\n\nexport const OAuth2AuthorizationCodeFlow = Schema.Struct({\n authorizationUrl: Schema.String,\n tokenUrl: Schema.String,\n refreshUrl: Schema.OptionFromOptional(Schema.String),\n scopes: OAuth2Scopes,\n});\nexport type OAuth2AuthorizationCodeFlow = typeof OAuth2AuthorizationCodeFlow.Type;\n\nexport const OAuth2ClientCredentialsFlow = Schema.Struct({\n tokenUrl: Schema.String,\n refreshUrl: Schema.OptionFromOptional(Schema.String),\n scopes: OAuth2Scopes,\n});\nexport type OAuth2ClientCredentialsFlow = typeof OAuth2ClientCredentialsFlow.Type;\n\nexport const OAuth2Flows = Schema.Struct({\n authorizationCode: Schema.OptionFromOptional(OAuth2AuthorizationCodeFlow),\n clientCredentials: Schema.OptionFromOptional(OAuth2ClientCredentialsFlow),\n});\nexport type OAuth2Flows = typeof OAuth2Flows.Type;\n\n// ---------------------------------------------------------------------------\n// Security scheme — what the spec declares it needs\n// ---------------------------------------------------------------------------\n\nexport const SecurityScheme = Schema.Struct({\n /** Key name in components.securitySchemes (e.g. \"api_token\") */\n name: Schema.String,\n /** OpenAPI security scheme type */\n type: SecuritySchemeType,\n /** For type: \"http\" — e.g. \"bearer\", \"basic\" */\n scheme: Schema.OptionFromOptional(Schema.String),\n /** For type: \"http\" with scheme \"bearer\" — e.g. \"JWT\" */\n bearerFormat: Schema.OptionFromOptional(Schema.String),\n /** For type: \"apiKey\" — where the key goes */\n in: Schema.OptionFromOptional(Schema.Literals([\"header\", \"query\", \"cookie\"])),\n /** For type: \"apiKey\" — the header/query/cookie name */\n headerName: Schema.OptionFromOptional(Schema.String),\n description: Schema.OptionFromOptional(Schema.String),\n /** For type: \"oauth2\" — declared flows (authorizationCode / clientCredentials only; implicit and password are deprecated). */\n flows: Schema.OptionFromOptional(OAuth2Flows),\n /** For type: \"openIdConnect\" — the discovery URL. */\n openIdConnectUrl: Schema.OptionFromOptional(Schema.String),\n});\nexport type SecurityScheme = typeof SecurityScheme.Type;\n\n// ---------------------------------------------------------------------------\n// Auth strategy — a valid combination of security schemes\n// ---------------------------------------------------------------------------\n\nexport const AuthStrategy = Schema.Struct({\n /** The security schemes required together for this strategy */\n schemes: Schema.Array(Schema.String),\n});\nexport type AuthStrategy = typeof AuthStrategy.Type;\n\n// ---------------------------------------------------------------------------\n// Header preset — derived from an auth strategy\n// ---------------------------------------------------------------------------\n\nexport const HeaderPreset = Schema.Struct({\n /** Human-readable label for the UI (e.g. \"Bearer Token\", \"API Key + Email\") */\n label: Schema.String,\n /** Headers this strategy needs. Value is null when the user must provide it. */\n headers: Schema.Record(Schema.String, Schema.NullOr(Schema.String)),\n /** Which headers should be stored as secrets */\n secretHeaders: Schema.Array(Schema.String),\n});\nexport type HeaderPreset = typeof HeaderPreset.Type;\n\n// ---------------------------------------------------------------------------\n// OAuth2 preset — derived from an oauth2 security scheme + a flow choice\n// ---------------------------------------------------------------------------\n\nexport const OAuth2Preset = Schema.Struct({\n /** Human-readable label for the UI (e.g. \"OAuth2 (Authorization Code) — oauth_app\") */\n label: Schema.String,\n /** The source security scheme this preset came from (components.securitySchemes key). */\n securitySchemeName: Schema.String,\n /** Which OAuth2 flow this preset uses. */\n flow: Schema.Literals([\"authorizationCode\", \"clientCredentials\"]),\n /** For authorizationCode: user-agent redirect URL (from the spec). */\n authorizationUrl: Schema.OptionFromOptional(Schema.String),\n /** Token endpoint to exchange the code / refresh. */\n tokenUrl: Schema.String,\n /** Optional refresh endpoint if the spec declares one separately. */\n refreshUrl: Schema.OptionFromOptional(Schema.String),\n /** Declared scopes for this flow: `{ scope: description }`. */\n scopes: Schema.Record(Schema.String, Schema.String),\n});\nexport type OAuth2Preset = typeof OAuth2Preset.Type;\n\n// ---------------------------------------------------------------------------\n// Preview operation — lightweight shape for the add-source UI list\n// ---------------------------------------------------------------------------\n\nexport const PreviewOperation = Schema.Struct({\n operationId: Schema.String,\n method: HttpMethod,\n path: Schema.String,\n summary: Schema.OptionFromOptional(Schema.String),\n tags: Schema.Array(Schema.String),\n deprecated: Schema.Boolean,\n});\nexport type PreviewOperation = typeof PreviewOperation.Type;\n\n// ---------------------------------------------------------------------------\n// Spec preview — everything the frontend needs\n// ---------------------------------------------------------------------------\n\nexport const SpecPreview = Schema.Struct({\n title: Schema.OptionFromOptional(Schema.String),\n version: Schema.OptionFromOptional(Schema.String),\n /** Reuses ServerInfo from extraction */\n servers: Schema.Array(ServerInfo),\n operationCount: Schema.Number,\n /** Lightweight operation list for the add-source UI */\n operations: Schema.Array(PreviewOperation),\n tags: Schema.Array(Schema.String),\n securitySchemes: Schema.Array(SecurityScheme),\n /** Valid auth strategies (each is a set of schemes used together) */\n authStrategies: Schema.Array(AuthStrategy),\n /** Pre-built header presets derived from auth strategies */\n headerPresets: Schema.Array(HeaderPreset),\n /** OAuth2 presets — one per (oauth2 scheme × supported flow) combination */\n oauth2Presets: Schema.Array(OAuth2Preset),\n});\nexport type SpecPreview = typeof SpecPreview.Type;\n\n// ---------------------------------------------------------------------------\n// Security scheme extraction\n// ---------------------------------------------------------------------------\n\nconst stringRecord = (value: unknown): Record<string, string> => {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (typeof v === \"string\") out[k] = v;\n }\n return out;\n};\n\nconst extractFlows = (rawFlows: unknown): Option.Option<OAuth2Flows> => {\n if (!rawFlows || typeof rawFlows !== \"object\") return Option.none();\n const flows = rawFlows as Record<string, unknown>;\n\n const parseFlow = <K extends \"authorizationCode\" | \"clientCredentials\">(key: K): unknown =>\n flows[key];\n\n let authorizationCode: Option.Option<OAuth2AuthorizationCodeFlow> = Option.none();\n const authCodeRaw = parseFlow(\"authorizationCode\");\n if (authCodeRaw && typeof authCodeRaw === \"object\") {\n const f = authCodeRaw as Record<string, unknown>;\n const authUrl = typeof f.authorizationUrl === \"string\" ? f.authorizationUrl : null;\n const tokenUrl = typeof f.tokenUrl === \"string\" ? f.tokenUrl : null;\n if (authUrl && tokenUrl) {\n authorizationCode = Option.some(\n OAuth2AuthorizationCodeFlow.make({\n authorizationUrl: authUrl,\n tokenUrl,\n refreshUrl: Option.fromNullishOr(\n typeof f.refreshUrl === \"string\" ? f.refreshUrl : undefined,\n ),\n scopes: stringRecord(f.scopes),\n }),\n );\n }\n }\n\n let clientCredentials: Option.Option<OAuth2ClientCredentialsFlow> = Option.none();\n const ccRaw = parseFlow(\"clientCredentials\");\n if (ccRaw && typeof ccRaw === \"object\") {\n const f = ccRaw as Record<string, unknown>;\n const tokenUrl = typeof f.tokenUrl === \"string\" ? f.tokenUrl : null;\n if (tokenUrl) {\n clientCredentials = Option.some(\n OAuth2ClientCredentialsFlow.make({\n tokenUrl,\n refreshUrl: Option.fromNullishOr(\n typeof f.refreshUrl === \"string\" ? f.refreshUrl : undefined,\n ),\n scopes: stringRecord(f.scopes),\n }),\n );\n }\n }\n\n if (Option.isNone(authorizationCode) && Option.isNone(clientCredentials)) {\n return Option.none();\n }\n return Option.some(OAuth2Flows.make({ authorizationCode, clientCredentials }));\n};\n\nconst extractSecuritySchemes = (\n rawSchemes: Record<string, unknown>,\n resolver: DocResolver,\n): SecurityScheme[] =>\n Object.entries(rawSchemes).flatMap(([name, schemeOrRef]) => {\n if (!schemeOrRef || typeof schemeOrRef !== \"object\") return [];\n // Resolve $ref so schemes defined via `$ref` aren't silently dropped.\n const resolved = resolver.resolve<Record<string, unknown>>(\n schemeOrRef as Record<string, unknown>,\n );\n if (!resolved || typeof resolved !== \"object\") return [];\n const scheme = resolved;\n\n const type = decodeSecuritySchemeType(scheme.type);\n if (Option.isNone(type)) return [];\n const schemeType = type.value;\n\n return [\n SecurityScheme.make({\n name,\n type: schemeType,\n scheme: Option.fromNullishOr(scheme.scheme as string | undefined),\n bearerFormat: Option.fromNullishOr(scheme.bearerFormat as string | undefined),\n in: Option.fromNullishOr(scheme.in as \"header\" | \"query\" | \"cookie\" | undefined),\n headerName: Option.fromNullishOr(scheme.name as string | undefined),\n description: Option.fromNullishOr(scheme.description as string | undefined),\n flows: schemeType === \"oauth2\" ? extractFlows(scheme.flows) : Option.none(),\n openIdConnectUrl: Option.fromNullishOr(scheme.openIdConnectUrl as string | undefined),\n }),\n ];\n });\n\n// ---------------------------------------------------------------------------\n// Header preset builder\n// ---------------------------------------------------------------------------\n\nconst buildHeaderPresets = (\n schemes: readonly SecurityScheme[],\n strategies: readonly AuthStrategy[],\n): HeaderPreset[] => {\n const schemeMap = new Map(schemes.map((s) => [s.name, s]));\n\n return strategies.flatMap((strategy) => {\n const resolved = strategy.schemes\n .map((name) => schemeMap.get(name))\n .filter((s): s is SecurityScheme => s !== undefined);\n\n if (resolved.length === 0) return [];\n\n const headers: Record<string, string | null> = {};\n const secretHeaders: string[] = [];\n const labelParts: string[] = [];\n\n for (const scheme of resolved) {\n if (scheme.type === \"http\" && Option.getOrElse(scheme.scheme, () => \"\") === \"bearer\") {\n headers[\"Authorization\"] = null;\n secretHeaders.push(\"Authorization\");\n labelParts.push(\"Bearer Token\");\n } else if (scheme.type === \"http\" && Option.getOrElse(scheme.scheme, () => \"\") === \"basic\") {\n headers[\"Authorization\"] = null;\n secretHeaders.push(\"Authorization\");\n labelParts.push(\"Basic Auth\");\n } else if (scheme.type === \"apiKey\" && Option.getOrElse(scheme.in, () => \"\") === \"header\") {\n const headerName = Option.getOrElse(scheme.headerName, () => scheme.name);\n headers[headerName] = null;\n secretHeaders.push(headerName);\n labelParts.push(scheme.name);\n } else if (scheme.type === \"apiKey\") {\n labelParts.push(`${scheme.name} (${Option.getOrElse(scheme.in, () => \"unknown\")})`);\n } else if (scheme.type === \"oauth2\" || scheme.type === \"openIdConnect\") {\n return [];\n } else {\n labelParts.push(scheme.name);\n }\n }\n\n if (Object.keys(headers).length === 0 && resolved.length > 0) {\n return [\n HeaderPreset.make({\n label: labelParts.join(\" + \"),\n headers: {},\n secretHeaders: [],\n }),\n ];\n }\n\n return [\n HeaderPreset.make({\n label: labelParts.join(\" + \"),\n headers,\n secretHeaders,\n }),\n ];\n });\n};\n\n// ---------------------------------------------------------------------------\n// OAuth2 preset builder\n// ---------------------------------------------------------------------------\n\nconst buildOAuth2Presets = (schemes: readonly SecurityScheme[]): OAuth2Preset[] => {\n const presets: OAuth2Preset[] = [];\n for (const scheme of schemes) {\n if (scheme.type !== \"oauth2\") continue;\n if (Option.isNone(scheme.flows)) continue;\n const flows = scheme.flows.value;\n\n if (Option.isSome(flows.authorizationCode)) {\n const flow = flows.authorizationCode.value;\n presets.push(\n OAuth2Preset.make({\n label: `OAuth2 Authorization Code · ${scheme.name}`,\n securitySchemeName: scheme.name,\n flow: \"authorizationCode\",\n authorizationUrl: Option.some(flow.authorizationUrl),\n tokenUrl: flow.tokenUrl,\n refreshUrl: flow.refreshUrl,\n scopes: flow.scopes,\n }),\n );\n }\n\n if (Option.isSome(flows.clientCredentials)) {\n const flow = flows.clientCredentials.value;\n presets.push(\n OAuth2Preset.make({\n label: `OAuth2 Client Credentials · ${scheme.name}`,\n securitySchemeName: scheme.name,\n flow: \"clientCredentials\",\n authorizationUrl: Option.none(),\n tokenUrl: flow.tokenUrl,\n refreshUrl: flow.refreshUrl,\n scopes: flow.scopes,\n }),\n );\n }\n }\n return presets;\n};\n\n// ---------------------------------------------------------------------------\n// Collect unique tags from extraction result\n// ---------------------------------------------------------------------------\n\nconst collectTags = (result: ExtractionResult): string[] => {\n const tagSet = new Set<string>();\n for (const op of result.operations) {\n for (const tag of op.tags) tagSet.add(tag);\n }\n return [...tagSet].sort();\n};\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/** Preview an OpenAPI spec — extract metadata without registering anything.\n * Accepts either a URL or raw JSON/YAML text. */\nexport const previewSpec = Effect.fn(\"OpenApi.previewSpec\")(function* (input: string) {\n const specText = yield* resolveSpecText(input);\n const doc: ParsedDocument = yield* parse(specText);\n const result = yield* extract(doc);\n\n const resolver = new DocResolver(doc);\n const securitySchemes = extractSecuritySchemes(doc.components?.securitySchemes ?? {}, resolver);\n\n const rawSecurity = (doc.security ?? []) as Array<Record<string, unknown>>;\n const declaredStrategies = rawSecurity.map((entry) =>\n AuthStrategy.make({ schemes: Object.keys(entry) }),\n );\n // Fall back to one strategy per scheme when the spec only declares schemes\n // under components (e.g. Sentry) so the user still sees auth options.\n const authStrategies =\n declaredStrategies.length > 0\n ? declaredStrategies\n : securitySchemes.map((scheme) => AuthStrategy.make({ schemes: [scheme.name] }));\n\n return SpecPreview.make({\n title: result.title,\n version: result.version,\n servers: result.servers,\n operationCount: result.operations.length,\n operations: result.operations.map((op) =>\n PreviewOperation.make({\n operationId: op.operationId,\n method: op.method,\n path: op.pathTemplate,\n summary: op.summary,\n tags: op.tags,\n deprecated: op.deprecated,\n }),\n ),\n tags: collectTags(result),\n securitySchemes,\n authStrategies,\n headerPresets: buildHeaderPresets(securitySchemes, authStrategies),\n oauth2Presets: buildOAuth2Presets(securitySchemes),\n });\n});\n","import { Effect, Option, Schema } from \"effect\";\n\nimport { defineSchema, type StorageDeps, type StorageFailure } from \"@executor-js/sdk/core\";\n\nimport {\n ConfiguredHeaderValue,\n ConfiguredHeaderBinding,\n OAuth2SourceConfig,\n OperationBinding,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Schema:\n// - openapi_source: one row per onboarded spec (baseUrl, oauth2, ...)\n// - openapi_operation: one row per operation binding keyed by tool id\n// ---------------------------------------------------------------------------\n\n// Each of the source-owned credential-structure child tables (`openapi_source_header`,\n// `openapi_source_query_param`,\n// `openapi_source_spec_fetch_header`,\n// `openapi_source_spec_fetch_query_param`) shares the same column shape:\n// id/scope_id/source_id/name plus a `kind` enum that discriminates a\n// literal text value from a credential slot binding (with optional prefix).\n// The fields are inlined per-table because `defineSchema`'s type\n// narrowing relies on the literal types staying on the original\n// declaration site.\n\nexport const openapiSchema = defineSchema({\n openapi_source: {\n fields: {\n id: { type: \"string\", required: true },\n scope_id: { type: \"string\", required: true, index: true },\n name: { type: \"string\", required: true },\n spec: { type: \"string\", required: true },\n // Origin URL the spec was fetched from. Set when `addSpec` was\n // invoked with an http(s) URL; null when the caller passed raw\n // spec text. Drives `canRefresh` on the core source row and\n // is the address re-fetched on `refreshSource`.\n source_url: { type: \"string\", required: false },\n base_url: { type: \"string\", required: false },\n // OAuth2 stays JSON because it is one typed source-owned config object\n // carrying slot names, not concrete secret/connection ids.\n oauth2: { type: \"json\", required: false },\n },\n },\n openapi_operation: {\n fields: {\n id: { type: \"string\", required: true },\n scope_id: { type: \"string\", required: true, index: true },\n source_id: { type: \"string\", required: true, index: true },\n binding: { type: \"json\", required: true },\n },\n },\n openapi_source_header: {\n fields: {\n id: { type: \"string\", required: true },\n scope_id: { type: \"string\", required: true, index: true },\n source_id: { type: \"string\", required: true, index: true },\n name: { type: \"string\", required: true },\n kind: { type: [\"text\", \"binding\"], required: true },\n text_value: { type: \"string\", required: false },\n slot_key: { type: \"string\", required: false },\n prefix: { type: \"string\", required: false },\n },\n },\n openapi_source_query_param: {\n fields: {\n id: { type: \"string\", required: true },\n scope_id: { type: \"string\", required: true, index: true },\n source_id: { type: \"string\", required: true, index: true },\n name: { type: \"string\", required: true },\n kind: { type: [\"text\", \"binding\"], required: true },\n text_value: { type: \"string\", required: false },\n slot_key: { type: \"string\", required: false },\n prefix: { type: \"string\", required: false },\n },\n },\n openapi_source_spec_fetch_header: {\n fields: {\n id: { type: \"string\", required: true },\n scope_id: { type: \"string\", required: true, index: true },\n source_id: { type: \"string\", required: true, index: true },\n name: { type: \"string\", required: true },\n kind: { type: [\"text\", \"binding\"], required: true },\n text_value: { type: \"string\", required: false },\n slot_key: { type: \"string\", required: false },\n prefix: { type: \"string\", required: false },\n },\n },\n openapi_source_spec_fetch_query_param: {\n fields: {\n id: { type: \"string\", required: true },\n scope_id: { type: \"string\", required: true, index: true },\n source_id: { type: \"string\", required: true, index: true },\n name: { type: \"string\", required: true },\n kind: { type: [\"text\", \"binding\"], required: true },\n text_value: { type: \"string\", required: false },\n slot_key: { type: \"string\", required: false },\n prefix: { type: \"string\", required: false },\n },\n },\n});\n\nexport type OpenapiSchema = typeof openapiSchema;\n\n// ---------------------------------------------------------------------------\n// In-memory shapes\n// ---------------------------------------------------------------------------\n\nexport interface SourceConfig {\n readonly spec: string;\n /** Origin URL when the spec was fetched from http(s). Absent for\n * raw-text adds. Persisted so `refreshSource` can re-fetch. */\n readonly sourceUrl?: string;\n readonly baseUrl?: string;\n readonly namespace?: string;\n readonly headers?: Record<string, ConfiguredHeaderValue>;\n readonly queryParams?: Record<string, ConfiguredHeaderValue>;\n readonly specFetchCredentials?: OpenApiSpecFetchCredentials;\n readonly oauth2?: OAuth2SourceConfig;\n}\n\nexport interface OpenApiSpecFetchCredentials {\n readonly headers?: Record<string, ConfiguredHeaderValue>;\n readonly queryParams?: Record<string, ConfiguredHeaderValue>;\n}\n\nexport interface StoredSource {\n readonly namespace: string;\n /** Executor scope id this source row lives in. Writes stamp this on\n * `scope_id`; reads return whichever scope's row the adapter's\n * fall-through filter sees first. */\n readonly scope: string;\n readonly name: string;\n readonly config: SourceConfig;\n}\n\n// ---------------------------------------------------------------------------\n// Schema-class mirror of StoredSource for the API layer, where we need\n// an encodable/decodable shape for HTTP responses.\n// ---------------------------------------------------------------------------\n\nexport const StoredSourceSchema = Schema.Struct({\n namespace: Schema.String,\n scope: Schema.String,\n name: Schema.String,\n config: Schema.Struct({\n spec: Schema.String,\n sourceUrl: Schema.optional(Schema.String),\n baseUrl: Schema.optional(Schema.String),\n namespace: Schema.optional(Schema.String),\n headers: Schema.optional(Schema.Record(Schema.String, ConfiguredHeaderValue)),\n queryParams: Schema.optional(Schema.Record(Schema.String, ConfiguredHeaderValue)),\n specFetchCredentials: Schema.optional(\n Schema.Struct({\n headers: Schema.optional(Schema.Record(Schema.String, ConfiguredHeaderValue)),\n queryParams: Schema.optional(Schema.Record(Schema.String, ConfiguredHeaderValue)),\n }),\n ),\n // Canonical source-owned OAuth config. Concrete client credentials\n // and connection ids live in OpenAPI-owned scoped binding rows.\n oauth2: Schema.optional(OAuth2SourceConfig),\n }),\n}).annotate({ identifier: \"OpenApiStoredSource\" });\nexport type StoredSourceSchema = typeof StoredSourceSchema.Type;\n\nexport type StoredSourceSchemaType = typeof StoredSourceSchema.Type;\n\nexport interface StoredOperation {\n readonly toolId: string;\n readonly sourceId: string;\n readonly binding: OperationBinding;\n}\n\n// ---------------------------------------------------------------------------\n// Schema encode/decode — OperationBinding has Option fields, so we must use\n// Schema.encode/decode rather than plain JSON to round-trip correctly.\n// ---------------------------------------------------------------------------\n\nconst encodeBinding = Schema.encodeSync(OperationBinding);\nconst decodeBinding = Schema.decodeUnknownSync(OperationBinding);\nconst decodeBindingJson = Schema.decodeUnknownSync(Schema.fromJsonString(OperationBinding));\n\nconst decodeOAuth2SourceConfigOption = Schema.decodeUnknownOption(OAuth2SourceConfig);\nconst decodeOAuth2SourceConfigJsonOption = Schema.decodeUnknownOption(\n Schema.fromJsonString(OAuth2SourceConfig),\n);\nconst encodeOAuth2SourceConfig = Schema.encodeSync(OAuth2SourceConfig);\n\nconst NullableString = Schema.NullOr(Schema.String);\nconst OptionalNullableString = Schema.optional(NullableString);\n\nconst ChildStorageRow = Schema.Struct({\n name: Schema.String,\n kind: Schema.Literals([\"text\", \"binding\"]),\n text_value: OptionalNullableString,\n slot_key: OptionalNullableString,\n prefix: OptionalNullableString,\n});\nconst decodeChildStorageRowOption = Schema.decodeUnknownOption(ChildStorageRow);\n\nconst SourceStorageRow = Schema.Struct({\n id: Schema.String,\n scope_id: Schema.String,\n name: Schema.String,\n spec: Schema.String,\n source_url: OptionalNullableString,\n base_url: OptionalNullableString,\n oauth2: Schema.optional(Schema.Unknown),\n});\nconst decodeSourceStorageRow = Schema.decodeUnknownSync(SourceStorageRow);\n\nconst OperationStorageRow = Schema.Struct({\n id: Schema.String,\n source_id: Schema.String,\n binding: Schema.Unknown,\n});\nconst decodeOperationStorageRow = Schema.decodeUnknownSync(OperationStorageRow);\n\ninterface ChildRow {\n readonly id: string;\n readonly scope_id: string;\n readonly source_id: string;\n readonly name: string;\n readonly kind: \"text\" | \"binding\";\n readonly text_value?: string;\n readonly slot_key?: string;\n readonly prefix?: string;\n // Index signature to satisfy adapter's `RowInput` shape (the typed\n // adapter exposes its row shape with one).\n readonly [k: string]: unknown;\n}\n\n// Collapse a structural credential map into the flat child-table column\n// shape used by openapi_source_header, openapi_source_query_param, and\n// the two openapi_source_spec_fetch_* tables. Returns one record per entry.\nconst valueMapToChildRows = (\n sourceId: string,\n scope: string,\n values: Record<string, ConfiguredHeaderValue> | undefined,\n): readonly ChildRow[] => {\n if (!values) return [];\n return Object.entries(values).map(([name, value]) => {\n const id = JSON.stringify([sourceId, name]);\n if (typeof value === \"string\") {\n return {\n id,\n scope_id: scope,\n source_id: sourceId,\n name,\n kind: \"text\",\n text_value: value,\n };\n }\n return {\n id,\n scope_id: scope,\n source_id: sourceId,\n name,\n kind: \"binding\",\n slot_key: value.slot,\n prefix: value.prefix,\n };\n });\n};\n\nconst childRowsToValueMap = (\n rows: readonly Record<string, unknown>[],\n): Record<string, ConfiguredHeaderValue> => {\n const out: Record<string, ConfiguredHeaderValue> = {};\n for (const row of rows) {\n const decoded = decodeChildStorageRowOption(row);\n if (Option.isSome(decoded)) {\n const child = decoded.value;\n if (child.kind === \"binding\" && child.slot_key != null) {\n out[child.name] =\n child.prefix != null\n ? ConfiguredHeaderBinding.make({\n kind: \"binding\",\n slot: child.slot_key,\n prefix: child.prefix,\n })\n : ConfiguredHeaderBinding.make({\n kind: \"binding\",\n slot: child.slot_key,\n });\n } else if (child.kind === \"text\" && child.text_value != null) {\n out[child.name] = child.text_value;\n }\n }\n }\n return out;\n};\n\n// oxlint-disable-next-line executor/no-explicit-unknown-record -- boundary: storage adapter accepts JSON object columns\nconst toJsonRecord = (value: unknown): Record<string, unknown> => value as Record<string, unknown>;\n\nconst slugifySlotPart = (value: string): string =>\n value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\") || \"default\";\n\nexport const headerBindingSlot = (headerName: string): string =>\n `header:${slugifySlotPart(headerName)}`;\n\nexport const queryParamBindingSlot = (name: string): string =>\n `query_param:${slugifySlotPart(name)}`;\n\nexport const oauth2ClientIdSlot = (securitySchemeName: string): string =>\n `oauth2:${slugifySlotPart(securitySchemeName)}:client-id`;\n\nexport const oauth2ClientSecretSlot = (securitySchemeName: string): string =>\n `oauth2:${slugifySlotPart(securitySchemeName)}:client-secret`;\n\nexport const oauth2ConnectionSlot = (securitySchemeName: string): string =>\n `oauth2:${slugifySlotPart(securitySchemeName)}:connection`;\n\nconst normalizeStoredOAuth2 = (value: unknown): OAuth2SourceConfig | undefined => {\n if (value == null) return undefined;\n const sourceConfig =\n typeof value === \"string\"\n ? decodeOAuth2SourceConfigJsonOption(value)\n : decodeOAuth2SourceConfigOption(value);\n if (Option.isSome(sourceConfig)) {\n return sourceConfig.value;\n }\n return undefined;\n};\n\n// ---------------------------------------------------------------------------\n// Store interface\n// ---------------------------------------------------------------------------\n\n// Every method routes through the typed adapter (`ctx.storage.adapter`)\n// so the typed error channel is `StorageFailure`. Schema-decode failures\n// inside `Effect.gen` land as defects, not typed errors, and are caught\n// by the HTTP edge's observability middleware.\n//\n// Every read/write that targets a single row pins BOTH the natural id\n// (namespace, toolId, sessionId) AND the owning `scope_id`. The store\n// runs behind the scoped adapter (which auto-injects `scope_id IN\n// (stack)`), so a bare `{id}` filter resolves to any matching row in\n// the stack in adapter-iteration order. For shadowed rows (same id at\n// multiple scopes — e.g. an org-level openapi source with a per-user\n// override), that's a scope-isolation bug: updates and deletes can\n// land on the wrong scope's row. Callers thread the resolved scope in\n// (typically `path.scopeId` for HTTP, `toolRow.scope_id` /\n// `input.scope` for invokeTool/lifecycle) so every keyed mutation\n// targets exactly one row.\nexport interface OpenapiStore {\n readonly upsertSource: (\n input: StoredSource,\n operations: readonly StoredOperation[],\n ) => Effect.Effect<void, StorageFailure>;\n\n readonly updateSourceMeta: (\n namespace: string,\n scope: string,\n patch: {\n readonly name?: string;\n readonly baseUrl?: string;\n readonly headers?: Record<string, ConfiguredHeaderValue>;\n readonly queryParams?: Record<string, ConfiguredHeaderValue>;\n readonly oauth2?: OAuth2SourceConfig;\n },\n ) => Effect.Effect<void, StorageFailure>;\n\n readonly getSource: (\n namespace: string,\n scope: string,\n ) => Effect.Effect<StoredSource | null, StorageFailure>;\n\n readonly listSources: () => Effect.Effect<readonly StoredSource[], StorageFailure>;\n\n readonly getOperationByToolId: (\n toolId: string,\n scope: string,\n ) => Effect.Effect<StoredOperation | null, StorageFailure>;\n\n readonly listOperationsBySource: (\n sourceId: string,\n scope: string,\n ) => Effect.Effect<readonly StoredOperation[], StorageFailure>;\n\n readonly removeSource: (namespace: string, scope: string) => Effect.Effect<void, StorageFailure>;\n\n // ---------------------------------------------------------------------\n // Query params and spec-fetch credentials are source-owned structural\n // rows only. Secret/connection ownership and usages live in core\n // `credential_binding`.\n}\n\n// ---------------------------------------------------------------------------\n// Default store implementation\n// ---------------------------------------------------------------------------\n\nexport const makeDefaultOpenapiStore = ({ adapter }: StorageDeps<OpenapiSchema>): OpenapiStore => {\n const loadChildValueMap = (\n model:\n | \"openapi_source_header\"\n | \"openapi_source_query_param\"\n | \"openapi_source_spec_fetch_header\"\n | \"openapi_source_spec_fetch_query_param\",\n sourceId: string,\n scope: string,\n ) =>\n adapter\n .findMany({\n model,\n where: [\n { field: \"source_id\", value: sourceId },\n { field: \"scope_id\", value: scope },\n ],\n })\n .pipe(Effect.map(childRowsToValueMap));\n\n const rowToSource = (row: Record<string, unknown>): Effect.Effect<StoredSource, StorageFailure> =>\n Effect.gen(function* () {\n const sourceRow = decodeSourceStorageRow(row);\n const sourceId = sourceRow.id;\n const scope = sourceRow.scope_id;\n const oauth2 = normalizeStoredOAuth2(sourceRow.oauth2);\n\n const headers = yield* loadChildValueMap(\"openapi_source_header\", sourceId, scope);\n const queryParams = yield* loadChildValueMap(\"openapi_source_query_param\", sourceId, scope);\n const specFetchHeaders = yield* loadChildValueMap(\n \"openapi_source_spec_fetch_header\",\n sourceId,\n scope,\n );\n const specFetchQueryParams = yield* loadChildValueMap(\n \"openapi_source_spec_fetch_query_param\",\n sourceId,\n scope,\n );\n const specFetchCredentials: OpenApiSpecFetchCredentials | undefined =\n Object.keys(specFetchHeaders).length === 0 && Object.keys(specFetchQueryParams).length === 0\n ? undefined\n : {\n ...(Object.keys(specFetchHeaders).length > 0 ? { headers: specFetchHeaders } : {}),\n ...(Object.keys(specFetchQueryParams).length > 0\n ? { queryParams: specFetchQueryParams }\n : {}),\n };\n\n return {\n namespace: sourceId,\n scope,\n name: sourceRow.name,\n config: {\n spec: sourceRow.spec,\n sourceUrl: sourceRow.source_url ?? undefined,\n baseUrl: sourceRow.base_url ?? undefined,\n headers,\n queryParams,\n specFetchCredentials,\n oauth2,\n },\n };\n });\n\n const rowToOperation = (row: Record<string, unknown>): StoredOperation => {\n const operationRow = decodeOperationStorageRow(row);\n return {\n toolId: operationRow.id,\n sourceId: operationRow.source_id,\n binding: decodeBinding(\n typeof operationRow.binding === \"string\"\n ? decodeBindingJson(operationRow.binding)\n : operationRow.binding,\n ),\n };\n };\n\n // Replace the rows of one child table for a source: delete then bulk\n // insert. Single helper so upsertSource and updateSourceMeta both\n // funnel through the same write path.\n const replaceChildRows = (\n model:\n | \"openapi_source_header\"\n | \"openapi_source_query_param\"\n | \"openapi_source_spec_fetch_header\"\n | \"openapi_source_spec_fetch_query_param\",\n sourceId: string,\n scope: string,\n values: Record<string, ConfiguredHeaderValue> | undefined,\n ) =>\n Effect.gen(function* () {\n yield* adapter.deleteMany({\n model,\n where: [\n { field: \"source_id\", value: sourceId },\n { field: \"scope_id\", value: scope },\n ],\n });\n const rows = valueMapToChildRows(sourceId, scope, values);\n if (rows.length === 0) return;\n yield* adapter.createMany({\n model,\n data: rows,\n forceAllowId: true,\n });\n });\n\n const deleteSource = (namespace: string, scope: string) =>\n Effect.gen(function* () {\n yield* adapter.deleteMany({\n model: \"openapi_operation\",\n where: [\n { field: \"source_id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n });\n // Drop every child table's rows for this source/scope.\n for (const model of [\n \"openapi_source_header\",\n \"openapi_source_query_param\",\n \"openapi_source_spec_fetch_header\",\n \"openapi_source_spec_fetch_query_param\",\n ] as const) {\n yield* adapter.deleteMany({\n model,\n where: [\n { field: \"source_id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n });\n }\n yield* adapter.delete({\n model: \"openapi_source\",\n where: [\n { field: \"id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n });\n });\n\n return {\n upsertSource: (input, operations) =>\n Effect.gen(function* () {\n yield* deleteSource(input.namespace, input.scope);\n yield* adapter.create({\n model: \"openapi_source\",\n data: {\n id: input.namespace,\n scope_id: input.scope,\n name: input.name,\n spec: input.config.spec,\n source_url: input.config.sourceUrl ?? undefined,\n base_url: input.config.baseUrl ?? undefined,\n oauth2: input.config.oauth2\n ? toJsonRecord(encodeOAuth2SourceConfig(input.config.oauth2))\n : undefined,\n },\n forceAllowId: true,\n });\n yield* replaceChildRows(\n \"openapi_source_header\",\n input.namespace,\n input.scope,\n input.config.headers,\n );\n yield* replaceChildRows(\n \"openapi_source_query_param\",\n input.namespace,\n input.scope,\n input.config.queryParams,\n );\n yield* replaceChildRows(\n \"openapi_source_spec_fetch_header\",\n input.namespace,\n input.scope,\n input.config.specFetchCredentials?.headers,\n );\n yield* replaceChildRows(\n \"openapi_source_spec_fetch_query_param\",\n input.namespace,\n input.scope,\n input.config.specFetchCredentials?.queryParams,\n );\n if (operations.length > 0) {\n yield* adapter.createMany({\n model: \"openapi_operation\",\n data: operations.map((op) => ({\n id: op.toolId,\n scope_id: input.scope,\n source_id: op.sourceId,\n binding: toJsonRecord(encodeBinding(op.binding)),\n })),\n forceAllowId: true,\n });\n }\n }),\n\n updateSourceMeta: (namespace, scope, patch) =>\n Effect.gen(function* () {\n const existingRow = yield* adapter.findOne({\n model: \"openapi_source\",\n where: [\n { field: \"id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n });\n if (!existingRow) return;\n const existing = yield* rowToSource(existingRow);\n\n const nextName = patch.name?.trim() || existing.name;\n const nextBaseUrl = patch.baseUrl !== undefined ? patch.baseUrl : existing.config.baseUrl;\n const nextOAuth2 = patch.oauth2 !== undefined ? patch.oauth2 : existing.config.oauth2;\n\n yield* adapter.update({\n model: \"openapi_source\",\n where: [\n { field: \"id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n update: {\n name: nextName,\n base_url: nextBaseUrl ?? undefined,\n oauth2: nextOAuth2 ? toJsonRecord(encodeOAuth2SourceConfig(nextOAuth2)) : undefined,\n },\n });\n if (patch.headers !== undefined) {\n yield* replaceChildRows(\"openapi_source_header\", namespace, scope, patch.headers);\n }\n if (patch.queryParams !== undefined) {\n yield* replaceChildRows(\n \"openapi_source_query_param\",\n namespace,\n scope,\n patch.queryParams,\n );\n }\n }),\n\n getSource: (namespace, scope) =>\n Effect.gen(function* () {\n const row = yield* adapter.findOne({\n model: \"openapi_source\",\n where: [\n { field: \"id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n });\n if (!row) return null;\n return yield* rowToSource(row);\n }),\n\n listSources: () =>\n Effect.gen(function* () {\n const rows = yield* adapter.findMany({ model: \"openapi_source\" });\n return yield* Effect.forEach(rows, rowToSource, {\n concurrency: \"unbounded\",\n });\n }),\n\n getOperationByToolId: (toolId, scope) =>\n adapter\n .findOne({\n model: \"openapi_operation\",\n where: [\n { field: \"id\", value: toolId },\n { field: \"scope_id\", value: scope },\n ],\n })\n .pipe(Effect.map((row) => (row ? rowToOperation(row) : null))),\n\n listOperationsBySource: (sourceId, scope) =>\n adapter\n .findMany({\n model: \"openapi_operation\",\n where: [\n { field: \"source_id\", value: sourceId },\n { field: \"scope_id\", value: scope },\n ],\n })\n .pipe(Effect.map((rows) => rows.map(rowToOperation))),\n\n removeSource: (namespace, scope) => deleteSource(namespace, scope),\n };\n};\n"],"mappings":";AAAA,SAAS,MAAM,cAAc;AAUtB,IAAM,oBAAN,cAAgC,OAAO,iBAAoC;AAAA,EAChF;AAAA,EACA;AAAA,IACE,SAAS,OAAO;AAAA,EAClB;AAAA,EACA,EAAE,eAAe,IAAI;AACvB,EAAE;AAAC;AAEI,IAAM,yBAAN,cAAqC,OAAO,iBAAyC;AAAA,EAC1F;AAAA,EACA;AAAA,IACE,SAAS,OAAO;AAAA,EAClB;AAAA,EACA,EAAE,eAAe,IAAI;AACvB,EAAE;AAAC;AAEI,IAAM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IAAI,cAAc,CAAC,CAAC;AAAA,IAExD,cAAc,CAAC,WAAW,UAAU,aAAa,WAAW,KAAK;AAAA,EACnE;AACF;","names":["Schema","Schema","Schema","Effect","Option","Option","Effect","Effect","Option","Schema","Schema","Option","Effect","Effect","Option","Schema","Schema","Option","Effect"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react/atoms.ts","../src/react/client.ts","../src/api/group.ts"],"sourcesContent":["import type { ScopeId } from \"@executor-js/sdk/core\";\nimport * as Atom from \"effect/unstable/reactivity/Atom\";\nimport * as AsyncResult from \"effect/unstable/reactivity/AsyncResult\";\nimport { sourcesOptimisticAtom } from \"@executor-js/react/api/atoms\";\nimport { ReactivityKey } from \"@executor-js/react/api/reactivity-keys\";\nimport { OpenApiClient } from \"./client\";\n\n// ---------------------------------------------------------------------------\n// Query atoms\n// ---------------------------------------------------------------------------\n\nexport const openApiSourceAtom = (scopeId: ScopeId, namespace: string) =>\n OpenApiClient.query(\"openapi\", \"getSource\", {\n params: { scopeId, namespace },\n timeToLive: \"15 seconds\",\n reactivityKeys: [ReactivityKey.sources, ReactivityKey.tools],\n });\n\nexport const openApiSourceBindingsAtom = (\n scopeId: ScopeId,\n namespace: string,\n sourceScopeId: ScopeId,\n) =>\n OpenApiClient.query(\"openapi\", \"listSourceBindings\", {\n params: { scopeId, namespace, sourceScopeId },\n timeToLive: \"15 seconds\",\n reactivityKeys: [ReactivityKey.sources, ReactivityKey.secrets, ReactivityKey.connections],\n });\n\n// ---------------------------------------------------------------------------\n// Mutation atoms\n// ---------------------------------------------------------------------------\n\nexport const previewOpenApiSpec = OpenApiClient.mutation(\"openapi\", \"previewSpec\");\n\nexport const addOpenApiSpec = OpenApiClient.mutation(\"openapi\", \"addSpec\");\n\nexport const addOpenApiSpecOptimistic = Atom.family((scopeId: ScopeId) =>\n sourcesOptimisticAtom(scopeId).pipe(\n Atom.optimisticFn({\n reducer: (current, arg) =>\n AsyncResult.map(current, (rows) => {\n const id = arg.payload.namespace ?? `pending-${Math.random().toString(36).slice(2)}`;\n const source = {\n id,\n scopeId: arg.payload.targetScope,\n kind: \"openapi\",\n pluginId: \"openapi\",\n name: arg.payload.name ?? id,\n ...(arg.payload.baseUrl ? { url: arg.payload.baseUrl } : {}),\n canRemove: false,\n canRefresh: false,\n canEdit: false,\n runtime: false,\n };\n return [source, ...rows.filter((row) => row.id !== id)].sort((a, b) =>\n a.name.localeCompare(b.name),\n );\n }),\n fn: addOpenApiSpec,\n }),\n ),\n);\n\nexport const updateOpenApiSource = OpenApiClient.mutation(\"openapi\", \"updateSource\");\n\nexport const setOpenApiSourceBinding = OpenApiClient.mutation(\"openapi\", \"setSourceBinding\");\n\nexport const removeOpenApiSourceBinding = OpenApiClient.mutation(\"openapi\", \"removeSourceBinding\");\n","import { createPluginAtomClient } from \"@executor-js/sdk/client\";\nimport { getBaseUrl } from \"@executor-js/react/api/base-url\";\nimport { OpenApiGroup } from \"../api/group\";\n\nexport const OpenApiClient = createPluginAtomClient(OpenApiGroup, {\n baseUrl: getBaseUrl,\n});\n","import { HttpApiEndpoint, HttpApiGroup } from \"effect/unstable/httpapi\";\nimport { Schema } from \"effect\";\nimport {\n InternalError,\n ScopeId,\n ScopedSecretCredentialInput,\n SecretBackedValue,\n} from \"@executor-js/sdk/core\";\n\nimport { OpenApiParseError, OpenApiExtractionError, OpenApiOAuthError } from \"../sdk/errors\";\nimport { SpecPreview } from \"../sdk/preview\";\nimport { StoredSourceSchema } from \"../sdk/store\";\nimport {\n OAuth2SourceConfig,\n OpenApiSourceBindingInput,\n OpenApiSourceBindingRef,\n} from \"../sdk/types\";\n\n// ---------------------------------------------------------------------------\n// Params\n// ---------------------------------------------------------------------------\n\nconst DomainErrors = [\n InternalError,\n OpenApiParseError,\n OpenApiExtractionError,\n OpenApiOAuthError,\n] as const;\n\nconst ScopeIdParam = {\n scopeId: ScopeId,\n};\n\nconst SourceParams = {\n scopeId: ScopeId,\n namespace: Schema.String,\n};\n\nconst SourceBindingParams = {\n scopeId: ScopeId,\n namespace: Schema.String,\n sourceScopeId: ScopeId,\n};\n\nconst SpecFetchCredentialsPayload = Schema.Struct({\n headers: Schema.optional(Schema.Record(Schema.String, SecretBackedValue)),\n queryParams: Schema.optional(Schema.Record(Schema.String, SecretBackedValue)),\n});\n\nconst ConfiguredCredentialBindingPayload = Schema.Struct({\n kind: Schema.Literal(\"binding\"),\n slot: Schema.String,\n prefix: Schema.optional(Schema.String),\n});\n\nconst ConfiguredCredentialValuePayload = Schema.Union([\n Schema.String,\n ConfiguredCredentialBindingPayload,\n]);\n\nconst OpenApiCredentialInputPayload = Schema.Union([\n ScopedSecretCredentialInput,\n SecretBackedValue,\n ConfiguredCredentialValuePayload,\n]);\n\n// ---------------------------------------------------------------------------\n// Payloads\n// ---------------------------------------------------------------------------\n\nconst AddSpecPayload = Schema.Struct({\n targetScope: ScopeId,\n credentialTargetScope: Schema.optional(ScopeId),\n spec: Schema.String,\n specFetchCredentials: Schema.optional(SpecFetchCredentialsPayload),\n name: Schema.optional(Schema.String),\n baseUrl: Schema.optional(Schema.String),\n namespace: Schema.optional(Schema.String),\n headers: Schema.optional(Schema.Record(Schema.String, OpenApiCredentialInputPayload)),\n queryParams: Schema.optional(Schema.Record(Schema.String, OpenApiCredentialInputPayload)),\n oauth2: Schema.optional(OAuth2SourceConfig),\n});\n\nconst PreviewSpecPayload = Schema.Struct({\n spec: Schema.String,\n specFetchCredentials: Schema.optional(SpecFetchCredentialsPayload),\n});\n\nconst UpdateSourcePayload = Schema.Struct({\n sourceScope: ScopeId,\n name: Schema.optional(Schema.String),\n baseUrl: Schema.optional(Schema.String),\n headers: Schema.optional(Schema.Record(Schema.String, OpenApiCredentialInputPayload)),\n queryParams: Schema.optional(Schema.Record(Schema.String, OpenApiCredentialInputPayload)),\n credentialTargetScope: Schema.optional(ScopeId),\n // Set after a successful re-authenticate to refresh the source's\n // stored OAuth2 metadata.\n oauth2: Schema.optional(OAuth2SourceConfig),\n});\n\nconst UpdateSourceResponse = Schema.Struct({\n updated: Schema.Boolean,\n});\n\nconst RemoveBindingPayload = Schema.Struct({\n sourceId: Schema.String,\n sourceScope: ScopeId,\n slot: Schema.String,\n scope: ScopeId,\n});\n\n// ---------------------------------------------------------------------------\n// Responses\n// ---------------------------------------------------------------------------\n\nconst AddSpecResponse = Schema.Struct({\n toolCount: Schema.Number,\n namespace: Schema.String,\n});\n\n// HTTP status on the three domain errors lives on their class\n// declarations in `../sdk/errors.ts` — see the comment there.\n\n// ---------------------------------------------------------------------------\n// Group\n//\n// Plugin SDK errors (OpenApiParseError, OpenApiExtractionError,\n// OpenApiOAuthError) are declared once at the group level via\n// `.addError(...)` — every endpoint inherits them. The errors themselves\n// carry their HTTP status via `HttpApiSchema.annotations` above, so\n// handlers just `return yield* ext.foo(...)` and the schema encodes\n// whatever comes out.\n//\n// 5xx is handled at the API level: `.addError(InternalError)` adds the\n// shared opaque 500 surface. Defects are captured + downgraded to it by\n// an HttpApiBuilder middleware (see apps/cloud/src/observability.ts).\n// StorageError → InternalError translation happens at service wiring\n// time via `withCapture(executor)`.\n// ---------------------------------------------------------------------------\n\nexport const OpenApiGroup = HttpApiGroup.make(\"openapi\")\n .add(\n HttpApiEndpoint.post(\"previewSpec\", \"/scopes/:scopeId/openapi/preview\", {\n params: ScopeIdParam,\n payload: PreviewSpecPayload,\n success: SpecPreview,\n error: DomainErrors,\n }),\n )\n .add(\n HttpApiEndpoint.post(\"addSpec\", \"/scopes/:scopeId/openapi/specs\", {\n params: ScopeIdParam,\n payload: AddSpecPayload,\n success: AddSpecResponse,\n error: DomainErrors,\n }),\n )\n .add(\n HttpApiEndpoint.get(\"getSource\", \"/scopes/:scopeId/openapi/sources/:namespace\", {\n params: SourceParams,\n success: Schema.NullOr(StoredSourceSchema),\n error: DomainErrors,\n }),\n )\n .add(\n HttpApiEndpoint.patch(\"updateSource\", \"/scopes/:scopeId/openapi/sources/:namespace\", {\n params: SourceParams,\n payload: UpdateSourcePayload,\n success: UpdateSourceResponse,\n error: DomainErrors,\n }),\n )\n .add(\n HttpApiEndpoint.get(\n \"listSourceBindings\",\n \"/scopes/:scopeId/openapi/sources/:namespace/base/:sourceScopeId/bindings\",\n {\n params: SourceBindingParams,\n success: Schema.Array(OpenApiSourceBindingRef),\n error: DomainErrors,\n },\n ),\n )\n .add(\n HttpApiEndpoint.post(\"setSourceBinding\", \"/scopes/:scopeId/openapi/source-bindings\", {\n params: ScopeIdParam,\n payload: OpenApiSourceBindingInput,\n success: OpenApiSourceBindingRef,\n error: DomainErrors,\n }),\n )\n .add(\n HttpApiEndpoint.post(\"removeSourceBinding\", \"/scopes/:scopeId/openapi/source-bindings/remove\", {\n params: ScopeIdParam,\n payload: RemoveBindingPayload,\n success: Schema.Struct({ removed: Schema.Boolean }),\n error: DomainErrors,\n }),\n );\n"],"mappings":";;;;;;;;;;;;AACA,YAAY,UAAU;AACtB,YAAY,iBAAiB;AAC7B,SAAS,6BAA6B;AACtC,SAAS,qBAAqB;;;ACJ9B,SAAS,8BAA8B;AACvC,SAAS,kBAAkB;;;ACD3B,SAAS,iBAAiB,oBAAoB;AAC9C,SAAS,cAAc;AACvB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAeP,IAAM,eAAe;AAAA,EACnB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAM,eAAe;AAAA,EACnB,SAAS;AACX;AAEA,IAAM,eAAe;AAAA,EACnB,SAAS;AAAA,EACT,WAAW,OAAO;AACpB;AAEA,IAAM,sBAAsB;AAAA,EAC1B,SAAS;AAAA,EACT,WAAW,OAAO;AAAA,EAClB,eAAe;AACjB;AAEA,IAAM,8BAA8B,OAAO,OAAO;AAAA,EAChD,SAAS,OAAO,SAAS,OAAO,OAAO,OAAO,QAAQ,iBAAiB,CAAC;AAAA,EACxE,aAAa,OAAO,SAAS,OAAO,OAAO,OAAO,QAAQ,iBAAiB,CAAC;AAC9E,CAAC;AAED,IAAM,qCA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