@burdenoff/be-sdk 2026.1130.2 → 2026.1201.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +6 -1
  2. package/dist/context/index.js +7 -2
  3. package/dist/context/index.js.map +1 -1
  4. package/dist/files/index.d.ts +2 -2
  5. package/dist/files/index.js +2 -2
  6. package/dist/{files-h5U-D2AF.js → files-BISdM0fh.js} +188 -28
  7. package/dist/files-BISdM0fh.js.map +1 -0
  8. package/dist/{bun-runtime-metrics-CPy5D6NT.js → incoming-request-span-DCou42Il.js} +56 -2
  9. package/dist/incoming-request-span-DCou42Il.js.map +1 -0
  10. package/dist/{index-CIgoeobA.d.ts → index-Bnz5Bqtl.d.ts} +14 -3
  11. package/dist/{index-8pUSoT85.d.ts → index-ieSQpD9r.d.ts} +26 -3
  12. package/dist/index.d.ts +2 -2
  13. package/dist/index.js +4 -4
  14. package/dist/prisma/index.js +2 -2
  15. package/dist/{prisma-Bo-C0XUv.js → prisma-D0f-THMv.js} +2 -2
  16. package/dist/{prisma-Bo-C0XUv.js.map → prisma-D0f-THMv.js.map} +1 -1
  17. package/dist/{sdk-7TBR987n.js → sdk-Oooulm2n.js} +22 -6
  18. package/dist/sdk-Oooulm2n.js.map +1 -0
  19. package/dist/server/index.js +5 -5
  20. package/dist/server/index.js.map +1 -1
  21. package/dist/{stub-DNkzpQvR.js → stub-CmVOE6ql.js} +2 -2
  22. package/dist/{stub-DNkzpQvR.js.map → stub-CmVOE6ql.js.map} +1 -1
  23. package/dist/telemetry/index.d.ts +40 -2
  24. package/dist/telemetry/index.js +3 -3
  25. package/dist/telemetry/index.js.map +1 -1
  26. package/dist/tracker/index.js +2 -2
  27. package/dist/{tracker-CDVYIoCb.js → tracker-CNF8TRpk.js} +2 -2
  28. package/dist/{tracker-CDVYIoCb.js.map → tracker-CNF8TRpk.js.map} +1 -1
  29. package/dist/validation/index.d.ts +2 -2
  30. package/dist/validation/index.js +2 -2
  31. package/dist/{validation-CPUITdMk.js → validation-bwJzOytZ.js} +66 -97
  32. package/dist/{validation-CPUITdMk.js.map → validation-bwJzOytZ.js.map} +1 -1
  33. package/dist/{workspace-extension-BcMPoGWr.js → workspace-extension-feJYFO9e.js} +41 -8
  34. package/dist/workspace-extension-feJYFO9e.js.map +1 -0
  35. package/package.json +1 -1
  36. package/dist/bun-runtime-metrics-CPy5D6NT.js.map +0 -1
  37. package/dist/files-h5U-D2AF.js.map +0 -1
  38. package/dist/sdk-7TBR987n.js.map +0 -1
  39. package/dist/workspace-extension-BcMPoGWr.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"files-BISdM0fh.js","names":[],"sources":["../src/files/types.ts","../src/files/errors.ts","../src/files/client.ts","../src/files/reference.ts","../src/files/index.ts"],"sourcesContent":["/**\n * Files client — shared types.\n *\n * wspace-files-svc is the one owner of workspace blobs. Product services never\n * presign S3 themselves or hold storage keys: they hand bytes to files-svc\n * through the internal workspace gateway and keep only the opaque `fileId`.\n * These types describe the wire shape the client reads from files-svc and the\n * projection it hands back to the service.\n */\nimport type { GraphQLRequestOptions, GraphQLResponse } from '../gateway/types.js';\n\n/** Actor types the gateway forwards in `x-actor-type`. */\nexport const FILE_ACTOR_TYPES = ['user', 'app', 'service', 'super_admin'] as const;\n\nexport type FileActorType = (typeof FILE_ACTOR_TYPES)[number];\n\n/**\n * The caller a file operation runs on behalf of (forwarded as `x-actor-*` /\n * `x-workspace-id`).\n *\n * Pass the END USER who asked for the operation, not the service: files-svc\n * records `actorId` as the uploader, scopes the File row to `workspaceId`, and\n * checks quota, folder access and read permission against that actor. A row\n * uploaded \"as the service\" belongs to nobody the workspace can see.\n */\nexport interface FileActor {\n /** `x-actor-id` — the user/app the gateway authenticated. */\n actorId: string;\n /** `x-workspace-id` — the workspace the File row belongs to. */\n workspaceId: string;\n /** `x-actor-type`; defaults to `user`. */\n actorType?: FileActorType;\n}\n\n/** `FileVisibility` enum members accepted by wspace-files-svc. */\nexport const FILE_VISIBILITIES = ['PRIVATE', 'PUBLIC', 'TEAM', 'WORKSPACE'] as const;\n\nexport type FileVisibility = (typeof FILE_VISIBILITIES)[number];\n\n/** `FileStatus` enum members returned by wspace-files-svc. */\nexport type FileStatus = 'ACTIVE' | 'ARCHIVED' | 'DELETED' | 'UPLOADING';\n\n/** `UploadType` chosen by files-svc for a session (it switches large files to MULTIPART). */\nexport type FileUploadType = 'DIRECT' | 'MULTIPART' | 'RESUMABLE';\n\n/** Bytes the client can upload. Node/Bun `Buffer` is a `Uint8Array`. */\nexport type FileBytes = Uint8Array | ArrayBuffer;\n\n/** Input for {@link FilesClient.uploadFile}. */\nexport interface UploadFileInput {\n /** File name shown in the workspace library, e.g. `soc2-evidence.pdf`. */\n fileName: string;\n /** The file contents. */\n data: FileBytes;\n /** MIME type, e.g. `application/pdf`. Sent as the PUT `Content-Type`. */\n mimeType: string;\n /** Extension without the dot. Default: taken from `fileName`, else `bin`. */\n extension?: string;\n /** Folder to file it in. The actor must be allowed to upload there. */\n folderId?: string | null;\n /** Description stored on the File row. */\n description?: string | null;\n /** Visibility. files-svc default is `PRIVATE`. */\n visibility?: FileVisibility;\n /**\n * Declare the SHA-256 of the bytes at initiate and complete, so files-svc can\n * verify what it stored. Default `true`.\n */\n declareSha256?: boolean;\n}\n\n/** What {@link FilesClient.uploadFile} returns: persist `fileId`, nothing else is needed. */\nexport interface StoredFile {\n fileId: string;\n name: string;\n mimeType: string;\n /** Size in bytes. */\n size: number;\n workspaceId: string;\n /** Lowercase hex SHA-256 when it was declared, else `null`. */\n sha256Hash: string | null;\n}\n\n/**\n * File metadata, read through the files graph's ROOT `getFile` field.\n *\n * Only scalars are selected: files-svc's `File` entity has no\n * `__resolveReference`, so federated sub-selections (folder, versions, …) are\n * deliberately not part of this shape.\n */\nexport interface FileMetadata {\n id: string;\n name: string;\n mimeType: string;\n extension: string;\n /** Size in bytes. */\n size: number;\n status: FileStatus;\n visibility: FileVisibility;\n workspaceId: string;\n folderId: string | null;\n uploadedById: string;\n description: string | null;\n sha256Hash: string | null;\n createdAt: Date | null;\n updatedAt: Date | null;\n /** Whether the actor may read the file (files-svc permission check). */\n canRead: boolean | null;\n /** Whether the actor may delete the file. */\n canDelete: boolean | null;\n}\n\n/** Options for {@link FilesClient.requireFile}. */\nexport interface RequireFileOptions {\n /** Reject files that are not `ACTIVE`. Default `true`. */\n requireActive?: boolean;\n /** Reject files the actor cannot read (`canRead !== true`). Default `true`. */\n requireReadable?: boolean;\n}\n\n/** Options for {@link FilesClient.getDownloadUrl}. */\nexport interface DownloadUrlOptions {\n /** URL lifetime in seconds, clamped to [60, 604800] (the S3 presign maximum). */\n expiresInSeconds?: number;\n}\n\n/** Options for {@link FilesClient.downloadFile}. */\nexport interface DownloadFileOptions {\n /** Refuse files larger than this many bytes. Default: the client's `maxDownloadBytes`. */\n maxBytes?: number;\n}\n\n/** What {@link FilesClient.downloadFile} returns. */\nexport interface DownloadedFile {\n bytes: Uint8Array;\n /** MIME type recorded by files-svc. */\n mimeType: string;\n name: string;\n size: number;\n}\n\n/**\n * Input for {@link FilesClient.createUploadSession}: a delegated upload, where\n * the service opens the files-svc session on the actor's behalf and hands the\n * presigned URL(s) to whoever holds the bytes (an agent, a CLI, a browser).\n */\nexport interface CreateUploadSessionInput {\n /** File name shown in the workspace library. */\n fileName: string;\n /** Exact size of the bytes the uploader will PUT. `completeUploadSession` must repeat it. */\n fileSize: number;\n /** MIME type. A DIRECT URL is signed for it, so the uploader must send it as `Content-Type`. */\n mimeType: string;\n /** Extension without the dot. Default: taken from `fileName`, else `bin`. */\n extension?: string;\n /** Lowercase hex SHA-256 the uploader declared; files-svc checks it again at completion. */\n sha256Hash?: string | null;\n /** Folder to file it in. The actor must be allowed to upload there. */\n folderId?: string | null;\n /** Visibility. files-svc default is `PRIVATE`. */\n visibility?: FileVisibility;\n}\n\n/** One presigned part of a MULTIPART {@link UploadSessionTicket}. */\nexport interface UploadSessionPart {\n /** 1-indexed part number. */\n partNumber: number;\n /** Presigned PUT URL for exactly the bytes `[offset, offset + length)`. */\n url: string;\n /** First byte of the part within the file. */\n offset: number;\n /** Number of bytes in the part. */\n length: number;\n}\n\n/**\n * An open files-svc upload session the caller hands to the uploader. Mint it per\n * upload; never persist the URLs (only `sessionId`).\n */\nexport interface UploadSessionTicket {\n sessionId: string;\n /** `DIRECT` → one PUT to `uploadUrl`; `MULTIPART` → one PUT per entry of `parts`. */\n uploadType: 'DIRECT' | 'MULTIPART';\n /** DIRECT only: the presigned PUT URL. `null` for MULTIPART. */\n uploadUrl: string | null;\n /** Headers the uploader must send on the DIRECT PUT (the signed `Content-Type`). Empty for MULTIPART parts. */\n requiredHeaders: Record<string, string>;\n /** MULTIPART only: every part, in order. Empty for DIRECT. */\n parts: UploadSessionPart[];\n partSize: number;\n totalParts: number;\n /** Size in bytes the session was opened for. */\n fileSize: number;\n /** The SHA-256 declared at initiate, or `null`. */\n sha256Hash: string | null;\n /** When files-svc expires the session, if it said. */\n expiresAt: Date | null;\n}\n\n/** An uploaded MULTIPART part: the ETag object storage returned for its PUT. */\nexport interface UploadedPart {\n partNumber: number;\n etag: string;\n}\n\n/** Input for {@link FilesClient.completeUploadSession}. */\nexport interface CompleteUploadSessionInput {\n /** Must equal the `fileSize` the session was opened with. */\n fileSize: number;\n /** Must equal the SHA-256 declared at initiate when one was declared. */\n sha256Hash?: string | null;\n /** Description stored on the File row. */\n description?: string | null;\n /** Folder to file it in (defaults to the one given at initiate). */\n folderId?: string | null;\n /** MULTIPART only: every part's ETag, registered before completion. */\n parts?: readonly UploadedPart[];\n}\n\n/** Options for {@link FilesClient.deleteFile}. */\nexport interface DeleteFileOptions {\n /** Hard delete (`permanentlyDeleteFile`) instead of moving to trash. Default `false`. */\n permanent?: boolean;\n}\n\n/** The slice of be-sdk's `GatewayClient` the files client needs (injectable for tests). */\nexport interface FilesTransport {\n internalQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>>;\n}\n\n/** `fetch`-compatible function used for the presigned PUT/GET legs (injectable for tests). */\nexport type FilesFetch = (url: string, init?: RequestInit) => Promise<Response>;\n\n/** `File` as selected over the wire (BigInt and DateTime arrive as strings). */\nexport interface RawFileMetadata {\n id: string;\n name: string;\n mimeType: string;\n extension: string;\n size: string | number;\n status: FileStatus;\n visibility: FileVisibility;\n workspaceId: string;\n folderId?: string | null;\n uploadedById: string;\n description?: string | null;\n sha256Hash?: string | null;\n createdAt?: string | null;\n updatedAt?: string | null;\n canRead?: boolean | null;\n canDelete?: boolean | null;\n}\n","/**\n * Files client — error type.\n *\n * Services map {@link FilesClientError} onto their own i18n GraphQL errors; the\n * `code` is stable so that mapping never parses messages. Upstream detail\n * (files-svc messages, storage status codes) lives in `details` for logging and\n * must not be returned to clients verbatim.\n *\n * The upstream GraphQL errors are kept as {@link FilesUpstreamError}s: a\n * whitelist of fields (code, i18n key, failing field, trace id and a sanitised,\n * capped message). Request variables, headers and URLs are never copied, so\n * {@link FilesClientError.summary} is safe to log and to show in a run error.\n */\nimport { GatewayError, type GraphQLError } from '../gateway/types.js';\n\nexport type FilesClientErrorCode =\n /** A required argument is empty or out of range. */\n | 'INVALID_INPUT'\n /** No actor/workspace on the request — files are always workspace-scoped. */\n | 'MISSING_CONTEXT'\n /** The file does not exist, is in another workspace, or the actor may not read it. */\n | 'NOT_FOUND'\n /** The workspace storage/file quota, or the per-upload size limit, rejected the upload. */\n | 'QUOTA_EXCEEDED'\n /** The bytes exceed the client's configured upload/download cap. */\n | 'TOO_LARGE'\n /** The presigned PUT/GET against object storage failed. */\n | 'STORAGE_ERROR'\n /** files-svc or the gateway failed, or answered without the expected payload. */\n | 'UPSTREAM_ERROR'\n /** The client was configured inconsistently (thrown at boot). */\n | 'CONFIGURATION_ERROR';\n\n/** GraphQL `extensions.code` each {@link FilesClientErrorCode} should surface as. */\nexport const FILES_CLIENT_GRAPHQL_CODES: Record<FilesClientErrorCode, string> = {\n INVALID_INPUT: 'BAD_USER_INPUT',\n MISSING_CONTEXT: 'UNAUTHENTICATED',\n // Never FORBIDDEN: a file the actor cannot see must be indistinguishable from one that does not exist.\n NOT_FOUND: 'NOT_FOUND',\n QUOTA_EXCEEDED: 'QUOTA_EXCEEDED',\n TOO_LARGE: 'BAD_USER_INPUT',\n STORAGE_ERROR: 'INTERNAL_SERVER_ERROR',\n UPSTREAM_ERROR: 'INTERNAL_SERVER_ERROR',\n CONFIGURATION_ERROR: 'INTERNAL_SERVER_ERROR',\n};\n\n/** Longest upstream message kept, in characters. */\nexport const MAX_UPSTREAM_MESSAGE_LENGTH = 200;\n/** Longest {@link FilesClientError.summary}, in characters. */\nexport const MAX_FILES_ERROR_SUMMARY_LENGTH = 400;\n\n/**\n * One files-svc (or gateway) GraphQL error, reduced to fields that are safe to\n * log and to show to the person who ran the operation.\n */\nexport interface FilesUpstreamError {\n /** `extensions.code`, e.g. `NOT_FOUND`; `null` when the error had none. */\n code: string | null;\n /** The sanitised, capped message. */\n message: string;\n /** `extensions.i18nKey`, e.g. `files.errors.notFound`, when it is a well-formed key. */\n i18nKey?: string;\n /** The failing field (`path` joined with `.`), e.g. `getFile`. */\n field?: string;\n /** The gateway's trace id (`extensions.traceId`), for finding the request in the logs. */\n traceId?: string;\n}\n\n/** Structured upstream context of a {@link FilesClientError}. */\nexport interface FilesClientErrorUpstream {\n /** The FilesClient operation that failed, e.g. `downloadFile`. */\n operation?: string;\n /** The GraphQL errors files-svc or the gateway answered with. */\n errors?: readonly FilesUpstreamError[];\n /** The HTTP status of the failed response, when known. */\n status?: number;\n}\n\nexport class FilesClientError extends Error {\n readonly code: FilesClientErrorCode;\n readonly details: Record<string, unknown>;\n /** The FilesClient operation that failed, when the error came from a files-svc call. */\n readonly operation: string | undefined;\n /** The sanitised upstream GraphQL errors (empty when there were none). */\n readonly upstreamErrors: readonly FilesUpstreamError[];\n /** The HTTP status of the failed response, when known. */\n readonly status: number | undefined;\n\n constructor(\n code: FilesClientErrorCode,\n message: string,\n details: Record<string, unknown> = {},\n upstream: FilesClientErrorUpstream = {}\n ) {\n super(message);\n this.name = 'FilesClientError';\n this.code = code;\n this.details = details;\n this.operation = upstream.operation;\n this.upstreamErrors = upstream.errors ?? [];\n this.status = upstream.status;\n }\n\n /** The GraphQL `extensions.code` this error maps to. */\n get graphqlCode(): string {\n return FILES_CLIENT_GRAPHQL_CODES[this.code];\n }\n\n /**\n * One line for logs and run errors: the class, the upstream reason and the\n * failing call, e.g.\n * `UPSTREAM_ERROR (INTERNAL_SERVER_ERROR, files.errors.fileExtensionCannotBeNull): wspace-files-svc getFile failed: File extension cannot be null`.\n * Built only from whitelisted, sanitised fields; never contains request\n * variables, headers or URLs.\n */\n get summary(): string {\n return summarizeFilesClientError(this);\n }\n}\n\nexport function isFilesClientError(error: unknown): error is FilesClientError {\n return error instanceof FilesClientError;\n}\n\nconst NOT_FOUND_UPSTREAM_CODES = new Set(['NOT_FOUND', 'FORBIDDEN', 'FILE_NOT_FOUND', 'ACCESS_DENIED', 'UNAUTHORIZED']);\nconst QUOTA_UPSTREAM_CODES = new Set(['QUOTA_EXCEEDED', 'QUOTA_EXHAUSTED', 'USAGE_LIMIT_EXCEEDED']);\nconst INVALID_UPSTREAM_CODES = new Set(['BAD_USER_INPUT', 'EXPIRED', 'VALIDATION_ERROR', 'INVALID_INPUT']);\n\nfunction upstreamCode(error: GraphQLError): string | null {\n const code = error.extensions?.['code'];\n return typeof code === 'string' ? code : null;\n}\n\n/** The class a single upstream code maps to. */\nfunction classOfUpstreamCode(code: string): FilesClientErrorCode {\n if (QUOTA_UPSTREAM_CODES.has(code)) return 'QUOTA_EXCEEDED';\n // A file the actor may not read answers NOT_FOUND, never a permission error.\n // An UNAUTHENTICATED answer stays UPSTREAM_ERROR: on this service-to-service\n // hop it means the caller's gateway credentials are wrong, not the user's\n // session, and surfacing it as UNAUTHENTICATED would sign the user out.\n if (NOT_FOUND_UPSTREAM_CODES.has(code)) return 'NOT_FOUND';\n if (INVALID_UPSTREAM_CODES.has(code)) return 'INVALID_INPUT';\n return 'UPSTREAM_ERROR';\n}\n\n/** Precedence when several upstream errors disagree: the first class listed wins. */\nconst CLASS_PRECEDENCE: readonly FilesClientErrorCode[] = ['QUOTA_EXCEEDED', 'NOT_FOUND', 'INVALID_INPUT'];\n\n/** Classify files-svc GraphQL errors into a {@link FilesClientErrorCode}. */\nexport function classifyFilesErrors(errors: readonly GraphQLError[]): FilesClientErrorCode {\n const classes = new Set(\n errors\n .map(upstreamCode)\n .filter((code): code is string => code !== null)\n .map(classOfUpstreamCode)\n );\n return CLASS_PRECEDENCE.find((candidate) => classes.has(candidate)) ?? 'UPSTREAM_ERROR';\n}\n\n// ── Sanitising ─────────────────────────────────────────────────────────\n\nconst UPSTREAM_CODE_PATTERN = /^[A-Z][A-Z0-9_]{0,63}$/;\nconst I18N_KEY_SEGMENT_PATTERN = /^[\\w-]+$/;\nconst MAX_I18N_KEY_LENGTH = 128;\nconst MAX_I18N_KEY_SEGMENTS = 8;\nconst FIELD_SEGMENT_PATTERN = /^[A-Za-z_]\\w{0,63}$/;\nconst MAX_FIELD_SEGMENTS = 6;\nconst TRACE_ID_PATTERN = /^[0-9a-f]{16,32}$/i;\n\nconst URL_PATTERN = /\\b[a-z][a-z0-9+.-]*:\\/\\/[^\\s\"'<>`]+/gi;\nconst JWT_PATTERN = /\\beyJ[\\w-]{4,}\\.[\\w-]{4,}\\.[\\w-]*/g;\nconst AUTH_SCHEME_PATTERN = /\\b(bearer|basic)\\s+[\\w.~+/=-]+/gi;\nconst ASSIGNMENT_PATTERN = /(?<![\\w-])([\\w-]+)([\"']?\\s?[:=]\\s?[\"']?)([^\\s\"',;&}]+)/g;\n/** Text longer than this is cut before the patterns run, so a huge upstream message costs nothing. */\nconst MAX_SCANNED_TEXT_LENGTH = 4_096;\nconst SECRET_NAME_PATTERN = /token|secret|passw|signature|credential|api[_-]?key|authorization|cookie/i;\n// graphql-js echoes a rejected variable's value: `Variable \"$id\" got invalid value \"…\"; …`.\nconst VARIABLE_VALUE_PATTERN = /(Variable \"\\$\\w+\" got invalid value)[\\s\\S]*/g;\n\n/** Replace C0/C1 control characters and DEL with spaces (log-line injection). */\nfunction withoutControlCharacters(value: string): string {\n let result = '';\n for (const character of value) {\n const code = character.charCodeAt(0);\n result += code < 0x20 || (code >= 0x7f && code <= 0x9f) ? ' ' : character;\n }\n return result;\n}\n\n/**\n * Reduce free text from an upstream error to something safe to log: control\n * characters, URLs (presigned ones carry signatures), bearer/JWT tokens,\n * `secret=…`-style assignments and echoed variable values are removed, and the\n * result is capped at `maxLength` characters.\n */\nexport function sanitizeUpstreamText(value: unknown, maxLength: number = MAX_UPSTREAM_MESSAGE_LENGTH): string {\n if (typeof value !== 'string') return '';\n const cleaned = withoutControlCharacters(value.slice(0, MAX_SCANNED_TEXT_LENGTH))\n .replace(VARIABLE_VALUE_PATTERN, '$1 (value omitted)')\n .replace(URL_PATTERN, '[url]')\n .replace(JWT_PATTERN, '[redacted]')\n .replace(AUTH_SCHEME_PATTERN, '$1 [redacted]')\n .replace(ASSIGNMENT_PATTERN, (assignment: string, name: string, separator: string) =>\n SECRET_NAME_PATTERN.test(name) ? `${name}${separator}[redacted]` : assignment\n )\n .replace(/\\s+/g, ' ')\n .trim();\n return cleaned.length > maxLength ? `${cleaned.slice(0, Math.max(0, maxLength - 1))}…` : cleaned;\n}\n\nfunction sanitizeField(path: GraphQLError['path']): string | undefined {\n if (!Array.isArray(path) || path.length === 0) return undefined;\n const segments: string[] = [];\n for (const segment of path.slice(0, MAX_FIELD_SEGMENTS)) {\n if (typeof segment === 'number' && Number.isSafeInteger(segment) && segment >= 0) {\n segments.push(String(segment));\n } else if (typeof segment === 'string' && FIELD_SEGMENT_PATTERN.test(segment)) {\n segments.push(segment);\n } else {\n break;\n }\n }\n return segments.length > 0 ? segments.join('.') : undefined;\n}\n\nfunction isI18nKey(value: unknown): value is string {\n if (typeof value !== 'string' || value.length > MAX_I18N_KEY_LENGTH) return false;\n const segments = value.split('.');\n return (\n segments.length >= 2 &&\n segments.length <= MAX_I18N_KEY_SEGMENTS &&\n /^[A-Za-z]/.test(value) &&\n segments.every((segment) => I18N_KEY_SEGMENT_PATTERN.test(segment))\n );\n}\n\nfunction matching(value: unknown, pattern: RegExp, maxLength: number): string | undefined {\n return typeof value === 'string' && value.length <= maxLength && pattern.test(value) ? value : undefined;\n}\n\n/**\n * Keep only the whitelisted fields of an upstream GraphQL error. Everything\n * else on it (other extensions, `locations`, the original error) is dropped.\n */\nexport function sanitizeUpstreamError(error: GraphQLError): FilesUpstreamError {\n const extensions = error.extensions ?? {};\n const result: FilesUpstreamError = {\n code: matching(extensions['code'], UPSTREAM_CODE_PATTERN, 64) ?? null,\n message: sanitizeUpstreamText(error.message),\n };\n const i18nKey = extensions['i18nKey'];\n if (isI18nKey(i18nKey)) result.i18nKey = i18nKey;\n const field = sanitizeField(error.path);\n if (field) result.field = field;\n const traceId = matching(extensions['traceId'], TRACE_ID_PATTERN, 32);\n if (traceId) result.traceId = traceId;\n return result;\n}\n\nfunction validStatus(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isInteger(value) && value >= 100 && value <= 599 ? value : undefined;\n}\n\n// ── Summary ────────────────────────────────────────────────────────────\n\nfunction primaryUpstreamError(\n errors: readonly FilesUpstreamError[],\n code: FilesClientErrorCode\n): FilesUpstreamError | undefined {\n // Prefer the error that decided the class, then any error that says something specific.\n return (\n (code === 'UPSTREAM_ERROR'\n ? undefined\n : errors.find((error) => error.code !== null && classOfUpstreamCode(error.code) === code)) ??\n errors.find((error) => error.i18nKey !== undefined) ??\n errors.find((error) => error.code !== null) ??\n errors[0]\n );\n}\n\nfunction capSummary(value: string): string {\n return value.length > MAX_FILES_ERROR_SUMMARY_LENGTH\n ? `${value.slice(0, MAX_FILES_ERROR_SUMMARY_LENGTH - 1)}…`\n : value;\n}\n\n/** See {@link FilesClientError.summary}. */\nexport function summarizeFilesClientError(error: FilesClientError): string {\n const primary = primaryUpstreamError(error.upstreamErrors, error.code);\n const tags: string[] = [];\n if (primary?.code && primary.code !== error.code) tags.push(primary.code);\n if (primary?.i18nKey) tags.push(primary.i18nKey);\n if (error.status !== undefined) tags.push(`HTTP ${error.status}`);\n if (primary?.traceId) tags.push(`trace ${primary.traceId}`);\n const tag = tags.length > 0 ? ` (${tags.join(', ')})` : '';\n\n const target = primary?.field ?? error.operation;\n if (!primary || !target) {\n return capSummary(`${error.code}${tag}: ${sanitizeUpstreamText(error.message, MAX_FILES_ERROR_SUMMARY_LENGTH)}`);\n }\n const reason = primary.message ? `: ${primary.message}` : '';\n const more = error.upstreamErrors.length > 1 ? ` (+${error.upstreamErrors.length - 1} more)` : '';\n return capSummary(`${error.code}${tag}: wspace-files-svc ${target} failed${reason}${more}`);\n}\n\n// ── Normalising ────────────────────────────────────────────────────────\n\n/** A {@link FilesClientError} for a files-svc response that carried GraphQL errors. */\nexport function filesGraphQLError(errors: readonly GraphQLError[], operation: string): FilesClientError {\n const upstream = errors.map(sanitizeUpstreamError);\n return new FilesClientError(\n classifyFilesErrors(errors),\n `wspace-files-svc ${operation} failed`,\n { operation, errors: upstream },\n { operation, errors: upstream }\n );\n}\n\n/**\n * Normalise anything a files-svc call threw (a `GatewayError` carrying GraphQL\n * errors, a timeout, a network error, …) into a {@link FilesClientError}.\n */\nexport function toFilesClientError(error: unknown, operation: string): FilesClientError {\n if (error instanceof FilesClientError) return error;\n if (error instanceof GatewayError) {\n const graphqlErrors = error.graphqlErrors ?? [];\n const code = graphqlErrors.length > 0 ? classifyFilesErrors(graphqlErrors) : 'UPSTREAM_ERROR';\n const upstream = graphqlErrors.map(sanitizeUpstreamError);\n const status = validStatus(error.statusCode);\n return new FilesClientError(\n code,\n `wspace-files-svc ${operation} failed: ${sanitizeUpstreamText(error.message)}`,\n {\n operation,\n gatewayErrorType: error.type,\n statusCode: error.statusCode,\n errors: upstream,\n },\n { operation, errors: upstream, ...(status !== undefined ? { status } : {}) }\n );\n }\n const message = sanitizeUpstreamText(error instanceof Error ? error.message : String(error));\n return new FilesClientError(\n 'UPSTREAM_ERROR',\n `wspace-files-svc ${operation} failed: ${message}`,\n { operation },\n { operation }\n );\n}\n","/**\n * FilesClient — store and read workspace blobs through wspace-files-svc.\n *\n * Module ownership makes wspace-files-svc the canonical owner of blobs, yet\n * services kept re-implementing storage: VibeControls hand-rolled SigV4 with\n * static S3 keys for security evidence, FluidGrids passed attachments between\n * nodes as base64, HealthyBowl carried its own three-step uploader. This class\n * is the shared client: a service hands it bytes and gets back an opaque\n * `fileId`, and resolves that id back to metadata, a short-lived download URL or\n * the bytes themselves.\n *\n * Every call is same-layer M2M through the internal workspace gateway\n * (`GatewayClient.internalQuery`, which signs the service JWT; the gateway adds\n * its own trusted token toward files-svc). The CALLER's actor and workspace are\n * forwarded explicitly, so the File row is owned by the user who asked for it,\n * shows up in their library, and files-svc applies quota, folder access and read\n * permission to that user. The internal gateway enforces neither `@rbac` nor\n * `@usage` for the product's own resolver, so the service must already have\n * authorized the action (its own `@rbac` plus a workspace-scoped row lookup).\n *\n * Upload is the files-svc protocol: `initiateUpload` → presigned PUT (DIRECT) or\n * per-part PUTs + `registerUploadedPart` (MULTIPART, which files-svc picks for\n * files over 5 MiB) → `completeUpload` with the same `fileSize` (required: it\n * must match the size declared at initiate). A failed upload aborts its session.\n *\n * @example\n * ```ts\n * import { FilesClient, toFileReference } from '@burdenoff/be-sdk/files';\n *\n * const files = new FilesClient({ serviceName: 'wspace-vibecontrols-svc' });\n *\n * const stored = await files.uploadFile(\n * { fileName: 'access-review.pdf', data: pdfBytes, mimeType: 'application/pdf', description: 'SOC 2 evidence' },\n * { actorId: ctx.actorId, workspaceId: ctx.workspaceId }\n * );\n * await db.securityEvidence.update({ where: { id }, data: { fileId: stored.fileId } });\n *\n * const url = await files.getDownloadUrl(evidence.fileId, actor, { expiresInSeconds: 300 });\n * ```\n */\nimport { createHash } from 'node:crypto';\n\nimport type { GraphQLResponse } from '../gateway/types.js';\n\nimport { FilesClientError, filesGraphQLError, toFilesClientError } from './errors.js';\nimport type {\n CompleteUploadSessionInput,\n CreateUploadSessionInput,\n DeleteFileOptions,\n DownloadFileOptions,\n DownloadUrlOptions,\n DownloadedFile,\n FileActor,\n FileBytes,\n FileMetadata,\n FileUploadType,\n FilesFetch,\n FilesTransport,\n RawFileMetadata,\n RequireFileOptions,\n StoredFile,\n UploadFileInput,\n UploadSessionPart,\n UploadSessionTicket,\n UploadedPart,\n} from './types.js';\nimport { FILE_ACTOR_TYPES, FILE_VISIBILITIES } from './types.js';\n\nconst MIB = 1024 * 1024;\n\n/** S3 refuses presigned URLs that live longer than 7 days; files-svc 500s above it. */\nexport const MAX_DOWNLOAD_URL_TTL_SECONDS = 604_800;\n/** Shortest URL lifetime the client will request. */\nexport const MIN_DOWNLOAD_URL_TTL_SECONDS = 60;\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 15_000;\nconst DEFAULT_TRANSFER_TIMEOUT_MS = 120_000;\nconst DEFAULT_MAX_UPLOAD_BYTES = 100 * MIB;\nconst DEFAULT_MAX_DOWNLOAD_BYTES = 25 * MIB;\nconst DEFAULT_DOWNLOAD_URL_TTL_SECONDS = 3_600;\n/** TTL of the URL `downloadFile` mints for its own immediate GET. */\nconst INTERNAL_DOWNLOAD_URL_TTL_SECONDS = 300;\nconst PART_URL_BATCH_SIZE = 20;\nconst SHA256_HEX = /^[0-9a-f]{64}$/;\n\nconst FILE_FIELDS =\n 'id name mimeType extension size status visibility workspaceId folderId uploadedById description sha256Hash createdAt updatedAt canRead canDelete';\n\nconst INITIATE_UPLOAD = `mutation FilesClientInitiateUpload($input: InitiateUploadInput!) {\n initiateUpload(input: $input) {\n uploadUrl\n session { id uploadType partSize totalParts fileSize expiresAt }\n }\n}`;\n\nconst PART_URLS = `query FilesClientPartUploadUrls($sessionId: ID!, $partNumbers: [Int!]!) {\n getBatchPartUploadUrls(sessionId: $sessionId, partNumbers: $partNumbers) { partNumber url }\n}`;\n\nconst REGISTER_PART = `mutation FilesClientRegisterUploadedPart($input: UploadPartInput!) {\n registerUploadedPart(input: $input) { session { id uploadedParts } }\n}`;\n\nconst COMPLETE_UPLOAD = `mutation FilesClientCompleteUpload($input: CompleteUploadInput!) {\n completeUpload(input: $input) { fileId file { id name mimeType size workspaceId sha256Hash } }\n}`;\n\nconst ABORT_UPLOAD = `mutation FilesClientAbortUpload($sessionId: ID!) { abortUpload(sessionId: $sessionId) }`;\n\nconst GET_FILE = `query FilesClientGetFile($id: ID!) { getFile(id: $id) { ${FILE_FIELDS} } }`;\n\nconst GET_DOWNLOAD_URL = `query FilesClientGetFileDownloadUrl($id: ID!, $expiresIn: Int) {\n getFileDownloadUrl(id: $id, expiresIn: $expiresIn)\n}`;\n\nconst RESOLVE_FOR_DOWNLOAD = `query FilesClientResolveForDownload($id: ID!, $expiresIn: Int) {\n getFile(id: $id) { ${FILE_FIELDS} }\n getFileDownloadUrl(id: $id, expiresIn: $expiresIn)\n}`;\n\nconst DELETE_FILE = `mutation FilesClientDeleteFile($id: ID!) { deleteFile(id: $id) }`;\n\nconst PERMANENTLY_DELETE_FILE = `mutation FilesClientPermanentlyDeleteFile($id: ID!) { permanentlyDeleteFile(id: $id) }`;\n\nexport interface FilesClientOptions {\n /**\n * Gateway client, or a factory for one. Defaults to a lazily constructed be-sdk\n * `GatewayClient` (`layer: 'wspace'`, `serviceName` below, or the\n * `SERVICE_LAYER`/`SERVICE_NAME` env when `serviceName` is omitted).\n */\n client?: FilesTransport | (() => FilesTransport | Promise<FilesTransport>);\n /** Service name for the default GatewayClient, e.g. `wspace-vibecontrols-svc`. */\n serviceName?: string;\n /** `fetch` used for the presigned PUT/GET legs. Default: the global `fetch`. */\n fetch?: FilesFetch;\n /** Per-request timeout for files-svc GraphQL calls. Default 15s. */\n requestTimeoutMs?: number;\n /** Per-request timeout for each presigned PUT/GET. Default 120s. */\n transferTimeoutMs?: number;\n /** Largest upload accepted (the bytes are held in memory). Default 100 MiB. */\n maxUploadBytes?: number;\n /** Largest download accepted by `downloadFile`. Default 25 MiB. */\n maxDownloadBytes?: number;\n /** Default `getDownloadUrl` lifetime in seconds. Default 3600. */\n defaultDownloadUrlTtlSeconds?: number;\n}\n\ninterface InitiatedSession {\n id: string;\n uploadType: FileUploadType;\n partSize: number;\n totalParts: number;\n}\n\nfunction requireNonEmpty(value: string | null | undefined, field: string): string {\n const trimmed = typeof value === 'string' ? value.trim() : '';\n if (!trimmed) {\n throw new FilesClientError('INVALID_INPUT', `${field} is required`, { field });\n }\n return trimmed;\n}\n\nfunction requirePositiveInteger(value: number, field: string): number {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new FilesClientError('CONFIGURATION_ERROR', `${field} must be a positive integer`, { field, value });\n }\n return value;\n}\n\nfunction toNumber(value: string | number, field: string): number {\n const parsed = typeof value === 'number' ? value : Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 0) {\n throw new FilesClientError('UPSTREAM_ERROR', `wspace-files-svc returned an invalid ${field}`, { field, value });\n }\n return parsed;\n}\n\nfunction toDate(value: string | null | undefined): Date | null {\n if (!value) return null;\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\n/** A view over `data` backed by a plain `ArrayBuffer` (what `fetch` bodies accept). */\nfunction toBytes(data: FileBytes): Uint8Array<ArrayBuffer> {\n if (data instanceof ArrayBuffer) return new Uint8Array(data);\n const { buffer } = data;\n if (buffer instanceof ArrayBuffer) return new Uint8Array(buffer, data.byteOffset, data.byteLength);\n // SharedArrayBuffer-backed view: copy, since a shared buffer can change under the upload.\n return new Uint8Array(data);\n}\n\n/** Extension for `fileName` (`report.PDF` → `pdf`), or `bin` when it has none. */\nexport function fileExtensionOf(fileName: string): string {\n const base = fileName.trim().split(/[\\\\/]/).pop() ?? '';\n const dot = base.lastIndexOf('.');\n if (dot <= 0 || dot === base.length - 1) return 'bin';\n const extension = base\n .slice(dot + 1)\n .toLowerCase()\n .replace(/[^a-z0-9]/g, '');\n return extension || 'bin';\n}\n\n/** Clamp a requested URL lifetime to what files-svc / S3 accept. */\nexport function clampDownloadUrlTtl(seconds: number | null | undefined, fallback: number): number {\n const value = seconds === null || seconds === undefined || !Number.isFinite(seconds) ? fallback : seconds;\n return Math.min(Math.max(Math.trunc(value), MIN_DOWNLOAD_URL_TTL_SECONDS), MAX_DOWNLOAD_URL_TTL_SECONDS);\n}\n\nfunction isHttpUrl(value: unknown): value is string {\n if (typeof value !== 'string' || value.length === 0) return false;\n try {\n const { protocol } = new URL(value);\n return protocol === 'https:' || protocol === 'http:';\n } catch {\n return false;\n }\n}\n\n/** Lowercase a declared SHA-256 and reject anything that is not 64 hex characters. */\nfunction normalizeSha256(value: string | null | undefined): string | null {\n if (value === null || value === undefined || value.trim() === '') return null;\n const normalized = value.trim().toLowerCase();\n if (!SHA256_HEX.test(normalized)) {\n throw new FilesClientError('INVALID_INPUT', 'sha256Hash must be 64 hex characters', { field: 'sha256Hash' });\n }\n return normalized;\n}\n\n/** Validate MULTIPART part ETags: positive, unique part numbers with a non-empty ETag, sorted. */\nfunction normalizeUploadedParts(parts: readonly UploadedPart[]): UploadedPart[] {\n const seen = new Set<number>();\n const normalized = parts.map((part) => {\n const etag = typeof part.etag === 'string' ? part.etag.trim() : '';\n if (!Number.isSafeInteger(part.partNumber) || part.partNumber <= 0 || seen.has(part.partNumber) || !etag) {\n throw new FilesClientError('INVALID_INPUT', 'parts must have unique positive part numbers and an ETag', {\n field: 'parts',\n partNumber: part.partNumber,\n });\n }\n seen.add(part.partNumber);\n return { partNumber: part.partNumber, etag };\n });\n return normalized.sort((a, b) => a.partNumber - b.partNumber);\n}\n\n/** Map a files-svc `File` selection onto {@link FileMetadata}. */\nexport function mapFileMetadata(raw: RawFileMetadata): FileMetadata {\n return {\n id: raw.id,\n name: raw.name,\n mimeType: raw.mimeType,\n extension: raw.extension,\n size: toNumber(raw.size, 'size'),\n status: raw.status,\n visibility: raw.visibility,\n workspaceId: raw.workspaceId,\n folderId: raw.folderId ?? null,\n uploadedById: raw.uploadedById,\n description: raw.description ?? null,\n sha256Hash: raw.sha256Hash ?? null,\n createdAt: toDate(raw.createdAt),\n updatedAt: toDate(raw.updatedAt),\n canRead: raw.canRead ?? null,\n canDelete: raw.canDelete ?? null,\n };\n}\n\nexport class FilesClient {\n private readonly clientOption: FilesClientOptions['client'];\n private readonly serviceName: string | undefined;\n private readonly fetchImpl: FilesFetch;\n private readonly requestTimeoutMs: number;\n private readonly transferTimeoutMs: number;\n private readonly maxUploadBytes: number;\n private readonly maxDownloadBytes: number;\n private readonly defaultDownloadUrlTtlSeconds: number;\n private clientPromise: Promise<FilesTransport> | null = null;\n\n constructor(options: FilesClientOptions = {}) {\n this.clientOption = options.client;\n this.serviceName = options.serviceName;\n this.fetchImpl = options.fetch ?? ((url, init) => fetch(url, init));\n this.requestTimeoutMs = requirePositiveInteger(\n options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,\n 'requestTimeoutMs'\n );\n this.transferTimeoutMs = requirePositiveInteger(\n options.transferTimeoutMs ?? DEFAULT_TRANSFER_TIMEOUT_MS,\n 'transferTimeoutMs'\n );\n this.maxUploadBytes = requirePositiveInteger(options.maxUploadBytes ?? DEFAULT_MAX_UPLOAD_BYTES, 'maxUploadBytes');\n this.maxDownloadBytes = requirePositiveInteger(\n options.maxDownloadBytes ?? DEFAULT_MAX_DOWNLOAD_BYTES,\n 'maxDownloadBytes'\n );\n const ttl = options.defaultDownloadUrlTtlSeconds ?? DEFAULT_DOWNLOAD_URL_TTL_SECONDS;\n if (!Number.isSafeInteger(ttl) || ttl < MIN_DOWNLOAD_URL_TTL_SECONDS || ttl > MAX_DOWNLOAD_URL_TTL_SECONDS) {\n throw new FilesClientError(\n 'CONFIGURATION_ERROR',\n `defaultDownloadUrlTtlSeconds must be between ${MIN_DOWNLOAD_URL_TTL_SECONDS} and ${MAX_DOWNLOAD_URL_TTL_SECONDS}`,\n { value: ttl }\n );\n }\n this.defaultDownloadUrlTtlSeconds = ttl;\n }\n\n // ── Upload ────────────────────────────────────────────────────────────\n\n /**\n * Store bytes in the actor's workspace file library and return the File's id.\n * Throws {@link FilesClientError}; on any failure after the session was opened\n * the session is aborted so no half-uploaded object is left behind.\n */\n async uploadFile(input: UploadFileInput, actor: FileActor): Promise<StoredFile> {\n const context = this.requireActor(actor);\n const fileName = requireNonEmpty(input.fileName, 'fileName');\n const mimeType = requireNonEmpty(input.mimeType, 'mimeType');\n const bytes = toBytes(input.data);\n if (bytes.byteLength === 0) {\n throw new FilesClientError('INVALID_INPUT', 'data must not be empty', { field: 'data' });\n }\n if (bytes.byteLength > this.maxUploadBytes) {\n throw new FilesClientError('TOO_LARGE', `File is larger than ${this.maxUploadBytes} bytes`, {\n size: bytes.byteLength,\n maxBytes: this.maxUploadBytes,\n });\n }\n if (input.visibility !== undefined && !FILE_VISIBILITIES.includes(input.visibility)) {\n throw new FilesClientError('INVALID_INPUT', `Unknown file visibility \"${String(input.visibility)}\"`, {\n field: 'visibility',\n });\n }\n const extension = input.extension?.trim()\n ? input.extension.trim().replace(/^\\./, '').toLowerCase()\n : fileExtensionOf(fileName);\n // `BigInt` travels as a string, and completeUpload must repeat exactly the value given to initiate.\n const fileSize = String(bytes.byteLength);\n const sha256Hash = input.declareSha256 === false ? null : createHash('sha256').update(bytes).digest('hex');\n const folderId = input.folderId?.trim() || undefined;\n\n const initiated = await this.request<{\n initiateUpload: {\n uploadUrl?: string | null;\n session?: {\n id: string;\n uploadType: FileUploadType;\n partSize: number | string;\n totalParts: number | string;\n } | null;\n } | null;\n }>(\n 'initiateUpload',\n INITIATE_UPLOAD,\n {\n input: {\n fileName,\n fileSize,\n mimeType,\n extension,\n ...(folderId ? { folderId } : {}),\n ...(input.visibility ? { visibility: input.visibility } : {}),\n ...(sha256Hash ? { sha256Hash } : {}),\n },\n },\n context\n );\n const rawSession = initiated.initiateUpload?.session;\n if (!rawSession?.id) {\n throw new FilesClientError('UPSTREAM_ERROR', 'wspace-files-svc initiateUpload returned no session');\n }\n const session: InitiatedSession = {\n id: rawSession.id,\n uploadType: rawSession.uploadType,\n partSize: toNumber(rawSession.partSize, 'partSize'),\n totalParts: toNumber(rawSession.totalParts, 'totalParts'),\n };\n\n try {\n if (session.uploadType === 'MULTIPART') {\n await this.uploadParts(session, bytes, context);\n } else {\n await this.putDirect(initiated.initiateUpload?.uploadUrl, bytes, mimeType);\n }\n\n return await this.completeSession(\n session.id,\n {\n fileSize,\n fallbackName: fileName,\n fallbackMimeType: mimeType,\n fallbackSize: bytes.byteLength,\n sha256Hash,\n folderId,\n description: input.description ?? null,\n },\n context\n );\n } catch (error) {\n await this.abortQuietly(session.id, context);\n throw toFilesClientError(error, 'uploadFile');\n }\n }\n\n // ── Delegated upload ──────────────────────────────────────────────────\n\n /**\n * Open a files-svc upload session on the actor's behalf for bytes that\n * someone else holds (an agent, a CLI, a browser), and return the presigned\n * URL(s) to hand them. The uploader PUTs the bytes — one PUT to `uploadUrl`\n * for DIRECT, one PUT per `parts` entry for MULTIPART (files-svc picks\n * MULTIPART above 5 MiB) — and the service then calls\n * {@link completeUploadSession} with the same `fileSize` (and the part ETags)\n * to turn the session into a File. The service never sees the bytes and never\n * holds storage credentials.\n *\n * Throws {@link FilesClientError}. If files-svc opened the session but the\n * client cannot hand it out (an unsupported upload type, missing part URLs),\n * the session is aborted before the error is thrown.\n */\n async createUploadSession(input: CreateUploadSessionInput, actor: FileActor): Promise<UploadSessionTicket> {\n const context = this.requireActor(actor);\n const fileName = requireNonEmpty(input.fileName, 'fileName');\n const mimeType = requireNonEmpty(input.mimeType, 'mimeType');\n if (!Number.isSafeInteger(input.fileSize) || input.fileSize <= 0) {\n throw new FilesClientError('INVALID_INPUT', 'fileSize must be a positive integer', { field: 'fileSize' });\n }\n if (input.fileSize > this.maxUploadBytes) {\n throw new FilesClientError('TOO_LARGE', `File is larger than ${this.maxUploadBytes} bytes`, {\n size: input.fileSize,\n maxBytes: this.maxUploadBytes,\n });\n }\n if (input.visibility !== undefined && !FILE_VISIBILITIES.includes(input.visibility)) {\n throw new FilesClientError('INVALID_INPUT', `Unknown file visibility \"${String(input.visibility)}\"`, {\n field: 'visibility',\n });\n }\n const sha256Hash = normalizeSha256(input.sha256Hash);\n const extension = input.extension?.trim()\n ? input.extension.trim().replace(/^\\./, '').toLowerCase()\n : fileExtensionOf(fileName);\n const folderId = input.folderId?.trim() || undefined;\n\n const initiated = await this.request<{\n initiateUpload: {\n uploadUrl?: string | null;\n session?: {\n id: string;\n uploadType: FileUploadType;\n partSize: number | string;\n totalParts: number | string;\n expiresAt?: string | null;\n } | null;\n } | null;\n }>(\n 'initiateUpload',\n INITIATE_UPLOAD,\n {\n input: {\n fileName,\n fileSize: String(input.fileSize),\n mimeType,\n extension,\n ...(folderId ? { folderId } : {}),\n ...(input.visibility ? { visibility: input.visibility } : {}),\n ...(sha256Hash ? { sha256Hash } : {}),\n },\n },\n context\n );\n const rawSession = initiated.initiateUpload?.session;\n if (!rawSession?.id) {\n throw new FilesClientError('UPSTREAM_ERROR', 'wspace-files-svc initiateUpload returned no session');\n }\n\n try {\n const partSize = toNumber(rawSession.partSize, 'partSize');\n const totalParts = toNumber(rawSession.totalParts, 'totalParts');\n const base = {\n sessionId: rawSession.id,\n partSize,\n totalParts,\n fileSize: input.fileSize,\n sha256Hash,\n expiresAt: toDate(rawSession.expiresAt),\n };\n if (rawSession.uploadType === 'MULTIPART') {\n const session: InitiatedSession = { id: rawSession.id, uploadType: 'MULTIPART', partSize, totalParts };\n this.assertMultipartPlan(session, input.fileSize);\n const parts = await this.presignParts(session, input.fileSize, context);\n return { ...base, uploadType: 'MULTIPART', uploadUrl: null, requiredHeaders: {}, parts };\n }\n if (rawSession.uploadType !== 'DIRECT') {\n throw new FilesClientError(\n 'UPSTREAM_ERROR',\n `wspace-files-svc opened an unsupported ${String(rawSession.uploadType)} session`,\n { sessionId: rawSession.id }\n );\n }\n const uploadUrl = initiated.initiateUpload?.uploadUrl;\n if (!isHttpUrl(uploadUrl)) {\n throw new FilesClientError('UPSTREAM_ERROR', 'wspace-files-svc initiateUpload returned no upload URL', {\n sessionId: rawSession.id,\n });\n }\n return { ...base, uploadType: 'DIRECT', uploadUrl, requiredHeaders: { 'Content-Type': mimeType }, parts: [] };\n } catch (error) {\n await this.abortQuietly(rawSession.id, context);\n throw toFilesClientError(error, 'createUploadSession');\n }\n }\n\n /**\n * Turn a session opened by {@link createUploadSession} into a File once the\n * uploader has PUT the bytes: registers the MULTIPART part ETags, then runs\n * `completeUpload` with the declared size (and SHA-256). files-svc verifies\n * the stored object; a size or checksum mismatch surfaces as `INVALID_INPUT`.\n * The session is left open on failure so the caller can retry or\n * {@link abortUploadSession} it.\n */\n async completeUploadSession(\n sessionId: string,\n input: CompleteUploadSessionInput,\n actor: FileActor\n ): Promise<StoredFile> {\n const context = this.requireActor(actor);\n const id = requireNonEmpty(sessionId, 'sessionId');\n if (!Number.isSafeInteger(input.fileSize) || input.fileSize <= 0) {\n throw new FilesClientError('INVALID_INPUT', 'fileSize must be a positive integer', { field: 'fileSize' });\n }\n const sha256Hash = normalizeSha256(input.sha256Hash);\n const parts = normalizeUploadedParts(input.parts ?? []);\n const folderId = input.folderId?.trim() || undefined;\n\n for (const part of parts) {\n await this.request(\n 'registerUploadedPart',\n REGISTER_PART,\n { input: { sessionId: id, partNumber: part.partNumber, etag: part.etag } },\n context\n );\n }\n return this.completeSession(\n id,\n {\n fileSize: String(input.fileSize),\n fallbackName: '',\n fallbackMimeType: '',\n fallbackSize: input.fileSize,\n sha256Hash,\n folderId,\n description: input.description ?? null,\n },\n context\n );\n }\n\n /** Abandon a session opened by {@link createUploadSession}. `true` when files-svc aborted it. */\n async abortUploadSession(sessionId: string, actor: FileActor): Promise<boolean> {\n const id = requireNonEmpty(sessionId, 'sessionId');\n const data = await this.request<{ abortUpload: boolean | null }>(\n 'abortUpload',\n ABORT_UPLOAD,\n { sessionId: id },\n actor\n );\n return data.abortUpload === true;\n }\n\n // ── Read ──────────────────────────────────────────────────────────────\n\n /** File metadata, or `null` when it does not exist or the actor cannot see it. */\n async getFile(fileId: string, actor: FileActor): Promise<FileMetadata | null> {\n try {\n return await this.fetchFile(fileId, actor);\n } catch (error) {\n if (error instanceof FilesClientError && error.code === 'NOT_FOUND') return null;\n throw error;\n }\n }\n\n /**\n * Prove that an opaque file id the caller supplied names a File in the actor's\n * workspace that they may read, before the service stores or acts on it.\n * Throws `NOT_FOUND` (never a permission error) otherwise.\n */\n async requireFile(fileId: string, actor: FileActor, options: RequireFileOptions = {}): Promise<FileMetadata> {\n const context = this.requireActor(actor);\n // fetchFile, not getFile: an upstream NOT_FOUND keeps its code, key and field.\n const file = await this.fetchFile(fileId, context);\n this.assertUsable(file, fileId, context, options);\n return file;\n }\n\n /** `getFile` without turning an upstream NOT_FOUND into `null`. */\n private async fetchFile(fileId: string, actor: FileActor): Promise<FileMetadata | null> {\n const id = requireNonEmpty(fileId, 'fileId');\n const data = await this.request<{ getFile: RawFileMetadata | null }>('getFile', GET_FILE, { id }, actor);\n return data.getFile ? mapFileMetadata(data.getFile) : null;\n }\n\n /**\n * A presigned download URL for the file, minted for the actor. Mint it when the\n * user opens the file; never persist it. The lifetime is clamped to\n * [60, 604800] seconds.\n */\n async getDownloadUrl(fileId: string, actor: FileActor, options: DownloadUrlOptions = {}): Promise<string> {\n const id = requireNonEmpty(fileId, 'fileId');\n const expiresIn = clampDownloadUrlTtl(options.expiresInSeconds, this.defaultDownloadUrlTtlSeconds);\n const data = await this.request<{ getFileDownloadUrl: string | null }>(\n 'getFileDownloadUrl',\n GET_DOWNLOAD_URL,\n { id, expiresIn },\n actor\n );\n if (!isHttpUrl(data.getFileDownloadUrl)) {\n throw new FilesClientError('UPSTREAM_ERROR', 'wspace-files-svc returned no usable download URL', { fileId: id });\n }\n return data.getFileDownloadUrl;\n }\n\n /**\n * Fetch the file's bytes for server-side processing (vision models, parsers,\n * workflow nodes). Checks the file is active, readable by the actor and within\n * `maxBytes` before downloading, and verifies the downloaded size.\n */\n async downloadFile(fileId: string, actor: FileActor, options: DownloadFileOptions = {}): Promise<DownloadedFile> {\n const context = this.requireActor(actor);\n const id = requireNonEmpty(fileId, 'fileId');\n const maxBytes = options.maxBytes ?? this.maxDownloadBytes;\n if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {\n throw new FilesClientError('INVALID_INPUT', 'maxBytes must be a positive integer', { field: 'maxBytes' });\n }\n\n const data = await this.request<{ getFile: RawFileMetadata | null; getFileDownloadUrl: string | null }>(\n 'downloadFile',\n RESOLVE_FOR_DOWNLOAD,\n { id, expiresIn: INTERNAL_DOWNLOAD_URL_TTL_SECONDS },\n context\n );\n const file = data.getFile ? mapFileMetadata(data.getFile) : null;\n this.assertUsable(file, id, context, {});\n if (file.size > maxBytes) {\n throw new FilesClientError('TOO_LARGE', `File is larger than ${maxBytes} bytes`, {\n fileId: id,\n size: file.size,\n maxBytes,\n });\n }\n const url = data.getFileDownloadUrl;\n if (!isHttpUrl(url)) {\n throw new FilesClientError('UPSTREAM_ERROR', 'wspace-files-svc returned no usable download URL', { fileId: id });\n }\n\n const response = await this.transfer(url, { method: 'GET' }, 'download');\n const bytes = await this.readBounded(response, maxBytes, id);\n if (bytes.byteLength !== file.size) {\n throw new FilesClientError('STORAGE_ERROR', 'Downloaded size does not match the stored file size', {\n fileId: id,\n expected: file.size,\n actual: bytes.byteLength,\n });\n }\n return { bytes, mimeType: file.mimeType, name: file.name, size: bytes.byteLength };\n }\n\n /** {@link downloadFile} as base64, for payloads that must stay JSON (model inputs). */\n async downloadFileAsBase64(\n fileId: string,\n actor: FileActor,\n options: DownloadFileOptions = {}\n ): Promise<{ base64: string; mimeType: string; name: string; size: number }> {\n const file = await this.downloadFile(fileId, actor, options);\n return {\n base64: Buffer.from(file.bytes).toString('base64'),\n mimeType: file.mimeType,\n name: file.name,\n size: file.size,\n };\n }\n\n // ── Delete ────────────────────────────────────────────────────────────\n\n /** Move the file to trash (or hard-delete with `permanent`). `true` when files-svc deleted it. */\n async deleteFile(fileId: string, actor: FileActor, options: DeleteFileOptions = {}): Promise<boolean> {\n const id = requireNonEmpty(fileId, 'fileId');\n if (options.permanent) {\n const data = await this.request<{ permanentlyDeleteFile: boolean | null }>(\n 'permanentlyDeleteFile',\n PERMANENTLY_DELETE_FILE,\n { id },\n actor\n );\n return data.permanentlyDeleteFile === true;\n }\n const data = await this.request<{ deleteFile: boolean | null }>('deleteFile', DELETE_FILE, { id }, actor);\n return data.deleteFile === true;\n }\n\n // ── Upload legs ───────────────────────────────────────────────────────\n\n private async putDirect(\n uploadUrl: string | null | undefined,\n bytes: Uint8Array<ArrayBuffer>,\n mimeType: string\n ): Promise<void> {\n if (!isHttpUrl(uploadUrl)) {\n // files-svc returns a DIRECT uploadUrl for every non-multipart session; its absence\n // means the storage provider is misconfigured, not that a fallback is wanted.\n throw new FilesClientError('UPSTREAM_ERROR', 'wspace-files-svc initiateUpload returned no upload URL');\n }\n // The presigned PUT is signed for this Content-Type, so it must match what initiate declared.\n await this.transfer(uploadUrl, { method: 'PUT', body: bytes, headers: { 'Content-Type': mimeType } }, 'upload');\n }\n\n private async uploadParts(\n session: InitiatedSession,\n bytes: Uint8Array<ArrayBuffer>,\n actor: FileActor\n ): Promise<void> {\n this.assertMultipartPlan(session, bytes.byteLength);\n\n for (let first = 1; first <= session.totalParts; first += PART_URL_BATCH_SIZE) {\n const partNumbers: number[] = [];\n for (let part = first; part < first + PART_URL_BATCH_SIZE && part <= session.totalParts; part += 1) {\n partNumbers.push(part);\n }\n const data = await this.request<{ getBatchPartUploadUrls: Array<{ partNumber: number; url: string }> | null }>(\n 'getBatchPartUploadUrls',\n PART_URLS,\n { sessionId: session.id, partNumbers },\n actor\n );\n const urls = new Map((data.getBatchPartUploadUrls ?? []).map((entry) => [entry.partNumber, entry.url]));\n\n for (const partNumber of partNumbers) {\n const url = urls.get(partNumber);\n if (!isHttpUrl(url)) {\n throw new FilesClientError('UPSTREAM_ERROR', `wspace-files-svc returned no URL for part ${partNumber}`, {\n sessionId: session.id,\n partNumber,\n });\n }\n const start = (partNumber - 1) * session.partSize;\n const body = bytes.subarray(start, Math.min(start + session.partSize, bytes.byteLength));\n const response = await this.transfer(url, { method: 'PUT', body }, 'upload');\n const etag = response.headers.get('etag');\n if (!etag) {\n throw new FilesClientError('STORAGE_ERROR', `Object storage returned no ETag for part ${partNumber}`, {\n sessionId: session.id,\n partNumber,\n });\n }\n await this.request(\n 'registerUploadedPart',\n REGISTER_PART,\n { input: { sessionId: session.id, partNumber, etag } },\n actor\n );\n }\n }\n }\n\n private async completeSession(\n sessionId: string,\n args: {\n fileSize: string;\n fallbackName: string;\n fallbackMimeType: string;\n fallbackSize: number;\n sha256Hash: string | null;\n folderId: string | undefined;\n description: string | null;\n },\n actor: FileActor\n ): Promise<StoredFile> {\n const completed = await this.request<{\n completeUpload: {\n fileId?: string | null;\n file?: {\n id: string;\n name: string;\n mimeType: string;\n size: string | number;\n workspaceId: string;\n sha256Hash?: string | null;\n } | null;\n } | null;\n }>(\n 'completeUpload',\n COMPLETE_UPLOAD,\n {\n input: {\n sessionId,\n fileSize: args.fileSize,\n ...(args.folderId ? { folderId: args.folderId } : {}),\n ...(args.description ? { description: args.description } : {}),\n ...(args.sha256Hash ? { sha256Hash: args.sha256Hash } : {}),\n },\n },\n actor\n );\n const file = completed.completeUpload?.file;\n const fileId = completed.completeUpload?.fileId ?? file?.id;\n if (!fileId) {\n throw new FilesClientError('UPSTREAM_ERROR', 'wspace-files-svc completeUpload returned no fileId', {\n sessionId,\n });\n }\n return {\n fileId,\n name: file?.name ?? args.fallbackName,\n mimeType: file?.mimeType ?? args.fallbackMimeType,\n size: file ? toNumber(file.size, 'size') : args.fallbackSize,\n workspaceId: file?.workspaceId ?? actor.workspaceId,\n sha256Hash: file?.sha256Hash ?? args.sha256Hash,\n };\n }\n\n private assertMultipartPlan(session: InitiatedSession, size: number): void {\n if (session.partSize <= 0 || session.totalParts !== Math.ceil(size / session.partSize)) {\n throw new FilesClientError('UPSTREAM_ERROR', 'wspace-files-svc returned an inconsistent multipart plan', {\n sessionId: session.id,\n partSize: session.partSize,\n totalParts: session.totalParts,\n size,\n });\n }\n }\n\n /** Presigned URL for every part, fetched in batches. */\n private async partUrls(session: InitiatedSession, actor: FileActor): Promise<Map<number, string>> {\n const urls = new Map<number, string>();\n for (let first = 1; first <= session.totalParts; first += PART_URL_BATCH_SIZE) {\n const partNumbers: number[] = [];\n for (let part = first; part < first + PART_URL_BATCH_SIZE && part <= session.totalParts; part += 1) {\n partNumbers.push(part);\n }\n const data = await this.request<{ getBatchPartUploadUrls: Array<{ partNumber: number; url: string }> | null }>(\n 'getBatchPartUploadUrls',\n PART_URLS,\n { sessionId: session.id, partNumbers },\n actor\n );\n for (const entry of data.getBatchPartUploadUrls ?? []) urls.set(entry.partNumber, entry.url);\n }\n return urls;\n }\n\n private async presignParts(session: InitiatedSession, size: number, actor: FileActor): Promise<UploadSessionPart[]> {\n const urls = await this.partUrls(session, actor);\n const parts: UploadSessionPart[] = [];\n for (let partNumber = 1; partNumber <= session.totalParts; partNumber += 1) {\n const url = urls.get(partNumber);\n if (!isHttpUrl(url)) {\n throw new FilesClientError('UPSTREAM_ERROR', `wspace-files-svc returned no URL for part ${partNumber}`, {\n sessionId: session.id,\n partNumber,\n });\n }\n const offset = (partNumber - 1) * session.partSize;\n parts.push({\n partNumber,\n url,\n offset,\n length: Math.min(session.partSize, size - offset),\n });\n }\n return parts;\n }\n\n private async abortQuietly(sessionId: string, actor: FileActor): Promise<void> {\n try {\n await this.request('abortUpload', ABORT_UPLOAD, { sessionId }, actor);\n } catch {\n // Best effort: files-svc's upload reaper expires abandoned sessions anyway, and the\n // original failure is what the caller needs to see.\n }\n }\n\n // ── Transport ─────────────────────────────────────────────────────────\n\n private assertUsable(\n file: FileMetadata | null,\n fileId: string,\n actor: FileActor,\n options: RequireFileOptions\n ): asserts file is FileMetadata {\n const requireActive = options.requireActive ?? true;\n const requireReadable = options.requireReadable ?? true;\n if (\n !file ||\n file.id !== fileId.trim() ||\n file.workspaceId !== actor.workspaceId ||\n (requireActive && file.status !== 'ACTIVE') ||\n (requireReadable && file.canRead !== true)\n ) {\n throw new FilesClientError('NOT_FOUND', 'File not found', { fileId });\n }\n }\n\n private async transfer(url: string, init: RequestInit, leg: 'upload' | 'download'): Promise<Response> {\n let response: Response;\n try {\n response = await this.fetchImpl(url, { ...init, signal: AbortSignal.timeout(this.transferTimeoutMs) });\n } catch (error) {\n throw new FilesClientError('STORAGE_ERROR', `Object storage ${leg} failed`, {\n leg,\n cause: error instanceof Error ? error.message : String(error),\n });\n }\n if (!response.ok) {\n throw new FilesClientError('STORAGE_ERROR', `Object storage ${leg} failed with HTTP ${response.status}`, {\n leg,\n status: response.status,\n });\n }\n return response;\n }\n\n private async readBounded(response: Response, maxBytes: number, fileId: string): Promise<Uint8Array> {\n const tooLarge = (): FilesClientError =>\n new FilesClientError('TOO_LARGE', `File is larger than ${maxBytes} bytes`, { fileId, maxBytes });\n\n const declared = Number(response.headers.get('content-length') ?? Number.NaN);\n if (Number.isFinite(declared) && declared > maxBytes) throw tooLarge();\n if (!response.body) {\n const buffer = new Uint8Array(await response.arrayBuffer());\n if (buffer.byteLength > maxBytes) throw tooLarge();\n return buffer;\n }\n\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n throw tooLarge();\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n }\n\n private requireActor(actor: FileActor): FileActor {\n if (!actor.actorId?.trim() || !actor.workspaceId?.trim()) {\n throw new FilesClientError('MISSING_CONTEXT', 'File operations need an authenticated actor and a workspace');\n }\n if (actor.actorType !== undefined && !FILE_ACTOR_TYPES.includes(actor.actorType)) {\n throw new FilesClientError('MISSING_CONTEXT', `Unknown actor type \"${String(actor.actorType)}\"`);\n }\n return actor;\n }\n\n private getClient(): Promise<FilesTransport> {\n if (!this.clientPromise) {\n const option = this.clientOption;\n this.clientPromise = (async (): Promise<FilesTransport> => {\n try {\n if (typeof option === 'function') return await option();\n if (option) return option;\n // Dynamic import keeps the gateway client (and its JWT/crypto deps) out of\n // the static module graph of `@burdenoff/be-sdk/files` consumers.\n const gateway = await import('../gateway/client.js');\n if (this.serviceName) {\n return new gateway.GatewayClient({\n layer: 'wspace',\n serviceName: this.serviceName,\n serviceIdentity: this.serviceName,\n });\n }\n return gateway.createGatewayClientFromEnv();\n } catch (error) {\n throw new FilesClientError('CONFIGURATION_ERROR', 'Files gateway client is not configured', {\n cause: error instanceof Error ? error.message : String(error),\n });\n }\n })();\n // A failed construction (bad env) must not be cached forever.\n this.clientPromise.catch(() => {\n this.clientPromise = null;\n });\n }\n return this.clientPromise;\n }\n\n private async request<T>(\n operation: string,\n query: string,\n variables: Record<string, unknown>,\n actor: FileActor\n ): Promise<T> {\n const { actorId, workspaceId, actorType } = this.requireActor(actor);\n const client = await this.getClient();\n let response: GraphQLResponse<T>;\n try {\n response = await client.internalQuery<T>({\n query,\n variables,\n timeout: this.requestTimeoutMs,\n headers: {\n 'x-actor-id': actorId,\n 'x-actor-type': actorType ?? 'user',\n 'x-workspace-id': workspaceId,\n },\n });\n } catch (error) {\n throw toFilesClientError(error, operation);\n }\n if (response.errors?.length) {\n throw filesGraphQLError(response.errors, operation);\n }\n if (!response.data) {\n throw new FilesClientError('UPSTREAM_ERROR', `wspace-files-svc ${operation} returned no data`, { operation });\n }\n return response.data;\n }\n}\n","/**\n * File references — the binary-data shape that travels instead of inline bytes.\n *\n * Workflow node outputs, attachments and evidence records should carry a small,\n * JSON-safe pointer to a wspace-files-svc File rather than a base64 payload: the\n * bytes stay in the workspace file library (quota-tracked, permission-checked),\n * and whoever needs them resolves the pointer with `FilesClient.downloadFile` or\n * `FilesClient.getDownloadUrl` on behalf of the current actor.\n */\nimport type { FileMetadata, StoredFile } from './types.js';\n\n/** Discriminator value of {@link FileReference.kind}. */\nexport const FILE_REFERENCE_KIND = 'burdenoff.file' as const;\n\n/** JSON-safe pointer to a File owned by wspace-files-svc. */\nexport interface FileReference {\n kind: typeof FILE_REFERENCE_KIND;\n fileId: string;\n name: string;\n mimeType: string;\n /** Size in bytes. */\n size: number;\n /** Lowercase hex SHA-256 when known. */\n sha256Hash: string | null;\n}\n\n/** Build a {@link FileReference} from an upload result or file metadata. */\nexport function toFileReference(file: StoredFile | FileMetadata): FileReference {\n return {\n kind: FILE_REFERENCE_KIND,\n fileId: 'fileId' in file ? file.fileId : file.id,\n name: file.name,\n mimeType: file.mimeType,\n size: file.size,\n sha256Hash: file.sha256Hash,\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Type guard for a {@link FileReference} read back from JSON (node output, DB column, …). */\nexport function isFileReference(value: unknown): value is FileReference {\n if (!isRecord(value)) return false;\n const size = value['size'];\n const sha256Hash = value['sha256Hash'];\n return (\n value['kind'] === FILE_REFERENCE_KIND &&\n typeof value['fileId'] === 'string' &&\n value['fileId'].length > 0 &&\n typeof value['name'] === 'string' &&\n typeof value['mimeType'] === 'string' &&\n typeof size === 'number' &&\n Number.isSafeInteger(size) &&\n size >= 0 &&\n (sha256Hash === null || sha256Hash === undefined || typeof sha256Hash === 'string')\n );\n}\n","/**\n * @burdenoff/be-sdk/files\n *\n * Shared client for workspace blobs owned by wspace-files-svc. Services hand it\n * bytes and keep the opaque `fileId`; they never presign object storage or hold\n * storage credentials themselves.\n *\n * - {@link FilesClient} — upload (DIRECT and MULTIPART, size + SHA-256 declared),\n * metadata, reference validation, short-lived download URLs, bounded byte\n * downloads and delete, all on behalf of the calling actor over the internal\n * workspace gateway. Delegated uploads (`createUploadSession` →\n * `completeUploadSession`) hand presigned URLs to whoever holds the bytes.\n * - {@link FileReference} — the JSON-safe pointer that node outputs, attachments\n * and evidence rows carry instead of inline base64.\n *\n * @example\n * ```ts\n * import { FilesClient, toFileReference } from '@burdenoff/be-sdk/files';\n *\n * const files = new FilesClient({ serviceName: 'wspace-workflow-svc' });\n * const stored = await files.uploadFile({ fileName: 'invoice.pdf', data, mimeType: 'application/pdf' }, actor);\n * return { attachment: toFileReference(stored) };\n * ```\n */\n\nexport {\n FILE_ACTOR_TYPES,\n FILE_VISIBILITIES,\n type CompleteUploadSessionInput,\n type CreateUploadSessionInput,\n type DeleteFileOptions,\n type DownloadFileOptions,\n type DownloadUrlOptions,\n type DownloadedFile,\n type FileActor,\n type FileActorType,\n type FileBytes,\n type FileMetadata,\n type FileStatus,\n type FileUploadType,\n type FileVisibility,\n type FilesFetch,\n type FilesTransport,\n type RawFileMetadata,\n type RequireFileOptions,\n type StoredFile,\n type UploadFileInput,\n type UploadSessionPart,\n type UploadSessionTicket,\n type UploadedPart,\n} from './types.js';\n\nexport {\n FILES_CLIENT_GRAPHQL_CODES,\n FilesClientError,\n MAX_FILES_ERROR_SUMMARY_LENGTH,\n MAX_UPSTREAM_MESSAGE_LENGTH,\n classifyFilesErrors,\n filesGraphQLError,\n isFilesClientError,\n sanitizeUpstreamError,\n sanitizeUpstreamText,\n summarizeFilesClientError,\n toFilesClientError,\n type FilesClientErrorCode,\n type FilesClientErrorUpstream,\n type FilesUpstreamError,\n} from './errors.js';\n\nexport {\n FilesClient,\n MAX_DOWNLOAD_URL_TTL_SECONDS,\n MIN_DOWNLOAD_URL_TTL_SECONDS,\n clampDownloadUrlTtl,\n fileExtensionOf,\n mapFileMetadata,\n type FilesClientOptions,\n} from './client.js';\n\nexport { FILE_REFERENCE_KIND, isFileReference, toFileReference, type FileReference } from './reference.js';\n"],"mappings":";;;;;;AAYA,MAAa,mBAAmB;CAAC;CAAQ;CAAO;CAAW;AAAa;;AAuBxE,MAAa,oBAAoB;CAAC;CAAW;CAAU;CAAQ;AAAW;;;;;;;;;;;;;;;;;ACD1E,MAAa,6BAAmE;CAC9E,eAAe;CACf,iBAAiB;CAEjB,WAAW;CACX,gBAAgB;CAChB,WAAW;CACX,eAAe;CACf,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AAoB,EAAE,UAAU,CAAC;EAE9G,OAAO,SAAS;CAClB;AACF;;;;ACz/BA,MAAa,sBAAsB;;AAenC,SAAgB,gBAAgB,MAAgD;CAC9E,OAAO;EACL,MAAM;EACN,QAAQ,YAAY,OAAO,KAAK,SAAS,KAAK;EAC9C,MAAM,KAAK;EACX,UAAU,KAAK;EACf,MAAM,KAAK;EACX,YAAY,KAAK;CACnB;AACF;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;;AAGA,SAAgB,gBAAgB,OAAwC;CACtE,IAAI,CAAC,SAAS,KAAK,GAAG,OAAO;CAC7B,MAAM,OAAO,MAAM;CACnB,MAAM,aAAa,MAAM;CACzB,OACE,MAAM,gCACN,OAAO,MAAM,cAAc,YAC3B,MAAM,SAAS,CAAC,SAAS,KACzB,OAAO,MAAM,YAAY,YACzB,OAAO,MAAM,gBAAgB,YAC7B,OAAO,SAAS,YAChB,OAAO,cAAc,IAAI,KACzB,QAAQ,MACP,eAAe,QAAQ,eAAe,UAAa,OAAO,eAAe;AAE9E"}
