From 23a1efd4deb914fdb8a63bbec416609cb877c9fa Mon Sep 17 00:00:00 2001 From: carsonxu <459452372@qq.com> Date: Wed, 3 Feb 2021 20:47:14 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A7=84=E8=8C=83=E9=94=99=E8=AF=AF=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + demo/demo.js | 8 +- dist/cos-js-sdk-v5.js | 2619 +++++++++++++++++++++++++++++++++---- dist/cos-js-sdk-v5.min.js | 9 +- lib/request.js | 2 +- package.json | 2 +- src/advance.js | 114 +- src/base.js | 246 ++-- src/cos.js | 6 +- src/session.js | 10 +- src/task.js | 5 +- src/util.js | 100 +- 12 files changed, 2634 insertions(+), 488 deletions(-) diff --git a/.gitignore b/.gitignore index aba6a35..5f35373 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ coverage node_modules package-lock.json +log.txt diff --git a/demo/demo.js b/demo/demo.js index 5d9cd02..a12060d 100644 --- a/demo/demo.js +++ b/demo/demo.js @@ -87,7 +87,7 @@ var getAuthorization = function (options, callback) { // callback({ // TmpSecretId: credentials.tmpSecretId, // TmpSecretKey: credentials.tmpSecretKey, - // XCosSecurityToken: credentials.sessionToken, + // SecurityToken: credentials.sessionToken, // StartTime: data.startTime, // 时间戳,单位秒,如:1580000000,建议返回服务器时间作为签名的开始时间,避免用户浏览器本地时间偏差过大导致签名错误 // ExpiredTime: data.expiredTime, // 时间戳,单位秒,如:1580000000 // ScopeLimit: true, // 细粒度控制权限需要设为 true,会限制密钥只在相同请求时重复使用 @@ -122,7 +122,7 @@ var getAuthorization = function (options, callback) { // if (!data || !data.authorization) return console.error('authorization invalid'); // callback({ // Authorization: data.authorization, - // // XCosSecurityToken: data.sessionToken, // 如果使用临时密钥,需要把 sessionToken 传给 XCosSecurityToken + // // SecurityToken: data.sessionToken, // 如果使用临时密钥,需要把 sessionToken 传给 SecurityToken // }); // }; // xhr.send(JSON.stringify(data)); @@ -140,7 +140,7 @@ var getAuthorization = function (options, callback) { // }); // callback({ // Authorization: authorization, - // // XCosSecurityToken: credentials.sessionToken, // 如果使用临时密钥,需要传 XCosSecurityToken + // // SecurityToken: credentials.sessionToken, // 如果使用临时密钥,需要传 SecurityToken // }); }; @@ -214,7 +214,7 @@ function getAuth() { var url = 'http://' + config.Bucket + '.cos.' + config.Region + '.myqcloud.com' + '/' + camSafeUrlEncode(key).replace(/%2F/g, '/') + '?' + AuthData + - (AuthData.XCosSecurityToken ? '&' + AuthData.XCosSecurityToken : ''); + (AuthData.SecurityToken ? '&' + AuthData.SecurityToken : ''); logger.log(url); }); } diff --git a/dist/cos-js-sdk-v5.js b/dist/cos-js-sdk-v5.js index 9ceeda7..222ff2b 100644 --- a/dist/cos-js-sdk-v5.js +++ b/dist/cos-js-sdk-v5.js @@ -70,7 +70,7 @@ return /******/ (function(modules) { // webpackBootstrap /******/ __webpack_require__.p = "/dist/"; /******/ /******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 4); +/******/ return __webpack_require__(__webpack_require__.s = 5); /******/ }) /************************************************************************/ /******/ ([ @@ -80,7 +80,7 @@ return /******/ (function(modules) { // webpackBootstrap "use strict"; -var md5 = __webpack_require__(6); +var md5 = __webpack_require__(7); var CryptoJS = __webpack_require__(10); var xml2json = __webpack_require__(11); var json2xml = __webpack_require__(14); @@ -109,8 +109,8 @@ var getAuth = function (opt) { pathname.indexOf('/') !== 0 && (pathname = '/' + pathname); } - if (!SecretId) return console.error('missing param SecretId'); - if (!SecretKey) return console.error('missing param SecretKey'); + if (!SecretId) throw new Error('missing param SecretId'); + if (!SecretKey) throw new Error('missing param SecretKey'); var getObjectKeys = function (obj, forKey) { var list = []; @@ -178,6 +178,65 @@ var getAuth = function (opt) { return authorization; }; +var readIntBE = function (chunk, size, offset) { + var bytes = size / 8; + var buf = chunk.slice(offset, offset + bytes); + new Uint8Array(buf).reverse(); + return new { 8: Uint8Array, 16: Uint16Array, 32: Uint32Array }[size](buf)[0]; +}; +var buf2str = function (chunk, start, end, isUtf8) { + var buf = chunk.slice(start, end); + var str = ''; + new Uint8Array(buf).forEach(function (charCode) { + str += String.fromCharCode(charCode); + }); + if (isUtf8) str = decodeURIComponent(escape(str)); + return str; +}; +var parseSelectPayload = function (chunk) { + var header = {}; + var body = buf2str(chunk); + var result = { records: [] }; + while (chunk.byteLength) { + var totalLength = readIntBE(chunk, 32, 0); + var headerLength = readIntBE(chunk, 32, 4); + var payloadRestLength = totalLength - headerLength - 16; + var offset = 0; + var content; + chunk = chunk.slice(12); + // 获取 Message 的 header 信息 + while (offset < headerLength) { + var headerNameLength = readIntBE(chunk, 8, offset); + var headerName = buf2str(chunk, offset + 1, offset + 1 + headerNameLength); + var headerValueLength = readIntBE(chunk, 16, offset + headerNameLength + 2); + var headerValue = buf2str(chunk, offset + headerNameLength + 4, offset + headerNameLength + 4 + headerValueLength); + header[headerName] = headerValue; + offset += headerNameLength + 4 + headerValueLength; + } + if (header[':event-type'] === 'Records') { + content = buf2str(chunk, offset, offset + payloadRestLength, true); + result.records.push(content); + } else if (header[':event-type'] === 'Stats') { + content = buf2str(chunk, offset, offset + payloadRestLength, true); + result.stats = util.xml2json(content).Stats; + } else if (header[':event-type'] === 'error') { + var errCode = header[':error-code']; + var errMessage = header[':error-message']; + var err = new Error(errMessage); + err.message = errMessage; + err.name = err.code = errCode; + result.error = err; + } else if (['Progress', 'Continuation', 'End'].includes(header[':event-type'])) { + // do nothing + } + chunk = chunk.slice(offset + payloadRestLength + 4); + } + return { + payload: result.records.join(''), + body: body + }; +}; + var noop = function () {}; // 清除对象里值为的 undefined 或 null 的属性 @@ -460,6 +519,7 @@ var formatParams = function (apiName, params) { 'x-cos-grant-read-acp': 'GrantReadAcp', 'x-cos-grant-write-acp': 'GrantWriteAcp', 'x-cos-storage-class': 'StorageClass', + 'x-cos-traffic-limit': 'TrafficLimit', // SSE-C 'x-cos-server-side-encryption-customer-algorithm': 'SSECustomerAlgorithm', 'x-cos-server-side-encryption-customer-key': 'SSECustomerKey', @@ -499,6 +559,7 @@ var apiWrapper = function (apiName, apiFn) { // 代理回调函数 var formatResult = function (result) { if (result && result.headers) { + result.headers['x-cos-request-id'] && (result.RequestId = result.headers['x-cos-request-id']); result.headers['x-cos-version-id'] && (result.VersionId = result.headers['x-cos-version-id']); result.headers['x-cos-delete-marker'] && (result.DeleteMarker = result.headers['x-cos-delete-marker']); } @@ -557,11 +618,11 @@ var apiWrapper = function (apiName, apiFn) { callback = function (err, data) { err ? reject(err) : resolve(data); }; - if (errMsg) return _callback({ error: errMsg }); + if (errMsg) return _callback(util.error(new Error(errMsg))); apiFn.call(self, params, _callback); }); } else { - if (errMsg) return _callback({ error: errMsg }); + if (errMsg) return _callback(util.error(new Error(errMsg))); var res = apiFn.call(self, params, _callback); if (isSync) return res; } @@ -620,7 +681,7 @@ var getFileSize = function (api, params, callback) { if (params.Body && (params.Body instanceof Blob || params.Body.toString() === '[object File]' || params.Body.toString() === '[object Blob]')) { size = params.Body.size; } else { - callback({ error: 'params body format error, Only allow File|Blob|String.' }); + callback(util.error(new Error('params body format error, Only allow File|Blob|String.'))); return; } params.ContentLength = size; @@ -632,6 +693,32 @@ var getSkewTime = function (offset) { return Date.now() + (offset || 0); }; +var error = function (err, opt) { + var sourceErr = err; + err.message = err.message || null; + + if (typeof opt === 'string') { + err.error = opt; + err.message = opt; + } else if (typeof opt === 'object' && opt !== null) { + extend(err, opt); + if (opt.code || opt.name) err.code = opt.code || opt.name; + if (opt.message) err.message = opt.message; + if (opt.stack) err.stack = opt.stack; + } + + if (typeof Object.defineProperty === 'function') { + Object.defineProperty(err, 'name', { writable: true, enumerable: false }); + Object.defineProperty(err, 'message', { enumerable: true }); + } + + err.name = opt && opt.name || err.name || err.code || 'Error'; + if (!err.code) err.code = err.name; + if (!err.error) err.error = clone(sourceErr); // 兼容老的错误格式 + + return err; +}; + var util = { noop: noop, formatParams: formatParams, @@ -658,7 +745,9 @@ var util = { throttleOnProgress: throttleOnProgress, getFileSize: getFileSize, getSkewTime: getSkewTime, + error: error, getAuth: getAuth, + parseSelectPayload: parseSelectPayload, isBrowser: true }; @@ -668,6 +757,33 @@ module.exports = util; /* 1 */ /***/ (function(module, exports) { +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || Function("return this")() || (1,eval)("this"); +} catch(e) { + // This works if the window reference is available + if(typeof window === "object") + g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }), +/* 2 */ +/***/ (function(module, exports) { + /* * DOM Level 2 * Object DOMException @@ -1915,7 +2031,7 @@ try{ /***/ }), -/* 2 */ +/* 3 */ /***/ (function(module, exports) { var initEvent = function (cos) { @@ -1954,7 +2070,7 @@ module.exports.init = initEvent; module.exports.EventProxy = EventProxy; /***/ }), -/* 3 */ +/* 4 */ /***/ (function(module, exports, __webpack_require__) { var util = __webpack_require__(0); @@ -1970,7 +2086,7 @@ var getCache = function () { var val = JSON.parse(localStorage.getItem(cacheKey)); } catch (e) {} if (!val) val = []; - return val; + cache = val; }; var setCache = function () { try { @@ -1980,7 +2096,7 @@ var setCache = function () { var init = function () { if (cache) return; - cache = getCache(); + getCache.call(this); // 清理太老旧的数据 var changed = false; var now = Math.round(Date.now() / 1000); @@ -2024,7 +2140,7 @@ var mod = { // 获取文件对应的 UploadId 列表 getUploadIdList: function (uuid) { if (!uuid) return null; - init(); + init.call(this); var list = []; for (var i = 0; i < cache.length; i++) { if (cache[i][0] === uuid) list.push(cache[i][1]); @@ -2033,7 +2149,7 @@ var mod = { }, // 缓存 UploadId saveUploadId: function (uuid, UploadId, limit) { - init(); + init.call(this); if (!uuid) return; // 清理没用的 UploadId,js 文件没有 FilePath ,只清理相同记录 for (var i = cache.length - 1; i >= 0; i--) { @@ -2048,7 +2164,7 @@ var mod = { }, // UploadId 已用完,移除掉 removeUploadId: function (UploadId) { - init(); + init.call(this); delete mod.using[UploadId]; for (var i = cache.length - 1; i >= 0; i--) { if (cache[i][1] === UploadId) cache.splice(i, 1); @@ -2060,30 +2176,30 @@ var mod = { module.exports = mod; /***/ }), -/* 4 */ +/* 5 */ /***/ (function(module, exports, __webpack_require__) { -var COS = __webpack_require__(5); +var COS = __webpack_require__(6); module.exports = COS; /***/ }), -/* 5 */ +/* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var util = __webpack_require__(0); -var event = __webpack_require__(2); +var event = __webpack_require__(3); var task = __webpack_require__(15); var base = __webpack_require__(16); -var advance = __webpack_require__(18); +var advance = __webpack_require__(22); var defaultOptions = { AppId: '', // AppId 已废弃,请拼接到 Bucket 后传入,例如:test-1250000000 SecretId: '', SecretKey: '', - XCosSecurityToken: '', // 使用临时密钥需要注意自行刷新 Token + SecurityToken: '', // 使用临时密钥需要注意自行刷新 Token ChunkRetryTimes: 2, FileParallelLimit: 3, ChunkParallelLimit: 3, @@ -2094,7 +2210,6 @@ var defaultOptions = { CopySliceSize: 1024 * 1024 * 10, MaxPartNumber: 10000, ProgressInterval: 1000, - UploadQueueSize: 10000, Domain: '', ServiceDomain: '', Protocol: '', @@ -2105,6 +2220,7 @@ var defaultOptions = { CorrectClockSkew: true, SystemClockOffset: 0, // 单位毫秒,ms UploadCheckContentMd5: false, + UploadQueueSize: 10000, UploadAddMetaMd5: false, UploadIdCacheLimit: 50 }; @@ -2132,12 +2248,12 @@ base.init(COS, task); advance.init(COS, task); COS.getAuthorization = util.getAuth; -COS.version = '1.1.11'; +COS.version = '1.2.0'; module.exports = COS; /***/ }), -/* 6 */ +/* 7 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process, global) {var __WEBPACK_AMD_DEFINE_RESULT__;/* https://github.com/emn178/js-md5 */ @@ -2807,10 +2923,10 @@ module.exports = COS; } } })(); -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7), __webpack_require__(8))) +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(8), __webpack_require__(1))) /***/ }), -/* 7 */ +/* 8 */ /***/ (function(module, exports) { // shim for using process in browser @@ -2999,33 +3115,6 @@ process.chdir = function (dir) { process.umask = function() { return 0; }; -/***/ }), -/* 8 */ -/***/ (function(module, exports) { - -var g; - -// This works in non-strict mode -g = (function() { - return this; -})(); - -try { - // This works if eval is allowed (see CSP) - g = g || Function("return this")() || (1,eval)("this"); -} catch(e) { - // This works if the window reference is available - if(typeof window === "object") - g = window; -} - -// g can still be undefined, but nothing to do about it... -// We return undefined, instead of nothing here, so it's -// easier to handle this case. if(!global) { ...} - -module.exports = g; - - /***/ }), /* 9 */ /***/ (function(module, exports) { @@ -3700,8 +3789,8 @@ function appendElement (hander,node) { //if(typeof require == 'function'){ var XMLReader = __webpack_require__(13).XMLReader; - var DOMImplementation = exports.DOMImplementation = __webpack_require__(1).DOMImplementation; - exports.XMLSerializer = __webpack_require__(1).XMLSerializer ; + var DOMImplementation = exports.DOMImplementation = __webpack_require__(2).DOMImplementation; + exports.XMLSerializer = __webpack_require__(2).XMLSerializer ; exports.DOMParser = DOMParser; //} @@ -4508,7 +4597,7 @@ module.exports = function (obj, options) { /* 15 */ /***/ (function(module, exports, __webpack_require__) { -var session = __webpack_require__(3); +var session = __webpack_require__(4); var util = __webpack_require__(0); var originApiMap = {}; @@ -4719,11 +4808,7 @@ var initTask = function (cos) { // 异步获取 filesize util.getFileSize(api, params, function (err, size) { // 开始处理上传 - if (err) { - // 如果获取大小出错,不加入队列 - callback(err); - return; - } + if (err) return callback(util.error(err)); // 如果获取大小出错,不加入队列 // 获取完文件大小再把任务加入队列 tasks[id] = task; queue.push(task); @@ -4768,7 +4853,7 @@ module.exports.init = initTask; /* 16 */ /***/ (function(module, exports, __webpack_require__) { -var REQUEST = __webpack_require__(17); +/* WEBPACK VAR INJECTION */(function(Buffer) {var REQUEST = __webpack_require__(21); var util = __webpack_require__(0); // Bucket 相关 @@ -4890,9 +4975,7 @@ function headBucket(params, callback) { Region: params.Region, headers: params.Headers, method: 'HEAD' - }, function (err, data) { - callback(err, data); - }); + }, callback); } /** @@ -5218,15 +5301,17 @@ function getBucketLocation(params, callback) { Region: params.Region, headers: params.Headers, action: 'location' - }, function (err, data) { - if (err) return callback(err); - callback(null, data); - }); + }, callback); } function putBucketPolicy(params, callback) { - var PolicyStr = params['Policy']; - if (typeof PolicyStr !== 'string') PolicyStr = JSON.stringify(PolicyStr); + var Policy = params['Policy']; + try { + if (typeof Policy === 'string') Policy = JSON.parse(Policy); + } catch (e) {} + if (!Policy || typeof Policy === 'string') return callback(util.error(new Error('Policy format error'))); + var PolicyStr = JSON.stringify(Policy); + if (!Policy.version) Policy.version = '2.0'; var headers = params.Headers; headers['Content-Type'] = 'application/json'; @@ -5274,13 +5359,13 @@ function getBucketPolicy(params, callback) { }, function (err, data) { if (err) { if (err.statusCode && err.statusCode === 403) { - return callback({ ErrorStatus: 'Access Denied' }); + return callback(util.error(err, { ErrorStatus: 'Access Denied' })); } if (err.statusCode && err.statusCode === 405) { - return callback({ ErrorStatus: 'Method Not Allowed' }); + return callback(util.error(err, { ErrorStatus: 'Method Not Allowed' })); } if (err.statusCode && err.statusCode === 404) { - return callback({ ErrorStatus: 'Policy Not Found' }); + return callback(util.error(err, { ErrorStatus: 'Policy Not Found' })); } return callback(err); } @@ -5534,7 +5619,7 @@ function deleteBucketLifecycle(params, callback) { function putBucketVersioning(params, callback) { if (!params['VersioningConfiguration']) { - callback({ error: 'missing param VersioningConfiguration' }); + callback(util.error(new Error('missing param VersioningConfiguration'))); return; } var VersioningConfiguration = params['VersioningConfiguration'] || {}; @@ -5638,7 +5723,7 @@ function getBucketReplication(params, callback) { !data.ReplicationConfiguration && (data.ReplicationConfiguration = {}); } if (data.ReplicationConfiguration.Rule) { - data.ReplicationConfiguration.Rules = data.ReplicationConfiguration.Rule; + data.ReplicationConfiguration.Rules = util.makeArray(data.ReplicationConfiguration.Rule); delete data.ReplicationConfiguration.Rule; } callback(err, data); @@ -5683,7 +5768,7 @@ function deleteBucketReplication(params, callback) { function putBucketWebsite(params, callback) { if (!params['WebsiteConfiguration']) { - callback({ error: 'missing param WebsiteConfiguration' }); + callback(util.error(new Error('missing param WebsiteConfiguration'))); return; } @@ -5817,7 +5902,7 @@ function deleteBucketWebsite(params, callback) { function putBucketReferer(params, callback) { if (!params['RefererConfiguration']) { - callback({ error: 'missing param RefererConfiguration' }); + callback(util.error(new Error('missing param RefererConfiguration'))); return; } @@ -6380,7 +6465,7 @@ function deleteBucketInventory(params, callback) { function putBucketAccelerate(params, callback) { if (!params['AccelerateConfiguration']) { - callback({ error: 'missing param AccelerateConfiguration' }); + callback(util.error(new Error('missing param AccelerateConfiguration'))); return; } @@ -6582,7 +6667,6 @@ function getObject(params, callback) { * @param {String} params.ContentType RFC 2616 中定义的内容类型(MIME),将作为 Object 元数据保存,非必须 * @param {String} params.Expect 当使用 Expect: 100-continue 时,在收到服务端确认后,才会发送请求内容,非必须 * @param {String} params.Expires RFC 2616 中定义的过期时间,将作为 Object 元数据保存,非必须 - * @param {String} params.ContentSha1 RFC 3174 中定义的 160-bit 内容 SHA-1 算法校验,非必须 * @param {String} params.ACL 允许用户自定义文件权限,有效值:private | public-read,非必须 * @param {String} params.GrantRead 赋予被授权者读取对象的权限,格式:id="[OwnerUin]",可使用半角逗号(,)分隔多组被授权者,非必须 * @param {String} params.GrantReadAcp 赋予被授权者读取对象的访问控制列表(ACL)的权限,格式:id="[OwnerUin]",可使用半角逗号(,)分隔多组被授权者,非必须 @@ -6670,9 +6754,7 @@ function deleteObject(params, callback) { }, function (err, data) { if (err) { var statusCode = err.statusCode; - if (statusCode && statusCode === 204) { - return callback(null, { statusCode: statusCode }); - } else if (statusCode && statusCode === 404) { + if (statusCode && statusCode === 404) { return callback(null, { BucketNotFound: true, statusCode: statusCode }); } else { return callback(err); @@ -6713,6 +6795,7 @@ function getObjectAcl(params, callback) { var Grant = AccessControlPolicy.AccessControlList && AccessControlPolicy.AccessControlList.Grant || []; Grant = util.isArray(Grant) ? Grant : [Grant]; var result = decodeAcl(AccessControlPolicy); + delete result.GrantWrite; if (data.headers && data.headers['x-cos-acl']) { result.ACL = data.headers['x-cos-acl']; } @@ -6857,12 +6940,12 @@ function putObjectCopy(params, callback) { // 特殊处理 Cache-Control var headers = params.Headers; - if (!headers['Cache-Control'] && !!headers['cache-control']) headers['Cache-Control'] = ''; + if (!headers['Cache-Control'] && !headers['cache-control']) headers['Cache-Control'] = ''; var CopySource = params.CopySource || ''; var m = CopySource.match(/^([^.]+-\d+)\.cos(v6)?\.([^.]+)\.[^/]+\/(.+)$/); if (!m) { - callback({ error: 'CopySource format error' }); + callback(util.error(new Error('CopySource format error'))); return; } @@ -6871,7 +6954,6 @@ function putObjectCopy(params, callback) { var SourceKey = decodeURIComponent(m[4]); submitRequest.call(this, { - Interface: 'PutObjectCopy', Scope: [{ action: 'name/cos:GetObject', bucket: SourceBucket, @@ -6905,7 +6987,7 @@ function uploadPartCopy(params, callback) { var CopySource = params.CopySource || ''; var m = CopySource.match(/^([^.]+-\d+)\.cos(v6)?\.([^.]+)\.[^/]+\/(.+)$/); if (!m) { - callback({ error: 'CopySource format error' }); + callback(util.error(new Error('CopySource format error'))); return; } @@ -6914,7 +6996,6 @@ function uploadPartCopy(params, callback) { var SourceKey = decodeURIComponent(m[4]); submitRequest.call(this, { - Interface: 'UploadPartCopy', Scope: [{ action: 'name/cos:GetObject', bucket: SourceBucket, @@ -6968,7 +7049,6 @@ function deleteMultipleObject(params, callback) { }); submitRequest.call(this, { - Interface: 'DeleteMultipleObjects', Scope: Scope, method: 'POST', Bucket: params.Bucket, @@ -6999,7 +7079,7 @@ function deleteMultipleObject(params, callback) { function restoreObject(params, callback) { var headers = params.Headers; if (!params['RestoreRequest']) { - callback({ error: 'missing param RestoreRequest' }); + callback(util.error(new Error('missing param RestoreRequest'))); return; } @@ -7019,9 +7099,7 @@ function restoreObject(params, callback) { body: xml, action: 'restore', headers: headers - }, function (err, data) { - callback(err, data); - }); + }, callback); } /** @@ -7159,7 +7237,7 @@ function deleteObjectTagging(params, callback) { */ function selectObjectContent(params, callback) { var SelectType = params['SelectType']; - if (!SelectType) return callback({ error: 'missing param SelectType' }); + if (!SelectType) return callback(util.error(new Error('missing param SelectType'))); var SelectRequest = params['SelectRequest'] || {}; var xml = util.json2xml({ SelectRequest: SelectRequest }); @@ -7169,7 +7247,6 @@ function selectObjectContent(params, callback) { headers['Content-MD5'] = util.binaryBase64(util.md5(xml)); submitRequest.call(this, { - Interface: 'SelectObjectContent', Action: 'name/cos:GetObject', method: 'POST', Bucket: params.Bucket, @@ -7182,6 +7259,7 @@ function selectObjectContent(params, callback) { }, VersionId: params.VersionId, body: xml, + DataType: 'arraybuffer', rawBody: true }, function (err, data) { if (err && err.statusCode === 204) { @@ -7189,10 +7267,12 @@ function selectObjectContent(params, callback) { } else if (err) { return callback(err); } + var result = util.parseSelectPayload(data.body); callback(null, { statusCode: data.statusCode, headers: data.headers, - Body: data.body + Body: result.body, + Payload: result.payload }); }); } @@ -7225,6 +7305,7 @@ function selectObjectContent(params, callback) { function multipartInit(params, callback) { var self = this; + // 特殊处理 Cache-Control var headers = params.Headers; // 特殊处理 Cache-Control、Content-Type @@ -7243,9 +7324,7 @@ function multipartInit(params, callback) { headers: params.Headers, qs: params.Query }, function (err, data) { - if (err) { - return callback(err); - } + if (err) return callback(err); data = util.clone(data || {}); if (data && data.InitiateMultipartUploadResult) { return callback(null, util.extend(data.InitiateMultipartUploadResult, { @@ -7433,14 +7512,8 @@ function multipartList(params, callback) { if (data && data.ListMultipartUploadsResult) { var Upload = data.ListMultipartUploadsResult.Upload || []; - - var CommonPrefixes = data.ListMultipartUploadsResult.CommonPrefixes || []; - - CommonPrefixes = util.isArray(CommonPrefixes) ? CommonPrefixes : [CommonPrefixes]; Upload = util.isArray(Upload) ? Upload : [Upload]; - data.ListMultipartUploadsResult.Upload = Upload; - data.ListMultipartUploadsResult.CommonPrefixes = CommonPrefixes; } var result = util.clone(data.ListMultipartUploadsResult || {}); util.extend(result, { @@ -7594,7 +7667,7 @@ function getObjectUrl(params, callback) { } var signUrl = url; signUrl += '?' + (AuthData.Authorization.indexOf('q-signature') > -1 ? AuthData.Authorization : 'sign=' + encodeURIComponent(AuthData.Authorization)); - AuthData.XCosSecurityToken && (signUrl += '&x-cos-security-token=' + AuthData.XCosSecurityToken); + AuthData.SecurityToken && (signUrl += '&x-cos-security-token=' + AuthData.SecurityToken); AuthData.ClientIP && (signUrl += '&clientIP=' + AuthData.ClientIP); AuthData.ClientUA && (signUrl += '&clientUA=' + AuthData.ClientUA); AuthData.Token && (signUrl += '&token=' + AuthData.Token); @@ -7603,7 +7676,7 @@ function getObjectUrl(params, callback) { }); }); if (AuthData) { - return url + '?' + AuthData.Authorization + (AuthData.XCosSecurityToken ? '&x-cos-security-token=' + AuthData.XCosSecurityToken : ''); + return url + '?' + AuthData.Authorization + (AuthData.SecurityToken ? '&x-cos-security-token=' + AuthData.SecurityToken : ''); } else { return url; } @@ -7721,36 +7794,16 @@ function getUrl(params) { function getAuthorizationAsync(params, callback) { var headers = util.clone(params.Headers); - delete headers['Content-Type']; - delete headers['Cache-Control']; util.each(headers, function (v, k) { - v === '' && delete headers[k]; + (v === '' || ['content-type', 'cache-control', 'expires'].indexOf(k.toLowerCase())) && delete headers[k]; }); - var cb = function (AuthData) { - - // 检查签名格式 - var formatAllow = false; - var auth = AuthData.Authorization; - if (auth) { - if (auth.indexOf(' ') > -1) { - formatAllow = false; - } else if (auth.indexOf('q-sign-algorithm=') > -1 && auth.indexOf('q-ak=') > -1 && auth.indexOf('q-sign-time=') > -1 && auth.indexOf('q-key-time=') > -1 && auth.indexOf('q-url-param-list=') > -1) { - formatAllow = true; - } else { - try { - auth = atob(auth); - if (auth.indexOf('a=') > -1 && auth.indexOf('k=') > -1 && auth.indexOf('t=') > -1 && auth.indexOf('r=') > -1 && auth.indexOf('b=') > -1) { - formatAllow = true; - } - } catch (e) {} - } - } - if (formatAllow) { - callback && callback(null, AuthData); - } else { - callback && callback({ error: 'authorization error' }); - } + // 获取凭证的回调,避免用户 callback 多次 + var cbDone = false; + var cb = function (err, AuthData) { + if (cbDone) return; + cbDone = true; + callback && callback(err, AuthData); }; var self = this; @@ -7813,12 +7866,42 @@ function getAuthorizationAsync(params, callback) { }); var AuthData = { Authorization: Authorization, - XCosSecurityToken: StsData.XCosSecurityToken || '', + SecurityToken: StsData.SecurityToken || StsData.XCosSecurityToken || '', Token: StsData.Token || '', ClientIP: StsData.ClientIP || '', ClientUA: StsData.ClientUA || '' }; - cb(AuthData); + cb(null, AuthData); + }; + var checkAuthError = function (AuthData) { + if (AuthData.Authorization) { + // 检查签名格式 + var formatAllow = false; + var auth = AuthData.Authorization; + if (auth) { + if (auth.indexOf(' ') > -1) { + formatAllow = false; + } else if (auth.indexOf('q-sign-algorithm=') > -1 && auth.indexOf('q-ak=') > -1 && auth.indexOf('q-sign-time=') > -1 && auth.indexOf('q-key-time=') > -1 && auth.indexOf('q-url-param-list=') > -1) { + formatAllow = true; + } else { + try { + auth = Buffer.from(auth, 'base64').toString(); + if (auth.indexOf('a=') > -1 && auth.indexOf('k=') > -1 && auth.indexOf('t=') > -1 && auth.indexOf('r=') > -1 && auth.indexOf('b=') > -1) { + formatAllow = true; + } + } catch (e) {} + } + } + if (!formatAllow) return util.error(new Error('getAuthorization callback params format error')); + } else { + if (!AuthData.TmpSecretId) return util.error(new Error('getAuthorization callback params missing "TmpSecretId"')); + if (!AuthData.TmpSecretKey) return util.error(new Error('getAuthorization callback params missing "TmpSecretKey"')); + if (!AuthData.SecurityToken && !AuthData.XCosSecurityToken) return util.error(new Error('getAuthorization callback params missing "SecurityToken"')); + if (!AuthData.ExpiredTime) return util.error(new Error('getAuthorization callback params missing "ExpiredTime"')); + if (AuthData.ExpiredTime && AuthData.ExpiredTime.toString().length !== 10) return util.error(new Error('getAuthorization callback params "ExpiredTime" should be 10 digits')); + if (AuthData.StartTime && AuthData.StartTime.toString().length !== 10) return util.error(new Error('getAuthorization callback params "StartTime" should be 10 StartTime')); + } + return false; }; // 先判断是否有临时密钥 @@ -7838,17 +7921,17 @@ function getAuthorizationAsync(params, callback) { Scope: Scope, SystemClockOffset: self.options.SystemClockOffset }, function (AuthData) { - if (typeof AuthData === 'string') { - AuthData = { Authorization: AuthData }; - } - if (AuthData.TmpSecretId && AuthData.TmpSecretKey && AuthData.XCosSecurityToken && AuthData.ExpiredTime) { + if (typeof AuthData === 'string') AuthData = { Authorization: AuthData }; + var AuthError = checkAuthError(AuthData); + if (AuthError) return cb(AuthError); + if (AuthData.Authorization) { + cb(null, AuthData); + } else { StsData = AuthData || {}; StsData.Scope = Scope; StsData.ScopeKey = ScopeKey; self._StsCache.push(StsData); calcAuthByTmpKey(); - } else { - cb(AuthData); } }); } else if (self.options.getSTS) { @@ -7860,8 +7943,10 @@ function getAuthorizationAsync(params, callback) { StsData = data || {}; StsData.Scope = Scope; StsData.ScopeKey = ScopeKey; - StsData.TmpSecretId = StsData.SecretId; - StsData.TmpSecretKey = StsData.SecretKey; + if (!StsData.TmpSecretId) StsData.TmpSecretId = StsData.SecretId; + if (!StsData.TmpSecretKey) StsData.TmpSecretKey = StsData.SecretKey; + var AuthError = checkAuthError(StsData); + if (AuthError) return cb(AuthError); self._StsCache.push(StsData); calcAuthByTmpKey(); }); @@ -7881,9 +7966,9 @@ function getAuthorizationAsync(params, callback) { }); var AuthData = { Authorization: Authorization, - XCosSecurityToken: self.options.XCosSecurityToken + SecurityToken: self.options.SecurityToken || self.options.XCosSecurityToken }; - cb(AuthData); + cb(null, AuthData); return AuthData; }(); } @@ -8013,7 +8098,7 @@ function _submitRequest(params, callback) { params.AuthData.Token && (opt.headers['token'] = params.AuthData.Token); params.AuthData.ClientIP && (opt.headers['clientIP'] = params.AuthData.ClientIP); params.AuthData.ClientUA && (opt.headers['clientUA'] = params.AuthData.ClientUA); - params.AuthData.XCosSecurityToken && (opt.headers['x-cos-security-token'] = params.AuthData.XCosSecurityToken); + params.AuthData.SecurityToken && (opt.headers['x-cos-security-token'] = params.AuthData.SecurityToken); // 清理 undefined 和 null 字段 opt.headers && (opt.headers = util.clearKey(opt.headers)); @@ -8038,13 +8123,6 @@ function _submitRequest(params, callback) { opt.timeout = this.options.Timeout; } - // 整理 cosInterface 用于 before-send 使用 - if (params.Interface) { - opt.cosInterface = params.Interface; - } else if (params.Action) { - opt.cosInterface = params.Action.replace(/^name\/cos:/, ''); - } - self.options.ForcePathStyle && (opt.pathStyle = self.options.ForcePathStyle); self.emit('before-send', opt); var sender = (self.options.Request || REQUEST)(opt, function (r) { @@ -8077,37 +8155,38 @@ function _submitRequest(params, callback) { }; // 请求错误,发生网络错误 - if (err) { - cb({ error: err }); - return; - } - - // 不对 body 进行转换,body 直接挂载返回 - var jsonRes; - if (rawBody) { - jsonRes = {}; - jsonRes.body = body; - } else { - try { - jsonRes = body && body.indexOf('<') > -1 && body.indexOf('>') > -1 && util.xml2json(body) || {}; - } catch (e) { - jsonRes = body || {}; - } - } + if (err) return cb(util.error(err)); // 请求返回码不为 200 var statusCode = response.statusCode; var statusSuccess = Math.floor(statusCode / 100) === 2; // 200 202 204 206 - if (!statusSuccess) { - cb({ error: jsonRes.Error || jsonRes }); - return; - } - if (jsonRes.Error) { - cb({ error: jsonRes.Error }); - return; + // 不对 body 进行转换,body 直接挂载返回 + if (rawBody && statusSuccess) return cb(null, { body: body }); + + // 解析 xml body + var json; + try { + json = body && body.indexOf('<') > -1 && body.indexOf('>') > -1 && util.xml2json(body) || {}; + } catch (e) { + json = {}; + } + + // 处理返回值 + var xmlError = json && json.Error; + if (statusSuccess) { + // 正确返回,状态码 2xx 时,body 不会有 Error + cb(null, json); + } else if (xmlError) { + // 正常返回了 xml body,且有 Error 节点 + cb(util.error(new Error(xmlError.Message), { code: xmlError.Code, error: xmlError })); + } else if (statusCode) { + // 有错误的状态码 + cb(util.error(new Error(response.statusMessage), { code: '' + statusCode })); + } else if (statusCode) { + // 无状态码,或者获取不到状态码 + cb(util.error(new Error('statusCode error'))); } - cb(null, jsonRes); }); // kill task @@ -8220,9 +8299,2066 @@ module.exports.init = function (COS, task) { warnOldApi(apiName, fn, COS.prototype); }); }; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(17).Buffer)) /***/ }), /* 17 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) {/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + + + +var base64 = __webpack_require__(18) +var ieee754 = __webpack_require__(19) +var isArray = __webpack_require__(20) + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + +/* + * Export kMaxLength after typed array support is determined. + */ +exports.kMaxLength = kMaxLength() + +function typedArraySupport () { + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } +} + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype + return arr +} + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +} + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) + } +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +} + +function allocUnsafe (that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0 + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +} + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + var actual = that.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual) + } + + return that +} + +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + that = createBuffer(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array) + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) + } + return that +} + +function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start] + } + } + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 +} + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1))) + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} + + +/***/ }), +/* 19 */ +/***/ (function(module, exports) { + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + + +/***/ }), +/* 20 */ +/***/ (function(module, exports) { + +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + + +/***/ }), +/* 21 */ /***/ (function(module, exports) { var stringifyPrimitive = function (v) { @@ -8330,7 +10466,7 @@ var request = function (opt, callback) { } else { // 0 var error = xhr.statusText; - if (!error && xhr.status === 0) error = 'CORS blocked or network error'; + if (!error && xhr.status === 0) error = new Error('CORS blocked or network error'); callback(xhrRes(error, xhr, body)); } }; @@ -8345,12 +10481,12 @@ var request = function (opt, callback) { module.exports = request; /***/ }), -/* 18 */ +/* 22 */ /***/ (function(module, exports, __webpack_require__) { -var session = __webpack_require__(3); -var Async = __webpack_require__(19); -var EventProxy = __webpack_require__(2).EventProxy; +var session = __webpack_require__(4); +var Async = __webpack_require__(23); +var EventProxy = __webpack_require__(3).EventProxy; var util = __webpack_require__(0); // 文件分块上传全过程,暴露的分块上传接口 @@ -8403,7 +10539,7 @@ function sliceUploadFile(params, callback) { onProgress(null, true); return ep.emit('error', err); } - session.removeUploadId(UploadData.UploadId); + session.removeUploadId.call(self, UploadData.UploadId); onProgress({ loaded: FileSize, total: FileSize }, true); ep.emit('upload_complete', data); }); @@ -8414,7 +10550,7 @@ function sliceUploadFile(params, callback) { // 处理 UploadId 缓存 var uuid = session.getFileId(Body, params.ChunkSize, Bucket, Key); - uuid && session.saveUploadId(uuid, UploadData.UploadId, self.options.UploadIdCacheLimit); // 缓存 UploadId + uuid && session.saveUploadId.call(self, uuid, UploadData.UploadId, self.options.UploadIdCacheLimit); // 缓存 UploadId session.setUsing(UploadData.UploadId); // 标记 UploadId 为正在使用 // 获取 UploadId @@ -8497,12 +10633,7 @@ function sliceUploadFile(params, callback) { params.Body = ''; params.ContentLength = 0; params.SkipTask = true; - self.putObject(params, function (err, data) { - if (err) { - return callback(err); - } - callback(null, data); - }); + self.putObject(params, callback); } else { ep.emit('get_file_size_finish'); } @@ -8539,17 +10670,17 @@ function getUploadIdAndPartList(params, callback) { } else { util.fileSlice(params.Body, start, end, false, function (chunkItem) { util.getFileMd5(chunkItem, function (err, md5) { - if (err) return callback(err); + if (err) return callback(util.error(err)); var ETag = '"' + md5 + '"'; ETagMap[PartNumber] = ETag; FinishSliceCount += 1; FinishSize += ChunkSize; - callback(err, { + onHashProgress({ loaded: FinishSize, total: FileSize }); + callback(null, { PartNumber: PartNumber, ETag: ETag, Size: ChunkSize }); - onHashProgress({ loaded: FinishSize, total: FileSize }); }); }); } @@ -8640,7 +10771,7 @@ function getUploadIdAndPartList(params, callback) { if (err) return ep.emit('error', err); var UploadId = data.UploadId; if (!UploadId) { - return callback({ Message: 'no upload id' }); + return callback(util.error(new Error('no such upload id'))); } ep.emit('upload_id_available', { UploadId: UploadId, PartList: [] }); }); @@ -8703,7 +10834,7 @@ function getUploadIdAndPartList(params, callback) { ep.on('seek_local_avail_upload_id', function (RemoteUploadIdList) { // 在本地找可用的 UploadId var uuid = session.getFileId(params.Body, params.ChunkSize, Bucket, Key); - var LocalUploadIdList = session.getUploadIdList(uuid); + var LocalUploadIdList = session.getUploadIdList.call(self, uuid); if (!uuid || !LocalUploadIdList) { ep.emit('has_and_check_upload_id', RemoteUploadIdList); return; @@ -8717,7 +10848,7 @@ function getUploadIdAndPartList(params, callback) { var UploadId = LocalUploadIdList[index]; // 如果不在远端 UploadId 列表里,跳过并删除 if (!util.isInArray(RemoteUploadIdList, UploadId)) { - session.removeUploadId(UploadId); + session.removeUploadId.call(self, UploadId); next(index + 1); return; } @@ -8736,7 +10867,7 @@ function getUploadIdAndPartList(params, callback) { if (!self._isRunningTask(TaskId)) return; if (err) { // 如果 UploadId 获取会出错,跳过并删除 - session.removeUploadId(UploadId); + session.removeUploadId.call(self, UploadId); next(index + 1); } else { // 找到可用 UploadId @@ -8759,9 +10890,7 @@ function getUploadIdAndPartList(params, callback) { Key: Key }, function (err, data) { if (!self._isRunningTask(TaskId)) return; - if (err) { - return ep.emit('error', err); - } + if (err) return ep.emit('error', err); // 整理远端 UploadId 列表 var RemoteUploadIdList = util.filter(data.UploadList, function (item) { return item.Key === Key && (!StorageClass || item.StorageClass.toUpperCase() === StorageClass.toUpperCase()); @@ -8774,9 +10903,9 @@ function getUploadIdAndPartList(params, callback) { // 远端没有 UploadId,清理缓存的 UploadId var uuid = session.getFileId(params.Body, params.ChunkSize, Bucket, Key), LocalUploadIdList; - if (uuid && (LocalUploadIdList = session.getUploadIdList(uuid))) { + if (uuid && (LocalUploadIdList = session.getUploadIdList.call(self, uuid))) { util.each(LocalUploadIdList, function (UploadId) { - session.removeUploadId(UploadId); + session.removeUploadId.call(self, UploadId); }); } ep.emit('no_available_upload_id'); @@ -8895,9 +11024,7 @@ function uploadSliceList(params, cb) { } }, function (err, data) { if (!self._isRunningTask(TaskId)) return; - if (!err && !data.ETag) { - err = 'get ETag error, please add "ETag" to CORS ExposeHeader setting.'; - } + if (!err && !data.ETag) err = 'get ETag error, please add "ETag" to CORS ExposeHeader setting.'; if (err) { FinishSize -= preAddSize; } else { @@ -8960,12 +11087,9 @@ function uploadSliceItem(params, callback) { onProgress: params.onProgress }, function (err, data) { if (!self._isRunningTask(TaskId)) return; - if (err) { - return tryCallback(err); - } else { - PartItem.Uploaded = true; - return tryCallback(null, data); - } + if (err) return tryCallback(err); + PartItem.Uploaded = true; + return tryCallback(null, data); }); }); }, function (err, data) { @@ -9035,12 +11159,7 @@ function abortUploadTask(params, callback) { Headers: params.Headers, AsyncLimit: AsyncLimit, AbortArray: AbortArray - }, function (err, data) { - if (err) { - return callback(err); - } - callback(null, data); - }); + }, callback); }); if (Level === 'bucket') { @@ -9049,34 +11168,30 @@ function abortUploadTask(params, callback) { Bucket: Bucket, Region: Region }, function (err, data) { - if (err) { - return callback(err); - } + if (err) return callback(err); ep.emit('get_abort_array', data.UploadList || []); }); } else if (Level === 'file') { // 文件级别的任务抛弃,抛弃该文件的全部上传任务 - if (!Key) return callback({ error: 'abort_upload_task_no_key' }); + if (!Key) return callback(util.error(new Error('abort_upload_task_no_key'))); wholeMultipartList.call(self, { Bucket: Bucket, Region: Region, Key: Key }, function (err, data) { - if (err) { - return callback(err); - } + if (err) return callback(err); ep.emit('get_abort_array', data.UploadList || []); }); } else if (Level === 'task') { // 单个任务级别的任务抛弃,抛弃指定 UploadId 的上传任务 - if (!UploadId) return callback({ error: 'abort_upload_task_no_id' }); - if (!Key) return callback({ error: 'abort_upload_task_no_key' }); + if (!UploadId) return callback(util.error(new Error('abort_upload_task_no_id'))); + if (!Key) return callback(util.error(new Error('abort_upload_task_no_key'))); ep.emit('get_abort_array', [{ Key: Key, UploadId: UploadId }]); } else { - return callback({ error: 'abort_unknown_level' }); + return callback(util.error(new Error('abort_unknown_level'))); } } @@ -9092,11 +11207,11 @@ function abortUploadTaskArray(params, callback) { var index = 0; var resultList = new Array(AbortArray.length); - Async.eachLimit(AbortArray, AsyncLimit, function (AbortItem, callback) { + Async.eachLimit(AbortArray, AsyncLimit, function (AbortItem, nextItem) { var eachIndex = index; if (Key && Key !== AbortItem.Key) { resultList[eachIndex] = { error: { KeyNotMatch: true } }; - callback(null); + nextItem(null); return; } var UploadId = AbortItem.UploadId || AbortItem.UploadID; @@ -9115,13 +11230,11 @@ function abortUploadTaskArray(params, callback) { UploadId: UploadId }; resultList[eachIndex] = { error: err, task: task }; - callback(null); + nextItem(null); }); index++; }, function (err) { - if (err) { - return callback(err); - } + if (err) return callback(err); var successList = []; var errorList = []; @@ -9169,9 +11282,7 @@ function uploadFiles(params, callback) { data: data }; if (--unFinishCount <= 0 && callback) { - callback(null, { - files: resultList - }); + callback(null, { files: resultList }); } }; @@ -9222,7 +11333,7 @@ function uploadFiles(params, callback) { }; // 添加上传任务 - var api = FileSize >= SliceSize ? 'sliceUploadFile' : 'putObject'; + var api = FileSize > SliceSize ? 'sliceUploadFile' : 'putObject'; taskList.push({ api: api, params: fileParams, @@ -9244,7 +11355,7 @@ function sliceCopyFile(params, callback) { var CopySource = params.CopySource; var m = CopySource.match(/^([^.]+-\d+)\.cos(v6)?\.([^.]+)\.[^/]+\/(.+)$/); if (!m) { - callback({ error: 'CopySource format error' }); + callback(util.error(new Error('CopySource format error'))); return; } @@ -9294,7 +11405,6 @@ function sliceCopyFile(params, callback) { var PartNumber = SliceItem.PartNumber; var CopySourceRange = SliceItem.CopySourceRange; var currentSize = SliceItem.end - SliceItem.start; - var preAddSize = 0; copySliceItem.call(self, { Bucket: Bucket, @@ -9303,19 +11413,11 @@ function sliceCopyFile(params, callback) { CopySource: CopySource, UploadId: UploadData.UploadId, PartNumber: PartNumber, - CopySourceRange: CopySourceRange, - onProgress: function (data) { - FinishSize += data.loaded - preAddSize; - preAddSize = data.loaded; - onProgress({ loaded: FinishSize, total: FileSize }); - } + CopySourceRange: CopySourceRange }, function (err, data) { - if (err) { - return asyncCallback(err); - } + if (err) return asyncCallback(err); + FinishSize += currentSize; onProgress({ loaded: FinishSize, total: FileSize }); - - FinishSize += currentSize - preAddSize; SliceItem.ETag = data.ETag; asyncCallback(err || null, data); }); @@ -9371,7 +11473,7 @@ function sliceCopyFile(params, callback) { if (SourceHeaders['x-cos-storage-class'] === 'ARCHIVE' || SourceHeaders['x-cos-storage-class'] === 'DEEP_ARCHIVE') { var restoreHeader = SourceHeaders['x-cos-restore']; if (!restoreHeader || restoreHeader === 'ongoing-request="true"') { - callback({ error: 'Unrestored archive object is not allowed to be copied' }); + callback(util.error(new Error('Unrestored archive object is not allowed to be copied'))); return; } } @@ -9391,9 +11493,7 @@ function sliceCopyFile(params, callback) { Key: Key, Headers: TargetHeader }, function (err, data) { - if (err) { - return callback(err); - } + if (err) return callback(err); params.UploadId = data.UploadId; ep.emit('get_copy_data_finish', params); }); @@ -9407,7 +11507,7 @@ function sliceCopyFile(params, callback) { }, function (err, data) { if (err) { if (err.statusCode && err.statusCode === 404) { - callback({ ErrorStatus: SourceKey + ' Not Exist' }); + callback(util.error(err, { ErrorStatus: SourceKey + ' Not Exist' })); } else { callback(err); } @@ -9416,7 +11516,7 @@ function sliceCopyFile(params, callback) { FileSize = params.FileSize = data.headers['content-length']; if (FileSize === undefined || !FileSize) { - callback({ error: 'get Content-Length error, please add "Content-Length" to CORS ExposeHeader setting.' }); + callback(util.error(new Error('get Content-Length error, please add "Content-Length" to CORS ExposeHeader setting.'))); return; } @@ -9479,8 +11579,7 @@ function copySliceItem(params, callback) { CopySource: CopySource, UploadId: UploadId, PartNumber: PartNumber, - CopySourceRange: CopySourceRange, - onProgress: params.onProgress + CopySourceRange: CopySourceRange }, function (err, data) { tryCallback(err || null, data); }); @@ -9504,7 +11603,7 @@ module.exports.init = function (COS, task) { }; /***/ }), -/* 19 */ +/* 23 */ /***/ (function(module, exports) { var eachLimit = function (arr, limit, iterator, callback) { diff --git a/dist/cos-js-sdk-v5.min.js b/dist/cos-js-sdk-v5.min.js index dcd0392..af49aff 100644 --- a/dist/cos-js-sdk-v5.min.js +++ b/dist/cos-js-sdk-v5.min.js @@ -1 +1,8 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.COS=t():e.COS=t()}("undefined"!=typeof self?self:this,function(){return function(e){function t(o){if(n[o])return n[o].exports;var r=n[o]={i:o,l:!1,exports:{}};return e[o].call(r.exports,r,r.exports,t),r.l=!0,r.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,o){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:o})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="/dist/",t(t.s=4)}([function(e,t,n){"use strict";function o(e){return encodeURIComponent(e).replace(/!/g,"%21").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/\*/g,"%2A")}function r(e){return d(e,function(e){return"object"==typeof e&&null!==e?r(e):e})}function i(e,t,n){return e&&t in e?e[t]:n}function a(e,t){return l(t,function(n,o){e[o]=t[o]}),e}function s(e){return e instanceof Array}function c(e,t){for(var n=!1,o=0;ot?1:-1})},f=function(e){var t,n,r,i=[],a=d(e);for(t=0;tparseInt(t[n])?1:-1;return 0};return function(t){var n=(t.match(/Chrome\/([.\d]+)/)||[])[1],o=(t.match(/QBCore\/([.\d]+)/)||[])[1],r=(t.match(/QQBrowser\/([.\d]+)/)||[])[1];return n&&e(n,"53.0.2785.116")<0&&o&&e(o,"3.53.991.400")<0&&r&&e(r,"9.0.2524.400")<=0||!1}(navigator&&navigator.userAgent)}(),S=function(e,t,n,o,r){var i;if(e.slice?i=e.slice(t,n):e.mozSlice?i=e.mozSlice(t,n):e.webkitSlice&&(i=e.webkitSlice(t,n)),o&&R){var a=new FileReader;a.onload=function(e){i=null,r(new Blob([a.result]))},a.readAsArrayBuffer(i)}else r(i)},A=function(e,t,n,o){n=n||C,e?"string"==typeof t?n(O.md5(t,!0)):Blob&&t instanceof Blob?O.getFileMd5(t,function(e,t){n(t)},o):n():n()},b=function(e,t,n){var o=e.size,r=0,i=h.getCtx(),a=function(s){if(s>=o){var c=i.digest("hex");return void t(null,c)}var u=Math.min(o,s+1048576);O.fileSlice(e,s,u,!1,function(e){k(e,function(t){e=null,i=i.update(t,!0),r+=t.length,t=null,n&&n({loaded:r,total:o,percent:Math.round(r/o*1e4)/1e4}),a(s+1048576)})})};a(0)},B=function(e){var t,n,o,r="";for(t=0,n=e.length/2;t-1||"deleteMultipleObject"===e||"multipartList"===e||"listObjectVersions"===e){if(!n)return"Bucket";if(!o)return"Region"}else if(e.indexOf("Object")>-1||e.indexOf("multipart")>-1||"sliceUploadFile"===e||"abortUploadTask"===e){if(!n)return"Bucket";if(!o)return"Region";if(!r)return"Key"}return!1},E=function(e,t){if(t=a({},t),"getAuth"!==e&&"getV4Auth"!==e&&"getObjectUrl"!==e){var n=t.Headers||{};if(t&&"object"==typeof t){!function(){for(var e in t)t.hasOwnProperty(e)&&e.indexOf("x-cos-")>-1&&(n[e]=t[e])}();var o={"x-cos-mfa":"MFA","Content-MD5":"ContentMD5","Content-Length":"ContentLength","Content-Type":"ContentType",Expect:"Expect",Expires:"Expires","Cache-Control":"CacheControl","Content-Disposition":"ContentDisposition","Content-Encoding":"ContentEncoding",Range:"Range","If-Modified-Since":"IfModifiedSince","If-Unmodified-Since":"IfUnmodifiedSince","If-Match":"IfMatch","If-None-Match":"IfNoneMatch","x-cos-copy-source":"CopySource","x-cos-copy-source-Range":"CopySourceRange","x-cos-metadata-directive":"MetadataDirective","x-cos-copy-source-If-Modified-Since":"CopySourceIfModifiedSince","x-cos-copy-source-If-Unmodified-Since":"CopySourceIfUnmodifiedSince","x-cos-copy-source-If-Match":"CopySourceIfMatch","x-cos-copy-source-If-None-Match":"CopySourceIfNoneMatch","x-cos-acl":"ACL","x-cos-grant-read":"GrantRead","x-cos-grant-write":"GrantWrite","x-cos-grant-full-control":"GrantFullControl","x-cos-grant-read-acp":"GrantReadAcp","x-cos-grant-write-acp":"GrantWriteAcp","x-cos-storage-class":"StorageClass","x-cos-server-side-encryption-customer-algorithm":"SSECustomerAlgorithm","x-cos-server-side-encryption-customer-key":"SSECustomerKey","x-cos-server-side-encryption-customer-key-MD5":"SSECustomerKeyMD5","x-cos-server-side-encryption":"ServerSideEncryption","x-cos-server-side-encryption-cos-kms-key-id":"SSEKMSKeyId","x-cos-server-side-encryption-context":"SSEContext"};O.each(o,function(e,o){void 0!==t[e]&&(n[o]=t[e])}),t.Headers=v(n)}}return t},_=function(e,t){return function(n,o){var r=this;"function"==typeof n&&(o=n,n={}),n=E(e,n);var i=function(e){return e&&e.headers&&(e.headers["x-cos-version-id"]&&(e.VersionId=e.headers["x-cos-version-id"]),e.headers["x-cos-delete-marker"]&&(e.DeleteMarker=e.headers["x-cos-delete-marker"])),e},a=function(e,t){o&&o(i(e),i(t))},s=function(){if("getService"!==e&&"abortUploadTask"!==e){var t=x(e,n);if(t)return"missing param "+t;if(n.Region){if(n.Region.indexOf("cos.")>-1)return'param Region should not be start with "cos."';if(!/^([a-z\d-]+)$/.test(n.Region))return"Region format error.";r.options.CompatibilityMode||-1!==n.Region.indexOf("-")||"yfb"===n.Region||"default"===n.Region||console.warn("warning: param Region format error, find help here: https://cloud.tencent.com/document/product/436/6224")}if(n.Bucket){if(!/^([a-z\d-]+)-(\d+)$/.test(n.Bucket))if(n.AppId)n.Bucket=n.Bucket+"-"+n.AppId;else{if(!r.options.AppId)return'Bucket should format as "test-1250000000".';n.Bucket=n.Bucket+"-"+r.options.AppId}n.AppId&&(console.warn('warning: AppId has been deprecated, Please put it at the end of parameter Bucket(E.g Bucket:"test-1250000000" ).'),delete n.AppId)}!r.options.UseRawKey&&n.Key&&"/"===n.Key.substr(0,1)&&(n.Key=n.Key.substr(1))}}(),c="getAuth"===e||"getObjectUrl"===e;if(Promise&&!c&&!o)return new Promise(function(e,i){if(o=function(t,n){t?i(t):e(n)},s)return a({error:s});t.call(r,n,a)});if(s)return a({error:s});var u=t.call(r,n,a);return c?u:void 0}},w=function(e,t){function n(){if(r=0,t&&"function"==typeof t){o=Date.now();var n,i=Math.max(0,Math.round((s-a)/((o-c)/1e3)*100)/100)||0;n=0===s&&0===e?1:Math.floor(s/e*100)/100||0,c=o,a=s;try{t({loaded:s,total:e,speed:i,percent:n})}catch(e){}}}var o,r,i=this,a=0,s=0,c=Date.now();return function(t,o){if(t&&(s=t.loaded,e=t.total),o)clearTimeout(r),n();else{if(r)return;r=setTimeout(n,i.options.ProgressInterval)}}},I=function(e,t,n){var o;if("string"==typeof t.Body?t.Body=new Blob([t.Body],{type:"text/plain"}):t.Body instanceof ArrayBuffer&&(t.Body=new Blob([t.Body])),!t.Body||!(t.Body instanceof Blob||"[object File]"===t.Body.toString()||"[object Blob]"===t.Body.toString()))return void n({error:"params body format error, Only allow File|Blob|String."});o=t.Body.size,t.ContentLength=o,n(null,o)},D=function(e){return Date.now()+(e||0)},O={noop:C,formatParams:E,apiWrapper:_,xml2json:g,json2xml:m,md5:h,clearKey:v,fileSlice:S,getBodyMd5:A,getFileMd5:b,binaryBase64:B,extend:a,isArray:s,isInArray:c,makeArray:u,each:l,map:d,filter:f,clone:r,attr:i,uuid:T,camSafeUrlEncode:o,throttleOnProgress:w,getFileSize:I,getSkewTime:D,getAuth:y,isBrowser:!0};e.exports=O},function(e,t){function n(e,t){for(var n in e)t[n]=e[n]}function o(e,t){function o(){}var r=e.prototype;if(Object.create){var i=Object.create(t.prototype);r.__proto__=i}r instanceof t||(o.prototype=t.prototype,o=new o,n(r,o),e.prototype=r=o),r.constructor!=e&&("function"!=typeof e&&console.error("unknow Class:"+e),r.constructor=e)}function r(e,t){if(t instanceof Error)var n=t;else n=this,Error.call(this,re[e]),this.message=re[e],Error.captureStackTrace&&Error.captureStackTrace(this,r);return n.code=e,t&&(this.message=this.message+": "+t),n}function i(){}function a(e,t){this._node=e,this._refresh=t,s(this)}function s(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!=t){var o=e._refresh(e._node);K(e,"length",o.length),n(o,e),e._inc=t}}function c(){}function u(e,t){for(var n=e.length;n--;)if(e[n]===t)return n}function l(e,t,n,o){if(o?t[u(t,o)]=n:t[t.length++]=n,e){n.ownerElement=e;var r=e.ownerDocument;r&&(o&&C(r,e,o),y(r,e,n))}}function d(e,t,n){var o=u(t,n);if(!(o>=0))throw r(ae,new Error(e.tagName+"@"+n));for(var i=t.length-1;o"==e&&">"||"&"==e&&"&"||'"'==e&&"""||"&#"+e.charCodeAt()+";"}function g(e,t){if(t(e))return!0;if(e=e.firstChild)do{if(g(e,t))return!0}while(e=e.nextSibling)}function m(){}function y(e,t,n){e&&e._inc++,"http://www.w3.org/2000/xmlns/"==n.namespaceURI&&(t._nsMap[n.prefix?n.localName:""]=n.value)}function C(e,t,n,o){e&&e._inc++,"http://www.w3.org/2000/xmlns/"==n.namespaceURI&&delete t._nsMap[n.prefix?n.localName:""]}function v(e,t,n){if(e&&e._inc){e._inc++;var o=t.childNodes;if(n)o[o.length++]=n;else{for(var r=t.firstChild,i=0;r;)o[i++]=r,r=r.nextSibling;o.length=i}}}function k(e,t){var n=t.previousSibling,o=t.nextSibling;return n?n.nextSibling=o:e.firstChild=o,o?o.previousSibling=n:e.lastChild=n,v(e.ownerDocument,e),t}function R(e,t,n){var o=t.parentNode;if(o&&o.removeChild(t),t.nodeType===te){var r=t.firstChild;if(null==r)return t;var i=t.lastChild}else r=i=t;var a=n?n.previousSibling:e.lastChild;r.previousSibling=a,i.nextSibling=n,a?a.nextSibling=r:e.firstChild=r,null==n?e.lastChild=i:n.previousSibling=i;do{r.parentNode=e}while(r!==i&&(r=r.nextSibling));return v(e.ownerDocument||e,e),t.nodeType==te&&(t.firstChild=t.lastChild=null),t}function S(e,t){var n=t.parentNode;if(n){var o=e.lastChild;n.removeChild(t);var o=e.lastChild}var o=e.lastChild;return t.parentNode=e,t.previousSibling=o,t.nextSibling=null,o?o.nextSibling=t:e.firstChild=t,e.lastChild=t,v(e.ownerDocument,e,t),t}function A(){this._nsMap={}}function b(){}function B(){}function T(){}function x(){}function E(){}function _(){}function w(){}function I(){}function D(){}function O(){}function N(){}function P(){}function M(e,t){var n=[],o=9==this.nodeType?this.documentElement:this,r=o.prefix,i=o.namespaceURI;if(i&&null==r){var r=o.lookupPrefix(i);if(null==r)var a=[{namespace:i,prefix:null}]}return H(this,n,e,t,a),n.join("")}function U(e,t,n){var o=e.prefix||"",r=e.namespaceURI;if(!o&&!r)return!1;if("xml"===o&&"http://www.w3.org/XML/1998/namespace"===r||"http://www.w3.org/2000/xmlns/"==r)return!1;for(var i=n.length;i--;){var a=n[i];if(a.prefix==o)return a.namespace!=r}return!0}function H(e,t,n,o,r){if(o){if(!(e=o(e)))return;if("string"==typeof e)return void t.push(e)}switch(e.nodeType){case q:r||(r=[]);var i=(r.length,e.attributes),a=i.length,s=e.firstChild,c=e.tagName;n=z===e.namespaceURI||n,t.push("<",c);for(var u=0;u"),n&&/^script$/i.test(c))for(;s;)s.data?t.push(s.data):H(s,t,n,o,r),s=s.nextSibling;else for(;s;)H(s,t,n,o,r),s=s.nextSibling;t.push("")}else t.push("/>");return;case Z:case te:for(var s=e.firstChild;s;)H(s,t,n,o,r),s=s.nextSibling;return;case X:return t.push(" ",e.name,'="',e.value.replace(/[<&"]/g,p),'"');case V:return t.push(e.data.replace(/[<&]/g,p));case W:return t.push("");case Y:return t.push("\x3c!--",e.data,"--\x3e");case ee:var g=e.publicId,m=e.systemId;if(t.push("');else if(m&&"."!=m)t.push(' SYSTEM "',m,'">');else{var y=e.internalSubset;y&&t.push(" [",y,"]"),t.push(">")}return;case J:return t.push("");case $:return t.push("&",e.nodeName,";");default:t.push("??",e.nodeName)}}function L(e,t,n){var o;switch(t.nodeType){case q:o=t.cloneNode(!1),o.ownerDocument=e;case te:break;case X:n=!0}if(o||(o=t.cloneNode(!1)),o.ownerDocument=e,o.parentNode=null,n)for(var r=t.firstChild;r;)o.appendChild(L(e,r,n)),r=r.nextSibling;return o}function F(e,t,n){var o=new t.constructor;for(var r in t){var a=t[r];"object"!=typeof a&&a!=o[r]&&(o[r]=a)}switch(t.childNodes&&(o.childNodes=new i),o.ownerDocument=e,o.nodeType){case q:var s=t.attributes,u=o.attributes=new c,l=s.length;u._ownerElement=o;for(var d=0;d0},lookupPrefix:function(e){for(var t=this;t;){var n=t._nsMap;if(n)for(var o in n)if(n[o]==e)return o;t=t.nodeType==X?t.ownerDocument:t.parentNode}return null},lookupNamespaceURI:function(e){for(var t=this;t;){var n=t._nsMap;if(n&&e in n)return n[e];t=t.nodeType==X?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){return null==this.lookupPrefix(e)}},n(G,h),n(G,h.prototype),m.prototype={nodeName:"#document",nodeType:Z,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==te){for(var n=e.firstChild;n;){var o=n.nextSibling;this.insertBefore(n,t),n=o}return e}return null==this.documentElement&&e.nodeType==q&&(this.documentElement=e),R(this,e,t),e.ownerDocument=this,e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),k(this,e)},importNode:function(e,t){return L(this,e,t)},getElementById:function(e){var t=null;return g(this.documentElement,function(n){if(n.nodeType==q&&n.getAttribute("id")==e)return t=n,!0}),t},createElement:function(e){var t=new A;return t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.childNodes=new i,(t.attributes=new c)._ownerElement=t,t},createDocumentFragment:function(){var e=new O;return e.ownerDocument=this,e.childNodes=new i,e},createTextNode:function(e){var t=new T;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new x;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){var t=new E;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var n=new N;return n.ownerDocument=this,n.tagName=n.target=e,n.nodeValue=n.data=t,n},createAttribute:function(e){var t=new b;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){var t=new D;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var n=new A,o=t.split(":"),r=n.attributes=new c;return n.childNodes=new i,n.ownerDocument=this,n.nodeName=t,n.tagName=t,n.namespaceURI=e,2==o.length?(n.prefix=o[0],n.localName=o[1]):n.localName=t,r._ownerElement=n,n},createAttributeNS:function(e,t){var n=new b,o=t.split(":");return n.ownerDocument=this,n.nodeName=t,n.name=t,n.namespaceURI=e,n.specified=!0,2==o.length?(n.prefix=o[0],n.localName=o[1]):n.localName=t,n}},o(m,h),A.prototype={nodeType:q,hasAttribute:function(e){return null!=this.getAttributeNode(e)},getAttribute:function(e){var t=this.getAttributeNode(e);return t&&t.value||""},getAttributeNode:function(e){return this.attributes.getNamedItem(e)},setAttribute:function(e,t){var n=this.ownerDocument.createAttribute(e);n.value=n.nodeValue=""+t,this.setAttributeNode(n)},removeAttribute:function(e){var t=this.getAttributeNode(e);t&&this.removeAttributeNode(t)},appendChild:function(e){return e.nodeType===te?this.insertBefore(e,null):S(this,e)},setAttributeNode:function(e){return this.attributes.setNamedItem(e)},setAttributeNodeNS:function(e){return this.attributes.setNamedItemNS(e)},removeAttributeNode:function(e){return this.attributes.removeNamedItem(e.nodeName)},removeAttributeNS:function(e,t){var n=this.getAttributeNodeNS(e,t);n&&this.removeAttributeNode(n)},hasAttributeNS:function(e,t){return null!=this.getAttributeNodeNS(e,t)},getAttributeNS:function(e,t){var n=this.getAttributeNodeNS(e,t);return n&&n.value||""},setAttributeNS:function(e,t,n){var o=this.ownerDocument.createAttributeNS(e,t);o.value=o.nodeValue=""+n,this.setAttributeNode(o)},getAttributeNodeNS:function(e,t){return this.attributes.getNamedItemNS(e,t)},getElementsByTagName:function(e){return new a(this,function(t){var n=[];return g(t,function(o){o===t||o.nodeType!=q||"*"!==e&&o.tagName!=e||n.push(o)}),n})},getElementsByTagNameNS:function(e,t){return new a(this,function(n){var o=[];return g(n,function(r){r===n||r.nodeType!==q||"*"!==e&&r.namespaceURI!==e||"*"!==t&&r.localName!=t||o.push(r)}),o})}},m.prototype.getElementsByTagName=A.prototype.getElementsByTagName,m.prototype.getElementsByTagNameNS=A.prototype.getElementsByTagNameNS,o(A,h),b.prototype.nodeType=X,o(b,h),B.prototype={data:"",substringData:function(e,t){return this.data.substring(e,e+t)},appendData:function(e){e=this.data+e,this.nodeValue=this.data=e,this.length=e.length},insertData:function(e,t){this.replaceData(e,0,t)},appendChild:function(e){throw new Error(re[ie])},deleteData:function(e,t){this.replaceData(e,t,"")},replaceData:function(e,t,n){n=this.data.substring(0,e)+n+this.data.substring(e+t),this.nodeValue=this.data=n,this.length=n.length}},o(B,h),T.prototype={nodeName:"#text",nodeType:V,splitText:function(e){var t=this.data,n=t.substring(e);t=t.substring(0,e),this.data=this.nodeValue=t,this.length=t.length;var o=this.ownerDocument.createTextNode(n);return this.parentNode&&this.parentNode.insertBefore(o,this.nextSibling),o}},o(T,B),x.prototype={nodeName:"#comment",nodeType:Y},o(x,B),E.prototype={nodeName:"#cdata-section",nodeType:W},o(E,B),_.prototype.nodeType=ee,o(_,h),w.prototype.nodeType=ne,o(w,h),I.prototype.nodeType=Q,o(I,h),D.prototype.nodeType=$,o(D,h),O.prototype.nodeName="#document-fragment",O.prototype.nodeType=te,o(O,h),N.prototype.nodeType=J,o(N,h),P.prototype.serializeToString=function(e,t,n){return M.call(e,t,n)},h.prototype.toString=M;try{Object.defineProperty&&(Object.defineProperty(a.prototype,"length",{get:function(){return s(this),this.$$length}}),Object.defineProperty(h.prototype,"textContent",{get:function(){return j(this)},set:function(e){switch(this.nodeType){case q:case te:for(;this.firstChild;)this.removeChild(this.firstChild);(e||String(e))&&this.appendChild(this.ownerDocument.createTextNode(e));break;default:this.data=e,this.value=e,this.nodeValue=e}}}),K=function(e,t,n){e["$$"+t]=n})}catch(e){}t.DOMImplementation=f,t.XMLSerializer=P},function(e,t){var n=function(e){var t={},n=function(e){return!t[e]&&(t[e]=[]),t[e]};e.on=function(e,t){"task-list-update"===e&&console.warn('warning: Event "'+e+'" has been deprecated. Please use "list-update" instead.'),n(e).push(t)},e.off=function(e,t){for(var o=n(e),r=o.length-1;r>=0;r--)t===o[r]&&o.splice(r,1)},e.emit=function(e,t){for(var o=n(e).map(function(e){return e}),r=0;r=0;n--){var r=o[n][2];(!r||r+2592e3=0;r--){var i=o[r];i[0]===e&&i[1]===t&&o.splice(r,1)}o.unshift([e,t,Math.round(Date.now()/1e3)]),o.length>n&&o.splice(n),u()}},removeUploadId:function(e){c(),delete l.using[e];for(var t=o.length-1;t>=0;t--)o[t][1]===e&&o.splice(t,1);u()}};e.exports=l},function(e,t,n){var o=n(5);e.exports=o},function(e,t,n){"use strict";var o=n(0),r=n(2),i=n(15),a=n(16),s=n(18),c={AppId:"",SecretId:"",SecretKey:"",XCosSecurityToken:"",ChunkRetryTimes:2,FileParallelLimit:3,ChunkParallelLimit:3,ChunkSize:1048576,SliceSize:1048576,CopyChunkParallelLimit:20,CopyChunkSize:10485760,CopySliceSize:10485760,MaxPartNumber:1e4,ProgressInterval:1e3,UploadQueueSize:1e4,Domain:"",ServiceDomain:"",Protocol:"",CompatibilityMode:!1,ForcePathStyle:!1,UseRawKey:!1,Timeout:0,CorrectClockSkew:!0,SystemClockOffset:0,UploadCheckContentMd5:!1,UploadAddMetaMd5:!1,UploadIdCacheLimit:50},u=function(e){this.options=o.extend(o.clone(c),e||{}),this.options.FileParallelLimit=Math.max(1,this.options.FileParallelLimit),this.options.ChunkParallelLimit=Math.max(1,this.options.ChunkParallelLimit),this.options.ChunkRetryTimes=Math.max(0,this.options.ChunkRetryTimes),this.options.ChunkSize=Math.max(1048576,this.options.ChunkSize),this.options.CopyChunkParallelLimit=Math.max(1,this.options.CopyChunkParallelLimit),this.options.CopyChunkSize=Math.max(1048576,this.options.CopyChunkSize),this.options.CopySliceSize=Math.max(0,this.options.CopySliceSize),this.options.MaxPartNumber=Math.max(1024,Math.min(1e4,this.options.MaxPartNumber)),this.options.Timeout=Math.max(0,this.options.Timeout),this.options.AppId&&console.warn('warning: AppId has been deprecated, Please put it at the end of parameter Bucket(E.g: "test-1250000000").'),r.init(this),i.init(this)};a.init(u,i),s.init(u,i),u.getAuthorization=o.getAuth,u.version="1.1.11",e.exports=u},function(module,exports,__webpack_require__){(function(process,global){var __WEBPACK_AMD_DEFINE_RESULT__;!function(){"use strict";function Md5(e){if(e)blocks[0]=blocks[16]=blocks[1]=blocks[2]=blocks[3]=blocks[4]=blocks[5]=blocks[6]=blocks[7]=blocks[8]=blocks[9]=blocks[10]=blocks[11]=blocks[12]=blocks[13]=blocks[14]=blocks[15]=0,this.blocks=blocks,this.buffer8=buffer8;else if(ARRAY_BUFFER){var t=new ArrayBuffer(68);this.buffer8=new Uint8Array(t),this.blocks=new Uint32Array(t)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}var ERROR="input is invalid type",WINDOW="object"==typeof window,root=WINDOW?window:{};root.JS_MD5_NO_WINDOW&&(WINDOW=!1);var WEB_WORKER=!WINDOW&&"object"==typeof self,NODE_JS=!root.JS_MD5_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node;NODE_JS?root=global:WEB_WORKER&&(root=self);var COMMON_JS=!root.JS_MD5_NO_COMMON_JS&&"object"==typeof module&&module.exports,AMD=__webpack_require__(9),ARRAY_BUFFER=!root.JS_MD5_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,HEX_CHARS="0123456789abcdef".split(""),EXTRA=[128,32768,8388608,-2147483648],SHIFT=[0,8,16,24],OUTPUT_TYPES=["hex","array","digest","buffer","arrayBuffer","base64"],BASE64_ENCODE_CHAR="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),blocks=[],buffer8;if(ARRAY_BUFFER){var buffer=new ArrayBuffer(68);buffer8=new Uint8Array(buffer),blocks=new Uint32Array(buffer)}!root.JS_MD5_NO_NODE_JS&&Array.isArray||(Array.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),!ARRAY_BUFFER||!root.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});var createOutputMethod=function(e){return function(t,n){return new Md5(!0).update(t,n)[e]()}},createMethod=function(){var e=createOutputMethod("hex");NODE_JS&&(e=nodeWrap(e)),e.getCtx=e.create=function(){return new Md5},e.update=function(t){return e.create().update(t)};for(var t=0;t>2]|=e[a]<>6,u[i++]=128|63&r):r<55296||r>=57344?(u[i++]=224|r>>12,u[i++]=128|r>>6&63,u[i++]=128|63&r):(r=65536+((1023&r)<<10|1023&e.charCodeAt(++a)),u[i++]=240|r>>18,u[i++]=128|r>>12&63,u[i++]=128|r>>6&63,u[i++]=128|63&r);else for(i=this.start;a>2]|=r<>2]|=(192|r>>6)<>2]|=(128|63&r)<=57344?(c[i>>2]|=(224|r>>12)<>2]|=(128|r>>6&63)<>2]|=(128|63&r)<>2]|=(240|r>>18)<>2]|=(128|r>>12&63)<>2]|=(128|r>>6&63)<>2]|=(128|63&r)<=64?(this.start=i-64,this.hash(),this.hashed=!0):this.start=i}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},Md5.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[t>>2]|=EXTRA[3&t],t>=56&&(this.hashed||this.hash(),e[0]=e[16],e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.bytes<<3,e[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},Md5.prototype.hash=function(){var e,t,n,o,r,i,a=this.blocks;this.first?(e=a[0]-680876937,e=(e<<7|e>>>25)-271733879<<0,o=(-1732584194^2004318071&e)+a[1]-117830708,o=(o<<12|o>>>20)+e<<0,n=(-271733879^o&(-271733879^e))+a[2]-1126478375,n=(n<<17|n>>>15)+o<<0,t=(e^n&(o^e))+a[3]-1316259209,t=(t<<22|t>>>10)+n<<0):(e=this.h0,t=this.h1,n=this.h2,o=this.h3,e+=(o^t&(n^o))+a[0]-680876936,e=(e<<7|e>>>25)+t<<0,o+=(n^e&(t^n))+a[1]-389564586,o=(o<<12|o>>>20)+e<<0,n+=(t^o&(e^t))+a[2]+606105819,n=(n<<17|n>>>15)+o<<0,t+=(e^n&(o^e))+a[3]-1044525330,t=(t<<22|t>>>10)+n<<0),e+=(o^t&(n^o))+a[4]-176418897,e=(e<<7|e>>>25)+t<<0,o+=(n^e&(t^n))+a[5]+1200080426,o=(o<<12|o>>>20)+e<<0,n+=(t^o&(e^t))+a[6]-1473231341,n=(n<<17|n>>>15)+o<<0,t+=(e^n&(o^e))+a[7]-45705983,t=(t<<22|t>>>10)+n<<0,e+=(o^t&(n^o))+a[8]+1770035416,e=(e<<7|e>>>25)+t<<0,o+=(n^e&(t^n))+a[9]-1958414417,o=(o<<12|o>>>20)+e<<0,n+=(t^o&(e^t))+a[10]-42063,n=(n<<17|n>>>15)+o<<0,t+=(e^n&(o^e))+a[11]-1990404162,t=(t<<22|t>>>10)+n<<0,e+=(o^t&(n^o))+a[12]+1804603682,e=(e<<7|e>>>25)+t<<0,o+=(n^e&(t^n))+a[13]-40341101,o=(o<<12|o>>>20)+e<<0,n+=(t^o&(e^t))+a[14]-1502002290,n=(n<<17|n>>>15)+o<<0,t+=(e^n&(o^e))+a[15]+1236535329,t=(t<<22|t>>>10)+n<<0,e+=(n^o&(t^n))+a[1]-165796510,e=(e<<5|e>>>27)+t<<0,o+=(t^n&(e^t))+a[6]-1069501632,o=(o<<9|o>>>23)+e<<0,n+=(e^t&(o^e))+a[11]+643717713,n=(n<<14|n>>>18)+o<<0,t+=(o^e&(n^o))+a[0]-373897302,t=(t<<20|t>>>12)+n<<0,e+=(n^o&(t^n))+a[5]-701558691,e=(e<<5|e>>>27)+t<<0,o+=(t^n&(e^t))+a[10]+38016083,o=(o<<9|o>>>23)+e<<0,n+=(e^t&(o^e))+a[15]-660478335,n=(n<<14|n>>>18)+o<<0,t+=(o^e&(n^o))+a[4]-405537848,t=(t<<20|t>>>12)+n<<0,e+=(n^o&(t^n))+a[9]+568446438,e=(e<<5|e>>>27)+t<<0,o+=(t^n&(e^t))+a[14]-1019803690,o=(o<<9|o>>>23)+e<<0,n+=(e^t&(o^e))+a[3]-187363961,n=(n<<14|n>>>18)+o<<0,t+=(o^e&(n^o))+a[8]+1163531501,t=(t<<20|t>>>12)+n<<0,e+=(n^o&(t^n))+a[13]-1444681467,e=(e<<5|e>>>27)+t<<0,o+=(t^n&(e^t))+a[2]-51403784,o=(o<<9|o>>>23)+e<<0,n+=(e^t&(o^e))+a[7]+1735328473,n=(n<<14|n>>>18)+o<<0,t+=(o^e&(n^o))+a[12]-1926607734,t=(t<<20|t>>>12)+n<<0,r=t^n,e+=(r^o)+a[5]-378558,e=(e<<4|e>>>28)+t<<0,o+=(r^e)+a[8]-2022574463,o=(o<<11|o>>>21)+e<<0,i=o^e,n+=(i^t)+a[11]+1839030562,n=(n<<16|n>>>16)+o<<0,t+=(i^n)+a[14]-35309556,t=(t<<23|t>>>9)+n<<0,r=t^n,e+=(r^o)+a[1]-1530992060,e=(e<<4|e>>>28)+t<<0,o+=(r^e)+a[4]+1272893353,o=(o<<11|o>>>21)+e<<0,i=o^e,n+=(i^t)+a[7]-155497632,n=(n<<16|n>>>16)+o<<0,t+=(i^n)+a[10]-1094730640,t=(t<<23|t>>>9)+n<<0,r=t^n,e+=(r^o)+a[13]+681279174,e=(e<<4|e>>>28)+t<<0,o+=(r^e)+a[0]-358537222,o=(o<<11|o>>>21)+e<<0,i=o^e,n+=(i^t)+a[3]-722521979,n=(n<<16|n>>>16)+o<<0,t+=(i^n)+a[6]+76029189,t=(t<<23|t>>>9)+n<<0,r=t^n,e+=(r^o)+a[9]-640364487,e=(e<<4|e>>>28)+t<<0,o+=(r^e)+a[12]-421815835,o=(o<<11|o>>>21)+e<<0,i=o^e,n+=(i^t)+a[15]+530742520,n=(n<<16|n>>>16)+o<<0,t+=(i^n)+a[2]-995338651,t=(t<<23|t>>>9)+n<<0,e+=(n^(t|~o))+a[0]-198630844,e=(e<<6|e>>>26)+t<<0,o+=(t^(e|~n))+a[7]+1126891415,o=(o<<10|o>>>22)+e<<0,n+=(e^(o|~t))+a[14]-1416354905,n=(n<<15|n>>>17)+o<<0,t+=(o^(n|~e))+a[5]-57434055,t=(t<<21|t>>>11)+n<<0,e+=(n^(t|~o))+a[12]+1700485571,e=(e<<6|e>>>26)+t<<0,o+=(t^(e|~n))+a[3]-1894986606,o=(o<<10|o>>>22)+e<<0,n+=(e^(o|~t))+a[10]-1051523,n=(n<<15|n>>>17)+o<<0,t+=(o^(n|~e))+a[1]-2054922799,t=(t<<21|t>>>11)+n<<0,e+=(n^(t|~o))+a[8]+1873313359,e=(e<<6|e>>>26)+t<<0,o+=(t^(e|~n))+a[15]-30611744,o=(o<<10|o>>>22)+e<<0,n+=(e^(o|~t))+a[6]-1560198380,n=(n<<15|n>>>17)+o<<0,t+=(o^(n|~e))+a[13]+1309151649,t=(t<<21|t>>>11)+n<<0,e+=(n^(t|~o))+a[4]-145523070,e=(e<<6|e>>>26)+t<<0,o+=(t^(e|~n))+a[11]-1120210379,o=(o<<10|o>>>22)+e<<0,n+=(e^(o|~t))+a[2]+718787259,n=(n<<15|n>>>17)+o<<0,t+=(o^(n|~e))+a[9]-343485551,t=(t<<21|t>>>11)+n<<0,this.first?(this.h0=e+1732584193<<0,this.h1=t-271733879<<0,this.h2=n-1732584194<<0,this.h3=o+271733878<<0,this.first=!1):(this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+n<<0,this.h3=this.h3+o<<0)},Md5.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,o=this.h3;return HEX_CHARS[e>>4&15]+HEX_CHARS[15&e]+HEX_CHARS[e>>12&15]+HEX_CHARS[e>>8&15]+HEX_CHARS[e>>20&15]+HEX_CHARS[e>>16&15]+HEX_CHARS[e>>28&15]+HEX_CHARS[e>>24&15]+HEX_CHARS[t>>4&15]+HEX_CHARS[15&t]+HEX_CHARS[t>>12&15]+HEX_CHARS[t>>8&15]+HEX_CHARS[t>>20&15]+HEX_CHARS[t>>16&15]+HEX_CHARS[t>>28&15]+HEX_CHARS[t>>24&15]+HEX_CHARS[n>>4&15]+HEX_CHARS[15&n]+HEX_CHARS[n>>12&15]+HEX_CHARS[n>>8&15]+HEX_CHARS[n>>20&15]+HEX_CHARS[n>>16&15]+HEX_CHARS[n>>28&15]+HEX_CHARS[n>>24&15]+HEX_CHARS[o>>4&15]+HEX_CHARS[15&o]+HEX_CHARS[o>>12&15]+HEX_CHARS[o>>8&15]+HEX_CHARS[o>>20&15]+HEX_CHARS[o>>16&15]+HEX_CHARS[o>>28&15]+HEX_CHARS[o>>24&15]},Md5.prototype.toString=Md5.prototype.hex,Md5.prototype.digest=function(e){if("hex"===e)return this.hex();this.finalize();var t=this.h0,n=this.h1,o=this.h2,r=this.h3;return[255&t,t>>8&255,t>>16&255,t>>24&255,255&n,n>>8&255,n>>16&255,n>>24&255,255&o,o>>8&255,o>>16&255,o>>24&255,255&r,r>>8&255,r>>16&255,r>>24&255]},Md5.prototype.array=Md5.prototype.digest,Md5.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(16),t=new Uint32Array(e);return t[0]=this.h0,t[1]=this.h1,t[2]=this.h2,t[3]=this.h3,e},Md5.prototype.buffer=Md5.prototype.arrayBuffer,Md5.prototype.base64=function(){for(var e,t,n,o="",r=this.array(),i=0;i<15;)e=r[i++],t=r[i++],n=r[i++],o+=BASE64_ENCODE_CHAR[e>>>2]+BASE64_ENCODE_CHAR[63&(e<<4|t>>>4)]+BASE64_ENCODE_CHAR[63&(t<<2|n>>>6)]+BASE64_ENCODE_CHAR[63&n];return e=r[i],o+=BASE64_ENCODE_CHAR[e>>>2]+BASE64_ENCODE_CHAR[e<<4&63]+"=="};var exports=createMethod();COMMON_JS?module.exports=exports:(root.md5=exports,AMD&&void 0!==(__WEBPACK_AMD_DEFINE_RESULT__=function(){return exports}.call(exports,__webpack_require__,exports,module))&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))}()}).call(exports,__webpack_require__(7),__webpack_require__(8))},function(e,t){function n(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function r(e){if(l===setTimeout)return setTimeout(e,0);if((l===n||!l)&&setTimeout)return l=setTimeout,setTimeout(e,0);try{return l(e,0)}catch(t){try{return l.call(null,e,0)}catch(t){return l.call(this,e,0)}}}function i(e){if(d===clearTimeout)return clearTimeout(e);if((d===o||!d)&&clearTimeout)return d=clearTimeout,clearTimeout(e);try{return d(e)}catch(t){try{return d.call(null,e)}catch(t){return d.call(this,e)}}}function a(){g&&h&&(g=!1,h.length?p=h.concat(p):m=-1,p.length&&s())}function s(){if(!g){var e=r(a);g=!0;for(var t=p.length;t;){for(h=p,p=[];++m1)for(var n=1;n>>2]|=(n[r>>>2]>>>24-r%4*8&255)<<24-(o+r)%4*8;else if(65535>>2]=n[r>>>2];else t.push.apply(t,n);return this.sigBytes+=e,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n=[],o=0;o>>2]>>>24-o%4*8&255;n.push((r>>>4).toString(16)),n.push((15&r).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,n=[],o=0;o>>3]|=parseInt(e.substr(o,2),16)<<24-o%8*4;return new a.init(n,t/2)}},u=s.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],o=0;o>>2]>>>24-o%4*8&255));return n.join("")},parse:function(e){for(var t=e.length,n=[],o=0;o>>2]|=(255&e.charCodeAt(o))<<24-o%4*8;return new a.init(n,t)}},l=s.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},d=o.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new a.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=l.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,o=n.words,r=n.sigBytes,i=this.blockSize,s=r/(4*i),s=t?e.ceil(s):e.max((0|s)-this._minBufferSize,0);if(t=s*i,r=e.min(4*t,r),t){for(var c=0;cu;u++){if(16>u)i[u]=0|e[t+u];else{var l=i[u-3]^i[u-8]^i[u-14]^i[u-16];i[u]=l<<1|l>>>31}l=(o<<5|o>>>27)+c+i[u],l=20>u?l+(1518500249+(r&a|~r&s)):40>u?l+(1859775393+(r^a^s)):60>u?l+((r&a|r&s|a&s)-1894007588):l+((r^a^s)-899497514),c=s,s=a,a=r<<30|r>>>2,r=o,o=l}n[0]=n[0]+o|0,n[1]=n[1]+r|0,n[2]=n[2]+a|0,n[3]=n[3]+s|0,n[4]=n[4]+c|0},_doFinalize:function(){var e=this._data,t=e.words,n=8*this._nDataBytes,o=8*e.sigBytes;return t[o>>>5]|=128<<24-o%32,t[14+(o+64>>>9<<4)]=Math.floor(n/4294967296),t[15+(o+64>>>9<<4)]=n,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}});e.SHA1=r._createHelper(t),e.HmacSHA1=r._createHmacHelper(t)}(),function(){var e=o,t=e.enc.Utf8;e.algo.HMAC=e.lib.Base.extend({init:function(e,n){e=this._hasher=new e.init,"string"==typeof n&&(n=t.parse(n));var o=e.blockSize,r=4*o;n.sigBytes>r&&(n=e.finalize(n)),n.clamp();for(var i=this._oKey=n.clone(),a=this._iKey=n.clone(),s=i.words,c=a.words,u=0;u>>2]>>>24-i%4*8&255,s=t[i+1>>>2]>>>24-(i+1)%4*8&255,c=t[i+2>>>2]>>>24-(i+2)%4*8&255,u=a<<16|s<<8|c,l=0;l<4&&i+.75*l>>6*(3-l)&63));var d=o.charAt(64);if(d)for(;r.length%4;)r.push(d);return r.join("")},parse:function(e){var t=e.length,o=this._map,r=o.charAt(64);if(r){var i=e.indexOf(r);-1!=i&&(t=i)}for(var a=[],s=0,c=0;c>>6-c%4*2;a[s>>>2]|=(u|l)<<24-s%4*8,s++}return n.create(a,s)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),e.exports=o},function(e,t,n){var o=n(12).DOMParser,r=function(){this.version="1.3.5";var e={mergeCDATA:!0,normalize:!0,stripElemPrefix:!0},t=new RegExp(/(?!xmlns)^.*:/);new RegExp(/^\s+|\s+$/g);return this.grokType=function(e){return/^\s*$/.test(e)?null:/^(?:true|false)$/i.test(e)?"true"===e.toLowerCase():isFinite(e)?parseFloat(e):e},this.parseString=function(e,t){if(e){var n=this.stringToXML(e);return n.getElementsByTagName("parsererror").length?null:this.parseXML(n,t)}return null},this.parseXML=function(n,o){for(var i in o)e[i]=o[i];var a={},s=0,c="";if(n.childNodes.length)for(var u,l,d,f=0;f=t+n||t?new java.lang.String(e,t,n)+"":e}function u(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}o.prototype.parseFromString=function(e,t){var n=this.options,o=new l,a=n.domBuilder||new i,s=n.errorHandler,c=n.locator,u=n.xmlns||{},d={lt:"<",gt:">",amp:"&",quot:'"',apos:"'"};return c&&a.setDocumentLocator(c),o.errorHandler=r(s,a,c),o.domBuilder=n.domBuilder||a,/\/x?html?$/.test(t)&&(d.nbsp="\xa0",d.copy="\xa9",u[""]="http://www.w3.org/1999/xhtml"),u.xml=u.xml||"http://www.w3.org/XML/1998/namespace",e?o.parse(e,u,d):o.errorHandler.error("invalid doc source"),a.doc},i.prototype={startDocument:function(){this.doc=(new d).createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(e,t,n,o){var r=this.doc,i=r.createElementNS(e,n||t),s=o.length;u(this,i),this.currentElement=i,this.locator&&a(this.locator,i);for(var c=0;c65535){e-=65536;var t=55296+(e>>10),n=56320+(1023&e);return String.fromCharCode(t,n)}return String.fromCharCode(e)}function p(e){var t=e.slice(1,-1);return t in n?n[t]:"#"===t.charAt(0)?h(parseInt(t.substr(1).replace("x","0x"))):(u.error("entity not found:"+e),e)}function g(t){if(t>A){var n=e.substring(A,t).replace(/&#?\w+;/g,p);k&&m(A),o.characters(n,0,t-A),A=t}}function m(t,n){for(;t>=C&&(n=v.exec(e));)y=n.index,C=y+n[0].length,k.lineNumber++;k.columnNumber=t-y+1}for(var y=0,C=0,v=/.*(?:\r\n?|\n)|.*$/g,k=o.locator,R=[{currentNSMap:t}],S={},A=0;;){try{var b=e.indexOf("<",A);if(b<0){if(!e.substr(A).match(/^\s*$/)){var B=o.doc,T=B.createTextNode(e.substr(A));B.appendChild(T),o.currentElement=T}return}switch(b>A&&g(b),e.charAt(b+1)){case"/":var x=e.indexOf(">",b+3),E=e.substring(b+2,x),_=R.pop();x<0?(E=e.substring(b+2).replace(/[\s<].*/,""),u.error("end tag name: "+E+" is not complete:"+_.tagName),x=b+1+E.length):E.match(/\sA?A=x:g(Math.max(b,A)+1)}}function r(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function i(e,t,n,o,r,i){for(var a,s,c=++t,u=C;;){var l=e.charAt(c);switch(l){case"=":if(u===v)a=e.slice(t,c),u=R;else{if(u!==k)throw new Error("attribute equal must after attrName");u=R}break;case"'":case'"':if(u===R||u===v){if(u===v&&(i.warning('attribute value must after "="'),a=e.slice(t,c)),t=c+1,!((c=e.indexOf(l,t))>0))throw new Error("attribute value no end '"+l+"' match");s=e.slice(t,c).replace(/&#?\w+;/g,r),n.add(a,s,t-1),u=A}else{if(u!=S)throw new Error('attribute value must after "="');s=e.slice(t,c).replace(/&#?\w+;/g,r),n.add(a,s,t),i.warning('attribute "'+a+'" missed start quot('+l+")!!"),t=c+1,u=A}break;case"/":switch(u){case C:n.setTagName(e.slice(t,c));case A:case b:case B:u=B,n.closed=!0;case S:case v:case k:break;default:throw new Error("attribute invalid close char('/')")}break;case"":return i.error("unexpected end of input"),u==C&&n.setTagName(e.slice(t,c)),c;case">":switch(u){case C:n.setTagName(e.slice(t,c));case A:case b:case B:break;case S:case v:s=e.slice(t,c),"/"===s.slice(-1)&&(n.closed=!0,s=s.slice(0,-1));case k:u===k&&(s=a),u==S?(i.warning('attribute "'+s+'" missed quot(")!!'),n.add(a,s.replace(/&#?\w+;/g,r),t)):("http://www.w3.org/1999/xhtml"===o[""]&&s.match(/^(?:disabled|checked|selected)$/i)||i.warning('attribute "'+s+'" missed value!! "'+s+'" instead!!'),n.add(s,s,t));break;case R:throw new Error("attribute value missed!!")}return c;case"\x80":l=" ";default:if(l<=" ")switch(u){case C:n.setTagName(e.slice(t,c)),u=b;break;case v:a=e.slice(t,c),u=k;break;case S:var s=e.slice(t,c).replace(/&#?\w+;/g,r);i.warning('attribute "'+s+'" missed quot(")!!'),n.add(a,s,t);case A:u=b}else switch(u){case k:n.tagName;"http://www.w3.org/1999/xhtml"===o[""]&&a.match(/^(?:disabled|checked|selected)$/i)||i.warning('attribute "'+a+'" missed value!! "'+a+'" instead2!!'),n.add(a,a,t),t=c,u=v;break;case A:i.warning('attribute space is required"'+a+'"!!');case b:u=v,t=c;break;case R:u=S,t=c;break;case B:throw new Error("elements closed character '/' and '>' must be connected to")}}c++}}function a(e,t,n){for(var o=e.tagName,r=null,i=e.length;i--;){var a=e[i],s=a.qName,c=a.value,l=s.indexOf(":");if(l>0)var d=a.prefix=s.slice(0,l),f=s.slice(l+1),h="xmlns"===d&&f;else f=s,d=null,h="xmlns"===s&&"";a.localName=f,!1!==h&&(null==r&&(r={},u(n,n={})),n[h]=r[h]=c,a.uri="http://www.w3.org/2000/xmlns/",t.startPrefixMapping(h,c))}for(var i=e.length;i--;){a=e[i];var d=a.prefix;d&&("xml"===d&&(a.uri="http://www.w3.org/XML/1998/namespace"),"xmlns"!==d&&(a.uri=n[d||""]))}var l=o.indexOf(":");l>0?(d=e.prefix=o.slice(0,l),f=e.localName=o.slice(l+1)):(d=null,f=e.localName=o);var p=e.uri=n[d||""];if(t.startElement(p,f,o,e),!e.closed)return e.currentNSMap=n,e.localNSMap=r,!0;if(t.endElement(p,f,o),r)for(d in r)t.endPrefixMapping(d)}function s(e,t,n,o,r){if(/^(?:script|textarea)$/i.test(n)){var i=e.indexOf("",t),a=e.substring(t+1,i);if(/[&<]/.test(a))return/^script$/i.test(n)?(r.characters(a,0,a.length),i):(a=a.replace(/&#?\w+;/g,o),r.characters(a,0,a.length),i)}return t+1}function c(e,t,n,o){var r=o[n];return null==r&&(r=e.lastIndexOf(""),rt?(n.comment(e,t+4,r-t-4),r+3):(o.error("Unclosed comment"),-1)}return-1;default:if("CDATA["==e.substr(t+3,6)){var r=e.indexOf("]]>",t+9);return n.startCDATA(),n.characters(e,t+9,r-t-9),n.endCDATA(),r+3}var i=p(e,t),a=i.length;if(a>1&&/!doctype/i.test(i[0][0])){var s=i[1][0],c=a>3&&/^public$/i.test(i[2][0])&&i[3][0],u=a>4&&i[4][0],l=i[a-1];return n.startDTD(s,c&&c.replace(/^(['"])(.*?)\1$/,"$2"),u&&u.replace(/^(['"])(.*?)\1$/,"$2")),n.endDTD(),l.index+l[0].length}}return-1}function d(e,t,n){var o=e.indexOf("?>",t);if(o){var r=e.substring(t,o).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);if(r){r[0].length;return n.processingInstruction(r[1],r[2]),o+2}return-1}return-1}function f(e){}function h(e,t){return e.__proto__=t,e}function p(e,t){var n,o=[],r=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(r.lastIndex=t,r.exec(e);n=r.exec(e);)if(o.push(n),n[1])return o}var g=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,m=new RegExp("[\\-\\.0-9"+g.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),y=new RegExp("^"+g.source+m.source+"*(?::"+g.source+m.source+"*)?$"),C=0,v=1,k=2,R=3,S=4,A=5,b=6,B=7;n.prototype={parse:function(e,t,n){var r=this.domBuilder;r.startDocument(),u(t,t={}),o(e,t,n,r,this.errorHandler),r.endDocument()}},f.prototype={setTagName:function(e){if(!y.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},add:function(e,t,n){if(!y.test(e))throw new Error("invalid attribute:"+e);this[this.length++]={qName:e,value:t,offset:n}},length:0,getLocalName:function(e){return this[e].localName},getLocator:function(e){return this[e].locator},getQName:function(e){return this[e].qName},getURI:function(e){return this[e].uri},getValue:function(e){return this[e].value}},h({},h.prototype)instanceof h||(h=function(e,t){function n(){}n.prototype=t,n=new n;for(t in e)n[t]=e[t];return n}),t.XMLReader=n},function(e,t){function n(e){return(""+e).replace(/&/g,"&").replace(//g,">").replace(/'/g,"'").replace(/"/g,""").replace(r,"")}var o=new RegExp("^([^a-zA-Z_\xc0-\xd6\xd8-\xf6\xf8-\xff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fff\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd])|^((x|X)(m|M)(l|L))|([^a-zA-Z_\xc0-\xd6\xd8-\xf6\xf8-\xff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fff\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd-.0-9\xb7\u0300-\u036f\u203f\u2040])","g"),r=/[^\x09\x0A\x0D\x20-\xFF\x85\xA0-\uD7FF\uE000-\uFDCF\uFDE0-\uFFFD]/gm,i=function(e){var t=[];if(e instanceof Object)for(var n in e)e.hasOwnProperty(n)&&t.push(n);return t},a=function(e,t){var r=function(e,n,r,i,a){var s=void 0!==t.indent?t.indent:"\t",c=t.prettyPrint?"\n"+new Array(i).join(s):"";t.removeIllegalNameCharacters&&(e=e.replace(o,"_"));var u=[c,"<",e,r||""];return n&&n.length>0?(u.push(">"),u.push(n),a&&u.push(c),u.push("")):u.push("/>"),u.join("")};return function e(o,a,s){var c=typeof o;switch((Array.isArray?Array.isArray(o):o instanceof Array)?c="array":o instanceof Date&&(c="date"),c){case"array":var u=[];return o.map(function(t){u.push(e(t,1,s+1))}),t.prettyPrint&&u.push("\n"),u.join("");case"date":return o.toJSON?o.toJSON():o+"";case"object":var l=[];for(var d in o)if(o.hasOwnProperty(d))if(o[d]instanceof Array)for(var f=0;f0&&l.push("\n"),l.join("");case"function":return o();default:return t.escape?n(o):""+o}}(e,0,0)},s=function(e){var t=['"),t.join("")};e.exports=function(e,t){if(t||(t={xmlHeader:{standalone:!0},prettyPrint:!0,indent:" ",escape:!0}),"string"==typeof e)try{e=JSON.parse(e.toString())}catch(e){return!1}var n="",o="";return t&&("object"==typeof t?(t.xmlHeader&&(n=s(!!t.xmlHeader.standalone)),void 0!==t.docType&&(o="")):n=s()),t=t||{},[n,t.prettyPrint&&o?"\n":"",o,a(e,t)].join("").replace(/\n{2,}/g,"\n").replace(/\s+$/g,"")}},function(e,t,n){var o=n(3),r=n(0),i={},a=function(e,t){i[t]=e[t],e[t]=function(e,n){e.SkipTask?i[t].call(this,e,n):this._addTask(t,e,n)}},s=function(e){var t=[],n={},a=0,s=0,c=function(e){var t={id:e.id,Bucket:e.Bucket,Region:e.Region,Key:e.Key,FilePath:e.FilePath,state:e.state,loaded:e.loaded,size:e.size,speed:e.speed,percent:e.percent,hashPercent:e.hashPercent,error:e.error};return e.FilePath&&(t.FilePath=e.FilePath),e._custom&&(t._custom=e._custom),t},u=function(){var n,o=function(){n=0,e.emit("task-list-update",{list:r.map(t,c)}),e.emit("list-update",{list:r.map(t,c)})};return function(){n||(n=setTimeout(o))}}(),l=function(){if(!(t.length<=e.options.UploadQueueSize)){for(var o=0;oe.options.UploadQueueSize;){var r="waiting"===t[o].state||"checking"===t[o].state||"uploading"===t[o].state;t[o]&&r?o++:(n[t[o].id]&&delete n[t[o].id],t.splice(o,1),s--)}u()}},d=function(){if(!(a>=e.options.FileParallelLimit)){for(;t[s]&&"waiting"!==t[s].state;)s++;if(!(s>=t.length)){var n=t[s];s++,a++,n.state="checking",n.params.onTaskStart&&n.params.onTaskStart(c(n)),!n.params.UploadData&&(n.params.UploadData={});var o=r.formatParams(n.api,n.params);i[n.api].call(e,o,function(t,o){e._isRunningTask(n.id)&&("checking"!==n.state&&"uploading"!==n.state||(n.state=t?"error":"success",t&&(n.error=t),a--,u(),d(),n.callback&&n.callback(t,o),"success"===n.state&&(n.params&&(delete n.params.UploadData,delete n.params.Body,delete n.params),delete n.callback)),l())}),u(),setTimeout(d)}}},f=function(t,r){var i=n[t];if(i){var s=i&&"waiting"===i.state,c=i&&("checking"===i.state||"uploading"===i.state);if("canceled"===r&&"canceled"!==i.state||"paused"===r&&s||"paused"===r&&c){if("paused"===r&&i.params.Body&&"function"==typeof i.params.Body.pipe)return void console.error("stream not support pause");i.state=r,e.emit("inner-kill-task",{TaskId:t,toState:r});try{var f=i&&i.params&&i.params.UploadData.UploadId}catch(e){}"canceled"===r&&f&&o.removeUsing(f),u(),c&&(a--,d()),"canceled"===r&&(i.params&&(delete i.params.UploadData,delete i.params.Body,delete i.params),delete i.callback)}l()}};e._addTasks=function(t){r.each(t,function(t){e._addTask(t.api,t.params,t.callback,!0)}),u()};var h=!0;e._addTask=function(o,i,a,s){i=r.formatParams(o,i);var c=r.uuid();i.TaskId=c,i.onTaskReady&&i.onTaskReady(c),i.TaskReady&&(i.TaskReady(c),h&&console.warn('warning: Param "TaskReady" has been deprecated. Please use "onTaskReady" instead.'),h=!1);var f={params:i,callback:a,api:o,index:t.length,id:c,Bucket:i.Bucket,Region:i.Region,Key:i.Key,FilePath:i.FilePath||"",state:"waiting",loaded:0,size:0,speed:0,percent:0,hashPercent:0,error:null,_custom:i._custom},p=i.onHashProgress;i.onHashProgress=function(t){e._isRunningTask(f.id)&&(f.hashPercent=t.percent,p&&p(t),u())};var g=i.onProgress;return i.onProgress=function(t){e._isRunningTask(f.id)&&("checking"===f.state&&(f.state="uploading"),f.loaded=t.loaded,f.speed=t.speed,f.percent=t.percent,g&&g(t),u())},r.getFileSize(o,i,function(e,o){if(e)return void a(e);n[c]=f,t.push(f),f.size=o,!s&&u(),d(),l()}),c},e._isRunningTask=function(e){var t=n[e];return!(!t||"checking"!==t.state&&"uploading"!==t.state)},e.getTaskList=function(){return r.map(t,c)},e.cancelTask=function(e){f(e,"canceled")},e.pauseTask=function(e){f(e,"paused")},e.restartTask=function(e){var t=n[e];!t||"paused"!==t.state&&"error"!==t.state||(t.state="waiting",u(),s=Math.min(s,t.index),d())},e.isUploadRunning=function(){return a||s/gi,"<$1Rule>"),o=o.replace(/<(\/?)Tags>/gi,"<$1Tag>");var r=e.Headers;r["Content-Type"]="application/xml",r["Content-MD5"]=Te.binaryBase64(Te.md5(o)),Se.call(this,{Action:"name/cos:PutBucketReplication",method:"PUT",Bucket:e.Bucket,Region:e.Region,body:o,action:"replication",headers:r},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function T(e,t){Se.call(this,{Action:"name/cos:GetBucketReplication",method:"GET",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"replication"},function(e,n){if(e)if(404!==e.statusCode||!e.error||"Not Found"!==e.error&&"ReplicationConfigurationnotFoundError"!==e.error.Code)t(e);else{var o={ReplicationConfiguration:{Rules:[]},statusCode:e.statusCode};e.headers&&(o.headers=e.headers),t(null,o)}else e||!n.ReplicationConfiguration&&(n.ReplicationConfiguration={}),n.ReplicationConfiguration.Rule&&(n.ReplicationConfiguration.Rules=n.ReplicationConfiguration.Rule,delete n.ReplicationConfiguration.Rule),t(e,n)})}function x(e,t){Se.call(this,{Action:"name/cos:DeleteBucketReplication",method:"DELETE",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"replication"},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function E(e,t){if(!e.WebsiteConfiguration)return void t({error:"missing param WebsiteConfiguration"});var n=Te.clone(e.WebsiteConfiguration||{}),o=n.RoutingRules||n.RoutingRule||[];o=Te.isArray(o)?o:[o],delete n.RoutingRule,delete n.RoutingRules,o.length&&(n.RoutingRules={RoutingRule:o});var r=Te.json2xml({WebsiteConfiguration:n}),i=e.Headers;i["Content-Type"]="application/xml",i["Content-MD5"]=Te.binaryBase64(Te.md5(r)),Se.call(this,{Action:"name/cos:PutBucketWebsite",method:"PUT",Bucket:e.Bucket,Region:e.Region,body:r,action:"website",headers:i},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function _(e,t){Se.call(this,{Action:"name/cos:GetBucketWebsite",method:"GET",Bucket:e.Bucket,Region:e.Region,Key:e.Key,headers:e.Headers,action:"website"},function(e,n){if(e)if(404===e.statusCode&&"NoSuchWebsiteConfiguration"===e.error.Code){var o={WebsiteConfiguration:{},statusCode:e.statusCode};e.headers&&(o.headers=e.headers),t(null,o)}else t(e);else{var r=n.WebsiteConfiguration||{};if(r.RoutingRules){var i=Te.clone(r.RoutingRules.RoutingRule||[]);i=Te.makeArray(i),r.RoutingRules=i}t(null,{WebsiteConfiguration:r,statusCode:n.statusCode,headers:n.headers})}})}function w(e,t){Se.call(this,{Action:"name/cos:DeleteBucketWebsite",method:"DELETE",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"website"},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function I(e,t){if(!e.RefererConfiguration)return void t({error:"missing param RefererConfiguration"});var n=Te.clone(e.RefererConfiguration||{}),o=n.DomainList||{},r=o.Domains||o.Domain||[];r=Te.isArray(r)?r:[r],r.length&&(n.DomainList={Domain:r});var i=Te.json2xml({RefererConfiguration:n}),a=e.Headers;a["Content-Type"]="application/xml",a["Content-MD5"]=Te.binaryBase64(Te.md5(i)),Se.call(this,{Action:"name/cos:PutBucketReferer",method:"PUT",Bucket:e.Bucket,Region:e.Region,body:i,action:"referer",headers:a},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function D(e,t){Se.call(this,{Action:"name/cos:GetBucketReferer",method:"GET",Bucket:e.Bucket,Region:e.Region,Key:e.Key,headers:e.Headers,action:"referer"},function(e,n){if(e)if(404===e.statusCode&&"NoSuchRefererConfiguration"===e.error.Code){var o={WebsiteConfiguration:{},statusCode:e.statusCode};e.headers&&(o.headers=e.headers),t(null,o)}else t(e);else{var r=n.RefererConfiguration||{};if(r.DomainList){var i=Te.clone(r.DomainList.Domain||[]);i=Te.makeArray(i),r.DomainList={Domains:i}}t(null,{RefererConfiguration:r,statusCode:n.statusCode,headers:n.headers})}})}function O(e,t){var n=e.DomainConfiguration||{},o=n.DomainRule||e.DomainRule||[];o=Te.clone(o);var r=Te.json2xml({DomainConfiguration:{DomainRule:o}}),i=e.Headers;i["Content-Type"]="application/xml",i["Content-MD5"]=Te.binaryBase64(Te.md5(r)),Se.call(this,{Action:"name/cos:PutBucketDomain",method:"PUT",Bucket:e.Bucket,Region:e.Region,body:r,action:"domain",headers:i},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function N(e,t){Se.call(this,{Action:"name/cos:GetBucketDomain",method:"GET",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"domain"},function(e,n){if(e)return t(e);var o=[];try{o=n.DomainConfiguration.DomainRule||[]}catch(e){}o=Te.clone(Te.isArray(o)?o:[o]),t(null,{DomainRule:o,statusCode:n.statusCode,headers:n.headers})})}function P(e,t){Se.call(this,{Action:"name/cos:DeleteBucketDomain",method:"DELETE",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"domain"},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function M(e,t){var n=e.OriginConfiguration||{},o=n.OriginRule||e.OriginRule||[];o=Te.clone(o);var r=Te.json2xml({OriginConfiguration:{OriginRule:o}}),i=e.Headers;i["Content-Type"]="application/xml",i["Content-MD5"]=Te.binaryBase64(Te.md5(r)),Se.call(this,{Action:"name/cos:PutBucketOrigin",method:"PUT",Bucket:e.Bucket,Region:e.Region,body:r,action:"origin",headers:i},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function U(e,t){Se.call(this,{Action:"name/cos:GetBucketOrigin",method:"GET",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"origin"},function(e,n){if(e)return t(e);var o=[];try{o=n.OriginConfiguration.OriginRule||[]}catch(e){}o=Te.clone(Te.isArray(o)?o:[o]),t(null,{OriginRule:o,statusCode:n.statusCode,headers:n.headers})})}function H(e,t){Se.call(this,{Action:"name/cos:DeleteBucketOrigin",method:"DELETE",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"origin"},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function L(e,t){var n=Te.json2xml({BucketLoggingStatus:e.BucketLoggingStatus||""}),o=e.Headers;o["Content-Type"]="application/xml",o["Content-MD5"]=Te.binaryBase64(Te.md5(n)),Se.call(this,{Action:"name/cos:PutBucketLogging",method:"PUT",Bucket:e.Bucket,Region:e.Region,body:n,action:"logging",headers:o},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function F(e,t){Se.call(this,{Action:"name/cos:GetBucketLogging",method:"GET",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"logging"},function(e,n){if(e)return t(e);t(null,{BucketLoggingStatus:n.BucketLoggingStatus,statusCode:n.statusCode,headers:n.headers})})}function K(e,t){var n=Te.clone(e.InventoryConfiguration);if(n.OptionalFields){var o=n.OptionalFields||[];n.OptionalFields={Field:o}}if(n.Destination&&n.Destination.COSBucketDestination&&n.Destination.COSBucketDestination.Encryption){var r=n.Destination.COSBucketDestination.Encryption;Object.keys(r).indexOf("SSECOS")>-1&&(r["SSE-COS"]=r.SSECOS,delete r.SSECOS)}var i=Te.json2xml({InventoryConfiguration:n}),a=e.Headers;a["Content-Type"]="application/xml",a["Content-MD5"]=Te.binaryBase64(Te.md5(i)),Se.call(this,{Action:"name/cos:PutBucketInventory",method:"PUT",Bucket:e.Bucket,Region:e.Region,body:i,action:"inventory",qs:{id:e.Id},headers:a},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function j(e,t){Se.call(this,{Action:"name/cos:GetBucketInventory",method:"GET",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"inventory",qs:{id:e.Id}},function(e,n){if(e)return t(e);var o=n.InventoryConfiguration;if(o&&o.OptionalFields&&o.OptionalFields.Field){var r=o.OptionalFields.Field;Te.isArray(r)||(r=[r]),o.OptionalFields=r}if(o.Destination&&o.Destination.COSBucketDestination&&o.Destination.COSBucketDestination.Encryption){var i=o.Destination.COSBucketDestination.Encryption;Object.keys(i).indexOf("SSE-COS")>-1&&(i.SSECOS=i["SSE-COS"],delete i["SSE-COS"])}t(null,{InventoryConfiguration:o,statusCode:n.statusCode,headers:n.headers})})}function z(e,t){Se.call(this,{Action:"name/cos:ListBucketInventory",method:"GET",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"inventory",qs:{"continuation-token":e.ContinuationToken}},function(e,n){if(e)return t(e);var o=n.ListInventoryConfigurationResult,r=o.InventoryConfiguration||[];r=Te.isArray(r)?r:[r],delete o.InventoryConfiguration,Te.each(r,function(e){if(e&&e.OptionalFields&&e.OptionalFields.Field){var t=e.OptionalFields.Field;Te.isArray(t)||(t=[t]),e.OptionalFields=t}if(e.Destination&&e.Destination.COSBucketDestination&&e.Destination.COSBucketDestination.Encryption){var n=e.Destination.COSBucketDestination.Encryption;Object.keys(n).indexOf("SSE-COS")>-1&&(n.SSECOS=n["SSE-COS"],delete n["SSE-COS"])}}),o.InventoryConfigurations=r,Te.extend(o,{statusCode:n.statusCode,headers:n.headers}),t(null,o)})}function G(e,t){Se.call(this,{Action:"name/cos:DeleteBucketInventory",method:"DELETE",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"inventory",qs:{id:e.Id}},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function q(e,t){if(!e.AccelerateConfiguration)return void t({error:"missing param AccelerateConfiguration"});var n={AccelerateConfiguration:e.AccelerateConfiguration||{}},o=Te.json2xml(n),r={};r["Content-Type"]="application/xml",r["Content-MD5"]=Te.binaryBase64(Te.md5(o)),Se.call(this,{Action:"name/cos:PutBucketAccelerate",method:"PUT",Bucket:e.Bucket,Region:e.Region,body:o,action:"accelerate",headers:r},function(e,n){if(e)return t(e);t(null,{statusCode:n.statusCode,headers:n.headers})})}function X(e,t){Se.call(this,{Action:"name/cos:GetBucketAccelerate",method:"GET",Bucket:e.Bucket,Region:e.Region,action:"accelerate"},function(e,n){e||!n.AccelerateConfiguration&&(n.AccelerateConfiguration={}),t(e,n)})}function V(e,t){Se.call(this,{Action:"name/cos:HeadObject",method:"HEAD",Bucket:e.Bucket,Region:e.Region,Key:e.Key,VersionId:e.VersionId,headers:e.Headers},function(n,o){if(n){var r=n.statusCode;return e.Headers["If-Modified-Since"]&&r&&304===r?t(null,{NotModified:!0,statusCode:r}):t(n)}o.ETag=Te.attr(o.headers,"etag",""),t(null,o)})}function W(e,t){var n={};n.prefix=e.Prefix||"",n.delimiter=e.Delimiter,n["key-marker"]=e.KeyMarker,n["version-id-marker"]=e.VersionIdMarker,n["max-keys"]=e.MaxKeys,n["encoding-type"]=e.EncodingType,Se.call(this,{Action:"name/cos:GetBucketObjectVersions",ResourceKey:n.prefix,method:"GET",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,qs:n,action:"versions"},function(e,n){if(e)return t(e);var o=n.ListVersionsResult||{},r=o.DeleteMarker||[];r=Te.isArray(r)?r:[r];var i=o.Version||[];i=Te.isArray(i)?i:[i];var a=Te.clone(o);delete a.DeleteMarker,delete a.Version,Te.extend(a,{DeleteMarkers:r,Versions:i,statusCode:n.statusCode,headers:n.headers}),t(null,a)})}function $(e,t){var n=e.Query||{},o=Te.throttleOnProgress.call(this,0,e.onProgress);n["response-content-type"]=e.ResponseContentType,n["response-content-language"]=e.ResponseContentLanguage,n["response-expires"]=e.ResponseExpires,n["response-cache-control"]=e.ResponseCacheControl,n["response-content-disposition"]=e.ResponseContentDisposition,n["response-content-encoding"]=e.ResponseContentEncoding,Se.call(this,{Action:"name/cos:GetObject",method:"GET",Bucket:e.Bucket,Region:e.Region,Key:e.Key,VersionId:e.VersionId,DataType:e.DataType,headers:e.Headers,qs:n,rawBody:!0,onDownloadProgress:o},function(n,r){if(o(null,!0),n){var i=n.statusCode;return e.Headers["If-Modified-Since"]&&i&&304===i?t(null,{NotModified:!0}):t(n)}t(null,{Body:r.body,ETag:Te.attr(r.headers,"etag",""),statusCode:r.statusCode,headers:r.headers})})}function Q(e,t){var n=this,o=e.ContentLength,r=Te.throttleOnProgress.call(n,o,e.onProgress),i=e.Headers;i["Cache-Control"]||i["cache-control"]||(i["Cache-Control"]=""),i["Content-Type"]||i["content-type"]||(i["Content-Type"]=e.Body&&e.Body.type||"");var a=e.UploadAddMetaMd5||n.options.UploadAddMetaMd5||n.options.UploadCheckContentMd5;Te.getBodyMd5(a,e.Body,function(a){a&&(n.options.UploadCheckContentMd5&&(i["Content-MD5"]=Te.binaryBase64(a)),(e.UploadAddMetaMd5||n.options.UploadAddMetaMd5)&&(i["x-cos-meta-md5"]=a)),void 0!==e.ContentLength&&(i["Content-Length"]=e.ContentLength),r(null,!0),Se.call(n,{Action:"name/cos:PutObject",TaskId:e.TaskId,method:"PUT",Bucket:e.Bucket,Region:e.Region,Key:e.Key,headers:e.Headers,qs:e.Query,body:e.Body,onProgress:r},function(i,a){if(i)return r(null,!0),t(i);r({loaded:o,total:o},!0);var s=ve({ForcePathStyle:n.options.ForcePathStyle,protocol:n.options.Protocol,domain:n.options.Domain,bucket:e.Bucket,region:e.Region,object:e.Key});s=s.substr(s.indexOf("://")+3),a.Location=s,a.ETag=Te.attr(a.headers,"etag",""),t(null,a)})},e.onHashProgress)}function J(e,t){Se.call(this,{Action:"name/cos:DeleteObject",method:"DELETE",Bucket:e.Bucket,Region:e.Region,Key:e.Key,headers:e.Headers,VersionId:e.VersionId},function(e,n){if(e){var o=e.statusCode;return o&&204===o?t(null,{statusCode:o}):o&&404===o?t(null,{BucketNotFound:!0,statusCode:o}):t(e)}t(null,{statusCode:n.statusCode,headers:n.headers})})}function Y(e,t){Se.call(this,{Action:"name/cos:GetObjectACL",method:"GET",Bucket:e.Bucket,Region:e.Region,Key:e.Key,headers:e.Headers,action:"acl"},function(e,n){if(e)return t(e);var o=n.AccessControlPolicy||{},r=o.Owner||{},i=o.AccessControlList&&o.AccessControlList.Grant||[];i=Te.isArray(i)?i:[i];var a=ye(o);n.headers&&n.headers["x-cos-acl"]&&(a.ACL=n.headers["x-cos-acl"]),a=Te.extend(a,{Owner:r,Grants:i,statusCode:n.statusCode,headers:n.headers}),t(null,a)})}function Z(e,t){var n=e.Headers,o="";if(e.AccessControlPolicy){var r=Te.clone(e.AccessControlPolicy||{}),i=r.Grants||r.Grant;i=Te.isArray(i)?i:[i],delete r.Grant,delete r.Grants,r.AccessControlList={Grant:i},o=Te.json2xml({AccessControlPolicy:r}),n["Content-Type"]="application/xml",n["Content-MD5"]=Te.binaryBase64(Te.md5(o))}Te.each(n,function(e,t){0===t.indexOf("x-cos-grant-")&&(n[t]=Ce(n[t]))}),Se.call(this,{Action:"name/cos:PutObjectACL",method:"PUT",Bucket:e.Bucket,Region:e.Region,Key:e.Key,action:"acl",headers:n,body:o},function(e,n){if(e)return t(e);t(null,{statusCode:n.statusCode,headers:n.headers})})}function ee(e,t){var n=e.Headers;n.Origin=e.Origin,n["Access-Control-Request-Method"]=e.AccessControlRequestMethod,n["Access-Control-Request-Headers"]=e.AccessControlRequestHeaders,Se.call(this,{Action:"name/cos:OptionsObject",method:"OPTIONS",Bucket:e.Bucket,Region:e.Region,Key:e.Key,headers:n},function(e,n){if(e)return e.statusCode&&403===e.statusCode?t(null,{OptionsForbidden:!0,statusCode:e.statusCode}):t(e);var o=n.headers||{};t(null,{AccessControlAllowOrigin:o["access-control-allow-origin"],AccessControlAllowMethods:o["access-control-allow-methods"],AccessControlAllowHeaders:o["access-control-allow-headers"],AccessControlExposeHeaders:o["access-control-expose-headers"],AccessControlMaxAge:o["access-control-max-age"],statusCode:n.statusCode,headers:n.headers})})}function te(e,t){var n=e.Headers;!n["Cache-Control"]&&n["cache-control"]&&(n["Cache-Control"]="");var o=e.CopySource||"",r=o.match(/^([^.]+-\d+)\.cos(v6)?\.([^.]+)\.[^\/]+\/(.+)$/);if(!r)return void t({error:"CopySource format error"});var i=r[1],a=r[3],s=decodeURIComponent(r[4]);Se.call(this,{Interface:"PutObjectCopy",Scope:[{action:"name/cos:GetObject",bucket:i,region:a,prefix:s},{action:"name/cos:PutObject",bucket:e.Bucket,region:e.Region,prefix:e.Key}],method:"PUT",Bucket:e.Bucket,Region:e.Region,Key:e.Key,VersionId:e.VersionId,headers:e.Headers},function(e,n){if(e)return t(e);var o=Te.clone(n.CopyObjectResult||{});Te.extend(o,{statusCode:n.statusCode,headers:n.headers}),t(null,o)})}function ne(e,t){var n=e.CopySource||"",o=n.match(/^([^.]+-\d+)\.cos(v6)?\.([^.]+)\.[^\/]+\/(.+)$/);if(!o)return void t({error:"CopySource format error"});var r=o[1],i=o[3],a=decodeURIComponent(o[4]);Se.call(this,{Interface:"UploadPartCopy",Scope:[{action:"name/cos:GetObject",bucket:r,region:i,prefix:a},{action:"name/cos:PutObject",bucket:e.Bucket,region:e.Region,prefix:e.Key}],method:"PUT",Bucket:e.Bucket,Region:e.Region,Key:e.Key,VersionId:e.VersionId,qs:{partNumber:e.PartNumber,uploadId:e.UploadId},headers:e.Headers},function(e,n){if(e)return t(e);var o=Te.clone(n.CopyPartResult||{});Te.extend(o,{statusCode:n.statusCode,headers:n.headers}),t(null,o)})}function oe(e,t){var n=e.Objects||[],o=e.Quiet;n=Te.isArray(n)?n:[n];var r=Te.json2xml({Delete:{Object:n,Quiet:o||!1}}),i=e.Headers;i["Content-Type"]="application/xml",i["Content-MD5"]=Te.binaryBase64(Te.md5(r));var a=Te.map(n,function(t){return{action:"name/cos:DeleteObject",bucket:e.Bucket,region:e.Region,prefix:t.Key}});Se.call(this,{Interface:"DeleteMultipleObjects",Scope:a,method:"POST",Bucket:e.Bucket,Region:e.Region,body:r,action:"delete",headers:i},function(e,n){if(e)return t(e);var o=n.DeleteResult||{},r=o.Deleted||[],i=o.Error||[];r=Te.isArray(r)?r:[r],i=Te.isArray(i)?i:[i];var a=Te.clone(o);Te.extend(a,{Error:i,Deleted:r,statusCode:n.statusCode,headers:n.headers}),t(null,a)})}function re(e,t){var n=e.Headers;if(!e.RestoreRequest)return void t({error:"missing param RestoreRequest"});var o=e.RestoreRequest||{},r=Te.json2xml({RestoreRequest:o});n["Content-Type"]="application/xml",n["Content-MD5"]=Te.binaryBase64(Te.md5(r)),Se.call(this,{Action:"name/cos:RestoreObject",method:"POST",Bucket:e.Bucket,Region:e.Region,Key:e.Key,VersionId:e.VersionId,body:r,action:"restore",headers:n},function(e,n){t(e,n)})}function ie(e,t){var n=e.Tagging||{},o=n.TagSet||n.Tags||e.Tags||[];o=Te.clone(Te.isArray(o)?o:[o]);var r=Te.json2xml({Tagging:{TagSet:{Tag:o}}}),i=e.Headers;i["Content-Type"]="application/xml",i["Content-MD5"]=Te.binaryBase64(Te.md5(r)),Se.call(this,{Action:"name/cos:PutObjectTagging",method:"PUT",Bucket:e.Bucket,Key:e.Key,Region:e.Region,body:r,action:"tagging",headers:i,VersionId:e.VersionId},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function ae(e,t){Se.call(this,{Action:"name/cos:GetObjectTagging",method:"GET",Key:e.Key,Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"tagging",VersionId:e.VersionId},function(e,n){if(e)if(404!==e.statusCode||!e.error||"Not Found"!==e.error&&"NoSuchTagSet"!==e.error.Code)t(e);else{var o={Tags:[],statusCode:e.statusCode};e.headers&&(o.headers=e.headers),t(null,o)}else{var r=[];try{r=n.Tagging.TagSet.Tag||[]}catch(e){}r=Te.clone(Te.isArray(r)?r:[r]),t(null,{Tags:r,statusCode:n.statusCode,headers:n.headers})}})}function se(e,t){Se.call(this,{Action:"name/cos:DeleteObjectTagging",method:"DELETE",Bucket:e.Bucket,Region:e.Region,Key:e.Key,headers:e.Headers,action:"tagging",VersionId:e.VersionId},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function ce(e,t){if(!e.SelectType)return t({error:"missing param SelectType"});var n=e.SelectRequest||{},o=Te.json2xml({SelectRequest:n}),r=e.Headers;r["Content-Type"]="application/xml",r["Content-MD5"]=Te.binaryBase64(Te.md5(o)),Se.call(this,{Interface:"SelectObjectContent",Action:"name/cos:GetObject",method:"POST",Bucket:e.Bucket,Region:e.Region,Key:e.Key,headers:e.Headers,action:"select",qs:{"select-type":e.SelectType},VersionId:e.VersionId,body:o,rawBody:!0},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers,Body:n.body})})}function ue(e,t){var n=this,o=e.Headers;o["Cache-Control"]||o["cache-control"]||(o["Cache-Control"]=""),o["Content-Type"]||o["content-type"]||(o["Content-Type"]=e.Body&&e.Body.type||""),Te.getBodyMd5(e.Body&&(e.UploadAddMetaMd5||n.options.UploadAddMetaMd5),e.Body,function(o){o&&(e.Headers["x-cos-meta-md5"]=o),Se.call(n,{Action:"name/cos:InitiateMultipartUpload",method:"POST",Bucket:e.Bucket,Region:e.Region,Key:e.Key,action:"uploads",headers:e.Headers,qs:e.Query},function(e,n){return e?t(e):(n=Te.clone(n||{}))&&n.InitiateMultipartUploadResult?t(null,Te.extend(n.InitiateMultipartUploadResult,{statusCode:n.statusCode,headers:n.headers})):void t(null,n)})},e.onHashProgress)}function le(e,t){var n=this;Te.getFileSize("multipartUpload",e,function(){Te.getBodyMd5(n.options.UploadCheckContentMd5,e.Body,function(o){o&&(e.Headers["Content-MD5"]=Te.binaryBase64(o)),Se.call(n,{Action:"name/cos:UploadPart",TaskId:e.TaskId,method:"PUT",Bucket:e.Bucket,Region:e.Region,Key:e.Key,qs:{partNumber:e.PartNumber,uploadId:e.UploadId},headers:e.Headers,onProgress:e.onProgress,body:e.Body||null},function(e,n){if(e)return t(e);t(null,{ETag:Te.attr(n.headers,"etag",""),statusCode:n.statusCode,headers:n.headers})})})})}function de(e,t){for(var n=this,o=e.UploadId,r=e.Parts,i=0,a=r.length;i-1?n.Authorization:"sign="+encodeURIComponent(n.Authorization)),n.XCosSecurityToken&&(r+="&x-cos-security-token="+n.XCosSecurityToken),n.ClientIP&&(r+="&clientIP="+n.ClientIP),n.ClientUA&&(r+="&clientUA="+n.ClientUA),n.Token&&(r+="&token="+n.Token),setTimeout(function(){t(null,{Url:r})})}});return r?o+"?"+r.Authorization+(r.XCosSecurityToken?"&x-cos-security-token="+r.XCosSecurityToken:""):o}function ye(e){var t={GrantFullControl:[],GrantWrite:[],GrantRead:[],GrantReadAcp:[],GrantWriteAcp:[],ACL:""},n={FULL_CONTROL:"GrantFullControl",WRITE:"GrantWrite",READ:"GrantRead",READ_ACP:"GrantReadAcp",WRITE_ACP:"GrantWriteAcp"},o=e&&e.AccessControlList||{},r=o.Grant;r&&(r=Te.isArray(r)?r:[r]);var i={READ:0,WRITE:0,FULL_CONTROL:0};return r&&r.length&&Te.each(r,function(o){"qcs::cam::anyone:anyone"===o.Grantee.ID||"http://cam.qcloud.com/groups/global/AllUsers"===o.Grantee.URI?i[o.Permission]=1:o.Grantee.ID!==e.Owner.ID&&t[n[o.Permission]].push('id="'+o.Grantee.ID+'"')}),i.FULL_CONTROL||i.WRITE&&i.READ?t.ACL="public-read-write":i.READ?t.ACL="public-read":t.ACL="private",Te.each(n,function(e){t[e]=Ce(t[e].join(","))}),t}function Ce(e){var t,n,o=e.split(","),r={};for(t=0;t-1?"{Region}.myqcloud.com":"cos.{Region}.myqcloud.com",e.ForcePathStyle||(r="{Bucket}."+r)),r=r.replace(/\{\{AppId\}\}/gi,o).replace(/\{\{Bucket\}\}/gi,n).replace(/\{\{Region\}\}/gi,i).replace(/\{\{.*?\}\}/gi,""),r=r.replace(/\{AppId\}/gi,o).replace(/\{BucketName\}/gi,n).replace(/\{Bucket\}/gi,t).replace(/\{Region\}/gi,i).replace(/\{.*?\}/gi,""),/^[a-zA-Z]+:\/\//.test(r)||(r=s+"//"+r),"/"===r.slice(-1)&&(r=r.slice(0,-1));var c=r;return e.ForcePathStyle&&(c+="/"+t),c+="/",a&&(c+=Te.camSafeUrlEncode(a).replace(/%2F/g,"/")),e.isLocation&&(c=c.replace(/^https?:\/\//,"")),c}function ke(e,t){var n=Te.clone(e.Headers);delete n["Content-Type"],delete n["Cache-Control"],Te.each(n,function(e,t){""===e&&delete n[t]});var o=function(e){var n=!1,o=e.Authorization;if(o)if(o.indexOf(" ")>-1)n=!1;else if(o.indexOf("q-sign-algorithm=")>-1&&o.indexOf("q-ak=")>-1&&o.indexOf("q-sign-time=")>-1&&o.indexOf("q-key-time=")>-1&&o.indexOf("q-url-param-list=")>-1)n=!0;else try{o=atob(o),o.indexOf("a=")>-1&&o.indexOf("k=")>-1&&o.indexOf("t=")>-1&&o.indexOf("r=")>-1&&o.indexOf("b=")>-1&&(n=!0)}catch(e){}n?t&&t(null,e):t&&t({error:"authorization error"})},r=this,i=e.Bucket||"",a=e.Region||"",s=e.Key||"";r.options.ForcePathStyle&&i&&(s=i+"/"+s);var c="/"+s,u={},l=e.Scope;if(!l){var d=e.Action||"",f=e.ResourceKey||e.Key||"";l=e.Scope||[{action:d,bucket:i,region:a,prefix:f}]}var h=Te.md5(JSON.stringify(l));r._StsCache=r._StsCache||[],function(){var e,t;for(e=r._StsCache.length-1;e>=0;e--){t=r._StsCache[e];var n=Math.round(Te.getSkewTime(r.options.SystemClockOffset)/1e3)+30;if(t.StartTime&&n=t.ExpiredTime)r._StsCache.splice(e,1);else if(!t.ScopeLimit||t.ScopeLimit&&t.ScopeKey===h){u=t;break}}}();var p=function(){var t=u.StartTime&&u.ExpiredTime?u.StartTime+";"+u.ExpiredTime:"",i=Te.getAuth({SecretId:u.TmpSecretId,SecretKey:u.TmpSecretKey,Method:e.Method,Pathname:c,Query:e.Query,Headers:n,Expires:e.Expires,UseRawKey:r.options.UseRawKey,SystemClockOffset:r.options.SystemClockOffset,KeyTime:t}),a={Authorization:i,XCosSecurityToken:u.XCosSecurityToken||"",Token:u.Token||"",ClientIP:u.ClientIP||"",ClientUA:u.ClientUA||""};o(a)};if(u.ExpiredTime&&u.ExpiredTime-Te.getSkewTime(r.options.SystemClockOffset)/1e3>60)p();else if(r.options.getAuthorization)r.options.getAuthorization.call(r,{Bucket:i,Region:a,Method:e.Method,Key:s,Pathname:c,Query:e.Query,Headers:n,Scope:l,SystemClockOffset:r.options.SystemClockOffset},function(e){"string"==typeof e&&(e={Authorization:e}),e.TmpSecretId&&e.TmpSecretKey&&e.XCosSecurityToken&&e.ExpiredTime?(u=e||{},u.Scope=l,u.ScopeKey=h,r._StsCache.push(u),p()):o(e)});else{if(!r.options.getSTS)return function(){var t=Te.getAuth({SecretId:e.SecretId||r.options.SecretId,SecretKey:e.SecretKey||r.options.SecretKey,Method:e.Method,Pathname:c,Query:e.Query,Headers:n,Expires:e.Expires,UseRawKey:r.options.UseRawKey,SystemClockOffset:r.options.SystemClockOffset}),i={Authorization:t,XCosSecurityToken:r.options.XCosSecurityToken};return o(i),i}();r.options.getSTS.call(r,{Bucket:i,Region:a},function(e){u=e||{},u.Scope=l,u.ScopeKey=h,u.TmpSecretId=u.SecretId,u.TmpSecretKey=u.SecretKey,r._StsCache.push(u),p()})}return""}function Re(e){var t=!1,n=!1,o=e.headers&&(e.headers.date||e.headers.Date)||e.error&&e.error.ServerTime;try{var r=e.error.Code,i=e.error.Message;("RequestTimeTooSkewed"===r||"AccessDenied"===r&&"Request has expired"===i)&&(n=!0)}catch(e){}if(e)if(n&&o){var a=Date.parse(o);this.options.CorrectClockSkew&&Math.abs(Te.getSkewTime(this.options.SystemClockOffset)-a)>=3e4&&(console.error("error: Local time is too skewed."),this.options.SystemClockOffset=a-Date.now(),t=!0)}else 5===Math.floor(e.statusCode/100)&&(t=!0);return t}function Se(e,t){var n=this;!e.headers&&(e.headers={}),!e.qs&&(e.qs={}),e.VersionId&&(e.qs.versionId=e.VersionId),e.qs=Te.clearKey(e.qs),e.headers&&(e.headers=Te.clearKey(e.headers)),e.qs&&(e.qs=Te.clearKey(e.qs));var o=Te.clone(e.qs);e.action&&(o[e.action]="");var r=function(i){var a=n.options.SystemClockOffset;ke.call(n,{Bucket:e.Bucket||"",Region:e.Region||"",Method:e.method,Key:e.Key,Query:o,Headers:e.headers,Action:e.Action,ResourceKey:e.ResourceKey,Scope:e.Scope},function(o,s){if(o)return void t(o);e.AuthData=s,Ae.call(n,e,function(o,s){o&&i<2&&(a!==n.options.SystemClockOffset||Re.call(n,o))?(e.headers&&(delete e.headers.Authorization,delete e.headers.token,delete e.headers.clientIP,delete e.headers.clientUA,delete e.headers["x-cos-security-token"]),r(i+1)):t(o,s)})})};r(1)}function Ae(e,t){var n=this,o=e.TaskId;if(!o||n._isRunningTask(o)){var r=e.Bucket,i=e.Region,a=e.Key,s=e.method||"GET",c=e.url,u=e.body,l=e.rawBody;c=c||ve({ForcePathStyle:n.options.ForcePathStyle,protocol:n.options.Protocol,domain:n.options.Domain,bucket:r,region:i,object:a}),e.action&&(c=c+"?"+e.action);var d={method:s,url:c,headers:e.headers,qs:e.qs,body:u};if(d.headers.Authorization=e.AuthData.Authorization,e.AuthData.Token&&(d.headers.token=e.AuthData.Token),e.AuthData.ClientIP&&(d.headers.clientIP=e.AuthData.ClientIP),e.AuthData.ClientUA&&(d.headers.clientUA=e.AuthData.ClientUA),e.AuthData.XCosSecurityToken&&(d.headers["x-cos-security-token"]=e.AuthData.XCosSecurityToken),d.headers&&(d.headers=Te.clearKey(d.headers)),d=Te.clearKey(d),e.onProgress&&"function"==typeof e.onProgress){var f=u&&(u.size||u.length)||0;d.onProgress=function(t){if(!o||n._isRunningTask(o)){var r=t?t.loaded:0;e.onProgress({loaded:r,total:f})}}}e.onDownloadProgress&&(d.onDownloadProgress=e.onDownloadProgress),e.DataType&&(d.dataType=e.DataType),this.options.Timeout&&(d.timeout=this.options.Timeout),e.Interface?d.cosInterface=e.Interface:e.Action&&(d.cosInterface=e.Action.replace(/^name\/cos:/,"")),n.options.ForcePathStyle&&(d.pathStyle=n.options.ForcePathStyle),n.emit("before-send",d);var h=(n.options.Request||Be)(d,function(e){if("abort"!==e.error){n.emit("after-receive",e);var r,i={statusCode:e.statusCode,statusMessage:e.statusMessage,headers:e.headers},a=e.error,s=e.body,c=function(e,a){if(o&&n.off("inner-kill-task",p),!r){r=!0;var s={};i&&i.statusCode&&(s.statusCode=i.statusCode),i&&i.headers&&(s.headers=i.headers),e?(e=Te.extend(e||{},s),t(e,null)):(a=Te.extend(a||{},s),t(null,a)),h=null}};if(a)return void c({error:a});var u;if(l)u={},u.body=s;else try{u=s&&s.indexOf("<")>-1&&s.indexOf(">")>-1&&Te.xml2json(s)||{}}catch(e){u=s||{}}var d=i.statusCode;return 2===Math.floor(d/100)?u.Error?void c({error:u.Error}):void c(null,u):void c({error:u.Error||u})}}),p=function(e){e.TaskId===o&&(h&&h.abort&&h.abort(),n.off("inner-kill-task",p))};o&&n.on("inner-kill-task",p)}}function be(e,t,n){Te.each(["Cors","Acl"],function(o){if(e.slice(-o.length)===o){var r=e.slice(0,-o.length)+o.toUpperCase(),i=Te.apiWrapper(e,t),a=!1;n[r]=function(){!a&&console.warn("warning: cos."+r+" has been deprecated. Please Use cos."+e+" instead."),a=!0,i.apply(this,arguments)}}})}var Be=n(17),Te=n(0),xe={getService:o,putBucket:r,headBucket:i,getBucket:a,deleteBucket:s,putBucketAcl:c,getBucketAcl:u,putBucketCors:l,getBucketCors:d,deleteBucketCors:f,getBucketLocation:h,getBucketPolicy:g,putBucketPolicy:p,deleteBucketPolicy:m,putBucketTagging:y,getBucketTagging:C,deleteBucketTagging:v,putBucketLifecycle:k,getBucketLifecycle:R,deleteBucketLifecycle:S,putBucketVersioning:A,getBucketVersioning:b,putBucketReplication:B,getBucketReplication:T,deleteBucketReplication:x,putBucketWebsite:E,getBucketWebsite:_,deleteBucketWebsite:w,putBucketReferer:I,getBucketReferer:D,putBucketDomain:O,getBucketDomain:N,deleteBucketDomain:P,putBucketOrigin:M,getBucketOrigin:U,deleteBucketOrigin:H,putBucketLogging:L,getBucketLogging:F,putBucketInventory:K,getBucketInventory:j,listBucketInventory:z,deleteBucketInventory:G,putBucketAccelerate:q,getBucketAccelerate:X,getObject:$,headObject:V,listObjectVersions:W,putObject:Q,deleteObject:J,getObjectAcl:Y,putObjectAcl:Z,optionsObject:ee,putObjectCopy:te,deleteMultipleObject:oe,restoreObject:re,putObjectTagging:ie,getObjectTagging:ae,deleteObjectTagging:se,selectObjectContent:ce,uploadPartCopy:ne,multipartInit:ue,multipartUpload:le,multipartComplete:de,multipartList:fe,multipartListPart:he,multipartAbort:pe,getObjectUrl:me,getAuth:ge};e.exports.init=function(e,t){t.transferToTaskMethod(xe,"putObject"),Te.each(xe,function(t,n){e.prototype[n]=Te.apiWrapper(n,t),be(n,t,e.prototype)})}},function(e,t){var n=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}},o=function(e,t,o,r){return t=t||"&",o=o||"=",null===e&&(e=void 0),"object"==typeof e?Object.keys(e).map(function(r){var i=encodeURIComponent(n(r))+o;return Array.isArray(e[r])?e[r].map(function(e){return i+encodeURIComponent(n(e))}).join(t):i+encodeURIComponent(n(e[r]))}).filter(Boolean).join(t):r?encodeURIComponent(n(r))+o+encodeURIComponent(n(e)):""},r=function(e,t,n){var o={};return t.getAllResponseHeaders().trim().split("\n").forEach(function(e){if(e){var t=e.indexOf(":"),n=e.substr(0,t).trim().toLowerCase(),r=e.substr(t+1).trim();o[n]=r}}),{error:e,statusCode:t.status,statusMessage:t.statusText,headers:o,body:n}},i=function(e,t){return t||"text"!==t?e.response:e.responseText},a=function(e,t){var n=(e.method||"GET").toUpperCase(),a=e.url;if(e.qs){var s=o(e.qs);s&&(a+=(-1===a.indexOf("?")?"?":"&")+s)}var c=new XMLHttpRequest;c.open(n,a,!0),c.responseType=e.dataType||"text";var u=e.headers;if(u)for(var l in u)u.hasOwnProperty(l)&&"content-length"!==l.toLowerCase()&&"user-agent"!==l.toLowerCase()&&"origin"!==l.toLowerCase()&&"host"!==l.toLowerCase()&&c.setRequestHeader(l,u[l]);return e.onProgress&&c.upload&&(c.upload.onprogress=e.onProgress),e.onDownloadProgress&&(c.onprogress=e.onDownloadProgress),c.onload=function(){t(r(null,c,i(c,e.dataType)))},c.onerror=function(n){var o=i(c,e.dataType);if(o)t(r(null,c,o));else{var a=c.statusText;a||0!==c.status||(a="CORS blocked or network error"),t(r(a,c,o))}},c.send(e.body||""),c};e.exports=a},function(e,t,n){function o(e,t){var n,o,i=this,a=new y,c=e.TaskId,l=e.Bucket,d=e.Region,f=e.Key,h=e.Body,p=e.ChunkSize||e.SliceSize||i.options.ChunkSize,m=e.AsyncLimit,v=e.StorageClass,k=e.ServerSideEncryption,R=e.onHashProgress;a.on("error",function(e){if(i._isRunningTask(c))return t(e)}),a.on("upload_complete",function(e){t(null,e)}),a.on("upload_slice_complete",function(t){var r={};C.each(e.Headers,function(e,t){var n=t.toLowerCase();0!==n.indexOf("x-cos-meta-")&&"pic-operations"!==n||(r[t]=e)}),u.call(i,{Bucket:l,Region:d,Key:f,UploadId:t.UploadId,SliceList:t.SliceList,Headers:r},function(e,r){if(i._isRunningTask(c)){if(g.removeUsing(t.UploadId),e)return o(null,!0),a.emit("error",e);g.removeUploadId(t.UploadId),o({loaded:n,total:n},!0),a.emit("upload_complete",r)}})}),a.on("get_upload_data_finish",function(t){var r=g.getFileId(h,e.ChunkSize,l,f);r&&g.saveUploadId(r,t.UploadId,i.options.UploadIdCacheLimit),g.setUsing(t.UploadId),o(null,!0),s.call(i,{TaskId:c,Bucket:l,Region:d,Key:f,Body:h,FileSize:n,SliceSize:p,AsyncLimit:m,ServerSideEncryption:k,UploadData:t,onProgress:o},function(e,t){if(i._isRunningTask(c))return e?(o(null,!0),a.emit("error",e)):void a.emit("upload_slice_complete",t)})}),a.on("get_file_size_finish",function(){if(o=C.throttleOnProgress.call(i,n,e.onProgress),e.UploadData.UploadId)a.emit("get_upload_data_finish",e.UploadData);else{var t=C.extend({TaskId:c,Bucket:l,Region:d,Key:f,Headers:e.Headers,StorageClass:v,Body:h,FileSize:n,SliceSize:p,onHashProgress:R},e);r.call(i,t,function(t,n){if(i._isRunningTask(c)){if(t)return a.emit("error",t);e.UploadData.UploadId=n.UploadId,e.UploadData.PartList=n.PartList,a.emit("get_upload_data_finish",e.UploadData)}})}}),n=e.ContentLength,delete e.ContentLength,!e.Headers&&(e.Headers={}),C.each(e.Headers,function(t,n){"content-length"===n.toLowerCase()&&delete e.Headers[n]}),function(){for(var t=[1,2,4,8,16,32,64,128,256,512,1024,2048,4096,5120],o=1048576,r=0;rh)return t(null,!1);if(n>1){if(Math.max(e[0].Size,e[1].Size)!==f)return t(null,!1)}var o=function(r){if(r=c.length)return void A.emit("has_and_check_upload_id",t);var i=c[e];return C.isInArray(t,i)?g.using[i]?void l(e+1):void a.call(u,{Bucket:o,Region:r,Key:s,UploadId:i},function(t,o){u._isRunningTask(n)&&(t?(g.removeUploadId(i),l(e+1)):A.emit("upload_id_available",{UploadId:i,PartList:o.PartList}))}):(g.removeUploadId(i),void l(e+1))};l(0)}),A.on("get_remote_upload_id_list",function(){i.call(u,{Bucket:o,Region:r,Key:s},function(t,r){if(u._isRunningTask(n)){if(t)return A.emit("error",t);var i=C.filter(r.UploadList,function(e){return e.Key===s&&(!c||e.StorageClass.toUpperCase()===c.toUpperCase())}).reverse().map(function(e){return e.UploadId||e.UploadID});if(i.length)A.emit("seek_local_avail_upload_id",i);else{var a,l=g.getFileId(e.Body,e.ChunkSize,o,s);l&&(a=g.getUploadIdList(l))&&C.each(a,function(e){g.removeUploadId(e)}),A.emit("no_available_upload_id")}}})}),A.emit("get_remote_upload_id_list")}function i(e,t){var n=this,o=[],r={Bucket:e.Bucket,Region:e.Region,Prefix:e.Key},i=function(){n.multipartList(r,function(e,n){if(e)return t(e);o.push.apply(o,n.Upload||[]),"true"===n.IsTruncated?(r.KeyMarker=n.NextKeyMarker,r.UploadIdMarker=n.NextUploadIdMarker,i()):t(null,{UploadList:o})})};i()}function a(e,t){var n=this,o=[],r={Bucket:e.Bucket,Region:e.Region,Key:e.Key,UploadId:e.UploadId},i=function(){n.multipartListPart(r,function(e,n){if(e)return t(e);o.push.apply(o,n.Part||[]),"true"===n.IsTruncated?(r.PartNumberMarker=n.NextPartNumberMarker,i()):t(null,{PartList:o})})};i()}function s(e,t){var n=this,o=e.TaskId,r=e.Bucket,i=e.Region,a=e.Key,s=e.UploadData,u=e.FileSize,l=e.SliceSize,d=Math.min(e.AsyncLimit||n.options.ChunkParallelLimit||1,256),f=e.Body,h=Math.ceil(u/l),p=0,g=e.ServerSideEncryption,y=C.filter(s.PartList,function(e){return e.Uploaded&&(p+=e.PartNumber>=h?u%l||l:l),!e.Uploaded}),v=e.onProgress;m.eachLimit(y,d,function(e,t){if(n._isRunningTask(o)){var d=e.PartNumber,h=Math.min(u,e.PartNumber*l)-(e.PartNumber-1)*l,m=0;c.call(n,{TaskId:o,Bucket:r,Region:i,Key:a,SliceSize:l,FileSize:u,PartNumber:d,ServerSideEncryption:g,Body:f,UploadData:s,onProgress:function(e){p+=e.loaded-m,m=e.loaded,v({loaded:p,total:u})}},function(r,i){n._isRunningTask(o)&&(r||i.ETag||(r='get ETag error, please add "ETag" to CORS ExposeHeader setting.'),r?p-=m:(p+=h-m,e.ETag=i.ETag),v({loaded:p,total:u}),t(r||null,i))})}},function(e){if(n._isRunningTask(o))return e?t(e):void t(null,{UploadId:s.UploadId,SliceList:s.PartList})})}function c(e,t){var n=this,o=e.TaskId,r=e.Bucket,i=e.Region,a=e.Key,s=e.FileSize,c=e.Body,u=1*e.PartNumber,l=e.SliceSize,d=e.ServerSideEncryption,f=e.UploadData,h=n.options.ChunkRetryTimes+1,p=l*(u-1),g=l,y=p+l;y>s&&(y=s,g=y-p);var v=f.PartList[u-1];m.retry(h,function(t){n._isRunningTask(o)&&C.fileSlice(c,p,y,!0,function(s){n.multipartUpload({TaskId:o,Bucket:r,Region:i,Key:a,ContentLength:g,PartNumber:u,UploadId:f.UploadId,ServerSideEncryption:d,Body:s,onProgress:e.onProgress},function(e,r){if(n._isRunningTask(o))return e?t(e):(v.Uploaded=!0,t(null,r))})})},function(e,r){if(n._isRunningTask(o))return t(e,r)})}function u(e,t){var n=e.Bucket,o=e.Region,r=e.Key,i=e.UploadId,a=e.SliceList,s=this,c=this.options.ChunkRetryTimes+1,u=e.Headers,l=a.map(function(e){return{PartNumber:e.PartNumber,ETag:e.ETag}});m.retry(c,function(e){s.multipartComplete({Bucket:n,Region:o,Key:r,UploadId:i,Parts:l,Headers:u},e)},function(e,n){t(e,n)})}function l(e,t){var n=e.Bucket,o=e.Region,r=e.Key,a=e.UploadId,s=e.Level||"task",c=e.AsyncLimit,u=this,l=new y;if(l.on("error",function(e){return t(e)}),l.on("get_abort_array",function(i){d.call(u,{Bucket:n,Region:o,Key:r,Headers:e.Headers,AsyncLimit:c,AbortArray:i},function(e,n){if(e)return t(e);t(null,n)})}),"bucket"===s)i.call(u,{Bucket:n,Region:o},function(e,n){if(e)return t(e);l.emit("get_abort_array",n.UploadList||[])});else if("file"===s){if(!r)return t({error:"abort_upload_task_no_key"});i.call(u,{Bucket:n,Region:o,Key:r},function(e,n){if(e)return t(e);l.emit("get_abort_array",n.UploadList||[])})}else{if("task"!==s)return t({error:"abort_unknown_level"});if(!a)return t({error:"abort_upload_task_no_id"});if(!r)return t({error:"abort_upload_task_no_key"});l.emit("get_abort_array",[{Key:r,UploadId:a}])}}function d(e,t){var n=e.Bucket,o=e.Region,r=e.Key,i=e.AbortArray,a=e.AsyncLimit||1,s=this,c=0,u=new Array(i.length);m.eachLimit(i,a,function(t,i){var a=c;if(r&&r!==t.Key)return u[a]={error:{KeyNotMatch:!0}},void i(null);var l=t.UploadId||t.UploadID;s.multipartAbort({Bucket:n,Region:o,Key:t.Key,Headers:e.Headers,UploadId:l},function(e){var r={Bucket:n,Region:o,Key:t.Key,UploadId:l};u[a]={error:e,task:r},i(null)}),c++},function(e){if(e)return t(e);for(var n=[],o=[],r=0,i=u.length;r=o?"sliceUploadFile":"putObject";d.push({api:v,params:e,callback:y})}()}),n._addTasks(d)}function h(e,t){var n=new y,o=this,r=e.Bucket,i=e.Region,a=e.Key,s=e.CopySource,c=s.match(/^([^.]+-\d+)\.cos(v6)?\.([^.]+)\.[^\/]+\/(.+)$/);if(!c)return void t({error:"CopySource format error"});var u=c[1],l=c[3],d=decodeURIComponent(c[4]),f=void 0===e.CopySliceSize?o.options.CopySliceSize:e.CopySliceSize;f=Math.max(0,f);var h,g,v=e.CopyChunkSize||this.options.CopyChunkSize,k=this.options.CopyChunkParallelLimit,R=0;n.on("copy_slice_complete",function(n){var s={};C.each(e.Headers,function(e,t){0===t.toLowerCase().indexOf("x-cos-meta-")&&(s[t]=e)});var c=C.map(n.PartList,function(e){return{PartNumber:e.PartNumber,ETag:e.ETag}});o.multipartComplete({Bucket:r,Region:i,Key:a,UploadId:n.UploadId,Parts:c},function(e,n){if(e)return g(null,!0),t(e);g({loaded:h,total:h},!0),t(null,n)})}),n.on("get_copy_data_finish",function(e){m.eachLimit(e.PartList,k,function(t,n){var c=t.PartNumber,u=t.CopySourceRange,l=t.end-t.start,d=0;p.call(o,{Bucket:r,Region:i,Key:a,CopySource:s,UploadId:e.UploadId,PartNumber:c,CopySourceRange:u,onProgress:function(e){R+=e.loaded-d,d=e.loaded,g({loaded:R,total:h})}},function(e,o){if(e)return n(e);g({loaded:R,total:h}),R+=l-d,t.ETag=o.ETag,n(e||null,o)})},function(o){if(o)return g(null,!0),t(o);n.emit("copy_slice_complete",e)})}),n.on("get_file_size_finish",function(s){!function(){for(var t=[1,2,4,8,16,32,64,128,256,512,1024,2048,4096,5120],n=1048576,r=0;r"x-cos-meta-".length&&(s[t]=e)}),n.emit("get_file_size_finish",s)}})}function p(e,t){var n=e.TaskId,o=e.Bucket,r=e.Region,i=e.Key,a=e.CopySource,s=e.UploadId,c=1*e.PartNumber,u=e.CopySourceRange,l=this.options.ChunkRetryTimes+1,d=this;m.retry(l,function(t){d.uploadPartCopy({TaskId:n,Bucket:o,Region:r,Key:i,CopySource:a,UploadId:s,PartNumber:c,CopySourceRange:u,onProgress:e.onProgress},function(e,n){t(e||null,n)})},function(e,n){return t(e,n)})}var g=n(3),m=n(19),y=n(2).EventProxy,C=n(0),v={sliceUploadFile:o,abortUploadTask:l,uploadFiles:f,sliceCopyFile:h};e.exports.init=function(e,t){t.transferToTaskMethod(v,"sliceUploadFile"),C.each(v,function(t,n){e.prototype[n]=C.apiWrapper(n,t)})}},function(e,t){var n=function(e,t,n,o){if(o=o||function(){},!e.length||t<=0)return o();var r=0,i=0,a=0;!function s(){if(r>=e.length)return o();for(;a=e.length?o():s())})}()},o=function(e,t,n){var o=function(r){t(function(t,i){t&&rt?1:-1})},f=function(e){var t,n,o,i=[],a=d(e);for(t=0;tparseInt(t[n])?1:-1;return 0};return function(t){var n=(t.match(/Chrome\/([.\d]+)/)||[])[1],r=(t.match(/QBCore\/([.\d]+)/)||[])[1],o=(t.match(/QQBrowser\/([.\d]+)/)||[])[1];return n&&e(n,"53.0.2785.116")<0&&r&&e(r,"3.53.991.400")<0&&o&&e(o,"9.0.2524.400")<=0||!1}(navigator&&navigator.userAgent)}(),w=function(e,t,n,r,o){var i;if(e.slice?i=e.slice(t,n):e.mozSlice?i=e.mozSlice(t,n):e.webkitSlice&&(i=e.webkitSlice(t,n)),r&&b){var a=new FileReader;a.onload=function(e){i=null,o(new Blob([a.result]))},a.readAsArrayBuffer(i)}else o(i)},E=function(e,t,n,r){n=n||k,e?"string"==typeof t?n(M.md5(t,!0)):Blob&&t instanceof Blob?M.getFileMd5(t,function(e,t){n(t)},r):n():n()},T=function(e,t,n){var r=e.size,o=0,i=h.getCtx(),a=function(s){if(s>=r){var u=i.digest("hex");return void t(null,u)}var c=Math.min(r,s+1048576);M.fileSlice(e,s,c,!1,function(e){A(e,function(t){e=null,i=i.update(t,!0),o+=t.length,t=null,n&&n({loaded:o,total:r,percent:Math.round(o/r*1e4)/1e4}),a(s+1048576)})})};a(0)},B=function(e){var t,n,r,o="";for(t=0,n=e.length/2;t-1||"deleteMultipleObject"===e||"multipartList"===e||"listObjectVersions"===e){if(!n)return"Bucket";if(!r)return"Region"}else if(e.indexOf("Object")>-1||e.indexOf("multipart")>-1||"sliceUploadFile"===e||"abortUploadTask"===e){if(!n)return"Bucket";if(!r)return"Region";if(!o)return"Key"}return!1},I=function(e,t){if(t=a({},t),"getAuth"!==e&&"getV4Auth"!==e&&"getObjectUrl"!==e){var n=t.Headers||{};if(t&&"object"==typeof t){!function(){for(var e in t)t.hasOwnProperty(e)&&e.indexOf("x-cos-")>-1&&(n[e]=t[e])}();var r={"x-cos-mfa":"MFA","Content-MD5":"ContentMD5","Content-Length":"ContentLength","Content-Type":"ContentType",Expect:"Expect",Expires:"Expires","Cache-Control":"CacheControl","Content-Disposition":"ContentDisposition","Content-Encoding":"ContentEncoding",Range:"Range","If-Modified-Since":"IfModifiedSince","If-Unmodified-Since":"IfUnmodifiedSince","If-Match":"IfMatch","If-None-Match":"IfNoneMatch","x-cos-copy-source":"CopySource","x-cos-copy-source-Range":"CopySourceRange","x-cos-metadata-directive":"MetadataDirective","x-cos-copy-source-If-Modified-Since":"CopySourceIfModifiedSince","x-cos-copy-source-If-Unmodified-Since":"CopySourceIfUnmodifiedSince","x-cos-copy-source-If-Match":"CopySourceIfMatch","x-cos-copy-source-If-None-Match":"CopySourceIfNoneMatch","x-cos-acl":"ACL","x-cos-grant-read":"GrantRead","x-cos-grant-write":"GrantWrite","x-cos-grant-full-control":"GrantFullControl","x-cos-grant-read-acp":"GrantReadAcp","x-cos-grant-write-acp":"GrantWriteAcp","x-cos-storage-class":"StorageClass","x-cos-traffic-limit":"TrafficLimit","x-cos-server-side-encryption-customer-algorithm":"SSECustomerAlgorithm","x-cos-server-side-encryption-customer-key":"SSECustomerKey","x-cos-server-side-encryption-customer-key-MD5":"SSECustomerKeyMD5","x-cos-server-side-encryption":"ServerSideEncryption","x-cos-server-side-encryption-cos-kms-key-id":"SSEKMSKeyId","x-cos-server-side-encryption-context":"SSEContext"};M.each(r,function(e,r){void 0!==t[e]&&(n[r]=t[e])}),t.Headers=S(n)}}return t},P=function(e,t){return function(n,r){var o=this;"function"==typeof n&&(r=n,n={}),n=I(e,n);var i=function(e){return e&&e.headers&&(e.headers["x-cos-request-id"]&&(e.RequestId=e.headers["x-cos-request-id"]),e.headers["x-cos-version-id"]&&(e.VersionId=e.headers["x-cos-version-id"]),e.headers["x-cos-delete-marker"]&&(e.DeleteMarker=e.headers["x-cos-delete-marker"])),e},a=function(e,t){r&&r(i(e),i(t))},s=function(){if("getService"!==e&&"abortUploadTask"!==e){var t=x(e,n);if(t)return"missing param "+t;if(n.Region){if(n.Region.indexOf("cos.")>-1)return'param Region should not be start with "cos."';if(!/^([a-z\d-]+)$/.test(n.Region))return"Region format error.";o.options.CompatibilityMode||-1!==n.Region.indexOf("-")||"yfb"===n.Region||"default"===n.Region||console.warn("warning: param Region format error, find help here: https://cloud.tencent.com/document/product/436/6224")}if(n.Bucket){if(!/^([a-z\d-]+)-(\d+)$/.test(n.Bucket))if(n.AppId)n.Bucket=n.Bucket+"-"+n.AppId;else{if(!o.options.AppId)return'Bucket should format as "test-1250000000".';n.Bucket=n.Bucket+"-"+o.options.AppId}n.AppId&&(console.warn('warning: AppId has been deprecated, Please put it at the end of parameter Bucket(E.g Bucket:"test-1250000000" ).'),delete n.AppId)}!o.options.UseRawKey&&n.Key&&"/"===n.Key.substr(0,1)&&(n.Key=n.Key.substr(1))}}(),u="getAuth"===e||"getObjectUrl"===e;if(Promise&&!u&&!r)return new Promise(function(e,i){if(r=function(t,n){t?i(t):e(n)},s)return a(M.error(new Error(s)));t.call(o,n,a)});if(s)return a(M.error(new Error(s)));var c=t.call(o,n,a);return u?c:void 0}},O=function(e,t){function n(){if(o=0,t&&"function"==typeof t){r=Date.now();var n,i=Math.max(0,Math.round((s-a)/((r-u)/1e3)*100)/100)||0;n=0===s&&0===e?1:Math.floor(s/e*100)/100||0,u=r,a=s;try{t({loaded:s,total:e,speed:i,percent:n})}catch(e){}}}var r,o,i=this,a=0,s=0,u=Date.now();return function(t,r){if(t&&(s=t.loaded,e=t.total),r)clearTimeout(o),n();else{if(o)return;o=setTimeout(n,i.options.ProgressInterval)}}},D=function(e,t,n){var r;if("string"==typeof t.Body?t.Body=new Blob([t.Body],{type:"text/plain"}):t.Body instanceof ArrayBuffer&&(t.Body=new Blob([t.Body])),!t.Body||!(t.Body instanceof Blob||"[object File]"===t.Body.toString()||"[object Blob]"===t.Body.toString()))return void n(M.error(new Error("params body format error, Only allow File|Blob|String.")));r=t.Body.size,t.ContentLength=r,n(null,r)},N=function(e){return Date.now()+(e||0)},U=function(e,t){var n=e;return e.message=e.message||null,"string"==typeof t?(e.error=t,e.message=t):"object"==typeof t&&null!==t&&(a(e,t),(t.code||t.name)&&(e.code=t.code||t.name),t.message&&(e.message=t.message),t.stack&&(e.stack=t.stack)),"function"==typeof Object.defineProperty&&(Object.defineProperty(e,"name",{writable:!0,enumerable:!1}),Object.defineProperty(e,"message",{enumerable:!0})),e.name=t&&t.name||e.name||e.code||"Error",e.code||(e.code=e.name),e.error||(e.error=o(n)),e},M={noop:k,formatParams:I,apiWrapper:P,xml2json:g,json2xml:m,md5:h,clearKey:S,fileSlice:w,getBodyMd5:E,getFileMd5:T,binaryBase64:B,extend:a,isArray:s,isInArray:u,makeArray:c,each:l,map:d,filter:f,clone:o,attr:i,uuid:_,camSafeUrlEncode:r,throttleOnProgress:O,getFileSize:D,getSkewTime:N,error:U,getAuth:y,parseSelectPayload:R,isBrowser:!0};e.exports=M},function(e,t){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t){function n(e,t){for(var n in e)t[n]=e[n]}function r(e,t){function r(){}var o=e.prototype;if(Object.create){var i=Object.create(t.prototype);o.__proto__=i}o instanceof t||(r.prototype=t.prototype,r=new r,n(o,r),e.prototype=o=r),o.constructor!=e&&("function"!=typeof e&&console.error("unknow Class:"+e),o.constructor=e)}function o(e,t){if(t instanceof Error)var n=t;else n=this,Error.call(this,oe[e]),this.message=oe[e],Error.captureStackTrace&&Error.captureStackTrace(this,o);return n.code=e,t&&(this.message=this.message+": "+t),n}function i(){}function a(e,t){this._node=e,this._refresh=t,s(this)}function s(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!=t){var r=e._refresh(e._node);K(e,"length",r.length),n(r,e),e._inc=t}}function u(){}function c(e,t){for(var n=e.length;n--;)if(e[n]===t)return n}function l(e,t,n,r){if(r?t[c(t,r)]=n:t[t.length++]=n,e){n.ownerElement=e;var o=e.ownerDocument;o&&(r&&v(o,e,r),y(o,e,n))}}function d(e,t,n){var r=c(t,n);if(!(r>=0))throw o(ae,new Error(e.tagName+"@"+n));for(var i=t.length-1;r"==e&&">"||"&"==e&&"&"||'"'==e&&"""||"&#"+e.charCodeAt()+";"}function g(e,t){if(t(e))return!0;if(e=e.firstChild)do{if(g(e,t))return!0}while(e=e.nextSibling)}function m(){}function y(e,t,n){e&&e._inc++,"http://www.w3.org/2000/xmlns/"==n.namespaceURI&&(t._nsMap[n.prefix?n.localName:""]=n.value)}function v(e,t,n,r){e&&e._inc++,"http://www.w3.org/2000/xmlns/"==n.namespaceURI&&delete t._nsMap[n.prefix?n.localName:""]}function C(e,t,n){if(e&&e._inc){e._inc++;var r=t.childNodes;if(n)r[r.length++]=n;else{for(var o=t.firstChild,i=0;o;)r[i++]=o,o=o.nextSibling;r.length=i}}}function R(e,t){var n=t.previousSibling,r=t.nextSibling;return n?n.nextSibling=r:e.firstChild=r,r?r.previousSibling=n:e.lastChild=n,C(e.ownerDocument,e),t}function k(e,t,n){var r=t.parentNode;if(r&&r.removeChild(t),t.nodeType===te){var o=t.firstChild;if(null==o)return t;var i=t.lastChild}else o=i=t;var a=n?n.previousSibling:e.lastChild;o.previousSibling=a,i.nextSibling=n,a?a.nextSibling=o:e.firstChild=o,null==n?e.lastChild=i:n.previousSibling=i;do{o.parentNode=e}while(o!==i&&(o=o.nextSibling));return C(e.ownerDocument||e,e),t.nodeType==te&&(t.firstChild=t.lastChild=null),t}function S(e,t){var n=t.parentNode;if(n){var r=e.lastChild;n.removeChild(t);var r=e.lastChild}var r=e.lastChild;return t.parentNode=e,t.previousSibling=r,t.nextSibling=null,r?r.nextSibling=t:e.firstChild=t,e.lastChild=t,C(e.ownerDocument,e,t),t}function A(){this._nsMap={}}function b(){}function w(){}function E(){}function T(){}function B(){}function _(){}function x(){}function I(){}function P(){}function O(){}function D(){}function N(){}function U(e,t){var n=[],r=9==this.nodeType?this.documentElement:this,o=r.prefix,i=r.namespaceURI;if(i&&null==o){var o=r.lookupPrefix(i);if(null==o)var a=[{namespace:i,prefix:null}]}return L(this,n,e,t,a),n.join("")}function M(e,t,n){var r=e.prefix||"",o=e.namespaceURI;if(!r&&!o)return!1;if("xml"===r&&"http://www.w3.org/XML/1998/namespace"===o||"http://www.w3.org/2000/xmlns/"==o)return!1;for(var i=n.length;i--;){var a=n[i];if(a.prefix==r)return a.namespace!=o}return!0}function L(e,t,n,r,o){if(r){if(!(e=r(e)))return;if("string"==typeof e)return void t.push(e)}switch(e.nodeType){case q:o||(o=[]);var i=(o.length,e.attributes),a=i.length,s=e.firstChild,u=e.tagName;n=z===e.namespaceURI||n,t.push("<",u);for(var c=0;c"),n&&/^script$/i.test(u))for(;s;)s.data?t.push(s.data):L(s,t,n,r,o),s=s.nextSibling;else for(;s;)L(s,t,n,r,o),s=s.nextSibling;t.push("")}else t.push("/>");return;case Z:case te:for(var s=e.firstChild;s;)L(s,t,n,r,o),s=s.nextSibling;return;case V:return t.push(" ",e.name,'="',e.value.replace(/[<&"]/g,p),'"');case Y:return t.push(e.data.replace(/[<&]/g,p));case X:return t.push("");case J:return t.push("\x3c!--",e.data,"--\x3e");case ee:var g=e.publicId,m=e.systemId;if(t.push("');else if(m&&"."!=m)t.push(' SYSTEM "',m,'">');else{var y=e.internalSubset;y&&t.push(" [",y,"]"),t.push(">")}return;case Q:return t.push("");case W:return t.push("&",e.nodeName,";");default:t.push("??",e.nodeName)}}function H(e,t,n){var r;switch(t.nodeType){case q:r=t.cloneNode(!1),r.ownerDocument=e;case te:break;case V:n=!0}if(r||(r=t.cloneNode(!1)),r.ownerDocument=e,r.parentNode=null,n)for(var o=t.firstChild;o;)r.appendChild(H(e,o,n)),o=o.nextSibling;return r}function F(e,t,n){var r=new t.constructor;for(var o in t){var a=t[o];"object"!=typeof a&&a!=r[o]&&(r[o]=a)}switch(t.childNodes&&(r.childNodes=new i),r.ownerDocument=e,r.nodeType){case q:var s=t.attributes,c=r.attributes=new u,l=s.length;c._ownerElement=r;for(var d=0;d0},lookupPrefix:function(e){for(var t=this;t;){var n=t._nsMap;if(n)for(var r in n)if(n[r]==e)return r;t=t.nodeType==V?t.ownerDocument:t.parentNode}return null},lookupNamespaceURI:function(e){for(var t=this;t;){var n=t._nsMap;if(n&&e in n)return n[e];t=t.nodeType==V?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){return null==this.lookupPrefix(e)}},n(G,h),n(G,h.prototype),m.prototype={nodeName:"#document",nodeType:Z,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==te){for(var n=e.firstChild;n;){var r=n.nextSibling;this.insertBefore(n,t),n=r}return e}return null==this.documentElement&&e.nodeType==q&&(this.documentElement=e),k(this,e,t),e.ownerDocument=this,e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),R(this,e)},importNode:function(e,t){return H(this,e,t)},getElementById:function(e){var t=null;return g(this.documentElement,function(n){if(n.nodeType==q&&n.getAttribute("id")==e)return t=n,!0}),t},createElement:function(e){var t=new A;return t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.childNodes=new i,(t.attributes=new u)._ownerElement=t,t},createDocumentFragment:function(){var e=new O;return e.ownerDocument=this,e.childNodes=new i,e},createTextNode:function(e){var t=new E;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new T;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){var t=new B;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var n=new D;return n.ownerDocument=this,n.tagName=n.target=e,n.nodeValue=n.data=t,n},createAttribute:function(e){var t=new b;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){var t=new P;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var n=new A,r=t.split(":"),o=n.attributes=new u;return n.childNodes=new i,n.ownerDocument=this,n.nodeName=t,n.tagName=t,n.namespaceURI=e,2==r.length?(n.prefix=r[0],n.localName=r[1]):n.localName=t,o._ownerElement=n,n},createAttributeNS:function(e,t){var n=new b,r=t.split(":");return n.ownerDocument=this,n.nodeName=t,n.name=t,n.namespaceURI=e,n.specified=!0,2==r.length?(n.prefix=r[0],n.localName=r[1]):n.localName=t,n}},r(m,h),A.prototype={nodeType:q,hasAttribute:function(e){return null!=this.getAttributeNode(e)},getAttribute:function(e){var t=this.getAttributeNode(e);return t&&t.value||""},getAttributeNode:function(e){return this.attributes.getNamedItem(e)},setAttribute:function(e,t){var n=this.ownerDocument.createAttribute(e);n.value=n.nodeValue=""+t,this.setAttributeNode(n)},removeAttribute:function(e){var t=this.getAttributeNode(e);t&&this.removeAttributeNode(t)},appendChild:function(e){return e.nodeType===te?this.insertBefore(e,null):S(this,e)},setAttributeNode:function(e){return this.attributes.setNamedItem(e)},setAttributeNodeNS:function(e){return this.attributes.setNamedItemNS(e)},removeAttributeNode:function(e){return this.attributes.removeNamedItem(e.nodeName)},removeAttributeNS:function(e,t){var n=this.getAttributeNodeNS(e,t);n&&this.removeAttributeNode(n)},hasAttributeNS:function(e,t){return null!=this.getAttributeNodeNS(e,t)},getAttributeNS:function(e,t){var n=this.getAttributeNodeNS(e,t);return n&&n.value||""},setAttributeNS:function(e,t,n){var r=this.ownerDocument.createAttributeNS(e,t);r.value=r.nodeValue=""+n,this.setAttributeNode(r)},getAttributeNodeNS:function(e,t){return this.attributes.getNamedItemNS(e,t)},getElementsByTagName:function(e){return new a(this,function(t){var n=[];return g(t,function(r){r===t||r.nodeType!=q||"*"!==e&&r.tagName!=e||n.push(r)}),n})},getElementsByTagNameNS:function(e,t){return new a(this,function(n){var r=[];return g(n,function(o){o===n||o.nodeType!==q||"*"!==e&&o.namespaceURI!==e||"*"!==t&&o.localName!=t||r.push(o)}),r})}},m.prototype.getElementsByTagName=A.prototype.getElementsByTagName,m.prototype.getElementsByTagNameNS=A.prototype.getElementsByTagNameNS,r(A,h),b.prototype.nodeType=V,r(b,h),w.prototype={data:"",substringData:function(e,t){return this.data.substring(e,e+t)},appendData:function(e){e=this.data+e,this.nodeValue=this.data=e,this.length=e.length},insertData:function(e,t){this.replaceData(e,0,t)},appendChild:function(e){throw new Error(oe[ie])},deleteData:function(e,t){this.replaceData(e,t,"")},replaceData:function(e,t,n){n=this.data.substring(0,e)+n+this.data.substring(e+t),this.nodeValue=this.data=n,this.length=n.length}},r(w,h),E.prototype={nodeName:"#text",nodeType:Y,splitText:function(e){var t=this.data,n=t.substring(e);t=t.substring(0,e),this.data=this.nodeValue=t,this.length=t.length;var r=this.ownerDocument.createTextNode(n);return this.parentNode&&this.parentNode.insertBefore(r,this.nextSibling),r}},r(E,w),T.prototype={nodeName:"#comment",nodeType:J},r(T,w),B.prototype={nodeName:"#cdata-section",nodeType:X},r(B,w),_.prototype.nodeType=ee,r(_,h),x.prototype.nodeType=ne,r(x,h),I.prototype.nodeType=$,r(I,h),P.prototype.nodeType=W,r(P,h),O.prototype.nodeName="#document-fragment",O.prototype.nodeType=te,r(O,h),D.prototype.nodeType=Q,r(D,h),N.prototype.serializeToString=function(e,t,n){return U.call(e,t,n)},h.prototype.toString=U;try{Object.defineProperty&&(Object.defineProperty(a.prototype,"length",{get:function(){return s(this),this.$$length}}),Object.defineProperty(h.prototype,"textContent",{get:function(){return j(this)},set:function(e){switch(this.nodeType){case q:case te:for(;this.firstChild;)this.removeChild(this.firstChild);(e||String(e))&&this.appendChild(this.ownerDocument.createTextNode(e));break;default:this.data=e,this.value=e,this.nodeValue=e}}}),K=function(e,t,n){e["$$"+t]=n})}catch(e){}t.DOMImplementation=f,t.XMLSerializer=N},function(e,t){var n=function(e){var t={},n=function(e){return!t[e]&&(t[e]=[]),t[e]};e.on=function(e,t){"task-list-update"===e&&console.warn('warning: Event "'+e+'" has been deprecated. Please use "list-update" instead.'),n(e).push(t)},e.off=function(e,t){for(var r=n(e),o=r.length-1;o>=0;o--)t===r[o]&&r.splice(o,1)},e.emit=function(e,t){for(var r=n(e).map(function(e){return e}),o=0;o=0;n--){var o=r[n][2];(!o||o+2592e3=0;o--){var i=r[o];i[0]===e&&i[1]===t&&r.splice(o,1)}r.unshift([e,t,Math.round(Date.now()/1e3)]),r.length>n&&r.splice(n),c()}},removeUploadId:function(e){u.call(this),delete l.using[e];for(var t=r.length-1;t>=0;t--)r[t][1]===e&&r.splice(t,1);c()}};e.exports=l},function(e,t,n){var r=n(6);e.exports=r},function(e,t,n){"use strict";var r=n(0),o=n(3),i=n(15),a=n(16),s=n(22),u={AppId:"",SecretId:"",SecretKey:"",SecurityToken:"",ChunkRetryTimes:2,FileParallelLimit:3,ChunkParallelLimit:3,ChunkSize:1048576,SliceSize:1048576,CopyChunkParallelLimit:20,CopyChunkSize:10485760,CopySliceSize:10485760,MaxPartNumber:1e4,ProgressInterval:1e3,Domain:"",ServiceDomain:"",Protocol:"",CompatibilityMode:!1,ForcePathStyle:!1,UseRawKey:!1,Timeout:0,CorrectClockSkew:!0,SystemClockOffset:0,UploadCheckContentMd5:!1,UploadQueueSize:1e4,UploadAddMetaMd5:!1,UploadIdCacheLimit:50},c=function(e){this.options=r.extend(r.clone(u),e||{}),this.options.FileParallelLimit=Math.max(1,this.options.FileParallelLimit),this.options.ChunkParallelLimit=Math.max(1,this.options.ChunkParallelLimit),this.options.ChunkRetryTimes=Math.max(0,this.options.ChunkRetryTimes),this.options.ChunkSize=Math.max(1048576,this.options.ChunkSize),this.options.CopyChunkParallelLimit=Math.max(1,this.options.CopyChunkParallelLimit),this.options.CopyChunkSize=Math.max(1048576,this.options.CopyChunkSize),this.options.CopySliceSize=Math.max(0,this.options.CopySliceSize),this.options.MaxPartNumber=Math.max(1024,Math.min(1e4,this.options.MaxPartNumber)),this.options.Timeout=Math.max(0,this.options.Timeout),this.options.AppId&&console.warn('warning: AppId has been deprecated, Please put it at the end of parameter Bucket(E.g: "test-1250000000").'),o.init(this),i.init(this)};a.init(c,i),s.init(c,i),c.getAuthorization=r.getAuth,c.version="1.2.0",e.exports=c},function(module,exports,__webpack_require__){(function(process,global){var __WEBPACK_AMD_DEFINE_RESULT__;!function(){"use strict";function Md5(e){if(e)blocks[0]=blocks[16]=blocks[1]=blocks[2]=blocks[3]=blocks[4]=blocks[5]=blocks[6]=blocks[7]=blocks[8]=blocks[9]=blocks[10]=blocks[11]=blocks[12]=blocks[13]=blocks[14]=blocks[15]=0,this.blocks=blocks,this.buffer8=buffer8;else if(ARRAY_BUFFER){var t=new ArrayBuffer(68);this.buffer8=new Uint8Array(t),this.blocks=new Uint32Array(t)}else this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];this.h0=this.h1=this.h2=this.h3=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}var ERROR="input is invalid type",WINDOW="object"==typeof window,root=WINDOW?window:{};root.JS_MD5_NO_WINDOW&&(WINDOW=!1);var WEB_WORKER=!WINDOW&&"object"==typeof self,NODE_JS=!root.JS_MD5_NO_NODE_JS&&"object"==typeof process&&process.versions&&process.versions.node;NODE_JS?root=global:WEB_WORKER&&(root=self);var COMMON_JS=!root.JS_MD5_NO_COMMON_JS&&"object"==typeof module&&module.exports,AMD=__webpack_require__(9),ARRAY_BUFFER=!root.JS_MD5_NO_ARRAY_BUFFER&&"undefined"!=typeof ArrayBuffer,HEX_CHARS="0123456789abcdef".split(""),EXTRA=[128,32768,8388608,-2147483648],SHIFT=[0,8,16,24],OUTPUT_TYPES=["hex","array","digest","buffer","arrayBuffer","base64"],BASE64_ENCODE_CHAR="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),blocks=[],buffer8;if(ARRAY_BUFFER){var buffer=new ArrayBuffer(68);buffer8=new Uint8Array(buffer),blocks=new Uint32Array(buffer)}!root.JS_MD5_NO_NODE_JS&&Array.isArray||(Array.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),!ARRAY_BUFFER||!root.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW&&ArrayBuffer.isView||(ArrayBuffer.isView=function(e){return"object"==typeof e&&e.buffer&&e.buffer.constructor===ArrayBuffer});var createOutputMethod=function(e){return function(t,n){return new Md5(!0).update(t,n)[e]()}},createMethod=function(){var e=createOutputMethod("hex");NODE_JS&&(e=nodeWrap(e)),e.getCtx=e.create=function(){return new Md5},e.update=function(t){return e.create().update(t)};for(var t=0;t>2]|=e[a]<>6,c[i++]=128|63&o):o<55296||o>=57344?(c[i++]=224|o>>12,c[i++]=128|o>>6&63,c[i++]=128|63&o):(o=65536+((1023&o)<<10|1023&e.charCodeAt(++a)),c[i++]=240|o>>18,c[i++]=128|o>>12&63,c[i++]=128|o>>6&63,c[i++]=128|63&o);else for(i=this.start;a>2]|=o<>2]|=(192|o>>6)<>2]|=(128|63&o)<=57344?(u[i>>2]|=(224|o>>12)<>2]|=(128|o>>6&63)<>2]|=(128|63&o)<>2]|=(240|o>>18)<>2]|=(128|o>>12&63)<>2]|=(128|o>>6&63)<>2]|=(128|63&o)<=64?(this.start=i-64,this.hash(),this.hashed=!0):this.start=i}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},Md5.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[t>>2]|=EXTRA[3&t],t>=56&&(this.hashed||this.hash(),e[0]=e[16],e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.bytes<<3,e[15]=this.hBytes<<3|this.bytes>>>29,this.hash()}},Md5.prototype.hash=function(){var e,t,n,r,o,i,a=this.blocks;this.first?(e=a[0]-680876937,e=(e<<7|e>>>25)-271733879<<0,r=(-1732584194^2004318071&e)+a[1]-117830708,r=(r<<12|r>>>20)+e<<0,n=(-271733879^r&(-271733879^e))+a[2]-1126478375,n=(n<<17|n>>>15)+r<<0,t=(e^n&(r^e))+a[3]-1316259209,t=(t<<22|t>>>10)+n<<0):(e=this.h0,t=this.h1,n=this.h2,r=this.h3,e+=(r^t&(n^r))+a[0]-680876936,e=(e<<7|e>>>25)+t<<0,r+=(n^e&(t^n))+a[1]-389564586,r=(r<<12|r>>>20)+e<<0,n+=(t^r&(e^t))+a[2]+606105819,n=(n<<17|n>>>15)+r<<0,t+=(e^n&(r^e))+a[3]-1044525330,t=(t<<22|t>>>10)+n<<0),e+=(r^t&(n^r))+a[4]-176418897,e=(e<<7|e>>>25)+t<<0,r+=(n^e&(t^n))+a[5]+1200080426,r=(r<<12|r>>>20)+e<<0,n+=(t^r&(e^t))+a[6]-1473231341,n=(n<<17|n>>>15)+r<<0,t+=(e^n&(r^e))+a[7]-45705983,t=(t<<22|t>>>10)+n<<0,e+=(r^t&(n^r))+a[8]+1770035416,e=(e<<7|e>>>25)+t<<0,r+=(n^e&(t^n))+a[9]-1958414417,r=(r<<12|r>>>20)+e<<0,n+=(t^r&(e^t))+a[10]-42063,n=(n<<17|n>>>15)+r<<0,t+=(e^n&(r^e))+a[11]-1990404162,t=(t<<22|t>>>10)+n<<0,e+=(r^t&(n^r))+a[12]+1804603682,e=(e<<7|e>>>25)+t<<0,r+=(n^e&(t^n))+a[13]-40341101,r=(r<<12|r>>>20)+e<<0,n+=(t^r&(e^t))+a[14]-1502002290,n=(n<<17|n>>>15)+r<<0,t+=(e^n&(r^e))+a[15]+1236535329,t=(t<<22|t>>>10)+n<<0,e+=(n^r&(t^n))+a[1]-165796510,e=(e<<5|e>>>27)+t<<0,r+=(t^n&(e^t))+a[6]-1069501632,r=(r<<9|r>>>23)+e<<0,n+=(e^t&(r^e))+a[11]+643717713,n=(n<<14|n>>>18)+r<<0,t+=(r^e&(n^r))+a[0]-373897302,t=(t<<20|t>>>12)+n<<0,e+=(n^r&(t^n))+a[5]-701558691,e=(e<<5|e>>>27)+t<<0,r+=(t^n&(e^t))+a[10]+38016083,r=(r<<9|r>>>23)+e<<0,n+=(e^t&(r^e))+a[15]-660478335,n=(n<<14|n>>>18)+r<<0,t+=(r^e&(n^r))+a[4]-405537848,t=(t<<20|t>>>12)+n<<0,e+=(n^r&(t^n))+a[9]+568446438,e=(e<<5|e>>>27)+t<<0,r+=(t^n&(e^t))+a[14]-1019803690,r=(r<<9|r>>>23)+e<<0,n+=(e^t&(r^e))+a[3]-187363961,n=(n<<14|n>>>18)+r<<0,t+=(r^e&(n^r))+a[8]+1163531501,t=(t<<20|t>>>12)+n<<0,e+=(n^r&(t^n))+a[13]-1444681467,e=(e<<5|e>>>27)+t<<0,r+=(t^n&(e^t))+a[2]-51403784,r=(r<<9|r>>>23)+e<<0,n+=(e^t&(r^e))+a[7]+1735328473,n=(n<<14|n>>>18)+r<<0,t+=(r^e&(n^r))+a[12]-1926607734,t=(t<<20|t>>>12)+n<<0,o=t^n,e+=(o^r)+a[5]-378558,e=(e<<4|e>>>28)+t<<0,r+=(o^e)+a[8]-2022574463,r=(r<<11|r>>>21)+e<<0,i=r^e,n+=(i^t)+a[11]+1839030562,n=(n<<16|n>>>16)+r<<0,t+=(i^n)+a[14]-35309556,t=(t<<23|t>>>9)+n<<0,o=t^n,e+=(o^r)+a[1]-1530992060,e=(e<<4|e>>>28)+t<<0,r+=(o^e)+a[4]+1272893353,r=(r<<11|r>>>21)+e<<0,i=r^e,n+=(i^t)+a[7]-155497632,n=(n<<16|n>>>16)+r<<0,t+=(i^n)+a[10]-1094730640,t=(t<<23|t>>>9)+n<<0,o=t^n,e+=(o^r)+a[13]+681279174,e=(e<<4|e>>>28)+t<<0,r+=(o^e)+a[0]-358537222,r=(r<<11|r>>>21)+e<<0,i=r^e,n+=(i^t)+a[3]-722521979,n=(n<<16|n>>>16)+r<<0,t+=(i^n)+a[6]+76029189,t=(t<<23|t>>>9)+n<<0,o=t^n,e+=(o^r)+a[9]-640364487,e=(e<<4|e>>>28)+t<<0,r+=(o^e)+a[12]-421815835,r=(r<<11|r>>>21)+e<<0,i=r^e,n+=(i^t)+a[15]+530742520,n=(n<<16|n>>>16)+r<<0,t+=(i^n)+a[2]-995338651,t=(t<<23|t>>>9)+n<<0,e+=(n^(t|~r))+a[0]-198630844,e=(e<<6|e>>>26)+t<<0,r+=(t^(e|~n))+a[7]+1126891415,r=(r<<10|r>>>22)+e<<0,n+=(e^(r|~t))+a[14]-1416354905,n=(n<<15|n>>>17)+r<<0,t+=(r^(n|~e))+a[5]-57434055,t=(t<<21|t>>>11)+n<<0,e+=(n^(t|~r))+a[12]+1700485571,e=(e<<6|e>>>26)+t<<0,r+=(t^(e|~n))+a[3]-1894986606,r=(r<<10|r>>>22)+e<<0,n+=(e^(r|~t))+a[10]-1051523,n=(n<<15|n>>>17)+r<<0,t+=(r^(n|~e))+a[1]-2054922799,t=(t<<21|t>>>11)+n<<0,e+=(n^(t|~r))+a[8]+1873313359,e=(e<<6|e>>>26)+t<<0,r+=(t^(e|~n))+a[15]-30611744,r=(r<<10|r>>>22)+e<<0,n+=(e^(r|~t))+a[6]-1560198380,n=(n<<15|n>>>17)+r<<0,t+=(r^(n|~e))+a[13]+1309151649,t=(t<<21|t>>>11)+n<<0,e+=(n^(t|~r))+a[4]-145523070,e=(e<<6|e>>>26)+t<<0,r+=(t^(e|~n))+a[11]-1120210379,r=(r<<10|r>>>22)+e<<0,n+=(e^(r|~t))+a[2]+718787259,n=(n<<15|n>>>17)+r<<0,t+=(r^(n|~e))+a[9]-343485551,t=(t<<21|t>>>11)+n<<0,this.first?(this.h0=e+1732584193<<0,this.h1=t-271733879<<0,this.h2=n-1732584194<<0,this.h3=r+271733878<<0,this.first=!1):(this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0)},Md5.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,n=this.h2,r=this.h3;return HEX_CHARS[e>>4&15]+HEX_CHARS[15&e]+HEX_CHARS[e>>12&15]+HEX_CHARS[e>>8&15]+HEX_CHARS[e>>20&15]+HEX_CHARS[e>>16&15]+HEX_CHARS[e>>28&15]+HEX_CHARS[e>>24&15]+HEX_CHARS[t>>4&15]+HEX_CHARS[15&t]+HEX_CHARS[t>>12&15]+HEX_CHARS[t>>8&15]+HEX_CHARS[t>>20&15]+HEX_CHARS[t>>16&15]+HEX_CHARS[t>>28&15]+HEX_CHARS[t>>24&15]+HEX_CHARS[n>>4&15]+HEX_CHARS[15&n]+HEX_CHARS[n>>12&15]+HEX_CHARS[n>>8&15]+HEX_CHARS[n>>20&15]+HEX_CHARS[n>>16&15]+HEX_CHARS[n>>28&15]+HEX_CHARS[n>>24&15]+HEX_CHARS[r>>4&15]+HEX_CHARS[15&r]+HEX_CHARS[r>>12&15]+HEX_CHARS[r>>8&15]+HEX_CHARS[r>>20&15]+HEX_CHARS[r>>16&15]+HEX_CHARS[r>>28&15]+HEX_CHARS[r>>24&15]},Md5.prototype.toString=Md5.prototype.hex,Md5.prototype.digest=function(e){if("hex"===e)return this.hex();this.finalize();var t=this.h0,n=this.h1,r=this.h2,o=this.h3;return[255&t,t>>8&255,t>>16&255,t>>24&255,255&n,n>>8&255,n>>16&255,n>>24&255,255&r,r>>8&255,r>>16&255,r>>24&255,255&o,o>>8&255,o>>16&255,o>>24&255]},Md5.prototype.array=Md5.prototype.digest,Md5.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(16),t=new Uint32Array(e);return t[0]=this.h0,t[1]=this.h1,t[2]=this.h2,t[3]=this.h3,e},Md5.prototype.buffer=Md5.prototype.arrayBuffer,Md5.prototype.base64=function(){for(var e,t,n,r="",o=this.array(),i=0;i<15;)e=o[i++],t=o[i++],n=o[i++],r+=BASE64_ENCODE_CHAR[e>>>2]+BASE64_ENCODE_CHAR[63&(e<<4|t>>>4)]+BASE64_ENCODE_CHAR[63&(t<<2|n>>>6)]+BASE64_ENCODE_CHAR[63&n];return e=o[i],r+=BASE64_ENCODE_CHAR[e>>>2]+BASE64_ENCODE_CHAR[e<<4&63]+"=="};var exports=createMethod();COMMON_JS?module.exports=exports:(root.md5=exports,AMD&&void 0!==(__WEBPACK_AMD_DEFINE_RESULT__=function(){return exports}.call(exports,__webpack_require__,exports,module))&&(module.exports=__WEBPACK_AMD_DEFINE_RESULT__))}()}).call(exports,__webpack_require__(8),__webpack_require__(1))},function(e,t){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function o(e){if(l===setTimeout)return setTimeout(e,0);if((l===n||!l)&&setTimeout)return l=setTimeout,setTimeout(e,0);try{return l(e,0)}catch(t){try{return l.call(null,e,0)}catch(t){return l.call(this,e,0)}}}function i(e){if(d===clearTimeout)return clearTimeout(e);if((d===r||!d)&&clearTimeout)return d=clearTimeout,clearTimeout(e);try{return d(e)}catch(t){try{return d.call(null,e)}catch(t){return d.call(this,e)}}}function a(){g&&h&&(g=!1,h.length?p=h.concat(p):m=-1,p.length&&s())}function s(){if(!g){var e=o(a);g=!0;for(var t=p.length;t;){for(h=p,p=[];++m1)for(var n=1;n>>2]|=(n[o>>>2]>>>24-o%4*8&255)<<24-(r+o)%4*8;else if(65535>>2]=n[o>>>2];else t.push.apply(t,n);return this.sigBytes+=e,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n=[],r=0;r>>2]>>>24-r%4*8&255;n.push((o>>>4).toString(16)),n.push((15&o).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new a.init(n,t/2)}},c=s.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var n=[],r=0;r>>2]>>>24-r%4*8&255));return n.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new a.init(n,t)}},l=s.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},d=r.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new a.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=l.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,r=n.words,o=n.sigBytes,i=this.blockSize,s=o/(4*i),s=t?e.ceil(s):e.max((0|s)-this._minBufferSize,0);if(t=s*i,o=e.min(4*t,o),t){for(var u=0;uc;c++){if(16>c)i[c]=0|e[t+c];else{var l=i[c-3]^i[c-8]^i[c-14]^i[c-16];i[c]=l<<1|l>>>31}l=(r<<5|r>>>27)+u+i[c],l=20>c?l+(1518500249+(o&a|~o&s)):40>c?l+(1859775393+(o^a^s)):60>c?l+((o&a|o&s|a&s)-1894007588):l+((o^a^s)-899497514),u=s,s=a,a=o<<30|o>>>2,o=r,r=l}n[0]=n[0]+r|0,n[1]=n[1]+o|0,n[2]=n[2]+a|0,n[3]=n[3]+s|0,n[4]=n[4]+u|0},_doFinalize:function(){var e=this._data,t=e.words,n=8*this._nDataBytes,r=8*e.sigBytes;return t[r>>>5]|=128<<24-r%32,t[14+(r+64>>>9<<4)]=Math.floor(n/4294967296),t[15+(r+64>>>9<<4)]=n,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}});e.SHA1=o._createHelper(t),e.HmacSHA1=o._createHmacHelper(t)}(),function(){var e=r,t=e.enc.Utf8;e.algo.HMAC=e.lib.Base.extend({init:function(e,n){e=this._hasher=new e.init,"string"==typeof n&&(n=t.parse(n));var r=e.blockSize,o=4*r;n.sigBytes>o&&(n=e.finalize(n)),n.clamp();for(var i=this._oKey=n.clone(),a=this._iKey=n.clone(),s=i.words,u=a.words,c=0;c>>2]>>>24-i%4*8&255,s=t[i+1>>>2]>>>24-(i+1)%4*8&255,u=t[i+2>>>2]>>>24-(i+2)%4*8&255,c=a<<16|s<<8|u,l=0;l<4&&i+.75*l>>6*(3-l)&63));var d=r.charAt(64);if(d)for(;o.length%4;)o.push(d);return o.join("")},parse:function(e){var t=e.length,r=this._map,o=r.charAt(64);if(o){var i=e.indexOf(o);-1!=i&&(t=i)}for(var a=[],s=0,u=0;u>>6-u%4*2;a[s>>>2]|=(c|l)<<24-s%4*8,s++}return n.create(a,s)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),e.exports=r},function(e,t,n){var r=n(12).DOMParser,o=function(){this.version="1.3.5";var e={mergeCDATA:!0,normalize:!0,stripElemPrefix:!0},t=new RegExp(/(?!xmlns)^.*:/);new RegExp(/^\s+|\s+$/g);return this.grokType=function(e){return/^\s*$/.test(e)?null:/^(?:true|false)$/i.test(e)?"true"===e.toLowerCase():isFinite(e)?parseFloat(e):e},this.parseString=function(e,t){if(e){var n=this.stringToXML(e);return n.getElementsByTagName("parsererror").length?null:this.parseXML(n,t)}return null},this.parseXML=function(n,r){for(var i in r)e[i]=r[i];var a={},s=0,u="";if(n.childNodes.length)for(var c,l,d,f=0;f=t+n||t?new java.lang.String(e,t,n)+"":e}function c(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}r.prototype.parseFromString=function(e,t){var n=this.options,r=new l,a=n.domBuilder||new i,s=n.errorHandler,u=n.locator,c=n.xmlns||{},d={lt:"<",gt:">",amp:"&",quot:'"',apos:"'"};return u&&a.setDocumentLocator(u),r.errorHandler=o(s,a,u),r.domBuilder=n.domBuilder||a,/\/x?html?$/.test(t)&&(d.nbsp="\xa0",d.copy="\xa9",c[""]="http://www.w3.org/1999/xhtml"),c.xml=c.xml||"http://www.w3.org/XML/1998/namespace",e?r.parse(e,c,d):r.errorHandler.error("invalid doc source"),a.doc},i.prototype={startDocument:function(){this.doc=(new d).createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(e,t,n,r){var o=this.doc,i=o.createElementNS(e,n||t),s=r.length;c(this,i),this.currentElement=i,this.locator&&a(this.locator,i);for(var u=0;u65535){e-=65536;var t=55296+(e>>10),n=56320+(1023&e);return String.fromCharCode(t,n)}return String.fromCharCode(e)}function p(e){var t=e.slice(1,-1);return t in n?n[t]:"#"===t.charAt(0)?h(parseInt(t.substr(1).replace("x","0x"))):(c.error("entity not found:"+e),e)}function g(t){if(t>A){var n=e.substring(A,t).replace(/&#?\w+;/g,p);R&&m(A),r.characters(n,0,t-A),A=t}}function m(t,n){for(;t>=v&&(n=C.exec(e));)y=n.index,v=y+n[0].length,R.lineNumber++;R.columnNumber=t-y+1}for(var y=0,v=0,C=/.*(?:\r\n?|\n)|.*$/g,R=r.locator,k=[{currentNSMap:t}],S={},A=0;;){try{var b=e.indexOf("<",A);if(b<0){if(!e.substr(A).match(/^\s*$/)){var w=r.doc,E=w.createTextNode(e.substr(A));w.appendChild(E),r.currentElement=E}return}switch(b>A&&g(b),e.charAt(b+1)){case"/":var T=e.indexOf(">",b+3),B=e.substring(b+2,T),_=k.pop();T<0?(B=e.substring(b+2).replace(/[\s<].*/,""),c.error("end tag name: "+B+" is not complete:"+_.tagName),T=b+1+B.length):B.match(/\sA?A=T:g(Math.max(b,A)+1)}}function o(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function i(e,t,n,r,o,i){for(var a,s,u=++t,c=v;;){var l=e.charAt(u);switch(l){case"=":if(c===C)a=e.slice(t,u),c=k;else{if(c!==R)throw new Error("attribute equal must after attrName");c=k}break;case"'":case'"':if(c===k||c===C){if(c===C&&(i.warning('attribute value must after "="'),a=e.slice(t,u)),t=u+1,!((u=e.indexOf(l,t))>0))throw new Error("attribute value no end '"+l+"' match");s=e.slice(t,u).replace(/&#?\w+;/g,o),n.add(a,s,t-1),c=A}else{if(c!=S)throw new Error('attribute value must after "="');s=e.slice(t,u).replace(/&#?\w+;/g,o),n.add(a,s,t),i.warning('attribute "'+a+'" missed start quot('+l+")!!"),t=u+1,c=A}break;case"/":switch(c){case v:n.setTagName(e.slice(t,u));case A:case b:case w:c=w,n.closed=!0;case S:case C:case R:break;default:throw new Error("attribute invalid close char('/')")}break;case"":return i.error("unexpected end of input"),c==v&&n.setTagName(e.slice(t,u)),u;case">":switch(c){case v:n.setTagName(e.slice(t,u));case A:case b:case w:break;case S:case C:s=e.slice(t,u),"/"===s.slice(-1)&&(n.closed=!0,s=s.slice(0,-1));case R:c===R&&(s=a),c==S?(i.warning('attribute "'+s+'" missed quot(")!!'),n.add(a,s.replace(/&#?\w+;/g,o),t)):("http://www.w3.org/1999/xhtml"===r[""]&&s.match(/^(?:disabled|checked|selected)$/i)||i.warning('attribute "'+s+'" missed value!! "'+s+'" instead!!'),n.add(s,s,t));break;case k:throw new Error("attribute value missed!!")}return u;case"\x80":l=" ";default:if(l<=" ")switch(c){case v:n.setTagName(e.slice(t,u)),c=b;break;case C:a=e.slice(t,u),c=R;break;case S:var s=e.slice(t,u).replace(/&#?\w+;/g,o);i.warning('attribute "'+s+'" missed quot(")!!'),n.add(a,s,t);case A:c=b}else switch(c){case R:n.tagName;"http://www.w3.org/1999/xhtml"===r[""]&&a.match(/^(?:disabled|checked|selected)$/i)||i.warning('attribute "'+a+'" missed value!! "'+a+'" instead2!!'),n.add(a,a,t),t=u,c=C;break;case A:i.warning('attribute space is required"'+a+'"!!');case b:c=C,t=u;break;case k:c=S,t=u;break;case w:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function a(e,t,n){for(var r=e.tagName,o=null,i=e.length;i--;){var a=e[i],s=a.qName,u=a.value,l=s.indexOf(":");if(l>0)var d=a.prefix=s.slice(0,l),f=s.slice(l+1),h="xmlns"===d&&f;else f=s,d=null,h="xmlns"===s&&"";a.localName=f,!1!==h&&(null==o&&(o={},c(n,n={})),n[h]=o[h]=u,a.uri="http://www.w3.org/2000/xmlns/",t.startPrefixMapping(h,u))}for(var i=e.length;i--;){a=e[i];var d=a.prefix;d&&("xml"===d&&(a.uri="http://www.w3.org/XML/1998/namespace"),"xmlns"!==d&&(a.uri=n[d||""]))}var l=r.indexOf(":");l>0?(d=e.prefix=r.slice(0,l),f=e.localName=r.slice(l+1)):(d=null,f=e.localName=r);var p=e.uri=n[d||""];if(t.startElement(p,f,r,e),!e.closed)return e.currentNSMap=n,e.localNSMap=o,!0;if(t.endElement(p,f,r),o)for(d in o)t.endPrefixMapping(d)}function s(e,t,n,r,o){if(/^(?:script|textarea)$/i.test(n)){var i=e.indexOf("",t),a=e.substring(t+1,i);if(/[&<]/.test(a))return/^script$/i.test(n)?(o.characters(a,0,a.length),i):(a=a.replace(/&#?\w+;/g,r),o.characters(a,0,a.length),i)}return t+1}function u(e,t,n,r){var o=r[n];return null==o&&(o=e.lastIndexOf(""),ot?(n.comment(e,t+4,o-t-4),o+3):(r.error("Unclosed comment"),-1)}return-1;default:if("CDATA["==e.substr(t+3,6)){var o=e.indexOf("]]>",t+9);return n.startCDATA(),n.characters(e,t+9,o-t-9),n.endCDATA(),o+3}var i=p(e,t),a=i.length;if(a>1&&/!doctype/i.test(i[0][0])){var s=i[1][0],u=a>3&&/^public$/i.test(i[2][0])&&i[3][0],c=a>4&&i[4][0],l=i[a-1];return n.startDTD(s,u&&u.replace(/^(['"])(.*?)\1$/,"$2"),c&&c.replace(/^(['"])(.*?)\1$/,"$2")),n.endDTD(),l.index+l[0].length}}return-1}function d(e,t,n){var r=e.indexOf("?>",t);if(r){var o=e.substring(t,r).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);if(o){o[0].length;return n.processingInstruction(o[1],o[2]),r+2}return-1}return-1}function f(e){}function h(e,t){return e.__proto__=t,e}function p(e,t){var n,r=[],o=/'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;for(o.lastIndex=t,o.exec(e);n=o.exec(e);)if(r.push(n),n[1])return r}var g=/[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,m=new RegExp("[\\-\\.0-9"+g.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),y=new RegExp("^"+g.source+m.source+"*(?::"+g.source+m.source+"*)?$"),v=0,C=1,R=2,k=3,S=4,A=5,b=6,w=7;n.prototype={parse:function(e,t,n){var o=this.domBuilder;o.startDocument(),c(t,t={}),r(e,t,n,o,this.errorHandler),o.endDocument()}},f.prototype={setTagName:function(e){if(!y.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},add:function(e,t,n){if(!y.test(e))throw new Error("invalid attribute:"+e);this[this.length++]={qName:e,value:t,offset:n}},length:0,getLocalName:function(e){return this[e].localName},getLocator:function(e){return this[e].locator},getQName:function(e){return this[e].qName},getURI:function(e){return this[e].uri},getValue:function(e){return this[e].value}},h({},h.prototype)instanceof h||(h=function(e,t){function n(){}n.prototype=t,n=new n;for(t in e)n[t]=e[t];return n}),t.XMLReader=n},function(e,t){function n(e){return(""+e).replace(/&/g,"&").replace(//g,">").replace(/'/g,"'").replace(/"/g,""").replace(o,"")}var r=new RegExp("^([^a-zA-Z_\xc0-\xd6\xd8-\xf6\xf8-\xff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fff\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd])|^((x|X)(m|M)(l|L))|([^a-zA-Z_\xc0-\xd6\xd8-\xf6\xf8-\xff\u0370-\u037d\u037f-\u1fff\u200c-\u200d\u2070-\u218f\u2c00-\u2fff\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd-.0-9\xb7\u0300-\u036f\u203f\u2040])","g"),o=/[^\x09\x0A\x0D\x20-\xFF\x85\xA0-\uD7FF\uE000-\uFDCF\uFDE0-\uFFFD]/gm,i=function(e){var t=[];if(e instanceof Object)for(var n in e)e.hasOwnProperty(n)&&t.push(n);return t},a=function(e,t){var o=function(e,n,o,i,a){var s=void 0!==t.indent?t.indent:"\t",u=t.prettyPrint?"\n"+new Array(i).join(s):"";t.removeIllegalNameCharacters&&(e=e.replace(r,"_"));var c=[u,"<",e,o||""];return n&&n.length>0?(c.push(">"),c.push(n),a&&c.push(u),c.push("")):c.push("/>"),c.join("")};return function e(r,a,s){var u=typeof r;switch((Array.isArray?Array.isArray(r):r instanceof Array)?u="array":r instanceof Date&&(u="date"),u){case"array":var c=[];return r.map(function(t){c.push(e(t,1,s+1))}),t.prettyPrint&&c.push("\n"),c.join("");case"date":return r.toJSON?r.toJSON():r+"";case"object":var l=[];for(var d in r)if(r.hasOwnProperty(d))if(r[d]instanceof Array)for(var f=0;f0&&l.push("\n"),l.join("");case"function":return r();default:return t.escape?n(r):""+r}}(e,0,0)},s=function(e){var t=['"),t.join("")};e.exports=function(e,t){if(t||(t={xmlHeader:{standalone:!0},prettyPrint:!0,indent:" ",escape:!0}),"string"==typeof e)try{e=JSON.parse(e.toString())}catch(e){return!1}var n="",r="";return t&&("object"==typeof t?(t.xmlHeader&&(n=s(!!t.xmlHeader.standalone)),void 0!==t.docType&&(r="")):n=s()),t=t||{},[n,t.prettyPrint&&r?"\n":"",r,a(e,t)].join("").replace(/\n{2,}/g,"\n").replace(/\s+$/g,"")}},function(e,t,n){var r=n(4),o=n(0),i={},a=function(e,t){i[t]=e[t],e[t]=function(e,n){e.SkipTask?i[t].call(this,e,n):this._addTask(t,e,n)}},s=function(e){var t=[],n={},a=0,s=0,u=function(e){var t={id:e.id,Bucket:e.Bucket,Region:e.Region,Key:e.Key,FilePath:e.FilePath,state:e.state,loaded:e.loaded,size:e.size,speed:e.speed,percent:e.percent,hashPercent:e.hashPercent,error:e.error};return e.FilePath&&(t.FilePath=e.FilePath),e._custom&&(t._custom=e._custom),t},c=function(){var n,r=function(){n=0,e.emit("task-list-update",{list:o.map(t,u)}),e.emit("list-update",{list:o.map(t,u)})};return function(){n||(n=setTimeout(r))}}(),l=function(){if(!(t.length<=e.options.UploadQueueSize)){for(var r=0;re.options.UploadQueueSize;){var o="waiting"===t[r].state||"checking"===t[r].state||"uploading"===t[r].state;t[r]&&o?r++:(n[t[r].id]&&delete n[t[r].id],t.splice(r,1),s--)}c()}},d=function(){if(!(a>=e.options.FileParallelLimit)){for(;t[s]&&"waiting"!==t[s].state;)s++;if(!(s>=t.length)){var n=t[s];s++,a++,n.state="checking",n.params.onTaskStart&&n.params.onTaskStart(u(n)),!n.params.UploadData&&(n.params.UploadData={});var r=o.formatParams(n.api,n.params);i[n.api].call(e,r,function(t,r){e._isRunningTask(n.id)&&("checking"!==n.state&&"uploading"!==n.state||(n.state=t?"error":"success",t&&(n.error=t),a--,c(),d(),n.callback&&n.callback(t,r),"success"===n.state&&(n.params&&(delete n.params.UploadData,delete n.params.Body,delete n.params),delete n.callback)),l())}),c(),setTimeout(d)}}},f=function(t,o){var i=n[t];if(i){var s=i&&"waiting"===i.state,u=i&&("checking"===i.state||"uploading"===i.state);if("canceled"===o&&"canceled"!==i.state||"paused"===o&&s||"paused"===o&&u){if("paused"===o&&i.params.Body&&"function"==typeof i.params.Body.pipe)return void console.error("stream not support pause");i.state=o,e.emit("inner-kill-task",{TaskId:t,toState:o});try{var f=i&&i.params&&i.params.UploadData.UploadId}catch(e){}"canceled"===o&&f&&r.removeUsing(f),c(),u&&(a--,d()),"canceled"===o&&(i.params&&(delete i.params.UploadData,delete i.params.Body,delete i.params),delete i.callback)}l()}};e._addTasks=function(t){o.each(t,function(t){e._addTask(t.api,t.params,t.callback,!0)}),c()};var h=!0;e._addTask=function(r,i,a,s){i=o.formatParams(r,i);var u=o.uuid();i.TaskId=u,i.onTaskReady&&i.onTaskReady(u),i.TaskReady&&(i.TaskReady(u),h&&console.warn('warning: Param "TaskReady" has been deprecated. Please use "onTaskReady" instead.'),h=!1);var f={params:i,callback:a,api:r,index:t.length,id:u,Bucket:i.Bucket,Region:i.Region,Key:i.Key,FilePath:i.FilePath||"",state:"waiting",loaded:0,size:0,speed:0,percent:0,hashPercent:0,error:null,_custom:i._custom},p=i.onHashProgress;i.onHashProgress=function(t){e._isRunningTask(f.id)&&(f.hashPercent=t.percent,p&&p(t),c())};var g=i.onProgress;return i.onProgress=function(t){e._isRunningTask(f.id)&&("checking"===f.state&&(f.state="uploading"),f.loaded=t.loaded,f.speed=t.speed,f.percent=t.percent,g&&g(t),c())},o.getFileSize(r,i,function(e,r){if(e)return a(o.error(e));n[u]=f,t.push(f),f.size=r,!s&&c(),d(),l()}),u},e._isRunningTask=function(e){var t=n[e];return!(!t||"checking"!==t.state&&"uploading"!==t.state)},e.getTaskList=function(){return o.map(t,u)},e.cancelTask=function(e){f(e,"canceled")},e.pauseTask=function(e){f(e,"paused")},e.restartTask=function(e){var t=n[e];!t||"paused"!==t.state&&"error"!==t.state||(t.state="waiting",c(),s=Math.min(s,t.index),d())},e.isUploadRunning=function(){return a||s/gi,"<$1Rule>"),r=r.replace(/<(\/?)Tags>/gi,"<$1Tag>");var o=e.Headers;o["Content-Type"]="application/xml",o["Content-MD5"]=Ee.binaryBase64(Ee.md5(r)),Se.call(this,{Action:"name/cos:PutBucketReplication",method:"PUT",Bucket:e.Bucket,Region:e.Region,body:r,action:"replication",headers:o},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function E(e,t){Se.call(this,{Action:"name/cos:GetBucketReplication",method:"GET",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"replication"},function(e,n){if(e)if(404!==e.statusCode||!e.error||"Not Found"!==e.error&&"ReplicationConfigurationnotFoundError"!==e.error.Code)t(e);else{var r={ReplicationConfiguration:{Rules:[]},statusCode:e.statusCode};e.headers&&(r.headers=e.headers),t(null,r)}else e||!n.ReplicationConfiguration&&(n.ReplicationConfiguration={}),n.ReplicationConfiguration.Rule&&(n.ReplicationConfiguration.Rules=Ee.makeArray(n.ReplicationConfiguration.Rule),delete n.ReplicationConfiguration.Rule),t(e,n)})}function T(e,t){Se.call(this,{Action:"name/cos:DeleteBucketReplication",method:"DELETE",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"replication"},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function B(e,t){if(!e.WebsiteConfiguration)return void t(Ee.error(new Error("missing param WebsiteConfiguration")));var n=Ee.clone(e.WebsiteConfiguration||{}),r=n.RoutingRules||n.RoutingRule||[];r=Ee.isArray(r)?r:[r],delete n.RoutingRule,delete n.RoutingRules,r.length&&(n.RoutingRules={RoutingRule:r});var o=Ee.json2xml({WebsiteConfiguration:n}),i=e.Headers;i["Content-Type"]="application/xml",i["Content-MD5"]=Ee.binaryBase64(Ee.md5(o)),Se.call(this,{Action:"name/cos:PutBucketWebsite",method:"PUT",Bucket:e.Bucket,Region:e.Region,body:o,action:"website",headers:i},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function _(e,t){Se.call(this,{Action:"name/cos:GetBucketWebsite",method:"GET",Bucket:e.Bucket,Region:e.Region,Key:e.Key,headers:e.Headers,action:"website"},function(e,n){if(e)if(404===e.statusCode&&"NoSuchWebsiteConfiguration"===e.error.Code){var r={WebsiteConfiguration:{},statusCode:e.statusCode};e.headers&&(r.headers=e.headers),t(null,r)}else t(e);else{var o=n.WebsiteConfiguration||{};if(o.RoutingRules){var i=Ee.clone(o.RoutingRules.RoutingRule||[]);i=Ee.makeArray(i),o.RoutingRules=i}t(null,{WebsiteConfiguration:o,statusCode:n.statusCode,headers:n.headers})}})}function x(e,t){Se.call(this,{Action:"name/cos:DeleteBucketWebsite",method:"DELETE",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"website"},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function I(e,t){if(!e.RefererConfiguration)return void t(Ee.error(new Error("missing param RefererConfiguration")));var n=Ee.clone(e.RefererConfiguration||{}),r=n.DomainList||{},o=r.Domains||r.Domain||[];o=Ee.isArray(o)?o:[o],o.length&&(n.DomainList={Domain:o});var i=Ee.json2xml({RefererConfiguration:n}),a=e.Headers;a["Content-Type"]="application/xml",a["Content-MD5"]=Ee.binaryBase64(Ee.md5(i)),Se.call(this,{Action:"name/cos:PutBucketReferer",method:"PUT",Bucket:e.Bucket,Region:e.Region,body:i,action:"referer",headers:a},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function P(e,t){Se.call(this,{Action:"name/cos:GetBucketReferer",method:"GET",Bucket:e.Bucket,Region:e.Region,Key:e.Key,headers:e.Headers,action:"referer"},function(e,n){if(e)if(404===e.statusCode&&"NoSuchRefererConfiguration"===e.error.Code){var r={WebsiteConfiguration:{},statusCode:e.statusCode};e.headers&&(r.headers=e.headers),t(null,r)}else t(e);else{var o=n.RefererConfiguration||{};if(o.DomainList){var i=Ee.clone(o.DomainList.Domain||[]);i=Ee.makeArray(i),o.DomainList={Domains:i}}t(null,{RefererConfiguration:o,statusCode:n.statusCode,headers:n.headers})}})}function O(e,t){var n=e.DomainConfiguration||{},r=n.DomainRule||e.DomainRule||[];r=Ee.clone(r);var o=Ee.json2xml({DomainConfiguration:{DomainRule:r}}),i=e.Headers;i["Content-Type"]="application/xml",i["Content-MD5"]=Ee.binaryBase64(Ee.md5(o)),Se.call(this,{Action:"name/cos:PutBucketDomain",method:"PUT",Bucket:e.Bucket,Region:e.Region,body:o,action:"domain",headers:i},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function D(e,t){Se.call(this,{Action:"name/cos:GetBucketDomain",method:"GET",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"domain"},function(e,n){if(e)return t(e);var r=[];try{r=n.DomainConfiguration.DomainRule||[]}catch(e){}r=Ee.clone(Ee.isArray(r)?r:[r]),t(null,{DomainRule:r,statusCode:n.statusCode,headers:n.headers})})}function N(e,t){Se.call(this,{Action:"name/cos:DeleteBucketDomain",method:"DELETE",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"domain"},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function U(e,t){var n=e.OriginConfiguration||{},r=n.OriginRule||e.OriginRule||[];r=Ee.clone(r);var o=Ee.json2xml({OriginConfiguration:{OriginRule:r}}),i=e.Headers;i["Content-Type"]="application/xml",i["Content-MD5"]=Ee.binaryBase64(Ee.md5(o)),Se.call(this,{Action:"name/cos:PutBucketOrigin",method:"PUT",Bucket:e.Bucket,Region:e.Region,body:o,action:"origin",headers:i},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function M(e,t){Se.call(this,{Action:"name/cos:GetBucketOrigin",method:"GET",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"origin"},function(e,n){if(e)return t(e);var r=[];try{r=n.OriginConfiguration.OriginRule||[]}catch(e){}r=Ee.clone(Ee.isArray(r)?r:[r]),t(null,{OriginRule:r,statusCode:n.statusCode,headers:n.headers})})}function L(e,t){Se.call(this,{Action:"name/cos:DeleteBucketOrigin",method:"DELETE",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"origin"},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function H(e,t){var n=Ee.json2xml({BucketLoggingStatus:e.BucketLoggingStatus||""}),r=e.Headers;r["Content-Type"]="application/xml",r["Content-MD5"]=Ee.binaryBase64(Ee.md5(n)),Se.call(this,{Action:"name/cos:PutBucketLogging",method:"PUT",Bucket:e.Bucket,Region:e.Region,body:n,action:"logging",headers:r},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function F(e,t){Se.call(this,{Action:"name/cos:GetBucketLogging",method:"GET",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"logging"},function(e,n){if(e)return t(e);t(null,{BucketLoggingStatus:n.BucketLoggingStatus,statusCode:n.statusCode,headers:n.headers})})}function K(e,t){var n=Ee.clone(e.InventoryConfiguration);if(n.OptionalFields){var r=n.OptionalFields||[];n.OptionalFields={Field:r}}if(n.Destination&&n.Destination.COSBucketDestination&&n.Destination.COSBucketDestination.Encryption){var o=n.Destination.COSBucketDestination.Encryption;Object.keys(o).indexOf("SSECOS")>-1&&(o["SSE-COS"]=o.SSECOS,delete o.SSECOS)}var i=Ee.json2xml({InventoryConfiguration:n}),a=e.Headers;a["Content-Type"]="application/xml",a["Content-MD5"]=Ee.binaryBase64(Ee.md5(i)),Se.call(this,{Action:"name/cos:PutBucketInventory",method:"PUT",Bucket:e.Bucket,Region:e.Region,body:i,action:"inventory",qs:{id:e.Id},headers:a},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function j(e,t){Se.call(this,{Action:"name/cos:GetBucketInventory",method:"GET",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"inventory",qs:{id:e.Id}},function(e,n){if(e)return t(e);var r=n.InventoryConfiguration;if(r&&r.OptionalFields&&r.OptionalFields.Field){var o=r.OptionalFields.Field;Ee.isArray(o)||(o=[o]),r.OptionalFields=o}if(r.Destination&&r.Destination.COSBucketDestination&&r.Destination.COSBucketDestination.Encryption){var i=r.Destination.COSBucketDestination.Encryption;Object.keys(i).indexOf("SSE-COS")>-1&&(i.SSECOS=i["SSE-COS"],delete i["SSE-COS"])}t(null,{InventoryConfiguration:r,statusCode:n.statusCode,headers:n.headers})})}function z(e,t){Se.call(this,{Action:"name/cos:ListBucketInventory",method:"GET",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"inventory",qs:{"continuation-token":e.ContinuationToken}},function(e,n){if(e)return t(e);var r=n.ListInventoryConfigurationResult,o=r.InventoryConfiguration||[];o=Ee.isArray(o)?o:[o],delete r.InventoryConfiguration,Ee.each(o,function(e){if(e&&e.OptionalFields&&e.OptionalFields.Field){var t=e.OptionalFields.Field;Ee.isArray(t)||(t=[t]),e.OptionalFields=t}if(e.Destination&&e.Destination.COSBucketDestination&&e.Destination.COSBucketDestination.Encryption){var n=e.Destination.COSBucketDestination.Encryption;Object.keys(n).indexOf("SSE-COS")>-1&&(n.SSECOS=n["SSE-COS"],delete n["SSE-COS"])}}),r.InventoryConfigurations=o,Ee.extend(r,{statusCode:n.statusCode,headers:n.headers}),t(null,r)})}function G(e,t){Se.call(this,{Action:"name/cos:DeleteBucketInventory",method:"DELETE",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"inventory",qs:{id:e.Id}},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function q(e,t){if(!e.AccelerateConfiguration)return void t(Ee.error(new Error("missing param AccelerateConfiguration")));var n={AccelerateConfiguration:e.AccelerateConfiguration||{}},r=Ee.json2xml(n),o={};o["Content-Type"]="application/xml",o["Content-MD5"]=Ee.binaryBase64(Ee.md5(r)),Se.call(this,{Action:"name/cos:PutBucketAccelerate",method:"PUT",Bucket:e.Bucket,Region:e.Region,body:r,action:"accelerate",headers:o},function(e,n){if(e)return t(e);t(null,{statusCode:n.statusCode,headers:n.headers})})}function V(e,t){Se.call(this,{Action:"name/cos:GetBucketAccelerate",method:"GET",Bucket:e.Bucket,Region:e.Region,action:"accelerate"},function(e,n){e||!n.AccelerateConfiguration&&(n.AccelerateConfiguration={}),t(e,n)})}function Y(e,t){Se.call(this,{Action:"name/cos:HeadObject",method:"HEAD",Bucket:e.Bucket,Region:e.Region,Key:e.Key,VersionId:e.VersionId,headers:e.Headers},function(n,r){if(n){var o=n.statusCode;return e.Headers["If-Modified-Since"]&&o&&304===o?t(null,{NotModified:!0,statusCode:o}):t(n)}r.ETag=Ee.attr(r.headers,"etag",""),t(null,r)})}function X(e,t){var n={};n.prefix=e.Prefix||"",n.delimiter=e.Delimiter,n["key-marker"]=e.KeyMarker,n["version-id-marker"]=e.VersionIdMarker,n["max-keys"]=e.MaxKeys,n["encoding-type"]=e.EncodingType,Se.call(this,{Action:"name/cos:GetBucketObjectVersions",ResourceKey:n.prefix,method:"GET",Bucket:e.Bucket,Region:e.Region,headers:e.Headers,qs:n,action:"versions"},function(e,n){if(e)return t(e);var r=n.ListVersionsResult||{},o=r.DeleteMarker||[];o=Ee.isArray(o)?o:[o];var i=r.Version||[];i=Ee.isArray(i)?i:[i];var a=Ee.clone(r);delete a.DeleteMarker,delete a.Version,Ee.extend(a,{DeleteMarkers:o,Versions:i,statusCode:n.statusCode,headers:n.headers}),t(null,a)})}function W(e,t){var n=e.Query||{},r=Ee.throttleOnProgress.call(this,0,e.onProgress);n["response-content-type"]=e.ResponseContentType,n["response-content-language"]=e.ResponseContentLanguage,n["response-expires"]=e.ResponseExpires,n["response-cache-control"]=e.ResponseCacheControl,n["response-content-disposition"]=e.ResponseContentDisposition,n["response-content-encoding"]=e.ResponseContentEncoding,Se.call(this,{Action:"name/cos:GetObject",method:"GET",Bucket:e.Bucket,Region:e.Region,Key:e.Key,VersionId:e.VersionId,DataType:e.DataType,headers:e.Headers,qs:n,rawBody:!0,onDownloadProgress:r},function(n,o){if(r(null,!0),n){var i=n.statusCode;return e.Headers["If-Modified-Since"]&&i&&304===i?t(null,{NotModified:!0}):t(n)}t(null,{Body:o.body,ETag:Ee.attr(o.headers,"etag",""),statusCode:o.statusCode,headers:o.headers})})}function $(e,t){var n=this,r=e.ContentLength,o=Ee.throttleOnProgress.call(n,r,e.onProgress),i=e.Headers;i["Cache-Control"]||i["cache-control"]||(i["Cache-Control"]=""),i["Content-Type"]||i["content-type"]||(i["Content-Type"]=e.Body&&e.Body.type||"");var a=e.UploadAddMetaMd5||n.options.UploadAddMetaMd5||n.options.UploadCheckContentMd5;Ee.getBodyMd5(a,e.Body,function(a){a&&(n.options.UploadCheckContentMd5&&(i["Content-MD5"]=Ee.binaryBase64(a)),(e.UploadAddMetaMd5||n.options.UploadAddMetaMd5)&&(i["x-cos-meta-md5"]=a)),void 0!==e.ContentLength&&(i["Content-Length"]=e.ContentLength),o(null,!0),Se.call(n,{Action:"name/cos:PutObject",TaskId:e.TaskId,method:"PUT",Bucket:e.Bucket,Region:e.Region,Key:e.Key,headers:e.Headers,qs:e.Query,body:e.Body,onProgress:o},function(i,a){if(i)return o(null,!0),t(i);o({loaded:r,total:r},!0);var s=Ce({ForcePathStyle:n.options.ForcePathStyle,protocol:n.options.Protocol,domain:n.options.Domain,bucket:e.Bucket,region:e.Region,object:e.Key});s=s.substr(s.indexOf("://")+3),a.Location=s,a.ETag=Ee.attr(a.headers,"etag",""),t(null,a)})},e.onHashProgress)}function Q(e,t){Se.call(this,{Action:"name/cos:DeleteObject",method:"DELETE",Bucket:e.Bucket,Region:e.Region,Key:e.Key,headers:e.Headers,VersionId:e.VersionId},function(e,n){if(e){var r=e.statusCode;return r&&404===r?t(null,{BucketNotFound:!0,statusCode:r}):t(e)}t(null,{statusCode:n.statusCode,headers:n.headers})})}function J(e,t){Se.call(this,{Action:"name/cos:GetObjectACL",method:"GET",Bucket:e.Bucket,Region:e.Region,Key:e.Key,headers:e.Headers,action:"acl"},function(e,n){if(e)return t(e);var r=n.AccessControlPolicy||{},o=r.Owner||{},i=r.AccessControlList&&r.AccessControlList.Grant||[];i=Ee.isArray(i)?i:[i];var a=ye(r);delete a.GrantWrite,n.headers&&n.headers["x-cos-acl"]&&(a.ACL=n.headers["x-cos-acl"]),a=Ee.extend(a,{Owner:o,Grants:i,statusCode:n.statusCode,headers:n.headers}),t(null,a)})}function Z(e,t){var n=e.Headers,r="";if(e.AccessControlPolicy){var o=Ee.clone(e.AccessControlPolicy||{}),i=o.Grants||o.Grant;i=Ee.isArray(i)?i:[i],delete o.Grant,delete o.Grants,o.AccessControlList={Grant:i},r=Ee.json2xml({AccessControlPolicy:o}),n["Content-Type"]="application/xml",n["Content-MD5"]=Ee.binaryBase64(Ee.md5(r))}Ee.each(n,function(e,t){0===t.indexOf("x-cos-grant-")&&(n[t]=ve(n[t]))}),Se.call(this,{Action:"name/cos:PutObjectACL",method:"PUT",Bucket:e.Bucket,Region:e.Region,Key:e.Key,action:"acl",headers:n,body:r},function(e,n){if(e)return t(e);t(null,{statusCode:n.statusCode,headers:n.headers})})}function ee(e,t){var n=e.Headers;n.Origin=e.Origin,n["Access-Control-Request-Method"]=e.AccessControlRequestMethod,n["Access-Control-Request-Headers"]=e.AccessControlRequestHeaders,Se.call(this,{Action:"name/cos:OptionsObject",method:"OPTIONS",Bucket:e.Bucket,Region:e.Region,Key:e.Key,headers:n},function(e,n){if(e)return e.statusCode&&403===e.statusCode?t(null,{OptionsForbidden:!0,statusCode:e.statusCode}):t(e);var r=n.headers||{};t(null,{AccessControlAllowOrigin:r["access-control-allow-origin"],AccessControlAllowMethods:r["access-control-allow-methods"],AccessControlAllowHeaders:r["access-control-allow-headers"],AccessControlExposeHeaders:r["access-control-expose-headers"],AccessControlMaxAge:r["access-control-max-age"],statusCode:n.statusCode,headers:n.headers})})}function te(e,t){var n=e.Headers;n["Cache-Control"]||n["cache-control"]||(n["Cache-Control"]="");var r=e.CopySource||"",o=r.match(/^([^.]+-\d+)\.cos(v6)?\.([^.]+)\.[^\/]+\/(.+)$/);if(!o)return void t(Ee.error(new Error("CopySource format error")));var i=o[1],a=o[3],s=decodeURIComponent(o[4]);Se.call(this,{Scope:[{action:"name/cos:GetObject",bucket:i,region:a,prefix:s},{action:"name/cos:PutObject",bucket:e.Bucket,region:e.Region,prefix:e.Key}],method:"PUT",Bucket:e.Bucket,Region:e.Region,Key:e.Key,VersionId:e.VersionId,headers:e.Headers},function(e,n){if(e)return t(e);var r=Ee.clone(n.CopyObjectResult||{});Ee.extend(r,{statusCode:n.statusCode,headers:n.headers}),t(null,r)})}function ne(e,t){var n=e.CopySource||"",r=n.match(/^([^.]+-\d+)\.cos(v6)?\.([^.]+)\.[^\/]+\/(.+)$/);if(!r)return void t(Ee.error(new Error("CopySource format error")));var o=r[1],i=r[3],a=decodeURIComponent(r[4]);Se.call(this,{Scope:[{action:"name/cos:GetObject",bucket:o,region:i,prefix:a},{action:"name/cos:PutObject",bucket:e.Bucket,region:e.Region,prefix:e.Key}],method:"PUT",Bucket:e.Bucket,Region:e.Region,Key:e.Key,VersionId:e.VersionId,qs:{partNumber:e.PartNumber,uploadId:e.UploadId},headers:e.Headers},function(e,n){if(e)return t(e);var r=Ee.clone(n.CopyPartResult||{});Ee.extend(r,{statusCode:n.statusCode,headers:n.headers}),t(null,r)})}function re(e,t){var n=e.Objects||[],r=e.Quiet;n=Ee.isArray(n)?n:[n];var o=Ee.json2xml({Delete:{Object:n,Quiet:r||!1}}),i=e.Headers;i["Content-Type"]="application/xml",i["Content-MD5"]=Ee.binaryBase64(Ee.md5(o));var a=Ee.map(n,function(t){return{action:"name/cos:DeleteObject",bucket:e.Bucket,region:e.Region,prefix:t.Key}});Se.call(this,{Scope:a,method:"POST",Bucket:e.Bucket,Region:e.Region,body:o,action:"delete",headers:i},function(e,n){if(e)return t(e);var r=n.DeleteResult||{},o=r.Deleted||[],i=r.Error||[];o=Ee.isArray(o)?o:[o],i=Ee.isArray(i)?i:[i];var a=Ee.clone(r);Ee.extend(a,{Error:i,Deleted:o,statusCode:n.statusCode,headers:n.headers}),t(null,a)})}function oe(e,t){var n=e.Headers;if(!e.RestoreRequest)return void t(Ee.error(new Error("missing param RestoreRequest")));var r=e.RestoreRequest||{},o=Ee.json2xml({RestoreRequest:r});n["Content-Type"]="application/xml",n["Content-MD5"]=Ee.binaryBase64(Ee.md5(o)),Se.call(this,{Action:"name/cos:RestoreObject",method:"POST",Bucket:e.Bucket,Region:e.Region,Key:e.Key,VersionId:e.VersionId,body:o,action:"restore",headers:n},t)}function ie(e,t){var n=e.Tagging||{},r=n.TagSet||n.Tags||e.Tags||[];r=Ee.clone(Ee.isArray(r)?r:[r]);var o=Ee.json2xml({Tagging:{TagSet:{Tag:r}}}),i=e.Headers;i["Content-Type"]="application/xml",i["Content-MD5"]=Ee.binaryBase64(Ee.md5(o)),Se.call(this,{Action:"name/cos:PutObjectTagging",method:"PUT",Bucket:e.Bucket,Key:e.Key,Region:e.Region,body:o,action:"tagging",headers:i,VersionId:e.VersionId},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function ae(e,t){Se.call(this,{Action:"name/cos:GetObjectTagging",method:"GET",Key:e.Key,Bucket:e.Bucket,Region:e.Region,headers:e.Headers,action:"tagging",VersionId:e.VersionId},function(e,n){if(e)if(404!==e.statusCode||!e.error||"Not Found"!==e.error&&"NoSuchTagSet"!==e.error.Code)t(e);else{var r={Tags:[],statusCode:e.statusCode};e.headers&&(r.headers=e.headers),t(null,r)}else{var o=[];try{o=n.Tagging.TagSet.Tag||[]}catch(e){}o=Ee.clone(Ee.isArray(o)?o:[o]),t(null,{Tags:o,statusCode:n.statusCode,headers:n.headers})}})}function se(e,t){Se.call(this,{Action:"name/cos:DeleteObjectTagging",method:"DELETE",Bucket:e.Bucket,Region:e.Region,Key:e.Key,headers:e.Headers,action:"tagging",VersionId:e.VersionId},function(e,n){return e&&204===e.statusCode?t(null,{statusCode:e.statusCode}):e?t(e):void t(null,{statusCode:n.statusCode,headers:n.headers})})}function ue(e,t){if(!e.SelectType)return t(Ee.error(new Error("missing param SelectType")));var n=e.SelectRequest||{},r=Ee.json2xml({SelectRequest:n}),o=e.Headers;o["Content-Type"]="application/xml",o["Content-MD5"]=Ee.binaryBase64(Ee.md5(r)),Se.call(this,{Action:"name/cos:GetObject",method:"POST",Bucket:e.Bucket,Region:e.Region,Key:e.Key,headers:e.Headers,action:"select",qs:{"select-type":e.SelectType},VersionId:e.VersionId,body:r,DataType:"arraybuffer",rawBody:!0},function(e,n){if(e&&204===e.statusCode)return t(null,{statusCode:e.statusCode});if(e)return t(e);var r=Ee.parseSelectPayload(n.body);t(null,{statusCode:n.statusCode,headers:n.headers,Body:r.body,Payload:r.payload})})}function ce(e,t){var n=this,r=e.Headers;r["Cache-Control"]||r["cache-control"]||(r["Cache-Control"]=""),r["Content-Type"]||r["content-type"]||(r["Content-Type"]=e.Body&&e.Body.type||""),Ee.getBodyMd5(e.Body&&(e.UploadAddMetaMd5||n.options.UploadAddMetaMd5),e.Body,function(r){r&&(e.Headers["x-cos-meta-md5"]=r),Se.call(n,{Action:"name/cos:InitiateMultipartUpload",method:"POST",Bucket:e.Bucket,Region:e.Region,Key:e.Key,action:"uploads",headers:e.Headers,qs:e.Query},function(e,n){return e?t(e):(n=Ee.clone(n||{}))&&n.InitiateMultipartUploadResult?t(null,Ee.extend(n.InitiateMultipartUploadResult,{statusCode:n.statusCode,headers:n.headers})):void t(null,n)})},e.onHashProgress)}function le(e,t){var n=this;Ee.getFileSize("multipartUpload",e,function(){Ee.getBodyMd5(n.options.UploadCheckContentMd5,e.Body,function(r){r&&(e.Headers["Content-MD5"]=Ee.binaryBase64(r)),Se.call(n,{Action:"name/cos:UploadPart",TaskId:e.TaskId,method:"PUT",Bucket:e.Bucket,Region:e.Region,Key:e.Key,qs:{partNumber:e.PartNumber,uploadId:e.UploadId},headers:e.Headers,onProgress:e.onProgress,body:e.Body||null},function(e,n){if(e)return t(e);t(null,{ETag:Ee.attr(n.headers,"etag",""),statusCode:n.statusCode,headers:n.headers})})})})}function de(e,t){for(var n=this,r=e.UploadId,o=e.Parts,i=0,a=o.length;i-1?n.Authorization:"sign="+encodeURIComponent(n.Authorization)),n.SecurityToken&&(o+="&x-cos-security-token="+n.SecurityToken),n.ClientIP&&(o+="&clientIP="+n.ClientIP),n.ClientUA&&(o+="&clientUA="+n.ClientUA),n.Token&&(o+="&token="+n.Token),setTimeout(function(){t(null,{Url:o})})}});return o?r+"?"+o.Authorization+(o.SecurityToken?"&x-cos-security-token="+o.SecurityToken:""):r}function ye(e){var t={GrantFullControl:[],GrantWrite:[],GrantRead:[],GrantReadAcp:[],GrantWriteAcp:[],ACL:""},n={FULL_CONTROL:"GrantFullControl",WRITE:"GrantWrite",READ:"GrantRead",READ_ACP:"GrantReadAcp",WRITE_ACP:"GrantWriteAcp"},r=e&&e.AccessControlList||{},o=r.Grant;o&&(o=Ee.isArray(o)?o:[o]);var i={READ:0,WRITE:0,FULL_CONTROL:0};return o&&o.length&&Ee.each(o,function(r){"qcs::cam::anyone:anyone"===r.Grantee.ID||"http://cam.qcloud.com/groups/global/AllUsers"===r.Grantee.URI?i[r.Permission]=1:r.Grantee.ID!==e.Owner.ID&&t[n[r.Permission]].push('id="'+r.Grantee.ID+'"')}),i.FULL_CONTROL||i.WRITE&&i.READ?t.ACL="public-read-write":i.READ?t.ACL="public-read":t.ACL="private",Ee.each(n,function(e){t[e]=ve(t[e].join(","))}),t}function ve(e){var t,n,r=e.split(","),o={};for(t=0;t-1?"{Region}.myqcloud.com":"cos.{Region}.myqcloud.com",e.ForcePathStyle||(o="{Bucket}."+o)),o=o.replace(/\{\{AppId\}\}/gi,r).replace(/\{\{Bucket\}\}/gi,n).replace(/\{\{Region\}\}/gi,i).replace(/\{\{.*?\}\}/gi,""),o=o.replace(/\{AppId\}/gi,r).replace(/\{BucketName\}/gi,n).replace(/\{Bucket\}/gi,t).replace(/\{Region\}/gi,i).replace(/\{.*?\}/gi,""),/^[a-zA-Z]+:\/\//.test(o)||(o=s+"//"+o),"/"===o.slice(-1)&&(o=o.slice(0,-1));var u=o;return e.ForcePathStyle&&(u+="/"+t),u+="/",a&&(u+=Ee.camSafeUrlEncode(a).replace(/%2F/g,"/")),e.isLocation&&(u=u.replace(/^https?:\/\//,"")),u}function Re(e,n){var r=Ee.clone(e.Headers);Ee.each(r,function(e,t){(""===e||["content-type","cache-control","expires"].indexOf(t.toLowerCase()))&&delete r[t]});var o=!1,i=function(e,t){o||(o=!0,n&&n(e,t))},a=this,s=e.Bucket||"",u=e.Region||"",c=e.Key||"";a.options.ForcePathStyle&&s&&(c=s+"/"+c);var l="/"+c,d={},f=e.Scope;if(!f){var h=e.Action||"",p=e.ResourceKey||e.Key||"";f=e.Scope||[{action:h,bucket:s,region:u,prefix:p}]}var g=Ee.md5(JSON.stringify(f));a._StsCache=a._StsCache||[],function(){var e,t;for(e=a._StsCache.length-1;e>=0;e--){t=a._StsCache[e];var n=Math.round(Ee.getSkewTime(a.options.SystemClockOffset)/1e3)+30;if(t.StartTime&&n=t.ExpiredTime)a._StsCache.splice(e,1);else if(!t.ScopeLimit||t.ScopeLimit&&t.ScopeKey===g){d=t;break}}}();var m=function(){var t=d.StartTime&&d.ExpiredTime?d.StartTime+";"+d.ExpiredTime:"",n=Ee.getAuth({SecretId:d.TmpSecretId,SecretKey:d.TmpSecretKey,Method:e.Method,Pathname:l,Query:e.Query,Headers:r,Expires:e.Expires,UseRawKey:a.options.UseRawKey,SystemClockOffset:a.options.SystemClockOffset,KeyTime:t}),o={Authorization:n,SecurityToken:d.SecurityToken||d.XCosSecurityToken||"",Token:d.Token||"",ClientIP:d.ClientIP||"",ClientUA:d.ClientUA||""};i(null,o)},y=function(e){if(e.Authorization){var n=!1,r=e.Authorization;if(r)if(r.indexOf(" ")>-1)n=!1;else if(r.indexOf("q-sign-algorithm=")>-1&&r.indexOf("q-ak=")>-1&&r.indexOf("q-sign-time=")>-1&&r.indexOf("q-key-time=")>-1&&r.indexOf("q-url-param-list=")>-1)n=!0;else try{r=t.from(r,"base64").toString(),r.indexOf("a=")>-1&&r.indexOf("k=")>-1&&r.indexOf("t=")>-1&&r.indexOf("r=")>-1&&r.indexOf("b=")>-1&&(n=!0)}catch(e){}if(!n)return Ee.error(new Error("getAuthorization callback params format error"))}else{if(!e.TmpSecretId)return Ee.error(new Error('getAuthorization callback params missing "TmpSecretId"'));if(!e.TmpSecretKey)return Ee.error(new Error('getAuthorization callback params missing "TmpSecretKey"'));if(!e.SecurityToken&&!e.XCosSecurityToken)return Ee.error(new Error('getAuthorization callback params missing "SecurityToken"'));if(!e.ExpiredTime)return Ee.error(new Error('getAuthorization callback params missing "ExpiredTime"'));if(e.ExpiredTime&&10!==e.ExpiredTime.toString().length)return Ee.error(new Error('getAuthorization callback params "ExpiredTime" should be 10 digits'));if(e.StartTime&&10!==e.StartTime.toString().length)return Ee.error(new Error('getAuthorization callback params "StartTime" should be 10 StartTime'))}return!1};if(d.ExpiredTime&&d.ExpiredTime-Ee.getSkewTime(a.options.SystemClockOffset)/1e3>60)m();else if(a.options.getAuthorization)a.options.getAuthorization.call(a,{Bucket:s,Region:u,Method:e.Method,Key:c,Pathname:l,Query:e.Query,Headers:r,Scope:f,SystemClockOffset:a.options.SystemClockOffset},function(e){"string"==typeof e&&(e={Authorization:e});var t=y(e);if(t)return i(t);e.Authorization?i(null,e):(d=e||{},d.Scope=f,d.ScopeKey=g,a._StsCache.push(d),m())});else{if(!a.options.getSTS)return function(){var t=Ee.getAuth({SecretId:e.SecretId||a.options.SecretId,SecretKey:e.SecretKey||a.options.SecretKey,Method:e.Method,Pathname:l,Query:e.Query,Headers:r,Expires:e.Expires,UseRawKey:a.options.UseRawKey,SystemClockOffset:a.options.SystemClockOffset}),n={Authorization:t,SecurityToken:a.options.SecurityToken||a.options.XCosSecurityToken};return i(null,n),n}();a.options.getSTS.call(a,{Bucket:s,Region:u},function(e){d=e||{},d.Scope=f,d.ScopeKey=g,d.TmpSecretId||(d.TmpSecretId=d.SecretId),d.TmpSecretKey||(d.TmpSecretKey=d.SecretKey);var t=y(d);if(t)return i(t);a._StsCache.push(d),m()})}return""}function ke(e){var t=!1,n=!1,r=e.headers&&(e.headers.date||e.headers.Date)||e.error&&e.error.ServerTime;try{var o=e.error.Code,i=e.error.Message;("RequestTimeTooSkewed"===o||"AccessDenied"===o&&"Request has expired"===i)&&(n=!0)}catch(e){}if(e)if(n&&r){var a=Date.parse(r);this.options.CorrectClockSkew&&Math.abs(Ee.getSkewTime(this.options.SystemClockOffset)-a)>=3e4&&(console.error("error: Local time is too skewed."),this.options.SystemClockOffset=a-Date.now(),t=!0)}else 5===Math.floor(e.statusCode/100)&&(t=!0);return t}function Se(e,t){var n=this;!e.headers&&(e.headers={}),!e.qs&&(e.qs={}),e.VersionId&&(e.qs.versionId=e.VersionId),e.qs=Ee.clearKey(e.qs),e.headers&&(e.headers=Ee.clearKey(e.headers)),e.qs&&(e.qs=Ee.clearKey(e.qs));var r=Ee.clone(e.qs);e.action&&(r[e.action]="");var o=function(i){var a=n.options.SystemClockOffset;Re.call(n,{Bucket:e.Bucket||"",Region:e.Region||"",Method:e.method,Key:e.Key,Query:r,Headers:e.headers,Action:e.Action,ResourceKey:e.ResourceKey,Scope:e.Scope},function(r,s){if(r)return void t(r);e.AuthData=s,Ae.call(n,e,function(r,s){r&&i<2&&(a!==n.options.SystemClockOffset||ke.call(n,r))?(e.headers&&(delete e.headers.Authorization,delete e.headers.token,delete e.headers.clientIP,delete e.headers.clientUA,delete e.headers["x-cos-security-token"]),o(i+1)):t(r,s)})})};o(1)}function Ae(e,t){var n=this,r=e.TaskId;if(!r||n._isRunningTask(r)){var o=e.Bucket,i=e.Region,a=e.Key,s=e.method||"GET",u=e.url,c=e.body,l=e.rawBody;u=u||Ce({ForcePathStyle:n.options.ForcePathStyle,protocol:n.options.Protocol,domain:n.options.Domain,bucket:o,region:i,object:a}),e.action&&(u=u+"?"+e.action);var d={method:s,url:u,headers:e.headers,qs:e.qs,body:c};if(d.headers.Authorization=e.AuthData.Authorization,e.AuthData.Token&&(d.headers.token=e.AuthData.Token),e.AuthData.ClientIP&&(d.headers.clientIP=e.AuthData.ClientIP),e.AuthData.ClientUA&&(d.headers.clientUA=e.AuthData.ClientUA),e.AuthData.SecurityToken&&(d.headers["x-cos-security-token"]=e.AuthData.SecurityToken),d.headers&&(d.headers=Ee.clearKey(d.headers)),d=Ee.clearKey(d),e.onProgress&&"function"==typeof e.onProgress){var f=c&&(c.size||c.length)||0;d.onProgress=function(t){if(!r||n._isRunningTask(r)){var o=t?t.loaded:0;e.onProgress({loaded:o,total:f})}}}e.onDownloadProgress&&(d.onDownloadProgress=e.onDownloadProgress),e.DataType&&(d.dataType=e.DataType),this.options.Timeout&&(d.timeout=this.options.Timeout),n.options.ForcePathStyle&&(d.pathStyle=n.options.ForcePathStyle),n.emit("before-send",d);var h=(n.options.Request||we)(d,function(e){if("abort"!==e.error){n.emit("after-receive",e);var o,i={statusCode:e.statusCode,statusMessage:e.statusMessage,headers:e.headers},a=e.error,s=e.body,u=function(e,a){if(r&&n.off("inner-kill-task",p),!o){o=!0;var s={};i&&i.statusCode&&(s.statusCode=i.statusCode),i&&i.headers&&(s.headers=i.headers),e?(e=Ee.extend(e||{},s),t(e,null)):(a=Ee.extend(a||{},s),t(null,a)),h=null}};if(a)return u(Ee.error(a));var c=i.statusCode,d=2===Math.floor(c/100);if(l&&d)return u(null,{body:s});var f;try{f=s&&s.indexOf("<")>-1&&s.indexOf(">")>-1&&Ee.xml2json(s)||{}}catch(e){f={}}var g=f&&f.Error;d?u(null,f):g?u(Ee.error(new Error(g.Message),{code:g.Code,error:g})):c?u(Ee.error(new Error(i.statusMessage),{code:""+c})):c&&u(Ee.error(new Error("statusCode error")))}}),p=function(e){e.TaskId===r&&(h&&h.abort&&h.abort(),n.off("inner-kill-task",p))};r&&n.on("inner-kill-task",p)}}function be(e,t,n){Ee.each(["Cors","Acl"],function(r){if(e.slice(-r.length)===r){var o=e.slice(0,-r.length)+r.toUpperCase(),i=Ee.apiWrapper(e,t),a=!1;n[o]=function(){!a&&console.warn("warning: cos."+o+" has been deprecated. Please Use cos."+e+" instead."),a=!0,i.apply(this,arguments)}}})}var we=n(21),Ee=n(0),Te={getService:r,putBucket:o,headBucket:i,getBucket:a,deleteBucket:s,putBucketAcl:u,getBucketAcl:c,putBucketCors:l,getBucketCors:d,deleteBucketCors:f,getBucketLocation:h,getBucketPolicy:g,putBucketPolicy:p,deleteBucketPolicy:m,putBucketTagging:y,getBucketTagging:v,deleteBucketTagging:C,putBucketLifecycle:R,getBucketLifecycle:k,deleteBucketLifecycle:S,putBucketVersioning:A,getBucketVersioning:b,putBucketReplication:w,getBucketReplication:E,deleteBucketReplication:T,putBucketWebsite:B,getBucketWebsite:_,deleteBucketWebsite:x,putBucketReferer:I,getBucketReferer:P,putBucketDomain:O,getBucketDomain:D,deleteBucketDomain:N,putBucketOrigin:U,getBucketOrigin:M,deleteBucketOrigin:L,putBucketLogging:H,getBucketLogging:F,putBucketInventory:K,getBucketInventory:j,listBucketInventory:z,deleteBucketInventory:G,putBucketAccelerate:q,getBucketAccelerate:V,getObject:W,headObject:Y,listObjectVersions:X,putObject:$,deleteObject:Q,getObjectAcl:J,putObjectAcl:Z,optionsObject:ee,putObjectCopy:te,deleteMultipleObject:re,restoreObject:oe,putObjectTagging:ie,getObjectTagging:ae,deleteObjectTagging:se,selectObjectContent:ue,uploadPartCopy:ne,multipartInit:ce,multipartUpload:le,multipartComplete:de,multipartList:fe,multipartListPart:he,multipartAbort:pe,getObjectUrl:me,getAuth:ge};e.exports.init=function(e,t){t.transferToTaskMethod(Te,"putObject"),Ee.each(Te,function(t,n){e.prototype[n]=Ee.apiWrapper(n,t),be(n,t,e.prototype)})}}).call(t,n(17).Buffer)},function(e,t,n){"use strict";(function(e){function r(){return i.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function o(e,t){if(r()=r())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r().toString(16)+" bytes");return 0|e}function g(e){return+e!=e&&(e=0),i.alloc(+e)}function m(e,t){if(i.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var n=e.length;if(0===n)return 0;for(var r=!1;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return G(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return Y(e).length;default:if(r)return G(e).length;t=(""+t).toLowerCase(),r=!0}}function y(e,t,n){var r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if(n>>>=0,t>>>=0,n<=t)return"";for(e||(e="utf8");;)switch(e){case"hex":return P(this,t,n);case"utf8":case"utf-8":return B(this,t,n);case"ascii":return x(this,t,n);case"latin1":case"binary":return I(this,t,n);case"base64":return T(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return O(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function v(e,t,n){var r=e[t];e[t]=e[n],e[n]=r}function C(e,t,n,r,o){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=o?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(o)return-1;n=e.length-1}else if(n<0){if(!o)return-1;n=0}if("string"==typeof t&&(t=i.from(t,r)),i.isBuffer(t))return 0===t.length?-1:R(e,t,n,r,o);if("number"==typeof t)return t&=255,i.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):R(e,[t],n,r,o);throw new TypeError("val must be string, number or Buffer")}function R(e,t,n,r,o){function i(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}var a=1,s=e.length,u=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,n/=2}var c;if(o){var l=-1;for(c=n;cs&&(n=s-u),c=n;c>=0;c--){for(var d=!0,f=0;fo&&(r=o):r=o;var i=t.length;if(i%2!=0)throw new TypeError("Invalid hex string");r>i/2&&(r=i/2);for(var a=0;a239?4:i>223?3:i>191?2:1;if(o+s<=n){var u,c,l,d;switch(s){case 1:i<128&&(a=i);break;case 2:u=e[o+1],128==(192&u)&&(d=(31&i)<<6|63&u)>127&&(a=d);break;case 3:u=e[o+1],c=e[o+2],128==(192&u)&&128==(192&c)&&(d=(15&i)<<12|(63&u)<<6|63&c)>2047&&(d<55296||d>57343)&&(a=d);break;case 4:u=e[o+1],c=e[o+2],l=e[o+3],128==(192&u)&&128==(192&c)&&128==(192&l)&&(d=(15&i)<<18|(63&u)<<12|(63&c)<<6|63&l)>65535&&d<1114112&&(a=d)}}null===a?(a=65533,s=1):a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|1023&a),r.push(a),o+=s}return _(r)}function _(e){var t=e.length;if(t<=Z)return String.fromCharCode.apply(String,e);for(var n="",r=0;rr)&&(n=r);for(var o="",i=t;in)throw new RangeError("Trying to access beyond buffer length")}function N(e,t,n,r,o,a){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||te.length)throw new RangeError("Index out of range")}function U(e,t,n,r){t<0&&(t=65535+t+1);for(var o=0,i=Math.min(e.length-n,2);o>>8*(r?o:1-o)}function M(e,t,n,r){t<0&&(t=4294967295+t+1);for(var o=0,i=Math.min(e.length-n,4);o>>8*(r?o:3-o)&255}function L(e,t,n,r,o,i){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function H(e,t,n,r,o){return o||L(e,t,n,4,3.4028234663852886e38,-3.4028234663852886e38),Q.write(e,t,n,r,23,4),n+4}function F(e,t,n,r,o){return o||L(e,t,n,8,1.7976931348623157e308,-1.7976931348623157e308),Q.write(e,t,n,r,52,8),n+8}function K(e){if(e=j(e).replace(ee,""),e.length<2)return"";for(;e.length%4!=0;)e+="=";return e}function j(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function z(e){return e<16?"0"+e.toString(16):e.toString(16)}function G(e,t){t=t||1/0;for(var n,r=e.length,o=null,i=[],a=0;a55295&&n<57344){if(!o){if(n>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(a+1===r){(t-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(t-=3)>-1&&i.push(239,191,189),o=n;continue}n=65536+(o-55296<<10|n-56320)}else o&&(t-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((t-=1)<0)break;i.push(n)}else if(n<2048){if((t-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function q(e){for(var t=[],n=0;n>8,o=n%256,i.push(o),i.push(r);return i}function Y(e){return $.toByteArray(K(e))}function X(e,t,n,r){for(var o=0;o=t.length||o>=e.length);++o)t[o+n]=e[o];return o}function W(e){return e!==e}/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +var $=n(18),Q=n(19),J=n(20);t.Buffer=i,t.SlowBuffer=g,t.INSPECT_MAX_BYTES=50,i.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}(),t.kMaxLength=r(),i.poolSize=8192,i._augment=function(e){return e.__proto__=i.prototype,e},i.from=function(e,t,n){return a(null,e,t,n)},i.TYPED_ARRAY_SUPPORT&&(i.prototype.__proto__=Uint8Array.prototype,i.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&i[Symbol.species]===i&&Object.defineProperty(i,Symbol.species,{value:null,configurable:!0})),i.alloc=function(e,t,n){return u(null,e,t,n)},i.allocUnsafe=function(e){return c(null,e)},i.allocUnsafeSlow=function(e){return c(null,e)},i.isBuffer=function(e){return!(null==e||!e._isBuffer)},i.compare=function(e,t){if(!i.isBuffer(e)||!i.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var n=e.length,r=t.length,o=0,a=Math.min(n,r);o0&&(e=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(e+=" ... ")),""},i.prototype.compare=function(e,t,n,r,o){if(!i.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===o&&(o=this.length),t<0||n>e.length||r<0||o>this.length)throw new RangeError("out of range index");if(r>=o&&t>=n)return 0;if(r>=o)return-1;if(t>=n)return 1;if(t>>>=0,n>>>=0,r>>>=0,o>>>=0,this===e)return 0;for(var a=o-r,s=n-t,u=Math.min(a,s),c=this.slice(r,o),l=e.slice(t,n),d=0;do)&&(n=o),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var i=!1;;)switch(r){case"hex":return k(this,e,t,n);case"utf8":case"utf-8":return S(this,e,t,n);case"ascii":return A(this,e,t,n);case"latin1":case"binary":return b(this,e,t,n);case"base64":return w(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Z=4096;i.prototype.slice=function(e,t){var n=this.length;e=~~e,t=void 0===t?n:~~t,e<0?(e+=n)<0&&(e=0):e>n&&(e=n),t<0?(t+=n)<0&&(t=0):t>n&&(t=n),t0&&(o*=256);)r+=this[e+--t]*o;return r},i.prototype.readUInt8=function(e,t){return t||D(e,1,this.length),this[e]},i.prototype.readUInt16LE=function(e,t){return t||D(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUInt16BE=function(e,t){return t||D(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUInt32LE=function(e,t){return t||D(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},i.prototype.readUInt32BE=function(e,t){return t||D(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},i.prototype.readIntLE=function(e,t,n){e|=0,t|=0,n||D(e,t,this.length);for(var r=this[e],o=1,i=0;++i=o&&(r-=Math.pow(2,8*t)),r},i.prototype.readIntBE=function(e,t,n){e|=0,t|=0,n||D(e,t,this.length);for(var r=t,o=1,i=this[e+--r];r>0&&(o*=256);)i+=this[e+--r]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},i.prototype.readInt8=function(e,t){return t||D(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},i.prototype.readInt16LE=function(e,t){t||D(e,2,this.length);var n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt16BE=function(e,t){t||D(e,2,this.length);var n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt32LE=function(e,t){return t||D(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},i.prototype.readInt32BE=function(e,t){return t||D(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},i.prototype.readFloatLE=function(e,t){return t||D(e,4,this.length),Q.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return t||D(e,4,this.length),Q.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return t||D(e,8,this.length),Q.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return t||D(e,8,this.length),Q.read(this,e,!1,52,8)},i.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t|=0,n|=0,!r){N(this,e,t,n,Math.pow(2,8*n)-1,0)}var o=1,i=0;for(this[t]=255&e;++i=0&&(i*=256);)this[t+o]=e/i&255;return t+n},i.prototype.writeUInt8=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,1,255,0),i.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},i.prototype.writeUInt16LE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,2,65535,0),i.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):U(this,e,t,!0),t+2},i.prototype.writeUInt16BE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,2,65535,0),i.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):U(this,e,t,!1),t+2},i.prototype.writeUInt32LE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,4,4294967295,0),i.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):M(this,e,t,!0),t+4},i.prototype.writeUInt32BE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,4,4294967295,0),i.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):M(this,e,t,!1),t+4},i.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t|=0,!r){var o=Math.pow(2,8*n-1);N(this,e,t,n,o-1,-o)}var i=0,a=1,s=0;for(this[t]=255&e;++i>0)-s&255;return t+n},i.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t|=0,!r){var o=Math.pow(2,8*n-1);N(this,e,t,n,o-1,-o)}var i=n-1,a=1,s=0;for(this[t+i]=255&e;--i>=0&&(a*=256);)e<0&&0===s&&0!==this[t+i+1]&&(s=1),this[t+i]=(e/a>>0)-s&255;return t+n},i.prototype.writeInt8=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,1,127,-128),i.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},i.prototype.writeInt16LE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,2,32767,-32768),i.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):U(this,e,t,!0),t+2},i.prototype.writeInt16BE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,2,32767,-32768),i.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):U(this,e,t,!1),t+2},i.prototype.writeInt32LE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,4,2147483647,-2147483648),i.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):M(this,e,t,!0),t+4},i.prototype.writeInt32BE=function(e,t,n){return e=+e,t|=0,n||N(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),i.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):M(this,e,t,!1),t+4},i.prototype.writeFloatLE=function(e,t,n){return H(this,e,t,!0,n)},i.prototype.writeFloatBE=function(e,t,n){return H(this,e,t,!1,n)},i.prototype.writeDoubleLE=function(e,t,n){return F(this,e,t,!0,n)},i.prototype.writeDoubleBE=function(e,t,n){return F(this,e,t,!1,n)},i.prototype.copy=function(e,t,n,r){if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t=0;--o)e[o+t]=this[o+n];else if(a<1e3||!i.TYPED_ARRAY_SUPPORT)for(o=0;o>>=0,n=void 0===n?this.length:n>>>0,e||(e=0);var a;if("number"==typeof e)for(a=t;a0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function o(e){var t=r(e),n=t[0],o=t[1];return 3*(n+o)/4-o}function i(e,t,n){return 3*(t+n)/4-n}function a(e){var t,n,o=r(e),a=o[0],s=o[1],u=new f(i(e,a,s)),c=0,l=s>0?a-4:a;for(n=0;n>16&255,u[c++]=t>>8&255,u[c++]=255&t;return 2===s&&(t=d[e.charCodeAt(n)]<<2|d[e.charCodeAt(n+1)]>>4,u[c++]=255&t),1===s&&(t=d[e.charCodeAt(n)]<<10|d[e.charCodeAt(n+1)]<<4|d[e.charCodeAt(n+2)]>>2,u[c++]=t>>8&255,u[c++]=255&t),u}function s(e){return l[e>>18&63]+l[e>>12&63]+l[e>>6&63]+l[63&e]}function u(e,t,n){for(var r,o=[],i=t;ia?a:i+16383));return 1===r?(t=e[n-1],o.push(l[t>>2]+l[t<<4&63]+"==")):2===r&&(t=(e[n-2]<<8)+e[n-1],o.push(l[t>>10]+l[t>>4&63]+l[t<<2&63]+"=")),o.join("")}t.byteLength=o,t.toByteArray=a,t.fromByteArray=c;for(var l=[],d=[],f="undefined"!=typeof Uint8Array?Uint8Array:Array,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p=0,g=h.length;p */ +t.read=function(e,t,n,r,o){var i,a,s=8*o-r-1,u=(1<>1,l=-7,d=n?o-1:0,f=n?-1:1,h=e[t+d];for(d+=f,i=h&(1<<-l)-1,h>>=-l,l+=s;l>0;i=256*i+e[t+d],d+=f,l-=8);for(a=i&(1<<-l)-1,i>>=-l,l+=r;l>0;a=256*a+e[t+d],d+=f,l-=8);if(0===i)i=1-c;else{if(i===u)return a?NaN:1/0*(h?-1:1);a+=Math.pow(2,r),i-=c}return(h?-1:1)*a*Math.pow(2,i-r)},t.write=function(e,t,n,r,o,i){var a,s,u,c=8*i-o-1,l=(1<>1,f=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=r?0:i-1,p=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),t+=a+d>=1?f/u:f*Math.pow(2,1-d),t*u>=2&&(a++,u/=2),a+d>=l?(s=0,a=l):a+d>=1?(s=(t*u-1)*Math.pow(2,o),a+=d):(s=t*Math.pow(2,d-1)*Math.pow(2,o),a=0));o>=8;e[n+h]=255&s,h+=p,s/=256,o-=8);for(a=a<0;e[n+h]=255&a,h+=p,a/=256,c-=8);e[n+h-p]|=128*g}},function(e,t){var n={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},function(e,t){var n=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}},r=function(e,t,r,o){return t=t||"&",r=r||"=",null===e&&(e=void 0),"object"==typeof e?Object.keys(e).map(function(o){var i=encodeURIComponent(n(o))+r;return Array.isArray(e[o])?e[o].map(function(e){return i+encodeURIComponent(n(e))}).join(t):i+encodeURIComponent(n(e[o]))}).filter(Boolean).join(t):o?encodeURIComponent(n(o))+r+encodeURIComponent(n(e)):""},o=function(e,t,n){var r={};return t.getAllResponseHeaders().trim().split("\n").forEach(function(e){if(e){var t=e.indexOf(":"),n=e.substr(0,t).trim().toLowerCase(),o=e.substr(t+1).trim();r[n]=o}}),{error:e,statusCode:t.status,statusMessage:t.statusText,headers:r,body:n}},i=function(e,t){return t||"text"!==t?e.response:e.responseText},a=function(e,t){var n=(e.method||"GET").toUpperCase(),a=e.url;if(e.qs){var s=r(e.qs);s&&(a+=(-1===a.indexOf("?")?"?":"&")+s)}var u=new XMLHttpRequest;u.open(n,a,!0),u.responseType=e.dataType||"text";var c=e.headers;if(c)for(var l in c)c.hasOwnProperty(l)&&"content-length"!==l.toLowerCase()&&"user-agent"!==l.toLowerCase()&&"origin"!==l.toLowerCase()&&"host"!==l.toLowerCase()&&u.setRequestHeader(l,c[l]);return e.onProgress&&u.upload&&(u.upload.onprogress=e.onProgress),e.onDownloadProgress&&(u.onprogress=e.onDownloadProgress),u.onload=function(){t(o(null,u,i(u,e.dataType)))},u.onerror=function(n){var r=i(u,e.dataType);if(r)t(o(null,u,r));else{var a=u.statusText;a||0!==u.status||(a=new Error("CORS blocked or network error")),t(o(a,u,r))}},u.send(e.body||""),u};e.exports=a},function(e,t,n){function r(e,t){var n,r,i=this,a=new y,u=e.TaskId,l=e.Bucket,d=e.Region,f=e.Key,h=e.Body,p=e.ChunkSize||e.SliceSize||i.options.ChunkSize,m=e.AsyncLimit,C=e.StorageClass,R=e.ServerSideEncryption,k=e.onHashProgress;a.on("error",function(e){if(i._isRunningTask(u))return t(e)}),a.on("upload_complete",function(e){t(null,e)}),a.on("upload_slice_complete",function(t){var o={};v.each(e.Headers,function(e,t){var n=t.toLowerCase();0!==n.indexOf("x-cos-meta-")&&"pic-operations"!==n||(o[t]=e)}),c.call(i,{Bucket:l,Region:d,Key:f,UploadId:t.UploadId,SliceList:t.SliceList,Headers:o},function(e,o){if(i._isRunningTask(u)){if(g.removeUsing(t.UploadId),e)return r(null,!0),a.emit("error",e);g.removeUploadId.call(i,t.UploadId),r({loaded:n,total:n},!0),a.emit("upload_complete",o)}})}),a.on("get_upload_data_finish",function(t){var o=g.getFileId(h,e.ChunkSize,l,f);o&&g.saveUploadId.call(i,o,t.UploadId,i.options.UploadIdCacheLimit),g.setUsing(t.UploadId),r(null,!0),s.call(i,{TaskId:u,Bucket:l,Region:d,Key:f,Body:h,FileSize:n,SliceSize:p,AsyncLimit:m,ServerSideEncryption:R,UploadData:t,onProgress:r},function(e,t){if(i._isRunningTask(u))return e?(r(null,!0),a.emit("error",e)):void a.emit("upload_slice_complete",t)})}),a.on("get_file_size_finish",function(){if(r=v.throttleOnProgress.call(i,n,e.onProgress),e.UploadData.UploadId)a.emit("get_upload_data_finish",e.UploadData);else{var t=v.extend({TaskId:u,Bucket:l,Region:d,Key:f,Headers:e.Headers,StorageClass:C,Body:h,FileSize:n,SliceSize:p,onHashProgress:k},e);o.call(i,t,function(t,n){if(i._isRunningTask(u)){if(t)return a.emit("error",t);e.UploadData.UploadId=n.UploadId,e.UploadData.PartList=n.PartList,a.emit("get_upload_data_finish",e.UploadData)}})}}),n=e.ContentLength,delete e.ContentLength,!e.Headers&&(e.Headers={}),v.each(e.Headers,function(t,n){"content-length"===n.toLowerCase()&&delete e.Headers[n]}),function(){for(var t=[1,2,4,8,16,32,64,128,256,512,1024,2048,4096,5120],r=1048576,o=0;oh)return t(null,!1);if(n>1){if(Math.max(e[0].Size,e[1].Size)!==f)return t(null,!1)}var r=function(o){if(o=u.length)return void A.emit("has_and_check_upload_id",t);var i=u[e];return v.isInArray(t,i)?g.using[i]?void l(e+1):void a.call(c,{Bucket:r,Region:o,Key:s,UploadId:i},function(t,r){c._isRunningTask(n)&&(t?(g.removeUploadId.call(c,i),l(e+1)):A.emit("upload_id_available",{UploadId:i,PartList:r.PartList}))}):(g.removeUploadId.call(c,i),void l(e+1))};l(0)}),A.on("get_remote_upload_id_list",function(){i.call(c,{Bucket:r,Region:o,Key:s},function(t,o){if(c._isRunningTask(n)){if(t)return A.emit("error",t);var i=v.filter(o.UploadList,function(e){return e.Key===s&&(!u||e.StorageClass.toUpperCase()===u.toUpperCase())}).reverse().map(function(e){return e.UploadId||e.UploadID});if(i.length)A.emit("seek_local_avail_upload_id",i);else{var a,l=g.getFileId(e.Body,e.ChunkSize,r,s);l&&(a=g.getUploadIdList.call(c,l))&&v.each(a,function(e){g.removeUploadId.call(c,e)}),A.emit("no_available_upload_id")}}})}),A.emit("get_remote_upload_id_list")}function i(e,t){var n=this,r=[],o={Bucket:e.Bucket,Region:e.Region,Prefix:e.Key},i=function(){n.multipartList(o,function(e,n){if(e)return t(e);r.push.apply(r,n.Upload||[]),"true"===n.IsTruncated?(o.KeyMarker=n.NextKeyMarker,o.UploadIdMarker=n.NextUploadIdMarker,i()):t(null,{UploadList:r})})};i()}function a(e,t){var n=this,r=[],o={Bucket:e.Bucket,Region:e.Region,Key:e.Key,UploadId:e.UploadId},i=function(){n.multipartListPart(o,function(e,n){if(e)return t(e);r.push.apply(r,n.Part||[]),"true"===n.IsTruncated?(o.PartNumberMarker=n.NextPartNumberMarker,i()):t(null,{PartList:r})})};i()}function s(e,t){var n=this,r=e.TaskId,o=e.Bucket,i=e.Region,a=e.Key,s=e.UploadData,c=e.FileSize,l=e.SliceSize,d=Math.min(e.AsyncLimit||n.options.ChunkParallelLimit||1,256),f=e.Body,h=Math.ceil(c/l),p=0,g=e.ServerSideEncryption,y=v.filter(s.PartList,function(e){return e.Uploaded&&(p+=e.PartNumber>=h?c%l||l:l),!e.Uploaded}),C=e.onProgress;m.eachLimit(y,d,function(e,t){if(n._isRunningTask(r)){var d=e.PartNumber,h=Math.min(c,e.PartNumber*l)-(e.PartNumber-1)*l,m=0;u.call(n,{TaskId:r,Bucket:o,Region:i,Key:a,SliceSize:l,FileSize:c,PartNumber:d,ServerSideEncryption:g,Body:f,UploadData:s,onProgress:function(e){p+=e.loaded-m,m=e.loaded,C({loaded:p,total:c})}},function(o,i){n._isRunningTask(r)&&(o||i.ETag||(o='get ETag error, please add "ETag" to CORS ExposeHeader setting.'),o?p-=m:(p+=h-m,e.ETag=i.ETag),C({loaded:p,total:c}),t(o||null,i))})}},function(e){if(n._isRunningTask(r))return e?t(e):void t(null,{UploadId:s.UploadId,SliceList:s.PartList})})}function u(e,t){var n=this,r=e.TaskId,o=e.Bucket,i=e.Region,a=e.Key,s=e.FileSize,u=e.Body,c=1*e.PartNumber,l=e.SliceSize,d=e.ServerSideEncryption,f=e.UploadData,h=n.options.ChunkRetryTimes+1,p=l*(c-1),g=l,y=p+l;y>s&&(y=s,g=y-p);var C=f.PartList[c-1];m.retry(h,function(t){n._isRunningTask(r)&&v.fileSlice(u,p,y,!0,function(s){n.multipartUpload({TaskId:r,Bucket:o,Region:i,Key:a,ContentLength:g,PartNumber:c,UploadId:f.UploadId,ServerSideEncryption:d,Body:s,onProgress:e.onProgress},function(e,o){if(n._isRunningTask(r))return e?t(e):(C.Uploaded=!0,t(null,o))})})},function(e,o){if(n._isRunningTask(r))return t(e,o)})}function c(e,t){var n=e.Bucket,r=e.Region,o=e.Key,i=e.UploadId,a=e.SliceList,s=this,u=this.options.ChunkRetryTimes+1,c=e.Headers,l=a.map(function(e){return{PartNumber:e.PartNumber,ETag:e.ETag}});m.retry(u,function(e){s.multipartComplete({Bucket:n,Region:r,Key:o,UploadId:i,Parts:l,Headers:c},e)},function(e,n){t(e,n)})}function l(e,t){var n=e.Bucket,r=e.Region,o=e.Key,a=e.UploadId,s=e.Level||"task",u=e.AsyncLimit,c=this,l=new y;if(l.on("error",function(e){return t(e)}),l.on("get_abort_array",function(i){d.call(c,{Bucket:n,Region:r,Key:o,Headers:e.Headers,AsyncLimit:u,AbortArray:i},t)}),"bucket"===s)i.call(c,{Bucket:n,Region:r},function(e,n){if(e)return t(e);l.emit("get_abort_array",n.UploadList||[])});else if("file"===s){if(!o)return t(v.error(new Error("abort_upload_task_no_key")));i.call(c,{Bucket:n,Region:r,Key:o},function(e,n){if(e)return t(e);l.emit("get_abort_array",n.UploadList||[])})}else{if("task"!==s)return t(v.error(new Error("abort_unknown_level")));if(!a)return t(v.error(new Error("abort_upload_task_no_id")));if(!o)return t(v.error(new Error("abort_upload_task_no_key")));l.emit("get_abort_array",[{Key:o,UploadId:a}])}}function d(e,t){var n=e.Bucket,r=e.Region,o=e.Key,i=e.AbortArray,a=e.AsyncLimit||1,s=this,u=0,c=new Array(i.length);m.eachLimit(i,a,function(t,i){var a=u;if(o&&o!==t.Key)return c[a]={error:{KeyNotMatch:!0}},void i(null);var l=t.UploadId||t.UploadID;s.multipartAbort({Bucket:n,Region:r,Key:t.Key,Headers:e.Headers,UploadId:l},function(e){var o={Bucket:n,Region:r,Key:t.Key,UploadId:l};c[a]={error:e,task:o},i(null)}),u++},function(e){if(e)return t(e);for(var n=[],r=[],o=0,i=c.length;or?"sliceUploadFile":"putObject";d.push({api:C,params:e,callback:y})}()}),n._addTasks(d)}function h(e,t){var n=new y,r=this,o=e.Bucket,i=e.Region,a=e.Key,s=e.CopySource,u=s.match(/^([^.]+-\d+)\.cos(v6)?\.([^.]+)\.[^\/]+\/(.+)$/);if(!u)return void t(v.error(new Error("CopySource format error")));var c=u[1],l=u[3],d=decodeURIComponent(u[4]),f=void 0===e.CopySliceSize?r.options.CopySliceSize:e.CopySliceSize;f=Math.max(0,f);var h,g,C=e.CopyChunkSize||this.options.CopyChunkSize,R=this.options.CopyChunkParallelLimit,k=0;n.on("copy_slice_complete",function(n){var s={};v.each(e.Headers,function(e,t){0===t.toLowerCase().indexOf("x-cos-meta-")&&(s[t]=e)});var u=v.map(n.PartList,function(e){return{PartNumber:e.PartNumber,ETag:e.ETag}});r.multipartComplete({Bucket:o,Region:i,Key:a,UploadId:n.UploadId,Parts:u},function(e,n){if(e)return g(null,!0),t(e);g({loaded:h,total:h},!0),t(null,n)})}),n.on("get_copy_data_finish",function(e){m.eachLimit(e.PartList,R,function(t,n){var u=t.PartNumber,c=t.CopySourceRange,l=t.end-t.start;p.call(r,{Bucket:o,Region:i,Key:a,CopySource:s,UploadId:e.UploadId,PartNumber:u,CopySourceRange:c},function(e,r){if(e)return n(e);k+=l,g({loaded:k,total:h}),t.ETag=r.ETag,n(e||null,r)})},function(r){if(r)return g(null,!0),t(r);n.emit("copy_slice_complete",e)})}),n.on("get_file_size_finish",function(s){!function(){for(var t=[1,2,4,8,16,32,64,128,256,512,1024,2048,4096,5120],n=1048576,o=0;o"x-cos-meta-".length&&(s[t]=e)}),n.emit("get_file_size_finish",s)}})}function p(e,t){var n=e.TaskId,r=e.Bucket,o=e.Region,i=e.Key,a=e.CopySource,s=e.UploadId,u=1*e.PartNumber,c=e.CopySourceRange,l=this.options.ChunkRetryTimes+1,d=this;m.retry(l,function(e){d.uploadPartCopy({TaskId:n,Bucket:r,Region:o,Key:i,CopySource:a,UploadId:s,PartNumber:u,CopySourceRange:c},function(t,n){e(t||null,n)})},function(e,n){return t(e,n)})}var g=n(4),m=n(23),y=n(3).EventProxy,v=n(0),C={sliceUploadFile:r,abortUploadTask:l,uploadFiles:f,sliceCopyFile:h};e.exports.init=function(e,t){t.transferToTaskMethod(C,"sliceUploadFile"),v.each(C,function(t,n){e.prototype[n]=v.apiWrapper(n,t)})}},function(e,t){var n=function(e,t,n,r){if(r=r||function(){},!e.length||t<=0)return r();var o=0,i=0,a=0;!function s(){if(o>=e.length)return r();for(;a=e.length?r():s())})}()},r=function(e,t,n){var r=function(o){t(function(t,i){t&&o= SliceSize ? 'sliceUploadFile' : 'putObject'; + var api = FileSize > SliceSize ? 'sliceUploadFile' : 'putObject'; taskList.push({ api: api, params: fileParams, @@ -895,7 +870,7 @@ function sliceCopyFile(params, callback) { var CopySource = params.CopySource; var m = CopySource.match(/^([^.]+-\d+)\.cos(v6)?\.([^.]+)\.[^/]+\/(.+)$/); if (!m) { - callback({error: 'CopySource format error'}); + callback(util.error(new Error('CopySource format error'))); return; } @@ -913,7 +888,8 @@ function sliceCopyFile(params, callback) { var onProgress; // 分片复制完成,开始 multipartComplete 操作 - ep.on('copy_slice_complete', function (UploadData) {var metaHeaders = {}; + ep.on('copy_slice_complete', function (UploadData) { + var metaHeaders = {}; util.each(params.Headers, function (val, k) { if (k.toLowerCase().indexOf('x-cos-meta-') === 0) metaHeaders[k] = val; }); @@ -944,7 +920,6 @@ function sliceCopyFile(params, callback) { var PartNumber = SliceItem.PartNumber; var CopySourceRange = SliceItem.CopySourceRange; var currentSize = SliceItem.end - SliceItem.start; - var preAddSize = 0; copySliceItem.call(self, { Bucket: Bucket, @@ -954,18 +929,10 @@ function sliceCopyFile(params, callback) { UploadId: UploadData.UploadId, PartNumber: PartNumber, CopySourceRange: CopySourceRange, - onProgress: function (data) { - FinishSize += data.loaded - preAddSize; - preAddSize = data.loaded; - onProgress({loaded: FinishSize, total: FileSize}); - } },function (err,data) { - if (err) { - return asyncCallback(err); - } + if (err) return asyncCallback(err); + FinishSize += currentSize; onProgress({loaded: FinishSize, total: FileSize}); - - FinishSize += currentSize - preAddSize; SliceItem.ETag = data.ETag; asyncCallback(err || null, data); }); @@ -1021,7 +988,7 @@ function sliceCopyFile(params, callback) { if (SourceHeaders['x-cos-storage-class'] === 'ARCHIVE' || SourceHeaders['x-cos-storage-class'] === 'DEEP_ARCHIVE') { var restoreHeader = SourceHeaders['x-cos-restore']; if (!restoreHeader || restoreHeader === 'ongoing-request="true"') { - callback({ error: 'Unrestored archive object is not allowed to be copied' }); + callback(util.error(new Error('Unrestored archive object is not allowed to be copied'))); return; } } @@ -1041,9 +1008,7 @@ function sliceCopyFile(params, callback) { Key: Key, Headers: TargetHeader, },function (err,data) { - if (err) { - return callback(err); - } + if (err) return callback(err); params.UploadId = data.UploadId; ep.emit('get_copy_data_finish', params); }); @@ -1057,7 +1022,7 @@ function sliceCopyFile(params, callback) { },function(err, data) { if (err) { if (err.statusCode && err.statusCode === 404) { - callback({ErrorStatus: SourceKey + ' Not Exist'}); + callback(util.error(err, {ErrorStatus: SourceKey + ' Not Exist'})); } else { callback(err); } @@ -1066,7 +1031,7 @@ function sliceCopyFile(params, callback) { FileSize = params.FileSize = data.headers['content-length']; if (FileSize === undefined || !FileSize) { - callback({error: 'get Content-Length error, please add "Content-Length" to CORS ExposeHeader setting.'}); + callback(util.error(new Error('get Content-Length error, please add "Content-Length" to CORS ExposeHeader setting.'))); return; } @@ -1130,7 +1095,6 @@ function copySliceItem(params, callback) { UploadId: UploadId, PartNumber:PartNumber, CopySourceRange:CopySourceRange, - onProgress:params.onProgress, },function (err,data) { tryCallback(err || null, data); }) diff --git a/src/base.js b/src/base.js index 3cae7eb..09f08c7 100644 --- a/src/base.js +++ b/src/base.js @@ -123,9 +123,7 @@ function headBucket(params, callback) { Region: params.Region, headers: params.Headers, method: 'HEAD', - }, function (err, data) { - callback(err, data); - }); + }, callback); } /** @@ -451,15 +449,18 @@ function getBucketLocation(params, callback) { Region: params.Region, headers: params.Headers, action: 'location', - }, function (err, data) { - if (err) return callback(err); - callback(null, data); - }); + }, callback); } function putBucketPolicy(params, callback) { - var PolicyStr = params['Policy']; - if (typeof PolicyStr !== 'string') PolicyStr = JSON.stringify(PolicyStr); + var Policy = params['Policy']; + try { + if (typeof Policy === 'string') Policy = JSON.parse(Policy); + } catch (e) { + } + if (!Policy || typeof Policy === 'string') return callback(util.error(new Error('Policy format error'))); + var PolicyStr = JSON.stringify(Policy); + if (!Policy.version) Policy.version = '2.0'; var headers = params.Headers; headers['Content-Type'] = 'application/json'; @@ -507,13 +508,13 @@ function getBucketPolicy(params, callback) { }, function (err, data) { if (err) { if (err.statusCode && err.statusCode === 403) { - return callback({ErrorStatus: 'Access Denied'}); + return callback(util.error(err, {ErrorStatus: 'Access Denied'})); } if (err.statusCode && err.statusCode === 405) { - return callback({ErrorStatus: 'Method Not Allowed'}); + return callback(util.error(err, {ErrorStatus: 'Method Not Allowed'})); } if (err.statusCode && err.statusCode === 404) { - return callback({ErrorStatus: 'Policy Not Found'}); + return callback(util.error(err, {ErrorStatus: 'Policy Not Found'})); } return callback(err); } @@ -770,7 +771,7 @@ function deleteBucketLifecycle(params, callback) { function putBucketVersioning(params, callback) { if (!params['VersioningConfiguration']) { - callback({error: 'missing param VersioningConfiguration'}); + callback(util.error(new Error('missing param VersioningConfiguration'))); return; } var VersioningConfiguration = params['VersioningConfiguration'] || {}; @@ -874,7 +875,7 @@ function getBucketReplication(params, callback) { !data.ReplicationConfiguration && (data.ReplicationConfiguration = {}); } if (data.ReplicationConfiguration.Rule) { - data.ReplicationConfiguration.Rules = data.ReplicationConfiguration.Rule; + data.ReplicationConfiguration.Rules = util.makeArray(data.ReplicationConfiguration.Rule); delete data.ReplicationConfiguration.Rule; } callback(err, data); @@ -919,7 +920,7 @@ function deleteBucketReplication(params, callback) { function putBucketWebsite(params, callback) { if (!params['WebsiteConfiguration']) { - callback({ error: 'missing param WebsiteConfiguration' }); + callback(util.error(new Error('missing param WebsiteConfiguration'))); return; } @@ -1053,7 +1054,7 @@ function deleteBucketWebsite(params, callback) { function putBucketReferer(params, callback) { if (!params['RefererConfiguration']) { - callback({ error: 'missing param RefererConfiguration' }); + callback(util.error(new Error('missing param RefererConfiguration'))); return; } @@ -1627,7 +1628,7 @@ function deleteBucketInventory(params, callback) { function putBucketAccelerate(params, callback) { if (!params['AccelerateConfiguration']) { - callback({error: 'missing param AccelerateConfiguration'}); + callback(util.error(new Error('missing param AccelerateConfiguration'))); return; } @@ -1831,7 +1832,6 @@ function getObject(params, callback) { * @param {String} params.ContentType RFC 2616 中定义的内容类型(MIME),将作为 Object 元数据保存,非必须 * @param {String} params.Expect 当使用 Expect: 100-continue 时,在收到服务端确认后,才会发送请求内容,非必须 * @param {String} params.Expires RFC 2616 中定义的过期时间,将作为 Object 元数据保存,非必须 - * @param {String} params.ContentSha1 RFC 3174 中定义的 160-bit 内容 SHA-1 算法校验,非必须 * @param {String} params.ACL 允许用户自定义文件权限,有效值:private | public-read,非必须 * @param {String} params.GrantRead 赋予被授权者读取对象的权限,格式:id="[OwnerUin]",可使用半角逗号(,)分隔多组被授权者,非必须 * @param {String} params.GrantReadAcp 赋予被授权者读取对象的访问控制列表(ACL)的权限,格式:id="[OwnerUin]",可使用半角逗号(,)分隔多组被授权者,非必须 @@ -1919,9 +1919,7 @@ function deleteObject(params, callback) { }, function (err, data) { if (err) { var statusCode = err.statusCode; - if (statusCode && statusCode === 204) { - return callback(null, {statusCode: statusCode}); - } else if (statusCode && statusCode === 404) { + if (statusCode && statusCode === 404) { return callback(null, {BucketNotFound: true, statusCode: statusCode,}); } else { return callback(err); @@ -1962,6 +1960,7 @@ function getObjectAcl(params, callback) { var Grant = AccessControlPolicy.AccessControlList && AccessControlPolicy.AccessControlList.Grant || []; Grant = util.isArray(Grant) ? Grant : [Grant]; var result = decodeAcl(AccessControlPolicy); + delete result.GrantWrite; if (data.headers && data.headers['x-cos-acl']) { result.ACL = data.headers['x-cos-acl']; } @@ -2106,12 +2105,12 @@ function putObjectCopy(params, callback) { // 特殊处理 Cache-Control var headers = params.Headers; - if (!headers['Cache-Control'] && !!headers['cache-control']) headers['Cache-Control'] = ''; + if (!headers['Cache-Control'] && !headers['cache-control']) headers['Cache-Control'] = ''; var CopySource = params.CopySource || ''; var m = CopySource.match(/^([^.]+-\d+)\.cos(v6)?\.([^.]+)\.[^/]+\/(.+)$/); if (!m) { - callback({error: 'CopySource format error'}); + callback(util.error(new Error('CopySource format error'))); return; } @@ -2120,7 +2119,6 @@ function putObjectCopy(params, callback) { var SourceKey = decodeURIComponent(m[4]); submitRequest.call(this, { - Interface: 'PutObjectCopy', Scope: [{ action: 'name/cos:GetObject', bucket: SourceBucket, @@ -2154,7 +2152,7 @@ function uploadPartCopy(params, callback) { var CopySource = params.CopySource || ''; var m = CopySource.match(/^([^.]+-\d+)\.cos(v6)?\.([^.]+)\.[^/]+\/(.+)$/); if (!m) { - callback({error: 'CopySource format error'}); + callback(util.error(new Error('CopySource format error'))); return; } @@ -2163,7 +2161,6 @@ function uploadPartCopy(params, callback) { var SourceKey = decodeURIComponent(m[4]); submitRequest.call(this, { - Interface: 'UploadPartCopy', Scope: [{ action: 'name/cos:GetObject', bucket: SourceBucket, @@ -2217,7 +2214,6 @@ function deleteMultipleObject(params, callback) { }); submitRequest.call(this, { - Interface: 'DeleteMultipleObjects', Scope: Scope, method: 'POST', Bucket: params.Bucket, @@ -2248,7 +2244,7 @@ function deleteMultipleObject(params, callback) { function restoreObject(params, callback) { var headers = params.Headers; if (!params['RestoreRequest']) { - callback({error: 'missing param RestoreRequest'}); + callback(util.error(new Error('missing param RestoreRequest'))); return; } @@ -2268,9 +2264,7 @@ function restoreObject(params, callback) { body: xml, action: 'restore', headers: headers, - }, function (err, data) { - callback(err, data); - }); + }, callback); } /** @@ -2409,7 +2403,7 @@ function deleteObjectTagging(params, callback) { */ function selectObjectContent(params, callback) { var SelectType = params['SelectType']; - if (!SelectType) return callback({error: 'missing param SelectType'}); + if (!SelectType) return callback(util.error(new Error('missing param SelectType'))); var SelectRequest = params['SelectRequest'] || {}; var xml = util.json2xml({SelectRequest: SelectRequest}); @@ -2419,7 +2413,6 @@ function selectObjectContent(params, callback) { headers['Content-MD5'] = util.binaryBase64(util.md5(xml)); submitRequest.call(this, { - Interface: 'SelectObjectContent', Action: 'name/cos:GetObject', method: 'POST', Bucket: params.Bucket, @@ -2432,6 +2425,7 @@ function selectObjectContent(params, callback) { }, VersionId: params.VersionId, body: xml, + DataType: 'arraybuffer', rawBody: true, }, function (err, data) { if (err && err.statusCode === 204) { @@ -2439,10 +2433,12 @@ function selectObjectContent(params, callback) { } else if (err) { return callback(err); } + var result = util.parseSelectPayload(data.body); callback(null, { statusCode: data.statusCode, headers: data.headers, - Body: data.body, + Body: result.body, + Payload: result.payload, }); }); } @@ -2476,6 +2472,7 @@ function selectObjectContent(params, callback) { function multipartInit(params, callback) { var self = this; + // 特殊处理 Cache-Control var headers = params.Headers; // 特殊处理 Cache-Control、Content-Type @@ -2494,9 +2491,7 @@ function multipartInit(params, callback) { headers: params.Headers, qs: params.Query, }, function (err, data) { - if (err) { - return callback(err); - } + if (err) return callback(err); data = util.clone(data || {}); if (data && data.InitiateMultipartUploadResult) { return callback(null, util.extend(data.InitiateMultipartUploadResult, { @@ -2685,14 +2680,8 @@ function multipartList(params, callback) { if (data && data.ListMultipartUploadsResult) { var Upload = data.ListMultipartUploadsResult.Upload || []; - - var CommonPrefixes = data.ListMultipartUploadsResult.CommonPrefixes || []; - - CommonPrefixes = util.isArray(CommonPrefixes) ? CommonPrefixes : [CommonPrefixes]; Upload = util.isArray(Upload) ? Upload : [Upload]; - data.ListMultipartUploadsResult.Upload = Upload; - data.ListMultipartUploadsResult.CommonPrefixes = CommonPrefixes; } var result = util.clone(data.ListMultipartUploadsResult || {}); util.extend(result, { @@ -2847,7 +2836,7 @@ function getObjectUrl(params, callback) { var signUrl = url; signUrl += '?' + (AuthData.Authorization.indexOf('q-signature') > -1 ? AuthData.Authorization : 'sign=' + encodeURIComponent(AuthData.Authorization)); - AuthData.XCosSecurityToken && (signUrl += '&x-cos-security-token=' + AuthData.XCosSecurityToken); + AuthData.SecurityToken && (signUrl += '&x-cos-security-token=' + AuthData.SecurityToken); AuthData.ClientIP && (signUrl += '&clientIP=' + AuthData.ClientIP); AuthData.ClientUA && (signUrl += '&clientUA=' + AuthData.ClientUA); AuthData.Token && (signUrl += '&token=' + AuthData.Token); @@ -2857,7 +2846,7 @@ function getObjectUrl(params, callback) { }); if (AuthData) { return url + '?' + AuthData.Authorization + - (AuthData.XCosSecurityToken ? '&x-cos-security-token=' + AuthData.XCosSecurityToken : ''); + (AuthData.SecurityToken ? '&x-cos-security-token=' + AuthData.SecurityToken : ''); } else { return url; } @@ -2983,44 +2972,16 @@ function getUrl(params) { function getAuthorizationAsync(params, callback) { var headers = util.clone(params.Headers); - delete headers['Content-Type']; - delete headers['Cache-Control']; util.each(headers, function (v, k) { - v === '' && delete headers[k]; - }); - - var cb = function (AuthData) { - - // 检查签名格式 - var formatAllow = false; - var auth = AuthData.Authorization; - if (auth) { - if (auth.indexOf(' ') > -1) { - formatAllow = false; - } else if (auth.indexOf('q-sign-algorithm=') > -1 && - auth.indexOf('q-ak=') > -1 && - auth.indexOf('q-sign-time=') > -1 && - auth.indexOf('q-key-time=') > -1 && - auth.indexOf('q-url-param-list=') > -1) { - formatAllow = true; - } else { - try { - auth = atob(auth); - if (auth.indexOf('a=') > -1 && - auth.indexOf('k=') > -1 && - auth.indexOf('t=') > -1 && - auth.indexOf('r=') > -1 && - auth.indexOf('b=') > -1) { - formatAllow = true; - } - } catch (e) {} - } - } - if (formatAllow) { - callback && callback(null, AuthData); - } else { - callback && callback({error: 'authorization error'}); - } + (v === '' || ['content-type', 'cache-control', 'expires'].indexOf(k.toLowerCase())) && delete headers[k]; + }); + + // 获取凭证的回调,避免用户 callback 多次 + var cbDone = false; + var cb = function (err, AuthData) { + if (cbDone) return; + cbDone = true; + callback && callback(err, AuthData); }; var self = this; @@ -3083,12 +3044,50 @@ function getAuthorizationAsync(params, callback) { }); var AuthData = { Authorization: Authorization, - XCosSecurityToken: StsData.XCosSecurityToken || '', + SecurityToken: StsData.SecurityToken || StsData.XCosSecurityToken || '', Token: StsData.Token || '', ClientIP: StsData.ClientIP || '', ClientUA: StsData.ClientUA || '', }; - cb(AuthData); + cb(null, AuthData); + }; + var checkAuthError = function (AuthData) { + if (AuthData.Authorization) { + // 检查签名格式 + var formatAllow = false; + var auth = AuthData.Authorization; + if (auth) { + if (auth.indexOf(' ') > -1) { + formatAllow = false; + } else if (auth.indexOf('q-sign-algorithm=') > -1 && + auth.indexOf('q-ak=') > -1 && + auth.indexOf('q-sign-time=') > -1 && + auth.indexOf('q-key-time=') > -1 && + auth.indexOf('q-url-param-list=') > -1) { + formatAllow = true; + } else { + try { + auth = Buffer.from(auth, 'base64').toString(); + if (auth.indexOf('a=') > -1 && + auth.indexOf('k=') > -1 && + auth.indexOf('t=') > -1 && + auth.indexOf('r=') > -1 && + auth.indexOf('b=') > -1) { + formatAllow = true; + } + } catch (e) {} + } + } + if (!formatAllow) return util.error(new Error('getAuthorization callback params format error')); + } else { + if (!AuthData.TmpSecretId) return util.error(new Error('getAuthorization callback params missing "TmpSecretId"')); + if (!AuthData.TmpSecretKey) return util.error(new Error('getAuthorization callback params missing "TmpSecretKey"')); + if (!AuthData.SecurityToken && !AuthData.XCosSecurityToken) return util.error(new Error('getAuthorization callback params missing "SecurityToken"')); + if (!AuthData.ExpiredTime) return util.error(new Error('getAuthorization callback params missing "ExpiredTime"')); + if (AuthData.ExpiredTime && AuthData.ExpiredTime.toString().length !== 10) return util.error(new Error('getAuthorization callback params "ExpiredTime" should be 10 digits')); + if (AuthData.StartTime && AuthData.StartTime.toString().length !== 10) return util.error(new Error('getAuthorization callback params "StartTime" should be 10 StartTime')); + } + return false; }; // 先判断是否有临时密钥 @@ -3106,20 +3105,17 @@ function getAuthorizationAsync(params, callback) { Scope: Scope, SystemClockOffset: self.options.SystemClockOffset, }, function (AuthData) { - if (typeof AuthData === 'string') { - AuthData = {Authorization: AuthData}; - } - if (AuthData.TmpSecretId && - AuthData.TmpSecretKey && - AuthData.XCosSecurityToken && - AuthData.ExpiredTime) { + if (typeof AuthData === 'string') AuthData = {Authorization: AuthData}; + var AuthError = checkAuthError(AuthData); + if (AuthError) return cb(AuthError); + if (AuthData.Authorization) { + cb(null, AuthData); + } else { StsData = AuthData || {}; StsData.Scope = Scope; StsData.ScopeKey = ScopeKey; self._StsCache.push(StsData); calcAuthByTmpKey(); - } else { - cb(AuthData); } }); } else if (self.options.getSTS) { // 外部获取临时密钥 @@ -3130,8 +3126,10 @@ function getAuthorizationAsync(params, callback) { StsData = data || {}; StsData.Scope = Scope; StsData.ScopeKey = ScopeKey; - StsData.TmpSecretId = StsData.SecretId; - StsData.TmpSecretKey = StsData.SecretKey; + if (!StsData.TmpSecretId) StsData.TmpSecretId = StsData.SecretId; + if (!StsData.TmpSecretKey) StsData.TmpSecretKey = StsData.SecretKey; + var AuthError = checkAuthError(StsData); + if (AuthError) return cb(AuthError); self._StsCache.push(StsData); calcAuthByTmpKey(); }); @@ -3150,9 +3148,9 @@ function getAuthorizationAsync(params, callback) { }); var AuthData = { Authorization: Authorization, - XCosSecurityToken: self.options.XCosSecurityToken, + SecurityToken: self.options.SecurityToken || self.options.XCosSecurityToken, }; - cb(AuthData); + cb(null, AuthData); return AuthData; })(); } @@ -3285,7 +3283,7 @@ function _submitRequest(params, callback) { params.AuthData.Token && (opt.headers['token'] = params.AuthData.Token); params.AuthData.ClientIP && (opt.headers['clientIP'] = params.AuthData.ClientIP); params.AuthData.ClientUA && (opt.headers['clientUA'] = params.AuthData.ClientUA); - params.AuthData.XCosSecurityToken && (opt.headers['x-cos-security-token'] = params.AuthData.XCosSecurityToken); + params.AuthData.SecurityToken && (opt.headers['x-cos-security-token'] = params.AuthData.SecurityToken); // 清理 undefined 和 null 字段 opt.headers && (opt.headers = util.clearKey(opt.headers)); @@ -3310,13 +3308,6 @@ function _submitRequest(params, callback) { opt.timeout = this.options.Timeout; } - // 整理 cosInterface 用于 before-send 使用 - if (params.Interface) { - opt.cosInterface = params.Interface; - } else if (params.Action) { - opt.cosInterface = params.Action.replace(/^name\/cos:/, ''); - } - self.options.ForcePathStyle && (opt.pathStyle = self.options.ForcePathStyle); self.emit('before-send', opt); var sender = (self.options.Request || REQUEST)(opt, function (r) { @@ -3349,37 +3340,34 @@ function _submitRequest(params, callback) { }; // 请求错误,发生网络错误 - if (err) { - cb({error: err}); - return; - } - - // 不对 body 进行转换,body 直接挂载返回 - var jsonRes; - if (rawBody) { - jsonRes = {}; - jsonRes.body = body; - } else { - try { - jsonRes = body && body.indexOf('<') > -1 && body.indexOf('>') > -1 && util.xml2json(body) || {}; - } catch (e) { - jsonRes = body || {}; - } - } + if (err) return cb(util.error(err)); // 请求返回码不为 200 var statusCode = response.statusCode; var statusSuccess = Math.floor(statusCode / 100) === 2; // 200 202 204 206 - if (!statusSuccess) { - cb({error: jsonRes.Error || jsonRes}); - return; + + // 不对 body 进行转换,body 直接挂载返回 + if (rawBody && statusSuccess) return cb(null, {body: body}); + + // 解析 xml body + var json; + try { + json = body && body.indexOf('<') > -1 && body.indexOf('>') > -1 && util.xml2json(body) || {}; + } catch (e) { + json = {}; } - if (jsonRes.Error) { - cb({error: jsonRes.Error}); - return; + // 处理返回值 + var xmlError = json && json.Error; + if (statusSuccess) { // 正确返回,状态码 2xx 时,body 不会有 Error + cb(null, json); + } else if (xmlError) { // 正常返回了 xml body,且有 Error 节点 + cb(util.error(new Error(xmlError.Message), {code: xmlError.Code, error: xmlError})); + } else if (statusCode) { // 有错误的状态码 + cb(util.error(new Error(response.statusMessage), {code: '' + statusCode})); + } else if (statusCode) { // 无状态码,或者获取不到状态码 + cb(util.error(new Error('statusCode error'))); } - cb(null, jsonRes); }); // kill task diff --git a/src/cos.js b/src/cos.js index ae0365a..4645979 100644 --- a/src/cos.js +++ b/src/cos.js @@ -10,7 +10,7 @@ var defaultOptions = { AppId: '', // AppId 已废弃,请拼接到 Bucket 后传入,例如:test-1250000000 SecretId: '', SecretKey: '', - XCosSecurityToken: '', // 使用临时密钥需要注意自行刷新 Token + SecurityToken: '', // 使用临时密钥需要注意自行刷新 Token ChunkRetryTimes: 2, FileParallelLimit: 3, ChunkParallelLimit: 3, @@ -21,7 +21,6 @@ var defaultOptions = { CopySliceSize: 1024 * 1024 * 10, MaxPartNumber: 10000, ProgressInterval: 1000, - UploadQueueSize: 10000, Domain: '', ServiceDomain: '', Protocol: '', @@ -32,6 +31,7 @@ var defaultOptions = { CorrectClockSkew: true, SystemClockOffset: 0, // 单位毫秒,ms UploadCheckContentMd5: false, + UploadQueueSize: 10000, UploadAddMetaMd5: false, UploadIdCacheLimit: 50, }; @@ -59,6 +59,6 @@ base.init(COS, task); advance.init(COS, task); COS.getAuthorization = util.getAuth; -COS.version = '1.1.11'; +COS.version = '1.2.0'; module.exports = COS; diff --git a/src/session.js b/src/session.js index f85f64c..c03b493 100644 --- a/src/session.js +++ b/src/session.js @@ -12,7 +12,7 @@ var getCache = function () { } catch (e) { } if (!val) val = []; - return val; + cache = val; }; var setCache = function () { try { @@ -23,7 +23,7 @@ var setCache = function () { var init = function () { if (cache) return; - cache = getCache(); + getCache.call(this); // 清理太老旧的数据 var changed = false; var now = Math.round(Date.now() / 1000); @@ -67,7 +67,7 @@ var mod = { // 获取文件对应的 UploadId 列表 getUploadIdList: function (uuid) { if (!uuid) return null; - init(); + init.call(this); var list = []; for (var i = 0; i < cache.length; i++) { if (cache[i][0] === uuid) @@ -77,7 +77,7 @@ var mod = { }, // 缓存 UploadId saveUploadId: function (uuid, UploadId, limit) { - init(); + init.call(this); if (!uuid) return; // 清理没用的 UploadId,js 文件没有 FilePath ,只清理相同记录 for (var i = cache.length - 1; i >= 0; i--) { @@ -92,7 +92,7 @@ var mod = { }, // UploadId 已用完,移除掉 removeUploadId: function (UploadId) { - init(); + init.call(this); delete mod.using[UploadId]; for (var i = cache.length - 1; i >= 0; i--) { if (cache[i][1] === UploadId) cache.splice(i, 1) diff --git a/src/task.js b/src/task.js index dd9f262..417e242 100644 --- a/src/task.js +++ b/src/task.js @@ -212,10 +212,7 @@ var initTask = function (cos) { // 异步获取 filesize util.getFileSize(api, params, function (err, size) { // 开始处理上传 - if (err) { // 如果获取大小出错,不加入队列 - callback(err); - return; - } + if (err) return callback(util.error(err)); // 如果获取大小出错,不加入队列 // 获取完文件大小再把任务加入队列 tasks[id] = task; queue.push(task); diff --git a/src/util.js b/src/util.js index f42cedf..9d1ac2a 100644 --- a/src/util.js +++ b/src/util.js @@ -34,8 +34,8 @@ var getAuth = function (opt) { pathname.indexOf('/') !== 0 && (pathname = '/' + pathname); } - if (!SecretId) return console.error('missing param SecretId'); - if (!SecretKey) return console.error('missing param SecretKey'); + if (!SecretId) throw new Error('missing param SecretId'); + if (!SecretKey) throw new Error('missing param SecretKey'); var getObjectKeys = function (obj, forKey) { var list = []; @@ -112,6 +112,65 @@ var getAuth = function (opt) { }; +var readIntBE = function (chunk, size, offset) { + var bytes = size / 8; + var buf = chunk.slice(offset, offset + bytes); + new Uint8Array(buf).reverse(); + return new ({8: Uint8Array, 16: Uint16Array, 32: Uint32Array})[size](buf)[0]; +}; +var buf2str = function (chunk, start, end, isUtf8) { + var buf = chunk.slice(start, end); + var str = ''; + new Uint8Array(buf).forEach(function (charCode) { + str += String.fromCharCode(charCode) + }); + if (isUtf8) str = decodeURIComponent(escape(str)); + return str; +}; +var parseSelectPayload = function (chunk) { + var header = {}; + var body = buf2str(chunk); + var result = {records:[]}; + while (chunk.byteLength) { + var totalLength = readIntBE(chunk, 32, 0); + var headerLength = readIntBE(chunk, 32, 4); + var payloadRestLength = totalLength - headerLength - 16; + var offset = 0; + var content; + chunk = chunk.slice(12); + // 获取 Message 的 header 信息 + while (offset < headerLength) { + var headerNameLength = readIntBE(chunk, 8, offset); + var headerName = buf2str(chunk, offset + 1, offset + 1 + headerNameLength); + var headerValueLength = readIntBE(chunk, 16, offset + headerNameLength + 2); + var headerValue = buf2str(chunk, offset + headerNameLength + 4, offset + headerNameLength + 4 + headerValueLength); + header[headerName] = headerValue; + offset += headerNameLength + 4 + headerValueLength; + } + if (header[':event-type'] === 'Records') { + content = buf2str(chunk, offset, offset + payloadRestLength, true); + result.records.push(content); + } else if (header[':event-type'] === 'Stats') { + content = buf2str(chunk, offset, offset + payloadRestLength, true); + result.stats = util.xml2json(content).Stats; + } else if (header[':event-type'] === 'error') { + var errCode = header[':error-code']; + var errMessage = header[':error-message']; + var err = new Error(errMessage); + err.message = errMessage; + err.name = err.code = errCode; + result.error = err; + } else if (['Progress', 'Continuation', 'End'].includes(header[':event-type'])) { + // do nothing + } + chunk = chunk.slice(offset + payloadRestLength + 4); + } + return { + payload: result.records.join(''), + body: body, + }; +}; + var noop = function () { }; @@ -394,6 +453,7 @@ var formatParams = function (apiName, params) { 'x-cos-grant-read-acp': 'GrantReadAcp', 'x-cos-grant-write-acp': 'GrantWriteAcp', 'x-cos-storage-class': 'StorageClass', + 'x-cos-traffic-limit': 'TrafficLimit', // SSE-C 'x-cos-server-side-encryption-customer-algorithm': 'SSECustomerAlgorithm', 'x-cos-server-side-encryption-customer-key': 'SSECustomerKey', @@ -433,6 +493,7 @@ var apiWrapper = function (apiName, apiFn) { // 代理回调函数 var formatResult = function (result) { if (result && result.headers) { + result.headers['x-cos-request-id'] && (result.RequestId = result.headers['x-cos-request-id']); result.headers['x-cos-version-id'] && (result.VersionId = result.headers['x-cos-version-id']); result.headers['x-cos-delete-marker'] && (result.DeleteMarker = result.headers['x-cos-delete-marker']); } @@ -491,11 +552,11 @@ var apiWrapper = function (apiName, apiFn) { callback = function (err, data) { err ? reject(err) : resolve(data); }; - if (errMsg) return _callback({error: errMsg}); + if (errMsg) return _callback(util.error(new Error(errMsg))); apiFn.call(self, params, _callback); }); } else { - if (errMsg) return _callback({error: errMsg}); + if (errMsg) return _callback(util.error(new Error(errMsg))); var res = apiFn.call(self, params, _callback); if (isSync) return res; } @@ -555,7 +616,7 @@ var getFileSize = function (api, params, callback) { if ((params.Body && (params.Body instanceof Blob || params.Body.toString() === '[object File]' || params.Body.toString() === '[object Blob]'))) { size = params.Body.size; } else { - callback({error: 'params body format error, Only allow File|Blob|String.'}); + callback(util.error(new Error('params body format error, Only allow File|Blob|String.'))); return; } params.ContentLength = size; @@ -567,6 +628,33 @@ var getSkewTime = function (offset) { return Date.now() + (offset || 0); }; + +var error = function (err, opt) { + var sourceErr = err; + err.message = err.message || null; + + if (typeof opt === 'string') { + err.error = opt; + err.message = opt; + } else if (typeof opt === 'object' && opt !== null) { + extend(err, opt); + if (opt.code || opt.name) err.code = opt.code || opt.name; + if (opt.message) err.message = opt.message; + if (opt.stack) err.stack = opt.stack; + } + + if (typeof Object.defineProperty === 'function') { + Object.defineProperty(err, 'name', {writable: true, enumerable: false}); + Object.defineProperty(err, 'message', {enumerable: true}); + } + + err.name = opt && opt.name || err.name || err.code || 'Error'; + if (!err.code) err.code = err.name; + if (!err.error) err.error = clone(sourceErr); // 兼容老的错误格式 + + return err; +} + var util = { noop: noop, formatParams: formatParams, @@ -593,7 +681,9 @@ var util = { throttleOnProgress: throttleOnProgress, getFileSize: getFileSize, getSkewTime: getSkewTime, + error: error, getAuth: getAuth, + parseSelectPayload: parseSelectPayload, isBrowser: true, };