@foxnose/sdk 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/auth/anonymous.ts","../src/auth/jwt.ts","../src/auth/secure.ts","../src/errors.ts","../src/auth/simple.ts","../src/config.ts","../src/http.ts","../src/_deprecation.ts","../src/management/models.ts","../src/management/paths.ts","../src/management/client.ts","../src/flux/models.ts","../src/flux/client.ts"],"sourcesContent":["// Auth\nexport {\n AnonymousAuth,\n JWTAuth,\n SecureKeyAuth,\n SimpleKeyAuth,\n StaticTokenProvider,\n} from './auth/index.js';\nexport type { AuthStrategy, RequestData, TokenProvider } from './auth/index.js';\n\n// Config\nexport type { FoxnoseConfig, RetryConfig } from './config.js';\nexport { createConfig, DEFAULT_RETRY_CONFIG, DEFAULT_USER_AGENT, SDK_VERSION } from './config.js';\n\n// Errors\nexport {\n FoxnoseError,\n FoxnoseAPIError,\n FoxnoseAuthError,\n FoxnoseTransportError,\n SpendCapExceededError,\n PlanExhaustedError,\n FilesQuotaExceededError,\n FilesQuotaUnavailableError,\n PlanLimitExceededError,\n RateLimitExceededError,\n CollectionNotWritableError,\n ExternalIdConflictError,\n ContentValidationFailedError,\n UpstreamError,\n} from './errors.js';\n\n// HTTP Transport\nexport { HttpTransport } from './http.js';\n\n// Management Client\nexport { ManagementClient } from './management/index.js';\nexport type {\n ApiFolderOptions,\n ApiFolderRouteDescriptionOptions,\n ManagementClientOptions,\n} from './management/index.js';\n\n// Flux Client\nexport { FluxClient } from './flux/index.js';\nexport { SearchMode, buildSearchBody } from './flux/index.js';\nexport type {\n FluxClientOptions,\n VectorSearchOptions,\n VectorFieldSearchOptions,\n HybridSearchOptions,\n BoostedSearchOptions,\n} from './flux/index.js';\nexport type {\n VectorSearch,\n VectorFieldSearch,\n VectorBoostConfig,\n HybridConfig,\n SearchRequest,\n UploadFileStatus,\n UploadSignature,\n UploadStatus,\n} from './flux/index.js';\n\n// Models\nexport type {\n PaginatedResponse,\n ResourceSummary,\n ResourceList,\n RevisionSummary,\n RevisionList,\n FolderSummary,\n FolderList,\n CollectionSummary,\n CollectionList,\n ComponentSummary,\n ComponentList,\n SchemaVersionSummary,\n SchemaVersionList,\n FieldSummary,\n FieldList,\n NestedFieldMeta,\n SyncComponentSkippedItem,\n SyncComponentResponse,\n ComponentSyncConflictDetail,\n RegionInfo,\n ProjectSummary,\n ProjectList,\n UserReference,\n EnvironmentSummary,\n EnvironmentList,\n LocaleSummary,\n LocaleList,\n ManagementAPIKeySummary,\n ManagementAPIKeyList,\n FluxAPIKeyBearerToken,\n FluxAPIKeySummary,\n FluxAPIKeyList,\n ManagementRoleSummary,\n ManagementRoleList,\n RolePermission,\n RolePermissionObject,\n FluxRoleSummary,\n FluxRoleList,\n APIInfo,\n APIList,\n APIFolderSummary,\n APIFolderList,\n APICollectionSummary,\n APICollectionList,\n FlatRoute,\n FlatRouteSummary,\n OrganizationOwner,\n OrganizationSummary,\n OrganizationList,\n PlanLimits,\n PlanDetails,\n OrganizationPlanStatus,\n OrganizationUsage,\n UnitsUsage,\n StorageUsage,\n UsageMetric,\n UsageBreakdown,\n CurrentUsage,\n BatchUpsertItem,\n BatchItemError,\n BatchUpsertResult,\n FileKind,\n UploadLinkCreateRequest,\n UploadLinkCreator,\n UploadFileProgress,\n UploadLinkFile,\n UploadLinkSession,\n UploadLink,\n UploadLinkList,\n UploadLinkCreated,\n FileAnalysis,\n FileCheck,\n FileFinding,\n FileCopyAvailability,\n FileActiveContent,\n FileDownloadOptions,\n FileRecordView,\n FileDownload,\n FilePageRedaction,\n FilePageTable,\n FilePageDetail,\n FileTombstone,\n FileTombstoneList,\n FileFindingsSummary,\n FileReviewItem,\n FileReviewQueue,\n FilesPolicyBody,\n FilesPolicy,\n FileSummary,\n FileRecordOwner,\n FileInfo,\n FileEvidencePart,\n FileTextEvidence,\n FileTrust,\n FilePagePii,\n FileFindingGroup,\n FilePageFinding,\n EnvironmentAccess,\n ContentTypeAccess,\n MyPermissions,\n FileOrigin,\n FileOriginActor,\n FileOriginLink,\n // Ref types\n FolderRef,\n CollectionRef,\n ResourceRef,\n RevisionRef,\n ComponentRef,\n SchemaVersionRef,\n OrgRef,\n ProjectRef,\n EnvironmentRef,\n ManagementRoleRef,\n FluxRoleRef,\n ManagementAPIKeyRef,\n FluxAPIKeyRef,\n APIRef,\n} from './management/models.js';\n\nexport { resolveKey, nestedFieldMeta, parseFindingEvidence } from './management/models.js';\n\nexport { SDK_VERSION as VERSION } from './config.js';\n","import type { AuthStrategy, RequestData } from './types.js';\n\n/**\n * Placeholder auth strategy when no credentials are required.\n */\nexport class AnonymousAuth implements AuthStrategy {\n buildHeaders(_request: RequestData): Record<string, string> {\n return {};\n }\n}\n","import type { AuthStrategy, RequestData, TokenProvider } from './types.js';\n\n/**\n * Simple token provider that always returns the same token.\n */\nexport class StaticTokenProvider implements TokenProvider {\n constructor(private readonly token: string) {}\n\n getToken(): string {\n return this.token;\n }\n}\n\n/**\n * Adds `Authorization: Bearer` headers using a token provider.\n */\nexport class JWTAuth implements AuthStrategy {\n private readonly provider: TokenProvider;\n private readonly scheme: string;\n\n constructor(provider: TokenProvider, options?: { scheme?: string }) {\n this.provider = provider;\n this.scheme = options?.scheme ?? 'Bearer';\n }\n\n buildHeaders(_request: RequestData): Record<string, string> {\n const token = this.provider.getToken();\n if (!token) {\n throw new Error('Token provider returned an empty token');\n }\n return { Authorization: `${this.scheme} ${token}` };\n }\n\n /**\n * Convenience constructor for scripts with manual token management.\n */\n static fromStaticToken(token: string, options?: { scheme?: string }): JWTAuth {\n return new JWTAuth(new StaticTokenProvider(token), options);\n }\n}\n","import { createHash, createSign } from 'node:crypto';\n\nimport { FoxnoseAuthError } from '../errors.js';\nimport type { AuthStrategy, RequestData } from './types.js';\n\ntype Clock = () => Date;\n\n/**\n * Implements the `Secure <public>:<signature>` header used by both APIs.\n *\n * The signature uses ECDSA P-256 over `<path>|<sha256(body)>|<timestamp>`.\n */\nexport class SecureKeyAuth implements AuthStrategy {\n private readonly publicKey: string;\n private readonly privateKeyPem: string;\n private readonly clock: Clock;\n\n constructor(publicKey: string, privateKey: string, options?: { clock?: Clock }) {\n if (!publicKey || !privateKey) {\n throw new Error('publicKey and privateKey are required');\n }\n this.publicKey = publicKey;\n this.clock = options?.clock ?? (() => new Date());\n\n try {\n // The private key comes as base64-encoded DER. Convert to PEM for node:crypto.\n const derB64 = privateKey;\n this.privateKeyPem =\n `-----BEGIN EC PRIVATE KEY-----\\n` +\n derB64.match(/.{1,64}/g)!.join('\\n') +\n `\\n-----END EC PRIVATE KEY-----`;\n } catch (err) {\n throw new FoxnoseAuthError(`Failed to load private key: ${err}`);\n }\n }\n\n buildHeaders(request: RequestData): Record<string, string> {\n const body = request.body ?? new Uint8Array(0);\n const now = this.clock();\n const timestamp = now.toISOString().replace(/\\.\\d{3}Z$/, 'Z');\n\n let path: string;\n try {\n const parsed = new URL(request.url);\n // Query parameters are excluded from the signature payload to match\n // server-side verification, which signs only the request path.\n path = parsed.pathname || '/';\n } catch {\n path = request.path || '/';\n }\n\n const bodyHash = createHash('sha256').update(body).digest('hex');\n const dataToSign = `${path}|${bodyHash}|${timestamp}`;\n\n const signer = createSign('SHA256');\n signer.update(dataToSign);\n signer.end();\n\n const signatureBuffer = signer.sign({\n key: this.privateKeyPem,\n dsaEncoding: 'der',\n });\n const signatureB64 = signatureBuffer.toString('base64');\n\n return {\n Authorization: `Secure ${this.publicKey}:${signatureB64}`,\n Date: timestamp,\n };\n }\n}\n","/**\n * Base class for all SDK errors.\n */\nexport class FoxnoseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'FoxnoseError';\n }\n}\n\n/**\n * Raised when the API responds with an error status (4xx/5xx).\n */\nexport class FoxnoseAPIError extends FoxnoseError {\n readonly statusCode: number;\n readonly errorCode?: string;\n readonly detail?: unknown;\n readonly responseHeaders?: Record<string, string>;\n readonly responseBody?: unknown;\n\n constructor(options: {\n message: string;\n statusCode: number;\n errorCode?: string;\n detail?: unknown;\n responseHeaders?: Record<string, string>;\n responseBody?: unknown;\n }) {\n const code = options.errorCode ? `, error_code=${options.errorCode}` : '';\n super(`${options.message} (status=${options.statusCode}${code})`);\n this.name = 'FoxnoseAPIError';\n this.statusCode = options.statusCode;\n this.errorCode = options.errorCode;\n this.detail = options.detail;\n this.responseHeaders = options.responseHeaders;\n this.responseBody = options.responseBody;\n }\n}\n\n/**\n * Options shared by every {@link FoxnoseAPIError} subclass.\n */\ntype APIErrorOptions = {\n message: string;\n statusCode: number;\n errorCode?: string;\n detail?: unknown;\n responseHeaders?: Record<string, string>;\n responseBody?: unknown;\n};\n\n/**\n * Raised on HTTP 402 when a configured spend cap has been reached.\n */\nexport class SpendCapExceededError extends FoxnoseAPIError {\n /** Spend cap in USD, or null when unset on the server side. */\n readonly capUsd?: number | null;\n /** ISO timestamp when the current billing cycle resets. */\n readonly cycleResetsAt?: string;\n /** URL where the spend cap can be raised. */\n readonly raiseCapUrl?: string;\n\n constructor(\n options: APIErrorOptions & {\n capUsd?: number | null;\n cycleResetsAt?: string;\n raiseCapUrl?: string;\n },\n ) {\n super(options);\n this.name = 'SpendCapExceededError';\n this.capUsd = options.capUsd;\n this.cycleResetsAt = options.cycleResetsAt;\n this.raiseCapUrl = options.raiseCapUrl;\n }\n}\n\n/**\n * Raised on HTTP 402 when the plan allowance for a usage axis is exhausted.\n */\nexport class PlanExhaustedError extends FoxnoseAPIError {\n /** Usage axis that was exhausted (e.g. retrievals, writes, data_storage, vector_storage). */\n readonly axis?: string;\n /** ISO timestamp when the usage window resets. */\n readonly windowResetsAt?: string;\n /** URL where the plan can be upgraded. */\n readonly upgradeUrl?: string;\n\n constructor(\n options: APIErrorOptions & {\n axis?: string;\n windowResetsAt?: string;\n upgradeUrl?: string;\n },\n ) {\n super(options);\n this.name = 'PlanExhaustedError';\n this.axis = options.axis;\n this.windowResetsAt = options.windowResetsAt;\n this.upgradeUrl = options.upgradeUrl;\n }\n}\n\n/**\n * Raised on HTTP 402 `files_quota_exceeded` when no file processing units are left.\n *\n * `reason` says what ran out, and the matching link is `upgradeUrl` or `raiseCapUrl`.\n * A refusal relayed by Flux carries the code only, so these fields are undefined there.\n */\nexport class FilesQuotaExceededError extends FoxnoseAPIError {\n readonly axis?: string;\n readonly reason?: string;\n readonly usedUnits?: number;\n readonly includedUnits?: number | null;\n readonly capUsd?: number | null;\n readonly windowResetsAt?: string | null;\n readonly upgradeUrl?: string;\n readonly raiseCapUrl?: string;\n\n constructor(\n options: APIErrorOptions & {\n axis?: string;\n reason?: string;\n usedUnits?: number;\n includedUnits?: number | null;\n capUsd?: number | null;\n windowResetsAt?: string | null;\n upgradeUrl?: string;\n raiseCapUrl?: string;\n },\n ) {\n super(options);\n this.name = 'FilesQuotaExceededError';\n this.axis = options.axis;\n this.reason = options.reason;\n this.usedUnits = options.usedUnits;\n this.includedUnits = options.includedUnits;\n this.capUsd = options.capUsd;\n this.windowResetsAt = options.windowResetsAt;\n this.upgradeUrl = options.upgradeUrl;\n this.raiseCapUrl = options.raiseCapUrl;\n }\n}\n\n/**\n * Raised on HTTP 503 `files_quota_unavailable` when the file processing quota could\n * not be read, so nothing was started. Retry after `retryAfter` seconds.\n */\nexport class FilesQuotaUnavailableError extends FoxnoseAPIError {\n readonly retryAfter?: number;\n\n constructor(options: APIErrorOptions & { retryAfter?: number }) {\n super(options);\n this.name = 'FilesQuotaUnavailableError';\n this.retryAfter = options.retryAfter;\n }\n}\n\n/**\n * Raised on HTTP 403 when a plan entity limit is exceeded.\n */\nexport class PlanLimitExceededError extends FoxnoseAPIError {\n /** Entity whose limit was exceeded (e.g. collections, environments, api_keys). */\n readonly entity?: string;\n /** Maximum allowed by the current plan. */\n readonly limit?: number;\n /** Current count that triggered the error. */\n readonly current?: number;\n /** URL where the plan can be upgraded, if provided. */\n readonly upgradeUrl?: string;\n\n constructor(\n options: APIErrorOptions & {\n entity?: string;\n limit?: number;\n current?: number;\n upgradeUrl?: string;\n },\n ) {\n super(options);\n this.name = 'PlanLimitExceededError';\n this.entity = options.entity;\n this.limit = options.limit;\n this.current = options.current;\n this.upgradeUrl = options.upgradeUrl;\n }\n}\n\n/**\n * Raised on HTTP 429 when the request rate limit is exceeded.\n */\nexport class RateLimitExceededError extends FoxnoseAPIError {\n /** Seconds to wait before retrying, from the Retry-After header. */\n readonly retryAfter?: number;\n\n constructor(options: APIErrorOptions & { retryAfter?: number }) {\n super(options);\n this.name = 'RateLimitExceededError';\n this.retryAfter = options.retryAfter;\n }\n}\n\n/**\n * Raised on HTTP 403 when the target collection does not accept writes (or the\n * key in use lacks write access).\n */\nexport class CollectionNotWritableError extends FoxnoseAPIError {\n constructor(options: APIErrorOptions) {\n super(options);\n this.name = 'CollectionNotWritableError';\n }\n}\n\n/**\n * Raised on HTTP 409 when the supplied `key` already identifies a resource.\n */\nexport class ExternalIdConflictError extends FoxnoseAPIError {\n constructor(options: APIErrorOptions) {\n super(options);\n this.name = 'ExternalIdConflictError';\n }\n}\n\n/**\n * Raised on HTTP 422 when submitted `data` fails the collection's schema.\n *\n * Two server error codes mean this, and both map here:\n * `content_validation_failed` and `data_validation_error`. The latter is what\n * a Flux resource write returns, so leaving it unmapped meant the most common\n * way to hit a schema violation raised a bare {@link FoxnoseAPIError}, and\n * `instanceof ContentValidationFailedError` never matched it.\n */\nexport class ContentValidationFailedError extends FoxnoseAPIError {\n /** Individual validation problems; each includes a `json_path`. */\n readonly errors: unknown[];\n /** True when the server capped a very large error list. */\n readonly errorsTruncated: boolean;\n\n constructor(options: APIErrorOptions & { errors?: unknown[]; errorsTruncated?: boolean }) {\n super(options);\n this.name = 'ContentValidationFailedError';\n this.errors = options.errors ?? [];\n this.errorsTruncated = options.errorsTruncated ?? false;\n }\n}\n\n/**\n * Raised on HTTP 502 when a write could not be confirmed. The write may or may\n * not have been applied — re-read the resource with a GET before retrying.\n */\nexport class UpstreamError extends FoxnoseAPIError {\n constructor(options: APIErrorOptions) {\n super(options);\n this.name = 'UpstreamError';\n }\n}\n\n/** Returns true only for a plain (non-null, non-array) object. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Case-insensitive header lookup over a header map. */\nfunction getHeader(headers: Record<string, string> | undefined, name: string): string | undefined {\n if (!headers) {\n return undefined;\n }\n const target = name.toLowerCase();\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === target) {\n return value;\n }\n }\n return undefined;\n}\n\n/** `Retry-After` in seconds, or undefined when absent or not a number. */\nfunction retryAfterSeconds(headers: Record<string, string> | undefined): number | undefined {\n const raw = getHeader(headers, 'Retry-After');\n const parsed = raw !== undefined ? Number(raw) : NaN;\n return Number.isNaN(parsed) ? undefined : parsed;\n}\n\n/**\n * Builds the most specific {@link FoxnoseAPIError} subclass for a response,\n * mapping known (statusCode, errorCode) pairs to typed exceptions. Never\n * throws while parsing; malformed payloads fall through to the base class.\n */\n/**\n * Codes that both describe data rejected by the collection schema.\n *\n * The resource-write path raises `RevisionValidationError`\n * (`data_validation_error`); other paths raise the content variant. They carry\n * the same detail payload, so both map to the same class.\n */\nconst CONTENT_VALIDATION_CODES = new Set(['content_validation_failed', 'data_validation_error']);\n\nexport function buildAPIError(options: APIErrorOptions): FoxnoseAPIError {\n const { statusCode, errorCode, detail, responseHeaders, responseBody } = options;\n const body = isPlainObject(responseBody) ? responseBody : undefined;\n\n if (statusCode === 402 && errorCode === 'spend_cap_reached' && body) {\n return new SpendCapExceededError({\n ...options,\n message: 'message' in body ? options.message : 'Spend cap reached',\n capUsd:\n typeof body.cap_usd === 'number' ? body.cap_usd : body.cap_usd === null ? null : undefined,\n cycleResetsAt: typeof body.cycle_resets_at === 'string' ? body.cycle_resets_at : undefined,\n raiseCapUrl: typeof body.raise_cap_url === 'string' ? body.raise_cap_url : undefined,\n });\n }\n\n if (statusCode === 402 && errorCode === 'plan_exhausted' && body) {\n return new PlanExhaustedError({\n ...options,\n message: 'message' in body ? options.message : 'Plan allowance exhausted',\n axis: typeof body.axis === 'string' ? body.axis : undefined,\n windowResetsAt: typeof body.window_resets_at === 'string' ? body.window_resets_at : undefined,\n upgradeUrl: typeof body.upgrade_url === 'string' ? body.upgrade_url : undefined,\n });\n }\n\n if (statusCode === 402 && errorCode === 'files_quota_exceeded' && body) {\n const numberOrNull = (value: unknown) =>\n typeof value === 'number' ? value : value === null ? null : undefined;\n const text = (value: unknown) => (typeof value === 'string' ? value : undefined);\n return new FilesQuotaExceededError({\n ...options,\n message: 'message' in body ? options.message : 'File processing quota reached',\n axis: text(body.axis),\n reason: text(body.reason),\n usedUnits: typeof body.used_units === 'number' ? body.used_units : undefined,\n includedUnits: numberOrNull(body.included_units),\n capUsd: numberOrNull(body.cap_usd),\n windowResetsAt: body.window_resets_at === null ? null : text(body.window_resets_at),\n upgradeUrl: text(body.upgrade_url),\n raiseCapUrl: text(body.raise_cap_url),\n });\n }\n\n if (statusCode === 503 && errorCode === 'files_quota_unavailable') {\n return new FilesQuotaUnavailableError({\n ...options,\n message: body && 'message' in body ? options.message : 'File processing quota is unavailable',\n retryAfter: retryAfterSeconds(responseHeaders),\n });\n }\n\n if (statusCode === 403 && errorCode === 'plan_limit_exceeded') {\n const d = isPlainObject(detail) ? detail : {};\n return new PlanLimitExceededError({\n ...options,\n entity: typeof d.entity === 'string' ? d.entity : undefined,\n limit: typeof d.limit === 'number' ? d.limit : undefined,\n current: typeof d.current === 'number' ? d.current : undefined,\n upgradeUrl: typeof d.upgrade_url === 'string' ? d.upgrade_url : undefined,\n });\n }\n\n if (statusCode === 429 && errorCode === 'rate_limited') {\n return new RateLimitExceededError({\n ...options,\n retryAfter: retryAfterSeconds(responseHeaders),\n });\n }\n\n if (statusCode === 403 && errorCode === 'collection_not_writable') {\n return new CollectionNotWritableError(options);\n }\n\n if (statusCode === 409 && errorCode === 'external_id_conflict') {\n return new ExternalIdConflictError(options);\n }\n\n if (statusCode === 422 && CONTENT_VALIDATION_CODES.has(errorCode as string)) {\n const d = isPlainObject(detail) ? detail : {};\n const errors = Array.isArray(d.errors) ? d.errors : typeof d.json_path === 'string' ? [d] : [];\n return new ContentValidationFailedError({\n ...options,\n errors,\n errorsTruncated: d.errors_truncated === true,\n });\n }\n\n if (statusCode === 502 && errorCode === 'upstream_error') {\n return new UpstreamError(options);\n }\n\n return new FoxnoseAPIError(options);\n}\n\n/**\n * Raised when authentication headers cannot be generated.\n */\nexport class FoxnoseAuthError extends FoxnoseError {\n constructor(message: string) {\n super(message);\n this.name = 'FoxnoseAuthError';\n }\n}\n\n/**\n * Raised when the HTTP layer fails before receiving a response.\n */\nexport class FoxnoseTransportError extends FoxnoseError {\n constructor(message: string) {\n super(message);\n this.name = 'FoxnoseTransportError';\n }\n}\n","import type { AuthStrategy, RequestData } from './types.js';\n\n/**\n * Adds `Authorization: Simple` headers for development usage.\n */\nexport class SimpleKeyAuth implements AuthStrategy {\n private readonly publicKey: string;\n private readonly secretKey: string;\n\n constructor(publicKey: string, secretKey: string) {\n if (!publicKey || !secretKey) {\n throw new Error('publicKey and secretKey are required');\n }\n this.publicKey = publicKey;\n this.secretKey = secretKey;\n }\n\n buildHeaders(_request: RequestData): Record<string, string> {\n return { Authorization: `Simple ${this.publicKey}:${this.secretKey}` };\n }\n}\n","/**\n * Controls HTTP retry behavior for idempotent requests.\n */\nexport interface RetryConfig {\n /** Total number of attempts (original request + retries). */\n attempts: number;\n /** Multiplier for exponential backoff delays. */\n backoffFactor: number;\n /** Response statuses that should be retried. */\n statusCodes: readonly number[];\n /** HTTP methods that are eligible for retrying. */\n methods: readonly string[];\n}\n\nexport const DEFAULT_RETRY_CONFIG: Readonly<RetryConfig> = {\n attempts: 3,\n backoffFactor: 0.5,\n statusCodes: [408, 425, 429, 500, 502, 503, 504],\n methods: ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE'],\n};\n\nexport const SDK_VERSION = '0.7.0';\n\nexport const DEFAULT_USER_AGENT = `foxnose-sdk-js/${SDK_VERSION}`;\n\n/**\n * General transport-level configuration shared by all clients.\n */\nexport interface FoxnoseConfig {\n /** Root URL (including scheme) for the API. */\n baseUrl: string;\n /** Request timeout in milliseconds. */\n timeout: number;\n /** Headers applied to every request (lower priority than per-call headers). */\n defaultHeaders?: Record<string, string>;\n /** User agent string reported to the API. */\n userAgent: string;\n}\n\n/**\n * Creates a validated FoxnoseConfig with defaults applied.\n */\nexport function createConfig(options: {\n baseUrl: string;\n timeout?: number;\n defaultHeaders?: Record<string, string>;\n userAgent?: string;\n}): FoxnoseConfig {\n if (!options.baseUrl) {\n throw new Error('baseUrl must be provided');\n }\n return {\n baseUrl: options.baseUrl.replace(/\\/+$/, ''),\n timeout: options.timeout ?? 30_000,\n defaultHeaders: options.defaultHeaders,\n userAgent: options.userAgent ?? DEFAULT_USER_AGENT,\n };\n}\n","import { AnonymousAuth } from './auth/anonymous.js';\nimport type { AuthStrategy, RequestData } from './auth/types.js';\nimport type { FoxnoseConfig, RetryConfig } from './config.js';\nimport { DEFAULT_RETRY_CONFIG } from './config.js';\nimport { buildAPIError, FoxnoseTransportError } from './errors.js';\n\n/**\n * Shared HTTP transport with retry logic built on native `fetch`.\n */\nexport class HttpTransport {\n private readonly config: FoxnoseConfig;\n private readonly auth: AuthStrategy;\n private readonly retry: RetryConfig;\n\n constructor(options: { config: FoxnoseConfig; auth?: AuthStrategy; retryConfig?: RetryConfig }) {\n this.config = options.config;\n this.auth = options.auth ?? new AnonymousAuth();\n this.retry = options.retryConfig ?? { ...DEFAULT_RETRY_CONFIG };\n }\n\n async request(\n method: string,\n path: string,\n options?: {\n params?: Record<string, any>;\n jsonBody?: any;\n content?: Uint8Array;\n headers?: Record<string, string>;\n parseJson?: boolean;\n allowRetries?: boolean;\n },\n ): Promise<any> {\n const parseJson = options?.parseJson ?? true;\n const response = await this.sendWithRetries(method, path, options);\n return this.maybeDecodeResponse(response, parseJson);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n close(): void {}\n\n private buildUrl(path: string, params?: Record<string, any>): string {\n const base = this.config.baseUrl + path;\n if (!params || Object.keys(params).length === 0) {\n return base;\n }\n const searchParams = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined && value !== null) {\n searchParams.append(key, String(value));\n }\n }\n const qs = searchParams.toString();\n return qs ? `${base}?${qs}` : base;\n }\n\n private buildRequest(\n method: string,\n path: string,\n options?: {\n params?: Record<string, any>;\n jsonBody?: any;\n content?: Uint8Array;\n headers?: Record<string, string>;\n },\n ): { url: string; init: RequestInit; body: Uint8Array } {\n const headers: Record<string, string> = {};\n\n if (this.config.defaultHeaders) {\n Object.assign(headers, this.config.defaultHeaders);\n }\n headers['User-Agent'] = headers['User-Agent'] ?? this.config.userAgent;\n\n if (options?.headers) {\n Object.assign(headers, options.headers);\n }\n\n let body: Uint8Array = new Uint8Array(0);\n let bodyInit: string | Uint8Array | undefined;\n\n if (options?.jsonBody !== undefined) {\n const jsonStr = JSON.stringify(options.jsonBody);\n body = new TextEncoder().encode(jsonStr);\n bodyInit = jsonStr;\n headers['Content-Type'] = headers['Content-Type'] ?? 'application/json';\n } else if (options?.content) {\n body = options.content;\n bodyInit = options.content;\n }\n\n const url = this.buildUrl(path, options?.params);\n\n const requestData: RequestData = {\n method: method.toUpperCase(),\n url,\n path: this.buildSigningPath(path, options?.params),\n body,\n };\n\n const authHeaders = this.auth.buildHeaders(requestData);\n if (authHeaders) {\n Object.assign(headers, authHeaders);\n }\n\n const init: RequestInit = {\n method: method.toUpperCase(),\n headers,\n body: bodyInit,\n };\n\n return { url, init, body };\n }\n\n private buildSigningPath(path: string, params?: Record<string, any>): string {\n if (!params || Object.keys(params).length === 0) {\n return path;\n }\n const searchParams = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined && value !== null) {\n searchParams.append(key, String(value));\n }\n }\n const qs = searchParams.toString();\n return qs ? `${path}?${qs}` : path;\n }\n\n private shouldRetry(method: string, statusCode: number): boolean {\n if (!this.retry.methods.includes(method.toUpperCase())) {\n return false;\n }\n return this.retry.statusCodes.includes(statusCode);\n }\n\n private computeDelay(attempt: number, retryAfter?: string | null): number {\n if (retryAfter) {\n const parsed = parseFloat(retryAfter);\n if (!isNaN(parsed)) {\n return parsed * 1000;\n }\n return 0;\n }\n const base = this.retry.backoffFactor * Math.pow(2, Math.max(attempt - 1, 0)) * 1000;\n return base * (0.5 + Math.random() * 0.5);\n }\n\n private async maybeDecodeResponse(response: Response, parseJson: boolean): Promise<any> {\n if (!parseJson) {\n return response;\n }\n const text = await response.text();\n if (!text) {\n return null;\n }\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n\n private async sendWithRetries(\n method: string,\n path: string,\n options?: {\n params?: Record<string, any>;\n jsonBody?: any;\n content?: Uint8Array;\n headers?: Record<string, string>;\n allowRetries?: boolean;\n },\n ): Promise<Response> {\n const allowRetries = options?.allowRetries !== false;\n for (let attempt = 1; attempt <= this.retry.attempts; attempt++) {\n const { url, init } = this.buildRequest(method, path, options);\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);\n init.signal = controller.signal;\n\n let response: Response;\n try {\n response = await fetch(url, init);\n } catch (err) {\n clearTimeout(timeoutId);\n const delay = this.handleTransportError(err, method, attempt, !allowRetries);\n if (delay > 0) {\n await this.sleep(delay);\n }\n continue;\n } finally {\n clearTimeout(timeoutId);\n }\n\n if (response.status >= 400) {\n if (\n allowRetries &&\n this.shouldRetry(method, response.status) &&\n attempt < this.retry.attempts\n ) {\n const delay = this.computeDelay(attempt, response.headers.get('Retry-After'));\n if (delay > 0) {\n await this.sleep(delay);\n }\n continue;\n }\n await this.raiseAPIError(response);\n }\n\n return response;\n }\n\n throw new FoxnoseTransportError('All retry attempts exhausted');\n }\n\n private handleTransportError(\n err: unknown,\n method: string,\n attempt: number,\n forbidRetry = false,\n ): number {\n const canRetry =\n !forbidRetry &&\n this.retry.methods.includes(method.toUpperCase()) &&\n attempt < this.retry.attempts;\n if (!canRetry) {\n const message = err instanceof Error ? err.message : String(err);\n throw new FoxnoseTransportError(message);\n }\n return this.computeDelay(attempt);\n }\n\n private async raiseAPIError(response: Response): Promise<never> {\n let message = '';\n let errorCode: string | undefined;\n let detail: unknown;\n let body: unknown;\n\n try {\n const text = await response.text();\n message = text;\n if (text) {\n try {\n const payload = JSON.parse(text);\n body = payload;\n if (payload && typeof payload === 'object' && !Array.isArray(payload)) {\n message = payload.message ?? message;\n errorCode = payload.error_code ?? payload.code;\n detail = payload.detail;\n }\n } catch {\n body = text;\n }\n }\n } catch {\n // ignore read errors\n }\n\n const responseHeaders: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n responseHeaders[key] = value;\n });\n\n throw buildAPIError({\n message: message || 'API request failed',\n statusCode: response.status,\n errorCode,\n detail,\n responseHeaders,\n responseBody: body,\n });\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n","/**\n * One-shot console.warn helper for renamed SDK methods.\n *\n * Each old method name warns at most once per process. Calling\n * {@link _resetWarned} clears the internal set — only intended for tests.\n */\n\nconst warned = new Set<string>();\n\nexport function warnDeprecatedMethod(oldName: string, newName: string, removal = '1.0'): void {\n if (warned.has(oldName)) {\n return;\n }\n warned.add(oldName);\n // eslint-disable-next-line no-console\n console.warn(\n `@foxnose/sdk: ${oldName}() is deprecated; use ${newName}() instead. ` +\n `${oldName}() will be removed in @foxnose/sdk ${removal}.`,\n );\n}\n\n/** Internal helper for tests — clears the warned set so tests stay independent. */\nexport function _resetWarned(): void {\n warned.clear();\n}\n","// ---------------------------------------------------------------------------\n// Generic pagination\n// ---------------------------------------------------------------------------\n\nexport interface PaginatedResponse<T> {\n count: number;\n next: string | null;\n previous: string | null;\n results: T[];\n}\n\n// ---------------------------------------------------------------------------\n// Resources & Revisions\n// ---------------------------------------------------------------------------\n\n/** Where a file stands in the processing steps. */\nexport interface UploadFileProgress {\n step: number;\n of: number;\n step_name: string | null;\n}\n\n/** The file attached to a record or a revision. */\nexport interface FileSummary {\n uuid: string | null;\n mime: string | null;\n width: number | null;\n height: number | null;\n cdn_url_base: string | null;\n filename: string | null;\n size: number | null;\n page_count: number | null;\n}\n\n/**\n * The parent record of a file record. `title` is `null` when the caller may not\n * read the owner, and `deleted` is `true` for a parent that was deleted.\n */\nexport interface FileRecordOwner {\n key: string;\n title: string | null;\n deleted?: boolean;\n}\n\n/** A file record's newest file, published or not. */\nexport interface FileInfo {\n filename: string | null;\n mime: string | null;\n size: number | null;\n page_count: number | null;\n}\n\nexport interface ResourceSummary {\n key: string;\n folder: string;\n content_type: string;\n created_at: string;\n vectors_size: number;\n name?: string | null;\n name_is_auto?: boolean;\n resource_owner?: string | null;\n current_revision?: string | null;\n external_id?: string | null;\n file?: FileSummary | null;\n /** Set on a record of a files collection, like the fields below it. */\n owner?: FileRecordOwner | null;\n status?: string | null;\n progress?: UploadFileProgress | null;\n analysis_state?: string | null;\n /** Short-lived. Keep it out of logs. */\n thumbnail_url?: string | null;\n file_info?: FileInfo | null;\n verdict?: string | null;\n verdict_reasons?: unknown[];\n /** The record's trust summary, where the API computes one. */\n guardrails?: Record<string, unknown> | null;\n}\n\nexport interface RevisionSummary {\n key: string;\n resource: string;\n /** `null` when the schema version is gone. */\n schema_version: string | null;\n /** `null` for a draft version, and when the schema version is gone. */\n schema_version_number?: number | null;\n file?: FileSummary | null;\n /** The revision's trust summary, where the API computes one. */\n guardrails?: Record<string, unknown> | null;\n number: number;\n size: number;\n created_at: string;\n status: string;\n is_valid: boolean | null;\n published_at: string | null;\n unpublished_at: string | null;\n}\n\nexport type ResourceList = PaginatedResponse<ResourceSummary>;\nexport type RevisionList = PaginatedResponse<RevisionSummary>;\n\n// ---------------------------------------------------------------------------\n// Folders\n// ---------------------------------------------------------------------------\n\nexport interface FolderSummary {\n key: string;\n name: string;\n alias: string;\n content_type: string;\n strict_reference: boolean;\n created_at: string;\n parent?: string | null;\n mode?: string | null;\n path?: string | null;\n auto_remove_revisions?: number | null;\n auto_remove_schema_versions?: number | null;\n embedding_model?: string | null;\n embedding_dimension?: number | null;\n}\n\nexport type FolderList = PaginatedResponse<FolderSummary>;\n\n// Collection-named aliases — same shape, preferred name in new code.\n/** @public Alias of {@link FolderSummary}. */\nexport type CollectionSummary = FolderSummary;\n/** @public Alias of {@link FolderList}. */\nexport type CollectionList = FolderList;\n\n// ---------------------------------------------------------------------------\n// Components\n// ---------------------------------------------------------------------------\n\nexport interface ComponentSummary {\n key: string;\n name: string;\n description?: string | null;\n environment: string;\n content_type: string;\n created_at: string;\n current_version?: string | null;\n}\n\nexport type ComponentList = PaginatedResponse<ComponentSummary>;\n\n// ---------------------------------------------------------------------------\n// Schema versions & fields\n// ---------------------------------------------------------------------------\n\nexport interface SchemaVersionSummary {\n key: string;\n name: string;\n description: string | null;\n version_number: number | null;\n created_at: string;\n published_at: string | null;\n archived_at: string | null;\n json_schema?: Record<string, any> | null;\n}\n\nexport interface FieldSummary {\n key: string;\n name: string;\n description: string | null;\n path: string;\n parent: string | null;\n type: string;\n meta: Record<string, any>;\n json_schema?: Record<string, any> | null;\n required: boolean;\n nullable: boolean;\n multiple?: boolean | null;\n localizable?: boolean | null;\n searchable?: boolean | null;\n private: boolean;\n vectorizable?: boolean | null;\n [extra: string]: any;\n}\n\nexport type SchemaVersionList = PaginatedResponse<SchemaVersionSummary>;\nexport type FieldList = PaginatedResponse<FieldSummary>;\n\n// ---------------------------------------------------------------------------\n// Component composition: nested field meta + sync_component\n// ---------------------------------------------------------------------------\n\n/**\n * Helper shape for the `meta` block of a Collection `nested` field.\n *\n * A `nested` field on a Collection schema embeds a Component schema at a\n * specific published version. The pin is required: even in auto-update\n * mode, `component_version` stores the most recently resolved version and\n * acts as a fallback if a future Component publish fails compatibility.\n *\n * Pass an object of this shape (or use {@link nestedFieldMeta}) as the\n * `meta` value when calling\n * {@link ManagementClient.createCollectionField} or\n * {@link ManagementClient.updateCollectionField}.\n *\n * @example\n * ```ts\n * await client.createCollectionField('articles', 'v1-draft', {\n * key: 'seo',\n * name: 'SEO',\n * type: 'nested',\n * required: true,\n * meta: nestedFieldMeta({\n * component: 'cmp-seo-metadata',\n * componentVersion: 'ver-abc12345',\n * autoUpdate: true,\n * }),\n * });\n * ```\n */\nexport interface NestedFieldMeta {\n component: string;\n component_version: string;\n auto_update?: boolean;\n [extra: string]: any;\n}\n\n/**\n * Build a {@link NestedFieldMeta} payload from camelCase ergonomics.\n *\n * The wire shape uses snake_case keys (`component_version`, `auto_update`);\n * this helper lets callers pass `componentVersion` / `autoUpdate` and\n * emits the right object.\n */\nexport function nestedFieldMeta(opts: {\n component: string;\n componentVersion: string;\n autoUpdate?: boolean;\n /**\n * Any additional meta keys (title, description, …) the API accepts.\n * `component`, `component_version`, and `auto_update` are reserved and\n * cannot be overridden via `extra` — passing them throws so callers see\n * the conflict at the call-site rather than silently winning the merge.\n */\n extra?: Record<string, any>;\n}): NestedFieldMeta {\n if (opts.extra) {\n const reserved = ['component', 'component_version', 'auto_update'];\n const collisions = reserved.filter((k) => Object.prototype.hasOwnProperty.call(opts.extra, k));\n if (collisions.length > 0) {\n throw new Error(\n `nestedFieldMeta: 'extra' must not include reserved keys: ${collisions.join(', ')}`,\n );\n }\n }\n return {\n ...(opts.extra ?? {}),\n component: opts.component,\n component_version: opts.componentVersion,\n auto_update: opts.autoUpdate ?? false,\n };\n}\n\n/**\n * One entry in the `skipped` list of a sync_component response.\n *\n * `reason` is one of:\n * - `\"not_requested\"` — `field_paths` was supplied and this path was not in it.\n * - `\"auto_update_mode\"` — the field has `meta.auto_update=true`.\n * - `\"already_at_target\"` — the field is already pinned to the requested\n * target version.\n * - `\"component_not_found\"` — referenced Component does not exist in this\n * environment.\n * - `\"component_unpublished\"` — Component has no published `current_version`.\n */\nexport interface SyncComponentSkippedItem {\n path: string;\n reason: string;\n [extra: string]: any;\n}\n\n/**\n * Response payload from\n * `POST /v1/{env}/collections/{key}/sync_component/`.\n *\n * - `syncedPaths` — field paths whose `meta.component_version` was advanced.\n * - `skipped` — per-path skip records explaining why each was left alone.\n * - `schemaVersion` — UID of the newly published Collection schema version.\n * `null` when no advance was needed (every requested path was skipped).\n */\nexport interface SyncComponentResponse {\n synced_paths: string[];\n skipped: SyncComponentSkippedItem[];\n schema_version: string | null;\n [extra: string]: any;\n}\n\n/**\n * One structured conflict entry inside a 409 `component_sync_conflict`\n * error detail. `blocking_reason` is one of:\n * - `\"required_field_added_no_default\"`\n * - `\"type_narrowed\"`\n * - `\"field_removed\"`\n */\nexport interface ComponentSyncConflictDetail {\n field_path: string;\n blocking_reason: string;\n [extra: string]: any;\n}\n\n// ---------------------------------------------------------------------------\n// Regions & Projects\n// ---------------------------------------------------------------------------\n\nexport interface RegionInfo {\n location: string;\n name: string;\n code: string;\n}\n\nexport interface ProjectSummary {\n key: string;\n name: string;\n organization: string;\n region: RegionInfo | string;\n environments: Array<Record<string, any>>;\n gdpr?: boolean | null;\n created_at?: string | null;\n [extra: string]: any;\n}\n\nexport type ProjectList = PaginatedResponse<ProjectSummary>;\n\n// ---------------------------------------------------------------------------\n// Environments\n// ---------------------------------------------------------------------------\n\nexport interface UserReference {\n key: string;\n email: string;\n first_name: string;\n last_name: string;\n full_name: string;\n}\n\nexport interface EnvironmentSummary {\n key: string;\n name: string;\n project: string;\n host: string;\n is_enabled: boolean;\n created_at: string;\n protection_level?: string | null;\n protection_level_display?: string | null;\n protected_by_user?: UserReference | null;\n protected_at?: string | null;\n protection_reason?: string | null;\n}\n\nexport type EnvironmentList = EnvironmentSummary[];\n\n// ---------------------------------------------------------------------------\n// Locales\n// ---------------------------------------------------------------------------\n\nexport interface LocaleSummary {\n name: string;\n code: string;\n environment: string;\n is_default: boolean;\n created_at: string;\n}\n\nexport type LocaleList = LocaleSummary[];\n\n// ---------------------------------------------------------------------------\n// API Keys\n// ---------------------------------------------------------------------------\n\nexport interface ManagementAPIKeySummary {\n key: string;\n description?: string | null;\n public_key: string;\n secret_key: string;\n role?: string | null;\n environment: string;\n created_at: string;\n}\n\nexport type ManagementAPIKeyList = PaginatedResponse<ManagementAPIKeySummary>;\n\nexport interface FluxAPIKeySummary {\n key: string;\n description?: string | null;\n public_key: string;\n secret_key: string;\n role?: string | null;\n environment: string;\n created_at: string;\n /**\n * First 12 characters of the key's bearer token (e.g. `fxk_A7fQ2mXe`), or\n * null when none is issued. Enough to recognise a token in a config file or\n * a log; never enough to use one — the token itself is returned only by\n * {@link ManagementClient.issueFluxApiKeyBearerToken}, once.\n */\n bearer_token_prefix?: string | null;\n /** When the current bearer token was issued, or null. */\n bearer_token_issued_at?: string | null;\n}\n\nexport type FluxAPIKeyList = PaginatedResponse<FluxAPIKeySummary>;\n\n/**\n * The one-time response from issuing or re-issuing a Flux key's bearer token.\n *\n * A bearer token is an opaque credential bound to a Flux API key, for hosted\n * MCP connectors that can only send `Authorization: Bearer <token>` and cannot\n * choose a scheme. It identifies the key and nothing more: role, grants and\n * per-collection permissions are the key's own.\n */\nexport interface FluxAPIKeyBearerToken {\n /**\n * The credential, e.g. `fxk_A7fQ2mXe...`. RETURNED ONLY HERE, ONLY ONCE —\n * the service stores a hash, so a lost token is re-issued, not recovered.\n */\n bearer_token: string;\n /** First 12 characters, also present on every subsequent key read. */\n bearer_token_prefix: string;\n bearer_token_issued_at: string;\n}\n\n// ---------------------------------------------------------------------------\n// Roles & Permissions\n// ---------------------------------------------------------------------------\n\nexport interface ManagementRoleSummary {\n key: string;\n name: string;\n description?: string | null;\n full_access: boolean;\n environment: string;\n created_at: string;\n}\n\nexport type ManagementRoleList = PaginatedResponse<ManagementRoleSummary>;\n\nexport interface RolePermission {\n content_type: string;\n actions: string[];\n all_objects: boolean;\n objects?: string[] | null;\n}\n\nexport interface RolePermissionObject {\n content_type: string;\n object_key: string;\n}\n\nexport interface FluxRoleSummary {\n key: string;\n name: string;\n description?: string | null;\n environment: string;\n created_at: string;\n}\n\nexport type FluxRoleList = PaginatedResponse<FluxRoleSummary>;\n\n// ---------------------------------------------------------------------------\n// APIs\n// ---------------------------------------------------------------------------\n\nexport interface APIInfo {\n key: string;\n name: string;\n prefix: string;\n description?: string | null;\n environment: string;\n version?: string | null;\n is_auth_required: boolean;\n /** Whether the MCP endpoint (`/{prefix}/_mcp`) is exposed. Defaults to true. */\n mcp_enabled?: boolean;\n /** Whether router introspection (`/{prefix}/_router`) is exposed. Defaults to true. */\n router_introspection_enabled?: boolean;\n /**\n * Allowed browser origins for cross-origin reads. Empty (the default) means\n * CORS is off; `[\"*\"]` allows any origin. Server-validated and normalized.\n * Covers public read traffic only — writes still require a key.\n */\n cors_origins?: string[];\n created_at: string;\n path?: string | null;\n}\n\nexport type APIList = PaginatedResponse<APIInfo>;\n\n/**\n * One entry in `flat_routes[]` on a collection's connection to an API — a\n * read-only address for a strict-reference collection that omits some\n * number of ancestor keys from the path. `level 0` is fully flat and drops\n * every ancestor key; `level >= 1` keeps the root-most `retained_ancestors`.\n *\n * `omitted_ancestors` and `retained_ancestors` are ancestor UUIDs, not the\n * short collection keys used elsewhere (e.g. `folder`) — do not treat them\n * as interchangeable.\n *\n * `read_methods` is typed as sent by the server, which currently mirrors\n * the connection's `allowed_methods` verbatim rather than filtering by what\n * is actually available at this level (docs and server disagree on both\n * Get Resource at level 0 and Search at any level). Do not \"correct\" it.\n */\nexport interface FlatRoute {\n level: number;\n path: string;\n omitted_ancestors: string[];\n retained_ancestors: string[];\n enabled: boolean;\n read_methods: string[];\n available: boolean;\n unavailable_reason: string | null;\n published_generation: number;\n router_generation: number;\n}\n\n/**\n * The singular `flat_route` on a connection. Undocumented: it appears to\n * mirror whichever entry of `flat_routes` is enabled, but unlike a\n * {@link FlatRoute} it carries no `level` or `retained_ancestors`. Type it\n * for forward compatibility; build no behavior on it.\n */\nexport interface FlatRouteSummary {\n path: string;\n omitted_ancestors: string[];\n enabled: boolean;\n read_methods: string[];\n available: boolean;\n unavailable_reason: string | null;\n published_generation: number;\n router_generation: number;\n}\n\nexport interface APIFolderSummary {\n folder: string;\n api?: string | null;\n path?: string | null;\n allowed_methods?: string[] | null;\n description_get_one?: string | null;\n description_get_many?: string | null;\n description_search?: string | null;\n description_schema?: string | null;\n created_at?: string | null;\n /**\n * Ancestor levels (0 = fully flat) exposed as cross-parent read addresses\n * for this connection. Sent together with `unscoped_ancestors` — a level\n * with no corresponding ancestor is rejected by the server. Present on\n * every connection observed (`[]` when unused), not nullable.\n */\n unscoped_levels: number[];\n /**\n * Ancestor UUIDs (not collection keys) left unscoped at the corresponding\n * `unscoped_levels`. Present on every connection observed (`[]` when\n * unused), not nullable.\n */\n unscoped_ancestors: string[];\n /**\n * Present in the response but documented nowhere; semantics unconfirmed.\n * Typed so it is no longer silently dropped. Do not build request-side\n * behavior on it.\n */\n expose_owner: boolean;\n /** Undocumented; see {@link FlatRouteSummary}. Observed `null`, not just absent. */\n flat_route?: FlatRouteSummary | null;\n /** Observed `null` (not `[]`) on a connection with no key-bearing ancestor. */\n flat_routes?: FlatRoute[] | null;\n}\n\nexport type APIFolderList = PaginatedResponse<APIFolderSummary>;\n\n// Collection-named aliases.\n/** @public Alias of {@link APIFolderSummary}. */\nexport type APICollectionSummary = APIFolderSummary;\n/** @public Alias of {@link APIFolderList}. */\nexport type APICollectionList = APIFolderList;\n\n// ---------------------------------------------------------------------------\n// Organizations\n// ---------------------------------------------------------------------------\n\nexport interface OrganizationOwner {\n key: string;\n email: string;\n first_name: string;\n last_name: string;\n full_name: string;\n}\n\nexport interface OrganizationSummary {\n key: string;\n name: string;\n owner: OrganizationOwner;\n tax_num: string;\n city: string;\n province: string;\n address: string;\n country_iso: string | null;\n zip_code: string;\n legal_name: string;\n created_at: string;\n block_dt?: string | null;\n block_reason?: string | null;\n is_blocked: boolean;\n is_verified?: boolean;\n verification_method?: string | null;\n}\n\nexport type OrganizationList = OrganizationSummary[];\n\n// ---------------------------------------------------------------------------\n// Plans & Usage\n// ---------------------------------------------------------------------------\n\nexport interface PlanLimits {\n units_included?: string | null;\n projects?: number | null;\n environments?: number | null;\n folders?: number | null;\n resources?: number | null;\n users?: number | null;\n components?: number | null;\n allow_negative?: boolean | null;\n negative_limit?: number | null;\n unit_cost?: number | null;\n api_keys_max_count?: number | null;\n roles_max_count?: number | null;\n locales_max_count?: number | null;\n schemas_max_count?: number | null;\n schemas_fields_max_count?: number | null;\n flux_api_max_count?: number | null;\n max_component_inheritance_depth?: number | null;\n}\n\nexport interface PlanDetails {\n code: string;\n name: string;\n price: number;\n from?: string | null;\n to?: string | null;\n transferred?: string | null;\n limits: PlanLimits;\n}\n\nexport interface OrganizationPlanStatus {\n active_plan: PlanDetails;\n next_plan: PlanDetails;\n}\n\nexport interface UnitsUsage {\n remained?: string | number | null;\n unit_cost?: number | null;\n allow_negative: boolean;\n negative_limit?: string | null;\n}\n\nexport interface StorageUsage {\n data_storage: number;\n vector_storage: number;\n}\n\nexport interface UsageMetric {\n max: number | null;\n current: number;\n}\n\nexport interface UsageBreakdown {\n projects: UsageMetric;\n resources: UsageMetric;\n users: UsageMetric;\n}\n\nexport interface CurrentUsage {\n api_requests: number;\n embedding_tokens: Record<string, any>;\n}\n\nexport interface OrganizationUsage {\n units: UnitsUsage;\n storage: StorageUsage;\n usage: UsageBreakdown;\n current_usage: CurrentUsage;\n}\n\n// ---------------------------------------------------------------------------\n// Batch upsert helpers\n// ---------------------------------------------------------------------------\n\nexport interface BatchUpsertItem {\n external_id: string;\n payload: Record<string, any>;\n}\n\nexport interface BatchItemError {\n index: number;\n external_id: string;\n error: Error;\n}\n\nexport interface BatchUpsertResult {\n succeeded: ResourceSummary[];\n failed: BatchItemError[];\n}\n\n// ---------------------------------------------------------------------------\n// Files\n// ---------------------------------------------------------------------------\n\n/** A kind of file a collection or an upload link accepts. */\nexport type FileKind = 'image' | 'document' | 'archive';\n\n/** Body of {@link ManagementClient.createUploadLink}. */\nexport interface UploadLinkCreateRequest {\n /** The parent record that owns the uploaded files; the caller must be able to read it. */\n owner: ResourceRef;\n /** Heading of the hosted page: 1 to 80 characters, one line. */\n title: string;\n /** Plain text under the heading, up to 500 characters. */\n instructions?: string;\n /** How many files the link accepts, from 1 to 10. Defaults to 1. */\n max_files?: number;\n /** Narrows the collection's kinds for this link. */\n allowed_kinds?: FileKind[];\n /** The link's lifetime in seconds, from 300 to 86400. Defaults to 30 minutes. */\n expires_in?: number;\n}\n\n/** Who created an upload link. */\nexport interface UploadLinkCreator {\n kind: 'user' | 'api_key';\n label: string | null;\n /** The user's uid, for `kind: 'user'`. */\n user?: string;\n /** The key's uid, for `kind: 'api_key'`. */\n key?: string;\n}\n\n/** One file uploaded through a link, as the link's owner sees it. */\nexport interface UploadLinkFile {\n state: 'processing' | 'ready' | 'pending_review' | 'rejected';\n record_key?: string | null;\n public_reason?: string;\n file_name?: string | null;\n progress?: UploadFileProgress;\n}\n\n/** One visit to a link's hosted page and the files it uploaded. */\nexport interface UploadLinkSession {\n created_at: string | null;\n expires_at: string | null;\n files: UploadLinkFile[];\n}\n\n/** An upload link with its sessions and the status of each file. */\nexport interface UploadLink {\n upload_id: string;\n created_by: UploadLinkCreator | null;\n owner_key: string | null;\n title: string | null;\n instructions: string | null;\n max_files: number;\n allowed_kinds: string[];\n consumed_count: number;\n created_at: string;\n expires_at: string;\n revoked_at: string | null;\n state: 'active' | 'consumed' | 'expired' | 'revoked';\n sessions: UploadLinkSession[];\n}\n\nexport type UploadLinkList = PaginatedResponse<UploadLink>;\n\n/**\n * The answer to creating an upload link. `upload_url` carries the link's token\n * and is returned only here: no later read reproduces it. Keep it out of logs.\n */\nexport interface UploadLinkCreated {\n upload_id: string;\n title: string;\n instructions: string | null;\n upload_url: string;\n expires_at: string;\n max_files: number;\n allowed_kinds: string[];\n}\n\n/** The active analysis of a file. */\nexport interface FileAnalysis {\n generation: number;\n state: string;\n verdict: string | null;\n verdict_reasons: unknown[];\n public_reason: string | null;\n error_code: string | null;\n in_review: boolean;\n publish_requested_by: string | null;\n policy_version: number | null;\n pipeline_version: string | null;\n source_format: string | null;\n scanned_at: string | null;\n step_times: Record<string, unknown>;\n state_changed_at: string | null;\n created_at: string | null;\n}\n\n/** The receipt of one check that ran on a file. */\nexport interface FileCheck {\n detector: string;\n detector_version: string | null;\n status: string;\n started_at: string | null;\n finished_at: string | null;\n}\n\n/** The text of one zone of a finding. */\nexport interface FileEvidencePart {\n box?: unknown;\n text?: string;\n}\n\n/**\n * The concealed or withheld text a finding holds, as it was in the file.\n *\n * `parts` says which text lies in which box of the page. It is empty for a finding\n * that does not carry it, so fall back to `text`.\n */\nexport interface FileTextEvidence {\n page?: number;\n box?: unknown;\n tokens?: number;\n text?: string;\n samples?: string[];\n reason?: string;\n parts: FileEvidencePart[];\n truncated?: boolean;\n list_truncated?: boolean;\n omitted?: number;\n}\n\n/** One finding of an analysis. */\nexport interface FileFinding {\n kind: string;\n sub_kind: string | null;\n severity: string;\n page: number | null;\n box: unknown;\n detector: string | null;\n detector_version: string | null;\n score: number | null;\n /**\n * The stored string, `null` once a blocked or rejected file's personal data is\n * redacted. It can quote text from the file. {@link parseFindingEvidence} reads it\n * for a finding that holds text.\n */\n evidence: string | null;\n detail: Record<string, unknown> | null;\n rule_id: string | null;\n}\n\n/** Whether one copy of a file can be downloaded now, and why not if it cannot. */\nexport interface FileCopyAvailability {\n available: boolean;\n reason: string | null;\n}\n\n/** Active content found in a file. `present` is `null` when it is unknown. */\nexport interface FileActiveContent {\n present?: boolean | null;\n kinds?: Record<string, number>;\n truncated?: boolean;\n}\n\n/** Who started an upload. `name` is `null` when it cannot be found. */\nexport interface FileOriginActor {\n kind: 'user' | 'management_key' | 'flux_key';\n name: string | null;\n}\n\n/** The upload link a file came through. */\nexport interface FileOriginLink {\n upload_id: string;\n title: string | null;\n}\n\n/**\n * Where a record's file came from. `external` is true for a file that came from\n * outside the team. `end_user` is the identifier given when an end user's upload was\n * signed: personal data, so keep it out of logs.\n */\nexport interface FileOrigin {\n channel: 'upload_link' | 'signed_upload' | 'management_api' | 'dashboard' | null;\n external: boolean;\n created_by: FileOriginActor | null;\n upload_link: FileOriginLink | null;\n end_user: string | null;\n}\n\n/**\n * What the caller may download of a record's file, and where it came from. `origin`\n * is set on `getFileAnalysis` for a file bound to the record, and `null` for a record\n * uploaded without an intent.\n */\nexport interface FileDownloadOptions {\n original: FileCopyAvailability;\n safe_copy: FileCopyAvailability;\n active_content: FileActiveContent;\n original_access: string;\n origin?: FileOrigin | null;\n}\n\n/** How agent surfaces mark the file's content. */\nexport interface FileTrust {\n processing: string;\n content_tainted: boolean;\n tainted_paths: string[];\n}\n\n/** A record's file, its active analysis, check receipts and findings. */\nexport interface FileRecordView {\n resource_key: string;\n file_uuid: string | null;\n page_count: number | null;\n asset_state: string | null;\n tombstone: boolean;\n trust: FileTrust | null;\n analysis: FileAnalysis | null;\n checks: FileCheck[];\n findings: FileFinding[];\n file: FileDownloadOptions | null;\n /** Set on the answer to an approval only. */\n outcome?: string;\n /** Set on the answer to an approval only. */\n reason?: string | null;\n}\n\n/** A short-lived link to one copy of a file. Keep `url` out of logs. */\nexport interface FileDownload {\n url: string;\n expires_in: number | null;\n expires_at: string | null;\n kind: 'original' | 'safe_copy' | 'page';\n filename: string | null;\n content_type: string | null;\n generation: number | null;\n state: string | null;\n active_content: FileActiveContent | null;\n warnings: Record<string, unknown>[];\n}\n\n/** A region withheld from a page image. */\nexport interface FilePageRedaction {\n reason: string;\n box: number[];\n label: string | null;\n}\n\n/** A table found on a page. */\nexport interface FilePageTable {\n box: unknown;\n}\n\n/**\n * Where personal data stands on a page. `unreliable` marks data found only in text\n * read with low confidence. The matched text is never included.\n */\nexport interface FilePagePii {\n type: string;\n label: string | null;\n box: number[];\n unreliable?: boolean;\n}\n\n/** The findings of a file that share a kind, severity and source. */\nexport interface FileFindingGroup {\n code: string;\n sub_kind: string | null;\n severity: string;\n source: string;\n pages: number[];\n removed_from_agents: boolean;\n label?: string;\n rule_id?: string;\n}\n\n/** A finding of one page. `box` is `null` when it has no place on the page. */\nexport interface FilePageFinding {\n code: string;\n sub_kind: string | null;\n severity: string;\n source: string;\n box: number[] | null;\n removed_from_agents: boolean;\n label?: string;\n rule_id?: string;\n}\n\n/**\n * One page of a file. `image_url` is short-lived. `redactions`, `tables`, `text`,\n * `content_flags`, `pii` and `pii_truncated` are `null` for a page without extracted\n * text. With `pii_truncated` true, an empty `pii` means locations were discarded, not\n * that none were found.\n *\n * `findings` covers the whole file and `page_findings` this page. Neither carries\n * evidence. `removed_passages` counts the file's findings whose text is withheld from\n * agents.\n */\nexport interface FilePageDetail {\n page: number;\n of: number | null;\n image_url: string;\n image_width: number | null;\n image_height: number | null;\n expires_in: number | null;\n redactions: FilePageRedaction[] | null;\n tables: FilePageTable[] | null;\n text: string | null;\n content_flags: Record<string, unknown>[] | null;\n pii: FilePagePii[] | null;\n pii_truncated: boolean | null;\n findings: FileFindingGroup[];\n page_findings: FilePageFinding[];\n removed_passages: number;\n trust: FileTrust;\n verdict: string | null;\n reasons: unknown[];\n generation: number | null;\n state: string | null;\n}\n\n/**\n * A blocked or rejected file. `original_filename`, `raw_payload`, `uploaded_by`,\n * `owner_key` and each finding's `evidence` are `null` once `redacted` is true.\n */\nexport interface FileTombstone {\n resource_key: string | null;\n file_uuid: string | null;\n reason: string;\n public_reason: string | null;\n error_code: string | null;\n verdict_reasons: unknown[];\n generation: number | null;\n asset_state: string | null;\n blocked_at: string | null;\n purge_completed_at: string | null;\n redacts_at: string | null;\n redacted: boolean;\n original_filename: string | null;\n raw_payload: unknown;\n uploaded_by: string | null;\n owner_key: string | null;\n findings: FileFinding[];\n}\n\nexport type FileTombstoneList = PaginatedResponse<FileTombstone>;\n\n/** Counts of a file's findings. */\nexport interface FileFindingsSummary {\n total: number;\n by_kind: Record<string, number>;\n by_severity: Record<string, number>;\n}\n\n/**\n * A file held for a reviewer. `owner` is `null` outside a strict collection.\n * `thumbnail_url` is short-lived; it is `null` for a caller who is not the record's\n * reviewer, for a file held by moderation and over the project's view budget.\n */\nexport interface FileReviewItem {\n resource_key: string;\n file_uuid: string | null;\n collection: string;\n file_name: string | null;\n generation: number | null;\n state: string | null;\n verdict: string | null;\n verdict_reasons: unknown[];\n public_reason: string | null;\n findings: FileFindingsSummary;\n owner: Record<string, unknown> | null;\n held_at: string | null;\n thumbnail_url: string | null;\n}\n\nexport type FileReviewQueue = PaginatedResponse<FileReviewItem>;\n\n/**\n * The settings of a collection's files policy. As a request body it is a full\n * replacement: a field left out takes its default.\n */\nexport interface FilesPolicyBody {\n suspicious_action?: 'deliver' | 'quarantine';\n overrides?: Record<string, string>;\n allowed_kinds?: FileKind[];\n tables?: 'auto' | 'never' | 'always';\n moderation_rules?: Record<string, unknown>[];\n acknowledge_explicit_delivery?: boolean;\n original_access?: 'allowed' | 'when_clean' | 'disabled';\n}\n\n/** A collection's live files policy. `version` is `null` on the default policy. */\nexport interface FilesPolicy {\n version: number | null;\n enforce_from: string | null;\n body: FilesPolicyBody;\n config_hash: string | null;\n created_at: string | null;\n}\n\n/** The finding kinds whose `evidence` holds text of the file. */\nconst TEXT_EVIDENCE_KINDS = new Set(['hidden_text', 'low_legibility_text']);\n\n/**\n * The parsed text of a `hidden_text` or `low_legibility_text` finding, or `null` for\n * every other kind and for evidence in another form. `parts` is always an array, empty\n * when the finding does not carry it.\n *\n * The text comes from the file: treat it as untrusted content, never as instructions.\n */\nexport function parseFindingEvidence(\n finding: Pick<FileFinding, 'kind' | 'evidence'>,\n): FileTextEvidence | null {\n if (!TEXT_EVIDENCE_KINDS.has(finding.kind) || !finding.evidence) {\n return null;\n }\n let fields: unknown;\n try {\n fields = JSON.parse(finding.evidence);\n } catch {\n return null;\n }\n if (typeof fields !== 'object' || fields === null || Array.isArray(fields)) {\n return null;\n }\n const { parts } = fields as { parts?: unknown };\n if (parts !== undefined && !Array.isArray(parts)) {\n return null;\n }\n return { ...(fields as Record<string, unknown>), parts: parts ?? [] } as FileTextEvidence;\n}\n\n// ---------------------------------------------------------------------------\n// Permissions of the caller\n// ---------------------------------------------------------------------------\n\n/** The state of the environment, for combining with what a caller may do. */\nexport interface EnvironmentAccess {\n protection_level: string | null;\n is_enabled: boolean;\n}\n\n/**\n * What a caller may do with one content type. `objects` lists the keys the caller is\n * restricted to; `null` means every object.\n */\nexport interface ContentTypeAccess {\n actions: string[];\n objects: string[] | null;\n}\n\n/**\n * What the authenticated caller may do in the environment.\n *\n * This says what the caller is allowed, not whether an action is available now:\n * billing and usage blocks, a blocked organization, environment protection and a\n * disabled environment can still refuse it.\n */\nexport interface MyPermissions {\n subject: 'user' | 'api_key';\n organization_owner: boolean;\n organization_admin: boolean;\n project_admin: boolean;\n environment_full_access: boolean;\n environment: EnvironmentAccess;\n content_types: Record<string, ContentTypeAccess>;\n}\n\n// ---------------------------------------------------------------------------\n// Reference types (allow string key or model object)\n// ---------------------------------------------------------------------------\n\nexport type FolderRef = string | FolderSummary;\n/** @public Alias of {@link FolderRef} — preferred name in new code. */\nexport type CollectionRef = FolderRef;\nexport type ResourceRef = string | ResourceSummary;\nexport type RevisionRef = string | RevisionSummary;\nexport type ComponentRef = string | ComponentSummary;\nexport type SchemaVersionRef = string | SchemaVersionSummary;\nexport type OrgRef = string | OrganizationSummary;\nexport type ProjectRef = string | ProjectSummary;\nexport type EnvironmentRef = string | EnvironmentSummary;\nexport type ManagementRoleRef = string | ManagementRoleSummary;\nexport type FluxRoleRef = string | FluxRoleSummary;\nexport type ManagementAPIKeyRef = string | ManagementAPIKeySummary;\nexport type FluxAPIKeyRef = string | FluxAPIKeySummary;\nexport type APIRef = string | APIInfo;\n\n/**\n * Extract a string key from a value that is either a string or\n * an object with a `key` attribute.\n */\nexport function resolveKey(value: string | { key: string }): string {\n if (typeof value === 'string') {\n return value;\n }\n if (value && typeof value === 'object' && 'key' in value && typeof value.key === 'string') {\n return value.key;\n }\n throw new TypeError(`Expected a string or an object with a 'key' attribute, got ${typeof value}`);\n}\n","/**\n * URL path builders for Management API endpoints.\n * Equivalent to Python SDK's _ManagementPathsMixin.\n */\nexport function managementPaths(environmentKey: string) {\n return {\n // Organization paths\n orgRoot: (orgKey: string) => `/organizations/${orgKey}`,\n projectsBase: (orgKey: string) => `/organizations/${orgKey}/projects`,\n projectRoot: (orgKey: string, projectKey: string) =>\n `/organizations/${orgKey}/projects/${projectKey}`,\n environmentsBase: (orgKey: string, projectKey: string) =>\n `/organizations/${orgKey}/projects/${projectKey}/environments`,\n environmentRoot: (orgKey: string, projectKey: string, envKey: string) =>\n `/organizations/${orgKey}/projects/${projectKey}/environments/${envKey}`,\n\n // Folder paths (deprecated — see Collection paths below).\n foldersTreeRoot: () => `/v1/${environmentKey}/folders/tree`,\n foldersTreeItem: () => `/v1/${environmentKey}/folders/tree/folder`,\n folderVersionsBase: (folderKey: string) =>\n `/v1/${environmentKey}/folders/${folderKey}/model/versions`,\n folderSchemaTree: (folderKey: string, versionKey: string) =>\n `/v1/${environmentKey}/folders/${folderKey}/model/versions/${versionKey}/schema/tree`,\n\n // Collection paths (canonical going forward; folder paths above hit the\n // deprecated /folders/ URL alias on the server side).\n collectionsTreeRoot: () => `/v1/${environmentKey}/collections/tree`,\n collectionsTreeItem: () => `/v1/${environmentKey}/collections/tree/collection`,\n collectionVersionsBase: (collectionKey: string) =>\n `/v1/${environmentKey}/collections/${collectionKey}/model/versions`,\n collectionSchemaTree: (collectionKey: string, versionKey: string) =>\n `/v1/${environmentKey}/collections/${collectionKey}/model/versions/${versionKey}/schema/tree`,\n collectionSyncComponent: (collectionKey: string) =>\n `/v1/${environmentKey}/collections/${collectionKey}/sync_component`,\n\n // Component paths\n componentsRoot: () => `/v1/${environmentKey}/components`,\n componentRoot: (componentKey: string) => `/v1/${environmentKey}/components/${componentKey}`,\n componentVersionsBase: (componentKey: string) =>\n `/v1/${environmentKey}/components/${componentKey}/model/versions`,\n componentSchemaTree: (componentKey: string, versionKey: string) =>\n `/v1/${environmentKey}/components/${componentKey}/model/versions/${versionKey}/schema/tree`,\n\n // Resource paths\n resourceBase: (folderKey: string) => `/v1/${environmentKey}/folders/${folderKey}/resources`,\n revisionBase: (folderKey: string, resourceKey: string) =>\n `/v1/${environmentKey}/folders/${folderKey}/resources/${resourceKey}/revisions`,\n\n // Files paths\n uploadLinksRoot: (collectionKey: string) =>\n `/v1/${environmentKey}/collections/${collectionKey}/upload-links`,\n uploadLinkRoot: (collectionKey: string, uploadId: string) =>\n `/v1/${environmentKey}/collections/${collectionKey}/upload-links/${encodeURIComponent(uploadId)}`,\n fileRoot: (collectionKey: string, resourceKey: string) =>\n `/v1/${environmentKey}/collections/${collectionKey}/files/${resourceKey}`,\n fileTombstonesRoot: (collectionKey: string) =>\n `/v1/${environmentKey}/collections/${collectionKey}/files/tombstones`,\n filesPolicyRoot: (collectionKey: string) =>\n `/v1/${environmentKey}/collections/${collectionKey}/files-policy`,\n filesReviewRoot: () => `/v1/${environmentKey}/files/review`,\n\n // Caller's own permissions\n myPermissionsRoot: () => `/v1/${environmentKey}/permissions/me`,\n\n // Management API key paths\n managementApiKeysRoot: () => `/v1/${environmentKey}/permissions/management-api/api-keys`,\n managementApiKeyRoot: (apiKey: string) =>\n `/v1/${environmentKey}/permissions/management-api/api-keys/${apiKey}`,\n\n // Flux API key paths\n fluxApiKeysRoot: () => `/v1/${environmentKey}/permissions/flux-api/api-keys`,\n fluxApiKeyRoot: (apiKey: string) =>\n `/v1/${environmentKey}/permissions/flux-api/api-keys/${apiKey}`,\n fluxApiKeyBearerTokenRoot: (apiKey: string) =>\n `/v1/${environmentKey}/permissions/flux-api/api-keys/${apiKey}/bearer-token`,\n\n // API management paths\n apisRoot: () => `/v1/${environmentKey}/api`,\n apiRoot: (apiKey: string) => `/v1/${environmentKey}/api/${apiKey}`,\n apiFoldersRoot: (apiKey: string) => `/v1/${environmentKey}/api/${apiKey}/folders`,\n apiCollectionsRoot: (apiKey: string) => `/v1/${environmentKey}/api/${apiKey}/collections`,\n\n // Management role paths\n managementRolesRoot: () => `/v1/${environmentKey}/permissions/management-api/roles`,\n managementRoleRoot: (roleKey: string) =>\n `/v1/${environmentKey}/permissions/management-api/roles/${roleKey}`,\n rolePermissionsRoot: (roleKey: string) =>\n `/v1/${environmentKey}/permissions/management-api/roles/${roleKey}/permissions`,\n rolePermissionsBatch: (roleKey: string) =>\n `/v1/${environmentKey}/permissions/management-api/roles/${roleKey}/permissions/batch`,\n rolePermissionObjectsRoot: (roleKey: string) =>\n `/v1/${environmentKey}/permissions/management-api/roles/${roleKey}/permissions/objects`,\n\n // Flux role paths\n fluxRolesRoot: () => `/v1/${environmentKey}/permissions/flux-api/roles`,\n fluxRoleRoot: (roleKey: string) =>\n `/v1/${environmentKey}/permissions/flux-api/roles/${roleKey}`,\n fluxRolePermissionsRoot: (roleKey: string) =>\n `/v1/${environmentKey}/permissions/flux-api/roles/${roleKey}/permissions`,\n fluxRolePermissionsBatch: (roleKey: string) =>\n `/v1/${environmentKey}/permissions/flux-api/roles/${roleKey}/permissions/batch`,\n fluxRolePermissionObjectsRoot: (roleKey: string) =>\n `/v1/${environmentKey}/permissions/flux-api/roles/${roleKey}/permissions/objects`,\n\n // Locale paths\n localesRoot: () => `/v1/${environmentKey}/locales`,\n localeRoot: (code: string) => `/v1/${environmentKey}/locales/${code}`,\n };\n}\n\nexport type ManagementPaths = ReturnType<typeof managementPaths>;\n","import type { AuthStrategy } from '../auth/types.js';\nimport type { RetryConfig } from '../config.js';\nimport { createConfig } from '../config.js';\nimport { HttpTransport } from '../http.js';\nimport { warnDeprecatedMethod } from '../_deprecation.js';\nimport type {\n APICollectionList,\n APICollectionSummary,\n APIFolderList,\n APIFolderSummary,\n APIInfo,\n APIList,\n APIRef,\n BatchItemError,\n BatchUpsertItem,\n BatchUpsertResult,\n CollectionList,\n CollectionRef,\n CollectionSummary,\n ComponentList,\n ComponentRef,\n ComponentSummary,\n EnvironmentList,\n EnvironmentRef,\n EnvironmentSummary,\n FieldList,\n FieldSummary,\n FileDownload,\n FilePageDetail,\n FileRecordView,\n FileReviewQueue,\n FilesPolicy,\n FilesPolicyBody,\n FileTombstoneList,\n FluxAPIKeyList,\n FluxAPIKeyRef,\n FluxAPIKeyBearerToken,\n FluxAPIKeySummary,\n FluxRoleList,\n FluxRoleRef,\n FluxRoleSummary,\n FolderList,\n FolderRef,\n FolderSummary,\n LocaleList,\n LocaleSummary,\n ManagementAPIKeyList,\n ManagementAPIKeyRef,\n ManagementAPIKeySummary,\n ManagementRoleList,\n ManagementRoleRef,\n ManagementRoleSummary,\n MyPermissions,\n OrgRef,\n OrganizationList,\n OrganizationPlanStatus,\n OrganizationSummary,\n OrganizationUsage,\n ProjectList,\n ProjectRef,\n ProjectSummary,\n RegionInfo,\n ResourceList,\n ResourceRef,\n ResourceSummary,\n RevisionList,\n RevisionRef,\n RevisionSummary,\n RolePermission,\n RolePermissionObject,\n SchemaVersionList,\n SchemaVersionRef,\n SchemaVersionSummary,\n SyncComponentResponse,\n UploadLink,\n UploadLinkCreated,\n UploadLinkCreateRequest,\n UploadLinkList,\n} from './models.js';\nimport { resolveKey } from './models.js';\nimport { managementPaths } from './paths.js';\nimport type { ManagementPaths } from './paths.js';\n\nexport interface ManagementClientOptions {\n baseUrl?: string;\n environmentKey: string;\n auth: AuthStrategy;\n timeout?: number;\n retryConfig?: RetryConfig;\n defaultHeaders?: Record<string, string>;\n}\n\nexport interface ApiFolderRouteDescriptionOptions {\n descriptionGetOne?: string;\n descriptionGetMany?: string;\n descriptionSearch?: string;\n descriptionSchema?: string;\n}\n\nexport interface ApiFolderOptions extends ApiFolderRouteDescriptionOptions {\n allowedMethods?: string[];\n /**\n * Ancestor levels (0 = fully flat) to expose as cross-parent read\n * addresses. Wire field `unscoped_levels`. Must be sent together with\n * `unscopedAncestors` — the server rejects a level with no corresponding\n * ancestor; not enforced client-side.\n */\n unscopedLevels?: number[];\n /**\n * Ancestor UUIDs (not collection keys) to leave unscoped at the\n * corresponding `unscopedLevels`. Wire field `unscoped_ancestors`.\n */\n unscopedAncestors?: string[];\n}\n\n/**\n * Client for the FoxNose Management API.\n *\n * All methods are async and return parsed response objects.\n */\nexport class ManagementClient {\n readonly environmentKey: string;\n private readonly transport: HttpTransport;\n private readonly paths: ManagementPaths;\n\n constructor(options: ManagementClientOptions) {\n if (!options.environmentKey) {\n throw new Error('environmentKey must be provided');\n }\n this.environmentKey = options.environmentKey;\n const config = createConfig({\n baseUrl: options.baseUrl ?? 'https://api.foxnose.net',\n timeout: options.timeout,\n defaultHeaders: options.defaultHeaders,\n });\n this.transport = new HttpTransport({\n config,\n auth: options.auth,\n retryConfig: options.retryConfig,\n });\n this.paths = managementPaths(options.environmentKey);\n }\n\n /**\n * Low-level escape hatch for calling arbitrary endpoints.\n */\n async request(\n method: string,\n path: string,\n options?: {\n params?: Record<string, any>;\n jsonBody?: any;\n headers?: Record<string, string>;\n parseJson?: boolean;\n },\n ): Promise<any> {\n return this.transport.request(method, path, options);\n }\n\n close(): void {\n this.transport.close();\n }\n\n private normalizeListPayload<T>(payload: unknown): T[] {\n if (Array.isArray(payload)) {\n return payload as T[];\n }\n if (payload && typeof payload === 'object') {\n const results = (payload as { results?: unknown }).results;\n if (Array.isArray(results)) {\n return results as T[];\n }\n return [payload as T];\n }\n return [];\n }\n\n private normalizePermissionObjectPayload(\n payload: unknown,\n requestPayload: Record<string, any>,\n ): RolePermissionObject {\n if (payload && typeof payload === 'object' && !Array.isArray(payload)) {\n const data = { ...(payload as Record<string, any>) };\n if (!('object_key' in data) && 'object' in data) {\n data.object_key = data.object;\n delete data.object;\n }\n return data as RolePermissionObject;\n }\n\n return {\n content_type: requestPayload.content_type,\n object_key: requestPayload.object_key ?? requestPayload.object,\n };\n }\n\n private normalizePermissionObjectListPayload(payload: unknown): RolePermissionObject[] {\n return this.normalizeListPayload<Record<string, any>>(payload).map((item) =>\n this.normalizePermissionObjectPayload(item, item),\n );\n }\n\n // ------------------------------------------------------------------ //\n // Organization operations\n // ------------------------------------------------------------------ //\n\n async listOrganizations(): Promise<OrganizationList> {\n const payload = (await this.request('GET', '/organizations/')) ?? [];\n return Array.isArray(payload) ? payload : [payload];\n }\n\n async getOrganization(orgKey: OrgRef): Promise<OrganizationSummary> {\n const key = resolveKey(orgKey);\n return this.request('GET', `${this.paths.orgRoot(key)}/`);\n }\n\n async updateOrganization(\n orgKey: OrgRef,\n payload: Record<string, any>,\n ): Promise<OrganizationSummary> {\n const key = resolveKey(orgKey);\n return this.request('PUT', `${this.paths.orgRoot(key)}/`, { jsonBody: payload });\n }\n\n /**\n * Write the given fields of an organization and leave the rest alone. The\n * response is the whole organization as stored.\n */\n async patchOrganization(\n orgKey: OrgRef,\n payload: Record<string, any>,\n ): Promise<OrganizationSummary> {\n const key = resolveKey(orgKey);\n return this.request('PATCH', `${this.paths.orgRoot(key)}/`, { jsonBody: payload });\n }\n\n async listRegions(): Promise<RegionInfo[]> {\n const payload = (await this.request('GET', '/regions/')) ?? [];\n return Array.isArray(payload) ? payload : [payload];\n }\n\n async getAvailablePlans(): Promise<OrganizationPlanStatus> {\n return this.request('GET', '/plans/');\n }\n\n async getOrganizationPlan(orgKey: OrgRef): Promise<OrganizationPlanStatus> {\n const key = resolveKey(orgKey);\n return this.request('GET', `${this.paths.orgRoot(key)}/plan/`);\n }\n\n async setOrganizationPlan(orgKey: OrgRef, planCode: string): Promise<OrganizationPlanStatus> {\n const key = resolveKey(orgKey);\n return this.request('POST', `${this.paths.orgRoot(key)}/plan/${planCode}/`);\n }\n\n async getOrganizationUsage(orgKey: OrgRef): Promise<OrganizationUsage> {\n const key = resolveKey(orgKey);\n return this.request('GET', `${this.paths.orgRoot(key)}/usage/`);\n }\n\n // ------------------------------------------------------------------ //\n // Management API key operations\n // ------------------------------------------------------------------ //\n\n async listManagementApiKeys(params?: Record<string, any>): Promise<ManagementAPIKeyList> {\n return this.request('GET', `${this.paths.managementApiKeysRoot()}/`, { params });\n }\n\n async createManagementApiKey(payload: Record<string, any>): Promise<ManagementAPIKeySummary> {\n return this.request('POST', `${this.paths.managementApiKeysRoot()}/`, {\n jsonBody: payload,\n });\n }\n\n async getManagementApiKey(key: ManagementAPIKeyRef): Promise<ManagementAPIKeySummary> {\n const k = resolveKey(key);\n return this.request('GET', `${this.paths.managementApiKeyRoot(k)}/`);\n }\n\n async updateManagementApiKey(\n key: ManagementAPIKeyRef,\n payload: Record<string, any>,\n ): Promise<ManagementAPIKeySummary> {\n const k = resolveKey(key);\n return this.request('PUT', `${this.paths.managementApiKeyRoot(k)}/`, {\n jsonBody: payload,\n });\n }\n\n async deleteManagementApiKey(key: ManagementAPIKeyRef): Promise<void> {\n const k = resolveKey(key);\n await this.request('DELETE', `${this.paths.managementApiKeyRoot(k)}/`, {\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Flux API key operations\n // ------------------------------------------------------------------ //\n\n async listFluxApiKeys(params?: Record<string, any>): Promise<FluxAPIKeyList> {\n return this.request('GET', `${this.paths.fluxApiKeysRoot()}/`, { params });\n }\n\n async createFluxApiKey(payload: Record<string, any>): Promise<FluxAPIKeySummary> {\n return this.request('POST', `${this.paths.fluxApiKeysRoot()}/`, { jsonBody: payload });\n }\n\n async getFluxApiKey(key: FluxAPIKeyRef): Promise<FluxAPIKeySummary> {\n const k = resolveKey(key);\n return this.request('GET', `${this.paths.fluxApiKeyRoot(k)}/`);\n }\n\n async updateFluxApiKey(\n key: FluxAPIKeyRef,\n payload: Record<string, any>,\n ): Promise<FluxAPIKeySummary> {\n const k = resolveKey(key);\n return this.request('PUT', `${this.paths.fluxApiKeyRoot(k)}/`, { jsonBody: payload });\n }\n\n async deleteFluxApiKey(key: FluxAPIKeyRef): Promise<void> {\n const k = resolveKey(key);\n await this.request('DELETE', `${this.paths.fluxApiKeyRoot(k)}/`, { parseJson: false });\n }\n\n /**\n * Issue a bearer token for a Flux API key, or replace the existing one.\n *\n * A bearer token exists for clients that accept a single token value and send\n * it as `Authorization: Bearer <token>` with no way to choose the scheme —\n * hosted MCP connectors, notably the Claude API's `mcp_servers`. Those clients\n * cannot send `Simple` or `Secure` at all.\n *\n * THE PLAINTEXT IS RETURNED ONLY HERE, AND ONLY ONCE. The service stores a\n * hash, exactly as it does for `secret_key`, so a lost token is re-issued\n * rather than recovered. Subsequent key reads expose only\n * `bearer_token_prefix`.\n *\n * The key itself is untouched: `public_key`, `secret_key`, `role` and grants\n * all survive, so `Simple` and `Secure` integrations keep working across a\n * re-issue. That is what makes this the way to cut off a connector without\n * recreating a key and reconfiguring everything that uses it.\n *\n * There is at most one token per key; calling this again replaces it.\n */\n async issueFluxApiKeyBearerToken(key: FluxAPIKeyRef): Promise<FluxAPIKeyBearerToken> {\n const k = resolveKey(key);\n return this.request('POST', `${this.paths.fluxApiKeyBearerTokenRoot(k)}/`);\n }\n\n /**\n * Revoke a Flux API key's bearer token. The key and its role keep working.\n *\n * Idempotent: succeeds whether or not a token was issued.\n */\n async revokeFluxApiKeyBearerToken(key: FluxAPIKeyRef): Promise<void> {\n const k = resolveKey(key);\n await this.request('DELETE', `${this.paths.fluxApiKeyBearerTokenRoot(k)}/`, {\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // API management operations\n // ------------------------------------------------------------------ //\n\n async listApis(params?: Record<string, any>): Promise<APIList> {\n return this.request('GET', `${this.paths.apisRoot()}/`, { params });\n }\n\n async createApi(payload: Record<string, any>): Promise<APIInfo> {\n return this.request('POST', `${this.paths.apisRoot()}/`, { jsonBody: payload });\n }\n\n async getApi(apiKey: APIRef): Promise<APIInfo> {\n const key = resolveKey(apiKey);\n return this.request('GET', `${this.paths.apiRoot(key)}/`);\n }\n\n async updateApi(apiKey: APIRef, payload: Record<string, any>): Promise<APIInfo> {\n const key = resolveKey(apiKey);\n return this.request('PUT', `${this.paths.apiRoot(key)}/`, { jsonBody: payload });\n }\n\n async deleteApi(apiKey: APIRef): Promise<void> {\n const key = resolveKey(apiKey);\n await this.request('DELETE', `${this.paths.apiRoot(key)}/`, { parseJson: false });\n }\n\n /**\n * Build the request body shared by all four API-collection-association\n * writers: {@link addApiCollection}, {@link updateApiCollection}, and\n * their deprecated `*ApiFolder*` twins. All four accept {@link\n * ApiFolderOptions}, so this is the one place that maps its camelCase\n * fields to wire snake_case — adding a field here, rather than to each\n * method separately, is what keeps the deprecated twins from silently\n * swallowing a field the type says they accept.\n */\n private buildApiFolderPayload(options?: ApiFolderOptions): Record<string, any> {\n const body: Record<string, any> = {};\n if (options?.allowedMethods !== undefined) {\n body.allowed_methods = options.allowedMethods;\n }\n if (options?.descriptionGetOne !== undefined) {\n body.description_get_one = options.descriptionGetOne;\n }\n if (options?.descriptionGetMany !== undefined) {\n body.description_get_many = options.descriptionGetMany;\n }\n if (options?.descriptionSearch !== undefined) {\n body.description_search = options.descriptionSearch;\n }\n if (options?.descriptionSchema !== undefined) {\n body.description_schema = options.descriptionSchema;\n }\n if (options?.unscopedLevels !== undefined) {\n body.unscoped_levels = options.unscopedLevels;\n }\n if (options?.unscopedAncestors !== undefined) {\n body.unscoped_ancestors = options.unscopedAncestors;\n }\n return body;\n }\n\n // ------------------------------------------------------------------ //\n // API ↔ Collection association (canonical)\n // ------------------------------------------------------------------ //\n\n async listApiCollections(\n apiKey: APIRef,\n params?: Record<string, any>,\n ): Promise<APICollectionList> {\n const key = resolveKey(apiKey);\n return this.request('GET', `${this.paths.apiCollectionsRoot(key)}/`, { params });\n }\n\n async addApiCollection(\n apiKey: APIRef,\n collectionKey: CollectionRef,\n options?: ApiFolderOptions,\n ): Promise<APICollectionSummary> {\n const aKey = resolveKey(apiKey);\n const cKey = resolveKey(collectionKey);\n // Wire field name `folder` is preserved for backwards compat.\n const body: Record<string, any> = { folder: cKey, ...this.buildApiFolderPayload(options) };\n return this.request('POST', `${this.paths.apiCollectionsRoot(aKey)}/`, {\n jsonBody: body,\n });\n }\n\n async getApiCollection(\n apiKey: APIRef,\n collectionKey: CollectionRef,\n ): Promise<APICollectionSummary> {\n const aKey = resolveKey(apiKey);\n const cKey = resolveKey(collectionKey);\n return this.request('GET', `${this.paths.apiCollectionsRoot(aKey)}/${cKey}/`);\n }\n\n async updateApiCollection(\n apiKey: APIRef,\n collectionKey: CollectionRef,\n options?: ApiFolderOptions,\n ): Promise<APICollectionSummary> {\n const aKey = resolveKey(apiKey);\n const cKey = resolveKey(collectionKey);\n const body = this.buildApiFolderPayload(options);\n return this.request('PUT', `${this.paths.apiCollectionsRoot(aKey)}/${cKey}/`, {\n jsonBody: body,\n });\n }\n\n async removeApiCollection(apiKey: APIRef, collectionKey: CollectionRef): Promise<void> {\n const aKey = resolveKey(apiKey);\n const cKey = resolveKey(collectionKey);\n await this.request('DELETE', `${this.paths.apiCollectionsRoot(aKey)}/${cKey}/`, {\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // API ↔ Folder association (deprecated; hits legacy /folders/ URL)\n // ------------------------------------------------------------------ //\n\n /** @deprecated Use {@link listApiCollections} instead. */\n async listApiFolders(apiKey: APIRef, params?: Record<string, any>): Promise<APIFolderList> {\n warnDeprecatedMethod('listApiFolders', 'listApiCollections');\n const key = resolveKey(apiKey);\n return this.request('GET', `${this.paths.apiFoldersRoot(key)}/`, { params });\n }\n\n /** @deprecated Use {@link addApiCollection} instead. */\n async addApiFolder(\n apiKey: APIRef,\n folderKey: FolderRef,\n options?: ApiFolderOptions,\n ): Promise<APIFolderSummary> {\n warnDeprecatedMethod('addApiFolder', 'addApiCollection');\n const aKey = resolveKey(apiKey);\n const fKey = resolveKey(folderKey);\n const body: Record<string, any> = { folder: fKey, ...this.buildApiFolderPayload(options) };\n return this.request('POST', `${this.paths.apiFoldersRoot(aKey)}/`, { jsonBody: body });\n }\n\n /** @deprecated Use {@link getApiCollection} instead. */\n async getApiFolder(apiKey: APIRef, folderKey: FolderRef): Promise<APIFolderSummary> {\n warnDeprecatedMethod('getApiFolder', 'getApiCollection');\n const aKey = resolveKey(apiKey);\n const fKey = resolveKey(folderKey);\n return this.request('GET', `${this.paths.apiFoldersRoot(aKey)}/${fKey}/`);\n }\n\n /** @deprecated Use {@link updateApiCollection} instead. */\n async updateApiFolder(\n apiKey: APIRef,\n folderKey: FolderRef,\n options?: ApiFolderOptions,\n ): Promise<APIFolderSummary> {\n warnDeprecatedMethod('updateApiFolder', 'updateApiCollection');\n const aKey = resolveKey(apiKey);\n const fKey = resolveKey(folderKey);\n const body = this.buildApiFolderPayload(options);\n return this.request('PUT', `${this.paths.apiFoldersRoot(aKey)}/${fKey}/`, {\n jsonBody: body,\n });\n }\n\n /** @deprecated Use {@link removeApiCollection} instead. */\n async removeApiFolder(apiKey: APIRef, folderKey: FolderRef): Promise<void> {\n warnDeprecatedMethod('removeApiFolder', 'removeApiCollection');\n const aKey = resolveKey(apiKey);\n const fKey = resolveKey(folderKey);\n await this.request('DELETE', `${this.paths.apiFoldersRoot(aKey)}/${fKey}/`, {\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Management role operations\n // ------------------------------------------------------------------ //\n\n async listManagementRoles(params?: Record<string, any>): Promise<ManagementRoleList> {\n return this.request('GET', `${this.paths.managementRolesRoot()}/`, { params });\n }\n\n async createManagementRole(payload: Record<string, any>): Promise<ManagementRoleSummary> {\n return this.request('POST', `${this.paths.managementRolesRoot()}/`, {\n jsonBody: payload,\n });\n }\n\n async getManagementRole(roleKey: ManagementRoleRef): Promise<ManagementRoleSummary> {\n const key = resolveKey(roleKey);\n return this.request('GET', `${this.paths.managementRoleRoot(key)}/`);\n }\n\n async updateManagementRole(\n roleKey: ManagementRoleRef,\n payload: Record<string, any>,\n ): Promise<ManagementRoleSummary> {\n const key = resolveKey(roleKey);\n return this.request('PUT', `${this.paths.managementRoleRoot(key)}/`, {\n jsonBody: payload,\n });\n }\n\n async deleteManagementRole(roleKey: ManagementRoleRef): Promise<void> {\n const key = resolveKey(roleKey);\n await this.request('DELETE', `${this.paths.managementRoleRoot(key)}/`, {\n parseJson: false,\n });\n }\n\n // Management role permissions\n\n async listManagementRolePermissions(roleKey: ManagementRoleRef): Promise<RolePermission[]> {\n const key = resolveKey(roleKey);\n const payload = (await this.request('GET', `${this.paths.rolePermissionsRoot(key)}/`)) ?? [];\n return Array.isArray(payload) ? payload : [payload];\n }\n\n async upsertManagementRolePermission(\n roleKey: ManagementRoleRef,\n payload: Record<string, any>,\n ): Promise<RolePermission> {\n const key = resolveKey(roleKey);\n return this.request('POST', `${this.paths.rolePermissionsRoot(key)}/`, {\n jsonBody: payload,\n });\n }\n\n async deleteManagementRolePermission(\n roleKey: ManagementRoleRef,\n contentType: string,\n ): Promise<void> {\n const key = resolveKey(roleKey);\n await this.request('DELETE', `${this.paths.rolePermissionsRoot(key)}/`, {\n params: { content_type: contentType },\n parseJson: false,\n });\n }\n\n async replaceManagementRolePermissions(\n roleKey: ManagementRoleRef,\n permissions: Array<Record<string, any>>,\n ): Promise<RolePermission[]> {\n const key = resolveKey(roleKey);\n const payload = await this.request('POST', `${this.paths.rolePermissionsBatch(key)}/`, {\n jsonBody: permissions,\n });\n return Array.isArray(payload) ? payload : [];\n }\n\n // Management permission objects\n\n async listManagementPermissionObjects(\n roleKey: ManagementRoleRef,\n contentType: string,\n ): Promise<RolePermissionObject[]> {\n const key = resolveKey(roleKey);\n const payload = await this.request('GET', `${this.paths.rolePermissionObjectsRoot(key)}/`, {\n params: { content_type: contentType },\n });\n return this.normalizePermissionObjectListPayload(payload);\n }\n\n async addManagementPermissionObject(\n roleKey: ManagementRoleRef,\n payload: Record<string, any>,\n ): Promise<RolePermissionObject> {\n const key = resolveKey(roleKey);\n const data = await this.request('POST', `${this.paths.rolePermissionObjectsRoot(key)}/`, {\n jsonBody: payload,\n });\n return this.normalizePermissionObjectPayload(data, payload);\n }\n\n async deleteManagementPermissionObject(\n roleKey: ManagementRoleRef,\n payload: Record<string, any>,\n ): Promise<void> {\n const key = resolveKey(roleKey);\n await this.request('DELETE', `${this.paths.rolePermissionObjectsRoot(key)}/`, {\n jsonBody: payload,\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Flux role operations\n // ------------------------------------------------------------------ //\n\n async listFluxRoles(params?: Record<string, any>): Promise<FluxRoleList> {\n return this.request('GET', `${this.paths.fluxRolesRoot()}/`, { params });\n }\n\n async createFluxRole(payload: Record<string, any>): Promise<FluxRoleSummary> {\n return this.request('POST', `${this.paths.fluxRolesRoot()}/`, { jsonBody: payload });\n }\n\n async getFluxRole(roleKey: FluxRoleRef): Promise<FluxRoleSummary> {\n const key = resolveKey(roleKey);\n return this.request('GET', `${this.paths.fluxRoleRoot(key)}/`);\n }\n\n async updateFluxRole(\n roleKey: FluxRoleRef,\n payload: Record<string, any>,\n ): Promise<FluxRoleSummary> {\n const key = resolveKey(roleKey);\n return this.request('PUT', `${this.paths.fluxRoleRoot(key)}/`, { jsonBody: payload });\n }\n\n async deleteFluxRole(roleKey: FluxRoleRef): Promise<void> {\n const key = resolveKey(roleKey);\n await this.request('DELETE', `${this.paths.fluxRoleRoot(key)}/`, { parseJson: false });\n }\n\n // Flux role permissions\n\n async listFluxRolePermissions(roleKey: FluxRoleRef): Promise<RolePermission[]> {\n const key = resolveKey(roleKey);\n const payload =\n (await this.request('GET', `${this.paths.fluxRolePermissionsRoot(key)}/`)) ?? [];\n return Array.isArray(payload) ? payload : [payload];\n }\n\n async upsertFluxRolePermission(\n roleKey: FluxRoleRef,\n payload: Record<string, any>,\n ): Promise<RolePermission> {\n const key = resolveKey(roleKey);\n return this.request('POST', `${this.paths.fluxRolePermissionsRoot(key)}/`, {\n jsonBody: payload,\n });\n }\n\n async deleteFluxRolePermission(roleKey: FluxRoleRef, contentType: string): Promise<void> {\n const key = resolveKey(roleKey);\n await this.request('DELETE', `${this.paths.fluxRolePermissionsRoot(key)}/`, {\n params: { content_type: contentType },\n parseJson: false,\n });\n }\n\n async replaceFluxRolePermissions(\n roleKey: FluxRoleRef,\n permissions: Array<Record<string, any>>,\n ): Promise<RolePermission[]> {\n const key = resolveKey(roleKey);\n const payload = await this.request('POST', `${this.paths.fluxRolePermissionsBatch(key)}/`, {\n jsonBody: permissions,\n });\n return Array.isArray(payload) ? payload : [];\n }\n\n // Flux permission objects\n\n async listFluxPermissionObjects(\n roleKey: FluxRoleRef,\n contentType: string,\n ): Promise<RolePermissionObject[]> {\n const key = resolveKey(roleKey);\n const payload = await this.request('GET', `${this.paths.fluxRolePermissionObjectsRoot(key)}/`, {\n params: { content_type: contentType },\n });\n return this.normalizePermissionObjectListPayload(payload);\n }\n\n async addFluxPermissionObject(\n roleKey: FluxRoleRef,\n payload: Record<string, any>,\n ): Promise<RolePermissionObject> {\n const key = resolveKey(roleKey);\n const data = await this.request('POST', `${this.paths.fluxRolePermissionObjectsRoot(key)}/`, {\n jsonBody: payload,\n });\n return this.normalizePermissionObjectPayload(data, payload);\n }\n\n async deleteFluxPermissionObject(\n roleKey: FluxRoleRef,\n payload: Record<string, any>,\n ): Promise<void> {\n const key = resolveKey(roleKey);\n await this.request('DELETE', `${this.paths.fluxRolePermissionObjectsRoot(key)}/`, {\n jsonBody: payload,\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Collection operations (canonical)\n // ------------------------------------------------------------------ //\n\n async listCollections(params?: Record<string, any>): Promise<CollectionList> {\n return this.request('GET', `${this.paths.collectionsTreeRoot()}/`, { params });\n }\n\n async getCollection(collectionKey: CollectionRef): Promise<CollectionSummary> {\n const key = resolveKey(collectionKey);\n return this.request('GET', `${this.paths.collectionsTreeItem()}/`, {\n params: { key },\n });\n }\n\n async getCollectionByPath(path: string): Promise<CollectionSummary> {\n return this.request('GET', `${this.paths.collectionsTreeItem()}/`, {\n params: { path },\n });\n }\n\n async listCollectionTree(options?: { key?: string; mode?: string }): Promise<CollectionList> {\n const params: Record<string, any> = {};\n if (options?.key) params.key = options.key;\n if (options?.mode) params.mode = options.mode;\n return this.request('GET', `${this.paths.collectionsTreeRoot()}/`, { params });\n }\n\n async createCollection(payload: Record<string, any>): Promise<CollectionSummary> {\n return this.request('POST', `${this.paths.collectionsTreeRoot()}/`, {\n jsonBody: payload,\n });\n }\n\n async updateCollection(\n collectionKey: CollectionRef,\n payload: Record<string, any>,\n ): Promise<CollectionSummary> {\n const key = resolveKey(collectionKey);\n return this.request('PUT', `${this.paths.collectionsTreeItem()}/`, {\n params: { key },\n jsonBody: payload,\n });\n }\n\n /**\n * Write the given fields of a collection and leave the rest alone.\n *\n * `updateCollection` replaces the whole record; this does not. An omitted\n * `parent` keeps the collection where it is, and `{ parent: null }` moves it\n * to the root. The response is the whole collection as stored.\n */\n async patchCollection(\n collectionKey: CollectionRef,\n payload: Record<string, any>,\n ): Promise<CollectionSummary> {\n const key = resolveKey(collectionKey);\n return this.request('PATCH', `${this.paths.collectionsTreeItem()}/`, {\n params: { key },\n jsonBody: payload,\n });\n }\n\n async deleteCollection(collectionKey: CollectionRef): Promise<void> {\n const key = resolveKey(collectionKey);\n await this.request('DELETE', `${this.paths.collectionsTreeItem()}/`, {\n params: { key },\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Collection schema version operations (canonical)\n // ------------------------------------------------------------------ //\n\n async listCollectionVersions(\n collectionKey: CollectionRef,\n params?: Record<string, any>,\n ): Promise<SchemaVersionList> {\n const key = resolveKey(collectionKey);\n return this.request('GET', `${this.paths.collectionVersionsBase(key)}/`, {\n params,\n });\n }\n\n async createCollectionVersion(\n collectionKey: CollectionRef,\n payload: Record<string, any>,\n options?: { copyFrom?: SchemaVersionRef },\n ): Promise<SchemaVersionSummary> {\n const key = resolveKey(collectionKey);\n const params: Record<string, any> = {};\n if (options?.copyFrom) {\n params.copy_from = resolveKey(options.copyFrom);\n }\n return this.request('POST', `${this.paths.collectionVersionsBase(key)}/`, {\n jsonBody: payload,\n params: Object.keys(params).length > 0 ? params : undefined,\n });\n }\n\n async getCollectionVersion(\n collectionKey: CollectionRef,\n versionKey: SchemaVersionRef,\n options?: { includeSchema?: boolean },\n ): Promise<SchemaVersionSummary> {\n const cKey = resolveKey(collectionKey);\n const vKey = resolveKey(versionKey);\n const params: Record<string, any> = {};\n if (options?.includeSchema !== undefined) {\n params.include_schema = options.includeSchema;\n }\n return this.request('GET', `${this.paths.collectionVersionsBase(cKey)}/${vKey}/`, {\n params: Object.keys(params).length > 0 ? params : undefined,\n });\n }\n\n async updateCollectionVersion(\n collectionKey: CollectionRef,\n versionKey: SchemaVersionRef,\n payload: Record<string, any>,\n ): Promise<SchemaVersionSummary> {\n const cKey = resolveKey(collectionKey);\n const vKey = resolveKey(versionKey);\n return this.request('PUT', `${this.paths.collectionVersionsBase(cKey)}/${vKey}/`, {\n jsonBody: payload,\n });\n }\n\n async deleteCollectionVersion(\n collectionKey: CollectionRef,\n versionKey: SchemaVersionRef,\n ): Promise<void> {\n const cKey = resolveKey(collectionKey);\n const vKey = resolveKey(versionKey);\n await this.request('DELETE', `${this.paths.collectionVersionsBase(cKey)}/${vKey}/`, {\n parseJson: false,\n });\n }\n\n async publishCollectionVersion(\n collectionKey: CollectionRef,\n versionKey: SchemaVersionRef,\n ): Promise<SchemaVersionSummary> {\n const cKey = resolveKey(collectionKey);\n const vKey = resolveKey(versionKey);\n return this.request('POST', `${this.paths.collectionVersionsBase(cKey)}/${vKey}/publish/`);\n }\n\n /**\n * Advance pinned nested fields on a Collection to a target Component version.\n *\n * Creates a new published Collection schema version with the affected\n * `meta.component_version` pins advanced. Fields with `auto_update=true`\n * and fields already at the requested target version are reported in\n * `skipped` rather than advanced.\n *\n * @param collectionKey The Collection to sync.\n * @param options.fieldPaths Optional list of nested field paths to advance.\n * When omitted, every pinned (`auto_update=false`) nested field on the\n * Collection's current version is considered.\n * @param options.toVersions Optional per-path override mapping field path\n * to target Component Version UID. Paths not in this mapping advance to\n * the referenced Component's `current_version`. When both `fieldPaths`\n * and `toVersions` are supplied, every key in `toVersions` must also\n * appear in `fieldPaths`.\n *\n * @returns Summary of synced and skipped paths, plus the new\n * `schema_version` UID (`null` if no paths were advanced).\n *\n * @throws `Error` locally (before any HTTP request) when both `fieldPaths`\n * and `toVersions` are supplied AND `toVersions` contains a key that is\n * not in `fieldPaths` (mirrors the server-side validator so the misuse\n * surfaces at the call-site).\n * @throws `FoxnoseApiError` on:\n * - 409 `component_sync_conflict` — target version would break existing resources\n * - 422 `too_many_versions` — Collection schema quota exhausted\n * - 422 `validation_error` — request body invalid\n * - 404 — Collection or specified target version missing\n *\n * @example\n * ```ts\n * // Advance every pinned nested field to its Component's current version.\n * await client.syncCollectionComponent('articles');\n *\n * // Advance a specific path to a chosen Component version.\n * await client.syncCollectionComponent('articles', {\n * fieldPaths: ['seo'],\n * toVersions: { seo: 'ver-def67890' },\n * });\n * ```\n */\n async syncCollectionComponent(\n collectionKey: CollectionRef,\n options: {\n fieldPaths?: string[];\n toVersions?: Record<string, string>;\n } = {},\n ): Promise<SyncComponentResponse> {\n const cKey = resolveKey(collectionKey);\n // Client-side invariant (mirrors the server validator): every key in\n // toVersions must also appear in fieldPaths when both are supplied.\n // Catch the misuse locally instead of round-tripping a 422.\n if (options.fieldPaths !== undefined && options.toVersions !== undefined) {\n const fieldPathSet = new Set(options.fieldPaths);\n const extras = Object.keys(options.toVersions)\n .filter((k) => !fieldPathSet.has(k))\n .sort();\n if (extras.length > 0) {\n throw new Error(\n `toVersions includes paths not present in fieldPaths: [${extras.join(', ')}]`,\n );\n }\n }\n const body: Record<string, unknown> = {};\n if (options.fieldPaths !== undefined) {\n body.field_paths = options.fieldPaths;\n }\n if (options.toVersions !== undefined) {\n body.to_versions = options.toVersions;\n }\n return this.request('POST', `${this.paths.collectionSyncComponent(cKey)}/`, { jsonBody: body });\n }\n\n // ------------------------------------------------------------------ //\n // Collection schema field operations (canonical)\n // ------------------------------------------------------------------ //\n\n async listCollectionFields(\n collectionKey: CollectionRef,\n versionKey: SchemaVersionRef,\n params?: Record<string, any>,\n ): Promise<FieldList> {\n const cKey = resolveKey(collectionKey);\n const vKey = resolveKey(versionKey);\n return this.request('GET', `${this.paths.collectionSchemaTree(cKey, vKey)}/`, { params });\n }\n\n async createCollectionField(\n collectionKey: CollectionRef,\n versionKey: SchemaVersionRef,\n payload: Record<string, any>,\n ): Promise<FieldSummary> {\n const cKey = resolveKey(collectionKey);\n const vKey = resolveKey(versionKey);\n return this.request('POST', `${this.paths.collectionSchemaTree(cKey, vKey)}/`, {\n jsonBody: payload,\n });\n }\n\n async getCollectionField(\n collectionKey: CollectionRef,\n versionKey: SchemaVersionRef,\n fieldPath: string,\n ): Promise<FieldSummary> {\n const cKey = resolveKey(collectionKey);\n const vKey = resolveKey(versionKey);\n return this.request('GET', `${this.paths.collectionSchemaTree(cKey, vKey)}/field/`, {\n params: { path: fieldPath },\n });\n }\n\n async updateCollectionField(\n collectionKey: CollectionRef,\n versionKey: SchemaVersionRef,\n fieldPath: string,\n payload: Record<string, any>,\n ): Promise<FieldSummary> {\n const cKey = resolveKey(collectionKey);\n const vKey = resolveKey(versionKey);\n return this.request('PUT', `${this.paths.collectionSchemaTree(cKey, vKey)}/field/`, {\n params: { path: fieldPath },\n jsonBody: payload,\n });\n }\n\n async deleteCollectionField(\n collectionKey: CollectionRef,\n versionKey: SchemaVersionRef,\n fieldPath: string,\n ): Promise<void> {\n const cKey = resolveKey(collectionKey);\n const vKey = resolveKey(versionKey);\n await this.request('DELETE', `${this.paths.collectionSchemaTree(cKey, vKey)}/field/`, {\n params: { path: fieldPath },\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Folder operations (deprecated; hit legacy /folders/ URL)\n // ------------------------------------------------------------------ //\n\n /** @deprecated Use {@link listCollections} instead. */\n async listFolders(params?: Record<string, any>): Promise<FolderList> {\n warnDeprecatedMethod('listFolders', 'listCollections');\n return this.request('GET', `${this.paths.foldersTreeRoot()}/`, { params });\n }\n\n /** @deprecated Use {@link getCollection} instead. */\n async getFolder(folderKey: FolderRef): Promise<FolderSummary> {\n warnDeprecatedMethod('getFolder', 'getCollection');\n const key = resolveKey(folderKey);\n return this.request('GET', `${this.paths.foldersTreeItem()}/`, {\n params: { key },\n });\n }\n\n /** @deprecated Use {@link getCollectionByPath} instead. */\n async getFolderByPath(path: string): Promise<FolderSummary> {\n warnDeprecatedMethod('getFolderByPath', 'getCollectionByPath');\n return this.request('GET', `${this.paths.foldersTreeItem()}/`, {\n params: { path },\n });\n }\n\n /** @deprecated Use {@link listCollectionTree} instead. */\n async listFolderTree(options?: { key?: string; mode?: string }): Promise<FolderList> {\n warnDeprecatedMethod('listFolderTree', 'listCollectionTree');\n const params: Record<string, any> = {};\n if (options?.key) params.key = options.key;\n if (options?.mode) params.mode = options.mode;\n return this.request('GET', `${this.paths.foldersTreeRoot()}/`, { params });\n }\n\n /** @deprecated Use {@link createCollection} instead. */\n async createFolder(payload: Record<string, any>): Promise<FolderSummary> {\n warnDeprecatedMethod('createFolder', 'createCollection');\n return this.request('POST', `${this.paths.foldersTreeRoot()}/`, { jsonBody: payload });\n }\n\n /** @deprecated Use {@link updateCollection} instead. */\n async updateFolder(folderKey: FolderRef, payload: Record<string, any>): Promise<FolderSummary> {\n warnDeprecatedMethod('updateFolder', 'updateCollection');\n const key = resolveKey(folderKey);\n return this.request('PUT', `${this.paths.foldersTreeItem()}/`, {\n params: { key },\n jsonBody: payload,\n });\n }\n\n /** @deprecated Use {@link deleteCollection} instead. */\n async deleteFolder(folderKey: FolderRef): Promise<void> {\n warnDeprecatedMethod('deleteFolder', 'deleteCollection');\n const key = resolveKey(folderKey);\n await this.request('DELETE', `${this.paths.foldersTreeItem()}/`, {\n params: { key },\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Folder version operations (deprecated)\n // ------------------------------------------------------------------ //\n\n /** @deprecated Use {@link listCollectionVersions} instead. */\n async listFolderVersions(\n folderKey: FolderRef,\n params?: Record<string, any>,\n ): Promise<SchemaVersionList> {\n warnDeprecatedMethod('listFolderVersions', 'listCollectionVersions');\n const key = resolveKey(folderKey);\n return this.request('GET', `${this.paths.folderVersionsBase(key)}/`, { params });\n }\n\n /** @deprecated Use {@link createCollectionVersion} instead. */\n async createFolderVersion(\n folderKey: FolderRef,\n payload: Record<string, any>,\n options?: { copyFrom?: SchemaVersionRef },\n ): Promise<SchemaVersionSummary> {\n warnDeprecatedMethod('createFolderVersion', 'createCollectionVersion');\n const key = resolveKey(folderKey);\n const params: Record<string, any> = {};\n if (options?.copyFrom) {\n params.copy_from = resolveKey(options.copyFrom);\n }\n return this.request('POST', `${this.paths.folderVersionsBase(key)}/`, {\n jsonBody: payload,\n params: Object.keys(params).length > 0 ? params : undefined,\n });\n }\n\n /** @deprecated Use {@link getCollectionVersion} instead. */\n async getFolderVersion(\n folderKey: FolderRef,\n versionKey: SchemaVersionRef,\n options?: { includeSchema?: boolean },\n ): Promise<SchemaVersionSummary> {\n warnDeprecatedMethod('getFolderVersion', 'getCollectionVersion');\n const fKey = resolveKey(folderKey);\n const vKey = resolveKey(versionKey);\n const params: Record<string, any> = {};\n if (options?.includeSchema !== undefined) {\n params.include_schema = options.includeSchema;\n }\n return this.request('GET', `${this.paths.folderVersionsBase(fKey)}/${vKey}/`, {\n params: Object.keys(params).length > 0 ? params : undefined,\n });\n }\n\n /** @deprecated Use {@link updateCollectionVersion} instead. */\n async updateFolderVersion(\n folderKey: FolderRef,\n versionKey: SchemaVersionRef,\n payload: Record<string, any>,\n ): Promise<SchemaVersionSummary> {\n warnDeprecatedMethod('updateFolderVersion', 'updateCollectionVersion');\n const fKey = resolveKey(folderKey);\n const vKey = resolveKey(versionKey);\n return this.request('PUT', `${this.paths.folderVersionsBase(fKey)}/${vKey}/`, {\n jsonBody: payload,\n });\n }\n\n /** @deprecated Use {@link deleteCollectionVersion} instead. */\n async deleteFolderVersion(folderKey: FolderRef, versionKey: SchemaVersionRef): Promise<void> {\n warnDeprecatedMethod('deleteFolderVersion', 'deleteCollectionVersion');\n const fKey = resolveKey(folderKey);\n const vKey = resolveKey(versionKey);\n await this.request('DELETE', `${this.paths.folderVersionsBase(fKey)}/${vKey}/`, {\n parseJson: false,\n });\n }\n\n /** @deprecated Use {@link publishCollectionVersion} instead. */\n async publishFolderVersion(\n folderKey: FolderRef,\n versionKey: SchemaVersionRef,\n ): Promise<SchemaVersionSummary> {\n warnDeprecatedMethod('publishFolderVersion', 'publishCollectionVersion');\n const fKey = resolveKey(folderKey);\n const vKey = resolveKey(versionKey);\n return this.request('POST', `${this.paths.folderVersionsBase(fKey)}/${vKey}/publish/`);\n }\n\n // ------------------------------------------------------------------ //\n // Folder field operations (deprecated)\n // ------------------------------------------------------------------ //\n\n /** @deprecated Use {@link listCollectionFields} instead. */\n async listFolderFields(\n folderKey: FolderRef,\n versionKey: SchemaVersionRef,\n params?: Record<string, any>,\n ): Promise<FieldList> {\n warnDeprecatedMethod('listFolderFields', 'listCollectionFields');\n const fKey = resolveKey(folderKey);\n const vKey = resolveKey(versionKey);\n return this.request('GET', `${this.paths.folderSchemaTree(fKey, vKey)}/`, { params });\n }\n\n /** @deprecated Use {@link createCollectionField} instead. */\n async createFolderField(\n folderKey: FolderRef,\n versionKey: SchemaVersionRef,\n payload: Record<string, any>,\n ): Promise<FieldSummary> {\n warnDeprecatedMethod('createFolderField', 'createCollectionField');\n const fKey = resolveKey(folderKey);\n const vKey = resolveKey(versionKey);\n return this.request('POST', `${this.paths.folderSchemaTree(fKey, vKey)}/`, {\n jsonBody: payload,\n });\n }\n\n /** @deprecated Use {@link getCollectionField} instead. */\n async getFolderField(\n folderKey: FolderRef,\n versionKey: SchemaVersionRef,\n fieldPath: string,\n ): Promise<FieldSummary> {\n warnDeprecatedMethod('getFolderField', 'getCollectionField');\n const fKey = resolveKey(folderKey);\n const vKey = resolveKey(versionKey);\n return this.request('GET', `${this.paths.folderSchemaTree(fKey, vKey)}/field/`, {\n params: { path: fieldPath },\n });\n }\n\n /** @deprecated Use {@link updateCollectionField} instead. */\n async updateFolderField(\n folderKey: FolderRef,\n versionKey: SchemaVersionRef,\n fieldPath: string,\n payload: Record<string, any>,\n ): Promise<FieldSummary> {\n warnDeprecatedMethod('updateFolderField', 'updateCollectionField');\n const fKey = resolveKey(folderKey);\n const vKey = resolveKey(versionKey);\n return this.request('PUT', `${this.paths.folderSchemaTree(fKey, vKey)}/field/`, {\n params: { path: fieldPath },\n jsonBody: payload,\n });\n }\n\n /** @deprecated Use {@link deleteCollectionField} instead. */\n async deleteFolderField(\n folderKey: FolderRef,\n versionKey: SchemaVersionRef,\n fieldPath: string,\n ): Promise<void> {\n warnDeprecatedMethod('deleteFolderField', 'deleteCollectionField');\n const fKey = resolveKey(folderKey);\n const vKey = resolveKey(versionKey);\n await this.request('DELETE', `${this.paths.folderSchemaTree(fKey, vKey)}/field/`, {\n params: { path: fieldPath },\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Component operations\n // ------------------------------------------------------------------ //\n\n async listComponents(params?: Record<string, any>): Promise<ComponentList> {\n return this.request('GET', `${this.paths.componentsRoot()}/`, { params });\n }\n\n async getComponent(componentKey: ComponentRef): Promise<ComponentSummary> {\n const key = resolveKey(componentKey);\n return this.request('GET', `${this.paths.componentRoot(key)}/`);\n }\n\n async createComponent(payload: Record<string, any>): Promise<ComponentSummary> {\n return this.request('POST', `${this.paths.componentsRoot()}/`, { jsonBody: payload });\n }\n\n async updateComponent(\n componentKey: ComponentRef,\n payload: Record<string, any>,\n ): Promise<ComponentSummary> {\n const key = resolveKey(componentKey);\n return this.request('PUT', `${this.paths.componentRoot(key)}/`, { jsonBody: payload });\n }\n\n /**\n * Write the given fields of a component and leave the rest alone. The response\n * is the whole component as stored.\n */\n async patchComponent(\n componentKey: ComponentRef,\n payload: Record<string, any>,\n ): Promise<ComponentSummary> {\n const key = resolveKey(componentKey);\n return this.request('PATCH', `${this.paths.componentRoot(key)}/`, { jsonBody: payload });\n }\n\n async deleteComponent(componentKey: ComponentRef): Promise<void> {\n const key = resolveKey(componentKey);\n await this.request('DELETE', `${this.paths.componentRoot(key)}/`, { parseJson: false });\n }\n\n // ------------------------------------------------------------------ //\n // Component version operations\n // ------------------------------------------------------------------ //\n\n async listComponentVersions(\n componentKey: ComponentRef,\n params?: Record<string, any>,\n ): Promise<SchemaVersionList> {\n const key = resolveKey(componentKey);\n return this.request('GET', `${this.paths.componentVersionsBase(key)}/`, { params });\n }\n\n async createComponentVersion(\n componentKey: ComponentRef,\n payload: Record<string, any>,\n options?: { copyFrom?: SchemaVersionRef },\n ): Promise<SchemaVersionSummary> {\n const key = resolveKey(componentKey);\n const params: Record<string, any> = {};\n if (options?.copyFrom) {\n params.copy_from = resolveKey(options.copyFrom);\n }\n return this.request('POST', `${this.paths.componentVersionsBase(key)}/`, {\n jsonBody: payload,\n params: Object.keys(params).length > 0 ? params : undefined,\n });\n }\n\n async getComponentVersion(\n componentKey: ComponentRef,\n versionKey: SchemaVersionRef,\n options?: { includeSchema?: boolean },\n ): Promise<SchemaVersionSummary> {\n const cKey = resolveKey(componentKey);\n const vKey = resolveKey(versionKey);\n const params: Record<string, any> = {};\n if (options?.includeSchema !== undefined) {\n params.include_schema = options.includeSchema;\n }\n return this.request('GET', `${this.paths.componentVersionsBase(cKey)}/${vKey}/`, {\n params: Object.keys(params).length > 0 ? params : undefined,\n });\n }\n\n async publishComponentVersion(\n componentKey: ComponentRef,\n versionKey: SchemaVersionRef,\n ): Promise<SchemaVersionSummary> {\n const cKey = resolveKey(componentKey);\n const vKey = resolveKey(versionKey);\n return this.request('POST', `${this.paths.componentVersionsBase(cKey)}/${vKey}/publish/`);\n }\n\n async updateComponentVersion(\n componentKey: ComponentRef,\n versionKey: SchemaVersionRef,\n payload: Record<string, any>,\n ): Promise<SchemaVersionSummary> {\n const cKey = resolveKey(componentKey);\n const vKey = resolveKey(versionKey);\n return this.request('PUT', `${this.paths.componentVersionsBase(cKey)}/${vKey}/`, {\n jsonBody: payload,\n });\n }\n\n async deleteComponentVersion(\n componentKey: ComponentRef,\n versionKey: SchemaVersionRef,\n ): Promise<void> {\n const cKey = resolveKey(componentKey);\n const vKey = resolveKey(versionKey);\n await this.request('DELETE', `${this.paths.componentVersionsBase(cKey)}/${vKey}/`, {\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Component field operations\n // ------------------------------------------------------------------ //\n\n async listComponentFields(\n componentKey: ComponentRef,\n versionKey: SchemaVersionRef,\n params?: Record<string, any>,\n ): Promise<FieldList> {\n const cKey = resolveKey(componentKey);\n const vKey = resolveKey(versionKey);\n return this.request('GET', `${this.paths.componentSchemaTree(cKey, vKey)}/`, { params });\n }\n\n async createComponentField(\n componentKey: ComponentRef,\n versionKey: SchemaVersionRef,\n payload: Record<string, any>,\n ): Promise<FieldSummary> {\n const cKey = resolveKey(componentKey);\n const vKey = resolveKey(versionKey);\n return this.request('POST', `${this.paths.componentSchemaTree(cKey, vKey)}/`, {\n jsonBody: payload,\n });\n }\n\n async getComponentField(\n componentKey: ComponentRef,\n versionKey: SchemaVersionRef,\n fieldPath: string,\n ): Promise<FieldSummary> {\n const cKey = resolveKey(componentKey);\n const vKey = resolveKey(versionKey);\n return this.request('GET', `${this.paths.componentSchemaTree(cKey, vKey)}/field/`, {\n params: { path: fieldPath },\n });\n }\n\n async updateComponentField(\n componentKey: ComponentRef,\n versionKey: SchemaVersionRef,\n fieldPath: string,\n payload: Record<string, any>,\n ): Promise<FieldSummary> {\n const cKey = resolveKey(componentKey);\n const vKey = resolveKey(versionKey);\n return this.request('PUT', `${this.paths.componentSchemaTree(cKey, vKey)}/field/`, {\n params: { path: fieldPath },\n jsonBody: payload,\n });\n }\n\n async deleteComponentField(\n componentKey: ComponentRef,\n versionKey: SchemaVersionRef,\n fieldPath: string,\n ): Promise<void> {\n const cKey = resolveKey(componentKey);\n const vKey = resolveKey(versionKey);\n await this.request('DELETE', `${this.paths.componentSchemaTree(cKey, vKey)}/field/`, {\n params: { path: fieldPath },\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Resource operations\n // ------------------------------------------------------------------ //\n\n async listResources(folderKey: FolderRef, params?: Record<string, any>): Promise<ResourceList> {\n const key = resolveKey(folderKey);\n return this.request('GET', `${this.paths.resourceBase(key)}/`, { params });\n }\n\n async getResource(folderKey: FolderRef, resourceKey: ResourceRef): Promise<ResourceSummary> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n return this.request('GET', `${this.paths.resourceBase(fKey)}/${rKey}/`);\n }\n\n async createResource(\n folderKey: FolderRef,\n payload: Record<string, any>,\n options?: { externalId?: string },\n ): Promise<ResourceSummary> {\n // Defensive runtime check: TypeScript callers are protected by the interface\n // but JS callers (or TS callers using `as any`) can still pass `component`.\n // Fail loudly so the migration is obvious.\n if (options && typeof options === 'object' && 'component' in options) {\n throw new TypeError(\n 'The `component` option has been removed. Resources now derive their ' +\n \"schema from the folder's model. Remove the `component` field from \" +\n 'your call site.',\n );\n }\n const key = resolveKey(folderKey);\n const body = { ...payload };\n if (options?.externalId) {\n body.external_id = options.externalId;\n }\n return this.request('POST', `${this.paths.resourceBase(key)}/`, {\n jsonBody: body,\n });\n }\n\n async upsertResource(\n folderKey: FolderRef,\n payload: Record<string, any>,\n options: { externalId: string },\n ): Promise<ResourceSummary> {\n // Defensive runtime check: TypeScript callers are protected by the interface\n // but JS callers (or TS callers using `as any`) can still pass `component`.\n // Fail loudly so the migration is obvious.\n if (options && typeof options === 'object' && 'component' in options) {\n throw new TypeError(\n 'The `component` option has been removed. Resources now derive their ' +\n \"schema from the folder's model. Remove the `component` field from \" +\n 'your call site.',\n );\n }\n const key = resolveKey(folderKey);\n const params: Record<string, string> = { external_id: options.externalId };\n return this.request('PUT', `${this.paths.resourceBase(key)}/`, {\n params,\n jsonBody: payload,\n });\n }\n\n async batchUpsertResources(\n folderKey: FolderRef,\n items: BatchUpsertItem[],\n options?: {\n maxConcurrency?: number;\n failFast?: boolean;\n onProgress?: (completed: number, total: number) => void;\n },\n ): Promise<BatchUpsertResult> {\n // Defensive runtime check: TypeScript callers are protected by the interface\n // but JS callers (or TS callers using `as any`) can still pass `component`\n // on individual items. Fail loudly so the migration is obvious.\n for (const item of items) {\n if (item && typeof item === 'object' && 'component' in item) {\n throw new TypeError(\n 'BatchUpsertItem.component has been removed. Resources now derive ' +\n \"their schema from the folder's model. Remove the `component` \" +\n 'field from your batch items.',\n );\n }\n }\n const fKey = resolveKey(folderKey);\n const maxConcurrency = options?.maxConcurrency ?? 5;\n if (maxConcurrency < 1) {\n throw new Error('maxConcurrency must be at least 1');\n }\n if (items.length === 0) {\n return { succeeded: [], failed: [] };\n }\n const failFast = options?.failFast ?? false;\n const onProgress = options?.onProgress;\n\n const succeeded: ResourceSummary[] = [];\n const failed: BatchItemError[] = [];\n let completed = 0;\n\n const queue = [...items.entries()];\n\n const processItem = async (index: number, item: BatchUpsertItem): Promise<void> => {\n try {\n const params: Record<string, string> = { external_id: item.external_id };\n const result: ResourceSummary = await this.request(\n 'PUT',\n `${this.paths.resourceBase(fKey)}/`,\n { params, jsonBody: item.payload },\n );\n succeeded.push(result);\n } catch (err) {\n failed.push({\n index,\n external_id: item.external_id,\n error: err instanceof Error ? err : new Error(String(err)),\n });\n if (failFast) {\n throw err;\n }\n } finally {\n completed++;\n onProgress?.(completed, items.length);\n }\n };\n\n // Process in batches of maxConcurrency\n let i = 0;\n while (i < queue.length) {\n const batch = queue.slice(i, i + maxConcurrency);\n try {\n await Promise.all(batch.map(([index, item]) => processItem(index, item)));\n } catch (err) {\n if (failFast) throw err;\n }\n i += maxConcurrency;\n }\n\n return { succeeded, failed };\n }\n\n async updateResource(\n folderKey: FolderRef,\n resourceKey: ResourceRef,\n payload: Record<string, any>,\n ): Promise<ResourceSummary> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n await this.request('PUT', `${this.paths.resourceBase(fKey)}/${rKey}/`, {\n jsonBody: payload,\n parseJson: false,\n });\n return this.getResource(fKey, rKey);\n }\n\n async deleteResource(folderKey: FolderRef, resourceKey: ResourceRef): Promise<void> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n await this.request('DELETE', `${this.paths.resourceBase(fKey)}/${rKey}/`, {\n parseJson: false,\n });\n }\n\n async getResourceData(\n folderKey: FolderRef,\n resourceKey: ResourceRef,\n ): Promise<Record<string, any>> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n return this.request('GET', `${this.paths.resourceBase(fKey)}/${rKey}/data/`);\n }\n\n // ------------------------------------------------------------------ //\n // Revision operations\n // ------------------------------------------------------------------ //\n\n async listRevisions(\n folderKey: FolderRef,\n resourceKey: ResourceRef,\n params?: Record<string, any>,\n ): Promise<RevisionList> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n return this.request('GET', `${this.paths.revisionBase(fKey, rKey)}/`, { params });\n }\n\n async createRevision(\n folderKey: FolderRef,\n resourceKey: ResourceRef,\n payload: Record<string, any>,\n ): Promise<RevisionSummary> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n return this.request('POST', `${this.paths.revisionBase(fKey, rKey)}/`, {\n jsonBody: payload,\n });\n }\n\n async getRevision(\n folderKey: FolderRef,\n resourceKey: ResourceRef,\n revisionKey: RevisionRef,\n ): Promise<RevisionSummary> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n const rvKey = resolveKey(revisionKey);\n return this.request('GET', `${this.paths.revisionBase(fKey, rKey)}/${rvKey}/`);\n }\n\n async updateRevision(\n folderKey: FolderRef,\n resourceKey: ResourceRef,\n revisionKey: RevisionRef,\n payload: Record<string, any>,\n ): Promise<RevisionSummary> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n const rvKey = resolveKey(revisionKey);\n return this.request('PUT', `${this.paths.revisionBase(fKey, rKey)}/${rvKey}/`, {\n jsonBody: payload,\n });\n }\n\n async deleteRevision(\n folderKey: FolderRef,\n resourceKey: ResourceRef,\n revisionKey: RevisionRef,\n ): Promise<void> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n const rvKey = resolveKey(revisionKey);\n await this.request('DELETE', `${this.paths.revisionBase(fKey, rKey)}/${rvKey}/`, {\n parseJson: false,\n });\n }\n\n async publishRevision(\n folderKey: FolderRef,\n resourceKey: ResourceRef,\n revisionKey: RevisionRef,\n payload?: Record<string, any>,\n ): Promise<RevisionSummary> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n const rvKey = resolveKey(revisionKey);\n return this.request(\n 'POST',\n `${this.paths.revisionBase(fKey, rKey)}/${rvKey}/publish/`,\n payload ? { jsonBody: payload } : undefined,\n );\n }\n\n async validateRevision(\n folderKey: FolderRef,\n resourceKey: ResourceRef,\n revisionKey: RevisionRef,\n ): Promise<Record<string, any>> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n const rvKey = resolveKey(revisionKey);\n return this.request('POST', `${this.paths.revisionBase(fKey, rKey)}/${rvKey}/validate/`);\n }\n\n async getRevisionData(\n folderKey: FolderRef,\n resourceKey: ResourceRef,\n revisionKey: RevisionRef,\n ): Promise<Record<string, any>> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n const rvKey = resolveKey(revisionKey);\n return this.request('GET', `${this.paths.revisionBase(fKey, rKey)}/${rvKey}/data/`);\n }\n\n // ------------------------------------------------------------------ //\n // Locale operations\n // ------------------------------------------------------------------ //\n\n async listLocales(): Promise<LocaleList> {\n const payload = (await this.request('GET', `${this.paths.localesRoot()}/`)) ?? [];\n return Array.isArray(payload) ? payload : [payload];\n }\n\n async createLocale(payload: Record<string, any>): Promise<LocaleSummary> {\n return this.request('POST', `${this.paths.localesRoot()}/`, { jsonBody: payload });\n }\n\n async getLocale(code: string): Promise<LocaleSummary> {\n return this.request('GET', `${this.paths.localeRoot(code)}/`);\n }\n\n async updateLocale(code: string, payload: Record<string, any>): Promise<LocaleSummary> {\n return this.request('PUT', `${this.paths.localeRoot(code)}/`, { jsonBody: payload });\n }\n\n async deleteLocale(code: string): Promise<void> {\n await this.request('DELETE', `${this.paths.localeRoot(code)}/`, { parseJson: false });\n }\n\n // ------------------------------------------------------------------ //\n // Project operations\n // ------------------------------------------------------------------ //\n\n async listProjects(orgKey: OrgRef, params?: Record<string, any>): Promise<ProjectList> {\n const key = resolveKey(orgKey);\n return this.request('GET', `${this.paths.projectsBase(key)}/`, { params });\n }\n\n async getProject(orgKey: OrgRef, projectKey: ProjectRef): Promise<ProjectSummary> {\n const oKey = resolveKey(orgKey);\n const pKey = resolveKey(projectKey);\n return this.request('GET', `${this.paths.projectRoot(oKey, pKey)}/`);\n }\n\n async createProject(orgKey: OrgRef, payload: Record<string, any>): Promise<ProjectSummary> {\n const key = resolveKey(orgKey);\n return this.request('POST', `${this.paths.projectsBase(key)}/`, { jsonBody: payload });\n }\n\n async updateProject(\n orgKey: OrgRef,\n projectKey: ProjectRef,\n payload: Record<string, any>,\n ): Promise<ProjectSummary> {\n const oKey = resolveKey(orgKey);\n const pKey = resolveKey(projectKey);\n return this.request('PUT', `${this.paths.projectRoot(oKey, pKey)}/`, {\n jsonBody: payload,\n });\n }\n\n async deleteProject(orgKey: OrgRef, projectKey: ProjectRef): Promise<void> {\n const oKey = resolveKey(orgKey);\n const pKey = resolveKey(projectKey);\n await this.request('DELETE', `${this.paths.projectRoot(oKey, pKey)}/`, {\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Environment operations\n // ------------------------------------------------------------------ //\n\n async listEnvironments(orgKey: OrgRef, projectKey: ProjectRef): Promise<EnvironmentList> {\n const oKey = resolveKey(orgKey);\n const pKey = resolveKey(projectKey);\n const payload =\n (await this.request('GET', `${this.paths.environmentsBase(oKey, pKey)}/`)) ?? [];\n if (Array.isArray(payload)) {\n return payload;\n }\n if (payload && typeof payload === 'object' && 'results' in payload) {\n return (payload as { results: EnvironmentSummary[] }).results;\n }\n return [payload];\n }\n\n async getEnvironment(\n orgKey: OrgRef,\n projectKey: ProjectRef,\n envKey: EnvironmentRef,\n ): Promise<EnvironmentSummary> {\n const oKey = resolveKey(orgKey);\n const pKey = resolveKey(projectKey);\n const eKey = resolveKey(envKey);\n return this.request('GET', `${this.paths.environmentRoot(oKey, pKey, eKey)}/`);\n }\n\n async createEnvironment(\n orgKey: OrgRef,\n projectKey: ProjectRef,\n payload: Record<string, any>,\n ): Promise<EnvironmentSummary> {\n const oKey = resolveKey(orgKey);\n const pKey = resolveKey(projectKey);\n return this.request('POST', `${this.paths.environmentsBase(oKey, pKey)}/`, {\n jsonBody: payload,\n });\n }\n\n async updateEnvironment(\n orgKey: OrgRef,\n projectKey: ProjectRef,\n envKey: EnvironmentRef,\n payload: Record<string, any>,\n ): Promise<EnvironmentSummary> {\n const oKey = resolveKey(orgKey);\n const pKey = resolveKey(projectKey);\n const eKey = resolveKey(envKey);\n return this.request('PUT', `${this.paths.environmentRoot(oKey, pKey, eKey)}/`, {\n jsonBody: payload,\n });\n }\n\n async deleteEnvironment(\n orgKey: OrgRef,\n projectKey: ProjectRef,\n envKey: EnvironmentRef,\n ): Promise<void> {\n const oKey = resolveKey(orgKey);\n const pKey = resolveKey(projectKey);\n const eKey = resolveKey(envKey);\n await this.request('DELETE', `${this.paths.environmentRoot(oKey, pKey, eKey)}/`, {\n parseJson: false,\n });\n }\n\n async toggleEnvironment(\n orgKey: OrgRef,\n projectKey: ProjectRef,\n envKey: EnvironmentRef,\n isEnabled: boolean,\n ): Promise<void> {\n const oKey = resolveKey(orgKey);\n const pKey = resolveKey(projectKey);\n const eKey = resolveKey(envKey);\n await this.request('POST', `${this.paths.environmentRoot(oKey, pKey, eKey)}/toggle/`, {\n jsonBody: { is_enabled: isEnabled },\n });\n }\n\n async updateEnvironmentProtection(\n orgKey: OrgRef,\n projectKey: ProjectRef,\n envKey: EnvironmentRef,\n options: { protectionLevel: string; protectionReason?: string },\n ): Promise<EnvironmentSummary> {\n const oKey = resolveKey(orgKey);\n const pKey = resolveKey(projectKey);\n const eKey = resolveKey(envKey);\n const body: Record<string, any> = { protection_level: options.protectionLevel };\n if (options.protectionReason) {\n body.protection_reason = options.protectionReason;\n }\n return this.request('PATCH', `${this.paths.environmentRoot(oKey, pKey, eKey)}/protection/`, {\n jsonBody: body,\n });\n }\n\n async clearEnvironmentProtection(\n orgKey: OrgRef,\n projectKey: ProjectRef,\n envKey: EnvironmentRef,\n ): Promise<EnvironmentSummary> {\n return this.updateEnvironmentProtection(orgKey, projectKey, envKey, {\n protectionLevel: 'none',\n });\n }\n\n // ------------------------------------------------------------------ //\n // Files\n // ------------------------------------------------------------------ //\n\n /**\n * List a files collection's upload links, newest first. `params` carries `limit` (at\n * most 100), `offset` and `state`: `active`, `ended` or `all` (the default).\n */\n async listUploadLinks(\n collectionKey: CollectionRef,\n params?: Record<string, any>,\n ): Promise<UploadLinkList> {\n const key = resolveKey(collectionKey);\n return this.request('GET', `${this.paths.uploadLinksRoot(key)}/`, { params });\n }\n\n /**\n * Create an upload link: a hosted page where an end user adds files.\n *\n * The collection must be strict. Works with a user token or a Management API\n * key of this environment. Read the link back with {@link getUploadLink}; the\n * Flux upload status answers only the Flux key that started an upload, never\n * a link made here.\n *\n * `upload_url` carries the link's token and is returned only by this call.\n */\n async createUploadLink(\n collectionKey: CollectionRef,\n request: UploadLinkCreateRequest,\n ): Promise<UploadLinkCreated> {\n const key = resolveKey(collectionKey);\n return this.transport.request('POST', `${this.paths.uploadLinksRoot(key)}/`, {\n jsonBody: { ...request, owner: resolveKey(request.owner) },\n allowRetries: false,\n });\n }\n\n /** Read one upload link with its sessions and the status of each file. */\n async getUploadLink(collectionKey: CollectionRef, uploadId: string): Promise<UploadLink> {\n const key = resolveKey(collectionKey);\n return this.request('GET', `${this.paths.uploadLinkRoot(key, uploadId)}/`);\n }\n\n /**\n * Revoke an upload link. Revoking a revoked link returns the same state. Files\n * already uploaded through the link are not affected.\n */\n async revokeUploadLink(collectionKey: CollectionRef, uploadId: string): Promise<UploadLink> {\n const key = resolveKey(collectionKey);\n return this.request('POST', `${this.paths.uploadLinkRoot(key, uploadId)}/revoke/`);\n }\n\n /** Read a record's file: its verdict, the checks that ran and every finding. */\n async getFileAnalysis(\n collectionKey: CollectionRef,\n resourceKey: ResourceRef,\n ): Promise<FileRecordView> {\n const root = this.fileRoot(collectionKey, resourceKey);\n return this.request('GET', `${root}/analysis/`);\n }\n\n /**\n * Release a file held for a reviewer.\n *\n * The answer's `outcome` says what happened; a publish that goes back through\n * processing completes on its own. A file no reviewer holds is\n * `409 file_not_in_review`, `file_not_ready` or `file_erased`.\n */\n async approveFile(\n collectionKey: CollectionRef,\n resourceKey: ResourceRef,\n ): Promise<FileRecordView> {\n const root = this.fileRoot(collectionKey, resourceKey);\n return this.transport.request('POST', `${root}/approve/`, { allowRetries: false });\n }\n\n /** Reject a file held for a reviewer. Repeating it returns the same state. */\n async rejectFile(\n collectionKey: CollectionRef,\n resourceKey: ResourceRef,\n ): Promise<FileRecordView> {\n const root = this.fileRoot(collectionKey, resourceKey);\n return this.request('POST', `${root}/reject/`);\n }\n\n /**\n * Analyze a file again under the collection's live policy.\n *\n * Accepted work runs in the background; a published generation keeps serving\n * until the new one publishes. A `storage_only` collection answers\n * `409 reanalysis_requires_agent_ready`. This is paid processing: a refusal over\n * the plan throws {@link FilesQuotaExceededError}, a quota that cannot be read\n * throws {@link FilesQuotaUnavailableError}, and over a budget is `429`.\n */\n async reanalyzeFile(\n collectionKey: CollectionRef,\n resourceKey: ResourceRef,\n ): Promise<FileRecordView> {\n const root = this.fileRoot(collectionKey, resourceKey);\n return this.transport.request('POST', `${root}/reanalyze/`, { allowRetries: false });\n }\n\n /**\n * Get a short-lived link to a record's original file.\n *\n * A state that cannot be downloaded now is a `409`: `detail.reason` of the\n * thrown error names it. Check `warnings` before opening the file.\n */\n async getFileOriginal(\n collectionKey: CollectionRef,\n resourceKey: ResourceRef,\n ): Promise<FileDownload> {\n const root = this.fileRoot(collectionKey, resourceKey);\n return this.request('GET', `${root}/file/original/`);\n }\n\n /**\n * Get a short-lived link to a record's safe copy. It is an image-only PDF, or a PNG\n * for an image: read `content_type`.\n */\n async getFileSafeCopy(\n collectionKey: CollectionRef,\n resourceKey: ResourceRef,\n ): Promise<FileDownload> {\n const root = this.fileRoot(collectionKey, resourceKey);\n return this.request('GET', `${root}/file/safe-copy/`);\n }\n\n /** Get a short-lived link to the redacted PNG of one page. */\n async getFilePage(\n collectionKey: CollectionRef,\n resourceKey: ResourceRef,\n page: number,\n ): Promise<FileDownload> {\n const root = this.fileRoot(collectionKey, resourceKey);\n return this.request('GET', `${root}/file/pages/${page}/`);\n }\n\n /**\n * Read one page: its redacted image, what was withheld, its tables and the\n * text an agent receives.\n */\n async getFilePageDetail(\n collectionKey: CollectionRef,\n resourceKey: ResourceRef,\n page: number,\n ): Promise<FilePageDetail> {\n const root = this.fileRoot(collectionKey, resourceKey);\n return this.request('GET', `${root}/file/pages/${page}/detail/`);\n }\n\n /** List a collection's blocked and rejected files, newest first. */\n async listFileTombstones(\n collectionKey: CollectionRef,\n params?: Record<string, any>,\n ): Promise<FileTombstoneList> {\n const key = resolveKey(collectionKey);\n return this.request('GET', `${this.paths.fileTombstonesRoot(key)}/`, { params });\n }\n\n /** Read a collection's live files policy. */\n async getFilesPolicy(collectionKey: CollectionRef): Promise<FilesPolicy> {\n const key = resolveKey(collectionKey);\n return this.request('GET', `${this.paths.filesPolicyRoot(key)}/`);\n }\n\n /**\n * Replace a collection's files policy with a new version.\n *\n * A full replacement: an omitted field takes its default. Sending the live\n * body again creates no version.\n */\n async updateFilesPolicy(\n collectionKey: CollectionRef,\n payload: FilesPolicyBody,\n ): Promise<FilesPolicy> {\n const key = resolveKey(collectionKey);\n return this.request('PUT', `${this.paths.filesPolicyRoot(key)}/`, { jsonBody: payload });\n }\n\n /**\n * List the files held for a reviewer in this environment, newest first.\n *\n * `collection` narrows the queue to one collection; one the caller cannot read,\n * or that does not exist, is an empty page. `params` carries `limit` (at most\n * 100) and `offset`.\n */\n async listFileReviewQueue(options?: {\n collection?: CollectionRef;\n params?: Record<string, any>;\n }): Promise<FileReviewQueue> {\n const params = { ...options?.params };\n if (options?.collection !== undefined) {\n params.collection = resolveKey(options.collection);\n }\n return this.request('GET', `${this.paths.filesReviewRoot()}/`, { params });\n }\n\n /**\n * Read what the authenticated caller may do in this environment.\n *\n * Works for a user token and for a Management API key of this environment. A caller\n * with no grants at all is a `403`; a key of another environment is a\n * `404 environment_not_found`.\n */\n async getMyPermissions(): Promise<MyPermissions> {\n return this.request('GET', `${this.paths.myPermissionsRoot()}/`);\n }\n\n private fileRoot(collectionKey: CollectionRef, resourceKey: ResourceRef): string {\n return this.paths.fileRoot(resolveKey(collectionKey), resolveKey(resourceKey));\n }\n}\n","/**\n * Types and validation for Flux vector search requests.\n */\n\n/** Search mode for the Flux search endpoint. */\nexport const SearchMode = {\n TEXT: 'text',\n VECTOR: 'vector',\n VECTOR_BOOSTED: 'vector_boosted',\n HYBRID: 'hybrid',\n} as const;\n\nexport type SearchMode = (typeof SearchMode)[keyof typeof SearchMode];\n\n/** Configuration for auto-generated embedding search. */\nexport interface VectorSearch {\n query: string;\n fields?: string[];\n top_k?: number;\n similarity_threshold?: number;\n}\n\n/** Configuration for custom pre-computed embedding search. */\nexport interface VectorFieldSearch {\n field: string;\n query_vector: number[];\n top_k?: number;\n similarity_threshold?: number;\n}\n\n/** Configuration for vector-boosted search mode. */\nexport interface VectorBoostConfig {\n boost_factor?: number;\n similarity_threshold?: number;\n max_boost_results?: number;\n}\n\n/** Configuration for hybrid (text + vector) search mode. */\nexport interface HybridConfig {\n vector_weight?: number;\n text_weight?: number;\n rerank_results?: boolean;\n}\n\n/** Full search request payload for the Flux search endpoint. */\nexport interface SearchRequest {\n search_mode?: SearchMode;\n find_text?: Record<string, any>;\n find_phrase?: Record<string, any>;\n vector_search?: VectorSearch;\n vector_field_search?: VectorFieldSearch;\n vector_boost_config?: VectorBoostConfig;\n hybrid_config?: HybridConfig;\n limit?: number;\n offset?: number;\n [extra: string]: any;\n}\n\nconst SEARCH_REQUEST_KNOWN_KEYS = new Set([\n 'search_mode',\n 'find_text',\n 'find_phrase',\n 'vector_search',\n 'vector_field_search',\n 'vector_boost_config',\n 'hybrid_config',\n 'limit',\n 'offset',\n]);\n\nfunction checkFinite(value: number, name: string): void {\n if (!Number.isFinite(value)) {\n throw new Error(`${name} must be a finite number`);\n }\n}\n\nfunction checkThreshold(value: number | undefined, name: string): void {\n if (value != null) {\n checkFinite(value, name);\n if (value < 0 || value > 1) {\n throw new Error(`${name} must be between 0.0 and 1.0`);\n }\n }\n}\n\nfunction checkPositiveInt(value: number | undefined, name: string): void {\n if (value != null) {\n checkFinite(value, name);\n if (!Number.isInteger(value) || value < 1) {\n throw new Error(`${name} must be a positive integer (>= 1)`);\n }\n }\n}\n\nfunction validateVectorSearch(vs: VectorSearch): void {\n checkPositiveInt(vs.top_k, 'top_k');\n checkThreshold(vs.similarity_threshold, 'similarity_threshold');\n}\n\nfunction validateVectorFieldSearch(vfs: VectorFieldSearch): void {\n if (!vfs.query_vector || vfs.query_vector.length === 0) {\n throw new Error('query_vector must not be empty');\n }\n for (let i = 0; i < vfs.query_vector.length; i++) {\n if (!Number.isFinite(vfs.query_vector[i])) {\n throw new Error(`query_vector[${i}] must be a finite number`);\n }\n }\n checkPositiveInt(vfs.top_k, 'top_k');\n checkThreshold(vfs.similarity_threshold, 'similarity_threshold');\n}\n\nfunction validateBoostConfig(cfg: VectorBoostConfig): void {\n if (cfg.boost_factor != null) {\n checkFinite(cfg.boost_factor, 'boost_factor');\n if (cfg.boost_factor <= 0) {\n throw new Error('boost_factor must be > 0');\n }\n }\n checkThreshold(cfg.similarity_threshold, 'similarity_threshold');\n checkPositiveInt(cfg.max_boost_results, 'max_boost_results');\n}\n\nfunction validateHybridConfig(cfg: HybridConfig): void {\n if (cfg.vector_weight != null) {\n checkFinite(cfg.vector_weight, 'vector_weight');\n if (cfg.vector_weight < 0 || cfg.vector_weight > 1) {\n throw new Error('vector_weight must be between 0.0 and 1.0');\n }\n }\n if (cfg.text_weight != null) {\n checkFinite(cfg.text_weight, 'text_weight');\n if (cfg.text_weight < 0 || cfg.text_weight > 1) {\n throw new Error('text_weight must be between 0.0 and 1.0');\n }\n }\n const vw = cfg.vector_weight ?? 0.6;\n const tw = cfg.text_weight ?? 0.4;\n if (Math.abs(vw + tw - 1.0) > 1e-6) {\n throw new Error(`vector_weight + text_weight must equal 1.0, got ${vw + tw}`);\n }\n}\n\n/**\n * Validate a {@link SearchRequest} and return a clean body object (no undefined values).\n *\n * Enforces cross-field constraints:\n * - `vector_search` and `vector_field_search` are mutually exclusive\n * - Each search mode has specific required/forbidden fields\n */\nexport function buildSearchBody(req: SearchRequest): Record<string, any> {\n const mode = req.search_mode ?? SearchMode.TEXT;\n const vs = req.vector_search;\n const vfs = req.vector_field_search;\n const boost = req.vector_boost_config;\n const hybrid = req.hybrid_config;\n const hasText = req.find_text != null || req.find_phrase != null;\n\n // Field-level validation\n if (vs) validateVectorSearch(vs);\n if (vfs) validateVectorFieldSearch(vfs);\n if (boost) validateBoostConfig(boost);\n if (hybrid) validateHybridConfig(hybrid);\n\n // Mutual exclusion\n if (vs && vfs) {\n throw new Error('vector_search and vector_field_search are mutually exclusive');\n }\n\n // Per-mode rules\n if (mode === SearchMode.TEXT) {\n if (vs) throw new Error('vector_search is not allowed in text search mode');\n if (vfs) throw new Error('vector_field_search is not allowed in text search mode');\n if (boost) throw new Error('vector_boost_config is not allowed in text search mode');\n if (hybrid) throw new Error('hybrid_config is not allowed in text search mode');\n } else if (mode === SearchMode.VECTOR) {\n if (!vs && !vfs) {\n throw new Error('vector search mode requires vector_search or vector_field_search');\n }\n if (boost) throw new Error('vector_boost_config is not allowed in vector search mode');\n if (hybrid) throw new Error('hybrid_config is not allowed in vector search mode');\n } else if (mode === SearchMode.VECTOR_BOOSTED) {\n if (!vs && !vfs) {\n throw new Error('vector_boosted mode requires vector_search or vector_field_search');\n }\n if (!hasText) throw new Error('vector_boosted mode requires find_text or find_phrase');\n if (hybrid) throw new Error('hybrid_config is not allowed in vector_boosted mode');\n } else if (mode === SearchMode.HYBRID) {\n if (vfs) throw new Error('vector_field_search is not allowed in hybrid mode');\n if (!vs) throw new Error('hybrid mode requires vector_search');\n if (!hasText) throw new Error('hybrid mode requires find_text or find_phrase');\n if (boost) throw new Error('vector_boost_config is not allowed in hybrid mode');\n } else {\n const validModes = Object.values(SearchMode).join(', ');\n throw new Error(`Unknown search_mode: \"${mode}\". Valid modes: ${validModes}`);\n }\n\n // Build clean body (strip undefined)\n const body: Record<string, any> = {};\n for (const [key, value] of Object.entries(req)) {\n if (value !== undefined) {\n body[key] = value;\n }\n }\n if (!body.search_mode) {\n body.search_mode = mode;\n }\n return body;\n}\n\n/**\n * Merge extra body params, rejecting keys that conflict with SearchRequest fields.\n * @internal\n */\nexport function mergeExtra(\n validated: Record<string, any>,\n extra: Record<string, any>,\n): Record<string, any> {\n if ('truncate_text' in extra) {\n throw new Error(\n \"'truncate_text' is a query parameter, not a body field. Pass it via the 'queryParams' option instead.\",\n );\n }\n const conflicts: string[] = [];\n for (const key of Object.keys(extra)) {\n if (SEARCH_REQUEST_KNOWN_KEYS.has(key)) {\n conflicts.push(key);\n }\n }\n if (conflicts.length > 0) {\n throw new Error(\n `extra keys conflict with SearchRequest fields: ${conflicts.sort().join(', ')}. ` +\n 'Use the explicit parameters instead.',\n );\n }\n return { ...validated, ...extra };\n}\n\n/**\n * A grant for one upload to a files collection.\n *\n * The grant is a credential. The field names are the wire names, so the object\n * can go to a browser as it is, and that same object prints every token: keep it\n * out of logs and error reports.\n */\nexport interface UploadSignature {\n publicKey: string;\n /** The upload host. */\n uploadBaseUrl: string;\n authToken: string;\n /** When the token ends, in Unix seconds. */\n tokenExpire: number;\n /** Passed to the upload unchanged. */\n store: string;\n /** Passed to the upload unchanged. */\n metadata: Record<string, unknown>;\n /** The id to poll with {@link FluxClient.getUploadStatus}. */\n upload_id: string;\n /** The end user's token for reading the status. */\n status_token: string;\n /** The order of status tokens in a session. */\n rotation: number;\n}\n\n/**\n * The status of one file of an upload.\n *\n * A key sees `state` as `processing`, `ready` (with `record_key`),\n * `pending_review` or `rejected` (with `public_reason`). A status token sees\n * `processing`, `accepted` or `rejected`, with `user_status`, `reason` and `slot`.\n */\nexport interface UploadFileStatus {\n state: string;\n record_key?: string | null;\n public_reason?: string;\n user_status?: string;\n reason?: string;\n slot?: number;\n}\n\n/**\n * The status of an upload.\n *\n * For an upload of one file these are that file's fields. For a link of several\n * files, `state` is `processing` or `done` and `files` and `remaining` are set; a\n * status token also gets `slots_uploading`.\n */\nexport interface UploadStatus extends UploadFileStatus {\n files?: UploadFileStatus[];\n remaining?: number;\n slots_uploading?: { slot: number }[];\n}\n","import type { AuthStrategy } from '../auth/types.js';\nimport type { RetryConfig } from '../config.js';\nimport { createConfig } from '../config.js';\nimport { HttpTransport } from '../http.js';\nimport type {\n HybridConfig,\n SearchRequest,\n UploadSignature,\n UploadStatus,\n VectorBoostConfig,\n VectorFieldSearch,\n VectorSearch,\n} from './models.js';\nimport { SearchMode, buildSearchBody, mergeExtra } from './models.js';\n\nfunction cleanPrefix(prefix: string): string {\n const value = prefix.replace(/^\\/+|\\/+$/g, '');\n if (!value) {\n throw new Error('apiPrefix cannot be empty');\n }\n return value;\n}\n\nfunction normalizeFolderPath(folderPath: string): string {\n return folderPath.replace(/^\\/+|\\/+$/g, '');\n}\n\nexport interface FluxClientOptions {\n baseUrl: string;\n apiPrefix: string;\n auth: AuthStrategy;\n timeout?: number;\n retryConfig?: RetryConfig;\n defaultHeaders?: Record<string, string>;\n}\n\nexport interface VectorSearchOptions {\n query: string;\n fields?: string[];\n top_k?: number;\n similarity_threshold?: number;\n limit?: number;\n offset?: number;\n /**\n * Query-string parameters for the underlying `search()` call (e.g.\n * `{ truncate_text: 200 }`). Named `queryParams`, not `params`: this\n * options object also carries an index signature that funnels unknown\n * keys into the JSON body, and an explicit `params` field would silently\n * reroute an existing `params` body extra to the query string.\n */\n queryParams?: Record<string, any>;\n [extra: string]: any;\n}\n\nexport interface VectorFieldSearchOptions {\n field: string;\n query_vector: number[];\n top_k?: number;\n similarity_threshold?: number;\n limit?: number;\n offset?: number;\n /** See {@link VectorSearchOptions.queryParams}. */\n queryParams?: Record<string, any>;\n [extra: string]: any;\n}\n\nexport interface HybridSearchOptions {\n query: string;\n find_text: Record<string, any>;\n fields?: string[];\n top_k?: number;\n similarity_threshold?: number;\n vector_weight?: number;\n text_weight?: number;\n rerank_results?: boolean;\n limit?: number;\n offset?: number;\n /** See {@link VectorSearchOptions.queryParams}. */\n queryParams?: Record<string, any>;\n [extra: string]: any;\n}\n\nexport interface BoostedSearchOptions {\n find_text: Record<string, any>;\n query?: string;\n field?: string;\n query_vector?: number[];\n top_k?: number;\n similarity_threshold?: number;\n boost_factor?: number;\n boost_similarity_threshold?: number;\n max_boost_results?: number;\n limit?: number;\n offset?: number;\n /** See {@link VectorSearchOptions.queryParams}. */\n queryParams?: Record<string, any>;\n [extra: string]: any;\n}\n\nfunction stripUndefined(obj: Record<string, any>): Record<string, any> {\n const result: Record<string, any> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (value !== undefined) {\n result[key] = value;\n }\n }\n return result;\n}\n\n/**\n * Client for FoxNose Flux delivery APIs.\n *\n * All methods are async and return parsed JSON responses.\n */\nexport class FluxClient {\n readonly apiPrefix: string;\n private readonly transport: HttpTransport;\n\n constructor(options: FluxClientOptions) {\n this.apiPrefix = cleanPrefix(options.apiPrefix);\n const config = createConfig({\n baseUrl: options.baseUrl,\n timeout: options.timeout ?? 15_000,\n defaultHeaders: options.defaultHeaders,\n });\n this.transport = new HttpTransport({\n config,\n auth: options.auth,\n retryConfig: options.retryConfig,\n });\n }\n\n private buildPath(folderPath: string, suffix = ''): string {\n const folder = normalizeFolderPath(folderPath);\n const base = `/${this.apiPrefix}/${folder}`;\n return suffix ? `${base}${suffix}` : base;\n }\n\n async listResources<T = any>(folderPath: string, params?: Record<string, any>): Promise<T> {\n const path = this.buildPath(folderPath);\n return this.transport.request('GET', path, { params });\n }\n\n async getResource<T = any>(\n folderPath: string,\n resourceKey: string,\n params?: Record<string, any>,\n ): Promise<T> {\n const path = this.buildPath(folderPath, `/${resourceKey}`);\n return this.transport.request('GET', path, { params });\n }\n\n async search<T = any>(\n folderPath: string,\n body: Record<string, any>,\n options?: { params?: Record<string, any> },\n ): Promise<T> {\n const path = this.buildPath(folderPath, '/_search');\n return this.transport.request('POST', path, { jsonBody: body, params: options?.params });\n }\n\n /**\n * Create a resource in a collection and publish it immediately.\n *\n * `folderPath` is the collection path (e.g. `articles` or a nested path such\n * as `users/usr_1/memories`). `options.key` is an optional external\n * identifier for deduplication — reusing an existing key raises\n * {@link ExternalIdConflictError}. The response carries `resource_key`,\n * `revision_key`, `write_units`, and `published`.\n *\n * Writes require an authenticated key with write access: an anonymous caller\n * gets 401, a key without the `create` grant gets a generic 403\n * (`access_denied`), and a collection whose connection does not allow writes\n * raises {@link CollectionNotWritableError}.\n *\n * Writes are never retried automatically: a failed write's outcome is\n * unknown, so re-read with a GET before retrying.\n */\n async createResource<T = any>(\n folderPath: string,\n data: Record<string, any>,\n options?: { key?: string },\n ): Promise<T> {\n const path = this.buildPath(folderPath, '/');\n const body: Record<string, any> = { data };\n if (options?.key !== undefined) {\n body.key = options.key;\n }\n return this.transport.request('POST', path, { jsonBody: body, allowRetries: false });\n }\n\n /**\n * Replace a resource's document and publish a new revision. This is a\n * full-document replace, not a partial merge: fields absent from `data` are\n * removed.\n *\n * Writes require an authenticated key with write access: an anonymous caller\n * gets 401, a key without the `update` grant gets a generic 403\n * (`access_denied`), and a collection whose connection does not allow writes\n * raises {@link CollectionNotWritableError}. Like {@link createResource}, it\n * is never retried automatically.\n */\n async updateResource<T = any>(\n folderPath: string,\n resourceKey: string,\n data: Record<string, any>,\n ): Promise<T> {\n const path = this.buildPath(folderPath, `/${resourceKey}/`);\n return this.transport.request('PUT', path, { jsonBody: { data }, allowRetries: false });\n }\n\n /**\n * Get a grant for one upload to a files collection.\n *\n * The grant is a credential: pass it on, do not log it. For a strict collection\n * `folderPath` names the owner, e.g. `support/tickets/tk_1/attachments`. Needs a\n * key with create access to the collection.\n *\n * `options.sessionKey` is an optional idempotency key of 43 URL-safe characters:\n * a repeat with the same key, collection and owner reaches the same upload\n * session. A failed request is never retried automatically, so send one to\n * retry safely.\n */\n async createUploadSignature(\n folderPath: string,\n options?: { sessionKey?: string },\n ): Promise<UploadSignature> {\n const path = this.buildPath(folderPath, '/_upload-signature');\n const sessionKey = options?.sessionKey;\n return this.transport.request('POST', path, {\n jsonBody: sessionKey === undefined ? undefined : { session_key: sessionKey },\n allowRetries: false,\n });\n }\n\n /**\n * Read the status of an upload.\n *\n * A key reads the uploads that key started, and the path must name the same\n * collection and owner. Any other combination is `404 not_found`, which includes\n * a link made through the Management API: read that one with\n * `ManagementClient.getUploadLink`.\n *\n * `options.statusToken` is the end user's token from the grant, for a client that\n * holds no key (use `AnonymousAuth`). It answers the end user's view, which never\n * carries a record key. A request authenticated by a key ignores it.\n */\n async getUploadStatus(\n folderPath: string,\n uploadId: string,\n options?: { statusToken?: string },\n ): Promise<UploadStatus> {\n const path = this.buildPath(folderPath, `/_uploads/${encodeURIComponent(uploadId)}`);\n const statusToken = options?.statusToken;\n return this.transport.request('GET', path, {\n headers: statusToken === undefined ? undefined : { 'X-Upload-Status-Token': statusToken },\n });\n }\n\n /** Semantic search using auto-generated embeddings. */\n async vectorSearch<T = any>(folderPath: string, options: VectorSearchOptions): Promise<T> {\n const {\n query,\n fields,\n top_k = 10,\n similarity_threshold,\n limit,\n offset,\n queryParams,\n ...rest\n } = options;\n const extra = stripUndefined(rest);\n const vs: VectorSearch = { query, fields, top_k, similarity_threshold };\n const req: SearchRequest = {\n search_mode: SearchMode.VECTOR,\n vector_search: vs,\n limit,\n offset,\n };\n const body = mergeExtra(buildSearchBody(req), extra);\n return this.search(folderPath, body, { params: queryParams });\n }\n\n /** Search using custom pre-computed embeddings. */\n async vectorFieldSearch<T = any>(\n folderPath: string,\n options: VectorFieldSearchOptions,\n ): Promise<T> {\n const {\n field,\n query_vector,\n top_k = 10,\n similarity_threshold,\n limit,\n offset,\n queryParams,\n ...rest\n } = options;\n const extra = stripUndefined(rest);\n const vfs: VectorFieldSearch = { field, query_vector, top_k, similarity_threshold };\n const req: SearchRequest = {\n search_mode: SearchMode.VECTOR,\n vector_field_search: vfs,\n limit,\n offset,\n };\n const body = mergeExtra(buildSearchBody(req), extra);\n return this.search(folderPath, body, { params: queryParams });\n }\n\n /** Blended text + vector search with configurable weights. */\n async hybridSearch<T = any>(folderPath: string, options: HybridSearchOptions): Promise<T> {\n const {\n query,\n find_text,\n fields,\n top_k = 10,\n similarity_threshold,\n vector_weight = 0.6,\n text_weight = 0.4,\n rerank_results = true,\n limit,\n offset,\n queryParams,\n ...rest\n } = options;\n const extra = stripUndefined(rest);\n const vs: VectorSearch = { query, fields, top_k, similarity_threshold };\n const hybrid: HybridConfig = { vector_weight, text_weight, rerank_results };\n const req: SearchRequest = {\n search_mode: SearchMode.HYBRID,\n find_text,\n vector_search: vs,\n hybrid_config: hybrid,\n limit,\n offset,\n };\n const body = mergeExtra(buildSearchBody(req), extra);\n return this.search(folderPath, body, { params: queryParams });\n }\n\n /** Text search with results boosted by vector similarity. */\n async boostedSearch<T = any>(folderPath: string, options: BoostedSearchOptions): Promise<T> {\n const {\n find_text,\n query,\n field,\n query_vector,\n top_k = 10,\n similarity_threshold,\n boost_factor = 1.5,\n boost_similarity_threshold,\n max_boost_results = 20,\n limit,\n offset,\n queryParams,\n ...rest\n } = options;\n const extra = stripUndefined(rest);\n\n const hasAuto = query != null;\n const hasCustom = field != null || query_vector != null;\n\n if (hasAuto && hasCustom) {\n throw new Error(\n \"Provide either 'query' for auto-generated embeddings \" +\n \"or 'field' + 'query_vector' for custom embeddings, not both\",\n );\n }\n\n let vs: VectorSearch | undefined;\n let vfs: VectorFieldSearch | undefined;\n\n if (hasAuto) {\n vs = { query: query!, top_k, similarity_threshold };\n } else if (field != null && query_vector != null) {\n vfs = { field, query_vector, top_k, similarity_threshold };\n } else {\n throw new Error(\n \"Provide either 'query' for auto-generated embeddings \" +\n \"or 'field' + 'query_vector' for custom embeddings\",\n );\n }\n\n const boostConfig: VectorBoostConfig = {\n boost_factor,\n similarity_threshold: boost_similarity_threshold,\n max_boost_results,\n };\n\n const req: SearchRequest = {\n search_mode: SearchMode.VECTOR_BOOSTED,\n find_text,\n vector_search: vs,\n vector_field_search: vfs,\n vector_boost_config: boostConfig,\n limit,\n offset,\n };\n const body = mergeExtra(buildSearchBody(req), extra);\n return this.search(folderPath, body, { params: queryParams });\n }\n\n async getRouter<T = any>(): Promise<T> {\n const path = `/${this.apiPrefix}/_router`;\n return this.transport.request('GET', path);\n }\n\n async getSchema<T = any>(folderPath: string): Promise<T> {\n const path = this.buildPath(folderPath, '/_schema');\n return this.transport.request('GET', path);\n }\n\n close(): void {\n this.transport.close();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKO,IAAM,gBAAN,MAA4C;AAAA,EACjD,aAAa,UAA+C;AAC1D,WAAO,CAAC;AAAA,EACV;AACF;;;ACJO,IAAM,sBAAN,MAAmD;AAAA,EACxD,YAA6B,OAAe;AAAf;AAAA,EAAgB;AAAA,EAE7C,WAAmB;AACjB,WAAO,KAAK;AAAA,EACd;AACF;AAKO,IAAM,UAAN,MAAM,SAAgC;AAAA,EAC1B;AAAA,EACA;AAAA,EAEjB,YAAY,UAAyB,SAA+B;AAClE,SAAK,WAAW;AAChB,SAAK,SAAS,SAAS,UAAU;AAAA,EACnC;AAAA,EAEA,aAAa,UAA+C;AAC1D,UAAM,QAAQ,KAAK,SAAS,SAAS;AACrC,QAAI,CAAC,OAAO;AACV,YAAM,IAAI,MAAM,wCAAwC;AAAA,IAC1D;AACA,WAAO,EAAE,eAAe,GAAG,KAAK,MAAM,IAAI,KAAK,GAAG;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA,EAKA,OAAO,gBAAgB,OAAe,SAAwC;AAC5E,WAAO,IAAI,SAAQ,IAAI,oBAAoB,KAAK,GAAG,OAAO;AAAA,EAC5D;AACF;;;ACvCA,yBAAuC;;;ACGhC,IAAM,eAAN,cAA2B,MAAM;AAAA,EACtC,YAAY,SAAiB;AAC3B,UAAM,OA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ACrB;AAAA,MACA;AAAA,IACF;AACA,UAAM,OAAO,WAAW,gBAAgB,GAAG,GAAG,KAAK;AACnD,WAAO,KAAK,OAAO,YAAY,MAAM,EAAE,QAAQ,YAAY,CAAC;AAAA,EAC9D;AAAA,EAEA,MAAM,YAAiC;AACrC,UAAM,OAAO,IAAI,KAAK,SAAS;AAC/B,WAAO,KAAK,UAAU,QAAQ,OAAO,IAAI;AAAA,EAC3C;AAAA,EAEA,MAAM,UAAmB,YAAgC;AACvD,UAAM,OAAO,KAAK,UAAU,YAAY,UAAU;AAClD,WAAO,KAAK,UAAU,QAAQ,OAAO,IAAI;AAAA,EAC3C;AAAA,EAEA,QAAc;AACZ,SAAK,UAAU,MAAM;AAAA,EACvB;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts","../src/auth/anonymous.ts","../src/auth/jwt.ts","../src/auth/secure.ts","../src/errors.ts","../src/auth/simple.ts","../src/tenantTokens.ts","../src/config.ts","../src/http.ts","../src/_deprecation.ts","../src/management/models.ts","../src/management/paths.ts","../src/management/client.ts","../src/flux/models.ts","../src/flux/client.ts","../src/flux/trust.ts"],"sourcesContent":["// Auth\nexport {\n AnonymousAuth,\n JWTAuth,\n SecureKeyAuth,\n SimpleKeyAuth,\n StaticTokenProvider,\n} from './auth/index.js';\nexport type { AuthStrategy, RequestData, TokenProvider } from './auth/index.js';\n\n// Tenant tokens\nexport {\n TENANT_TOKEN_PREFIX,\n TenantTokenAuth,\n TenantTokenSource,\n bearerErrors,\n generateTenantSigningKey,\n isInvalidTokenChallenge,\n signTenantToken,\n tenantTokenFetch,\n} from './tenantTokens.js';\nexport type {\n SignTenantTokenOptions,\n TenantPrivateKey,\n TenantSigningKeyPair,\n TenantTokenAnchor,\n TenantTokenFetchOptions,\n TenantTokenSourceOptions,\n} from './tenantTokens.js';\n\n// Config\nexport type { FoxnoseConfig, RetryConfig } from './config.js';\nexport { createConfig, DEFAULT_RETRY_CONFIG, DEFAULT_USER_AGENT, SDK_VERSION } from './config.js';\n\n// Errors\nexport {\n FoxnoseError,\n FoxnoseAPIError,\n FoxnoseAuthError,\n FoxnoseTransportError,\n SpendCapExceededError,\n PlanExhaustedError,\n FilesQuotaExceededError,\n FilesQuotaUnavailableError,\n PlanLimitExceededError,\n RateLimitExceededError,\n CollectionNotWritableError,\n ExternalIdConflictError,\n ContentValidationFailedError,\n UpstreamError,\n WebhookEndpointNotFoundError,\n WebhookEventNotFoundError,\n WebhookEndpointLimitExceededError,\n WebhookEndpointNotActiveError,\n WebhookEndpointNotSubscribedError,\n} from './errors.js';\n\n// HTTP Transport\nexport { HttpTransport } from './http.js';\n\n// Management Client\nexport { ManagementClient } from './management/index.js';\nexport type {\n ApiFolderOptions,\n ApiFolderRouteDescriptionOptions,\n ManagementClientOptions,\n} from './management/index.js';\n\n// Flux Client\nexport { FluxClient } from './flux/index.js';\nexport { SearchMode, buildSearchBody } from './flux/index.js';\nexport type {\n FluxClientOptions,\n VectorSearchOptions,\n VectorFieldSearchOptions,\n HybridSearchOptions,\n BoostedSearchOptions,\n WriteProvenance,\n} from './flux/index.js';\nexport {\n MalformedTrustMetadataError,\n getRecordTrust,\n getFileTrust,\n getUntrustedFields,\n isRecognizedRecordTrust,\n isRecognizedFileTrust,\n} from './flux/index.js';\nexport type { RecordTrust, FileContentTrust, FileRegion, FileContentFlag } from './flux/index.js';\nexport type {\n VectorSearch,\n VectorFieldSearch,\n VectorBoostConfig,\n HybridConfig,\n SearchRequest,\n UploadFileStatus,\n UploadSignature,\n UploadStatus,\n} from './flux/index.js';\n\n// Models\nexport type {\n PaginatedResponse,\n ResourceSummary,\n ResourceList,\n RevisionSummary,\n RevisionList,\n FolderSummary,\n FolderList,\n CollectionSummary,\n CollectionList,\n ComponentSummary,\n ComponentList,\n SchemaVersionSummary,\n SchemaVersionList,\n FieldSummary,\n FieldList,\n NestedFieldMeta,\n SyncComponentSkippedItem,\n SyncComponentResponse,\n ComponentSyncConflictDetail,\n RegionInfo,\n ProjectSummary,\n ProjectList,\n UserReference,\n EnvironmentSummary,\n EnvironmentList,\n LocaleSummary,\n LocaleList,\n ManagementAPIKeySummary,\n ManagementAPIKeyList,\n FluxAPIKeyBearerToken,\n FluxAPIKeySummary,\n FluxAPIKeyList,\n ManagementRoleSummary,\n ManagementRoleList,\n RolePermission,\n RolePermissionObject,\n FluxRoleSummary,\n FluxRoleList,\n APIInfo,\n APIList,\n APIFolderSummary,\n APIFolderList,\n APICollectionSummary,\n APICollectionList,\n FlatRoute,\n FlatRouteSummary,\n OrganizationOwner,\n OrganizationSummary,\n OrganizationList,\n PlanLimits,\n PlanDetails,\n OrganizationPlanStatus,\n OrganizationUsage,\n UnitsUsage,\n StorageUsage,\n UsageMetric,\n UsageBreakdown,\n CurrentUsage,\n BatchUpsertItem,\n BatchItemError,\n BatchUpsertResult,\n FileKind,\n UploadLinkCreateRequest,\n UploadLinkCreator,\n UploadFileProgress,\n UploadLinkFile,\n UploadLinkSession,\n UploadLink,\n UploadLinkList,\n UploadLinkCreated,\n FileAnalysis,\n FileCheck,\n FileFinding,\n FileCopyAvailability,\n FileActiveContent,\n FileDownloadOptions,\n FileRecordView,\n FileDownload,\n FilePageRedaction,\n FilePageTable,\n FilePageDetail,\n FileTombstone,\n FileTombstoneList,\n FileFindingsSummary,\n FileReviewItem,\n FileReviewQueue,\n FilesPolicyBody,\n FilesPolicy,\n FileSummary,\n FileRecordOwner,\n FileInfo,\n FileEvidencePart,\n FileTextEvidence,\n FileTrust,\n FilePagePii,\n FileFindingGroup,\n FilePageFinding,\n EnvironmentAccess,\n ContentTypeAccess,\n MyPermissions,\n FileOrigin,\n FileOriginActor,\n FileOriginLink,\n WebhookPayloadMode,\n WebhookEndpointStatus,\n WebhookStats24h,\n WebhookEndpoint,\n WebhookEndpointList,\n WebhookEndpointCreated,\n WebhookSecret,\n WebhookSecretRotation,\n WebhookEndpointCreateRequest,\n WebhookEndpointUpdateRequest,\n WebhookEndpointRef,\n WebhookDelivery,\n WebhookDeliveryEvent,\n WebhookEndpointDelivery,\n WebhookEndpointDeliveryList,\n WebhookDeliveryCounts,\n WebhookEvent,\n WebhookEventList,\n WebhookEventDetail,\n WebhookAttempt,\n WebhookAttemptList,\n WebhookTestEvent,\n WebhookRecovery,\n WebhookRedelivery,\n WebhookSkippedEndpoint,\n WebhookRedeliveryResult,\n WebhookEventType,\n WebhookEventTypeList,\n WebhookEventListParams,\n // Ref types\n FolderRef,\n CollectionRef,\n ResourceRef,\n RevisionRef,\n ComponentRef,\n SchemaVersionRef,\n OrgRef,\n ProjectRef,\n EnvironmentRef,\n ManagementRoleRef,\n FluxRoleRef,\n ManagementAPIKeyRef,\n FluxAPIKeyRef,\n APIRef,\n TenantSigningKey,\n TenantSigningKeyList,\n TenantSigningKeyCreated,\n TenantSigningKeyCreateRequest,\n TenantSigningKeyUpdateRequest,\n TenantTokenRevocation,\n TenantLimits,\n TenantLimitValues,\n GuardrailsUntrustedField,\n ResourceGuardrailsSummary,\n RevisionGuardrailsSummary,\n GuardrailsPolicyBody,\n GuardrailsPolicy,\n GuardrailsDeliveredBy,\n GuardrailsFinding,\n GuardrailsWhy,\n GuardrailsWriter,\n GuardrailsTaintedField,\n HeldRevision,\n HeldRevisionList,\n HeldRevisionStatus,\n HeldRevisionDecision,\n HeldRevisionRef,\n GuardrailsBatchItemResult,\n GuardrailsBatchResult,\n GuardrailsUsage,\n GuardrailsReviewItem,\n GuardrailsReviewQueue,\n RevisionGuardrails,\n MarkReviewedResult,\n GuardrailsCatalog,\n} from './management/models.js';\n\nexport {\n resolveKey,\n nestedFieldMeta,\n parseFindingEvidence,\n getResourceGuardrailsSummary,\n getRevisionGuardrailsSummary,\n GUARDRAILS_POLICY_FIELDS,\n} from './management/models.js';\n\nexport { SDK_VERSION as VERSION } from './config.js';\n","import type { AuthStrategy, RequestData } from './types.js';\n\n/**\n * Placeholder auth strategy when no credentials are required.\n */\nexport class AnonymousAuth implements AuthStrategy {\n buildHeaders(_request: RequestData): Record<string, string> {\n return {};\n }\n}\n","import type { AuthStrategy, RequestData, TokenProvider } from './types.js';\n\n/**\n * Simple token provider that always returns the same token.\n */\nexport class StaticTokenProvider implements TokenProvider {\n constructor(private readonly token: string) {}\n\n getToken(): string {\n return this.token;\n }\n}\n\n/**\n * Adds `Authorization: Bearer` headers using a token provider.\n */\nexport class JWTAuth implements AuthStrategy {\n private readonly provider: TokenProvider;\n private readonly scheme: string;\n\n constructor(provider: TokenProvider, options?: { scheme?: string }) {\n this.provider = provider;\n this.scheme = options?.scheme ?? 'Bearer';\n }\n\n buildHeaders(_request: RequestData): Record<string, string> {\n const token = this.provider.getToken();\n if (!token) {\n throw new Error('Token provider returned an empty token');\n }\n return { Authorization: `${this.scheme} ${token}` };\n }\n\n /**\n * Convenience constructor for scripts with manual token management.\n */\n static fromStaticToken(token: string, options?: { scheme?: string }): JWTAuth {\n return new JWTAuth(new StaticTokenProvider(token), options);\n }\n}\n","import { createHash, createSign } from 'node:crypto';\n\nimport { FoxnoseAuthError } from '../errors.js';\nimport type { AuthStrategy, RequestData } from './types.js';\n\ntype Clock = () => Date;\n\n/**\n * Implements the `Secure <public>:<signature>` header used by both APIs.\n *\n * The signature uses ECDSA P-256 over `<path>|<sha256(body)>|<timestamp>`.\n */\nexport class SecureKeyAuth implements AuthStrategy {\n private readonly publicKey: string;\n private readonly privateKeyPem: string;\n private readonly clock: Clock;\n\n constructor(publicKey: string, privateKey: string, options?: { clock?: Clock }) {\n if (!publicKey || !privateKey) {\n throw new Error('publicKey and privateKey are required');\n }\n this.publicKey = publicKey;\n this.clock = options?.clock ?? (() => new Date());\n\n try {\n // The private key comes as base64-encoded DER. Convert to PEM for node:crypto.\n const derB64 = privateKey;\n this.privateKeyPem =\n `-----BEGIN EC PRIVATE KEY-----\\n` +\n derB64.match(/.{1,64}/g)!.join('\\n') +\n `\\n-----END EC PRIVATE KEY-----`;\n } catch (err) {\n throw new FoxnoseAuthError(`Failed to load private key: ${err}`);\n }\n }\n\n buildHeaders(request: RequestData): Record<string, string> {\n const body = request.body ?? new Uint8Array(0);\n const now = this.clock();\n const timestamp = now.toISOString().replace(/\\.\\d{3}Z$/, 'Z');\n\n let path: string;\n try {\n const parsed = new URL(request.url);\n // Query parameters are excluded from the signature payload to match\n // server-side verification, which signs only the request path.\n path = parsed.pathname || '/';\n } catch {\n path = request.path || '/';\n }\n\n const bodyHash = createHash('sha256').update(body).digest('hex');\n const dataToSign = `${path}|${bodyHash}|${timestamp}`;\n\n const signer = createSign('SHA256');\n signer.update(dataToSign);\n signer.end();\n\n const signatureBuffer = signer.sign({\n key: this.privateKeyPem,\n dsaEncoding: 'der',\n });\n const signatureB64 = signatureBuffer.toString('base64');\n\n return {\n Authorization: `Secure ${this.publicKey}:${signatureB64}`,\n Date: timestamp,\n };\n }\n}\n","/**\n * Base class for all SDK errors.\n */\nexport class FoxnoseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'FoxnoseError';\n }\n}\n\n/**\n * Raised when the API responds with an error status (4xx/5xx).\n */\nexport class FoxnoseAPIError extends FoxnoseError {\n readonly statusCode: number;\n readonly errorCode?: string;\n readonly detail?: unknown;\n readonly responseHeaders?: Record<string, string>;\n readonly responseBody?: unknown;\n\n constructor(options: {\n message: string;\n statusCode: number;\n errorCode?: string;\n detail?: unknown;\n responseHeaders?: Record<string, string>;\n responseBody?: unknown;\n }) {\n const code = options.errorCode ? `, error_code=${options.errorCode}` : '';\n super(`${options.message} (status=${options.statusCode}${code})`);\n this.name = 'FoxnoseAPIError';\n this.statusCode = options.statusCode;\n this.errorCode = options.errorCode;\n this.detail = options.detail;\n this.responseHeaders = options.responseHeaders;\n this.responseBody = options.responseBody;\n }\n}\n\n/**\n * Options shared by every {@link FoxnoseAPIError} subclass.\n */\ntype APIErrorOptions = {\n message: string;\n statusCode: number;\n errorCode?: string;\n detail?: unknown;\n responseHeaders?: Record<string, string>;\n responseBody?: unknown;\n};\n\n/**\n * Raised on HTTP 402 when a configured spend cap has been reached.\n */\nexport class SpendCapExceededError extends FoxnoseAPIError {\n /** Spend cap in USD, or null when unset on the server side. */\n readonly capUsd?: number | null;\n /** ISO timestamp when the current billing cycle resets. */\n readonly cycleResetsAt?: string;\n /** URL where the spend cap can be raised. */\n readonly raiseCapUrl?: string;\n\n constructor(\n options: APIErrorOptions & {\n capUsd?: number | null;\n cycleResetsAt?: string;\n raiseCapUrl?: string;\n },\n ) {\n super(options);\n this.name = 'SpendCapExceededError';\n this.capUsd = options.capUsd;\n this.cycleResetsAt = options.cycleResetsAt;\n this.raiseCapUrl = options.raiseCapUrl;\n }\n}\n\n/**\n * Raised on HTTP 402 when the plan allowance for a usage axis is exhausted.\n */\nexport class PlanExhaustedError extends FoxnoseAPIError {\n /** Usage axis that was exhausted (e.g. retrievals, writes, data_storage, vector_storage). */\n readonly axis?: string;\n /** ISO timestamp when the usage window resets. */\n readonly windowResetsAt?: string;\n /** URL where the plan can be upgraded. */\n readonly upgradeUrl?: string;\n\n constructor(\n options: APIErrorOptions & {\n axis?: string;\n windowResetsAt?: string;\n upgradeUrl?: string;\n },\n ) {\n super(options);\n this.name = 'PlanExhaustedError';\n this.axis = options.axis;\n this.windowResetsAt = options.windowResetsAt;\n this.upgradeUrl = options.upgradeUrl;\n }\n}\n\n/**\n * Raised on HTTP 402 `files_quota_exceeded` when no file processing units are left.\n *\n * `reason` says what ran out, and the matching link is `upgradeUrl` or `raiseCapUrl`.\n * A refusal relayed by Flux carries the code only, so these fields are undefined there.\n */\nexport class FilesQuotaExceededError extends FoxnoseAPIError {\n readonly axis?: string;\n readonly reason?: string;\n readonly usedUnits?: number;\n readonly includedUnits?: number | null;\n readonly capUsd?: number | null;\n readonly windowResetsAt?: string | null;\n readonly upgradeUrl?: string;\n readonly raiseCapUrl?: string;\n\n constructor(\n options: APIErrorOptions & {\n axis?: string;\n reason?: string;\n usedUnits?: number;\n includedUnits?: number | null;\n capUsd?: number | null;\n windowResetsAt?: string | null;\n upgradeUrl?: string;\n raiseCapUrl?: string;\n },\n ) {\n super(options);\n this.name = 'FilesQuotaExceededError';\n this.axis = options.axis;\n this.reason = options.reason;\n this.usedUnits = options.usedUnits;\n this.includedUnits = options.includedUnits;\n this.capUsd = options.capUsd;\n this.windowResetsAt = options.windowResetsAt;\n this.upgradeUrl = options.upgradeUrl;\n this.raiseCapUrl = options.raiseCapUrl;\n }\n}\n\n/**\n * Raised on HTTP 503 `files_quota_unavailable` when the file processing quota could\n * not be read, so nothing was started. Retry after `retryAfter` seconds.\n */\nexport class FilesQuotaUnavailableError extends FoxnoseAPIError {\n readonly retryAfter?: number;\n\n constructor(options: APIErrorOptions & { retryAfter?: number }) {\n super(options);\n this.name = 'FilesQuotaUnavailableError';\n this.retryAfter = options.retryAfter;\n }\n}\n\n/**\n * Raised on HTTP 403 when a plan entity limit is exceeded.\n */\nexport class PlanLimitExceededError extends FoxnoseAPIError {\n /** Entity whose limit was exceeded (e.g. collections, environments, api_keys). */\n readonly entity?: string;\n /** Maximum allowed by the current plan. */\n readonly limit?: number;\n /** Current count that triggered the error. */\n readonly current?: number;\n /** URL where the plan can be upgraded, if provided. */\n readonly upgradeUrl?: string;\n\n constructor(\n options: APIErrorOptions & {\n entity?: string;\n limit?: number;\n current?: number;\n upgradeUrl?: string;\n },\n ) {\n super(options);\n this.name = 'PlanLimitExceededError';\n this.entity = options.entity;\n this.limit = options.limit;\n this.current = options.current;\n this.upgradeUrl = options.upgradeUrl;\n }\n}\n\n/**\n * Raised on HTTP 429 when the request rate limit is exceeded.\n */\nexport class RateLimitExceededError extends FoxnoseAPIError {\n /** Seconds to wait before retrying, from the Retry-After header. */\n readonly retryAfter?: number;\n\n constructor(options: APIErrorOptions & { retryAfter?: number }) {\n super(options);\n this.name = 'RateLimitExceededError';\n this.retryAfter = options.retryAfter;\n }\n}\n\n/**\n * Raised on HTTP 403 when the target collection does not accept writes (or the\n * key in use lacks write access).\n */\nexport class CollectionNotWritableError extends FoxnoseAPIError {\n constructor(options: APIErrorOptions) {\n super(options);\n this.name = 'CollectionNotWritableError';\n }\n}\n\n/**\n * Raised on HTTP 409 when the supplied `key` already identifies a resource.\n */\nexport class ExternalIdConflictError extends FoxnoseAPIError {\n constructor(options: APIErrorOptions) {\n super(options);\n this.name = 'ExternalIdConflictError';\n }\n}\n\n/**\n * Raised on HTTP 422 when submitted `data` fails the collection's schema.\n *\n * Two server error codes mean this, and both map here:\n * `content_validation_failed` and `data_validation_error`. The latter is what\n * a Flux resource write returns, so leaving it unmapped meant the most common\n * way to hit a schema violation raised a bare {@link FoxnoseAPIError}, and\n * `instanceof ContentValidationFailedError` never matched it.\n */\nexport class ContentValidationFailedError extends FoxnoseAPIError {\n /** Individual validation problems; each includes a `json_path`. */\n readonly errors: unknown[];\n /** True when the server capped a very large error list. */\n readonly errorsTruncated: boolean;\n\n constructor(options: APIErrorOptions & { errors?: unknown[]; errorsTruncated?: boolean }) {\n super(options);\n this.name = 'ContentValidationFailedError';\n this.errors = options.errors ?? [];\n this.errorsTruncated = options.errorsTruncated ?? false;\n }\n}\n\n/**\n * Raised on HTTP 502 when a write could not be confirmed. The write may or may\n * not have been applied — re-read the resource with a GET before retrying.\n */\nexport class UpstreamError extends FoxnoseAPIError {\n constructor(options: APIErrorOptions) {\n super(options);\n this.name = 'UpstreamError';\n }\n}\n\n/**\n * Raised on HTTP 404 `webhook_endpoint_not_found`: no endpoint with this id in the\n * environment.\n */\nexport class WebhookEndpointNotFoundError extends FoxnoseAPIError {\n constructor(options: APIErrorOptions) {\n super(options);\n this.name = 'WebhookEndpointNotFoundError';\n }\n}\n\n/**\n * Raised on HTTP 404 `webhook_event_not_found`: no such event in the environment\n * within the last 30 days.\n */\nexport class WebhookEventNotFoundError extends FoxnoseAPIError {\n constructor(options: APIErrorOptions) {\n super(options);\n this.name = 'WebhookEventNotFoundError';\n }\n}\n\n/**\n * Raised on HTTP 409 `limit_exceeded`: the environment already has the most webhook\n * endpoints it can have (20).\n */\nexport class WebhookEndpointLimitExceededError extends FoxnoseAPIError {\n constructor(options: APIErrorOptions) {\n super(options);\n this.name = 'WebhookEndpointLimitExceededError';\n }\n}\n\n/**\n * Raised on HTTP 409 `endpoint_not_active`: the endpoint is paused, disabled or\n * deleted, so a test event, a recovery or a redelivery cannot go to it.\n */\nexport class WebhookEndpointNotActiveError extends FoxnoseAPIError {\n /** The endpoint's state (`paused`, `disabled` or `deleted`) when the call named it. */\n readonly reason?: string;\n /** Endpoints a redelivery without `endpoint_id` passed over, each with `endpoint_id` and `reason`. */\n readonly skipped: unknown[];\n\n constructor(options: APIErrorOptions & { reason?: string; skipped?: unknown[] }) {\n super(options);\n this.name = 'WebhookEndpointNotActiveError';\n this.reason = options.reason;\n this.skipped = options.skipped ?? [];\n }\n}\n\n/**\n * Raised on HTTP 409 `endpoint_not_subscribed`: the endpoint's current event types or\n * collection filter do not cover the event.\n */\nexport class WebhookEndpointNotSubscribedError extends FoxnoseAPIError {\n /** Endpoints a redelivery without `endpoint_id` passed over, each with `endpoint_id` and `reason`. */\n readonly skipped: unknown[];\n\n constructor(options: APIErrorOptions & { skipped?: unknown[] }) {\n super(options);\n this.name = 'WebhookEndpointNotSubscribedError';\n this.skipped = options.skipped ?? [];\n }\n}\n\n/** Returns true only for a plain (non-null, non-array) object. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Case-insensitive header lookup over a header map. */\nfunction getHeader(headers: Record<string, string> | undefined, name: string): string | undefined {\n if (!headers) {\n return undefined;\n }\n const target = name.toLowerCase();\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === target) {\n return value;\n }\n }\n return undefined;\n}\n\n/** `Retry-After` in seconds, or undefined when absent or not a number. */\nfunction retryAfterSeconds(headers: Record<string, string> | undefined): number | undefined {\n const raw = getHeader(headers, 'Retry-After');\n const parsed = raw !== undefined ? Number(raw) : NaN;\n return Number.isNaN(parsed) ? undefined : parsed;\n}\n\n/**\n * Builds the most specific {@link FoxnoseAPIError} subclass for a response,\n * mapping known (statusCode, errorCode) pairs to typed exceptions. Never\n * throws while parsing; malformed payloads fall through to the base class.\n */\n/**\n * Codes that both describe data rejected by the collection schema.\n *\n * The resource-write path raises `RevisionValidationError`\n * (`data_validation_error`); other paths raise the content variant. They carry\n * the same detail payload, so both map to the same class.\n */\nconst CONTENT_VALIDATION_CODES = new Set(['content_validation_failed', 'data_validation_error']);\n\nexport function buildAPIError(options: APIErrorOptions): FoxnoseAPIError {\n const { statusCode, errorCode, detail, responseHeaders, responseBody } = options;\n const body = isPlainObject(responseBody) ? responseBody : undefined;\n\n if (statusCode === 402 && errorCode === 'spend_cap_reached' && body) {\n return new SpendCapExceededError({\n ...options,\n message: 'message' in body ? options.message : 'Spend cap reached',\n capUsd:\n typeof body.cap_usd === 'number' ? body.cap_usd : body.cap_usd === null ? null : undefined,\n cycleResetsAt: typeof body.cycle_resets_at === 'string' ? body.cycle_resets_at : undefined,\n raiseCapUrl: typeof body.raise_cap_url === 'string' ? body.raise_cap_url : undefined,\n });\n }\n\n if (statusCode === 402 && errorCode === 'plan_exhausted' && body) {\n return new PlanExhaustedError({\n ...options,\n message: 'message' in body ? options.message : 'Plan allowance exhausted',\n axis: typeof body.axis === 'string' ? body.axis : undefined,\n windowResetsAt: typeof body.window_resets_at === 'string' ? body.window_resets_at : undefined,\n upgradeUrl: typeof body.upgrade_url === 'string' ? body.upgrade_url : undefined,\n });\n }\n\n if (statusCode === 402 && errorCode === 'files_quota_exceeded' && body) {\n const numberOrNull = (value: unknown) =>\n typeof value === 'number' ? value : value === null ? null : undefined;\n const text = (value: unknown) => (typeof value === 'string' ? value : undefined);\n return new FilesQuotaExceededError({\n ...options,\n message: 'message' in body ? options.message : 'File processing quota reached',\n axis: text(body.axis),\n reason: text(body.reason),\n usedUnits: typeof body.used_units === 'number' ? body.used_units : undefined,\n includedUnits: numberOrNull(body.included_units),\n capUsd: numberOrNull(body.cap_usd),\n windowResetsAt: body.window_resets_at === null ? null : text(body.window_resets_at),\n upgradeUrl: text(body.upgrade_url),\n raiseCapUrl: text(body.raise_cap_url),\n });\n }\n\n if (statusCode === 503 && errorCode === 'files_quota_unavailable') {\n return new FilesQuotaUnavailableError({\n ...options,\n message: body && 'message' in body ? options.message : 'File processing quota is unavailable',\n retryAfter: retryAfterSeconds(responseHeaders),\n });\n }\n\n if (statusCode === 403 && errorCode === 'plan_limit_exceeded') {\n const d = isPlainObject(detail) ? detail : {};\n return new PlanLimitExceededError({\n ...options,\n entity: typeof d.entity === 'string' ? d.entity : undefined,\n limit: typeof d.limit === 'number' ? d.limit : undefined,\n current: typeof d.current === 'number' ? d.current : undefined,\n upgradeUrl: typeof d.upgrade_url === 'string' ? d.upgrade_url : undefined,\n });\n }\n\n if (statusCode === 429 && errorCode === 'rate_limited') {\n return new RateLimitExceededError({\n ...options,\n retryAfter: retryAfterSeconds(responseHeaders),\n });\n }\n\n if (statusCode === 403 && errorCode === 'collection_not_writable') {\n return new CollectionNotWritableError(options);\n }\n\n if (statusCode === 409 && errorCode === 'external_id_conflict') {\n return new ExternalIdConflictError(options);\n }\n\n if (statusCode === 422 && CONTENT_VALIDATION_CODES.has(errorCode as string)) {\n const d = isPlainObject(detail) ? detail : {};\n const errors = Array.isArray(d.errors) ? d.errors : typeof d.json_path === 'string' ? [d] : [];\n return new ContentValidationFailedError({\n ...options,\n errors,\n errorsTruncated: d.errors_truncated === true,\n });\n }\n\n if (statusCode === 404 && errorCode === 'webhook_endpoint_not_found') {\n return new WebhookEndpointNotFoundError(options);\n }\n\n if (statusCode === 404 && errorCode === 'webhook_event_not_found') {\n return new WebhookEventNotFoundError(options);\n }\n\n if (statusCode === 409 && errorCode === 'limit_exceeded') {\n return new WebhookEndpointLimitExceededError(options);\n }\n\n if (statusCode === 409 && errorCode === 'endpoint_not_active') {\n const d = isPlainObject(detail) ? detail : {};\n return new WebhookEndpointNotActiveError({\n ...options,\n reason: typeof d.reason === 'string' ? d.reason : undefined,\n skipped: Array.isArray(d.skipped) ? d.skipped : undefined,\n });\n }\n\n if (statusCode === 409 && errorCode === 'endpoint_not_subscribed') {\n const d = isPlainObject(detail) ? detail : {};\n return new WebhookEndpointNotSubscribedError({\n ...options,\n skipped: Array.isArray(d.skipped) ? d.skipped : undefined,\n });\n }\n\n if (statusCode === 502 && errorCode === 'upstream_error') {\n return new UpstreamError(options);\n }\n\n return new FoxnoseAPIError(options);\n}\n\n/**\n * Raised when authentication headers cannot be generated.\n */\nexport class FoxnoseAuthError extends FoxnoseError {\n constructor(message: string) {\n super(message);\n this.name = 'FoxnoseAuthError';\n }\n}\n\n/**\n * Raised when the HTTP layer fails before receiving a response.\n */\nexport class FoxnoseTransportError extends FoxnoseError {\n constructor(message: string) {\n super(message);\n this.name = 'FoxnoseTransportError';\n }\n}\n","import type { AuthStrategy, RequestData } from './types.js';\n\n/**\n * Adds `Authorization: Simple` headers for development usage.\n */\nexport class SimpleKeyAuth implements AuthStrategy {\n private readonly publicKey: string;\n private readonly secretKey: string;\n\n constructor(publicKey: string, secretKey: string) {\n if (!publicKey || !secretKey) {\n throw new Error('publicKey and secretKey are required');\n }\n this.publicKey = publicKey;\n this.secretKey = secretKey;\n }\n\n buildHeaders(_request: RequestData): Record<string, string> {\n return { Authorization: `Simple ${this.publicKey}:${this.secretKey}` };\n }\n}\n","/**\n * Tenant tokens: sign `fxt_` tokens for one end user and keep them fresh.\n *\n * Your backend holds the private key of a tenant signing key and signs one token per\n * end user and session. FoxNose stores only the public key. A token reaches only the\n * records under the owner records it names (its anchors) and the shared collections its\n * signing key allows, and reads, creates, updates and uploads there as far as the\n * signing key's actions allow.\n *\n * @module\n */\n\nimport {\n createPrivateKey,\n generateKeyPairSync,\n randomBytes,\n sign as cryptoSign,\n type KeyObject,\n} from 'node:crypto';\n\nimport type { AuthStrategy, RequestData } from './auth/types.js';\n\nexport const TENANT_TOKEN_PREFIX = 'fxt_';\nconst MAX_TOKEN_BYTES = 4096;\nconst MAX_TTL_SECONDS = 86400;\nconst MAX_ANCHORS = 10;\nconst SUB_MAX = 128;\nconst ANCHOR_RECORD_MAX = 64;\nconst KID_RE = /^tsk_[A-Za-z0-9]{12}$/;\nconst JTI_RE = /^[A-Za-z0-9_-]{16,64}$/;\n// Python's str.isprintable(): no character of the Other or Separator categories,\n// except the ASCII space.\nconst NOT_PRINTABLE_RE = /[\\p{C}\\p{Z}]/u;\n\n/** A P-256 key pair made locally for a tenant signing key. */\nexport interface TenantSigningKeyPair {\n /** Base64 PKCS#8 DER. Not enumerable, so it stays out of `JSON.stringify` and logs. */\n readonly privateKey: string;\n /** Base64 SPKI DER: register it with `createTenantSigningKey({ public_key })`. */\n readonly publicKey: string;\n}\n\n/**\n * Make a P-256 key pair for a tenant signing key. Register `publicKey` and keep\n * `privateKey` on your backend: it never has to leave it.\n */\nexport function generateTenantSigningKey(): TenantSigningKeyPair {\n const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });\n const pair = {\n publicKey: publicKey.export({ format: 'der', type: 'spki' }).toString('base64'),\n } as TenantSigningKeyPair;\n Object.defineProperty(pair, 'privateKey', {\n value: privateKey.export({ format: 'der', type: 'pkcs8' }).toString('base64'),\n enumerable: false,\n writable: false,\n });\n return pair;\n}\n\n/** An anchor: an owner record, by collection key (not alias) and record key. */\nexport type TenantTokenAnchor =\n | readonly [collection: string, record: string]\n | { readonly collection: string; readonly record: string };\n\nexport interface SignTenantTokenOptions {\n /** The signing key id, `tsk_` and 12 characters. */\n kid: string;\n /** Key of the environment; the token's `aud` is `flux:<environmentKey>`. */\n environmentKey: string;\n /** Your id for the end user, 1 to 128 printable characters. */\n sub: string;\n /** The owner records the token reads under, 1 to 10. */\n anchors: readonly TenantTokenAnchor[];\n /** Lifetime in seconds, 1 to 86400 and at most the key's `max_ttl_seconds`. @default 900 */\n ttl?: number;\n /** Narrows the key's `apis`, such as `{ support: ['read'] }`. */\n apis?: Record<string, readonly string[]>;\n /** Narrows the key's `collections` (claim `col`). */\n collections?: readonly string[];\n /** Narrows the key's `shared_read` (claim `shr`). */\n sharedRead?: readonly string[];\n /** Not valid before this time, in seconds since the epoch (claim `nbf`). */\n notBefore?: number;\n /** A unique id for the token, 16 to 64 characters of `A-Z a-z 0-9 - _`. Random by default. */\n jti?: string;\n /** Issue time in seconds since the epoch. The current time by default. */\n now?: number;\n}\n\n/** A private key: base64 PKCS#8 DER, PEM, DER bytes, or a `KeyObject`. */\nexport type TenantPrivateKey = string | Uint8Array | KeyObject;\n\nfunction isInt(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value);\n}\n\nfunction stringList(name: string, value: unknown): string[] {\n if (!Array.isArray(value) || !value.every((v) => typeof v === 'string')) {\n throw new Error(`${name} must be an array of strings`);\n }\n return [...value];\n}\n\nfunction anchorClaim(anchors: unknown): Array<{ c: string; r: string }> {\n if (!Array.isArray(anchors)) {\n throw new Error('anchors must be an array of [collectionKey, recordKey] pairs');\n }\n if (anchors.length < 1 || anchors.length > MAX_ANCHORS) {\n throw new Error(`anchors must hold 1 to ${MAX_ANCHORS} entries`);\n }\n const seen = new Set<string>();\n return anchors.map((item: unknown) => {\n let collection: unknown;\n let record: unknown;\n if (Array.isArray(item) && item.length === 2) {\n [collection, record] = item;\n } else if (item && typeof item === 'object' && !Array.isArray(item)) {\n const anchor = item as Record<string, unknown>;\n collection = anchor.collection ?? anchor.c;\n record = anchor.record ?? anchor.r;\n } else {\n throw new Error('each anchor must be a [collectionKey, recordKey] pair');\n }\n if (typeof collection !== 'string' || collection.length === 0) {\n throw new Error(\"an anchor's collection key must be a non-empty string\");\n }\n if (\n typeof record !== 'string' ||\n [...record].length < 1 ||\n [...record].length > ANCHOR_RECORD_MAX\n ) {\n throw new Error(\n `an anchor's record key must be a string of 1 to ${ANCHOR_RECORD_MAX} characters`,\n );\n }\n const id = `${collection}\\u0000${record}`;\n if (seen.has(id)) {\n throw new Error('anchors must not repeat');\n }\n seen.add(id);\n return { c: collection, r: record };\n });\n}\n\nfunction loadPrivateKey(privateKey: TenantPrivateKey): KeyObject {\n let key: KeyObject;\n try {\n if (typeof privateKey === 'object' && 'asymmetricKeyType' in privateKey) {\n key = privateKey as KeyObject;\n } else if (typeof privateKey === 'string' && privateKey.trimStart().startsWith('-----BEGIN')) {\n key = createPrivateKey(privateKey);\n } else {\n const der =\n typeof privateKey === 'string'\n ? Buffer.from(privateKey, 'base64')\n : Buffer.from(privateKey as Uint8Array);\n try {\n key = createPrivateKey({ key: der, format: 'der', type: 'pkcs8' });\n } catch {\n key = createPrivateKey({ key: der, format: 'der', type: 'sec1' });\n }\n }\n } catch {\n // The message never quotes the key.\n throw new Error(\n 'privateKey is not a P-256 private key in PEM, PKCS#8 DER or base64 PKCS#8 DER form',\n );\n }\n if (\n key.type !== 'private' ||\n key.asymmetricKeyType !== 'ec' ||\n key.asymmetricKeyDetails?.namedCurve !== 'prime256v1'\n ) {\n throw new Error('privateKey must be a P-256 (prime256v1) private key');\n }\n return key;\n}\n\nfunction b64url(data: Buffer | string): string {\n return Buffer.from(data).toString('base64url');\n}\n\n/**\n * Sign a tenant token for one end user.\n *\n * The checks here are the ones every token must pass. The signing key's own limits\n * (`max_ttl_seconds`, `max_anchors`, its owner collections and ceilings) are checked\n * by Flux, which answers a token that fails them with `401`.\n *\n * @returns The token, `fxt_` followed by a compact JWS (ES256, 64-byte `R || S`\n * signature). Send it as `Authorization: Bearer <token>`.\n * @throws Error An option breaks a rule every token must follow. The message never\n * contains the key.\n */\nexport function signTenantToken(\n privateKey: TenantPrivateKey,\n options: SignTenantTokenOptions,\n): string {\n const { kid, environmentKey, sub } = options;\n if (typeof kid !== 'string' || !KID_RE.test(kid)) {\n throw new Error(\"kid must be 'tsk_' followed by 12 letters or digits\");\n }\n if (typeof environmentKey !== 'string' || environmentKey.length === 0) {\n throw new Error('environmentKey must be a non-empty string');\n }\n if (\n typeof sub !== 'string' ||\n [...sub].length < 1 ||\n [...sub].length > SUB_MAX ||\n [...sub].some((ch) => ch !== ' ' && NOT_PRINTABLE_RE.test(ch))\n ) {\n throw new Error(`sub must be 1 to ${SUB_MAX} printable characters`);\n }\n const ttl = options.ttl ?? 900;\n if (!isInt(ttl) || ttl < 1 || ttl > MAX_TTL_SECONDS) {\n throw new Error(`ttl must be an integer from 1 to ${MAX_TTL_SECONDS}`);\n }\n const jti = options.jti ?? randomBytes(24).toString('base64url');\n if (typeof jti !== 'string' || !JTI_RE.test(jti)) {\n throw new Error('jti must be 16 to 64 characters of A-Z a-z 0-9 - _');\n }\n const iat = options.now ?? Math.floor(Date.now() / 1000);\n if (!isInt(iat)) {\n throw new Error('now must be an integer number of seconds');\n }\n const exp = iat + ttl;\n\n const claims: Record<string, unknown> = {\n aud: `flux:${environmentKey}`,\n sub,\n anc: anchorClaim(options.anchors),\n iat,\n exp,\n jti,\n };\n if (options.notBefore !== undefined) {\n if (!isInt(options.notBefore) || options.notBefore >= exp) {\n throw new Error(\"notBefore must be an integer before the token's expiry\");\n }\n claims.nbf = options.notBefore;\n }\n if (options.apis !== undefined) {\n if (!options.apis || typeof options.apis !== 'object' || Array.isArray(options.apis)) {\n throw new Error('apis must map an API prefix to a list of actions');\n }\n const apis: Record<string, string[]> = {};\n for (const [prefix, actions] of Object.entries(options.apis)) {\n apis[prefix] = stringList('each apis entry', actions);\n }\n claims.apis = apis;\n }\n if (options.collections !== undefined) {\n claims.col = stringList('collections', options.collections);\n }\n if (options.sharedRead !== undefined) {\n claims.shr = stringList('sharedRead', options.sharedRead);\n }\n\n const key = loadPrivateKey(privateKey);\n const header = { alg: 'ES256', typ: 'fxt+jwt', kid };\n const signingInput = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(claims))}`;\n const signature = cryptoSign('sha256', Buffer.from(signingInput, 'ascii'), {\n key,\n dsaEncoding: 'ieee-p1363',\n });\n const token = `${TENANT_TOKEN_PREFIX}${signingInput}.${b64url(signature)}`;\n if (Buffer.byteLength(token, 'utf8') > MAX_TOKEN_BYTES) {\n throw new Error(\n `the token is longer than ${MAX_TOKEN_BYTES} bytes; use fewer or shorter claims`,\n );\n }\n return token;\n}\n\n// ---------------------------------------------------------------------------\n// WWW-Authenticate\n// ---------------------------------------------------------------------------\n\nconst HTTP_TOKEN = \"[!#$%&'*+\\\\-.^_`|~0-9A-Za-z]+\";\nconst SCHEME_RE = new RegExp(HTTP_TOKEN, 'y');\nconst PARAM_RE = new RegExp(\n `(${HTTP_TOKEN})[ \\\\t]*=[ \\\\t]*(?:\"((?:[^\"\\\\\\\\]|\\\\\\\\.)*)\"|(${HTTP_TOKEN}))`,\n 'y',\n);\n\n/** The `error` parameters of the `Bearer` challenges in a `WWW-Authenticate` header. */\nexport function bearerErrors(wwwAuthenticate: string): string[] {\n const errors: string[] = [];\n let scheme: string | null = null;\n let i = 0;\n while (i < wwwAuthenticate.length) {\n const ch = wwwAuthenticate[i];\n if (ch === ' ' || ch === '\\t' || ch === ',') {\n i += 1;\n continue;\n }\n PARAM_RE.lastIndex = i;\n const param = scheme !== null ? PARAM_RE.exec(wwwAuthenticate) : null;\n if (param) {\n const name = param[1].toLowerCase();\n const value = param[2] !== undefined ? param[2].replace(/\\\\(.)/g, '$1') : param[3];\n if (scheme === 'bearer' && name === 'error') {\n errors.push(value);\n }\n i = PARAM_RE.lastIndex;\n continue;\n }\n SCHEME_RE.lastIndex = i;\n const word = SCHEME_RE.exec(wwwAuthenticate);\n if (word) {\n scheme = word[0].toLowerCase();\n i = SCHEME_RE.lastIndex;\n continue;\n }\n i += 1;\n }\n return errors;\n}\n\n/** Whether a response refuses a Bearer token as `invalid_token`. */\nexport function isInvalidTokenChallenge(\n status: number,\n wwwAuthenticate: string | null | undefined,\n): boolean {\n if (status !== 401 || !wwwAuthenticate) {\n return false;\n }\n return bearerErrors(wwwAuthenticate).includes('invalid_token');\n}\n\n// ---------------------------------------------------------------------------\n// Token source: one cache shared by TenantTokenAuth and tenantTokenFetch\n// ---------------------------------------------------------------------------\n\ninterface MintedToken {\n token: string;\n expiresAt: number;\n scope: string;\n}\n\nfunction notAToken(detail: string): Error {\n return new Error(`mint must return a tenant token (fxt_...): ${detail}`);\n}\n\nfunction decodeSegment(segment: string): unknown {\n if (!/^[A-Za-z0-9_-]*$/.test(segment)) {\n throw notAToken('it cannot be decoded');\n }\n try {\n return JSON.parse(Buffer.from(segment, 'base64url').toString('utf8'));\n } catch {\n throw notAToken('it cannot be decoded');\n }\n}\n\n/** A narrowing claim's values, sorted and unique; `null` when the claim is absent. */\nfunction sortedStrings(value: unknown, name: string): string[] | null {\n // A claim that is present must be a list of strings: an explicit `null` is refused.\n if (value === undefined) {\n return null;\n }\n if (!Array.isArray(value) || !value.every((v) => typeof v === 'string')) {\n throw notAToken(`${name} is not a list of strings`);\n }\n return [...new Set(value as string[])].sort();\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** Read a minted token's expiry and canonical scope, without verifying it (it is ours). */\nfunction inspectMinted(token: unknown): MintedToken {\n if (typeof token !== 'string' || !token.startsWith(TENANT_TOKEN_PREFIX)) {\n throw notAToken('no fxt_ prefix');\n }\n const parts = token.slice(TENANT_TOKEN_PREFIX.length).split('.');\n if (parts.length !== 3) {\n throw notAToken('it cannot be decoded');\n }\n const header = decodeSegment(parts[0]);\n const claims = decodeSegment(parts[1]);\n if (!isObject(header) || !isObject(claims)) {\n throw notAToken('its header or claims are not objects');\n }\n for (const [name, value] of [\n ['kid', header.kid],\n ['aud', claims.aud],\n ['sub', claims.sub],\n ] as const) {\n if (typeof value !== 'string') {\n throw notAToken(`${name} is not a string`);\n }\n }\n if (!isInt(claims.exp)) {\n throw notAToken('exp is not an integer');\n }\n const anchors = claims.anc;\n if (\n !Array.isArray(anchors) ||\n !anchors.every(\n (a) =>\n isObject(a) &&\n Object.keys(a).sort().join(',') === 'c,r' &&\n typeof a.c === 'string' &&\n typeof a.r === 'string',\n )\n ) {\n throw notAToken('anc is not a list of {c, r} strings');\n }\n let apis: Record<string, string[] | null> | null = null;\n if (claims.apis !== undefined) {\n if (!isObject(claims.apis)) {\n throw notAToken('apis is not an object');\n }\n apis = {};\n for (const prefix of Object.keys(claims.apis).sort()) {\n apis[prefix] = sortedStrings(claims.apis[prefix], 'an apis entry');\n }\n }\n const scope = JSON.stringify([\n header.kid,\n claims.aud,\n claims.sub,\n [\n ...new Set((anchors as Array<{ c: string; r: string }>).map((a) => `${a.c}\\u0000${a.r}`)),\n ].sort(),\n apis === null ? null : Object.entries(apis),\n sortedStrings(claims.col, 'col'),\n sortedStrings(claims.shr, 'shr'),\n ]);\n return { token, expiresAt: claims.exp, scope };\n}\n\nexport interface TenantTokenSourceOptions {\n /** Seconds before `exp` at which a new token is minted. @default 60 */\n refreshBefore?: number;\n /** Returns the current time in milliseconds; for tests. @default Date.now */\n clock?: () => number;\n}\n\n/**\n * Caches the token `mint` returns and mints again before it expires.\n *\n * One source serves one end user: every token `mint` returns must name the same\n * signing key, environment, `sub`, anchors and narrowing claims as the first one,\n * or it is refused and not used. Make one source per end user, and do not let `mint`\n * pick the user from global or request-local state. Flux ties an MCP session to that\n * scope; a new `jti` keeps the session.\n */\ninterface SourceState {\n current: MintedToken | null;\n scope: string | null;\n inFlight: Promise<string> | null;\n}\n\n// The cached token lives here, not on the instance, so `console.log`, `util.inspect`,\n// `JSON.stringify` and a spread of a source or an auth never show it.\nconst SOURCE_STATE = new WeakMap<TenantTokenSource, SourceState>();\n\nfunction stateOf(source: TenantTokenSource): SourceState {\n return SOURCE_STATE.get(source)!;\n}\n\nconst INSPECT = Symbol.for('nodejs.util.inspect.custom');\n\nexport class TenantTokenSource {\n private readonly mint: () => string | Promise<string>;\n private readonly refreshBefore: number;\n private readonly clock: () => number;\n\n constructor(mint: () => string | Promise<string>, options?: TenantTokenSourceOptions) {\n if (typeof mint !== 'function') {\n throw new TypeError('mint must be a function that returns a token');\n }\n const refreshBefore = options?.refreshBefore ?? 60;\n if (!isInt(refreshBefore) || refreshBefore < 0) {\n throw new Error('refreshBefore must be a non-negative integer');\n }\n this.mint = mint;\n this.refreshBefore = refreshBefore;\n this.clock = options?.clock ?? Date.now;\n SOURCE_STATE.set(this, { current: null, scope: null, inFlight: null });\n }\n\n toJSON(): { refreshBefore: number } {\n return { refreshBefore: this.refreshBefore };\n }\n\n [INSPECT](): string {\n return `TenantTokenSource { refreshBefore: ${this.refreshBefore} }`;\n }\n\n private fresh(): string | null {\n const current = stateOf(this).current;\n if (current && this.clock() / 1000 < current.expiresAt - this.refreshBefore) {\n return current.token;\n }\n return null;\n }\n\n private accept(raw: unknown): string {\n const minted = inspectMinted(raw);\n const state = stateOf(this);\n if (state.scope === null) {\n state.scope = minted.scope;\n } else if (minted.scope !== state.scope) {\n throw new Error(\n 'mint returned a token for another scope (signing key, environment, sub, anchors ' +\n 'or narrowing claims); use one TenantTokenSource per end user',\n );\n }\n state.current = minted;\n return minted.token;\n }\n\n /** The current token, minted again when close to expiry. `mint` must be synchronous. */\n tokenSync(): string {\n const fresh = this.fresh();\n if (fresh !== null) {\n return fresh;\n }\n const raw = this.mint();\n if (raw && typeof (raw as Promise<string>).then === 'function') {\n (raw as Promise<string>).then(undefined, () => undefined);\n throw new TypeError('mint returned a Promise; use token() or tenantTokenFetch');\n }\n return this.accept(raw);\n }\n\n /** The current token, minted again when close to expiry. Concurrent callers share one mint. */\n async token(): Promise<string> {\n const fresh = this.fresh();\n if (fresh !== null) {\n return fresh;\n }\n const state = stateOf(this);\n if (state.inFlight === null) {\n state.inFlight = (async () => {\n try {\n return this.accept(await this.mint());\n } finally {\n state.inFlight = null;\n }\n })();\n }\n return state.inFlight;\n }\n\n /**\n * Mint a new token on the next request. With `token`, only if the cached token is\n * still that one, so a refusal of an older token leaves a newer one in place.\n */\n invalidate(token?: string): void {\n const state = stateOf(this);\n if (token === undefined || (state.current !== null && state.current.token === token)) {\n state.current = null;\n }\n }\n}\n\nfunction sourceOf(\n mint: (() => string | Promise<string>) | TenantTokenSource,\n options?: TenantTokenSourceOptions,\n): TenantTokenSource {\n return mint instanceof TenantTokenSource ? mint : new TenantTokenSource(mint, options);\n}\n\n/** If a failed request carried one of our tokens and Flux refused it as `invalid_token`. */\nfunction refusedToken(\n status: number,\n wwwAuthenticate: string | null | undefined,\n failedAuthorization: string | null | undefined,\n): string | null {\n if (!isInvalidTokenChallenge(status, wwwAuthenticate)) {\n return null;\n }\n const prefix = `Bearer ${TENANT_TOKEN_PREFIX}`;\n if (!failedAuthorization || !failedAuthorization.startsWith(prefix)) {\n return null;\n }\n return failedAuthorization.slice('Bearer '.length);\n}\n\n/**\n * Sends a tenant token with {@link FluxClient}, and mints a new one before it expires.\n *\n * A `401` whose `WWW-Authenticate` carries a `Bearer` challenge with\n * `error=\"invalid_token\"` makes it mint a new token and send the request once more.\n * Flux checks a token before it processes the request, so a refused write was not\n * applied and is sent again too. `mint` must be synchronous here, as\n * {@link signTenantToken} is; for an asynchronous mint use {@link tenantTokenFetch}.\n *\n * One instance serves one end user; see {@link TenantTokenSource}.\n */\nexport class TenantTokenAuth implements AuthStrategy {\n readonly source: TenantTokenSource;\n\n constructor(mint: (() => string) | TenantTokenSource, options?: TenantTokenSourceOptions) {\n this.source = sourceOf(mint, options);\n }\n\n buildHeaders(_request: RequestData): Record<string, string> {\n return { Authorization: `Bearer ${this.source.tokenSync()}` };\n }\n\n refreshAfterUnauthorized(\n status: number,\n headers: Headers,\n failedAuthorization: string | undefined,\n ): boolean {\n const refused = refusedToken(status, headers.get('www-authenticate'), failedAuthorization);\n if (refused === null) {\n return false;\n }\n this.source.invalidate(refused);\n return true;\n }\n\n toJSON(): { refreshBefore: number } {\n return this.source.toJSON();\n }\n\n [INSPECT](): string {\n return `TenantTokenAuth { source: ${this.source[INSPECT]()} }`;\n }\n}\n\nexport interface TenantTokenFetchOptions extends TenantTokenSourceOptions {\n /** The fetch to wrap. @default globalThis.fetch */\n fetch?: typeof fetch;\n}\n\nfunction replayableBody(body: unknown): boolean {\n if (body === undefined || body === null || typeof body === 'string') {\n return true;\n }\n if (body instanceof URLSearchParams || body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {\n return true;\n }\n if (typeof Blob !== 'undefined' && body instanceof Blob) {\n return true;\n }\n if (typeof FormData !== 'undefined' && body instanceof FormData) {\n return true;\n }\n return false;\n}\n\n/**\n * A `fetch` that sends a tenant token, for HTTP clients that take a `fetch`, such as\n * `new StreamableHTTPClientTransport(url, { fetch: tenantTokenFetch(mint) })` of the\n * MCP TypeScript SDK.\n *\n * It mints a new token before expiry (concurrent requests share one mint), and on a\n * `401` with `error=\"invalid_token\"` mints again and sends the request once more when\n * its body can be sent again: no body, a string, `URLSearchParams`, `Blob`,\n * `FormData` or bytes. A stream body, a `Request` with a body, and an aborted request\n * are sent once. The caller's `Request` and `init` are not changed.\n *\n * One instance serves one end user; see {@link TenantTokenSource}.\n */\nexport function tenantTokenFetch(\n mint: (() => string | Promise<string>) | TenantTokenSource,\n options?: TenantTokenFetchOptions,\n): typeof fetch {\n const source = sourceOf(mint, options);\n const wrapped = async (input: Request | string | URL, init?: RequestInit): Promise<Response> => {\n const baseFetch = options?.fetch ?? globalThis.fetch;\n const isRequest = typeof Request !== 'undefined' && input instanceof Request;\n const signal = init?.signal ?? (isRequest ? (input as Request).signal : undefined);\n // A Request that carries a body is sent once, whatever body init supplies.\n const canReplay =\n replayableBody(init?.body) && !(isRequest && (input as Request).body !== null);\n\n const send = async (): Promise<{ response: Response; authorization: string }> => {\n const authorization = `Bearer ${await source.token()}`;\n const headers = new Headers(isRequest ? (input as Request).headers : undefined);\n if (init?.headers !== undefined) {\n new Headers(init.headers).forEach((value, name) => headers.set(name, value));\n }\n headers.set('Authorization', authorization);\n const response = isRequest\n ? await baseFetch(new Request(input as Request, { ...init, headers }))\n : await baseFetch(input, { ...init, headers });\n return { response, authorization };\n };\n\n const first = await send();\n if (!canReplay || signal?.aborted) {\n return first.response;\n }\n const refused = refusedToken(\n first.response.status,\n first.response.headers.get('www-authenticate'),\n first.authorization,\n );\n if (refused === null) {\n return first.response;\n }\n source.invalidate(refused);\n await first.response.body?.cancel().catch(() => undefined);\n return (await send()).response;\n };\n return wrapped as typeof fetch;\n}\n","/**\n * Controls HTTP retry behavior for idempotent requests.\n */\nexport interface RetryConfig {\n /** Total number of attempts (original request + retries). */\n attempts: number;\n /** Multiplier for exponential backoff delays. */\n backoffFactor: number;\n /** Response statuses that should be retried. */\n statusCodes: readonly number[];\n /** HTTP methods that are eligible for retrying. */\n methods: readonly string[];\n}\n\nexport const DEFAULT_RETRY_CONFIG: Readonly<RetryConfig> = {\n attempts: 3,\n backoffFactor: 0.5,\n statusCodes: [408, 425, 429, 500, 502, 503, 504],\n methods: ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE'],\n};\n\nexport const SDK_VERSION = '0.9.0';\n\nexport const DEFAULT_USER_AGENT = `foxnose-sdk-js/${SDK_VERSION}`;\n\n/**\n * General transport-level configuration shared by all clients.\n */\nexport interface FoxnoseConfig {\n /** Root URL (including scheme) for the API. */\n baseUrl: string;\n /** Request timeout in milliseconds. */\n timeout: number;\n /** Headers applied to every request (lower priority than per-call headers). */\n defaultHeaders?: Record<string, string>;\n /** User agent string reported to the API. */\n userAgent: string;\n}\n\n/**\n * Creates a validated FoxnoseConfig with defaults applied.\n */\nexport function createConfig(options: {\n baseUrl: string;\n timeout?: number;\n defaultHeaders?: Record<string, string>;\n userAgent?: string;\n}): FoxnoseConfig {\n if (!options.baseUrl) {\n throw new Error('baseUrl must be provided');\n }\n return {\n baseUrl: options.baseUrl.replace(/\\/+$/, ''),\n timeout: options.timeout ?? 30_000,\n defaultHeaders: options.defaultHeaders,\n userAgent: options.userAgent ?? DEFAULT_USER_AGENT,\n };\n}\n","import { AnonymousAuth } from './auth/anonymous.js';\nimport type { AuthStrategy, RequestData } from './auth/types.js';\nimport type { FoxnoseConfig, RetryConfig } from './config.js';\nimport { DEFAULT_RETRY_CONFIG } from './config.js';\nimport { buildAPIError, FoxnoseTransportError } from './errors.js';\n\n/**\n * Shared HTTP transport with retry logic built on native `fetch`.\n */\nexport class HttpTransport {\n private readonly config: FoxnoseConfig;\n private readonly auth: AuthStrategy;\n private readonly retry: RetryConfig;\n\n constructor(options: { config: FoxnoseConfig; auth?: AuthStrategy; retryConfig?: RetryConfig }) {\n this.config = options.config;\n this.auth = options.auth ?? new AnonymousAuth();\n this.retry = options.retryConfig ?? { ...DEFAULT_RETRY_CONFIG };\n }\n\n async request(\n method: string,\n path: string,\n options?: {\n params?: Record<string, any>;\n jsonBody?: any;\n content?: Uint8Array;\n headers?: Record<string, string>;\n parseJson?: boolean;\n allowRetries?: boolean;\n },\n ): Promise<any> {\n const parseJson = options?.parseJson ?? true;\n const response = await this.sendWithRetries(method, path, options);\n return this.maybeDecodeResponse(response, parseJson);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n close(): void {}\n\n private buildUrl(path: string, params?: Record<string, any>): string {\n const base = this.config.baseUrl + path;\n if (!params || Object.keys(params).length === 0) {\n return base;\n }\n const searchParams = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined && value !== null) {\n searchParams.append(key, String(value));\n }\n }\n const qs = searchParams.toString();\n return qs ? `${base}?${qs}` : base;\n }\n\n private buildRequest(\n method: string,\n path: string,\n options?: {\n params?: Record<string, any>;\n jsonBody?: any;\n content?: Uint8Array;\n headers?: Record<string, string>;\n },\n ): { url: string; init: RequestInit; body: Uint8Array } {\n const headers: Record<string, string> = {};\n\n if (this.config.defaultHeaders) {\n Object.assign(headers, this.config.defaultHeaders);\n }\n headers['User-Agent'] = headers['User-Agent'] ?? this.config.userAgent;\n\n if (options?.headers) {\n Object.assign(headers, options.headers);\n }\n\n let body: Uint8Array = new Uint8Array(0);\n let bodyInit: string | Uint8Array | undefined;\n\n if (options?.jsonBody !== undefined) {\n const jsonStr = JSON.stringify(options.jsonBody);\n body = new TextEncoder().encode(jsonStr);\n bodyInit = jsonStr;\n headers['Content-Type'] = headers['Content-Type'] ?? 'application/json';\n } else if (options?.content) {\n body = options.content;\n bodyInit = options.content;\n }\n\n const url = this.buildUrl(path, options?.params);\n\n const requestData: RequestData = {\n method: method.toUpperCase(),\n url,\n path: this.buildSigningPath(path, options?.params),\n body,\n };\n\n const authHeaders = this.auth.buildHeaders(requestData);\n if (authHeaders) {\n Object.assign(headers, authHeaders);\n }\n\n const init: RequestInit = {\n method: method.toUpperCase(),\n headers,\n body: bodyInit,\n };\n\n return { url, init, body };\n }\n\n private buildSigningPath(path: string, params?: Record<string, any>): string {\n if (!params || Object.keys(params).length === 0) {\n return path;\n }\n const searchParams = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined && value !== null) {\n searchParams.append(key, String(value));\n }\n }\n const qs = searchParams.toString();\n return qs ? `${path}?${qs}` : path;\n }\n\n private shouldRetry(method: string, statusCode: number): boolean {\n if (!this.retry.methods.includes(method.toUpperCase())) {\n return false;\n }\n return this.retry.statusCodes.includes(statusCode);\n }\n\n private computeDelay(attempt: number, retryAfter?: string | null): number {\n if (retryAfter) {\n const parsed = parseFloat(retryAfter);\n if (!isNaN(parsed)) {\n return parsed * 1000;\n }\n return 0;\n }\n const base = this.retry.backoffFactor * Math.pow(2, Math.max(attempt - 1, 0)) * 1000;\n return base * (0.5 + Math.random() * 0.5);\n }\n\n private async maybeDecodeResponse(response: Response, parseJson: boolean): Promise<any> {\n if (!parseJson) {\n return response;\n }\n const text = await response.text();\n if (!text) {\n return null;\n }\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n\n private async sendWithRetries(\n method: string,\n path: string,\n options?: {\n params?: Record<string, any>;\n jsonBody?: any;\n content?: Uint8Array;\n headers?: Record<string, string>;\n allowRetries?: boolean;\n },\n ): Promise<Response> {\n const allowRetries = options?.allowRetries !== false;\n let replayed = false;\n for (let attempt = 1; attempt <= this.retry.attempts; attempt++) {\n // Built outside the try: an error from the auth strategy (a tenant token mint,\n // a refused scope) is not a network failure, so it escapes as it is.\n const request = this.buildRequest(method, path, options);\n let response: Response;\n try {\n response = await this.send(request);\n } catch (err) {\n const delay = this.handleTransportError(err, method, attempt, !allowRetries);\n if (delay > 0) {\n await this.sleep(delay);\n }\n continue;\n }\n if (!replayed && this.refreshAuthAfter(response)) {\n // Flux authenticates before it processes a request, so a refused request,\n // a write included, was not applied: send it once more, outside the\n // ordinary retries.\n replayed = true;\n await response.body?.cancel().catch(() => undefined);\n const again = this.buildRequest(method, path, options);\n try {\n response = await this.send(again);\n } catch (err) {\n const delay = this.handleTransportError(err, method, attempt, !allowRetries);\n if (delay > 0) {\n await this.sleep(delay);\n }\n continue;\n }\n }\n\n if (response.status >= 400) {\n if (\n allowRetries &&\n this.shouldRetry(method, response.status) &&\n attempt < this.retry.attempts\n ) {\n const delay = this.computeDelay(attempt, response.headers.get('Retry-After'));\n if (delay > 0) {\n await this.sleep(delay);\n }\n continue;\n }\n await this.raiseAPIError(response);\n }\n\n return response;\n }\n\n throw new FoxnoseTransportError('All retry attempts exhausted');\n }\n\n /** Send one built request; the `Authorization` it carried is kept for the 401 hook. */\n private async send(request: { url: string; init: RequestInit }): Promise<Response> {\n const { url, init } = request;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);\n init.signal = controller.signal;\n try {\n const response = await fetch(url, init);\n // Header names are case-insensitive: a strategy may send `authorization`.\n const sent = new Headers(init.headers).get('authorization');\n this.sentAuthorization.set(response, sent ?? undefined);\n return response;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n\n private readonly sentAuthorization = new WeakMap<Response, string | undefined>();\n\n /** Whether the auth strategy wants a `401` sent once more with new credentials. */\n private refreshAuthAfter(response: Response): boolean {\n if (response.status !== 401 || typeof this.auth.refreshAfterUnauthorized !== 'function') {\n return false;\n }\n return this.auth.refreshAfterUnauthorized(\n response.status,\n response.headers,\n this.sentAuthorization.get(response),\n );\n }\n\n private handleTransportError(\n err: unknown,\n method: string,\n attempt: number,\n forbidRetry = false,\n ): number {\n const canRetry =\n !forbidRetry &&\n this.retry.methods.includes(method.toUpperCase()) &&\n attempt < this.retry.attempts;\n if (!canRetry) {\n const message = err instanceof Error ? err.message : String(err);\n throw new FoxnoseTransportError(message);\n }\n return this.computeDelay(attempt);\n }\n\n private async raiseAPIError(response: Response): Promise<never> {\n let message = '';\n let errorCode: string | undefined;\n let detail: unknown;\n let body: unknown;\n\n try {\n const text = await response.text();\n message = text;\n if (text) {\n try {\n const payload = JSON.parse(text);\n body = payload;\n if (payload && typeof payload === 'object' && !Array.isArray(payload)) {\n message = payload.message ?? message;\n errorCode = payload.error_code ?? payload.code;\n detail = payload.detail;\n }\n } catch {\n body = text;\n }\n }\n } catch {\n // ignore read errors\n }\n\n const responseHeaders: Record<string, string> = {};\n response.headers.forEach((value, key) => {\n responseHeaders[key] = value;\n });\n\n throw buildAPIError({\n message: message || 'API request failed',\n statusCode: response.status,\n errorCode,\n detail,\n responseHeaders,\n responseBody: body,\n });\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n","/**\n * One-shot console.warn helper for renamed SDK methods.\n *\n * Each old method name warns at most once per process. Calling\n * {@link _resetWarned} clears the internal set — only intended for tests.\n */\n\nconst warned = new Set<string>();\n\nexport function warnDeprecatedMethod(oldName: string, newName: string, removal = '1.0'): void {\n if (warned.has(oldName)) {\n return;\n }\n warned.add(oldName);\n // eslint-disable-next-line no-console\n console.warn(\n `@foxnose/sdk: ${oldName}() is deprecated; use ${newName}() instead. ` +\n `${oldName}() will be removed in @foxnose/sdk ${removal}.`,\n );\n}\n\n/** Internal helper for tests — clears the warned set so tests stay independent. */\nexport function _resetWarned(): void {\n warned.clear();\n}\n","// ---------------------------------------------------------------------------\n// Generic pagination\n// ---------------------------------------------------------------------------\n\nexport interface PaginatedResponse<T> {\n count: number;\n next: string | null;\n previous: string | null;\n results: T[];\n}\n\n// ---------------------------------------------------------------------------\n// Resources & Revisions\n// ---------------------------------------------------------------------------\n\n/** Where a file stands in the processing steps. */\nexport interface UploadFileProgress {\n step: number;\n of: number;\n step_name: string | null;\n}\n\n/** The file attached to a record or a revision. */\nexport interface FileSummary {\n uuid: string | null;\n mime: string | null;\n width: number | null;\n height: number | null;\n cdn_url_base: string | null;\n filename: string | null;\n size: number | null;\n page_count: number | null;\n}\n\n/**\n * The parent record of a file record. `title` is `null` when the caller may not\n * read the owner, and `deleted` is `true` for a parent that was deleted.\n */\nexport interface FileRecordOwner {\n key: string;\n title: string | null;\n deleted?: boolean;\n}\n\n/** A file record's newest file, published or not. */\nexport interface FileInfo {\n filename: string | null;\n mime: string | null;\n size: number | null;\n page_count: number | null;\n}\n\nexport interface ResourceSummary {\n key: string;\n folder: string;\n content_type: string;\n created_at: string;\n vectors_size: number;\n name?: string | null;\n name_is_auto?: boolean;\n resource_owner?: string | null;\n current_revision?: string | null;\n external_id?: string | null;\n file?: FileSummary | null;\n /** Set on a record of a files collection, like the fields below it. */\n owner?: FileRecordOwner | null;\n status?: string | null;\n progress?: UploadFileProgress | null;\n analysis_state?: string | null;\n /** Short-lived. Keep it out of logs. */\n thumbnail_url?: string | null;\n file_info?: FileInfo | null;\n verdict?: string | null;\n verdict_reasons?: unknown[];\n /** The record's trust summary, where the API computes one. */\n guardrails?: Record<string, unknown> | null;\n}\n\nexport interface RevisionSummary {\n key: string;\n resource: string;\n /** `null` when the schema version is gone. */\n schema_version: string | null;\n /** `null` for a draft version, and when the schema version is gone. */\n schema_version_number?: number | null;\n file?: FileSummary | null;\n /** The revision's trust summary, where the API computes one. */\n guardrails?: Record<string, unknown> | null;\n number: number;\n size: number;\n created_at: string;\n status: string;\n is_valid: boolean | null;\n published_at: string | null;\n unpublished_at: string | null;\n}\n\nexport type ResourceList = PaginatedResponse<ResourceSummary>;\nexport type RevisionList = PaginatedResponse<RevisionSummary>;\n\n// ---------------------------------------------------------------------------\n// Folders\n// ---------------------------------------------------------------------------\n\nexport interface FolderSummary {\n key: string;\n name: string;\n alias: string;\n content_type: string;\n strict_reference: boolean;\n created_at: string;\n parent?: string | null;\n mode?: string | null;\n path?: string | null;\n auto_remove_revisions?: number | null;\n auto_remove_schema_versions?: number | null;\n embedding_model?: string | null;\n embedding_dimension?: number | null;\n}\n\nexport type FolderList = PaginatedResponse<FolderSummary>;\n\n// Collection-named aliases — same shape, preferred name in new code.\n/** @public Alias of {@link FolderSummary}. */\nexport type CollectionSummary = FolderSummary;\n/** @public Alias of {@link FolderList}. */\nexport type CollectionList = FolderList;\n\n// ---------------------------------------------------------------------------\n// Components\n// ---------------------------------------------------------------------------\n\nexport interface ComponentSummary {\n key: string;\n name: string;\n description?: string | null;\n environment: string;\n content_type: string;\n created_at: string;\n current_version?: string | null;\n}\n\nexport type ComponentList = PaginatedResponse<ComponentSummary>;\n\n// ---------------------------------------------------------------------------\n// Schema versions & fields\n// ---------------------------------------------------------------------------\n\nexport interface SchemaVersionSummary {\n key: string;\n name: string;\n description: string | null;\n version_number: number | null;\n created_at: string;\n published_at: string | null;\n archived_at: string | null;\n json_schema?: Record<string, any> | null;\n}\n\nexport interface FieldSummary {\n key: string;\n name: string;\n description: string | null;\n path: string;\n parent: string | null;\n type: string;\n meta: Record<string, any>;\n json_schema?: Record<string, any> | null;\n required: boolean;\n nullable: boolean;\n multiple?: boolean | null;\n localizable?: boolean | null;\n searchable?: boolean | null;\n private: boolean;\n vectorizable?: boolean | null;\n [extra: string]: any;\n}\n\nexport type SchemaVersionList = PaginatedResponse<SchemaVersionSummary>;\nexport type FieldList = PaginatedResponse<FieldSummary>;\n\n// ---------------------------------------------------------------------------\n// Component composition: nested field meta + sync_component\n// ---------------------------------------------------------------------------\n\n/**\n * Helper shape for the `meta` block of a Collection `nested` field.\n *\n * A `nested` field on a Collection schema embeds a Component schema at a\n * specific published version. The pin is required: even in auto-update\n * mode, `component_version` stores the most recently resolved version and\n * acts as a fallback if a future Component publish fails compatibility.\n *\n * Pass an object of this shape (or use {@link nestedFieldMeta}) as the\n * `meta` value when calling\n * {@link ManagementClient.createCollectionField} or\n * {@link ManagementClient.updateCollectionField}.\n *\n * @example\n * ```ts\n * await client.createCollectionField('articles', 'v1-draft', {\n * key: 'seo',\n * name: 'SEO',\n * type: 'nested',\n * required: true,\n * meta: nestedFieldMeta({\n * component: 'cmp-seo-metadata',\n * componentVersion: 'ver-abc12345',\n * autoUpdate: true,\n * }),\n * });\n * ```\n */\nexport interface NestedFieldMeta {\n component: string;\n component_version: string;\n auto_update?: boolean;\n [extra: string]: any;\n}\n\n/**\n * Build a {@link NestedFieldMeta} payload from camelCase ergonomics.\n *\n * The wire shape uses snake_case keys (`component_version`, `auto_update`);\n * this helper lets callers pass `componentVersion` / `autoUpdate` and\n * emits the right object.\n */\nexport function nestedFieldMeta(opts: {\n component: string;\n componentVersion: string;\n autoUpdate?: boolean;\n /**\n * Any additional meta keys (title, description, …) the API accepts.\n * `component`, `component_version`, and `auto_update` are reserved and\n * cannot be overridden via `extra` — passing them throws so callers see\n * the conflict at the call-site rather than silently winning the merge.\n */\n extra?: Record<string, any>;\n}): NestedFieldMeta {\n if (opts.extra) {\n const reserved = ['component', 'component_version', 'auto_update'];\n const collisions = reserved.filter((k) => Object.prototype.hasOwnProperty.call(opts.extra, k));\n if (collisions.length > 0) {\n throw new Error(\n `nestedFieldMeta: 'extra' must not include reserved keys: ${collisions.join(', ')}`,\n );\n }\n }\n return {\n ...(opts.extra ?? {}),\n component: opts.component,\n component_version: opts.componentVersion,\n auto_update: opts.autoUpdate ?? false,\n };\n}\n\n/**\n * One entry in the `skipped` list of a sync_component response.\n *\n * `reason` is one of:\n * - `\"not_requested\"` — `field_paths` was supplied and this path was not in it.\n * - `\"auto_update_mode\"` — the field has `meta.auto_update=true`.\n * - `\"already_at_target\"` — the field is already pinned to the requested\n * target version.\n * - `\"component_not_found\"` — referenced Component does not exist in this\n * environment.\n * - `\"component_unpublished\"` — Component has no published `current_version`.\n */\nexport interface SyncComponentSkippedItem {\n path: string;\n reason: string;\n [extra: string]: any;\n}\n\n/**\n * Response payload from\n * `POST /v1/{env}/collections/{key}/sync_component/`.\n *\n * - `syncedPaths` — field paths whose `meta.component_version` was advanced.\n * - `skipped` — per-path skip records explaining why each was left alone.\n * - `schemaVersion` — UID of the newly published Collection schema version.\n * `null` when no advance was needed (every requested path was skipped).\n */\nexport interface SyncComponentResponse {\n synced_paths: string[];\n skipped: SyncComponentSkippedItem[];\n schema_version: string | null;\n [extra: string]: any;\n}\n\n/**\n * One structured conflict entry inside a 409 `component_sync_conflict`\n * error detail. `blocking_reason` is one of:\n * - `\"required_field_added_no_default\"`\n * - `\"type_narrowed\"`\n * - `\"field_removed\"`\n */\nexport interface ComponentSyncConflictDetail {\n field_path: string;\n blocking_reason: string;\n [extra: string]: any;\n}\n\n// ---------------------------------------------------------------------------\n// Regions & Projects\n// ---------------------------------------------------------------------------\n\nexport interface RegionInfo {\n location: string;\n name: string;\n code: string;\n}\n\nexport interface ProjectSummary {\n key: string;\n name: string;\n organization: string;\n region: RegionInfo | string;\n environments: Array<Record<string, any>>;\n gdpr?: boolean | null;\n created_at?: string | null;\n [extra: string]: any;\n}\n\nexport type ProjectList = PaginatedResponse<ProjectSummary>;\n\n// ---------------------------------------------------------------------------\n// Environments\n// ---------------------------------------------------------------------------\n\nexport interface UserReference {\n key: string;\n email: string;\n first_name: string;\n last_name: string;\n full_name: string;\n}\n\nexport interface EnvironmentSummary {\n key: string;\n name: string;\n project: string;\n host: string;\n is_enabled: boolean;\n created_at: string;\n protection_level?: string | null;\n protection_level_display?: string | null;\n protected_by_user?: UserReference | null;\n protected_at?: string | null;\n protection_reason?: string | null;\n}\n\nexport type EnvironmentList = EnvironmentSummary[];\n\n// ---------------------------------------------------------------------------\n// Locales\n// ---------------------------------------------------------------------------\n\nexport interface LocaleSummary {\n name: string;\n code: string;\n environment: string;\n is_default: boolean;\n created_at: string;\n}\n\nexport type LocaleList = LocaleSummary[];\n\n// ---------------------------------------------------------------------------\n// API Keys\n// ---------------------------------------------------------------------------\n\nexport interface ManagementAPIKeySummary {\n key: string;\n description?: string | null;\n public_key: string;\n secret_key: string;\n role?: string | null;\n environment: string;\n created_at: string;\n}\n\nexport type ManagementAPIKeyList = PaginatedResponse<ManagementAPIKeySummary>;\n\nexport interface FluxAPIKeySummary {\n key: string;\n description?: string | null;\n public_key: string;\n secret_key: string;\n role?: string | null;\n environment: string;\n created_at: string;\n /**\n * First 12 characters of the key's bearer token (e.g. `fxk_A7fQ2mXe`), or\n * null when none is issued. Enough to recognise a token in a config file or\n * a log; never enough to use one — the token itself is returned only by\n * {@link ManagementClient.issueFluxApiKeyBearerToken}, once.\n */\n bearer_token_prefix?: string | null;\n /** When the current bearer token was issued, or null. */\n bearer_token_issued_at?: string | null;\n}\n\nexport type FluxAPIKeyList = PaginatedResponse<FluxAPIKeySummary>;\n\n/**\n * The one-time response from issuing or re-issuing a Flux key's bearer token.\n *\n * A bearer token is an opaque credential bound to a Flux API key, for hosted\n * MCP connectors that can only send `Authorization: Bearer <token>` and cannot\n * choose a scheme. It identifies the key and nothing more: role, grants and\n * per-collection permissions are the key's own.\n */\nexport interface FluxAPIKeyBearerToken {\n /**\n * The credential, e.g. `fxk_A7fQ2mXe...`. RETURNED ONLY HERE, ONLY ONCE —\n * the service stores a hash, so a lost token is re-issued, not recovered.\n */\n bearer_token: string;\n /** First 12 characters, also present on every subsequent key read. */\n bearer_token_prefix: string;\n bearer_token_issued_at: string;\n}\n\n// ---------------------------------------------------------------------------\n// Roles & Permissions\n// ---------------------------------------------------------------------------\n\nexport interface ManagementRoleSummary {\n key: string;\n name: string;\n description?: string | null;\n full_access: boolean;\n environment: string;\n created_at: string;\n}\n\nexport type ManagementRoleList = PaginatedResponse<ManagementRoleSummary>;\n\nexport interface RolePermission {\n content_type: string;\n actions: string[];\n all_objects: boolean;\n objects?: string[] | null;\n}\n\nexport interface RolePermissionObject {\n content_type: string;\n object_key: string;\n}\n\nexport interface FluxRoleSummary {\n key: string;\n name: string;\n description?: string | null;\n environment: string;\n created_at: string;\n}\n\nexport type FluxRoleList = PaginatedResponse<FluxRoleSummary>;\n\n// ---------------------------------------------------------------------------\n// APIs\n// ---------------------------------------------------------------------------\n\nexport interface APIInfo {\n key: string;\n name: string;\n prefix: string;\n description?: string | null;\n environment: string;\n version?: string | null;\n is_auth_required: boolean;\n /** Whether the MCP endpoint (`/{prefix}/_mcp`) is exposed. Defaults to true. */\n mcp_enabled?: boolean;\n /** Whether router introspection (`/{prefix}/_router`) is exposed. Defaults to true. */\n router_introspection_enabled?: boolean;\n /**\n * Allowed browser origins for cross-origin reads. Empty (the default) means\n * CORS is off; `[\"*\"]` allows any origin. Server-validated and normalized.\n * Covers public read traffic only — writes still require a key.\n */\n cors_origins?: string[];\n /** `metadata` (records carry `_sys.trust`) or `off`. */\n trust_delivery?: string | null;\n created_at: string;\n path?: string | null;\n}\n\nexport type APIList = PaginatedResponse<APIInfo>;\n\n/**\n * One entry in `flat_routes[]` on a collection's connection to an API — a\n * read-only address for a strict-reference collection that omits some\n * number of ancestor keys from the path. `level 0` is fully flat and drops\n * every ancestor key; `level >= 1` keeps the root-most `retained_ancestors`.\n *\n * `omitted_ancestors` and `retained_ancestors` are ancestor UUIDs, not the\n * short collection keys used elsewhere (e.g. `folder`) — do not treat them\n * as interchangeable.\n *\n * `read_methods` is typed as sent by the server, which currently mirrors\n * the connection's `allowed_methods` verbatim rather than filtering by what\n * is actually available at this level (docs and server disagree on both\n * Get Resource at level 0 and Search at any level). Do not \"correct\" it.\n */\nexport interface FlatRoute {\n level: number;\n path: string;\n omitted_ancestors: string[];\n retained_ancestors: string[];\n enabled: boolean;\n read_methods: string[];\n available: boolean;\n unavailable_reason: string | null;\n published_generation: number;\n router_generation: number;\n}\n\n/**\n * The singular `flat_route` on a connection. Undocumented: it appears to\n * mirror whichever entry of `flat_routes` is enabled, but unlike a\n * {@link FlatRoute} it carries no `level` or `retained_ancestors`. Type it\n * for forward compatibility; build no behavior on it.\n */\nexport interface FlatRouteSummary {\n path: string;\n omitted_ancestors: string[];\n enabled: boolean;\n read_methods: string[];\n available: boolean;\n unavailable_reason: string | null;\n published_generation: number;\n router_generation: number;\n}\n\nexport interface APIFolderSummary {\n folder: string;\n api?: string | null;\n path?: string | null;\n allowed_methods?: string[] | null;\n description_get_one?: string | null;\n description_get_many?: string | null;\n description_search?: string | null;\n description_schema?: string | null;\n created_at?: string | null;\n /**\n * Ancestor levels (0 = fully flat) exposed as cross-parent read addresses\n * for this connection. Sent together with `unscoped_ancestors` — a level\n * with no corresponding ancestor is rejected by the server. Present on\n * every connection observed (`[]` when unused), not nullable.\n */\n unscoped_levels: number[];\n /**\n * Ancestor UUIDs (not collection keys) left unscoped at the corresponding\n * `unscoped_levels`. Present on every connection observed (`[]` when\n * unused), not nullable.\n */\n unscoped_ancestors: string[];\n /**\n * Present in the response but documented nowhere; semantics unconfirmed.\n * Typed so it is no longer silently dropped. Do not build request-side\n * behavior on it.\n */\n expose_owner: boolean;\n /** Undocumented; see {@link FlatRouteSummary}. Observed `null`, not just absent. */\n flat_route?: FlatRouteSummary | null;\n /** Observed `null` (not `[]`) on a connection with no key-bearing ancestor. */\n flat_routes?: FlatRoute[] | null;\n}\n\nexport type APIFolderList = PaginatedResponse<APIFolderSummary>;\n\n// Collection-named aliases.\n/** @public Alias of {@link APIFolderSummary}. */\nexport type APICollectionSummary = APIFolderSummary;\n/** @public Alias of {@link APIFolderList}. */\nexport type APICollectionList = APIFolderList;\n\n// ---------------------------------------------------------------------------\n// Organizations\n// ---------------------------------------------------------------------------\n\nexport interface OrganizationOwner {\n key: string;\n email: string;\n first_name: string;\n last_name: string;\n full_name: string;\n}\n\nexport interface OrganizationSummary {\n key: string;\n name: string;\n owner: OrganizationOwner;\n tax_num: string;\n city: string;\n province: string;\n address: string;\n country_iso: string | null;\n zip_code: string;\n legal_name: string;\n created_at: string;\n block_dt?: string | null;\n block_reason?: string | null;\n is_blocked: boolean;\n is_verified?: boolean;\n verification_method?: string | null;\n}\n\nexport type OrganizationList = OrganizationSummary[];\n\n// ---------------------------------------------------------------------------\n// Plans & Usage\n// ---------------------------------------------------------------------------\n\nexport interface PlanLimits {\n units_included?: string | null;\n projects?: number | null;\n environments?: number | null;\n folders?: number | null;\n resources?: number | null;\n users?: number | null;\n components?: number | null;\n allow_negative?: boolean | null;\n negative_limit?: number | null;\n unit_cost?: number | null;\n api_keys_max_count?: number | null;\n roles_max_count?: number | null;\n locales_max_count?: number | null;\n schemas_max_count?: number | null;\n schemas_fields_max_count?: number | null;\n flux_api_max_count?: number | null;\n max_component_inheritance_depth?: number | null;\n}\n\nexport interface PlanDetails {\n code: string;\n name: string;\n price: number;\n from?: string | null;\n to?: string | null;\n transferred?: string | null;\n limits: PlanLimits;\n}\n\nexport interface OrganizationPlanStatus {\n active_plan: PlanDetails;\n next_plan: PlanDetails;\n}\n\nexport interface UnitsUsage {\n remained?: string | number | null;\n unit_cost?: number | null;\n allow_negative: boolean;\n negative_limit?: string | null;\n}\n\nexport interface StorageUsage {\n data_storage: number;\n vector_storage: number;\n}\n\nexport interface UsageMetric {\n max: number | null;\n current: number;\n}\n\nexport interface UsageBreakdown {\n projects: UsageMetric;\n resources: UsageMetric;\n users: UsageMetric;\n}\n\nexport interface CurrentUsage {\n api_requests: number;\n embedding_tokens: Record<string, any>;\n}\n\nexport interface OrganizationUsage {\n units: UnitsUsage;\n storage: StorageUsage;\n usage: UsageBreakdown;\n current_usage: CurrentUsage;\n}\n\n// ---------------------------------------------------------------------------\n// Batch upsert helpers\n// ---------------------------------------------------------------------------\n\nexport interface BatchUpsertItem {\n external_id: string;\n payload: Record<string, any>;\n}\n\nexport interface BatchItemError {\n index: number;\n external_id: string;\n error: Error;\n}\n\nexport interface BatchUpsertResult {\n succeeded: ResourceSummary[];\n failed: BatchItemError[];\n}\n\n// ---------------------------------------------------------------------------\n// Files\n// ---------------------------------------------------------------------------\n\n/** A kind of file a collection or an upload link accepts. */\nexport type FileKind = 'image' | 'document' | 'archive';\n\n/** Body of {@link ManagementClient.createUploadLink}. */\nexport interface UploadLinkCreateRequest {\n /** The parent record that owns the uploaded files; the caller must be able to read it. */\n owner: ResourceRef;\n /** Heading of the hosted page: 1 to 80 characters, one line. */\n title: string;\n /** Plain text under the heading, up to 500 characters. */\n instructions?: string;\n /** How many files the link accepts, from 1 to 10. Defaults to 1. */\n max_files?: number;\n /** Narrows the collection's kinds for this link. */\n allowed_kinds?: FileKind[];\n /** The link's lifetime in seconds, from 300 to 86400. Defaults to 30 minutes. */\n expires_in?: number;\n}\n\n/** Who created an upload link. */\nexport interface UploadLinkCreator {\n kind: 'user' | 'api_key';\n label: string | null;\n /** The user's uid, for `kind: 'user'`. */\n user?: string;\n /** The key's uid, for `kind: 'api_key'`. */\n key?: string;\n}\n\n/** One file uploaded through a link, as the link's owner sees it. */\nexport interface UploadLinkFile {\n state: 'processing' | 'ready' | 'pending_review' | 'rejected';\n record_key?: string | null;\n public_reason?: string;\n file_name?: string | null;\n progress?: UploadFileProgress;\n}\n\n/** One visit to a link's hosted page and the files it uploaded. */\nexport interface UploadLinkSession {\n created_at: string | null;\n expires_at: string | null;\n files: UploadLinkFile[];\n}\n\n/** An upload link with its sessions and the status of each file. */\nexport interface UploadLink {\n upload_id: string;\n created_by: UploadLinkCreator | null;\n owner_key: string | null;\n title: string | null;\n instructions: string | null;\n max_files: number;\n allowed_kinds: string[];\n consumed_count: number;\n created_at: string;\n expires_at: string;\n revoked_at: string | null;\n state: 'active' | 'consumed' | 'expired' | 'revoked';\n sessions: UploadLinkSession[];\n}\n\nexport type UploadLinkList = PaginatedResponse<UploadLink>;\n\n/**\n * The answer to creating an upload link. `upload_url` carries the link's token\n * and is returned only here: no later read reproduces it. Keep it out of logs.\n */\nexport interface UploadLinkCreated {\n upload_id: string;\n title: string;\n instructions: string | null;\n upload_url: string;\n expires_at: string;\n max_files: number;\n allowed_kinds: string[];\n}\n\n/** The active analysis of a file. */\nexport interface FileAnalysis {\n generation: number;\n state: string;\n verdict: string | null;\n verdict_reasons: unknown[];\n public_reason: string | null;\n error_code: string | null;\n in_review: boolean;\n publish_requested_by: string | null;\n policy_version: number | null;\n pipeline_version: string | null;\n source_format: string | null;\n scanned_at: string | null;\n step_times: Record<string, unknown>;\n state_changed_at: string | null;\n created_at: string | null;\n}\n\n/** The receipt of one check that ran on a file. */\nexport interface FileCheck {\n detector: string;\n detector_version: string | null;\n status: string;\n started_at: string | null;\n finished_at: string | null;\n}\n\n/** The text of one zone of a finding. */\nexport interface FileEvidencePart {\n box?: unknown;\n text?: string;\n}\n\n/**\n * The concealed or withheld text a finding holds, as it was in the file.\n *\n * `parts` says which text lies in which box of the page. It is empty for a finding\n * that does not carry it, so fall back to `text`.\n */\nexport interface FileTextEvidence {\n page?: number;\n box?: unknown;\n tokens?: number;\n text?: string;\n samples?: string[];\n reason?: string;\n parts: FileEvidencePart[];\n truncated?: boolean;\n list_truncated?: boolean;\n omitted?: number;\n}\n\n/** One finding of an analysis. */\nexport interface FileFinding {\n kind: string;\n sub_kind: string | null;\n severity: string;\n page: number | null;\n box: unknown;\n detector: string | null;\n detector_version: string | null;\n score: number | null;\n /**\n * The stored string, `null` once a blocked or rejected file's personal data is\n * redacted. It can quote text from the file. {@link parseFindingEvidence} reads it\n * for a finding that holds text.\n */\n evidence: string | null;\n detail: Record<string, unknown> | null;\n rule_id: string | null;\n}\n\n/** Whether one copy of a file can be downloaded now, and why not if it cannot. */\nexport interface FileCopyAvailability {\n available: boolean;\n reason: string | null;\n}\n\n/** Active content found in a file. `present` is `null` when it is unknown. */\nexport interface FileActiveContent {\n present?: boolean | null;\n kinds?: Record<string, number>;\n truncated?: boolean;\n}\n\n/** Who started an upload. `name` is `null` when it cannot be found. */\nexport interface FileOriginActor {\n kind: 'user' | 'management_key' | 'flux_key';\n name: string | null;\n}\n\n/** The upload link a file came through. */\nexport interface FileOriginLink {\n upload_id: string;\n title: string | null;\n}\n\n/**\n * Where a record's file came from. `external` is true for a file that came from\n * outside the team. `end_user` is the identifier given when an end user's upload was\n * signed: personal data, so keep it out of logs.\n */\nexport interface FileOrigin {\n channel: 'upload_link' | 'signed_upload' | 'management_api' | 'dashboard' | null;\n external: boolean;\n created_by: FileOriginActor | null;\n upload_link: FileOriginLink | null;\n end_user: string | null;\n}\n\n/**\n * What the caller may download of a record's file, and where it came from. `origin`\n * is set on `getFileAnalysis` for a file bound to the record, and `null` for a record\n * uploaded without an intent.\n */\nexport interface FileDownloadOptions {\n original: FileCopyAvailability;\n safe_copy: FileCopyAvailability;\n active_content: FileActiveContent;\n original_access: string;\n origin?: FileOrigin | null;\n}\n\n/** How agent surfaces mark the file's content. */\nexport interface FileTrust {\n processing: string;\n content_tainted: boolean;\n tainted_paths: string[];\n}\n\n/** A record's file, its active analysis, check receipts and findings. */\nexport interface FileRecordView {\n resource_key: string;\n file_uuid: string | null;\n page_count: number | null;\n asset_state: string | null;\n tombstone: boolean;\n trust: FileTrust | null;\n analysis: FileAnalysis | null;\n checks: FileCheck[];\n findings: FileFinding[];\n file: FileDownloadOptions | null;\n /** Set on the answer to an approval only. */\n outcome?: string;\n /** Set on the answer to an approval only. */\n reason?: string | null;\n}\n\n/** A short-lived link to one copy of a file. Keep `url` out of logs. */\nexport interface FileDownload {\n url: string;\n expires_in: number | null;\n expires_at: string | null;\n kind: 'original' | 'safe_copy' | 'page';\n filename: string | null;\n content_type: string | null;\n generation: number | null;\n state: string | null;\n active_content: FileActiveContent | null;\n warnings: Record<string, unknown>[];\n}\n\n/** A region withheld from a page image. */\nexport interface FilePageRedaction {\n reason: string;\n box: number[];\n label: string | null;\n}\n\n/** A table found on a page. */\nexport interface FilePageTable {\n box: unknown;\n}\n\n/**\n * Where personal data stands on a page. `unreliable` marks data found only in text\n * read with low confidence. The matched text is never included.\n */\nexport interface FilePagePii {\n type: string;\n label: string | null;\n box: number[];\n unreliable?: boolean;\n}\n\n/** The findings of a file that share a kind, severity and source. */\nexport interface FileFindingGroup {\n code: string;\n sub_kind: string | null;\n severity: string;\n source: string;\n pages: number[];\n removed_from_agents: boolean;\n label?: string;\n rule_id?: string;\n}\n\n/** A finding of one page. `box` is `null` when it has no place on the page. */\nexport interface FilePageFinding {\n code: string;\n sub_kind: string | null;\n severity: string;\n source: string;\n box: number[] | null;\n removed_from_agents: boolean;\n label?: string;\n rule_id?: string;\n}\n\n/**\n * One page of a file. `image_url` is short-lived. `redactions`, `tables`, `text`,\n * `content_flags`, `pii` and `pii_truncated` are `null` for a page without extracted\n * text. With `pii_truncated` true, an empty `pii` means locations were discarded, not\n * that none were found.\n *\n * `findings` covers the whole file and `page_findings` this page. Neither carries\n * evidence. `removed_passages` counts the file's findings whose text is withheld from\n * agents.\n */\nexport interface FilePageDetail {\n page: number;\n of: number | null;\n image_url: string;\n image_width: number | null;\n image_height: number | null;\n expires_in: number | null;\n redactions: FilePageRedaction[] | null;\n tables: FilePageTable[] | null;\n text: string | null;\n content_flags: Record<string, unknown>[] | null;\n pii: FilePagePii[] | null;\n pii_truncated: boolean | null;\n findings: FileFindingGroup[];\n page_findings: FilePageFinding[];\n removed_passages: number;\n trust: FileTrust;\n verdict: string | null;\n reasons: unknown[];\n generation: number | null;\n state: string | null;\n}\n\n/**\n * A blocked or rejected file. `original_filename`, `raw_payload`, `uploaded_by`,\n * `owner_key` and each finding's `evidence` are `null` once `redacted` is true.\n */\nexport interface FileTombstone {\n resource_key: string | null;\n file_uuid: string | null;\n reason: string;\n public_reason: string | null;\n error_code: string | null;\n verdict_reasons: unknown[];\n generation: number | null;\n asset_state: string | null;\n blocked_at: string | null;\n purge_completed_at: string | null;\n redacts_at: string | null;\n redacted: boolean;\n original_filename: string | null;\n raw_payload: unknown;\n uploaded_by: string | null;\n owner_key: string | null;\n findings: FileFinding[];\n}\n\nexport type FileTombstoneList = PaginatedResponse<FileTombstone>;\n\n/** Counts of a file's findings. */\nexport interface FileFindingsSummary {\n total: number;\n by_kind: Record<string, number>;\n by_severity: Record<string, number>;\n}\n\n/**\n * A file held for a reviewer. `owner` is `null` outside a strict collection.\n * `thumbnail_url` is short-lived; it is `null` for a caller who is not the record's\n * reviewer, for a file held by moderation and over the project's view budget.\n */\nexport interface FileReviewItem {\n resource_key: string;\n file_uuid: string | null;\n collection: string;\n file_name: string | null;\n generation: number | null;\n state: string | null;\n verdict: string | null;\n verdict_reasons: unknown[];\n public_reason: string | null;\n findings: FileFindingsSummary;\n owner: Record<string, unknown> | null;\n held_at: string | null;\n thumbnail_url: string | null;\n}\n\nexport type FileReviewQueue = PaginatedResponse<FileReviewItem>;\n\n/**\n * The settings of a collection's files policy. As a request body it is a full\n * replacement: a field left out takes its default.\n */\nexport interface FilesPolicyBody {\n suspicious_action?: 'deliver' | 'quarantine';\n overrides?: Record<string, string>;\n allowed_kinds?: FileKind[];\n tables?: 'auto' | 'never' | 'always';\n moderation_rules?: Record<string, unknown>[];\n acknowledge_explicit_delivery?: boolean;\n original_access?: 'allowed' | 'when_clean' | 'disabled';\n}\n\n/** A collection's live files policy. `version` is `null` on the default policy. */\nexport interface FilesPolicy {\n version: number | null;\n enforce_from: string | null;\n body: FilesPolicyBody;\n config_hash: string | null;\n created_at: string | null;\n}\n\n/** The finding kinds whose `evidence` holds text of the file. */\nconst TEXT_EVIDENCE_KINDS = new Set(['hidden_text', 'low_legibility_text']);\n\n/**\n * The parsed text of a `hidden_text` or `low_legibility_text` finding, or `null` for\n * every other kind and for evidence in another form. `parts` is always an array, empty\n * when the finding does not carry it.\n *\n * The text comes from the file: treat it as untrusted content, never as instructions.\n */\nexport function parseFindingEvidence(\n finding: Pick<FileFinding, 'kind' | 'evidence'>,\n): FileTextEvidence | null {\n if (!TEXT_EVIDENCE_KINDS.has(finding.kind) || !finding.evidence) {\n return null;\n }\n let fields: unknown;\n try {\n fields = JSON.parse(finding.evidence);\n } catch {\n return null;\n }\n if (typeof fields !== 'object' || fields === null || Array.isArray(fields)) {\n return null;\n }\n const { parts } = fields as { parts?: unknown };\n if (parts !== undefined && !Array.isArray(parts)) {\n return null;\n }\n return { ...(fields as Record<string, unknown>), parts: parts ?? [] } as FileTextEvidence;\n}\n\n// ---------------------------------------------------------------------------\n// Permissions of the caller\n// ---------------------------------------------------------------------------\n\n/** The state of the environment, for combining with what a caller may do. */\nexport interface EnvironmentAccess {\n protection_level: string | null;\n is_enabled: boolean;\n}\n\n/**\n * What a caller may do with one content type. `objects` lists the keys the caller is\n * restricted to; `null` means every object.\n */\nexport interface ContentTypeAccess {\n actions: string[];\n objects: string[] | null;\n}\n\n/**\n * What the authenticated caller may do in the environment.\n *\n * This says what the caller is allowed, not whether an action is available now:\n * billing and usage blocks, a blocked organization, environment protection and a\n * disabled environment can still refuse it.\n */\nexport interface MyPermissions {\n subject: 'user' | 'api_key';\n organization_owner: boolean;\n organization_admin: boolean;\n project_admin: boolean;\n environment_full_access: boolean;\n environment: EnvironmentAccess;\n content_types: Record<string, ContentTypeAccess>;\n}\n\n// ---------------------------------------------------------------------------\n// Reference types (allow string key or model object)\n// ---------------------------------------------------------------------------\n\nexport type FolderRef = string | FolderSummary;\n/** @public Alias of {@link FolderRef} — preferred name in new code. */\nexport type CollectionRef = FolderRef;\nexport type ResourceRef = string | ResourceSummary;\nexport type RevisionRef = string | RevisionSummary;\nexport type ComponentRef = string | ComponentSummary;\nexport type SchemaVersionRef = string | SchemaVersionSummary;\nexport type OrgRef = string | OrganizationSummary;\nexport type ProjectRef = string | ProjectSummary;\nexport type EnvironmentRef = string | EnvironmentSummary;\nexport type ManagementRoleRef = string | ManagementRoleSummary;\nexport type FluxRoleRef = string | FluxRoleSummary;\nexport type ManagementAPIKeyRef = string | ManagementAPIKeySummary;\nexport type FluxAPIKeyRef = string | FluxAPIKeySummary;\nexport type APIRef = string | APIInfo;\n\n/**\n * Extract a string key from a value that is either a string or\n * an object with a `key` attribute.\n */\nexport function resolveKey(value: string | { key: string }): string {\n if (typeof value === 'string') {\n return value;\n }\n if (value && typeof value === 'object' && 'key' in value && typeof value.key === 'string') {\n return value.key;\n }\n throw new TypeError(`Expected a string or an object with a 'key' attribute, got ${typeof value}`);\n}\n\n// ---------------------------------------------------------------------------\n// Webhooks\n// ---------------------------------------------------------------------------\n\n/** What an endpoint receives: ids and links only, or a snapshot of the content. */\nexport type WebhookPayloadMode = 'references' | 'content';\n\n/** `active`, `paused`, or `disabled` by FoxNose after `410 Gone` or five days of failures. */\nexport type WebhookEndpointStatus = 'active' | 'paused' | 'disabled';\n\n/** Attempts of the last 24 hours: all of them and those answered with `2xx`. */\nexport interface WebhookStats24h {\n attempts: number;\n succeeded: number;\n}\n\n/**\n * A webhook endpoint. It never carries the signing secret. `stats_24h` is set on\n * the items of a list only.\n */\nexport interface WebhookEndpoint {\n id: string;\n url: string;\n description: string;\n event_types: string[];\n collection_keys: string[];\n payload_mode: WebhookPayloadMode;\n version: number;\n status: WebhookEndpointStatus;\n /** `gone` (it answered `410 Gone`) or `failing` (no success for 5 days). */\n disabled_reason: string | null;\n failing_since: string | null;\n disabled_at: string | null;\n created_at: string;\n updated_at: string;\n stats_24h?: WebhookStats24h;\n}\n\nexport type WebhookEndpointList = PaginatedResponse<WebhookEndpoint>;\n\n/**\n * The answer to creating an endpoint: the endpoint and its signing secret.\n *\n * `secret` is not enumerable: `console.log`, `JSON.stringify`, `util.inspect` and a\n * spread leave it out, and only a direct read, `created.secret`, returns it. Read it\n * again later with {@link ManagementClient.getWebhookEndpointSecret}.\n */\nexport interface WebhookEndpointCreated extends WebhookEndpoint {\n readonly secret: string;\n}\n\n/** The current signing secret. `secret` is not enumerable, like {@link WebhookEndpointCreated.secret}. */\nexport interface WebhookSecret {\n readonly secret: string | null;\n}\n\n/**\n * The answer to rotating a secret. `previous_secret_expires_at` is when the old\n * secret stops being used, or `null` when none is left. `secret` is not enumerable.\n */\nexport interface WebhookSecretRotation {\n readonly secret: string;\n previous_secret_expires_at: string | null;\n}\n\n/** Body of {@link ManagementClient.createWebhookEndpoint}. */\nexport interface WebhookEndpointCreateRequest {\n /** The `https` URL deliveries are sent to. */\n url: string;\n /** Event types to receive, at least one. */\n event_types: string[];\n /** At most 255 characters. */\n description?: string;\n /** Collections to receive events from, at most 50. Empty or omitted for every collection. */\n collection_keys?: CollectionRef[];\n /** `references` (the default) or `content`. */\n payload_mode?: WebhookPayloadMode;\n /** Payload version; `1` is the only one. */\n version?: number;\n}\n\n/** Body of {@link ManagementClient.updateWebhookEndpoint}: send only the fields to change. */\nexport interface WebhookEndpointUpdateRequest extends Partial<WebhookEndpointCreateRequest> {\n /** `active` resumes a paused or disabled endpoint and clears its failure streak. */\n status?: 'active' | 'paused';\n}\n\n/** The endpoint of a delivery or an attempt; `deleted` once it was removed. */\nexport interface WebhookEndpointRef {\n id: string;\n deleted: boolean;\n}\n\n/** One event sent to one endpoint, with all its attempts. */\nexport interface WebhookDelivery {\n id: string;\n endpoint: WebhookEndpointRef;\n /** `pending`, `succeeded` or `dead`. */\n status: 'pending' | 'succeeded' | 'dead';\n attempts: number;\n last_status_code: number | null;\n last_error: string | null;\n created_at: string;\n finished_at: string | null;\n /** Set only while the delivery is pending. */\n next_attempt_at: string | null;\n}\n\n/** The event a delivery carries. */\nexport interface WebhookDeliveryEvent {\n id: string;\n type: string;\n test: boolean;\n}\n\n/** A delivery in an endpoint's delivery list. `event` is `null` once the event has aged out. */\nexport interface WebhookEndpointDelivery extends WebhookDelivery {\n event_id: string;\n event: WebhookDeliveryEvent | null;\n}\n\nexport type WebhookEndpointDeliveryList = PaginatedResponse<WebhookEndpointDelivery>;\n\n/** How many deliveries of an event are in each status. */\nexport interface WebhookDeliveryCounts {\n pending: number;\n succeeded: number;\n dead: number;\n}\n\n/** An event of the log. `delivery_counts` is set on the items of a list only. */\nexport interface WebhookEvent {\n id: string;\n type: string;\n created_at: string;\n test: boolean;\n collection_key: string | null;\n delivery_counts?: WebhookDeliveryCounts;\n}\n\nexport type WebhookEventList = PaginatedResponse<WebhookEvent>;\n\n/**\n * One event with its envelope and all its deliveries, oldest first. `envelope` is the\n * event as a references-only endpoint receives it; the log never returns content.\n */\nexport interface WebhookEventDetail extends WebhookEvent {\n envelope: Record<string, unknown>;\n deliveries: WebhookDelivery[];\n}\n\n/**\n * One try to deliver an event. `response_excerpt` is the first 1 KB of what the\n * endpoint answered.\n */\nexport interface WebhookAttempt {\n id: string;\n delivery_id: string;\n endpoint: WebhookEndpointRef;\n created_at: string;\n status_code: number | null;\n latency_ms: number;\n error_class: string | null;\n response_excerpt: string;\n}\n\nexport type WebhookAttemptList = PaginatedResponse<WebhookAttempt>;\n\n/** The answer to sending a test event. */\nexport interface WebhookTestEvent {\n event_id: string;\n delivery_id: string;\n}\n\n/**\n * The answer to recovering failed deliveries: `requeued` were queued, and `more` is\n * `true` when another call with the same `since` has more to do.\n */\nexport interface WebhookRecovery {\n requeued: number;\n more: boolean;\n}\n\n/** A delivery created by redelivering an event. */\nexport interface WebhookRedelivery {\n id: string;\n endpoint_id: string;\n}\n\n/**\n * An endpoint an event was not redelivered to. `reason` is `deleted`, `paused`,\n * `disabled` or `endpoint_not_subscribed`.\n */\nexport interface WebhookSkippedEndpoint {\n endpoint_id: string;\n reason: string;\n}\n\n/** The answer to redelivering an event. */\nexport interface WebhookRedeliveryResult {\n event_id: string;\n deliveries: WebhookRedelivery[];\n skipped: WebhookSkippedEndpoint[];\n}\n\n/** An event type of the catalogue. `collection_scoped` is true when every event of the type belongs to a collection. */\nexport interface WebhookEventType {\n name: string;\n description: string;\n collection_scoped: boolean;\n /** JSON Schemas (draft 2020-12) of the event's `data` per payload mode. */\n schemas: {\n references: Record<string, unknown>;\n content: Record<string, unknown>;\n };\n}\n\n/** The event-type catalogue; it is not paginated. */\nexport interface WebhookEventTypeList {\n results: WebhookEventType[];\n}\n\n/** Filters of {@link ManagementClient.listWebhookEvents}. */\nexport interface WebhookEventListParams {\n type?: string;\n /** An endpoint `id`. */\n endpoint?: string;\n status?: 'pending' | 'succeeded' | 'dead';\n /** `true` for test events only, `false` to leave them out. */\n test?: boolean;\n /** ISO 8601; a time without a zone is read as UTC. */\n after?: string;\n before?: string;\n /** At most 200. */\n limit?: number;\n offset?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Tenant signing keys and tenant limits\n// ---------------------------------------------------------------------------\n\n/**\n * A tenant signing key: the public key your backend signs tenant tokens with.\n * `status` is `active`, `revoked` or `parent_deleted`. Every field except\n * `description`, `limits` and `not_before` is fixed at creation.\n */\nexport interface TenantSigningKey {\n kid: string;\n status: string;\n parent_key: string;\n public_key: string;\n anchor_collections: string[];\n collections: string[];\n shared_read: string[];\n apis: Record<string, string[]>;\n max_ttl_seconds: number;\n max_anchors: number;\n limits: Record<string, number | null> | null;\n not_before: string | null;\n revocation_generation: number;\n description: string;\n created_at: string;\n revoked_at: string | null;\n revoked_by: string | null;\n last_used_at: string | null;\n oauth: null;\n oauth_state: string;\n [key: string]: unknown;\n}\n\nexport type TenantSigningKeyList = PaginatedResponse<TenantSigningKey>;\n\n/**\n * The answer to creating a signing key. `private_key` (base64 PKCS#8 DER) is set only\n * when FoxNose generated the pair, only in this answer, and is not enumerable: read it\n * as `created.private_key`; it stays out of `JSON.stringify` and logs.\n */\nexport interface TenantSigningKeyCreated extends TenantSigningKey {\n private_key?: string | null;\n}\n\n/** The body of {@link ManagementClient.createTenantSigningKey}. Send exactly one of `public_key` and `generate`. */\nexport interface TenantSigningKeyCreateRequest {\n parent_key: FluxAPIKeyRef;\n anchor_collections: CollectionRef[];\n apis: Record<string, string[]>;\n public_key?: string;\n generate?: boolean;\n collections?: CollectionRef[];\n shared_read?: CollectionRef[];\n max_ttl_seconds?: number;\n max_anchors?: number;\n limits?: { rpm_per_subject?: number | null; uploads_per_subject_per_hour?: number | null };\n description?: string;\n}\n\n/** The body of {@link ManagementClient.updateTenantSigningKey}. Send at least one field. */\nexport interface TenantSigningKeyUpdateRequest {\n description?: string;\n /** `null` clears the per-key limits. */\n limits?: { rpm_per_subject?: number | null; uploads_per_subject_per_hour?: number | null } | null;\n /** `'now'` (60 seconds from now), a `Date`, or an ISO 8601 time with an offset. */\n not_before?: 'now' | Date | string;\n}\n\n/** A revocation entry. The `jti` or `sub` itself is not stored, only its hash. */\nexport interface TenantTokenRevocation {\n kind: 'jti' | 'sub' | string;\n value_hash: string;\n before?: string | null;\n created_at?: string | null;\n expires_at?: string | null;\n revocation_generation?: number | null;\n [key: string]: unknown;\n}\n\n/** Rate limits for tenant tokens. `null` means the default. */\nexport interface TenantLimitValues {\n /** Requests per minute for one end user (`sub`). */\n rpm_per_subject: number | null;\n /** Requests per minute for one owner record, across every token that names it. */\n rpm_per_anchor: number | null;\n /** Upload starts per hour for one end user (`sub`). */\n uploads_per_subject_per_hour: number | null;\n}\n\nexport interface TenantLimits extends TenantLimitValues {\n defaults?: TenantLimitValues;\n ceilings?: TenantLimitValues;\n [key: string]: unknown;\n}\n\n// ---------------------------------------------------------------------------\n// Guardrails\n// ---------------------------------------------------------------------------\n\n/** A tainted field of a record or revision. `cause` is `writer`, `declared` or `schema`. */\nexport interface GuardrailsUntrustedField {\n path: string;\n field_label?: string | null;\n writer_type?: string | null;\n cause?: string | null;\n reviewed?: boolean | null;\n principal_key?: string | null;\n [key: string]: unknown;\n}\n\n/** A record's trust summary (`ResourceSummary.guardrails`). */\nexport interface ResourceGuardrailsSummary {\n untrusted: boolean;\n needs_review: boolean;\n verdict: string | null;\n held: boolean;\n untrusted_fields: GuardrailsUntrustedField[];\n [key: string]: unknown;\n}\n\n/** A revision's trust summary (`RevisionSummary.guardrails`). */\nexport interface RevisionGuardrailsSummary {\n untrusted: boolean;\n needs_review: boolean;\n tainted_paths: string[];\n state: string | null;\n review_state: string | null;\n verdict: string | null;\n reason: string | null;\n reasons: string[];\n held: boolean;\n untrusted_fields: GuardrailsUntrustedField[];\n [key: string]: unknown;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction untrustedFields(value: unknown): GuardrailsUntrustedField[] {\n // always sent: missing or null must not read as \"nothing untrusted\"\n if (!Array.isArray(value) || !value.every(isUntrustedField)) {\n throw new TypeError('guardrails.untrusted_fields is malformed');\n }\n return value as GuardrailsUntrustedField[];\n}\n\nconst UNTRUSTED_FIELD_STRINGS = ['field_label', 'writer_type', 'cause', 'principal_key'];\n\n/** Every documented field has its type; other fields pass through. */\nfunction isUntrustedField(value: unknown): boolean {\n if (!isPlainObject(value) || typeof value.path !== 'string') {\n return false;\n }\n const absentOrNull = (v: unknown) => v === undefined || v === null;\n return (\n UNTRUSTED_FIELD_STRINGS.every((k) => absentOrNull(value[k]) || typeof value[k] === 'string') &&\n (absentOrNull(value.reviewed) || typeof value.reviewed === 'boolean')\n );\n}\n\nfunction str(value: unknown, name: string): string | null {\n if (value === undefined || value === null) {\n return null;\n }\n if (typeof value !== 'string') {\n throw new TypeError(`guardrails.${name} is not a string`);\n }\n return value;\n}\n\nfunction bool(value: unknown, name: string): boolean {\n // always sent: missing or null must not read as false\n if (typeof value !== 'boolean') {\n throw new TypeError(`guardrails.${name} is not a boolean`);\n }\n return value;\n}\n\n/**\n * A record's `guardrails` as a typed summary, or `null` when it has none.\n * The field itself stays a plain object.\n * @throws TypeError The summary does not have the documented shape.\n */\nexport function getResourceGuardrailsSummary(\n resource: Pick<ResourceSummary, 'guardrails'>,\n): ResourceGuardrailsSummary | null {\n const g = resource.guardrails;\n if (g === undefined || g === null) {\n return null;\n }\n if (!isPlainObject(g)) {\n throw new TypeError('guardrails is not an object');\n }\n return {\n ...g,\n untrusted: bool(g.untrusted, 'untrusted'),\n needs_review: bool(g.needs_review, 'needs_review'),\n verdict: str(g.verdict, 'verdict'),\n held: bool(g.held, 'held'),\n untrusted_fields: untrustedFields(g.untrusted_fields),\n };\n}\n\n/**\n * A revision's `guardrails` as a typed summary, or `null` when it has none.\n * @throws TypeError The summary does not have the documented shape.\n */\nexport function getRevisionGuardrailsSummary(\n revision: Pick<RevisionSummary, 'guardrails'>,\n): RevisionGuardrailsSummary | null {\n const g = revision.guardrails;\n if (g === undefined || g === null) {\n return null;\n }\n if (!isPlainObject(g)) {\n throw new TypeError('guardrails is not an object');\n }\n const list = (v: unknown, name: string): string[] => {\n if (!Array.isArray(v) || !v.every((x) => typeof x === 'string')) {\n throw new TypeError(`guardrails.${name} is not a list of strings`);\n }\n return v as string[];\n };\n return {\n ...g,\n untrusted: bool(g.untrusted, 'untrusted'),\n needs_review: bool(g.needs_review, 'needs_review'),\n tainted_paths: list(g.tainted_paths, 'tainted_paths'),\n state: str(g.state, 'state'),\n review_state: str(g.review_state, 'review_state'),\n verdict: str(g.verdict, 'verdict'),\n reason: str(g.reason, 'reason'),\n reasons: list(g.reasons, 'reasons'),\n held: bool(g.held, 'held'),\n untrusted_fields: untrustedFields(g.untrusted_fields),\n };\n}\n\n/** The guardrails policy body keys the API accepts. */\nexport const GUARDRAILS_POLICY_FIELDS = [\n 'mode',\n 'overrides',\n 'trusted_keys',\n 'acknowledge_agent_trust',\n 'link_allowlist',\n 'hold',\n 'suspicious_action',\n 'screen',\n 'max_screened_chars',\n] as const;\n\n/**\n * A guardrails policy to send. Only the fields that are set are sent: a `mode` left\n * out keeps the collection's mode. `hold`, `suspicious_action`, `screen` and\n * `max_screened_chars` belong to `screened` mode.\n */\nexport interface GuardrailsPolicyBody {\n mode?: 'off' | 'provenance' | 'screened';\n overrides?: Record<string, string>;\n trusted_keys?: string[];\n acknowledge_agent_trust?: boolean;\n link_allowlist?: string[];\n hold?: boolean;\n suspicious_action?: string;\n screen?: string;\n max_screened_chars?: number;\n}\n\n/** A Flux API that delivers the collection with trust metadata. */\nexport interface GuardrailsDeliveredBy {\n api_key: string;\n name?: string | null;\n trust_delivery?: string | null;\n}\n\n/** A collection's live guardrails policy. `version` is `null` without a policy. */\nexport interface GuardrailsPolicy {\n version: number | null;\n body: GuardrailsPolicyBody & Record<string, unknown>;\n config_hash: string | null;\n created_at: string | null;\n delivered_by: GuardrailsDeliveredBy[];\n [key: string]: unknown;\n}\n\n/** A guardrails finding, with its words from the catalog. */\nexport interface GuardrailsFinding {\n kind: string;\n sub_kind?: string | null;\n /** `held` for a `screen_unavailable` finding. */\n severity?: string | null;\n path?: string | null;\n detector?: string | null;\n detector_version?: string | null;\n detail?: Record<string, unknown> | null;\n policy_version?: number | null;\n created_at?: string | null;\n title?: string | null;\n field_label?: string | null;\n summary?: string | null;\n [key: string]: unknown;\n}\n\n/** One reason a revision is or was held. */\nexport interface GuardrailsWhy {\n code: string;\n text: string;\n}\n\nexport interface GuardrailsWriter {\n writer_type?: string | null;\n surface?: string | null;\n principal_key?: string | null;\n [key: string]: unknown;\n}\n\nexport interface GuardrailsTaintedField {\n path: string;\n field_label?: string | null;\n writer_type?: string | null;\n revision_number?: number | null;\n carried?: boolean | null;\n cause?: string | null;\n [key: string]: unknown;\n}\n\n/** The named fields of a held revision, without an index signature. */\nexport interface HeldRevisionFields {\n resource_key: string;\n revision_key: string;\n number?: number | null;\n state?: string | null;\n review_state?: string | null;\n verdict?: string | null;\n reasons: string[];\n reviewed_by?: string | null;\n reviewed_at?: string | null;\n review_reason?: string | null;\n release_policy?: string | null;\n created_at?: string | null;\n writer?: GuardrailsWriter | null;\n tainted: GuardrailsTaintedField[];\n findings: GuardrailsFinding[];\n why: GuardrailsWhy[];\n}\n\n/**\n * A retained held revision. `state` is `pending`, `failed` or `done`; `review_state`\n * is `none`, `superseded`, `blocked` or `rejected`.\n */\nexport interface HeldRevision extends HeldRevisionFields {\n [key: string]: unknown;\n}\n\nexport type HeldRevisionList = PaginatedResponse<HeldRevision>;\n\n/** `needs_review`, `screening`, `blocked`, `rejected` or `superseded`. */\nexport type HeldRevisionStatus =\n | 'needs_review'\n | 'screening'\n | 'blocked'\n | 'rejected'\n | 'superseded';\n\n/** The answer to releasing or rejecting a held revision. */\nexport interface HeldRevisionDecision {\n revision_key: string;\n published: boolean;\n review_state?: string | null;\n verdict?: string | null;\n reasons?: string[] | null;\n screened?: boolean | null;\n [key: string]: unknown;\n}\n\n/** A held revision for a batch call: a pair, or an object with both keys. */\nexport type HeldRevisionRef =\n | readonly [resource: ResourceRef, revision: RevisionRef]\n | { resource_key: string; revision_key: string };\n\nexport interface GuardrailsBatchItemResult {\n resource_key: string;\n revision_key: string;\n /** `rejected`, `queued` or `error`. */\n outcome: string;\n code?: string | null;\n}\n\n/** Every item's outcome, in request order. */\nexport interface GuardrailsBatchResult {\n results: GuardrailsBatchItemResult[];\n}\n\nexport interface GuardrailsUsage {\n backlog: { candidates: number; max_candidates?: number; bytes: number; max_bytes?: number };\n screening_budget: {\n available: boolean;\n hour_ends_at?: string | null;\n principals: Array<{\n principal_key: string | null;\n writer_type?: string | null;\n trusted?: boolean | null;\n used_chars: number;\n limit?: number | null;\n variants: Array<Record<string, unknown>>;\n }>;\n principals_total?: number;\n };\n [key: string]: unknown;\n}\n\n/**\n * An entry of the environment's review queue. With `kind=held` it is a held revision\n * plus `collection`, `collection_name` and `name`; with `kind=needs_review` it is a\n * record with `guardrails`, `current_revision` and `current_revision_published_at`.\n */\nexport interface GuardrailsReviewItem extends Partial<Omit<HeldRevisionFields, 'resource_key'>> {\n collection: string;\n collection_name?: string | null;\n resource_key: string;\n name?: string | null;\n guardrails?: ResourceGuardrailsSummary | null;\n current_revision?: string | null;\n current_revision_published_at?: string | null;\n created_at?: string | null;\n [key: string]: unknown;\n}\n\nexport type GuardrailsReviewQueue = PaginatedResponse<GuardrailsReviewItem>;\n\n/** The team view of a revision's guardrails. */\nexport interface RevisionGuardrails {\n review: {\n state: string | null;\n review_state: string | null;\n verdict: string | null;\n reviewed_by: string | null;\n reviewed_at: string | null;\n reason: string | null;\n release_policy: string | null;\n } | null;\n provenance: Record<string, unknown> | null;\n findings: GuardrailsFinding[];\n why: GuardrailsWhy[];\n untrusted_fields: GuardrailsUntrustedField[];\n needs_review: boolean;\n [key: string]: unknown;\n}\n\n/** The revision created by marking a record as reviewed. */\nexport interface MarkReviewedResult {\n revision_key: string;\n number: number;\n tainted_paths: string[];\n}\n\n/** The wording the API uses for findings, states and writers. */\nexport interface GuardrailsCatalog {\n kinds: Record<string, { title: string; description: string }>;\n unicode_classes?: Record<string, unknown>;\n severities?: Record<string, unknown>;\n writers?: Record<string, unknown>;\n trust?: Record<string, unknown>;\n provenance?: Record<string, unknown>;\n verdicts?: Record<string, unknown>;\n review_states?: Record<string, unknown>;\n screening_states?: Record<string, unknown>;\n held?: string;\n causes?: Record<string, string>;\n default_cause?: string;\n [key: string]: unknown;\n}\n","/**\n * URL path builders for Management API endpoints.\n * Equivalent to Python SDK's _ManagementPathsMixin.\n */\nexport function managementPaths(environmentKey: string) {\n return {\n // Organization paths\n orgRoot: (orgKey: string) => `/organizations/${orgKey}`,\n projectsBase: (orgKey: string) => `/organizations/${orgKey}/projects`,\n projectRoot: (orgKey: string, projectKey: string) =>\n `/organizations/${orgKey}/projects/${projectKey}`,\n environmentsBase: (orgKey: string, projectKey: string) =>\n `/organizations/${orgKey}/projects/${projectKey}/environments`,\n environmentRoot: (orgKey: string, projectKey: string, envKey: string) =>\n `/organizations/${orgKey}/projects/${projectKey}/environments/${envKey}`,\n\n // Folder paths (deprecated — see Collection paths below).\n foldersTreeRoot: () => `/v1/${environmentKey}/folders/tree`,\n foldersTreeItem: () => `/v1/${environmentKey}/folders/tree/folder`,\n folderVersionsBase: (folderKey: string) =>\n `/v1/${environmentKey}/folders/${folderKey}/model/versions`,\n folderSchemaTree: (folderKey: string, versionKey: string) =>\n `/v1/${environmentKey}/folders/${folderKey}/model/versions/${versionKey}/schema/tree`,\n\n // Collection paths (canonical going forward; folder paths above hit the\n // deprecated /folders/ URL alias on the server side).\n collectionsTreeRoot: () => `/v1/${environmentKey}/collections/tree`,\n collectionsTreeItem: () => `/v1/${environmentKey}/collections/tree/collection`,\n collectionVersionsBase: (collectionKey: string) =>\n `/v1/${environmentKey}/collections/${collectionKey}/model/versions`,\n collectionSchemaTree: (collectionKey: string, versionKey: string) =>\n `/v1/${environmentKey}/collections/${collectionKey}/model/versions/${versionKey}/schema/tree`,\n collectionSyncComponent: (collectionKey: string) =>\n `/v1/${environmentKey}/collections/${collectionKey}/sync_component`,\n\n // Component paths\n componentsRoot: () => `/v1/${environmentKey}/components`,\n componentRoot: (componentKey: string) => `/v1/${environmentKey}/components/${componentKey}`,\n componentVersionsBase: (componentKey: string) =>\n `/v1/${environmentKey}/components/${componentKey}/model/versions`,\n componentSchemaTree: (componentKey: string, versionKey: string) =>\n `/v1/${environmentKey}/components/${componentKey}/model/versions/${versionKey}/schema/tree`,\n\n // Resource paths\n resourceBase: (folderKey: string) => `/v1/${environmentKey}/folders/${folderKey}/resources`,\n revisionBase: (folderKey: string, resourceKey: string) =>\n `/v1/${environmentKey}/folders/${folderKey}/resources/${resourceKey}/revisions`,\n\n // Files paths\n uploadLinksRoot: (collectionKey: string) =>\n `/v1/${environmentKey}/collections/${collectionKey}/upload-links`,\n uploadLinkRoot: (collectionKey: string, uploadId: string) =>\n `/v1/${environmentKey}/collections/${collectionKey}/upload-links/${encodeURIComponent(uploadId)}`,\n fileRoot: (collectionKey: string, resourceKey: string) =>\n `/v1/${environmentKey}/collections/${collectionKey}/files/${resourceKey}`,\n fileTombstonesRoot: (collectionKey: string) =>\n `/v1/${environmentKey}/collections/${collectionKey}/files/tombstones`,\n filesPolicyRoot: (collectionKey: string) =>\n `/v1/${environmentKey}/collections/${collectionKey}/files-policy`,\n filesReviewRoot: () => `/v1/${environmentKey}/files/review`,\n\n // Webhooks paths\n webhooksRoot: () => `/v1/${environmentKey}/webhooks`,\n webhookEndpointRoot: (endpointId: string) =>\n `/v1/${environmentKey}/webhooks/endpoints/${encodeURIComponent(endpointId)}`,\n webhookEventRoot: (eventId: string) =>\n `/v1/${environmentKey}/webhooks/events/${encodeURIComponent(eventId)}`,\n\n // Tenant token paths\n tenantSigningKeysRoot: () => `/v1/${environmentKey}/tenant-signing-keys`,\n tenantSigningKeyRoot: (kid: string) =>\n `/v1/${environmentKey}/tenant-signing-keys/${encodeURIComponent(kid)}`,\n tenantLimitsRoot: () => `/v1/${environmentKey}/tenant-limits`,\n\n // Guardrails paths\n guardrailsPolicyRoot: (collectionKey: string) =>\n `/v1/${environmentKey}/collections/${collectionKey}/guardrails-policy`,\n guardrailsHeldRoot: (collectionKey: string) =>\n `/v1/${environmentKey}/collections/${collectionKey}/guardrails/held`,\n guardrailsUsageRoot: (collectionKey: string) =>\n `/v1/${environmentKey}/collections/${collectionKey}/guardrails/usage`,\n revisionGuardrailsRoot: (collectionKey: string, resourceKey: string, revisionKey: string) =>\n `/v1/${environmentKey}/collections/${collectionKey}/resources/${resourceKey}/revisions/${revisionKey}/guardrails`,\n resourceGuardrailsRoot: (collectionKey: string, resourceKey: string) =>\n `/v1/${environmentKey}/collections/${collectionKey}/resources/${resourceKey}/guardrails`,\n guardrailsReviewRoot: () => `/v1/${environmentKey}/guardrails/review`,\n guardrailsCatalogRoot: () => `/v1/${environmentKey}/guardrails/catalog`,\n\n // Caller's own permissions\n myPermissionsRoot: () => `/v1/${environmentKey}/permissions/me`,\n\n // Management API key paths\n managementApiKeysRoot: () => `/v1/${environmentKey}/permissions/management-api/api-keys`,\n managementApiKeyRoot: (apiKey: string) =>\n `/v1/${environmentKey}/permissions/management-api/api-keys/${apiKey}`,\n\n // Flux API key paths\n fluxApiKeysRoot: () => `/v1/${environmentKey}/permissions/flux-api/api-keys`,\n fluxApiKeyRoot: (apiKey: string) =>\n `/v1/${environmentKey}/permissions/flux-api/api-keys/${apiKey}`,\n fluxApiKeyBearerTokenRoot: (apiKey: string) =>\n `/v1/${environmentKey}/permissions/flux-api/api-keys/${apiKey}/bearer-token`,\n\n // API management paths\n apisRoot: () => `/v1/${environmentKey}/api`,\n apiRoot: (apiKey: string) => `/v1/${environmentKey}/api/${apiKey}`,\n apiFoldersRoot: (apiKey: string) => `/v1/${environmentKey}/api/${apiKey}/folders`,\n apiCollectionsRoot: (apiKey: string) => `/v1/${environmentKey}/api/${apiKey}/collections`,\n\n // Management role paths\n managementRolesRoot: () => `/v1/${environmentKey}/permissions/management-api/roles`,\n managementRoleRoot: (roleKey: string) =>\n `/v1/${environmentKey}/permissions/management-api/roles/${roleKey}`,\n rolePermissionsRoot: (roleKey: string) =>\n `/v1/${environmentKey}/permissions/management-api/roles/${roleKey}/permissions`,\n rolePermissionsBatch: (roleKey: string) =>\n `/v1/${environmentKey}/permissions/management-api/roles/${roleKey}/permissions/batch`,\n rolePermissionObjectsRoot: (roleKey: string) =>\n `/v1/${environmentKey}/permissions/management-api/roles/${roleKey}/permissions/objects`,\n\n // Flux role paths\n fluxRolesRoot: () => `/v1/${environmentKey}/permissions/flux-api/roles`,\n fluxRoleRoot: (roleKey: string) =>\n `/v1/${environmentKey}/permissions/flux-api/roles/${roleKey}`,\n fluxRolePermissionsRoot: (roleKey: string) =>\n `/v1/${environmentKey}/permissions/flux-api/roles/${roleKey}/permissions`,\n fluxRolePermissionsBatch: (roleKey: string) =>\n `/v1/${environmentKey}/permissions/flux-api/roles/${roleKey}/permissions/batch`,\n fluxRolePermissionObjectsRoot: (roleKey: string) =>\n `/v1/${environmentKey}/permissions/flux-api/roles/${roleKey}/permissions/objects`,\n\n // Locale paths\n localesRoot: () => `/v1/${environmentKey}/locales`,\n localeRoot: (code: string) => `/v1/${environmentKey}/locales/${code}`,\n };\n}\n\nexport type ManagementPaths = ReturnType<typeof managementPaths>;\n","import type { AuthStrategy } from '../auth/types.js';\nimport type { RetryConfig } from '../config.js';\nimport { createConfig } from '../config.js';\nimport { HttpTransport } from '../http.js';\nimport { warnDeprecatedMethod } from '../_deprecation.js';\nimport type {\n GuardrailsBatchResult,\n GuardrailsCatalog,\n GuardrailsPolicy,\n GuardrailsPolicyBody,\n GuardrailsReviewQueue,\n GuardrailsUsage,\n HeldRevisionDecision,\n HeldRevisionList,\n HeldRevisionRef,\n HeldRevisionStatus,\n MarkReviewedResult,\n RevisionGuardrails,\n TenantLimitValues,\n TenantLimits,\n TenantSigningKey,\n TenantSigningKeyCreateRequest,\n TenantSigningKeyCreated,\n TenantSigningKeyList,\n TenantSigningKeyUpdateRequest,\n TenantTokenRevocation,\n APICollectionList,\n APICollectionSummary,\n APIFolderList,\n APIFolderSummary,\n APIInfo,\n APIList,\n APIRef,\n BatchItemError,\n BatchUpsertItem,\n BatchUpsertResult,\n CollectionList,\n CollectionRef,\n CollectionSummary,\n ComponentList,\n ComponentRef,\n ComponentSummary,\n EnvironmentList,\n EnvironmentRef,\n EnvironmentSummary,\n FieldList,\n FieldSummary,\n FileDownload,\n FilePageDetail,\n FileRecordView,\n FileReviewQueue,\n FilesPolicy,\n FilesPolicyBody,\n FileTombstoneList,\n FluxAPIKeyList,\n FluxAPIKeyRef,\n FluxAPIKeyBearerToken,\n FluxAPIKeySummary,\n FluxRoleList,\n FluxRoleRef,\n FluxRoleSummary,\n FolderList,\n FolderRef,\n FolderSummary,\n LocaleList,\n LocaleSummary,\n ManagementAPIKeyList,\n ManagementAPIKeyRef,\n ManagementAPIKeySummary,\n ManagementRoleList,\n ManagementRoleRef,\n ManagementRoleSummary,\n MyPermissions,\n OrgRef,\n OrganizationList,\n OrganizationPlanStatus,\n OrganizationSummary,\n OrganizationUsage,\n ProjectList,\n ProjectRef,\n ProjectSummary,\n RegionInfo,\n ResourceList,\n ResourceRef,\n ResourceSummary,\n RevisionList,\n RevisionRef,\n RevisionSummary,\n RolePermission,\n RolePermissionObject,\n SchemaVersionList,\n SchemaVersionRef,\n SchemaVersionSummary,\n SyncComponentResponse,\n UploadLink,\n UploadLinkCreated,\n UploadLinkCreateRequest,\n UploadLinkList,\n WebhookAttemptList,\n WebhookEndpoint,\n WebhookEndpointCreateRequest,\n WebhookEndpointCreated,\n WebhookEndpointDeliveryList,\n WebhookEndpointList,\n WebhookEndpointUpdateRequest,\n WebhookEventDetail,\n WebhookEventList,\n WebhookEventListParams,\n WebhookEventTypeList,\n WebhookRecovery,\n WebhookRedeliveryResult,\n WebhookSecret,\n WebhookSecretRotation,\n WebhookTestEvent,\n} from './models.js';\nimport { GUARDRAILS_POLICY_FIELDS, resolveKey } from './models.js';\nimport { managementPaths } from './paths.js';\nimport type { ManagementPaths } from './paths.js';\n\nexport interface ManagementClientOptions {\n baseUrl?: string;\n environmentKey: string;\n auth: AuthStrategy;\n timeout?: number;\n retryConfig?: RetryConfig;\n defaultHeaders?: Record<string, string>;\n}\n\nexport interface ApiFolderRouteDescriptionOptions {\n descriptionGetOne?: string;\n descriptionGetMany?: string;\n descriptionSearch?: string;\n descriptionSchema?: string;\n}\n\nexport interface ApiFolderOptions extends ApiFolderRouteDescriptionOptions {\n allowedMethods?: string[];\n /**\n * Ancestor levels (0 = fully flat) to expose as cross-parent read\n * addresses. Wire field `unscoped_levels`. Must be sent together with\n * `unscopedAncestors` — the server rejects a level with no corresponding\n * ancestor; not enforced client-side.\n */\n unscopedLevels?: number[];\n /**\n * Ancestor UUIDs (not collection keys) to leave unscoped at the\n * corresponding `unscopedLevels`. Wire field `unscoped_ancestors`.\n */\n unscopedAncestors?: string[];\n}\n\n/**\n * Make the signing secret of a response non-enumerable: `console.log`,\n * `JSON.stringify`, `util.inspect` and a spread leave it out, and a direct read,\n * `response.secret`, still returns it.\n */\nfunction hideSecret<T extends { secret?: string | null }>(response: T): T {\n if (response && typeof response === 'object' && 'secret' in response) {\n Object.defineProperty(response, 'secret', {\n value: response.secret,\n enumerable: false,\n writable: false,\n configurable: true,\n });\n }\n return response;\n}\n\n// ---------------------------------------------------------------------------\n// Tenant signing keys and guardrails: request bodies\n// ---------------------------------------------------------------------------\n\nfunction isInteger(value: unknown): boolean {\n return typeof value === 'number' && Number.isSafeInteger(value);\n}\n\n/** Per-key or environment limits, each an integer or `null`. */\nfunction limitValues(limits: Record<string, unknown>, name: string): Record<string, unknown> {\n for (const [key, value] of Object.entries(limits)) {\n if (value !== null && value !== undefined && !isInteger(value)) {\n throw new Error(`${name}.${key} must be an integer or null`);\n }\n }\n return limits;\n}\n\n// An ISO 8601 timestamp with a UTC offset (`Z` or `+hh:mm`), extended or basic form.\n// An ISO 8601 calendar date and time with a UTC offset, extended or basic form.\nconst TIMESTAMP_WITH_OFFSET =\n /^(\\d{4})(-?)(\\d{2})\\2(\\d{2})[Tt ](\\d{2})(?:(:?)(\\d{2})(?:\\6(\\d{2})(?:[.,](\\d+))?)?)?(?:[Zz]|[+-](\\d{2})(?::?(\\d{2}))?)$/;\nconst DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n\n/**\n * An ISO 8601 date and time with a UTC offset that core's parser reads: a calendar\n * date (`YYYY-MM-DD` or `YYYYMMDD`), `T`, `t` or a space, a time, and `Z`,\n * `+HH[[:]MM]` or `-HH[[:]MM]`. The date, the time and the offset must exist: no\n * month 13, no 30 February, no hour 25, no offset +24:00. `24:00` is accepted as\n * the end of the day, as core accepts it.\n */\nfunction isTimestampWithOffset(value: string): boolean {\n const match = TIMESTAMP_WITH_OFFSET.exec(value);\n if (match === null) return false;\n const n = (i: number) => Number(match[i] ?? 0);\n const [year, month, day, hour, minute, second] = [1, 3, 4, 5, 7, 8].map(n);\n const fraction = match[9] ?? '';\n const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n if (year < 1 || month < 1 || month > 12) return false;\n const days = month === 2 && leap ? 29 : DAYS_IN_MONTH[month - 1];\n if (day < 1 || day > days) return false;\n if (hour === 24) {\n // midnight at the end of the day, which does not exist after 9999-12-31\n const lastDay = year === 9999 && month === 12 && day === 31;\n if (minute || second || /[1-9]/.test(fraction) || lastDay) return false;\n } else if (hour > 23 || minute > 59 || second > 59) {\n return false;\n }\n if (match[10] !== undefined && (n(10) > 23 || n(11) > 59)) return false;\n return true;\n}\n\n/** A cutoff time: a `Date`, an ISO 8601 string with a UTC offset, or `'now'` where allowed. */\nfunction cutoff(value: Date | string, name: string, allowNow: boolean): string {\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) {\n throw new Error(`${name} is an invalid Date`);\n }\n return value.toISOString();\n }\n if (typeof value !== 'string') {\n throw new TypeError(`${name} must be a Date or a string`);\n }\n if (allowNow && value === 'now') {\n return value;\n }\n if (!isTimestampWithOffset(value)) {\n const expected = allowNow ? '\"now\" or ' : '';\n throw new Error(`${name} must be ${expected}an ISO 8601 timestamp with a UTC offset`);\n }\n return value;\n}\n\nfunction signingKeyBody(request: TenantSigningKeyCreateRequest): Record<string, unknown> {\n const hasPublic = request.public_key !== undefined;\n const generate = request.generate === true;\n if (hasPublic === generate) {\n throw new Error('Pass exactly one of public_key and generate: true');\n }\n const body: Record<string, unknown> = {\n parent_key: resolveKey(request.parent_key),\n anchor_collections: request.anchor_collections.map((c) => resolveKey(c)),\n apis: request.apis,\n };\n if (hasPublic) {\n body.public_key = request.public_key;\n } else {\n body.generate = true;\n }\n if (request.collections !== undefined) {\n body.collections = request.collections.map((c) => resolveKey(c));\n }\n if (request.shared_read !== undefined) {\n body.shared_read = request.shared_read.map((c) => resolveKey(c));\n }\n for (const name of ['max_ttl_seconds', 'max_anchors'] as const) {\n if (request[name] !== undefined) {\n if (!isInteger(request[name])) {\n throw new Error(`${name} must be an integer`);\n }\n body[name] = request[name];\n }\n }\n if (request.limits !== undefined) {\n body.limits = limitValues(request.limits, 'limits');\n }\n if (request.description !== undefined) {\n body.description = request.description;\n }\n return body;\n}\n\nfunction signingKeyPatchBody(changes: TenantSigningKeyUpdateRequest): Record<string, unknown> {\n const body: Record<string, unknown> = {};\n if (changes.description !== undefined) {\n body.description = changes.description;\n }\n if (changes.limits !== undefined) {\n body.limits = changes.limits === null ? null : limitValues(changes.limits, 'limits');\n }\n if (changes.not_before !== undefined) {\n body.not_before = cutoff(changes.not_before, 'not_before', true);\n }\n if (Object.keys(body).length === 0) {\n throw new Error('Pass at least one of description, limits and not_before');\n }\n return body;\n}\n\nfunction revocationBody(entry: {\n jti?: string;\n sub?: string;\n before?: Date | string;\n}): Record<string, unknown> {\n if ((entry.jti === undefined) === (entry.sub === undefined)) {\n throw new Error('Pass exactly one of jti and sub');\n }\n if (entry.jti !== undefined) {\n if (entry.before !== undefined) {\n throw new Error('before applies to a sub revocation only');\n }\n return { jti: entry.jti };\n }\n const body: Record<string, unknown> = { sub: entry.sub };\n if (entry.before !== undefined) {\n if (typeof entry.before === 'string' && entry.before.trim().toLowerCase() === 'now') {\n throw new Error('before must be a time; leave it out for 60 seconds from now');\n }\n body.before = cutoff(entry.before, 'before', false);\n }\n return body;\n}\n\nconst POLICY_FIELDS = new Set<string>(GUARDRAILS_POLICY_FIELDS);\n\nfunction guardrailsPolicyBody(payload: GuardrailsPolicyBody): Record<string, unknown> {\n if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {\n throw new TypeError('payload must be an object');\n }\n const unknown = Object.keys(payload).filter((name) => !POLICY_FIELDS.has(name));\n if (unknown.length > 0) {\n throw new Error(`Unknown guardrails policy field(s): ${unknown.sort().join(', ')}`);\n }\n const body: Record<string, unknown> = {};\n for (const [name, value] of Object.entries(payload)) {\n if (value !== undefined) {\n body[name] = value;\n }\n }\n return body;\n}\n\nfunction heldItems(\n items: readonly HeldRevisionRef[],\n): Array<{ resource_key: string; revision_key: string }> {\n const seen = new Set<string>();\n const result = items.map((item) => {\n const pair = Array.isArray(item)\n ? { resource_key: resolveKey(item[0]), revision_key: resolveKey(item[1]) }\n : {\n resource_key: (item as { resource_key: string }).resource_key,\n revision_key: (item as { revision_key: string }).revision_key,\n };\n const id = `${pair.resource_key}\\u0000${pair.revision_key}`;\n if (seen.has(id)) {\n throw new Error('Each held revision may appear once');\n }\n seen.add(id);\n return pair;\n });\n if (result.length < 1 || result.length > 50) {\n throw new Error('Pass 1 to 50 held revisions');\n }\n return result;\n}\n\n/** Make `private_key` non-enumerable, like a webhook secret. */\nfunction hidePrivateKey<T extends { private_key?: string | null }>(response: T): T {\n if (response && typeof response === 'object' && 'private_key' in response) {\n Object.defineProperty(response, 'private_key', {\n value: response.private_key,\n enumerable: false,\n writable: false,\n configurable: true,\n });\n }\n return response;\n}\n\n/** The body of an endpoint create or update, with collection keys resolved. */\nfunction webhookEndpointBody(\n request: WebhookEndpointCreateRequest | WebhookEndpointUpdateRequest,\n): Record<string, unknown> {\n const { collection_keys, ...rest } = request;\n return collection_keys === undefined\n ? rest\n : { ...rest, collection_keys: collection_keys.map((key) => resolveKey(key)) };\n}\n\n/**\n * Client for the FoxNose Management API.\n *\n * All methods are async and return parsed response objects.\n */\nexport class ManagementClient {\n readonly environmentKey: string;\n private readonly transport: HttpTransport;\n private readonly paths: ManagementPaths;\n\n constructor(options: ManagementClientOptions) {\n if (!options.environmentKey) {\n throw new Error('environmentKey must be provided');\n }\n this.environmentKey = options.environmentKey;\n const config = createConfig({\n baseUrl: options.baseUrl ?? 'https://api.foxnose.net',\n timeout: options.timeout,\n defaultHeaders: options.defaultHeaders,\n });\n this.transport = new HttpTransport({\n config,\n auth: options.auth,\n retryConfig: options.retryConfig,\n });\n this.paths = managementPaths(options.environmentKey);\n }\n\n /**\n * Low-level escape hatch for calling arbitrary endpoints.\n */\n async request(\n method: string,\n path: string,\n options?: {\n params?: Record<string, any>;\n jsonBody?: any;\n headers?: Record<string, string>;\n parseJson?: boolean;\n },\n ): Promise<any> {\n return this.transport.request(method, path, options);\n }\n\n close(): void {\n this.transport.close();\n }\n\n private normalizeListPayload<T>(payload: unknown): T[] {\n if (Array.isArray(payload)) {\n return payload as T[];\n }\n if (payload && typeof payload === 'object') {\n const results = (payload as { results?: unknown }).results;\n if (Array.isArray(results)) {\n return results as T[];\n }\n return [payload as T];\n }\n return [];\n }\n\n private normalizePermissionObjectPayload(\n payload: unknown,\n requestPayload: Record<string, any>,\n ): RolePermissionObject {\n if (payload && typeof payload === 'object' && !Array.isArray(payload)) {\n const data = { ...(payload as Record<string, any>) };\n if (!('object_key' in data) && 'object' in data) {\n data.object_key = data.object;\n delete data.object;\n }\n return data as RolePermissionObject;\n }\n\n return {\n content_type: requestPayload.content_type,\n object_key: requestPayload.object_key ?? requestPayload.object,\n };\n }\n\n private normalizePermissionObjectListPayload(payload: unknown): RolePermissionObject[] {\n return this.normalizeListPayload<Record<string, any>>(payload).map((item) =>\n this.normalizePermissionObjectPayload(item, item),\n );\n }\n\n // ------------------------------------------------------------------ //\n // Organization operations\n // ------------------------------------------------------------------ //\n\n async listOrganizations(): Promise<OrganizationList> {\n const payload = (await this.request('GET', '/organizations/')) ?? [];\n return Array.isArray(payload) ? payload : [payload];\n }\n\n async getOrganization(orgKey: OrgRef): Promise<OrganizationSummary> {\n const key = resolveKey(orgKey);\n return this.request('GET', `${this.paths.orgRoot(key)}/`);\n }\n\n async updateOrganization(\n orgKey: OrgRef,\n payload: Record<string, any>,\n ): Promise<OrganizationSummary> {\n const key = resolveKey(orgKey);\n return this.request('PUT', `${this.paths.orgRoot(key)}/`, { jsonBody: payload });\n }\n\n /**\n * Write the given fields of an organization and leave the rest alone. The\n * response is the whole organization as stored.\n */\n async patchOrganization(\n orgKey: OrgRef,\n payload: Record<string, any>,\n ): Promise<OrganizationSummary> {\n const key = resolveKey(orgKey);\n return this.request('PATCH', `${this.paths.orgRoot(key)}/`, { jsonBody: payload });\n }\n\n async listRegions(): Promise<RegionInfo[]> {\n const payload = (await this.request('GET', '/regions/')) ?? [];\n return Array.isArray(payload) ? payload : [payload];\n }\n\n async getAvailablePlans(): Promise<OrganizationPlanStatus> {\n return this.request('GET', '/plans/');\n }\n\n async getOrganizationPlan(orgKey: OrgRef): Promise<OrganizationPlanStatus> {\n const key = resolveKey(orgKey);\n return this.request('GET', `${this.paths.orgRoot(key)}/plan/`);\n }\n\n async setOrganizationPlan(orgKey: OrgRef, planCode: string): Promise<OrganizationPlanStatus> {\n const key = resolveKey(orgKey);\n return this.request('POST', `${this.paths.orgRoot(key)}/plan/${planCode}/`);\n }\n\n async getOrganizationUsage(orgKey: OrgRef): Promise<OrganizationUsage> {\n const key = resolveKey(orgKey);\n return this.request('GET', `${this.paths.orgRoot(key)}/usage/`);\n }\n\n // ------------------------------------------------------------------ //\n // Management API key operations\n // ------------------------------------------------------------------ //\n\n async listManagementApiKeys(params?: Record<string, any>): Promise<ManagementAPIKeyList> {\n return this.request('GET', `${this.paths.managementApiKeysRoot()}/`, { params });\n }\n\n async createManagementApiKey(payload: Record<string, any>): Promise<ManagementAPIKeySummary> {\n return this.request('POST', `${this.paths.managementApiKeysRoot()}/`, {\n jsonBody: payload,\n });\n }\n\n async getManagementApiKey(key: ManagementAPIKeyRef): Promise<ManagementAPIKeySummary> {\n const k = resolveKey(key);\n return this.request('GET', `${this.paths.managementApiKeyRoot(k)}/`);\n }\n\n async updateManagementApiKey(\n key: ManagementAPIKeyRef,\n payload: Record<string, any>,\n ): Promise<ManagementAPIKeySummary> {\n const k = resolveKey(key);\n return this.request('PUT', `${this.paths.managementApiKeyRoot(k)}/`, {\n jsonBody: payload,\n });\n }\n\n async deleteManagementApiKey(key: ManagementAPIKeyRef): Promise<void> {\n const k = resolveKey(key);\n await this.request('DELETE', `${this.paths.managementApiKeyRoot(k)}/`, {\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Flux API key operations\n // ------------------------------------------------------------------ //\n\n async listFluxApiKeys(params?: Record<string, any>): Promise<FluxAPIKeyList> {\n return this.request('GET', `${this.paths.fluxApiKeysRoot()}/`, { params });\n }\n\n async createFluxApiKey(payload: Record<string, any>): Promise<FluxAPIKeySummary> {\n return this.request('POST', `${this.paths.fluxApiKeysRoot()}/`, { jsonBody: payload });\n }\n\n async getFluxApiKey(key: FluxAPIKeyRef): Promise<FluxAPIKeySummary> {\n const k = resolveKey(key);\n return this.request('GET', `${this.paths.fluxApiKeyRoot(k)}/`);\n }\n\n async updateFluxApiKey(\n key: FluxAPIKeyRef,\n payload: Record<string, any>,\n ): Promise<FluxAPIKeySummary> {\n const k = resolveKey(key);\n return this.request('PUT', `${this.paths.fluxApiKeyRoot(k)}/`, { jsonBody: payload });\n }\n\n async deleteFluxApiKey(key: FluxAPIKeyRef): Promise<void> {\n const k = resolveKey(key);\n await this.request('DELETE', `${this.paths.fluxApiKeyRoot(k)}/`, { parseJson: false });\n }\n\n /**\n * Issue a bearer token for a Flux API key, or replace the existing one.\n *\n * A bearer token exists for clients that accept a single token value and send\n * it as `Authorization: Bearer <token>` with no way to choose the scheme —\n * hosted MCP connectors, notably the Claude API's `mcp_servers`. Those clients\n * cannot send `Simple` or `Secure` at all.\n *\n * THE PLAINTEXT IS RETURNED ONLY HERE, AND ONLY ONCE. The service stores a\n * hash, exactly as it does for `secret_key`, so a lost token is re-issued\n * rather than recovered. Subsequent key reads expose only\n * `bearer_token_prefix`.\n *\n * The key itself is untouched: `public_key`, `secret_key`, `role` and grants\n * all survive, so `Simple` and `Secure` integrations keep working across a\n * re-issue. That is what makes this the way to cut off a connector without\n * recreating a key and reconfiguring everything that uses it.\n *\n * There is at most one token per key; calling this again replaces it.\n */\n async issueFluxApiKeyBearerToken(key: FluxAPIKeyRef): Promise<FluxAPIKeyBearerToken> {\n const k = resolveKey(key);\n return this.request('POST', `${this.paths.fluxApiKeyBearerTokenRoot(k)}/`);\n }\n\n /**\n * Revoke a Flux API key's bearer token. The key and its role keep working.\n *\n * Idempotent: succeeds whether or not a token was issued.\n */\n async revokeFluxApiKeyBearerToken(key: FluxAPIKeyRef): Promise<void> {\n const k = resolveKey(key);\n await this.request('DELETE', `${this.paths.fluxApiKeyBearerTokenRoot(k)}/`, {\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // API management operations\n // ------------------------------------------------------------------ //\n\n async listApis(params?: Record<string, any>): Promise<APIList> {\n return this.request('GET', `${this.paths.apisRoot()}/`, { params });\n }\n\n async createApi(payload: Record<string, any>): Promise<APIInfo> {\n return this.request('POST', `${this.paths.apisRoot()}/`, { jsonBody: payload });\n }\n\n async getApi(apiKey: APIRef): Promise<APIInfo> {\n const key = resolveKey(apiKey);\n return this.request('GET', `${this.paths.apiRoot(key)}/`);\n }\n\n async updateApi(apiKey: APIRef, payload: Record<string, any>): Promise<APIInfo> {\n const key = resolveKey(apiKey);\n return this.request('PUT', `${this.paths.apiRoot(key)}/`, { jsonBody: payload });\n }\n\n async deleteApi(apiKey: APIRef): Promise<void> {\n const key = resolveKey(apiKey);\n await this.request('DELETE', `${this.paths.apiRoot(key)}/`, { parseJson: false });\n }\n\n /**\n * Build the request body shared by all four API-collection-association\n * writers: {@link addApiCollection}, {@link updateApiCollection}, and\n * their deprecated `*ApiFolder*` twins. All four accept {@link\n * ApiFolderOptions}, so this is the one place that maps its camelCase\n * fields to wire snake_case — adding a field here, rather than to each\n * method separately, is what keeps the deprecated twins from silently\n * swallowing a field the type says they accept.\n */\n private buildApiFolderPayload(options?: ApiFolderOptions): Record<string, any> {\n const body: Record<string, any> = {};\n if (options?.allowedMethods !== undefined) {\n body.allowed_methods = options.allowedMethods;\n }\n if (options?.descriptionGetOne !== undefined) {\n body.description_get_one = options.descriptionGetOne;\n }\n if (options?.descriptionGetMany !== undefined) {\n body.description_get_many = options.descriptionGetMany;\n }\n if (options?.descriptionSearch !== undefined) {\n body.description_search = options.descriptionSearch;\n }\n if (options?.descriptionSchema !== undefined) {\n body.description_schema = options.descriptionSchema;\n }\n if (options?.unscopedLevels !== undefined) {\n body.unscoped_levels = options.unscopedLevels;\n }\n if (options?.unscopedAncestors !== undefined) {\n body.unscoped_ancestors = options.unscopedAncestors;\n }\n return body;\n }\n\n // ------------------------------------------------------------------ //\n // API ↔ Collection association (canonical)\n // ------------------------------------------------------------------ //\n\n async listApiCollections(\n apiKey: APIRef,\n params?: Record<string, any>,\n ): Promise<APICollectionList> {\n const key = resolveKey(apiKey);\n return this.request('GET', `${this.paths.apiCollectionsRoot(key)}/`, { params });\n }\n\n async addApiCollection(\n apiKey: APIRef,\n collectionKey: CollectionRef,\n options?: ApiFolderOptions,\n ): Promise<APICollectionSummary> {\n const aKey = resolveKey(apiKey);\n const cKey = resolveKey(collectionKey);\n // Wire field name `folder` is preserved for backwards compat.\n const body: Record<string, any> = { folder: cKey, ...this.buildApiFolderPayload(options) };\n return this.request('POST', `${this.paths.apiCollectionsRoot(aKey)}/`, {\n jsonBody: body,\n });\n }\n\n async getApiCollection(\n apiKey: APIRef,\n collectionKey: CollectionRef,\n ): Promise<APICollectionSummary> {\n const aKey = resolveKey(apiKey);\n const cKey = resolveKey(collectionKey);\n return this.request('GET', `${this.paths.apiCollectionsRoot(aKey)}/${cKey}/`);\n }\n\n async updateApiCollection(\n apiKey: APIRef,\n collectionKey: CollectionRef,\n options?: ApiFolderOptions,\n ): Promise<APICollectionSummary> {\n const aKey = resolveKey(apiKey);\n const cKey = resolveKey(collectionKey);\n const body = this.buildApiFolderPayload(options);\n return this.request('PUT', `${this.paths.apiCollectionsRoot(aKey)}/${cKey}/`, {\n jsonBody: body,\n });\n }\n\n async removeApiCollection(apiKey: APIRef, collectionKey: CollectionRef): Promise<void> {\n const aKey = resolveKey(apiKey);\n const cKey = resolveKey(collectionKey);\n await this.request('DELETE', `${this.paths.apiCollectionsRoot(aKey)}/${cKey}/`, {\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // API ↔ Folder association (deprecated; hits legacy /folders/ URL)\n // ------------------------------------------------------------------ //\n\n /** @deprecated Use {@link listApiCollections} instead. */\n async listApiFolders(apiKey: APIRef, params?: Record<string, any>): Promise<APIFolderList> {\n warnDeprecatedMethod('listApiFolders', 'listApiCollections');\n const key = resolveKey(apiKey);\n return this.request('GET', `${this.paths.apiFoldersRoot(key)}/`, { params });\n }\n\n /** @deprecated Use {@link addApiCollection} instead. */\n async addApiFolder(\n apiKey: APIRef,\n folderKey: FolderRef,\n options?: ApiFolderOptions,\n ): Promise<APIFolderSummary> {\n warnDeprecatedMethod('addApiFolder', 'addApiCollection');\n const aKey = resolveKey(apiKey);\n const fKey = resolveKey(folderKey);\n const body: Record<string, any> = { folder: fKey, ...this.buildApiFolderPayload(options) };\n return this.request('POST', `${this.paths.apiFoldersRoot(aKey)}/`, { jsonBody: body });\n }\n\n /** @deprecated Use {@link getApiCollection} instead. */\n async getApiFolder(apiKey: APIRef, folderKey: FolderRef): Promise<APIFolderSummary> {\n warnDeprecatedMethod('getApiFolder', 'getApiCollection');\n const aKey = resolveKey(apiKey);\n const fKey = resolveKey(folderKey);\n return this.request('GET', `${this.paths.apiFoldersRoot(aKey)}/${fKey}/`);\n }\n\n /** @deprecated Use {@link updateApiCollection} instead. */\n async updateApiFolder(\n apiKey: APIRef,\n folderKey: FolderRef,\n options?: ApiFolderOptions,\n ): Promise<APIFolderSummary> {\n warnDeprecatedMethod('updateApiFolder', 'updateApiCollection');\n const aKey = resolveKey(apiKey);\n const fKey = resolveKey(folderKey);\n const body = this.buildApiFolderPayload(options);\n return this.request('PUT', `${this.paths.apiFoldersRoot(aKey)}/${fKey}/`, {\n jsonBody: body,\n });\n }\n\n /** @deprecated Use {@link removeApiCollection} instead. */\n async removeApiFolder(apiKey: APIRef, folderKey: FolderRef): Promise<void> {\n warnDeprecatedMethod('removeApiFolder', 'removeApiCollection');\n const aKey = resolveKey(apiKey);\n const fKey = resolveKey(folderKey);\n await this.request('DELETE', `${this.paths.apiFoldersRoot(aKey)}/${fKey}/`, {\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Management role operations\n // ------------------------------------------------------------------ //\n\n async listManagementRoles(params?: Record<string, any>): Promise<ManagementRoleList> {\n return this.request('GET', `${this.paths.managementRolesRoot()}/`, { params });\n }\n\n async createManagementRole(payload: Record<string, any>): Promise<ManagementRoleSummary> {\n return this.request('POST', `${this.paths.managementRolesRoot()}/`, {\n jsonBody: payload,\n });\n }\n\n async getManagementRole(roleKey: ManagementRoleRef): Promise<ManagementRoleSummary> {\n const key = resolveKey(roleKey);\n return this.request('GET', `${this.paths.managementRoleRoot(key)}/`);\n }\n\n async updateManagementRole(\n roleKey: ManagementRoleRef,\n payload: Record<string, any>,\n ): Promise<ManagementRoleSummary> {\n const key = resolveKey(roleKey);\n return this.request('PUT', `${this.paths.managementRoleRoot(key)}/`, {\n jsonBody: payload,\n });\n }\n\n async deleteManagementRole(roleKey: ManagementRoleRef): Promise<void> {\n const key = resolveKey(roleKey);\n await this.request('DELETE', `${this.paths.managementRoleRoot(key)}/`, {\n parseJson: false,\n });\n }\n\n // Management role permissions\n\n async listManagementRolePermissions(roleKey: ManagementRoleRef): Promise<RolePermission[]> {\n const key = resolveKey(roleKey);\n const payload = (await this.request('GET', `${this.paths.rolePermissionsRoot(key)}/`)) ?? [];\n return Array.isArray(payload) ? payload : [payload];\n }\n\n async upsertManagementRolePermission(\n roleKey: ManagementRoleRef,\n payload: Record<string, any>,\n ): Promise<RolePermission> {\n const key = resolveKey(roleKey);\n return this.request('POST', `${this.paths.rolePermissionsRoot(key)}/`, {\n jsonBody: payload,\n });\n }\n\n async deleteManagementRolePermission(\n roleKey: ManagementRoleRef,\n contentType: string,\n ): Promise<void> {\n const key = resolveKey(roleKey);\n await this.request('DELETE', `${this.paths.rolePermissionsRoot(key)}/`, {\n params: { content_type: contentType },\n parseJson: false,\n });\n }\n\n async replaceManagementRolePermissions(\n roleKey: ManagementRoleRef,\n permissions: Array<Record<string, any>>,\n ): Promise<RolePermission[]> {\n const key = resolveKey(roleKey);\n const payload = await this.request('POST', `${this.paths.rolePermissionsBatch(key)}/`, {\n jsonBody: permissions,\n });\n return Array.isArray(payload) ? payload : [];\n }\n\n // Management permission objects\n\n async listManagementPermissionObjects(\n roleKey: ManagementRoleRef,\n contentType: string,\n ): Promise<RolePermissionObject[]> {\n const key = resolveKey(roleKey);\n const payload = await this.request('GET', `${this.paths.rolePermissionObjectsRoot(key)}/`, {\n params: { content_type: contentType },\n });\n return this.normalizePermissionObjectListPayload(payload);\n }\n\n async addManagementPermissionObject(\n roleKey: ManagementRoleRef,\n payload: Record<string, any>,\n ): Promise<RolePermissionObject> {\n const key = resolveKey(roleKey);\n const data = await this.request('POST', `${this.paths.rolePermissionObjectsRoot(key)}/`, {\n jsonBody: payload,\n });\n return this.normalizePermissionObjectPayload(data, payload);\n }\n\n async deleteManagementPermissionObject(\n roleKey: ManagementRoleRef,\n payload: Record<string, any>,\n ): Promise<void> {\n const key = resolveKey(roleKey);\n await this.request('DELETE', `${this.paths.rolePermissionObjectsRoot(key)}/`, {\n jsonBody: payload,\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Flux role operations\n // ------------------------------------------------------------------ //\n\n async listFluxRoles(params?: Record<string, any>): Promise<FluxRoleList> {\n return this.request('GET', `${this.paths.fluxRolesRoot()}/`, { params });\n }\n\n async createFluxRole(payload: Record<string, any>): Promise<FluxRoleSummary> {\n return this.request('POST', `${this.paths.fluxRolesRoot()}/`, { jsonBody: payload });\n }\n\n async getFluxRole(roleKey: FluxRoleRef): Promise<FluxRoleSummary> {\n const key = resolveKey(roleKey);\n return this.request('GET', `${this.paths.fluxRoleRoot(key)}/`);\n }\n\n async updateFluxRole(\n roleKey: FluxRoleRef,\n payload: Record<string, any>,\n ): Promise<FluxRoleSummary> {\n const key = resolveKey(roleKey);\n return this.request('PUT', `${this.paths.fluxRoleRoot(key)}/`, { jsonBody: payload });\n }\n\n async deleteFluxRole(roleKey: FluxRoleRef): Promise<void> {\n const key = resolveKey(roleKey);\n await this.request('DELETE', `${this.paths.fluxRoleRoot(key)}/`, { parseJson: false });\n }\n\n // Flux role permissions\n\n async listFluxRolePermissions(roleKey: FluxRoleRef): Promise<RolePermission[]> {\n const key = resolveKey(roleKey);\n const payload =\n (await this.request('GET', `${this.paths.fluxRolePermissionsRoot(key)}/`)) ?? [];\n return Array.isArray(payload) ? payload : [payload];\n }\n\n async upsertFluxRolePermission(\n roleKey: FluxRoleRef,\n payload: Record<string, any>,\n ): Promise<RolePermission> {\n const key = resolveKey(roleKey);\n return this.request('POST', `${this.paths.fluxRolePermissionsRoot(key)}/`, {\n jsonBody: payload,\n });\n }\n\n async deleteFluxRolePermission(roleKey: FluxRoleRef, contentType: string): Promise<void> {\n const key = resolveKey(roleKey);\n await this.request('DELETE', `${this.paths.fluxRolePermissionsRoot(key)}/`, {\n params: { content_type: contentType },\n parseJson: false,\n });\n }\n\n async replaceFluxRolePermissions(\n roleKey: FluxRoleRef,\n permissions: Array<Record<string, any>>,\n ): Promise<RolePermission[]> {\n const key = resolveKey(roleKey);\n const payload = await this.request('POST', `${this.paths.fluxRolePermissionsBatch(key)}/`, {\n jsonBody: permissions,\n });\n return Array.isArray(payload) ? payload : [];\n }\n\n // Flux permission objects\n\n async listFluxPermissionObjects(\n roleKey: FluxRoleRef,\n contentType: string,\n ): Promise<RolePermissionObject[]> {\n const key = resolveKey(roleKey);\n const payload = await this.request('GET', `${this.paths.fluxRolePermissionObjectsRoot(key)}/`, {\n params: { content_type: contentType },\n });\n return this.normalizePermissionObjectListPayload(payload);\n }\n\n async addFluxPermissionObject(\n roleKey: FluxRoleRef,\n payload: Record<string, any>,\n ): Promise<RolePermissionObject> {\n const key = resolveKey(roleKey);\n const data = await this.request('POST', `${this.paths.fluxRolePermissionObjectsRoot(key)}/`, {\n jsonBody: payload,\n });\n return this.normalizePermissionObjectPayload(data, payload);\n }\n\n async deleteFluxPermissionObject(\n roleKey: FluxRoleRef,\n payload: Record<string, any>,\n ): Promise<void> {\n const key = resolveKey(roleKey);\n await this.request('DELETE', `${this.paths.fluxRolePermissionObjectsRoot(key)}/`, {\n jsonBody: payload,\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Collection operations (canonical)\n // ------------------------------------------------------------------ //\n\n async listCollections(params?: Record<string, any>): Promise<CollectionList> {\n return this.request('GET', `${this.paths.collectionsTreeRoot()}/`, { params });\n }\n\n async getCollection(collectionKey: CollectionRef): Promise<CollectionSummary> {\n const key = resolveKey(collectionKey);\n return this.request('GET', `${this.paths.collectionsTreeItem()}/`, {\n params: { key },\n });\n }\n\n async getCollectionByPath(path: string): Promise<CollectionSummary> {\n return this.request('GET', `${this.paths.collectionsTreeItem()}/`, {\n params: { path },\n });\n }\n\n async listCollectionTree(options?: { key?: string; mode?: string }): Promise<CollectionList> {\n const params: Record<string, any> = {};\n if (options?.key) params.key = options.key;\n if (options?.mode) params.mode = options.mode;\n return this.request('GET', `${this.paths.collectionsTreeRoot()}/`, { params });\n }\n\n async createCollection(payload: Record<string, any>): Promise<CollectionSummary> {\n return this.request('POST', `${this.paths.collectionsTreeRoot()}/`, {\n jsonBody: payload,\n });\n }\n\n async updateCollection(\n collectionKey: CollectionRef,\n payload: Record<string, any>,\n ): Promise<CollectionSummary> {\n const key = resolveKey(collectionKey);\n return this.request('PUT', `${this.paths.collectionsTreeItem()}/`, {\n params: { key },\n jsonBody: payload,\n });\n }\n\n /**\n * Write the given fields of a collection and leave the rest alone.\n *\n * `updateCollection` replaces the whole record; this does not. An omitted\n * `parent` keeps the collection where it is, and `{ parent: null }` moves it\n * to the root. The response is the whole collection as stored.\n */\n async patchCollection(\n collectionKey: CollectionRef,\n payload: Record<string, any>,\n ): Promise<CollectionSummary> {\n const key = resolveKey(collectionKey);\n return this.request('PATCH', `${this.paths.collectionsTreeItem()}/`, {\n params: { key },\n jsonBody: payload,\n });\n }\n\n async deleteCollection(collectionKey: CollectionRef): Promise<void> {\n const key = resolveKey(collectionKey);\n await this.request('DELETE', `${this.paths.collectionsTreeItem()}/`, {\n params: { key },\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Collection schema version operations (canonical)\n // ------------------------------------------------------------------ //\n\n async listCollectionVersions(\n collectionKey: CollectionRef,\n params?: Record<string, any>,\n ): Promise<SchemaVersionList> {\n const key = resolveKey(collectionKey);\n return this.request('GET', `${this.paths.collectionVersionsBase(key)}/`, {\n params,\n });\n }\n\n async createCollectionVersion(\n collectionKey: CollectionRef,\n payload: Record<string, any>,\n options?: { copyFrom?: SchemaVersionRef },\n ): Promise<SchemaVersionSummary> {\n const key = resolveKey(collectionKey);\n const params: Record<string, any> = {};\n if (options?.copyFrom) {\n params.copy_from = resolveKey(options.copyFrom);\n }\n return this.request('POST', `${this.paths.collectionVersionsBase(key)}/`, {\n jsonBody: payload,\n params: Object.keys(params).length > 0 ? params : undefined,\n });\n }\n\n async getCollectionVersion(\n collectionKey: CollectionRef,\n versionKey: SchemaVersionRef,\n options?: { includeSchema?: boolean },\n ): Promise<SchemaVersionSummary> {\n const cKey = resolveKey(collectionKey);\n const vKey = resolveKey(versionKey);\n const params: Record<string, any> = {};\n if (options?.includeSchema !== undefined) {\n params.include_schema = options.includeSchema;\n }\n return this.request('GET', `${this.paths.collectionVersionsBase(cKey)}/${vKey}/`, {\n params: Object.keys(params).length > 0 ? params : undefined,\n });\n }\n\n async updateCollectionVersion(\n collectionKey: CollectionRef,\n versionKey: SchemaVersionRef,\n payload: Record<string, any>,\n ): Promise<SchemaVersionSummary> {\n const cKey = resolveKey(collectionKey);\n const vKey = resolveKey(versionKey);\n return this.request('PUT', `${this.paths.collectionVersionsBase(cKey)}/${vKey}/`, {\n jsonBody: payload,\n });\n }\n\n async deleteCollectionVersion(\n collectionKey: CollectionRef,\n versionKey: SchemaVersionRef,\n ): Promise<void> {\n const cKey = resolveKey(collectionKey);\n const vKey = resolveKey(versionKey);\n await this.request('DELETE', `${this.paths.collectionVersionsBase(cKey)}/${vKey}/`, {\n parseJson: false,\n });\n }\n\n async publishCollectionVersion(\n collectionKey: CollectionRef,\n versionKey: SchemaVersionRef,\n ): Promise<SchemaVersionSummary> {\n const cKey = resolveKey(collectionKey);\n const vKey = resolveKey(versionKey);\n return this.request('POST', `${this.paths.collectionVersionsBase(cKey)}/${vKey}/publish/`);\n }\n\n /**\n * Advance pinned nested fields on a Collection to a target Component version.\n *\n * Creates a new published Collection schema version with the affected\n * `meta.component_version` pins advanced. Fields with `auto_update=true`\n * and fields already at the requested target version are reported in\n * `skipped` rather than advanced.\n *\n * @param collectionKey The Collection to sync.\n * @param options.fieldPaths Optional list of nested field paths to advance.\n * When omitted, every pinned (`auto_update=false`) nested field on the\n * Collection's current version is considered.\n * @param options.toVersions Optional per-path override mapping field path\n * to target Component Version UID. Paths not in this mapping advance to\n * the referenced Component's `current_version`. When both `fieldPaths`\n * and `toVersions` are supplied, every key in `toVersions` must also\n * appear in `fieldPaths`.\n *\n * @returns Summary of synced and skipped paths, plus the new\n * `schema_version` UID (`null` if no paths were advanced).\n *\n * @throws `Error` locally (before any HTTP request) when both `fieldPaths`\n * and `toVersions` are supplied AND `toVersions` contains a key that is\n * not in `fieldPaths` (mirrors the server-side validator so the misuse\n * surfaces at the call-site).\n * @throws `FoxnoseApiError` on:\n * - 409 `component_sync_conflict` — target version would break existing resources\n * - 422 `too_many_versions` — Collection schema quota exhausted\n * - 422 `validation_error` — request body invalid\n * - 404 — Collection or specified target version missing\n *\n * @example\n * ```ts\n * // Advance every pinned nested field to its Component's current version.\n * await client.syncCollectionComponent('articles');\n *\n * // Advance a specific path to a chosen Component version.\n * await client.syncCollectionComponent('articles', {\n * fieldPaths: ['seo'],\n * toVersions: { seo: 'ver-def67890' },\n * });\n * ```\n */\n async syncCollectionComponent(\n collectionKey: CollectionRef,\n options: {\n fieldPaths?: string[];\n toVersions?: Record<string, string>;\n } = {},\n ): Promise<SyncComponentResponse> {\n const cKey = resolveKey(collectionKey);\n // Client-side invariant (mirrors the server validator): every key in\n // toVersions must also appear in fieldPaths when both are supplied.\n // Catch the misuse locally instead of round-tripping a 422.\n if (options.fieldPaths !== undefined && options.toVersions !== undefined) {\n const fieldPathSet = new Set(options.fieldPaths);\n const extras = Object.keys(options.toVersions)\n .filter((k) => !fieldPathSet.has(k))\n .sort();\n if (extras.length > 0) {\n throw new Error(\n `toVersions includes paths not present in fieldPaths: [${extras.join(', ')}]`,\n );\n }\n }\n const body: Record<string, unknown> = {};\n if (options.fieldPaths !== undefined) {\n body.field_paths = options.fieldPaths;\n }\n if (options.toVersions !== undefined) {\n body.to_versions = options.toVersions;\n }\n return this.request('POST', `${this.paths.collectionSyncComponent(cKey)}/`, { jsonBody: body });\n }\n\n // ------------------------------------------------------------------ //\n // Collection schema field operations (canonical)\n // ------------------------------------------------------------------ //\n\n async listCollectionFields(\n collectionKey: CollectionRef,\n versionKey: SchemaVersionRef,\n params?: Record<string, any>,\n ): Promise<FieldList> {\n const cKey = resolveKey(collectionKey);\n const vKey = resolveKey(versionKey);\n return this.request('GET', `${this.paths.collectionSchemaTree(cKey, vKey)}/`, { params });\n }\n\n async createCollectionField(\n collectionKey: CollectionRef,\n versionKey: SchemaVersionRef,\n payload: Record<string, any>,\n ): Promise<FieldSummary> {\n const cKey = resolveKey(collectionKey);\n const vKey = resolveKey(versionKey);\n return this.request('POST', `${this.paths.collectionSchemaTree(cKey, vKey)}/`, {\n jsonBody: payload,\n });\n }\n\n async getCollectionField(\n collectionKey: CollectionRef,\n versionKey: SchemaVersionRef,\n fieldPath: string,\n ): Promise<FieldSummary> {\n const cKey = resolveKey(collectionKey);\n const vKey = resolveKey(versionKey);\n return this.request('GET', `${this.paths.collectionSchemaTree(cKey, vKey)}/field/`, {\n params: { path: fieldPath },\n });\n }\n\n async updateCollectionField(\n collectionKey: CollectionRef,\n versionKey: SchemaVersionRef,\n fieldPath: string,\n payload: Record<string, any>,\n ): Promise<FieldSummary> {\n const cKey = resolveKey(collectionKey);\n const vKey = resolveKey(versionKey);\n return this.request('PUT', `${this.paths.collectionSchemaTree(cKey, vKey)}/field/`, {\n params: { path: fieldPath },\n jsonBody: payload,\n });\n }\n\n async deleteCollectionField(\n collectionKey: CollectionRef,\n versionKey: SchemaVersionRef,\n fieldPath: string,\n ): Promise<void> {\n const cKey = resolveKey(collectionKey);\n const vKey = resolveKey(versionKey);\n await this.request('DELETE', `${this.paths.collectionSchemaTree(cKey, vKey)}/field/`, {\n params: { path: fieldPath },\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Folder operations (deprecated; hit legacy /folders/ URL)\n // ------------------------------------------------------------------ //\n\n /** @deprecated Use {@link listCollections} instead. */\n async listFolders(params?: Record<string, any>): Promise<FolderList> {\n warnDeprecatedMethod('listFolders', 'listCollections');\n return this.request('GET', `${this.paths.foldersTreeRoot()}/`, { params });\n }\n\n /** @deprecated Use {@link getCollection} instead. */\n async getFolder(folderKey: FolderRef): Promise<FolderSummary> {\n warnDeprecatedMethod('getFolder', 'getCollection');\n const key = resolveKey(folderKey);\n return this.request('GET', `${this.paths.foldersTreeItem()}/`, {\n params: { key },\n });\n }\n\n /** @deprecated Use {@link getCollectionByPath} instead. */\n async getFolderByPath(path: string): Promise<FolderSummary> {\n warnDeprecatedMethod('getFolderByPath', 'getCollectionByPath');\n return this.request('GET', `${this.paths.foldersTreeItem()}/`, {\n params: { path },\n });\n }\n\n /** @deprecated Use {@link listCollectionTree} instead. */\n async listFolderTree(options?: { key?: string; mode?: string }): Promise<FolderList> {\n warnDeprecatedMethod('listFolderTree', 'listCollectionTree');\n const params: Record<string, any> = {};\n if (options?.key) params.key = options.key;\n if (options?.mode) params.mode = options.mode;\n return this.request('GET', `${this.paths.foldersTreeRoot()}/`, { params });\n }\n\n /** @deprecated Use {@link createCollection} instead. */\n async createFolder(payload: Record<string, any>): Promise<FolderSummary> {\n warnDeprecatedMethod('createFolder', 'createCollection');\n return this.request('POST', `${this.paths.foldersTreeRoot()}/`, { jsonBody: payload });\n }\n\n /** @deprecated Use {@link updateCollection} instead. */\n async updateFolder(folderKey: FolderRef, payload: Record<string, any>): Promise<FolderSummary> {\n warnDeprecatedMethod('updateFolder', 'updateCollection');\n const key = resolveKey(folderKey);\n return this.request('PUT', `${this.paths.foldersTreeItem()}/`, {\n params: { key },\n jsonBody: payload,\n });\n }\n\n /** @deprecated Use {@link deleteCollection} instead. */\n async deleteFolder(folderKey: FolderRef): Promise<void> {\n warnDeprecatedMethod('deleteFolder', 'deleteCollection');\n const key = resolveKey(folderKey);\n await this.request('DELETE', `${this.paths.foldersTreeItem()}/`, {\n params: { key },\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Folder version operations (deprecated)\n // ------------------------------------------------------------------ //\n\n /** @deprecated Use {@link listCollectionVersions} instead. */\n async listFolderVersions(\n folderKey: FolderRef,\n params?: Record<string, any>,\n ): Promise<SchemaVersionList> {\n warnDeprecatedMethod('listFolderVersions', 'listCollectionVersions');\n const key = resolveKey(folderKey);\n return this.request('GET', `${this.paths.folderVersionsBase(key)}/`, { params });\n }\n\n /** @deprecated Use {@link createCollectionVersion} instead. */\n async createFolderVersion(\n folderKey: FolderRef,\n payload: Record<string, any>,\n options?: { copyFrom?: SchemaVersionRef },\n ): Promise<SchemaVersionSummary> {\n warnDeprecatedMethod('createFolderVersion', 'createCollectionVersion');\n const key = resolveKey(folderKey);\n const params: Record<string, any> = {};\n if (options?.copyFrom) {\n params.copy_from = resolveKey(options.copyFrom);\n }\n return this.request('POST', `${this.paths.folderVersionsBase(key)}/`, {\n jsonBody: payload,\n params: Object.keys(params).length > 0 ? params : undefined,\n });\n }\n\n /** @deprecated Use {@link getCollectionVersion} instead. */\n async getFolderVersion(\n folderKey: FolderRef,\n versionKey: SchemaVersionRef,\n options?: { includeSchema?: boolean },\n ): Promise<SchemaVersionSummary> {\n warnDeprecatedMethod('getFolderVersion', 'getCollectionVersion');\n const fKey = resolveKey(folderKey);\n const vKey = resolveKey(versionKey);\n const params: Record<string, any> = {};\n if (options?.includeSchema !== undefined) {\n params.include_schema = options.includeSchema;\n }\n return this.request('GET', `${this.paths.folderVersionsBase(fKey)}/${vKey}/`, {\n params: Object.keys(params).length > 0 ? params : undefined,\n });\n }\n\n /** @deprecated Use {@link updateCollectionVersion} instead. */\n async updateFolderVersion(\n folderKey: FolderRef,\n versionKey: SchemaVersionRef,\n payload: Record<string, any>,\n ): Promise<SchemaVersionSummary> {\n warnDeprecatedMethod('updateFolderVersion', 'updateCollectionVersion');\n const fKey = resolveKey(folderKey);\n const vKey = resolveKey(versionKey);\n return this.request('PUT', `${this.paths.folderVersionsBase(fKey)}/${vKey}/`, {\n jsonBody: payload,\n });\n }\n\n /** @deprecated Use {@link deleteCollectionVersion} instead. */\n async deleteFolderVersion(folderKey: FolderRef, versionKey: SchemaVersionRef): Promise<void> {\n warnDeprecatedMethod('deleteFolderVersion', 'deleteCollectionVersion');\n const fKey = resolveKey(folderKey);\n const vKey = resolveKey(versionKey);\n await this.request('DELETE', `${this.paths.folderVersionsBase(fKey)}/${vKey}/`, {\n parseJson: false,\n });\n }\n\n /** @deprecated Use {@link publishCollectionVersion} instead. */\n async publishFolderVersion(\n folderKey: FolderRef,\n versionKey: SchemaVersionRef,\n ): Promise<SchemaVersionSummary> {\n warnDeprecatedMethod('publishFolderVersion', 'publishCollectionVersion');\n const fKey = resolveKey(folderKey);\n const vKey = resolveKey(versionKey);\n return this.request('POST', `${this.paths.folderVersionsBase(fKey)}/${vKey}/publish/`);\n }\n\n // ------------------------------------------------------------------ //\n // Folder field operations (deprecated)\n // ------------------------------------------------------------------ //\n\n /** @deprecated Use {@link listCollectionFields} instead. */\n async listFolderFields(\n folderKey: FolderRef,\n versionKey: SchemaVersionRef,\n params?: Record<string, any>,\n ): Promise<FieldList> {\n warnDeprecatedMethod('listFolderFields', 'listCollectionFields');\n const fKey = resolveKey(folderKey);\n const vKey = resolveKey(versionKey);\n return this.request('GET', `${this.paths.folderSchemaTree(fKey, vKey)}/`, { params });\n }\n\n /** @deprecated Use {@link createCollectionField} instead. */\n async createFolderField(\n folderKey: FolderRef,\n versionKey: SchemaVersionRef,\n payload: Record<string, any>,\n ): Promise<FieldSummary> {\n warnDeprecatedMethod('createFolderField', 'createCollectionField');\n const fKey = resolveKey(folderKey);\n const vKey = resolveKey(versionKey);\n return this.request('POST', `${this.paths.folderSchemaTree(fKey, vKey)}/`, {\n jsonBody: payload,\n });\n }\n\n /** @deprecated Use {@link getCollectionField} instead. */\n async getFolderField(\n folderKey: FolderRef,\n versionKey: SchemaVersionRef,\n fieldPath: string,\n ): Promise<FieldSummary> {\n warnDeprecatedMethod('getFolderField', 'getCollectionField');\n const fKey = resolveKey(folderKey);\n const vKey = resolveKey(versionKey);\n return this.request('GET', `${this.paths.folderSchemaTree(fKey, vKey)}/field/`, {\n params: { path: fieldPath },\n });\n }\n\n /** @deprecated Use {@link updateCollectionField} instead. */\n async updateFolderField(\n folderKey: FolderRef,\n versionKey: SchemaVersionRef,\n fieldPath: string,\n payload: Record<string, any>,\n ): Promise<FieldSummary> {\n warnDeprecatedMethod('updateFolderField', 'updateCollectionField');\n const fKey = resolveKey(folderKey);\n const vKey = resolveKey(versionKey);\n return this.request('PUT', `${this.paths.folderSchemaTree(fKey, vKey)}/field/`, {\n params: { path: fieldPath },\n jsonBody: payload,\n });\n }\n\n /** @deprecated Use {@link deleteCollectionField} instead. */\n async deleteFolderField(\n folderKey: FolderRef,\n versionKey: SchemaVersionRef,\n fieldPath: string,\n ): Promise<void> {\n warnDeprecatedMethod('deleteFolderField', 'deleteCollectionField');\n const fKey = resolveKey(folderKey);\n const vKey = resolveKey(versionKey);\n await this.request('DELETE', `${this.paths.folderSchemaTree(fKey, vKey)}/field/`, {\n params: { path: fieldPath },\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Component operations\n // ------------------------------------------------------------------ //\n\n async listComponents(params?: Record<string, any>): Promise<ComponentList> {\n return this.request('GET', `${this.paths.componentsRoot()}/`, { params });\n }\n\n async getComponent(componentKey: ComponentRef): Promise<ComponentSummary> {\n const key = resolveKey(componentKey);\n return this.request('GET', `${this.paths.componentRoot(key)}/`);\n }\n\n async createComponent(payload: Record<string, any>): Promise<ComponentSummary> {\n return this.request('POST', `${this.paths.componentsRoot()}/`, { jsonBody: payload });\n }\n\n async updateComponent(\n componentKey: ComponentRef,\n payload: Record<string, any>,\n ): Promise<ComponentSummary> {\n const key = resolveKey(componentKey);\n return this.request('PUT', `${this.paths.componentRoot(key)}/`, { jsonBody: payload });\n }\n\n /**\n * Write the given fields of a component and leave the rest alone. The response\n * is the whole component as stored.\n */\n async patchComponent(\n componentKey: ComponentRef,\n payload: Record<string, any>,\n ): Promise<ComponentSummary> {\n const key = resolveKey(componentKey);\n return this.request('PATCH', `${this.paths.componentRoot(key)}/`, { jsonBody: payload });\n }\n\n async deleteComponent(componentKey: ComponentRef): Promise<void> {\n const key = resolveKey(componentKey);\n await this.request('DELETE', `${this.paths.componentRoot(key)}/`, { parseJson: false });\n }\n\n // ------------------------------------------------------------------ //\n // Component version operations\n // ------------------------------------------------------------------ //\n\n async listComponentVersions(\n componentKey: ComponentRef,\n params?: Record<string, any>,\n ): Promise<SchemaVersionList> {\n const key = resolveKey(componentKey);\n return this.request('GET', `${this.paths.componentVersionsBase(key)}/`, { params });\n }\n\n async createComponentVersion(\n componentKey: ComponentRef,\n payload: Record<string, any>,\n options?: { copyFrom?: SchemaVersionRef },\n ): Promise<SchemaVersionSummary> {\n const key = resolveKey(componentKey);\n const params: Record<string, any> = {};\n if (options?.copyFrom) {\n params.copy_from = resolveKey(options.copyFrom);\n }\n return this.request('POST', `${this.paths.componentVersionsBase(key)}/`, {\n jsonBody: payload,\n params: Object.keys(params).length > 0 ? params : undefined,\n });\n }\n\n async getComponentVersion(\n componentKey: ComponentRef,\n versionKey: SchemaVersionRef,\n options?: { includeSchema?: boolean },\n ): Promise<SchemaVersionSummary> {\n const cKey = resolveKey(componentKey);\n const vKey = resolveKey(versionKey);\n const params: Record<string, any> = {};\n if (options?.includeSchema !== undefined) {\n params.include_schema = options.includeSchema;\n }\n return this.request('GET', `${this.paths.componentVersionsBase(cKey)}/${vKey}/`, {\n params: Object.keys(params).length > 0 ? params : undefined,\n });\n }\n\n async publishComponentVersion(\n componentKey: ComponentRef,\n versionKey: SchemaVersionRef,\n ): Promise<SchemaVersionSummary> {\n const cKey = resolveKey(componentKey);\n const vKey = resolveKey(versionKey);\n return this.request('POST', `${this.paths.componentVersionsBase(cKey)}/${vKey}/publish/`);\n }\n\n async updateComponentVersion(\n componentKey: ComponentRef,\n versionKey: SchemaVersionRef,\n payload: Record<string, any>,\n ): Promise<SchemaVersionSummary> {\n const cKey = resolveKey(componentKey);\n const vKey = resolveKey(versionKey);\n return this.request('PUT', `${this.paths.componentVersionsBase(cKey)}/${vKey}/`, {\n jsonBody: payload,\n });\n }\n\n async deleteComponentVersion(\n componentKey: ComponentRef,\n versionKey: SchemaVersionRef,\n ): Promise<void> {\n const cKey = resolveKey(componentKey);\n const vKey = resolveKey(versionKey);\n await this.request('DELETE', `${this.paths.componentVersionsBase(cKey)}/${vKey}/`, {\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Component field operations\n // ------------------------------------------------------------------ //\n\n async listComponentFields(\n componentKey: ComponentRef,\n versionKey: SchemaVersionRef,\n params?: Record<string, any>,\n ): Promise<FieldList> {\n const cKey = resolveKey(componentKey);\n const vKey = resolveKey(versionKey);\n return this.request('GET', `${this.paths.componentSchemaTree(cKey, vKey)}/`, { params });\n }\n\n async createComponentField(\n componentKey: ComponentRef,\n versionKey: SchemaVersionRef,\n payload: Record<string, any>,\n ): Promise<FieldSummary> {\n const cKey = resolveKey(componentKey);\n const vKey = resolveKey(versionKey);\n return this.request('POST', `${this.paths.componentSchemaTree(cKey, vKey)}/`, {\n jsonBody: payload,\n });\n }\n\n async getComponentField(\n componentKey: ComponentRef,\n versionKey: SchemaVersionRef,\n fieldPath: string,\n ): Promise<FieldSummary> {\n const cKey = resolveKey(componentKey);\n const vKey = resolveKey(versionKey);\n return this.request('GET', `${this.paths.componentSchemaTree(cKey, vKey)}/field/`, {\n params: { path: fieldPath },\n });\n }\n\n async updateComponentField(\n componentKey: ComponentRef,\n versionKey: SchemaVersionRef,\n fieldPath: string,\n payload: Record<string, any>,\n ): Promise<FieldSummary> {\n const cKey = resolveKey(componentKey);\n const vKey = resolveKey(versionKey);\n return this.request('PUT', `${this.paths.componentSchemaTree(cKey, vKey)}/field/`, {\n params: { path: fieldPath },\n jsonBody: payload,\n });\n }\n\n async deleteComponentField(\n componentKey: ComponentRef,\n versionKey: SchemaVersionRef,\n fieldPath: string,\n ): Promise<void> {\n const cKey = resolveKey(componentKey);\n const vKey = resolveKey(versionKey);\n await this.request('DELETE', `${this.paths.componentSchemaTree(cKey, vKey)}/field/`, {\n params: { path: fieldPath },\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Resource operations\n // ------------------------------------------------------------------ //\n\n async listResources(folderKey: FolderRef, params?: Record<string, any>): Promise<ResourceList> {\n const key = resolveKey(folderKey);\n return this.request('GET', `${this.paths.resourceBase(key)}/`, { params });\n }\n\n async getResource(folderKey: FolderRef, resourceKey: ResourceRef): Promise<ResourceSummary> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n return this.request('GET', `${this.paths.resourceBase(fKey)}/${rKey}/`);\n }\n\n async createResource(\n folderKey: FolderRef,\n payload: Record<string, any>,\n options?: { externalId?: string },\n ): Promise<ResourceSummary> {\n // Defensive runtime check: TypeScript callers are protected by the interface\n // but JS callers (or TS callers using `as any`) can still pass `component`.\n // Fail loudly so the migration is obvious.\n if (options && typeof options === 'object' && 'component' in options) {\n throw new TypeError(\n 'The `component` option has been removed. Resources now derive their ' +\n \"schema from the folder's model. Remove the `component` field from \" +\n 'your call site.',\n );\n }\n const key = resolveKey(folderKey);\n const body = { ...payload };\n if (options?.externalId) {\n body.external_id = options.externalId;\n }\n return this.request('POST', `${this.paths.resourceBase(key)}/`, {\n jsonBody: body,\n });\n }\n\n async upsertResource(\n folderKey: FolderRef,\n payload: Record<string, any>,\n options: { externalId: string },\n ): Promise<ResourceSummary> {\n // Defensive runtime check: TypeScript callers are protected by the interface\n // but JS callers (or TS callers using `as any`) can still pass `component`.\n // Fail loudly so the migration is obvious.\n if (options && typeof options === 'object' && 'component' in options) {\n throw new TypeError(\n 'The `component` option has been removed. Resources now derive their ' +\n \"schema from the folder's model. Remove the `component` field from \" +\n 'your call site.',\n );\n }\n const key = resolveKey(folderKey);\n const params: Record<string, string> = { external_id: options.externalId };\n return this.request('PUT', `${this.paths.resourceBase(key)}/`, {\n params,\n jsonBody: payload,\n });\n }\n\n async batchUpsertResources(\n folderKey: FolderRef,\n items: BatchUpsertItem[],\n options?: {\n maxConcurrency?: number;\n failFast?: boolean;\n onProgress?: (completed: number, total: number) => void;\n },\n ): Promise<BatchUpsertResult> {\n // Defensive runtime check: TypeScript callers are protected by the interface\n // but JS callers (or TS callers using `as any`) can still pass `component`\n // on individual items. Fail loudly so the migration is obvious.\n for (const item of items) {\n if (item && typeof item === 'object' && 'component' in item) {\n throw new TypeError(\n 'BatchUpsertItem.component has been removed. Resources now derive ' +\n \"their schema from the folder's model. Remove the `component` \" +\n 'field from your batch items.',\n );\n }\n }\n const fKey = resolveKey(folderKey);\n const maxConcurrency = options?.maxConcurrency ?? 5;\n if (maxConcurrency < 1) {\n throw new Error('maxConcurrency must be at least 1');\n }\n if (items.length === 0) {\n return { succeeded: [], failed: [] };\n }\n const failFast = options?.failFast ?? false;\n const onProgress = options?.onProgress;\n\n const succeeded: ResourceSummary[] = [];\n const failed: BatchItemError[] = [];\n let completed = 0;\n\n const queue = [...items.entries()];\n\n const processItem = async (index: number, item: BatchUpsertItem): Promise<void> => {\n try {\n const params: Record<string, string> = { external_id: item.external_id };\n const result: ResourceSummary = await this.request(\n 'PUT',\n `${this.paths.resourceBase(fKey)}/`,\n { params, jsonBody: item.payload },\n );\n succeeded.push(result);\n } catch (err) {\n failed.push({\n index,\n external_id: item.external_id,\n error: err instanceof Error ? err : new Error(String(err)),\n });\n if (failFast) {\n throw err;\n }\n } finally {\n completed++;\n onProgress?.(completed, items.length);\n }\n };\n\n // Process in batches of maxConcurrency\n let i = 0;\n while (i < queue.length) {\n const batch = queue.slice(i, i + maxConcurrency);\n try {\n await Promise.all(batch.map(([index, item]) => processItem(index, item)));\n } catch (err) {\n if (failFast) throw err;\n }\n i += maxConcurrency;\n }\n\n return { succeeded, failed };\n }\n\n async updateResource(\n folderKey: FolderRef,\n resourceKey: ResourceRef,\n payload: Record<string, any>,\n ): Promise<ResourceSummary> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n await this.request('PUT', `${this.paths.resourceBase(fKey)}/${rKey}/`, {\n jsonBody: payload,\n parseJson: false,\n });\n return this.getResource(fKey, rKey);\n }\n\n async deleteResource(folderKey: FolderRef, resourceKey: ResourceRef): Promise<void> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n await this.request('DELETE', `${this.paths.resourceBase(fKey)}/${rKey}/`, {\n parseJson: false,\n });\n }\n\n async getResourceData(\n folderKey: FolderRef,\n resourceKey: ResourceRef,\n ): Promise<Record<string, any>> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n return this.request('GET', `${this.paths.resourceBase(fKey)}/${rKey}/data/`);\n }\n\n // ------------------------------------------------------------------ //\n // Revision operations\n // ------------------------------------------------------------------ //\n\n async listRevisions(\n folderKey: FolderRef,\n resourceKey: ResourceRef,\n params?: Record<string, any>,\n ): Promise<RevisionList> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n return this.request('GET', `${this.paths.revisionBase(fKey, rKey)}/`, { params });\n }\n\n async createRevision(\n folderKey: FolderRef,\n resourceKey: ResourceRef,\n payload: Record<string, any>,\n ): Promise<RevisionSummary> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n return this.request('POST', `${this.paths.revisionBase(fKey, rKey)}/`, {\n jsonBody: payload,\n });\n }\n\n async getRevision(\n folderKey: FolderRef,\n resourceKey: ResourceRef,\n revisionKey: RevisionRef,\n ): Promise<RevisionSummary> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n const rvKey = resolveKey(revisionKey);\n return this.request('GET', `${this.paths.revisionBase(fKey, rKey)}/${rvKey}/`);\n }\n\n async updateRevision(\n folderKey: FolderRef,\n resourceKey: ResourceRef,\n revisionKey: RevisionRef,\n payload: Record<string, any>,\n ): Promise<RevisionSummary> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n const rvKey = resolveKey(revisionKey);\n return this.request('PUT', `${this.paths.revisionBase(fKey, rKey)}/${rvKey}/`, {\n jsonBody: payload,\n });\n }\n\n async deleteRevision(\n folderKey: FolderRef,\n resourceKey: ResourceRef,\n revisionKey: RevisionRef,\n ): Promise<void> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n const rvKey = resolveKey(revisionKey);\n await this.request('DELETE', `${this.paths.revisionBase(fKey, rKey)}/${rvKey}/`, {\n parseJson: false,\n });\n }\n\n async publishRevision(\n folderKey: FolderRef,\n resourceKey: ResourceRef,\n revisionKey: RevisionRef,\n payload?: Record<string, any>,\n ): Promise<RevisionSummary> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n const rvKey = resolveKey(revisionKey);\n return this.request(\n 'POST',\n `${this.paths.revisionBase(fKey, rKey)}/${rvKey}/publish/`,\n payload ? { jsonBody: payload } : undefined,\n );\n }\n\n async validateRevision(\n folderKey: FolderRef,\n resourceKey: ResourceRef,\n revisionKey: RevisionRef,\n ): Promise<Record<string, any>> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n const rvKey = resolveKey(revisionKey);\n return this.request('POST', `${this.paths.revisionBase(fKey, rKey)}/${rvKey}/validate/`);\n }\n\n async getRevisionData(\n folderKey: FolderRef,\n resourceKey: ResourceRef,\n revisionKey: RevisionRef,\n ): Promise<Record<string, any>> {\n const fKey = resolveKey(folderKey);\n const rKey = resolveKey(resourceKey);\n const rvKey = resolveKey(revisionKey);\n return this.request('GET', `${this.paths.revisionBase(fKey, rKey)}/${rvKey}/data/`);\n }\n\n // ------------------------------------------------------------------ //\n // Locale operations\n // ------------------------------------------------------------------ //\n\n async listLocales(): Promise<LocaleList> {\n const payload = (await this.request('GET', `${this.paths.localesRoot()}/`)) ?? [];\n return Array.isArray(payload) ? payload : [payload];\n }\n\n async createLocale(payload: Record<string, any>): Promise<LocaleSummary> {\n return this.request('POST', `${this.paths.localesRoot()}/`, { jsonBody: payload });\n }\n\n async getLocale(code: string): Promise<LocaleSummary> {\n return this.request('GET', `${this.paths.localeRoot(code)}/`);\n }\n\n async updateLocale(code: string, payload: Record<string, any>): Promise<LocaleSummary> {\n return this.request('PUT', `${this.paths.localeRoot(code)}/`, { jsonBody: payload });\n }\n\n async deleteLocale(code: string): Promise<void> {\n await this.request('DELETE', `${this.paths.localeRoot(code)}/`, { parseJson: false });\n }\n\n // ------------------------------------------------------------------ //\n // Project operations\n // ------------------------------------------------------------------ //\n\n async listProjects(orgKey: OrgRef, params?: Record<string, any>): Promise<ProjectList> {\n const key = resolveKey(orgKey);\n return this.request('GET', `${this.paths.projectsBase(key)}/`, { params });\n }\n\n async getProject(orgKey: OrgRef, projectKey: ProjectRef): Promise<ProjectSummary> {\n const oKey = resolveKey(orgKey);\n const pKey = resolveKey(projectKey);\n return this.request('GET', `${this.paths.projectRoot(oKey, pKey)}/`);\n }\n\n async createProject(orgKey: OrgRef, payload: Record<string, any>): Promise<ProjectSummary> {\n const key = resolveKey(orgKey);\n return this.request('POST', `${this.paths.projectsBase(key)}/`, { jsonBody: payload });\n }\n\n async updateProject(\n orgKey: OrgRef,\n projectKey: ProjectRef,\n payload: Record<string, any>,\n ): Promise<ProjectSummary> {\n const oKey = resolveKey(orgKey);\n const pKey = resolveKey(projectKey);\n return this.request('PUT', `${this.paths.projectRoot(oKey, pKey)}/`, {\n jsonBody: payload,\n });\n }\n\n async deleteProject(orgKey: OrgRef, projectKey: ProjectRef): Promise<void> {\n const oKey = resolveKey(orgKey);\n const pKey = resolveKey(projectKey);\n await this.request('DELETE', `${this.paths.projectRoot(oKey, pKey)}/`, {\n parseJson: false,\n });\n }\n\n // ------------------------------------------------------------------ //\n // Environment operations\n // ------------------------------------------------------------------ //\n\n async listEnvironments(orgKey: OrgRef, projectKey: ProjectRef): Promise<EnvironmentList> {\n const oKey = resolveKey(orgKey);\n const pKey = resolveKey(projectKey);\n const payload =\n (await this.request('GET', `${this.paths.environmentsBase(oKey, pKey)}/`)) ?? [];\n if (Array.isArray(payload)) {\n return payload;\n }\n if (payload && typeof payload === 'object' && 'results' in payload) {\n return (payload as { results: EnvironmentSummary[] }).results;\n }\n return [payload];\n }\n\n async getEnvironment(\n orgKey: OrgRef,\n projectKey: ProjectRef,\n envKey: EnvironmentRef,\n ): Promise<EnvironmentSummary> {\n const oKey = resolveKey(orgKey);\n const pKey = resolveKey(projectKey);\n const eKey = resolveKey(envKey);\n return this.request('GET', `${this.paths.environmentRoot(oKey, pKey, eKey)}/`);\n }\n\n async createEnvironment(\n orgKey: OrgRef,\n projectKey: ProjectRef,\n payload: Record<string, any>,\n ): Promise<EnvironmentSummary> {\n const oKey = resolveKey(orgKey);\n const pKey = resolveKey(projectKey);\n return this.request('POST', `${this.paths.environmentsBase(oKey, pKey)}/`, {\n jsonBody: payload,\n });\n }\n\n async updateEnvironment(\n orgKey: OrgRef,\n projectKey: ProjectRef,\n envKey: EnvironmentRef,\n payload: Record<string, any>,\n ): Promise<EnvironmentSummary> {\n const oKey = resolveKey(orgKey);\n const pKey = resolveKey(projectKey);\n const eKey = resolveKey(envKey);\n return this.request('PUT', `${this.paths.environmentRoot(oKey, pKey, eKey)}/`, {\n jsonBody: payload,\n });\n }\n\n async deleteEnvironment(\n orgKey: OrgRef,\n projectKey: ProjectRef,\n envKey: EnvironmentRef,\n ): Promise<void> {\n const oKey = resolveKey(orgKey);\n const pKey = resolveKey(projectKey);\n const eKey = resolveKey(envKey);\n await this.request('DELETE', `${this.paths.environmentRoot(oKey, pKey, eKey)}/`, {\n parseJson: false,\n });\n }\n\n async toggleEnvironment(\n orgKey: OrgRef,\n projectKey: ProjectRef,\n envKey: EnvironmentRef,\n isEnabled: boolean,\n ): Promise<void> {\n const oKey = resolveKey(orgKey);\n const pKey = resolveKey(projectKey);\n const eKey = resolveKey(envKey);\n await this.request('POST', `${this.paths.environmentRoot(oKey, pKey, eKey)}/toggle/`, {\n jsonBody: { is_enabled: isEnabled },\n });\n }\n\n async updateEnvironmentProtection(\n orgKey: OrgRef,\n projectKey: ProjectRef,\n envKey: EnvironmentRef,\n options: { protectionLevel: string; protectionReason?: string },\n ): Promise<EnvironmentSummary> {\n const oKey = resolveKey(orgKey);\n const pKey = resolveKey(projectKey);\n const eKey = resolveKey(envKey);\n const body: Record<string, any> = { protection_level: options.protectionLevel };\n if (options.protectionReason) {\n body.protection_reason = options.protectionReason;\n }\n return this.request('PATCH', `${this.paths.environmentRoot(oKey, pKey, eKey)}/protection/`, {\n jsonBody: body,\n });\n }\n\n async clearEnvironmentProtection(\n orgKey: OrgRef,\n projectKey: ProjectRef,\n envKey: EnvironmentRef,\n ): Promise<EnvironmentSummary> {\n return this.updateEnvironmentProtection(orgKey, projectKey, envKey, {\n protectionLevel: 'none',\n });\n }\n\n // ------------------------------------------------------------------ //\n // Files\n // ------------------------------------------------------------------ //\n\n /**\n * List a files collection's upload links, newest first. `params` carries `limit` (at\n * most 100), `offset` and `state`: `active`, `ended` or `all` (the default).\n */\n async listUploadLinks(\n collectionKey: CollectionRef,\n params?: Record<string, any>,\n ): Promise<UploadLinkList> {\n const key = resolveKey(collectionKey);\n return this.request('GET', `${this.paths.uploadLinksRoot(key)}/`, { params });\n }\n\n /**\n * Create an upload link: a hosted page where an end user adds files.\n *\n * The collection must be strict. Works with a user token or a Management API\n * key of this environment. Read the link back with {@link getUploadLink}; the\n * Flux upload status answers only the Flux key that started an upload, never\n * a link made here.\n *\n * `upload_url` carries the link's token and is returned only by this call.\n */\n async createUploadLink(\n collectionKey: CollectionRef,\n request: UploadLinkCreateRequest,\n ): Promise<UploadLinkCreated> {\n const key = resolveKey(collectionKey);\n return this.transport.request('POST', `${this.paths.uploadLinksRoot(key)}/`, {\n jsonBody: { ...request, owner: resolveKey(request.owner) },\n allowRetries: false,\n });\n }\n\n /** Read one upload link with its sessions and the status of each file. */\n async getUploadLink(collectionKey: CollectionRef, uploadId: string): Promise<UploadLink> {\n const key = resolveKey(collectionKey);\n return this.request('GET', `${this.paths.uploadLinkRoot(key, uploadId)}/`);\n }\n\n /**\n * Revoke an upload link. Revoking a revoked link returns the same state. Files\n * already uploaded through the link are not affected.\n */\n async revokeUploadLink(collectionKey: CollectionRef, uploadId: string): Promise<UploadLink> {\n const key = resolveKey(collectionKey);\n return this.request('POST', `${this.paths.uploadLinkRoot(key, uploadId)}/revoke/`);\n }\n\n /** Read a record's file: its verdict, the checks that ran and every finding. */\n async getFileAnalysis(\n collectionKey: CollectionRef,\n resourceKey: ResourceRef,\n ): Promise<FileRecordView> {\n const root = this.fileRoot(collectionKey, resourceKey);\n return this.request('GET', `${root}/analysis/`);\n }\n\n /**\n * Release a file held for a reviewer.\n *\n * The answer's `outcome` says what happened; a publish that goes back through\n * processing completes on its own. A file no reviewer holds is\n * `409 file_not_in_review`, `file_not_ready` or `file_erased`.\n */\n async approveFile(\n collectionKey: CollectionRef,\n resourceKey: ResourceRef,\n ): Promise<FileRecordView> {\n const root = this.fileRoot(collectionKey, resourceKey);\n return this.transport.request('POST', `${root}/approve/`, { allowRetries: false });\n }\n\n /** Reject a file held for a reviewer. Repeating it returns the same state. */\n async rejectFile(\n collectionKey: CollectionRef,\n resourceKey: ResourceRef,\n ): Promise<FileRecordView> {\n const root = this.fileRoot(collectionKey, resourceKey);\n return this.request('POST', `${root}/reject/`);\n }\n\n /**\n * Analyze a file again under the collection's live policy.\n *\n * Accepted work runs in the background; a published generation keeps serving\n * until the new one publishes. A `storage_only` collection answers\n * `409 reanalysis_requires_agent_ready`. This is paid processing: a refusal over\n * the plan throws {@link FilesQuotaExceededError}, a quota that cannot be read\n * throws {@link FilesQuotaUnavailableError}, and over a budget is `429`.\n */\n async reanalyzeFile(\n collectionKey: CollectionRef,\n resourceKey: ResourceRef,\n ): Promise<FileRecordView> {\n const root = this.fileRoot(collectionKey, resourceKey);\n return this.transport.request('POST', `${root}/reanalyze/`, { allowRetries: false });\n }\n\n /**\n * Get a short-lived link to a record's original file.\n *\n * A state that cannot be downloaded now is a `409`: `detail.reason` of the\n * thrown error names it. Check `warnings` before opening the file.\n */\n async getFileOriginal(\n collectionKey: CollectionRef,\n resourceKey: ResourceRef,\n ): Promise<FileDownload> {\n const root = this.fileRoot(collectionKey, resourceKey);\n return this.request('GET', `${root}/file/original/`);\n }\n\n /**\n * Get a short-lived link to a record's safe copy. It is an image-only PDF, or a PNG\n * for an image: read `content_type`.\n */\n async getFileSafeCopy(\n collectionKey: CollectionRef,\n resourceKey: ResourceRef,\n ): Promise<FileDownload> {\n const root = this.fileRoot(collectionKey, resourceKey);\n return this.request('GET', `${root}/file/safe-copy/`);\n }\n\n /** Get a short-lived link to the redacted PNG of one page. */\n async getFilePage(\n collectionKey: CollectionRef,\n resourceKey: ResourceRef,\n page: number,\n ): Promise<FileDownload> {\n const root = this.fileRoot(collectionKey, resourceKey);\n return this.request('GET', `${root}/file/pages/${page}/`);\n }\n\n /**\n * Read one page: its redacted image, what was withheld, its tables and the\n * text an agent receives.\n */\n async getFilePageDetail(\n collectionKey: CollectionRef,\n resourceKey: ResourceRef,\n page: number,\n ): Promise<FilePageDetail> {\n const root = this.fileRoot(collectionKey, resourceKey);\n return this.request('GET', `${root}/file/pages/${page}/detail/`);\n }\n\n /** List a collection's blocked and rejected files, newest first. */\n async listFileTombstones(\n collectionKey: CollectionRef,\n params?: Record<string, any>,\n ): Promise<FileTombstoneList> {\n const key = resolveKey(collectionKey);\n return this.request('GET', `${this.paths.fileTombstonesRoot(key)}/`, { params });\n }\n\n /** Read a collection's live files policy. */\n async getFilesPolicy(collectionKey: CollectionRef): Promise<FilesPolicy> {\n const key = resolveKey(collectionKey);\n return this.request('GET', `${this.paths.filesPolicyRoot(key)}/`);\n }\n\n /**\n * Replace a collection's files policy with a new version.\n *\n * A full replacement: an omitted field takes its default. Sending the live\n * body again creates no version.\n */\n async updateFilesPolicy(\n collectionKey: CollectionRef,\n payload: FilesPolicyBody,\n ): Promise<FilesPolicy> {\n const key = resolveKey(collectionKey);\n return this.request('PUT', `${this.paths.filesPolicyRoot(key)}/`, { jsonBody: payload });\n }\n\n /**\n * List the files held for a reviewer in this environment, newest first.\n *\n * `collection` narrows the queue to one collection; one the caller cannot read,\n * or that does not exist, is an empty page. `params` carries `limit` (at most\n * 100) and `offset`.\n */\n async listFileReviewQueue(options?: {\n collection?: CollectionRef;\n params?: Record<string, any>;\n }): Promise<FileReviewQueue> {\n const params = { ...options?.params };\n if (options?.collection !== undefined) {\n params.collection = resolveKey(options.collection);\n }\n return this.request('GET', `${this.paths.filesReviewRoot()}/`, { params });\n }\n\n /**\n * Read what the authenticated caller may do in this environment.\n *\n * Works for a user token and for a Management API key of this environment. A caller\n * with no grants at all is a `403`; a key of another environment is a\n * `404 environment_not_found`.\n */\n async getMyPermissions(): Promise<MyPermissions> {\n return this.request('GET', `${this.paths.myPermissionsRoot()}/`);\n }\n\n // ------------------------------------------------------------------ //\n // Tenant signing keys and tenant limits\n // ------------------------------------------------------------------ //\n\n /**\n * List the environment's tenant signing keys, revoked ones included, oldest first.\n * Keys the caller cannot read are left out. `params` carries `limit` and `offset`.\n */\n async listTenantSigningKeys(options?: {\n parentKey?: FluxAPIKeyRef;\n params?: Record<string, any>;\n }): Promise<TenantSigningKeyList> {\n const params = { ...options?.params };\n if (options?.parentKey !== undefined) {\n params.parent_key = resolveKey(options.parentKey);\n }\n return this.request('GET', `${this.paths.tenantSigningKeysRoot()}/`, { params });\n }\n\n /**\n * Register a tenant signing key, or have FoxNose generate the key pair.\n *\n * Send exactly one of `public_key` and `generate: true`. With `generate` the answer\n * carries `private_key` once (not enumerable; it is not stored). To keep the private\n * key on your side only, make the pair with {@link generateTenantSigningKey} and send\n * its `publicKey`. Never retried automatically.\n */\n async createTenantSigningKey(\n request: TenantSigningKeyCreateRequest,\n ): Promise<TenantSigningKeyCreated> {\n const created = await this.transport.request('POST', `${this.paths.tenantSigningKeysRoot()}/`, {\n jsonBody: signingKeyBody(request),\n allowRetries: false,\n });\n return hidePrivateKey(created);\n }\n\n /** Read one tenant signing key. */\n async getTenantSigningKey(kid: string): Promise<TenantSigningKey> {\n return this.request('GET', `${this.paths.tenantSigningKeyRoot(kid)}/`);\n }\n\n /**\n * Change a signing key's label, per-key limits or cutoff for older tokens.\n *\n * `not_before: 'now'` means 60 seconds from now; an explicit time must be at least\n * that far ahead. Tokens with `iat` before it are refused. It only moves forward.\n */\n async updateTenantSigningKey(\n kid: string,\n changes: TenantSigningKeyUpdateRequest,\n ): Promise<TenantSigningKey> {\n return this.request('PATCH', `${this.paths.tenantSigningKeyRoot(kid)}/`, {\n jsonBody: signingKeyPatchBody(changes),\n });\n }\n\n /** Revoke a signing key. Repeating the call also succeeds. */\n async deleteTenantSigningKey(kid: string): Promise<void> {\n await this.request('DELETE', `${this.paths.tenantSigningKeyRoot(kid)}/`, {\n parseJson: false,\n });\n }\n\n /**\n * Refuse one token (`jti`) or one end user's tokens (`sub`, those with `iat` at or\n * before `before`, 60 seconds from now by default). Send exactly one of `jti` and\n * `sub`. Neither value is stored, only its hash. Never retried automatically.\n */\n async addTenantTokenRevocation(\n kid: string,\n entry: { jti?: string; sub?: string; before?: Date | string },\n ): Promise<TenantTokenRevocation> {\n return this.transport.request('POST', `${this.paths.tenantSigningKeyRoot(kid)}/revocations/`, {\n jsonBody: revocationBody(entry),\n allowRetries: false,\n });\n }\n\n /** Read the environment's tenant-token rate limits, with defaults and ceilings. */\n async getTenantLimits(): Promise<TenantLimits> {\n return this.request('GET', `${this.paths.tenantLimitsRoot()}/`);\n }\n\n /** Replace the environment's tenant-token rate limits. A field left out returns to its default. */\n async updateTenantLimits(limits: Partial<TenantLimitValues>): Promise<TenantLimits> {\n return this.request('PUT', `${this.paths.tenantLimitsRoot()}/`, {\n jsonBody: limitValues(\n {\n rpm_per_subject: limits.rpm_per_subject ?? null,\n rpm_per_anchor: limits.rpm_per_anchor ?? null,\n uploads_per_subject_per_hour: limits.uploads_per_subject_per_hour ?? null,\n },\n 'limits',\n ),\n });\n }\n\n // ------------------------------------------------------------------ //\n // Guardrails\n // ------------------------------------------------------------------ //\n\n /** Read a collection's guardrails policy. Without one, mode is `off` and `version` is `null`. */\n async getGuardrailsPolicy(collectionKey: CollectionRef): Promise<GuardrailsPolicy> {\n return this.request('GET', `${this.paths.guardrailsPolicyRoot(resolveKey(collectionKey))}/`);\n }\n\n /**\n * Replace a collection's guardrails policy with a new version. Only the fields that\n * are set are sent; a `mode` left out keeps the collection's mode. An unknown field\n * throws before anything is sent.\n */\n async updateGuardrailsPolicy(\n collectionKey: CollectionRef,\n payload: GuardrailsPolicyBody,\n ): Promise<GuardrailsPolicy> {\n return this.request('PUT', `${this.paths.guardrailsPolicyRoot(resolveKey(collectionKey))}/`, {\n jsonBody: guardrailsPolicyBody(payload),\n });\n }\n\n /** List a collection's retained held revisions, newest first. `params` carries `limit` (at most 200) and `offset`. */\n async listHeldRevisions(\n collectionKey: CollectionRef,\n options?: { status?: HeldRevisionStatus; params?: Record<string, any> },\n ): Promise<HeldRevisionList> {\n const params = { ...options?.params };\n if (options?.status !== undefined) {\n params.status = options.status;\n }\n return this.request('GET', `${this.paths.guardrailsHeldRoot(resolveKey(collectionKey))}/`, {\n params,\n });\n }\n\n /** Publish a held revision; it is re-evaluated under the live policy first. Never retried automatically. */\n async releaseHeldRevision(\n collectionKey: CollectionRef,\n resourceKey: ResourceRef,\n revisionKey: RevisionRef,\n ): Promise<HeldRevisionDecision> {\n const root = this.paths.revisionGuardrailsRoot(\n resolveKey(collectionKey),\n resolveKey(resourceKey),\n resolveKey(revisionKey),\n );\n return this.transport.request('POST', `${root}/release/`, { allowRetries: false });\n }\n\n /** Reject a held revision; it is never published. `reason` is at most 500 characters. */\n async rejectHeldRevision(\n collectionKey: CollectionRef,\n resourceKey: ResourceRef,\n revisionKey: RevisionRef,\n options?: { reason?: string },\n ): Promise<HeldRevisionDecision> {\n const root = this.paths.revisionGuardrailsRoot(\n resolveKey(collectionKey),\n resolveKey(resourceKey),\n resolveKey(revisionKey),\n );\n return this.transport.request('POST', `${root}/reject/`, {\n jsonBody: options?.reason === undefined ? undefined : { reason: options.reason },\n allowRetries: false,\n });\n }\n\n /** Reject up to 50 held revisions. Each item succeeds or fails on its own. */\n async rejectHeldRevisions(\n collectionKey: CollectionRef,\n items: readonly HeldRevisionRef[],\n options?: { reason?: string },\n ): Promise<GuardrailsBatchResult> {\n const body: Record<string, unknown> = { items: heldItems(items) };\n if (options?.reason !== undefined) {\n body.reason = options.reason;\n }\n return this.transport.request(\n 'POST',\n `${this.paths.guardrailsHeldRoot(resolveKey(collectionKey))}/reject/`,\n { jsonBody: body, allowRetries: false },\n );\n }\n\n /** Screen up to 50 held revisions again; each is published only if `clean`. */\n async rescreenHeldRevisions(\n collectionKey: CollectionRef,\n items: readonly HeldRevisionRef[],\n ): Promise<GuardrailsBatchResult> {\n return this.transport.request(\n 'POST',\n `${this.paths.guardrailsHeldRoot(resolveKey(collectionKey))}/rescreen/`,\n { jsonBody: { items: heldItems(items) }, allowRetries: false },\n );\n }\n\n /** Read a collection's review backlog and this hour's screening budget. */\n async getGuardrailsUsage(collectionKey: CollectionRef): Promise<GuardrailsUsage> {\n return this.request('GET', `${this.paths.guardrailsUsageRoot(resolveKey(collectionKey))}/`);\n }\n\n /**\n * List what the environment holds for a person to review, newest first. `kind` is\n * `held` (the default) or `needs_review`; `status` applies to `held` only.\n * `params` carries `limit` (at most 100) and `offset`.\n */\n async listGuardrailsReviewQueue(options?: {\n kind?: 'held' | 'needs_review';\n collection?: CollectionRef;\n status?: HeldRevisionStatus;\n params?: Record<string, any>;\n }): Promise<GuardrailsReviewQueue> {\n const params = { ...options?.params };\n if (options?.kind !== undefined) params.kind = options.kind;\n if (options?.collection !== undefined) params.collection = resolveKey(options.collection);\n if (options?.status !== undefined) params.status = options.status;\n return this.request('GET', `${this.paths.guardrailsReviewRoot()}/`, { params });\n }\n\n /** Read the team view of a revision: provenance, findings and review state. */\n async getRevisionGuardrails(\n collectionKey: CollectionRef,\n resourceKey: ResourceRef,\n revisionKey: RevisionRef,\n ): Promise<RevisionGuardrails> {\n const root = this.paths.revisionGuardrailsRoot(\n resolveKey(collectionKey),\n resolveKey(resourceKey),\n resolveKey(revisionKey),\n );\n return this.request('GET', `${root}/`);\n }\n\n /**\n * Vouch for a record's published content: a revision with the same data is created\n * and published, with the caller as its origin. Never retried automatically.\n */\n async markResourceReviewed(\n collectionKey: CollectionRef,\n resourceKey: ResourceRef,\n ): Promise<MarkReviewedResult> {\n const root = this.paths.resourceGuardrailsRoot(\n resolveKey(collectionKey),\n resolveKey(resourceKey),\n );\n return this.transport.request('POST', `${root}/mark-reviewed/`, { allowRetries: false });\n }\n\n /** Read the wording the API uses for findings, states and writers. */\n async getGuardrailsCatalog(): Promise<GuardrailsCatalog> {\n return this.request('GET', `${this.paths.guardrailsCatalogRoot()}/`);\n }\n\n // ------------------------------------------------------------------ //\n // Webhooks\n // ------------------------------------------------------------------ //\n\n /**\n * List the environment's webhook endpoints, newest first. Each item carries\n * `stats_24h`; secrets are never included. `params` carries `status` (`active`,\n * `paused` or `disabled`), `limit` (at most 200) and `offset`.\n */\n async listWebhookEndpoints(params?: Record<string, any>): Promise<WebhookEndpointList> {\n return this.request('GET', `${this.paths.webhooksRoot()}/endpoints/`, { params });\n }\n\n /**\n * Create a webhook endpoint.\n *\n * The answer carries the signing `secret`, which is not enumerable: read it as\n * `created.secret`, and read it again later with {@link getWebhookEndpointSecret}.\n * An environment holds at most 20 endpoints ({@link WebhookEndpointLimitExceededError}).\n * A `content` endpoint also needs read access to the content it will deliver.\n */\n async createWebhookEndpoint(\n request: WebhookEndpointCreateRequest,\n ): Promise<WebhookEndpointCreated> {\n const created = await this.transport.request(\n 'POST',\n `${this.paths.webhooksRoot()}/endpoints/`,\n {\n jsonBody: webhookEndpointBody(request),\n allowRetries: false,\n },\n );\n return hideSecret(created);\n }\n\n /** Read one webhook endpoint. It carries neither the secret nor `stats_24h`. */\n async getWebhookEndpoint(endpointId: string): Promise<WebhookEndpoint> {\n return this.request('GET', `${this.paths.webhookEndpointRoot(endpointId)}/`);\n }\n\n /**\n * Change the given fields of an endpoint and leave the rest alone.\n *\n * `status: 'active'` resumes a paused or disabled endpoint and clears its failure\n * streak; events that happened meanwhile are not sent, but failed deliveries can be\n * sent again with {@link recoverWebhookDeliveries}.\n */\n async updateWebhookEndpoint(\n endpointId: string,\n changes: WebhookEndpointUpdateRequest,\n ): Promise<WebhookEndpoint> {\n return this.request('PATCH', `${this.paths.webhookEndpointRoot(endpointId)}/`, {\n jsonBody: webhookEndpointBody(changes),\n });\n }\n\n /**\n * Delete an endpoint and its pending deliveries. Its finished deliveries and\n * attempts stay in the event log for 30 days, with `endpoint.deleted` true.\n */\n async deleteWebhookEndpoint(endpointId: string): Promise<void> {\n await this.request('DELETE', `${this.paths.webhookEndpointRoot(endpointId)}/`, {\n parseJson: false,\n });\n }\n\n /**\n * List an endpoint's deliveries, newest first, each with the event it carries.\n * `params` carries `limit` (at most 200) and `offset`.\n */\n async listWebhookEndpointDeliveries(\n endpointId: string,\n params?: Record<string, any>,\n ): Promise<WebhookEndpointDeliveryList> {\n return this.request('GET', `${this.paths.webhookEndpointRoot(endpointId)}/deliveries/`, {\n params,\n });\n }\n\n /**\n * Read the endpoint's current signing secret: the newest, during a rotation. Needs\n * `webhooks:update`. `secret` is not enumerable: read it as `response.secret`.\n */\n async getWebhookEndpointSecret(endpointId: string): Promise<WebhookSecret> {\n const response = await this.request(\n 'GET',\n `${this.paths.webhookEndpointRoot(endpointId)}/secret/`,\n );\n return hideSecret(response);\n }\n\n /**\n * Create a new signing secret and return it.\n *\n * The previous secret stays valid for 24 hours, and deliveries carry a signature for\n * each valid secret; with `expire_previous_now` it stops at once. Needs\n * `webhooks:update`. `secret` is not enumerable: read it as `rotation.secret`.\n */\n async rotateWebhookEndpointSecret(\n endpointId: string,\n options?: { expire_previous_now?: boolean },\n ): Promise<WebhookSecretRotation> {\n const response = await this.transport.request(\n 'POST',\n `${this.paths.webhookEndpointRoot(endpointId)}/secret/rotate/`,\n {\n jsonBody: { expire_previous_now: options?.expire_previous_now ?? false },\n allowRetries: false,\n },\n );\n return hideSecret(response);\n }\n\n /**\n * Send a sample event of `eventType` to this endpoint only, with `test` true in the\n * envelope. It is sent whatever the endpoint's event types and collection filter,\n * but the endpoint must be active ({@link WebhookEndpointNotActiveError}).\n */\n async sendWebhookTestEvent(endpointId: string, eventType: string): Promise<WebhookTestEvent> {\n return this.transport.request('POST', `${this.paths.webhookEndpointRoot(endpointId)}/test/`, {\n jsonBody: { event_type: eventType },\n allowRetries: false,\n });\n }\n\n /**\n * Send again the endpoint's failed deliveries created at or after `since`.\n *\n * Each becomes a new pending delivery of the same event. One call queues at most\n * 10,000 deliveries; when `more` is true, call again with the same `since`. `since`\n * is an ISO 8601 time within the last 30 days; a time without a zone is read as UTC.\n */\n async recoverWebhookDeliveries(\n endpointId: string,\n since: string | Date,\n ): Promise<WebhookRecovery> {\n return this.transport.request(\n 'POST',\n `${this.paths.webhookEndpointRoot(endpointId)}/recover/`,\n {\n jsonBody: { since: since instanceof Date ? since.toISOString() : since },\n allowRetries: false,\n },\n );\n }\n\n /**\n * List the events of the last 30 days, newest first, with `delivery_counts`.\n * `params` carries `type`, `endpoint` (an endpoint `id`), `status` (`pending`,\n * `succeeded` or `dead`), `test`, `after`, `before` (ISO 8601), `limit` (at most 200)\n * and `offset`.\n */\n async listWebhookEvents(params?: WebhookEventListParams): Promise<WebhookEventList> {\n return this.request('GET', `${this.paths.webhooksRoot()}/events/`, { params });\n }\n\n /** Read one event with its envelope and all its deliveries, oldest first. */\n async getWebhookEvent(eventId: string): Promise<WebhookEventDetail> {\n return this.request('GET', `${this.paths.webhookEventRoot(eventId)}/`);\n }\n\n /**\n * List every attempt to deliver the event, across endpoints, oldest first. `params`\n * carries `limit` (at most 200) and `offset`.\n */\n async listWebhookEventAttempts(\n eventId: string,\n params?: Record<string, any>,\n ): Promise<WebhookAttemptList> {\n return this.request('GET', `${this.paths.webhookEventRoot(eventId)}/attempts/`, { params });\n }\n\n /**\n * Send the event again as a new delivery, with the same event `id`.\n *\n * With `endpoint_id` the event goes to that endpoint. Without it, the event goes to\n * every endpoint that had a delivery of it and is active and subscribed to it now;\n * the others are listed in `skipped`.\n */\n async redeliverWebhookEvent(\n eventId: string,\n options?: { endpoint_id?: string },\n ): Promise<WebhookRedeliveryResult> {\n return this.transport.request('POST', `${this.paths.webhookEventRoot(eventId)}/redeliver/`, {\n jsonBody: options?.endpoint_id !== undefined ? { endpoint_id: options.endpoint_id } : {},\n allowRetries: false,\n });\n }\n\n /** List the event-type catalogue with the JSON Schema of each payload mode. */\n async listWebhookEventTypes(): Promise<WebhookEventTypeList> {\n return this.request('GET', `${this.paths.webhooksRoot()}/event-types/`);\n }\n\n private fileRoot(collectionKey: CollectionRef, resourceKey: ResourceRef): string {\n return this.paths.fileRoot(resolveKey(collectionKey), resolveKey(resourceKey));\n }\n}\n","/**\n * Types and validation for Flux vector search requests.\n */\n\n/** Search mode for the Flux search endpoint. */\nexport const SearchMode = {\n TEXT: 'text',\n VECTOR: 'vector',\n VECTOR_BOOSTED: 'vector_boosted',\n HYBRID: 'hybrid',\n} as const;\n\nexport type SearchMode = (typeof SearchMode)[keyof typeof SearchMode];\n\n/** Configuration for auto-generated embedding search. */\nexport interface VectorSearch {\n query: string;\n fields?: string[];\n top_k?: number;\n similarity_threshold?: number;\n}\n\n/** Configuration for custom pre-computed embedding search. */\nexport interface VectorFieldSearch {\n field: string;\n query_vector: number[];\n top_k?: number;\n similarity_threshold?: number;\n}\n\n/** Configuration for vector-boosted search mode. */\nexport interface VectorBoostConfig {\n boost_factor?: number;\n similarity_threshold?: number;\n max_boost_results?: number;\n}\n\n/** Configuration for hybrid (text + vector) search mode. */\nexport interface HybridConfig {\n vector_weight?: number;\n text_weight?: number;\n rerank_results?: boolean;\n}\n\n/** Full search request payload for the Flux search endpoint. */\nexport interface SearchRequest {\n search_mode?: SearchMode;\n find_text?: Record<string, any>;\n find_phrase?: Record<string, any>;\n vector_search?: VectorSearch;\n vector_field_search?: VectorFieldSearch;\n vector_boost_config?: VectorBoostConfig;\n hybrid_config?: HybridConfig;\n limit?: number;\n offset?: number;\n [extra: string]: any;\n}\n\nconst SEARCH_REQUEST_KNOWN_KEYS = new Set([\n 'search_mode',\n 'find_text',\n 'find_phrase',\n 'vector_search',\n 'vector_field_search',\n 'vector_boost_config',\n 'hybrid_config',\n 'limit',\n 'offset',\n]);\n\nfunction checkFinite(value: number, name: string): void {\n if (!Number.isFinite(value)) {\n throw new Error(`${name} must be a finite number`);\n }\n}\n\nfunction checkThreshold(value: number | undefined, name: string): void {\n if (value != null) {\n checkFinite(value, name);\n if (value < 0 || value > 1) {\n throw new Error(`${name} must be between 0.0 and 1.0`);\n }\n }\n}\n\nfunction checkPositiveInt(value: number | undefined, name: string): void {\n if (value != null) {\n checkFinite(value, name);\n if (!Number.isInteger(value) || value < 1) {\n throw new Error(`${name} must be a positive integer (>= 1)`);\n }\n }\n}\n\nfunction validateVectorSearch(vs: VectorSearch): void {\n checkPositiveInt(vs.top_k, 'top_k');\n checkThreshold(vs.similarity_threshold, 'similarity_threshold');\n}\n\nfunction validateVectorFieldSearch(vfs: VectorFieldSearch): void {\n if (!vfs.query_vector || vfs.query_vector.length === 0) {\n throw new Error('query_vector must not be empty');\n }\n for (let i = 0; i < vfs.query_vector.length; i++) {\n if (!Number.isFinite(vfs.query_vector[i])) {\n throw new Error(`query_vector[${i}] must be a finite number`);\n }\n }\n checkPositiveInt(vfs.top_k, 'top_k');\n checkThreshold(vfs.similarity_threshold, 'similarity_threshold');\n}\n\nfunction validateBoostConfig(cfg: VectorBoostConfig): void {\n if (cfg.boost_factor != null) {\n checkFinite(cfg.boost_factor, 'boost_factor');\n if (cfg.boost_factor <= 0) {\n throw new Error('boost_factor must be > 0');\n }\n }\n checkThreshold(cfg.similarity_threshold, 'similarity_threshold');\n checkPositiveInt(cfg.max_boost_results, 'max_boost_results');\n}\n\nfunction validateHybridConfig(cfg: HybridConfig): void {\n if (cfg.vector_weight != null) {\n checkFinite(cfg.vector_weight, 'vector_weight');\n if (cfg.vector_weight < 0 || cfg.vector_weight > 1) {\n throw new Error('vector_weight must be between 0.0 and 1.0');\n }\n }\n if (cfg.text_weight != null) {\n checkFinite(cfg.text_weight, 'text_weight');\n if (cfg.text_weight < 0 || cfg.text_weight > 1) {\n throw new Error('text_weight must be between 0.0 and 1.0');\n }\n }\n const vw = cfg.vector_weight ?? 0.6;\n const tw = cfg.text_weight ?? 0.4;\n if (Math.abs(vw + tw - 1.0) > 1e-6) {\n throw new Error(`vector_weight + text_weight must equal 1.0, got ${vw + tw}`);\n }\n}\n\n/**\n * Validate a {@link SearchRequest} and return a clean body object (no undefined values).\n *\n * Enforces cross-field constraints:\n * - `vector_search` and `vector_field_search` are mutually exclusive\n * - Each search mode has specific required/forbidden fields\n */\nexport function buildSearchBody(req: SearchRequest): Record<string, any> {\n const mode = req.search_mode ?? SearchMode.TEXT;\n const vs = req.vector_search;\n const vfs = req.vector_field_search;\n const boost = req.vector_boost_config;\n const hybrid = req.hybrid_config;\n const hasText = req.find_text != null || req.find_phrase != null;\n\n // Field-level validation\n if (vs) validateVectorSearch(vs);\n if (vfs) validateVectorFieldSearch(vfs);\n if (boost) validateBoostConfig(boost);\n if (hybrid) validateHybridConfig(hybrid);\n\n // Mutual exclusion\n if (vs && vfs) {\n throw new Error('vector_search and vector_field_search are mutually exclusive');\n }\n\n // Per-mode rules\n if (mode === SearchMode.TEXT) {\n if (vs) throw new Error('vector_search is not allowed in text search mode');\n if (vfs) throw new Error('vector_field_search is not allowed in text search mode');\n if (boost) throw new Error('vector_boost_config is not allowed in text search mode');\n if (hybrid) throw new Error('hybrid_config is not allowed in text search mode');\n } else if (mode === SearchMode.VECTOR) {\n if (!vs && !vfs) {\n throw new Error('vector search mode requires vector_search or vector_field_search');\n }\n if (boost) throw new Error('vector_boost_config is not allowed in vector search mode');\n if (hybrid) throw new Error('hybrid_config is not allowed in vector search mode');\n } else if (mode === SearchMode.VECTOR_BOOSTED) {\n if (!vs && !vfs) {\n throw new Error('vector_boosted mode requires vector_search or vector_field_search');\n }\n if (!hasText) throw new Error('vector_boosted mode requires find_text or find_phrase');\n if (hybrid) throw new Error('hybrid_config is not allowed in vector_boosted mode');\n } else if (mode === SearchMode.HYBRID) {\n if (vfs) throw new Error('vector_field_search is not allowed in hybrid mode');\n if (!vs) throw new Error('hybrid mode requires vector_search');\n if (!hasText) throw new Error('hybrid mode requires find_text or find_phrase');\n if (boost) throw new Error('vector_boost_config is not allowed in hybrid mode');\n } else {\n const validModes = Object.values(SearchMode).join(', ');\n throw new Error(`Unknown search_mode: \"${mode}\". Valid modes: ${validModes}`);\n }\n\n // Build clean body (strip undefined)\n const body: Record<string, any> = {};\n for (const [key, value] of Object.entries(req)) {\n if (value !== undefined) {\n body[key] = value;\n }\n }\n if (!body.search_mode) {\n body.search_mode = mode;\n }\n return body;\n}\n\n/**\n * Merge extra body params, rejecting keys that conflict with SearchRequest fields.\n * @internal\n */\nexport function mergeExtra(\n validated: Record<string, any>,\n extra: Record<string, any>,\n): Record<string, any> {\n if ('truncate_text' in extra) {\n throw new Error(\n \"'truncate_text' is a query parameter, not a body field. Pass it via the 'queryParams' option instead.\",\n );\n }\n const conflicts: string[] = [];\n for (const key of Object.keys(extra)) {\n if (SEARCH_REQUEST_KNOWN_KEYS.has(key)) {\n conflicts.push(key);\n }\n }\n if (conflicts.length > 0) {\n throw new Error(\n `extra keys conflict with SearchRequest fields: ${conflicts.sort().join(', ')}. ` +\n 'Use the explicit parameters instead.',\n );\n }\n return { ...validated, ...extra };\n}\n\n/**\n * A grant for one upload to a files collection.\n *\n * The grant is a credential. The field names are the wire names, so the object\n * can go to a browser as it is, and that same object prints every token: keep it\n * out of logs and error reports.\n */\nexport interface UploadSignature {\n publicKey: string;\n /** The upload host. */\n uploadBaseUrl: string;\n authToken: string;\n /** When the token ends, in Unix seconds. */\n tokenExpire: number;\n /** Passed to the upload unchanged. */\n store: string;\n /** Passed to the upload unchanged. */\n metadata: Record<string, unknown>;\n /** The id to poll with {@link FluxClient.getUploadStatus}. */\n upload_id: string;\n /** The end user's token for reading the status. */\n status_token: string;\n /** The order of status tokens in a session. */\n rotation: number;\n}\n\n/**\n * The status of one file of an upload.\n *\n * A key sees `state` as `processing`, `ready` (with `record_key`),\n * `pending_review` or `rejected` (with `public_reason`). A status token sees\n * `processing`, `accepted` or `rejected`, with `user_status`, `reason` and `slot`.\n */\nexport interface UploadFileStatus {\n state: string;\n record_key?: string | null;\n public_reason?: string;\n user_status?: string;\n reason?: string;\n slot?: number;\n}\n\n/**\n * The status of an upload.\n *\n * For an upload of one file these are that file's fields. For a link of several\n * files, `state` is `processing` or `done` and `files` and `remaining` are set; a\n * status token also gets `slots_uploading`.\n */\nexport interface UploadStatus extends UploadFileStatus {\n files?: UploadFileStatus[];\n remaining?: number;\n slots_uploading?: { slot: number }[];\n}\n","import type { AuthStrategy } from '../auth/types.js';\nimport type { RetryConfig } from '../config.js';\nimport { createConfig } from '../config.js';\nimport { HttpTransport } from '../http.js';\nimport type {\n HybridConfig,\n SearchRequest,\n UploadSignature,\n UploadStatus,\n VectorBoostConfig,\n VectorFieldSearch,\n VectorSearch,\n} from './models.js';\nimport { SearchMode, buildSearchBody, mergeExtra } from './models.js';\n\nfunction cleanPrefix(prefix: string): string {\n const value = prefix.replace(/^\\/+|\\/+$/g, '');\n if (!value) {\n throw new Error('apiPrefix cannot be empty');\n }\n return value;\n}\n\nfunction normalizeFolderPath(folderPath: string): string {\n return folderPath.replace(/^\\/+|\\/+$/g, '');\n}\n\nexport interface FluxClientOptions {\n baseUrl: string;\n apiPrefix: string;\n auth: AuthStrategy;\n timeout?: number;\n retryConfig?: RetryConfig;\n defaultHeaders?: Record<string, string>;\n}\n\nexport interface VectorSearchOptions {\n query: string;\n fields?: string[];\n top_k?: number;\n similarity_threshold?: number;\n limit?: number;\n offset?: number;\n /**\n * Query-string parameters for the underlying `search()` call (e.g.\n * `{ truncate_text: 200 }`). Named `queryParams`, not `params`: this\n * options object also carries an index signature that funnels unknown\n * keys into the JSON body, and an explicit `params` field would silently\n * reroute an existing `params` body extra to the query string.\n */\n queryParams?: Record<string, any>;\n [extra: string]: any;\n}\n\nexport interface VectorFieldSearchOptions {\n field: string;\n query_vector: number[];\n top_k?: number;\n similarity_threshold?: number;\n limit?: number;\n offset?: number;\n /** See {@link VectorSearchOptions.queryParams}. */\n queryParams?: Record<string, any>;\n [extra: string]: any;\n}\n\nexport interface HybridSearchOptions {\n query: string;\n find_text: Record<string, any>;\n fields?: string[];\n top_k?: number;\n similarity_threshold?: number;\n vector_weight?: number;\n text_weight?: number;\n rerank_results?: boolean;\n limit?: number;\n offset?: number;\n /** See {@link VectorSearchOptions.queryParams}. */\n queryParams?: Record<string, any>;\n [extra: string]: any;\n}\n\nexport interface BoostedSearchOptions {\n find_text: Record<string, any>;\n query?: string;\n field?: string;\n query_vector?: number[];\n top_k?: number;\n similarity_threshold?: number;\n boost_factor?: number;\n boost_similarity_threshold?: number;\n max_boost_results?: number;\n limit?: number;\n offset?: number;\n /** See {@link VectorSearchOptions.queryParams}. */\n queryParams?: Record<string, any>;\n [extra: string]: any;\n}\n\nfunction stripUndefined(obj: Record<string, any>): Record<string, any> {\n const result: Record<string, any> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (value !== undefined) {\n result[key] = value;\n }\n }\n return result;\n}\n\n/**\n * Client for FoxNose Flux delivery APIs.\n *\n * All methods are async and return parsed JSON responses.\n */\n/**\n * Declares untrusted content for a collection's guardrails, next to `data` on a write:\n * top-level fields to mark untrusted, and an optional `source` label\n * (`[a-z0-9_-]{1,32}`).\n */\nexport interface WriteProvenance {\n untrusted_fields: string[];\n source?: string;\n}\n\nexport class FluxClient {\n readonly apiPrefix: string;\n private readonly transport: HttpTransport;\n\n constructor(options: FluxClientOptions) {\n this.apiPrefix = cleanPrefix(options.apiPrefix);\n const config = createConfig({\n baseUrl: options.baseUrl,\n timeout: options.timeout ?? 15_000,\n defaultHeaders: options.defaultHeaders,\n });\n this.transport = new HttpTransport({\n config,\n auth: options.auth,\n retryConfig: options.retryConfig,\n });\n }\n\n private buildPath(folderPath: string, suffix = ''): string {\n const folder = normalizeFolderPath(folderPath);\n const base = `/${this.apiPrefix}/${folder}`;\n return suffix ? `${base}${suffix}` : base;\n }\n\n async listResources<T = any>(folderPath: string, params?: Record<string, any>): Promise<T> {\n const path = this.buildPath(folderPath);\n return this.transport.request('GET', path, { params });\n }\n\n async getResource<T = any>(\n folderPath: string,\n resourceKey: string,\n params?: Record<string, any>,\n ): Promise<T> {\n const path = this.buildPath(folderPath, `/${resourceKey}`);\n return this.transport.request('GET', path, { params });\n }\n\n async search<T = any>(\n folderPath: string,\n body: Record<string, any>,\n options?: { params?: Record<string, any> },\n ): Promise<T> {\n const path = this.buildPath(folderPath, '/_search');\n return this.transport.request('POST', path, { jsonBody: body, params: options?.params });\n }\n\n /**\n * Create a resource in a collection and publish it immediately.\n *\n * `folderPath` is the collection path (e.g. `articles` or a nested path such\n * as `users/usr_1/memories`). `options.key` is an optional external\n * identifier for deduplication — reusing an existing key raises\n * {@link ExternalIdConflictError}. The response carries `resource_key`,\n * `revision_key`, `write_units`, and `published`.\n *\n * Writes require an authenticated key with write access: an anonymous caller\n * gets 401, a key without the `create` grant gets a generic 403\n * (`access_denied`), and a collection whose connection does not allow writes\n * raises {@link CollectionNotWritableError}.\n *\n * Writes are never retried automatically: a failed write's outcome is\n * unknown, so re-read with a GET before retrying.\n *\n * `options.provenance` declares untrusted fields for the collection's guardrails,\n * such as `{ untrusted_fields: ['body'], source: 'support-inbox' }`.\n */\n async createResource<T = any>(\n folderPath: string,\n data: Record<string, any>,\n options?: { key?: string; provenance?: WriteProvenance },\n ): Promise<T> {\n const path = this.buildPath(folderPath, '/');\n const body: Record<string, any> = { data };\n if (options?.key !== undefined) {\n body.key = options.key;\n }\n if (options?.provenance !== undefined) {\n body.provenance = options.provenance;\n }\n return this.transport.request('POST', path, { jsonBody: body, allowRetries: false });\n }\n\n /**\n * Replace a resource's document and publish a new revision. This is a\n * full-document replace, not a partial merge: fields absent from `data` are\n * removed.\n *\n * Writes require an authenticated key with write access: an anonymous caller\n * gets 401, a key without the `update` grant gets a generic 403\n * (`access_denied`), and a collection whose connection does not allow writes\n * raises {@link CollectionNotWritableError}. Like {@link createResource}, it\n * is never retried automatically.\n */\n async updateResource<T = any>(\n folderPath: string,\n resourceKey: string,\n data: Record<string, any>,\n options?: { provenance?: WriteProvenance },\n ): Promise<T> {\n const path = this.buildPath(folderPath, `/${resourceKey}/`);\n const body: Record<string, any> = { data };\n if (options?.provenance !== undefined) {\n body.provenance = options.provenance;\n }\n return this.transport.request('PUT', path, { jsonBody: body, allowRetries: false });\n }\n\n /**\n * Get a grant for one upload to a files collection.\n *\n * The grant is a credential: pass it on, do not log it. For a strict collection\n * `folderPath` names the owner, e.g. `support/tickets/tk_1/attachments`. Needs a\n * key with create access to the collection.\n *\n * `options.sessionKey` is an optional idempotency key of 43 URL-safe characters:\n * a repeat with the same key, collection and owner reaches the same upload\n * session. A failed request is never retried automatically, so send one to\n * retry safely.\n */\n async createUploadSignature(\n folderPath: string,\n options?: { sessionKey?: string },\n ): Promise<UploadSignature> {\n const path = this.buildPath(folderPath, '/_upload-signature');\n const sessionKey = options?.sessionKey;\n return this.transport.request('POST', path, {\n jsonBody: sessionKey === undefined ? undefined : { session_key: sessionKey },\n allowRetries: false,\n });\n }\n\n /**\n * Read the status of an upload.\n *\n * A key reads the uploads that key started, and the path must name the same\n * collection and owner. Any other combination is `404 not_found`, which includes\n * a link made through the Management API: read that one with\n * `ManagementClient.getUploadLink`.\n *\n * `options.statusToken` is the end user's token from the grant, for a client that\n * holds no key (use `AnonymousAuth`). It answers the end user's view, which never\n * carries a record key. A request authenticated by a key ignores it.\n */\n async getUploadStatus(\n folderPath: string,\n uploadId: string,\n options?: { statusToken?: string },\n ): Promise<UploadStatus> {\n const path = this.buildPath(folderPath, `/_uploads/${encodeURIComponent(uploadId)}`);\n const statusToken = options?.statusToken;\n return this.transport.request('GET', path, {\n headers: statusToken === undefined ? undefined : { 'X-Upload-Status-Token': statusToken },\n });\n }\n\n /** Semantic search using auto-generated embeddings. */\n async vectorSearch<T = any>(folderPath: string, options: VectorSearchOptions): Promise<T> {\n const {\n query,\n fields,\n top_k = 10,\n similarity_threshold,\n limit,\n offset,\n queryParams,\n ...rest\n } = options;\n const extra = stripUndefined(rest);\n const vs: VectorSearch = { query, fields, top_k, similarity_threshold };\n const req: SearchRequest = {\n search_mode: SearchMode.VECTOR,\n vector_search: vs,\n limit,\n offset,\n };\n const body = mergeExtra(buildSearchBody(req), extra);\n return this.search(folderPath, body, { params: queryParams });\n }\n\n /** Search using custom pre-computed embeddings. */\n async vectorFieldSearch<T = any>(\n folderPath: string,\n options: VectorFieldSearchOptions,\n ): Promise<T> {\n const {\n field,\n query_vector,\n top_k = 10,\n similarity_threshold,\n limit,\n offset,\n queryParams,\n ...rest\n } = options;\n const extra = stripUndefined(rest);\n const vfs: VectorFieldSearch = { field, query_vector, top_k, similarity_threshold };\n const req: SearchRequest = {\n search_mode: SearchMode.VECTOR,\n vector_field_search: vfs,\n limit,\n offset,\n };\n const body = mergeExtra(buildSearchBody(req), extra);\n return this.search(folderPath, body, { params: queryParams });\n }\n\n /** Blended text + vector search with configurable weights. */\n async hybridSearch<T = any>(folderPath: string, options: HybridSearchOptions): Promise<T> {\n const {\n query,\n find_text,\n fields,\n top_k = 10,\n similarity_threshold,\n vector_weight = 0.6,\n text_weight = 0.4,\n rerank_results = true,\n limit,\n offset,\n queryParams,\n ...rest\n } = options;\n const extra = stripUndefined(rest);\n const vs: VectorSearch = { query, fields, top_k, similarity_threshold };\n const hybrid: HybridConfig = { vector_weight, text_weight, rerank_results };\n const req: SearchRequest = {\n search_mode: SearchMode.HYBRID,\n find_text,\n vector_search: vs,\n hybrid_config: hybrid,\n limit,\n offset,\n };\n const body = mergeExtra(buildSearchBody(req), extra);\n return this.search(folderPath, body, { params: queryParams });\n }\n\n /** Text search with results boosted by vector similarity. */\n async boostedSearch<T = any>(folderPath: string, options: BoostedSearchOptions): Promise<T> {\n const {\n find_text,\n query,\n field,\n query_vector,\n top_k = 10,\n similarity_threshold,\n boost_factor = 1.5,\n boost_similarity_threshold,\n max_boost_results = 20,\n limit,\n offset,\n queryParams,\n ...rest\n } = options;\n const extra = stripUndefined(rest);\n\n const hasAuto = query != null;\n const hasCustom = field != null || query_vector != null;\n\n if (hasAuto && hasCustom) {\n throw new Error(\n \"Provide either 'query' for auto-generated embeddings \" +\n \"or 'field' + 'query_vector' for custom embeddings, not both\",\n );\n }\n\n let vs: VectorSearch | undefined;\n let vfs: VectorFieldSearch | undefined;\n\n if (hasAuto) {\n vs = { query: query!, top_k, similarity_threshold };\n } else if (field != null && query_vector != null) {\n vfs = { field, query_vector, top_k, similarity_threshold };\n } else {\n throw new Error(\n \"Provide either 'query' for auto-generated embeddings \" +\n \"or 'field' + 'query_vector' for custom embeddings\",\n );\n }\n\n const boostConfig: VectorBoostConfig = {\n boost_factor,\n similarity_threshold: boost_similarity_threshold,\n max_boost_results,\n };\n\n const req: SearchRequest = {\n search_mode: SearchMode.VECTOR_BOOSTED,\n find_text,\n vector_search: vs,\n vector_field_search: vfs,\n vector_boost_config: boostConfig,\n limit,\n offset,\n };\n const body = mergeExtra(buildSearchBody(req), extra);\n return this.search(folderPath, body, { params: queryParams });\n }\n\n async getRouter<T = any>(): Promise<T> {\n const path = `/${this.apiPrefix}/_router`;\n return this.transport.request('GET', path);\n }\n\n async getSchema<T = any>(folderPath: string): Promise<T> {\n const path = this.buildPath(folderPath, '/_schema');\n return this.transport.request('GET', path);\n }\n\n close(): void {\n this.transport.close();\n }\n}\n","/**\n * Typed trust metadata of Flux records.\n *\n * Flux reads return plain objects. These readers check the trust metadata they carry:\n *\n * - `_sys.trust` on a record of a collection with guardrails in `provenance` or\n * `screened` mode, when the Flux API's `trust_delivery` is `metadata`;\n * - `data.trust` on a record of a files collection.\n *\n * A record without trust metadata says nothing about whether it can be trusted: the\n * collection may have guardrails off, or the API may not deliver the metadata. Trust\n * metadata that is present but malformed throws {@link MalformedTrustMetadataError};\n * treat that record as untrusted.\n *\n * @module\n */\n\nexport const RECORD_TRUST_SOURCE = 'record_write';\nexport const FILE_TRUST_SOURCE = 'end_user_upload';\nconst FILE_VERDICTS = ['clean', 'suspicious'];\nconst PROVENANCE_STATES = ['recorded', 'unknown'];\nconst FILE_PROCESSING = ['agent_ready', 'storage_only'];\nconst FLAG_SCOPES = ['line', 'page', 'region'];\n/** The key of a collection's file block unless the collection names it otherwise. */\nconst DEFAULT_FILE_BLOCK_KEY = 'file';\n\n/** A record carries trust metadata that cannot be read. Treat it as untrusted. */\nexport class MalformedTrustMetadataError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'MalformedTrustMetadataError';\n }\n}\n\n/** The guardrails trust object of a record (`_sys.trust`). */\nexport interface RecordTrust {\n version: number;\n source: string;\n provenance: string;\n screened: boolean;\n /** Set on a revision that was screened: `clean` or `suspicious`. */\n verdict?: string | null;\n reasons?: string[] | null;\n path_format: string;\n /** JSON Pointers relative to the record's `data`. */\n tainted_paths: string[];\n writers: Record<string, string>;\n sources: Record<string, string>;\n [key: string]: unknown;\n}\n\n/** A region withheld from a page's text and painted over in its image. */\nexport interface FileRegion {\n /** Counts from 1. */\n page: number;\n reason: string;\n /** `[x0, y0, x1, y1]`, fractions of the page width and height (`x0 <= x1`, `y0 <= y1`). */\n boxes: number[][];\n [key: string]: unknown;\n}\n\n/** Delivered text that is flagged as unreliable. */\nexport interface FileContentFlag extends FileRegion {\n /** `line`, `page` or `region`. */\n scope: string | null;\n /** Zero-based. */\n lines: number[];\n}\n\n/**\n * The trust object of a files record (`data.trust`). Everything file-derived is\n * untrusted. Every field is always sent; a missing one makes the object malformed.\n */\nexport interface FileContentTrust {\n version: number;\n source: string;\n /** The `uuid` of the file block. */\n upload: string;\n verdict: string;\n reasons: string[];\n processing: string;\n redacted: FileRegion[];\n unreliable: FileContentFlag[];\n /** Dotted paths of the record, such as `content` and `file.original_filename`. */\n tainted_paths: string[];\n [key: string]: unknown;\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isInt(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value);\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((v) => typeof v === 'string');\n}\n\nfunction isStringMap(value: unknown): value is Record<string, string> {\n return isObject(value) && Object.values(value).every((v) => typeof v === 'string');\n}\n\nconst TOP_LEVEL_POINTER = /^\\/(?:[^/~]|~[01])*$/;\n\n/**\n * The field a top-level JSON Pointer names: `/body` is `body`, `/a~1b` is `a/b`.\n * @throws MalformedTrustMetadataError The value is not a top-level JSON Pointer.\n */\nexport function pointerField(pointer: unknown): string {\n if (typeof pointer !== 'string' || !TOP_LEVEL_POINTER.test(pointer)) {\n throw new MalformedTrustMetadataError('a tainted path is not a top-level JSON Pointer');\n }\n return pointer.slice(1).replace(/~1/g, '/').replace(/~0/g, '~');\n}\n\n/**\n * The top-level field a dotted files path names: `file.original_filename` is `file`.\n * @throws MalformedTrustMetadataError The value is not a dotted path of non-empty segments.\n */\nexport function dottedField(path: unknown): string {\n if (\n typeof path !== 'string' ||\n path.length === 0 ||\n path.startsWith('/') ||\n path.split('.').some((part) => part.length === 0)\n ) {\n throw new MalformedTrustMetadataError('a files tainted path is not a dotted path');\n }\n return path.split('.')[0];\n}\n\n/** A field that may be absent or `null`. */\nfunction optional(value: unknown, check: (v: unknown) => boolean): boolean {\n return value === undefined || value === null || check(value);\n}\n\n/** A box: `[x0, y0, x1, y1]`, each a fraction of the page, with `x0 <= x1` and `y0 <= y1`. */\nfunction isBox(value: unknown): boolean {\n return (\n Array.isArray(value) &&\n value.length === 4 &&\n value.every((n) => typeof n === 'number' && Number.isFinite(n) && n >= 0 && n <= 1) &&\n value[0] <= value[2] &&\n value[1] <= value[3]\n );\n}\n\nfunction isRegion(value: unknown): boolean {\n return (\n isObject(value) &&\n isInt(value.page) &&\n value.page >= 1 &&\n typeof value.reason === 'string' &&\n Array.isArray(value.boxes) &&\n value.boxes.every(isBox)\n );\n}\n\nfunction isFlag(value: unknown): boolean {\n if (!isRegion(value)) return false;\n const flag = value as Record<string, unknown>;\n return (\n (flag.scope === null || FLAG_SCOPES.includes(flag.scope as string)) &&\n Array.isArray(flag.lines) &&\n flag.lines.every((line) => isInt(line) && line >= 0)\n );\n}\n\nfunction parseRecordTrust(value: unknown): RecordTrust {\n if (!isObject(value)) {\n throw new MalformedTrustMetadataError('_sys.trust is not an object');\n }\n const ok =\n isInt(value.version) &&\n typeof value.source === 'string' &&\n typeof value.provenance === 'string' &&\n typeof value.screened === 'boolean' &&\n optional(value.verdict, (v) => typeof v === 'string') &&\n optional(value.reasons, isStringArray) &&\n typeof value.path_format === 'string' &&\n isStringArray(value.tainted_paths) &&\n isStringMap(value.writers) &&\n isStringMap(value.sources);\n // A screened revision carries verdict and reasons together (absent, never null), and\n // `screened` only with them; one writer per tainted path, a source only for one.\n const tainted = new Set(ok ? (value.tainted_paths as string[]) : []);\n const writers = ok ? Object.keys(value.writers as object) : [];\n const consistent =\n value.verdict !== null &&\n value.reasons !== null &&\n (value.verdict === undefined) === (value.reasons === undefined) &&\n !(value.screened === true && value.verdict === undefined) &&\n writers.length === tainted.size &&\n writers.every((path) => tainted.has(path)) &&\n // writers not recorded: no path is known to be tainted (nor, so, a writer or source)\n !(value.provenance === 'unknown' && tainted.size > 0) &&\n (!ok || Object.keys(value.sources as object).every((path) => tainted.has(path)));\n if (!ok || !consistent) {\n throw new MalformedTrustMetadataError('_sys.trust is malformed');\n }\n const trust = { ...value } as RecordTrust;\n for (const path of [\n ...trust.tainted_paths,\n ...Object.keys(trust.writers),\n ...Object.keys(trust.sources),\n ]) {\n pointerField(path);\n }\n return trust;\n}\n\nfunction parseFileTrust(value: unknown): FileContentTrust {\n if (!isObject(value)) {\n throw new MalformedTrustMetadataError('data.trust is not an object');\n }\n const ok =\n isInt(value.version) &&\n typeof value.source === 'string' &&\n typeof value.upload === 'string' &&\n typeof value.verdict === 'string' &&\n isStringArray(value.reasons) &&\n typeof value.processing === 'string' &&\n Array.isArray(value.redacted) &&\n value.redacted.every(isRegion) &&\n Array.isArray(value.unreliable) &&\n value.unreliable.every(isFlag) &&\n isStringArray(value.tainted_paths);\n if (!ok) {\n throw new MalformedTrustMetadataError('data.trust is malformed');\n }\n const trust = { ...value } as FileContentTrust;\n for (const path of trust.tainted_paths) {\n dottedField(path);\n }\n return trust;\n}\n\n/** Whether this SDK knows a record trust object's version, source, provenance, path format and verdict. */\nexport function isRecognizedRecordTrust(trust: RecordTrust): boolean {\n return (\n trust.version === 1 &&\n trust.source === RECORD_TRUST_SOURCE &&\n PROVENANCE_STATES.includes(trust.provenance) &&\n trust.path_format === 'json_pointer' &&\n (trust.verdict === undefined || FILE_VERDICTS.includes(trust.verdict as string))\n );\n}\n\n/** Whether this SDK knows a files trust object's version, source, verdict and processing. */\nexport function isRecognizedFileTrust(trust: FileContentTrust): boolean {\n return (\n trust.version === 1 &&\n trust.source === FILE_TRUST_SOURCE &&\n FILE_VERDICTS.includes(trust.verdict) &&\n FILE_PROCESSING.includes(trust.processing)\n );\n}\n\n/**\n * Read a record's guardrails trust object (`_sys.trust`).\n * @returns `null` when the record carries none.\n * @throws MalformedTrustMetadataError `_sys.trust` is present but cannot be read.\n */\nexport function getRecordTrust(record: unknown): RecordTrust | null {\n const sys = isObject(record) ? record._sys : undefined;\n if (!isObject(sys) || !('trust' in sys)) {\n return null;\n }\n return parseRecordTrust(sys.trust);\n}\n\nfunction fileBlocks(data: Record<string, unknown>): Record<string, unknown>[] {\n // The objects of `data` that are a file block on their own: `file` (the default key)\n // with `processing`, which a storage-only block also has (a missing `uuid` then\n // leaves `upload` unbound: malformed, not skipped), or one under any key with the\n // `uuid` and `tainted_paths` an agent-ready block adds. A customer component\n // elsewhere with only `uuid` and `processing` is not a file block.\n return Object.entries(data)\n .filter(\n ([key, value]) =>\n isObject(value) &&\n 'processing' in value &&\n (key === DEFAULT_FILE_BLOCK_KEY || ('uuid' in value && 'tainted_paths' in value)),\n )\n .map(([, value]) => value as Record<string, unknown>);\n}\n\nfunction boundBlock(\n data: Record<string, unknown>,\n upload: unknown,\n): Record<string, unknown> | undefined {\n // The object of `data` with `processing` whose string `uuid` is `upload`: the block\n // `data.trust` names, under any key (a storage-only block under the collection's own\n // key has no `tainted_paths`).\n if (typeof upload !== 'string' || upload.length === 0) return undefined;\n const found = Object.entries(data).find(\n ([key, value]) =>\n key !== 'trust' && isObject(value) && 'processing' in value && value.uuid === upload,\n );\n return found?.[1] as Record<string, unknown> | undefined;\n}\n\nfunction isFilesData(data: Record<string, unknown>): boolean {\n // A files record is known by a `data.trust` with source `end_user_upload`, by a file\n // block, or by an object that `data.trust.upload` names. A customer field named\n // `trust` alone does not make one.\n const trust = data.trust;\n return (\n (isObject(trust) && trust.source === FILE_TRUST_SOURCE) ||\n fileBlocks(data).length > 0 ||\n (isObject(trust) && boundBlock(data, trust.upload) !== undefined)\n );\n}\n\n/**\n * Read the trust object of a files record (`data.trust`).\n *\n * A files record is one whose `data.trust` has source `end_user_upload`, or whose\n * `data` holds its file block: `file` with `processing`, an object under\n * another key with `uuid`, `processing` and `tainted_paths`, or an object with\n * `processing` whose `uuid` is `data.trust.upload`. `upload` names the `uuid` of the\n * file block, which a files record always has, and `processing` is `agent_ready`\n * exactly when the block's is.\n * @returns `null` when the record is not a files record.\n * @throws MalformedTrustMetadataError The record is a files record and its `trust`\n * is missing or cannot be read.\n */\nexport function getFileTrust(record: unknown): FileContentTrust | null {\n const data = isObject(record) ? record.data : undefined;\n if (!isObject(data) || !isFilesData(data)) {\n return null;\n }\n if (!('trust' in data)) {\n throw new MalformedTrustMetadataError('a files record has no data.trust');\n }\n const trust = parseFileTrust(data.trust);\n const block = boundBlock(data, trust.upload);\n if (block === undefined) {\n throw new MalformedTrustMetadataError(\"data.trust.upload is not a file block's uuid\");\n }\n // Flux reports agent_ready exactly when the block is agent_ready (a processing this\n // SDK does not know is left to isRecognizedFileTrust).\n if (\n FILE_PROCESSING.includes(trust.processing) &&\n (block.processing === 'agent_ready') !== (trust.processing === 'agent_ready')\n ) {\n throw new MalformedTrustMetadataError('data.trust.processing disagrees with the file block');\n }\n return trust;\n}\n\n/**\n * The record's top-level `data` fields that hold untrusted values, sorted.\n *\n * The union of what `_sys.trust` and a files record's `data.trust` list. When either\n * is present but not recognized, every `data` field is returned (and none of the\n * paths it lists, which are not read).\n *\n * @throws MalformedTrustMetadataError Trust metadata is present but cannot be read.\n */\nexport function getUntrustedFields(record: unknown): string[] {\n const data = isObject(record) && isObject(record.data) ? record.data : {};\n const fields = new Set<string>();\n const recordTrust = getRecordTrust(record);\n const fileTrust = getFileTrust(record);\n if (recordTrust) {\n const tainted = recordTrust.tainted_paths.map(pointerField);\n if (!isRecognizedRecordTrust(recordTrust)) {\n return Object.keys(data).sort();\n }\n tainted.forEach((f) => fields.add(f));\n }\n if (fileTrust) {\n const tainted = fileTrust.tainted_paths.map(dottedField);\n if (!isRecognizedFileTrust(fileTrust)) {\n return Object.keys(data).sort();\n }\n tainted.forEach((f) => fields.add(f));\n }\n return [...fields].sort();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKO,IAAM,gBAAN,MAA4C;AAAA,EACjD,aAAa,UAA+C;AAC1D,WAAO,CAAC;AAAA,EACV;AACF;;;ACJO,IAAM,sBAAN,MAAmD;AAAA,EACxD,YAA6B,OAAe;AAAf;AAAA,EAAgB;AAAA,EAE7C,WAAmB;AACjB,WAAO,KAAK;AAAA,EACd;AACF;AAKO,IAAM,UAAN,MAAM,SAAgC;AAAA,EAC1B;AAAA,EACA;AAAA,EAEjB,YAAY,UAAyB,SAA+B;AAClE,SAAK,WAAW;AAChB,SAAK,SAAS,SAAS,UAAU;AAAA,EACnC;AAAA,EAEA,aAAa,UAA+C;AAC1D,UAAM,QAAQ,KAAK,SAAS,SAAS;AACrC,QAAI,CAAC,OAAO;AACV,YAAM,IAAI,MAAM,wCAAwC;AAAA,IAC1D;AACA,WAAO,EAAE,eAAe,GAAG,KAAK,MAAM,IAAI,KAAK,GAAG;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA,EAKA,OAAO,gBAAgB,OAAe,SAAwC;AAC5E,WAAO,I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