@@ -54,5 +54,59 @@ function collectPromDefaultMetrics(prom, bun = isBunRuntime()) {
54
54
  for (const name of BUN_HEAP_WALK_DEFAULT_METRICS) prom.register.removeSingleMetric(name);
55
55
  }
56
56
 
57
- export { isBunRuntime as n, collectPromDefaultMetrics as t };
58
- //# sourceMappingURL=bun-runtime-metrics-CPy5D6NT.js.map
57
+ // src/telemetry/incoming-request-span.ts
58
+ /** Tracer (instrumentation scope) name of the spans this module creates. */
59
+ const INCOMING_REQUEST_TRACER = "@burdenoff/be-sdk/server";
60
+ const headerGetter = {
61
+ get: (carrier, key) => carrier.get(key) ?? void 0,
62
+ keys: (carrier) => [...carrier.keys()]
63
+ };
64
+ let apiPromise = null;
65
+ function isIncomingSpanApi(mod) {
66
+ if (typeof mod !== "object" || mod === null) return false;
67
+ const candidate = mod;
68
+ return typeof candidate.propagation === "object" && typeof candidate.context === "object" && typeof candidate.trace === "object" && typeof candidate.SpanKind === "object";
69
+ }
70
+ /** Loads `@opentelemetry/api` once; resolves null when it is not installed. */
71
+ function loadIncomingSpanApi() {
72
+ apiPromise ??= import("./dist-BGKdXVy3.js").then((mod) => isIncomingSpanApi(mod) ? mod : null, () => null);
73
+ return apiPromise;
74
+ }
75
+ /**
76
+ * Runs `handle` inside a SERVER span that continues the trace in the request's
77
+ * `traceparent` (or starts a new one). The span is named `<METHOD> <route>`,
78
+ * carries the HTTP method, route and response status, and is marked as an
79
+ * error for a thrown handler or a 5xx response.
80
+ */
81
+ async function withIncomingRequestSpan(request, route, handle, api = null) {
82
+ const otel = api ?? await loadIncomingSpanApi();
83
+ if (!otel) return handle();
84
+ const parent = otel.propagation.extract(otel.ROOT_CONTEXT, request.headers, headerGetter);
85
+ const span = otel.trace.getTracer(INCOMING_REQUEST_TRACER).startSpan(`${request.method} ${route}`, {
86
+ kind: otel.SpanKind.SERVER,
87
+ attributes: {
88
+ "http.request.method": request.method,
89
+ "http.route": route,
90
+ "url.path": route
91
+ }
92
+ }, parent);
93
+ try {
94
+ const response = await otel.context.with(otel.trace.setSpan(parent, span), handle);
95
+ span.setAttribute("http.response.status_code", response.status);
96
+ if (response.status >= 500) span.setStatus({ code: otel.SpanStatusCode.ERROR });
97
+ return response;
98
+ } catch (error) {
99
+ const err = error instanceof Error ? error : new Error(String(error));
100
+ span.recordException(err);
101
+ span.setStatus({
102
+ code: otel.SpanStatusCode.ERROR,
103
+ message: err.message
104
+ });
105
+ throw error;
106
+ } finally {
107
+ span.end();
108
+ }
109
+ }
110
+
111
+ export { isBunRuntime as i, withIncomingRequestSpan as n, collectPromDefaultMetrics as r, INCOMING_REQUEST_TRACER as t };
112
+ //# sourceMappingURL=incoming-request-span-DCou42Il.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"incoming-request-span-DCou42Il.js","names":[],"sources":["../src/telemetry/bun-runtime-metrics.ts","../src/telemetry/incoming-request-span.ts"],"sourcesContent":["/**\n * Runtime metrics that stall a Bun process (BOFF-12287).\n *\n * `v8.getHeapStatistics()` and `v8.getHeapSpaceStatistics()` are cheap under\n * Node. Under Bun 1.4 they walk the whole JavaScriptCore heap synchronously:\n * about 0.44 s per call on a 3M-object heap, during which the process serves\n * nothing. Two collectors that be-sdk services load call one of them on a\n * timer, so every Bun 1.4 service paid a recurring block sized to its heap:\n *\n * - prom-client's default `nodejs_heap_space_size_*_bytes` gauges, on every\n * Prometheus scrape. Bun 1.3 threw `ERR_NOT_IMPLEMENTED` and prom-client\n * skipped them; Bun 1.4 implements the call, so from the Bun 1.4.4 upgrade\n * on the scrape itself became the block (wspace-int-gateway: 0.01 s →\n * 0.5–0.76 s per scrape). Handled here.\n * - the OpenTelemetry `runtime-node` instrumentation, on every 60 s OTLP\n * metric export. Handled in `sdk.ts` (`autoInstrumentationConfig`).\n *\n * Heap size stays visible through prom-client's `nodejs_heap_size_*_bytes`,\n * which reads `process.memoryUsage()`, and event-loop lag through\n * `nodejs_eventloop_lag_*`. No dashboard or alert reads the dropped series.\n */\n\n/** True when the process runs on Bun (also inside a `bun build --compile` binary). */\nexport function isBunRuntime(): boolean {\n return typeof process.versions['bun'] === 'string';\n}\n\n/**\n * prom-client default metrics that are not served under Bun. The `total` gauge\n * carries the collect callback that calls `v8.getHeapSpaceStatistics()`; the\n * other two are only filled by it, so all three go.\n */\nexport const BUN_HEAP_WALK_DEFAULT_METRICS: readonly string[] = [\n 'nodejs_heap_space_size_total_bytes',\n 'nodejs_heap_space_size_used_bytes',\n 'nodejs_heap_space_size_available_bytes',\n];\n\n/** The part of the `prom-client` module that {@link collectPromDefaultMetrics} uses. */\nexport interface PromDefaultMetricsClient {\n register: { removeSingleMetric: (name: string) => void };\n collectDefaultMetrics: (opts?: Record<string, unknown>) => void;\n}\n\n/**\n * Registers prom-client's default metrics on `prom.register` and, under Bun,\n * removes the heap-space gauges again.\n *\n * Safe to call on every scrape: prom-client throws on the first metric name\n * that is already registered, before it reaches the heap-space gauges, and the\n * removal is a map delete. Calling it again also removes the gauges when the\n * service registered the default metrics on the same registry itself.\n *\n * prom-client probes `v8.getHeapSpaceStatistics()` once when it registers the\n * defaults, so a Bun process still pays one heap walk, on its first scrape.\n */\nexport function collectPromDefaultMetrics(prom: PromDefaultMetricsClient, bun: boolean = isBunRuntime()): void {\n try {\n prom.collectDefaultMetrics({ register: prom.register });\n } catch {\n // Already registered on this registry: prom-client rejects duplicate names.\n }\n if (!bun) return;\n for (const name of BUN_HEAP_WALK_DEFAULT_METRICS) prom.register.removeSingleMetric(name);\n}\n","/**\n * Server span for incoming GraphQL requests, continuing the caller's trace\n * (BOFF-17552).\n *\n * WHY THIS EXISTS\n * `createServer` runs on Bun.serve through Elysia. OpenTelemetry's\n * `instrumentation-http` only patches Node's `http` module, so no SERVER span\n * was ever created for an incoming request and the W3C `traceparent` header\n * the gateway sends was never extracted. Request traces in X-Ray therefore\n * stopped at the gateway, and nothing a subgraph did for a request (its own\n * spans, Postgres queries) was attached to the trace that caused it.\n *\n * `withIncomingRequestSpan` extracts the caller's context from the request\n * headers with the globally registered propagator, starts a SERVER span as\n * its child and runs the handler with that span active, so every span the\n * handler starts joins the same trace. The parent's sampled flag is honoured\n * by the SDK's parent-based sampler, so a request the gateway did not sample\n * stays unsampled here.\n *\n * `@opentelemetry/api` is an optional peer: it is loaded lazily, and when it\n * is missing (or a service runs without the OTel SDK, which makes the API a\n * no-op) the handler simply runs unwrapped.\n */\n\n/** The slice of `@opentelemetry/api` this module uses. Injectable for tests. */\nexport interface IncomingSpanApi {\n ROOT_CONTEXT: unknown;\n SpanKind: { SERVER: number };\n SpanStatusCode: { ERROR: number };\n propagation: {\n extract: (\n ctx: unknown,\n carrier: Headers,\n getter: { get: (carrier: Headers, key: string) => string | undefined; keys: (carrier: Headers) => string[] }\n ) => unknown;\n };\n context: { with: <T>(ctx: unknown, fn: () => T) => T };\n trace: {\n getTracer: (name: string) => {\n startSpan: (\n name: string,\n options: { kind: number; attributes: Record<string, string | number> },\n ctx: unknown\n ) => IncomingSpan;\n };\n setSpan: (ctx: unknown, span: IncomingSpan) => unknown;\n };\n}\n\nexport interface IncomingSpan {\n setAttribute: (key: string, value: string | number) => unknown;\n setStatus: (status: { code: number; message?: string }) => unknown;\n recordException: (exception: Error) => unknown;\n end: () => void;\n}\n\n/** Tracer (instrumentation scope) name of the spans this module creates. */\nexport const INCOMING_REQUEST_TRACER = '@burdenoff/be-sdk/server';\n\nconst headerGetter = {\n get: (carrier: Headers, key: string): string | undefined => carrier.get(key) ?? undefined,\n keys: (carrier: Headers): string[] => [...carrier.keys()],\n};\n\nlet apiPromise: Promise<IncomingSpanApi | null> | null = null;\n\nfunction isIncomingSpanApi(mod: unknown): mod is IncomingSpanApi {\n if (typeof mod !== 'object' || mod === null) return false;\n const candidate = mod as Partial<Record<keyof IncomingSpanApi, unknown>>;\n return (\n typeof candidate.propagation === 'object' &&\n typeof candidate.context === 'object' &&\n typeof candidate.trace === 'object' &&\n typeof candidate.SpanKind === 'object'\n );\n}\n\n/** Loads `@opentelemetry/api` once; resolves null when it is not installed. */\nexport function loadIncomingSpanApi(): Promise<IncomingSpanApi | null> {\n apiPromise ??= import('@opentelemetry/api').then(\n (mod: unknown) => (isIncomingSpanApi(mod) ? mod : null),\n () => null\n );\n return apiPromise;\n}\n\n/**\n * Runs `handle` inside a SERVER span that continues the trace in the request's\n * `traceparent` (or starts a new one). The span is named `<METHOD> <route>`,\n * carries the HTTP method, route and response status, and is marked as an\n * error for a thrown handler or a 5xx response.\n */\nexport async function withIncomingRequestSpan(\n request: Request,\n route: string,\n handle: () => Promise<Response>,\n api: IncomingSpanApi | null = null\n): Promise<Response> {\n const otel = api ?? (await loadIncomingSpanApi());\n if (!otel) return handle();\n\n const parent = otel.propagation.extract(otel.ROOT_CONTEXT, request.headers, headerGetter);\n const span = otel.trace.getTracer(INCOMING_REQUEST_TRACER).startSpan(\n `${request.method} ${route}`,\n {\n kind: otel.SpanKind.SERVER,\n attributes: { 'http.request.method': request.method, 'http.route': route, 'url.path': route },\n },\n parent\n );\n try {\n const response = await otel.context.with(otel.trace.setSpan(parent, span), handle);\n span.setAttribute('http.response.status_code', response.status);\n if (response.status >= 500) span.setStatus({ code: otel.SpanStatusCode.ERROR });\n return response;\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n span.recordException(err);\n span.setStatus({ code: otel.SpanStatusCode.ERROR, message: err.message });\n throw error;\n } finally {\n span.end();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,eAAwB;CACtC,OAAO,OAAO,QAAQ,SAAS,WAAW;AAC5C;;;;;;AAOA,MAAa,gCAAmD;CAC9D;CACA;CACA;AACF;;;;;;;;;;;;;AAoBA,SAAgB,0BAA0B,MAAgC,MAAe,aAAa,GAAS;CAC7G,IAAI;EACF,KAAK,sBAAsB,EAAE,UAAU,KAAK,SAAS,CAAC;CACxD,QAAQ,CAER;CACA,IAAI,CAAC,KAAK;CACV,KAAK,MAAM,QAAQ,+BAA+B,KAAK,SAAS,mBAAmB,IAAI;AACzF;;;;ACPA,MAAa,0BAA0B;AAEvC,MAAM,eAAe;CACnB,MAAM,SAAkB,QAAoC,QAAQ,IAAI,GAAG,KAAK;CAChF,OAAO,YAA+B,CAAC,GAAG,QAAQ,KAAK,CAAC;AAC1D;AAEA,IAAI,aAAqD;AAEzD,SAAS,kBAAkB,KAAsC;CAC/D,IAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM,OAAO;CACpD,MAAM,YAAY;CAClB,OACE,OAAO,UAAU,gBAAgB,YACjC,OAAO,UAAU,YAAY,YAC7B,OAAO,UAAU,UAAU,YAC3B,OAAO,UAAU,aAAa;AAElC;;AAGA,SAAgB,sBAAuD;CACrE,eAAe,OAAO,qBAAqB,CAAC,MACzC,QAAkB,kBAAkB,GAAG,IAAI,MAAM,YAC5C,IACR;CACA,OAAO;AACT;;;;;;;AAQA,eAAsB,wBACpB,SACA,OACA,QACA,MAA8B,MACX;CACnB,MAAM,OAAO,OAAQ,MAAM,oBAAoB;CAC/C,IAAI,CAAC,MAAM,OAAO,OAAO;CAEzB,MAAM,SAAS,KAAK,YAAY,QAAQ,KAAK,cAAc,QAAQ,SAAS,YAAY;CACxF,MAAM,OAAO,KAAK,MAAM,UAAU,uBAAuB,CAAC,CAAC,UACzD,GAAG,QAAQ,OAAO,GAAG,SACrB;EACE,MAAM,KAAK,SAAS;EACpB,YAAY;GAAE,uBAAuB,QAAQ;GAAQ,cAAc;GAAO,YAAY;EAAM;CAC9F,GACA,MACF;CACA,IAAI;EACF,MAAM,WAAW,MAAM,KAAK,QAAQ,KAAK,KAAK,MAAM,QAAQ,QAAQ,IAAI,GAAG,MAAM;EACjF,KAAK,aAAa,6BAA6B,SAAS,MAAM;EAC9D,IAAI,SAAS,UAAU,KAAK,KAAK,UAAU,EAAE,MAAM,KAAK,eAAe,MAAM,CAAC;EAC9E,OAAO;CACT,SAAS,OAAO;EACd,MAAM,MAAM,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;EACpE,KAAK,gBAAgB,GAAG;EACxB,KAAK,UAAU;GAAE,MAAM,KAAK,eAAe;GAAO,SAAS,IAAI;EAAQ,CAAC;EACxE,MAAM;CACR,UAAU;EACR,KAAK,IAAI;CACX;AACF"}
@@ -108,8 +108,19 @@ declare function rbacArgPathProblem(field: FieldDefinitionNode, path: string, in
108
108
  }): string | null;
