@tearleads/client-sdk 0.1.256 → 0.1.258
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client/documents/index.d.ts +5 -2
- package/client/documents/index.js +6 -1
- package/client/documents/index.js.map +1 -1
- package/client/index.d.ts +1 -1
- package/client/index.js.map +1 -1
- package/data/blobs/attachments/types.d.ts +4 -2
- package/data/blobs/attachments/types.js.map +1 -1
- package/data/documents/documentContent.d.ts +2 -0
- package/data/documents/documentContent.js +7 -0
- package/data/documents/documentContent.js.map +1 -1
- package/data/documents/shared/manifestBundleReaders.js +1 -1
- package/data/documents/shared/manifestBundleReaders.js.map +1 -1
- package/data/documents/shared/projection/documentCreateSigner.d.ts +19 -0
- package/data/documents/shared/projection/documentCreateSigner.js +49 -0
- package/data/documents/shared/projection/documentCreateSigner.js.map +1 -0
- package/data/documents/shared/projection/index.d.ts +1 -0
- package/data/documents/shared/projection/index.js +1 -0
- package/data/documents/shared/projection/index.js.map +1 -1
- package/data/documents/shared/readers.js +1 -1
- package/data/documents/shared/readers.js.map +1 -1
- package/data/documents/shared/types.d.ts +1 -0
- package/data/documents/shared/types.js.map +1 -1
- package/data/persistence/documents/documentsPersistence.d.ts +1 -1
- package/data/persistence/documents/documentsPersistence.js +4 -1
- package/data/persistence/documents/documentsPersistence.js.map +1 -1
- package/index.d.ts +3 -3
- package/index.js +2 -2
- package/index.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +2 -2
- package/internal/api-client/apiRequestRuntime.js +12 -8
- package/internal/api-client/apiRequestRuntime.js.map +1 -1
- package/internal/api-client/binaryResponseOperationTransport.js +2 -2
- package/internal/api-client/binaryResponseOperationTransport.js.map +1 -1
- package/internal/api-client/client/blobs.d.ts +2 -2
- package/internal/api-client/client/blobs.js +21 -9
- package/internal/api-client/client/blobs.js.map +1 -1
- package/internal/api-client/client/writerProjections.js +2 -1
- package/internal/api-client/client/writerProjections.js.map +1 -1
- package/internal/api-client/operationResponse.js +3 -3
- package/internal/api-client/operationResponse.js.map +1 -1
- package/internal/api-client/routes/blobs/multipartUpload.js +10 -3
- package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
- package/internal/api-client/sessionRefresh.js +6 -1
- package/internal/api-client/sessionRefresh.js.map +1 -1
- package/internal/api-client/sessionResponse.js +5 -2
- package/internal/api-client/sessionResponse.js.map +1 -1
- package/internal/api-client/types.d.ts +2 -0
- package/internal/api-client/types.js.map +1 -1
- package/package.json +1 -1
- package/sqlite/worker.js +4 -4
- package/stores/documents/documentStore/initialization/createSeededDocument.d.ts +16 -0
- package/stores/documents/documentStore/initialization/createSeededDocument.js +119 -0
- package/stores/documents/documentStore/initialization/createSeededDocument.js.map +1 -0
- package/stores/documents/documentStore/initialization/initialContent.js.map +1 -1
- package/stores/documents/documentStore/rows/rowAttribution.js.map +1 -1
- package/stores/documents/documentStore/state.js +3 -1
- package/stores/documents/documentStore/state.js.map +1 -1
- package/stores/documents/documentStore/sync/syncShared.js +3 -2
- package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
- package/stores/documents/index.d.ts +1 -0
- package/stores/documents/index.js +1 -0
- package/stores/documents/index.js.map +1 -1
- package/stores/documents/types.d.ts +1 -0
- package/stores/documents/types.js.map +1 -1
- package/workflows/blobs/upload/index.d.ts +1 -1
- package/workflows/blobs/upload/index.js +36 -18
- package/workflows/blobs/upload/index.js.map +1 -1
- package/workflows/blobs/upload/multipartStageResolution.js +12 -2
- package/workflows/blobs/upload/multipartStageResolution.js.map +1 -1
- package/workflows/blobs/upload/multipartUpload.js +10 -2
- package/workflows/blobs/upload/multipartUpload.js.map +1 -1
- package/workflows/container-contents/documentDiscovery/documentDiscoveryTypes.d.ts +160 -0
- package/workflows/container-contents/documentQueries/index.d.ts +1 -1
- package/workflows/container-contents/documentQueries/index.js +2 -2
- package/workflows/container-contents/documentQueries/index.js.map +1 -1
- package/workflows/container-contents/index.d.ts +1 -0
- package/workflows/container-contents/index.js +1 -0
- package/workflows/container-contents/index.js.map +1 -1
- package/workflows/container-contents/tombstones/documentTombstoneEvidence.d.ts +42 -0
- package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +41 -17
- package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
- package/workflows/documents/create/createAdoption.js +2 -50
- package/workflows/documents/create/createAdoption.js.map +1 -1
- package/workflows/documents/create/createResponse.js +12 -1
- package/workflows/documents/create/createResponse.js.map +1 -1
- package/workflows/documents/create/createSubmission.js +14 -0
- package/workflows/documents/create/createSubmission.js.map +1 -0
- package/workflows/documents/create/index.d.ts +3 -14
- package/workflows/documents/create/index.js +76 -67
- package/workflows/documents/create/index.js.map +1 -1
- package/workflows/documents/create/remoteDocumentCreateRequest.d.ts +16 -15
- package/workflows/documents/create/remoteDocumentCreateRequest.js.map +1 -1
- package/workflows/documents/purge/absentDocumentPurge.d.ts +3 -0
- package/workflows/documents/purge/absentDocumentPurge.js +23 -0
- package/workflows/documents/purge/absentDocumentPurge.js.map +1 -0
- package/workflows/documents/purge/index.d.ts +1 -0
- package/workflows/documents/purge/index.js +1 -0
- package/workflows/documents/purge/index.js.map +1 -1
- package/workflows/documents/remote/remoteDocumentService.d.ts +2 -2
- package/workflows/documents/remote/remoteDocumentService.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"multipartUpload.js","sourceRoot":"","sources":["multipartUpload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,yBAAyB,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EACL,yCAAyC,EACzC,kBAAkB,EAClB,oBAAoB,EACpB,qCAAqC,GACtC,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EACL,6BAA6B,GAG9B,MAAM,4BAA4B,CAAC;AAIpC,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAI5D,SAAS,WAAW,CAAC,SAA6B,EAAE,IAAY;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S,oBAAoB,CAC3B,SAA6B,EAC7B,IAAY,EACZ,UAAkB,EAClB,MAAqB;IAErB,SAAS,CAAC,aAAa,CAAC;QACtB,IAAI,EAAE,SAAS;QACf,MAAM,EAAE,yCAAyC,CAAC,MAAM;QACxD,IAAI;QACJ,MAAM;QACN,UAAU,EAAE,EAAE;QACd,OAAO,EACL,MAAM,KAAK,GAAG;YACZ,CAAC,CAAC,kBAAkB,UAAU,gEAAgE;YAC9F,CAAC,CAAC,kBAAkB,UAAU,yBAAyB,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,MAAM,GAAG,EAAE;KACxG,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { md5 } from \"@noble/hashes/legacy.js\";\nimport { bytesToHex } from \"@tearleads/crypto\";\nimport {\n authorizeMultipartBlobPartUploadOperation,\n blobWireHeaderKeys,\n operationRequestPath,\n uploadMultipartBlobPartBytesOperation,\n} from \"@tearleads/validators/operation\";\nimport type { UploadMultipartBlobPartResponse } from \"@tearleads/validators/response\";\nimport {\n MAX_MULTIPART_BLOB_PART_BYTES,\n type MultipartBlobPartDescriptor,\n type MultipartBlobPartUploadSource,\n} from \"@tearleads/validators/util\";\nimport type { OperationTransport } from \"../../operationTransportFactory\";\nimport type { RequestResultOptions } from \"../../types\";\nimport type { UploadMultipartBlobPartBytesRequest } from \"./get\";\nimport { storageFetchOptions } from \"./storageFetchOptions\";\n\ntype UploadFetch = (url: string, init: RequestInit) => Promise<Response>;\n\nfunction invalidPart(transport: OperationTransport, path: string) {\n transport.reportFailure({\n kind: \"shape\",\n method: authorizeMultipartBlobPartUploadOperation.method,\n path,\n status: null,\n statusText: \"\",\n message: \"Multipart part bytes do not match the declared length or SHA-256\",\n });\n return null;\n}\n\nasync function retryStorageStatus(status: number, attempt: number) {\n if (status === 403) return true;\n const transient = status === 429 || (status >= 500 && status <= 599);\n if (transient && attempt === 0) {\n await new Promise<void>((resolve) => setTimeout(resolve, 250));\n }\n return transient;\n}\n\nfunction contentMd5Base64(bytes: Uint8Array): string {\n return btoa(String.fromCharCode(...md5(bytes)));\n}\n\n/**\n * Describe an encrypted part the way a stage initiation lists the parts it\n * will send first: number, exact length, and the Content-MD5 a signed upload\n * URL binds.\n */\nexport function describeMultipartBlobPart(\n partNumber: number,\n encryptedBytes: Uint8Array,\n): MultipartBlobPartDescriptor {\n return {\n byteLength: encryptedBytes.byteLength,\n contentMd5: contentMd5Base64(encryptedBytes),\n partNumber,\n };\n}\n\nasync function preparePart(input: UploadMultipartBlobPartBytesRequest) {\n // File snapshots mutable buffers and preserves ciphertext across Capacitor's\n // native HTTP bridge. Uint8Array is UTF-8 decoded there; a plain Blob becomes\n // JSON. File's base64 bridge path is byte-for-byte, including non-UTF-8 data.\n const file =\n input.encryptedBytes instanceof File\n ? input.encryptedBytes\n : new File([input.encryptedBytes], \"encrypted-blob-part\", {\n type: \"application/octet-stream\",\n });\n if (\n file.size !== input.byteLength ||\n file.size < 1 ||\n file.size > MAX_MULTIPART_BLOB_PART_BYTES\n ) {\n throw new TypeError(\"Invalid multipart part byte length\");\n }\n const bytes = await file.arrayBuffer();\n if (\n bytesToHex(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", bytes))) !==\n input.sha256\n ) {\n throw new TypeError(\"Multipart part SHA-256 does not match its bytes\");\n }\n return { file, contentMd5: contentMd5Base64(new Uint8Array(bytes)) };\n}\n\ninterface PartUploadContext {\n readonly contentMd5: string;\n readonly input: UploadMultipartBlobPartBytesRequest;\n readonly options: RequestResultOptions;\n readonly partNumber: number;\n readonly path: string;\n readonly stageId: string;\n readonly transport: OperationTransport;\n}\n\n// Sign just in time for this part. The returned descriptor must name exactly\n// the part, upload, length, and checksum that were requested.\nasync function authorizePart(\n context: PartUploadContext,\n): Promise<MultipartBlobPartUploadSource | null> {\n const operation = authorizeMultipartBlobPartUploadOperation;\n const { input, partNumber, stageId } = context;\n const result = await context.transport.requestResult(\n operation,\n {\n params: { stageId, partNumber },\n body: {\n byteLength: input.byteLength,\n contentMd5: context.contentMd5,\n uploadId: input.uploadId,\n },\n },\n context.options,\n );\n if (!result.ok) return null;\n const descriptor = result.data;\n if (\n descriptor.stageId !== stageId ||\n descriptor.uploadId !== input.uploadId ||\n descriptor.partNumber !== partNumber ||\n descriptor.byteLength !== input.byteLength ||\n descriptor.contentMd5 !== context.contentMd5\n ) {\n context.transport.reportFailure({\n kind: \"shape\",\n method: operation.method,\n path: context.path,\n status: 200,\n statusText: \"\",\n message: \"Multipart upload descriptor does not match its part\",\n });\n return null;\n }\n return descriptor.source;\n}\n\n// Parts can wait behind other transfers in the shared pool. An issued URL that\n// is about to lapse would only spend this part's retry on a certain 403, so\n// authorize afresh instead; a skewed clock errs toward authorizing.\nconst ISSUED_URL_MIN_REMAINING_MS = 30_000;\n\nfunction isUsableIssuedSource(\n source: MultipartBlobPartUploadSource | undefined,\n): source is MultipartBlobPartUploadSource {\n return (\n source !== undefined &&\n (source.kind === \"api\" ||\n Date.parse(source.expiresAt) - Date.now() > ISSUED_URL_MIN_REMAINING_MS)\n );\n}\n\n// A capability path for memory/custom stores; S3/R2 never proxy parts.\nfunction uploadThroughApi(context: PartUploadContext, file: File) {\n const { input } = context;\n return context.transport.requestBinaryRequest(\n uploadMultipartBlobPartBytesOperation,\n {\n params: { stageId: context.stageId, partNumber: context.partNumber },\n body: input.encryptedBytes,\n headers: {\n [blobWireHeaderKeys.partByteLength]: input.byteLength.toString(),\n [blobWireHeaderKeys.partSha256]: input.sha256,\n [blobWireHeaderKeys.partUploadId]: input.uploadId,\n },\n },\n { ...context.options, encodeBody: () => file },\n );\n}\n\nfunction firstAttemptSource(\n attempt: number,\n source: MultipartBlobPartUploadSource | undefined,\n): MultipartBlobPartUploadSource | null {\n return attempt === 0 && isUsableIssuedSource(source) ? source : null;\n}\n\nexport async function uploadMultipartBlobPartBytes(\n transport: OperationTransport,\n stageId: string,\n partNumber: number,\n input: UploadMultipartBlobPartBytesRequest,\n uploadFetch: UploadFetch = (url, init) => fetch(url, init),\n options: RequestResultOptions = {},\n): Promise<UploadMultipartBlobPartResponse | null> {\n if (options.signal?.aborted) return null;\n const path = operationRequestPath(authorizeMultipartBlobPartUploadOperation, {\n stageId,\n partNumber,\n });\n const prepared = await preparePart(input).catch(() =>\n invalidPart(transport, path),\n );\n if (!prepared) return null;\n const { file, contentMd5 } = prepared;\n const context: PartUploadContext = {\n contentMd5,\n input,\n options,\n partNumber,\n path,\n stageId,\n transport,\n };\n let status: number | null = null;\n // The first attempt uses the source the stage initiation issued, if any. A\n // network failure may be an expired URL hidden by R2 CORS, or a lost success\n // response; reauthorize once and send the same immutable bytes to the same\n // part number.\n for (let attempt = 0; attempt < 2; attempt += 1) {\n if (options.signal?.aborted) return null;\n const source =\n firstAttemptSource(attempt, input.source) ??\n (await authorizePart(context));\n if (!source || options.signal?.aborted) return null;\n if (source.kind === \"api\") return uploadThroughApi(context, file);\n const outcome = await putStoragePart(\n context,\n file,\n source.url,\n uploadFetch,\n attempt,\n );\n if (outcome.kind === \"uploaded\") return outcome.response;\n status = outcome.status;\n if (!outcome.retry) break;\n }\n reportStorageFailureUnlessAborted(context, status);\n return null;\n}\n\nfunction reportStorageFailureUnlessAborted(\n context: PartUploadContext,\n status: number | null,\n): void {\n if (context.options.signal?.aborted) return;\n reportStorageFailure(\n context.transport,\n context.path,\n context.partNumber,\n status,\n );\n}\n\ntype StoragePartAttempt =\n | {\n readonly kind: \"uploaded\";\n readonly response: UploadMultipartBlobPartResponse;\n }\n | {\n readonly kind: \"failed\";\n readonly retry: boolean;\n readonly status: number | null;\n };\n\nasync function putStoragePart(\n context: PartUploadContext,\n file: File,\n url: string,\n uploadFetch: UploadFetch,\n attempt: number,\n): Promise<StoragePartAttempt> {\n const { input, partNumber } = context;\n try {\n const response = await uploadFetch(url, {\n method: \"PUT\",\n body: file,\n headers: {\n \"Content-Type\": \"application/octet-stream\",\n \"Content-MD5\": context.contentMd5,\n },\n ...storageFetchOptions(context.options),\n });\n const status = response.status;\n const etag = response.headers.get(\"ETag\")?.trim();\n await response.body?.cancel().catch(() => {});\n if (status === 200 && etag) {\n return {\n kind: \"uploaded\",\n response: {\n stageId: context.stageId,\n uploadId: input.uploadId,\n part: { byteLength: input.byteLength, partNumber, etag },\n },\n };\n }\n const retry = await retryStorageStatus(status, attempt);\n return { kind: \"failed\", retry, status };\n } catch {\n // Never expose a provider exception or body: it may contain the bearer URL.\n return { kind: \"failed\", retry: true, status: null };\n }\n}\n\nfunction reportStorageFailure(\n transport: OperationTransport,\n path: string,\n partNumber: number,\n status: number | null,\n) {\n transport.reportFailure({\n kind: \"storage\",\n method: authorizeMultipartBlobPartUploadOperation.method,\n path,\n status,\n statusText: \"\",\n message:\n status === 200\n ? `Multipart part ${partNumber} storage response is missing ETag; check storage CORS exposure`\n : `Multipart part ${partNumber} storage upload failed${status === null ? \"\" : ` (HTTP ${status})`}`,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"multipartUpload.js","sourceRoot":"","sources":["multipartUpload.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,yBAAyB,CAAC;AAC9C,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EACL,yCAAyC,EACzC,kBAAkB,EAClB,oBAAoB,EACpB,qCAAqC,GACtC,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EACL,6BAA6B,GAG9B,MAAM,4BAA4B,CAAC;AAIpC,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAI5D,SAAS,WAAW,CAAC,SAA6B,EAAE,IAAY;IAC9D,SAAS,CAAC,aAAa,CAAC;QACtB,IAAI,EAAE,OAAO;QACb,MAAM,EAAE,yCAAyC,CAAC,MAAM;QACxD,IAAI;QACJ,MAAM,EAAE,IAAI;QACZ,UAAU,EAAE,EAAE;QACd,OAAO,EAAE,kEAAkE;KAC5E,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACd,CAAC;AAED,K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EAA4E;QAC5E,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;IACvD,CAAC;AACH,CAAC;AAED,SAAS,oBAAoB,CAC3B,SAA6B,EAC7B,IAAY,EACZ,UAAkB,EAClB,MAAqB;IAErB,SAAS,CAAC,aAAa,CAAC;QACtB,IAAI,EAAE,SAAS;QACf,MAAM,EAAE,yCAAyC,CAAC,MAAM;QACxD,IAAI;QACJ,MAAM;QACN,UAAU,EAAE,EAAE;QACd,OAAO,EACL,MAAM,KAAK,GAAG;YACZ,CAAC,CAAC,kBAAkB,UAAU,gEAAgE;YAC9F,CAAC,CAAC,kBAAkB,UAAU,yBAAyB,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,MAAM,GAAG,EAAE;KACxG,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { md5 } from \"@noble/hashes/legacy.js\";\nimport { bytesToHex } from \"@tearleads/crypto\";\nimport {\n authorizeMultipartBlobPartUploadOperation,\n blobWireHeaderKeys,\n operationRequestPath,\n uploadMultipartBlobPartBytesOperation,\n} from \"@tearleads/validators/operation\";\nimport type { UploadMultipartBlobPartResponse } from \"@tearleads/validators/response\";\nimport {\n MAX_MULTIPART_BLOB_PART_BYTES,\n type MultipartBlobPartDescriptor,\n type MultipartBlobPartUploadSource,\n} from \"@tearleads/validators/util\";\nimport type { OperationTransport } from \"../../operationTransportFactory\";\nimport type { RequestResultOptions } from \"../../types\";\nimport type { UploadMultipartBlobPartBytesRequest } from \"./get\";\nimport { storageFetchOptions } from \"./storageFetchOptions\";\n\ntype UploadFetch = (url: string, init: RequestInit) => Promise<Response>;\n\nfunction invalidPart(transport: OperationTransport, path: string) {\n transport.reportFailure({\n kind: \"shape\",\n method: authorizeMultipartBlobPartUploadOperation.method,\n path,\n status: null,\n statusText: \"\",\n message: \"Multipart part bytes do not match the declared length or SHA-256\",\n });\n return null;\n}\n\nasync function retryStorageStatus(status: number, attempt: number) {\n if (status === 403) return true;\n const transient = status === 429 || (status >= 500 && status <= 599);\n if (transient && attempt === 0) {\n await new Promise<void>((resolve) => setTimeout(resolve, 250));\n }\n return transient;\n}\n\nfunction contentMd5Base64(bytes: Uint8Array): string {\n return btoa(String.fromCharCode(...md5(bytes)));\n}\n\n/**\n * Describe an encrypted part the way a stage initiation lists the parts it\n * will send first: number, exact length, and the Content-MD5 a signed upload\n * URL binds.\n */\nexport function describeMultipartBlobPart(\n partNumber: number,\n encryptedBytes: Uint8Array,\n): MultipartBlobPartDescriptor {\n return {\n byteLength: encryptedBytes.byteLength,\n contentMd5: contentMd5Base64(encryptedBytes),\n partNumber,\n };\n}\n\nasync function preparePart(input: UploadMultipartBlobPartBytesRequest) {\n // File snapshots mutable buffers and preserves ciphertext across Capacitor's\n // native HTTP bridge. Uint8Array is UTF-8 decoded there; a plain Blob becomes\n // JSON. File's base64 bridge path is byte-for-byte, including non-UTF-8 data.\n const file =\n input.encryptedBytes instanceof File\n ? input.encryptedBytes\n : new File([input.encryptedBytes], \"encrypted-blob-part\", {\n type: \"application/octet-stream\",\n });\n if (\n file.size !== input.byteLength ||\n file.size < 1 ||\n file.size > MAX_MULTIPART_BLOB_PART_BYTES\n ) {\n throw new TypeError(\"Invalid multipart part byte length\");\n }\n const bytes = await file.arrayBuffer();\n if (\n bytesToHex(new Uint8Array(await crypto.subtle.digest(\"SHA-256\", bytes))) !==\n input.sha256\n ) {\n throw new TypeError(\"Multipart part SHA-256 does not match its bytes\");\n }\n return { file, contentMd5: contentMd5Base64(new Uint8Array(bytes)) };\n}\n\ninterface PartUploadContext {\n readonly contentMd5: string;\n readonly input: UploadMultipartBlobPartBytesRequest;\n readonly options: RequestResultOptions;\n readonly partNumber: number;\n readonly path: string;\n readonly stageId: string;\n readonly transport: OperationTransport;\n}\n\n// Sign just in time for this part. The returned descriptor must name exactly\n// the part, upload, length, and checksum that were requested.\nasync function authorizePart(\n context: PartUploadContext,\n): Promise<MultipartBlobPartUploadSource | null> {\n const operation = authorizeMultipartBlobPartUploadOperation;\n const { input, partNumber, stageId } = context;\n const result = await context.transport.requestResult(\n operation,\n {\n params: { stageId, partNumber },\n body: {\n byteLength: input.byteLength,\n contentMd5: context.contentMd5,\n uploadId: input.uploadId,\n },\n },\n context.options,\n );\n if (!result.ok) return null;\n const descriptor = result.data;\n if (\n descriptor.stageId !== stageId ||\n descriptor.uploadId !== input.uploadId ||\n descriptor.partNumber !== partNumber ||\n descriptor.byteLength !== input.byteLength ||\n descriptor.contentMd5 !== context.contentMd5\n ) {\n context.transport.reportFailure({\n kind: \"shape\",\n method: operation.method,\n path: context.path,\n status: 200,\n statusText: \"\",\n message: \"Multipart upload descriptor does not match its part\",\n });\n return null;\n }\n return descriptor.source;\n}\n\n// Parts can wait behind other transfers in the shared pool. An issued URL that\n// is about to lapse would only spend this part's retry on a certain 403, so\n// authorize afresh instead; a skewed clock errs toward authorizing.\nconst ISSUED_URL_MIN_REMAINING_MS = 30_000;\n\nfunction isUsableIssuedSource(\n source: MultipartBlobPartUploadSource | undefined,\n): source is MultipartBlobPartUploadSource {\n return (\n source !== undefined &&\n (source.kind === \"api\" ||\n Date.parse(source.expiresAt) - Date.now() > ISSUED_URL_MIN_REMAINING_MS)\n );\n}\n\n// A capability path for memory/custom stores; S3/R2 never proxy parts.\nfunction uploadThroughApi(context: PartUploadContext, file: File) {\n const { input } = context;\n return context.transport.requestBinaryRequest(\n uploadMultipartBlobPartBytesOperation,\n {\n params: { stageId: context.stageId, partNumber: context.partNumber },\n body: input.encryptedBytes,\n headers: {\n [blobWireHeaderKeys.partByteLength]: input.byteLength.toString(),\n [blobWireHeaderKeys.partSha256]: input.sha256,\n [blobWireHeaderKeys.partUploadId]: input.uploadId,\n },\n },\n { ...context.options, encodeBody: () => file },\n );\n}\n\nfunction firstAttemptSource(\n attempt: number,\n source: MultipartBlobPartUploadSource | undefined,\n): MultipartBlobPartUploadSource | null {\n return attempt === 0 && isUsableIssuedSource(source) ? source : null;\n}\n\nexport async function uploadMultipartBlobPartBytes(\n transport: OperationTransport,\n stageId: string,\n partNumber: number,\n input: UploadMultipartBlobPartBytesRequest,\n uploadFetch: UploadFetch = (url, init) => fetch(url, init),\n options: RequestResultOptions = {},\n): Promise<UploadMultipartBlobPartResponse | null> {\n const current = () =>\n !options.signal?.aborted && options.stillCurrent?.() !== false;\n if (!current()) return null;\n const path = operationRequestPath(authorizeMultipartBlobPartUploadOperation, {\n stageId,\n partNumber,\n });\n const prepared = await preparePart(input).catch(() =>\n invalidPart(transport, path),\n );\n if (!prepared) return null;\n const { file, contentMd5 } = prepared;\n const context: PartUploadContext = {\n contentMd5,\n input,\n options,\n partNumber,\n path,\n stageId,\n transport,\n };\n return transferPreparedPart(context, file, uploadFetch, current);\n}\n\nasync function transferPreparedPart(\n context: PartUploadContext,\n file: File,\n uploadFetch: UploadFetch,\n current: () => boolean,\n): Promise<UploadMultipartBlobPartResponse | null> {\n const { input } = context;\n let status: number | null = null;\n // The first attempt uses the source the stage initiation issued, if any. A\n // network failure may be an expired URL hidden by R2 CORS, or a lost success\n // response; reauthorize once and send the same immutable bytes to the same\n // part number.\n for (let attempt = 0; attempt < 2; attempt += 1) {\n if (!current()) return null;\n const source =\n firstAttemptSource(attempt, input.source) ??\n (await authorizePart(context));\n if (!source || !current()) return null;\n if (source.kind === \"api\") return uploadThroughApi(context, file);\n const outcome = await putStoragePart(\n context,\n file,\n source.url,\n uploadFetch,\n attempt,\n );\n if (!current()) return null;\n if (outcome.kind === \"uploaded\") return outcome.response;\n status = outcome.status;\n if (!outcome.retry) break;\n }\n reportStorageFailureUnlessAborted(context, status);\n return null;\n}\n\nfunction reportStorageFailureUnlessAborted(\n context: PartUploadContext,\n status: number | null,\n): void {\n if (context.options.signal?.aborted) return;\n reportStorageFailure(\n context.transport,\n context.path,\n context.partNumber,\n status,\n );\n}\n\ntype StoragePartAttempt =\n | {\n readonly kind: \"uploaded\";\n readonly response: UploadMultipartBlobPartResponse;\n }\n | {\n readonly kind: \"failed\";\n readonly retry: boolean;\n readonly status: number | null;\n };\n\nasync function putStoragePart(\n context: PartUploadContext,\n file: File,\n url: string,\n uploadFetch: UploadFetch,\n attempt: number,\n): Promise<StoragePartAttempt> {\n const { input, partNumber } = context;\n try {\n const response = await uploadFetch(url, {\n method: \"PUT\",\n body: file,\n headers: {\n \"Content-Type\": \"application/octet-stream\",\n \"Content-MD5\": context.contentMd5,\n },\n ...storageFetchOptions(context.options),\n });\n const status = response.status;\n const etag = response.headers.get(\"ETag\")?.trim();\n await response.body?.cancel().catch(() => {});\n if (status === 200 && etag) {\n return {\n kind: \"uploaded\",\n response: {\n stageId: context.stageId,\n uploadId: input.uploadId,\n part: { byteLength: input.byteLength, partNumber, etag },\n },\n };\n }\n const retry = await retryStorageStatus(status, attempt);\n return { kind: \"failed\", retry, status };\n } catch {\n // Never expose a provider exception or body: it may contain the bearer URL.\n return { kind: \"failed\", retry: true, status: null };\n }\n}\n\nfunction reportStorageFailure(\n transport: OperationTransport,\n path: string,\n partNumber: number,\n status: number | null,\n) {\n transport.reportFailure({\n kind: \"storage\",\n method: authorizeMultipartBlobPartUploadOperation.method,\n path,\n status,\n statusText: \"\",\n message:\n status === 200\n ? `Multipart part ${partNumber} storage response is missing ETag; check storage CORS exposure`\n : `Multipart part ${partNumber} storage upload failed${status === null ? \"\" : ` (HTTP ${status})`}`,\n });\n}\n"]}
|
|
@@ -45,6 +45,9 @@ export function renewalUnlessAborted(renewal, signal) {
|
|
|
45
45
|
});
|
|
46
46
|
});
|
|
47
47
|
}
|
|
48
|
+
function shouldReportRenewalError(options) {
|
|
49
|
+
return options.stillCurrent?.() !== false && (options.reportErrors ?? true);
|
|
50
|
+
}
|
|
48
51
|
/**
|
|
49
52
|
* Decides whether a failed request can be replayed after session renewal.
|
|
50
53
|
* Identity-integrity failures are terminal and must retain their typed error.
|
|
@@ -71,10 +74,12 @@ export async function shouldRetryAfterSessionExpired(input) {
|
|
|
71
74
|
if (error instanceof KeyingVerificationError) {
|
|
72
75
|
throw error;
|
|
73
76
|
}
|
|
74
|
-
if (input.options
|
|
77
|
+
if (shouldReportRenewalError(input.options)) {
|
|
75
78
|
input.reportError(`Session refresh failed: ${errorMessage(error)}`);
|
|
76
79
|
}
|
|
77
80
|
}
|
|
81
|
+
if (input.options.stillCurrent?.() === false)
|
|
82
|
+
return false;
|
|
78
83
|
const refreshedToken = input.getCurrentAuthToken();
|
|
79
84
|
const renewed = Boolean(refreshed &&
|
|
80
85
|
refreshedToken &&
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessionRefresh.js","sourceRoot":"","sources":["sessionRefresh.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,YAAY,EACZ,yBAAyB,EACzB,uBAAuB,GACxB,MAAM,oBAAoB,CAAC;AAgB5B;;;GAGG;AACH,SAAS,iBAAiB,CACxB,KAA0B,EAC1B,SAAiB;IAEjB,MAAM,gBAAgB,GAAG,KAAK,CAAC,mBAAmB,EAAE,CAAC;IACrD,IAAI,gBAAgB,KAAK,SAAS;QAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC7D,MAAM,OAAO,GACX,gBAAgB,KAAK,IAAI;QACzB,KAAK,CAAC,qBAAqB,CAAC,SAAS,EAAE,gBAAgB,CAAC,CAAC;IAC3D,IAAI,OAAO,EAAE,CAAC;QACZ,KAAK,CAAC,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC;QACnC,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,OAAO,GAAG,KAAK,CAAC,qBAAqB,CAAC,SAAS,CAAC,CAAC;IACvD,IAAI,CAAC,gBAAgB,IAAI,CAAC,OAAO;QAAE,OAAO,KAAK,CAAC;IAChD,OAAO,EAAE,OAAO,EAAE,CAAC;AACrB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,oBAAoB,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,CAAC,CAAC;QACtE,CAAC;IACH,CAAC;IAED,IAAI,KAAK,CAAC,OAAO,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,KAAK,CAAC;IAC3D,MAAM,cAAc,GAAG,KAAK,CAAC,mBAAmB,EAAE,CAAC;IACnD,MAAM,OAAO,GAAG,OAAO,CACrB,SAAS;QACP,cAAc;QACd,KAAK,CAAC,qBAAqB,CAAC,KAAK,CAAC,SAAS,EAAE,cAAc,CAAC,CAC/D,CAAC;IACF,IAAI,OAAO;QAAE,KAAK,CAAC,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC;IAChD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n errorMessage,\n isRefreshableSessionError,\n isReplayableRequestBody,\n} from \"./requestInternals\";\nimport type { RequestBody, RequestResultOptions } from \"./types\";\n\ninterface SessionRefreshInput {\n readonly authToken: string | null;\n readonly body: RequestBody | undefined;\n readonly code: string | null;\n readonly getCurrentAuthToken: () => string | null;\n readonly isKnownSessionRenewal: (from: string, to: string) => boolean;\n readonly options: RequestResultOptions;\n readonly pendingSessionRenewal: (from: string) => Promise<boolean> | null;\n readonly refreshSession: () => boolean | Promise<boolean>;\n readonly reportError: (message: string) => void;\n readonly responseStatus: number;\n}\n\n/**\n * Checks for a renewal that another request already started or finished: a\n * boolean is the final answer, otherwise `pending` (null when none) is awaited.\n */\nfunction concurrentRenewal(\n input: SessionRefreshInput,\n authToken: string,\n): boolean | { readonly pending: Promise<boolean> | null } {\n const currentAuthToken = input.getCurrentAuthToken();\n if (currentAuthToken === authToken) return { pending: null };\n const renewed =\n currentAuthToken !== null &&\n input.isKnownSessionRenewal(authToken, currentAuthToken);\n if (renewed) {\n input.options.onSessionRenewed?.();\n return true;\n }\n const pending = input.pendingSessionRenewal(authToken);\n if (!currentAuthToken || !pending) return false;\n return { pending };\n}\n\n/**\n * Ends a request's wait for a renewal when its signal aborts. Only the wait\n * ends: the renewal is shared with other requests and keeps running, and a\n * rejection it settles with later is still delivered to them.\n */\nexport function renewalUnlessAborted(\n renewal: boolean | Promise<boolean>,\n signal: AbortSignal | undefined,\n): Promise<boolean> {\n if (!signal) return Promise.resolve(renewal);\n // Starting the renewal can abort the signal before a listener exists. The\n // renewal is still consumed, so a later rejection is never unhandled.\n if (signal.aborted) {\n Promise.resolve(renewal).catch(() => undefined);\n return Promise.resolve(false);\n }\n return new Promise<boolean>((resolve, reject) => {\n const abandon = () => resolve(false);\n signal.addEventListener(\"abort\", abandon, { once: true });\n Promise.resolve(renewal).then(\n (renewed) => {\n signal.removeEventListener(\"abort\", abandon);\n resolve(renewed);\n },\n (error: unknown) => {\n signal.removeEventListener(\"abort\", abandon);\n reject(error);\n },\n );\n });\n}\n\nfunction shouldReportRenewalError(options: RequestResultOptions) {\n return options.stillCurrent?.() !== false && (options.reportErrors ?? true);\n}\n\n/**\n * Decides whether a failed request can be replayed after session renewal.\n * Identity-integrity failures are terminal and must retain their typed error.\n */\nexport async function shouldRetryAfterSessionExpired(\n input: SessionRefreshInput,\n): Promise<boolean> {\n if (\n input.options.retryOnSessionExpired === false ||\n !input.authToken ||\n !isReplayableRequestBody(input.body) ||\n !isRefreshableSessionError(input.responseStatus, input.code)\n ) {\n return false;\n }\n\n const concurrent = concurrentRenewal(input, input.authToken);\n if (typeof concurrent === \"boolean\") return concurrent;\n const pending = concurrent.pending;\n // An aborted request has no use for a renewal and must not start one.\n if (input.options.signal?.aborted) return false;\n\n let refreshed = false;\n try {\n refreshed = await renewalUnlessAborted(\n pending ?? input.refreshSession(),\n input.options.signal,\n );\n } catch (error: unknown) {\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n if (shouldReportRenewalError(input.options)) {\n input.reportError(`Session refresh failed: ${errorMessage(error)}`);\n }\n }\n\n if (input.options.stillCurrent?.() === false) return false;\n const refreshedToken = input.getCurrentAuthToken();\n const renewed = Boolean(\n refreshed &&\n refreshedToken &&\n input.isKnownSessionRenewal(input.authToken, refreshedToken),\n );\n if (renewed) input.options.onSessionRenewed?.();\n return renewed;\n}\n"]}
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { errorMessage } from "./requestInternals.js";
|
|
2
2
|
import { responseBodyFailure } from "./responseBodyFailure.js";
|
|
3
|
+
export function requestRetired(session, options) {
|
|
4
|
+
return session?.aborted || options?.stillCurrent?.() === false;
|
|
5
|
+
}
|
|
3
6
|
/** A retired request cannot overwrite the active session's failure cache. */
|
|
4
7
|
export function retiredRequest(method, path) {
|
|
5
8
|
return {
|
|
@@ -17,12 +20,12 @@ export function retiredRequest(method, path) {
|
|
|
17
20
|
export async function readSessionJson(request, response, method, path, options, session) {
|
|
18
21
|
try {
|
|
19
22
|
const data = await response.json();
|
|
20
|
-
if (session
|
|
23
|
+
if (requestRetired(session, options))
|
|
21
24
|
return retiredRequest(method, path);
|
|
22
25
|
return { ok: true, data };
|
|
23
26
|
}
|
|
24
27
|
catch (error) {
|
|
25
|
-
if (session
|
|
28
|
+
if (requestRetired(session, options))
|
|
26
29
|
return retiredRequest(method, path);
|
|
27
30
|
const failure = responseBodyFailure(error, errorMessage(error), options.signal?.aborted === true);
|
|
28
31
|
return request.reportFailure({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessionResponse.js","sourceRoot":"","sources":["sessionResponse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAS5D,6EAA6E;AAC7E,MAAM,UAAU,cAAc,CAC5B,MAAkB,EAClB,IAAY;IAEZ,OAAO;QACL,IAAI,EAAE,iBAAiB;QACvB,IAAI,EAAE,WAAW;QACjB,OAAO,EAAE,GAAG,MAAM,IAAI,IAAI,iBAAiB;QAC3C,MAAM;QACN,EAAE,EAAE,KAAK;QACT,IAAI;QACJ,MAAM,EAAE,GAAG,EAAE,GAAE,CAA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Ac,CAAC,OAAO,EAAE,OAAO,CAAC;YAAE,OAAO,cAAc,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAC1E,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAC5B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC;YAAE,OAAO,cAAc,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAC1E,MAAM,OAAO,GAAG,mBAAmB,CACjC,KAAK,EACL,YAAY,CAAC,KAAK,CAAC,EACnB,OAAO,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,CACjC,CAAC;QACF,OAAO,OAAO,CAAC,aAAa,CAAC;YAC3B,GAAG,OAAO;YACV,OAAO,EAAE,GAAG,MAAM,IAAI,IAAI,KAAK,OAAO,CAAC,OAAO,EAAE;YAChD,MAAM;YACN,OAAO;YACP,IAAI;YACJ,MAAM,EAAE,QAAQ,CAAC,MAAM;YACvB,UAAU,EAAE,QAAQ,CAAC,UAAU;SAChC,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["import { errorMessage } from \"./requestInternals\";\nimport { responseBodyFailure } from \"./responseBodyFailure\";\nimport type {\n HttpMethod,\n OperationResponseRequestFn,\n RequestFailure,\n RequestResult,\n RequestResultOptions,\n} from \"./types\";\n\nexport function requestRetired(\n session: AbortSignal | undefined,\n options?: RequestResultOptions,\n) {\n return session?.aborted || options?.stillCurrent?.() === false;\n}\n\n/** A retired request cannot overwrite the active session's failure cache. */\nexport function retiredRequest(\n method: HttpMethod,\n path: string,\n): RequestFailure {\n return {\n code: \"request_aborted\",\n kind: \"cancelled\",\n message: `${method} ${path}: Sign-in ended`,\n method,\n ok: false,\n path,\n report: () => {},\n status: null,\n statusText: \"\",\n };\n}\n\nexport async function readSessionJson(\n request: OperationResponseRequestFn,\n response: Response,\n method: HttpMethod,\n path: string,\n options: RequestResultOptions,\n session: AbortSignal | undefined,\n): Promise<RequestResult<unknown>> {\n try {\n const data: unknown = await response.json();\n if (requestRetired(session, options)) return retiredRequest(method, path);\n return { ok: true, data };\n } catch (error) {\n if (requestRetired(session, options)) return retiredRequest(method, path);\n const failure = responseBodyFailure(\n error,\n errorMessage(error),\n options.signal?.aborted === true,\n );\n return request.reportFailure({\n ...failure,\n message: `${method} ${path}: ${failure.message}`,\n method,\n options,\n path,\n status: response.status,\n statusText: response.statusText,\n });\n }\n}\n"]}
|
|
@@ -8,6 +8,8 @@ export type ListDocumentEditAttributionRangesOptions = Omit<DocumentAttributionR
|
|
|
8
8
|
cursor?: DocumentAttributionRangesQuery["cursor"] | null;
|
|
9
9
|
};
|
|
10
10
|
export interface RequestResultOptions {
|
|
11
|
+
/** Checked at dispatch, on renewal and before handling the response. */
|
|
12
|
+
readonly stillCurrent?: (() => boolean) | undefined;
|
|
11
13
|
readonly signal?: AbortSignal | undefined;
|
|
12
14
|
/** Expected target for a declared 402; mismatched response identities fail closed. */
|
|
13
15
|
readonly expectedPaymentRequiredOrganizationId?: string | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n DocumentAttributionRangesQuery,\n HttpOperation,\n HttpOperationMethod,\n} from \"@tearleads/validators/operation\";\nimport type { ReferencedPrincipalStateResponse } from \"@tearleads/validators/response\";\nimport type { ApiNetworkError } from \"./networkFailure\";\nimport type { WriterProjectionListing } from \"./verifiedManifestCitations\";\n\nexport type HttpMethod = HttpOperationMethod;\nexport type RequestBody = BodyInit;\n\nexport type ListDocumentEditAttributionRangesOptions = Omit<\n DocumentAttributionRangesQuery,\n \"cursor\"\n> & {\n cursor?: DocumentAttributionRangesQuery[\"cursor\"] | null;\n};\n\nexport interface RequestResultOptions {\n readonly signal?: AbortSignal | undefined;\n /** Expected target for a declared 402; mismatched response identities fail closed. */\n readonly expectedPaymentRequiredOrganizationId?: string | undefined;\n readonly headers?: Record<string, string> | undefined;\n readonly reportErrors?: boolean | undefined;\n /** Called after this request or a concurrent request renews the same session. */\n readonly onSessionRenewed?: (() => void) | undefined;\n readonly retryOnSessionExpired?: boolean | \"renew-only\" | undefined;\n /**\n * Writer-projection reads only: where a listing placed the container, so\n * an unplaced container can cite its listed parent's held bytes. It\n * changes which hashes the read cites, never what the read accepts.\n */\n readonly projectionListing?: WriterProjectionListing | undefined;\n /**\n * Group creates, group policy commits and shares only: the organization\n * read-model cursor the caller holds. The response then carries the\n * read-model delta from it when the commit advanced from that cursor.\n */\n readonly readModelCursor?: string | undefined;\n}\n\nexport type OperationRequestFn = <T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: HttpOperation,\n) => Promise<T | null>;\n\nexport type OperationRequestResultFn = <T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: HttpOperation,\n) => Promise<RequestResult<T>>;\n\nexport type RequestFailureKind =\n | \"storage\"\n | \"http\"\n | \"network\"\n | \"json\"\n | \"shape\"\n | \"cancelled\"\n | \"outcome-unknown\";\n\nexport interface RequestFailure {\n readonly code?: string | undefined;\n readonly kind: RequestFailureKind;\n readonly message: string;\n readonly method: HttpMethod;\n /** Set when the fetch itself threw: what the client could observe, without secrets. */\n readonly networkError?: ApiNetworkError | undefined;\n readonly ok: false;\n readonly path: string;\n readonly report: () => void;\n readonly status: number | null;\n readonly statusText: string;\n readonly stalePrincipalHeads?: ReferencedPrincipalStateResponse[] | undefined;\n /**\n * With `container_descendant_rekeys_required`, the full owed set, parent-first;\n * with `container_descendant_rekeys_inaccessible`, its unwritable subset.\n * A hint, never authority; verify each container before signing for it.\n */\n readonly requiredContainerIds?: readonly string[] | undefined;\n}\n\nexport interface RequestSuccess<T> {\n readonly data: T;\n readonly ok: true;\n}\n\nexport type RequestResult<T> = RequestFailure | RequestSuccess<T>;\n\nexport interface ResponseRequestValidationFailureInput {\n readonly code?: string | undefined;\n readonly kind: RequestFailureKind;\n readonly message: string;\n readonly method: HttpMethod;\n readonly options?: RequestResultOptions | undefined;\n readonly path: string;\n readonly status: number | null;\n readonly statusText: string;\n}\n\nexport interface OperationResponseRequestFn {\n (\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions,\n additionalSuccessStatuses: readonly number[],\n failureOperation: HttpOperation,\n ): Promise<RequestResult<Response>>;\n readonly sessionSignal?: () => AbortSignal;\n readonly reportFailure: (\n input: ResponseRequestValidationFailureInput,\n ) => RequestFailure;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n DocumentAttributionRangesQuery,\n HttpOperation,\n HttpOperationMethod,\n} from \"@tearleads/validators/operation\";\nimport type { ReferencedPrincipalStateResponse } from \"@tearleads/validators/response\";\nimport type { ApiNetworkError } from \"./networkFailure\";\nimport type { WriterProjectionListing } from \"./verifiedManifestCitations\";\n\nexport type HttpMethod = HttpOperationMethod;\nexport type RequestBody = BodyInit;\n\nexport type ListDocumentEditAttributionRangesOptions = Omit<\n DocumentAttributionRangesQuery,\n \"cursor\"\n> & {\n cursor?: DocumentAttributionRangesQuery[\"cursor\"] | null;\n};\n\nexport interface RequestResultOptions {\n /** Checked at dispatch, on renewal and before handling the response. */\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly signal?: AbortSignal | undefined;\n /** Expected target for a declared 402; mismatched response identities fail closed. */\n readonly expectedPaymentRequiredOrganizationId?: string | undefined;\n readonly headers?: Record<string, string> | undefined;\n readonly reportErrors?: boolean | undefined;\n /** Called after this request or a concurrent request renews the same session. */\n readonly onSessionRenewed?: (() => void) | undefined;\n readonly retryOnSessionExpired?: boolean | \"renew-only\" | undefined;\n /**\n * Writer-projection reads only: where a listing placed the container, so\n * an unplaced container can cite its listed parent's held bytes. It\n * changes which hashes the read cites, never what the read accepts.\n */\n readonly projectionListing?: WriterProjectionListing | undefined;\n /**\n * Group creates, group policy commits and shares only: the organization\n * read-model cursor the caller holds. The response then carries the\n * read-model delta from it when the commit advanced from that cursor.\n */\n readonly readModelCursor?: string | undefined;\n}\n\nexport type OperationRequestFn = <T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: HttpOperation,\n) => Promise<T | null>;\n\nexport type OperationRequestResultFn = <T>(\n path: string,\n validator: (value: unknown) => value is T,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions | undefined,\n failureOperation: HttpOperation,\n) => Promise<RequestResult<T>>;\n\nexport type RequestFailureKind =\n | \"storage\"\n | \"http\"\n | \"network\"\n | \"json\"\n | \"shape\"\n | \"cancelled\"\n | \"outcome-unknown\";\n\nexport interface RequestFailure {\n readonly code?: string | undefined;\n readonly kind: RequestFailureKind;\n readonly message: string;\n readonly method: HttpMethod;\n /** Set when the fetch itself threw: what the client could observe, without secrets. */\n readonly networkError?: ApiNetworkError | undefined;\n readonly ok: false;\n readonly path: string;\n readonly report: () => void;\n readonly status: number | null;\n readonly statusText: string;\n readonly stalePrincipalHeads?: ReferencedPrincipalStateResponse[] | undefined;\n /**\n * With `container_descendant_rekeys_required`, the full owed set, parent-first;\n * with `container_descendant_rekeys_inaccessible`, its unwritable subset.\n * A hint, never authority; verify each container before signing for it.\n */\n readonly requiredContainerIds?: readonly string[] | undefined;\n}\n\nexport interface RequestSuccess<T> {\n readonly data: T;\n readonly ok: true;\n}\n\nexport type RequestResult<T> = RequestFailure | RequestSuccess<T>;\n\nexport interface ResponseRequestValidationFailureInput {\n readonly code?: string | undefined;\n readonly kind: RequestFailureKind;\n readonly message: string;\n readonly method: HttpMethod;\n readonly options?: RequestResultOptions | undefined;\n readonly path: string;\n readonly status: number | null;\n readonly statusText: string;\n}\n\nexport interface OperationResponseRequestFn {\n (\n path: string,\n method: HttpMethod,\n body: RequestBody | undefined,\n options: RequestResultOptions,\n additionalSuccessStatuses: readonly number[],\n failureOperation: HttpOperation,\n ): Promise<RequestResult<Response>>;\n readonly sessionSignal?: () => AbortSignal;\n readonly reportFailure: (\n input: ResponseRequestValidationFailureInput,\n ) => RequestFailure;\n}\n"]}
|
package/package.json
CHANGED