;\n}\n","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nimport { Credentials, Logger, getAmplifyUserAgent, } from '@aws-amplify/core';\nimport { S3Client } from '@aws-sdk/client-s3';\nimport { AxiosHttpHandler } from '../providers/axios-http-handler';\nimport { localTestingStorageEndpoint, SET_CONTENT_LENGTH_HEADER, } from './StorageConstants';\nvar logger = new Logger('S3ClientUtils');\n// placeholder credentials in order to satisfy type requirement, always results in 403 when used\nvar INVALID_CRED = { accessKeyId: '', secretAccessKey: '' };\nexport var getPrefix = function (config) {\n var credentials = config.credentials, level = config.level, customPrefix = config.customPrefix, identityId = config.identityId;\n var resolvedCustomPrefix = customPrefix || {};\n var resolvedIdentityId = identityId || credentials.identityId;\n var privatePath = (resolvedCustomPrefix.private !== undefined\n ? resolvedCustomPrefix.private\n : 'private/') +\n resolvedIdentityId +\n '/';\n var protectedPath = (resolvedCustomPrefix.protected !== undefined\n ? resolvedCustomPrefix.protected\n : 'protected/') +\n resolvedIdentityId +\n '/';\n var publicPath = resolvedCustomPrefix.public !== undefined\n ? resolvedCustomPrefix.public\n : 'public/';\n switch (level) {\n case 'private':\n return privatePath;\n case 'protected':\n return protectedPath;\n default:\n return publicPath;\n }\n};\nexport var createPrefixMiddleware = function (opt, key) { return function (next, _context) { return function (args) { return __awaiter(void 0, void 0, void 0, function () {\n var credentials, cred, prefix, clonedInput, result;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, Credentials.get()];\n case 1:\n credentials = _a.sent();\n cred = Credentials.shear(credentials);\n prefix = getPrefix(__assign(__assign({}, opt), { credentials: cred }));\n clonedInput = Object.assign({}, args.input);\n if (Object.prototype.hasOwnProperty.call(args.input, 'Key')) {\n clonedInput.Key = prefix + key;\n args.input = clonedInput;\n }\n else if (Object.prototype.hasOwnProperty.call(args.input, 'Prefix')) {\n clonedInput.Prefix = prefix + key;\n args.input = clonedInput;\n }\n result = next(args);\n return [2 /*return*/, result];\n }\n });\n}); }; }; };\nvar isTimeSkewedError = function (err) {\n return err.ServerTime &&\n typeof err.Code === 'string' &&\n err.Code === 'RequestTimeTooSkewed';\n};\n// we want to take the S3Client config in parameter so we can modify it's systemClockOffset\nexport var autoAdjustClockskewMiddleware = function (config) { return function (next, _context) { return function (args) { return __awaiter(void 0, void 0, void 0, function () {\n var err_1, serverDate;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 2, , 3]);\n return [4 /*yield*/, next(args)];\n case 1: return [2 /*return*/, _a.sent()];\n case 2:\n err_1 = _a.sent();\n if (isTimeSkewedError(err_1)) {\n serverDate = new Date(err_1.ServerTime);\n config.systemClockOffset = serverDate.getTime() - Date.now();\n }\n throw err_1;\n case 3: return [2 /*return*/];\n }\n });\n}); }; }; };\nexport var autoAdjustClockskewMiddlewareOptions = {\n step: 'finalizeRequest',\n name: 'autoAdjustClockskewMiddleware',\n};\nexport var prefixMiddlewareOptions = {\n step: 'initialize',\n name: 'addPrefixMiddleware',\n};\nexport var credentialsProvider = function () { return __awaiter(void 0, void 0, void 0, function () {\n var credentials, cred, error_1;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 2, , 3]);\n return [4 /*yield*/, Credentials.get()];\n case 1:\n credentials = _a.sent();\n if (!credentials)\n return [2 /*return*/, INVALID_CRED];\n cred = Credentials.shear(credentials);\n logger.debug('credentials provider get credentials', cred);\n return [2 /*return*/, cred];\n case 2:\n error_1 = _a.sent();\n logger.warn('credentials provider error', error_1);\n return [2 /*return*/, INVALID_CRED];\n case 3: return [2 /*return*/];\n }\n });\n}); };\nexport var createS3Client = function (config, emitter) {\n var region = config.region, cancelTokenSource = config.cancelTokenSource, dangerouslyConnectToHttpEndpointForTesting = config.dangerouslyConnectToHttpEndpointForTesting, useAccelerateEndpoint = config.useAccelerateEndpoint;\n var localTestingConfig = {};\n if (dangerouslyConnectToHttpEndpointForTesting) {\n localTestingConfig = {\n endpoint: localTestingStorageEndpoint,\n tls: false,\n bucketEndpoint: false,\n forcePathStyle: true,\n };\n }\n var s3client = new S3Client(__assign(__assign({ region: region, \n // Using provider instead of a static credentials, so that if an upload task was in progress, but credentials gets\n // changed or invalidated (e.g user signed out), the subsequent requests will fail.\n credentials: credentialsProvider, customUserAgent: getAmplifyUserAgent() }, localTestingConfig), { requestHandler: new AxiosHttpHandler({}, emitter, cancelTokenSource), useAccelerateEndpoint: useAccelerateEndpoint }));\n s3client.middlewareStack.remove(SET_CONTENT_LENGTH_HEADER);\n return s3client;\n};\n//# sourceMappingURL=S3ClientUtils.js.map","import { __extends } from \"tslib\";\nimport { PutObjectOutput, PutObjectRequest } from \"../models/models_0\";\nimport { deserializeAws_restXmlPutObjectCommand, serializeAws_restXmlPutObjectCommand } from \"../protocols/Aws_restXml\";\nimport { getBucketEndpointPlugin } from \"@aws-sdk/middleware-bucket-endpoint\";\nimport { getSerdePlugin } from \"@aws-sdk/middleware-serde\";\nimport { getSsecPlugin } from \"@aws-sdk/middleware-ssec\";\nimport { Command as $Command } from \"@aws-sdk/smithy-client\";\n/**\n * Adds an object to a bucket. You must have WRITE permissions on a bucket to add an object\n * to it.
\n *\n *\n * Amazon S3 never adds partial objects; if you receive a success response, Amazon S3 added the\n * entire object to the bucket.
\n *\n * Amazon S3 is a distributed system. If it receives multiple write requests for the same object\n * simultaneously, it overwrites all but the last object written. Amazon S3 does not provide object\n * locking; if you need this, make sure to build it into your application layer or use\n * versioning instead.
\n *\n * To ensure that data is not corrupted traversing the network, use the\n * Content-MD5
header. When you use this header, Amazon S3 checks the object\n * against the provided MD5 value and, if they do not match, returns an error. Additionally,\n * you can calculate the MD5 while putting an object to Amazon S3 and compare the returned ETag to\n * the calculated MD5 value.
\n * \n * The Content-MD5
header is required for any request to upload an object\n * with a retention period configured using Amazon S3 Object Lock. For more information about\n * Amazon S3 Object Lock, see Amazon S3 Object Lock Overview\n * in the Amazon Simple Storage Service Developer Guide.
\n * \n *\n *\n * \n * Server-side Encryption\n *
\n * You can optionally request server-side encryption. With server-side encryption, Amazon S3 encrypts your data as it writes it to disks in its data centers and decrypts the data\n * when you access it. You have the option to provide your own encryption key or use AWS\n * managed encryption keys (SSE-S3 or SSE-KMS). For more information, see Using Server-Side\n * Encryption.
\n * If you request server-side encryption using AWS Key Management Service (SSE-KMS), you can enable an S3 Bucket Key at the object-level. For more information, see Amazon S3 Bucket Keys in the Amazon Simple Storage Service Developer Guide.
\n * \n * Access Control List (ACL)-Specific Request\n * Headers\n *
\n * You can use headers to grant ACL- based permissions. By default, all objects are\n * private. Only the owner has full access control. When adding a new object, you can grant\n * permissions to individual AWS accounts or to predefined groups defined by Amazon S3. These\n * permissions are then added to the ACL on the object. For more information, see Access Control List\n * (ACL) Overview and Managing ACLs Using the REST\n * API.
\n *\n * \n * Storage Class Options\n *
\n * By default, Amazon S3 uses the STANDARD Storage Class to store newly created objects. The\n * STANDARD storage class provides high durability and high availability. Depending on\n * performance needs, you can specify a different Storage Class. Amazon S3 on Outposts only uses\n * the OUTPOSTS Storage Class. For more information, see Storage Classes in the Amazon S3\n * Service Developer Guide.
\n *\n *\n * \n * Versioning\n *
\n * If you enable versioning for a bucket, Amazon S3 automatically generates a unique version ID\n * for the object being stored. Amazon S3 returns this ID in the response. When you enable\n * versioning for a bucket, if Amazon S3 receives multiple write requests for the same object\n * simultaneously, it stores all of the objects.
\n * For more information about versioning, see Adding Objects to\n * Versioning Enabled Buckets. For information about returning the versioning state\n * of a bucket, see GetBucketVersioning.
\n *\n *\n * \n * Related Resources\n *
\n * \n */\nvar PutObjectCommand = /** @class */ (function (_super) {\n __extends(PutObjectCommand, _super);\n // Start section: command_properties\n // End section: command_properties\n function PutObjectCommand(input) {\n var _this = \n // Start section: command_constructor\n _super.call(this) || this;\n _this.input = input;\n return _this;\n // End section: command_constructor\n }\n /**\n * @internal\n */\n PutObjectCommand.prototype.resolveMiddleware = function (clientStack, configuration, options) {\n this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));\n this.middlewareStack.use(getSsecPlugin(configuration));\n this.middlewareStack.use(getBucketEndpointPlugin(configuration));\n var stack = clientStack.concat(this.middlewareStack);\n var logger = configuration.logger;\n var clientName = \"S3Client\";\n var commandName = \"PutObjectCommand\";\n var handlerExecutionContext = {\n logger: logger,\n clientName: clientName,\n commandName: commandName,\n inputFilterSensitiveLog: PutObjectRequest.filterSensitiveLog,\n outputFilterSensitiveLog: PutObjectOutput.filterSensitiveLog,\n };\n var requestHandler = configuration.requestHandler;\n return stack.resolve(function (request) {\n return requestHandler.handle(request.request, options || {});\n }, handlerExecutionContext);\n };\n PutObjectCommand.prototype.serialize = function (input, context) {\n return serializeAws_restXmlPutObjectCommand(input, context);\n };\n PutObjectCommand.prototype.deserialize = function (output, context) {\n return deserializeAws_restXmlPutObjectCommand(output, context);\n };\n return PutObjectCommand;\n}($Command));\nexport { PutObjectCommand };\n//# sourceMappingURL=PutObjectCommand.js.map","import { __extends } from \"tslib\";\nimport { CreateMultipartUploadOutput, CreateMultipartUploadRequest } from \"../models/models_0\";\nimport { deserializeAws_restXmlCreateMultipartUploadCommand, serializeAws_restXmlCreateMultipartUploadCommand, } from \"../protocols/Aws_restXml\";\nimport { getBucketEndpointPlugin } from \"@aws-sdk/middleware-bucket-endpoint\";\nimport { getSerdePlugin } from \"@aws-sdk/middleware-serde\";\nimport { getSsecPlugin } from \"@aws-sdk/middleware-ssec\";\nimport { Command as $Command } from \"@aws-sdk/smithy-client\";\n/**\n * This operation initiates a multipart upload and returns an upload ID. This upload ID is\n * used to associate all of the parts in the specific multipart upload. You specify this\n * upload ID in each of your subsequent upload part requests (see UploadPart). You also include this\n * upload ID in the final request to either complete or abort the multipart upload\n * request.
\n *\n * For more information about multipart uploads, see Multipart Upload Overview.
\n *\n * If you have configured a lifecycle rule to abort incomplete multipart uploads, the\n * upload must complete within the number of days specified in the bucket lifecycle\n * configuration. Otherwise, the incomplete multipart upload becomes eligible for an abort\n * operation and Amazon S3 aborts the multipart upload. For more information, see Aborting\n * Incomplete Multipart Uploads Using a Bucket Lifecycle Policy.
\n *\n * For information about the permissions required to use the multipart upload API, see\n * Multipart Upload API and\n * Permissions.
\n *\n * For request signing, multipart upload is just a series of regular requests. You initiate\n * a multipart upload, send one or more requests to upload parts, and then complete the\n * multipart upload process. You sign each request individually. There is nothing special\n * about signing multipart upload requests. For more information about signing, see Authenticating\n * Requests (AWS Signature Version 4).
\n *\n * \n * After you initiate a multipart upload and upload one or more parts, to stop being\n * charged for storing the uploaded parts, you must either complete or abort the multipart\n * upload. Amazon S3 frees up the space used to store the parts and stop charging you for\n * storing them only after you either complete or abort a multipart upload.
\n * \n *\n * You can optionally request server-side encryption. For server-side encryption, Amazon S3\n * encrypts your data as it writes it to disks in its data centers and decrypts it when you\n * access it. You can provide your own encryption key, or use AWS Key Management Service (AWS\n * KMS) customer master keys (CMKs) or Amazon S3-managed encryption keys. If you choose to provide\n * your own encryption key, the request headers you provide in UploadPart and UploadPartCopy requests must match the headers you used in the request to\n * initiate the upload by using CreateMultipartUpload
.
\n * To perform a multipart upload with encryption using an AWS KMS CMK, the requester must\n * have permission to the kms:Encrypt
, kms:Decrypt
,\n * kms:ReEncrypt*
, kms:GenerateDataKey*
, and\n * kms:DescribeKey
actions on the key. These permissions are required because\n * Amazon S3 must decrypt and read data from the encrypted file parts before it completes the\n * multipart upload.
\n *\n * If your AWS Identity and Access Management (IAM) user or role is in the same AWS account\n * as the AWS KMS CMK, then you must have these permissions on the key policy. If your IAM\n * user or role belongs to a different account than the key, then you must have the\n * permissions on both the key policy and your IAM user or role.
\n *\n *\n * For more information, see Protecting\n * Data Using Server-Side Encryption.
\n *\n * \n * - Access Permissions
\n * - \n *
When copying an object, you can optionally specify the accounts or groups that\n * should be granted specific permissions on the new object. There are two ways to\n * grant the permissions using the request headers:
\n * \n * - \n *
Specify a canned ACL with the x-amz-acl
request header. For\n * more information, see Canned ACL.
\n * \n * - \n *
Specify access permissions explicitly with the\n * x-amz-grant-read
, x-amz-grant-read-acp
,\n * x-amz-grant-write-acp
, and\n * x-amz-grant-full-control
headers. These parameters map to\n * the set of permissions that Amazon S3 supports in an ACL. For more information,\n * see Access Control List (ACL)\n * Overview.
\n * \n *
\n * You can use either a canned ACL or specify access permissions explicitly. You\n * cannot do both.
\n * \n * - Server-Side- Encryption-Specific Request Headers
\n * - \n *
You can optionally tell Amazon S3 to encrypt data at rest using server-side\n * encryption. Server-side encryption is for data encryption at rest. Amazon S3 encrypts\n * your data as it writes it to disks in its data centers and decrypts it when you\n * access it. The option you use depends on whether you want to use AWS managed\n * encryption keys or provide your own encryption key.
\n * \n * - \n *
Use encryption keys managed by Amazon S3 or customer master keys (CMKs) stored\n * in AWS Key Management Service (AWS KMS) – If you want AWS to manage the keys\n * used to encrypt data, specify the following headers in the request.
\n * \n * - \n *
x-amz-server-side-encryption
\n * \n * - \n *
x-amz-server-side-encryption-aws-kms-key-id
\n * \n * - \n *
x-amz-server-side-encryption-context
\n * \n *
\n * \n * If you specify x-amz-server-side-encryption:aws:kms
, but\n * don't provide x-amz-server-side-encryption-aws-kms-key-id
,\n * Amazon S3 uses the AWS managed CMK in AWS KMS to protect the data.
\n * \n * \n * All GET and PUT requests for an object protected by AWS KMS fail if\n * you don't make them with SSL or by using SigV4.
\n * \n * For more information about server-side encryption with CMKs stored in AWS\n * KMS (SSE-KMS), see Protecting Data Using Server-Side Encryption with CMKs stored in AWS\n * KMS.
\n * \n * - \n *
Use customer-provided encryption keys – If you want to manage your own\n * encryption keys, provide all the following headers in the request.
\n * \n * - \n *
x-amz-server-side-encryption-customer-algorithm
\n * \n * - \n *
x-amz-server-side-encryption-customer-key
\n * \n * - \n *
x-amz-server-side-encryption-customer-key-MD5
\n * \n *
\n * For more information about server-side encryption with CMKs stored in AWS\n * KMS (SSE-KMS), see Protecting Data Using Server-Side Encryption with CMKs stored in AWS\n * KMS.
\n * \n *
\n * \n * - Access-Control-List (ACL)-Specific Request Headers
\n * - \n *
You also can use the following access control–related headers with this\n * operation. By default, all objects are private. Only the owner has full access\n * control. When adding a new object, you can grant permissions to individual AWS\n * accounts or to predefined groups defined by Amazon S3. These permissions are then added\n * to the access control list (ACL) on the object. For more information, see Using ACLs. With this\n * operation, you can grant access permissions using one of the following two\n * methods:
\n * \n * - \n *
Specify a canned ACL (x-amz-acl
) — Amazon S3 supports a set of\n * predefined ACLs, known as canned ACLs. Each canned ACL\n * has a predefined set of grantees and permissions. For more information, see\n * Canned\n * ACL.
\n * \n * - \n *
Specify access permissions explicitly — To explicitly grant access\n * permissions to specific AWS accounts or groups, use the following headers.\n * Each header maps to specific permissions that Amazon S3 supports in an ACL. For\n * more information, see Access\n * Control List (ACL) Overview. In the header, you specify a list of\n * grantees who get the specific permission. To grant permissions explicitly,\n * use:
\n * \n * - \n *
x-amz-grant-read
\n * \n * - \n *
x-amz-grant-write
\n * \n * - \n *
x-amz-grant-read-acp
\n * \n * - \n *
x-amz-grant-write-acp
\n * \n * - \n *
x-amz-grant-full-control
\n * \n *
\n * You specify each grantee as a type=value pair, where the type is one of\n * the following:
\n * \n * - \n *
\n * id
– if the value specified is the canonical user ID\n * of an AWS account
\n * \n * - \n *
\n * uri
– if you are granting permissions to a predefined\n * group
\n * \n * - \n *
\n * emailAddress
– if the value specified is the email\n * address of an AWS account
\n * \n * Using email addresses to specify a grantee is only supported in the following AWS Regions:
\n * \n * For a list of all the Amazon S3 supported Regions and endpoints, see Regions and Endpoints in the AWS General Reference.
\n * \n * \n *
\n * For example, the following x-amz-grant-read
header grants the AWS accounts identified by account IDs permissions to read object data and its metadata:
\n * \n * x-amz-grant-read: id=\"11112222333\", id=\"444455556666\"
\n *
\n * \n *
\n *\n * \n *
\n *\n * The following operations are related to CreateMultipartUpload
:
\n * \n */\nvar CreateMultipartUploadCommand = /** @class */ (function (_super) {\n __extends(CreateMultipartUploadCommand, _super);\n // Start section: command_properties\n // End section: command_properties\n function CreateMultipartUploadCommand(input) {\n var _this = \n // Start section: command_constructor\n _super.call(this) || this;\n _this.input = input;\n return _this;\n // End section: command_constructor\n }\n /**\n * @internal\n */\n CreateMultipartUploadCommand.prototype.resolveMiddleware = function (clientStack, configuration, options) {\n this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));\n this.middlewareStack.use(getSsecPlugin(configuration));\n this.middlewareStack.use(getBucketEndpointPlugin(configuration));\n var stack = clientStack.concat(this.middlewareStack);\n var logger = configuration.logger;\n var clientName = \"S3Client\";\n var commandName = \"CreateMultipartUploadCommand\";\n var handlerExecutionContext = {\n logger: logger,\n clientName: clientName,\n commandName: commandName,\n inputFilterSensitiveLog: CreateMultipartUploadRequest.filterSensitiveLog,\n outputFilterSensitiveLog: CreateMultipartUploadOutput.filterSensitiveLog,\n };\n var requestHandler = configuration.requestHandler;\n return stack.resolve(function (request) {\n return requestHandler.handle(request.request, options || {});\n }, handlerExecutionContext);\n };\n CreateMultipartUploadCommand.prototype.serialize = function (input, context) {\n return serializeAws_restXmlCreateMultipartUploadCommand(input, context);\n };\n CreateMultipartUploadCommand.prototype.deserialize = function (output, context) {\n return deserializeAws_restXmlCreateMultipartUploadCommand(output, context);\n };\n return CreateMultipartUploadCommand;\n}($Command));\nexport { CreateMultipartUploadCommand };\n//# sourceMappingURL=CreateMultipartUploadCommand.js.map","import { __extends } from \"tslib\";\nimport { UploadPartOutput, UploadPartRequest } from \"../models/models_1\";\nimport { deserializeAws_restXmlUploadPartCommand, serializeAws_restXmlUploadPartCommand, } from \"../protocols/Aws_restXml\";\nimport { getBucketEndpointPlugin } from \"@aws-sdk/middleware-bucket-endpoint\";\nimport { getSerdePlugin } from \"@aws-sdk/middleware-serde\";\nimport { getSsecPlugin } from \"@aws-sdk/middleware-ssec\";\nimport { Command as $Command } from \"@aws-sdk/smithy-client\";\n/**\n * Uploads a part in a multipart upload.
\n * \n * In this operation, you provide part data in your request. However, you have an option\n * to specify your existing Amazon S3 object as a data source for the part you are uploading. To\n * upload a part from an existing object, you use the UploadPartCopy operation.\n *
\n * \n *\n * You must initiate a multipart upload (see CreateMultipartUpload)\n * before you can upload any part. In response to your initiate request, Amazon S3 returns an\n * upload ID, a unique identifier, that you must include in your upload part request.
\n * Part numbers can be any number from 1 to 10,000, inclusive. A part number uniquely\n * identifies a part and also defines its position within the object being created. If you\n * upload a new part using the same part number that was used with a previous part, the\n * previously uploaded part is overwritten. Each part must be at least 5 MB in size, except\n * the last part. There is no size limit on the last part of your multipart upload.
\n * To ensure that data is not corrupted when traversing the network, specify the\n * Content-MD5
header in the upload part request. Amazon S3 checks the part data\n * against the provided MD5 value. If they do not match, Amazon S3 returns an error.
\n *\n * If the upload request is signed with Signature Version 4, then AWS S3 uses the\n * x-amz-content-sha256
header as a checksum instead of\n * Content-MD5
. For more information see Authenticating Requests: Using the Authorization Header (AWS Signature Version\n * 4).
\n *\n *\n *\n * \n * Note: After you initiate multipart upload and upload\n * one or more parts, you must either complete or abort multipart upload in order to stop\n * getting charged for storage of the uploaded parts. Only after you either complete or abort\n * multipart upload, Amazon S3 frees up the parts storage and stops charging you for the parts\n * storage.
\n *\n * For more information on multipart uploads, go to Multipart Upload Overview in the\n * Amazon Simple Storage Service Developer Guide .
\n * For information on the permissions required to use the multipart upload API, go to\n * Multipart Upload API and\n * Permissions in the Amazon Simple Storage Service Developer Guide.
\n *\n * You can optionally request server-side encryption where Amazon S3 encrypts your data as it\n * writes it to disks in its data centers and decrypts it for you when you access it. You have\n * the option of providing your own encryption key, or you can use the AWS managed encryption\n * keys. If you choose to provide your own encryption key, the request headers you provide in\n * the request must match the headers you used in the request to initiate the upload by using\n * CreateMultipartUpload. For more information, go to Using Server-Side Encryption in\n * the Amazon Simple Storage Service Developer Guide.
\n *\n * Server-side encryption is supported by the S3 Multipart Upload actions. Unless you are\n * using a customer-provided encryption key, you don't need to specify the encryption\n * parameters in each UploadPart request. Instead, you only need to specify the server-side\n * encryption parameters in the initial Initiate Multipart request. For more information, see\n * CreateMultipartUpload.
\n *\n * If you requested server-side encryption using a customer-provided encryption key in your\n * initiate multipart upload request, you must provide identical encryption information in\n * each part upload using the following headers.
\n *\n *\n * \n * - \n *
x-amz-server-side-encryption-customer-algorithm
\n * \n * - \n *
x-amz-server-side-encryption-customer-key
\n * \n * - \n *
x-amz-server-side-encryption-customer-key-MD5
\n * \n *
\n *\n * \n * Special Errors\n *
\n * \n * - \n *
\n * - \n *
\n * Code: NoSuchUpload\n *
\n * \n * - \n *
\n * Cause: The specified multipart upload does not exist. The upload\n * ID might be invalid, or the multipart upload might have been aborted or\n * completed.\n *
\n * \n * - \n *
\n * HTTP Status Code: 404 Not Found \n *
\n * \n * - \n *
\n * SOAP Fault Code Prefix: Client\n *
\n * \n *
\n * \n *
\n *\n *\n *\n *\n *\n *\n * \n * Related Resources\n *
\n * \n */\nvar UploadPartCommand = /** @class */ (function (_super) {\n __extends(UploadPartCommand, _super);\n // Start section: command_properties\n // End section: command_properties\n function UploadPartCommand(input) {\n var _this = \n // Start section: command_constructor\n _super.call(this) || this;\n _this.input = input;\n return _this;\n // End section: command_constructor\n }\n /**\n * @internal\n */\n UploadPartCommand.prototype.resolveMiddleware = function (clientStack, configuration, options) {\n this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));\n this.middlewareStack.use(getSsecPlugin(configuration));\n this.middlewareStack.use(getBucketEndpointPlugin(configuration));\n var stack = clientStack.concat(this.middlewareStack);\n var logger = configuration.logger;\n var clientName = \"S3Client\";\n var commandName = \"UploadPartCommand\";\n var handlerExecutionContext = {\n logger: logger,\n clientName: clientName,\n commandName: commandName,\n inputFilterSensitiveLog: UploadPartRequest.filterSensitiveLog,\n outputFilterSensitiveLog: UploadPartOutput.filterSensitiveLog,\n };\n var requestHandler = configuration.requestHandler;\n return stack.resolve(function (request) {\n return requestHandler.handle(request.request, options || {});\n }, handlerExecutionContext);\n };\n UploadPartCommand.prototype.serialize = function (input, context) {\n return serializeAws_restXmlUploadPartCommand(input, context);\n };\n UploadPartCommand.prototype.deserialize = function (output, context) {\n return deserializeAws_restXmlUploadPartCommand(output, context);\n };\n return UploadPartCommand;\n}($Command));\nexport { UploadPartCommand };\n//# sourceMappingURL=UploadPartCommand.js.map","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n};\nimport { UploadPartCommand, CompleteMultipartUploadCommand, AbortMultipartUploadCommand, ListPartsCommand, CreateMultipartUploadCommand, ListObjectsV2Command, } from '@aws-sdk/client-s3';\nimport axios from 'axios';\nimport { Logger } from '@aws-amplify/core';\nimport { byteLength, isFile } from '../common/StorageUtils';\nimport { AWSS3ProviderUploadErrorStrings } from '../common/StorageErrorStrings';\nimport { SET_CONTENT_LENGTH_HEADER, UPLOADS_STORAGE_KEY, } from '../common/StorageConstants';\nvar logger = new Logger('AWSS3UploadTask');\nexport var AWSS3UploadTaskState;\n(function (AWSS3UploadTaskState) {\n AWSS3UploadTaskState[AWSS3UploadTaskState[\"INIT\"] = 0] = \"INIT\";\n AWSS3UploadTaskState[AWSS3UploadTaskState[\"IN_PROGRESS\"] = 1] = \"IN_PROGRESS\";\n AWSS3UploadTaskState[AWSS3UploadTaskState[\"PAUSED\"] = 2] = \"PAUSED\";\n AWSS3UploadTaskState[AWSS3UploadTaskState[\"CANCELLED\"] = 3] = \"CANCELLED\";\n AWSS3UploadTaskState[AWSS3UploadTaskState[\"COMPLETED\"] = 4] = \"COMPLETED\";\n})(AWSS3UploadTaskState || (AWSS3UploadTaskState = {}));\nexport var TaskEvents;\n(function (TaskEvents) {\n TaskEvents[\"CANCEL\"] = \"cancel\";\n TaskEvents[\"UPLOAD_COMPLETE\"] = \"uploadComplete\";\n TaskEvents[\"UPLOAD_PROGRESS\"] = \"uploadPartProgress\";\n TaskEvents[\"ERROR\"] = \"error\";\n})(TaskEvents || (TaskEvents = {}));\n// maximum number of parts per upload request according the S3 spec,\n// see: https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html\nvar MAX_PARTS = 10000;\n// 5MB in bytes\nvar PART_SIZE = 5 * 1024 * 1024;\nvar DEFAULT_QUEUE_SIZE = 4;\nfunction comparePartNumber(a, b) {\n return a.PartNumber - b.PartNumber;\n}\nvar AWSS3UploadTask = /** @class */ (function () {\n function AWSS3UploadTask(_a) {\n var s3Client = _a.s3Client, file = _a.file, emitter = _a.emitter, storage = _a.storage, params = _a.params, level = _a.level, prefixPromise = _a.prefixPromise;\n this.partSize = PART_SIZE;\n this.queueSize = DEFAULT_QUEUE_SIZE;\n this.inProgress = [];\n this.completedParts = [];\n this.queued = [];\n this.bytesUploaded = 0;\n this.totalBytes = 0;\n this.state = AWSS3UploadTaskState.INIT;\n this.prefixPromise = prefixPromise;\n this.s3client = s3Client;\n this.s3client.middlewareStack.remove(SET_CONTENT_LENGTH_HEADER);\n this.storage = storage;\n this.storageSync = Promise.resolve();\n if (typeof this.storage['sync'] === 'function') {\n this.storageSync = this.storage['sync']();\n }\n this.params = params;\n this.file = file;\n this.totalBytes = this.file.size;\n this.bytesUploaded = 0;\n this.emitter = emitter;\n this.queued = [];\n this.fileId = this._getFileId(level);\n this._validateParams();\n // event emitter will re-throw an error if an event emits an error unless there's a listener, attaching a no-op\n // function to it unless user adds their own onError callback\n this.emitter.on(TaskEvents.ERROR, function () { });\n }\n Object.defineProperty(AWSS3UploadTask.prototype, \"percent\", {\n get: function () {\n return (this.bytesUploaded / this.totalBytes) * 100;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(AWSS3UploadTask.prototype, \"isInProgress\", {\n get: function () {\n return this.state === AWSS3UploadTaskState.IN_PROGRESS;\n },\n enumerable: true,\n configurable: true\n });\n AWSS3UploadTask.prototype._listSingleFile = function (_a) {\n var key = _a.key, bucket = _a.bucket;\n return __awaiter(this, void 0, void 0, function () {\n var listObjectRes, _b, Contents, prefix, obj;\n return __generator(this, function (_c) {\n switch (_c.label) {\n case 0: return [4 /*yield*/, this.s3client.send(new ListObjectsV2Command({\n Bucket: bucket,\n Prefix: key,\n }))];\n case 1:\n listObjectRes = _c.sent();\n _b = listObjectRes.Contents, Contents = _b === void 0 ? [] : _b;\n return [4 /*yield*/, this.prefixPromise];\n case 2:\n prefix = _c.sent();\n obj = Contents.find(function (o) { return o.Key === \"\" + prefix + key; });\n return [2 /*return*/, obj];\n }\n });\n });\n };\n AWSS3UploadTask.prototype._getFileId = function (level) {\n // We should check if it's a File first because File is also instance of a Blob\n if (isFile(this.file)) {\n return [\n this.file.name,\n this.file.lastModified,\n this.file.size,\n this.file.type,\n this.params.Bucket,\n level,\n this.params.Key,\n ].join('-');\n }\n else {\n return [\n this.file.size,\n this.file.type,\n this.params.Bucket,\n level,\n this.params.Key,\n ].join('-');\n }\n };\n AWSS3UploadTask.prototype._findCachedUploadParts = function () {\n return __awaiter(this, void 0, void 0, function () {\n var uploadRequests, cachedUploadFileData, listPartsOutput;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, this._listCachedUploadTasks()];\n case 1:\n uploadRequests = _a.sent();\n if (Object.keys(uploadRequests).length === 0 ||\n !Object.prototype.hasOwnProperty.call(uploadRequests, this.fileId)) {\n return [2 /*return*/, { parts: [], uploadId: null }];\n }\n cachedUploadFileData = uploadRequests[this.fileId];\n cachedUploadFileData.lastTouched = Date.now();\n this.storage.setItem(UPLOADS_STORAGE_KEY, JSON.stringify(uploadRequests));\n return [4 /*yield*/, this.s3client.send(new ListPartsCommand({\n Bucket: this.params.Bucket,\n Key: this.params.Key,\n UploadId: cachedUploadFileData.uploadId,\n }))];\n case 2:\n listPartsOutput = _a.sent();\n return [2 /*return*/, {\n parts: listPartsOutput.Parts || [],\n uploadId: cachedUploadFileData.uploadId,\n }];\n }\n });\n });\n };\n AWSS3UploadTask.prototype._emitEvent = function (event, payload) {\n this.emitter.emit(event, payload);\n };\n AWSS3UploadTask.prototype._validateParams = function () {\n if (this.file.size / this.partSize > MAX_PARTS) {\n throw new Error(\"Too many parts. Number of parts is \" + this.file.size /\n this.partSize + \", maximum is \" + MAX_PARTS + \".\");\n }\n };\n AWSS3UploadTask.prototype._listCachedUploadTasks = function () {\n return __awaiter(this, void 0, void 0, function () {\n var tasks;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, this.storageSync];\n case 1:\n _a.sent();\n tasks = this.storage.getItem(UPLOADS_STORAGE_KEY) || '{}';\n return [2 /*return*/, JSON.parse(tasks)];\n }\n });\n });\n };\n AWSS3UploadTask.prototype._cache = function (fileMetadata) {\n return __awaiter(this, void 0, void 0, function () {\n var uploadRequests;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, this._listCachedUploadTasks()];\n case 1:\n uploadRequests = _a.sent();\n uploadRequests[this.fileId] = fileMetadata;\n this.storage.setItem(UPLOADS_STORAGE_KEY, JSON.stringify(uploadRequests));\n return [2 /*return*/];\n }\n });\n });\n };\n AWSS3UploadTask.prototype._isCached = function () {\n return __awaiter(this, void 0, void 0, function () {\n var _a, _b;\n return __generator(this, function (_c) {\n switch (_c.label) {\n case 0:\n _b = (_a = Object.prototype.hasOwnProperty).call;\n return [4 /*yield*/, this._listCachedUploadTasks()];\n case 1: return [2 /*return*/, _b.apply(_a, [_c.sent(),\n this.fileId])];\n }\n });\n });\n };\n AWSS3UploadTask.prototype._removeFromCache = function () {\n return __awaiter(this, void 0, void 0, function () {\n var uploadRequests;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, this._listCachedUploadTasks()];\n case 1:\n uploadRequests = _a.sent();\n delete uploadRequests[this.fileId];\n this.storage.setItem(UPLOADS_STORAGE_KEY, JSON.stringify(uploadRequests));\n return [2 /*return*/];\n }\n });\n });\n };\n AWSS3UploadTask.prototype._onPartUploadCompletion = function (_a) {\n var eTag = _a.eTag, partNumber = _a.partNumber, chunk = _a.chunk;\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_b) {\n this.completedParts.push({\n ETag: eTag,\n PartNumber: partNumber,\n });\n this.bytesUploaded += byteLength(chunk);\n this._emitEvent(TaskEvents.UPLOAD_PROGRESS, {\n loaded: this.bytesUploaded,\n total: this.totalBytes,\n });\n // Remove the completed item from the inProgress array\n this.inProgress = this.inProgress.filter(function (job) { return job.uploadPartInput.PartNumber !== partNumber; });\n if (this.queued.length && this.state !== AWSS3UploadTaskState.PAUSED)\n this._startNextPart();\n if (this._isDone())\n this._completeUpload();\n return [2 /*return*/];\n });\n });\n };\n AWSS3UploadTask.prototype._completeUpload = function () {\n return __awaiter(this, void 0, void 0, function () {\n var err_1;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 2, , 3]);\n return [4 /*yield*/, this.s3client.send(new CompleteMultipartUploadCommand({\n Bucket: this.params.Bucket,\n Key: this.params.Key,\n UploadId: this.uploadId,\n MultipartUpload: {\n // Parts are not always completed in order, we need to manually sort them\n Parts: this.completedParts.sort(comparePartNumber),\n },\n }))];\n case 1:\n _a.sent();\n this._verifyFileSize();\n this._emitEvent(TaskEvents.UPLOAD_COMPLETE, {\n key: this.params.Bucket + \"/\" + this.params.Key,\n });\n this._removeFromCache();\n this.state = AWSS3UploadTaskState.COMPLETED;\n return [3 /*break*/, 3];\n case 2:\n err_1 = _a.sent();\n logger.error('error completing upload', err_1);\n this._emitEvent(TaskEvents.ERROR, err_1);\n return [3 /*break*/, 3];\n case 3: return [2 /*return*/];\n }\n });\n });\n };\n AWSS3UploadTask.prototype._makeUploadPartRequest = function (input, cancelTokenSource) {\n return __awaiter(this, void 0, void 0, function () {\n var res, err_2;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 3, , 4]);\n return [4 /*yield*/, this.s3client.send(new UploadPartCommand(input), {\n cancelTokenSource: cancelTokenSource,\n })];\n case 1:\n res = _a.sent();\n return [4 /*yield*/, this._onPartUploadCompletion({\n eTag: res.ETag,\n partNumber: input.PartNumber,\n chunk: input.Body,\n })];\n case 2:\n _a.sent();\n return [3 /*break*/, 4];\n case 3:\n err_2 = _a.sent();\n if (this.state === AWSS3UploadTaskState.PAUSED) {\n logger.log('upload paused');\n }\n else if (this.state === AWSS3UploadTaskState.CANCELLED) {\n logger.log('upload aborted');\n }\n else {\n logger.error('error starting next part of upload: ', err_2);\n }\n // axios' cancel will also throw an error, however we don't need to emit an event in that case as it's an\n // expected behavior\n if (!axios.isCancel(err_2) &&\n err_2.message !== AWSS3ProviderUploadErrorStrings.UPLOAD_PAUSED_MESSAGE) {\n this._emitEvent(TaskEvents.ERROR, err_2);\n this.pause();\n }\n return [3 /*break*/, 4];\n case 4: return [2 /*return*/];\n }\n });\n });\n };\n AWSS3UploadTask.prototype._startNextPart = function () {\n if (this.queued.length > 0 && this.state !== AWSS3UploadTaskState.PAUSED) {\n var cancelTokenSource = axios.CancelToken.source();\n var nextPart = this.queued.shift();\n this.inProgress.push({\n uploadPartInput: nextPart,\n s3Request: this._makeUploadPartRequest(nextPart, cancelTokenSource),\n cancel: cancelTokenSource.cancel,\n });\n }\n };\n /**\n * Verify on S3 side that the file size matches the one on the client side.\n *\n * @async\n * @throws throws an error if the file size does not match between local copy of the file and the file on s3.\n */\n AWSS3UploadTask.prototype._verifyFileSize = function () {\n return __awaiter(this, void 0, void 0, function () {\n var obj, valid;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, this._listSingleFile({\n key: this.params.Key,\n bucket: this.params.Bucket,\n })];\n case 1:\n obj = _a.sent();\n valid = Boolean(obj && obj.Size === this.file.size);\n if (!valid) {\n throw new Error('File size does not match between local file and file on s3');\n }\n return [2 /*return*/, valid];\n }\n });\n });\n };\n AWSS3UploadTask.prototype._isDone = function () {\n return (!this.queued.length &&\n !this.inProgress.length &&\n this.bytesUploaded === this.totalBytes);\n };\n AWSS3UploadTask.prototype._createParts = function () {\n var size = this.file.size;\n var parts = [];\n for (var bodyStart = 0; bodyStart < size;) {\n var bodyEnd = Math.min(bodyStart + this.partSize, size);\n parts.push({\n Body: this.file.slice(bodyStart, bodyEnd),\n Key: this.params.Key,\n Bucket: this.params.Bucket,\n PartNumber: parts.length + 1,\n UploadId: this.uploadId,\n });\n bodyStart += this.partSize;\n }\n return parts;\n };\n AWSS3UploadTask.prototype._initCachedUploadParts = function (cachedParts) {\n this.bytesUploaded += cachedParts.reduce(function (acc, part) { return acc + part.Size; }, 0);\n // Find the set of part numbers that have already been uploaded\n var uploadedPartNumSet = new Set(cachedParts.map(function (part) { return part.PartNumber; }));\n this.queued = this.queued.filter(function (part) { return !uploadedPartNumSet.has(part.PartNumber); });\n this.completedParts = cachedParts.map(function (part) { return ({\n PartNumber: part.PartNumber,\n ETag: part.ETag,\n }); });\n this._emitEvent(TaskEvents.UPLOAD_PROGRESS, {\n loaded: this.bytesUploaded,\n total: this.totalBytes,\n });\n };\n AWSS3UploadTask.prototype._initMultipartUpload = function () {\n return __awaiter(this, void 0, void 0, function () {\n var res;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, this.s3client.send(new CreateMultipartUploadCommand(this.params))];\n case 1:\n res = _a.sent();\n this._cache({\n uploadId: res.UploadId,\n lastTouched: Date.now(),\n bucket: this.params.Bucket,\n key: this.params.Key,\n fileName: this.file instanceof File ? this.file.name : '',\n });\n return [2 /*return*/, res.UploadId];\n }\n });\n });\n };\n AWSS3UploadTask.prototype._initializeUploadTask = function () {\n return __awaiter(this, void 0, void 0, function () {\n var _a, parts, uploadId, uploadId, err_3;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n this.state = AWSS3UploadTaskState.IN_PROGRESS;\n _b.label = 1;\n case 1:\n _b.trys.push([1, 7, , 8]);\n return [4 /*yield*/, this._isCached()];\n case 2:\n if (!_b.sent()) return [3 /*break*/, 4];\n return [4 /*yield*/, this._findCachedUploadParts()];\n case 3:\n _a = _b.sent(), parts = _a.parts, uploadId = _a.uploadId;\n this.uploadId = uploadId;\n this.queued = this._createParts();\n this._initCachedUploadParts(parts);\n this._startUpload();\n return [3 /*break*/, 6];\n case 4:\n if (!!this.uploadId) return [3 /*break*/, 6];\n return [4 /*yield*/, this._initMultipartUpload()];\n case 5:\n uploadId = _b.sent();\n this.uploadId = uploadId;\n this.queued = this._createParts();\n this._startUpload();\n _b.label = 6;\n case 6: return [3 /*break*/, 8];\n case 7:\n err_3 = _b.sent();\n if (!axios.isCancel(err_3)) {\n logger.error('Error initializing the upload task', err_3);\n }\n return [3 /*break*/, 8];\n case 8: return [2 /*return*/];\n }\n });\n });\n };\n AWSS3UploadTask.prototype.resume = function () {\n if (this.state === AWSS3UploadTaskState.CANCELLED) {\n logger.warn('This task has already been cancelled');\n }\n else if (this.state === AWSS3UploadTaskState.COMPLETED) {\n logger.warn('This task has already been completed');\n }\n else if (this.state === AWSS3UploadTaskState.IN_PROGRESS) {\n logger.warn('Upload task already in progress');\n // first time running resume, find any cached parts on s3 or start a new multipart upload request before\n // starting the upload\n }\n else if (!this.uploadId) {\n this._initializeUploadTask();\n }\n else {\n this._startUpload();\n }\n };\n AWSS3UploadTask.prototype._startUpload = function () {\n this.state = AWSS3UploadTaskState.IN_PROGRESS;\n for (var i = 0; i < this.queueSize; i++) {\n this._startNextPart();\n }\n };\n AWSS3UploadTask.prototype._cancel = function () {\n return __awaiter(this, void 0, void 0, function () {\n var err_4;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!(this.state === AWSS3UploadTaskState.CANCELLED)) return [3 /*break*/, 1];\n logger.warn('This task has already been cancelled');\n return [2 /*return*/, false];\n case 1:\n if (!(this.state === AWSS3UploadTaskState.COMPLETED)) return [3 /*break*/, 2];\n logger.warn('This task has already been completed');\n return [2 /*return*/, false];\n case 2:\n this.pause();\n this.queued = [];\n this.completedParts = [];\n this.bytesUploaded = 0;\n this.state = AWSS3UploadTaskState.CANCELLED;\n _a.label = 3;\n case 3:\n _a.trys.push([3, 6, , 7]);\n return [4 /*yield*/, this.s3client.send(new AbortMultipartUploadCommand({\n Bucket: this.params.Bucket,\n Key: this.params.Key,\n UploadId: this.uploadId,\n }))];\n case 4:\n _a.sent();\n return [4 /*yield*/, this._removeFromCache()];\n case 5:\n _a.sent();\n return [2 /*return*/, true];\n case 6:\n err_4 = _a.sent();\n logger.error('Error cancelling upload task', err_4);\n return [2 /*return*/, false];\n case 7: return [2 /*return*/];\n }\n });\n });\n };\n /**\n * pause this particular upload task\n **/\n AWSS3UploadTask.prototype.pause = function () {\n var _a;\n if (this.state === AWSS3UploadTaskState.CANCELLED) {\n logger.warn('This task has already been cancelled');\n }\n else if (this.state === AWSS3UploadTaskState.COMPLETED) {\n logger.warn('This task has already been completed');\n }\n else if (this.state === AWSS3UploadTaskState.PAUSED) {\n logger.warn('This task is already paused');\n }\n this.state = AWSS3UploadTaskState.PAUSED;\n // Use axios cancel token to abort the part request immediately\n // Add the inProgress parts back to pending\n var removedInProgressReq = this.inProgress.splice(0, this.inProgress.length);\n removedInProgressReq.forEach(function (req) {\n req.cancel(AWSS3ProviderUploadErrorStrings.UPLOAD_PAUSED_MESSAGE);\n });\n // Put all removed in progress parts back into the queue\n (_a = this.queued).unshift.apply(_a, __spread(removedInProgressReq.map(function (req) { return req.uploadPartInput; })));\n };\n return AWSS3UploadTask;\n}());\nexport { AWSS3UploadTask };\n//# sourceMappingURL=AWSS3UploadTask.js.map","import { __extends } from \"tslib\";\nimport { CompleteMultipartUploadOutput, CompleteMultipartUploadRequest } from \"../models/models_0\";\nimport { deserializeAws_restXmlCompleteMultipartUploadCommand, serializeAws_restXmlCompleteMultipartUploadCommand, } from \"../protocols/Aws_restXml\";\nimport { getBucketEndpointPlugin } from \"@aws-sdk/middleware-bucket-endpoint\";\nimport { getThrow200ExceptionsPlugin } from \"@aws-sdk/middleware-sdk-s3\";\nimport { getSerdePlugin } from \"@aws-sdk/middleware-serde\";\nimport { Command as $Command } from \"@aws-sdk/smithy-client\";\n/**\n * Completes a multipart upload by assembling previously uploaded parts.
\n * You first initiate the multipart upload and then upload all parts using the UploadPart\n * operation. After successfully uploading all relevant parts of an upload, you call this\n * operation to complete the upload. Upon receiving this request, Amazon S3 concatenates all\n * the parts in ascending order by part number to create a new object. In the Complete\n * Multipart Upload request, you must provide the parts list. You must ensure that the parts\n * list is complete. This operation concatenates the parts that you provide in the list. For\n * each part in the list, you must provide the part number and the ETag
value,\n * returned after that part was uploaded.
\n * Processing of a Complete Multipart Upload request could take several minutes to\n * complete. After Amazon S3 begins processing the request, it sends an HTTP response header that\n * specifies a 200 OK response. While processing is in progress, Amazon S3 periodically sends white\n * space characters to keep the connection from timing out. Because a request could fail after\n * the initial 200 OK response has been sent, it is important that you check the response body\n * to determine whether the request succeeded.
\n * Note that if CompleteMultipartUpload
fails, applications should be prepared\n * to retry the failed requests. For more information, see Amazon S3 Error Best Practices.
\n * For more information about multipart uploads, see Uploading Objects Using Multipart\n * Upload.
\n * For information about permissions required to use the multipart upload API, see Multipart Upload API and\n * Permissions.
\n *\n *\n * \n * CompleteMultipartUpload
has the following special errors:
\n * \n * - \n *
Error code: EntityTooSmall
\n *
\n * \n * \n * - \n *
Error code: InvalidPart
\n *
\n * \n * \n * - \n *
Error code: InvalidPartOrder
\n *
\n * \n * \n * - \n *
Error code: NoSuchUpload
\n *
\n * \n * \n *
\n *\n * The following operations are related to CompleteMultipartUpload
:
\n * \n */\nvar CompleteMultipartUploadCommand = /** @class */ (function (_super) {\n __extends(CompleteMultipartUploadCommand, _super);\n // Start section: command_properties\n // End section: command_properties\n function CompleteMultipartUploadCommand(input) {\n var _this = \n // Start section: command_constructor\n _super.call(this) || this;\n _this.input = input;\n return _this;\n // End section: command_constructor\n }\n /**\n * @internal\n */\n CompleteMultipartUploadCommand.prototype.resolveMiddleware = function (clientStack, configuration, options) {\n this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));\n this.middlewareStack.use(getThrow200ExceptionsPlugin(configuration));\n this.middlewareStack.use(getBucketEndpointPlugin(configuration));\n var stack = clientStack.concat(this.middlewareStack);\n var logger = configuration.logger;\n var clientName = \"S3Client\";\n var commandName = \"CompleteMultipartUploadCommand\";\n var handlerExecutionContext = {\n logger: logger,\n clientName: clientName,\n commandName: commandName,\n inputFilterSensitiveLog: CompleteMultipartUploadRequest.filterSensitiveLog,\n outputFilterSensitiveLog: CompleteMultipartUploadOutput.filterSensitiveLog,\n };\n var requestHandler = configuration.requestHandler;\n return stack.resolve(function (request) {\n return requestHandler.handle(request.request, options || {});\n }, handlerExecutionContext);\n };\n CompleteMultipartUploadCommand.prototype.serialize = function (input, context) {\n return serializeAws_restXmlCompleteMultipartUploadCommand(input, context);\n };\n CompleteMultipartUploadCommand.prototype.deserialize = function (output, context) {\n return deserializeAws_restXmlCompleteMultipartUploadCommand(output, context);\n };\n return CompleteMultipartUploadCommand;\n}($Command));\nexport { CompleteMultipartUploadCommand };\n//# sourceMappingURL=CompleteMultipartUploadCommand.js.map","import { __extends } from \"tslib\";\nimport { AbortMultipartUploadOutput, AbortMultipartUploadRequest } from \"../models/models_0\";\nimport { deserializeAws_restXmlAbortMultipartUploadCommand, serializeAws_restXmlAbortMultipartUploadCommand, } from \"../protocols/Aws_restXml\";\nimport { getBucketEndpointPlugin } from \"@aws-sdk/middleware-bucket-endpoint\";\nimport { getSerdePlugin } from \"@aws-sdk/middleware-serde\";\nimport { Command as $Command } from \"@aws-sdk/smithy-client\";\n/**\n * This operation aborts a multipart upload. After a multipart upload is aborted, no\n * additional parts can be uploaded using that upload ID. The storage consumed by any\n * previously uploaded parts will be freed. However, if any part uploads are currently in\n * progress, those part uploads might or might not succeed. As a result, it might be necessary\n * to abort a given multipart upload multiple times in order to completely free all storage\n * consumed by all parts.
\n * To verify that all parts have been removed, so you don't get charged for the part\n * storage, you should call the ListParts operation and ensure that\n * the parts list is empty.
\n * For information about permissions required to use the multipart upload API, see Multipart Upload API and\n * Permissions.
\n * The following operations are related to AbortMultipartUpload
:
\n * \n */\nvar AbortMultipartUploadCommand = /** @class */ (function (_super) {\n __extends(AbortMultipartUploadCommand, _super);\n // Start section: command_properties\n // End section: command_properties\n function AbortMultipartUploadCommand(input) {\n var _this = \n // Start section: command_constructor\n _super.call(this) || this;\n _this.input = input;\n return _this;\n // End section: command_constructor\n }\n /**\n * @internal\n */\n AbortMultipartUploadCommand.prototype.resolveMiddleware = function (clientStack, configuration, options) {\n this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));\n this.middlewareStack.use(getBucketEndpointPlugin(configuration));\n var stack = clientStack.concat(this.middlewareStack);\n var logger = configuration.logger;\n var clientName = \"S3Client\";\n var commandName = \"AbortMultipartUploadCommand\";\n var handlerExecutionContext = {\n logger: logger,\n clientName: clientName,\n commandName: commandName,\n inputFilterSensitiveLog: AbortMultipartUploadRequest.filterSensitiveLog,\n outputFilterSensitiveLog: AbortMultipartUploadOutput.filterSensitiveLog,\n };\n var requestHandler = configuration.requestHandler;\n return stack.resolve(function (request) {\n return requestHandler.handle(request.request, options || {});\n }, handlerExecutionContext);\n };\n AbortMultipartUploadCommand.prototype.serialize = function (input, context) {\n return serializeAws_restXmlAbortMultipartUploadCommand(input, context);\n };\n AbortMultipartUploadCommand.prototype.deserialize = function (output, context) {\n return deserializeAws_restXmlAbortMultipartUploadCommand(output, context);\n };\n return AbortMultipartUploadCommand;\n}($Command));\nexport { AbortMultipartUploadCommand };\n//# sourceMappingURL=AbortMultipartUploadCommand.js.map","import { __extends } from \"tslib\";\nimport { ListPartsOutput, ListPartsRequest } from \"../models/models_0\";\nimport { deserializeAws_restXmlListPartsCommand, serializeAws_restXmlListPartsCommand } from \"../protocols/Aws_restXml\";\nimport { getBucketEndpointPlugin } from \"@aws-sdk/middleware-bucket-endpoint\";\nimport { getSerdePlugin } from \"@aws-sdk/middleware-serde\";\nimport { Command as $Command } from \"@aws-sdk/smithy-client\";\n/**\n * Lists the parts that have been uploaded for a specific multipart upload. This operation\n * must include the upload ID, which you obtain by sending the initiate multipart upload\n * request (see CreateMultipartUpload).\n * This request returns a maximum of 1,000 uploaded parts. The default number of parts\n * returned is 1,000 parts. You can restrict the number of parts returned by specifying the\n * max-parts
request parameter. If your multipart upload consists of more than\n * 1,000 parts, the response returns an IsTruncated
field with the value of true,\n * and a NextPartNumberMarker
element. In subsequent ListParts
\n * requests you can include the part-number-marker query string parameter and set its value to\n * the NextPartNumberMarker
field value from the previous response.
\n *\n * For more information on multipart uploads, see Uploading Objects Using Multipart\n * Upload.
\n *\n * For information on permissions required to use the multipart upload API, see Multipart Upload API and\n * Permissions.
\n *\n * The following operations are related to ListParts
:
\n * \n */\nvar ListPartsCommand = /** @class */ (function (_super) {\n __extends(ListPartsCommand, _super);\n // Start section: command_properties\n // End section: command_properties\n function ListPartsCommand(input) {\n var _this = \n // Start section: command_constructor\n _super.call(this) || this;\n _this.input = input;\n return _this;\n // End section: command_constructor\n }\n /**\n * @internal\n */\n ListPartsCommand.prototype.resolveMiddleware = function (clientStack, configuration, options) {\n this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));\n this.middlewareStack.use(getBucketEndpointPlugin(configuration));\n var stack = clientStack.concat(this.middlewareStack);\n var logger = configuration.logger;\n var clientName = \"S3Client\";\n var commandName = \"ListPartsCommand\";\n var handlerExecutionContext = {\n logger: logger,\n clientName: clientName,\n commandName: commandName,\n inputFilterSensitiveLog: ListPartsRequest.filterSensitiveLog,\n outputFilterSensitiveLog: ListPartsOutput.filterSensitiveLog,\n };\n var requestHandler = configuration.requestHandler;\n return stack.resolve(function (request) {\n return requestHandler.handle(request.request, options || {});\n }, handlerExecutionContext);\n };\n ListPartsCommand.prototype.serialize = function (input, context) {\n return serializeAws_restXmlListPartsCommand(input, context);\n };\n ListPartsCommand.prototype.deserialize = function (output, context) {\n return deserializeAws_restXmlListPartsCommand(output, context);\n };\n return ListPartsCommand;\n}($Command));\nexport { ListPartsCommand };\n//# sourceMappingURL=ListPartsCommand.js.map","/*\n * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with\n * the License. A copy of the License is located at\n *\n * http://aws.amazon.com/apache2.0/\n *\n * or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions\n * and limitations under the License.\n */\nvar __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nimport { ConsoleLogger as Logger } from '@aws-amplify/core';\nimport { PutObjectCommand, CreateMultipartUploadCommand, UploadPartCommand, CompleteMultipartUploadCommand, ListPartsCommand, AbortMultipartUploadCommand, } from '@aws-sdk/client-s3';\nimport { SEND_UPLOAD_PROGRESS_EVENT, SEND_DOWNLOAD_PROGRESS_EVENT, } from './axios-http-handler';\nimport * as events from 'events';\nimport { createPrefixMiddleware, prefixMiddlewareOptions, autoAdjustClockskewMiddleware, autoAdjustClockskewMiddlewareOptions, createS3Client, } from '../common/S3ClientUtils';\nvar logger = new Logger('AWSS3ProviderManagedUpload');\nvar AWSS3ProviderManagedUpload = /** @class */ (function () {\n function AWSS3ProviderManagedUpload(params, opts, emitter) {\n // Defaults\n this.minPartSize = 5 * 1024 * 1024; // in MB\n this.queueSize = 4;\n // Data for current upload\n this.body = null;\n this.params = null;\n this.opts = null;\n this.completedParts = [];\n this.cancel = false;\n // Progress reporting\n this.bytesUploaded = 0;\n this.totalBytesToUpload = 0;\n this.emitter = null;\n this.params = params;\n this.opts = opts;\n this.emitter = emitter;\n this.s3client = this._createNewS3Client(opts, emitter);\n }\n AWSS3ProviderManagedUpload.prototype.upload = function () {\n return __awaiter(this, void 0, void 0, function () {\n var _a, putObjectCommand, uploadId, numberOfPartsToUpload, parts, start;\n var _this = this;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n _a = this;\n return [4 /*yield*/, this.validateAndSanitizeBody(this.params.Body)];\n case 1:\n _a.body = _b.sent();\n this.totalBytesToUpload = this.byteLength(this.body);\n if (!(this.totalBytesToUpload <= this.minPartSize)) return [3 /*break*/, 2];\n // Multipart upload is not required. Upload the sanitized body as is\n this.params.Body = this.body;\n putObjectCommand = new PutObjectCommand(this.params);\n return [2 /*return*/, this.s3client.send(putObjectCommand)];\n case 2: return [4 /*yield*/, this.createMultiPartUpload()];\n case 3:\n uploadId = _b.sent();\n numberOfPartsToUpload = Math.ceil(this.totalBytesToUpload / this.minPartSize);\n parts = this.createParts();\n start = 0;\n _b.label = 4;\n case 4:\n if (!(start < numberOfPartsToUpload)) return [3 /*break*/, 9];\n /** This first block will try to cancel the upload if the cancel\n *\trequest came before any parts uploads have started.\n **/\n return [4 /*yield*/, this.checkIfUploadCancelled(uploadId)];\n case 5:\n /** This first block will try to cancel the upload if the cancel\n *\trequest came before any parts uploads have started.\n **/\n _b.sent();\n // Upload as many as `queueSize` parts simultaneously\n return [4 /*yield*/, this.uploadParts(uploadId, parts.slice(start, start + this.queueSize))];\n case 6:\n // Upload as many as `queueSize` parts simultaneously\n _b.sent();\n /** Call cleanup a second time in case there were part upload requests\n * in flight. This is to ensure that all parts are cleaned up.\n */\n return [4 /*yield*/, this.checkIfUploadCancelled(uploadId)];\n case 7:\n /** Call cleanup a second time in case there were part upload requests\n * in flight. This is to ensure that all parts are cleaned up.\n */\n _b.sent();\n _b.label = 8;\n case 8:\n start += this.queueSize;\n return [3 /*break*/, 4];\n case 9:\n parts.map(function (part) {\n _this.removeEventListener(part);\n });\n return [4 /*yield*/, this.finishMultiPartUpload(uploadId)];\n case 10: \n // Step 3: Finalize the upload such that S3 can recreate the file\n return [2 /*return*/, _b.sent()];\n }\n });\n });\n };\n AWSS3ProviderManagedUpload.prototype.createParts = function () {\n var parts = [];\n for (var bodyStart = 0; bodyStart < this.totalBytesToUpload;) {\n var bodyEnd = Math.min(bodyStart + this.minPartSize, this.totalBytesToUpload);\n parts.push({\n bodyPart: this.body.slice(bodyStart, bodyEnd),\n partNumber: parts.length + 1,\n emitter: new events.EventEmitter(),\n _lastUploadedBytes: 0,\n });\n bodyStart += this.minPartSize;\n }\n return parts;\n };\n AWSS3ProviderManagedUpload.prototype.createMultiPartUpload = function () {\n return __awaiter(this, void 0, void 0, function () {\n var createMultiPartUploadCommand, response;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n createMultiPartUploadCommand = new CreateMultipartUploadCommand(this.params);\n return [4 /*yield*/, this.s3client.send(createMultiPartUploadCommand)];\n case 1:\n response = _a.sent();\n logger.debug(response.UploadId);\n return [2 /*return*/, response.UploadId];\n }\n });\n });\n };\n /**\n * @private Not to be extended outside of tests\n * @VisibleFotTesting\n */\n AWSS3ProviderManagedUpload.prototype.uploadParts = function (uploadId, parts) {\n return __awaiter(this, void 0, void 0, function () {\n var allResults, i, error_1;\n var _this = this;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 2, , 3]);\n return [4 /*yield*/, Promise.all(parts.map(function (part) { return __awaiter(_this, void 0, void 0, function () {\n var options, _a, Key, Bucket, SSECustomerAlgorithm, SSECustomerKey, SSECustomerKeyMD5, res;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n this.setupEventListener(part);\n options = { emitter: part.emitter };\n _a = this.params, Key = _a.Key, Bucket = _a.Bucket, SSECustomerAlgorithm = _a.SSECustomerAlgorithm, SSECustomerKey = _a.SSECustomerKey, SSECustomerKeyMD5 = _a.SSECustomerKeyMD5;\n return [4 /*yield*/, this.s3client.send(new UploadPartCommand(__assign(__assign(__assign({ PartNumber: part.partNumber, Body: part.bodyPart, UploadId: uploadId, Key: Key,\n Bucket: Bucket }, (SSECustomerAlgorithm && { SSECustomerAlgorithm: SSECustomerAlgorithm })), (SSECustomerKey && { SSECustomerKey: SSECustomerKey })), (SSECustomerKeyMD5 && { SSECustomerKeyMD5: SSECustomerKeyMD5 }))), options)];\n case 1:\n res = _b.sent();\n return [2 /*return*/, res];\n }\n });\n }); }))];\n case 1:\n allResults = _a.sent();\n // The order of resolved promises is the same as input promise order.\n for (i = 0; i < allResults.length; i++) {\n this.completedParts.push({\n PartNumber: parts[i].partNumber,\n ETag: allResults[i].ETag,\n });\n }\n return [3 /*break*/, 3];\n case 2:\n error_1 = _a.sent();\n logger.error('error happened while uploading a part. Cancelling the multipart upload', error_1);\n this.cancelUpload();\n return [2 /*return*/];\n case 3: return [2 /*return*/];\n }\n });\n });\n };\n AWSS3ProviderManagedUpload.prototype.finishMultiPartUpload = function (uploadId) {\n return __awaiter(this, void 0, void 0, function () {\n var input, completeUploadCommand, data, error_2;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n input = {\n Bucket: this.params.Bucket,\n Key: this.params.Key,\n UploadId: uploadId,\n MultipartUpload: { Parts: this.completedParts },\n };\n completeUploadCommand = new CompleteMultipartUploadCommand(input);\n _a.label = 1;\n case 1:\n _a.trys.push([1, 3, , 4]);\n return [4 /*yield*/, this.s3client.send(completeUploadCommand)];\n case 2:\n data = _a.sent();\n return [2 /*return*/, data.Key];\n case 3:\n error_2 = _a.sent();\n logger.error('error happened while finishing the upload. Cancelling the multipart upload', error_2);\n this.cancelUpload();\n return [2 /*return*/];\n case 4: return [2 /*return*/];\n }\n });\n });\n };\n AWSS3ProviderManagedUpload.prototype.checkIfUploadCancelled = function (uploadId) {\n return __awaiter(this, void 0, void 0, function () {\n var errorMessage, error_3;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!this.cancel) return [3 /*break*/, 5];\n errorMessage = 'Upload was cancelled.';\n _a.label = 1;\n case 1:\n _a.trys.push([1, 3, , 4]);\n return [4 /*yield*/, this.cleanup(uploadId)];\n case 2:\n _a.sent();\n return [3 /*break*/, 4];\n case 3:\n error_3 = _a.sent();\n errorMessage += \" \" + error_3.message;\n return [3 /*break*/, 4];\n case 4: throw new Error(errorMessage);\n case 5: return [2 /*return*/];\n }\n });\n });\n };\n AWSS3ProviderManagedUpload.prototype.cancelUpload = function () {\n this.cancel = true;\n };\n AWSS3ProviderManagedUpload.prototype.cleanup = function (uploadId) {\n return __awaiter(this, void 0, void 0, function () {\n var input, data;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n // Reset this's state\n this.body = null;\n this.completedParts = [];\n this.bytesUploaded = 0;\n this.totalBytesToUpload = 0;\n input = {\n Bucket: this.params.Bucket,\n Key: this.params.Key,\n UploadId: uploadId,\n };\n return [4 /*yield*/, this.s3client.send(new AbortMultipartUploadCommand(input))];\n case 1:\n _a.sent();\n return [4 /*yield*/, this.s3client.send(new ListPartsCommand(input))];\n case 2:\n data = _a.sent();\n if (data && data.Parts && data.Parts.length > 0) {\n throw new Error('Multi Part upload clean up failed');\n }\n return [2 /*return*/];\n }\n });\n });\n };\n AWSS3ProviderManagedUpload.prototype.removeEventListener = function (part) {\n part.emitter.removeAllListeners(SEND_UPLOAD_PROGRESS_EVENT);\n part.emitter.removeAllListeners(SEND_DOWNLOAD_PROGRESS_EVENT);\n };\n AWSS3ProviderManagedUpload.prototype.setupEventListener = function (part) {\n var _this = this;\n part.emitter.on(SEND_UPLOAD_PROGRESS_EVENT, function (progress) {\n _this.progressChanged(part.partNumber, progress.loaded - part._lastUploadedBytes);\n part._lastUploadedBytes = progress.loaded;\n });\n };\n AWSS3ProviderManagedUpload.prototype.progressChanged = function (partNumber, incrementalUpdate) {\n this.bytesUploaded += incrementalUpdate;\n this.emitter.emit(SEND_UPLOAD_PROGRESS_EVENT, {\n loaded: this.bytesUploaded,\n total: this.totalBytesToUpload,\n part: partNumber,\n key: this.params.Key,\n });\n };\n AWSS3ProviderManagedUpload.prototype.byteLength = function (input) {\n if (input === null || input === undefined)\n return 0;\n if (typeof input.byteLength === 'number') {\n return input.byteLength;\n }\n else if (typeof input.length === 'number') {\n return input.length;\n }\n else if (typeof input.size === 'number') {\n return input.size;\n }\n else if (typeof input.path === 'string') {\n /* NodeJs Support\n return require('fs').lstatSync(input.path).size;\n */\n }\n else {\n throw new Error('Cannot determine length of ' + input);\n }\n };\n AWSS3ProviderManagedUpload.prototype.validateAndSanitizeBody = function (body) {\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n if (this.isGenericObject(body)) {\n // Any javascript object\n return [2 /*return*/, JSON.stringify(body)];\n }\n else {\n // Files, arrayBuffer etc\n return [2 /*return*/, body];\n }\n return [2 /*return*/];\n });\n });\n };\n AWSS3ProviderManagedUpload.prototype.isGenericObject = function (body) {\n if (body !== null && typeof body === 'object') {\n try {\n return !(this.byteLength(body) >= 0);\n }\n catch (error) {\n // If we cannot determine the length of the body, consider it\n // as a generic object and upload a stringified version of it\n return true;\n }\n }\n return false;\n };\n AWSS3ProviderManagedUpload.prototype._createNewS3Client = function (config, emitter) {\n var s3client = createS3Client(config, emitter);\n s3client.middlewareStack.add(createPrefixMiddleware(this.opts, this.params.Key), prefixMiddlewareOptions);\n s3client.middlewareStack.add(autoAdjustClockskewMiddleware(s3client.config), autoAdjustClockskewMiddlewareOptions);\n return s3client;\n };\n return AWSS3ProviderManagedUpload;\n}());\nexport { AWSS3ProviderManagedUpload };\n//# sourceMappingURL=AWSS3ProviderManagedUpload.js.map","import { __extends } from \"tslib\";\nimport { ListObjectsV2Output, ListObjectsV2Request } from \"../models/models_0\";\nimport { deserializeAws_restXmlListObjectsV2Command, serializeAws_restXmlListObjectsV2Command, } from \"../protocols/Aws_restXml\";\nimport { getBucketEndpointPlugin } from \"@aws-sdk/middleware-bucket-endpoint\";\nimport { getSerdePlugin } from \"@aws-sdk/middleware-serde\";\nimport { Command as $Command } from \"@aws-sdk/smithy-client\";\n/**\n * Returns some or all (up to 1,000) of the objects in a bucket. You can use the request\n * parameters as selection criteria to return a subset of the objects in a bucket. A 200\n * OK
response can contain valid or invalid XML. Make sure to design your\n * application to parse the contents of the response and handle it appropriately.
\n *\n * To use this operation, you must have READ access to the bucket.
\n *\n * To use this operation in an AWS Identity and Access Management (IAM) policy, you must\n * have permissions to perform the s3:ListBucket
action. The bucket owner has\n * this permission by default and can grant this permission to others. For more information\n * about permissions, see Permissions Related to Bucket Subresource Operations and Managing Access Permissions to Your Amazon S3\n * Resources.
\n * \n * This section describes the latest revision of the API. We recommend that you use this\n * revised API for application development. For backward compatibility, Amazon S3 continues to\n * support the prior version of this API, ListObjects.
\n * \n *\n * To get a list of your buckets, see ListBuckets.
\n *\n * The following operations are related to ListObjectsV2
:
\n * \n */\nvar ListObjectsV2Command = /** @class */ (function (_super) {\n __extends(ListObjectsV2Command, _super);\n // Start section: command_properties\n // End section: command_properties\n function ListObjectsV2Command(input) {\n var _this = \n // Start section: command_constructor\n _super.call(this) || this;\n _this.input = input;\n return _this;\n // End section: command_constructor\n }\n /**\n * @internal\n */\n ListObjectsV2Command.prototype.resolveMiddleware = function (clientStack, configuration, options) {\n this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));\n this.middlewareStack.use(getBucketEndpointPlugin(configuration));\n var stack = clientStack.concat(this.middlewareStack);\n var logger = configuration.logger;\n var clientName = \"S3Client\";\n var commandName = \"ListObjectsV2Command\";\n var handlerExecutionContext = {\n logger: logger,\n clientName: clientName,\n commandName: commandName,\n inputFilterSensitiveLog: ListObjectsV2Request.filterSensitiveLog,\n outputFilterSensitiveLog: ListObjectsV2Output.filterSensitiveLog,\n };\n var requestHandler = configuration.requestHandler;\n return stack.resolve(function (request) {\n return requestHandler.handle(request.request, options || {});\n }, handlerExecutionContext);\n };\n ListObjectsV2Command.prototype.serialize = function (input, context) {\n return serializeAws_restXmlListObjectsV2Command(input, context);\n };\n ListObjectsV2Command.prototype.deserialize = function (output, context) {\n return deserializeAws_restXmlListObjectsV2Command(output, context);\n };\n return ListObjectsV2Command;\n}($Command));\nexport { ListObjectsV2Command };\n//# sourceMappingURL=ListObjectsV2Command.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\n/*\n * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with\n * the License. A copy of the License is located at\n *\n * http://aws.amazon.com/apache2.0/\n *\n * or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions\n * and limitations under the License.\n */\nimport { ConsoleLogger as Logger, Credentials, Parser, StorageHelper, Hub, } from '@aws-amplify/core';\nimport { GetObjectCommand, DeleteObjectCommand, ListObjectsCommand, CopyObjectCommand, } from '@aws-sdk/client-s3';\nimport { formatUrl } from '@aws-sdk/util-format-url';\nimport { createRequest } from '@aws-sdk/util-create-request';\nimport { S3RequestPresigner } from '@aws-sdk/s3-request-presigner';\nimport { SEND_DOWNLOAD_PROGRESS_EVENT, SEND_UPLOAD_PROGRESS_EVENT, } from './axios-http-handler';\nimport { StorageErrorStrings } from '../common/StorageErrorStrings';\nimport { dispatchStorageEvent } from '../common/StorageUtils';\nimport { createPrefixMiddleware, prefixMiddlewareOptions, getPrefix, autoAdjustClockskewMiddleware, autoAdjustClockskewMiddlewareOptions, createS3Client, } from '../common/S3ClientUtils';\nimport { AWSS3ProviderManagedUpload } from './AWSS3ProviderManagedUpload';\nimport { AWSS3UploadTask, TaskEvents } from './AWSS3UploadTask';\nimport { UPLOADS_STORAGE_KEY } from '../common/StorageConstants';\nimport * as events from 'events';\nvar logger = new Logger('AWSS3Provider');\nvar DEFAULT_STORAGE_LEVEL = 'public';\nvar DEFAULT_PRESIGN_EXPIRATION = 900;\n/**\n * Provide storage methods to use AWS S3\n */\nvar AWSS3Provider = /** @class */ (function () {\n /**\n * Initialize Storage with AWS configurations\n * @param {Object} config - Configuration object for storage\n */\n function AWSS3Provider(config) {\n var _this = this;\n this._config = config ? config : {};\n this._storage = new StorageHelper().getStorage();\n Hub.listen('auth', function (data) {\n var payload = data.payload;\n if (payload.event === 'signOut' || payload.event === 'signIn') {\n _this._storage.removeItem(UPLOADS_STORAGE_KEY);\n }\n });\n logger.debug('Storage Options', this._config);\n }\n /**\n * get the category of the plugin\n */\n AWSS3Provider.prototype.getCategory = function () {\n return AWSS3Provider.CATEGORY;\n };\n /**\n * get provider name of the plugin\n */\n AWSS3Provider.prototype.getProviderName = function () {\n return AWSS3Provider.PROVIDER_NAME;\n };\n /**\n * Configure Storage part with aws configuration\n * @param {Object} config - Configuration of the Storage\n * @return {Object} - Current configuration\n */\n AWSS3Provider.prototype.configure = function (config) {\n logger.debug('configure Storage', config);\n if (!config)\n return this._config;\n var amplifyConfig = Parser.parseMobilehubConfig(config);\n this._config = Object.assign({}, this._config, amplifyConfig.Storage);\n if (!this._config.bucket) {\n logger.debug('Do not have bucket yet');\n }\n return this._config;\n };\n AWSS3Provider.prototype.startResumableUpload = function (addTaskInput, config) {\n var s3Client = addTaskInput.s3Client, emitter = addTaskInput.emitter, key = addTaskInput.key, file = addTaskInput.file, params = addTaskInput.params;\n var progressCallback = config.progressCallback, completeCallback = config.completeCallback, errorCallback = config.errorCallback, _a = config.track, track = _a === void 0 ? false : _a;\n if (!(file instanceof Blob)) {\n throw new Error(StorageErrorStrings.INVALID_BLOB);\n }\n emitter.on(TaskEvents.UPLOAD_PROGRESS, function (event) {\n if (progressCallback) {\n if (typeof progressCallback === 'function') {\n progressCallback(event);\n }\n else {\n logger.warn('progressCallback should be a function, not a ' +\n typeof progressCallback);\n }\n }\n });\n emitter.on(TaskEvents.UPLOAD_COMPLETE, function (event) {\n if (completeCallback) {\n if (typeof completeCallback === 'function') {\n completeCallback(event);\n }\n else {\n logger.warn('completeCallback should be a function, not a ' +\n typeof completeCallback);\n }\n }\n });\n emitter.on(TaskEvents.ERROR, function (err) {\n if (errorCallback) {\n if (typeof errorCallback === 'function') {\n errorCallback(err);\n }\n else {\n logger.warn('errorCallback should be a function, not a ' + typeof errorCallback);\n }\n }\n });\n // we want to keep this function sync so we defer this promise to AWSS3UploadTask to resolve when it's needed\n // when its doing a final check with _listSingleFile function\n var prefixPromise = Credentials.get().then(function (credentials) {\n var cred = Credentials.shear(credentials);\n return getPrefix(__assign(__assign({}, config), { credentials: cred }));\n });\n var task = new AWSS3UploadTask({\n s3Client: s3Client,\n file: file,\n emitter: emitter,\n level: config.level,\n storage: this._storage,\n params: params,\n prefixPromise: prefixPromise,\n });\n dispatchStorageEvent(track, 'upload', { method: 'put', result: 'success' }, null, \"Upload Task created successfully for \" + key);\n // automatically start the upload task\n task.resume();\n return task;\n };\n /**\n * Copy an object from a source object to a new object within the same bucket. Can optionally copy files across\n * different level or identityId (if source object's level is 'protected').\n *\n * @async\n * @param {S3CopySource} src - Key and optionally access level and identityId of the source object.\n * @param {S3CopyDestination} dest - Key and optionally access level of the destination object.\n * @param {S3ProviderCopyConfig} [config] - Optional configuration for s3 commands.\n * @return {Promise} The key of the copied object.\n */\n AWSS3Provider.prototype.copy = function (src, dest, config) {\n return __awaiter(this, void 0, void 0, function () {\n var credentialsOK, opt, acl, bucket, cacheControl, expires, track, serverSideEncryption, SSECustomerAlgorithm, SSECustomerKey, SSECustomerKeyMD5, SSEKMSKeyId, _a, srcLevel, srcIdentityId, srcKey, _b, destLevel, destKey, srcPrefix, destPrefix, finalSrcKey, finalDestKey, params, s3, error_1;\n return __generator(this, function (_c) {\n switch (_c.label) {\n case 0: return [4 /*yield*/, this._ensureCredentials()];\n case 1:\n credentialsOK = _c.sent();\n if (!credentialsOK || !this._isWithCredentials(this._config)) {\n throw new Error(StorageErrorStrings.NO_CREDENTIALS);\n }\n opt = Object.assign({}, this._config, config);\n acl = opt.acl, bucket = opt.bucket, cacheControl = opt.cacheControl, expires = opt.expires, track = opt.track, serverSideEncryption = opt.serverSideEncryption, SSECustomerAlgorithm = opt.SSECustomerAlgorithm, SSECustomerKey = opt.SSECustomerKey, SSECustomerKeyMD5 = opt.SSECustomerKeyMD5, SSEKMSKeyId = opt.SSEKMSKeyId;\n _a = src.level, srcLevel = _a === void 0 ? DEFAULT_STORAGE_LEVEL : _a, srcIdentityId = src.identityId, srcKey = src.key;\n _b = dest.level, destLevel = _b === void 0 ? DEFAULT_STORAGE_LEVEL : _b, destKey = dest.key;\n if (!srcKey || typeof srcKey !== 'string') {\n throw new Error(StorageErrorStrings.NO_SRC_KEY);\n }\n if (!destKey || typeof destKey !== 'string') {\n throw new Error(StorageErrorStrings.NO_DEST_KEY);\n }\n if (srcLevel !== 'protected' && srcIdentityId) {\n logger.warn(\"You may copy files from another user if the source level is \\\"protected\\\", currently it's \" + srcLevel);\n }\n srcPrefix = this._prefix(__assign(__assign(__assign({}, opt), { level: srcLevel }), (srcIdentityId && { identityId: srcIdentityId })));\n destPrefix = this._prefix(__assign(__assign({}, opt), { level: destLevel }));\n finalSrcKey = bucket + \"/\" + srcPrefix + srcKey;\n finalDestKey = \"\" + destPrefix + destKey;\n logger.debug(\"copying \" + finalSrcKey + \" to \" + finalDestKey);\n params = {\n Bucket: bucket,\n CopySource: finalSrcKey,\n Key: finalDestKey,\n // Copies over metadata like contentType as well\n MetadataDirective: 'COPY',\n };\n if (cacheControl)\n params.CacheControl = cacheControl;\n if (expires)\n params.Expires = expires;\n if (serverSideEncryption) {\n params.ServerSideEncryption = serverSideEncryption;\n }\n if (SSECustomerAlgorithm) {\n params.SSECustomerAlgorithm = SSECustomerAlgorithm;\n }\n if (SSECustomerKey) {\n params.SSECustomerKey = SSECustomerKey;\n }\n if (SSECustomerKeyMD5) {\n params.SSECustomerKeyMD5 = SSECustomerKeyMD5;\n }\n if (SSEKMSKeyId) {\n params.SSEKMSKeyId = SSEKMSKeyId;\n }\n if (acl)\n params.ACL = acl;\n s3 = this._createNewS3Client(opt);\n _c.label = 2;\n case 2:\n _c.trys.push([2, 4, , 5]);\n return [4 /*yield*/, s3.send(new CopyObjectCommand(params))];\n case 3:\n _c.sent();\n dispatchStorageEvent(track, 'copy', {\n method: 'copy',\n result: 'success',\n }, null, \"Copy success from \" + srcKey + \" to \" + destKey);\n return [2 /*return*/, {\n key: destKey,\n }];\n case 4:\n error_1 = _c.sent();\n dispatchStorageEvent(track, 'copy', {\n method: 'copy',\n result: 'failed',\n }, null, \"Copy failed from \" + srcKey + \" to \" + destKey);\n throw error_1;\n case 5: return [2 /*return*/];\n }\n });\n });\n };\n AWSS3Provider.prototype.get = function (key, config) {\n return __awaiter(this, void 0, void 0, function () {\n var credentialsOK, opt, bucket, download, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType, expires, track, SSECustomerAlgorithm, SSECustomerKey, SSECustomerKeyMD5, progressCallback, prefix, final_key, emitter, s3, params, getObjectCommand, response, error_2, signer, request, url, _a, error_3;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0: return [4 /*yield*/, this._ensureCredentials()];\n case 1:\n credentialsOK = _b.sent();\n if (!credentialsOK || !this._isWithCredentials(this._config)) {\n throw new Error(StorageErrorStrings.NO_CREDENTIALS);\n }\n opt = Object.assign({}, this._config, config);\n bucket = opt.bucket, download = opt.download, cacheControl = opt.cacheControl, contentDisposition = opt.contentDisposition, contentEncoding = opt.contentEncoding, contentLanguage = opt.contentLanguage, contentType = opt.contentType, expires = opt.expires, track = opt.track, SSECustomerAlgorithm = opt.SSECustomerAlgorithm, SSECustomerKey = opt.SSECustomerKey, SSECustomerKeyMD5 = opt.SSECustomerKeyMD5, progressCallback = opt.progressCallback;\n prefix = this._prefix(opt);\n final_key = prefix + key;\n emitter = new events.EventEmitter();\n s3 = this._createNewS3Client(opt, emitter);\n logger.debug('get ' + key + ' from ' + final_key);\n params = {\n Bucket: bucket,\n Key: final_key,\n };\n // See: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getObject-property\n if (cacheControl)\n params.ResponseCacheControl = cacheControl;\n if (contentDisposition)\n params.ResponseContentDisposition = contentDisposition;\n if (contentEncoding)\n params.ResponseContentEncoding = contentEncoding;\n if (contentLanguage)\n params.ResponseContentLanguage = contentLanguage;\n if (contentType)\n params.ResponseContentType = contentType;\n if (SSECustomerAlgorithm) {\n params.SSECustomerAlgorithm = SSECustomerAlgorithm;\n }\n if (SSECustomerKey) {\n params.SSECustomerKey = SSECustomerKey;\n }\n if (SSECustomerKeyMD5) {\n params.SSECustomerKeyMD5 = SSECustomerKeyMD5;\n }\n if (!(download === true)) return [3 /*break*/, 5];\n getObjectCommand = new GetObjectCommand(params);\n _b.label = 2;\n case 2:\n _b.trys.push([2, 4, , 5]);\n if (progressCallback) {\n if (typeof progressCallback === 'function') {\n emitter.on(SEND_DOWNLOAD_PROGRESS_EVENT, function (progress) {\n progressCallback(progress);\n });\n }\n else {\n logger.warn('progressCallback should be a function, not a ' +\n typeof progressCallback);\n }\n }\n return [4 /*yield*/, s3.send(getObjectCommand)];\n case 3:\n response = _b.sent();\n emitter.removeAllListeners(SEND_DOWNLOAD_PROGRESS_EVENT);\n dispatchStorageEvent(track, 'download', { method: 'get', result: 'success' }, {\n fileSize: Number(response.Body['size'] || response.Body['length']),\n }, \"Download success for \" + key);\n return [2 /*return*/, response];\n case 4:\n error_2 = _b.sent();\n dispatchStorageEvent(track, 'download', {\n method: 'get',\n result: 'failed',\n }, null, \"Download failed with \" + error_2.message);\n throw error_2;\n case 5:\n _b.trys.push([5, 8, , 9]);\n signer = new S3RequestPresigner(__assign({}, s3.config));\n return [4 /*yield*/, createRequest(s3, new GetObjectCommand(params))];\n case 6:\n request = _b.sent();\n _a = formatUrl;\n return [4 /*yield*/, signer.presign(request, {\n expiresIn: expires || DEFAULT_PRESIGN_EXPIRATION,\n })];\n case 7:\n url = _a.apply(void 0, [_b.sent()]);\n dispatchStorageEvent(track, 'getSignedUrl', { method: 'get', result: 'success' }, null, \"Signed URL: \" + url);\n return [2 /*return*/, url];\n case 8:\n error_3 = _b.sent();\n logger.warn('get signed url error', error_3);\n dispatchStorageEvent(track, 'getSignedUrl', { method: 'get', result: 'failed' }, null, \"Could not get a signed URL for \" + key);\n throw error_3;\n case 9: return [2 /*return*/];\n }\n });\n });\n };\n /**\n * Put a file in S3 bucket specified to configure method\n * @param key - key of the object\n * @param object - File to be put in Amazon S3 bucket\n * @param [config] - Optional configuration for the underlying S3 command\n * @return an instance of AWSS3UploadTask or a promise that resolves to an object with the new object's key on\n * success.\n */\n AWSS3Provider.prototype.put = function (key, object, config) {\n var opt = Object.assign({}, this._config, config);\n var bucket = opt.bucket, track = opt.track, progressCallback = opt.progressCallback, level = opt.level, resumable = opt.resumable;\n var contentType = opt.contentType, contentDisposition = opt.contentDisposition, contentEncoding = opt.contentEncoding, cacheControl = opt.cacheControl, expires = opt.expires, metadata = opt.metadata, tagging = opt.tagging, acl = opt.acl;\n var serverSideEncryption = opt.serverSideEncryption, SSECustomerAlgorithm = opt.SSECustomerAlgorithm, SSECustomerKey = opt.SSECustomerKey, SSECustomerKeyMD5 = opt.SSECustomerKeyMD5, SSEKMSKeyId = opt.SSEKMSKeyId;\n var type = contentType ? contentType : 'binary/octet-stream';\n var params = {\n Bucket: bucket,\n Key: key,\n Body: object,\n ContentType: type,\n };\n if (cacheControl) {\n params.CacheControl = cacheControl;\n }\n if (contentDisposition) {\n params.ContentDisposition = contentDisposition;\n }\n if (contentEncoding) {\n params.ContentEncoding = contentEncoding;\n }\n if (expires) {\n params.Expires = expires;\n }\n if (metadata) {\n params.Metadata = metadata;\n }\n if (tagging) {\n params.Tagging = tagging;\n }\n if (serverSideEncryption) {\n params.ServerSideEncryption = serverSideEncryption;\n }\n if (SSECustomerAlgorithm) {\n params.SSECustomerAlgorithm = SSECustomerAlgorithm;\n }\n if (SSECustomerKey) {\n params.SSECustomerKey = SSECustomerKey;\n }\n if (SSECustomerKeyMD5) {\n params.SSECustomerKeyMD5 = SSECustomerKeyMD5;\n }\n if (SSEKMSKeyId) {\n params.SSEKMSKeyId = SSEKMSKeyId;\n }\n var emitter = new events.EventEmitter();\n var uploader = new AWSS3ProviderManagedUpload(params, opt, emitter);\n if (acl) {\n params.ACL = acl;\n }\n if (resumable === true) {\n var s3Client = this._createNewS3Client(opt);\n // we are using aws sdk middleware to inject the prefix to key, this way we don't have to call\n // this._ensureCredentials() which allows us to make this function sync so we can return non-Promise like UploadTask\n s3Client.middlewareStack.add(createPrefixMiddleware(opt, key), prefixMiddlewareOptions);\n var addTaskInput = {\n bucket: bucket,\n key: key,\n s3Client: s3Client,\n file: object,\n emitter: emitter,\n accessLevel: level,\n params: params,\n };\n // explicitly asserting the type here as Typescript could not infer that resumable is of type true\n return this.startResumableUpload(addTaskInput, config);\n }\n try {\n if (progressCallback) {\n if (typeof progressCallback === 'function') {\n emitter.on(SEND_UPLOAD_PROGRESS_EVENT, function (progress) {\n progressCallback(progress);\n });\n }\n else {\n logger.warn('progressCallback should be a function, not a ' +\n typeof progressCallback);\n }\n }\n return uploader.upload().then(function (response) {\n logger.debug('upload result', response);\n dispatchStorageEvent(track, 'upload', { method: 'put', result: 'success' }, null, \"Upload success for \" + key);\n return { key: key };\n });\n }\n catch (error) {\n logger.warn('error uploading', error);\n dispatchStorageEvent(track, 'upload', { method: 'put', result: 'failed' }, null, \"Error uploading \" + key);\n throw error;\n }\n };\n /**\n * Remove the object for specified key\n * @param {string} key - key of the object\n * @param {S3ProviderRemoveConfig} [config] - Optional configuration for the underlying S3 command\n * @return {Promise} - Promise resolves upon successful removal of the object\n */\n AWSS3Provider.prototype.remove = function (key, config) {\n return __awaiter(this, void 0, void 0, function () {\n var credentialsOK, opt, bucket, track, prefix, final_key, s3, params, deleteObjectCommand, response, error_4;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, this._ensureCredentials()];\n case 1:\n credentialsOK = _a.sent();\n if (!credentialsOK || !this._isWithCredentials(this._config)) {\n throw new Error(StorageErrorStrings.NO_CREDENTIALS);\n }\n opt = Object.assign({}, this._config, config);\n bucket = opt.bucket, track = opt.track;\n prefix = this._prefix(opt);\n final_key = prefix + key;\n s3 = this._createNewS3Client(opt);\n logger.debug('remove ' + key + ' from ' + final_key);\n params = {\n Bucket: bucket,\n Key: final_key,\n };\n deleteObjectCommand = new DeleteObjectCommand(params);\n _a.label = 2;\n case 2:\n _a.trys.push([2, 4, , 5]);\n return [4 /*yield*/, s3.send(deleteObjectCommand)];\n case 3:\n response = _a.sent();\n dispatchStorageEvent(track, 'delete', { method: 'remove', result: 'success' }, null, \"Deleted \" + key + \" successfully\");\n return [2 /*return*/, response];\n case 4:\n error_4 = _a.sent();\n dispatchStorageEvent(track, 'delete', { method: 'remove', result: 'failed' }, null, \"Deletion of \" + key + \" failed with \" + error_4);\n throw error_4;\n case 5: return [2 /*return*/];\n }\n });\n });\n };\n /**\n * List bucket objects relative to the level and prefix specified\n * @param {string} path - the path that contains objects\n * @param {S3ProviderListConfig} [config] - Optional configuration for the underlying S3 command\n * @return {Promise} - Promise resolves to list of keys, eTags, lastModified and file size for\n * all objects in path\n */\n AWSS3Provider.prototype.list = function (path, config) {\n return __awaiter(this, void 0, void 0, function () {\n var credentialsOK, opt, bucket, track, maxKeys, prefix, final_path, s3, params, listObjectsCommand, response, list, error_5;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, this._ensureCredentials()];\n case 1:\n credentialsOK = _a.sent();\n if (!credentialsOK || !this._isWithCredentials(this._config)) {\n throw new Error(StorageErrorStrings.NO_CREDENTIALS);\n }\n opt = Object.assign({}, this._config, config);\n bucket = opt.bucket, track = opt.track, maxKeys = opt.maxKeys;\n prefix = this._prefix(opt);\n final_path = prefix + path;\n s3 = this._createNewS3Client(opt);\n logger.debug('list ' + path + ' from ' + final_path);\n params = {\n Bucket: bucket,\n Prefix: final_path,\n MaxKeys: maxKeys,\n };\n listObjectsCommand = new ListObjectsCommand(params);\n _a.label = 2;\n case 2:\n _a.trys.push([2, 4, , 5]);\n return [4 /*yield*/, s3.send(listObjectsCommand)];\n case 3:\n response = _a.sent();\n list = [];\n if (response && response.Contents) {\n list = response.Contents.map(function (item) {\n return {\n key: item.Key.substr(prefix.length),\n eTag: item.ETag,\n lastModified: item.LastModified,\n size: item.Size,\n };\n });\n }\n dispatchStorageEvent(track, 'list', { method: 'list', result: 'success' }, null, list.length + \" items returned from list operation\");\n logger.debug('list', list);\n return [2 /*return*/, list];\n case 4:\n error_5 = _a.sent();\n logger.warn('list error', error_5);\n dispatchStorageEvent(track, 'list', { method: 'list', result: 'failed' }, null, \"Listing items failed: \" + error_5.message);\n throw error_5;\n case 5: return [2 /*return*/];\n }\n });\n });\n };\n AWSS3Provider.prototype._ensureCredentials = function () {\n return __awaiter(this, void 0, void 0, function () {\n var credentials, cred, error_6;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 2, , 3]);\n return [4 /*yield*/, Credentials.get()];\n case 1:\n credentials = _a.sent();\n if (!credentials)\n return [2 /*return*/, false];\n cred = Credentials.shear(credentials);\n logger.debug('set credentials for storage', cred);\n this._config.credentials = cred;\n return [2 /*return*/, true];\n case 2:\n error_6 = _a.sent();\n logger.warn('ensure credentials error', error_6);\n return [2 /*return*/, false];\n case 3: return [2 /*return*/];\n }\n });\n });\n };\n AWSS3Provider.prototype._isWithCredentials = function (config) {\n return typeof config === 'object' && config.hasOwnProperty('credentials');\n };\n AWSS3Provider.prototype._prefix = function (config) {\n var credentials = config.credentials, level = config.level;\n var customPrefix = config.customPrefix || {};\n var identityId = config.identityId || credentials.identityId;\n var privatePath = (customPrefix.private !== undefined ? customPrefix.private : 'private/') +\n identityId +\n '/';\n var protectedPath = (customPrefix.protected !== undefined\n ? customPrefix.protected\n : 'protected/') +\n identityId +\n '/';\n var publicPath = customPrefix.public !== undefined ? customPrefix.public : 'public/';\n switch (level) {\n case 'private':\n return privatePath;\n case 'protected':\n return protectedPath;\n default:\n return publicPath;\n }\n };\n /**\n * Creates an S3 client with new V3 aws sdk\n */\n AWSS3Provider.prototype._createNewS3Client = function (config, emitter) {\n var s3client = createS3Client(config, emitter);\n s3client.middlewareStack.add(autoAdjustClockskewMiddleware(s3client.config), autoAdjustClockskewMiddlewareOptions);\n return s3client;\n };\n AWSS3Provider.CATEGORY = 'Storage';\n AWSS3Provider.PROVIDER_NAME = 'AWSS3';\n return AWSS3Provider;\n}());\nexport { AWSS3Provider };\n/**\n * @deprecated use named import\n */\nexport default AWSS3Provider;\n//# sourceMappingURL=AWSS3Provider.js.map","/*\n * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with\n * the License. A copy of the License is located at\n *\n * http://aws.amazon.com/apache2.0/\n *\n * or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions\n * and limitations under the License.\n */\nvar __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nimport { ConsoleLogger as Logger, Parser } from '@aws-amplify/core';\nimport { AWSS3Provider } from './providers';\nimport axios from 'axios';\nimport { AWSS3UploadTask } from './providers/AWSS3UploadTask';\nvar logger = new Logger('StorageClass');\nvar DEFAULT_PROVIDER = 'AWSS3';\n/**\n * Provide storage methods to use AWS S3\n */\nvar Storage = /** @class */ (function () {\n /**\n * Initialize Storage\n * @param {Object} config - Configuration object for storage\n */\n function Storage() {\n this._config = {};\n this._pluggables = [];\n this._cancelTokenSourceMap = new WeakMap();\n logger.debug('Storage Options', this._config);\n this.get = this.get.bind(this);\n this.put = this.put.bind(this);\n this.remove = this.remove.bind(this);\n this.list = this.list.bind(this);\n }\n Storage.prototype.getModuleName = function () {\n return 'Storage';\n };\n /**\n * add plugin into Storage category\n * @param {Object} pluggable - an instance of the plugin\n */\n Storage.prototype.addPluggable = function (pluggable) {\n if (pluggable && pluggable.getCategory() === 'Storage') {\n this._pluggables.push(pluggable);\n var config = {};\n config = pluggable.configure(this._config[pluggable.getProviderName()]);\n return config;\n }\n };\n /**\n * Get the plugin object\n * @param providerName - the name of the plugin\n */\n Storage.prototype.getPluggable = function (providerName) {\n var pluggable = this._pluggables.find(function (pluggable) { return pluggable.getProviderName() === providerName; });\n if (pluggable === undefined) {\n logger.debug('No plugin found with providerName', providerName);\n return null;\n }\n else\n return pluggable;\n };\n /**\n * Remove the plugin object\n * @param providerName - the name of the plugin\n */\n Storage.prototype.removePluggable = function (providerName) {\n this._pluggables = this._pluggables.filter(function (pluggable) { return pluggable.getProviderName() !== providerName; });\n return;\n };\n /**\n * Configure Storage\n * @param {Object} config - Configuration object for storage\n * @return {Object} - Current configuration\n */\n Storage.prototype.configure = function (config) {\n var _this = this;\n logger.debug('configure Storage');\n if (!config)\n return this._config;\n var amplifyConfig = Parser.parseMobilehubConfig(config);\n var storageKeysFromConfig = Object.keys(amplifyConfig.Storage);\n var storageArrayKeys = [\n 'bucket',\n 'region',\n 'level',\n 'track',\n 'customPrefix',\n 'serverSideEncryption',\n 'SSECustomerAlgorithm',\n 'SSECustomerKey',\n 'SSECustomerKeyMD5',\n 'SSEKMSKeyId',\n ];\n var isInStorageArrayKeys = function (k) {\n return storageArrayKeys.some(function (x) { return x === k; });\n };\n var checkConfigKeysFromArray = function (k) {\n return k.find(function (k) { return isInStorageArrayKeys(k); });\n };\n if (storageKeysFromConfig &&\n checkConfigKeysFromArray(storageKeysFromConfig) &&\n !amplifyConfig.Storage[DEFAULT_PROVIDER]) {\n amplifyConfig.Storage[DEFAULT_PROVIDER] = {};\n }\n Object.entries(amplifyConfig.Storage).map(function (_a) {\n var _b = __read(_a, 2), key = _b[0], value = _b[1];\n if (key && isInStorageArrayKeys(key) && value !== undefined) {\n amplifyConfig.Storage[DEFAULT_PROVIDER][key] = value;\n delete amplifyConfig.Storage[key];\n }\n });\n // only update new values for each provider\n Object.keys(amplifyConfig.Storage).forEach(function (providerName) {\n if (typeof amplifyConfig.Storage[providerName] !== 'string') {\n _this._config[providerName] = __assign(__assign({}, _this._config[providerName]), amplifyConfig.Storage[providerName]);\n }\n });\n this._pluggables.forEach(function (pluggable) {\n pluggable.configure(_this._config[pluggable.getProviderName()]);\n });\n if (this._pluggables.length === 0) {\n this.addPluggable(new AWSS3Provider());\n }\n return this._config;\n };\n Storage.prototype.getCancellableTokenSource = function () {\n return axios.CancelToken.source();\n };\n Storage.prototype.updateRequestToBeCancellable = function (request, cancelTokenSource) {\n this._cancelTokenSourceMap.set(request, cancelTokenSource);\n };\n Storage.prototype.isUploadTask = function (x) {\n return (typeof x !== 'undefined' &&\n typeof x['pause'] === 'function' &&\n typeof x['resume'] === 'function');\n };\n Storage.prototype.cancel = function (request, message) {\n if (request instanceof AWSS3UploadTask) {\n return request._cancel();\n }\n var cancelTokenSource = this._cancelTokenSourceMap.get(request);\n if (cancelTokenSource) {\n cancelTokenSource.cancel(message);\n }\n else {\n logger.debug('The request does not map to any cancel token');\n }\n };\n Storage.prototype.copy = function (src, dest, config) {\n var provider = (config === null || config === void 0 ? void 0 : config.provider) || DEFAULT_PROVIDER;\n var prov = this._pluggables.find(function (pluggable) { return pluggable.getProviderName() === provider; });\n if (prov === undefined) {\n logger.debug('No plugin found with providerName', provider);\n return Promise.reject('No plugin found in Storage for the provider');\n }\n var cancelTokenSource = this.getCancellableTokenSource();\n if (typeof prov.copy !== 'function') {\n return Promise.reject(\".copy is not implemented on provider \" + prov.getProviderName());\n }\n var responsePromise = prov.copy(src, dest, __assign(__assign({}, config), { cancelTokenSource: cancelTokenSource }));\n this.updateRequestToBeCancellable(responsePromise, cancelTokenSource);\n return responsePromise;\n };\n Storage.prototype.get = function (key, config) {\n var provider = (config === null || config === void 0 ? void 0 : config.provider) || DEFAULT_PROVIDER;\n var prov = this._pluggables.find(function (pluggable) { return pluggable.getProviderName() === provider; });\n if (prov === undefined) {\n logger.debug('No plugin found with providerName', provider);\n return Promise.reject('No plugin found in Storage for the provider');\n }\n var cancelTokenSource = this.getCancellableTokenSource();\n var responsePromise = prov.get(key, __assign(__assign({}, config), { cancelTokenSource: cancelTokenSource }));\n this.updateRequestToBeCancellable(responsePromise, cancelTokenSource);\n return responsePromise;\n };\n Storage.prototype.isCancelError = function (error) {\n return axios.isCancel(error);\n };\n Storage.prototype.put = function (key, object, config) {\n var provider = (config === null || config === void 0 ? void 0 : config.provider) || DEFAULT_PROVIDER;\n var prov = this._pluggables.find(function (pluggable) { return pluggable.getProviderName() === provider; });\n if (prov === undefined) {\n logger.debug('No plugin found with providerName', provider);\n return Promise.reject('No plugin found in Storage for the provider');\n }\n var cancelTokenSource = this.getCancellableTokenSource();\n var response = prov.put(key, object, __assign(__assign({}, config), { cancelTokenSource: cancelTokenSource }));\n if (!this.isUploadTask(response)) {\n this.updateRequestToBeCancellable(response, cancelTokenSource);\n }\n return response;\n };\n Storage.prototype.remove = function (key, config) {\n var provider = (config === null || config === void 0 ? void 0 : config.provider) || DEFAULT_PROVIDER;\n var prov = this._pluggables.find(function (pluggable) { return pluggable.getProviderName() === provider; });\n if (prov === undefined) {\n logger.debug('No plugin found with providerName', provider);\n return Promise.reject('No plugin found in Storage for the provider');\n }\n return prov.remove(key, config);\n };\n Storage.prototype.list = function (path, config) {\n var provider = (config === null || config === void 0 ? void 0 : config.provider) || DEFAULT_PROVIDER;\n var prov = this._pluggables.find(function (pluggable) { return pluggable.getProviderName() === provider; });\n if (prov === undefined) {\n logger.debug('No plugin found with providerName', provider);\n return Promise.reject('No plugin found in Storage for the provider');\n }\n return prov.list(path, config);\n };\n return Storage;\n}());\nexport { Storage };\n/**\n * @deprecated use named import\n */\nexport default Storage;\n//# sourceMappingURL=Storage.js.map","/*\n * Copyright 2019-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with\n * the License. A copy of the License is located at\n *\n * http://aws.amazon.com/apache2.0/\n *\n * or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions\n * and limitations under the License.\n */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { ConsoleLogger as Logger } from '@aws-amplify/core';\nimport { AuthErrorStrings } from './common/AuthErrorStrings';\nvar logger = new Logger('AuthError');\nvar AuthError = /** @class */ (function (_super) {\n __extends(AuthError, _super);\n function AuthError(type) {\n var _this = this;\n var _a = authErrorMessages[type], message = _a.message, log = _a.log;\n _this = _super.call(this, message) || this;\n // Hack for making the custom error class work when transpiled to es5\n // TODO: Delete the following 2 lines after we change the build target to >= es2015\n _this.constructor = AuthError;\n Object.setPrototypeOf(_this, AuthError.prototype);\n _this.name = 'AuthError';\n _this.log = log || message;\n logger.error(_this.log);\n return _this;\n }\n return AuthError;\n}(Error));\nexport { AuthError };\nvar NoUserPoolError = /** @class */ (function (_super) {\n __extends(NoUserPoolError, _super);\n function NoUserPoolError(type) {\n var _this = _super.call(this, type) || this;\n // Hack for making the custom error class work when transpiled to es5\n // TODO: Delete the following 2 lines after we change the build target to >= es2015\n _this.constructor = NoUserPoolError;\n Object.setPrototypeOf(_this, NoUserPoolError.prototype);\n _this.name = 'NoUserPoolError';\n return _this;\n }\n return NoUserPoolError;\n}(AuthError));\nexport { NoUserPoolError };\nexport var authErrorMessages = {\n noConfig: {\n message: AuthErrorStrings.DEFAULT_MSG,\n log: \"\\n Error: Amplify has not been configured correctly.\\n This error is typically caused by one of the following scenarios:\\n\\n 1. Make sure you're passing the awsconfig object to Amplify.configure() in your app's entry point\\n See https://aws-amplify.github.io/docs/js/authentication#configure-your-app for more information\\n \\n 2. There might be multiple conflicting versions of amplify packages in your node_modules.\\n\\t\\t\\t\\tRefer to our docs site for help upgrading Amplify packages (https://docs.amplify.aws/lib/troubleshooting/upgrading/q/platform/js)\\n \",\n },\n missingAuthConfig: {\n message: AuthErrorStrings.DEFAULT_MSG,\n log: \"\\n Error: Amplify has not been configured correctly. \\n The configuration object is missing required auth properties.\\n This error is typically caused by one of the following scenarios:\\n\\n 1. Did you run `amplify push` after adding auth via `amplify add auth`?\\n See https://aws-amplify.github.io/docs/js/authentication#amplify-project-setup for more information\\n\\n 2. This could also be caused by multiple conflicting versions of amplify packages, see (https://docs.amplify.aws/lib/troubleshooting/upgrading/q/platform/js) for help upgrading Amplify packages.\\n \",\n },\n emptyUsername: {\n message: AuthErrorStrings.EMPTY_USERNAME,\n },\n // TODO: should include a list of valid sign-in types\n invalidUsername: {\n message: AuthErrorStrings.INVALID_USERNAME,\n },\n emptyPassword: {\n message: AuthErrorStrings.EMPTY_PASSWORD,\n },\n emptyCode: {\n message: AuthErrorStrings.EMPTY_CODE,\n },\n signUpError: {\n message: AuthErrorStrings.SIGN_UP_ERROR,\n log: 'The first parameter should either be non-null string or object',\n },\n noMFA: {\n message: AuthErrorStrings.NO_MFA,\n },\n invalidMFA: {\n message: AuthErrorStrings.INVALID_MFA,\n },\n emptyChallengeResponse: {\n message: AuthErrorStrings.EMPTY_CHALLENGE,\n },\n noUserSession: {\n message: AuthErrorStrings.NO_USER_SESSION,\n },\n deviceConfig: {\n message: AuthErrorStrings.DEVICE_CONFIG,\n },\n networkError: {\n message: AuthErrorStrings.NETWORK_ERROR,\n },\n default: {\n message: AuthErrorStrings.DEFAULT_MSG,\n },\n};\n//# sourceMappingURL=Errors.js.map","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar punycode = require('punycode');\nvar util = require('./util');\n\nexports.parse = urlParse;\nexports.resolve = urlResolve;\nexports.resolveObject = urlResolveObject;\nexports.format = urlFormat;\n\nexports.Url = Url;\n\nfunction Url() {\n this.protocol = null;\n this.slashes = null;\n this.auth = null;\n this.host = null;\n this.port = null;\n this.hostname = null;\n this.hash = null;\n this.search = null;\n this.query = null;\n this.pathname = null;\n this.path = null;\n this.href = null;\n}\n\n// Reference: RFC 3986, RFC 1808, RFC 2396\n\n// define these here so at least they only have to be\n// compiled once on the first module load.\nvar protocolPattern = /^([a-z0-9.+-]+:)/i,\n portPattern = /:[0-9]*$/,\n\n // Special case for a simple path URL\n simplePathPattern = /^(\\/\\/?(?!\\/)[^\\?\\s]*)(\\?[^\\s]*)?$/,\n\n // RFC 2396: characters reserved for delimiting URLs.\n // We actually just auto-escape these.\n delims = ['<', '>', '\"', '`', ' ', '\\r', '\\n', '\\t'],\n\n // RFC 2396: characters not allowed for various reasons.\n unwise = ['{', '}', '|', '\\\\', '^', '`'].concat(delims),\n\n // Allowed by RFCs, but cause of XSS attacks. Always escape these.\n autoEscape = ['\\''].concat(unwise),\n // Characters that are never ever allowed in a hostname.\n // Note that any invalid chars are also handled, but these\n // are the ones that are *expected* to be seen, so we fast-path\n // them.\n nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),\n hostEndingChars = ['/', '?', '#'],\n hostnameMaxLen = 255,\n hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,\n hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,\n // protocols that can allow \"unsafe\" and \"unwise\" chars.\n unsafeProtocol = {\n 'javascript': true,\n 'javascript:': true\n },\n // protocols that never have a hostname.\n hostlessProtocol = {\n 'javascript': true,\n 'javascript:': true\n },\n // protocols that always contain a // bit.\n slashedProtocol = {\n 'http': true,\n 'https': true,\n 'ftp': true,\n 'gopher': true,\n 'file': true,\n 'http:': true,\n 'https:': true,\n 'ftp:': true,\n 'gopher:': true,\n 'file:': true\n },\n querystring = require('querystring');\n\nfunction urlParse(url, parseQueryString, slashesDenoteHost) {\n if (url && util.isObject(url) && url instanceof Url) return url;\n\n var u = new Url;\n u.parse(url, parseQueryString, slashesDenoteHost);\n return u;\n}\n\nUrl.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {\n if (!util.isString(url)) {\n throw new TypeError(\"Parameter 'url' must be a string, not \" + typeof url);\n }\n\n // Copy chrome, IE, opera backslash-handling behavior.\n // Back slashes before the query string get converted to forward slashes\n // See: https://code.google.com/p/chromium/issues/detail?id=25916\n var queryIndex = url.indexOf('?'),\n splitter =\n (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',\n uSplit = url.split(splitter),\n slashRegex = /\\\\/g;\n uSplit[0] = uSplit[0].replace(slashRegex, '/');\n url = uSplit.join(splitter);\n\n var rest = url;\n\n // trim before proceeding.\n // This is to support parse stuff like \" http://foo.com \\n\"\n rest = rest.trim();\n\n if (!slashesDenoteHost && url.split('#').length === 1) {\n // Try fast path regexp\n var simplePath = simplePathPattern.exec(rest);\n if (simplePath) {\n this.path = rest;\n this.href = rest;\n this.pathname = simplePath[1];\n if (simplePath[2]) {\n this.search = simplePath[2];\n if (parseQueryString) {\n this.query = querystring.parse(this.search.substr(1));\n } else {\n this.query = this.search.substr(1);\n }\n } else if (parseQueryString) {\n this.search = '';\n this.query = {};\n }\n return this;\n }\n }\n\n var proto = protocolPattern.exec(rest);\n if (proto) {\n proto = proto[0];\n var lowerProto = proto.toLowerCase();\n this.protocol = lowerProto;\n rest = rest.substr(proto.length);\n }\n\n // figure out if it's got a host\n // user@server is *always* interpreted as a hostname, and url\n // resolution will treat //foo/bar as host=foo,path=bar because that's\n // how the browser resolves relative URLs.\n if (slashesDenoteHost || proto || rest.match(/^\\/\\/[^@\\/]+@[^@\\/]+/)) {\n var slashes = rest.substr(0, 2) === '//';\n if (slashes && !(proto && hostlessProtocol[proto])) {\n rest = rest.substr(2);\n this.slashes = true;\n }\n }\n\n if (!hostlessProtocol[proto] &&\n (slashes || (proto && !slashedProtocol[proto]))) {\n\n // there's a hostname.\n // the first instance of /, ?, ;, or # ends the host.\n //\n // If there is an @ in the hostname, then non-host chars *are* allowed\n // to the left of the last @ sign, unless some host-ending character\n // comes *before* the @-sign.\n // URLs are obnoxious.\n //\n // ex:\n // http://a@b@c/ => user:a@b host:c\n // http://a@b?@c => user:a host:c path:/?@c\n\n // v0.12 TODO(isaacs): This is not quite how Chrome does things.\n // Review our test case against browsers more comprehensively.\n\n // find the first instance of any hostEndingChars\n var hostEnd = -1;\n for (var i = 0; i < hostEndingChars.length; i++) {\n var hec = rest.indexOf(hostEndingChars[i]);\n if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))\n hostEnd = hec;\n }\n\n // at this point, either we have an explicit point where the\n // auth portion cannot go past, or the last @ char is the decider.\n var auth, atSign;\n if (hostEnd === -1) {\n // atSign can be anywhere.\n atSign = rest.lastIndexOf('@');\n } else {\n // atSign must be in auth portion.\n // http://a@b/c@d => host:b auth:a path:/c@d\n atSign = rest.lastIndexOf('@', hostEnd);\n }\n\n // Now we have a portion which is definitely the auth.\n // Pull that off.\n if (atSign !== -1) {\n auth = rest.slice(0, atSign);\n rest = rest.slice(atSign + 1);\n this.auth = decodeURIComponent(auth);\n }\n\n // the host is the remaining to the left of the first non-host char\n hostEnd = -1;\n for (var i = 0; i < nonHostChars.length; i++) {\n var hec = rest.indexOf(nonHostChars[i]);\n if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))\n hostEnd = hec;\n }\n // if we still have not hit it, then the entire thing is a host.\n if (hostEnd === -1)\n hostEnd = rest.length;\n\n this.host = rest.slice(0, hostEnd);\n rest = rest.slice(hostEnd);\n\n // pull out port.\n this.parseHost();\n\n // we've indicated that there is a hostname,\n // so even if it's empty, it has to be present.\n this.hostname = this.hostname || '';\n\n // if hostname begins with [ and ends with ]\n // assume that it's an IPv6 address.\n var ipv6Hostname = this.hostname[0] === '[' &&\n this.hostname[this.hostname.length - 1] === ']';\n\n // validate a little.\n if (!ipv6Hostname) {\n var hostparts = this.hostname.split(/\\./);\n for (var i = 0, l = hostparts.length; i < l; i++) {\n var part = hostparts[i];\n if (!part) continue;\n if (!part.match(hostnamePartPattern)) {\n var newpart = '';\n for (var j = 0, k = part.length; j < k; j++) {\n if (part.charCodeAt(j) > 127) {\n // we replace non-ASCII char with a temporary placeholder\n // we need this to make sure size of hostname is not\n // broken by replacing non-ASCII by nothing\n newpart += 'x';\n } else {\n newpart += part[j];\n }\n }\n // we test again with ASCII char only\n if (!newpart.match(hostnamePartPattern)) {\n var validParts = hostparts.slice(0, i);\n var notHost = hostparts.slice(i + 1);\n var bit = part.match(hostnamePartStart);\n if (bit) {\n validParts.push(bit[1]);\n notHost.unshift(bit[2]);\n }\n if (notHost.length) {\n rest = '/' + notHost.join('.') + rest;\n }\n this.hostname = validParts.join('.');\n break;\n }\n }\n }\n }\n\n if (this.hostname.length > hostnameMaxLen) {\n this.hostname = '';\n } else {\n // hostnames are always lower case.\n this.hostname = this.hostname.toLowerCase();\n }\n\n if (!ipv6Hostname) {\n // IDNA Support: Returns a punycoded representation of \"domain\".\n // It only converts parts of the domain name that\n // have non-ASCII characters, i.e. it doesn't matter if\n // you call it with a domain that already is ASCII-only.\n this.hostname = punycode.toASCII(this.hostname);\n }\n\n var p = this.port ? ':' + this.port : '';\n var h = this.hostname || '';\n this.host = h + p;\n this.href += this.host;\n\n // strip [ and ] from the hostname\n // the host field still retains them, though\n if (ipv6Hostname) {\n this.hostname = this.hostname.substr(1, this.hostname.length - 2);\n if (rest[0] !== '/') {\n rest = '/' + rest;\n }\n }\n }\n\n // now rest is set to the post-host stuff.\n // chop off any delim chars.\n if (!unsafeProtocol[lowerProto]) {\n\n // First, make 100% sure that any \"autoEscape\" chars get\n // escaped, even if encodeURIComponent doesn't think they\n // need to be.\n for (var i = 0, l = autoEscape.length; i < l; i++) {\n var ae = autoEscape[i];\n if (rest.indexOf(ae) === -1)\n continue;\n var esc = encodeURIComponent(ae);\n if (esc === ae) {\n esc = escape(ae);\n }\n rest = rest.split(ae).join(esc);\n }\n }\n\n\n // chop off from the tail first.\n var hash = rest.indexOf('#');\n if (hash !== -1) {\n // got a fragment string.\n this.hash = rest.substr(hash);\n rest = rest.slice(0, hash);\n }\n var qm = rest.indexOf('?');\n if (qm !== -1) {\n this.search = rest.substr(qm);\n this.query = rest.substr(qm + 1);\n if (parseQueryString) {\n this.query = querystring.parse(this.query);\n }\n rest = rest.slice(0, qm);\n } else if (parseQueryString) {\n // no query string, but parseQueryString still requested\n this.search = '';\n this.query = {};\n }\n if (rest) this.pathname = rest;\n if (slashedProtocol[lowerProto] &&\n this.hostname && !this.pathname) {\n this.pathname = '/';\n }\n\n //to support http.request\n if (this.pathname || this.search) {\n var p = this.pathname || '';\n var s = this.search || '';\n this.path = p + s;\n }\n\n // finally, reconstruct the href based on what has been validated.\n this.href = this.format();\n return this;\n};\n\n// format a parsed object into a url string\nfunction urlFormat(obj) {\n // ensure it's an object, and not a string url.\n // If it's an obj, this is a no-op.\n // this way, you can call url_format() on strings\n // to clean up potentially wonky urls.\n if (util.isString(obj)) obj = urlParse(obj);\n if (!(obj instanceof Url)) return Url.prototype.format.call(obj);\n return obj.format();\n}\n\nUrl.prototype.format = function() {\n var auth = this.auth || '';\n if (auth) {\n auth = encodeURIComponent(auth);\n auth = auth.replace(/%3A/i, ':');\n auth += '@';\n }\n\n var protocol = this.protocol || '',\n pathname = this.pathname || '',\n hash = this.hash || '',\n host = false,\n query = '';\n\n if (this.host) {\n host = auth + this.host;\n } else if (this.hostname) {\n host = auth + (this.hostname.indexOf(':') === -1 ?\n this.hostname :\n '[' + this.hostname + ']');\n if (this.port) {\n host += ':' + this.port;\n }\n }\n\n if (this.query &&\n util.isObject(this.query) &&\n Object.keys(this.query).length) {\n query = querystring.stringify(this.query);\n }\n\n var search = this.search || (query && ('?' + query)) || '';\n\n if (protocol && protocol.substr(-1) !== ':') protocol += ':';\n\n // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.\n // unless they had them to begin with.\n if (this.slashes ||\n (!protocol || slashedProtocol[protocol]) && host !== false) {\n host = '//' + (host || '');\n if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;\n } else if (!host) {\n host = '';\n }\n\n if (hash && hash.charAt(0) !== '#') hash = '#' + hash;\n if (search && search.charAt(0) !== '?') search = '?' + search;\n\n pathname = pathname.replace(/[?#]/g, function(match) {\n return encodeURIComponent(match);\n });\n search = search.replace('#', '%23');\n\n return protocol + host + pathname + search + hash;\n};\n\nfunction urlResolve(source, relative) {\n return urlParse(source, false, true).resolve(relative);\n}\n\nUrl.prototype.resolve = function(relative) {\n return this.resolveObject(urlParse(relative, false, true)).format();\n};\n\nfunction urlResolveObject(source, relative) {\n if (!source) return relative;\n return urlParse(source, false, true).resolveObject(relative);\n}\n\nUrl.prototype.resolveObject = function(relative) {\n if (util.isString(relative)) {\n var rel = new Url();\n rel.parse(relative, false, true);\n relative = rel;\n }\n\n var result = new Url();\n var tkeys = Object.keys(this);\n for (var tk = 0; tk < tkeys.length; tk++) {\n var tkey = tkeys[tk];\n result[tkey] = this[tkey];\n }\n\n // hash is always overridden, no matter what.\n // even href=\"\" will remove it.\n result.hash = relative.hash;\n\n // if the relative url is empty, then there's nothing left to do here.\n if (relative.href === '') {\n result.href = result.format();\n return result;\n }\n\n // hrefs like //foo/bar always cut to the protocol.\n if (relative.slashes && !relative.protocol) {\n // take everything except the protocol from relative\n var rkeys = Object.keys(relative);\n for (var rk = 0; rk < rkeys.length; rk++) {\n var rkey = rkeys[rk];\n if (rkey !== 'protocol')\n result[rkey] = relative[rkey];\n }\n\n //urlParse appends trailing / to urls like http://www.example.com\n if (slashedProtocol[result.protocol] &&\n result.hostname && !result.pathname) {\n result.path = result.pathname = '/';\n }\n\n result.href = result.format();\n return result;\n }\n\n if (relative.protocol && relative.protocol !== result.protocol) {\n // if it's a known url protocol, then changing\n // the protocol does weird things\n // first, if it's not file:, then we MUST have a host,\n // and if there was a path\n // to begin with, then we MUST have a path.\n // if it is file:, then the host is dropped,\n // because that's known to be hostless.\n // anything else is assumed to be absolute.\n if (!slashedProtocol[relative.protocol]) {\n var keys = Object.keys(relative);\n for (var v = 0; v < keys.length; v++) {\n var k = keys[v];\n result[k] = relative[k];\n }\n result.href = result.format();\n return result;\n }\n\n result.protocol = relative.protocol;\n if (!relative.host && !hostlessProtocol[relative.protocol]) {\n var relPath = (relative.pathname || '').split('/');\n while (relPath.length && !(relative.host = relPath.shift()));\n if (!relative.host) relative.host = '';\n if (!relative.hostname) relative.hostname = '';\n if (relPath[0] !== '') relPath.unshift('');\n if (relPath.length < 2) relPath.unshift('');\n result.pathname = relPath.join('/');\n } else {\n result.pathname = relative.pathname;\n }\n result.search = relative.search;\n result.query = relative.query;\n result.host = relative.host || '';\n result.auth = relative.auth;\n result.hostname = relative.hostname || relative.host;\n result.port = relative.port;\n // to support http.request\n if (result.pathname || result.search) {\n var p = result.pathname || '';\n var s = result.search || '';\n result.path = p + s;\n }\n result.slashes = result.slashes || relative.slashes;\n result.href = result.format();\n return result;\n }\n\n var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),\n isRelAbs = (\n relative.host ||\n relative.pathname && relative.pathname.charAt(0) === '/'\n ),\n mustEndAbs = (isRelAbs || isSourceAbs ||\n (result.host && relative.pathname)),\n removeAllDots = mustEndAbs,\n srcPath = result.pathname && result.pathname.split('/') || [],\n relPath = relative.pathname && relative.pathname.split('/') || [],\n psychotic = result.protocol && !slashedProtocol[result.protocol];\n\n // if the url is a non-slashed url, then relative\n // links like ../.. should be able\n // to crawl up to the hostname, as well. This is strange.\n // result.protocol has already been set by now.\n // Later on, put the first path part into the host field.\n if (psychotic) {\n result.hostname = '';\n result.port = null;\n if (result.host) {\n if (srcPath[0] === '') srcPath[0] = result.host;\n else srcPath.unshift(result.host);\n }\n result.host = '';\n if (relative.protocol) {\n relative.hostname = null;\n relative.port = null;\n if (relative.host) {\n if (relPath[0] === '') relPath[0] = relative.host;\n else relPath.unshift(relative.host);\n }\n relative.host = null;\n }\n mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');\n }\n\n if (isRelAbs) {\n // it's absolute.\n result.host = (relative.host || relative.host === '') ?\n relative.host : result.host;\n result.hostname = (relative.hostname || relative.hostname === '') ?\n relative.hostname : result.hostname;\n result.search = relative.search;\n result.query = relative.query;\n srcPath = relPath;\n // fall through to the dot-handling below.\n } else if (relPath.length) {\n // it's relative\n // throw away the existing file, and take the new path instead.\n if (!srcPath) srcPath = [];\n srcPath.pop();\n srcPath = srcPath.concat(relPath);\n result.search = relative.search;\n result.query = relative.query;\n } else if (!util.isNullOrUndefined(relative.search)) {\n // just pull out the search.\n // like href='?foo'.\n // Put this after the other two cases because it simplifies the booleans\n if (psychotic) {\n result.hostname = result.host = srcPath.shift();\n //occationaly the auth can get stuck only in host\n //this especially happens in cases like\n //url.resolveObject('mailto:local1@domain1', 'local2@domain2')\n var authInHost = result.host && result.host.indexOf('@') > 0 ?\n result.host.split('@') : false;\n if (authInHost) {\n result.auth = authInHost.shift();\n result.host = result.hostname = authInHost.shift();\n }\n }\n result.search = relative.search;\n result.query = relative.query;\n //to support http.request\n if (!util.isNull(result.pathname) || !util.isNull(result.search)) {\n result.path = (result.pathname ? result.pathname : '') +\n (result.search ? result.search : '');\n }\n result.href = result.format();\n return result;\n }\n\n if (!srcPath.length) {\n // no path at all. easy.\n // we've already handled the other stuff above.\n result.pathname = null;\n //to support http.request\n if (result.search) {\n result.path = '/' + result.search;\n } else {\n result.path = null;\n }\n result.href = result.format();\n return result;\n }\n\n // if a url ENDs in . or .., then it must get a trailing slash.\n // however, if it ends in anything else non-slashy,\n // then it must NOT get a trailing slash.\n var last = srcPath.slice(-1)[0];\n var hasTrailingSlash = (\n (result.host || relative.host || srcPath.length > 1) &&\n (last === '.' || last === '..') || last === '');\n\n // strip single dots, resolve double dots to parent dir\n // if the path tries to go above the root, `up` ends up > 0\n var up = 0;\n for (var i = srcPath.length; i >= 0; i--) {\n last = srcPath[i];\n if (last === '.') {\n srcPath.splice(i, 1);\n } else if (last === '..') {\n srcPath.splice(i, 1);\n up++;\n } else if (up) {\n srcPath.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (!mustEndAbs && !removeAllDots) {\n for (; up--; up) {\n srcPath.unshift('..');\n }\n }\n\n if (mustEndAbs && srcPath[0] !== '' &&\n (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {\n srcPath.unshift('');\n }\n\n if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {\n srcPath.push('');\n }\n\n var isAbsolute = srcPath[0] === '' ||\n (srcPath[0] && srcPath[0].charAt(0) === '/');\n\n // put the host back\n if (psychotic) {\n result.hostname = result.host = isAbsolute ? '' :\n srcPath.length ? srcPath.shift() : '';\n //occationaly the auth can get stuck only in host\n //this especially happens in cases like\n //url.resolveObject('mailto:local1@domain1', 'local2@domain2')\n var authInHost = result.host && result.host.indexOf('@') > 0 ?\n result.host.split('@') : false;\n if (authInHost) {\n result.auth = authInHost.shift();\n result.host = result.hostname = authInHost.shift();\n }\n }\n\n mustEndAbs = mustEndAbs || (result.host && srcPath.length);\n\n if (mustEndAbs && !isAbsolute) {\n srcPath.unshift('');\n }\n\n if (!srcPath.length) {\n result.pathname = null;\n result.path = null;\n } else {\n result.pathname = srcPath.join('/');\n }\n\n //to support request.http\n if (!util.isNull(result.pathname) || !util.isNull(result.search)) {\n result.path = (result.pathname ? result.pathname : '') +\n (result.search ? result.search : '');\n }\n result.auth = relative.auth || result.auth;\n result.slashes = result.slashes || relative.slashes;\n result.href = result.format();\n return result;\n};\n\nUrl.prototype.parseHost = function() {\n var host = this.host;\n var port = portPattern.exec(host);\n if (port) {\n port = port[0];\n if (port !== ':') {\n this.port = port.substr(1);\n }\n host = host.substr(0, host.length - port.length);\n }\n if (host) this.hostname = host;\n};\n","var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nimport { ConsoleLogger as LoggerClass } from './Logger';\nvar logger = new LoggerClass('Amplify');\nvar AmplifyClass = /** @class */ (function () {\n function AmplifyClass() {\n // Everything that is `register`ed is tracked here\n this._components = [];\n this._config = {};\n // All modules (with `getModuleName()`) are stored here for dependency injection\n this._modules = {};\n // for backward compatibility to avoid breaking change\n // if someone is using like Amplify.Auth\n this.Auth = null;\n this.Analytics = null;\n this.API = null;\n this.Credentials = null;\n this.Storage = null;\n this.I18n = null;\n this.Cache = null;\n this.PubSub = null;\n this.Interactions = null;\n this.Pushnotification = null;\n this.UI = null;\n this.XR = null;\n this.Predictions = null;\n this.DataStore = null;\n this.Geo = null;\n this.Logger = LoggerClass;\n this.ServiceWorker = null;\n }\n AmplifyClass.prototype.register = function (comp) {\n logger.debug('component registered in amplify', comp);\n this._components.push(comp);\n if (typeof comp.getModuleName === 'function') {\n this._modules[comp.getModuleName()] = comp;\n this[comp.getModuleName()] = comp;\n }\n else {\n logger.debug('no getModuleName method for component', comp);\n }\n // Finally configure this new component(category) loaded\n // With the new modularization changes in Amplify V3, all the Amplify\n // component are not loaded/registered right away but when they are\n // imported (and hence instantiated) in the client's app. This ensures\n // that all new components imported get correctly configured with the\n // configuration that Amplify.configure() was called with.\n comp.configure(this._config);\n };\n AmplifyClass.prototype.configure = function (config) {\n var _this = this;\n if (!config)\n return this._config;\n this._config = Object.assign(this._config, config);\n logger.debug('amplify config', this._config);\n // Dependency Injection via property-setting.\n // This avoids introducing a public method/interface/setter that's difficult to remove later.\n // Plus, it reduces `if` statements within the `constructor` and `configure` of each module\n Object.entries(this._modules).forEach(function (_a) {\n var _b = __read(_a, 2), Name = _b[0], comp = _b[1];\n // e.g. Auth.*\n Object.keys(comp).forEach(function (property) {\n // e.g. Auth[\"Credentials\"] = this._modules[\"Credentials\"] when set\n if (_this._modules[property]) {\n comp[property] = _this._modules[property];\n }\n });\n });\n this._components.map(function (comp) {\n comp.configure(_this._config);\n });\n return this._config;\n };\n AmplifyClass.prototype.addPluggable = function (pluggable) {\n if (pluggable &&\n pluggable['getCategory'] &&\n typeof pluggable['getCategory'] === 'function') {\n this._components.map(function (comp) {\n if (comp['addPluggable'] &&\n typeof comp['addPluggable'] === 'function') {\n comp.addPluggable(pluggable);\n }\n });\n }\n };\n return AmplifyClass;\n}());\nexport { AmplifyClass };\nexport var Amplify = new AmplifyClass();\n/**\n * @deprecated use named import\n */\nexport default Amplify;\n//# sourceMappingURL=Amplify.js.map","import {\n AbsoluteLocation,\n FinalizeHandler,\n FinalizeHandlerArguments,\n FinalizeHandlerOutput,\n FinalizeRequestHandlerOptions,\n HandlerExecutionContext,\n MetadataBearer,\n Pluggable,\n} from \"@aws-sdk/types\";\n\nimport { RetryResolvedConfig } from \"./configurations\";\n\nexport const retryMiddleware = (options: RetryResolvedConfig) =>