109
109
  declare function analyzeRbacCoverage(source: RbacCoverageSource, options?: RbacCoverageOptions): RbacCoverageReport;
110
110
  declare function assertRbacCoverage(source: RbacCoverageSource, options?: RbacCoverageOptions): RbacCoverageReport;
111
- declare const SUPPORTED_BILLING_CURRENCIES: readonly ["USD", "EUR", "GBP", "INR", "AUD", "CAD", "SGD", "JPY", "CNY", "BRL", "MXN", "KRW", "HKD", "NOK", "SEK", "DKK", "CHF", "NZD", "ZAR", "AED", "SAR", "QAR", "OMR", "BHD", "KWD", "JOD", "EGP", "PKR", "BDT", "LKR", "THB", "MYR", "IDR", "PHP", "VND", "TWD", "CZK", "HUF", "PLN", "RON", "RUB", "TRY", "ILS", "NGN", "GHS", "KES", "TZS", "UGX", "ETB", "MAD", "DZD", "TND", "BWP", "MUR", "MVR", "BND", "KHR", "MMK", "KZT", "UZS", "AZN", "GEL", "AMD", "UAH", "BGN", "HRK", "MKD", "ALL", "RSD", "CLP", "COP", "PEN", "ARS", "BOB", "PYG", "UYU", "GTQ", "HNL", "NIO", "CRC", "DOP", "TTD", "JMD", "BBD", "HTG", "BZD", "GYD", "SRD", "XCD", "PAB"];
111
+ declare const SUPPORTED_BILLING_CURRENCIES: readonly ["USD", "INR", "EUR", "GBP", "AUD"];
112
112
  type SupportedBillingCurrency = (typeof SUPPORTED_BILLING_CURRENCIES)[number];
