@rafads/plugin-openapi 1.5.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/README.md +83 -0
  2. package/dist/AddOpenApiIntegration-JPAEXE56.js +512 -0
  3. package/dist/AddOpenApiIntegration-JPAEXE56.js.map +1 -0
  4. package/dist/OpenApiAccountsPanel-GZFDSTAU.js +106 -0
  5. package/dist/OpenApiAccountsPanel-GZFDSTAU.js.map +1 -0
  6. package/dist/UpdateSpecSection-KUSNI44Q.js +106 -0
  7. package/dist/UpdateSpecSection-KUSNI44Q.js.map +1 -0
  8. package/dist/api/group.d.ts +239 -0
  9. package/dist/api/handlers.d.ts +7 -0
  10. package/dist/api/index.d.ts +237 -0
  11. package/dist/chunk-6V45G2XQ.js +199 -0
  12. package/dist/chunk-6V45G2XQ.js.map +1 -0
  13. package/dist/chunk-CURJJXB3.js +132 -0
  14. package/dist/chunk-CURJJXB3.js.map +1 -0
  15. package/dist/chunk-CXFO6TLJ.js +39 -0
  16. package/dist/chunk-CXFO6TLJ.js.map +1 -0
  17. package/dist/chunk-HTHEUUJA.js +2873 -0
  18. package/dist/chunk-HTHEUUJA.js.map +1 -0
  19. package/dist/chunk-IG6QTTZB.js +79 -0
  20. package/dist/chunk-IG6QTTZB.js.map +1 -0
  21. package/dist/chunk-O2LMSZ2Z.js +120 -0
  22. package/dist/chunk-O2LMSZ2Z.js.map +1 -0
  23. package/dist/chunk-OR27BCXQ.js +956 -0
  24. package/dist/chunk-OR27BCXQ.js.map +1 -0
  25. package/dist/chunk-R7TVM3XD.js +275 -0
  26. package/dist/chunk-R7TVM3XD.js.map +1 -0
  27. package/dist/client.js +38 -0
  28. package/dist/client.js.map +1 -0
  29. package/dist/core.js +331 -0
  30. package/dist/core.js.map +1 -0
  31. package/dist/index.js +19 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/providers/google/config.d.ts +34 -0
  34. package/dist/providers/google/discovery.d.ts +49 -0
  35. package/dist/providers/google/discovery.test.d.ts +1 -0
  36. package/dist/providers/google/index.d.ts +5 -0
  37. package/dist/providers/google/oauth-scopes.d.ts +3 -0
  38. package/dist/providers/google/oauth-scopes.test.d.ts +1 -0
  39. package/dist/providers/google/openapi-ownership-migration.d.ts +7 -0
  40. package/dist/providers/google/openapi-ownership-migration.test.d.ts +1 -0
  41. package/dist/providers/google/presets.d.ts +31 -0
  42. package/dist/providers/google/presets.test.d.ts +1 -0
  43. package/dist/providers/google/spec-format-adapter.d.ts +3 -0
  44. package/dist/providers/google/spec-format-adapter.test.d.ts +1 -0
  45. package/dist/providers/google.js +1446 -0
  46. package/dist/providers/google.js.map +1 -0
  47. package/dist/providers/microsoft/graph.d.ts +76 -0
  48. package/dist/providers/microsoft/graph.test.d.ts +1 -0
  49. package/dist/providers/microsoft/index.d.ts +3 -0
  50. package/dist/providers/microsoft/presets.d.ts +46 -0
  51. package/dist/providers/microsoft/presets.test.d.ts +1 -0
  52. package/dist/providers/microsoft/spec-format-adapter.d.ts +2 -0
  53. package/dist/providers/microsoft/spec-format-adapter.test.d.ts +1 -0
  54. package/dist/providers/microsoft.js +1056 -0
  55. package/dist/providers/microsoft.js.map +1 -0
  56. package/dist/react/AddOpenApiIntegration.d.ts +22 -0
  57. package/dist/react/AddOpenApiIntegration.test.d.ts +1 -0
  58. package/dist/react/OpenApiAccountsPanel.d.ts +6 -0
  59. package/dist/react/OpenApiIntegrationDetailsFields.d.ts +25 -0
  60. package/dist/react/UpdateSpecSection.d.ts +2 -0
  61. package/dist/react/atoms.d.ts +317 -0
  62. package/dist/react/auth-method-config.d.ts +18 -0
  63. package/dist/react/auth-method-config.test.d.ts +1 -0
  64. package/dist/react/client.d.ts +233 -0
  65. package/dist/react/index.d.ts +5 -0
  66. package/dist/react/integration-plugin.d.ts +6 -0
  67. package/dist/react/plugin-client.d.ts +2 -0
  68. package/dist/sdk/backing.d.ts +188 -0
  69. package/dist/sdk/client-credentials-oauth.test.d.ts +1 -0
  70. package/dist/sdk/compiled-spec-cache.test.d.ts +1 -0
  71. package/dist/sdk/config.d.ts +81 -0
  72. package/dist/sdk/configure.test.d.ts +1 -0
  73. package/dist/sdk/definitions.d.ts +57 -0
  74. package/dist/sdk/derive-auth.d.ts +11 -0
  75. package/dist/sdk/describe-auth-methods.test.d.ts +1 -0
  76. package/dist/sdk/errors.d.ts +45 -0
  77. package/dist/sdk/extract.d.ts +157 -0
  78. package/dist/sdk/extract.test.d.ts +1 -0
  79. package/dist/sdk/form-urlencoded-body.test.d.ts +1 -0
  80. package/dist/sdk/index.d.ts +19 -0
  81. package/dist/sdk/index.test.d.ts +1 -0
  82. package/dist/sdk/invoke.d.ts +150 -0
  83. package/dist/sdk/migrate-config.d.ts +4 -0
  84. package/dist/sdk/migrate-config.test.d.ts +1 -0
  85. package/dist/sdk/multi-scope-bearer.test.d.ts +1 -0
  86. package/dist/sdk/multi-scope-oauth.test.d.ts +1 -0
  87. package/dist/sdk/ndjson-output-migration.d.ts +13 -0
  88. package/dist/sdk/ndjson-output-migration.test.d.ts +1 -0
  89. package/dist/sdk/non-json-body.test.d.ts +1 -0
  90. package/dist/sdk/oauth-refresh.test.d.ts +1 -0
  91. package/dist/sdk/openapi-utils.d.ts +65 -0
  92. package/dist/sdk/output-schema-migration.d.ts +21 -0
  93. package/dist/sdk/output-schema-migration.test.d.ts +1 -0
  94. package/dist/sdk/parse.d.ts +33 -0
  95. package/dist/sdk/parse.test.d.ts +1 -0
  96. package/dist/sdk/plugin.d.ts +109 -0
  97. package/dist/sdk/plugin.test.d.ts +1 -0
  98. package/dist/sdk/presets.d.ts +15 -0
  99. package/dist/sdk/preview-oauth2.test.d.ts +1 -0
  100. package/dist/sdk/preview.d.ts +514 -0
  101. package/dist/sdk/query-serialization.test.d.ts +1 -0
  102. package/dist/sdk/real-specs.test.d.ts +1 -0
  103. package/dist/sdk/request-user-agent.test.d.ts +1 -0
  104. package/dist/sdk/response-headers-timeout.test.d.ts +1 -0
  105. package/dist/sdk/server-url-resolution.test.d.ts +1 -0
  106. package/dist/sdk/spec-blob-migration.d.ts +7 -0
  107. package/dist/sdk/spec-blob.test.d.ts +1 -0
  108. package/dist/sdk/spec-format.d.ts +36 -0
  109. package/dist/sdk/spec-format.test.d.ts +1 -0
  110. package/dist/sdk/split.d.ts +84 -0
  111. package/dist/sdk/store.d.ts +49 -0
  112. package/dist/sdk/store.test.d.ts +1 -0
  113. package/dist/sdk/streaming-response.test.d.ts +1 -0
  114. package/dist/sdk/tool-row-projection.test.d.ts +1 -0
  115. package/dist/sdk/types.d.ts +352 -0
  116. package/dist/sdk/upstream-failures.test.d.ts +1 -0
  117. package/dist/sdk/usage-scope-isolation.test.d.ts +1 -0
  118. package/dist/testing/index.d.ts +177 -0
  119. package/dist/testing.js +454 -0
  120. package/dist/testing.js.map +1 -0
  121. package/dist/testing.test.d.ts +1 -0
  122. package/package.json +103 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sdk/store.ts","../src/sdk/spec-format.ts","../src/sdk/plugin.ts"],"sourcesContent":["import { Effect, Option, Predicate, Schema } from \"effect\";\n\nimport { type PluginStorageEntry, type StorageDeps, type StorageFailure } from \"@rafads/sdk/core\";\n\nimport { OperationBinding } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// OpenAPI plugin store (v2). The catalog row (integration.config) owns the\n// auth templates plus the spec's content hash; the resolved spec text itself\n// lives in the plugin blob store under `spec/<hash>` (it's multi-MB and only\n// a build input). This store keeps the per-operation invocation bindings\n// (method / path / params), keyed by integration slug, so `invokeTool` can map\n// a tool name back to its HTTP operation without re-parsing the spec on every\n// call. There are NO credential bindings, slots, or StoredSource credential\n// config here — those concepts are gone in v2.\n//\n// Operations are spec-derived (identical for every connection on an\n// integration), so they live under the org owner (the integration catalog is\n// tenant-level). The plugin storage facade partitions by owner; \"org\" keeps a\n// single shared copy per integration.\n// ---------------------------------------------------------------------------\n\nconst OPERATION_COLLECTION = \"operation\";\nconst STORE_OWNER = \"org\" as const;\nconst OPERATION_KEY_VERSION = \"op\";\n\nconst encodeBinding = Schema.encodeSync(OperationBinding);\nconst decodeBinding = Schema.decodeUnknownSync(OperationBinding);\nconst decodeBindingJson = Schema.decodeUnknownSync(Schema.fromJsonString(OperationBinding));\n\nconst toJsonRecord = (value: unknown): Record<string, unknown> => value as Record<string, unknown>;\n\nconst OperationStorage = Schema.Struct({\n integration: Schema.String,\n toolName: Schema.String,\n binding: Schema.Unknown,\n // Resolved tool description (operation description / summary / method+path\n // fallback), persisted so the serve path can rebuild the tool def without\n // re-parsing the spec. Optional: legacy rows predate it and resolve via the\n // parse fallback.\n description: Schema.optional(Schema.String),\n});\nconst decodeOperationStorage = Schema.decodeUnknownOption(OperationStorage);\n\nexport interface StoredOperation {\n /** The integration slug this operation belongs to. */\n readonly integration: string;\n /** The tool name (the `<tool>` address segment) this operation backs. */\n readonly toolName: string;\n readonly binding: OperationBinding;\n /** Resolved tool description, persisted alongside the binding so the serve\n * path can rebuild the tool def without re-parsing the spec. */\n readonly description?: string;\n}\n\nconst rowToOperation = (row: PluginStorageEntry): StoredOperation | null => {\n const decoded = decodeOperationStorage(row.data);\n if (Option.isNone(decoded)) return null;\n const operation = decoded.value;\n return {\n integration: operation.integration,\n toolName: operation.toolName,\n binding: decodeBinding(\n typeof operation.binding === \"string\"\n ? decodeBindingJson(operation.binding)\n : operation.binding,\n ),\n ...(operation.description !== undefined ? { description: operation.description } : {}),\n };\n};\n\nconst stableKeyHash = (value: string): string => {\n let hash = 0xcbf29ce484222325n;\n const prime = 0x100000001b3n;\n const mask = 0xffffffffffffffffn;\n for (let index = 0; index < value.length; index += 1) {\n hash ^= BigInt(value.charCodeAt(index));\n hash = (hash * prime) & mask;\n }\n return hash.toString(36).padStart(13, \"0\");\n};\n\nconst operationKey = (integration: string, toolName: string): string =>\n `${OPERATION_KEY_VERSION}.${stableKeyHash(integration)}.${stableKeyHash(toolName)}`;\n\nconst legacyOperationKey = (integration: string, toolName: string): string =>\n `${integration}.${toolName}`;\n\n/** Blob key for a spec's content hash. Content-addressed so re-puts are\n * idempotent and identical specs share one blob per partition. */\nexport const specBlobKey = (specHash: string): string => `spec/${specHash}`;\n\n/** Blob key for a spec's compiled `#/$defs/*` schemas, keyed by the same\n * content hash as the spec. The serve path reads this instead of re-parsing\n * the (potentially multi-MB) spec to rebuild the shared `definitions`. */\nexport const defsBlobKey = (specHash: string): string => `defs/${specHash}`;\n\nexport interface OpenapiStore {\n /** Replace all stored operations for an integration. */\n readonly putOperations: (\n integration: string,\n operations: readonly StoredOperation[],\n ) => Effect.Effect<void, StorageFailure>;\n /** Append operations without clearing existing ones. The caller is\n * responsible for `removeOperations` first when doing a full rebuild. Used\n * by the streaming compile path, which persists operations chunk by chunk so\n * a huge spec's bindings are never all materialized at once. */\n readonly appendOperations: (\n integration: string,\n operations: readonly StoredOperation[],\n ) => Effect.Effect<void, StorageFailure>;\n /** Look up one operation by integration + tool name. */\n readonly getOperation: (\n integration: string,\n toolName: string,\n ) => Effect.Effect<StoredOperation | null, StorageFailure>;\n /** List every stored operation for an integration. */\n readonly listOperations: (\n integration: string,\n ) => Effect.Effect<readonly StoredOperation[], StorageFailure>;\n /** Drop all stored operations for an integration. */\n readonly removeOperations: (integration: string) => Effect.Effect<void, StorageFailure>;\n /** Persist resolved spec text under its content hash. Org-owned and\n * content-addressed; never removed on integration removal because another\n * integration in the tenant may share the hash. */\n readonly putSpec: (specHash: string, specText: string) => Effect.Effect<void, StorageFailure>;\n /** Load spec text by content hash; null when no blob exists. */\n readonly getSpec: (specHash: string) => Effect.Effect<string | null, StorageFailure>;\n /** Persist the compiled `#/$defs/*` JSON for a spec under its content hash.\n * Content-addressed like the spec blob; lets the serve path serve the shared\n * `definitions` without re-parsing the spec. */\n readonly putDefs: (specHash: string, defsJson: string) => Effect.Effect<void, StorageFailure>;\n /** Load the compiled `#/$defs/*` JSON by content hash; null when no blob\n * exists (legacy rows added before the defs blob). */\n readonly getDefs: (specHash: string) => Effect.Effect<string | null, StorageFailure>;\n}\n\nexport const makeDefaultOpenapiStore = ({ pluginStorage, blobs }: StorageDeps): OpenapiStore => {\n const operationData = (operation: StoredOperation) => ({\n integration: operation.integration,\n toolName: operation.toolName,\n binding: toJsonRecord(encodeBinding(operation.binding)),\n ...(operation.description !== undefined ? { description: operation.description } : {}),\n });\n\n const listRows = (integration: string) =>\n pluginStorage\n .list({ collection: OPERATION_COLLECTION })\n .pipe(\n Effect.map((rows: readonly PluginStorageEntry[]) =>\n rows.filter((row) => rowToOperation(row)?.integration === integration),\n ),\n );\n\n const removeOperations = (integration: string) =>\n Effect.gen(function* () {\n const rows = yield* listRows(integration);\n yield* pluginStorage.removeMany({\n owner: STORE_OWNER,\n entries: rows.map((row) => ({ collection: OPERATION_COLLECTION, key: row.key })),\n });\n });\n\n const appendOperations = (integration: string, operations: readonly StoredOperation[]) =>\n pluginStorage.putMany({\n owner: STORE_OWNER,\n entries: operations.map((operation) => ({\n collection: OPERATION_COLLECTION,\n key: operationKey(integration, operation.toolName),\n data: operationData(operation),\n })),\n });\n\n return {\n putOperations: (integration, operations) =>\n Effect.gen(function* () {\n yield* removeOperations(integration);\n yield* appendOperations(integration, operations);\n }),\n\n appendOperations,\n\n getOperation: (integration, toolName) =>\n Effect.gen(function* () {\n const row = yield* pluginStorage.get({\n collection: OPERATION_COLLECTION,\n key: operationKey(integration, toolName),\n });\n if (row) return rowToOperation(row);\n const legacyKey = legacyOperationKey(integration, toolName);\n if (legacyKey.length > 255) return null;\n const legacyRow = yield* pluginStorage.get({\n collection: OPERATION_COLLECTION,\n key: legacyKey,\n });\n return legacyRow ? rowToOperation(legacyRow) : null;\n }),\n\n listOperations: (integration) =>\n listRows(integration).pipe(\n Effect.map((rows) => rows.map(rowToOperation).filter(Predicate.isNotNull)),\n ),\n\n removeOperations,\n\n putSpec: (specHash, specText) =>\n blobs.put(specBlobKey(specHash), specText, { owner: STORE_OWNER }),\n\n getSpec: (specHash) => blobs.get(specBlobKey(specHash)),\n\n putDefs: (specHash, defsJson) =>\n blobs.put(defsBlobKey(specHash), defsJson, { owner: STORE_OWNER }),\n\n getDefs: (specHash) => blobs.get(defsBlobKey(specHash)),\n };\n};\n","import type { Layer } from \"effect\";\nimport { Effect } from \"effect\";\nimport type { HttpClient } from \"effect/unstable/http\";\n\nimport type { Authentication } from \"./types\";\nimport type { OpenApiIntegrationConfig } from \"./config\";\nimport type { KeepPathItem } from \"./split\";\nimport { OpenApiParseError } from \"./errors\";\n\nexport interface SpecFetchCredentials {\n readonly headers?: Record<string, string>;\n readonly queryParams?: Record<string, string>;\n}\n\nexport interface SpecFetchInput {\n readonly urls: readonly string[];\n readonly credentials?: SpecFetchCredentials;\n readonly httpClientLayer: Layer.Layer<HttpClient.HttpClient, never, never>;\n}\n\nexport interface DerivedIdentity {\n readonly slug: string;\n readonly name: string;\n readonly description?: string;\n}\n\nexport interface ConvertedSpec {\n readonly specText: string;\n readonly specUrl?: string;\n readonly baseUrl?: string;\n readonly authenticationTemplate?: readonly Authentication[];\n readonly config?: Partial<OpenApiIntegrationConfig> & Readonly<Record<string, unknown>>;\n readonly keepPathItem?: KeepPathItem;\n readonly document?: unknown;\n}\n\nexport interface SpecFormatAdapter {\n readonly id: string;\n readonly fetch: (input: SpecFetchInput) => Effect.Effect<ConvertedSpec, OpenApiParseError>;\n readonly deriveIdentity?: (doc: unknown) => DerivedIdentity | null;\n}\n\nexport const resolveSpecFormatAdapter = (\n adapters: readonly SpecFormatAdapter[],\n id: string | undefined,\n): Effect.Effect<SpecFormatAdapter | null, OpenApiParseError> => {\n if (!id) return Effect.succeed(null);\n const adapter = adapters.find((candidate) => candidate.id === id);\n if (adapter) return Effect.succeed(adapter);\n return Effect.fail(new OpenApiParseError({ message: `Unknown OpenAPI spec format: ${id}` }));\n};\n","import { Effect, Option, Schema } from \"effect\";\nimport type { Layer } from \"effect\";\nimport { HttpClient } from \"effect/unstable/http\";\n\nimport {\n IntegrationAlreadyExistsError,\n IntegrationDetectionResult,\n IntegrationNotFoundError,\n IntegrationSlug,\n ToolResult,\n definePlugin,\n HealthCheckSpec,\n mergeAuthTemplates,\n sha256Hex,\n tool,\n type AuthMethodDescriptor,\n type Integration,\n type IntegrationConfig,\n type IntegrationRecord,\n type PluginCtx,\n type StorageFailure,\n} from \"@rafads/sdk/core\";\n\nimport { decodeOpenApiIntegrationConfig, type OpenApiIntegrationConfig } from \"./config\";\nimport { OpenApiExtractionError, OpenApiOAuthError, OpenApiParseError } from \"./errors\";\nimport { parse, resolveSpecText } from \"./parse\";\nimport { extract } from \"./extract\";\nimport {\n OAuth2AuthorizationCodeFlow,\n OAuth2Flows,\n OAuth2Preset,\n SecurityScheme,\n previewSpecText,\n type SpecPreview,\n} from \"./preview\";\nimport { deriveAuthenticationTemplateFromPreview, firstBaseUrlForPreview } from \"./derive-auth\";\nimport { openApiPresets, type OpenApiPreset } from \"./presets\";\nimport { makeDefaultOpenapiStore, type OpenapiStore } from \"./store\";\nimport {\n resolveSpecFormatAdapter,\n type ConvertedSpec,\n type SpecFormatAdapter,\n} from \"./spec-format\";\nimport type { Authentication } from \"./types\";\nimport { normalizeOpenApiAuthInputs, type AuthenticationInput } from \"./types\";\nimport { ApiKeyAuthTemplate, describeApiKeyAuthMethod } from \"@rafads/sdk/http-auth\";\nimport {\n checkHealthOpenApi,\n compileAndPersistOpenApiSpecStreaming,\n compileOpenApiSpec,\n invokeOpenApiBackedTool,\n listHealthCheckCandidatesOpenApi,\n openApiStoredOperationsFromCompiled,\n resolveOpenApiBackedAnnotations,\n resolveOpenApiBackedTools,\n validateOpenApiBackedToolArgs,\n} from \"./backing\";\nimport type { InvokeOptions } from \"./invoke\";\nimport { resolveServerUrl } from \"./openapi-utils\";\n\n// ---------------------------------------------------------------------------\n// Extension input shapes\n// ---------------------------------------------------------------------------\n\nexport type OpenApiSpecInput = typeof OpenApiSpecInputSchema.Type;\n\nexport interface OpenApiPreviewInput {\n readonly spec: string;\n readonly specFormat?: string;\n}\n\n/** Add an OpenAPI integration to the catalog. The integration is the API\n * surface; connections (the credentials) are attached separately and resolve\n * their value through the declared `authenticationTemplate`. */\nexport interface OpenApiSpecConfig {\n readonly spec: OpenApiSpecInput;\n /** The catalog slug for the new integration (the `<integration>` segment). */\n readonly slug?: string;\n /** Display name (defaults to the spec title). */\n readonly name?: string;\n /** Agent-visible description (defaults to the spec's `info.description`,\n * then the title). */\n readonly description?: string;\n readonly baseUrl?: string;\n /** Static headers applied to every request (no secret material). */\n readonly headers?: Record<string, string>;\n /** Static query params applied to every request. */\n readonly queryParams?: Record<string, string>;\n readonly specFormat?: string;\n readonly family?: string;\n readonly healthCheck?: HealthCheckSpec;\n /** Auth methods a connection's value renders through - canonical\n * placements or the request-shaped authoring dialect. */\n readonly authenticationTemplate?: readonly AuthenticationInput[];\n}\n\nexport interface OpenApiExtensionFailure {\n readonly _tag: string;\n}\n\n/** Add / merge custom auth methods onto an existing OpenAPI integration's\n * `authenticationTemplate`, and update request routing metadata. Mirrors the\n * GraphQL plugin's `configure`. */\nexport interface OpenApiConfigureInput {\n /** The auth methods to add. Each entry is appended to (or, when its `slug`\n * already exists, replaces) the integration's existing template array. A\n * custom apiKey method with no `slug` is assigned a generated `custom_<id>`\n * slug that is collision-checked against the existing template. */\n readonly authenticationTemplate?: readonly AuthenticationInput[];\n readonly mode?: \"merge\" | \"replace\";\n readonly baseUrl?: string;\n}\n\n/** What changed in the tool catalog when a spec was updated in place. Tool\n * names, not addresses - the same diff applies to every connection. */\nexport interface UpdateSpecResult {\n readonly slug: IntegrationSlug;\n readonly toolCount: number;\n readonly addedTools: readonly string[];\n readonly removedTools: readonly string[];\n}\n\nexport interface OpenApiUpdateSpecInput {\n /** New spec source. Omit to re-fetch from the integration's stored\n * `specUrl`. */\n readonly spec?: OpenApiSpecInput;\n}\n\nexport interface OpenApiPluginExtension {\n readonly previewSpec: (\n input: string | OpenApiPreviewInput,\n ) => Effect.Effect<\n SpecPreview,\n OpenApiParseError | OpenApiExtractionError | OpenApiOAuthError | StorageFailure\n >;\n readonly addSpec: (\n config: OpenApiSpecConfig,\n ) => Effect.Effect<\n { readonly slug: IntegrationSlug; readonly toolCount: number },\n | OpenApiParseError\n | OpenApiExtractionError\n | OpenApiOAuthError\n | IntegrationAlreadyExistsError\n | StorageFailure\n >;\n /** Re-resolve the integration's spec (from its stored source URL, or the\n * provided input) and rebuild its tools IN PLACE - connections,\n * credentials, policies, and the curated description are untouched. */\n readonly updateSpec: (\n slug: string,\n input?: OpenApiUpdateSpecInput,\n ) => Effect.Effect<\n UpdateSpecResult,\n | OpenApiParseError\n | OpenApiExtractionError\n | OpenApiOAuthError\n | IntegrationNotFoundError\n | StorageFailure\n >;\n readonly removeSpec: (slug: string) => Effect.Effect<void, StorageFailure>;\n readonly getIntegration: (slug: string) => Effect.Effect<Integration | null, StorageFailure>;\n /** Read the integration's full opaque config, including its\n * `authenticationTemplate`. Returns null when the integration is absent. */\n readonly getConfig: (\n slug: string,\n ) => Effect.Effect<OpenApiIntegrationConfig | null, StorageFailure>;\n /** Add / merge custom auth methods onto the integration's\n * `authenticationTemplate`. Returns the resulting template array. */\n readonly configure: (\n slug: string,\n input: OpenApiConfigureInput,\n ) => Effect.Effect<readonly Authentication[], StorageFailure>;\n}\n\n// ---------------------------------------------------------------------------\n// Control-tool input/output schemas\n// ---------------------------------------------------------------------------\n\nconst PreviewSpecInputSchema = Schema.Struct({\n spec: Schema.String,\n specFormat: Schema.optional(Schema.String),\n});\n\nconst StaticPreviewServerVariableSchema = Schema.Struct({\n default: Schema.String,\n enum: Schema.NullOr(Schema.Array(Schema.String)),\n description: Schema.NullOr(Schema.String),\n});\nconst StaticPreviewServerSchema = Schema.Struct({\n url: Schema.String,\n description: Schema.NullOr(Schema.String),\n variables: Schema.NullOr(Schema.Record(Schema.String, StaticPreviewServerVariableSchema)),\n});\nconst StaticPreviewOAuthAuthorizationCodeFlowSchema = Schema.Struct({\n authorizationUrl: Schema.String,\n tokenUrl: Schema.String,\n refreshUrl: Schema.NullOr(Schema.String),\n scopes: Schema.Record(Schema.String, Schema.String),\n});\nconst StaticPreviewOAuthClientCredentialsFlowSchema = Schema.Struct({\n tokenUrl: Schema.String,\n refreshUrl: Schema.NullOr(Schema.String),\n scopes: Schema.Record(Schema.String, Schema.String),\n});\nconst StaticPreviewOAuthFlowsSchema = Schema.Struct({\n authorizationCode: Schema.NullOr(StaticPreviewOAuthAuthorizationCodeFlowSchema),\n clientCredentials: Schema.NullOr(StaticPreviewOAuthClientCredentialsFlowSchema),\n});\nconst StaticPreviewSecuritySchemeSchema = Schema.Struct({\n name: Schema.String,\n type: Schema.Literals([\"http\", \"apiKey\", \"oauth2\", \"openIdConnect\"]),\n scheme: Schema.NullOr(Schema.String),\n bearerFormat: Schema.NullOr(Schema.String),\n in: Schema.NullOr(Schema.Literals([\"header\", \"query\", \"cookie\"])),\n headerName: Schema.NullOr(Schema.String),\n description: Schema.NullOr(Schema.String),\n flows: Schema.NullOr(StaticPreviewOAuthFlowsSchema),\n openIdConnectUrl: Schema.NullOr(Schema.String),\n});\nconst StaticPreviewOAuth2PresetSchema = Schema.Struct({\n label: Schema.String,\n securitySchemeName: Schema.String,\n flow: Schema.Literals([\"authorizationCode\", \"clientCredentials\"]),\n authorizationUrl: Schema.NullOr(Schema.String),\n tokenUrl: Schema.String,\n resource: Schema.NullOr(Schema.String),\n refreshUrl: Schema.NullOr(Schema.String),\n scopes: Schema.Record(Schema.String, Schema.String),\n identityScopes: Schema.Union([\n Schema.Literal(\"auto\"),\n Schema.Literal(false),\n Schema.Array(Schema.String),\n ]),\n supportsClientIdMetadataDocument: Schema.optional(Schema.Boolean),\n});\nconst StaticPreviewSpecOutputSchema = Schema.Struct({\n title: Schema.NullOr(Schema.String),\n version: Schema.NullOr(Schema.String),\n servers: Schema.Array(StaticPreviewServerSchema),\n operationCount: Schema.Number,\n tags: Schema.Array(Schema.String),\n securitySchemes: Schema.Array(StaticPreviewSecuritySchemeSchema),\n authStrategies: Schema.Array(Schema.Struct({ schemes: Schema.Array(Schema.String) })),\n headerPresets: Schema.Array(\n Schema.Struct({\n label: Schema.String,\n headers: Schema.Record(Schema.String, Schema.NullOr(Schema.String)),\n secretHeaders: Schema.Array(Schema.String),\n }),\n ),\n oauth2Presets: Schema.Array(StaticPreviewOAuth2PresetSchema),\n});\ntype StaticPreviewSpecOutput = typeof StaticPreviewSpecOutputSchema.Type;\n\nconst OpenApiSpecInputSchema = Schema.Union([\n Schema.Struct({ kind: Schema.Literal(\"url\"), url: Schema.String }),\n Schema.Struct({ kind: Schema.Literal(\"blob\"), value: Schema.String }),\n]);\n\nconst AuthenticationSchema = Schema.Union([\n Schema.Struct({\n slug: Schema.String,\n kind: Schema.Literal(\"oauth2\"),\n authorizationUrl: Schema.String,\n tokenUrl: Schema.String,\n resource: Schema.optional(Schema.NullOr(Schema.String)),\n scopes: Schema.Array(Schema.String),\n supportsClientIdMetadataDocument: Schema.optional(Schema.Boolean),\n }),\n // Credential methods are authored request-shaped - the ONE apikey input\n // dialect: `{ type: \"apiKey\", headers: { Authorization: [\"Bearer \",\n // variable(\"token\")] }, queryParams: { … } }`.\n ApiKeyAuthTemplate,\n]);\n\nconst AddIntegrationInputSchema = Schema.Struct({\n spec: OpenApiSpecInputSchema,\n slug: Schema.optional(Schema.String),\n name: Schema.optional(Schema.String),\n description: Schema.optional(Schema.String),\n baseUrl: Schema.optional(Schema.String),\n headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n specFormat: Schema.optional(Schema.String),\n family: Schema.optional(Schema.String),\n healthCheck: Schema.optional(HealthCheckSpec),\n authenticationTemplate: Schema.optional(Schema.Array(AuthenticationSchema)),\n});\n\nconst AddIntegrationOutputSchema = Schema.Struct({\n slug: Schema.String,\n toolCount: Schema.Number,\n});\n\nconst PreviewSpecInputStandardSchema = Schema.toStandardSchemaV1(\n Schema.toStandardJSONSchemaV1(PreviewSpecInputSchema),\n);\nconst PreviewSpecOutputStandardSchema = Schema.toStandardSchemaV1(\n Schema.toStandardJSONSchemaV1(StaticPreviewSpecOutputSchema),\n);\nconst AddIntegrationInputStandardSchema = Schema.toStandardSchemaV1(\n Schema.toStandardJSONSchemaV1(AddIntegrationInputSchema),\n);\nconst AddIntegrationOutputStandardSchema = Schema.toStandardSchemaV1(\n Schema.toStandardJSONSchemaV1(AddIntegrationOutputSchema),\n);\n\nconst openApiToolFailure = (code: string, message: string, details?: unknown) =>\n ToolResult.fail({\n code,\n message,\n ...(details === undefined ? {} : { details }),\n });\n\nconst staticPreviewOutput = (preview: SpecPreview): StaticPreviewSpecOutput => ({\n title: Option.getOrNull(preview.title),\n version: Option.getOrNull(preview.version),\n servers: preview.servers.map((server) => ({\n url: server.url,\n description: Option.getOrNull(server.description),\n variables: Option.getOrNull(server.variables)\n ? Object.fromEntries(\n Object.entries(Option.getOrNull(server.variables) ?? {}).map(([name, variable]) => [\n name,\n {\n default: variable.default,\n enum: Option.getOrNull(variable.enum),\n description: Option.getOrNull(variable.description),\n },\n ]),\n )\n : null,\n })),\n operationCount: preview.operationCount,\n tags: preview.tags,\n securitySchemes: preview.securitySchemes.map((scheme) => ({\n name: scheme.name,\n type: scheme.type,\n scheme: Option.getOrNull(scheme.scheme),\n bearerFormat: Option.getOrNull(scheme.bearerFormat),\n in: Option.getOrNull(scheme.in),\n headerName: Option.getOrNull(scheme.headerName),\n description: Option.getOrNull(scheme.description),\n flows: Option.isSome(scheme.flows)\n ? {\n authorizationCode: Option.isSome(scheme.flows.value.authorizationCode)\n ? {\n authorizationUrl: scheme.flows.value.authorizationCode.value.authorizationUrl,\n tokenUrl: scheme.flows.value.authorizationCode.value.tokenUrl,\n refreshUrl: Option.getOrNull(scheme.flows.value.authorizationCode.value.refreshUrl),\n scopes: scheme.flows.value.authorizationCode.value.scopes,\n }\n : null,\n clientCredentials: Option.isSome(scheme.flows.value.clientCredentials)\n ? {\n tokenUrl: scheme.flows.value.clientCredentials.value.tokenUrl,\n refreshUrl: Option.getOrNull(scheme.flows.value.clientCredentials.value.refreshUrl),\n scopes: scheme.flows.value.clientCredentials.value.scopes,\n }\n : null,\n }\n : null,\n openIdConnectUrl: Option.getOrNull(scheme.openIdConnectUrl),\n })),\n authStrategies: preview.authStrategies,\n headerPresets: preview.headerPresets,\n oauth2Presets: preview.oauth2Presets.map((preset) => ({\n label: preset.label,\n securitySchemeName: preset.securitySchemeName,\n flow: preset.flow,\n authorizationUrl: Option.getOrNull(preset.authorizationUrl),\n tokenUrl: preset.tokenUrl,\n resource: Option.getOrNull(preset.resource),\n refreshUrl: Option.getOrNull(preset.refreshUrl),\n scopes: preset.scopes,\n identityScopes: preset.identityScopes,\n supportsClientIdMetadataDocument: preset.supportsClientIdMetadataDocument,\n })),\n});\n\nconst specInputToSpecUrl = (spec: OpenApiSpecInput): string | undefined =>\n spec.kind === \"url\" ? spec.url : undefined;\n\nconst OAUTH_DISCOVERED_SCHEME_NAME = \"DiscoveredOAuth2\";\nconst OPENAPI_HTTP_METHODS = new Set([\n \"get\",\n \"put\",\n \"post\",\n \"delete\",\n \"patch\",\n \"head\",\n \"options\",\n \"trace\",\n]);\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst maybeUrl = (value: string): URL | null => {\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: URL parsing accepts user-pasted spec/base URLs\n try {\n return new URL(value);\n } catch {\n return null;\n }\n};\n\nconst addProbeCandidate = (candidates: string[], value: string | undefined): void => {\n const trimmed = value?.trim();\n if (!trimmed) return;\n const parsed = maybeUrl(trimmed);\n if (!parsed || (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\")) return;\n const normalized = parsed.toString();\n const origin = parsed.origin;\n if (!candidates.includes(normalized)) candidates.push(normalized);\n if (!candidates.includes(origin)) candidates.push(origin);\n};\n\nconst oauthProbeCandidates = (\n preview: SpecPreview,\n specUrl: string | undefined,\n baseUrl: string | undefined,\n): readonly string[] => {\n const candidates: string[] = [];\n addProbeCandidate(candidates, baseUrl);\n for (const server of preview.servers) {\n addProbeCandidate(\n candidates,\n resolveServerUrl(server.url, Option.getOrUndefined(server.variables), {}),\n );\n }\n addProbeCandidate(candidates, specUrl);\n return candidates;\n};\n\nconst securityRequirementScopes = (\n security: unknown,\n targetSchemes: ReadonlySet<string>,\n): readonly string[] => {\n if (!Array.isArray(security)) return [];\n const scopes = new Set<string>();\n for (const requirement of security) {\n if (!isRecord(requirement)) continue;\n for (const [scheme, rawScopes] of Object.entries(requirement)) {\n if (targetSchemes.size > 0 && !targetSchemes.has(scheme)) continue;\n if (!Array.isArray(rawScopes)) continue;\n for (const scope of rawScopes) {\n if (typeof scope === \"string\" && scope.trim().length > 0) scopes.add(scope.trim());\n }\n }\n }\n return [...scopes];\n};\n\nconst collectDeclaredSecurityScopes = (doc: unknown, targetSchemes: ReadonlySet<string>) => {\n const scopes = new Set<string>();\n if (!isRecord(doc)) return [] as readonly string[];\n\n for (const scope of securityRequirementScopes(doc.security, targetSchemes)) scopes.add(scope);\n\n const paths = doc.paths;\n if (!isRecord(paths)) return [...scopes].sort();\n for (const pathItem of Object.values(paths)) {\n if (!isRecord(pathItem)) continue;\n for (const [method, operation] of Object.entries(pathItem)) {\n if (!OPENAPI_HTTP_METHODS.has(method.toLowerCase()) || !isRecord(operation)) continue;\n for (const scope of securityRequirementScopes(operation.security, targetSchemes)) {\n scopes.add(scope);\n }\n }\n }\n return [...scopes].sort();\n};\n\nconst nonOAuthSecuritySchemeNames = (preview: SpecPreview): ReadonlySet<string> =>\n new Set(\n preview.securitySchemes\n .filter((scheme) => scheme.type === \"http\" || scheme.type === \"apiKey\")\n .map((scheme) => scheme.name),\n );\n\nconst discoveredOAuthPreview = (input: {\n readonly preview: SpecPreview;\n readonly authorizationUrl: string;\n readonly tokenUrl: string;\n readonly resource?: string | null;\n readonly scopes: readonly string[];\n readonly supportsClientIdMetadataDocument?: boolean;\n}): SpecPreview => {\n const scopes = Object.fromEntries(input.scopes.map((scope) => [scope, \"\"]));\n const flow = OAuth2AuthorizationCodeFlow.make({\n authorizationUrl: input.authorizationUrl,\n tokenUrl: input.tokenUrl,\n refreshUrl: Option.none(),\n scopes,\n });\n const flows = OAuth2Flows.make({\n authorizationCode: Option.some(flow),\n clientCredentials: Option.none(),\n });\n return {\n ...input.preview,\n securitySchemes: [\n ...input.preview.securitySchemes,\n SecurityScheme.make({\n name: OAUTH_DISCOVERED_SCHEME_NAME,\n type: \"oauth2\",\n scheme: Option.none(),\n bearerFormat: Option.none(),\n in: Option.none(),\n headerName: Option.none(),\n description: Option.some(\"Discovered from OAuth authorization-server metadata\"),\n flows: Option.some(flows),\n openIdConnectUrl: Option.none(),\n }),\n ],\n oauth2Presets: [\n ...input.preview.oauth2Presets,\n OAuth2Preset.make({\n label: `OAuth2 Authorization Code · ${OAUTH_DISCOVERED_SCHEME_NAME}`,\n securitySchemeName: OAUTH_DISCOVERED_SCHEME_NAME,\n flow: \"authorizationCode\",\n authorizationUrl: Option.some(input.authorizationUrl),\n tokenUrl: input.tokenUrl,\n resource: input.resource ? Option.some(input.resource) : Option.none(),\n refreshUrl: Option.none(),\n scopes,\n identityScopes: \"auto\",\n ...(input.supportsClientIdMetadataDocument === true\n ? { supportsClientIdMetadataDocument: true }\n : {}),\n }),\n ],\n };\n};\n\n// ---------------------------------------------------------------------------\n// Declared auth methods - project the stored `authenticationTemplate` into the\n// catalog's plugin-agnostic `AuthMethodDescriptor[]`. This mirrors the client's\n// `authMethodsFromConfig` (in the React auth-method-config module) on the\n// server so the catalog field is consistent. apikey/none projection comes from\n// the shared model; the oauth method carries the stored endpoints + scopes.\n// ---------------------------------------------------------------------------\n\nexport const describeOpenApiAuthMethods = (\n record: IntegrationRecord,\n): readonly AuthMethodDescriptor[] => {\n const config = decodeOpenApiIntegrationConfig(record.config);\n if (!config) return [];\n return (config.authenticationTemplate ?? []).map(\n (template: Authentication): AuthMethodDescriptor => {\n if (template.kind === \"oauth2\") {\n return {\n id: String(template.slug),\n label: \"OAuth2\",\n kind: \"oauth\",\n template: String(template.slug),\n oauth: {\n authorizationUrl: template.authorizationUrl,\n tokenUrl: template.tokenUrl,\n resource: template.resource ?? null,\n scopes: template.scopes,\n supportsClientIdMetadataDocument: template.supportsClientIdMetadataDocument,\n },\n };\n }\n return describeApiKeyAuthMethod(template);\n },\n );\n};\n\nexport const describeOpenApiIntegrationDisplay = (\n record: IntegrationRecord,\n): { readonly url?: string; readonly family?: string } => {\n const config = decodeOpenApiIntegrationConfig(record.config);\n return {\n url: config?.baseUrl ?? config?.specUrl,\n ...(config?.family ? { family: config.family } : {}),\n };\n};\n\n// ---------------------------------------------------------------------------\n// Plugin factory\n// ---------------------------------------------------------------------------\n\nexport interface OpenApiPluginOptions {\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient, never, never>;\n readonly invokeOptions?: InvokeOptions;\n readonly specFormats?: readonly SpecFormatAdapter[];\n readonly presets?: readonly OpenApiPreset[];\n}\n\nexport const openApiPlugin = definePlugin<\n \"openapi\",\n OpenApiPluginExtension,\n OpenapiStore,\n OpenApiPluginOptions\n>((options?: OpenApiPluginOptions) => {\n const resolveSpecForInput = (\n config: Pick<OpenApiSpecConfig, \"spec\" | \"specFormat\" | \"headers\" | \"queryParams\" | \"baseUrl\">,\n httpClientLayer: Layer.Layer<HttpClient.HttpClient, never, never>,\n ): Effect.Effect<ConvertedSpec, OpenApiParseError | OpenApiExtractionError | OpenApiOAuthError> =>\n Effect.gen(function* () {\n const adapter = yield* resolveSpecFormatAdapter(\n options?.specFormats ?? [],\n config.specFormat,\n );\n if (adapter) {\n if (config.spec.kind !== \"url\") {\n return yield* new OpenApiParseError({\n message: \"Spec format adapters require a URL spec input\",\n });\n }\n return yield* adapter.fetch({\n urls: [config.spec.url],\n credentials: {\n ...(config.headers ? { headers: config.headers } : {}),\n ...(config.queryParams ? { queryParams: config.queryParams } : {}),\n },\n httpClientLayer,\n });\n }\n if (config.spec.kind === \"url\") {\n const specText = yield* resolveSpecText(config.spec.url).pipe(\n Effect.provide(httpClientLayer),\n );\n return { specText, specUrl: config.spec.url };\n }\n return { specText: config.spec.value };\n });\n\n return {\n id: \"openapi\" as const,\n packageName: \"@rafads/plugin-openapi\",\n clientConfig: options?.presets ? { presets: options.presets } : undefined,\n integrationPresets: [...openApiPresets, ...(options?.presets ?? [])].map((preset) => ({\n id: preset.id,\n name: preset.name,\n summary: preset.summary,\n ...(preset.url ? { url: preset.url } : {}),\n ...(preset.icon ? { icon: preset.icon } : {}),\n ...(preset.featured ? { featured: preset.featured } : {}),\n ...(preset.family ? { family: preset.family } : {}),\n ...(preset.specFormat ? { specFormat: preset.specFormat } : {}),\n ...(preset.defaultSlug ? { defaultSlug: preset.defaultSlug } : {}),\n ...(preset.authTemplate ? { authTemplate: preset.authTemplate } : {}),\n ...(preset.healthCheck ? { healthCheck: preset.healthCheck } : {}),\n })),\n storage: (deps): OpenapiStore => makeDefaultOpenapiStore(deps),\n\n extension: (ctx: PluginCtx<OpenapiStore>) => {\n const httpClientLayer = options?.httpClientLayer ?? ctx.httpClientLayer;\n\n const enrichPreviewWithDiscoveredOAuth = (input: {\n readonly specText: string;\n readonly preview: SpecPreview;\n readonly specUrl?: string;\n readonly baseUrl?: string;\n }): Effect.Effect<SpecPreview, OpenApiParseError | OpenApiExtractionError> =>\n Effect.gen(function* () {\n if (input.preview.oauth2Presets.length > 0) return input.preview;\n\n const candidates = oauthProbeCandidates(input.preview, input.specUrl, input.baseUrl);\n if (candidates.length === 0) return input.preview;\n\n for (const candidate of candidates) {\n const oauth = yield* ctx.oauth.probe({ url: candidate }).pipe(\n Effect.map((result) => ({ ok: true as const, result })),\n Effect.catch(() => Effect.succeed({ ok: false as const, result: null })),\n );\n if (!oauth.ok) continue;\n\n const doc = yield* parse(input.specText);\n const declaredScopes = collectDeclaredSecurityScopes(\n doc,\n nonOAuthSecuritySchemeNames(input.preview),\n );\n const supportedScopes =\n oauth.result.scopesSupported && oauth.result.scopesSupported.length > 0\n ? new Set(oauth.result.scopesSupported)\n : null;\n const scopes = supportedScopes\n ? declaredScopes.filter((scope) => supportedScopes.has(scope))\n : declaredScopes;\n return discoveredOAuthPreview({\n preview: input.preview,\n authorizationUrl: oauth.result.authorizationUrl,\n tokenUrl: oauth.result.tokenUrl,\n resource: oauth.result.resource ?? null,\n scopes,\n supportsClientIdMetadataDocument:\n oauth.result.clientIdMetadataDocumentSupported === true,\n });\n }\n\n return input.preview;\n });\n\n const addSpec = (config: OpenApiSpecConfig) =>\n Effect.gen(function* () {\n // Resolve URL → text and parse BEFORE opening a transaction. Holding\n // `BEGIN` across a network fetch is the Hyperdrive deadlock path.\n const resolved = yield* resolveSpecForInput(config, httpClientLayer);\n const compiled = resolved.keepPathItem\n ? undefined\n : yield* compileOpenApiSpec(resolved.specText);\n const adapter = yield* resolveSpecFormatAdapter(\n options?.specFormats ?? [],\n config.specFormat,\n );\n const derivedIdentity =\n adapter?.deriveIdentity && resolved.document\n ? adapter.deriveIdentity(resolved.document)\n : null;\n const resolvedSlug = config.slug?.trim() || derivedIdentity?.slug;\n if (!resolvedSlug) {\n return yield* new OpenApiParseError({\n message: \"OpenAPI integration slug is required\",\n });\n }\n\n // Defaults the add page derives from its preview, applied here so\n // headless callers (MCP, API) get the same integration the UI's\n // add flow would produce - see e2e/scenarios/connect-handoff.test.ts:\n // - effectiveBaseUrl: the spec's first server, used to anchor the\n // derived auth template's absolute URLs. It is NOT stored as the\n // connection baseUrl - the request host is resolved per call from\n // the operation's extracted `servers`.\n // - authenticationTemplate: the spec's declared security schemes\n // (else the Add-connection modal is a dead \"No authentication\"\n // end with nowhere to paste a credential)\n // An explicit input always wins; for auth, an explicit EMPTY array\n // means \"no auth methods\" and suppresses the derivation.\n const explicitBaseUrl = config.baseUrl ?? resolved.baseUrl;\n const needsDerivedBaseUrl = explicitBaseUrl == null;\n const needsDerivedAuth = config.authenticationTemplate == null;\n const preview =\n needsDerivedBaseUrl || needsDerivedAuth\n ? yield* previewSpecText(resolved.specText).pipe(\n Effect.flatMap((rawPreview) =>\n enrichPreviewWithDiscoveredOAuth({\n specText: resolved.specText,\n preview: rawPreview,\n specUrl: resolved.specUrl ?? specInputToSpecUrl(config.spec),\n baseUrl: explicitBaseUrl,\n }),\n ),\n )\n : undefined;\n const derivedBaseUrl =\n needsDerivedBaseUrl && preview ? firstBaseUrlForPreview(preview) : undefined;\n const effectiveBaseUrl = explicitBaseUrl ?? (derivedBaseUrl || undefined);\n const derivedAuthenticationTemplate =\n needsDerivedAuth && preview\n ? deriveAuthenticationTemplateFromPreview(preview, effectiveBaseUrl)\n : undefined;\n\n const slug = IntegrationSlug.make(resolvedSlug);\n\n // Block re-adding an existing slug. The core `integrations.register`\n // primitive upserts (so boot re-registration is idempotent), but an\n // explicit add must NOT silently clobber an existing integration's\n // tools, connections, and policies. To add more auth, update the\n // existing integration instead.\n const existing = yield* ctx.core.integrations.get(slug);\n if (existing) {\n return yield* new IntegrationAlreadyExistsError({ slug });\n }\n\n const specHash = yield* sha256Hex(resolved.specText);\n\n const integrationConfig: OpenApiIntegrationConfig = {\n ...(resolved.config ?? {}),\n specHash,\n ...((resolved.specUrl ?? specInputToSpecUrl(config.spec)) !== undefined\n ? { specUrl: resolved.specUrl ?? specInputToSpecUrl(config.spec) }\n : {}),\n // baseUrl is an optional override only. The host is otherwise\n // resolved per call from the operation's `servers` (extracted from\n // the spec), so we never bake a derived base URL into the config.\n ...(config.baseUrl ? { baseUrl: config.baseUrl } : {}),\n ...(config.headers ? { headers: config.headers } : {}),\n ...(config.queryParams ? { queryParams: config.queryParams } : {}),\n ...(config.specFormat ? { specFormat: config.specFormat } : {}),\n ...(config.family ? { family: config.family } : {}),\n // Prefer the caller's explicit template; otherwise derive from the\n // spec's declared security schemes.\n ...(config.authenticationTemplate\n ? {\n authenticationTemplate: normalizeOpenApiAuthInputs(config.authenticationTemplate),\n }\n : resolved.authenticationTemplate && resolved.authenticationTemplate.length > 0\n ? { authenticationTemplate: resolved.authenticationTemplate }\n : derivedAuthenticationTemplate && derivedAuthenticationTemplate.length > 0\n ? { authenticationTemplate: derivedAuthenticationTemplate }\n : {}),\n };\n\n // The spec blob is written OUTSIDE the transaction: it's\n // content-addressed (re-puts are idempotent) and an aborted register\n // leaves only an unreferenced blob behind - while blob backends like\n // R2 couldn't roll back with the transaction anyway.\n yield* ctx.storage.putSpec(specHash, resolved.specText);\n // The content-addressed defs blob lets the serve path resolve the\n // shared `definitions` without re-parsing the spec. Same idempotent,\n // outside-the-transaction rationale as the spec blob.\n if (compiled) {\n yield* ctx.storage.putDefs(specHash, JSON.stringify(compiled.hoistedDefs));\n }\n\n yield* ctx.transaction(\n Effect.gen(function* () {\n yield* ctx.core.integrations.register({\n slug,\n name:\n config.name?.trim() || derivedIdentity?.name || compiled?.title || resolvedSlug,\n description:\n config.description ??\n derivedIdentity?.description ??\n compiled?.description ??\n compiled?.title ??\n resolvedSlug,\n config: integrationConfig satisfies OpenApiIntegrationConfig as IntegrationConfig,\n canRemove: true,\n canRefresh: integrationConfig.specUrl != null,\n });\n if (config.healthCheck) {\n yield* ctx.core.integrations.setHealthCheck(slug, config.healthCheck);\n }\n if (compiled) {\n yield* ctx.storage.putOperations(\n resolvedSlug,\n openApiStoredOperationsFromCompiled(resolvedSlug, compiled),\n );\n return compiled.definitions.length;\n }\n const persisted = yield* compileAndPersistOpenApiSpecStreaming({\n specText: resolved.specText,\n integration: resolvedSlug,\n storage: ctx.storage,\n specHash,\n keepPathItem: resolved.keepPathItem,\n });\n return persisted.toolCount;\n }),\n );\n\n const toolCount = compiled\n ? compiled.definitions.length\n : yield* ctx.storage\n .listOperations(resolvedSlug)\n .pipe(Effect.map((operations) => operations.length));\n return { slug, toolCount };\n });\n\n // Update the spec IN PLACE: re-resolve (stored source URL / bundle, or a\n // caller-supplied new input), recompile, swap the stored operations, and\n // rebuild every connection's tools. Auth templates, base URL, headers,\n // the curated description, connections, and policies are all untouched -\n // this is the \"spec changed upstream\" path, not a re-add.\n const updateSpec = (rawSlug: string, input?: OpenApiUpdateSpecInput) =>\n Effect.gen(function* () {\n const slug = IntegrationSlug.make(rawSlug);\n const record = yield* ctx.core.integrations.get(slug);\n const current = record ? decodeOpenApiIntegrationConfig(record.config) : null;\n if (!record || !current) {\n return yield* new IntegrationNotFoundError({ slug });\n }\n\n // The new spec source: explicit input wins; otherwise re-fetch from\n // where the spec originally came from. A pasted-blob integration has\n // no origin, so updating it requires a new input.\n const specInput: OpenApiSpecInput | null =\n input?.spec ?? (current.specUrl ? { kind: \"url\", url: current.specUrl } : null);\n if (specInput === null) {\n return yield* new OpenApiParseError({\n message:\n \"This integration's spec was pasted inline and has no source URL to re-fetch. Provide the updated spec content.\",\n });\n }\n\n // Resolve + compile BEFORE the transaction (same Hyperdrive-deadlock\n // rule as addSpec: never hold BEGIN across a network fetch).\n const resolved = yield* resolveSpecForInput(\n {\n spec: specInput,\n specFormat: current.specFormat,\n headers: current.headers,\n queryParams: current.queryParams,\n baseUrl: current.baseUrl,\n },\n httpClientLayer,\n );\n const compiled = resolved.keepPathItem\n ? undefined\n : yield* compileOpenApiSpec(resolved.specText);\n\n const previousOperations = yield* ctx.storage.listOperations(rawSlug);\n const previousNames = new Set(previousOperations.map((op) => op.toolName));\n\n // The resolved spec text lives in the plugin blob store keyed by its\n // content hash (`spec/<hash>`); the config carries only the hash. Put\n // the blob outside the transaction - re-puts are idempotent and an\n // aborted config update just leaves an unreferenced blob.\n const specHash = yield* sha256Hex(resolved.specText);\n yield* ctx.storage.putSpec(specHash, resolved.specText);\n if (compiled) {\n yield* ctx.storage.putDefs(specHash, JSON.stringify(compiled.hoistedDefs));\n }\n\n const nextConfig: OpenApiIntegrationConfig = {\n ...current,\n specHash,\n ...((resolved.specUrl ?? specInputToSpecUrl(specInput)) !== undefined\n ? { specUrl: resolved.specUrl ?? specInputToSpecUrl(specInput) }\n : {}),\n };\n\n yield* ctx.transaction(\n Effect.gen(function* () {\n yield* ctx.core.integrations.update(slug, {\n config: nextConfig satisfies OpenApiIntegrationConfig as IntegrationConfig,\n });\n if (compiled) {\n yield* ctx.storage.putOperations(\n rawSlug,\n openApiStoredOperationsFromCompiled(rawSlug, compiled),\n );\n } else {\n yield* compileAndPersistOpenApiSpecStreaming({\n specText: resolved.specText,\n integration: rawSlug,\n storage: ctx.storage,\n specHash,\n keepPathItem: resolved.keepPathItem,\n });\n }\n }),\n );\n\n const nextOperations = compiled\n ? openApiStoredOperationsFromCompiled(rawSlug, compiled)\n : yield* ctx.storage.listOperations(rawSlug);\n const nextNames = new Set(nextOperations.map((op) => op.toolName));\n\n // Rebuild each connection's tool rows from the new spec. Outside the\n // transaction: refresh opens its own, and a half-refreshed catalog\n // self-heals on the next refresh anyway.\n const connections = yield* ctx.connections.list({ integration: slug });\n yield* Effect.forEach(\n connections,\n (connection) =>\n ctx.connections\n .refresh({\n owner: connection.owner,\n integration: connection.integration,\n name: connection.name,\n })\n .pipe(Effect.catchTag(\"ConnectionNotFoundError\", () => Effect.succeed([]))),\n { discard: true },\n ).pipe(\n Effect.catchTag(\"IntegrationNotFoundError\", () => Effect.void),\n Effect.withSpan(\"openapi.plugin.update_spec.refresh_connections\", {\n attributes: { \"openapi.connection_count\": connections.length },\n }),\n );\n\n return {\n slug,\n toolCount: nextNames.size,\n addedTools: [...nextNames].filter((name) => !previousNames.has(name)).sort(),\n removedTools: [...previousNames].filter((name) => !nextNames.has(name)).sort(),\n } satisfies UpdateSpecResult;\n }).pipe(\n Effect.withSpan(\"openapi.plugin.update_spec\", {\n attributes: { \"openapi.integration.slug\": rawSlug },\n }),\n );\n\n return {\n previewSpec: (input: string | OpenApiPreviewInput) =>\n Effect.gen(function* () {\n const previewInput = typeof input === \"string\" ? { spec: input } : input;\n const spec = maybeUrl(previewInput.spec.trim())\n ? { kind: \"url\" as const, url: previewInput.spec.trim() }\n : { kind: \"blob\" as const, value: previewInput.spec };\n const resolved = yield* resolveSpecForInput(\n { spec, specFormat: previewInput.specFormat },\n httpClientLayer,\n );\n const preview = yield* previewSpecText(resolved.specText);\n return yield* enrichPreviewWithDiscoveredOAuth({\n specText: resolved.specText,\n preview,\n specUrl: resolved.specUrl ?? (spec.kind === \"url\" ? spec.url : undefined),\n });\n }),\n\n addSpec,\n\n updateSpec,\n\n removeSpec: (slug: string) =>\n ctx.transaction(\n Effect.gen(function* () {\n yield* ctx.storage.removeOperations(slug);\n yield* ctx.core.integrations\n .remove(IntegrationSlug.make(slug))\n .pipe(Effect.catchTag(\"IntegrationRemovalNotAllowedError\", () => Effect.void));\n }),\n ),\n\n getIntegration: (slug: string) =>\n ctx.core.integrations.get(IntegrationSlug.make(slug)).pipe(\n Effect.map((record) =>\n record\n ? ({\n slug: record.slug,\n description: record.description,\n kind: record.kind,\n canRemove: record.canRemove,\n canRefresh: record.canRefresh,\n } as Integration)\n : null,\n ),\n ),\n\n getConfig: (slug: string): Effect.Effect<OpenApiIntegrationConfig | null, StorageFailure> =>\n ctx.core.integrations\n .get(IntegrationSlug.make(slug))\n .pipe(\n Effect.map((record) =>\n record ? decodeOpenApiIntegrationConfig(record.config) : null,\n ),\n ),\n\n configure: (\n slug: string,\n input: OpenApiConfigureInput,\n ): Effect.Effect<readonly Authentication[], StorageFailure> =>\n ctx.transaction(\n Effect.gen(function* () {\n const record = yield* ctx.core.integrations.get(IntegrationSlug.make(slug));\n if (!record) return [] as readonly Authentication[];\n const current = decodeOpenApiIntegrationConfig(record.config);\n if (!current) return [] as readonly Authentication[];\n\n const merged =\n input.authenticationTemplate === undefined\n ? (current.authenticationTemplate ?? [])\n : input.mode === \"replace\"\n ? normalizeOpenApiAuthInputs(input.authenticationTemplate)\n : mergeAuthTemplates(\n current.authenticationTemplate ?? [],\n normalizeOpenApiAuthInputs(input.authenticationTemplate),\n );\n\n const next: OpenApiIntegrationConfig = {\n ...current,\n ...(input.baseUrl !== undefined ? { baseUrl: input.baseUrl } : {}),\n authenticationTemplate: merged,\n };\n\n yield* ctx.core.integrations.update(IntegrationSlug.make(slug), {\n config: next satisfies OpenApiIntegrationConfig as IntegrationConfig,\n });\n\n return merged;\n }),\n ),\n };\n },\n\n staticIntegrations: (self: OpenApiPluginExtension) => [\n {\n id: \"openapi\",\n kind: \"executor\",\n name: \"OpenAPI\",\n tools: [\n tool({\n name: \"previewSpec\",\n description:\n \"Preview an OpenAPI document before adding it as an integration. Call this first when the user provides a spec URL/blob so you can inspect servers, auth schemes, operation count, and tags before `addSpec`. Do not collect API keys or OAuth client secrets in chat; use the connections tools for those values.\",\n inputSchema: PreviewSpecInputStandardSchema,\n outputSchema: PreviewSpecOutputStandardSchema,\n execute: (input: typeof PreviewSpecInputSchema.Type) =>\n self.previewSpec(input).pipe(\n Effect.map((preview) => ToolResult.ok(staticPreviewOutput(preview))),\n Effect.catchTags({\n OpenApiParseError: ({ message }: OpenApiParseError) =>\n Effect.succeed(openApiToolFailure(\"openapi_parse_failed\", message)),\n OpenApiExtractionError: ({ message }: OpenApiExtractionError) =>\n Effect.succeed(openApiToolFailure(\"openapi_extraction_failed\", message)),\n OpenApiOAuthError: ({ message }: OpenApiOAuthError) =>\n Effect.succeed(openApiToolFailure(\"openapi_oauth_failed\", message)),\n }),\n ),\n }),\n tool({\n name: \"addSpec\",\n description:\n \"Add an OpenAPI integration to the catalog and persist its operations as tools. Recommended flow: call `previewSpec`, choose a `slug`, then create a connection for that integration with the user's API key or via `oauth.start`. When `baseUrl` is omitted it defaults to the spec's first server; when `authenticationTemplate` is omitted the auth methods are derived from the spec's declared security schemes (pass an explicit template to override how a credential is applied - apiKey header/query, or oauth bearer - or an empty array for no auth methods).\",\n annotations: {\n requiresApproval: true,\n approvalDescription: \"Add an OpenAPI integration\",\n },\n inputSchema: AddIntegrationInputStandardSchema,\n outputSchema: AddIntegrationOutputStandardSchema,\n execute: (input: typeof AddIntegrationInputSchema.Type) =>\n self\n .addSpec({\n spec: input.spec,\n slug: input.slug,\n name: input.name,\n description: input.description,\n baseUrl: input.baseUrl,\n headers: input.headers,\n queryParams: input.queryParams,\n specFormat: input.specFormat,\n family: input.family,\n healthCheck: input.healthCheck,\n authenticationTemplate: input.authenticationTemplate as\n | readonly AuthenticationInput[]\n | undefined,\n })\n .pipe(\n Effect.map((result) =>\n ToolResult.ok({\n slug: String(result.slug),\n toolCount: result.toolCount,\n }),\n ),\n Effect.catchTags({\n OpenApiParseError: ({ message }: OpenApiParseError) =>\n Effect.succeed(openApiToolFailure(\"openapi_parse_failed\", message)),\n OpenApiExtractionError: ({ message }: OpenApiExtractionError) =>\n Effect.succeed(openApiToolFailure(\"openapi_extraction_failed\", message)),\n OpenApiOAuthError: ({ message }: OpenApiOAuthError) =>\n Effect.succeed(openApiToolFailure(\"openapi_oauth_failed\", message)),\n IntegrationAlreadyExistsError: ({ slug }: IntegrationAlreadyExistsError) =>\n Effect.succeed(\n openApiToolFailure(\n \"integration_already_exists\",\n `Integration ${slug} already exists; update it instead of re-adding.`,\n ),\n ),\n }),\n ),\n }),\n ],\n },\n ],\n\n describeAuthMethods: describeOpenApiAuthMethods,\n describeIntegrationDisplay: describeOpenApiIntegrationDisplay,\n\n // Health checks: the declared liveness/identity probe. Core owns the spec\n // storage; the plugin only enumerates candidates and runs probes.\n listHealthCheckCandidates: (input) =>\n listHealthCheckCandidatesOpenApi({ ctx: input.ctx, integration: input.integration }),\n checkHealth: (input) =>\n checkHealthOpenApi({\n ctx: input.ctx,\n integration: input.integration,\n credential: input.credential,\n spec: input.spec,\n httpClientLayer: options?.httpClientLayer ?? input.ctx.httpClientLayer,\n }),\n\n // Produce one tool per spec operation. Spec-derived, identical for every\n // connection on the integration - so `getValue` is never called here. The\n // operation bindings invokeTool needs are persisted at addSpec time; this\n // hook only shapes the per-connection ToolDefs from the spec blob the\n // catalog config points at.\n resolveTools: ({ integration, config, storage }) =>\n resolveOpenApiBackedTools({ integration, config, storage }),\n\n invokeTool: ({ ctx: invokeCtx, toolRow, credential, args }) => {\n const httpClientLayer = options?.httpClientLayer ?? invokeCtx.httpClientLayer;\n return invokeOpenApiBackedTool({\n ctx: invokeCtx,\n toolRow,\n credential,\n args,\n httpClientLayer,\n invokeOptions: options?.invokeOptions,\n });\n },\n\n validateToolArgs: ({ ctx: validateCtx, toolRow, args }) =>\n validateOpenApiBackedToolArgs({ ctx: validateCtx, toolRow, args }),\n\n resolveAnnotations: ({ ctx: annotationsCtx, integration, toolRows }) =>\n resolveOpenApiBackedAnnotations({\n ctx: annotationsCtx,\n integration: String(integration),\n toolRows,\n }),\n\n removeConnection: () => Effect.void,\n\n detect: ({\n ctx: detectCtx,\n url,\n }: {\n readonly ctx: PluginCtx<OpenapiStore>;\n readonly url: string;\n }) =>\n Effect.gen(function* () {\n const httpClientLayer = options?.httpClientLayer ?? detectCtx.httpClientLayer;\n const trimmed = url.trim();\n if (!trimmed) return null;\n const parsed = yield* Effect.try({\n try: () => new URL(trimmed),\n catch: (error) => error,\n }).pipe(Effect.option);\n if (Option.isNone(parsed)) return null;\n const specText = yield* resolveSpecText(trimmed).pipe(\n Effect.provide(httpClientLayer),\n Effect.catch(() => Effect.succeed(null)),\n );\n if (specText === null) return null;\n const doc = yield* parse(specText).pipe(Effect.catch(() => Effect.succeed(null)));\n if (!doc) return null;\n const result = yield* extract(doc).pipe(Effect.catch(() => Effect.succeed(null)));\n if (!result) return null;\n const slug = Option.getOrElse(result.title, () => \"api\")\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\");\n const name = Option.getOrElse(result.title, () => slug);\n return IntegrationDetectionResult.make({\n kind: \"openapi\",\n confidence: \"high\",\n endpoint: trimmed,\n name,\n slug,\n });\n }),\n };\n // HTTP transport (routes/handlers/extensionService) is layered on by\n // the api-aware factory in `@rafads/plugin-openapi/api`. Hosts that\n // want the HTTP surface import the plugin from there; SDK-only consumers\n // stay on this entry and avoid the server-only deps.\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,QAAQ,QAAQ,WAAW,cAAc;AAsBlD,IAAM,uBAAuB;AAC7B,IAAM,cAAc;AACpB,IAAM,wBAAwB;AAE9B,IAAM,gBAAgB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QACZ,UAAU;AAAA,QACV;AAAA,QACA;AAAA,MACF,CAAC;AAAA,IACH,CAAC;AAAA,EACL;AAKF,CAAC;","names":["Effect","Effect","Effect","Option","Schema","Schema","Option","Effect"]}
