@tearleads/client-sdk 0.1.42 → 0.1.43
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/data/blobs/transferPool.js +35 -8
- package/data/blobs/transferPool.js.map +1 -1
- package/data/containers/shared/projection.js +12 -0
- package/data/containers/shared/projection.js.map +1 -1
- package/data/documents/blob/shared/types.d.ts +2 -3
- package/data/documents/blob/shared/types.js.map +1 -1
- package/data/documents/shared/events.js +0 -1
- package/data/documents/shared/events.js.map +1 -1
- package/data/persistence/container-contents/containerContentsPersistence.js +6 -22
- package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerMetadataMutationPersistence.js +5 -15
- package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerPendingUpdatePersistence.js +6 -15
- package/data/persistence/container-contents/containerPendingUpdatePersistence.js.map +1 -1
- package/data/persistence/container-contents/containerRecoveryPersistence.js +3 -4
- package/data/persistence/container-contents/containerRecoveryPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerRemovalWork.js +3 -5
- package/data/persistence/container-contents/containerRemovalWork.js.map +1 -1
- package/data/persistence/container-contents/dormantContainerMetadata.js +1 -5
- package/data/persistence/container-contents/dormantContainerMetadata.js.map +1 -1
- package/data/persistence/documents/documentsPersistence.js +4 -9
- package/data/persistence/documents/documentsPersistence.js.map +1 -1
- package/data/persistence/documents/internal/discardDocument.js +1 -2
- package/data/persistence/documents/internal/discardDocument.js.map +1 -1
- package/data/persistence/documents/internal/documentDeletionPersistence.js +1 -2
- package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
- package/data/persistence/documents/internal/documentMutationPersistence.js +17 -25
- package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
- package/data/persistence/documents/internal/orphanSideRows.js +2 -14
- package/data/persistence/documents/internal/orphanSideRows.js.map +1 -1
- package/data/persistence/documents/internal/syncQueuePersistence.js +3 -3
- package/data/persistence/documents/internal/syncQueuePersistence.js.map +1 -1
- package/data/sqlite/documentHistoryPersistence.d.ts +9 -3
- package/data/sqlite/documentHistoryPersistence.js +31 -8
- package/data/sqlite/documentHistoryPersistence.js.map +1 -1
- package/data/sqlite/documentPendingUpdatePersistence.d.ts +58 -11
- package/data/sqlite/documentPendingUpdatePersistence.js +137 -63
- package/data/sqlite/documentPendingUpdatePersistence.js.map +1 -1
- package/data/sqlite/documentPersistence.d.ts +1 -1
- package/data/sqlite/documentPersistence.js +1 -1
- package/data/sqlite/documentPersistence.js.map +1 -1
- package/data/sqlite/documentPersistenceTypes.d.ts +2 -2
- package/data/sqlite/documentPersistenceTypes.js.map +1 -1
- package/data/sqlite/documentRecordPersistence.js +5 -4
- package/data/sqlite/documentRecordPersistence.js.map +1 -1
- package/data/sqlite/schema.d.ts +127 -377
- package/data/sqlite/schema.js +46 -47
- package/data/sqlite/schema.js.map +1 -1
- package/internal/api-client/ApiClient.d.ts +13 -8
- package/internal/api-client/ApiClient.js +2 -5
- package/internal/api-client/ApiClient.js.map +1 -1
- package/internal/api-client/binaryRequestOperationTransport.d.ts +18 -0
- package/internal/api-client/index.d.ts +1 -0
- package/internal/api-client/index.js +1 -0
- package/internal/api-client/index.js.map +1 -1
- package/internal/api-client/operationTransportFactory.d.ts +6 -0
- package/internal/api-client/routes/blobs/get.d.ts +7 -0
- package/internal/api-client/routes/blobs/get.js.map +1 -1
- package/internal/api-client/routes/blobs/multipart.js +1 -11
- package/internal/api-client/routes/blobs/multipart.js.map +1 -1
- package/internal/api-client/routes/blobs/multipartUpload.d.ts +14 -0
- package/internal/api-client/routes/blobs/multipartUpload.js +94 -43
- package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
- package/internal/validators/operation/attachments.d.ts +80 -160
- package/internal/validators/operation/auth.d.ts +760 -1664
- package/internal/validators/operation/blobDownloads.js +1 -1
- package/internal/validators/operation/blobDownloads.js.map +1 -1
- package/internal/validators/operation/containerMutations.d.ts +416 -856
- package/internal/validators/operation/documentMutations.d.ts +120 -264
- package/internal/validators/operation/documentSync.d.ts +40 -80
- package/internal/validators/operation/index.d.ts +1 -1
- package/internal/validators/operation/index.js +1 -1
- package/internal/validators/operation/index.js.map +1 -1
- package/internal/validators/operation/multipartBlobs.d.ts +70 -190
- package/internal/validators/operation/multipartBlobs.js +2 -24
- package/internal/validators/operation/multipartBlobs.js.map +1 -1
- package/internal/validators/operation/multipartPartUploads.d.ts +5 -5
- package/internal/validators/operation/multipartPartUploads.js +6 -20
- package/internal/validators/operation/multipartPartUploads.js.map +1 -1
- package/internal/validators/operation/organizations.d.ts +882 -1906
- package/internal/validators/operation/principals.d.ts +120 -240
- package/internal/validators/operation/registry.d.ts +1 -2
- package/internal/validators/operation/registry.js +1 -2
- package/internal/validators/operation/registry.js.map +1 -1
- package/internal/validators/request/blob.d.ts +100 -201
- package/internal/validators/request/blob.js +6 -13
- package/internal/validators/request/blob.js.map +1 -1
- package/internal/validators/request/container.d.ts +136 -272
- package/internal/validators/request/container.js +16 -10
- package/internal/validators/request/container.js.map +1 -1
- package/internal/validators/request/containerManifestRef.d.ts +54 -0
- package/internal/validators/request/containerManifestRef.js +28 -0
- package/internal/validators/request/containerManifestRef.js.map +1 -0
- package/internal/validators/request/containerMetadata.d.ts +160 -368
- package/internal/validators/request/document.d.ts +100 -245
- package/internal/validators/request/document.js +1 -2
- package/internal/validators/request/document.js.map +1 -1
- package/internal/validators/request/documentSyncSchema.d.ts +42 -109
- package/internal/validators/request/documentSyncSchema.js +8 -25
- package/internal/validators/request/documentSyncSchema.js.map +1 -1
- package/internal/validators/request/index.d.ts +1 -1
- package/internal/validators/request/index.js +1 -1
- package/internal/validators/request/index.js.map +1 -1
- package/internal/validators/request/organization.d.ts +160 -320
- package/internal/validators/request/organizationProvisioning.d.ts +2424 -5312
- package/internal/validators/request/principal.d.ts +160 -320
- package/internal/validators/request/registration.d.ts +760 -1664
- package/internal/validators/response/blob.d.ts +48 -27
- package/internal/validators/response/blob.js +3 -10
- package/internal/validators/response/blob.js.map +1 -1
- package/internal/validators/response/index.d.ts +1 -1
- package/internal/validators/response/index.js +1 -1
- package/internal/validators/response/index.js.map +1 -1
- package/internal/validators/util/blob.d.ts +7 -0
- package/internal/validators/util/blob.js +7 -0
- package/internal/validators/util/blob.js.map +1 -1
- package/internal/validators/util/blobTransferSchemas.d.ts +41 -0
- package/internal/validators/util/blobTransferSchemas.js +39 -0
- package/internal/validators/util/blobTransferSchemas.js.map +1 -0
- package/internal/validators/util/containerLimits.d.ts +7 -0
- package/internal/validators/util/containerLimits.js +7 -0
- package/internal/validators/util/containerLimits.js.map +1 -1
- package/internal/validators/util/index.d.ts +2 -1
- package/internal/validators/util/index.js +2 -1
- package/internal/validators/util/index.js.map +1 -1
- package/package.json +1 -1
- package/workflows/blobs/multipartFirstParts.js +82 -0
- package/workflows/blobs/multipartFirstParts.js.map +1 -0
- package/workflows/blobs/multipartStageResolution.js +83 -0
- package/workflows/blobs/multipartStageResolution.js.map +1 -0
- package/workflows/blobs/multipartUpload.js +45 -89
- package/workflows/blobs/multipartUpload.js.map +1 -1
- package/workflows/container-contents/documentPriming.js +2 -1
- package/workflows/container-contents/documentPriming.js.map +1 -1
- package/workflows/container-contents/documentQueries/sql.js +4 -4
- package/workflows/container-contents/documentQueries/sql.js.map +1 -1
- package/workflows/container-contents/pendingWrites/deferredTails.js +6 -3
- package/workflows/container-contents/pendingWrites/deferredTails.js.map +1 -1
- package/workflows/container-contents/pendingWrites/sources.js +2 -1
- package/workflows/container-contents/pendingWrites/sources.js.map +1 -1
- package/workflows/container-contents/pendingWrites.js +2 -1
- package/workflows/container-contents/pendingWrites.js.map +1 -1
- package/workflows/containers/child/create.js +3 -3
- package/workflows/containers/child/create.js.map +1 -1
- package/workflows/containers/child/move.js +2 -2
- package/workflows/containers/child/move.js.map +1 -1
- package/workflows/containers/child/mutationRequestCore.js +5 -4
- package/workflows/containers/child/mutationRequestCore.js.map +1 -1
- package/workflows/containers/child/recitePlan.js +3 -2
- package/workflows/containers/child/recitePlan.js.map +1 -1
- package/workflows/containers/child/sharePlanCore.js +2 -2
- package/workflows/containers/child/sharePlanCore.js.map +1 -1
- package/workflows/containers/root/create.js +2 -2
- package/workflows/containers/root/create.js.map +1 -1
- package/workflows/registration/provisioningBootstrapBuilders.d.ts +20 -46
- package/workflows/sync/remoteReset.js +9 -9
- package/workflows/sync/remoteReset.js.map +1 -1
- package/workflows/sync/remoteResetPlans.js +6 -3
- package/workflows/sync/remoteResetPlans.js.map +1 -1
- package/internal/validators/operation/blobTransferSchemas.js +0 -11
- package/internal/validators/operation/blobTransferSchemas.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"get.js","sourceRoot":"","sources":["get.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,wBAAwB,GACzB,MAAM,iCAAiC,CAAC;AAOzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAsB5D,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,SAAgC,EAChC,MAAc,EACd,gBAA+B,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC,EAC9D,UAAgC,EAAE;IAElC,wEAAwE;IACxE,4EAA4E;IAC5E,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,GAAG,CAAC,EAAE,OAAO,IAAI,CAAC,EAAE,CAAC;QAChD,IAAI,OAAO,CAAC,MAAM,EAAE,OAAO;YAAE,OAAO,IAAI,CAAC;QACzC,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,aAAa,CAC1C,wBAAwB,EACxB,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,EAAE,EACtB,EAAE,GAAG,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,CACpC,CAAC;QACF,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;YACf,IAAI,MAAM,CAAC,I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;AAC9E,qEAAqE;AACrE,0DAA0D;AAC1D,yEAAyE;AACzE,yCAAyC;AACzC,SAAS,0BAA0B,CACjC,MAAmB;IAEnB,MAAM,KAAK,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;IACrC,OAAO,IAAI,cAAc,CAAa;QACpC,KAAK,CAAC,UAAU;YACd,IAAI,KAAK,CAAC,UAAU,GAAG,CAAC,EAAE,CAAC;gBACzB,UAAU,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC5B,CAAC;YACD,UAAU,CAAC,KAAK,EAAE,CAAC;QACrB,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n blobWireHeaderKeys,\n getBlobBytesOperation,\n getBlobDownloadOperation,\n} from \"@tearleads/validators/operation\";\nimport type { BinaryResponseOperationTransport } from \"../../binaryResponseOperationTransport\";\nimport type { JsonOperationTransport } from \"../../operationTransport\";\nimport type {\n OperationResponseRequestFn,\n RequestResultOptions,\n} from \"../../types\";\nimport { storageFetchOptions } from \"./storageFetchOptions\";\n\nexport interface BlobBytesResponse {\n readonly blobId: string;\n readonly byteLength: number;\n readonly encryptedBytes: ReadableStream<Uint8Array>;\n readonly sha256: string;\n}\n\nexport interface UploadMultipartBlobPartBytesRequest {\n readonly byteLength: number;\n readonly encryptedBytes: Blob | BufferSource;\n readonly sha256: string;\n readonly uploadId: string;\n}\n\ntype BlobDownloadTransport = Pick<JsonOperationTransport, \"requestResult\"> &\n Pick<BinaryResponseOperationTransport, \"requestBinaryResponse\"> &\n Pick<OperationResponseRequestFn, \"reportFailure\">;\n\ntype DownloadFetch = (url: string, init: RequestInit) => Promise<Response>;\n\nexport async function getBlobBytes(\n transport: BlobDownloadTransport,\n blobId: string,\n downloadFetch: DownloadFetch = (url, init) => fetch(url, init),\n options: RequestResultOptions = {},\n): Promise<BlobBytesResponse | null> {\n // Refresh at most once. R2 expiration errors can appear as CORS/network\n // failures in browsers, so both rejected fetches and 403s need a fresh URL.\n for (let attempt = 0; attempt < 2; attempt += 1) {\n if (options.signal?.aborted) return null;\n const result = await transport.requestResult(\n getBlobDownloadOperation,\n { params: { blobId } },\n { ...options, reportErrors: false },\n );\n if (!result.ok) {\n if (result.kind === \"http\" && result.status === 404) {\n return getBlobStream(transport, blobId, options);\n }\n result.report();\n return null;\n }\n const descriptor = result.data;\n if (descriptor.blobId !== blobId) {\n transport.reportFailure({\n kind: \"shape\",\n method: \"GET\",\n path: `/blobs/${blobId}/download`,\n status: 200,\n statusText: \"\",\n message: `Blob ${blobId} download descriptor has the wrong identity`,\n });\n return null;\n }\n if (descriptor.source.kind === \"api\") {\n return getBlobStream(transport, blobId, options);\n }\n try {\n // Never send the application's session or cookies to the object store.\n // Reject redirects and keep bearer URLs out of referrers and errors.\n const response = await downloadFetch(\n descriptor.source.url,\n storageFetchOptions(options),\n );\n if (response.status !== 200) {\n await response.body?.cancel().catch(() => {});\n if (response.status === 403) {\n continue;\n }\n break;\n }\n return await signedBlobResponse(descriptor, response);\n } catch {\n // The downstream SDK still verifies length, hash and authenticated\n // encryption. An error after streaming begins propagates to that reader.\n }\n }\n // Preserve downloads when storage is unreachable or a native HTTP bridge\n // cannot use the signed URL. This endpoint checks current access again.\n // A storage failure alone must not signal that the API is offline.\n return getBlobStream(transport, blobId, options);\n}\n\nasync function signedBlobResponse(\n descriptor: Pick<BlobBytesResponse, \"blobId\" | \"byteLength\" | \"sha256\">,\n response: Response,\n): Promise<BlobBytesResponse> {\n return {\n blobId: descriptor.blobId,\n byteLength: descriptor.byteLength,\n sha256: descriptor.sha256,\n encryptedBytes: response.body\n ? signedDownloadBodyStream(response.body)\n : bufferedResponseBodyStream(await response.arrayBuffer()),\n };\n}\n\nfunction signedDownloadBodyStream(\n stream: ReadableStream<Uint8Array>,\n): ReadableStream<Uint8Array> {\n const reader = stream.getReader();\n // Native network errors may contain the bearer URL. Keep failures generic\n // before downstream readers log them, without buffering or eager reads.\n return new ReadableStream<Uint8Array>(\n {\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n reader.releaseLock();\n } else {\n controller.enqueue(value);\n }\n } catch {\n controller.error(new Error(\"Blob download interrupted\"));\n reader.releaseLock();\n }\n },\n async cancel(reason) {\n try {\n await reader.cancel(reason);\n } catch {\n throw new Error(\"Blob download cancellation failed\");\n } finally {\n reader.releaseLock();\n }\n },\n },\n { highWaterMark: 0 },\n );\n}\n\nasync function getBlobStream(\n transport: Pick<BinaryResponseOperationTransport, \"requestBinaryResponse\">,\n blobId: string,\n options: RequestResultOptions,\n): Promise<BlobBytesResponse | null> {\n if (options.signal?.aborted) return null;\n const result = await transport.requestBinaryResponse(\n getBlobBytesOperation,\n {\n params: { blobId },\n },\n options,\n );\n if (!result) {\n return null;\n }\n\n const { headers, response } = result;\n const byteLength = Number(headers[blobWireHeaderKeys.blobByteLength]);\n\n // On the browser / WKWebView-fetch path the body is streamed, so\n // `response.body` is a live ReadableStream. Under a native HTTP bridge\n // (CapacitorHttp — which the Capacitor iOS/Android builds enable so cross-origin\n // API requests reach the backend at all; the WKWebView's own fetch fails from\n // the app's https://localhost origin) the response is buffered natively and\n // `response.body` is null even for a valid 200. So take the bytes either way:\n // the stream when present, otherwise buffer the response and re-wrap it as a\n // one-shot ReadableStream so callers keep a single streaming interface. This\n // does not weaken validation — a truncated or corrupted body is still caught\n // downstream by the X-Tearleads-Blob-Sha256 integrity check; it only stops a\n // buffered-but-valid response from being rejected here as malformed.\n const encryptedBytes =\n response.body ?? bufferedResponseBodyStream(await response.arrayBuffer());\n\n return {\n blobId: headers[blobWireHeaderKeys.blobId],\n byteLength,\n encryptedBytes,\n sha256: headers[blobWireHeaderKeys.blobSha256],\n };\n}\n\n// Wraps a fully-buffered response body as a single-chunk ReadableStream, so a\n// native HTTP bridge that only exposes the buffered bytes (no WHATWG\n// `response.body` stream) can still satisfy the streaming\n// `BlobBytesResponse.encryptedBytes` contract. An empty buffer yields an\n// immediately-closed, zero-chunk stream.\nfunction bufferedResponseBodyStream(\n buffer: ArrayBuffer,\n): ReadableStream<Uint8Array> {\n const bytes = new Uint8Array(buffer);\n return new ReadableStream<Uint8Array>({\n start(controller) {\n if (bytes.byteLength > 0) {\n controller.enqueue(bytes);\n }\n controller.close();\n },\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"get.js","sourceRoot":"","sources":["get.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,wBAAwB,GACzB,MAAM,iCAAiC,CAAC;AAQzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AA4B5D,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,SAAgC,EAChC,MAAc,EACd,gBAA+B,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC,EAC9D,UAAgC,EAAE;IAElC,wEAAwE;IACxE,4EAA4E;IAC5E,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,GAAG,CAAC,EAAE,OAAO,IAAI,CAAC,EAAE,CAAC;QAChD,IAAI,OAAO,CAAC,MAAM,EAAE,OAAO;YAAE,OAAO,IAAI,CAAC;QACzC,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,aAAa,CAC1C,wBAAwB,EACxB,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,EAAE,EACtB,EAAE,GAAG,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,CACpC,CAAC;QACF,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;YACf,IAAI,MAAM,CAAC,IAAI,KAAK,MAAM,IAAI,MAAM,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;gBACpD,OAAO,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;YACnD,CAAC;YACD,MAAM,CAAC,MAAM,EAAE,CAAC;YAChB,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,UAAU,GAAG,MAAM,CAAC,IAAI,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E,CAAC;gBACzB,UAAU,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC5B,CAAC;YACD,UAAU,CAAC,KAAK,EAAE,CAAC;QACrB,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n blobWireHeaderKeys,\n getBlobBytesOperation,\n getBlobDownloadOperation,\n} from \"@tearleads/validators/operation\";\nimport type { MultipartBlobPartUploadSource } from \"@tearleads/validators/util\";\nimport type { BinaryResponseOperationTransport } from \"../../binaryResponseOperationTransport\";\nimport type { JsonOperationTransport } from \"../../operationTransport\";\nimport type {\n OperationResponseRequestFn,\n RequestResultOptions,\n} from \"../../types\";\nimport { storageFetchOptions } from \"./storageFetchOptions\";\n\nexport interface BlobBytesResponse {\n readonly blobId: string;\n readonly byteLength: number;\n readonly encryptedBytes: ReadableStream<Uint8Array>;\n readonly sha256: string;\n}\n\nexport interface UploadMultipartBlobPartBytesRequest {\n readonly byteLength: number;\n readonly encryptedBytes: Blob | BufferSource;\n readonly sha256: string;\n /**\n * An upload source the stage initiation already issued for this part. The\n * first attempt uses it instead of authorizing; a failed attempt still\n * reauthorizes once, exactly as when no source was issued.\n */\n readonly source?: MultipartBlobPartUploadSource | undefined;\n readonly uploadId: string;\n}\n\ntype BlobDownloadTransport = Pick<JsonOperationTransport, \"requestResult\"> &\n Pick<BinaryResponseOperationTransport, \"requestBinaryResponse\"> &\n Pick<OperationResponseRequestFn, \"reportFailure\">;\n\ntype DownloadFetch = (url: string, init: RequestInit) => Promise<Response>;\n\nexport async function getBlobBytes(\n transport: BlobDownloadTransport,\n blobId: string,\n downloadFetch: DownloadFetch = (url, init) => fetch(url, init),\n options: RequestResultOptions = {},\n): Promise<BlobBytesResponse | null> {\n // Refresh at most once. R2 expiration errors can appear as CORS/network\n // failures in browsers, so both rejected fetches and 403s need a fresh URL.\n for (let attempt = 0; attempt < 2; attempt += 1) {\n if (options.signal?.aborted) return null;\n const result = await transport.requestResult(\n getBlobDownloadOperation,\n { params: { blobId } },\n { ...options, reportErrors: false },\n );\n if (!result.ok) {\n if (result.kind === \"http\" && result.status === 404) {\n return getBlobStream(transport, blobId, options);\n }\n result.report();\n return null;\n }\n const descriptor = result.data;\n if (descriptor.blobId !== blobId) {\n transport.reportFailure({\n kind: \"shape\",\n method: \"GET\",\n path: `/blobs/${blobId}/download`,\n status: 200,\n statusText: \"\",\n message: `Blob ${blobId} download descriptor has the wrong identity`,\n });\n return null;\n }\n if (descriptor.source.kind === \"api\") {\n return getBlobStream(transport, blobId, options);\n }\n try {\n // Never send the application's session or cookies to the object store.\n // Reject redirects and keep bearer URLs out of referrers and errors.\n const response = await downloadFetch(\n descriptor.source.url,\n storageFetchOptions(options),\n );\n if (response.status !== 200) {\n await response.body?.cancel().catch(() => {});\n if (response.status === 403) {\n continue;\n }\n break;\n }\n return await signedBlobResponse(descriptor, response);\n } catch {\n // The downstream SDK still verifies length, hash and authenticated\n // encryption. An error after streaming begins propagates to that reader.\n }\n }\n // Preserve downloads when storage is unreachable or a native HTTP bridge\n // cannot use the signed URL. This endpoint checks current access again.\n // A storage failure alone must not signal that the API is offline.\n return getBlobStream(transport, blobId, options);\n}\n\nasync function signedBlobResponse(\n descriptor: Pick<BlobBytesResponse, \"blobId\" | \"byteLength\" | \"sha256\">,\n response: Response,\n): Promise<BlobBytesResponse> {\n return {\n blobId: descriptor.blobId,\n byteLength: descriptor.byteLength,\n sha256: descriptor.sha256,\n encryptedBytes: response.body\n ? signedDownloadBodyStream(response.body)\n : bufferedResponseBodyStream(await response.arrayBuffer()),\n };\n}\n\nfunction signedDownloadBodyStream(\n stream: ReadableStream<Uint8Array>,\n): ReadableStream<Uint8Array> {\n const reader = stream.getReader();\n // Native network errors may contain the bearer URL. Keep failures generic\n // before downstream readers log them, without buffering or eager reads.\n return new ReadableStream<Uint8Array>(\n {\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n reader.releaseLock();\n } else {\n controller.enqueue(value);\n }\n } catch {\n controller.error(new Error(\"Blob download interrupted\"));\n reader.releaseLock();\n }\n },\n async cancel(reason) {\n try {\n await reader.cancel(reason);\n } catch {\n throw new Error(\"Blob download cancellation failed\");\n } finally {\n reader.releaseLock();\n }\n },\n },\n { highWaterMark: 0 },\n );\n}\n\nasync function getBlobStream(\n transport: Pick<BinaryResponseOperationTransport, \"requestBinaryResponse\">,\n blobId: string,\n options: RequestResultOptions,\n): Promise<BlobBytesResponse | null> {\n if (options.signal?.aborted) return null;\n const result = await transport.requestBinaryResponse(\n getBlobBytesOperation,\n {\n params: { blobId },\n },\n options,\n );\n if (!result) {\n return null;\n }\n\n const { headers, response } = result;\n const byteLength = Number(headers[blobWireHeaderKeys.blobByteLength]);\n\n // On the browser / WKWebView-fetch path the body is streamed, so\n // `response.body` is a live ReadableStream. Under a native HTTP bridge\n // (CapacitorHttp — which the Capacitor iOS/Android builds enable so cross-origin\n // API requests reach the backend at all; the WKWebView's own fetch fails from\n // the app's https://localhost origin) the response is buffered natively and\n // `response.body` is null even for a valid 200. So take the bytes either way:\n // the stream when present, otherwise buffer the response and re-wrap it as a\n // one-shot ReadableStream so callers keep a single streaming interface. This\n // does not weaken validation — a truncated or corrupted body is still caught\n // downstream by the X-Tearleads-Blob-Sha256 integrity check; it only stops a\n // buffered-but-valid response from being rejected here as malformed.\n const encryptedBytes =\n response.body ?? bufferedResponseBodyStream(await response.arrayBuffer());\n\n return {\n blobId: headers[blobWireHeaderKeys.blobId],\n byteLength,\n encryptedBytes,\n sha256: headers[blobWireHeaderKeys.blobSha256],\n };\n}\n\n// Wraps a fully-buffered response body as a single-chunk ReadableStream, so a\n// native HTTP bridge that only exposes the buffered bytes (no WHATWG\n// `response.body` stream) can still satisfy the streaming\n// `BlobBytesResponse.encryptedBytes` contract. An empty buffer yields an\n// immediately-closed, zero-chunk stream.\nfunction bufferedResponseBodyStream(\n buffer: ArrayBuffer,\n): ReadableStream<Uint8Array> {\n const bytes = new Uint8Array(buffer);\n return new ReadableStream<Uint8Array>({\n start(controller) {\n if (bytes.byteLength > 0) {\n controller.enqueue(bytes);\n }\n controller.close();\n },\n });\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { getMultipartBlobStageOperation, initiateMultipartBlobStageOperation, isGetMultipartBlobStageOperationResponse, isInitiateMultipartBlobStageOperationRequest, isInitiateMultipartBlobStageOperationResponse, operationRequestPath, } from "../../../validators/operation/index.js";
|
|
2
2
|
export const initiateMultipartBlobStage = {
|
|
3
3
|
isRequest: isInitiateMultipartBlobStageOperationRequest,
|
|
4
4
|
isResponse: isInitiateMultipartBlobStageOperationResponse,
|
|
@@ -12,14 +12,4 @@ export const getMultipartBlobStage = {
|
|
|
12
12
|
return operationRequestPath(getMultipartBlobStageOperation, { stageId });
|
|
13
13
|
},
|
|
14
14
|
};
|
|
15
|
-
export const completeMultipartBlobStage = {
|
|
16
|
-
isRequest: isCompleteMultipartBlobStageOperationRequest,
|
|
17
|
-
isResponse: isCompleteMultipartBlobStageOperationResponse,
|
|
18
|
-
method: completeMultipartBlobStageOperation.method,
|
|
19
|
-
path(stageId) {
|
|
20
|
-
return operationRequestPath(completeMultipartBlobStageOperation, {
|
|
21
|
-
stageId,
|
|
22
|
-
});
|
|
23
|
-
},
|
|
24
|
-
};
|
|
25
15
|
//# sourceMappingURL=multipart.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"multipart.js","sourceRoot":"","sources":["multipart.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,
|
|
1
|
+
{"version":3,"file":"multipart.js","sourceRoot":"","sources":["multipart.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,8BAA8B,EAC9B,mCAAmC,EACnC,wCAAwC,EACxC,4CAA4C,EAC5C,6CAA6C,EAC7C,oBAAoB,GACrB,MAAM,iCAAiC,CAAC;AAEzC,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACxC,SAAS,EAAE,4CAA4C;IACvD,UAAU,EAAE,6CAA6C;IACzD,MAAM,EAAE,mCAAmC,CAAC,MAAM;IAClD,IAAI,EAAE,oBAAoB,CAAC,mCAAmC,EAAE,EAAE,CAAC;CACpE,CAAC;AAEF,MAAM,CAAC,MAAM,qBAAqB,GAAG;IACnC,UAAU,EAAE,wCAAwC;IACpD,MAAM,EAAE,8BAA8B,CAAC,MAAM;IAC7C,IAAI,CAAC,OAAe;QAClB,OAAO,oBAAoB,CAAC,8BAA8B,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;IAC3E,CAAC;CACF,CAAC","sourcesContent":["import {\n getMultipartBlobStageOperation,\n initiateMultipartBlobStageOperation,\n isGetMultipartBlobStageOperationResponse,\n isInitiateMultipartBlobStageOperationRequest,\n isInitiateMultipartBlobStageOperationResponse,\n operationRequestPath,\n} from \"@tearleads/validators/operation\";\n\nexport const initiateMultipartBlobStage = {\n isRequest: isInitiateMultipartBlobStageOperationRequest,\n isResponse: isInitiateMultipartBlobStageOperationResponse,\n method: initiateMultipartBlobStageOperation.method,\n path: operationRequestPath(initiateMultipartBlobStageOperation, {}),\n};\n\nexport const getMultipartBlobStage = {\n isResponse: isGetMultipartBlobStageOperationResponse,\n method: getMultipartBlobStageOperation.method,\n path(stageId: string) {\n return operationRequestPath(getMultipartBlobStageOperation, { stageId });\n },\n};\n"]}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { UploadMultipartBlobPartResponse } from "../../../validators/response/index.js";
|
|
2
|
+
import { type MultipartBlobPartDescriptor } from "../../../validators/util/index.js";
|
|
3
|
+
import type { OperationTransport } from "../../operationTransportFactory.js";
|
|
4
|
+
import type { RequestResultOptions } from "../../types.js";
|
|
5
|
+
import type { UploadMultipartBlobPartBytesRequest } from "./get.js";
|
|
6
|
+
type UploadFetch = (url: string, init: RequestInit) => Promise<Response>;
|
|
7
|
+
/**
|
|
8
|
+
* Describe an encrypted part the way a stage initiation lists the parts it
|
|
9
|
+
* will send first: number, exact length, and the Content-MD5 a signed upload
|
|
10
|
+
* URL binds.
|
|
11
|
+
*/
|
|
12
|
+
export declare function describeMultipartBlobPart(partNumber: number, encryptedBytes: Uint8Array): MultipartBlobPartDescriptor;
|
|
13
|
+
export declare function uploadMultipartBlobPartBytes(transport: OperationTransport, stageId: string, partNumber: number, input: UploadMultipartBlobPartBytesRequest, uploadFetch?: UploadFetch, options?: RequestResultOptions): Promise<UploadMultipartBlobPartResponse | null>;
|
|
14
|
+
export {};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { md5 } from "@noble/hashes/legacy.js";
|
|
2
2
|
import { bytesToHex } from "../../../crypto/index.js";
|
|
3
3
|
import { authorizeMultipartBlobPartUploadOperation, blobWireHeaderKeys, operationRequestPath, uploadMultipartBlobPartBytesOperation, } from "../../../validators/operation/index.js";
|
|
4
|
-
import { MAX_MULTIPART_BLOB_PART_BYTES } from "../../../validators/util/index.js";
|
|
4
|
+
import { MAX_MULTIPART_BLOB_PART_BYTES, } from "../../../validators/util/index.js";
|
|
5
5
|
import { storageFetchOptions } from "./storageFetchOptions.js";
|
|
6
6
|
function invalidPart(transport, path) {
|
|
7
7
|
transport.reportFailure({
|
|
@@ -23,6 +23,21 @@ async function retryStorageStatus(status, attempt) {
|
|
|
23
23
|
}
|
|
24
24
|
return transient;
|
|
25
25
|
}
|
|
26
|
+
function contentMd5Base64(bytes) {
|
|
27
|
+
return btoa(String.fromCharCode(...md5(bytes)));
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Describe an encrypted part the way a stage initiation lists the parts it
|
|
31
|
+
* will send first: number, exact length, and the Content-MD5 a signed upload
|
|
32
|
+
* URL binds.
|
|
33
|
+
*/
|
|
34
|
+
export function describeMultipartBlobPart(partNumber, encryptedBytes) {
|
|
35
|
+
return {
|
|
36
|
+
byteLength: encryptedBytes.byteLength,
|
|
37
|
+
contentMd5: contentMd5Base64(encryptedBytes),
|
|
38
|
+
partNumber,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
26
41
|
async function preparePart(input) {
|
|
27
42
|
// File snapshots mutable buffers and preserves ciphertext across Capacitor's
|
|
28
43
|
// native HTTP bridge. Uint8Array is UTF-8 decoded there; a plain Blob becomes
|
|
@@ -42,64 +57,100 @@ async function preparePart(input) {
|
|
|
42
57
|
input.sha256) {
|
|
43
58
|
throw new TypeError("Multipart part SHA-256 does not match its bytes");
|
|
44
59
|
}
|
|
45
|
-
|
|
46
|
-
|
|
60
|
+
return { file, contentMd5: contentMd5Base64(new Uint8Array(bytes)) };
|
|
61
|
+
}
|
|
62
|
+
// Sign just in time for this part. The returned descriptor must name exactly
|
|
63
|
+
// the part, upload, length, and checksum that were requested.
|
|
64
|
+
async function authorizePart(context) {
|
|
65
|
+
const operation = authorizeMultipartBlobPartUploadOperation;
|
|
66
|
+
const { input, partNumber, stageId } = context;
|
|
67
|
+
const result = await context.transport.requestResult(operation, {
|
|
68
|
+
params: { stageId, partNumber },
|
|
69
|
+
body: {
|
|
70
|
+
byteLength: input.byteLength,
|
|
71
|
+
contentMd5: context.contentMd5,
|
|
72
|
+
uploadId: input.uploadId,
|
|
73
|
+
},
|
|
74
|
+
}, context.options);
|
|
75
|
+
if (!result.ok)
|
|
76
|
+
return null;
|
|
77
|
+
const descriptor = result.data;
|
|
78
|
+
if (descriptor.stageId !== stageId ||
|
|
79
|
+
descriptor.uploadId !== input.uploadId ||
|
|
80
|
+
descriptor.partNumber !== partNumber ||
|
|
81
|
+
descriptor.byteLength !== input.byteLength ||
|
|
82
|
+
descriptor.contentMd5 !== context.contentMd5) {
|
|
83
|
+
context.transport.reportFailure({
|
|
84
|
+
kind: "shape",
|
|
85
|
+
method: operation.method,
|
|
86
|
+
path: context.path,
|
|
87
|
+
status: 200,
|
|
88
|
+
statusText: "",
|
|
89
|
+
message: "Multipart upload descriptor does not match its part",
|
|
90
|
+
});
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
return descriptor.source;
|
|
94
|
+
}
|
|
95
|
+
// Parts can wait behind other transfers in the shared pool. An issued URL that
|
|
96
|
+
// is about to lapse would only spend this part's retry on a certain 403, so
|
|
97
|
+
// authorize afresh instead; a skewed clock errs toward authorizing.
|
|
98
|
+
const ISSUED_URL_MIN_REMAINING_MS = 30_000;
|
|
99
|
+
function isUsableIssuedSource(source) {
|
|
100
|
+
return (source !== undefined &&
|
|
101
|
+
(source.kind === "api" ||
|
|
102
|
+
Date.parse(source.expiresAt) - Date.now() > ISSUED_URL_MIN_REMAINING_MS));
|
|
103
|
+
}
|
|
104
|
+
// A capability path for memory/custom stores; S3/R2 never proxy parts.
|
|
105
|
+
function uploadThroughApi(context, file) {
|
|
106
|
+
const { input } = context;
|
|
107
|
+
return context.transport.requestBinaryRequest(uploadMultipartBlobPartBytesOperation, {
|
|
108
|
+
params: { stageId: context.stageId, partNumber: context.partNumber },
|
|
109
|
+
body: input.encryptedBytes,
|
|
110
|
+
headers: {
|
|
111
|
+
[blobWireHeaderKeys.partByteLength]: input.byteLength.toString(),
|
|
112
|
+
[blobWireHeaderKeys.partSha256]: input.sha256,
|
|
113
|
+
[blobWireHeaderKeys.partUploadId]: input.uploadId,
|
|
114
|
+
},
|
|
115
|
+
}, { ...context.options, encodeBody: () => file });
|
|
47
116
|
}
|
|
48
117
|
export async function uploadMultipartBlobPartBytes(transport, stageId, partNumber, input, uploadFetch = (url, init) => fetch(url, init), options = {}) {
|
|
49
118
|
if (options.signal?.aborted)
|
|
50
119
|
return null;
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
|
|
120
|
+
const path = operationRequestPath(authorizeMultipartBlobPartUploadOperation, {
|
|
121
|
+
stageId,
|
|
122
|
+
partNumber,
|
|
123
|
+
});
|
|
54
124
|
const prepared = await preparePart(input).catch(() => invalidPart(transport, path));
|
|
55
125
|
if (!prepared)
|
|
56
126
|
return null;
|
|
57
127
|
const { file, contentMd5 } = prepared;
|
|
58
|
-
const
|
|
59
|
-
byteLength: input.byteLength,
|
|
128
|
+
const context = {
|
|
60
129
|
contentMd5,
|
|
61
|
-
|
|
130
|
+
input,
|
|
131
|
+
options,
|
|
132
|
+
partNumber,
|
|
133
|
+
path,
|
|
134
|
+
stageId,
|
|
135
|
+
transport,
|
|
62
136
|
};
|
|
63
137
|
let status = null;
|
|
64
|
-
//
|
|
65
|
-
// failure may be an expired URL hidden by R2 CORS, or a lost success
|
|
66
|
-
// reauthorize once and send the same immutable bytes to the same
|
|
138
|
+
// The first attempt uses the source the stage initiation issued, if any. A
|
|
139
|
+
// network failure may be an expired URL hidden by R2 CORS, or a lost success
|
|
140
|
+
// response; reauthorize once and send the same immutable bytes to the same
|
|
141
|
+
// part number.
|
|
67
142
|
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
68
143
|
if (options.signal?.aborted)
|
|
69
144
|
return null;
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
if (descriptor.stageId !== stageId ||
|
|
75
|
-
descriptor.uploadId !== input.uploadId ||
|
|
76
|
-
descriptor.partNumber !== partNumber ||
|
|
77
|
-
descriptor.byteLength !== input.byteLength ||
|
|
78
|
-
descriptor.contentMd5 !== contentMd5) {
|
|
79
|
-
transport.reportFailure({
|
|
80
|
-
kind: "shape",
|
|
81
|
-
method: operation.method,
|
|
82
|
-
path,
|
|
83
|
-
status: 200,
|
|
84
|
-
statusText: "",
|
|
85
|
-
message: "Multipart upload descriptor does not match its part",
|
|
86
|
-
});
|
|
145
|
+
const source = attempt === 0 && isUsableIssuedSource(input.source)
|
|
146
|
+
? input.source
|
|
147
|
+
: await authorizePart(context);
|
|
148
|
+
if (!source)
|
|
87
149
|
return null;
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
// A capability path for memory/custom stores; S3/R2 never proxy parts.
|
|
91
|
-
return transport.requestBinaryRequest(uploadMultipartBlobPartBytesOperation, {
|
|
92
|
-
params,
|
|
93
|
-
body: input.encryptedBytes,
|
|
94
|
-
headers: {
|
|
95
|
-
[blobWireHeaderKeys.partByteLength]: input.byteLength.toString(),
|
|
96
|
-
[blobWireHeaderKeys.partSha256]: input.sha256,
|
|
97
|
-
[blobWireHeaderKeys.partUploadId]: input.uploadId,
|
|
98
|
-
},
|
|
99
|
-
}, { ...options, encodeBody: () => file });
|
|
100
|
-
}
|
|
150
|
+
if (source.kind === "api")
|
|
151
|
+
return uploadThroughApi(context, file);
|
|
101
152
|
try {
|
|
102
|
-
const response = await uploadFetch(
|
|
153
|
+
const response = await uploadFetch(source.url, {
|
|
103
154
|
method: "PUT",
|
|
104
155
|
body: file,
|
|
105
156
|
headers: {
|
|
@@ -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,EAAE,6BAA6B,EAAE,MAAM,4BAA4B,CAAC;AAI3E,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,KAAK,UAAU,kBAAkB,CAAC,MAAc,EAAE,OAAe;IAC/D,IAAI,MAAM,KAAK,GAAG;QAAE,OAAO,IAAI,CAAC;IAChC,MAAM,SAAS,GAAG,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,IAAI,GAAG,IAAI,MAAM,IAAI,GAAG,CAAC,CAAC;IACrE,IAAI,SAAS,IAAI,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AU,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 { MAX_MULTIPART_BLOB_PART_BYTES } 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\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 const contentMd5 = btoa(String.fromCharCode(...md5(new Uint8Array(bytes))));\n return { file, contentMd5 };\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 operation = authorizeMultipartBlobPartUploadOperation;\n const params = { stageId, partNumber };\n const path = operationRequestPath(operation, params);\n const prepared = await preparePart(input).catch(() =>\n invalidPart(transport, path),\n );\n if (!prepared) return null;\n const { file, contentMd5 } = prepared;\n const body = {\n byteLength: input.byteLength,\n contentMd5,\n uploadId: input.uploadId,\n };\n let status: number | null = null;\n // Sign just in time for each part, not once for the entire file. A network\n // failure may be an expired URL hidden by R2 CORS, or a lost success response;\n // reauthorize once and send the same immutable bytes to the same part number.\n for (let attempt = 0; attempt < 2; attempt += 1) {\n if (options.signal?.aborted) return null;\n const result = await transport.requestResult(\n operation,\n { params, body },\n 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 !== contentMd5\n ) {\n transport.reportFailure({\n kind: \"shape\",\n method: operation.method,\n path,\n status: 200,\n statusText: \"\",\n message: \"Multipart upload descriptor does not match its part\",\n });\n return null;\n }\n if (descriptor.source.kind === \"api\") {\n // A capability path for memory/custom stores; S3/R2 never proxy parts.\n return transport.requestBinaryRequest(\n uploadMultipartBlobPartBytesOperation,\n {\n params,\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 { ...options, encodeBody: () => file },\n );\n }\n try {\n const response = await uploadFetch(descriptor.source.url, {\n method: \"PUT\",\n body: file,\n headers: {\n \"Content-Type\": \"application/octet-stream\",\n \"Content-MD5\": contentMd5,\n },\n ...storageFetchOptions(options),\n });\n 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 stageId,\n uploadId: input.uploadId,\n part: { byteLength: input.byteLength, partNumber, etag },\n };\n }\n if (!(await retryStorageStatus(status, attempt))) break;\n } catch {\n // Never expose a provider exception or body: it may contain the bearer URL.\n status = null;\n }\n }\n if (options.signal?.aborted) return null;\n reportStorageFailure(transport, path, partNumber, status);\n return null;\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,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,MAAM,GAAG,IAAI,CAAC;QAChB,CAAC;IACH,CAAC;IACD,IAAI,OAAO,CAAC,MAAM,EAAE,OAAO;QAAE,OAAO,IAAI,CAAC;IACzC,oBAAoB,CAAC,SAAS,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,CAAC,CAAC;IAC1D,OAAO,IAAI,CAAC;AACd,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\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 attempt === 0 && isUsableIssuedSource(input.source)\n ? input.source\n : await authorizePart(context);\n if (!source) return null;\n if (source.kind === \"api\") return uploadThroughApi(context, file);\n try {\n const response = await uploadFetch(source.url, {\n method: \"PUT\",\n body: file,\n headers: {\n \"Content-Type\": \"application/octet-stream\",\n \"Content-MD5\": contentMd5,\n },\n ...storageFetchOptions(options),\n });\n 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 stageId,\n uploadId: input.uploadId,\n part: { byteLength: input.byteLength, partNumber, etag },\n };\n }\n if (!(await retryStorageStatus(status, attempt))) break;\n } catch {\n // Never expose a provider exception or body: it may contain the bearer URL.\n status = null;\n }\n }\n if (options.signal?.aborted) return null;\n reportStorageFailure(transport, path, partNumber, status);\n return null;\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"]}
|