113
+ type BillingCurrencyPaymentProvider = 'STRIPE' | 'RAZORPAY';
114
+ interface SupportedBillingCurrencyInfo {
115
+ readonly code: SupportedBillingCurrency;
116
+ readonly name: string;
117
+ readonly symbol: string;
118
+ readonly minorUnits: number;
119
+ readonly paymentProvider: BillingCurrencyPaymentProvider;
120
+ }
121
+ declare const SUPPORTED_BILLING_CURRENCY_INFO: Readonly<Record<SupportedBillingCurrency, SupportedBillingCurrencyInfo>>;
122
+ declare function toSupportedBillingCurrency(currency: unknown): SupportedBillingCurrency | null;
123
+ declare function getSupportedBillingCurrencyInfo(currency: unknown): SupportedBillingCurrencyInfo | null;
113
124
  declare const MAX_BILLING_AMOUNT = 1000000000;
114
125
  declare function isSupportedBillingCurrency(currency: unknown): boolean;
115
126
  type BillingAmountErrorCode = 'not_finite' | 'not_positive' | 'negative' | 'exceeds_maximum';
@@ -140,6 +151,6 @@ declare function validateBillingMoney(amount: unknown, currency: unknown, option
140
151
  allowZero?: boolean;
141
152
  }): BillingMoneyValidationResult;
