@aws-amplify/storage 6.9.5-unstable.76548ca.0 → 6.9.6-unstable.0f5e997.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/providers/s3/apis/internal/uploadData/multipart/uploadCache.js +2 -1
- package/dist/cjs/providers/s3/apis/internal/uploadData/multipart/uploadCache.js.map +1 -1
- package/dist/cjs/providers/s3/apis/internal/uploadData/multipart/uploadHandlers.js +4 -1
- package/dist/cjs/providers/s3/apis/internal/uploadData/multipart/uploadHandlers.js.map +1 -1
- package/dist/cjs/providers/s3/apis/internal/uploadData/putObjectJob.js +4 -1
- package/dist/cjs/providers/s3/apis/internal/uploadData/putObjectJob.js.map +1 -1
- package/dist/cjs/providers/s3/utils/client/runtime/xhrTransferHandler.js +5 -1
- package/dist/cjs/providers/s3/utils/client/runtime/xhrTransferHandler.js.map +1 -1
- package/dist/cjs/utils/contentType.js +101 -0
- package/dist/cjs/utils/contentType.js.map +1 -0
- package/dist/esm/providers/s3/apis/internal/uploadData/multipart/uploadCache.mjs +2 -1
- package/dist/esm/providers/s3/apis/internal/uploadData/multipart/uploadCache.mjs.map +1 -1
- package/dist/esm/providers/s3/apis/internal/uploadData/multipart/uploadHandlers.mjs +4 -1
- package/dist/esm/providers/s3/apis/internal/uploadData/multipart/uploadHandlers.mjs.map +1 -1
- package/dist/esm/providers/s3/apis/internal/uploadData/putObjectJob.mjs +4 -1
- package/dist/esm/providers/s3/apis/internal/uploadData/putObjectJob.mjs.map +1 -1
- package/dist/esm/providers/s3/utils/client/runtime/xhrTransferHandler.mjs +5 -1
- package/dist/esm/providers/s3/utils/client/runtime/xhrTransferHandler.mjs.map +1 -1
- package/dist/esm/utils/contentType.d.ts +4 -0
- package/dist/esm/utils/contentType.mjs +98 -0
- package/dist/esm/utils/contentType.mjs.map +1 -0
- package/package.json +5 -5
- package/src/providers/s3/apis/internal/uploadData/multipart/uploadCache.ts +2 -1
- package/src/providers/s3/apis/internal/uploadData/multipart/uploadHandlers.ts +4 -1
- package/src/providers/s3/apis/internal/uploadData/putObjectJob.ts +4 -1
- package/src/providers/s3/utils/client/runtime/xhrTransferHandler.ts +5 -1
- package/src/utils/contentType.ts +99 -0
|
@@ -7,6 +7,7 @@ exports.removeCachedUpload = exports.cacheMultipartUpload = exports.getUploadsCa
|
|
|
7
7
|
const constants_1 = require("../../../../utils/constants");
|
|
8
8
|
const s3data_1 = require("../../../../utils/client/s3data");
|
|
9
9
|
const utils_1 = require("../../../../../../utils");
|
|
10
|
+
const contentType_1 = require("../../../../../../utils/contentType");
|
|
10
11
|
const ONE_HOUR = 1000 * 60 * 60;
|
|
11
12
|
/**
|
|
12
13
|
* Find the cached multipart upload id and get the parts that have been uploaded
|
|
@@ -81,7 +82,7 @@ exports.serializeUploadOptions = serializeUploadOptions;
|
|
|
81
82
|
*/
|
|
82
83
|
const getUploadsCacheKey = ({ file, size, contentType, bucket, accessLevel, key, optionsHash, }) => {
|
|
83
84
|
let levelStr;
|
|
84
|
-
const resolvedContentType = contentType ?? file
|
|
85
|
+
const resolvedContentType = contentType ?? (0, contentType_1.getContentType)(file, key) ?? 'application/octet-stream';
|
|
85
86
|
// If no access level is defined, we're using custom gen2 access rules
|
|
86
87
|
if (accessLevel === undefined) {
|
|
87
88
|
levelStr = 'custom';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uploadCache.js","sources":["../../../../../../../../src/providers/s3/apis/internal/uploadData/multipart/uploadCache.ts"],"sourcesContent":["\"use strict\";\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.removeCachedUpload = exports.cacheMultipartUpload = exports.getUploadsCacheKey = exports.serializeUploadOptions = exports.findCachedUploadPartsAndEvictExpired = void 0;\nconst constants_1 = require(\"../../../../utils/constants\");\nconst s3data_1 = require(\"../../../../utils/client/s3data\");\nconst utils_1 = require(\"../../../../../../utils\");\nconst ONE_HOUR = 1000 * 60 * 60;\n/**\n * Find the cached multipart upload id and get the parts that have been uploaded\n * with ListParts API. If the cached upload is expired(1 hour), return null.\n */\nconst findCachedUploadPartsAndEvictExpired = async ({ resumableUploadsCache, cacheKey, s3Config, bucket, finalKey, }) => {\n const allCachedUploads = await listCachedUploadTasks(resumableUploadsCache);\n // Evict all outdated uploads.\n const validCachedUploads = Object.fromEntries(Object.entries(allCachedUploads).filter(([_, cacheValue]) => cacheValue.lastTouched >= Date.now() - ONE_HOUR));\n if (Object.keys(validCachedUploads).length !==\n Object.keys(allCachedUploads).length) {\n await resumableUploadsCache.setItem(constants_1.UPLOADS_STORAGE_KEY, JSON.stringify(validCachedUploads));\n }\n if (!validCachedUploads[cacheKey]) {\n return null;\n }\n const cachedUpload = validCachedUploads[cacheKey];\n cachedUpload.lastTouched = Date.now();\n await resumableUploadsCache.setItem(constants_1.UPLOADS_STORAGE_KEY, JSON.stringify(validCachedUploads));\n try {\n const { Parts = [] } = await (0, s3data_1.listParts)(s3Config, {\n Bucket: bucket,\n Key: finalKey,\n UploadId: cachedUpload.uploadId,\n });\n return {\n parts: Parts,\n uploadId: cachedUpload.uploadId,\n finalCrc32: cachedUpload.finalCrc32,\n };\n }\n catch (e) {\n utils_1.logger.debug('failed to list cached parts, removing cached upload.');\n await (0, exports.removeCachedUpload)(resumableUploadsCache, cacheKey);\n return null;\n }\n};\nexports.findCachedUploadPartsAndEvictExpired = findCachedUploadPartsAndEvictExpired;\nconst listCachedUploadTasks = async (resumableUploadsCache) => {\n try {\n return JSON.parse((await resumableUploadsCache.getItem(constants_1.UPLOADS_STORAGE_KEY)) ?? '{}');\n }\n catch (e) {\n utils_1.logger.debug('failed to parse cached uploads record.');\n return {};\n }\n};\n/**\n * Serialize the uploadData API options to string so it can be hashed.\n */\nconst serializeUploadOptions = (options = {}) => {\n const unserializableOptionProperties = [\n 'onProgress',\n 'resumableUploadsCache', // Internally injected implementation not set by customers\n 'locationCredentialsProvider', // Internally injected implementation not set by customers\n ];\n const serializableOptionEntries = Object.entries(options).filter(([key]) => !unserializableOptionProperties.includes(key));\n if (options.checksumAlgorithm === 'crc-32') {\n // Additional options to differentiate the upload cache created before introducing the full-object checksum and\n // after. If full-object checksum is enabled, the previous upload caches that created with composite checksum should\n // be ignored.\n serializableOptionEntries.push(['checksumType', 'FULL_OBJECT']);\n }\n const serializableOptions = Object.fromEntries(serializableOptionEntries);\n return JSON.stringify(serializableOptions);\n};\nexports.serializeUploadOptions = serializeUploadOptions;\n/**\n * Get the cache key of a multipart upload. Data source cached by different: size, content type, bucket, access level,\n * key. If the data source is a File instance, the upload is additionally indexed by file name and last modified time.\n * So the library always created a new multipart upload if the file is modified.\n */\nconst getUploadsCacheKey = ({ file, size, contentType, bucket, accessLevel, key, optionsHash, }) => {\n let levelStr;\n const resolvedContentType = contentType ?? file?.type ?? 'application/octet-stream';\n // If no access level is defined, we're using custom gen2 access rules\n if (accessLevel === undefined) {\n levelStr = 'custom';\n }\n else {\n levelStr = accessLevel === 'guest' ? 'public' : accessLevel;\n }\n const baseId = `${optionsHash}_${size}_${resolvedContentType}_${bucket}_${levelStr}_${key}`;\n if (file) {\n return `${file.name}_${file.lastModified}_${baseId}`;\n }\n else {\n return baseId;\n }\n};\nexports.getUploadsCacheKey = getUploadsCacheKey;\nconst cacheMultipartUpload = async (resumableUploadsCache, cacheKey, fileMetadata) => {\n const cachedUploads = await listCachedUploadTasks(resumableUploadsCache);\n cachedUploads[cacheKey] = {\n ...fileMetadata,\n lastTouched: Date.now(),\n };\n await resumableUploadsCache.setItem(constants_1.UPLOADS_STORAGE_KEY, JSON.stringify(cachedUploads));\n};\nexports.cacheMultipartUpload = cacheMultipartUpload;\nconst removeCachedUpload = async (resumableUploadsCache, cacheKey) => {\n const cachedUploads = await listCachedUploadTasks(resumableUploadsCache);\n delete cachedUploads[cacheKey];\n await resumableUploadsCache.setItem(constants_1.UPLOADS_STORAGE_KEY, JSON.stringify(cachedUploads));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|
+
{"version":3,"file":"uploadCache.js","sources":["../../../../../../../../src/providers/s3/apis/internal/uploadData/multipart/uploadCache.ts"],"sourcesContent":["\"use strict\";\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.removeCachedUpload = exports.cacheMultipartUpload = exports.getUploadsCacheKey = exports.serializeUploadOptions = exports.findCachedUploadPartsAndEvictExpired = void 0;\nconst constants_1 = require(\"../../../../utils/constants\");\nconst s3data_1 = require(\"../../../../utils/client/s3data\");\nconst utils_1 = require(\"../../../../../../utils\");\nconst contentType_1 = require(\"../../../../../../utils/contentType\");\nconst ONE_HOUR = 1000 * 60 * 60;\n/**\n * Find the cached multipart upload id and get the parts that have been uploaded\n * with ListParts API. If the cached upload is expired(1 hour), return null.\n */\nconst findCachedUploadPartsAndEvictExpired = async ({ resumableUploadsCache, cacheKey, s3Config, bucket, finalKey, }) => {\n const allCachedUploads = await listCachedUploadTasks(resumableUploadsCache);\n // Evict all outdated uploads.\n const validCachedUploads = Object.fromEntries(Object.entries(allCachedUploads).filter(([_, cacheValue]) => cacheValue.lastTouched >= Date.now() - ONE_HOUR));\n if (Object.keys(validCachedUploads).length !==\n Object.keys(allCachedUploads).length) {\n await resumableUploadsCache.setItem(constants_1.UPLOADS_STORAGE_KEY, JSON.stringify(validCachedUploads));\n }\n if (!validCachedUploads[cacheKey]) {\n return null;\n }\n const cachedUpload = validCachedUploads[cacheKey];\n cachedUpload.lastTouched = Date.now();\n await resumableUploadsCache.setItem(constants_1.UPLOADS_STORAGE_KEY, JSON.stringify(validCachedUploads));\n try {\n const { Parts = [] } = await (0, s3data_1.listParts)(s3Config, {\n Bucket: bucket,\n Key: finalKey,\n UploadId: cachedUpload.uploadId,\n });\n return {\n parts: Parts,\n uploadId: cachedUpload.uploadId,\n finalCrc32: cachedUpload.finalCrc32,\n };\n }\n catch (e) {\n utils_1.logger.debug('failed to list cached parts, removing cached upload.');\n await (0, exports.removeCachedUpload)(resumableUploadsCache, cacheKey);\n return null;\n }\n};\nexports.findCachedUploadPartsAndEvictExpired = findCachedUploadPartsAndEvictExpired;\nconst listCachedUploadTasks = async (resumableUploadsCache) => {\n try {\n return JSON.parse((await resumableUploadsCache.getItem(constants_1.UPLOADS_STORAGE_KEY)) ?? '{}');\n }\n catch (e) {\n utils_1.logger.debug('failed to parse cached uploads record.');\n return {};\n }\n};\n/**\n * Serialize the uploadData API options to string so it can be hashed.\n */\nconst serializeUploadOptions = (options = {}) => {\n const unserializableOptionProperties = [\n 'onProgress',\n 'resumableUploadsCache', // Internally injected implementation not set by customers\n 'locationCredentialsProvider', // Internally injected implementation not set by customers\n ];\n const serializableOptionEntries = Object.entries(options).filter(([key]) => !unserializableOptionProperties.includes(key));\n if (options.checksumAlgorithm === 'crc-32') {\n // Additional options to differentiate the upload cache created before introducing the full-object checksum and\n // after. If full-object checksum is enabled, the previous upload caches that created with composite checksum should\n // be ignored.\n serializableOptionEntries.push(['checksumType', 'FULL_OBJECT']);\n }\n const serializableOptions = Object.fromEntries(serializableOptionEntries);\n return JSON.stringify(serializableOptions);\n};\nexports.serializeUploadOptions = serializeUploadOptions;\n/**\n * Get the cache key of a multipart upload. Data source cached by different: size, content type, bucket, access level,\n * key. If the data source is a File instance, the upload is additionally indexed by file name and last modified time.\n * So the library always created a new multipart upload if the file is modified.\n */\nconst getUploadsCacheKey = ({ file, size, contentType, bucket, accessLevel, key, optionsHash, }) => {\n let levelStr;\n const resolvedContentType = contentType ?? (0, contentType_1.getContentType)(file, key) ?? 'application/octet-stream';\n // If no access level is defined, we're using custom gen2 access rules\n if (accessLevel === undefined) {\n levelStr = 'custom';\n }\n else {\n levelStr = accessLevel === 'guest' ? 'public' : accessLevel;\n }\n const baseId = `${optionsHash}_${size}_${resolvedContentType}_${bucket}_${levelStr}_${key}`;\n if (file) {\n return `${file.name}_${file.lastModified}_${baseId}`;\n }\n else {\n return baseId;\n }\n};\nexports.getUploadsCacheKey = getUploadsCacheKey;\nconst cacheMultipartUpload = async (resumableUploadsCache, cacheKey, fileMetadata) => {\n const cachedUploads = await listCachedUploadTasks(resumableUploadsCache);\n cachedUploads[cacheKey] = {\n ...fileMetadata,\n lastTouched: Date.now(),\n };\n await resumableUploadsCache.setItem(constants_1.UPLOADS_STORAGE_KEY, JSON.stringify(cachedUploads));\n};\nexports.cacheMultipartUpload = cacheMultipartUpload;\nconst removeCachedUpload = async (resumableUploadsCache, cacheKey) => {\n const cachedUploads = await listCachedUploadTasks(resumableUploadsCache);\n delete cachedUploads[cacheKey];\n await resumableUploadsCache.setItem(constants_1.UPLOADS_STORAGE_KEY, JSON.stringify(cachedUploads));\n};\nexports.removeCachedUpload = removeCachedUpload;\n"],"names":[],"mappings":";;AACA;AACA;AACA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;AAC7D,OAAO,CAAC,kBAAkB,GAAG,OAAO,CAAC,oBAAoB,GAAG,OAAO,CAAC,kBAAkB,GAAG,OAAO,CAAC,sBAAsB,GAAG,OAAO,CAAC,oCAAoC,GAAG,MAAM;AAC/K,MAAM,WAAW,GAAG,OAAO,CAAC,6BAA6B,CAAC;AAC1D,MAAM,QAAQ,GAAG,OAAO,CAAC,iCAAiC,CAAC;AAC3D,MAAM,OAAO,GAAG,OAAO,CAAC,yBAAyB,CAAC;AAClD,MAAM,aAAa,GAAG,OAAO,CAAC,qCAAqC,CAAC;AACpE,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAE,GAAG,EAAE;AAC/B;AACA;AACA;AACA;AACA,MAAM,oCAAoC,GAAG,OAAO,EAAE,qBAAqB,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,GAAG,KAAK;AACzH,IAAI,MAAM,gBAAgB,GAAG,MAAM,qBAAqB,CAAC,qBAAqB,CAAC;AAC/E;AACA,IAAI,MAAM,kBAAkB,GAAG,MAAM,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B,KAAK;AACL,IAAI,MAAM,qBAAqB,CAAC,OAAO,CAAC,WAAW,CAAC,mBAAmB,EAAE,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC;AACvG,CAAC;AACD,OAAO,CAAC,oBAAoB,GAAG,oBAAoB;AACnD,MAAM,kBAAkB,GAAG,OAAO,qBAAqB,EAAE,QAAQ,KAAK;AACtE,IAAI,MAAM,aAAa,GAAG,MAAM,qBAAqB,CAAC,qBAAqB,CAAC;AAC5E,IAAI,OAAO,aAAa,CAAC,QAAQ,CAAC;AAClC,IAAI,MAAM,qBAAqB,CAAC,OAAO,CAAC,WAAW,CAAC,mBAAmB,EAAE,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC;AACvG,CAAC;AACD,OAAO,CAAC,kBAAkB,GAAG,kBAAkB;;"}
|
|
@@ -15,6 +15,7 @@ const userAgent_1 = require("../../../../utils/userAgent");
|
|
|
15
15
|
const utils_3 = require("../../../../../../utils");
|
|
16
16
|
const crc32_1 = require("../../../../utils/crc32");
|
|
17
17
|
const IntegrityError_1 = require("../../../../../../errors/IntegrityError");
|
|
18
|
+
const contentType_1 = require("../../../../../../utils/contentType");
|
|
18
19
|
const uploadPartExecutor_1 = require("./uploadPartExecutor");
|
|
19
20
|
const uploadCache_1 = require("./uploadCache");
|
|
20
21
|
const progressTracker_1 = require("./progressTracker");
|
|
@@ -55,7 +56,9 @@ const getMultipartUploadHandlers = (uploadDataInput, size) => {
|
|
|
55
56
|
resolvedIdentityId = resolvedS3Options.identityId;
|
|
56
57
|
expectedBucketOwner = uploadDataOptions?.expectedBucketOwner;
|
|
57
58
|
const { inputType, objectKey } = (0, utils_2.validateStorageOperationInput)(uploadDataInput, resolvedIdentityId);
|
|
58
|
-
const { contentDisposition, contentEncoding, contentType =
|
|
59
|
+
const { contentDisposition, contentEncoding, contentType = uploadDataOptions?.contentType ??
|
|
60
|
+
(0, contentType_1.getContentType)(data, objectKey) ??
|
|
61
|
+
'application/octet-stream', metadata, preventOverwrite, onProgress, } = uploadDataOptions ?? {};
|
|
59
62
|
finalKey = objectKey;
|
|
60
63
|
// Resolve "key" specific options
|
|
61
64
|
if (inputType === constants_1.STORAGE_INPUT_KEY) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uploadHandlers.js","sources":["../../../../../../../../src/providers/s3/apis/internal/uploadData/multipart/uploadHandlers.ts"],"sourcesContent":["\"use strict\";\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getMultipartUploadHandlers = void 0;\nconst core_1 = require(\"@aws-amplify/core\");\nconst utils_1 = require(\"@aws-amplify/core/internals/utils\");\nconst utils_2 = require(\"../../../../utils\");\nconst constants_1 = require(\"../../../../utils/constants\");\nconst StorageError_1 = require(\"../../../../../../errors/StorageError\");\nconst CanceledError_1 = require(\"../../../../../../errors/CanceledError\");\nconst s3data_1 = require(\"../../../../utils/client/s3data\");\nconst userAgent_1 = require(\"../../../../utils/userAgent\");\nconst utils_3 = require(\"../../../../../../utils\");\nconst crc32_1 = require(\"../../../../utils/crc32\");\nconst IntegrityError_1 = require(\"../../../../../../errors/IntegrityError\");\nconst uploadPartExecutor_1 = require(\"./uploadPartExecutor\");\nconst uploadCache_1 = require(\"./uploadCache\");\nconst progressTracker_1 = require(\"./progressTracker\");\nconst initialUpload_1 = require(\"./initialUpload\");\nconst getDataChunker_1 = require(\"./getDataChunker\");\nconst calculatePartSize_1 = require(\"./calculatePartSize\");\n/**\n * Create closure hiding the multipart upload implementation details and expose the upload job and control functions(\n * onPause, onResume, onCancel).\n *\n * @internal\n */\nconst getMultipartUploadHandlers = (uploadDataInput, size) => {\n let resolveCallback;\n let rejectCallback;\n let inProgressUpload;\n let resolvedS3Config;\n let abortController;\n let resolvedAccessLevel;\n let resolvedBucket;\n let resolvedKeyPrefix;\n let resolvedIdentityId;\n let uploadCacheKey;\n let finalKey;\n let expectedBucketOwner;\n // Special flag that differentiates HTTP requests abort error caused by pause() from ones caused by cancel().\n // The former one should NOT cause the upload job to throw, but cancels any pending HTTP requests.\n // This should be replaced by a special abort reason. However,the support of this API is lagged behind.\n let isAbortSignalFromPause = false;\n const { resumableUploadsCache } = uploadDataInput.options ?? {};\n const startUpload = async () => {\n const { options: uploadDataOptions, data } = uploadDataInput;\n const resolvedS3Options = await (0, utils_2.resolveS3ConfigAndInput)(core_1.Amplify, uploadDataInput);\n abortController = new AbortController();\n isAbortSignalFromPause = false;\n resolvedS3Config = resolvedS3Options.s3Config;\n resolvedBucket = resolvedS3Options.bucket;\n resolvedIdentityId = resolvedS3Options.identityId;\n expectedBucketOwner = uploadDataOptions?.expectedBucketOwner;\n const { inputType, objectKey } = (0, utils_2.validateStorageOperationInput)(uploadDataInput, resolvedIdentityId);\n const { contentDisposition, contentEncoding, contentType = 'application/octet-stream', metadata, preventOverwrite, onProgress, } = uploadDataOptions ?? {};\n finalKey = objectKey;\n // Resolve \"key\" specific options\n if (inputType === constants_1.STORAGE_INPUT_KEY) {\n const accessLevel = uploadDataOptions\n ?.accessLevel;\n resolvedKeyPrefix = resolvedS3Options.keyPrefix;\n finalKey = resolvedKeyPrefix + objectKey;\n resolvedAccessLevel = resolveAccessLevel(accessLevel);\n }\n const optionsHash = await (0, crc32_1.calculateContentCRC32)((0, uploadCache_1.serializeUploadOptions)(uploadDataOptions));\n if (!inProgressUpload) {\n const { uploadId, cachedParts, finalCrc32 } = await (0, initialUpload_1.loadOrCreateMultipartUpload)({\n s3Config: resolvedS3Config,\n accessLevel: resolvedAccessLevel,\n bucket: resolvedBucket,\n keyPrefix: resolvedKeyPrefix,\n key: objectKey,\n contentType,\n contentDisposition,\n contentEncoding,\n metadata,\n data,\n size,\n abortSignal: abortController.signal,\n checksumAlgorithm: uploadDataOptions?.checksumAlgorithm,\n optionsHash,\n resumableUploadsCache,\n expectedBucketOwner,\n });\n inProgressUpload = {\n uploadId,\n completedParts: cachedParts,\n finalCrc32,\n };\n }\n uploadCacheKey = size\n ? (0, uploadCache_1.getUploadsCacheKey)({\n file: data instanceof File ? data : undefined,\n accessLevel: resolvedAccessLevel,\n contentType: uploadDataOptions?.contentType,\n bucket: resolvedBucket,\n size,\n key: objectKey,\n optionsHash,\n })\n : undefined;\n const dataChunker = (0, getDataChunker_1.getDataChunker)(data, size);\n const completedPartNumberSet = new Set(inProgressUpload.completedParts.map(({ PartNumber }) => PartNumber));\n const onPartUploadCompletion = (partNumber, eTag, crc32) => {\n inProgressUpload?.completedParts.push({\n PartNumber: partNumber,\n ETag: eTag,\n // TODO: crc32 can always be added once RN also has an implementation\n ...(crc32 ? { ChecksumCRC32: crc32 } : {}),\n });\n };\n const concurrentUploadsProgressTracker = (0, progressTracker_1.getConcurrentUploadsProgressTracker)({\n size,\n onProgress,\n });\n const concurrentUploadPartExecutors = [];\n for (let index = 0; index < constants_1.DEFAULT_QUEUE_SIZE; index++) {\n concurrentUploadPartExecutors.push((0, uploadPartExecutor_1.uploadPartExecutor)({\n dataChunkerGenerator: dataChunker,\n completedPartNumberSet,\n s3Config: resolvedS3Config,\n abortSignal: abortController.signal,\n bucket: resolvedBucket,\n finalKey,\n uploadId: inProgressUpload.uploadId,\n onPartUploadCompletion,\n onProgress: concurrentUploadsProgressTracker.getOnProgressListener(),\n isObjectLockEnabled: resolvedS3Options.isObjectLockEnabled,\n useCRC32Checksum: Boolean(inProgressUpload.finalCrc32),\n expectedBucketOwner,\n }));\n }\n await Promise.all(concurrentUploadPartExecutors);\n validateCompletedParts(inProgressUpload.completedParts, size);\n const { ETag: eTag } = await (0, s3data_1.completeMultipartUpload)({\n ...resolvedS3Config,\n abortSignal: abortController.signal,\n userAgentValue: (0, userAgent_1.getStorageUserAgentValue)(utils_1.StorageAction.UploadData),\n }, {\n Bucket: resolvedBucket,\n Key: finalKey,\n UploadId: inProgressUpload.uploadId,\n ChecksumCRC32: inProgressUpload.finalCrc32,\n ChecksumType: inProgressUpload.finalCrc32 ? 'FULL_OBJECT' : undefined,\n IfNoneMatch: preventOverwrite ? '*' : undefined,\n MultipartUpload: {\n Parts: sortUploadParts(inProgressUpload.completedParts),\n },\n ExpectedBucketOwner: expectedBucketOwner,\n });\n // If full-object CRC32 checksum is NOT enabled, we need to ensure the upload integrity by making extra HEAD call\n // to verify the uploaded object size.\n if (!inProgressUpload.finalCrc32) {\n const { ContentLength: uploadedObjectSize, $metadata } = await (0, s3data_1.headObject)(resolvedS3Config, {\n Bucket: resolvedBucket,\n Key: finalKey,\n ExpectedBucketOwner: expectedBucketOwner,\n });\n if (uploadedObjectSize && uploadedObjectSize !== size) {\n throw new StorageError_1.StorageError({\n name: 'Error',\n message: `Upload failed. Expected object size ${size}, but got ${uploadedObjectSize}.`,\n metadata: $metadata,\n });\n }\n }\n if (resumableUploadsCache && uploadCacheKey) {\n await (0, uploadCache_1.removeCachedUpload)(resumableUploadsCache, uploadCacheKey);\n }\n const result = {\n eTag,\n contentType,\n metadata,\n };\n return inputType === constants_1.STORAGE_INPUT_KEY\n ? { key: objectKey, ...result }\n : { path: objectKey, ...result };\n };\n const startUploadWithResumability = () => startUpload()\n .then(resolveCallback)\n .catch(error => {\n const abortSignal = abortController?.signal;\n if (abortSignal?.aborted && isAbortSignalFromPause) {\n utils_3.logger.debug('upload paused.');\n }\n else {\n // Uncaught errors should be exposed to the users.\n rejectCallback(error);\n }\n });\n const multipartUploadJob = () => new Promise((resolve, reject) => {\n resolveCallback = resolve;\n rejectCallback = reject;\n startUploadWithResumability();\n });\n const onPause = () => {\n isAbortSignalFromPause = true;\n abortController?.abort();\n };\n const onResume = () => {\n startUploadWithResumability();\n };\n const onCancel = (message) => {\n // 1. abort in-flight API requests\n abortController?.abort(message);\n const cancelUpload = async () => {\n // 2. clear upload cache.\n if (uploadCacheKey && resumableUploadsCache) {\n await (0, uploadCache_1.removeCachedUpload)(resumableUploadsCache, uploadCacheKey);\n }\n // 3. clear multipart upload on server side.\n await (0, s3data_1.abortMultipartUpload)(resolvedS3Config, {\n Bucket: resolvedBucket,\n Key: finalKey,\n UploadId: inProgressUpload?.uploadId,\n ExpectedBucketOwner: expectedBucketOwner,\n });\n };\n cancelUpload().catch(e => {\n utils_3.logger.debug('error when cancelling upload task.', e);\n });\n rejectCallback(\n // Internal error that should not be exposed to the users. They should use isCancelError() to check if\n // the error is caused by cancel().\n new CanceledError_1.CanceledError(message ? { message } : undefined));\n };\n return {\n multipartUploadJob,\n onPause,\n onResume,\n onCancel,\n };\n};\nexports.getMultipartUploadHandlers = getMultipartUploadHandlers;\nconst resolveAccessLevel = (accessLevel) => accessLevel ??\n core_1.Amplify.libraryOptions.Storage?.S3?.defaultAccessLevel ??\n constants_1.DEFAULT_ACCESS_LEVEL;\nconst validateCompletedParts = (completedParts, size) => {\n const partsExpected = Math.ceil(size / (0, calculatePartSize_1.calculatePartSize)(size));\n const validPartCount = completedParts.length === partsExpected;\n const sorted = sortUploadParts(completedParts);\n const validPartNumbers = sorted.every((part, index) => part.PartNumber === index + 1);\n if (!validPartCount || !validPartNumbers) {\n throw new IntegrityError_1.IntegrityError();\n }\n};\nconst sortUploadParts = (parts) => {\n return [...parts].sort((partA, partB) => partA.PartNumber - partB.PartNumber);\n};\n"],"names":[],"mappings":";;AACA;AACA;AACA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;AAC7D,OAAO,CAAC,0BAA0B,GAAG,MAAM;AAC3C,MAAM,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC;AAC3C,MAAM,OAAO,GAAG,OAAO,CAAC,mCAAmC,CAAC;AAC5D,MAAM,OAAO,GAAG,OAAO,CAAC,mBAAmB,CAAC;AAC5C,MAAM,WAAW,GAAG,OAAO,CAAC,6BAA6B,CAAC;AAC1D,MAAM,cAAc,GAAG,OAAO,CAAC,uCAAuC,CAAC;AACvE,MAAM,eAAe,GAAG,OAAO,CAAC,wCAAwC,CAAC;AACzE,MAAM,QAAQ,G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E,IAAI,KAAK;AACzD,IAAI,MAAM,aAAa,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,GAAG,IAAI,mBAAmB,CAAC,iBAAiB,EAAE,IAAI,CAAC,CAAC;AAC5F,IAAI,MAAM,cAAc,GAAG,cAAc,CAAC,MAAM,KAAK,aAAa;AAClE,IAAI,MAAM,MAAM,GAAG,eAAe,CAAC,cAAc,CAAC;AAClD,IAAI,MAAM,gBAAgB,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,KAAK,KAAK,IAAI,CAAC,UAAU,KAAK,KAAK,GAAG,CAAC,CAAC;AACzF,IAAI,IAAI,CAAC,cAAc,IAAI,CAAC,gBAAgB,EAAE;AAC9C,QAAQ,MAAM,IAAI,gBAAgB,CAAC,cAAc,EAAE;AACnD,IAAI;AACJ,CAAC;AACD,MAAM,eAAe,GAAG,CAAC,KAAK,KAAK;AACnC,IAAI,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,KAAK,KAAK,KAAK,CAAC,UAAU,GAAG,KAAK,CAAC,UAAU,CAAC;AACjF,CAAC;;"}
|
|
1
|
+
{"version":3,"file":"uploadHandlers.js","sources":["../../../../../../../../src/providers/s3/apis/internal/uploadData/multipart/uploadHandlers.ts"],"sourcesContent":["\"use strict\";\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getMultipartUploadHandlers = void 0;\nconst core_1 = require(\"@aws-amplify/core\");\nconst utils_1 = require(\"@aws-amplify/core/internals/utils\");\nconst utils_2 = require(\"../../../../utils\");\nconst constants_1 = require(\"../../../../utils/constants\");\nconst StorageError_1 = require(\"../../../../../../errors/StorageError\");\nconst CanceledError_1 = require(\"../../../../../../errors/CanceledError\");\nconst s3data_1 = require(\"../../../../utils/client/s3data\");\nconst userAgent_1 = require(\"../../../../utils/userAgent\");\nconst utils_3 = require(\"../../../../../../utils\");\nconst crc32_1 = require(\"../../../../utils/crc32\");\nconst IntegrityError_1 = require(\"../../../../../../errors/IntegrityError\");\nconst contentType_1 = require(\"../../../../../../utils/contentType\");\nconst uploadPartExecutor_1 = require(\"./uploadPartExecutor\");\nconst uploadCache_1 = require(\"./uploadCache\");\nconst progressTracker_1 = require(\"./progressTracker\");\nconst initialUpload_1 = require(\"./initialUpload\");\nconst getDataChunker_1 = require(\"./getDataChunker\");\nconst calculatePartSize_1 = require(\"./calculatePartSize\");\n/**\n * Create closure hiding the multipart upload implementation details and expose the upload job and control functions(\n * onPause, onResume, onCancel).\n *\n * @internal\n */\nconst getMultipartUploadHandlers = (uploadDataInput, size) => {\n let resolveCallback;\n let rejectCallback;\n let inProgressUpload;\n let resolvedS3Config;\n let abortController;\n let resolvedAccessLevel;\n let resolvedBucket;\n let resolvedKeyPrefix;\n let resolvedIdentityId;\n let uploadCacheKey;\n let finalKey;\n let expectedBucketOwner;\n // Special flag that differentiates HTTP requests abort error caused by pause() from ones caused by cancel().\n // The former one should NOT cause the upload job to throw, but cancels any pending HTTP requests.\n // This should be replaced by a special abort reason. However,the support of this API is lagged behind.\n let isAbortSignalFromPause = false;\n const { resumableUploadsCache } = uploadDataInput.options ?? {};\n const startUpload = async () => {\n const { options: uploadDataOptions, data } = uploadDataInput;\n const resolvedS3Options = await (0, utils_2.resolveS3ConfigAndInput)(core_1.Amplify, uploadDataInput);\n abortController = new AbortController();\n isAbortSignalFromPause = false;\n resolvedS3Config = resolvedS3Options.s3Config;\n resolvedBucket = resolvedS3Options.bucket;\n resolvedIdentityId = resolvedS3Options.identityId;\n expectedBucketOwner = uploadDataOptions?.expectedBucketOwner;\n const { inputType, objectKey } = (0, utils_2.validateStorageOperationInput)(uploadDataInput, resolvedIdentityId);\n const { contentDisposition, contentEncoding, contentType = uploadDataOptions?.contentType ??\n (0, contentType_1.getContentType)(data, objectKey) ??\n 'application/octet-stream', metadata, preventOverwrite, onProgress, } = uploadDataOptions ?? {};\n finalKey = objectKey;\n // Resolve \"key\" specific options\n if (inputType === constants_1.STORAGE_INPUT_KEY) {\n const accessLevel = uploadDataOptions\n ?.accessLevel;\n resolvedKeyPrefix = resolvedS3Options.keyPrefix;\n finalKey = resolvedKeyPrefix + objectKey;\n resolvedAccessLevel = resolveAccessLevel(accessLevel);\n }\n const optionsHash = await (0, crc32_1.calculateContentCRC32)((0, uploadCache_1.serializeUploadOptions)(uploadDataOptions));\n if (!inProgressUpload) {\n const { uploadId, cachedParts, finalCrc32 } = await (0, initialUpload_1.loadOrCreateMultipartUpload)({\n s3Config: resolvedS3Config,\n accessLevel: resolvedAccessLevel,\n bucket: resolvedBucket,\n keyPrefix: resolvedKeyPrefix,\n key: objectKey,\n contentType,\n contentDisposition,\n contentEncoding,\n metadata,\n data,\n size,\n abortSignal: abortController.signal,\n checksumAlgorithm: uploadDataOptions?.checksumAlgorithm,\n optionsHash,\n resumableUploadsCache,\n expectedBucketOwner,\n });\n inProgressUpload = {\n uploadId,\n completedParts: cachedParts,\n finalCrc32,\n };\n }\n uploadCacheKey = size\n ? (0, uploadCache_1.getUploadsCacheKey)({\n file: data instanceof File ? data : undefined,\n accessLevel: resolvedAccessLevel,\n contentType: uploadDataOptions?.contentType,\n bucket: resolvedBucket,\n size,\n key: objectKey,\n optionsHash,\n })\n : undefined;\n const dataChunker = (0, getDataChunker_1.getDataChunker)(data, size);\n const completedPartNumberSet = new Set(inProgressUpload.completedParts.map(({ PartNumber }) => PartNumber));\n const onPartUploadCompletion = (partNumber, eTag, crc32) => {\n inProgressUpload?.completedParts.push({\n PartNumber: partNumber,\n ETag: eTag,\n // TODO: crc32 can always be added once RN also has an implementation\n ...(crc32 ? { ChecksumCRC32: crc32 } : {}),\n });\n };\n const concurrentUploadsProgressTracker = (0, progressTracker_1.getConcurrentUploadsProgressTracker)({\n size,\n onProgress,\n });\n const concurrentUploadPartExecutors = [];\n for (let index = 0; index < constants_1.DEFAULT_QUEUE_SIZE; index++) {\n concurrentUploadPartExecutors.push((0, uploadPartExecutor_1.uploadPartExecutor)({\n dataChunkerGenerator: dataChunker,\n completedPartNumberSet,\n s3Config: resolvedS3Config,\n abortSignal: abortController.signal,\n bucket: resolvedBucket,\n finalKey,\n uploadId: inProgressUpload.uploadId,\n onPartUploadCompletion,\n onProgress: concurrentUploadsProgressTracker.getOnProgressListener(),\n isObjectLockEnabled: resolvedS3Options.isObjectLockEnabled,\n useCRC32Checksum: Boolean(inProgressUpload.finalCrc32),\n expectedBucketOwner,\n }));\n }\n await Promise.all(concurrentUploadPartExecutors);\n validateCompletedParts(inProgressUpload.completedParts, size);\n const { ETag: eTag } = await (0, s3data_1.completeMultipartUpload)({\n ...resolvedS3Config,\n abortSignal: abortController.signal,\n userAgentValue: (0, userAgent_1.getStorageUserAgentValue)(utils_1.StorageAction.UploadData),\n }, {\n Bucket: resolvedBucket,\n Key: finalKey,\n UploadId: inProgressUpload.uploadId,\n ChecksumCRC32: inProgressUpload.finalCrc32,\n ChecksumType: inProgressUpload.finalCrc32 ? 'FULL_OBJECT' : undefined,\n IfNoneMatch: preventOverwrite ? '*' : undefined,\n MultipartUpload: {\n Parts: sortUploadParts(inProgressUpload.completedParts),\n },\n ExpectedBucketOwner: expectedBucketOwner,\n });\n // If full-object CRC32 checksum is NOT enabled, we need to ensure the upload integrity by making extra HEAD call\n // to verify the uploaded object size.\n if (!inProgressUpload.finalCrc32) {\n const { ContentLength: uploadedObjectSize, $metadata } = await (0, s3data_1.headObject)(resolvedS3Config, {\n Bucket: resolvedBucket,\n Key: finalKey,\n ExpectedBucketOwner: expectedBucketOwner,\n });\n if (uploadedObjectSize && uploadedObjectSize !== size) {\n throw new StorageError_1.StorageError({\n name: 'Error',\n message: `Upload failed. Expected object size ${size}, but got ${uploadedObjectSize}.`,\n metadata: $metadata,\n });\n }\n }\n if (resumableUploadsCache && uploadCacheKey) {\n await (0, uploadCache_1.removeCachedUpload)(resumableUploadsCache, uploadCacheKey);\n }\n const result = {\n eTag,\n contentType,\n metadata,\n };\n return inputType === constants_1.STORAGE_INPUT_KEY\n ? { key: objectKey, ...result }\n : { path: objectKey, ...result };\n };\n const startUploadWithResumability = () => startUpload()\n .then(resolveCallback)\n .catch(error => {\n const abortSignal = abortController?.signal;\n if (abortSignal?.aborted && isAbortSignalFromPause) {\n utils_3.logger.debug('upload paused.');\n }\n else {\n // Uncaught errors should be exposed to the users.\n rejectCallback(error);\n }\n });\n const multipartUploadJob = () => new Promise((resolve, reject) => {\n resolveCallback = resolve;\n rejectCallback = reject;\n startUploadWithResumability();\n });\n const onPause = () => {\n isAbortSignalFromPause = true;\n abortController?.abort();\n };\n const onResume = () => {\n startUploadWithResumability();\n };\n const onCancel = (message) => {\n // 1. abort in-flight API requests\n abortController?.abort(message);\n const cancelUpload = async () => {\n // 2. clear upload cache.\n if (uploadCacheKey && resumableUploadsCache) {\n await (0, uploadCache_1.removeCachedUpload)(resumableUploadsCache, uploadCacheKey);\n }\n // 3. clear multipart upload on server side.\n await (0, s3data_1.abortMultipartUpload)(resolvedS3Config, {\n Bucket: resolvedBucket,\n Key: finalKey,\n UploadId: inProgressUpload?.uploadId,\n ExpectedBucketOwner: expectedBucketOwner,\n });\n };\n cancelUpload().catch(e => {\n utils_3.logger.debug('error when cancelling upload task.', e);\n });\n rejectCallback(\n // Internal error that should not be exposed to the users. They should use isCancelError() to check if\n // the error is caused by cancel().\n new CanceledError_1.CanceledError(message ? { message } : undefined));\n };\n return {\n multipartUploadJob,\n onPause,\n onResume,\n onCancel,\n };\n};\nexports.getMultipartUploadHandlers = getMultipartUploadHandlers;\nconst resolveAccessLevel = (accessLevel) => accessLevel ??\n core_1.Amplify.libraryOptions.Storage?.S3?.defaultAccessLevel ??\n constants_1.DEFAULT_ACCESS_LEVEL;\nconst validateCompletedParts = (completedParts, size) => {\n const partsExpected = Math.ceil(size / (0, calculatePartSize_1.calculatePartSize)(size));\n const validPartCount = completedParts.length === partsExpected;\n const sorted = sortUploadParts(completedParts);\n const validPartNumbers = sorted.every((part, index) => part.PartNumber === index + 1);\n if (!validPartCount || !validPartNumbers) {\n throw new IntegrityError_1.IntegrityError();\n }\n};\nconst sortUploadParts = (parts) => {\n return [...parts].sort((partA, partB) => partA.PartNumber - partB.PartNumber);\n};\n"],"names":[],"mappings":";;AACA;AACA;AACA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;AAC7D,OAAO,CAAC,0BAA0B,GAAG,MAAM;AAC3C,MAAM,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC;AAC3C,MAAM,OAAO,GAAG,OAAO,CAAC,mCAAmC,CAAC;AAC5D,MAAM,OAAO,GAAG,OAAO,CAAC,mBAAmB,CAAC;AAC5C,MAAM,WAAW,GAAG,OAAO,CAAC,6BAA6B,CAAC;AAC1D,MAAM,cAAc,GAAG,OAAO,CAAC,uCAAuC,CAAC;AACvE,MAAM,eAAe,GAAG,OAAO,CAAC,wCAAwC,CAAC;AACzE,MAAM,QAAQ,GAAG,OAAO,CAAC,iCAAiC,CAAC;AAC3D,MAAM,WAAW,GAAG,OAAO,CAAC,6BAA6B,CAAC;AAC1D,MAAM,OAAO,GAAG,OAAO,CAAC,yBAAyB,CAAC;AAClD,MAAM,OAAO,GAAG,OAAO,CAAC,yBAAyB,CAAC;AAClD,MAAM,gBAAgB,GAAG,OAAO,CAAC,yCAAyC,CAAC;AAC3E,MAAM,aAAa,GAAG,OAAO,CAAC,qCAAqC,CAAC;AACpE,MAAM,oBAAoB,GAAG,OAAO,CAAC,sBAAsB,CAAC;AAC5D,MAAM,aAAa,GAAG,OAAO,CAAC,eAAe,CAAC;AAC9C,MAAM,iBAAiB,GAAG,OAAO,CAAC,mBAAmB,CAAC;AACtD,MAAM,eAAe,GAAG,OAAO,CAAC,iBAAiB,CAAC;AAClD,MAAM,gBAAgB,GAAG,OAAO,CAAC,kBAAkB,CAAC;AACpD,MAAM,mBAAmB,GAAG,OAAO,CAAC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AAE;AAC9C,QAAQ,MAAM,IAAI,gBAAgB,CAAC,cAAc,EAAE;AACnD,IAAI;AACJ,CAAC;AACD,MAAM,eAAe,GAAG,CAAC,KAAK,KAAK;AACnC,IAAI,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,KAAK,KAAK,KAAK,CAAC,UAAU,GAAG,KAAK,CAAC,UAAU,CAAC;AACjF,CAAC;;"}
|
|
@@ -12,6 +12,7 @@ const userAgent_1 = require("../../../utils/userAgent");
|
|
|
12
12
|
const constants_1 = require("../../../utils/constants");
|
|
13
13
|
const crc32_1 = require("../../../utils/crc32");
|
|
14
14
|
const constructContentDisposition_1 = require("../../../utils/constructContentDisposition");
|
|
15
|
+
const contentType_1 = require("../../../../../utils/contentType");
|
|
15
16
|
/**
|
|
16
17
|
* Get a function the returns a promise to call putObject API to S3.
|
|
17
18
|
*
|
|
@@ -23,7 +24,9 @@ const putObjectJob = (uploadDataInput, abortSignal, totalLength) => async () =>
|
|
|
23
24
|
const { inputType, objectKey } = (0, utils_2.validateStorageOperationInput)(uploadDataInput, identityId);
|
|
24
25
|
(0, utils_2.validateBucketOwnerID)(uploadDataOptions?.expectedBucketOwner);
|
|
25
26
|
const finalKey = inputType === constants_1.STORAGE_INPUT_KEY ? keyPrefix + objectKey : objectKey;
|
|
26
|
-
const { contentDisposition, contentEncoding, contentType =
|
|
27
|
+
const { contentDisposition, contentEncoding, contentType = uploadDataOptions?.contentType ??
|
|
28
|
+
(0, contentType_1.getContentType)(data, objectKey) ??
|
|
29
|
+
'application/octet-stream', preventOverwrite, metadata, checksumAlgorithm, onProgress, expectedBucketOwner, } = uploadDataOptions ?? {};
|
|
27
30
|
const checksumCRC32 = checksumAlgorithm === constants_1.CHECKSUM_ALGORITHM_CRC32
|
|
28
31
|
? await (0, crc32_1.calculateContentCRC32)(data)
|
|
29
32
|
: undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"putObjectJob.js","sources":["../../../../../../../src/providers/s3/apis/internal/uploadData/putObjectJob.ts"],"sourcesContent":["\"use strict\";\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.putObjectJob = void 0;\nconst core_1 = require(\"@aws-amplify/core\");\nconst utils_1 = require(\"@aws-amplify/core/internals/utils\");\nconst utils_2 = require(\"../../../utils\");\nconst s3data_1 = require(\"../../../utils/client/s3data\");\nconst userAgent_1 = require(\"../../../utils/userAgent\");\nconst constants_1 = require(\"../../../utils/constants\");\nconst crc32_1 = require(\"../../../utils/crc32\");\nconst constructContentDisposition_1 = require(\"../../../utils/constructContentDisposition\");\n/**\n * Get a function the returns a promise to call putObject API to S3.\n *\n * @internal\n */\nconst putObjectJob = (uploadDataInput, abortSignal, totalLength) => async () => {\n const { options: uploadDataOptions, data } = uploadDataInput;\n const { bucket, keyPrefix, s3Config, isObjectLockEnabled, identityId } = await (0, utils_2.resolveS3ConfigAndInput)(core_1.Amplify, uploadDataInput);\n const { inputType, objectKey } = (0, utils_2.validateStorageOperationInput)(uploadDataInput, identityId);\n (0, utils_2.validateBucketOwnerID)(uploadDataOptions?.expectedBucketOwner);\n const finalKey = inputType === constants_1.STORAGE_INPUT_KEY ? keyPrefix + objectKey : objectKey;\n const { contentDisposition, contentEncoding, contentType = 'application/octet-stream', preventOverwrite, metadata, checksumAlgorithm, onProgress, expectedBucketOwner, } = uploadDataOptions ?? {};\n const checksumCRC32 = checksumAlgorithm === constants_1.CHECKSUM_ALGORITHM_CRC32\n ? await (0, crc32_1.calculateContentCRC32)(data)\n : undefined;\n const contentMD5 = \n // check if checksum exists. ex: should not exist in react native\n !checksumCRC32 && isObjectLockEnabled\n ? await (0, utils_2.calculateContentMd5)(data)\n : undefined;\n const { ETag: eTag, VersionId: versionId } = await (0, s3data_1.putObject)({\n ...s3Config,\n abortSignal,\n onUploadProgress: onProgress,\n userAgentValue: (0, userAgent_1.getStorageUserAgentValue)(utils_1.StorageAction.UploadData),\n }, {\n Bucket: bucket,\n Key: finalKey,\n Body: data,\n ContentType: contentType,\n ContentDisposition: (0, constructContentDisposition_1.constructContentDisposition)(contentDisposition),\n ContentEncoding: contentEncoding,\n Metadata: metadata,\n ContentMD5: contentMD5,\n ChecksumCRC32: checksumCRC32,\n ExpectedBucketOwner: expectedBucketOwner,\n IfNoneMatch: preventOverwrite ? '*' : undefined,\n });\n const result = {\n eTag,\n versionId,\n contentType,\n metadata,\n size: totalLength,\n };\n return inputType === constants_1.STORAGE_INPUT_KEY\n ? { key: objectKey, ...result }\n : { path: objectKey, ...result };\n};\nexports.putObjectJob = putObjectJob;\n"],"names":[],"mappings":";;AACA;AACA;AACA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;AAC7D,OAAO,CAAC,YAAY,GAAG,MAAM;AAC7B,MAAM,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC;AAC3C,MAAM,OAAO,GAAG,OAAO,CAAC,mCAAmC,CAAC;AAC5D,MAAM,OAAO,GAAG,OAAO,CAAC,gBAAgB,CAAC;AACzC,MAAM,QAAQ,GAAG,OAAO,CAAC,8BAA8B,CAAC;AACxD,MAAM,WAAW,GAAG,OAAO,CAAC,0BAA0B,CAAC;AACvD,MAAM,WAAW,GAAG,OAAO,CAAC,0BAA0B,CAAC;AACvD,MAAM,OAAO,GAAG,OAAO,CAAC,sBAAsB,CAAC;AAC/C,MAAM,6BAA6B,GAAG,OAAO,CAAC,4CAA4C,CAAC;AAC3F;AACA;AACA;AACA;AACA;AACA,MAAM,YAAY,GAAG,CAAC,eAAe,EAAE,WAAW,EAAE,WAAW,KAAK,YAAY;AAChF,IAAI,MAAM,EAAE,OAAO,EAAE,iBAAiB,EAAE,IAAI,EAAE,GAAG,eAAe;AAChE,IAAI,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,QAAQ,EAAE,mBAAmB,EAAE,UAAU,EAAE,GAAG,MAAM,IAAI,OAAO,CAAC,uBAAuB,EAAE,MAAM,CAAC,OAAO,EAAE,eAAe,CAAC;AACxJ,IAAI,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,IAAI,OAAO,CAAC,6BAA6B,EAAE,eAAe,EAAE,UAAU,CAAC;AAC5G,IAAI,IAAI,OAAO,CAAC,qBAAqB,EAAE,iBAAiB,EAAE,mBAAmB,CAAC;AAC9E,IAAI,MAAM,QAAQ,GAAG,SAAS,KAAK,WAAW,CAAC,iBAAiB,GAAG,SAAS,GAAG,SAAS,GAAG,SAAS;AACpG,IAAI,MAAM,EAAE,kBAAkB,EAAE,eAAe,EAAE,WAAW,GAAG,0BAA0B,EAAE,gBAAgB,EAAE,QAAQ,EAAE,iBAAiB,EAAE,UAAU,EAAE,mBAAmB,GAAG,GAAG,iBAAiB,IAAI,EAAE;
|
|
1
|
+
{"version":3,"file":"putObjectJob.js","sources":["../../../../../../../src/providers/s3/apis/internal/uploadData/putObjectJob.ts"],"sourcesContent":["\"use strict\";\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.putObjectJob = void 0;\nconst core_1 = require(\"@aws-amplify/core\");\nconst utils_1 = require(\"@aws-amplify/core/internals/utils\");\nconst utils_2 = require(\"../../../utils\");\nconst s3data_1 = require(\"../../../utils/client/s3data\");\nconst userAgent_1 = require(\"../../../utils/userAgent\");\nconst constants_1 = require(\"../../../utils/constants\");\nconst crc32_1 = require(\"../../../utils/crc32\");\nconst constructContentDisposition_1 = require(\"../../../utils/constructContentDisposition\");\nconst contentType_1 = require(\"../../../../../utils/contentType\");\n/**\n * Get a function the returns a promise to call putObject API to S3.\n *\n * @internal\n */\nconst putObjectJob = (uploadDataInput, abortSignal, totalLength) => async () => {\n const { options: uploadDataOptions, data } = uploadDataInput;\n const { bucket, keyPrefix, s3Config, isObjectLockEnabled, identityId } = await (0, utils_2.resolveS3ConfigAndInput)(core_1.Amplify, uploadDataInput);\n const { inputType, objectKey } = (0, utils_2.validateStorageOperationInput)(uploadDataInput, identityId);\n (0, utils_2.validateBucketOwnerID)(uploadDataOptions?.expectedBucketOwner);\n const finalKey = inputType === constants_1.STORAGE_INPUT_KEY ? keyPrefix + objectKey : objectKey;\n const { contentDisposition, contentEncoding, contentType = uploadDataOptions?.contentType ??\n (0, contentType_1.getContentType)(data, objectKey) ??\n 'application/octet-stream', preventOverwrite, metadata, checksumAlgorithm, onProgress, expectedBucketOwner, } = uploadDataOptions ?? {};\n const checksumCRC32 = checksumAlgorithm === constants_1.CHECKSUM_ALGORITHM_CRC32\n ? await (0, crc32_1.calculateContentCRC32)(data)\n : undefined;\n const contentMD5 = \n // check if checksum exists. ex: should not exist in react native\n !checksumCRC32 && isObjectLockEnabled\n ? await (0, utils_2.calculateContentMd5)(data)\n : undefined;\n const { ETag: eTag, VersionId: versionId } = await (0, s3data_1.putObject)({\n ...s3Config,\n abortSignal,\n onUploadProgress: onProgress,\n userAgentValue: (0, userAgent_1.getStorageUserAgentValue)(utils_1.StorageAction.UploadData),\n }, {\n Bucket: bucket,\n Key: finalKey,\n Body: data,\n ContentType: contentType,\n ContentDisposition: (0, constructContentDisposition_1.constructContentDisposition)(contentDisposition),\n ContentEncoding: contentEncoding,\n Metadata: metadata,\n ContentMD5: contentMD5,\n ChecksumCRC32: checksumCRC32,\n ExpectedBucketOwner: expectedBucketOwner,\n IfNoneMatch: preventOverwrite ? '*' : undefined,\n });\n const result = {\n eTag,\n versionId,\n contentType,\n metadata,\n size: totalLength,\n };\n return inputType === constants_1.STORAGE_INPUT_KEY\n ? { key: objectKey, ...result }\n : { path: objectKey, ...result };\n};\nexports.putObjectJob = putObjectJob;\n"],"names":[],"mappings":";;AACA;AACA;AACA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,C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QAAQ,IAAI;AACZ,QAAQ,SAAS;AACjB,QAAQ,WAAW;AACnB,QAAQ,QAAQ;AAChB,QAAQ,IAAI,EAAE,WAAW;AACzB,KAAK;AACL,IAAI,OAAO,SAAS,KAAK,WAAW,CAAC;AACrC,UAAU,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,MAAM;AACrC,UAAU,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG,MAAM,EAAE;AACxC,CAAC;AACD,OAAO,CAAC,YAAY,GAAG,YAAY;;"}
|
|
@@ -134,7 +134,11 @@ const xhrTransferHandler = (request, options) => {
|
|
|
134
134
|
};
|
|
135
135
|
exports.xhrTransferHandler = xhrTransferHandler;
|
|
136
136
|
const convertToTransferProgressEvent = (event) => ({
|
|
137
|
-
|
|
137
|
+
// `loaded` can exceed the `total` in some cases due to platform issues/bugs e.g. React Native & Expo Android
|
|
138
|
+
// clamp `loaded` values down to `total` if possible.
|
|
139
|
+
transferredBytes: event.lengthComputable
|
|
140
|
+
? Math.min(event.loaded, event.total)
|
|
141
|
+
: event.loaded,
|
|
138
142
|
totalBytes: event.lengthComputable ? event.total : undefined,
|
|
139
143
|
});
|
|
140
144
|
const buildHandlerError = (message, name) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"xhrTransferHandler.js","sources":["../../../../../../../src/providers/s3/utils/client/runtime/xhrTransferHandler.ts"],"sourcesContent":["\"use strict\";\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.xhrTransferHandler = void 0;\nconst aws_client_utils_1 = require(\"@aws-amplify/core/internals/aws-client-utils\");\nconst core_1 = require(\"@aws-amplify/core\");\nconst CanceledError_1 = require(\"../../../../../errors/CanceledError\");\nconst StorageError_1 = require(\"../../../../../errors/StorageError\");\nconst constants_1 = require(\"./constants\");\nconst logger = new core_1.ConsoleLogger('xhr-http-handler');\n/**\n * Base transfer handler implementation using XMLHttpRequest to support upload and download progress events.\n *\n * @param request - The request object.\n * @param options - The request options.\n * @returns A promise that will be resolved with the response object.\n *\n * @internal\n */\nconst xhrTransferHandler = (request, options) => {\n const { url, method, headers, body } = request;\n const { onDownloadProgress, onUploadProgress, responseType, abortSignal } = options;\n return new Promise((resolve, reject) => {\n let xhr = new XMLHttpRequest();\n xhr.open(method.toUpperCase(), url.toString());\n Object.entries(headers)\n .filter(([header]) => !FORBIDDEN_HEADERS.includes(header))\n .forEach(([header, value]) => {\n xhr.setRequestHeader(header, value);\n });\n xhr.responseType = responseType;\n if (onDownloadProgress) {\n xhr.addEventListener('progress', event => {\n onDownloadProgress(convertToTransferProgressEvent(event));\n logger.debug(event);\n });\n }\n if (onUploadProgress) {\n xhr.upload.addEventListener('progress', event => {\n onUploadProgress(convertToTransferProgressEvent(event));\n logger.debug(event);\n });\n }\n xhr.addEventListener('error', () => {\n const networkError = new StorageError_1.StorageError({\n message: constants_1.NETWORK_ERROR_MESSAGE,\n name: constants_1.NETWORK_ERROR_CODE,\n });\n logger.error(constants_1.NETWORK_ERROR_MESSAGE);\n reject(networkError);\n xhr = null; // clean up request\n });\n // Handle browser request cancellation (as opposed to a manual cancellation)\n xhr.addEventListener('abort', () => {\n // The abort event can be triggered after the error or load event. So we need to check if the xhr is null.\n // When request is aborted by AbortSignal, the promise is rejected in the abortSignal's 'abort' event listener.\n if (!xhr || abortSignal?.aborted)\n return;\n // Handle abort request caused by browser instead of AbortController\n // see: https://github.com/axios/axios/issues/537\n const error = buildHandlerError(constants_1.ABORT_ERROR_MESSAGE, constants_1.ABORT_ERROR_CODE);\n logger.error(constants_1.ABORT_ERROR_MESSAGE);\n reject(error);\n xhr = null; // clean up request\n });\n // Skip handling timeout error since we don't have a timeout\n xhr.addEventListener('readystatechange', () => {\n if (!xhr || xhr.readyState !== xhr.DONE) {\n return;\n }\n const onloadend = () => {\n // The load event is triggered after the error/abort/load event. So we need to check if the xhr is null.\n if (!xhr)\n return;\n const responseHeaders = convertResponseHeaders(xhr.getAllResponseHeaders());\n const { responseType: loadEndResponseType } = xhr;\n const responseBlob = xhr.response;\n const responseText = loadEndResponseType === 'text' ? xhr.responseText : '';\n const bodyMixIn = {\n blob: () => Promise.resolve(responseBlob),\n text: (0, aws_client_utils_1.withMemoization)(() => loadEndResponseType === 'blob'\n ? readBlobAsText(responseBlob)\n : Promise.resolve(responseText)),\n json: () => Promise.reject(\n // S3 does not support JSON response. So fail-fast here with nicer error message.\n new Error('Parsing response to JSON is not implemented. Please use response.text() instead.')),\n };\n const response = {\n statusCode: xhr.status,\n headers: responseHeaders,\n // The xhr.responseType is only set to 'blob' for streaming binary S3 object data. The streaming data is\n // exposed via public interface of Storage.get(). So we need to return the response as a Blob object for\n // backward compatibility. In other cases, the response payload is only used internally, we return it is\n // {@link ResponseBodyMixin}\n body: (xhr.responseType === 'blob'\n ? Object.assign(responseBlob, bodyMixIn)\n : bodyMixIn),\n };\n resolve(response);\n xhr = null; // clean up request\n };\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n // @see https://github.com/axios/axios/blob/9588fcdec8aca45c3ba2f7968988a5d03f23168c/lib/adapters/xhr.js#L98-L99\n setTimeout(onloadend);\n });\n if (abortSignal) {\n const onCanceled = () => {\n // The abort event is triggered after the error or load event. So we need to check if the xhr is null.\n if (!xhr) {\n return;\n }\n const canceledError = new CanceledError_1.CanceledError({\n name: constants_1.CANCELED_ERROR_CODE,\n message: constants_1.CANCELED_ERROR_MESSAGE,\n });\n reject(canceledError);\n xhr.abort();\n xhr = null;\n };\n abortSignal.aborted\n ? onCanceled()\n : abortSignal.addEventListener('abort', onCanceled);\n }\n if (typeof ReadableStream === 'function' &&\n body instanceof ReadableStream) {\n // This does not matter as previous implementation uses Axios which does not support ReadableStream anyway.\n throw new Error('ReadableStream request payload is not supported.');\n }\n xhr.send(body ?? null);\n });\n};\nexports.xhrTransferHandler = xhrTransferHandler;\nconst convertToTransferProgressEvent = (event) => ({\n transferredBytes: event.loaded,\n totalBytes: event.lengthComputable ? event.total : undefined,\n});\nconst buildHandlerError = (message, name) => {\n const error = new Error(message);\n error.name = name;\n return error;\n};\n/**\n * Convert xhr.getAllResponseHeaders() string to a Record<string, string>. Note that modern browser already returns\n * header names in lowercase.\n * @param xhrHeaders - string of headers returned from xhr.getAllResponseHeaders()\n */\nconst convertResponseHeaders = (xhrHeaders) => {\n if (!xhrHeaders) {\n return {};\n }\n return xhrHeaders\n .split('\\r\\n')\n .reduce((headerMap, line) => {\n const parts = line.split(': ');\n const header = parts.shift();\n const value = parts.join(': ');\n headerMap[header.toLowerCase()] = value;\n return headerMap;\n }, {});\n};\nconst readBlobAsText = (blob) => {\n const reader = new FileReader();\n return new Promise((resolve, reject) => {\n reader.onloadend = () => {\n if (reader.readyState !== FileReader.DONE) {\n return;\n }\n resolve(reader.result);\n };\n reader.onerror = () => {\n reject(reader.error);\n };\n reader.readAsText(blob);\n });\n};\n// To add more forbidden headers as found set by S3. Intentionally NOT list all of them here to save bundle size.\n// https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name\nconst FORBIDDEN_HEADERS = ['host'];\n"],"names":[],"mappings":";;AACA;AACA;AACA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;AAC7D,OAAO,CAAC,kBAAkB,GAAG,MAAM;AACnC,MAAM,kBAAkB,GAAG,OAAO,CAAC,8CAA8C,CAAC;AAClF,MAAM,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC;AAC3C,MAAM,eAAe,GAAG,OAAO,CAAC,qCAAqC,CAAC;AACtE,MAAM,cAAc,GAAG,OAAO,CAAC,oCAAoC,CAAC;AACpE,MAAM,WAAW,GAAG,OAAO,CAAC,aAAa,CAAC;AAC1C,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,aAAa,CAAC,kBAAkB,CAAC;AAC3D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;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AAS,MAAM,CAAC,CAAC,SAAS,EAAE,IAAI,KAAK;AACrC,QAAQ,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC;AACtC,QAAQ,MAAM,MAAM,GAAG,KAAK,CAAC,KAAK,EAAE;AACpC,QAAQ,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC;AACtC,QAAQ,SAAS,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,GAAG,KAAK;AAC/C,QAAQ,OAAO,SAAS;AACxB,IAAI,CAAC,EAAE,EAAE,CAAC;AACV,CAAC;AACD,MAAM,cAAc,GAAG,CAAC,IAAI,KAAK;AACjC,IAAI,MAAM,MAAM,GAAG,IAAI,UAAU,EAAE;AACnC,IAAI,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,KAAK;AAC5C,QAAQ,MAAM,CAAC,SAAS,GAAG,MAAM;AACjC,YAAY,IAAI,MAAM,CAAC,UAAU,KAAK,UAAU,CAAC,IAAI,EAAE;AACvD,gBAAgB;AAChB,YAAY;AACZ,YAAY,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC;AAClC,QAAQ,CAAC;AACT,QAAQ,MAAM,CAAC,OAAO,GAAG,MAAM;AAC/B,YAAY,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC;AAChC,QAAQ,CAAC;AACT,QAAQ,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC;AAC/B,IAAI,CAAC,CAAC;AACN,CAAC;AACD;AACA;AACA,MAAM,iBAAiB,GAAG,CAAC,MAAM,CAAC;;"}
|
|
1
|
+
{"version":3,"file":"xhrTransferHandler.js","sources":["../../../../../../../src/providers/s3/utils/client/runtime/xhrTransferHandler.ts"],"sourcesContent":["\"use strict\";\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.xhrTransferHandler = void 0;\nconst aws_client_utils_1 = require(\"@aws-amplify/core/internals/aws-client-utils\");\nconst core_1 = require(\"@aws-amplify/core\");\nconst CanceledError_1 = require(\"../../../../../errors/CanceledError\");\nconst StorageError_1 = require(\"../../../../../errors/StorageError\");\nconst constants_1 = require(\"./constants\");\nconst logger = new core_1.ConsoleLogger('xhr-http-handler');\n/**\n * Base transfer handler implementation using XMLHttpRequest to support upload and download progress events.\n *\n * @param request - The request object.\n * @param options - The request options.\n * @returns A promise that will be resolved with the response object.\n *\n * @internal\n */\nconst xhrTransferHandler = (request, options) => {\n const { url, method, headers, body } = request;\n const { onDownloadProgress, onUploadProgress, responseType, abortSignal } = options;\n return new Promise((resolve, reject) => {\n let xhr = new XMLHttpRequest();\n xhr.open(method.toUpperCase(), url.toString());\n Object.entries(headers)\n .filter(([header]) => !FORBIDDEN_HEADERS.includes(header))\n .forEach(([header, value]) => {\n xhr.setRequestHeader(header, value);\n });\n xhr.responseType = responseType;\n if (onDownloadProgress) {\n xhr.addEventListener('progress', event => {\n onDownloadProgress(convertToTransferProgressEvent(event));\n logger.debug(event);\n });\n }\n if (onUploadProgress) {\n xhr.upload.addEventListener('progress', event => {\n onUploadProgress(convertToTransferProgressEvent(event));\n logger.debug(event);\n });\n }\n xhr.addEventListener('error', () => {\n const networkError = new StorageError_1.StorageError({\n message: constants_1.NETWORK_ERROR_MESSAGE,\n name: constants_1.NETWORK_ERROR_CODE,\n });\n logger.error(constants_1.NETWORK_ERROR_MESSAGE);\n reject(networkError);\n xhr = null; // clean up request\n });\n // Handle browser request cancellation (as opposed to a manual cancellation)\n xhr.addEventListener('abort', () => {\n // The abort event can be triggered after the error or load event. So we need to check if the xhr is null.\n // When request is aborted by AbortSignal, the promise is rejected in the abortSignal's 'abort' event listener.\n if (!xhr || abortSignal?.aborted)\n return;\n // Handle abort request caused by browser instead of AbortController\n // see: https://github.com/axios/axios/issues/537\n const error = buildHandlerError(constants_1.ABORT_ERROR_MESSAGE, constants_1.ABORT_ERROR_CODE);\n logger.error(constants_1.ABORT_ERROR_MESSAGE);\n reject(error);\n xhr = null; // clean up request\n });\n // Skip handling timeout error since we don't have a timeout\n xhr.addEventListener('readystatechange', () => {\n if (!xhr || xhr.readyState !== xhr.DONE) {\n return;\n }\n const onloadend = () => {\n // The load event is triggered after the error/abort/load event. So we need to check if the xhr is null.\n if (!xhr)\n return;\n const responseHeaders = convertResponseHeaders(xhr.getAllResponseHeaders());\n const { responseType: loadEndResponseType } = xhr;\n const responseBlob = xhr.response;\n const responseText = loadEndResponseType === 'text' ? xhr.responseText : '';\n const bodyMixIn = {\n blob: () => Promise.resolve(responseBlob),\n text: (0, aws_client_utils_1.withMemoization)(() => loadEndResponseType === 'blob'\n ? readBlobAsText(responseBlob)\n : Promise.resolve(responseText)),\n json: () => Promise.reject(\n // S3 does not support JSON response. So fail-fast here with nicer error message.\n new Error('Parsing response to JSON is not implemented. Please use response.text() instead.')),\n };\n const response = {\n statusCode: xhr.status,\n headers: responseHeaders,\n // The xhr.responseType is only set to 'blob' for streaming binary S3 object data. The streaming data is\n // exposed via public interface of Storage.get(). So we need to return the response as a Blob object for\n // backward compatibility. In other cases, the response payload is only used internally, we return it is\n // {@link ResponseBodyMixin}\n body: (xhr.responseType === 'blob'\n ? Object.assign(responseBlob, bodyMixIn)\n : bodyMixIn),\n };\n resolve(response);\n xhr = null; // clean up request\n };\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n // @see https://github.com/axios/axios/blob/9588fcdec8aca45c3ba2f7968988a5d03f23168c/lib/adapters/xhr.js#L98-L99\n setTimeout(onloadend);\n });\n if (abortSignal) {\n const onCanceled = () => {\n // The abort event is triggered after the error or load event. So we need to check if the xhr is null.\n if (!xhr) {\n return;\n }\n const canceledError = new CanceledError_1.CanceledError({\n name: constants_1.CANCELED_ERROR_CODE,\n message: constants_1.CANCELED_ERROR_MESSAGE,\n });\n reject(canceledError);\n xhr.abort();\n xhr = null;\n };\n abortSignal.aborted\n ? onCanceled()\n : abortSignal.addEventListener('abort', onCanceled);\n }\n if (typeof ReadableStream === 'function' &&\n body instanceof ReadableStream) {\n // This does not matter as previous implementation uses Axios which does not support ReadableStream anyway.\n throw new Error('ReadableStream request payload is not supported.');\n }\n xhr.send(body ?? null);\n });\n};\nexports.xhrTransferHandler = xhrTransferHandler;\nconst convertToTransferProgressEvent = (event) => ({\n // `loaded` can exceed the `total` in some cases due to platform issues/bugs e.g. React Native & Expo Android\n // clamp `loaded` values down to `total` if possible.\n transferredBytes: event.lengthComputable\n ? Math.min(event.loaded, event.total)\n : event.loaded,\n totalBytes: event.lengthComputable ? event.total : undefined,\n});\nconst buildHandlerError = (message, name) => {\n const error = new Error(message);\n error.name = name;\n return error;\n};\n/**\n * Convert xhr.getAllResponseHeaders() string to a Record<string, string>. Note that modern browser already returns\n * header names in lowercase.\n * @param xhrHeaders - string of headers returned from xhr.getAllResponseHeaders()\n */\nconst convertResponseHeaders = (xhrHeaders) => {\n if (!xhrHeaders) {\n return {};\n }\n return xhrHeaders\n .split('\\r\\n')\n .reduce((headerMap, line) => {\n const parts = line.split(': ');\n const header = parts.shift();\n const value = parts.join(': ');\n headerMap[header.toLowerCase()] = value;\n return headerMap;\n }, {});\n};\nconst readBlobAsText = (blob) => {\n const reader = new FileReader();\n return new Promise((resolve, reject) => {\n reader.onloadend = () => {\n if (reader.readyState !== FileReader.DONE) {\n return;\n }\n resolve(reader.result);\n };\n reader.onerror = () => {\n reject(reader.error);\n };\n reader.readAsText(blob);\n });\n};\n// To add more forbidden headers as found set by S3. Intentionally NOT list all of them here to save bundle size.\n// https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name\nconst FORBIDDEN_HEADERS = ['host'];\n"],"names":[],"mappings":";;AACA;AACA;AACA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC;AAC7D,OAAO,CAAC,kBAAkB,GAAG,MAAM;AACnC,MAAM,kBAAkB,GAAG,OAAO,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,YAAY,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC;AAChC,QAAQ,CAAC;AACT,QAAQ,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC;AAC/B,IAAI,CAAC,CAAC;AACN,CAAC;AACD;AACA;AACA,MAAM,iBAAiB,GAAG,CAAC,MAAM,CAAC;;"}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
4
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.getContentType = void 0;
|
|
7
|
+
const MIME_TYPES = {
|
|
8
|
+
// Audio
|
|
9
|
+
aac: 'audio/aac',
|
|
10
|
+
mid: 'audio/midi',
|
|
11
|
+
midi: 'audio/x-midi',
|
|
12
|
+
mp3: 'audio/mpeg',
|
|
13
|
+
oga: 'audio/ogg',
|
|
14
|
+
opus: 'audio/ogg',
|
|
15
|
+
wav: 'audio/wav',
|
|
16
|
+
weba: 'audio/webm',
|
|
17
|
+
// Video
|
|
18
|
+
avi: 'video/x-msvideo',
|
|
19
|
+
mp4: 'video/mp4',
|
|
20
|
+
mpeg: 'video/mpeg',
|
|
21
|
+
ogv: 'video/ogg',
|
|
22
|
+
ts: 'video/mp2t',
|
|
23
|
+
webm: 'video/webm',
|
|
24
|
+
// Images
|
|
25
|
+
apng: 'image/apng',
|
|
26
|
+
avif: 'image/avif',
|
|
27
|
+
bmp: 'image/bmp',
|
|
28
|
+
gif: 'image/gif',
|
|
29
|
+
ico: 'image/vnd.microsoft.icon',
|
|
30
|
+
jpeg: 'image/jpeg',
|
|
31
|
+
jpg: 'image/jpeg',
|
|
32
|
+
png: 'image/png',
|
|
33
|
+
svg: 'image/svg+xml',
|
|
34
|
+
tif: 'image/tiff',
|
|
35
|
+
tiff: 'image/tiff',
|
|
36
|
+
webp: 'image/webp',
|
|
37
|
+
// Text
|
|
38
|
+
css: 'text/css',
|
|
39
|
+
csv: 'text/csv',
|
|
40
|
+
htm: 'text/html',
|
|
41
|
+
html: 'text/html',
|
|
42
|
+
ics: 'text/calendar',
|
|
43
|
+
js: 'text/javascript',
|
|
44
|
+
md: 'text/markdown',
|
|
45
|
+
mjs: 'text/javascript',
|
|
46
|
+
txt: 'text/plain',
|
|
47
|
+
// Application
|
|
48
|
+
abw: 'application/x-abiword',
|
|
49
|
+
arc: 'application/x-freearc',
|
|
50
|
+
azw: 'application/vnd.amazon.ebook',
|
|
51
|
+
bin: 'application/octet-stream',
|
|
52
|
+
bz: 'application/x-bzip',
|
|
53
|
+
bz2: 'application/x-bzip2',
|
|
54
|
+
cda: 'application/x-cdf',
|
|
55
|
+
csh: 'application/x-csh',
|
|
56
|
+
doc: 'application/msword',
|
|
57
|
+
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
58
|
+
eot: 'application/vnd.ms-fontobject',
|
|
59
|
+
epub: 'application/epub+zip',
|
|
60
|
+
gz: 'application/gzip',
|
|
61
|
+
jar: 'application/java-archive',
|
|
62
|
+
json: 'application/json',
|
|
63
|
+
jsonld: 'application/ld+json',
|
|
64
|
+
mpkg: 'application/vnd.apple.installer+xml',
|
|
65
|
+
odp: 'application/vnd.oasis.opendocument.presentation',
|
|
66
|
+
ods: 'application/vnd.oasis.opendocument.spreadsheet',
|
|
67
|
+
odt: 'application/vnd.oasis.opendocument.text',
|
|
68
|
+
ogx: 'application/ogg',
|
|
69
|
+
pdf: 'application/pdf',
|
|
70
|
+
php: 'application/x-httpd-php',
|
|
71
|
+
ppt: 'application/vnd.ms-powerpoint',
|
|
72
|
+
pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
|
73
|
+
rar: 'application/vnd.rar',
|
|
74
|
+
rtf: 'application/rtf',
|
|
75
|
+
sh: 'application/x-sh',
|
|
76
|
+
tar: 'application/x-tar',
|
|
77
|
+
vsd: 'application/vnd.visio',
|
|
78
|
+
webmanifest: 'application/manifest+json',
|
|
79
|
+
xhtml: 'application/xhtml+xml',
|
|
80
|
+
xls: 'application/vnd.ms-excel',
|
|
81
|
+
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
82
|
+
xml: 'application/xml',
|
|
83
|
+
zip: 'application/zip',
|
|
84
|
+
// Fonts
|
|
85
|
+
otf: 'font/otf',
|
|
86
|
+
ttf: 'font/ttf',
|
|
87
|
+
woff: 'font/woff',
|
|
88
|
+
woff2: 'font/woff2',
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* Detect content type from file data or filename extension
|
|
92
|
+
*/
|
|
93
|
+
const getContentType = (data, key) => {
|
|
94
|
+
if (data instanceof File && data.type) {
|
|
95
|
+
return data.type;
|
|
96
|
+
}
|
|
97
|
+
const ext = key.split('.').pop()?.toLowerCase();
|
|
98
|
+
return ext ? MIME_TYPES[ext] : undefined;
|
|
99
|
+
};
|
|
100
|
+
exports.getContentType = getContentType;
|
|
101
|
+
//# sourceMappingURL=contentType.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"contentType.js","sources":["../../../src/utils/contentType.ts"],"sourcesContent":["\"use strict\";\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getContentType = void 0;\nconst MIME_TYPES = {\n // Audio\n aac: 'audio/aac',\n mid: 'audio/midi',\n midi: 'audio/x-midi',\n mp3: 'audio/mpeg',\n oga: 'audio/ogg',\n opus: 'audio/ogg',\n wav: 'audio/wav',\n weba: 'audio/webm',\n // Video\n avi: 'video/x-msvideo',\n mp4: 'video/mp4',\n mpeg: 'video/mpeg',\n ogv: 'video/ogg',\n ts: 'video/mp2t',\n webm: 'video/webm',\n // Images\n apng: 'image/apng',\n avif: 'image/avif',\n bmp: 'image/bmp',\n gif: 'image/gif',\n ico: 'image/vnd.microsoft.icon',\n jpeg: 'image/jpeg',\n jpg: 'image/jpeg',\n png: 'image/png',\n svg: 'image/svg+xml',\n tif: 'image/tiff',\n tiff: 'image/tiff',\n webp: 'image/webp',\n // Text\n css: 'text/css',\n csv: 'text/csv',\n htm: 'text/html',\n html: 'text/html',\n ics: 'text/calendar',\n js: 'text/javascript',\n md: 'text/markdown',\n mjs: 'text/javascript',\n txt: 'text/plain',\n // Application\n abw: 'application/x-abiword',\n arc: 'application/x-freearc',\n azw: 'application/vnd.amazon.ebook',\n bin: 'application/octet-stream',\n bz: 'application/x-bzip',\n bz2: 'application/x-bzip2',\n cda: 'application/x-cdf',\n csh: 'application/x-csh',\n doc: 'application/msword',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n eot: 'application/vnd.ms-fontobject',\n epub: 'application/epub+zip',\n gz: 'application/gzip',\n jar: 'application/java-archive',\n json: 'application/json',\n jsonld: 'application/ld+json',\n mpkg: 'application/vnd.apple.installer+xml',\n odp: 'application/vnd.oasis.opendocument.presentation',\n ods: 'application/vnd.oasis.opendocument.spreadsheet',\n odt: 'application/vnd.oasis.opendocument.text',\n ogx: 'application/ogg',\n pdf: 'application/pdf',\n php: 'application/x-httpd-php',\n ppt: 'application/vnd.ms-powerpoint',\n pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n rar: 'application/vnd.rar',\n rtf: 'application/rtf',\n sh: 'application/x-sh',\n tar: 'application/x-tar',\n vsd: 'application/vnd.visio',\n webmanifest: 'application/manifest+json',\n xhtml: 'application/xhtml+xml',\n xls: 'application/vnd.ms-excel',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n xml: 'application/xml',\n zip: 'application/zip',\n // Fonts\n otf: 'font/otf',\n ttf: 'font/ttf',\n woff: 'font/woff',\n woff2: 'font/woff2',\n};\n/**\n * Detect content type from file data or filename extension\n */\nconst getContentType = (data, key) => {\n if (data instanceof File && data.type) {\n return data.type;\n }\n const ext = key.split('.').pop()?.toLowerCase();\n return ext ? M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iB;AAC1B,IAAI,GAAG,EAAE,iBAAiB;AAC1B;AACA,IAAI,GAAG,EAAE,UAAU;AACnB,IAAI,GAAG,EAAE,UAAU;AACnB,IAAI,IAAI,EAAE,WAAW;AACrB,IAAI,KAAK,EAAE,YAAY;AACvB,CAAC;AACD;AACA;AACA;AACA,MAAM,cAAc,GAAG,CAAC,IAAI,EAAE,GAAG,KAAK;AACtC,IAAI,IAAI,IAAI,YAAY,IAAI,IAAI,IAAI,CAAC,IAAI,EAAE;AAC3C,QAAQ,OAAO,IAAI,CAAC,IAAI;AACxB,IAAI;AACJ,IAAI,MAAM,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,WAAW,EAAE;AACnD,IAAI,OAAO,GAAG,GAAG,UAAU,CAAC,GAAG,CAAC,GAAG,SAAS;AAC5C,CAAC;AACD,OAAO,CAAC,cAAc,GAAG,cAAc;;"}
|
|
@@ -14,6 +14,7 @@ import '../../../../utils/client/s3data/deleteObject.mjs';
|
|
|
14
14
|
import '../../../../../../errors/types/validation.mjs';
|
|
15
15
|
import '@aws-amplify/core/internals/utils';
|
|
16
16
|
import { logger } from '../../../../../../utils/logger.mjs';
|
|
17
|
+
import { getContentType } from '../../../../../../utils/contentType.mjs';
|
|
17
18
|
|
|
18
19
|
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
19
20
|
// SPDX-License-Identifier: Apache-2.0
|
|
@@ -89,7 +90,7 @@ const serializeUploadOptions = (options = {}) => {
|
|
|
89
90
|
*/
|
|
90
91
|
const getUploadsCacheKey = ({ file, size, contentType, bucket, accessLevel, key, optionsHash, }) => {
|
|
91
92
|
let levelStr;
|
|
92
|
-
const resolvedContentType = contentType ?? file
|
|
93
|
+
const resolvedContentType = contentType ?? getContentType(file, key) ?? 'application/octet-stream';
|
|
93
94
|
// If no access level is defined, we're using custom gen2 access rules
|
|
94
95
|
if (accessLevel === undefined) {
|
|
95
96
|
levelStr = 'custom';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uploadCache.mjs","sources":["../../../../../../../../src/providers/s3/apis/internal/uploadData/multipart/uploadCache.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { UPLOADS_STORAGE_KEY } from '../../../../utils/constants';\nimport { listParts } from '../../../../utils/client/s3data';\nimport { logger } from '../../../../../../utils';\nconst ONE_HOUR = 1000 * 60 * 60;\n/**\n * Find the cached multipart upload id and get the parts that have been uploaded\n * with ListParts API. If the cached upload is expired(1 hour), return null.\n */\nexport const findCachedUploadPartsAndEvictExpired = async ({ resumableUploadsCache, cacheKey, s3Config, bucket, finalKey, }) => {\n const allCachedUploads = await listCachedUploadTasks(resumableUploadsCache);\n // Evict all outdated uploads.\n const validCachedUploads = Object.fromEntries(Object.entries(allCachedUploads).filter(([_, cacheValue]) => cacheValue.lastTouched >= Date.now() - ONE_HOUR));\n if (Object.keys(validCachedUploads).length !==\n Object.keys(allCachedUploads).length) {\n await resumableUploadsCache.setItem(UPLOADS_STORAGE_KEY, JSON.stringify(validCachedUploads));\n }\n if (!validCachedUploads[cacheKey]) {\n return null;\n }\n const cachedUpload = validCachedUploads[cacheKey];\n cachedUpload.lastTouched = Date.now();\n await resumableUploadsCache.setItem(UPLOADS_STORAGE_KEY, JSON.stringify(validCachedUploads));\n try {\n const { Parts = [] } = await listParts(s3Config, {\n Bucket: bucket,\n Key: finalKey,\n UploadId: cachedUpload.uploadId,\n });\n return {\n parts: Parts,\n uploadId: cachedUpload.uploadId,\n finalCrc32: cachedUpload.finalCrc32,\n };\n }\n catch (e) {\n logger.debug('failed to list cached parts, removing cached upload.');\n await removeCachedUpload(resumableUploadsCache, cacheKey);\n return null;\n }\n};\nconst listCachedUploadTasks = async (resumableUploadsCache) => {\n try {\n return JSON.parse((await resumableUploadsCache.getItem(UPLOADS_STORAGE_KEY)) ?? '{}');\n }\n catch (e) {\n logger.debug('failed to parse cached uploads record.');\n return {};\n }\n};\n/**\n * Serialize the uploadData API options to string so it can be hashed.\n */\nexport const serializeUploadOptions = (options = {}) => {\n const unserializableOptionProperties = [\n 'onProgress',\n 'resumableUploadsCache', // Internally injected implementation not set by customers\n 'locationCredentialsProvider', // Internally injected implementation not set by customers\n ];\n const serializableOptionEntries = Object.entries(options).filter(([key]) => !unserializableOptionProperties.includes(key));\n if (options.checksumAlgorithm === 'crc-32') {\n // Additional options to differentiate the upload cache created before introducing the full-object checksum and\n // after. If full-object checksum is enabled, the previous upload caches that created with composite checksum should\n // be ignored.\n serializableOptionEntries.push(['checksumType', 'FULL_OBJECT']);\n }\n const serializableOptions = Object.fromEntries(serializableOptionEntries);\n return JSON.stringify(serializableOptions);\n};\n/**\n * Get the cache key of a multipart upload. Data source cached by different: size, content type, bucket, access level,\n * key. If the data source is a File instance, the upload is additionally indexed by file name and last modified time.\n * So the library always created a new multipart upload if the file is modified.\n */\nexport const getUploadsCacheKey = ({ file, size, contentType, bucket, accessLevel, key, optionsHash, }) => {\n let levelStr;\n const resolvedContentType = contentType ?? file
|
|
1
|
+
{"version":3,"file":"uploadCache.mjs","sources":["../../../../../../../../src/providers/s3/apis/internal/uploadData/multipart/uploadCache.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { UPLOADS_STORAGE_KEY } from '../../../../utils/constants';\nimport { listParts } from '../../../../utils/client/s3data';\nimport { logger } from '../../../../../../utils';\nimport { getContentType } from '../../../../../../utils/contentType';\nconst ONE_HOUR = 1000 * 60 * 60;\n/**\n * Find the cached multipart upload id and get the parts that have been uploaded\n * with ListParts API. If the cached upload is expired(1 hour), return null.\n */\nexport const findCachedUploadPartsAndEvictExpired = async ({ resumableUploadsCache, cacheKey, s3Config, bucket, finalKey, }) => {\n const allCachedUploads = await listCachedUploadTasks(resumableUploadsCache);\n // Evict all outdated uploads.\n const validCachedUploads = Object.fromEntries(Object.entries(allCachedUploads).filter(([_, cacheValue]) => cacheValue.lastTouched >= Date.now() - ONE_HOUR));\n if (Object.keys(validCachedUploads).length !==\n Object.keys(allCachedUploads).length) {\n await resumableUploadsCache.setItem(UPLOADS_STORAGE_KEY, JSON.stringify(validCachedUploads));\n }\n if (!validCachedUploads[cacheKey]) {\n return null;\n }\n const cachedUpload = validCachedUploads[cacheKey];\n cachedUpload.lastTouched = Date.now();\n await resumableUploadsCache.setItem(UPLOADS_STORAGE_KEY, JSON.stringify(validCachedUploads));\n try {\n const { Parts = [] } = await listParts(s3Config, {\n Bucket: bucket,\n Key: finalKey,\n UploadId: cachedUpload.uploadId,\n });\n return {\n parts: Parts,\n uploadId: cachedUpload.uploadId,\n finalCrc32: cachedUpload.finalCrc32,\n };\n }\n catch (e) {\n logger.debug('failed to list cached parts, removing cached upload.');\n await removeCachedUpload(resumableUploadsCache, cacheKey);\n return null;\n }\n};\nconst listCachedUploadTasks = async (resumableUploadsCache) => {\n try {\n return JSON.parse((await resumableUploadsCache.getItem(UPLOADS_STORAGE_KEY)) ?? '{}');\n }\n catch (e) {\n logger.debug('failed to parse cached uploads record.');\n return {};\n }\n};\n/**\n * Serialize the uploadData API options to string so it can be hashed.\n */\nexport const serializeUploadOptions = (options = {}) => {\n const unserializableOptionProperties = [\n 'onProgress',\n 'resumableUploadsCache', // Internally injected implementation not set by customers\n 'locationCredentialsProvider', // Internally injected implementation not set by customers\n ];\n const serializableOptionEntries = Object.entries(options).filter(([key]) => !unserializableOptionProperties.includes(key));\n if (options.checksumAlgorithm === 'crc-32') {\n // Additional options to differentiate the upload cache created before introducing the full-object checksum and\n // after. If full-object checksum is enabled, the previous upload caches that created with composite checksum should\n // be ignored.\n serializableOptionEntries.push(['checksumType', 'FULL_OBJECT']);\n }\n const serializableOptions = Object.fromEntries(serializableOptionEntries);\n return JSON.stringify(serializableOptions);\n};\n/**\n * Get the cache key of a multipart upload. Data source cached by different: size, content type, bucket, access level,\n * key. If the data source is a File instance, the upload is additionally indexed by file name and last modified time.\n * So the library always created a new multipart upload if the file is modified.\n */\nexport const getUploadsCacheKey = ({ file, size, contentType, bucket, accessLevel, key, optionsHash, }) => {\n let levelStr;\n const resolvedContentType = contentType ?? getContentType(file, key) ?? 'application/octet-stream';\n // If no access level is defined, we're using custom gen2 access rules\n if (accessLevel === undefined) {\n levelStr = 'custom';\n }\n else {\n levelStr = accessLevel === 'guest' ? 'public' : accessLevel;\n }\n const baseId = `${optionsHash}_${size}_${resolvedContentType}_${bucket}_${levelStr}_${key}`;\n if (file) {\n return `${file.name}_${file.lastModified}_${baseId}`;\n }\n else {\n return baseId;\n }\n};\nexport const cacheMultipartUpload = async (resumableUploadsCache, cacheKey, fileMetadata) => {\n const cachedUploads = await listCachedUploadTasks(resumableUploadsCache);\n cachedUploads[cacheKey] = {\n ...fileMetadata,\n lastTouched: Date.now(),\n };\n await resumableUploadsCache.setItem(UPLOADS_STORAGE_KEY, JSON.stringify(cachedUploads));\n};\nexport const removeCachedUpload = async (resumableUploadsCache, cacheKey) => {\n const cachedUploads = await listCachedUploadTasks(resumableUploadsCache);\n delete cachedUploads[cacheKey];\n await resumableUploadsCache.setItem(UPLOADS_STORAGE_KEY, JSON.stringify(cachedUploads));\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AACA;AAKA,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAE,GAAG,EAAE;AAC/B;AACA;AACA;AACA;AACY,MAAC,oCAAoC,GAAG,OAAO,EAAE,qBAAqB,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,GAAG,KAAK;AAChI,IAAI,MAAM,gBAAgB,GAAG,MAAM,qBAAqB,CAAC,qBAAqB,CAAC;AAC/E;AACA,IAAI,MAAM,kBAAkB,GAAG,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,KAAK,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AC;AAC3F;;;;"}
|
|
@@ -28,6 +28,7 @@ import '../../../../utils/client/s3data/deleteObject.mjs';
|
|
|
28
28
|
import { getStorageUserAgentValue } from '../../../../utils/userAgent.mjs';
|
|
29
29
|
import { calculateContentCRC32 } from '../../../../utils/crc32.mjs';
|
|
30
30
|
import { IntegrityError } from '../../../../../../errors/IntegrityError.mjs';
|
|
31
|
+
import { getContentType } from '../../../../../../utils/contentType.mjs';
|
|
31
32
|
import { uploadPartExecutor } from './uploadPartExecutor.mjs';
|
|
32
33
|
import { serializeUploadOptions, getUploadsCacheKey, removeCachedUpload } from './uploadCache.mjs';
|
|
33
34
|
import { getConcurrentUploadsProgressTracker } from './progressTracker.mjs';
|
|
@@ -71,7 +72,9 @@ const getMultipartUploadHandlers = (uploadDataInput, size) => {
|
|
|
71
72
|
resolvedIdentityId = resolvedS3Options.identityId;
|
|
72
73
|
expectedBucketOwner = uploadDataOptions?.expectedBucketOwner;
|
|
73
74
|
const { inputType, objectKey } = validateStorageOperationInput(uploadDataInput, resolvedIdentityId);
|
|
74
|
-
const { contentDisposition, contentEncoding, contentType =
|
|
75
|
+
const { contentDisposition, contentEncoding, contentType = uploadDataOptions?.contentType ??
|
|
76
|
+
getContentType(data, objectKey) ??
|
|
77
|
+
'application/octet-stream', metadata, preventOverwrite, onProgress, } = uploadDataOptions ?? {};
|
|
75
78
|
finalKey = objectKey;
|
|
76
79
|
// Resolve "key" specific options
|
|
77
80
|
if (inputType === STORAGE_INPUT_KEY) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uploadHandlers.mjs","sources":["../../../../../../../../src/providers/s3/apis/internal/uploadData/multipart/uploadHandlers.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, } from '@aws-amplify/core';\nimport { StorageAction } from '@aws-amplify/core/internals/utils';\nimport { resolveS3ConfigAndInput, validateStorageOperationInput, } from '../../../../utils';\nimport { DEFAULT_ACCESS_LEVEL, DEFAULT_QUEUE_SIZE, STORAGE_INPUT_KEY, } from '../../../../utils/constants';\nimport { StorageError } from '../../../../../../errors/StorageError';\nimport { CanceledError } from '../../../../../../errors/CanceledError';\nimport { abortMultipartUpload, completeMultipartUpload, headObject, } from '../../../../utils/client/s3data';\nimport { getStorageUserAgentValue } from '../../../../utils/userAgent';\nimport { logger } from '../../../../../../utils';\nimport { calculateContentCRC32 } from '../../../../utils/crc32';\nimport { IntegrityError } from '../../../../../../errors/IntegrityError';\nimport { uploadPartExecutor } from './uploadPartExecutor';\nimport { getUploadsCacheKey, removeCachedUpload, serializeUploadOptions, } from './uploadCache';\nimport { getConcurrentUploadsProgressTracker } from './progressTracker';\nimport { loadOrCreateMultipartUpload } from './initialUpload';\nimport { getDataChunker } from './getDataChunker';\nimport { calculatePartSize } from './calculatePartSize';\n/**\n * Create closure hiding the multipart upload implementation details and expose the upload job and control functions(\n * onPause, onResume, onCancel).\n *\n * @internal\n */\nexport const getMultipartUploadHandlers = (uploadDataInput, size) => {\n let resolveCallback;\n let rejectCallback;\n let inProgressUpload;\n let resolvedS3Config;\n let abortController;\n let resolvedAccessLevel;\n let resolvedBucket;\n let resolvedKeyPrefix;\n let resolvedIdentityId;\n let uploadCacheKey;\n let finalKey;\n let expectedBucketOwner;\n // Special flag that differentiates HTTP requests abort error caused by pause() from ones caused by cancel().\n // The former one should NOT cause the upload job to throw, but cancels any pending HTTP requests.\n // This should be replaced by a special abort reason. However,the support of this API is lagged behind.\n let isAbortSignalFromPause = false;\n const { resumableUploadsCache } = uploadDataInput.options ?? {};\n const startUpload = async () => {\n const { options: uploadDataOptions, data } = uploadDataInput;\n const resolvedS3Options = await resolveS3ConfigAndInput(Amplify, uploadDataInput);\n abortController = new AbortController();\n isAbortSignalFromPause = false;\n resolvedS3Config = resolvedS3Options.s3Config;\n resolvedBucket = resolvedS3Options.bucket;\n resolvedIdentityId = resolvedS3Options.identityId;\n expectedBucketOwner = uploadDataOptions?.expectedBucketOwner;\n const { inputType, objectKey } = validateStorageOperationInput(uploadDataInput, resolvedIdentityId);\n const { contentDisposition, contentEncoding, contentType = 'application/octet-stream', metadata, preventOverwrite, onProgress, } = uploadDataOptions ?? {};\n finalKey = objectKey;\n // Resolve \"key\" specific options\n if (inputType === STORAGE_INPUT_KEY) {\n const accessLevel = uploadDataOptions\n ?.accessLevel;\n resolvedKeyPrefix = resolvedS3Options.keyPrefix;\n finalKey = resolvedKeyPrefix + objectKey;\n resolvedAccessLevel = resolveAccessLevel(accessLevel);\n }\n const optionsHash = await calculateContentCRC32(serializeUploadOptions(uploadDataOptions));\n if (!inProgressUpload) {\n const { uploadId, cachedParts, finalCrc32 } = await loadOrCreateMultipartUpload({\n s3Config: resolvedS3Config,\n accessLevel: resolvedAccessLevel,\n bucket: resolvedBucket,\n keyPrefix: resolvedKeyPrefix,\n key: objectKey,\n contentType,\n contentDisposition,\n contentEncoding,\n metadata,\n data,\n size,\n abortSignal: abortController.signal,\n checksumAlgorithm: uploadDataOptions?.checksumAlgorithm,\n optionsHash,\n resumableUploadsCache,\n expectedBucketOwner,\n });\n inProgressUpload = {\n uploadId,\n completedParts: cachedParts,\n finalCrc32,\n };\n }\n uploadCacheKey = size\n ? getUploadsCacheKey({\n file: data instanceof File ? data : undefined,\n accessLevel: resolvedAccessLevel,\n contentType: uploadDataOptions?.contentType,\n bucket: resolvedBucket,\n size,\n key: objectKey,\n optionsHash,\n })\n : undefined;\n const dataChunker = getDataChunker(data, size);\n const completedPartNumberSet = new Set(inProgressUpload.completedParts.map(({ PartNumber }) => PartNumber));\n const onPartUploadCompletion = (partNumber, eTag, crc32) => {\n inProgressUpload?.completedParts.push({\n PartNumber: partNumber,\n ETag: eTag,\n // TODO: crc32 can always be added once RN also has an implementation\n ...(crc32 ? { ChecksumCRC32: crc32 } : {}),\n });\n };\n const concurrentUploadsProgressTracker = getConcurrentUploadsProgressTracker({\n size,\n onProgress,\n });\n const concurrentUploadPartExecutors = [];\n for (let index = 0; index < DEFAULT_QUEUE_SIZE; index++) {\n concurrentUploadPartExecutors.push(uploadPartExecutor({\n dataChunkerGenerator: dataChunker,\n completedPartNumberSet,\n s3Config: resolvedS3Config,\n abortSignal: abortController.signal,\n bucket: resolvedBucket,\n finalKey,\n uploadId: inProgressUpload.uploadId,\n onPartUploadCompletion,\n onProgress: concurrentUploadsProgressTracker.getOnProgressListener(),\n isObjectLockEnabled: resolvedS3Options.isObjectLockEnabled,\n useCRC32Checksum: Boolean(inProgressUpload.finalCrc32),\n expectedBucketOwner,\n }));\n }\n await Promise.all(concurrentUploadPartExecutors);\n validateCompletedParts(inProgressUpload.completedParts, size);\n const { ETag: eTag } = await completeMultipartUpload({\n ...resolvedS3Config,\n abortSignal: abortController.signal,\n userAgentValue: getStorageUserAgentValue(StorageAction.UploadData),\n }, {\n Bucket: resolvedBucket,\n Key: finalKey,\n UploadId: inProgressUpload.uploadId,\n ChecksumCRC32: inProgressUpload.finalCrc32,\n ChecksumType: inProgressUpload.finalCrc32 ? 'FULL_OBJECT' : undefined,\n IfNoneMatch: preventOverwrite ? '*' : undefined,\n MultipartUpload: {\n Parts: sortUploadParts(inProgressUpload.completedParts),\n },\n ExpectedBucketOwner: expectedBucketOwner,\n });\n // If full-object CRC32 checksum is NOT enabled, we need to ensure the upload integrity by making extra HEAD call\n // to verify the uploaded object size.\n if (!inProgressUpload.finalCrc32) {\n const { ContentLength: uploadedObjectSize, $metadata } = await headObject(resolvedS3Config, {\n Bucket: resolvedBucket,\n Key: finalKey,\n ExpectedBucketOwner: expectedBucketOwner,\n });\n if (uploadedObjectSize && uploadedObjectSize !== size) {\n throw new StorageError({\n name: 'Error',\n message: `Upload failed. Expected object size ${size}, but got ${uploadedObjectSize}.`,\n metadata: $metadata,\n });\n }\n }\n if (resumableUploadsCache && uploadCacheKey) {\n await removeCachedUpload(resumableUploadsCache, uploadCacheKey);\n }\n const result = {\n eTag,\n contentType,\n metadata,\n };\n return inputType === STORAGE_INPUT_KEY\n ? { key: objectKey, ...result }\n : { path: objectKey, ...result };\n };\n const startUploadWithResumability = () => startUpload()\n .then(resolveCallback)\n .catch(error => {\n const abortSignal = abortController?.signal;\n if (abortSignal?.aborted && isAbortSignalFromPause) {\n logger.debug('upload paused.');\n }\n else {\n // Uncaught errors should be exposed to the users.\n rejectCallback(error);\n }\n });\n const multipartUploadJob = () => new Promise((resolve, reject) => {\n resolveCallback = resolve;\n rejectCallback = reject;\n startUploadWithResumability();\n });\n const onPause = () => {\n isAbortSignalFromPause = true;\n abortController?.abort();\n };\n const onResume = () => {\n startUploadWithResumability();\n };\n const onCancel = (message) => {\n // 1. abort in-flight API requests\n abortController?.abort(message);\n const cancelUpload = async () => {\n // 2. clear upload cache.\n if (uploadCacheKey && resumableUploadsCache) {\n await removeCachedUpload(resumableUploadsCache, uploadCacheKey);\n }\n // 3. clear multipart upload on server side.\n await abortMultipartUpload(resolvedS3Config, {\n Bucket: resolvedBucket,\n Key: finalKey,\n UploadId: inProgressUpload?.uploadId,\n ExpectedBucketOwner: expectedBucketOwner,\n });\n };\n cancelUpload().catch(e => {\n logger.debug('error when cancelling upload task.', e);\n });\n rejectCallback(\n // Internal error that should not be exposed to the users. They should use isCancelError() to check if\n // the error is caused by cancel().\n new CanceledError(message ? { message } : undefined));\n };\n return {\n multipartUploadJob,\n onPause,\n onResume,\n onCancel,\n };\n};\nconst resolveAccessLevel = (accessLevel) => accessLevel ??\n Amplify.libraryOptions.Storage?.S3?.defaultAccessLevel ??\n DEFAULT_ACCESS_LEVEL;\nconst validateCompletedParts = (completedParts, size) => {\n const partsExpected = Math.ceil(size / calculatePartSize(size));\n const validPartCount = completedParts.length === partsExpected;\n const sorted = sortUploadParts(completedParts);\n const validPartNumbers = sorted.every((part, index) => part.PartNumber === index + 1);\n if (!validPartCount || !validPartNumbers) {\n throw new IntegrityError();\n }\n};\nconst sortUploadParts = (parts) => {\n return [...parts].sort((partA, partB) => partA.PartNumber - partB.PartNumber);\n};\n"],"names":[],"mappings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X,QAAQ,kBAAkB;AAC1B,QAAQ,OAAO;AACf,QAAQ,QAAQ;AAChB,QAAQ,QAAQ;AAChB,KAAK;AACL;AACA,MAAM,kBAAkB,GAAG,CAAC,WAAW,KAAK,WAAW;AACvD,IAAI,OAAO,CAAC,cAAc,CAAC,OAAO,EAAE,EAAE,EAAE,kBAAkB;AAC1D,IAAI,oBAAoB;AACxB,MAAM,sBAAsB,GAAG,CAAC,cAAc,EAAE,IAAI,KAAK;AACzD,IAAI,MAAM,aAAa,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC;AACnE,IAAI,MAAM,cAAc,GAAG,cAAc,CAAC,MAAM,KAAK,aAAa;AAClE,IAAI,MAAM,MAAM,GAAG,eAAe,CAAC,cAAc,CAAC;AAClD,IAAI,MAAM,gBAAgB,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,KAAK,KAAK,IAAI,CAAC,UAAU,KAAK,KAAK,GAAG,CAAC,CAAC;AACzF,IAAI,IAAI,CAAC,cAAc,IAAI,CAAC,gBAAgB,EAAE;AAC9C,QAAQ,MAAM,IAAI,cAAc,EAAE;AAClC,IAAI;AACJ,CAAC;AACD,MAAM,eAAe,GAAG,CAAC,KAAK,KAAK;AACnC,IAAI,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,KAAK,KAAK,KAAK,CAAC,UAAU,GAAG,KAAK,CAAC,UAAU,CAAC;AACjF,CAAC;;;;"}
|
|
1
|
+
{"version":3,"file":"uploadHandlers.mjs","sources":["../../../../../../../../src/providers/s3/apis/internal/uploadData/multipart/uploadHandlers.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify, } from '@aws-amplify/core';\nimport { StorageAction } from '@aws-amplify/core/internals/utils';\nimport { resolveS3ConfigAndInput, validateStorageOperationInput, } from '../../../../utils';\nimport { DEFAULT_ACCESS_LEVEL, DEFAULT_QUEUE_SIZE, STORAGE_INPUT_KEY, } from '../../../../utils/constants';\nimport { StorageError } from '../../../../../../errors/StorageError';\nimport { CanceledError } from '../../../../../../errors/CanceledError';\nimport { abortMultipartUpload, completeMultipartUpload, headObject, } from '../../../../utils/client/s3data';\nimport { getStorageUserAgentValue } from '../../../../utils/userAgent';\nimport { logger } from '../../../../../../utils';\nimport { calculateContentCRC32 } from '../../../../utils/crc32';\nimport { IntegrityError } from '../../../../../../errors/IntegrityError';\nimport { getContentType } from '../../../../../../utils/contentType';\nimport { uploadPartExecutor } from './uploadPartExecutor';\nimport { getUploadsCacheKey, removeCachedUpload, serializeUploadOptions, } from './uploadCache';\nimport { getConcurrentUploadsProgressTracker } from './progressTracker';\nimport { loadOrCreateMultipartUpload } from './initialUpload';\nimport { getDataChunker } from './getDataChunker';\nimport { calculatePartSize } from './calculatePartSize';\n/**\n * Create closure hiding the multipart upload implementation details and expose the upload job and control functions(\n * onPause, onResume, onCancel).\n *\n * @internal\n */\nexport const getMultipartUploadHandlers = (uploadDataInput, size) => {\n let resolveCallback;\n let rejectCallback;\n let inProgressUpload;\n let resolvedS3Config;\n let abortController;\n let resolvedAccessLevel;\n let resolvedBucket;\n let resolvedKeyPrefix;\n let resolvedIdentityId;\n let uploadCacheKey;\n let finalKey;\n let expectedBucketOwner;\n // Special flag that differentiates HTTP requests abort error caused by pause() from ones caused by cancel().\n // The former one should NOT cause the upload job to throw, but cancels any pending HTTP requests.\n // This should be replaced by a special abort reason. However,the support of this API is lagged behind.\n let isAbortSignalFromPause = false;\n const { resumableUploadsCache } = uploadDataInput.options ?? {};\n const startUpload = async () => {\n const { options: uploadDataOptions, data } = uploadDataInput;\n const resolvedS3Options = await resolveS3ConfigAndInput(Amplify, uploadDataInput);\n abortController = new AbortController();\n isAbortSignalFromPause = false;\n resolvedS3Config = resolvedS3Options.s3Config;\n resolvedBucket = resolvedS3Options.bucket;\n resolvedIdentityId = resolvedS3Options.identityId;\n expectedBucketOwner = uploadDataOptions?.expectedBucketOwner;\n const { inputType, objectKey } = validateStorageOperationInput(uploadDataInput, resolvedIdentityId);\n const { contentDisposition, contentEncoding, contentType = uploadDataOptions?.contentType ??\n getContentType(data, objectKey) ??\n 'application/octet-stream', metadata, preventOverwrite, onProgress, } = uploadDataOptions ?? {};\n finalKey = objectKey;\n // Resolve \"key\" specific options\n if (inputType === STORAGE_INPUT_KEY) {\n const accessLevel = uploadDataOptions\n ?.accessLevel;\n resolvedKeyPrefix = resolvedS3Options.keyPrefix;\n finalKey = resolvedKeyPrefix + objectKey;\n resolvedAccessLevel = resolveAccessLevel(accessLevel);\n }\n const optionsHash = await calculateContentCRC32(serializeUploadOptions(uploadDataOptions));\n if (!inProgressUpload) {\n const { uploadId, cachedParts, finalCrc32 } = await loadOrCreateMultipartUpload({\n s3Config: resolvedS3Config,\n accessLevel: resolvedAccessLevel,\n bucket: resolvedBucket,\n keyPrefix: resolvedKeyPrefix,\n key: objectKey,\n contentType,\n contentDisposition,\n contentEncoding,\n metadata,\n data,\n size,\n abortSignal: abortController.signal,\n checksumAlgorithm: uploadDataOptions?.checksumAlgorithm,\n optionsHash,\n resumableUploadsCache,\n expectedBucketOwner,\n });\n inProgressUpload = {\n uploadId,\n completedParts: cachedParts,\n finalCrc32,\n };\n }\n uploadCacheKey = size\n ? getUploadsCacheKey({\n file: data instanceof File ? data : undefined,\n accessLevel: resolvedAccessLevel,\n contentType: uploadDataOptions?.contentType,\n bucket: resolvedBucket,\n size,\n key: objectKey,\n optionsHash,\n })\n : undefined;\n const dataChunker = getDataChunker(data, size);\n const completedPartNumberSet = new Set(inProgressUpload.completedParts.map(({ PartNumber }) => PartNumber));\n const onPartUploadCompletion = (partNumber, eTag, crc32) => {\n inProgressUpload?.completedParts.push({\n PartNumber: partNumber,\n ETag: eTag,\n // TODO: crc32 can always be added once RN also has an implementation\n ...(crc32 ? { ChecksumCRC32: crc32 } : {}),\n });\n };\n const concurrentUploadsProgressTracker = getConcurrentUploadsProgressTracker({\n size,\n onProgress,\n });\n const concurrentUploadPartExecutors = [];\n for (let index = 0; index < DEFAULT_QUEUE_SIZE; index++) {\n concurrentUploadPartExecutors.push(uploadPartExecutor({\n dataChunkerGenerator: dataChunker,\n completedPartNumberSet,\n s3Config: resolvedS3Config,\n abortSignal: abortController.signal,\n bucket: resolvedBucket,\n finalKey,\n uploadId: inProgressUpload.uploadId,\n onPartUploadCompletion,\n onProgress: concurrentUploadsProgressTracker.getOnProgressListener(),\n isObjectLockEnabled: resolvedS3Options.isObjectLockEnabled,\n useCRC32Checksum: Boolean(inProgressUpload.finalCrc32),\n expectedBucketOwner,\n }));\n }\n await Promise.all(concurrentUploadPartExecutors);\n validateCompletedParts(inProgressUpload.completedParts, size);\n const { ETag: eTag } = await completeMultipartUpload({\n ...resolvedS3Config,\n abortSignal: abortController.signal,\n userAgentValue: getStorageUserAgentValue(StorageAction.UploadData),\n }, {\n Bucket: resolvedBucket,\n Key: finalKey,\n UploadId: inProgressUpload.uploadId,\n ChecksumCRC32: inProgressUpload.finalCrc32,\n ChecksumType: inProgressUpload.finalCrc32 ? 'FULL_OBJECT' : undefined,\n IfNoneMatch: preventOverwrite ? '*' : undefined,\n MultipartUpload: {\n Parts: sortUploadParts(inProgressUpload.completedParts),\n },\n ExpectedBucketOwner: expectedBucketOwner,\n });\n // If full-object CRC32 checksum is NOT enabled, we need to ensure the upload integrity by making extra HEAD call\n // to verify the uploaded object size.\n if (!inProgressUpload.finalCrc32) {\n const { ContentLength: uploadedObjectSize, $metadata } = await headObject(resolvedS3Config, {\n Bucket: resolvedBucket,\n Key: finalKey,\n ExpectedBucketOwner: expectedBucketOwner,\n });\n if (uploadedObjectSize && uploadedObjectSize !== size) {\n throw new StorageError({\n name: 'Error',\n message: `Upload failed. Expected object size ${size}, but got ${uploadedObjectSize}.`,\n metadata: $metadata,\n });\n }\n }\n if (resumableUploadsCache && uploadCacheKey) {\n await removeCachedUpload(resumableUploadsCache, uploadCacheKey);\n }\n const result = {\n eTag,\n contentType,\n metadata,\n };\n return inputType === STORAGE_INPUT_KEY\n ? { key: objectKey, ...result }\n : { path: objectKey, ...result };\n };\n const startUploadWithResumability = () => startUpload()\n .then(resolveCallback)\n .catch(error => {\n const abortSignal = abortController?.signal;\n if (abortSignal?.aborted && isAbortSignalFromPause) {\n logger.debug('upload paused.');\n }\n else {\n // Uncaught errors should be exposed to the users.\n rejectCallback(error);\n }\n });\n const multipartUploadJob = () => new Promise((resolve, reject) => {\n resolveCallback = resolve;\n rejectCallback = reject;\n startUploadWithResumability();\n });\n const onPause = () => {\n isAbortSignalFromPause = true;\n abortController?.abort();\n };\n const onResume = () => {\n startUploadWithResumability();\n };\n const onCancel = (message) => {\n // 1. abort in-flight API requests\n abortController?.abort(message);\n const cancelUpload = async () => {\n // 2. clear upload cache.\n if (uploadCacheKey && resumableUploadsCache) {\n await removeCachedUpload(resumableUploadsCache, uploadCacheKey);\n }\n // 3. clear multipart upload on server side.\n await abortMultipartUpload(resolvedS3Config, {\n Bucket: resolvedBucket,\n Key: finalKey,\n UploadId: inProgressUpload?.uploadId,\n ExpectedBucketOwner: expectedBucketOwner,\n });\n };\n cancelUpload().catch(e => {\n logger.debug('error when cancelling upload task.', e);\n });\n rejectCallback(\n // Internal error that should not be exposed to the users. They should use isCancelError() to check if\n // the error is caused by cancel().\n new CanceledError(message ? { message } : undefined));\n };\n return {\n multipartUploadJob,\n onPause,\n onResume,\n onCancel,\n };\n};\nconst resolveAccessLevel = (accessLevel) => accessLevel ??\n Amplify.libraryOptions.Storage?.S3?.defaultAccessLevel ??\n DEFAULT_ACCESS_LEVEL;\nconst validateCompletedParts = (completedParts, size) => {\n const partsExpected = Math.ceil(size / calculatePartSize(size));\n const validPartCount = completedParts.length === partsExpected;\n const sorted = sortUploadParts(completedParts);\n const validPartNumbers = sorted.every((part, index) => part.PartNumber === index + 1);\n if (!validPartCount || !validPartNumbers) {\n throw new IntegrityError();\n }\n};\nconst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23
23
|
import { calculateContentCRC32 } from '../../../utils/crc32.mjs';
|
|
24
24
|
import { constructContentDisposition } from '../../../utils/constructContentDisposition.mjs';
|
|
25
|
+
import { getContentType } from '../../../../../utils/contentType.mjs';
|
|
25
26
|
|
|
26
27
|
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
27
28
|
// SPDX-License-Identifier: Apache-2.0
|
|
@@ -36,7 +37,9 @@ const putObjectJob = (uploadDataInput, abortSignal, totalLength) => async () =>
|
|
|
36
37
|
const { inputType, objectKey } = validateStorageOperationInput(uploadDataInput, identityId);
|
|
37
38
|
validateBucketOwnerID(uploadDataOptions?.expectedBucketOwner);
|
|
38
39
|
const finalKey = inputType === STORAGE_INPUT_KEY ? keyPrefix + objectKey : objectKey;
|
|
39
|
-
const { contentDisposition, contentEncoding, contentType =
|
|
40
|
+
const { contentDisposition, contentEncoding, contentType = uploadDataOptions?.contentType ??
|
|
41
|
+
getContentType(data, objectKey) ??
|
|
42
|
+
'application/octet-stream', preventOverwrite, metadata, checksumAlgorithm, onProgress, expectedBucketOwner, } = uploadDataOptions ?? {};
|
|
40
43
|
const checksumCRC32 = checksumAlgorithm === CHECKSUM_ALGORITHM_CRC32
|
|
41
44
|
? await calculateContentCRC32(data)
|
|
42
45
|
: undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"putObjectJob.mjs","sources":["../../../../../../../src/providers/s3/apis/internal/uploadData/putObjectJob.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '@aws-amplify/core';\nimport { StorageAction } from '@aws-amplify/core/internals/utils';\nimport { calculateContentMd5, resolveS3ConfigAndInput, validateBucketOwnerID, validateStorageOperationInput, } from '../../../utils';\nimport { putObject } from '../../../utils/client/s3data';\nimport { getStorageUserAgentValue } from '../../../utils/userAgent';\nimport { CHECKSUM_ALGORITHM_CRC32, STORAGE_INPUT_KEY, } from '../../../utils/constants';\nimport { calculateContentCRC32 } from '../../../utils/crc32';\nimport { constructContentDisposition } from '../../../utils/constructContentDisposition';\n/**\n * Get a function the returns a promise to call putObject API to S3.\n *\n * @internal\n */\nexport const putObjectJob = (uploadDataInput, abortSignal, totalLength) => async () => {\n const { options: uploadDataOptions, data } = uploadDataInput;\n const { bucket, keyPrefix, s3Config, isObjectLockEnabled, identityId } = await resolveS3ConfigAndInput(Amplify, uploadDataInput);\n const { inputType, objectKey } = validateStorageOperationInput(uploadDataInput, identityId);\n validateBucketOwnerID(uploadDataOptions?.expectedBucketOwner);\n const finalKey = inputType === STORAGE_INPUT_KEY ? keyPrefix + objectKey : objectKey;\n const { contentDisposition, contentEncoding, contentType = 'application/octet-stream', preventOverwrite, metadata, checksumAlgorithm, onProgress, expectedBucketOwner, } = uploadDataOptions ?? {};\n const checksumCRC32 = checksumAlgorithm === CHECKSUM_ALGORITHM_CRC32\n ? await calculateContentCRC32(data)\n : undefined;\n const contentMD5 = \n // check if checksum exists. ex: should not exist in react native\n !checksumCRC32 && isObjectLockEnabled\n ? await calculateContentMd5(data)\n : undefined;\n const { ETag: eTag, VersionId: versionId } = await putObject({\n ...s3Config,\n abortSignal,\n onUploadProgress: onProgress,\n userAgentValue: getStorageUserAgentValue(StorageAction.UploadData),\n }, {\n Bucket: bucket,\n Key: finalKey,\n Body: data,\n ContentType: contentType,\n ContentDisposition: constructContentDisposition(contentDisposition),\n ContentEncoding: contentEncoding,\n Metadata: metadata,\n ContentMD5: contentMD5,\n ChecksumCRC32: checksumCRC32,\n ExpectedBucketOwner: expectedBucketOwner,\n IfNoneMatch: preventOverwrite ? '*' : undefined,\n });\n const result = {\n eTag,\n versionId,\n contentType,\n metadata,\n size: totalLength,\n };\n return inputType === STORAGE_INPUT_KEY\n ? { key: objectKey, ...result }\n : { path: objectKey, ...result };\n};\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"putObjectJob.mjs","sources":["../../../../../../../src/providers/s3/apis/internal/uploadData/putObjectJob.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Amplify } from '@aws-amplify/core';\nimport { StorageAction } from '@aws-amplify/core/internals/utils';\nimport { calculateContentMd5, resolveS3ConfigAndInput, validateBucketOwnerID, validateStorageOperationInput, } from '../../../utils';\nimport { putObject } from '../../../utils/client/s3data';\nimport { getStorageUserAgentValue } from '../../../utils/userAgent';\nimport { CHECKSUM_ALGORITHM_CRC32, STORAGE_INPUT_KEY, } from '../../../utils/constants';\nimport { calculateContentCRC32 } from '../../../utils/crc32';\nimport { constructContentDisposition } from '../../../utils/constructContentDisposition';\nimport { getContentType } from '../../../../../utils/contentType';\n/**\n * Get a function the returns a promise to call putObject API to S3.\n *\n * @internal\n */\nexport const putObjectJob = (uploadDataInput, abortSignal, totalLength) => async () => {\n const { options: uploadDataOptions, data } = uploadDataInput;\n const { bucket, keyPrefix, s3Config, isObjectLockEnabled, identityId } = await resolveS3ConfigAndInput(Amplify, uploadDataInput);\n const { inputType, objectKey } = validateStorageOperationInput(uploadDataInput, identityId);\n validateBucketOwnerID(uploadDataOptions?.expectedBucketOwner);\n const finalKey = inputType === STORAGE_INPUT_KEY ? keyPrefix + objectKey : objectKey;\n const { contentDisposition, contentEncoding, contentType = uploadDataOptions?.contentType ??\n getContentType(data, objectKey) ??\n 'application/octet-stream', preventOverwrite, metadata, checksumAlgorithm, onProgress, expectedBucketOwner, } = uploadDataOptions ?? {};\n const checksumCRC32 = checksumAlgorithm === CHECKSUM_ALGORITHM_CRC32\n ? await calculateContentCRC32(data)\n : undefined;\n const contentMD5 = \n // check if checksum exists. ex: should not exist in react native\n !checksumCRC32 && isObjectLockEnabled\n ? await calculateContentMd5(data)\n : undefined;\n const { ETag: eTag, VersionId: versionId } = await putObject({\n ...s3Config,\n abortSignal,\n onUploadProgress: onProgress,\n userAgentValue: getStorageUserAgentValue(StorageAction.UploadData),\n }, {\n Bucket: bucket,\n Key: finalKey,\n Body: data,\n ContentType: contentType,\n ContentDisposition: constructContentDisposition(contentDisposition),\n ContentEncoding: contentEncoding,\n Metadata: metadata,\n ContentMD5: contentMD5,\n ChecksumCRC32: checksumCRC32,\n ExpectedBucketOwner: expectedBucketOwner,\n IfNoneMatch: preventOverwrite ? '*' : undefined,\n });\n const result = {\n eTag,\n versionId,\n contentType,\n metadata,\n size: totalLength,\n };\n return inputType === STORAGE_INPUT_KEY\n ? { key: objectKey, ...result }\n : { path: objectKey, ...result };\n};\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AAUA;AACA;AACA;AACA;AACA;AACY,MAAC,YAAY,GAAG,CAAC,eAAe,EAAE,WAAW,EAAE,WAAW,KAAK,YAAY;AACvF,IAAI,MAAM,EAAE,OAAO,EAAE,iBAAiB,EAAE,IAAI,EAAE,GAAG,eAAe;AAChE,IAAI,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,QAAQ,EAAE,mBAAmB,EAAE,UAAU,EAAE,GAAG,MAAM,uBAAuB,CAAC,OAAO,EAAE,eAAe,CAAC;AACpI,IAAI,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,6BAA6B,CAAC,eAAe,EAAE,UAAU,CAAC;AAC/F,IAAI,qBAAqB,CAAC,iBAAiB,EAAE,mBAAmB,CAAC;AACjE,IAAI,MAAM,QAAQ,GAAG,SAAS,KAAK,iBAAiB,GAAG,SAAS,GAAG,SAAS,GAAG,SAAS;AACxF,IAAI,MAAM,EAAE,kBAAkB,EAAE,eAAe,EAAE,WAAW,GAAG,iBAAiB,EAAE,WAAW;AAC7F,QAAQ,cAAc,CAAC,IAAI,EAAE,SAAS,CAAC;AACvC,QAAQ,0BAA0B,EAAE,gBAAgB,EAAE,QAAQ,EAAE,iBAAiB,EAAE,UAAU,EAAE,mBAAmB,GAAG,GAAG,iBAAiB,IAAI,EAAE;AAC/I,IAAI,MAAM,aAAa,GAAG,iBAAiB,KAAK;AA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131
|
};
|
|
132
132
|
const convertToTransferProgressEvent = (event) => ({
|
|
133
|
-
|
|
133
|
+
// `loaded` can exceed the `total` in some cases due to platform issues/bugs e.g. React Native & Expo Android
|
|
134
|
+
// clamp `loaded` values down to `total` if possible.
|
|
135
|
+
transferredBytes: event.lengthComputable
|
|
136
|
+
? Math.min(event.loaded, event.total)
|
|
137
|
+
: event.loaded,
|
|
134
138
|
totalBytes: event.lengthComputable ? event.total : undefined,
|
|
135
139
|
});
|
|
136
140
|
const buildHandlerError = (message, name) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"xhrTransferHandler.mjs","sources":["../../../../../../../src/providers/s3/utils/client/runtime/xhrTransferHandler.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { withMemoization, } from '@aws-amplify/core/internals/aws-client-utils';\nimport { ConsoleLogger } from '@aws-amplify/core';\nimport { CanceledError } from '../../../../../errors/CanceledError';\nimport { StorageError } from '../../../../../errors/StorageError';\nimport { ABORT_ERROR_CODE, ABORT_ERROR_MESSAGE, CANCELED_ERROR_CODE, CANCELED_ERROR_MESSAGE, NETWORK_ERROR_CODE, NETWORK_ERROR_MESSAGE, } from './constants';\nconst logger = new ConsoleLogger('xhr-http-handler');\n/**\n * Base transfer handler implementation using XMLHttpRequest to support upload and download progress events.\n *\n * @param request - The request object.\n * @param options - The request options.\n * @returns A promise that will be resolved with the response object.\n *\n * @internal\n */\nexport const xhrTransferHandler = (request, options) => {\n const { url, method, headers, body } = request;\n const { onDownloadProgress, onUploadProgress, responseType, abortSignal } = options;\n return new Promise((resolve, reject) => {\n let xhr = new XMLHttpRequest();\n xhr.open(method.toUpperCase(), url.toString());\n Object.entries(headers)\n .filter(([header]) => !FORBIDDEN_HEADERS.includes(header))\n .forEach(([header, value]) => {\n xhr.setRequestHeader(header, value);\n });\n xhr.responseType = responseType;\n if (onDownloadProgress) {\n xhr.addEventListener('progress', event => {\n onDownloadProgress(convertToTransferProgressEvent(event));\n logger.debug(event);\n });\n }\n if (onUploadProgress) {\n xhr.upload.addEventListener('progress', event => {\n onUploadProgress(convertToTransferProgressEvent(event));\n logger.debug(event);\n });\n }\n xhr.addEventListener('error', () => {\n const networkError = new StorageError({\n message: NETWORK_ERROR_MESSAGE,\n name: NETWORK_ERROR_CODE,\n });\n logger.error(NETWORK_ERROR_MESSAGE);\n reject(networkError);\n xhr = null; // clean up request\n });\n // Handle browser request cancellation (as opposed to a manual cancellation)\n xhr.addEventListener('abort', () => {\n // The abort event can be triggered after the error or load event. So we need to check if the xhr is null.\n // When request is aborted by AbortSignal, the promise is rejected in the abortSignal's 'abort' event listener.\n if (!xhr || abortSignal?.aborted)\n return;\n // Handle abort request caused by browser instead of AbortController\n // see: https://github.com/axios/axios/issues/537\n const error = buildHandlerError(ABORT_ERROR_MESSAGE, ABORT_ERROR_CODE);\n logger.error(ABORT_ERROR_MESSAGE);\n reject(error);\n xhr = null; // clean up request\n });\n // Skip handling timeout error since we don't have a timeout\n xhr.addEventListener('readystatechange', () => {\n if (!xhr || xhr.readyState !== xhr.DONE) {\n return;\n }\n const onloadend = () => {\n // The load event is triggered after the error/abort/load event. So we need to check if the xhr is null.\n if (!xhr)\n return;\n const responseHeaders = convertResponseHeaders(xhr.getAllResponseHeaders());\n const { responseType: loadEndResponseType } = xhr;\n const responseBlob = xhr.response;\n const responseText = loadEndResponseType === 'text' ? xhr.responseText : '';\n const bodyMixIn = {\n blob: () => Promise.resolve(responseBlob),\n text: withMemoization(() => loadEndResponseType === 'blob'\n ? readBlobAsText(responseBlob)\n : Promise.resolve(responseText)),\n json: () => Promise.reject(\n // S3 does not support JSON response. So fail-fast here with nicer error message.\n new Error('Parsing response to JSON is not implemented. Please use response.text() instead.')),\n };\n const response = {\n statusCode: xhr.status,\n headers: responseHeaders,\n // The xhr.responseType is only set to 'blob' for streaming binary S3 object data. The streaming data is\n // exposed via public interface of Storage.get(). So we need to return the response as a Blob object for\n // backward compatibility. In other cases, the response payload is only used internally, we return it is\n // {@link ResponseBodyMixin}\n body: (xhr.responseType === 'blob'\n ? Object.assign(responseBlob, bodyMixIn)\n : bodyMixIn),\n };\n resolve(response);\n xhr = null; // clean up request\n };\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n // @see https://github.com/axios/axios/blob/9588fcdec8aca45c3ba2f7968988a5d03f23168c/lib/adapters/xhr.js#L98-L99\n setTimeout(onloadend);\n });\n if (abortSignal) {\n const onCanceled = () => {\n // The abort event is triggered after the error or load event. So we need to check if the xhr is null.\n if (!xhr) {\n return;\n }\n const canceledError = new CanceledError({\n name: CANCELED_ERROR_CODE,\n message: CANCELED_ERROR_MESSAGE,\n });\n reject(canceledError);\n xhr.abort();\n xhr = null;\n };\n abortSignal.aborted\n ? onCanceled()\n : abortSignal.addEventListener('abort', onCanceled);\n }\n if (typeof ReadableStream === 'function' &&\n body instanceof ReadableStream) {\n // This does not matter as previous implementation uses Axios which does not support ReadableStream anyway.\n throw new Error('ReadableStream request payload is not supported.');\n }\n xhr.send(body ?? null);\n });\n};\nconst convertToTransferProgressEvent = (event) => ({\n transferredBytes: event.loaded,\n totalBytes: event.lengthComputable ? event.total : undefined,\n});\nconst buildHandlerError = (message, name) => {\n const error = new Error(message);\n error.name = name;\n return error;\n};\n/**\n * Convert xhr.getAllResponseHeaders() string to a Record<string, string>. Note that modern browser already returns\n * header names in lowercase.\n * @param xhrHeaders - string of headers returned from xhr.getAllResponseHeaders()\n */\nconst convertResponseHeaders = (xhrHeaders) => {\n if (!xhrHeaders) {\n return {};\n }\n return xhrHeaders\n .split('\\r\\n')\n .reduce((headerMap, line) => {\n const parts = line.split(': ');\n const header = parts.shift();\n const value = parts.join(': ');\n headerMap[header.toLowerCase()] = value;\n return headerMap;\n }, {});\n};\nconst readBlobAsText = (blob) => {\n const reader = new FileReader();\n return new Promise((resolve, reject) => {\n reader.onloadend = () => {\n if (reader.readyState !== FileReader.DONE) {\n return;\n }\n resolve(reader.result);\n };\n reader.onerror = () => {\n reject(reader.error);\n };\n reader.readAsText(blob);\n });\n};\n// To add more forbidden headers as found set by S3. Intentionally NOT list all of them here to save bundle size.\n// https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name\nconst FORBIDDEN_HEADERS = ['host'];\n"],"names":[],"mappings":";;;;;;AAAA;AACA;AAMA,MAAM,MAAM,GAAG,IAAI,aAAa,CAAC,kBAAkB,CAAC;AACpD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACY,MAAC,kBAAkB,GAAG,CAAC,OAAO,EAAE,OAAO,KAAK;AACxD,IAAI,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,OAAO;AAClD,IAAI,MAAM,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,YAAY,EAAE,WAAW,EAAE,GAAG,OAAO;AACvF,IAAI,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,KAAK;AAC5C,QAAQ,IAAI,GAAG,GAAG,IAAI,cAAc,EAAE;AACtC,QAAQ,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE,EAAE,GAAG,CAAC,QAAQ,EAAE,CAAC;AACtD,QAAQ,MAAM,CAAC,OAAO,CAAC,OAAO;AAC9B,aAAa,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,iBAAiB,CAAC,QAAQ,CAAC,MAAM,CAAC;AACrE,aAAa,OAAO,CAAC,CAAC,CAAC,MAAM,EAAE,KAAK,CAAC,KAAK;AAC1C,YAAY,GAAG,CAAC,gBAAgB,CAAC,MAAM,EAAE,KAAK,CAAC;AAC/C,QAAQ,CAAC,CAAC;AACV,QAAQ,GAAG,CAAC,YAAY,GAAG,YAAY;AACvC,QAAQ,IAAI,kBAAkB,EAAE;AAChC,YAAY,GAAG,CAAC,gBAAgB,CAAC,UAAU,EAAE,KAAK,IAAI;AACtD,gBAAgB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Content":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { withMemoization, } from '@aws-amplify/core/internals/aws-client-utils';\nimport { ConsoleLogger } from '@aws-amplify/core';\nimport { CanceledError } from '../../../../../errors/CanceledError';\nimport { StorageError } from '../../../../../errors/StorageError';\nimport { ABORT_ERROR_CODE, ABORT_ERROR_MESSAGE, CANCELED_ERROR_CODE, CANCELED_ERROR_MESSAGE, NETWORK_ERROR_CODE, NETWORK_ERROR_MESSAGE, } from './constants';\nconst logger = new ConsoleLogger('xhr-http-handler');\n/**\n * Base transfer handler implementation using XMLHttpRequest to support upload and download progress events.\n *\n * @param request - The request object.\n * @param options - The request options.\n * @returns A promise that will be resolved with the response object.\n *\n * @internal\n */\nexport const xhrTransferHandler = (request, options) => {\n const { url, method, headers, body } = request;\n const { onDownloadProgress, onUploadProgress, responseType, abortSignal } = options;\n return new Promise((resolve, reject) => {\n let xhr = new XMLHttpRequest();\n xhr.open(method.toUpperCase(), url.toString());\n Object.entries(headers)\n .filter(([header]) => !FORBIDDEN_HEADERS.includes(header))\n .forEach(([header, value]) => {\n xhr.setRequestHeader(header, value);\n });\n xhr.responseType = responseType;\n if (onDownloadProgress) {\n xhr.addEventListener('progress', event => {\n onDownloadProgress(convertToTransferProgressEvent(event));\n logger.debug(event);\n });\n }\n if (onUploadProgress) {\n xhr.upload.addEventListener('progress', event => {\n onUploadProgress(convertToTransferProgressEvent(event));\n logger.debug(event);\n });\n }\n xhr.addEventListener('error', () => {\n const networkError = new StorageError({\n message: NETWORK_ERROR_MESSAGE,\n name: NETWORK_ERROR_CODE,\n });\n logger.error(NETWORK_ERROR_MESSAGE);\n reject(networkError);\n xhr = null; // clean up request\n });\n // Handle browser request cancellation (as opposed to a manual cancellation)\n xhr.addEventListener('abort', () => {\n // The abort event can be triggered after the error or load event. So we need to check if the xhr is null.\n // When request is aborted by AbortSignal, the promise is rejected in the abortSignal's 'abort' event listener.\n if (!xhr || abortSignal?.aborted)\n return;\n // Handle abort request caused by browser instead of AbortController\n // see: https://github.com/axios/axios/issues/537\n const error = buildHandlerError(ABORT_ERROR_MESSAGE, ABORT_ERROR_CODE);\n logger.error(ABORT_ERROR_MESSAGE);\n reject(error);\n xhr = null; // clean up request\n });\n // Skip handling timeout error since we don't have a timeout\n xhr.addEventListener('readystatechange', () => {\n if (!xhr || xhr.readyState !== xhr.DONE) {\n return;\n }\n const onloadend = () => {\n // The load event is triggered after the error/abort/load event. So we need to check if the xhr is null.\n if (!xhr)\n return;\n const responseHeaders = convertResponseHeaders(xhr.getAllResponseHeaders());\n const { responseType: loadEndResponseType } = xhr;\n const responseBlob = xhr.response;\n const responseText = loadEndResponseType === 'text' ? xhr.responseText : '';\n const bodyMixIn = {\n blob: () => Promise.resolve(responseBlob),\n text: withMemoization(() => loadEndResponseType === 'blob'\n ? readBlobAsText(responseBlob)\n : Promise.resolve(responseText)),\n json: () => Promise.reject(\n // S3 does not support JSON response. So fail-fast here with nicer error message.\n new Error('Parsing response to JSON is not implemented. Please use response.text() instead.')),\n };\n const response = {\n statusCode: xhr.status,\n headers: responseHeaders,\n // The xhr.responseType is only set to 'blob' for streaming binary S3 object data. The streaming data is\n // exposed via public interface of Storage.get(). So we need to return the response as a Blob object for\n // backward compatibility. In other cases, the response payload is only used internally, we return it is\n // {@link ResponseBodyMixin}\n body: (xhr.responseType === 'blob'\n ? Object.assign(responseBlob, bodyMixIn)\n : bodyMixIn),\n };\n resolve(response);\n xhr = null; // clean up request\n };\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n // @see https://github.com/axios/axios/blob/9588fcdec8aca45c3ba2f7968988a5d03f23168c/lib/adapters/xhr.js#L98-L99\n setTimeout(onloadend);\n });\n if (abortSignal) {\n const onCanceled = () => {\n // The abort event is triggered after the error or load event. So we need to check if the xhr is null.\n if (!xhr) {\n return;\n }\n const canceledError = new CanceledError({\n name: CANCELED_ERROR_CODE,\n message: CANCELED_ERROR_MESSAGE,\n });\n reject(canceledError);\n xhr.abort();\n xhr = null;\n };\n abortSignal.aborted\n ? onCanceled()\n : abortSignal.addEventListener('abort', onCanceled);\n }\n if (typeof ReadableStream === 'function' &&\n body instanceof ReadableStream) {\n // This does not matter as previous implementation uses Axios which does not support ReadableStream anyway.\n throw new Error('ReadableStream request payload is not supported.');\n }\n xhr.send(body ?? null);\n });\n};\nconst convertToTransferProgressEvent = (event) => ({\n // `loaded` can exceed the `total` in some cases due to platform issues/bugs e.g. React Native & Expo Android\n // clamp `loaded` values down to `total` if possible.\n transferredBytes: event.lengthComputable\n ? Math.min(event.loaded, event.total)\n : event.loaded,\n totalBytes: event.lengthComputable ? event.total : undefined,\n});\nconst buildHandlerError = (message, name) => {\n const error = new Error(message);\n error.name = name;\n return error;\n};\n/**\n * Convert xhr.getAllResponseHeaders() string to a Record<string, string>. Note that modern browser already returns\n * header names in lowercase.\n * @param xhrHeaders - string of headers returned from xhr.getAllResponseHeaders()\n */\nconst convertResponseHeaders = (xhrHeaders) => {\n if (!xhrHeaders) {\n return {};\n }\n return xhrHeaders\n .split('\\r\\n')\n .reduce((headerMap, line) => {\n const parts = line.split(': ');\n const header = parts.shift();\n const value = parts.join(': ');\n headerMap[header.toLowerCase()] = value;\n return headerMap;\n }, {});\n};\nconst readBlobAsText = (blob) => {\n const reader = new FileReader();\n return new Promise((resolve, reject) => {\n reader.onloadend = () => {\n if (reader.readyState !== FileReader.DONE) {\n return;\n }\n resolve(reader.result);\n };\n reader.onerror = () => {\n reject(reader.error);\n };\n reader.readAsText(blob);\n });\n};\n// To add more forbidden headers as found set by S3. Intentionally NOT list all of them here to save bundle size.\n// https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name\nconst FORBIDDEN_HEADERS = ['host'];\n"],"names":[],"mappings":";;;;;;AAAA;AACA;AAMA,MAAM,MAAM,GAAG,IAAI,aAAa,CAAC,kBAAkB,CAAC;AACpD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;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AAI,CAAC,KAAK,CAAC,IAAI,CAAC;AACtC,QAAQ,MAAM,MAAM,GAAG,KAAK,CAAC,KAAK,EAAE;AACpC,QAAQ,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC;AACtC,QAAQ,SAAS,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,GAAG,KAAK;AAC/C,QAAQ,OAAO,SAAS;AACxB,IAAI,CAAC,EAAE,EAAE,CAAC;AACV,CAAC;AACD,MAAM,cAAc,GAAG,CAAC,IAAI,KAAK;AACjC,IAAI,MAAM,MAAM,GAAG,IAAI,UAAU,EAAE;AACnC,IAAI,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,KAAK;AAC5C,QAAQ,MAAM,CAAC,SAAS,GAAG,MAAM;AACjC,YAAY,IAAI,MAAM,CAAC,UAAU,KAAK,UAAU,CAAC,IAAI,EAAE;AACvD,gBAAgB;AAChB,YAAY;AACZ,YAAY,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC;AAClC,QAAQ,CAAC;AACT,QAAQ,MAAM,CAAC,OAAO,GAAG,MAAM;AAC/B,YAAY,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC;AAChC,QAAQ,CAAC;AACT,QAAQ,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC;AAC/B,IAAI,CAAC,CAAC;AACN,CAAC;AACD;AACA;AACA,MAAM,iBAAiB,GAAG,CAAC,MAAM,CAAC;;;;"}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
const MIME_TYPES = {
|
|
4
|
+
// Audio
|
|
5
|
+
aac: 'audio/aac',
|
|
6
|
+
mid: 'audio/midi',
|
|
7
|
+
midi: 'audio/x-midi',
|
|
8
|
+
mp3: 'audio/mpeg',
|
|
9
|
+
oga: 'audio/ogg',
|
|
10
|
+
opus: 'audio/ogg',
|
|
11
|
+
wav: 'audio/wav',
|
|
12
|
+
weba: 'audio/webm',
|
|
13
|
+
// Video
|
|
14
|
+
avi: 'video/x-msvideo',
|
|
15
|
+
mp4: 'video/mp4',
|
|
16
|
+
mpeg: 'video/mpeg',
|
|
17
|
+
ogv: 'video/ogg',
|
|
18
|
+
ts: 'video/mp2t',
|
|
19
|
+
webm: 'video/webm',
|
|
20
|
+
// Images
|
|
21
|
+
apng: 'image/apng',
|
|
22
|
+
avif: 'image/avif',
|
|
23
|
+
bmp: 'image/bmp',
|
|
24
|
+
gif: 'image/gif',
|
|
25
|
+
ico: 'image/vnd.microsoft.icon',
|
|
26
|
+
jpeg: 'image/jpeg',
|
|
27
|
+
jpg: 'image/jpeg',
|
|
28
|
+
png: 'image/png',
|
|
29
|
+
svg: 'image/svg+xml',
|
|
30
|
+
tif: 'image/tiff',
|
|
31
|
+
tiff: 'image/tiff',
|
|
32
|
+
webp: 'image/webp',
|
|
33
|
+
// Text
|
|
34
|
+
css: 'text/css',
|
|
35
|
+
csv: 'text/csv',
|
|
36
|
+
htm: 'text/html',
|
|
37
|
+
html: 'text/html',
|
|
38
|
+
ics: 'text/calendar',
|
|
39
|
+
js: 'text/javascript',
|
|
40
|
+
md: 'text/markdown',
|
|
41
|
+
mjs: 'text/javascript',
|
|
42
|
+
txt: 'text/plain',
|
|
43
|
+
// Application
|
|
44
|
+
abw: 'application/x-abiword',
|
|
45
|
+
arc: 'application/x-freearc',
|
|
46
|
+
azw: 'application/vnd.amazon.ebook',
|
|
47
|
+
bin: 'application/octet-stream',
|
|
48
|
+
bz: 'application/x-bzip',
|
|
49
|
+
bz2: 'application/x-bzip2',
|
|
50
|
+
cda: 'application/x-cdf',
|
|
51
|
+
csh: 'application/x-csh',
|
|
52
|
+
doc: 'application/msword',
|
|
53
|
+
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
54
|
+
eot: 'application/vnd.ms-fontobject',
|
|
55
|
+
epub: 'application/epub+zip',
|
|
56
|
+
gz: 'application/gzip',
|
|
57
|
+
jar: 'application/java-archive',
|
|
58
|
+
json: 'application/json',
|
|
59
|
+
jsonld: 'application/ld+json',
|
|
60
|
+
mpkg: 'application/vnd.apple.installer+xml',
|
|
61
|
+
odp: 'application/vnd.oasis.opendocument.presentation',
|
|
62
|
+
ods: 'application/vnd.oasis.opendocument.spreadsheet',
|
|
63
|
+
odt: 'application/vnd.oasis.opendocument.text',
|
|
64
|
+
ogx: 'application/ogg',
|
|
65
|
+
pdf: 'application/pdf',
|
|
66
|
+
php: 'application/x-httpd-php',
|
|
67
|
+
ppt: 'application/vnd.ms-powerpoint',
|
|
68
|
+
pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
|
69
|
+
rar: 'application/vnd.rar',
|
|
70
|
+
rtf: 'application/rtf',
|
|
71
|
+
sh: 'application/x-sh',
|
|
72
|
+
tar: 'application/x-tar',
|
|
73
|
+
vsd: 'application/vnd.visio',
|
|
74
|
+
webmanifest: 'application/manifest+json',
|
|
75
|
+
xhtml: 'application/xhtml+xml',
|
|
76
|
+
xls: 'application/vnd.ms-excel',
|
|
77
|
+
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
78
|
+
xml: 'application/xml',
|
|
79
|
+
zip: 'application/zip',
|
|
80
|
+
// Fonts
|
|
81
|
+
otf: 'font/otf',
|
|
82
|
+
ttf: 'font/ttf',
|
|
83
|
+
woff: 'font/woff',
|
|
84
|
+
woff2: 'font/woff2',
|
|
85
|
+
};
|
|
86
|
+
/**
|
|
87
|
+
* Detect content type from file data or filename extension
|
|
88
|
+
*/
|
|
89
|
+
const getContentType = (data, key) => {
|
|
90
|
+
if (data instanceof File && data.type) {
|
|
91
|
+
return data.type;
|
|
92
|
+
}
|
|
93
|
+
const ext = key.split('.').pop()?.toLowerCase();
|
|
94
|
+
return ext ? MIME_TYPES[ext] : undefined;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
export { getContentType };
|
|
98
|
+
//# sourceMappingURL=contentType.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"contentType.mjs","sources":["../../../src/utils/contentType.ts"],"sourcesContent":["// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst MIME_TYPES = {\n // Audio\n aac: 'audio/aac',\n mid: 'audio/midi',\n midi: 'audio/x-midi',\n mp3: 'audio/mpeg',\n oga: 'audio/ogg',\n opus: 'audio/ogg',\n wav: 'audio/wav',\n weba: 'audio/webm',\n // Video\n avi: 'video/x-msvideo',\n mp4: 'video/mp4',\n mpeg: 'video/mpeg',\n ogv: 'video/ogg',\n ts: 'video/mp2t',\n webm: 'video/webm',\n // Images\n apng: 'image/apng',\n avif: 'image/avif',\n bmp: 'image/bmp',\n gif: 'image/gif',\n ico: 'image/vnd.microsoft.icon',\n jpeg: 'image/jpeg',\n jpg: 'image/jpeg',\n png: 'image/png',\n svg: 'image/svg+xml',\n tif: 'image/tiff',\n tiff: 'image/tiff',\n webp: 'image/webp',\n // Text\n css: 'text/css',\n csv: 'text/csv',\n htm: 'text/html',\n html: 'text/html',\n ics: 'text/calendar',\n js: 'text/javascript',\n md: 'text/markdown',\n mjs: 'text/javascript',\n txt: 'text/plain',\n // Application\n abw: 'application/x-abiword',\n arc: 'application/x-freearc',\n azw: 'application/vnd.amazon.ebook',\n bin: 'application/octet-stream',\n bz: 'application/x-bzip',\n bz2: 'application/x-bzip2',\n cda: 'application/x-cdf',\n csh: 'application/x-csh',\n doc: 'application/msword',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n eot: 'application/vnd.ms-fontobject',\n epub: 'application/epub+zip',\n gz: 'application/gzip',\n jar: 'application/java-archive',\n json: 'application/json',\n jsonld: 'application/ld+json',\n mpkg: 'application/vnd.apple.installer+xml',\n odp: 'application/vnd.oasis.opendocument.presentation',\n ods: 'application/vnd.oasis.opendocument.spreadsheet',\n odt: 'application/vnd.oasis.opendocument.text',\n ogx: 'application/ogg',\n pdf: 'application/pdf',\n php: 'application/x-httpd-php',\n ppt: 'application/vnd.ms-powerpoint',\n pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n rar: 'application/vnd.rar',\n rtf: 'application/rtf',\n sh: 'application/x-sh',\n tar: 'application/x-tar',\n vsd: 'application/vnd.visio',\n webmanifest: 'application/manifest+json',\n xhtml: 'application/xhtml+xml',\n xls: 'application/vnd.ms-excel',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n xml: 'application/xml',\n zip: 'application/zip',\n // Fonts\n otf: 'font/otf',\n ttf: 'font/ttf',\n woff: 'font/woff',\n woff2: 'font/woff2',\n};\n/**\n * Detect content type from file data or filename extension\n */\nexport const getContentType = (data, key) => {\n if (data instanceof File && data.type) {\n return data.type;\n }\n const ext = key.split('.').pop()?.toLowerCase();\n return ext ? MIME_TYPES[ext] : undefined;\n};\n"],"names":[],"mappings":"AAAA;AACA;AACA,MAAM,UAAU,GAAG;AACnB;AACA,IAAI,GAAG,EAAE,WAAW;AACpB,IAAI,GAAG,EAAE,YAAY;AACrB,IAAI,IAAI,EAAE,cAAc;AACxB,IAAI,GAAG,EAAE,YAAY;AACrB,IAAI,GAAG,EAAE,WAAW;AACpB,IAAI,IAAI,EAAE,WAAW;AACrB,IAAI,GAAG,EAAE,WAAW;AACpB,IAAI,IAAI,EAAE,YAAY;AACtB;AACA,IAAI,GAAG,EAAE,iBAAiB;AAC1B,IAAI,GAAG,EAAE,WAAW;AACpB,IAAI,IAAI,EAAE,YAAY;AACtB,IAAI,GAAG,EAAE,WAAW;AACpB,IAAI,EAAE,EAAE,YAAY;AACpB,IAAI,IAAI,EAAE,YAAY;AACtB;AACA,IAAI,IAAI,EAAE,YAAY;AACtB,IAAI,IAAI,EAAE,YAAY;AACtB,IAAI,GAAG,EAAE,WAAW;AACpB,IAAI,GAAG,EAAE,WAAW;AACpB,IAAI,GAAG,EAAE,0BAA0B;AACnC,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AAG,EAAE,yBAAyB;AAClC,IAAI,GAAG,EAAE,+BAA+B;AACxC,IAAI,IAAI,EAAE,2EAA2E;AACrF,IAAI,GAAG,EAAE,qBAAqB;AAC9B,IAAI,GAAG,EAAE,iBAAiB;AAC1B,IAAI,EAAE,EAAE,kBAAkB;AAC1B,IAAI,GAAG,EAAE,mBAAmB;AAC5B,IAAI,GAAG,EAAE,uBAAuB;AAChC,IAAI,WAAW,EAAE,2BAA2B;AAC5C,IAAI,KAAK,EAAE,uBAAuB;AAClC,IAAI,GAAG,EAAE,0BAA0B;AACnC,IAAI,IAAI,EAAE,mEAAmE;AAC7E,IAAI,GAAG,EAAE,iBAAiB;AAC1B,IAAI,GAAG,EAAE,iBAAiB;AAC1B;AACA,IAAI,GAAG,EAAE,UAAU;AACnB,IAAI,GAAG,EAAE,UAAU;AACnB,IAAI,IAAI,EAAE,WAAW;AACrB,IAAI,KAAK,EAAE,YAAY;AACvB,CAAC;AACD;AACA;AACA;AACY,MAAC,cAAc,GAAG,CAAC,IAAI,EAAE,GAAG,KAAK;AAC7C,IAAI,IAAI,IAAI,YAAY,IAAI,IAAI,IAAI,CAAC,IAAI,EAAE;AAC3C,QAAQ,OAAO,IAAI,CAAC,IAAI;AACxB,IAAI;AACJ,IAAI,MAAM,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,WAAW,EAAE;AACnD,IAAI,OAAO,GAAG,GAAG,UAAU,CAAC,GAAG,CAAC,GAAG,SAAS;AAC5C;;;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aws-amplify/storage",
|
|
3
|
-
"version": "6.9.
|
|
3
|
+
"version": "6.9.6-unstable.0f5e997.0+0f5e997",
|
|
4
4
|
"description": "Storage category of aws-amplify",
|
|
5
5
|
"main": "./dist/cjs/index.js",
|
|
6
6
|
"module": "./dist/esm/index.mjs",
|
|
@@ -108,12 +108,12 @@
|
|
|
108
108
|
"./package.json": "./package.json"
|
|
109
109
|
},
|
|
110
110
|
"peerDependencies": {
|
|
111
|
-
"@aws-amplify/core": "6.13.
|
|
111
|
+
"@aws-amplify/core": "6.13.2-unstable.0f5e997.0+0f5e997"
|
|
112
112
|
},
|
|
113
113
|
"devDependencies": {
|
|
114
|
-
"@aws-amplify/core": "6.13.
|
|
115
|
-
"@aws-amplify/react-native": "1.1.11-unstable.
|
|
114
|
+
"@aws-amplify/core": "6.13.2-unstable.0f5e997.0+0f5e997",
|
|
115
|
+
"@aws-amplify/react-native": "1.1.11-unstable.0f5e997.0+0f5e997",
|
|
116
116
|
"@types/node": "20.14.12"
|
|
117
117
|
},
|
|
118
|
-
"gitHead": "
|
|
118
|
+
"gitHead": "0f5e997fa9a641a459b8fd3392e0f6fc4de5ad94"
|
|
119
119
|
}
|
|
@@ -12,6 +12,7 @@ import { Part, listParts } from '../../../../utils/client/s3data';
|
|
|
12
12
|
import { logger } from '../../../../../../utils';
|
|
13
13
|
// TODO: Remove this interface when we move to public advanced APIs.
|
|
14
14
|
import { UploadDataInput as UploadDataWithPathInputWithAdvancedOptions } from '../../../../../../internals/types/inputs';
|
|
15
|
+
import { getContentType } from '../../../../../../utils/contentType';
|
|
15
16
|
|
|
16
17
|
const ONE_HOUR = 1000 * 60 * 60;
|
|
17
18
|
|
|
@@ -166,7 +167,7 @@ export const getUploadsCacheKey = ({
|
|
|
166
167
|
}: UploadsCacheKeyOptions) => {
|
|
167
168
|
let levelStr;
|
|
168
169
|
const resolvedContentType =
|
|
169
|
-
contentType ?? file
|
|
170
|
+
contentType ?? getContentType(file, key) ?? 'application/octet-stream';
|
|
170
171
|
|
|
171
172
|
// If no access level is defined, we're using custom gen2 access rules
|
|
172
173
|
if (accessLevel === undefined) {
|
|
@@ -38,6 +38,7 @@ import { logger } from '../../../../../../utils';
|
|
|
38
38
|
import { calculateContentCRC32 } from '../../../../utils/crc32';
|
|
39
39
|
import { StorageOperationOptionsInput } from '../../../../../../types/inputs';
|
|
40
40
|
import { IntegrityError } from '../../../../../../errors/IntegrityError';
|
|
41
|
+
import { getContentType } from '../../../../../../utils/contentType';
|
|
41
42
|
|
|
42
43
|
import { uploadPartExecutor } from './uploadPartExecutor';
|
|
43
44
|
import {
|
|
@@ -137,7 +138,9 @@ export const getMultipartUploadHandlers = (
|
|
|
137
138
|
const {
|
|
138
139
|
contentDisposition,
|
|
139
140
|
contentEncoding,
|
|
140
|
-
contentType =
|
|
141
|
+
contentType = uploadDataOptions?.contentType ??
|
|
142
|
+
getContentType(data, objectKey) ??
|
|
143
|
+
'application/octet-stream',
|
|
141
144
|
metadata,
|
|
142
145
|
preventOverwrite,
|
|
143
146
|
onProgress,
|
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
} from '../../../utils/constants';
|
|
23
23
|
import { calculateContentCRC32 } from '../../../utils/crc32';
|
|
24
24
|
import { constructContentDisposition } from '../../../utils/constructContentDisposition';
|
|
25
|
+
import { getContentType } from '../../../../../utils/contentType';
|
|
25
26
|
|
|
26
27
|
/**
|
|
27
28
|
* The input interface for UploadData API with only the options needed for single part upload.
|
|
@@ -60,7 +61,9 @@ export const putObjectJob =
|
|
|
60
61
|
const {
|
|
61
62
|
contentDisposition,
|
|
62
63
|
contentEncoding,
|
|
63
|
-
contentType =
|
|
64
|
+
contentType = uploadDataOptions?.contentType ??
|
|
65
|
+
getContentType(data, objectKey) ??
|
|
66
|
+
'application/octet-stream',
|
|
64
67
|
preventOverwrite,
|
|
65
68
|
metadata,
|
|
66
69
|
checksumAlgorithm,
|
|
@@ -190,7 +190,11 @@ export const xhrTransferHandler: TransferHandler<
|
|
|
190
190
|
const convertToTransferProgressEvent = (
|
|
191
191
|
event: ProgressEvent,
|
|
192
192
|
): TransferProgressEvent => ({
|
|
193
|
-
|
|
193
|
+
// `loaded` can exceed the `total` in some cases due to platform issues/bugs e.g. React Native & Expo Android
|
|
194
|
+
// clamp `loaded` values down to `total` if possible.
|
|
195
|
+
transferredBytes: event.lengthComputable
|
|
196
|
+
? Math.min(event.loaded, event.total)
|
|
197
|
+
: event.loaded,
|
|
194
198
|
totalBytes: event.lengthComputable ? event.total : undefined,
|
|
195
199
|
});
|
|
196
200
|
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
const MIME_TYPES: Record<string, string> = {
|
|
5
|
+
// Audio
|
|
6
|
+
aac: 'audio/aac',
|
|
7
|
+
mid: 'audio/midi',
|
|
8
|
+
midi: 'audio/x-midi',
|
|
9
|
+
mp3: 'audio/mpeg',
|
|
10
|
+
oga: 'audio/ogg',
|
|
11
|
+
opus: 'audio/ogg',
|
|
12
|
+
wav: 'audio/wav',
|
|
13
|
+
weba: 'audio/webm',
|
|
14
|
+
// Video
|
|
15
|
+
avi: 'video/x-msvideo',
|
|
16
|
+
mp4: 'video/mp4',
|
|
17
|
+
mpeg: 'video/mpeg',
|
|
18
|
+
ogv: 'video/ogg',
|
|
19
|
+
ts: 'video/mp2t',
|
|
20
|
+
webm: 'video/webm',
|
|
21
|
+
// Images
|
|
22
|
+
apng: 'image/apng',
|
|
23
|
+
avif: 'image/avif',
|
|
24
|
+
bmp: 'image/bmp',
|
|
25
|
+
gif: 'image/gif',
|
|
26
|
+
ico: 'image/vnd.microsoft.icon',
|
|
27
|
+
jpeg: 'image/jpeg',
|
|
28
|
+
jpg: 'image/jpeg',
|
|
29
|
+
png: 'image/png',
|
|
30
|
+
svg: 'image/svg+xml',
|
|
31
|
+
tif: 'image/tiff',
|
|
32
|
+
tiff: 'image/tiff',
|
|
33
|
+
webp: 'image/webp',
|
|
34
|
+
// Text
|
|
35
|
+
css: 'text/css',
|
|
36
|
+
csv: 'text/csv',
|
|
37
|
+
htm: 'text/html',
|
|
38
|
+
html: 'text/html',
|
|
39
|
+
ics: 'text/calendar',
|
|
40
|
+
js: 'text/javascript',
|
|
41
|
+
md: 'text/markdown',
|
|
42
|
+
mjs: 'text/javascript',
|
|
43
|
+
txt: 'text/plain',
|
|
44
|
+
// Application
|
|
45
|
+
abw: 'application/x-abiword',
|
|
46
|
+
arc: 'application/x-freearc',
|
|
47
|
+
azw: 'application/vnd.amazon.ebook',
|
|
48
|
+
bin: 'application/octet-stream',
|
|
49
|
+
bz: 'application/x-bzip',
|
|
50
|
+
bz2: 'application/x-bzip2',
|
|
51
|
+
cda: 'application/x-cdf',
|
|
52
|
+
csh: 'application/x-csh',
|
|
53
|
+
doc: 'application/msword',
|
|
54
|
+
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
55
|
+
eot: 'application/vnd.ms-fontobject',
|
|
56
|
+
epub: 'application/epub+zip',
|
|
57
|
+
gz: 'application/gzip',
|
|
58
|
+
jar: 'application/java-archive',
|
|
59
|
+
json: 'application/json',
|
|
60
|
+
jsonld: 'application/ld+json',
|
|
61
|
+
mpkg: 'application/vnd.apple.installer+xml',
|
|
62
|
+
odp: 'application/vnd.oasis.opendocument.presentation',
|
|
63
|
+
ods: 'application/vnd.oasis.opendocument.spreadsheet',
|
|
64
|
+
odt: 'application/vnd.oasis.opendocument.text',
|
|
65
|
+
ogx: 'application/ogg',
|
|
66
|
+
pdf: 'application/pdf',
|
|
67
|
+
php: 'application/x-httpd-php',
|
|
68
|
+
ppt: 'application/vnd.ms-powerpoint',
|
|
69
|
+
pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
|
70
|
+
rar: 'application/vnd.rar',
|
|
71
|
+
rtf: 'application/rtf',
|
|
72
|
+
sh: 'application/x-sh',
|
|
73
|
+
tar: 'application/x-tar',
|
|
74
|
+
vsd: 'application/vnd.visio',
|
|
75
|
+
webmanifest: 'application/manifest+json',
|
|
76
|
+
xhtml: 'application/xhtml+xml',
|
|
77
|
+
xls: 'application/vnd.ms-excel',
|
|
78
|
+
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
79
|
+
xml: 'application/xml',
|
|
80
|
+
zip: 'application/zip',
|
|
81
|
+
// Fonts
|
|
82
|
+
otf: 'font/otf',
|
|
83
|
+
ttf: 'font/ttf',
|
|
84
|
+
woff: 'font/woff',
|
|
85
|
+
woff2: 'font/woff2',
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Detect content type from file data or filename extension
|
|
90
|
+
*/
|
|
91
|
+
export const getContentType = (data: any, key: string): string | undefined => {
|
|
92
|
+
if (data instanceof File && data.type) {
|
|
93
|
+
return data.type;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const ext = key.split('.').pop()?.toLowerCase();
|
|
97
|
+
|
|
98
|
+
return ext ? MIME_TYPES[ext] : undefined;
|
|
99
|
+
};
|