@@ -0,0 +1,275 @@
1
+ // src/sdk/config.ts
2
+ import { Option, Schema } from "effect";
3
+ import {
4
+ ApiKeyAuthMethod,
5
+ TOKEN_VARIABLE,
6
+ renderAuthPlacements,
7
+ requiredPlacementVariables
8
+ } from "@rafads/sdk/http-auth";
9
+ var OAuthAuthenticationSchema = Schema.Struct({
10
+ slug: Schema.String,
11
+ kind: Schema.Literal("oauth2"),
12
+ authorizationUrl: Schema.String,
13
+ tokenUrl: Schema.String,
14
+ resource: Schema.optional(Schema.NullOr(Schema.String)),
15
+ scopes: Schema.Array(Schema.String),
16
+ supportsClientIdMetadataDocument: Schema.optional(Schema.Boolean)
17
+ });
18
+ var AuthenticationSchema = Schema.Union([OAuthAuthenticationSchema, ApiKeyAuthMethod]);
19
+ var OpenApiIntegrationConfigSchema = Schema.Struct({
20
+ /** Hex SHA-256 of the resolved spec text — the content address of the spec
21
+ * blob (`spec/<hash>` in the plugin blob store). */
22
+ specHash: Schema.optional(Schema.String),
23
+ /** Origin URL the spec was fetched from, when known. Enables refresh. */
24
+ specUrl: Schema.optional(Schema.String),
25
+ /** Optional base URL override. */
26
+ baseUrl: Schema.optional(Schema.String),
27
+ /** Static headers applied to every request (no secret material). */
28
+ headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),
29
+ /** Static query params applied to every request (no secret material). */
30
+ queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),
31
+ /** Adapter id used to fetch/convert the source format, when not plain OpenAPI. */
32
+ specFormat: Schema.optional(Schema.String),
33
+ /** Catalog family for grouped integration display. */
34
+ family: Schema.optional(Schema.String),
35
+ /** The auth methods a connection's value can be applied through. */
36
+ authenticationTemplate: Schema.optional(Schema.Array(AuthenticationSchema))
37
+ });
38
+ var decodeConfig = Schema.decodeUnknownOption(OpenApiIntegrationConfigSchema);
39
+ var decodeOpenApiIntegrationConfig = (value) => Option.getOrNull(decodeConfig(value));
40
+ var renderAuthTemplate = (template, values) => {
41
+ if (template.kind === "oauth2") {
42
+ return {
43
+ headers: { authorization: `Bearer ${values[TOKEN_VARIABLE] ?? ""}` },
44
+ queryParams: {}
45
+ };
46
+ }
47
+ return renderAuthPlacements(template.placements, values);
48
+ };
49
+ var requiredTemplateVariables = (template) => {
50
+ if (template.kind === "oauth2") return [TOKEN_VARIABLE];
51
+ return requiredPlacementVariables(template.placements);
52
+ };
53
+
54
+ // src/sdk/split.ts
55
+ import { JSON_SCHEMA, load as parseYamlDocument } from "js-yaml";
56
+ var SPACE = 32;
57
+ var HASH = 35;
58
+ var DASH = 45;
59
+ var SMALL_COMPONENT_SECTIONS = /* @__PURE__ */ new Set([
60
+ "parameters",
61
+ "requestBodies",
62
+ "responses",
63
+ "headers",
64
+ "links",
65
+ "securitySchemes"
66
+ ]);
67
+ var indentOf = (text, lineStart, lineEnd) => {
68
+ let i = lineStart;
69
+ while (i < lineEnd && text.charCodeAt(i) === SPACE) i++;
70
+ return i - lineStart;
71
+ };
72
+ var isBlankOrComment = (text, contentStart, lineEnd) => contentStart >= lineEnd || text.charCodeAt(contentStart) === HASH;
73
+ var opensBlockScalar = (line) => /:\s*[|>][+-]?\d*\s*(#.*)?$/.test(line) || /^\s*[|>][+-]?\d*\s*(#.*)?$/.test(line);
74
+ var lineAt = (text, from, limit) => {
75
+ if (from >= limit) return null;
76
+ let lineEnd = text.indexOf("\n", from);
77
+ if (lineEnd === -1 || lineEnd > limit) lineEnd = limit;
78
+ const indent = indentOf(text, from, lineEnd);
79
+ const contentStart = from + indent;
80
+ return {
81
+ lineStart: from,
82
+ lineEnd,
83
+ nextStart: lineEnd + 1,
84
+ indent,
85
+ contentStart
86
+ };
87
+ };
88
+ var keyLineStartsAtIndent = (text, start, end, indent) => {
89
+ const starts = [];
90
+ let blockScalarIndent = -1;
91
+ let pos = start;
92
+ while (pos < end) {
93
+ const line = lineAt(text, pos, end);
94
+ if (!line) break;
95
+ pos = line.nextStart;
96
+ if (isBlankOrComment(text, line.contentStart, line.lineEnd)) continue;
97
+ if (blockScalarIndent >= 0) {
98
+ if (line.indent > blockScalarIndent) continue;
99
+ blockScalarIndent = -1;
100
+ }
101
+ if (line.indent === indent && text.charCodeAt(line.contentStart) !== DASH) {
102
+ starts.push(line.lineStart);
103
+ }
104
+ if (line.indent <= indent && opensBlockScalar(text.slice(line.contentStart, line.lineEnd))) {
105
+ blockScalarIndent = line.indent;
106
+ }
107
+ }
108
+ return starts;
109
+ };
110
+ var rangesFromStarts = (starts, blockEnd) => starts.map((s, i) => ({ start: s, end: i + 1 < starts.length ? starts[i + 1] : blockEnd }));
111
+ var keyNameAt = (text, lineStart, lineEnd) => {
112
+ const indent = indentOf(text, lineStart, lineEnd);
113
+ const colon = text.indexOf(":", lineStart + indent);
114
+ const keyEnd = colon === -1 || colon > lineEnd ? lineEnd : colon;
115
+ return text.slice(lineStart + indent, keyEnd).trim();
116
+ };
117
+ var structuralSplit = (text) => {
118
+ const len = text.length;
119
+ const topStarts = [];
120
+ const topNames = [];
121
+ {
122
+ let blockScalarIndent = -1;
123
+ let pos = 0;
124
+ while (pos < len) {
125
+ const line = lineAt(text, pos, len);
126
+ if (!line) break;
127
+ pos = line.nextStart;
128
+ if (isBlankOrComment(text, line.contentStart, line.lineEnd)) continue;
129
+ if (blockScalarIndent >= 0) {
130
+ if (line.indent > blockScalarIndent) continue;
131
+ blockScalarIndent = -1;
132
+ }
133
+ if (line.indent === 0) {
134
+ topStarts.push(line.lineStart);
135
+ topNames.push(keyNameAt(text, line.lineStart, line.lineEnd));
136
+ }
137
+ if (opensBlockScalar(text.slice(line.contentStart, line.lineEnd))) {
138
+ blockScalarIndent = line.indent;
139
+ }
140
+ }
141
+ }
142
+ const topRanges = rangesFromStarts(topStarts, len);
143
+ const pathsIdx = topNames.indexOf("paths");
144
+ if (pathsIdx === -1) return null;
145
+ const componentsIdx = topNames.indexOf("components");
146
+ const headRanges = [];
147
+ for (let i = 0; i < topRanges.length; i++) {
148
+ if (i === pathsIdx || i === componentsIdx) continue;
149
+ headRanges.push(topRanges[i]);
150
+ }
151
+ const pathsRange = topRanges[pathsIdx];
152
+ const pathsBodyStart = lineAt(text, pathsRange.start, pathsRange.end)?.nextStart ?? pathsRange.end;
153
+ const pathItems = rangesFromStarts(
154
+ keyLineStartsAtIndent(text, pathsBodyStart, pathsRange.end, 2),
155
+ pathsRange.end
156
+ );
157
+ const schemas = [];
158
+ const smallComponentRanges = [];
159
+ if (componentsIdx !== -1) {
160
+ const componentsRange = topRanges[componentsIdx];
161
+ const componentsBodyStart = lineAt(text, componentsRange.start, componentsRange.end)?.nextStart ?? componentsRange.end;
162
+ const subStarts = keyLineStartsAtIndent(text, componentsBodyStart, componentsRange.end, 2);
163
+ const subRanges = rangesFromStarts(subStarts, componentsRange.end);
164
+ for (const range of subRanges) {
165
+ const name = keyNameAt(text, range.start, lineAt(text, range.start, range.end).lineEnd);
166
+ if (name === "schemas") {
167
+ const bodyStart = lineAt(text, range.start, range.end)?.nextStart ?? range.end;
168
+ for (const s of rangesFromStarts(
169
+ keyLineStartsAtIndent(text, bodyStart, range.end, 4),
170
+ range.end
171
+ )) {
172
+ schemas.push(s);
173
+ }
174
+ } else if (SMALL_COMPONENT_SECTIONS.has(name)) {
175
+ smallComponentRanges.push(range);
176
+ }
177
+ }
178
+ }
179
+ return { text, headRanges, pathItems, schemas, smallComponentRanges };
180
+ };
181
+ var dedent = (fragment, indent) => indent === 0 ? fragment : fragment.replace(new RegExp(`^ {1,${indent}}`, "gm"), "");
182
+ var parseYaml = (text) => parseYamlDocument(text, { json: true, schema: JSON_SCHEMA });
183
+ var parseEntry = (text, range, indent) => {
184
+ const parsed = parseYaml(dedent(text.slice(range.start, range.end), indent));
185
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
186
+ const entries = Object.entries(parsed);
187
+ if (entries.length !== 1) return null;
188
+ return entries[0];
189
+ };
190
+ var parseHead = (structure) => {
191
+ const text = structure.headRanges.map((r) => structure.text.slice(r.start, r.end)).join("");
192
+ const parsed = parseYaml(text);
193
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
194
+ };
195
+ var parseSmallComponents = (structure) => {
196
+ if (structure.smallComponentRanges.length === 0) return {};
197
+ const body = structure.smallComponentRanges.map((r) => structure.text.slice(r.start, r.end)).join("");
198
+ const parsed = parseYaml(`components:
199
+ ${body}`);
200
+ const components = parsed && typeof parsed === "object" ? parsed.components : null;
201
+ return components && typeof components === "object" ? components : {};
202
+ };
203
+ var isStreamableSpec = (text) => {
204
+ if (text.indexOf(" ") !== -1) return false;
205
+ if (/(^|\s)[&*][A-Za-z0-9_]/m.test(text)) return false;
206
+ if (/<<\s*:/.test(text)) return false;
207
+ return /^paths:/m.test(text);
208
+ };
209
+ var SCHEMA_REF_PREFIX = "#/components/schemas/";
210
+ var indexSchemas = (structure) => {
211
+ const index = /* @__PURE__ */ new Map();
212
+ for (const range of structure.schemas) {
213
+ const line = lineAt(structure.text, range.start, range.end);
214
+ if (!line) continue;
215
+ const name = keyNameAt(structure.text, range.start, line.lineEnd);
216
+ if (name) index.set(name, range);
217
+ }
218
+ return index;
219
+ };
220
+ var decodeSchemaRefName = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
221
+ var collectSchemaRefNames = (value, into) => {
222
+ if (typeof value === "string") {
223
+ if (value.startsWith(SCHEMA_REF_PREFIX)) {
224
+ const name = decodeSchemaRefName(value.slice(SCHEMA_REF_PREFIX.length));
225
+ if (name.length > 0) into.add(name);
226
+ }
227
+ return;
228
+ }
229
+ if (Array.isArray(value)) {
230
+ for (const item of value) collectSchemaRefNames(item, into);
231
+ return;
232
+ }
233
+ if (value !== null && typeof value === "object") {
234
+ for (const item of Object.values(value)) {
235
+ collectSchemaRefNames(item, into);
236
+ }
237
+ }
238
+ };
239
+ var collectReferencedSchemas = (structure, index, roots) => {
240
+ const result = {};
241
+ const wanted = /* @__PURE__ */ new Set();
242
+ for (const root of roots) collectSchemaRefNames(root, wanted);
243
+ const queue = [...wanted];
244
+ for (let i = 0; i < queue.length; i += 1) {
245
+ const name = queue[i];
246
+ if (Object.prototype.hasOwnProperty.call(result, name)) continue;
247
+ const range = index.get(name);
248
+ if (!range) continue;
249
+ const entry = parseEntry(structure.text, range, 4);
250
+ if (!entry) continue;
251
+ result[name] = entry[1];
252
+ const next = /* @__PURE__ */ new Set();
253
+ collectSchemaRefNames(entry[1], next);
254
+ for (const ref of next) {
255
+ if (!Object.prototype.hasOwnProperty.call(result, ref)) queue.push(ref);
256
+ }
257
+ }
258
+ return result;
259
+ };
260
+
261
+ export {
262
+ AuthenticationSchema,
263
+ OpenApiIntegrationConfigSchema,
264
+ decodeOpenApiIntegrationConfig,
265
+ renderAuthTemplate,
266
+ requiredTemplateVariables,
267
+ structuralSplit,
268
+ parseEntry,
269
+ parseHead,
270
+ parseSmallComponents,
271
+ isStreamableSpec,
272
+ indexSchemas,
273
+ collectReferencedSchemas
274
+ };
275
+ //# sourceMappingURL=chunk-R7TVM3XD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sdk/config.ts","../src/sdk/split.ts"],"sourcesContent":["import { Option, Schema } from \"effect\";\nimport {\n ApiKeyAuthMethod,\n TOKEN_VARIABLE,\n renderAuthPlacements,\n requiredPlacementVariables,\n} from \"@rafads/sdk/http-auth\";\n\nimport type { Authentication } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// OpenAPI integration config — the opaque blob stored on the catalog\n// `integration.config` column (D1). Core never parses it; the plugin writes it\n// at register time and reads it back in `resolveTools` / `invokeTool`.\n//\n// In v2 there are NO credential bindings, NO per-source secret slots, and NO\n// StoredSource credential config. The config carries only:\n// - the content hash of the spec blob and/or the source URL to (re)fetch\n// from,\n// - the optional base URL override,\n// - the auth templates a connection's value is rendered through.\n// The resolved spec text itself lives in the plugin blob store, keyed\n// `spec/<specHash>` — it's a build input for resolveTools/refresh, not data\n// any list/invoke path should pay to load. Rows that predate the blob store\n// (inline `spec` text) are rewritten before this schema sees them: cloud by\n// the out-of-band migrate-specs-to-blobs script, the libSQL hosts by the\n// boot-time ledger migration.\n// ---------------------------------------------------------------------------\n\nconst OAuthAuthenticationSchema = Schema.Struct({\n slug: Schema.String,\n kind: Schema.Literal(\"oauth2\"),\n authorizationUrl: Schema.String,\n tokenUrl: Schema.String,\n resource: Schema.optional(Schema.NullOr(Schema.String)),\n scopes: Schema.Array(Schema.String),\n supportsClientIdMetadataDocument: Schema.optional(Schema.Boolean),\n});\n\nexport const AuthenticationSchema = Schema.Union([OAuthAuthenticationSchema, ApiKeyAuthMethod]);\n\nexport const OpenApiIntegrationConfigSchema = Schema.Struct({\n /** Hex SHA-256 of the resolved spec text — the content address of the spec\n * blob (`spec/<hash>` in the plugin blob store). */\n specHash: Schema.optional(Schema.String),\n /** Origin URL the spec was fetched from, when known. Enables refresh. */\n specUrl: Schema.optional(Schema.String),\n /** Optional base URL override. */\n baseUrl: Schema.optional(Schema.String),\n /** Static headers applied to every request (no secret material). */\n headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n /** Static query params applied to every request (no secret material). */\n queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n /** Adapter id used to fetch/convert the source format, when not plain OpenAPI. */\n specFormat: Schema.optional(Schema.String),\n /** Catalog family for grouped integration display. */\n family: Schema.optional(Schema.String),\n /** The auth methods a connection's value can be applied through. */\n authenticationTemplate: Schema.optional(Schema.Array(AuthenticationSchema)),\n});\n\nexport type OpenApiIntegrationConfig = Omit<\n typeof OpenApiIntegrationConfigSchema.Type,\n \"authenticationTemplate\"\n> & {\n /** Branded over the schema's structural form so the template renderer can\n * treat `slug` as an `AuthTemplateSlug`. */\n readonly authenticationTemplate?: readonly Authentication[];\n};\n\nconst decodeConfig = Schema.decodeUnknownOption(OpenApiIntegrationConfigSchema);\n\n/** Decode the opaque integration config blob into the openapi shape.\n * Returns null when the blob is missing/incompatible. */\nexport const decodeOpenApiIntegrationConfig = (value: unknown): OpenApiIntegrationConfig | null =>\n Option.getOrNull(decodeConfig(value)) as OpenApiIntegrationConfig | null;\n\n// ---------------------------------------------------------------------------\n// Template rendering — \"auth state derived into the auth-template format\"\n// (D11). An apiKey method renders through the shared placements renderer; an\n// oauth template (no explicit placement) renders a bearer `authorization`\n// header from the `token` input (the access token).\n// ---------------------------------------------------------------------------\n\nexport interface RenderedAuth {\n readonly headers: Record<string, string>;\n readonly queryParams: Record<string, string>;\n}\n\n/** Render an auth template against a connection's resolved input `values`\n * (`variable → value`). Each placement substitutes from its own entry, so a\n * method with two distinct inputs (e.g. Datadog) fills each header from a\n * different value. */\nexport const renderAuthTemplate = (\n template: Authentication,\n values: Record<string, string | null>,\n): RenderedAuth => {\n if (template.kind === \"oauth2\") {\n return {\n headers: { authorization: `Bearer ${values[TOKEN_VARIABLE] ?? \"\"}` },\n queryParams: {},\n };\n }\n return renderAuthPlacements(template.placements, values);\n};\n\n/** The distinct input variables a template references — the inputs a connection\n * must supply. An oauth template needs `token`; an apiKey method needs every\n * variable across its placements. */\nexport const requiredTemplateVariables = (template: Authentication): readonly string[] => {\n if (template.kind === \"oauth2\") return [TOKEN_VARIABLE];\n return requiredPlacementVariables(template.placements);\n};\n","/**\n * Structural splitter for large OpenAPI documents written in clean block YAML.\n *\n * The whole-document parse of a 37MB spec (Microsoft Graph: 16.5k operations,\n * 8.2k schemas) builds a ~300MB JS tree that OOMs the 128MB Cloudflare Workers\n * isolate. This splitter avoids ever holding that tree: it scans the text once,\n * recording the byte range of each top-level key, each path-item (the indent-2\n * entries under `paths:`), and each schema (the indent-4 entries under\n * `components.schemas:`). The streaming compile then slices one item at a time,\n * de-indents it back to column 0, hands the isolated fragment to a real YAML\n * parser, and discards the result before moving on. Peak memory stays near the\n * size of the largest single item plus the raw text, not the parsed whole.\n *\n * This is not a YAML reimplementation: it extracts safe byte ranges from a\n * constrained document shape, then defers every actual parse to `js-yaml`. It\n * is only valid for the block-YAML profile `isStreamableSpec` accepts (2-space\n * block maps, top-level keys at column 0, no anchors/aliases/merge keys). Block\n * scalars (`|` / `>`) in descriptions are tracked so their indented content is\n * never mistaken for structure.\n */\n\nimport { JSON_SCHEMA, load as parseYamlDocument } from \"js-yaml\";\n\nexport interface ByteRange {\n readonly start: number;\n readonly end: number;\n}\n\nexport interface SpecStructure {\n /** Raw spec text. Every range below indexes into this string. */\n readonly text: string;\n /** Byte ranges of the top-level keys that are not `paths` / `components`\n * (openapi, info, servers, tags, security, ...). Concatenated and parsed as\n * one small document for the head (servers, info). */\n readonly headRanges: readonly ByteRange[];\n /** One range per path-item: the indent-2 entries under `paths:`. */\n readonly pathItems: readonly ByteRange[];\n /** One range per schema entry: the indent-4 entries under\n * `components.schemas:`. */\n readonly schemas: readonly ByteRange[];\n /** Ranges of the indent-2 `components` subkeys we keep whole because they are\n * small and may be `$ref`'d by a kept operation (parameters / requestBodies /\n * responses / headers / links / securitySchemes). Excludes the huge `schemas`\n * (streamed and pruned separately) and `examples` (never referenced by a\n * binding). */\n readonly smallComponentRanges: readonly ByteRange[];\n}\n\nconst SPACE = 32;\nconst HASH = 35;\nconst DASH = 45;\n\n/** `components` subkeys kept whole during a reduce: small, and a kept operation\n * may `$ref` into any of them. `schemas` is streamed/pruned separately and\n * `examples` is dropped (large, never referenced by a binding). */\nconst SMALL_COMPONENT_SECTIONS = new Set([\n \"parameters\",\n \"requestBodies\",\n \"responses\",\n \"headers\",\n \"links\",\n \"securitySchemes\",\n]);\n\n/** Count of leading spaces on the line starting at `lineStart`. */\nconst indentOf = (text: string, lineStart: number, lineEnd: number): number => {\n let i = lineStart;\n while (i < lineEnd && text.charCodeAt(i) === SPACE) i++;\n return i - lineStart;\n};\n\n/** True for a blank (whitespace-only) or comment line. */\nconst isBlankOrComment = (text: string, contentStart: number, lineEnd: number): boolean =>\n contentStart >= lineEnd || text.charCodeAt(contentStart) === HASH;\n\n/**\n * True when the line opens a block scalar (`key: |`, `key: >-`, etc.), meaning\n * every following more-indented line is literal content, not structure.\n */\nconst opensBlockScalar = (line: string): boolean =>\n /:\\s*[|>][+-]?\\d*\\s*(#.*)?$/.test(line) || /^\\s*[|>][+-]?\\d*\\s*(#.*)?$/.test(line);\n\ninterface LineCursor {\n readonly lineStart: number;\n readonly lineEnd: number;\n readonly nextStart: number;\n readonly indent: number;\n readonly contentStart: number;\n}\n\n/** Advance to the next significant line at offset `from`, returning null at EOF.\n * Blank lines, comments, and block-scalar content (lines indented deeper than\n * the scalar key, tracked by the caller) are still returned; the caller skips\n * them. */\nconst lineAt = (text: string, from: number, limit: number): LineCursor | null => {\n if (from >= limit) return null;\n let lineEnd = text.indexOf(\"\\n\", from);\n if (lineEnd === -1 || lineEnd > limit) lineEnd = limit;\n const indent = indentOf(text, from, lineEnd);\n const contentStart = from + indent;\n return {\n lineStart: from,\n lineEnd,\n nextStart: lineEnd + 1,\n indent,\n contentStart,\n };\n};\n\n/**\n * Find the start offset of every key line at exactly `indent` within\n * `[start, end)`, skipping blank/comment lines, deeper child lines, and\n * block-scalar content. Sequence items (`- `) at the target indent are not\n * treated as keys. Returns offsets in document order.\n */\nconst keyLineStartsAtIndent = (\n text: string,\n start: number,\n end: number,\n indent: number,\n): number[] => {\n const starts: number[] = [];\n let blockScalarIndent = -1;\n let pos = start;\n while (pos < end) {\n const line = lineAt(text, pos, end);\n if (!line) break;\n pos = line.nextStart;\n if (isBlankOrComment(text, line.contentStart, line.lineEnd)) continue;\n if (blockScalarIndent >= 0) {\n if (line.indent > blockScalarIndent) continue;\n blockScalarIndent = -1;\n }\n if (line.indent === indent && text.charCodeAt(line.contentStart) !== DASH) {\n starts.push(line.lineStart);\n }\n if (line.indent <= indent && opensBlockScalar(text.slice(line.contentStart, line.lineEnd))) {\n blockScalarIndent = line.indent;\n }\n }\n return starts;\n};\n\n/** Contiguous ranges from a sorted list of block-start offsets within\n * `[blockStart, blockEnd)`: each range runs to the next start (or blockEnd). */\nconst rangesFromStarts = (starts: readonly number[], blockEnd: number): ByteRange[] =>\n starts.map((s, i) => ({ start: s, end: i + 1 < starts.length ? starts[i + 1]! : blockEnd }));\n\n/** The simple (unquoted) key name on a key line, e.g. `paths`, `schemas`. */\nconst keyNameAt = (text: string, lineStart: number, lineEnd: number): string => {\n const indent = indentOf(text, lineStart, lineEnd);\n const colon = text.indexOf(\":\", lineStart + indent);\n const keyEnd = colon === -1 || colon > lineEnd ? lineEnd : colon;\n return text.slice(lineStart + indent, keyEnd).trim();\n};\n\n/**\n * Scan a document into its structural ranges. Pure and synchronous; never\n * parses. Returns null when the document does not present the expected shape\n * (no `paths:` block), so the caller can fall back to a whole-document parse.\n */\nexport const structuralSplit = (text: string): SpecStructure | null => {\n const len = text.length;\n\n // Top-level keys (column 0). Record each key's start + name, respecting\n // block scalars whose content could sit at column >= 1.\n const topStarts: number[] = [];\n const topNames: string[] = [];\n {\n let blockScalarIndent = -1;\n let pos = 0;\n while (pos < len) {\n const line = lineAt(text, pos, len);\n if (!line) break;\n pos = line.nextStart;\n if (isBlankOrComment(text, line.contentStart, line.lineEnd)) continue;\n if (blockScalarIndent >= 0) {\n if (line.indent > blockScalarIndent) continue;\n blockScalarIndent = -1;\n }\n if (line.indent === 0) {\n topStarts.push(line.lineStart);\n topNames.push(keyNameAt(text, line.lineStart, line.lineEnd));\n }\n if (opensBlockScalar(text.slice(line.contentStart, line.lineEnd))) {\n blockScalarIndent = line.indent;\n }\n }\n }\n\n const topRanges = rangesFromStarts(topStarts, len);\n const pathsIdx = topNames.indexOf(\"paths\");\n if (pathsIdx === -1) return null;\n const componentsIdx = topNames.indexOf(\"components\");\n\n const headRanges: ByteRange[] = [];\n for (let i = 0; i < topRanges.length; i++) {\n if (i === pathsIdx || i === componentsIdx) continue;\n headRanges.push(topRanges[i]!);\n }\n\n // Path-items: indent-2 keys inside the `paths:` block (after its key line).\n const pathsRange = topRanges[pathsIdx]!;\n const pathsBodyStart =\n lineAt(text, pathsRange.start, pathsRange.end)?.nextStart ?? pathsRange.end;\n const pathItems = rangesFromStarts(\n keyLineStartsAtIndent(text, pathsBodyStart, pathsRange.end, 2),\n pathsRange.end,\n );\n\n const schemas: ByteRange[] = [];\n const smallComponentRanges: ByteRange[] = [];\n if (componentsIdx !== -1) {\n const componentsRange = topRanges[componentsIdx]!;\n const componentsBodyStart =\n lineAt(text, componentsRange.start, componentsRange.end)?.nextStart ?? componentsRange.end;\n const subStarts = keyLineStartsAtIndent(text, componentsBodyStart, componentsRange.end, 2);\n const subRanges = rangesFromStarts(subStarts, componentsRange.end);\n for (const range of subRanges) {\n const name = keyNameAt(text, range.start, lineAt(text, range.start, range.end)!.lineEnd);\n if (name === \"schemas\") {\n const bodyStart = lineAt(text, range.start, range.end)?.nextStart ?? range.end;\n for (const s of rangesFromStarts(\n keyLineStartsAtIndent(text, bodyStart, range.end, 4),\n range.end,\n )) {\n schemas.push(s);\n }\n } else if (SMALL_COMPONENT_SECTIONS.has(name)) {\n smallComponentRanges.push(range);\n }\n // `examples` and any other subkey are intentionally dropped: no binding\n // field references them, and they can be large.\n }\n }\n\n return { text, headRanges, pathItems, schemas, smallComponentRanges };\n};\n\n/** Strip exactly `indent` leading spaces from every line of `fragment`, lifting\n * an indent-N block back to column 0 so it parses as a standalone document. */\nconst dedent = (fragment: string, indent: number): string =>\n indent === 0 ? fragment : fragment.replace(new RegExp(`^ {1,${indent}}`, \"gm\"), \"\");\n\nconst parseYaml = (text: string): unknown =>\n parseYamlDocument(text, { json: true, schema: JSON_SCHEMA });\n\n/**\n * Parse a single indent-N entry range (a path-item or a schema) in isolation.\n * Returns `[name, value]` where `name` is the entry's key and `value` its\n * parsed body, or null when the fragment does not parse to a single-key map.\n */\nexport const parseEntry = (\n text: string,\n range: ByteRange,\n indent: number,\n): readonly [string, unknown] | null => {\n const parsed = parseYaml(dedent(text.slice(range.start, range.end), indent));\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n const entries = Object.entries(parsed as Record<string, unknown>);\n if (entries.length !== 1) return null;\n return entries[0]!;\n};\n\n/** Parse the concatenation of the head ranges into the document head (openapi,\n * info, servers, tags). Small; safe to materialize whole. */\nexport const parseHead = (structure: SpecStructure): Record<string, unknown> => {\n const text = structure.headRanges.map((r) => structure.text.slice(r.start, r.end)).join(\"\");\n const parsed = parseYaml(text);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n};\n\n/** Parse the small component subkeys (parameters / requestBodies / responses)\n * into a `components`-shaped object for `$ref` resolution. */\nexport const parseSmallComponents = (structure: SpecStructure): Record<string, unknown> => {\n if (structure.smallComponentRanges.length === 0) return {};\n const body = structure.smallComponentRanges\n .map((r) => structure.text.slice(r.start, r.end))\n .join(\"\");\n const parsed = parseYaml(`components:\\n${body}`);\n const components =\n parsed && typeof parsed === \"object\" ? (parsed as Record<string, unknown>).components : null;\n return components && typeof components === \"object\"\n ? (components as Record<string, unknown>)\n : {};\n};\n\n/**\n * Accept only the block-YAML profile the splitter can safely slice: no tabs, no\n * anchors/aliases, no merge keys, and a `paths:` block present. Block scalars\n * are allowed (tracked during the scan). Conservative by design: a false\n * negative just routes a spec through the whole-document parse.\n */\nexport const isStreamableSpec = (text: string): boolean => {\n if (text.indexOf(\"\\t\") !== -1) return false;\n // Anchors/aliases/merge keys: cheap substring rejects before structural work.\n if (/(^|\\s)[&*][A-Za-z0-9_]/m.test(text)) return false;\n if (/<<\\s*:/.test(text)) return false;\n return /^paths:/m.test(text);\n};\n\nconst SCHEMA_REF_PREFIX = \"#/components/schemas/\";\n\n/** Map each `components.schemas` entry name to its byte range, reading only the\n * key line (never parsing the schema body). The schema name is the raw YAML\n * key, which matches the trailing segment of a `#/components/schemas/<name>`\n * reference. */\nexport const indexSchemas = (structure: SpecStructure): ReadonlyMap<string, ByteRange> => {\n const index = new Map<string, ByteRange>();\n for (const range of structure.schemas) {\n const line = lineAt(structure.text, range.start, range.end);\n if (!line) continue;\n const name = keyNameAt(structure.text, range.start, line.lineEnd);\n if (name) index.set(name, range);\n }\n return index;\n};\n\n/** Decode a `#/components/schemas/<segment>` name segment. Schema names are raw\n * YAML keys, so only JSON-pointer tilde escaping can appear (no `%`-encoding\n * in the wild specs we target); decode `~1`/`~0` and leave the rest verbatim. */\nconst decodeSchemaRefName = (segment: string): string =>\n segment.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n\n/** Collect the names of every `#/components/schemas/X` reference reachable in\n * `value`, without resolving them. */\nconst collectSchemaRefNames = (value: unknown, into: Set<string>): void => {\n if (typeof value === \"string\") {\n if (value.startsWith(SCHEMA_REF_PREFIX)) {\n const name = decodeSchemaRefName(value.slice(SCHEMA_REF_PREFIX.length));\n if (name.length > 0) into.add(name);\n }\n return;\n }\n if (Array.isArray(value)) {\n for (const item of value) collectSchemaRefNames(item, into);\n return;\n }\n if (value !== null && typeof value === \"object\") {\n for (const item of Object.values(value as Record<string, unknown>)) {\n collectSchemaRefNames(item, into);\n }\n }\n};\n\n/**\n * Resolve the transitive closure of schemas referenced by `roots`, parsing each\n * referenced schema once from its byte range (BFS over `$ref`s). Schemas not\n * reachable from `roots` are never parsed, so peak memory tracks the kept\n * subset rather than the full `components.schemas` map.\n */\nexport const collectReferencedSchemas = (\n structure: SpecStructure,\n index: ReadonlyMap<string, ByteRange>,\n roots: readonly unknown[],\n): Record<string, unknown> => {\n const result: Record<string, unknown> = {};\n const wanted = new Set<string>();\n for (const root of roots) collectSchemaRefNames(root, wanted);\n\n const queue = [...wanted];\n for (let i = 0; i < queue.length; i += 1) {\n const name = queue[i]!;\n if (Object.prototype.hasOwnProperty.call(result, name)) continue;\n const range = index.get(name);\n if (!range) continue;\n const entry = parseEntry(structure.text, range, 4);\n if (!entry) continue;\n result[name] = entry[1];\n const next = new Set<string>();\n collectSchemaRefNames(entry[1], next);\n for (const ref of next) {\n if (!Object.prototype.hasOwnProperty.call(result, ref)) queue.push(ref);\n }\n }\n return result;\n};\n\n/** A path-item filter for the streaming compile: given a parsed path-item,\n * return the (possibly trimmed) value to keep, or null to drop the path\n * entirely. Applied per path-item by `streamOperationBindingsFromStructure`. */\nexport type KeepPathItem = (\n path: string,\n pathItem: Record<string, unknown>,\n) => Record<string, unknown> | null;\n"],"mappings":";AAAA,SAAS,QAAQ,cAAc;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAuBP,IAAM,4BAA4B,OAAO,OAAO;AAAA,EAC9C,MAAM,OAAO;AAAA,EACb,MAAM,OAAO,QAAQ,QAAQ;AAAA,EAC7B,kBAAkB,OAAO;AAAA,EACzB,UAAU,OAAO;AAAA,EACjB,UAAU,OAAO,SAAS,OAAO,OAAO,OAAO,MAAM,CAAC;AAAA,EACtD,QAAQ,OAAO,MAAM,OAAO,MAAM;AAAA,EAClC,kCAAkC,OAAO,SAAS,OAAO,OAAO;AAClE,CAAC;AAEM,IAAM,uBAAuB,OAAO,MAAM,CAAC,2BAA2B,gBAAgB,CAAC;AAEvF,IAAM,iCAAiC,OAAO,OAAO;AAAA;AAAA;AAAA,EAG1D,UAAU,OAAO,SAAS,OAAO,MAAM;AAAA;AAAA,EAEvC,SAAS,OAAO,SAAS,OAAO,MAAM;AAAA;AAAA,EAEtC,SAAS,OAAO,SAAS,OAAO,MAAM;AAAA;AAAA,EAEtC,SAAS,OAAO,SAAS,OAAO,OAAO,OAAO,QAAQ,OAAO,MAAM,CAAC;AAAA;AAAA,EAEpE,aAAa,OAAO,SAAS,OAAO,OAAO,OAAO,QAAQ,OAAO,MAAM,CAAC;AAAA;AAAA,EAExE,YAAY,OAAO,SAAS,OAAO,MAAM;AAAA;AAAA,EAEzC,QAAQ,OAAO,SAAS,OAAO,MAAM;AAAA;AAAA,EAErC,wBAAwB,OAAO,SAAS,OAAO,MAAM,oBAAoB,CAAC;AAC5E,CAAC;AAWD,IAAM,eAAe,OAAO,oBAAoB,8BAA8B;AAIvE,IAAM,iCAAiC,CAAC,UAC7C,OAAO,UAAU,aAAa,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tE,UAAI,KAAK,SAAS,EAAG,MAAK,IAAI,IAAI;AAAA,IACpC;AACA;AAAA,EACF;AACA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,eAAW,QAAQ,MAAO,uBAAsB,MAAM,IAAI;AAC1D;AAAA,EACF;AACA,MAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;AAC/C,eAAW,QAAQ,OAAO,OAAO,KAAgC,GAAG;AAClE,4BAAsB,MAAM,IAAI;AAAA,IAClC;AAAA,EACF;AACF;AAQO,IAAM,2BAA2B,CACtC,WACA,OACA,UAC4B;AAC5B,QAAM,SAAkC,CAAC;AACzC,QAAM,SAAS,oBAAI,IAAY;AAC/B,aAAW,QAAQ,MAAO,uBAAsB,MAAM,MAAM;AAE5D,QAAM,QAAQ,CAAC,GAAG,MAAM;AACxB,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,GAAG;AACxC,UAAM,OAAO,MAAM,CAAC;AACpB,QAAI,OAAO,UAAU,eAAe,KAAK,QAAQ,IAAI,EAAG;AACxD,UAAM,QAAQ,MAAM,IAAI,IAAI;AAC5B,QAAI,CAAC,MAAO;AACZ,UAAM,QAAQ,WAAW,UAAU,MAAM,OAAO,CAAC;AACjD,QAAI,CAAC,MAAO;AACZ,WAAO,IAAI,IAAI,MAAM,CAAC;AACtB,UAAM,OAAO,oBAAI,IAAY;AAC7B,0BAAsB,MAAM,CAAC,GAAG,IAAI;AACpC,eAAW,OAAO,MAAM;AACtB,UAAI,CAAC,OAAO,UAAU,eAAe,KAAK,QAAQ,GAAG,EAAG,OAAM,KAAK,GAAG;AAAA,IACxE;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
package/dist/client.js ADDED
@@ -0,0 +1,38 @@
1
+ import {
2
+ openApiPresets
3
+ } from "./chunk-CURJJXB3.js";
4
+
5
+ // src/react/plugin-client.tsx
6
+ import { defineClientPlugin } from "@rafads/sdk/client";
7
+
8
+ // src/react/integration-plugin.ts
9
+ import { lazy } from "react";
10
+ var importAdd = () => import("./AddOpenApiIntegration-JPAEXE56.js");
11
+ var importEditSheet = () => import("./UpdateSpecSection-KUSNI44Q.js");
12
+ var importAccounts = () => import("./OpenApiAccountsPanel-GZFDSTAU.js");
13
+ var createOpenApiIntegrationPlugin = (config) => ({
14
+ key: "openapi",
15
+ label: "OpenAPI",
16
+ add: lazy(importAdd),
17
+ editSheet: lazy(importEditSheet),
18
+ accounts: lazy(importAccounts),
19
+ presets: [...openApiPresets, ...config?.presets ?? []],
20
+ preload: () => {
21
+ void importAdd();
22
+ void importEditSheet();
23
+ void importAccounts();
24
+ }
25
+ });
26
+ var openApiIntegrationPlugin = createOpenApiIntegrationPlugin();
27
+
28
+ // src/react/plugin-client.tsx
29
+ function createOpenApiClientPlugin(config) {
30
+ return defineClientPlugin({
31
+ id: "openapi",
32
+ integrationPlugin: createOpenApiIntegrationPlugin(config)
33
+ });
34
+ }
35
+ export {
36
+ createOpenApiClientPlugin as default
37
+ };
38
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/react/plugin-client.tsx","../src/react/integration-plugin.ts"],"sourcesContent":["// ---------------------------------------------------------------------------\n// @rafads/plugin-openapi/client — `defineClientPlugin` entry.\n//\n// Aggregates the openapi plugin's frontend contributions into a single\n// declarative spec. The host's Vite plugin reads this via\n// `virtual:executor/plugins-client`, so the host's integrations page derives\n// the openapi entry from here without a direct `*/react` import.\n//\n// The richer add/edit/summary components still live in `./react`; this\n// module just imports them and bundles them into the spec.\n// ---------------------------------------------------------------------------\n\nimport { defineClientPlugin } from \"@rafads/sdk/client\";\n\nimport { createOpenApiIntegrationPlugin, type OpenApiClientConfig } from \"./integration-plugin\";\n\nexport default function createOpenApiClientPlugin(config?: OpenApiClientConfig) {\n return defineClientPlugin({\n id: \"openapi\" as const,\n integrationPlugin: createOpenApiIntegrationPlugin(config),\n });\n}\n","import { lazy } from \"react\";\nimport type { IntegrationPlugin, IntegrationPreset } from \"@rafads/sdk/client\";\nimport { openApiPresets } from \"../sdk/presets\";\n\nconst importAdd = () => import(\"./AddOpenApiIntegration\");\nconst importEditSheet = () => import(\"./UpdateSpecSection\");\nconst importAccounts = () => import(\"./OpenApiAccountsPanel\");\n\nexport interface OpenApiClientConfig {\n readonly presets?: readonly IntegrationPreset[];\n}\n\nexport const createOpenApiIntegrationPlugin = (\n config?: OpenApiClientConfig,\n): IntegrationPlugin => ({\n key: \"openapi\",\n label: \"OpenAPI\",\n add: lazy(importAdd),\n editSheet: lazy(importEditSheet),\n accounts: lazy(importAccounts),\n presets: [...openApiPresets, ...(config?.presets ?? [])],\n preload: () => {\n void importAdd();\n void importEditSheet();\n void importAccounts();\n },\n});\n\nexport const openApiIntegrationPlugin: IntegrationPlugin = createOpenApiIntegrationPlugin();\n"],"mappings":";;;;;AAYA,SAAS,0BAA0B;;;ACZnC,SAAS,YAAY;AAIrB,IAAM,YAAY,MAAM,OAAO,qCAAyB;AACxD,IAAM,kBAAkB,MAAM,OAAO,iCAAqB;AAC1D,IAAM,iBAAiB,MAAM,OAAO,oCAAwB;AAMrD,IAAM,iCAAiC,CAC5C,YACuB;AAAA,EACvB,KAAK;AAAA,EACL,OAAO;AAAA,EACP,KAAK,KAAK,SAAS;AAAA,EACnB,WAAW,KAAK,eAAe;AAAA,EAC/B,UAAU,KAAK,cAAc;AAAA,EAC7B,SAAS,CAAC,GAAG,gBAAgB,GAAI,QAAQ,WAAW,CAAC,CAAE;AAAA,EACvD,SAAS,MAAM;AACb,SAAK,UAAU;AACf,SAAK,gBAAgB;AACrB,SAAK,eAAe;AAAA,EACtB;AACF;AAEO,IAAM,2BAA8C,+BAA+B;;;ADZ3E,SAAR,0BAA2C,QAA8B;AAC9E,SAAO,mBAAmB;AAAA,IACxB,IAAI;AAAA,IACJ,mBAAmB,+BAA+B,MAAM;AAAA,EAC1D,CAAC;AACH;","names":[]}