142
153
  declare namespace index_d_exports {
143
- export { BillingAmountErrorCode, BillingAmountValidationResult, BillingMoneyErrorCode, BillingMoneyValidationResult, DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS, DEFAULT_RBAC_ROOT_TYPES, MAX_BILLING_AMOUNT, NAME_MAX_LENGTH, NAME_MIN_LENGTH, NameErrorCode, NameValidationResult, RBAC_GATED_SCOPE_TYPES, RBAC_SCOPE_TYPES, RbacCoverageError, RbacCoverageOptions, RbacCoverageReport, RbacCoverageSource, RbacDirectiveArgs, RbacFieldPin, RbacRootField, RbacSchemaDocument, RbacScopeType, SUPPORTED_BILLING_CURRENCIES, SupportedBillingCurrency, USERNAME_MAX_LENGTH, USERNAME_MIN_LENGTH, UserFieldError, UserFieldKey, UserFieldsValidationResult, UsernameErrorCode, UsernameValidationResult, ValidatedUserFields, analyzeRbacCoverage, assertRbacCoverage, convertBillingToMinorUnits, isSupportedBillingCurrency, lengthInCodePoints, loadRbacSchemaDocuments, rbacArgPathProblem, readRbacDirectiveArgs, validateBillingAmount, validateBillingMoney, validateName, validateUserFields, validateUsername };
154
+ export { BillingAmountErrorCode, BillingAmountValidationResult, BillingCurrencyPaymentProvider, BillingMoneyErrorCode, BillingMoneyValidationResult, DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS, DEFAULT_RBAC_ROOT_TYPES, MAX_BILLING_AMOUNT, NAME_MAX_LENGTH, NAME_MIN_LENGTH, NameErrorCode, NameValidationResult, RBAC_GATED_SCOPE_TYPES, RBAC_SCOPE_TYPES, RbacCoverageError, RbacCoverageOptions, RbacCoverageReport, RbacCoverageSource, RbacDirectiveArgs, RbacFieldPin, RbacRootField, RbacSchemaDocument, RbacScopeType, SUPPORTED_BILLING_CURRENCIES, SUPPORTED_BILLING_CURRENCY_INFO, SupportedBillingCurrency, SupportedBillingCurrencyInfo, USERNAME_MAX_LENGTH, USERNAME_MIN_LENGTH, UserFieldError, UserFieldKey, UserFieldsValidationResult, UsernameErrorCode, UsernameValidationResult, ValidatedUserFields, analyzeRbacCoverage, assertRbacCoverage, convertBillingToMinorUnits, getSupportedBillingCurrencyInfo, isSupportedBillingCurrency, lengthInCodePoints, loadRbacSchemaDocuments, rbacArgPathProblem, readRbacDirectiveArgs, toSupportedBillingCurrency, validateBillingAmount, validateBillingMoney, validateName, validateUserFields, validateUsername };
144
155
  }
145
- export { readRbacDirectiveArgs as A, validateUsername as B, RbacRootField as C, assertRbacCoverage as D, analyzeRbacCoverage as E, validateUserFields as F, lengthInCodePoints as G, NAME_MIN_LENGTH as H, USERNAME_MAX_LENGTH as I, validateName as K, USERNAME_MIN_LENGTH as L, UserFieldKey as M, UserFieldsValidationResult as N, loadRbacSchemaDocuments as O, ValidatedUserFields as P, UsernameErrorCode as R, RbacFieldPin as S, RbacScopeType as T, NameErrorCode as U, NAME_MAX_LENGTH as V, NameValidationResult as W, RbacCoverageError as _, BillingMoneyValidationResult as a, RbacCoverageSource as b, SupportedBillingCurrency as c, validateBillingAmount as d, validateBillingMoney as f, RBAC_SCOPE_TYPES as g, RBAC_GATED_SCOPE_TYPES as h, BillingMoneyErrorCode as i, UserFieldError as j, rbacArgPathProblem as k, convertBillingToMinorUnits as l, DEFAULT_RBAC_ROOT_TYPES as m, BillingAmountErrorCode as n, MAX_BILLING_AMOUNT as o, DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS as p, BillingAmountValidationResult as r, SUPPORTED_BILLING_CURRENCIES as s, index_d_exports as t, isSupportedBillingCurrency as u, RbacCoverageOptions as v, RbacSchemaDocument as w, RbacDirectiveArgs as x, RbacCoverageReport as y, UsernameValidationResult as z };
156
+ export { RbacScopeType as A, validateUserFields as B, RbacCoverageOptions as C, RbacFieldPin as D, RbacDirectiveArgs as E, readRbacDirectiveArgs as F, validateUsername as G, USERNAME_MIN_LENGTH as H, UserFieldError as I, NameErrorCode as J, NAME_MAX_LENGTH as K, UserFieldKey as L, assertRbacCoverage as M, loadRbacSchemaDocuments as N, RbacRootField as O, rbacArgPathProblem as P, UserFieldsValidationResult as R, RbacCoverageError as S, RbacCoverageSource as T, UsernameErrorCode as U, USERNAME_MAX_LENGTH as V, UsernameValidationResult as W, lengthInCodePoints as X, NameValidationResult as Y, validateName as Z, validateBillingMoney as _, BillingMoneyErrorCode as a, RBAC_GATED_SCOPE_TYPES as b, SUPPORTED_BILLING_CURRENCIES as c, SupportedBillingCurrencyInfo as d, convertBillingToMinorUnits as f, validateBillingAmount as g, toSupportedBillingCurrency as h, BillingCurrencyPaymentProvider as i, analyzeRbacCoverage as j, RbacSchemaDocument as k, SUPPORTED_BILLING_CURRENCY_INFO as l, isSupportedBillingCurrency as m, BillingAmountErrorCode as n, BillingMoneyValidationResult as o, getSupportedBillingCurrencyInfo as p, NAME_MIN_LENGTH as q, BillingAmountValidationResult as r, MAX_BILLING_AMOUNT as s, index_d_exports as t, SupportedBillingCurrency as u, DEFAULT_MAX_RBAC_ARG_PATH_SEGMENTS as v, RbacCoverageReport as w, RBAC_SCOPE_TYPES as x, DEFAULT_RBAC_ROOT_TYPES as y, ValidatedUserFields as z };
@@ -128,14 +128,36 @@ interface RawFileMetadata {
128
128
  }
129
129
  type FilesClientErrorCode = 'INVALID_INPUT' | 'MISSING_CONTEXT' | 'NOT_FOUND' | 'QUOTA_EXCEEDED' | 'TOO_LARGE' | 'STORAGE_ERROR' | 'UPSTREAM_ERROR' | 'CONFIGURATION_ERROR';
130
130
  declare const FILES_CLIENT_GRAPHQL_CODES: Record<FilesClientErrorCode, string>;
131
+ declare const MAX_UPSTREAM_MESSAGE_LENGTH = 200;
132
+ declare const MAX_FILES_ERROR_SUMMARY_LENGTH = 400;
133
+ interface FilesUpstreamError {
134
+ code: string | null;
135
+ message: string;
136
+ i18nKey?: string;
137
+ field?: string;
138
+ traceId?: string;
139
+ }
140
+ interface FilesClientErrorUpstream {
141
+ operation?: string;
142
+ errors?: readonly FilesUpstreamError[];
143
+ status?: number;
144
+ }
131
145
  declare class FilesClientError extends Error {
132
146
  readonly code: FilesClientErrorCode;
133
147
  readonly details: Record<string, unknown>;
134
- constructor(code: FilesClientErrorCode, message: string, details?: Record<string, unknown>);
148
+ readonly operation: string | undefined;
149
+ readonly upstreamErrors: readonly FilesUpstreamError[];
150
+ readonly status: number | undefined;
151
+ constructor(code: FilesClientErrorCode, message: string, details?: Record<string, unknown>, upstream?: FilesClientErrorUpstream);
135
152
  get graphqlCode(): string;
153
+ get summary(): string;
136
154
  }
137
155
  declare function isFilesClientError(error: unknown): error is FilesClientError;
138
156
  declare function classifyFilesErrors(errors: readonly GraphQLError[]): FilesClientErrorCode;
157
+ declare function sanitizeUpstreamText(value: unknown, maxLength?: number): string;
158
+ declare function sanitizeUpstreamError(error: GraphQLError): FilesUpstreamError;
159
+ declare function summarizeFilesClientError(error: FilesClientError): string;
160
+ declare function filesGraphQLError(errors: readonly GraphQLError[], operation: string): FilesClientError;
139
161
  declare function toFilesClientError(error: unknown, operation: string): FilesClientError;
140
162
  declare const MAX_DOWNLOAD_URL_TTL_SECONDS = 604800;
141
163
  declare const MIN_DOWNLOAD_URL_TTL_SECONDS = 60;
@@ -169,6 +191,7 @@ declare class FilesClient {
169
191
  abortUploadSession(sessionId: string, actor: FileActor): Promise<boolean>;
170
192
  getFile(fileId: string, actor: FileActor): Promise<FileMetadata | null>;
171
193
  requireFile(fileId: string, actor: FileActor, options?: RequireFileOptions): Promise<FileMetadata>;
194
+ private fetchFile;
172
195
  getDownloadUrl(fileId: string, actor: FileActor, options?: DownloadUrlOptions): Promise<string>;
173
196
  downloadFile(fileId: string, actor: FileActor, options?: DownloadFileOptions): Promise<DownloadedFile>;
174
197
  downloadFileAsBase64(fileId: string, actor: FileActor, options?: DownloadFileOptions): Promise<{
@@ -204,6 +227,6 @@ interface FileReference {
204
227
  declare function toFileReference(file: StoredFile | FileMetadata): FileReference;
205
228
  declare function isFileReference(value: unknown): value is FileReference;
206
229
  declare namespace index_d_exports {
207
- export { CompleteUploadSessionInput, CreateUploadSessionInput, DeleteFileOptions, DownloadFileOptions, DownloadUrlOptions, DownloadedFile, FILES_CLIENT_GRAPHQL_CODES, FILE_ACTOR_TYPES, FILE_REFERENCE_KIND, FILE_VISIBILITIES, FileActor, FileActorType, FileBytes, FileMetadata, FileReference, FileStatus, FileUploadType, FileVisibility, FilesClient, FilesClientError, FilesClientErrorCode, FilesClientOptions, FilesFetch, FilesTransport, MAX_DOWNLOAD_URL_TTL_SECONDS, MIN_DOWNLOAD_URL_TTL_SECONDS, RawFileMetadata, RequireFileOptions, StoredFile, UploadFileInput, UploadSessionPart, UploadSessionTicket, UploadedPart, clampDownloadUrlTtl, classifyFilesErrors, fileExtensionOf, isFileReference, isFilesClientError, mapFileMetadata, toFileReference, toFilesClientError };
230
+ export { CompleteUploadSessionInput, CreateUploadSessionInput, DeleteFileOptions, DownloadFileOptions, DownloadUrlOptions, DownloadedFile, FILES_CLIENT_GRAPHQL_CODES, FILE_ACTOR_TYPES, FILE_REFERENCE_KIND, FILE_VISIBILITIES, FileActor, FileActorType, FileBytes, FileMetadata, FileReference, FileStatus, FileUploadType, FileVisibility, FilesClient, FilesClientError, FilesClientErrorCode, FilesClientErrorUpstream, FilesClientOptions, FilesFetch, FilesTransport, FilesUpstreamError, MAX_DOWNLOAD_URL_TTL_SECONDS, MAX_FILES_ERROR_SUMMARY_LENGTH, MAX_UPSTREAM_MESSAGE_LENGTH, MIN_DOWNLOAD_URL_TTL_SECONDS, RawFileMetadata, RequireFileOptions, StoredFile, UploadFileInput, UploadSessionPart, UploadSessionTicket, UploadedPart, clampDownloadUrlTtl, classifyFilesErrors, fileExtensionOf, filesGraphQLError, isFileReference, isFilesClientError, mapFileMetadata, sanitizeUpstreamError, sanitizeUpstreamText, summarizeFilesClientError, toFileReference, toFilesClientError };
208
231
  }
209
- export { FileMetadata as A, UploadSessionPart as B, DownloadUrlOptions as C, FileActor as D, FILE_VISIBILITIES as E, FilesTransport as F, UploadedPart as H, RawFileMetadata as I, RequireFileOptions as L, FileUploadType as M, FileVisibility as N, FileActorType as O, FilesFetch as P, StoredFile as R, DownloadFileOptions as S, FILE_ACTOR_TYPES as T, UploadSessionTicket as V, isFilesClientError as _, toFileReference as a, CreateUploadSessionInput as b, MAX_DOWNLOAD_URL_TTL_SECONDS as c, fileExtensionOf as d, mapFileMetadata as f, classifyFilesErrors as g, FilesClientErrorCode as h, isFileReference as i, FileStatus as j, FileBytes as k, MIN_DOWNLOAD_URL_TTL_SECONDS as l, FilesClientError as m, FILE_REFERENCE_KIND as n, FilesClient as o, FILES_CLIENT_GRAPHQL_CODES as p, FileReference as r, FilesClientOptions as s, index_d_exports as t, clampDownloadUrlTtl as u, toFilesClientError as v, DownloadedFile as w, DeleteFileOptions as x, CompleteUploadSessionInput as y, UploadFileInput as z };
232
+ export { DownloadFileOptions as A, FileUploadType as B, sanitizeUpstreamError as C, CompleteUploadSessionInput as D, toFilesClientError as E, FileActor as F, RequireFileOptions as G, FilesFetch as H, FileActorType as I, UploadSessionPart as J, StoredFile as K, FileBytes as L, DownloadedFile as M, FILE_ACTOR_TYPES as N, CreateUploadSessionInput as O, FILE_VISIBILITIES as P, FileMetadata as R, isFilesClientError as S, summarizeFilesClientError as T, FilesTransport as U, FileVisibility as V, RawFileMetadata as W, UploadedPart as X, UploadSessionTicket as Y, FilesUpstreamError as _, toFileReference as a, classifyFilesErrors as b, MAX_DOWNLOAD_URL_TTL_SECONDS as c, fileExtensionOf as d, mapFileMetadata as f, FilesClientErrorUpstream as g, FilesClientErrorCode as h, isFileReference as i, DownloadUrlOptions as j, DeleteFileOptions as k, MIN_DOWNLOAD_URL_TTL_SECONDS as l, FilesClientError as m, FILE_REFERENCE_KIND as n, FilesClient as o, FILES_CLIENT_GRAPHQL_CODES as p, UploadFileInput as q, FileReference as r, FilesClientOptions as s, index_d_exports as t, clampDownloadUrlTtl as u, MAX_FILES_ERROR_SUMMARY_LENGTH as v, sanitizeUpstreamText as w, filesGraphQLError as x, MAX_UPSTREAM_MESSAGE_LENGTH as y, FileStatus as z };
package/dist/index.d.ts CHANGED
@@ -22,7 +22,7 @@ import { a as registerDisposable, i as getRegisteredDisposableCount, n as Shutdo
22
22
  import { BillingPlanTransport, PlanTier, RESOURCE_CAP_DEFAULTS, ResourceCap, ResourceCapDefaults, ResourceCapExceededError, ResourceCapsConfig, ResourceCapsModule, ResourceName, WorkspaceResourceCapScope, configureResourceCaps, getResourceCaps } from "./resource-caps/index.js";
23
23
  import { t as index_d_exports$23 } from "./index-CliOgq6L.js";
24
24
  import { t as index_d_exports$24 } from "./index-BaskMO3C.js";
25
- import { t as index_d_exports$8 } from "./index-8pUSoT85.js";
25
+ import { t as index_d_exports$8 } from "./index-ieSQpD9r.js";
26
26
  import { t as index_d_exports } from "./index-BJwHEzpN.js";
27
27
  import { o as index_d_exports$1 } from "./index-SvWwlTUC.js";
28
28
  import { t as index_d_exports$18 } from "./index-BMIMnp6T.js";
@@ -41,7 +41,7 @@ import { t as index_d_exports$9 } from "./index-XkPephwV.js";
41
41
  import { t as index_d_exports$7 } from "./index-Cl3Xiw1O.js";
42
42
  import { a as index_d_exports$2, c as verifyCaptchaIfEnabled, n as RecaptchaVerifyResult, o as isCaptchaEnabled, s as verifyCaptcha, t as RecaptchaVerifyOptions } from "./index-yBSjMY32.js";
43
43
  import { t as index_d_exports$20 } from "./index-DY3dNhMN.js";
44
- import { B as validateUsername, D as assertRbacCoverage, E as analyzeRbacCoverage, F as validateUserFields, G as lengthInCodePoints, H as NAME_MIN_LENGTH, I as USERNAME_MAX_LENGTH, K as validateName, L as USERNAME_MIN_LENGTH, M as UserFieldKey, N as UserFieldsValidationResult, P as ValidatedUserFields, R as UsernameErrorCode, U as NameErrorCode, V as NAME_MAX_LENGTH, W as NameValidationResult, _ as RbacCoverageError, b as RbacCoverageSource, j as UserFieldError, t as index_d_exports$26, v as RbacCoverageOptions, y as RbacCoverageReport, z as UsernameValidationResult } from "./index-CIgoeobA.js";
44
+ import { B as validateUserFields, C as RbacCoverageOptions, G as validateUsername, H as USERNAME_MIN_LENGTH, I as UserFieldError, J as NameErrorCode, K as NAME_MAX_LENGTH, L as UserFieldKey, M as assertRbacCoverage, R as UserFieldsValidationResult, S as RbacCoverageError, T as RbacCoverageSource, U as UsernameErrorCode, V as USERNAME_MAX_LENGTH, W as UsernameValidationResult, X as lengthInCodePoints, Y as NameValidationResult, Z as validateName, j as analyzeRbacCoverage, q as NAME_MIN_LENGTH, t as index_d_exports$26, w as RbacCoverageReport, z as ValidatedUserFields } from "./index-Bnz5Bqtl.js";
45
45
  import { A as normalizeTemplateKey, C as isSameTemplateKey, D as normalizeProductSlug, E as normalizeGraphQLName, F as templateKeyVariants, I as toCurrentName, L as toLegacyName, M as quotaKeyVariants, N as rbacResourceVariants, O as normalizeQuotaKey, P as readRenamedEnv, S as isSameRbacResource, T as normalizeBillingId, _ as isSameBillingId, a as ProductRename, b as isSameProductSlug, c as billingIdVariants, d as emitProductSlug, f as emitQuotaKey, g as isLegacyName, h as index_d_exports$22, i as PRODUCT_SLUG_ALIASES, j as productSlugVariants, k as normalizeRbacResource, l as emitBillingId, m as emitTemplateKey, n as PRODUCT_RENAMES, o as RENAME_CONCERNS, p as emitRbacResource, r as PRODUCT_RENAME_EMIT, s as RenameConcern, t as EmitGeneration, u as emitName, v as isSameGraphQLName, w as nameVariants, x as isSameQuotaKey, y as isSameName } from "./index-BBqooJ52.js";
46
46
  import { A as assertDsarOrchestrator, C as DSAR_REQUIRE_VERIFIED_SERVICE_TOKEN_ENV, D as DsarOrchestratorRejectionReason, E as DsarOrchestratorOptions, M as isDsarOrchestratorActor, N as resolveDsarCallerIdentity, O as ResolvedDsarCaller, S as DSAR_ALLOWED_ORCHESTRATORS_ENV, T as DsarOrchestratorForbiddenError, j as getAllowedDsarOrchestrators, k as VERIFIED_SERVICE_IDENTITY_HEADER, w as DsarOrchestratorContext, x as DEFAULT_DSAR_ORCHESTRATOR_ID } from "./index-C4hRRihw.js";
47
47
  interface TenantBackendClientConfig {
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import { c as tenant_notifications_exports, r as NotificationsModule, s as Tenan
9
9
  import { c as createRBACDirectiveFromEnv, o as createRBACDirective, s as createRBACDirectiveForLayer, t as RBACModule } from "./rbac-pRCcWVS_.js";
10
10
  import { ActivityModule, ActivityOperationUnsupportedError } from "./activity/index.js";
11
11
  import { a as UsageModule, c as BillingUsageClient } from "./usage-BK7eyP42.js";
12
- import { t as TrackerModule } from "./tracker-CDVYIoCb.js";
12
+ import { t as TrackerModule } from "./tracker-CNF8TRpk.js";
13
13
  import { DatabaseModule } from "./database/index.js";
14
14
  import { j as EventsModule, t as event_queue_exports } from "./event-queue-C58O9KEG.js";
15
15
  import { a as unregisterDisposable, i as registerDisposable, n as disposeAll, r as getRegisteredDisposableCount, t as lifecycle_exports } from "./lifecycle-DeoLSX0U.js";
@@ -24,14 +24,14 @@ import { createInternalClient, createInternalClientForTenant, createInternalClie
24
24
  import { RESOURCE_CAP_DEFAULTS, ResourceCapExceededError, ResourceCapsModule, configureResourceCaps, getResourceCaps } from "./resource-caps/index.js";
25
25
  import { t as sharing_exports } from "./sharing-CflDsSJ-.js";
26
26
  import { t as tags_exports } from "./tags-C316oA9r.js";
27
- import { t as files_exports } from "./files-h5U-D2AF.js";
27
+ import { t as files_exports } from "./files-BISdM0fh.js";
28
28
  import { t as ai_credits_exports } from "./ai-credits-xxfwGpHS.js";
29
29
  import { a as TemporalClient, i as TemporalWorkerManager, n as TemporalWorker, o as TemporalClientFactory, r as TemporalWorkerFactory, t as TemporalModule } from "./temporal-B534uYK8.js";
30
30
  import { t as cache_exports } from "./cache-CU0uLwcS.js";
31
31
  import { t as middleware_exports } from "./middleware-Cq0zFMGp.js";
32
32
  import { t as observability_exports } from "./observability-DBDXipTU.js";
33
33
  import { t as graphql_exports } from "./graphql-Gusog8jG.js";
34
- import { t as prisma_exports } from "./prisma-Bo-C0XUv.js";
34
+ import { t as prisma_exports } from "./prisma-D0f-THMv.js";
35
35
  import { v as utils_exports } from "./utils-DpW6K_iB.js";
36
36
  import { a as getLanguage, c as t, i as createTranslator, o as getLocale, r as i18n_exports, s as hasI18n } from "./i18n-BBMYFd0P.js";
37
37
  import { t as export_exports } from "./export-D3EySJjJ.js";
@@ -44,7 +44,7 @@ import { t as gateway_exports } from "./gateway-B9p8PD82.js";
44
44
  import { t as feature_flags_exports } from "./feature-flags-CP1KRgwD.js";
45
45
  import { i as verifyCaptchaIfEnabled, n as isCaptchaEnabled, r as verifyCaptcha, t as captcha_exports } from "./captcha-BT7yh1YS.js";
46
46
  import { t as platform_exports } from "./platform-DZwczW7v.js";
47
- import { C as NAME_MIN_LENGTH, S as NAME_MAX_LENGTH, T as validateName, b as USERNAME_MIN_LENGTH, f as RbacCoverageError, m as assertRbacCoverage, p as analyzeRbacCoverage, t as validation_exports, v as validateUserFields, w as lengthInCodePoints, x as validateUsername, y as USERNAME_MAX_LENGTH } from "./validation-CPUITdMk.js";
47
+ import { C as USERNAME_MIN_LENGTH, D as lengthInCodePoints, E as NAME_MIN_LENGTH, O as validateName, S as USERNAME_MAX_LENGTH, T as NAME_MAX_LENGTH, _ as assertRbacCoverage, g as analyzeRbacCoverage, h as RbacCoverageError, t as validation_exports, w as validateUsername, x as validateUserFields } from "./validation-bwJzOytZ.js";
48
48
  import { A as rbacResourceVariants, C as normalizeProductSlug, D as productSlugVariants, E as normalizeTemplateKey, M as templateKeyVariants, N as toCurrentName, O as product_alias_exports, P as toLegacyName, S as normalizeGraphQLName, T as normalizeRbacResource, _ as isSameQuotaKey, a as billingIdVariants, b as nameVariants, c as emitProductSlug, d as emitTemplateKey, f as isLegacyName, g as isSameProductSlug, h as isSameName, i as RENAME_CONCERNS, j as readRenamedEnv, k as quotaKeyVariants, l as emitQuotaKey, m as isSameGraphQLName, n as PRODUCT_RENAME_EMIT, o as emitBillingId, p as isSameBillingId, r as PRODUCT_SLUG_ALIASES, s as emitName, t as PRODUCT_RENAMES, u as emitRbacResource, v as isSameRbacResource, w as normalizeQuotaKey, x as normalizeBillingId, y as isSameTemplateKey } from "./product-alias-BPqtskMq.js";
49
49
  import { a as VERIFIED_SERVICE_IDENTITY_HEADER, c as isDsarOrchestratorActor, i as DsarOrchestratorForbiddenError, l as resolveDsarCallerIdentity, n as DSAR_ALLOWED_ORCHESTRATORS_ENV, o as assertDsarOrchestrator, r as DSAR_REQUIRE_VERIFIED_SERVICE_TOKEN_ENV, s as getAllowedDsarOrchestrators, t as DEFAULT_DSAR_ORCHESTRATOR_ID } from "./dsar-orchestrator-BlOSa9A_.js";
50
50
  import { GraphQLClient } from "graphql-request";
@@ -1,6 +1,6 @@
1
- import { C as withSystemScopeSync, S as withSystemScope, T as withWorkspaceContextSync, _ as resetCallerTransactionStateForTests, a as defaultWorkspaceExtensionConfig, b as runOperationWithRlsGuc, c as getScopedWorkspaceContext, d as injectCreateFields, f as injectWhereWorkspaceId, g as requireWorkspaceContext, h as maybeTagConnection, i as configureWorkspaceContextFallback, l as getWorkspaceContext, m as maybeSetRlsGuc, n as addWorkspaceExtension, o as explicitWorkspaceIdFromArgs, p as isSystemScope, r as buildTransactionContextStatement, s as getCallerTransaction, t as WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE, u as getWorkspaceContextFallbackMode, v as resetWorkspaceContextStateForTests, w as withWorkspaceContext, x as setWorkspaceContext, y as runOperationInCallerTransaction } from "../workspace-extension-BcMPoGWr.js";
1
+ import { C as withSystemScopeSync, S as withSystemScope, T as withWorkspaceContextSync, _ as resetCallerTransactionStateForTests, a as defaultWorkspaceExtensionConfig, b as runOperationWithRlsGuc, c as getScopedWorkspaceContext, d as injectCreateFields, f as injectWhereWorkspaceId, g as requireWorkspaceContext, h as maybeTagConnection, i as configureWorkspaceContextFallback, l as getWorkspaceContext, m as maybeSetRlsGuc, n as addWorkspaceExtension, o as explicitWorkspaceIdFromArgs, p as isSystemScope, r as buildTransactionContextStatement, s as getCallerTransaction, t as WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE, u as getWorkspaceContextFallbackMode, v as resetWorkspaceContextStateForTests, w as withWorkspaceContext, x as setWorkspaceContext, y as runOperationInCallerTransaction } from "../workspace-extension-feJYFO9e.js";
2
2
  import { a as createConnectionPool, c as ensureServiceApplicationName, d as isTransientAcquireError, f as normalizeSqlTemplate, i as configurePrismaLogging, l as fingerprintSqlQuery, o as createPrismaAdapter, r as PrismaClientWrapper, s as createPrismaClient, u as installAcquireRetry } from "../middleware-Cd1Z4_DD.js";
3
- import { C as isDatabaseInitialized, D as resolvePoolTuningFromEnv, E as createDatabaseClientFromEnv, S as initializeDatabaseWithConfig, T as createDatabaseClient, _ as testConnection, a as createContextFromSDK, b as getDb, c as toContextJson, d as getModelFields, f as hasModel, g as getDatabaseVersion, h as getDatabaseStats, i as contextMatches, l as extractFieldsFromModel, m as checkDatabaseHealth, n as buildContextWhereClause, o as mergeContext, p as loadGeneratedFields, r as buildContextWhereConditions, s as parseContext, u as getAllModelNames, v as getDatabaseManager, w as resetDatabaseManager, x as initializeDatabase, y as getDatabaseProductName } from "../prisma-Bo-C0XUv.js";
3
+ import { C as isDatabaseInitialized, D as resolvePoolTuningFromEnv, E as createDatabaseClientFromEnv, S as initializeDatabaseWithConfig, T as createDatabaseClient, _ as testConnection, a as createContextFromSDK, b as getDb, c as toContextJson, d as getModelFields, f as hasModel, g as getDatabaseVersion, h as getDatabaseStats, i as contextMatches, l as extractFieldsFromModel, m as checkDatabaseHealth, n as buildContextWhereClause, o as mergeContext, p as loadGeneratedFields, r as buildContextWhereConditions, s as parseContext, u as getAllModelNames, v as getDatabaseManager, w as resetDatabaseManager, x as initializeDatabase, y as getDatabaseProductName } from "../prisma-D0f-THMv.js";
4
4
 
5
5
  export { PrismaClientWrapper, WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE, addWorkspaceExtension, buildContextWhereClause, buildContextWhereConditions, buildTransactionContextStatement, checkDatabaseHealth, configurePrismaLogging, configureWorkspaceContextFallback, contextMatches, createConnectionPool, createContextFromSDK, createDatabaseClient, createDatabaseClientFromEnv, createPrismaAdapter, createPrismaClient, defaultWorkspaceExtensionConfig, ensureServiceApplicationName, explicitWorkspaceIdFromArgs, extractFieldsFromModel, fingerprintSqlQuery, getAllModelNames, getCallerTransaction, getDatabaseManager, getDatabaseProductName, getDatabaseStats, getDatabaseVersion, getDb, getModelFields, getScopedWorkspaceContext, getWorkspaceContext, getWorkspaceContextFallbackMode, hasModel, initializeDatabase, initializeDatabaseWithConfig, injectCreateFields, injectWhereWorkspaceId, installAcquireRetry, isDatabaseInitialized, isSystemScope, isTransientAcquireError, loadGeneratedFields, maybeSetRlsGuc, maybeTagConnection, mergeContext, normalizeSqlTemplate, parseContext, requireWorkspaceContext, resetCallerTransactionStateForTests, resetDatabaseManager, resetWorkspaceContextStateForTests, resolvePoolTuningFromEnv, runOperationInCallerTransaction, runOperationWithRlsGuc, setWorkspaceContext, testConnection, toContextJson, withSystemScope, withSystemScopeSync, withWorkspaceContext, withWorkspaceContextSync };
6
6
  //# sourceMappingURL=index.js.map
@@ -2,7 +2,7 @@ import { t as __exportAll } from "./rolldown-runtime-ad2WFvuA.js";
2
2
  import { a as logger } from "./logger-B6rCpb7D.js";
3
3
  import { a as createConnectionPool, c as ensureServiceApplicationName, d as isTransientAcquireError, f as normalizeSqlTemplate, i as configurePrismaLogging, l as fingerprintSqlQuery, o as createPrismaAdapter, r as PrismaClientWrapper, s as createPrismaClient, t as addGraphExtension, u as installAcquireRetry } from "./middleware-Cd1Z4_DD.js";
4
4
  import { r as getGraphEventEmitter } from "./graph-emitter-D_zQC0MZ.js";
5
- import { C as withSystemScopeSync, S as withSystemScope, T as withWorkspaceContextSync, _ as resetCallerTransactionStateForTests, a as defaultWorkspaceExtensionConfig, b as runOperationWithRlsGuc, c as getScopedWorkspaceContext, d as injectCreateFields, f as injectWhereWorkspaceId, g as requireWorkspaceContext, h as maybeTagConnection, i as configureWorkspaceContextFallback, l as getWorkspaceContext, m as maybeSetRlsGuc, n as addWorkspaceExtension, o as explicitWorkspaceIdFromArgs, p as isSystemScope, r as buildTransactionContextStatement, s as getCallerTransaction, t as WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE, u as getWorkspaceContextFallbackMode, v as resetWorkspaceContextStateForTests, w as withWorkspaceContext, x as setWorkspaceContext, y as runOperationInCallerTransaction } from "./workspace-extension-BcMPoGWr.js";
5
+ import { C as withSystemScopeSync, S as withSystemScope, T as withWorkspaceContextSync, _ as resetCallerTransactionStateForTests, a as defaultWorkspaceExtensionConfig, b as runOperationWithRlsGuc, c as getScopedWorkspaceContext, d as injectCreateFields, f as injectWhereWorkspaceId, g as requireWorkspaceContext, h as maybeTagConnection, i as configureWorkspaceContextFallback, l as getWorkspaceContext, m as maybeSetRlsGuc, n as addWorkspaceExtension, o as explicitWorkspaceIdFromArgs, p as isSystemScope, r as buildTransactionContextStatement, s as getCallerTransaction, t as WORKSPACE_CONTEXT_WARN_MODE_REMOVAL_DATE, u as getWorkspaceContextFallbackMode, v as resetWorkspaceContextStateForTests, w as withWorkspaceContext, x as setWorkspaceContext, y as runOperationInCallerTransaction } from "./workspace-extension-feJYFO9e.js";
6
6
  import { D as productSlugVariants, g as isSameProductSlug } from "./product-alias-BPqtskMq.js";
7
7
  import { createRequire } from "node:module";
8
8
 
@@ -871,4 +871,4 @@ var prisma_exports = /* @__PURE__ */ __exportAll({
871
871
  });
872
872
 
873
873
  export { isDatabaseInitialized as C, resolvePoolTuningFromEnv as D, createDatabaseClientFromEnv as E, initializeDatabaseWithConfig as S, createDatabaseClient as T, testConnection as _, createContextFromSDK as a, getDb as b, toContextJson as c, getModelFields as d, hasModel as f, getDatabaseVersion as g, getDatabaseStats as h, contextMatches as i, extractFieldsFromModel as l, checkDatabaseHealth as m, buildContextWhereClause as n, mergeContext as o, loadGeneratedFields as p, buildContextWhereConditions as r, parseContext as s, prisma_exports as t, getAllModelNames as u, getDatabaseManager as v, resetDatabaseManager as w, initializeDatabase as x, getDatabaseProductName as y };
874
- //# sourceMappingURL=prisma-Bo-C0XUv.js.map
874
+ //# sourceMappingURL=prisma-D0f-THMv.js.map