From 47ea3e8ba3b6a06f5a957a7565e67130b8d5fa41 Mon Sep 17 00:00:00 2001 From: Lukas Malkmus Date: Tue, 27 Oct 2020 01:21:40 +0100 Subject: [PATCH] Try to get version from go.mod file --- dist/post_run/index.js | 9513 +++++++++++++++++----------------------- dist/run/index.js | 9513 +++++++++++++++++----------------------- src/version.ts | 14 +- 3 files changed, 7931 insertions(+), 11109 deletions(-) diff --git a/dist/post_run/index.js b/dist/post_run/index.js index 4879f6304e..6e83d8b45a 100644 --- a/dist/post_run/index.js +++ b/dist/post_run/index.js @@ -1483,9 +1483,7 @@ function resolvePaths(patterns) { try { for (var _c = __asyncValues(globber.globGenerator()), _d; _d = yield _c.next(), !_d.done;) { const file = _d.value; - const relativeFile = path - .relative(workspace, file) - .replace(new RegExp(`\\${path.sep}`, 'g'), '/'); + const relativeFile = path.relative(workspace, file); core.debug(`Matched: ${relativeFile}`); // Paths are made relative so the tar entries are all relative to the root of the workspace. paths.push(`${relativeFile}`); @@ -2602,7 +2600,9 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.findLintVersion = exports.stringifyVersion = void 0; const core = __importStar(__webpack_require__(470)); const httpm = __importStar(__webpack_require__(539)); +const fs = __importStar(__webpack_require__(747)); const versionRe = /^v(\d+)\.(\d+)(?:\.(\d+))?$/; +const modVersionRe = /github.com\/golangci\/golangci-lint\sv(.+)/; const parseVersion = (s) => { if (s == "latest" || s == "") { return null; @@ -2617,13 +2617,12 @@ const parseVersion = (s) => { patch: match[3] === undefined ? null : parseInt(match[3]), }; }; -const stringifyVersion = (v) => { +exports.stringifyVersion = (v) => { if (v == null) { return "latest"; } return `v${v.major}.${v.minor}${v.patch !== null ? `.${v.patch}` : ``}`; }; -exports.stringifyVersion = stringifyVersion; const minVersion = { major: 1, minor: 28, @@ -2644,7 +2643,15 @@ const isLessVersion = (a, b) => { return a.minor < b.minor; }; const getRequestedLintVersion = () => { - const requestedLintVersion = core.getInput(`version`); + let requestedLintVersion = core.getInput(`version`); + if (requestedLintVersion == "") { + const content = fs.readFileSync("go.mod", "utf-8"); + const match = content.match(modVersionRe); + if (match) { + requestedLintVersion = match[1]; + core.info(`Found golangci-lint version '${requestedLintVersion}' in go.mod`); + } + } const parsedRequestedLintVersion = parseVersion(requestedLintVersion); if (parsedRequestedLintVersion == null) { return null; @@ -2707,49 +2714,7 @@ exports.findLintVersion = findLintVersion; /***/ }), -/* 53 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -/*! - * Copyright 2019, OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const context_1 = __webpack_require__(560); -class NoopContextManager { - active() { - return context_1.Context.ROOT_CONTEXT; - } - with(context, fn) { - return fn(); - } - bind(target, context) { - return target; - } - enable() { - return this; - } - disable() { - return this; - } -} -exports.NoopContextManager = NoopContextManager; -//# sourceMappingURL=NoopContextManager.js.map - -/***/ }), +/* 53 */, /* 54 */, /* 55 */, /* 56 */, @@ -4149,7 +4114,7 @@ module.exports = bytesToUuid; Object.defineProperty(exports, '__esModule', { value: true }); -var tslib = __webpack_require__(640); +var tslib = __webpack_require__(422); var listenersMap = new WeakMap(); var abortedMap = new WeakMap(); @@ -4591,12 +4556,9 @@ function uploadChunk(httpClient, resourceUrl, openStream, start, end) { 'Content-Type': 'application/octet-stream', 'Content-Range': getContentRange(start, end) }; - const uploadChunkResponse = yield requestUtils_1.retryHttpClientResponse(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter(this, void 0, void 0, function* () { + yield requestUtils_1.retryHttpClientResponse(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter(this, void 0, void 0, function* () { return httpClient.sendStream('PATCH', resourceUrl, openStream(), additionalHeaders); })); - if (!requestUtils_1.isSuccessStatusCode(uploadChunkResponse.message.statusCode)) { - throw new Error(`Cache service responded with ${uploadChunkResponse.message.statusCode} during upload chunk.`); - } }); } function uploadFile(httpClient, cacheId, archivePath, options) { @@ -4653,7 +4615,6 @@ function saveCache(cacheId, archivePath, options) { // Commit Cache core.debug('Commiting cache'); const cacheSize = utils.getArchiveFileSizeIsBytes(archivePath); - core.info(`Cache Size: ~${Math.round(cacheSize / (1024 * 1024))} MB (${cacheSize} B)`); const commitCacheResponse = yield commitCache(httpClient, cacheId, cacheSize); if (!requestUtils_1.isSuccessStatusCode(commitCacheResponse.statusCode)) { throw new Error(`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`); @@ -7511,7 +7472,43 @@ exports.isTokenCredential = isTokenCredential; /***/ }), /* 230 */, -/* 231 */, +/* 231 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(__webpack_require__(328), exports); +__exportStar(__webpack_require__(715), exports); +__exportStar(__webpack_require__(924), exports); +//# sourceMappingURL=index.js.map + +/***/ }), /* 232 */, /* 233 */, /* 234 */, @@ -10078,19 +10075,12 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; Object.defineProperty(exports, "__esModule", { value: true }); -const core = __importStar(__webpack_require__(470)); -const fs = __importStar(__webpack_require__(747)); -const globOptionsHelper = __importStar(__webpack_require__(601)); -const path = __importStar(__webpack_require__(622)); -const patternHelper = __importStar(__webpack_require__(597)); +const core = __webpack_require__(470); +const fs = __webpack_require__(747); +const globOptionsHelper = __webpack_require__(601); +const path = __webpack_require__(622); +const patternHelper = __webpack_require__(597); const internal_match_kind_1 = __webpack_require__(327); const internal_pattern_1 = __webpack_require__(923); const internal_search_state_1 = __webpack_require__(728); @@ -10889,7 +10879,30 @@ var MatchKind; //# sourceMappingURL=internal-match-kind.js.map /***/ }), -/* 328 */, +/* 328 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map + +/***/ }), /* 329 */, /* 330 */, /* 331 */, @@ -11557,13 +11570,6 @@ var StorageError = { type: { name: "String" } - }, - code: { - xmlName: "Code", - serializedName: "Code", - type: { - name: "String" - } } } } @@ -11924,13 +11930,6 @@ var BlobPropertiesInternal = { type: { name: "String" } - }, - lastAccessedOn: { - xmlName: "LastAccessTime", - serializedName: "LastAccessTime", - type: { - name: "DateTimeRfc1123" - } } } } @@ -12636,70 +12635,6 @@ var JsonTextConfiguration = { } } }; -var ArrowField = { - xmlName: "Field", - serializedName: "ArrowField", - type: { - name: "Composite", - className: "ArrowField", - modelProperties: { - type: { - xmlName: "Type", - required: true, - serializedName: "Type", - type: { - name: "String" - } - }, - name: { - xmlName: "Name", - serializedName: "Name", - type: { - name: "String" - } - }, - precision: { - xmlName: "Precision", - serializedName: "Precision", - type: { - name: "Number" - } - }, - scale: { - xmlName: "Scale", - serializedName: "Scale", - type: { - name: "Number" - } - } - } - } -}; -var ArrowConfiguration = { - serializedName: "ArrowConfiguration", - type: { - name: "Composite", - className: "ArrowConfiguration", - modelProperties: { - schema: { - xmlIsWrapped: true, - xmlName: "Schema", - xmlElementName: "Field", - required: true, - serializedName: "Schema", - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "ArrowField" - } - } - } - } - } - } -}; var ListContainersSegmentResponse = { xmlName: "EnumerationResults", serializedName: "ListContainersSegmentResponse", @@ -12838,12 +12773,12 @@ var FilterBlobItem = { name: "String" } }, - tags: { - xmlName: "Tags", - serializedName: "Tags", + tagValue: { + xmlName: "TagValue", + required: true, + serializedName: "TagValue", type: { - name: "Composite", - className: "BlobTags" + name: "String" } } } @@ -13140,8 +13075,7 @@ var QueryFormat = { name: "Enum", allowedValues: [ "delimited", - "json", - "arrow" + "json" ] } }, @@ -13160,14 +13094,6 @@ var QueryFormat = { name: "Composite", className: "JsonTextConfiguration" } - }, - arrowConfiguration: { - xmlName: "ArrowConfiguration", - serializedName: "ArrowConfiguration", - type: { - name: "Composite", - className: "ArrowConfiguration" - } } } } @@ -13620,12 +13546,6 @@ var ServiceGetAccountInfoHeaders = { ] } }, - isHierarchicalNamespaceEnabled: { - serializedName: "x-ms-is-hns-enabled", - type: { - name: "Boolean" - } - }, errorCode: { serializedName: "x-ms-error-code", type: { @@ -14827,12 +14747,6 @@ var BlobDownloadHeaders = { name: "Boolean" } }, - lastAccessed: { - serializedName: "x-ms-last-access-time", - type: { - name: "DateTimeRfc1123" - } - }, contentCrc64: { serializedName: "x-ms-content-crc64", type: { @@ -15162,12 +15076,6 @@ var BlobGetPropertiesHeaders = { name: "String" } }, - lastAccessed: { - serializedName: "x-ms-last-access-time", - type: { - name: "DateTimeRfc1123" - } - }, errorCode: { serializedName: "x-ms-error-code", type: { @@ -15624,30 +15532,12 @@ var BlockBlobUploadHeaders = { } } }; -var BlockBlobPutBlobFromUrlHeaders = { - serializedName: "blockblob-putblobfromurl-headers", +var BlobUndeleteHeaders = { + serializedName: "blob-undelete-headers", type: { name: "Composite", - className: "BlockBlobPutBlobFromUrlHeaders", + className: "BlobUndeleteHeaders", modelProperties: { - etag: { - serializedName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - contentMD5: { - serializedName: "content-md5", - type: { - name: "ByteArray" - } - }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { @@ -15666,36 +15556,12 @@ var BlockBlobPutBlobFromUrlHeaders = { name: "String" } }, - versionId: { - serializedName: "x-ms-version-id", - type: { - name: "String" - } - }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, - isServerEncrypted: { - serializedName: "x-ms-request-server-encrypted", - type: { - name: "Boolean" - } - }, - encryptionKeySha256: { - serializedName: "x-ms-encryption-key-sha256", - type: { - name: "String" - } - }, - encryptionScope: { - serializedName: "x-ms-encryption-scope", - type: { - name: "String" - } - }, errorCode: { serializedName: "x-ms-error-code", type: { @@ -15705,12 +15571,24 @@ var BlockBlobPutBlobFromUrlHeaders = { } } }; -var BlobUndeleteHeaders = { - serializedName: "blob-undelete-headers", +var BlobSetExpiryHeaders = { + serializedName: "blob-setexpiry-headers", type: { name: "Composite", - className: "BlobUndeleteHeaders", + className: "BlobSetExpiryHeaders", modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { @@ -15744,11 +15622,11 @@ var BlobUndeleteHeaders = { } } }; -var BlobSetExpiryHeaders = { - serializedName: "blob-setexpiry-headers", +var BlobSetHTTPHeadersHeaders = { + serializedName: "blob-sethttpheaders-headers", type: { name: "Composite", - className: "BlobSetExpiryHeaders", + className: "BlobSetHTTPHeadersHeaders", modelProperties: { etag: { serializedName: "etag", @@ -15760,63 +15638,12 @@ var BlobSetExpiryHeaders = { serializedName: "last-modified", type: { name: "DateTimeRfc1123" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - type: { - name: "String" - } - } - } - } -}; -var BlobSetHTTPHeadersHeaders = { - serializedName: "blob-sethttpheaders-headers", - type: { - name: "Composite", - className: "BlobSetHTTPHeadersHeaders", - modelProperties: { - etag: { - serializedName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - blobSequenceNumber: { - serializedName: "x-ms-blob-sequence-number", - type: { - name: "Number" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + type: { + name: "Number" } }, clientRequestId: { @@ -17966,8 +17793,6 @@ var Mappers = /*#__PURE__*/Object.freeze({ __proto__: null, BlobServiceProperties: BlobServiceProperties, BlobServiceStatistics: BlobServiceStatistics, - BlobTag: BlobTag, - BlobTags: BlobTags, ContainerItem: ContainerItem, ContainerProperties: ContainerProperties, CorsRule: CorsRule, @@ -18198,21 +18023,6 @@ var blobContentType = { } } }; -var blobDeleteType = { - parameterPath: [ - "options", - "blobDeleteType" - ], - mapper: { - serializedName: "deletetype", - type: { - name: "Enum", - allowedValues: [ - "Permanent" - ] - } - } -}; var blobSequenceNumber = { parameterPath: [ "options", @@ -18679,18 +18489,6 @@ var copySource = { } } }; -var copySourceBlobProperties = { - parameterPath: [ - "options", - "copySourceBlobProperties" - ], - mapper: { - serializedName: "x-ms-copy-source-blob-properties", - type: { - name: "Boolean" - } - } -}; var defaultEncryptionScope = { parameterPath: [ "options", @@ -19664,7 +19462,7 @@ var version = { required: true, isConstant: true, serializedName: "x-ms-version", - defaultValue: '2020-04-08', + defaultValue: '2019-12-12', type: { name: "String" } @@ -20656,8 +20454,6 @@ var getAccountInfoOperationSpec$1 = { var Mappers$2 = /*#__PURE__*/Object.freeze({ __proto__: null, - ArrowConfiguration: ArrowConfiguration, - ArrowField: ArrowField, BlobAbortCopyFromURLHeaders: BlobAbortCopyFromURLHeaders, BlobAcquireLeaseHeaders: BlobAcquireLeaseHeaders, BlobBreakLeaseHeaders: BlobBreakLeaseHeaders, @@ -20945,8 +20741,7 @@ var deleteMethodOperationSpec$1 = { queryParameters: [ snapshot, versionId, - timeoutInSeconds, - blobDeleteType + timeoutInSeconds ], headerParameters: [ deleteSnapshots, @@ -21662,8 +21457,7 @@ var getTagsOperationSpec = { headerParameters: [ version, requestId, - ifTags, - leaseId0 + ifTags ], responses: { 200: { @@ -21694,8 +21488,7 @@ var setTagsOperationSpec = { transactionalContentMD5, transactionalContentCrc64, requestId, - ifTags, - leaseId0 + ifTags ], requestBody: { parameterPath: [ @@ -22448,7 +22241,6 @@ var Mappers$5 = /*#__PURE__*/Object.freeze({ Block: Block, BlockBlobCommitBlockListHeaders: BlockBlobCommitBlockListHeaders, BlockBlobGetBlockListHeaders: BlockBlobGetBlockListHeaders, - BlockBlobPutBlobFromUrlHeaders: BlockBlobPutBlobFromUrlHeaders, BlockBlobStageBlockFromURLHeaders: BlockBlobStageBlockFromURLHeaders, BlockBlobStageBlockHeaders: BlockBlobStageBlockHeaders, BlockBlobUploadHeaders: BlockBlobUploadHeaders, @@ -22482,13 +22274,6 @@ var BlockBlob = /** @class */ (function () { options: options }, uploadOperationSpec, callback); }; - BlockBlob.prototype.putBlobFromUrl = function (contentLength, copySource, options, callback) { - return this.client.sendOperationRequest({ - contentLength: contentLength, - copySource: copySource, - options: options - }, putBlobFromUrlOperationSpec, callback); - }; BlockBlob.prototype.stageBlock = function (blockId, contentLength, body, options, callback) { return this.client.sendOperationRequest({ blockId: blockId, @@ -22579,61 +22364,6 @@ var uploadOperationSpec = { isXML: true, serializer: serializer$5 }; -var putBlobFromUrlOperationSpec = { - httpMethod: "PUT", - path: "{containerName}/{blob}", - urlParameters: [ - url - ], - queryParameters: [ - timeoutInSeconds - ], - headerParameters: [ - transactionalContentMD5, - contentLength, - metadata, - encryptionScope, - tier0, - version, - requestId, - sourceContentMD5, - blobTagsString, - copySource, - copySourceBlobProperties, - blobType2, - blobContentType, - blobContentEncoding, - blobContentLanguage, - blobContentMD5, - blobCacheControl, - blobContentDisposition, - leaseId0, - encryptionKey, - encryptionKeySha256, - encryptionAlgorithm, - ifModifiedSince, - ifUnmodifiedSince, - ifMatch, - ifNoneMatch, - ifTags, - sourceIfModifiedSince, - sourceIfUnmodifiedSince, - sourceIfMatch, - sourceIfNoneMatch, - sourceIfTags - ], - responses: { - 201: { - headersMapper: BlockBlobPutBlobFromUrlHeaders - }, - default: { - bodyMapper: StorageError, - headersMapper: BlockBlobPutBlobFromUrlHeaders - } - }, - isXML: true, - serializer: serializer$5 -}; var stageBlockOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", @@ -22813,8 +22543,8 @@ var logger = logger$1.createClientLogger("storage-blob"); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -var SDK_VERSION = "12.4.1"; -var SERVICE_VERSION = "2020-04-08"; +var SDK_VERSION = "12.2.1"; +var SERVICE_VERSION = "2019-12-12"; var BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES = 256 * 1024 * 1024; // 256MB var BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES = 4000 * 1024 * 1024; // 4000MB var BLOCK_BLOB_MAX_BLOCKS = 50000; @@ -23210,18 +22940,6 @@ function setURLParameter(url, name, value) { urlParsed.setQueryParameter(name, value); return urlParsed.toString(); } -/** - * Get URL parameter by name. - * - * @export - * @param {string} url - * @param {string} name - * @returns {(string | string[] | undefined)} - */ -function getURLParameter(url, name) { - var urlParsed = coreHttp.URLBuilder.parse(url); - return urlParsed.getQueryParameterValue(name); -} /** * Set URL host. * @@ -23307,26 +23025,6 @@ function getURLQueries(url) { } return queries; } -/** - * Append a string to URL query. - * - * @export - * @param {string} url Source URL string. - * @param {string} queryParts String to be appended to the URL query. - * @returns {string} An updated URL string. - */ -function appendToURLQuery(url, queryParts) { - var urlParsed = coreHttp.URLBuilder.parse(url); - var query = urlParsed.getQuery(); - if (query) { - query += "&" + queryParts; - } - else { - query = queryParts; - } - urlParsed.setQuery(query); - return urlParsed.toString(); -} /** * Rounds a date off to seconds. * @@ -23553,7 +23251,7 @@ function toTags(tags) { * Convert BlobQueryTextConfiguration to QuerySerialization type. * * @export - * @param {(BlobQueryJsonTextConfiguration | BlobQueryCsvTextConfiguration | BlobQueryArrowConfiguration)} [textConfiguration] + * @param {(BlobQueryJsonTextConfiguration | BlobQueryCsvTextConfiguration)} [textConfiguration] * @returns {(QuerySerialization | undefined)} */ function toQuerySerialization(textConfiguration) { @@ -23583,15 +23281,6 @@ function toQuerySerialization(textConfiguration) { } } }; - case "arrow": - return { - format: { - type: "arrow", - arrowConfiguration: { - schema: textConfiguration.schema - } - } - }; default: throw Error("Invalid BlobQueryTextConfiguration."); } @@ -23632,18 +23321,6 @@ function parseObjectReplicationRecord(objectReplicationRecord) { } return orProperties; } -/** - * Attach a TokenCredential to an object. - * - * @export - * @param {T} thing - * @param {TokenCredential} credential - * @returns {T} - */ -function attachCredential(thing, credential) { - thing.credential = credential; - return thing; -} // Copyright (c) Microsoft Corporation. All rights reserved. /** @@ -23888,7 +23565,11 @@ var StorageRetryPolicy = /** @class */ (function (_super) { var retriableError = retriableErrors_1[_i]; if (err.name.toUpperCase().includes(retriableError) || err.message.toUpperCase().includes(retriableError) || - (err.code && err.code.toString().toUpperCase() === retriableError)) { + (err.code && + err.code + .toString() + .toUpperCase() + .includes(retriableError))) { logger.info("RetryPolicy: Network error " + retriableError + " found, will retry."); return true; } @@ -23909,10 +23590,6 @@ var StorageRetryPolicy = /** @class */ (function (_super) { return true; } } - if ((err === null || err === void 0 ? void 0 : err.code) === "PARSE_ERROR" && (err === null || err === void 0 ? void 0 : err.message.startsWith("Error \"Error: Unclosed root tag"))) { - logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry."); - return true; - } return false; }; /** @@ -24172,7 +23849,9 @@ var TelemetryPolicyFactory = /** @class */ (function () { var userAgentInfo = []; { if (telemetry) { - var telemetryString = telemetry.userAgentPrefix || ""; + // FIXME: replace() only replaces the first space. And we have no idea why we need to replace spaces in the first place. + // But fixing this would be a breaking change. Logged an issue here: https://github.com/Azure/azure-sdk-for-js/issues/10793 + var telemetryString = (telemetry.userAgentPrefix || "").replace(" ", ""); if (telemetryString.length > 0 && userAgentInfo.indexOf(telemetryString) === -1) { userAgentInfo.push(telemetryString); } @@ -24275,11 +23954,8 @@ function newPipeline(credential, pipelineOptions) { telemetryPolicy, coreHttp.generateClientRequestIdPolicy(), new StorageBrowserPolicyFactory(), + coreHttp.deserializationPolicy(), new StorageRetryPolicyFactory(pipelineOptions.retryOptions), - // Default deserializationPolicy is provided by protocol layer - // Use customized XML char key of "#" so we could deserialize metadata - // with "_" key - coreHttp.deserializationPolicy(undefined, { xmlCharKey: "#" }), coreHttp.logPolicy({ logger: logger.info, allowedHeaderNames: StorageBlobLoggingAllowedHeaderNames, @@ -24292,12 +23968,13 @@ function newPipeline(credential, pipelineOptions) { factories.push(coreHttp.disableResponseDecompressionPolicy()); } factories.push(coreHttp.isTokenCredential(credential) - ? attachCredential(coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes), credential) + ? coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes) : credential); return new Pipeline(factories, pipelineOptions); } // Copyright (c) Microsoft Corporation. All rights reserved. +var ABORT_ERROR = new abortController.AbortError("The operation was aborted."); /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -24321,9 +23998,36 @@ var RetriableReadableStream = /** @class */ (function (_super) { */ function RetriableReadableStream(source, getter, offset, count, options) { if (options === void 0) { options = {}; } - var _this = _super.call(this, { highWaterMark: options.highWaterMark }) || this; + var _this = _super.call(this) || this; _this.retries = 0; - _this.sourceDataHandler = function (data) { + _this.abortHandler = function () { + _this.source.pause(); + _this.emit("error", ABORT_ERROR); + }; + _this.aborter = options.abortSignal || abortController.AbortSignal.none; + _this.getter = getter; + _this.source = source; + _this.start = offset; + _this.offset = offset; + _this.end = offset + count - 1; + _this.maxRetryRequests = + options.maxRetryRequests && options.maxRetryRequests >= 0 ? options.maxRetryRequests : 0; + _this.onProgress = options.onProgress; + _this.options = options; + _this.aborter.addEventListener("abort", _this.abortHandler); + _this.setSourceDataHandler(); + _this.setSourceEndHandler(); + _this.setSourceErrorHandler(); + return _this; + } + RetriableReadableStream.prototype._read = function () { + if (!this.aborter.aborted) { + this.source.resume(); + } + }; + RetriableReadableStream.prototype.setSourceDataHandler = function () { + var _this = this; + this.source.on("data", function (data) { if (_this.options.doInjectErrorOnce) { _this.options.doInjectErrorOnce = undefined; _this.source.pause(); @@ -24341,19 +24045,18 @@ var RetriableReadableStream = /** @class */ (function (_super) { if (!_this.push(data)) { _this.source.pause(); } - }; - _this.sourceErrorOrEndHandler = function (err) { - if (err && err.name === "AbortError") { - _this.destroy(err); - return; - } + }); + }; + RetriableReadableStream.prototype.setSourceEndHandler = function () { + var _this = this; + this.source.on("end", function () { // console.log( - // `Source stream emits end or error, offset: ${ + // `Source stream emits end, offset: ${ // this.offset // }, dest end : ${this.end}` // ); - _this.removeSourceEventHandlers(); if (_this.offset - 1 === _this.end) { + _this.aborter.removeEventListener("abort", _this.abortHandler); _this.push(null); } else if (_this.offset <= _this.end) { @@ -24365,53 +24068,31 @@ var RetriableReadableStream = /** @class */ (function (_super) { _this.getter(_this.offset) .then(function (newSource) { _this.source = newSource; - _this.setSourceEventHandlers(); + _this.setSourceDataHandler(); + _this.setSourceEndHandler(); + _this.setSourceErrorHandler(); }) .catch(function (error) { - _this.destroy(error); + _this.emit("error", error); }); } else { - _this.destroy(new Error( + _this.emit("error", new Error( // tslint:disable-next-line:max-line-length "Data corruption failure: received less data than required and reached maxRetires limitation. Received data offset: " + (_this .offset - 1) + ", data needed offset: " + _this.end + ", retries: " + _this.retries + ", max retries: " + _this.maxRetryRequests)); } } else { - _this.destroy(new Error("Data corruption failure: Received more data than original request, data needed offset is " + _this.end + ", received offset: " + (_this.offset - 1))); + _this.emit("error", new Error("Data corruption failure: Received more data than original request, data needed offset is " + _this.end + ", received offset: " + (_this.offset - 1))); } - }; - _this.getter = getter; - _this.source = source; - _this.start = offset; - _this.offset = offset; - _this.end = offset + count - 1; - _this.maxRetryRequests = - options.maxRetryRequests && options.maxRetryRequests >= 0 ? options.maxRetryRequests : 0; - _this.onProgress = options.onProgress; - _this.options = options; - _this.setSourceEventHandlers(); - return _this; - } - RetriableReadableStream.prototype._read = function () { - this.source.resume(); - }; - RetriableReadableStream.prototype.setSourceEventHandlers = function () { - this.source.on("data", this.sourceDataHandler); - this.source.on("end", this.sourceErrorOrEndHandler); - this.source.on("error", this.sourceErrorOrEndHandler); - }; - RetriableReadableStream.prototype.removeSourceEventHandlers = function () { - this.source.removeListener("data", this.sourceDataHandler); - this.source.removeListener("end", this.sourceErrorOrEndHandler); - this.source.removeListener("error", this.sourceErrorOrEndHandler); + }); }; - RetriableReadableStream.prototype._destroy = function (error, callback) { - // remove listener from source and release source - this.removeSourceEventHandlers(); - this.source.destroy(); - callback(error === null ? undefined : error); + RetriableReadableStream.prototype.setSourceErrorHandler = function () { + var _this = this; + this.source.on("error", function (error) { + _this.emit("error", error); + }); }; return RetriableReadableStream; }(stream.Readable)); @@ -24887,21 +24568,6 @@ var BlobDownloadResponse = /** @class */ (function () { enumerable: false, configurable: true }); - Object.defineProperty(BlobDownloadResponse.prototype, "lastAccessed", { - /** - * Returns the UTC date and time generated by the service that indicates the time at which the blob was - * last read or written to. - * - * @readonly - * @type {(Date | undefined)} - * @memberof BlobDownloadResponse - */ - get: function () { - return this.originalResponse.lastAccessed; - }, - enumerable: false, - configurable: true - }); Object.defineProperty(BlobDownloadResponse.prototype, "metadata", { /** * A name-value pair @@ -25870,7 +25536,7 @@ var AvroReadable = /** @class */ (function () { }()); // Copyright (c) Microsoft Corporation. -var ABORT_ERROR = new abortController.AbortError("Reading from the avro stream was aborted."); +var ABORT_ERROR$1 = new abortController.AbortError("Reading from the avro stream was aborted."); var AvroReadableFromStream = /** @class */ (function (_super) { tslib.__extends(AvroReadableFromStream, _super); function AvroReadableFromStream(readable) { @@ -25900,7 +25566,7 @@ var AvroReadableFromStream = /** @class */ (function (_super) { var _this = this; return tslib.__generator(this, function (_b) { if ((_a = options.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { - throw ABORT_ERROR; + throw ABORT_ERROR$1; } if (size < 0) { throw new Error("size parameter should be positive: " + size); @@ -25944,7 +25610,7 @@ var AvroReadableFromStream = /** @class */ (function (_super) { }; var abortHandler = function () { cleanUp(); - reject(ABORT_ERROR); + reject(ABORT_ERROR$1); }; _this._readable.on("readable", readableCallback); _this._readable.once("error", rejectCallback); @@ -25982,7 +25648,6 @@ var BlobQuickQueryStream = /** @class */ (function (_super) { function BlobQuickQueryStream(source, options) { if (options === void 0) { options = {}; } var _this = _super.call(this) || this; - _this.avroPaused = true; _this.source = source; _this.onProgress = options.onProgress; _this.onError = options.onError; @@ -25992,31 +25657,29 @@ var BlobQuickQueryStream = /** @class */ (function (_super) { } BlobQuickQueryStream.prototype._read = function () { var _this = this; - if (this.avroPaused) { - this.readInternal().catch(function (err) { - _this.emit("error", err); - }); - } + this.readInternal().catch(function (err) { + _this.emit("error", err); + }); }; BlobQuickQueryStream.prototype.readInternal = function () { + var e_1, _a; return tslib.__awaiter(this, void 0, void 0, function () { - var avroNext, obj, schema, data, bytesScanned, totalBytes, fatal, name_1, description, position; - return tslib.__generator(this, function (_a) { - switch (_a.label) { + var _b, _c, obj, schema, exit, data, bytesScanned, totalBytes, fatal, name_1, description, position, e_1_1; + return tslib.__generator(this, function (_d) { + switch (_d.label) { case 0: - this.avroPaused = false; - _a.label = 1; - case 1: return [4 /*yield*/, this.avroIter.next()]; + _d.trys.push([0, 5, 6, 11]); + _b = tslib.__asyncValues(this.avroIter); + _d.label = 1; + case 1: return [4 /*yield*/, _b.next()]; case 2: - avroNext = _a.sent(); - if (avroNext.done) { - return [3 /*break*/, 4]; - } - obj = avroNext.value; + if (!(_c = _d.sent(), !_c.done)) return [3 /*break*/, 4]; + obj = _c.value; schema = obj.$schema; if (typeof schema !== "string") { throw Error("Missing schema in avro record."); } + exit = false; switch (schema) { case "com.microsoft.azure.storage.queryBlobContents.resultData": data = obj.data; @@ -26024,7 +25687,7 @@ var BlobQuickQueryStream = /** @class */ (function (_super) { throw Error("Invalid data in avro result record."); } if (!this.push(Buffer.from(data))) { - this.avroPaused = true; + exit = true; } break; case "com.microsoft.azure.storage.queryBlobContents.progress": @@ -26075,11 +25738,29 @@ var BlobQuickQueryStream = /** @class */ (function (_super) { default: throw Error("Unknown schema " + schema + " in avro progress record."); } - _a.label = 3; - case 3: - if (!avroNext.done && !this.avroPaused) return [3 /*break*/, 1]; - _a.label = 4; - case 4: return [2 /*return*/]; + if (exit) { + return [3 /*break*/, 4]; + } + _d.label = 3; + case 3: return [3 /*break*/, 1]; + case 4: return [3 /*break*/, 11]; + case 5: + e_1_1 = _d.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 11]; + case 6: + _d.trys.push([6, , 9, 10]); + if (!(_c && !_c.done && (_a = _b.return))) return [3 /*break*/, 8]; + return [4 /*yield*/, _a.call(_b)]; + case 7: + _d.sent(); + _d.label = 8; + case 8: return [3 /*break*/, 10]; + case 9: + if (e_1) throw e_1.error; + return [7 /*endfinally*/]; + case 10: return [7 /*endfinally*/]; + case 11: return [2 /*return*/]; } }); }); @@ -26891,7 +26572,7 @@ var StorageSharedKeyCredential = /** @class */ (function (_super) { * regenerated. */ var packageName = "azure-storage-blob"; -var packageVersion = "12.4.1"; +var packageVersion = "12.2.1"; var StorageClientContext = /** @class */ (function (_super) { tslib.__extends(StorageClientContext, _super); /** @@ -26913,7 +26594,7 @@ var StorageClientContext = /** @class */ (function (_super) { options.userAgent = packageName + "/" + packageVersion + " " + defaultUserAgent; } _this = _super.call(this, undefined, options) || this; - _this.version = '2020-04-08'; + _this.version = "2019-12-12"; _this.baseUri = "{url}"; _this.requestContentType = "application/json; charset=utf-8"; _this.url = url; @@ -27026,7 +26707,7 @@ function rangeResponseFromModel(response) { * This is the poller returned by {@link BlobClient.beginCopyFromURL}. * This can not be instantiated directly outside of this package. * - * @hidden + * @ignore */ var BlobBeginCopyFromUrlPoller = /** @class */ (function (_super) { tslib.__extends(BlobBeginCopyFromUrlPoller, _super); @@ -27056,7 +26737,7 @@ var BlobBeginCopyFromUrlPoller = /** @class */ (function (_super) { * Note: Intentionally using function expression over arrow function expression * so that the function can be invoked with a different context. * This affects what `this` refers to. - * @hidden + * @ignore */ var cancel = function cancel(options) { if (options === void 0) { options = {}; } @@ -27091,7 +26772,7 @@ var cancel = function cancel(options) { * Note: Intentionally using function expression over arrow function expression * so that the function can be invoked with a different context. * This affects what `this` refers to. - * @hidden + * @ignore */ var update = function update(options) { if (options === void 0) { options = {}; } @@ -27156,7 +26837,7 @@ var update = function update(options) { * Note: Intentionally using function expression over arrow function expression * so that the function can be invoked with a different context. * This affects what `this` refers to. - * @hidden + * @ignore */ var toString = function toString() { return JSON.stringify({ state: this.state }, function (key, value) { @@ -27169,7 +26850,7 @@ var toString = function toString() { }; /** * Creates a poll operation given the provided state. - * @hidden + * @ignore */ function makeBlobBeginCopyFromURLPollOperation(state) { return { @@ -27229,14 +26910,10 @@ var StorageClient = /** @class */ (function () { for (var _i = 0, _a = this.pipeline.factories; _i < _a.length; _i++) { var factory = _a[_i]; if ((coreHttp.isNode && factory instanceof StorageSharedKeyCredential) || - factory instanceof AnonymousCredential) { + factory instanceof AnonymousCredential || + coreHttp.isTokenCredential(factory)) { this.credential = factory; } - else if (coreHttp.isTokenCredential(factory.credential)) { - // Only works if the factory has been attached a "credential" property. - // We do that in newPipeline() when using TokenCredential. - this.credential = factory.credential; - } } // Override protocol layer's default content-type var storageClientContext = this.storageClientContext; @@ -28085,1520 +27762,424 @@ function readStreamToLocalFile(rs, file) { var fsStat = util.promisify(fs.stat); var fsCreateReadStream = fs.createReadStream; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. /** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a blob. Setting - * a value to true means that any SAS which uses these permissions will grant permissions for that operation. Once all - * the values are set, this should be serialized with toString and set as the permissions field on a - * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but - * the order of the permissions is particular and this class guarantees correctness. + * A BlobClient represents a URL to an Azure Storage blob; the blob may be a block blob, + * append blob, or page blob. * * @export - * @class BlobSASPermissions + * @class BlobClient */ -var BlobSASPermissions = /** @class */ (function () { - function BlobSASPermissions() { - /** - * Specifies Read access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.read = false; - /** - * Specifies Add access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.add = false; - /** - * Specifies Create access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.create = false; - /** - * Specifies Write access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.write = false; - /** - * Specifies Delete access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.delete = false; - /** - * Specifies Delete version access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.deleteVersion = false; - /** - * Specfies Tag access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.tag = false; +var BlobClient = /** @class */ (function (_super) { + tslib.__extends(BlobClient, _super); + function BlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { + var _a; + var _this = this; + options = options || {}; + var pipeline; + var url; + if (credentialOrPipelineOrContainerName instanceof Pipeline) { + // (url: string, pipeline: Pipeline) + url = urlOrConnectionString; + pipeline = credentialOrPipelineOrContainerName; + } + else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || + credentialOrPipelineOrContainerName instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + url = urlOrConnectionString; + options = blobNameOrOptions; + pipeline = newPipeline(credentialOrPipelineOrContainerName, options); + } + else if (!credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName !== "string") { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + // The second parameter is undefined. Use anonymous credential. + url = urlOrConnectionString; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else if (credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName === "string" && + blobNameOrOptions && + typeof blobNameOrOptions === "string") { + // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) + var containerName = credentialOrPipelineOrContainerName; + var blobName = blobNameOrOptions; + var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + if (extractedCreds.kind === "AccountConnString") { + { + var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); + options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); + pipeline = newPipeline(sharedKeyCredential, options); + } + } + else if (extractedCreds.kind === "SASConnString") { + url = + appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + + "?" + + extractedCreds.accountSas; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } + else { + throw new Error("Expecting non-empty strings for containerName and blobName parameters"); + } + _this = _super.call(this, url, pipeline) || this; + (_a = _this.getBlobAndContainerNamesFromUrl(), _this._name = _a.blobName, _this._containerName = _a.containerName); + _this.blobContext = new Blob$1(_this.storageClientContext); + return _this; + } + Object.defineProperty(BlobClient.prototype, "name", { /** - * Specifies Move access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions + * The name of the blob. */ - this.move = false; + get: function () { + return this._name; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobClient.prototype, "containerName", { /** - * Specifies Execute access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions + * The name of the storage container the blob is associated with. */ - this.execute = false; - } + get: function () { + return this._containerName; + }, + enumerable: false, + configurable: true + }); /** - * Creates a {@link BlobSASPermissions} from the specified permissions string. This method will throw an - * Error if it encounters a character that does not correspond to a valid permission. + * Creates a new BlobClient object identical to the source but with the specified snapshot timestamp. + * Provide "" will remove the snapshot and return a Client to the base blob. * - * @static - * @param {string} permissions - * @returns {BlobSASPermissions} - * @memberof BlobSASPermissions + * @param {string} snapshot The snapshot timestamp. + * @returns {BlobClient} A new BlobClient object identical to the source but with the specified snapshot timestamp + * @memberof BlobClient */ - BlobSASPermissions.parse = function (permissions) { - var blobSASPermissions = new BlobSASPermissions(); - for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { - var char = permissions_1[_i]; - switch (char) { - case "r": - blobSASPermissions.read = true; - break; - case "a": - blobSASPermissions.add = true; - break; - case "c": - blobSASPermissions.create = true; - break; - case "w": - blobSASPermissions.write = true; - break; - case "d": - blobSASPermissions.delete = true; - break; - case "x": - blobSASPermissions.deleteVersion = true; - break; - case "t": - blobSASPermissions.tag = true; - break; - case "m": - blobSASPermissions.move = true; - break; - case "e": - blobSASPermissions.execute = true; - break; - default: - throw new RangeError("Invalid permission: " + char); - } - } - return blobSASPermissions; + BlobClient.prototype.withSnapshot = function (snapshot) { + return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); }; /** - * Creates a {@link BlobSASPermissions} from a raw object which contains same keys as it - * and boolean values for them. + * Creates a new BlobClient object pointing to a version of this blob. + * Provide "" will remove the versionId and return a Client to the base blob. * - * @static - * @param {BlobSASPermissionsLike} permissionLike - * @returns {BlobSASPermissions} - * @memberof BlobSASPermissions + * @param {string} versionId The versionId. + * @returns {BlobClient} A new BlobClient object pointing to the version of this blob. + * @memberof BlobClient */ - BlobSASPermissions.from = function (permissionLike) { - var blobSASPermissions = new BlobSASPermissions(); - if (permissionLike.read) { - blobSASPermissions.read = true; - } - if (permissionLike.add) { - blobSASPermissions.add = true; - } - if (permissionLike.create) { - blobSASPermissions.create = true; - } - if (permissionLike.write) { - blobSASPermissions.write = true; - } - if (permissionLike.delete) { - blobSASPermissions.delete = true; - } - if (permissionLike.deleteVersion) { - blobSASPermissions.deleteVersion = true; - } - if (permissionLike.tag) { - blobSASPermissions.tag = true; - } - if (permissionLike.move) { - blobSASPermissions.move = true; - } - if (permissionLike.execute) { - blobSASPermissions.execute = true; - } - return blobSASPermissions; + BlobClient.prototype.withVersion = function (versionId) { + return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.VERSIONID, versionId.length === 0 ? undefined : versionId), this.pipeline); }; /** - * Converts the given permissions to a string. Using this method will guarantee the permissions are in an - * order accepted by the service. + * Creates a AppendBlobClient object. * - * @returns {string} A string which represents the BlobSASPermissions - * @memberof BlobSASPermissions + * @returns {AppendBlobClient} + * @memberof BlobClient */ - BlobSASPermissions.prototype.toString = function () { - var permissions = []; - if (this.read) { - permissions.push("r"); - } - if (this.add) { - permissions.push("a"); - } - if (this.create) { - permissions.push("c"); - } - if (this.write) { - permissions.push("w"); - } - if (this.delete) { - permissions.push("d"); - } - if (this.deleteVersion) { - permissions.push("x"); - } - if (this.tag) { - permissions.push("t"); - } - if (this.move) { - permissions.push("m"); - } - if (this.execute) { - permissions.push("e"); - } - return permissions.join(""); + BlobClient.prototype.getAppendBlobClient = function () { + return new AppendBlobClient(this.url, this.pipeline); }; - return BlobSASPermissions; -}()); - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -/** - * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a container. - * Setting a value to true means that any SAS which uses these permissions will grant permissions for that operation. - * Once all the values are set, this should be serialized with toString and set as the permissions field on a - * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but - * the order of the permissions is particular and this class guarantees correctness. - * - * @export - * @class ContainerSASPermissions - */ -var ContainerSASPermissions = /** @class */ (function () { - function ContainerSASPermissions() { - /** - * Specifies Read access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.read = false; - /** - * Specifies Add access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.add = false; - /** - * Specifies Create access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.create = false; - /** - * Specifies Write access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.write = false; - /** - * Specifies Delete access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.delete = false; - /** - * Specifies Delete version access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.deleteVersion = false; - /** - * Specifies List access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.list = false; - /** - * Specfies Tag access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.tag = false; - /** - * Specifies Move access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.move = false; - /** - * Specifies Execute access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.execute = false; - } /** - * Creates an {@link ContainerSASPermissions} from the specified permissions string. This method will throw an - * Error if it encounters a character that does not correspond to a valid permission. + * Creates a BlockBlobClient object. * - * @static - * @param {string} permissions - * @returns {ContainerSASPermissions} - * @memberof ContainerSASPermissions + * @returns {BlockBlobClient} + * @memberof BlobClient */ - ContainerSASPermissions.parse = function (permissions) { - var containerSASPermissions = new ContainerSASPermissions(); - for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { - var char = permissions_1[_i]; - switch (char) { - case "r": - containerSASPermissions.read = true; - break; - case "a": - containerSASPermissions.add = true; - break; - case "c": - containerSASPermissions.create = true; - break; - case "w": - containerSASPermissions.write = true; - break; - case "d": - containerSASPermissions.delete = true; - break; - case "l": - containerSASPermissions.list = true; - break; - case "t": - containerSASPermissions.tag = true; - break; - case "x": - containerSASPermissions.deleteVersion = true; - break; - case "m": - containerSASPermissions.move = true; - break; - case "e": - containerSASPermissions.execute = true; - break; - default: - throw new RangeError("Invalid permission " + char); - } - } - return containerSASPermissions; + BlobClient.prototype.getBlockBlobClient = function () { + return new BlockBlobClient(this.url, this.pipeline); }; /** - * Creates a {@link ContainerSASPermissions} from a raw object which contains same keys as it - * and boolean values for them. + * Creates a PageBlobClient object. * - * @static - * @param {ContainerSASPermissionsLike} permissionLike - * @returns {ContainerSASPermissions} - * @memberof ContainerSASPermissions + * @returns {PageBlobClient} + * @memberof BlobClient */ - ContainerSASPermissions.from = function (permissionLike) { - var containerSASPermissions = new ContainerSASPermissions(); - if (permissionLike.read) { - containerSASPermissions.read = true; - } - if (permissionLike.add) { - containerSASPermissions.add = true; - } - if (permissionLike.create) { - containerSASPermissions.create = true; - } - if (permissionLike.write) { - containerSASPermissions.write = true; - } - if (permissionLike.delete) { - containerSASPermissions.delete = true; - } - if (permissionLike.list) { - containerSASPermissions.list = true; - } - if (permissionLike.deleteVersion) { - containerSASPermissions.deleteVersion = true; - } - if (permissionLike.tag) { - containerSASPermissions.tag = true; - } - if (permissionLike.move) { - containerSASPermissions.move = true; - } - if (permissionLike.execute) { - containerSASPermissions.execute = true; - } - return containerSASPermissions; + BlobClient.prototype.getPageBlobClient = function () { + return new PageBlobClient(this.url, this.pipeline); }; /** - * Converts the given permissions to a string. Using this method will guarantee the permissions are in an - * order accepted by the service. + * Reads or downloads a blob from the system, including its metadata and properties. + * You can also call Get Blob to read a snapshot. * - * The order of the characters should be as specified here to ensure correctness. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas + * * In Node.js, data returns in a Readable stream readableStreamBody + * * In browsers, data returns in a promise blobBody * - * @returns {string} - * @memberof ContainerSASPermissions + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob + * + * @param {number} [offset] From which position of the blob to download, >= 0 + * @param {number} [count] How much data to be downloaded, > 0. Will download to the end when undefined + * @param {BlobDownloadOptions} [options] Optional options to Blob Download operation. + * @returns {Promise} + * @memberof BlobClient + * + * Example usage (Node.js): + * + * ```js + * // Download and convert a blob to a string + * const downloadBlockBlobResponse = await blobClient.download(); + * const downloaded = await streamToBuffer(downloadBlockBlobResponse.readableStreamBody); + * console.log("Downloaded blob content:", downloaded.toString()); + * + * async function streamToBuffer(readableStream) { + * return new Promise((resolve, reject) => { + * const chunks = []; + * readableStream.on("data", (data) => { + * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); + * }); + * readableStream.on("end", () => { + * resolve(Buffer.concat(chunks)); + * }); + * readableStream.on("error", reject); + * }); + * } + * ``` + * + * Example usage (browser): + * + * ```js + * // Download and convert a blob to a string + * const downloadBlockBlobResponse = await blobClient.download(); + * const downloaded = await blobToString(await downloadBlockBlobResponse.blobBody); + * console.log( + * "Downloaded blob content", + * downloaded + * ); + * + * async function blobToString(blob: Blob): Promise { + * const fileReader = new FileReader(); + * return new Promise((resolve, reject) => { + * fileReader.onloadend = (ev: any) => { + * resolve(ev.target!.result); + * }; + * fileReader.onerror = reject; + * fileReader.readAsText(blob); + * }); + * } + * ``` */ - ContainerSASPermissions.prototype.toString = function () { - var permissions = []; - if (this.read) { - permissions.push("r"); - } - if (this.add) { - permissions.push("a"); - } - if (this.create) { - permissions.push("c"); - } - if (this.write) { - permissions.push("w"); - } - if (this.delete) { - permissions.push("d"); - } - if (this.deleteVersion) { - permissions.push("x"); - } - if (this.list) { - permissions.push("l"); - } - if (this.tag) { - permissions.push("t"); - } - if (this.move) { - permissions.push("m"); - } - if (this.execute) { - permissions.push("e"); - } - return permissions.join(""); + BlobClient.prototype.download = function (offset, count, options) { + var _a; + if (offset === void 0) { offset = 0; } + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, res_1, wrappedRes, e_1; + var _this = this; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + _b = createSpan("BlobClient-download", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.blobContext.download({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + onDownloadProgress: coreHttp.isNode ? undefined : options.onProgress, + range: offset === 0 && !count ? undefined : rangeToString({ offset: offset, count: count }), + rangeGetContentMD5: options.rangeGetContentMD5, + rangeGetContentCRC64: options.rangeGetContentCrc64, + snapshot: options.snapshot, + cpkInfo: options.customerProvidedKey, + spanOptions: spanOptions + })]; + case 2: + res_1 = _c.sent(); + wrappedRes = tslib.__assign(tslib.__assign({}, res_1), { _response: res_1._response, objectReplicationDestinationPolicyId: res_1.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res_1.objectReplicationRules) }); + // We support retrying when download stream unexpected ends in Node.js runtime + // Following code shouldn't be bundled into browser build, however some + // bundlers may try to bundle following code and "FileReadResponse.ts". + // In this case, "FileDownloadResponse.browser.ts" will be used as a shim of "FileDownloadResponse.ts" + // The config is in package.json "browser" field + if (options.maxRetryRequests === undefined || options.maxRetryRequests < 0) { + // TODO: Default value or make it a required parameter? + options.maxRetryRequests = DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS; + } + if (res_1.contentLength === undefined) { + throw new RangeError("File download response doesn't contain valid content length header"); + } + if (!res_1.etag) { + throw new RangeError("File download response doesn't contain valid etag header"); + } + return [2 /*return*/, new BlobDownloadResponse(wrappedRes, function (start) { return tslib.__awaiter(_this, void 0, void 0, function () { + var updatedOptions; + var _a; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + updatedOptions = { + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ifMatch: options.conditions.ifMatch || res_1.etag, + ifModifiedSince: options.conditions.ifModifiedSince, + ifNoneMatch: options.conditions.ifNoneMatch, + ifUnmodifiedSince: options.conditions.ifUnmodifiedSince, + ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions + }, + range: rangeToString({ + count: offset + res_1.contentLength - start, + offset: start + }), + rangeGetContentMD5: options.rangeGetContentMD5, + rangeGetContentCRC64: options.rangeGetContentCrc64, + snapshot: options.snapshot, + cpkInfo: options.customerProvidedKey + }; + return [4 /*yield*/, this.blobContext.download(tslib.__assign({ abortSignal: options.abortSignal }, updatedOptions))]; + case 1: + // Debug purpose only + // console.log( + // `Read from internal stream, range: ${ + // updatedOptions.range + // }, options: ${JSON.stringify(updatedOptions)}` + // ); + return [2 /*return*/, (_b.sent()).readableStreamBody]; + } + }); + }); }, offset, res_1.contentLength, { + abortSignal: options.abortSignal, + maxRetryRequests: options.maxRetryRequests, + onProgress: options.onProgress + })]; + case 3: + e_1 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_1.message + }); + throw e_1; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; - return ContainerSASPermissions; -}()); - -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * UserDelegationKeyCredential is only used for generation of user delegation SAS. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas - * - * @export - * @class UserDelegationKeyCredential - */ -var UserDelegationKeyCredential = /** @class */ (function () { - /** - * Creates an instance of UserDelegationKeyCredential. - * @param {string} accountName - * @param {UserDelegationKey} userDelegationKey - * @memberof UserDelegationKeyCredential - */ - function UserDelegationKeyCredential(accountName, userDelegationKey) { - this.accountName = accountName; - this.userDelegationKey = userDelegationKey; - this.key = Buffer.from(userDelegationKey.value, "base64"); - } /** - * Generates a hash signature for an HTTP request or for a SAS. + * Returns true if the Azure blob resource represented by this client exists; false otherwise. * - * @param {string} stringToSign - * @returns {string} - * @memberof UserDelegationKeyCredential + * NOTE: use this function with care since an existing blob might be deleted by other clients or + * applications. Vice versa new blobs might be added by other clients or applications after this + * function completes. + * + * @param {BlobExistsOptions} [options] options to Exists operation. + * @returns {Promise} + * @memberof BlobClient */ - UserDelegationKeyCredential.prototype.computeHMACSHA256 = function (stringToSign) { - // console.log(`stringToSign: ${JSON.stringify(stringToSign)}`); - return crypto.createHmac("sha256", this.key) - .update(stringToSign, "utf8") - .digest("base64"); + BlobClient.prototype.exists = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_2; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobClient-exists", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.getProperties({ + abortSignal: options.abortSignal, + customerProvidedKey: options.customerProvidedKey, + conditions: options.conditions, + tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) + })]; + case 2: + _b.sent(); + return [2 /*return*/, true]; + case 3: + e_2 = _b.sent(); + if (e_2.statusCode === 404) { + span.setStatus({ + code: api.CanonicalCode.NOT_FOUND, + message: "Expected exception when checking blob existence" + }); + return [2 /*return*/, false]; + } + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_2.message + }); + throw e_2; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; - return UserDelegationKeyCredential; -}()); - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -/** - * Generate SasIPRange format string. For example: - * - * "8.8.8.8" or "1.1.1.1-255.255.255.255" - * - * @export - * @param {SasIPRange} ipRange - * @returns {string} - */ -function ipRangeToString(ipRange) { - return ipRange.end ? ipRange.start + "-" + ipRange.end : ipRange.start; -} - -// Copyright (c) Microsoft Corporation. All rights reserved. -(function (SASProtocol) { /** - * Protocol that allows HTTPS only + * Returns all user-defined metadata, standard HTTP properties, and system properties + * for the blob. It does not return the content of the blob. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-properties + * + * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if + * they originally contained uppercase characters. This differs from the metadata keys returned by + * the methods of {@link ContainerClient} that list blobs using the `includeMetadata` option, which + * will retain their original casing. + * + * @param {BlobGetPropertiesOptions} [options] Optional options to Get Properties operation. + * @returns {Promise} + * @memberof BlobClient */ - SASProtocol["Https"] = "https"; + BlobClient.prototype.getProperties = function (options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, res, e_3; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _b = createSpan("BlobClient-getProperties", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blobContext.getProperties({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, + spanOptions: spanOptions + })]; + case 2: + res = _c.sent(); + return [2 /*return*/, tslib.__assign(tslib.__assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) })]; + case 3: + e_3 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_3.message + }); + throw e_3; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; /** - * Protocol that allows both HTTPS and HTTP - */ - SASProtocol["HttpsAndHttp"] = "https,http"; -})(exports.SASProtocol || (exports.SASProtocol = {})); -/** - * Represents the components that make up an Azure Storage SAS' query parameters. This type is not constructed directly - * by the user; it is only generated by the {@link AccountSASSignatureValues} and {@link BlobSASSignatureValues} - * types. Once generated, it can be encoded into a {@code String} and appended to a URL directly (though caution should - * be taken here in case there are existing query parameters, which might affect the appropriate means of appending - * these query parameters). - * - * NOTE: Instances of this class are immutable. - * - * @export - * @class SASQueryParameters - */ -var SASQueryParameters = /** @class */ (function () { - function SASQueryParameters(version, signature, permissionsOrOptions, services, resourceTypes, protocol, startsOn, expiresOn, ipRange, identifier, resource, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType, userDelegationKey, preauthorizedAgentObjectId, correlationId) { - this.version = version; - this.signature = signature; - if (permissionsOrOptions !== undefined && typeof permissionsOrOptions !== "string") { - // SASQueryParametersOptions - this.permissions = permissionsOrOptions.permissions; - this.services = permissionsOrOptions.services; - this.resourceTypes = permissionsOrOptions.resourceTypes; - this.protocol = permissionsOrOptions.protocol; - this.startsOn = permissionsOrOptions.startsOn; - this.expiresOn = permissionsOrOptions.expiresOn; - this.ipRangeInner = permissionsOrOptions.ipRange; - this.identifier = permissionsOrOptions.identifier; - this.resource = permissionsOrOptions.resource; - this.cacheControl = permissionsOrOptions.cacheControl; - this.contentDisposition = permissionsOrOptions.contentDisposition; - this.contentEncoding = permissionsOrOptions.contentEncoding; - this.contentLanguage = permissionsOrOptions.contentLanguage; - this.contentType = permissionsOrOptions.contentType; - if (permissionsOrOptions.userDelegationKey) { - this.signedOid = permissionsOrOptions.userDelegationKey.signedObjectId; - this.signedTenantId = permissionsOrOptions.userDelegationKey.signedTenantId; - this.signedStartsOn = permissionsOrOptions.userDelegationKey.signedStartsOn; - this.signedExpiresOn = permissionsOrOptions.userDelegationKey.signedExpiresOn; - this.signedService = permissionsOrOptions.userDelegationKey.signedService; - this.signedVersion = permissionsOrOptions.userDelegationKey.signedVersion; - this.preauthorizedAgentObjectId = permissionsOrOptions.preauthorizedAgentObjectId; - this.correlationId = permissionsOrOptions.correlationId; - } - } - else { - this.services = services; - this.resourceTypes = resourceTypes; - this.expiresOn = expiresOn; - this.permissions = permissionsOrOptions; - this.protocol = protocol; - this.startsOn = startsOn; - this.ipRangeInner = ipRange; - this.identifier = identifier; - this.resource = resource; - this.cacheControl = cacheControl; - this.contentDisposition = contentDisposition; - this.contentEncoding = contentEncoding; - this.contentLanguage = contentLanguage; - this.contentType = contentType; - if (userDelegationKey) { - this.signedOid = userDelegationKey.signedObjectId; - this.signedTenantId = userDelegationKey.signedTenantId; - this.signedStartsOn = userDelegationKey.signedStartsOn; - this.signedExpiresOn = userDelegationKey.signedExpiresOn; - this.signedService = userDelegationKey.signedService; - this.signedVersion = userDelegationKey.signedVersion; - this.preauthorizedAgentObjectId = preauthorizedAgentObjectId; - this.correlationId = correlationId; - } - } - } - Object.defineProperty(SASQueryParameters.prototype, "ipRange", { - /** - * Optional. IP range allowed for this SAS. - * - * @readonly - * @type {(SasIPRange | undefined)} - * @memberof SASQueryParameters - */ - get: function () { - if (this.ipRangeInner) { - return { - end: this.ipRangeInner.end, - start: this.ipRangeInner.start - }; - } - return undefined; - }, - enumerable: false, - configurable: true - }); - /** - * Encodes all SAS query parameters into a string that can be appended to a URL. - * - * @returns {string} - * @memberof SASQueryParameters - */ - SASQueryParameters.prototype.toString = function () { - var params = [ - "sv", - "ss", - "srt", - "spr", - "st", - "se", - "sip", - "si", - "skoid", - "sktid", - "skt", - "ske", - "sks", - "skv", - "sr", - "sp", - "sig", - "rscc", - "rscd", - "rsce", - "rscl", - "rsct", - "saoid", - "scid" - ]; - var queries = []; - for (var _i = 0, params_1 = params; _i < params_1.length; _i++) { - var param = params_1[_i]; - switch (param) { - case "sv": - this.tryAppendQueryParameter(queries, param, this.version); - break; - case "ss": - this.tryAppendQueryParameter(queries, param, this.services); - break; - case "srt": - this.tryAppendQueryParameter(queries, param, this.resourceTypes); - break; - case "spr": - this.tryAppendQueryParameter(queries, param, this.protocol); - break; - case "st": - this.tryAppendQueryParameter(queries, param, this.startsOn ? truncatedISO8061Date(this.startsOn, false) : undefined); - break; - case "se": - this.tryAppendQueryParameter(queries, param, this.expiresOn ? truncatedISO8061Date(this.expiresOn, false) : undefined); - break; - case "sip": - this.tryAppendQueryParameter(queries, param, this.ipRange ? ipRangeToString(this.ipRange) : undefined); - break; - case "si": - this.tryAppendQueryParameter(queries, param, this.identifier); - break; - case "skoid": // Signed object ID - this.tryAppendQueryParameter(queries, param, this.signedOid); - break; - case "sktid": // Signed tenant ID - this.tryAppendQueryParameter(queries, param, this.signedTenantId); - break; - case "skt": // Signed key start time - this.tryAppendQueryParameter(queries, param, this.signedStartsOn ? truncatedISO8061Date(this.signedStartsOn, false) : undefined); - break; - case "ske": // Signed key expiry time - this.tryAppendQueryParameter(queries, param, this.signedExpiresOn ? truncatedISO8061Date(this.signedExpiresOn, false) : undefined); - break; - case "sks": // Signed key service - this.tryAppendQueryParameter(queries, param, this.signedService); - break; - case "skv": // Signed key version - this.tryAppendQueryParameter(queries, param, this.signedVersion); - break; - case "sr": - this.tryAppendQueryParameter(queries, param, this.resource); - break; - case "sp": - this.tryAppendQueryParameter(queries, param, this.permissions); - break; - case "sig": - this.tryAppendQueryParameter(queries, param, this.signature); - break; - case "rscc": - this.tryAppendQueryParameter(queries, param, this.cacheControl); - break; - case "rscd": - this.tryAppendQueryParameter(queries, param, this.contentDisposition); - break; - case "rsce": - this.tryAppendQueryParameter(queries, param, this.contentEncoding); - break; - case "rscl": - this.tryAppendQueryParameter(queries, param, this.contentLanguage); - break; - case "rsct": - this.tryAppendQueryParameter(queries, param, this.contentType); - break; - case "saoid": - this.tryAppendQueryParameter(queries, param, this.preauthorizedAgentObjectId); - break; - case "scid": - this.tryAppendQueryParameter(queries, param, this.correlationId); - break; - } - } - return queries.join("&"); - }; - /** - * A private helper method used to filter and append query key/value pairs into an array. - * - * @private - * @param {string[]} queries - * @param {string} key - * @param {string} [value] - * @returns {void} - * @memberof SASQueryParameters - */ - SASQueryParameters.prototype.tryAppendQueryParameter = function (queries, key, value) { - if (!value) { - return; - } - key = encodeURIComponent(key); - value = encodeURIComponent(value); - if (key.length > 0 && value.length > 0) { - queries.push(key + "=" + value); - } - }; - return SASQueryParameters; -}()); - -// Copyright (c) Microsoft Corporation. All rights reserved. -function generateBlobSASQueryParameters(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { - var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; - var sharedKeyCredential = sharedKeyCredentialOrUserDelegationKey instanceof StorageSharedKeyCredential - ? sharedKeyCredentialOrUserDelegationKey - : undefined; - var userDelegationKeyCredential; - if (sharedKeyCredential === undefined && accountName !== undefined) { - userDelegationKeyCredential = new UserDelegationKeyCredential(accountName, sharedKeyCredentialOrUserDelegationKey); - } - if (sharedKeyCredential === undefined && userDelegationKeyCredential === undefined) { - throw TypeError("Invalid sharedKeyCredential, userDelegationKey or accountName."); - } - // Version 2019-12-12 adds support for the blob tags permission. - // Version 2018-11-09 adds support for the signed resource and signed blob snapshot time fields. - // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas#constructing-the-signature-string - if (version >= "2018-11-09") { - if (sharedKeyCredential !== undefined) { - return generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential); - } - else { - // Version 2020-02-10 delegation SAS signature construction includes preauthorizedAgentObjectId, agentObjectId, correlationId. - if (version >= "2020-02-10") { - return generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userDelegationKeyCredential); - } - else { - return generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential); - } - } - } - if (version >= "2015-04-05") { - if (sharedKeyCredential !== undefined) { - return generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential); - } - else { - throw new RangeError("'version' must be >= '2018-11-09' when generating user delegation SAS using user delegation key."); - } - } - throw new RangeError("'version' must be >= '2015-04-05'."); -} -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * IMPLEMENTATION FOR API VERSION FROM 2015-04-05 AND BEFORE 2018-11-09. - * - * Creates an instance of SASQueryParameters. - * - * Only accepts required settings needed to create a SAS. For optional settings please - * set corresponding properties directly, such as permissions, startsOn and identifier. - * - * WARNING: When identifier is not provided, permissions and expiresOn are required. - * You MUST assign value to identifier or expiresOn & permissions manually if you initial with - * this constructor. - * - * @param {BlobSASSignatureValues} blobSASSignatureValues - * @param {StorageSharedKeyCredential} sharedKeyCredential - * @returns {SASQueryParameters} - */ -function generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential) { - blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); - if (!blobSASSignatureValues.identifier && - !(blobSASSignatureValues.permissions && blobSASSignatureValues.expiresOn)) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); - } - var resource = "c"; - if (blobSASSignatureValues.blobName) { - resource = "b"; - } - // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; - if (blobSASSignatureValues.permissions) { - if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - else { - verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - } - // Signature is generated on the un-url-encoded values. - var stringToSign = [ - verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn - ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) - : "", - blobSASSignatureValues.expiresOn - ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) - : "", - getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), - blobSASSignatureValues.identifier, - blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", - blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", - blobSASSignatureValues.version, - blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", - blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", - blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", - blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", - blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" - ].join("\n"); - var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); -} -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. - * - * Creates an instance of SASQueryParameters. - * - * Only accepts required settings needed to create a SAS. For optional settings please - * set corresponding properties directly, such as permissions, startsOn and identifier. - * - * WARNING: When identifier is not provided, permissions and expiresOn are required. - * You MUST assign value to identifier or expiresOn & permissions manually if you initial with - * this constructor. - * - * @param {BlobSASSignatureValues} blobSASSignatureValues - * @param {StorageSharedKeyCredential} sharedKeyCredential - * @returns {SASQueryParameters} - */ -function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential) { - blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); - if (!blobSASSignatureValues.identifier && - !(blobSASSignatureValues.permissions && blobSASSignatureValues.expiresOn)) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); - } - var resource = "c"; - var timestamp = blobSASSignatureValues.snapshotTime; - if (blobSASSignatureValues.blobName) { - resource = "b"; - if (blobSASSignatureValues.snapshotTime) { - resource = "bs"; - } - else if (blobSASSignatureValues.versionId) { - resource = "bv"; - timestamp = blobSASSignatureValues.versionId; - } - } - // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; - if (blobSASSignatureValues.permissions) { - if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - else { - verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - } - // Signature is generated on the un-url-encoded values. - var stringToSign = [ - verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn - ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) - : "", - blobSASSignatureValues.expiresOn - ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) - : "", - getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), - blobSASSignatureValues.identifier, - blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", - blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", - blobSASSignatureValues.version, - resource, - timestamp, - blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", - blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", - blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", - blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", - blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" - ].join("\n"); - var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); -} -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. - * - * Creates an instance of SASQueryParameters. - * - * Only accepts required settings needed to create a SAS. For optional settings please - * set corresponding properties directly, such as permissions, startsOn. - * - * WARNING: identifier will be ignored, permissions and expiresOn are required. - * - * @param {BlobSASSignatureValues} blobSASSignatureValues - * @param {UserDelegationKeyCredential} userDelegationKeyCredential - * @returns {SASQueryParameters} - */ -function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential) { - blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); - // Stored access policies are not supported for a user delegation SAS. - if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); - } - var resource = "c"; - var timestamp = blobSASSignatureValues.snapshotTime; - if (blobSASSignatureValues.blobName) { - resource = "b"; - if (blobSASSignatureValues.snapshotTime) { - resource = "bs"; - } - else if (blobSASSignatureValues.versionId) { - resource = "bv"; - timestamp = blobSASSignatureValues.versionId; - } - } - // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; - if (blobSASSignatureValues.permissions) { - if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - else { - verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - } - // Signature is generated on the un-url-encoded values. - var stringToSign = [ - verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn - ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) - : "", - blobSASSignatureValues.expiresOn - ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) - : "", - getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), - userDelegationKeyCredential.userDelegationKey.signedObjectId, - userDelegationKeyCredential.userDelegationKey.signedTenantId, - userDelegationKeyCredential.userDelegationKey.signedStartsOn - ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) - : "", - userDelegationKeyCredential.userDelegationKey.signedExpiresOn - ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) - : "", - userDelegationKeyCredential.userDelegationKey.signedService, - userDelegationKeyCredential.userDelegationKey.signedVersion, - blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", - blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", - blobSASSignatureValues.version, - resource, - timestamp, - blobSASSignatureValues.cacheControl, - blobSASSignatureValues.contentDisposition, - blobSASSignatureValues.contentEncoding, - blobSASSignatureValues.contentLanguage, - blobSASSignatureValues.contentType - ].join("\n"); - var signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey); -} -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * IMPLEMENTATION FOR API VERSION FROM 2020-02-10. - * - * Creates an instance of SASQueryParameters. - * - * Only accepts required settings needed to create a SAS. For optional settings please - * set corresponding properties directly, such as permissions, startsOn. - * - * WARNING: identifier will be ignored, permissions and expiresOn are required. - * - * @param {BlobSASSignatureValues} blobSASSignatureValues - * @param {UserDelegationKeyCredential} userDelegationKeyCredential - * @returns {SASQueryParameters} - */ -function generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userDelegationKeyCredential) { - blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); - // Stored access policies are not supported for a user delegation SAS. - if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); - } - var resource = "c"; - var timestamp = blobSASSignatureValues.snapshotTime; - if (blobSASSignatureValues.blobName) { - resource = "b"; - if (blobSASSignatureValues.snapshotTime) { - resource = "bs"; - } - else if (blobSASSignatureValues.versionId) { - resource = "bv"; - timestamp = blobSASSignatureValues.versionId; - } - } - // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; - if (blobSASSignatureValues.permissions) { - if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - else { - verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - } - // Signature is generated on the un-url-encoded values. - var stringToSign = [ - verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn - ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) - : "", - blobSASSignatureValues.expiresOn - ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) - : "", - getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), - userDelegationKeyCredential.userDelegationKey.signedObjectId, - userDelegationKeyCredential.userDelegationKey.signedTenantId, - userDelegationKeyCredential.userDelegationKey.signedStartsOn - ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) - : "", - userDelegationKeyCredential.userDelegationKey.signedExpiresOn - ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) - : "", - userDelegationKeyCredential.userDelegationKey.signedService, - userDelegationKeyCredential.userDelegationKey.signedVersion, - blobSASSignatureValues.preauthorizedAgentObjectId, - undefined, - blobSASSignatureValues.correlationId, - blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", - blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", - blobSASSignatureValues.version, - resource, - timestamp, - blobSASSignatureValues.cacheControl, - blobSASSignatureValues.contentDisposition, - blobSASSignatureValues.contentEncoding, - blobSASSignatureValues.contentLanguage, - blobSASSignatureValues.contentType - ].join("\n"); - var signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId); -} -function getCanonicalName(accountName, containerName, blobName) { - // Container: "/blob/account/containerName" - // Blob: "/blob/account/containerName/blobName" - var elements = ["/blob/" + accountName + "/" + containerName]; - if (blobName) { - elements.push("/" + blobName); - } - return elements.join(""); -} -function SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues) { - var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; - if (blobSASSignatureValues.snapshotTime && version < "2018-11-09") { - throw RangeError("'version' must be >= '2018-11-09' when providing 'snapshotTime'."); - } - if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.snapshotTime) { - throw RangeError("Must provide 'blobName' when providing 'snapshotTime'."); - } - if (blobSASSignatureValues.versionId && version < "2019-10-10") { - throw RangeError("'version' must be >= '2019-10-10' when providing 'versionId'."); - } - if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.versionId) { - throw RangeError("Must provide 'blobName' when providing 'versionId'."); - } - if (blobSASSignatureValues.permissions && - blobSASSignatureValues.permissions.deleteVersion && - version < "2019-10-10") { - throw RangeError("'version' must be >= '2019-10-10' when providing 'x' permission."); - } - if (blobSASSignatureValues.permissions && - blobSASSignatureValues.permissions.tag && - version < "2019-12-12") { - throw RangeError("'version' must be >= '2019-12-12' when providing 't' permission."); - } - if (version < "2020-02-10" && - blobSASSignatureValues.permissions && - (blobSASSignatureValues.permissions.move || blobSASSignatureValues.permissions.execute)) { - throw RangeError("'version' must be >= '2020-02-10' when providing the 'm' or 'e' permission."); - } - if (version < "2020-02-10" && - (blobSASSignatureValues.preauthorizedAgentObjectId || blobSASSignatureValues.correlationId)) { - throw RangeError("'version' must be >= '2020-02-10' when providing 'preauthorizedAgentObjectId' or 'correlationId'."); - } - blobSASSignatureValues.version = version; - return blobSASSignatureValues; -} - -/** - * A BlobClient represents a URL to an Azure Storage blob; the blob may be a block blob, - * append blob, or page blob. - * - * @export - * @class BlobClient - */ -var BlobClient = /** @class */ (function (_super) { - tslib.__extends(BlobClient, _super); - function BlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { - var _a; - var _this = this; - options = options || {}; - var pipeline; - var url; - if (credentialOrPipelineOrContainerName instanceof Pipeline) { - // (url: string, pipeline: Pipeline) - url = urlOrConnectionString; - pipeline = credentialOrPipelineOrContainerName; - } - else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || - credentialOrPipelineOrContainerName instanceof AnonymousCredential || - coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { - // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) - url = urlOrConnectionString; - options = blobNameOrOptions; - pipeline = newPipeline(credentialOrPipelineOrContainerName, options); - } - else if (!credentialOrPipelineOrContainerName && - typeof credentialOrPipelineOrContainerName !== "string") { - // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) - // The second parameter is undefined. Use anonymous credential. - url = urlOrConnectionString; - pipeline = newPipeline(new AnonymousCredential(), options); - } - else if (credentialOrPipelineOrContainerName && - typeof credentialOrPipelineOrContainerName === "string" && - blobNameOrOptions && - typeof blobNameOrOptions === "string") { - // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) - var containerName = credentialOrPipelineOrContainerName; - var blobName = blobNameOrOptions; - var extractedCreds = extractConnectionStringParts(urlOrConnectionString); - if (extractedCreds.kind === "AccountConnString") { - { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); - options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); - pipeline = newPipeline(sharedKeyCredential, options); - } - } - else if (extractedCreds.kind === "SASConnString") { - url = - appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + - "?" + - extractedCreds.accountSas; - pipeline = newPipeline(new AnonymousCredential(), options); - } - else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); - } - } - else { - throw new Error("Expecting non-empty strings for containerName and blobName parameters"); - } - _this = _super.call(this, url, pipeline) || this; - (_a = _this.getBlobAndContainerNamesFromUrl(), _this._name = _a.blobName, _this._containerName = _a.containerName); - _this.blobContext = new Blob$1(_this.storageClientContext); - _this._snapshot = getURLParameter(_this.url, URLConstants.Parameters.SNAPSHOT); - _this._versionId = getURLParameter(_this.url, URLConstants.Parameters.VERSIONID); - return _this; - } - Object.defineProperty(BlobClient.prototype, "name", { - /** - * The name of the blob. - */ - get: function () { - return this._name; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobClient.prototype, "containerName", { - /** - * The name of the storage container the blob is associated with. - */ - get: function () { - return this._containerName; - }, - enumerable: false, - configurable: true - }); - /** - * Creates a new BlobClient object identical to the source but with the specified snapshot timestamp. - * Provide "" will remove the snapshot and return a Client to the base blob. - * - * @param {string} snapshot The snapshot timestamp. - * @returns {BlobClient} A new BlobClient object identical to the source but with the specified snapshot timestamp - * @memberof BlobClient - */ - BlobClient.prototype.withSnapshot = function (snapshot) { - return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); - }; - /** - * Creates a new BlobClient object pointing to a version of this blob. - * Provide "" will remove the versionId and return a Client to the base blob. - * - * @param {string} versionId The versionId. - * @returns {BlobClient} A new BlobClient object pointing to the version of this blob. - * @memberof BlobClient - */ - BlobClient.prototype.withVersion = function (versionId) { - return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.VERSIONID, versionId.length === 0 ? undefined : versionId), this.pipeline); - }; - /** - * Creates a AppendBlobClient object. - * - * @returns {AppendBlobClient} - * @memberof BlobClient - */ - BlobClient.prototype.getAppendBlobClient = function () { - return new AppendBlobClient(this.url, this.pipeline); - }; - /** - * Creates a BlockBlobClient object. - * - * @returns {BlockBlobClient} - * @memberof BlobClient - */ - BlobClient.prototype.getBlockBlobClient = function () { - return new BlockBlobClient(this.url, this.pipeline); - }; - /** - * Creates a PageBlobClient object. - * - * @returns {PageBlobClient} - * @memberof BlobClient - */ - BlobClient.prototype.getPageBlobClient = function () { - return new PageBlobClient(this.url, this.pipeline); - }; - /** - * Reads or downloads a blob from the system, including its metadata and properties. - * You can also call Get Blob to read a snapshot. - * - * * In Node.js, data returns in a Readable stream readableStreamBody - * * In browsers, data returns in a promise blobBody - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob - * - * @param {number} [offset] From which position of the blob to download, >= 0 - * @param {number} [count] How much data to be downloaded, > 0. Will download to the end when undefined - * @param {BlobDownloadOptions} [options] Optional options to Blob Download operation. - * @returns {Promise} - * @memberof BlobClient - * - * Example usage (Node.js): - * - * ```js - * // Download and convert a blob to a string - * const downloadBlockBlobResponse = await blobClient.download(); - * const downloaded = await streamToBuffer(downloadBlockBlobResponse.readableStreamBody); - * console.log("Downloaded blob content:", downloaded.toString()); - * - * async function streamToBuffer(readableStream) { - * return new Promise((resolve, reject) => { - * const chunks = []; - * readableStream.on("data", (data) => { - * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); - * }); - * readableStream.on("end", () => { - * resolve(Buffer.concat(chunks)); - * }); - * readableStream.on("error", reject); - * }); - * } - * ``` - * - * Example usage (browser): - * - * ```js - * // Download and convert a blob to a string - * const downloadBlockBlobResponse = await blobClient.download(); - * const downloaded = await blobToString(await downloadBlockBlobResponse.blobBody); - * console.log( - * "Downloaded blob content", - * downloaded - * ); - * - * async function blobToString(blob: Blob): Promise { - * const fileReader = new FileReader(); - * return new Promise((resolve, reject) => { - * fileReader.onloadend = (ev: any) => { - * resolve(ev.target!.result); - * }; - * fileReader.onerror = reject; - * fileReader.readAsText(blob); - * }); - * } - * ``` - */ - BlobClient.prototype.download = function (offset, count, options) { - var _a; - if (offset === void 0) { offset = 0; } - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, res_1, wrappedRes, e_1; - var _this = this; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - options.conditions = options.conditions || {}; - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - _b = createSpan("BlobClient-download", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.download({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - onDownloadProgress: coreHttp.isNode ? undefined : options.onProgress, - range: offset === 0 && !count ? undefined : rangeToString({ offset: offset, count: count }), - rangeGetContentMD5: options.rangeGetContentMD5, - rangeGetContentCRC64: options.rangeGetContentCrc64, - snapshot: options.snapshot, - cpkInfo: options.customerProvidedKey, - spanOptions: spanOptions - })]; - case 2: - res_1 = _c.sent(); - wrappedRes = tslib.__assign(tslib.__assign({}, res_1), { _response: res_1._response, objectReplicationDestinationPolicyId: res_1.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res_1.objectReplicationRules) }); - // We support retrying when download stream unexpected ends in Node.js runtime - // Following code shouldn't be bundled into browser build, however some - // bundlers may try to bundle following code and "FileReadResponse.ts". - // In this case, "FileDownloadResponse.browser.ts" will be used as a shim of "FileDownloadResponse.ts" - // The config is in package.json "browser" field - if (options.maxRetryRequests === undefined || options.maxRetryRequests < 0) { - // TODO: Default value or make it a required parameter? - options.maxRetryRequests = DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS; - } - if (res_1.contentLength === undefined) { - throw new RangeError("File download response doesn't contain valid content length header"); - } - if (!res_1.etag) { - throw new RangeError("File download response doesn't contain valid etag header"); - } - return [2 /*return*/, new BlobDownloadResponse(wrappedRes, function (start) { return tslib.__awaiter(_this, void 0, void 0, function () { - var updatedOptions; - var _a; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - updatedOptions = { - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ifMatch: options.conditions.ifMatch || res_1.etag, - ifModifiedSince: options.conditions.ifModifiedSince, - ifNoneMatch: options.conditions.ifNoneMatch, - ifUnmodifiedSince: options.conditions.ifUnmodifiedSince, - ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions - }, - range: rangeToString({ - count: offset + res_1.contentLength - start, - offset: start - }), - rangeGetContentMD5: options.rangeGetContentMD5, - rangeGetContentCRC64: options.rangeGetContentCrc64, - snapshot: options.snapshot, - cpkInfo: options.customerProvidedKey - }; - return [4 /*yield*/, this.blobContext.download(tslib.__assign({ abortSignal: options.abortSignal }, updatedOptions))]; - case 1: - // Debug purpose only - // console.log( - // `Read from internal stream, range: ${ - // updatedOptions.range - // }, options: ${JSON.stringify(updatedOptions)}` - // ); - return [2 /*return*/, (_b.sent()).readableStreamBody]; - } - }); - }); }, offset, res_1.contentLength, { - maxRetryRequests: options.maxRetryRequests, - onProgress: options.onProgress - })]; - case 3: - e_1 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_1.message - }); - throw e_1; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; - /** - * Returns true if the Azure blob resource represented by this client exists; false otherwise. - * - * NOTE: use this function with care since an existing blob might be deleted by other clients or - * applications. Vice versa new blobs might be added by other clients or applications after this - * function completes. - * - * @param {BlobExistsOptions} [options] options to Exists operation. - * @returns {Promise} - * @memberof BlobClient - */ - BlobClient.prototype.exists = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_2; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobClient-exists", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.getProperties({ - abortSignal: options.abortSignal, - customerProvidedKey: options.customerProvidedKey, - conditions: options.conditions, - tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) - })]; - case 2: - _b.sent(); - return [2 /*return*/, true]; - case 3: - e_2 = _b.sent(); - if (e_2.statusCode === 404) { - span.setStatus({ - code: api.CanonicalCode.NOT_FOUND, - message: "Expected exception when checking blob existence" - }); - return [2 /*return*/, false]; - } - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_2.message - }); - throw e_2; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; - /** - * Returns all user-defined metadata, standard HTTP properties, and system properties - * for the blob. It does not return the content of the blob. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-properties - * - * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if - * they originally contained uppercase characters. This differs from the metadata keys returned by - * the methods of {@link ContainerClient} that list blobs using the `includeMetadata` option, which - * will retain their original casing. - * - * @param {BlobGetPropertiesOptions} [options] Optional options to Get Properties operation. - * @returns {Promise} - * @memberof BlobClient - */ - BlobClient.prototype.getProperties = function (options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, res, e_3; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-getProperties", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - options.conditions = options.conditions || {}; - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blobContext.getProperties({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - cpkInfo: options.customerProvidedKey, - spanOptions: spanOptions - })]; - case 2: - res = _c.sent(); - return [2 /*return*/, tslib.__assign(tslib.__assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) })]; - case 3: - e_3 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_3.message - }); - throw e_3; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; - /** - * Marks the specified blob or snapshot for deletion. The blob is later deleted - * during garbage collection. Note that in order to delete a blob, you must delete - * all of its snapshots. You can delete both at the same time with the Delete - * Blob operation. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob - * - * @param {BlobDeleteOptions} [options] Optional options to Blob Delete operation. - * @returns {Promise} - * @memberof BlobClient + * Marks the specified blob or snapshot for deletion. The blob is later deleted + * during garbage collection. Note that in order to delete a blob, you must delete + * all of its snapshots. You can delete both at the same time with the Delete + * Blob operation. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob + * + * @param {BlobDeleteOptions} [options] Optional options to Blob Delete operation. + * @returns {Promise} + * @memberof BlobClient */ BlobClient.prototype.delete = function (options) { var _a; @@ -29856,7 +28437,6 @@ var BlobClient = /** @class */ (function (_super) { _c.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.blobContext.setTags({ abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), spanOptions: spanOptions, tags: toBlobTags(tags) @@ -29898,7 +28478,6 @@ var BlobClient = /** @class */ (function (_super) { _c.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.blobContext.getTags({ abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), spanOptions: spanOptions })]; @@ -30466,7 +29045,10 @@ var BlobClient = /** @class */ (function (_super) { // Azure Storage Server will replace "\" with "/" in the blob names // doing the same in the SDK side so that the user doesn't have to replace "\" instances in the blobName blobName = blobName.replace(/\\/g, "/"); - if (!containerName) { + if (!blobName) { + throw new Error("Provided blobName is invalid."); + } + else if (!containerName) { throw new Error("Provided containerName is invalid."); } return { blobName: blobName, containerName: containerName }; @@ -30538,28 +29120,6 @@ var BlobClient = /** @class */ (function (_super) { }); }); }; - /** - * Only available for BlobClient constructed with a shared key credential. - * - * Generates a Blob Service Shared Access Signature (SAS) URI based on the client properties - * and parameters passed in. The SAS is signed by the shared key credential of the client. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas - * - * @param {BlobGenerateSasUrlOptions} options Optional parameters. - * @returns {Promise} The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. - * @memberof BlobClient - */ - BlobClient.prototype.generateSasUrl = function (options) { - var _this = this; - return new Promise(function (resolve) { - if (!(_this.credential instanceof StorageSharedKeyCredential)) { - throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); - } - var sas = generateBlobSASQueryParameters(tslib.__assign({ containerName: _this._containerName, blobName: _this._name, snapshotTime: _this._snapshot, versionId: _this._versionId }, options), _this.credential).toString(); - resolve(appendToURLQuery(_this.url, sas)); - }); - }; return BlobClient; }(StorageClient)); /** @@ -31158,63 +29718,6 @@ var BlockBlobClient = /** @class */ (function (_super) { }); }); }; - /** - * Creates a new Block Blob where the contents of the blob are read from a given URL. - * This API is supported beginning with the 2020-04-08 version. Partial updates - * are not supported with Put Blob from URL; the content of an existing blob is overwritten with - * the content of the new blob. To perform partial updates to a block blob’s contents using a - * source URL, use {@link stageBlockFromURL} and {@link commitBlockList}. - * - * @param {string} sourceURL Specifies the URL of the blob. The value - * may be a URL of up to 2 KB in length that specifies a blob. - * The value should be URL-encoded as it would appear - * in a request URI. The source blob must either be public - * or must be authenticated via a shared access signature. - * If the source blob is public, no authentication is required - * to perform the operation. Here are some examples of source object URLs: - * - https://myaccount.blob.core.windows.net/mycontainer/myblob - * - https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= - * @param {BlockBlobSyncUploadFromURLOptions} [options={}] Optional parameters. - * @returns Promise - * @memberof BlockBlobClient - */ - BlockBlobClient.prototype.syncUploadFromURL = function (sourceURL, options) { - var _a, _b, _c, _d, _e; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _f, span, spanOptions, e_25; - return tslib.__generator(this, function (_g) { - switch (_g.label) { - case 0: - options.conditions = options.conditions || {}; - _f = createSpan("BlockBlobClient-syncUploadFromURL", options.tracingOptions), span = _f.span, spanOptions = _f.spanOptions; - _g.label = 1; - case 1: - _g.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blockBlobContext.putBlobFromUrl(0, sourceURL, tslib.__assign(tslib.__assign({}, options), { leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: options.conditions.tagConditions }), sourceModifiedAccessConditions: { - sourceIfMatch: (_a = options.sourceConditions) === null || _a === void 0 ? void 0 : _a.ifMatch, - sourceIfModifiedSince: (_b = options.sourceConditions) === null || _b === void 0 ? void 0 : _b.ifModifiedSince, - sourceIfNoneMatch: (_c = options.sourceConditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch, - sourceIfUnmodifiedSince: (_d = options.sourceConditions) === null || _d === void 0 ? void 0 : _d.ifUnmodifiedSince, - sourceIfTags: (_e = options.sourceConditions) === null || _e === void 0 ? void 0 : _e.tagConditions - }, cpkInfo: options.customerProvidedKey, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), spanOptions: spanOptions }))]; - case 2: return [2 /*return*/, _g.sent()]; - case 3: - e_25 = _g.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_25.message - }); - throw e_25; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; /** * Uploads the specified block to the block blob's "staging area" to be later * committed by a call to commitBlockList. @@ -31230,7 +29733,7 @@ var BlockBlobClient = /** @class */ (function (_super) { BlockBlobClient.prototype.stageBlock = function (blockId, body, contentLength, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_26; + var _a, span, spanOptions, e_25; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: @@ -31251,12 +29754,12 @@ var BlockBlobClient = /** @class */ (function (_super) { })]; case 2: return [2 /*return*/, _b.sent()]; case 3: - e_26 = _b.sent(); + e_25 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_26.message + message: e_25.message }); - throw e_26; + throw e_25; case 4: span.end(); return [7 /*endfinally*/]; @@ -31291,7 +29794,7 @@ var BlockBlobClient = /** @class */ (function (_super) { if (offset === void 0) { offset = 0; } if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_27; + var _a, span, spanOptions, e_26; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: @@ -31312,12 +29815,12 @@ var BlockBlobClient = /** @class */ (function (_super) { })]; case 2: return [2 /*return*/, _b.sent()]; case 3: - e_27 = _b.sent(); + e_26 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_27.message + message: e_26.message }); - throw e_27; + throw e_26; case 4: span.end(); return [7 /*endfinally*/]; @@ -31343,7 +29846,7 @@ var BlockBlobClient = /** @class */ (function (_super) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_28; + var _b, span, spanOptions, e_27; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: @@ -31367,12 +29870,12 @@ var BlockBlobClient = /** @class */ (function (_super) { })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_28 = _c.sent(); + e_27 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_28.message + message: e_27.message }); - throw e_28; + throw e_27; case 4: span.end(); return [7 /*endfinally*/]; @@ -31396,7 +29899,7 @@ var BlockBlobClient = /** @class */ (function (_super) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, res, e_29; + var _b, span, spanOptions, res, e_28; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: @@ -31420,12 +29923,12 @@ var BlockBlobClient = /** @class */ (function (_super) { } return [2 /*return*/, res]; case 3: - e_29 = _c.sent(); + e_28 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_29.message + message: e_28.message }); - throw e_29; + throw e_28; case 4: span.end(); return [7 /*endfinally*/]; @@ -31435,56 +29938,6 @@ var BlockBlobClient = /** @class */ (function (_super) { }); }; // High level functions - /** - * Uploads a Buffer(Node.js)/Blob(browsers)/ArrayBuffer/ArrayBufferView object to a BlockBlob. - * - * When data length is no more than the specifiled {@link BlockBlobParallelUploadOptions.maxSingleShotSize} (default is - * {@link BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}), this method will use 1 {@link upload} call to finish the upload. - * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList} - * to commit the block list. - * - * @export - * @param {Buffer | Blob | ArrayBuffer | ArrayBufferView} data Buffer(Node.js), Blob, ArrayBuffer or ArrayBufferView - * @param {BlockBlobParallelUploadOptions} [options] - * @returns {Promise} - * @memberof BlockBlobClient - */ - BlockBlobClient.prototype.uploadData = function (data, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, buffer_1, browserBlob_1; - return tslib.__generator(this, function (_b) { - _a = createSpan("BlockBlobClient-uploadData", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - try { - if (true) { - if (data instanceof Buffer) { - buffer_1 = data; - } - else if (data instanceof ArrayBuffer) { - buffer_1 = Buffer.from(data); - } - else { - data = data; - buffer_1 = Buffer.from(data.buffer, data.byteOffset, data.byteLength); - } - return [2 /*return*/, this.uploadSeekableInternal(function (offset, size) { return buffer_1.slice(offset, offset + size); }, buffer_1.byteLength, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - } - else {} - } - catch (e) { - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e.message - }); - throw e; - } - finally { - span.end(); - } - return [2 /*return*/]; - }); - }); - }; /** * ONLY AVAILABLE IN BROWSERS. * @@ -31494,8 +29947,6 @@ var BlockBlobClient = /** @class */ (function (_super) { * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call * {@link commitBlockList} to commit the block list. * - * @deprecated Use {@link uploadData} instead. - * * @export * @param {Blob | ArrayBuffer | ArrayBufferView} browserData Blob, File, ArrayBuffer or ArrayBufferView * @param {BlockBlobParallelUploadOptions} [options] Options to upload browser data. @@ -31505,7 +29956,7 @@ var BlockBlobClient = /** @class */ (function (_super) { BlockBlobClient.prototype.uploadBrowserData = function (browserData, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, browserBlob_2, e_30; + var _a, span, spanOptions, browserBlob_1, e_29; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: @@ -31513,16 +29964,18 @@ var BlockBlobClient = /** @class */ (function (_super) { _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - browserBlob_2 = new Blob([browserData]); - return [4 /*yield*/, this.uploadSeekableInternal(function (offset, size) { return browserBlob_2.slice(offset, offset + size); }, browserBlob_2.size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + browserBlob_1 = new Blob([browserData]); + return [4 /*yield*/, this.uploadSeekableBlob(function (offset, size) { + return browserBlob_1.slice(offset, offset + size); + }, browserBlob_1.size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: return [2 /*return*/, _b.sent()]; case 3: - e_30 = _b.sent(); + e_29 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_30.message + message: e_29.message }); - throw e_30; + throw e_29; case 4: span.end(); return [7 /*endfinally*/]; @@ -31532,25 +29985,25 @@ var BlockBlobClient = /** @class */ (function (_super) { }); }; /** + * ONLY AVAILABLE IN BROWSERS. * - * Uploads data to block blob. Requires a bodyFactory as the data source, - * which need to return a {@link HttpRequestBody} object with the offset and size provided. + * Uploads a browser {@link Blob} object to block blob. Requires a blobFactory as the data source, + * which need to return a {@link Blob} object with the offset and size provided. * - * When data length is no more than the specifiled {@link BlockBlobParallelUploadOptions.maxSingleShotSize} (default is - * {@link BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}), this method will use 1 {@link upload} call to finish the upload. - * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList} + * When buffer length <= 256MB, this method will use 1 upload call to finish the upload. + * Otherwise, this method will call stageBlock to upload blocks, and finally call commitBlockList * to commit the block list. * - * @param {(offset: number, size: number) => HttpRequestBody} bodyFactory + * @param {(offset: number, size: number) => Blob} blobFactory * @param {number} size size of the data to upload. * @param {BlockBlobParallelUploadOptions} [options] Options to Upload to Block Blob operation. * @returns {Promise} Response data for the Blob Upload operation. * @memberof BlockBlobClient */ - BlockBlobClient.prototype.uploadSeekableInternal = function (bodyFactory, size, options) { + BlockBlobClient.prototype.uploadSeekableBlob = function (blobFactory, size, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, numBlocks_1, blockList_1, blockIDPrefix_1, transferProgress_2, batch, _loop_2, i, e_31; + var _a, span, spanOptions, numBlocks_1, blockList_1, blockIDPrefix_1, transferProgress_2, batch, _loop_2, i, e_30; var _this = this; return tslib.__generator(this, function (_b) { switch (_b.label) { @@ -31585,12 +30038,12 @@ var BlockBlobClient = /** @class */ (function (_super) { if (!options.conditions) { options.conditions = {}; } - _a = createSpan("BlockBlobClient-uploadSeekableInternal", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("BlockBlobClient-UploadSeekableBlob", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 5, 6, 7]); if (!(size <= options.maxSingleShotSize)) return [3 /*break*/, 3]; - return [4 /*yield*/, this.upload(bodyFactory(0, size), size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + return [4 /*yield*/, this.upload(blobFactory(0, size), size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: return [2 /*return*/, _b.sent()]; case 3: numBlocks_1 = Math.floor((size - 1) / options.blockSize) + 1; @@ -31613,7 +30066,7 @@ var BlockBlobClient = /** @class */ (function (_super) { end = i === numBlocks_1 - 1 ? size : start + options.blockSize; contentLength = end - start; blockList_1.push(blockID); - return [4 /*yield*/, this.stageBlock(blockID, bodyFactory(start, contentLength), contentLength, { + return [4 /*yield*/, this.stageBlock(blockID, blobFactory(start, contentLength), contentLength, { abortSignal: options.abortSignal, conditions: options.conditions, encryptionScope: options.encryptionScope, @@ -31642,12 +30095,12 @@ var BlockBlobClient = /** @class */ (function (_super) { _b.sent(); return [2 /*return*/, this.commitBlockList(blockList_1, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 5: - e_31 = _b.sent(); + e_30 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_31.message + message: e_30.message }); - throw e_31; + throw e_30; case 6: span.end(); return [7 /*endfinally*/]; @@ -31673,7 +30126,7 @@ var BlockBlobClient = /** @class */ (function (_super) { BlockBlobClient.prototype.uploadFile = function (filePath, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, size, e_32; + var _a, span, spanOptions, size, e_31; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: @@ -31684,23 +30137,21 @@ var BlockBlobClient = /** @class */ (function (_super) { return [4 /*yield*/, fsStat(filePath)]; case 2: size = (_b.sent()).size; - return [4 /*yield*/, this.uploadSeekableInternal(function (offset, count) { - return function () { - return fsCreateReadStream(filePath, { - autoClose: true, - end: count ? offset + count - 1 : Infinity, - start: offset - }); - }; + return [4 /*yield*/, this.uploadResetableStream(function (offset, count) { + return fsCreateReadStream(filePath, { + autoClose: true, + end: count ? offset + count - 1 : Infinity, + start: offset + }); }, size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 3: return [2 /*return*/, _b.sent()]; case 4: - e_32 = _b.sent(); + e_31 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_32.message + message: e_31.message }); - throw e_32; + throw e_31; case 5: span.end(); return [7 /*endfinally*/]; @@ -31731,7 +30182,7 @@ var BlockBlobClient = /** @class */ (function (_super) { if (maxConcurrency === void 0) { maxConcurrency = 5; } if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, blockNum_1, blockIDPrefix_2, transferProgress_3, blockList_2, scheduler, e_33; + var _a, span, spanOptions, blockNum_1, blockIDPrefix_2, transferProgress_3, blockList_2, scheduler, e_32; var _this = this; return tslib.__generator(this, function (_b) { switch (_b.label) { @@ -31785,16 +30236,142 @@ var BlockBlobClient = /** @class */ (function (_super) { return [4 /*yield*/, this.commitBlockList(blockList_2, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 3: return [2 /*return*/, _b.sent()]; case 4: + e_32 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_32.message + }); + throw e_32; + case 5: + span.end(); + return [7 /*endfinally*/]; + case 6: return [2 /*return*/]; + } + }); + }); + }; + /** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * Accepts a Node.js Readable stream factory, and uploads in blocks to a block blob. + * The Readable stream factory must returns a Node.js Readable stream starting from the offset defined. The offset + * is the offset in the block blob to be uploaded. + * + * When buffer length <= 256MB, this method will use 1 upload call to finish the upload. + * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList} + * to commit the block list. + * + * @export + * @param {(offset: number) => NodeJS.ReadableStream} streamFactory Returns a Node.js Readable stream starting + * from the offset defined + * @param {number} size Size of the block blob + * @param {BlockBlobParallelUploadOptions} [options] Options to Upload to Block Blob operation. + * @returns {(Promise)} Response data for the Blob Upload operation. + * @memberof BlockBlobClient + */ + BlockBlobClient.prototype.uploadResetableStream = function (streamFactory, size, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, numBlocks_2, blockList_3, blockIDPrefix_3, transferProgress_4, batch, _loop_3, i, e_33; + var _this = this; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!options.blockSize) { + options.blockSize = 0; + } + if (options.blockSize < 0 || options.blockSize > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES) { + throw new RangeError("blockSize option must be >= 0 and <= " + BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES); + } + if (options.maxSingleShotSize !== 0 && !options.maxSingleShotSize) { + options.maxSingleShotSize = BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES; + } + if (options.maxSingleShotSize < 0 || + options.maxSingleShotSize > BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES) { + throw new RangeError("maxSingleShotSize option must be >= 0 and <= " + BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES); + } + if (options.blockSize === 0) { + if (size > BLOCK_BLOB_MAX_BLOCKS * BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES) { + throw new RangeError(size + " is too larger to upload to a block blob."); + } + if (size > options.maxSingleShotSize) { + options.blockSize = Math.ceil(size / BLOCK_BLOB_MAX_BLOCKS); + if (options.blockSize < DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES) { + options.blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; + } + } + } + if (!options.blobHTTPHeaders) { + options.blobHTTPHeaders = {}; + } + if (!options.conditions) { + options.conditions = {}; + } + _a = createSpan("BlockBlobClient-uploadResetableStream", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 6, 7, 8]); + if (!(size <= options.maxSingleShotSize)) return [3 /*break*/, 3]; + return [4 /*yield*/, this.upload(function () { return streamFactory(0); }, size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + numBlocks_2 = Math.floor((size - 1) / options.blockSize) + 1; + if (numBlocks_2 > BLOCK_BLOB_MAX_BLOCKS) { + throw new RangeError("The buffer's size is too big or the BlockSize is too small;" + + ("the number of blocks must be <= " + BLOCK_BLOB_MAX_BLOCKS)); + } + blockList_3 = []; + blockIDPrefix_3 = coreHttp.generateUuid(); + transferProgress_4 = 0; + batch = new Batch(options.concurrency); + _loop_3 = function (i) { + batch.addOperation(function () { return tslib.__awaiter(_this, void 0, void 0, function () { + var blockID, start, end, contentLength; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + blockID = generateBlockID(blockIDPrefix_3, i); + start = options.blockSize * i; + end = i === numBlocks_2 - 1 ? size : start + options.blockSize; + contentLength = end - start; + blockList_3.push(blockID); + return [4 /*yield*/, this.stageBlock(blockID, function () { return streamFactory(start, contentLength); }, contentLength, { + abortSignal: options.abortSignal, + conditions: options.conditions, + encryptionScope: options.encryptionScope, + tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) + })]; + case 1: + _a.sent(); + // Update progress after block is successfully uploaded to server, in case of block trying + transferProgress_4 += contentLength; + if (options.onProgress) { + options.onProgress({ loadedBytes: transferProgress_4 }); + } + return [2 /*return*/]; + } + }); + }); }); + }; + for (i = 0; i < numBlocks_2; i++) { + _loop_3(i); + } + return [4 /*yield*/, batch.do()]; + case 4: + _b.sent(); + return [4 /*yield*/, this.commitBlockList(blockList_3, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 5: return [2 /*return*/, _b.sent()]; + case 6: e_33 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_33.message }); throw e_33; - case 5: + case 7: span.end(); return [7 /*endfinally*/]; - case 6: return [2 /*return*/]; + case 8: return [2 /*return*/]; } }); }); @@ -33943,7 +32520,7 @@ var ContainerClient = /** @class */ (function (_super) { * } * entity = await iter.next(); * } - * ``` + * ```js * * Example using `byPage()`: * @@ -33988,7 +32565,8 @@ var ContainerClient = /** @class */ (function (_super) { * @param {ContainerListBlobsOptions} [options={}] Options to list blobs operation. * @returns {(PagedAsyncIterableIterator< * { kind: "prefix" } & BlobPrefix | { kind: "blob" } & BlobItem, - * ContainerListBlobHierarchySegmentResponse>)} + * ContainerListBlobHierarchySegmentResponse + * >)} * @memberof ContainerClient */ ContainerClient.prototype.listBlobsByHierarchy = function (delimiter, options) { @@ -34090,28 +32668,6 @@ var ContainerClient = /** @class */ (function (_super) { throw new Error("Unable to extract containerName with provided information."); } }; - /** - * Only available for ContainerClient constructed with a shared key credential. - * - * Generates a Blob Container Service Shared Access Signature (SAS) URI based on the client properties - * and parameters passed in. The SAS is signed by the shared key credential of the client. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas - * - * @param {ContainerGenerateSasUrlOptions} options Optional parameters. - * @returns {Promise} The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. - * @memberof ContainerClient - */ - ContainerClient.prototype.generateSasUrl = function (options) { - var _this = this; - return new Promise(function (resolve) { - if (!(_this.credential instanceof StorageSharedKeyCredential)) { - throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); - } - var sas = generateBlobSASQueryParameters(tslib.__assign({ containerName: _this._containerName }, options), _this.credential).toString(); - resolve(appendToURLQuery(_this.url, sas)); - }); - }; return ContainerClient; }(StorageClient)); @@ -34191,7 +32747,8 @@ var BatchResponseParser = /** @class */ (function () { // Parse sub subResponses. for (index = 0; index < subResponseCount; index++) { subResponse = subResponses[index]; - deserializedSubResponse = {}; + deserializedSubResponses[index] = {}; + deserializedSubResponse = deserializedSubResponses[index]; deserializedSubResponse.headers = new coreHttp.HttpHeaders(); responseLines = subResponse.split("" + HTTP_LINE_ENDING); subRespHeaderStartFound = false; @@ -34243,20 +32800,8 @@ var BatchResponseParser = /** @class */ (function () { deserializedSubResponse.bodyAsText += responseLine; } } // Inner for end - // The response will contain the Content-ID header for each corresponding subrequest response to use for tracking. - // The Content-IDs are set to a valid index in the subrequests we sent. In the status code 202 path, we could expect it - // to be 1-1 mapping from the [0, subRequests.size) to the Content-IDs returned. If not, we simply don't return that - // unexpected subResponse in the parsed reponse and we can always look it up in the raw response for debugging purpose. - if (contentId != NOT_FOUND && - Number.isInteger(contentId) && - contentId >= 0 && - contentId < this.subRequests.size && - deserializedSubResponses[contentId] === undefined) { + if (contentId != NOT_FOUND) { deserializedSubResponse._request = this.subRequests.get(contentId); - deserializedSubResponses[contentId] = deserializedSubResponse; - } - else { - logger.error("subResponses[" + index + "] is dropped as the Content-ID is not found or invalid, Content-ID: " + contentId); } if (subRespFailed) { subResponsesFailedCount++; @@ -34594,7 +33139,7 @@ var InnerBatchRequest = /** @class */ (function () { factories[1] = new BatchHeaderFilterPolicyFactory(); // Use batch header filter policy to exclude unnecessary headers if (!isAnonymousCreds) { factories[2] = coreHttp.isTokenCredential(credential) - ? attachCredential(coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes), credential) + ? coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes) : credential; } factories[policyFactoryLength - 1] = new BatchRequestAssemblePolicyFactory(this); // Use batch assemble policy to assemble request and intercept request from going to wire @@ -34697,690 +33242,196 @@ var BatchHeaderFilterPolicy = /** @class */ (function (_super) { request.headers.remove(xMsHeaderName); // The subrequests should not have the x-ms-version header. } return [2 /*return*/, this._nextPolicy.sendRequest(request)]; - }); - }); - }; - return BatchHeaderFilterPolicy; -}(coreHttp.BaseRequestPolicy)); -var BatchHeaderFilterPolicyFactory = /** @class */ (function () { - function BatchHeaderFilterPolicyFactory() { - } - BatchHeaderFilterPolicyFactory.prototype.create = function (nextPolicy, options) { - return new BatchHeaderFilterPolicy(nextPolicy, options); - }; - return BatchHeaderFilterPolicyFactory; -}()); - -// Copyright (c) Microsoft Corporation. All rights reserved. -/** - * A BlobBatchClient allows you to make batched requests to the Azure Storage Blob service. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch - */ -var BlobBatchClient = /** @class */ (function () { - function BlobBatchClient(url, credentialOrPipeline, options) { - var pipeline; - if (credentialOrPipeline instanceof Pipeline) { - pipeline = credentialOrPipeline; - } - else if (!credentialOrPipeline) { - // no credential provided - pipeline = newPipeline(new AnonymousCredential(), options); - } - else { - pipeline = newPipeline(credentialOrPipeline, options); - } - var storageClientContext = new StorageClientContext(url, pipeline.toServiceClientOptions()); - this._serviceContext = new Service(storageClientContext); - } - /** - * Creates a {@link BlobBatch}. - * A BlobBatch represents an aggregated set of operations on blobs. - */ - BlobBatchClient.prototype.createBatch = function () { - return new BlobBatch(); - }; - BlobBatchClient.prototype.deleteBlobs = function (urlsOrBlobClients, credentialOrOptions, options) { - return tslib.__awaiter(this, void 0, void 0, function () { - var batch, _i, urlsOrBlobClients_1, urlOrBlobClient; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - batch = new BlobBatch(); - _i = 0, urlsOrBlobClients_1 = urlsOrBlobClients; - _a.label = 1; - case 1: - if (!(_i < urlsOrBlobClients_1.length)) return [3 /*break*/, 6]; - urlOrBlobClient = urlsOrBlobClients_1[_i]; - if (!(typeof urlOrBlobClient === "string")) return [3 /*break*/, 3]; - return [4 /*yield*/, batch.deleteBlob(urlOrBlobClient, credentialOrOptions, options)]; - case 2: - _a.sent(); - return [3 /*break*/, 5]; - case 3: return [4 /*yield*/, batch.deleteBlob(urlOrBlobClient, credentialOrOptions)]; - case 4: - _a.sent(); - _a.label = 5; - case 5: - _i++; - return [3 /*break*/, 1]; - case 6: return [2 /*return*/, this.submitBatch(batch)]; - } - }); - }); - }; - BlobBatchClient.prototype.setBlobsAccessTier = function (urlsOrBlobClients, credentialOrTier, tierOrOptions, options) { - return tslib.__awaiter(this, void 0, void 0, function () { - var batch, _i, urlsOrBlobClients_2, urlOrBlobClient; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - batch = new BlobBatch(); - _i = 0, urlsOrBlobClients_2 = urlsOrBlobClients; - _a.label = 1; - case 1: - if (!(_i < urlsOrBlobClients_2.length)) return [3 /*break*/, 6]; - urlOrBlobClient = urlsOrBlobClients_2[_i]; - if (!(typeof urlOrBlobClient === "string")) return [3 /*break*/, 3]; - return [4 /*yield*/, batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options)]; - case 2: - _a.sent(); - return [3 /*break*/, 5]; - case 3: return [4 /*yield*/, batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions)]; - case 4: - _a.sent(); - _a.label = 5; - case 5: - _i++; - return [3 /*break*/, 1]; - case 6: return [2 /*return*/, this.submitBatch(batch)]; - } - }); - }); - }; - /** - * Submit batch request which consists of multiple subrequests. - * - * Get `blobBatchClient` and other details before running the snippets. - * `blobServiceClient.getBlobBatchClient()` gives the `blobBatchClient` - * - * Example usage: - * - * ```js - * let batchRequest = new BlobBatch(); - * await batchRequest.deleteBlob(urlInString0, credential0); - * await batchRequest.deleteBlob(urlInString1, credential1, { - * deleteSnapshots: "include" - * }); - * const batchResp = await blobBatchClient.submitBatch(batchRequest); - * console.log(batchResp.subResponsesSucceededCount); - * ``` - * - * Example using a lease: - * - * ```js - * let batchRequest = new BlobBatch(); - * await batchRequest.setBlobAccessTier(blockBlobClient0, "Cool"); - * await batchRequest.setBlobAccessTier(blockBlobClient1, "Cool", { - * conditions: { leaseId: leaseId } - * }); - * const batchResp = await blobBatchClient.submitBatch(batchRequest); - * console.log(batchResp.subResponsesSucceededCount); - * ``` - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch - * - * @param {BlobBatch} batchRequest A set of Delete or SetTier operations. - * @param {BlobBatchSubmitBatchOptionalParams} [options] - * @returns {Promise} - * @memberof BlobBatchClient - */ - BlobBatchClient.prototype.submitBatch = function (batchRequest, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, batchRequestBody, rawBatchResponse, batchResponseParser, responseSummary, res, e_1; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!batchRequest || batchRequest.getSubRequests().size == 0) { - throw new RangeError("Batch request should contain one or more sub requests."); - } - _a = createSpan("BlobBatchClient-submitBatch", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 4, 5, 6]); - batchRequestBody = batchRequest.getHttpRequestBody(); - return [4 /*yield*/, this._serviceContext.submitBatch(batchRequestBody, utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), tslib.__assign(tslib.__assign({}, options), { spanOptions: spanOptions }))]; - case 2: - rawBatchResponse = _b.sent(); - batchResponseParser = new BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests()); - return [4 /*yield*/, batchResponseParser.parseBatchResponse()]; - case 3: - responseSummary = _b.sent(); - res = { - _response: rawBatchResponse._response, - contentType: rawBatchResponse.contentType, - errorCode: rawBatchResponse.errorCode, - requestId: rawBatchResponse.requestId, - clientRequestId: rawBatchResponse.clientRequestId, - version: rawBatchResponse.version, - subResponses: responseSummary.subResponses, - subResponsesSucceededCount: responseSummary.subResponsesSucceededCount, - subResponsesFailedCount: responseSummary.subResponsesFailedCount - }; - return [2 /*return*/, res]; - case 4: - e_1 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_1.message - }); - throw e_1; - case 5: - span.end(); - return [7 /*endfinally*/]; - case 6: return [2 /*return*/]; - } - }); - }); - }; - return BlobBatchClient; -}()); - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * This is a helper class to construct a string representing the permissions granted by an AccountSAS. Setting a value - * to true means that any SAS which uses these permissions will grant permissions for that operation. Once all the - * values are set, this should be serialized with toString and set as the permissions field on an - * {@link AccountSASSignatureValues} object. It is possible to construct the permissions string without this class, but - * the order of the permissions is particular and this class guarantees correctness. - * - * @export - * @class AccountSASPermissions - */ -var AccountSASPermissions = /** @class */ (function () { - function AccountSASPermissions() { - /** - * Permission to read resources and list queues and tables granted. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.read = false; - /** - * Permission to write resources granted. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.write = false; - /** - * Permission to create blobs and files granted. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.delete = false; - /** - * Permission to delete versions granted. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.deleteVersion = false; - /** - * Permission to list blob containers, blobs, shares, directories, and files granted. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.list = false; - /** - * Permission to add messages, table entities, and append to blobs granted. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.add = false; - /** - * Permission to create blobs and files granted. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.create = false; - /** - * Permissions to update messages and table entities granted. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.update = false; - /** - * Permission to get and delete messages granted. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.process = false; - /** - * Specfies Tag access granted. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.tag = false; - /** - * Permission to filter blobs. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.filter = false; - } - /** - * Parse initializes the AccountSASPermissions fields from a string. - * - * @static - * @param {string} permissions - * @returns {AccountSASPermissions} - * @memberof AccountSASPermissions - */ - AccountSASPermissions.parse = function (permissions) { - var accountSASPermissions = new AccountSASPermissions(); - for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { - var c = permissions_1[_i]; - switch (c) { - case "r": - accountSASPermissions.read = true; - break; - case "w": - accountSASPermissions.write = true; - break; - case "d": - accountSASPermissions.delete = true; - break; - case "x": - accountSASPermissions.deleteVersion = true; - break; - case "l": - accountSASPermissions.list = true; - break; - case "a": - accountSASPermissions.add = true; - break; - case "c": - accountSASPermissions.create = true; - break; - case "u": - accountSASPermissions.update = true; - break; - case "p": - accountSASPermissions.process = true; - break; - case "t": - accountSASPermissions.tag = true; - break; - case "f": - accountSASPermissions.filter = true; - break; - default: - throw new RangeError("Invalid permission character: " + c); - } - } - return accountSASPermissions; - }; - /** - * Creates a {@link AccountSASPermissions} from a raw object which contains same keys as it - * and boolean values for them. - * - * @static - * @param {AccountSASPermissionsLike} permissionLike - * @returns {AccountSASPermissions} - * @memberof AccountSASPermissions - */ - AccountSASPermissions.from = function (permissionLike) { - var accountSASPermissions = new AccountSASPermissions(); - if (permissionLike.read) { - accountSASPermissions.read = true; - } - if (permissionLike.write) { - accountSASPermissions.write = true; - } - if (permissionLike.delete) { - accountSASPermissions.delete = true; - } - if (permissionLike.deleteVersion) { - accountSASPermissions.deleteVersion = true; - } - if (permissionLike.filter) { - accountSASPermissions.filter = true; - } - if (permissionLike.tag) { - accountSASPermissions.tag = true; - } - if (permissionLike.list) { - accountSASPermissions.list = true; - } - if (permissionLike.add) { - accountSASPermissions.add = true; - } - if (permissionLike.create) { - accountSASPermissions.create = true; - } - if (permissionLike.update) { - accountSASPermissions.update = true; - } - if (permissionLike.process) { - accountSASPermissions.process = true; - } - return accountSASPermissions; - }; - /** - * Produces the SAS permissions string for an Azure Storage account. - * Call this method to set AccountSASSignatureValues Permissions field. - * - * Using this method will guarantee the resource types are in - * an order accepted by the service. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas - * - * @returns {string} - * @memberof AccountSASPermissions - */ - AccountSASPermissions.prototype.toString = function () { - // The order of the characters should be as specified here to ensure correctness: - // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas - // Use a string array instead of string concatenating += operator for performance - var permissions = []; - if (this.read) { - permissions.push("r"); - } - if (this.write) { - permissions.push("w"); - } - if (this.delete) { - permissions.push("d"); - } - if (this.deleteVersion) { - permissions.push("x"); - } - if (this.filter) { - permissions.push("f"); - } - if (this.tag) { - permissions.push("t"); - } - if (this.list) { - permissions.push("l"); - } - if (this.add) { - permissions.push("a"); - } - if (this.create) { - permissions.push("c"); - } - if (this.update) { - permissions.push("u"); - } - if (this.process) { - permissions.push("p"); - } - return permissions.join(""); - }; - return AccountSASPermissions; -}()); - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * This is a helper class to construct a string representing the resources accessible by an AccountSAS. Setting a value - * to true means that any SAS which uses these permissions will grant access to that resource type. Once all the - * values are set, this should be serialized with toString and set as the resources field on an - * {@link AccountSASSignatureValues} object. It is possible to construct the resources string without this class, but - * the order of the resources is particular and this class guarantees correctness. - * - * @export - * @class AccountSASResourceTypes - */ -var AccountSASResourceTypes = /** @class */ (function () { - function AccountSASResourceTypes() { - /** - * Permission to access service level APIs granted. - * - * @type {boolean} - * @memberof AccountSASResourceTypes - */ - this.service = false; - /** - * Permission to access container level APIs (Blob Containers, Tables, Queues, File Shares) granted. - * - * @type {boolean} - * @memberof AccountSASResourceTypes - */ - this.container = false; - /** - * Permission to access object level APIs (Blobs, Table Entities, Queue Messages, Files) granted. - * - * @type {boolean} - * @memberof AccountSASResourceTypes - */ - this.object = false; - } - /** - * Creates an {@link AccountSASResourceTypes} from the specified resource types string. This method will throw an - * Error if it encounters a character that does not correspond to a valid resource type. - * - * @static - * @param {string} resourceTypes - * @returns {AccountSASResourceTypes} - * @memberof AccountSASResourceTypes - */ - AccountSASResourceTypes.parse = function (resourceTypes) { - var accountSASResourceTypes = new AccountSASResourceTypes(); - for (var _i = 0, resourceTypes_1 = resourceTypes; _i < resourceTypes_1.length; _i++) { - var c = resourceTypes_1[_i]; - switch (c) { - case "s": - accountSASResourceTypes.service = true; - break; - case "c": - accountSASResourceTypes.container = true; - break; - case "o": - accountSASResourceTypes.object = true; - break; - default: - throw new RangeError("Invalid resource type: " + c); - } - } - return accountSASResourceTypes; + }); + }); }; - /** - * Converts the given resource types to a string. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas - * - * @returns {string} - * @memberof AccountSASResourceTypes - */ - AccountSASResourceTypes.prototype.toString = function () { - var resourceTypes = []; - if (this.service) { - resourceTypes.push("s"); - } - if (this.container) { - resourceTypes.push("c"); - } - if (this.object) { - resourceTypes.push("o"); - } - return resourceTypes.join(""); + return BatchHeaderFilterPolicy; +}(coreHttp.BaseRequestPolicy)); +var BatchHeaderFilterPolicyFactory = /** @class */ (function () { + function BatchHeaderFilterPolicyFactory() { + } + BatchHeaderFilterPolicyFactory.prototype.create = function (nextPolicy, options) { + return new BatchHeaderFilterPolicy(nextPolicy, options); }; - return AccountSASResourceTypes; + return BatchHeaderFilterPolicyFactory; }()); // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. /** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * This is a helper class to construct a string representing the services accessible by an AccountSAS. Setting a value - * to true means that any SAS which uses these permissions will grant access to that service. Once all the - * values are set, this should be serialized with toString and set as the services field on an - * {@link AccountSASSignatureValues} object. It is possible to construct the services string without this class, but - * the order of the services is particular and this class guarantees correctness. + * A BlobBatchClient allows you to make batched requests to the Azure Storage Blob service. * - * @export - * @class AccountSASServices + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch */ -var AccountSASServices = /** @class */ (function () { - function AccountSASServices() { - /** - * Permission to access blob resources granted. - * - * @type {boolean} - * @memberof AccountSASServices - */ - this.blob = false; - /** - * Permission to access file resources granted. - * - * @type {boolean} - * @memberof AccountSASServices - */ - this.file = false; - /** - * Permission to access queue resources granted. - * - * @type {boolean} - * @memberof AccountSASServices - */ - this.queue = false; - /** - * Permission to access table resources granted. - * - * @type {boolean} - * @memberof AccountSASServices - */ - this.table = false; +var BlobBatchClient = /** @class */ (function () { + function BlobBatchClient(url, credentialOrPipeline, options) { + var pipeline; + if (credentialOrPipeline instanceof Pipeline) { + pipeline = credentialOrPipeline; + } + else if (!credentialOrPipeline) { + // no credential provided + pipeline = newPipeline(new AnonymousCredential(), options); + } + else { + pipeline = newPipeline(credentialOrPipeline, options); + } + var storageClientContext = new StorageClientContext(url, pipeline.toServiceClientOptions()); + this._serviceContext = new Service(storageClientContext); } /** - * Creates an {@link AccountSASServices} from the specified services string. This method will throw an - * Error if it encounters a character that does not correspond to a valid service. - * - * @static - * @param {string} services - * @returns {AccountSASServices} - * @memberof AccountSASServices + * Creates a {@link BlobBatch}. + * A BlobBatch represents an aggregated set of operations on blobs. */ - AccountSASServices.parse = function (services) { - var accountSASServices = new AccountSASServices(); - for (var _i = 0, services_1 = services; _i < services_1.length; _i++) { - var c = services_1[_i]; - switch (c) { - case "b": - accountSASServices.blob = true; - break; - case "f": - accountSASServices.file = true; - break; - case "q": - accountSASServices.queue = true; - break; - case "t": - accountSASServices.table = true; - break; - default: - throw new RangeError("Invalid service character: " + c); - } - } - return accountSASServices; + BlobBatchClient.prototype.createBatch = function () { + return new BlobBatch(); + }; + BlobBatchClient.prototype.deleteBlobs = function (urlsOrBlobClients, credentialOrOptions, options) { + return tslib.__awaiter(this, void 0, void 0, function () { + var batch, _i, urlsOrBlobClients_1, urlOrBlobClient; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + batch = new BlobBatch(); + _i = 0, urlsOrBlobClients_1 = urlsOrBlobClients; + _a.label = 1; + case 1: + if (!(_i < urlsOrBlobClients_1.length)) return [3 /*break*/, 6]; + urlOrBlobClient = urlsOrBlobClients_1[_i]; + if (!(typeof urlOrBlobClient === "string")) return [3 /*break*/, 3]; + return [4 /*yield*/, batch.deleteBlob(urlOrBlobClient, credentialOrOptions, options)]; + case 2: + _a.sent(); + return [3 /*break*/, 5]; + case 3: return [4 /*yield*/, batch.deleteBlob(urlOrBlobClient, credentialOrOptions)]; + case 4: + _a.sent(); + _a.label = 5; + case 5: + _i++; + return [3 /*break*/, 1]; + case 6: return [2 /*return*/, this.submitBatch(batch)]; + } + }); + }); + }; + BlobBatchClient.prototype.setBlobsAccessTier = function (urlsOrBlobClients, credentialOrTier, tierOrOptions, options) { + return tslib.__awaiter(this, void 0, void 0, function () { + var batch, _i, urlsOrBlobClients_2, urlOrBlobClient; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + batch = new BlobBatch(); + _i = 0, urlsOrBlobClients_2 = urlsOrBlobClients; + _a.label = 1; + case 1: + if (!(_i < urlsOrBlobClients_2.length)) return [3 /*break*/, 6]; + urlOrBlobClient = urlsOrBlobClients_2[_i]; + if (!(typeof urlOrBlobClient === "string")) return [3 /*break*/, 3]; + return [4 /*yield*/, batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options)]; + case 2: + _a.sent(); + return [3 /*break*/, 5]; + case 3: return [4 /*yield*/, batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions)]; + case 4: + _a.sent(); + _a.label = 5; + case 5: + _i++; + return [3 /*break*/, 1]; + case 6: return [2 /*return*/, this.submitBatch(batch)]; + } + }); + }); }; /** - * Converts the given services to a string. + * Submit batch request which consists of multiple subrequests. * - * @returns {string} - * @memberof AccountSASServices + * Get `blobBatchClient` and other details before running the snippets. + * `blobServiceClient.getBlobBatchClient()` gives the `blobBatchClient` + * + * Example usage: + * + * ```js + * let batchRequest = new BlobBatch(); + * await batchRequest.deleteBlob(urlInString0, credential0); + * await batchRequest.deleteBlob(urlInString1, credential1, { + * deleteSnapshots: "include" + * }); + * const batchResp = await blobBatchClient.submitBatch(batchRequest); + * console.log(batchResp.subResponsesSucceededCount); + * ``` + * + * Example using a lease: + * + * ```js + * let batchRequest = new BlobBatch(); + * await batchRequest.setBlobAccessTier(blockBlobClient0, "Cool"); + * await batchRequest.setBlobAccessTier(blockBlobClient1, "Cool", { + * conditions: { leaseId: leaseId } + * }); + * const batchResp = await blobBatchClient.submitBatch(batchRequest); + * console.log(batchResp.subResponsesSucceededCount); + * ``` + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch + * + * @param {BlobBatch} batchRequest A set of Delete or SetTier operations. + * @param {BlobBatchSubmitBatchOptionalParams} [options] + * @returns {Promise} + * @memberof BlobBatchClient */ - AccountSASServices.prototype.toString = function () { - var services = []; - if (this.blob) { - services.push("b"); - } - if (this.table) { - services.push("t"); - } - if (this.queue) { - services.push("q"); - } - if (this.file) { - services.push("f"); - } - return services.join(""); + BlobBatchClient.prototype.submitBatch = function (batchRequest, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, batchRequestBody, rawBatchResponse, batchResponseParser, responseSummary, res, e_1; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!batchRequest || batchRequest.getSubRequests().size == 0) { + throw new RangeError("Batch request should contain one or more sub requests."); + } + _a = createSpan("BlobBatchClient-submitBatch", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 4, 5, 6]); + batchRequestBody = batchRequest.getHttpRequestBody(); + return [4 /*yield*/, this._serviceContext.submitBatch(batchRequestBody, utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), tslib.__assign(tslib.__assign({}, options), { spanOptions: spanOptions }))]; + case 2: + rawBatchResponse = _b.sent(); + batchResponseParser = new BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests()); + return [4 /*yield*/, batchResponseParser.parseBatchResponse()]; + case 3: + responseSummary = _b.sent(); + res = { + _response: rawBatchResponse._response, + contentType: rawBatchResponse.contentType, + errorCode: rawBatchResponse.errorCode, + requestId: rawBatchResponse.requestId, + clientRequestId: rawBatchResponse.clientRequestId, + version: rawBatchResponse.version, + subResponses: responseSummary.subResponses, + subResponsesSucceededCount: responseSummary.subResponsesSucceededCount, + subResponsesFailedCount: responseSummary.subResponsesFailedCount + }; + return [2 /*return*/, res]; + case 4: + e_1 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_1.message + }); + throw e_1; + case 5: + span.end(); + return [7 /*endfinally*/]; + case 6: return [2 /*return*/]; + } + }); + }); }; - return AccountSASServices; + return BlobBatchClient; }()); -// Copyright (c) Microsoft Corporation. All rights reserved. -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * Generates a {@link SASQueryParameters} object which contains all SAS query parameters needed to make an actual - * REST request. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas - * - * @param {AccountSASSignatureValues} accountSASSignatureValues - * @param {StorageSharedKeyCredential} sharedKeyCredential - * @returns {SASQueryParameters} - * @memberof AccountSASSignatureValues - */ -function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { - var version = accountSASSignatureValues.version - ? accountSASSignatureValues.version - : SERVICE_VERSION; - if (accountSASSignatureValues.permissions && - accountSASSignatureValues.permissions.deleteVersion && - version < "2019-10-10") { - throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); - } - if (accountSASSignatureValues.permissions && - accountSASSignatureValues.permissions.tag && - version < "2019-12-12") { - throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); - } - if (accountSASSignatureValues.permissions && - accountSASSignatureValues.permissions.filter && - version < "2019-12-12") { - throw RangeError("'version' must be >= '2019-12-12' when provided 'f' permission."); - } - var parsedPermissions = AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()); - var parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); - var parsedResourceTypes = AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString(); - var stringToSign = [ - sharedKeyCredential.accountName, - parsedPermissions, - parsedServices, - parsedResourceTypes, - accountSASSignatureValues.startsOn - ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) - : "", - truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), - accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", - accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", - version, - "" // Account SAS requires an additional newline character - ].join("\n"); - var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(version, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange); -} - /** * A BlobServiceClient represents a Client to the Azure Storage Blob service allowing you * to manipulate blob containers. @@ -35411,86 +33462,330 @@ var BlobServiceClient = /** @class */ (function (_super) { } /** * - * Creates an instance of BlobServiceClient from connection string. - * - * @param {string} connectionString Account connection string or a SAS connection string of an Azure storage account. - * [ Note - Account connection string can only be used in NODE.JS runtime. ] - * Account connection string example - - * `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net` - * SAS connection string example - - * `BlobEndpoint=https://myaccount.blob.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString` - * @param {StoragePipelineOptions} [options] Optional. Options to configure the HTTP pipeline. + * Creates an instance of BlobServiceClient from connection string. + * + * @param {string} connectionString Account connection string or a SAS connection string of an Azure storage account. + * [ Note - Account connection string can only be used in NODE.JS runtime. ] + * Account connection string example - + * `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net` + * SAS connection string example - + * `BlobEndpoint=https://myaccount.blob.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString` + * @param {StoragePipelineOptions} [options] Optional. Options to configure the HTTP pipeline. + * @memberof BlobServiceClient + */ + BlobServiceClient.fromConnectionString = function (connectionString, options) { + options = options || {}; + var extractedCreds = extractConnectionStringParts(connectionString); + if (extractedCreds.kind === "AccountConnString") { + { + var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); + var pipeline = newPipeline(sharedKeyCredential, options); + return new BlobServiceClient(extractedCreds.url, pipeline); + } + } + else if (extractedCreds.kind === "SASConnString") { + var pipeline = newPipeline(new AnonymousCredential(), options); + return new BlobServiceClient(extractedCreds.url + "?" + extractedCreds.accountSas, pipeline); + } + else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + }; + /** + * Creates a {@link ContainerClient} object + * + * @param {string} containerName A container name + * @returns {ContainerClient} A new ContainerClient object for the given container name. + * @memberof BlobServiceClient + * + * Example usage: + * + * ```js + * const containerClient = blobServiceClient.getContainerClient(""); + * ``` + */ + BlobServiceClient.prototype.getContainerClient = function (containerName) { + return new ContainerClient(appendToURLPath(this.url, encodeURIComponent(containerName)), this.pipeline); + }; + /** + * Create a Blob container. + * + * @param {string} containerName Name of the container to create. + * @param {ContainerCreateOptions} [options] Options to configure Container Create operation. + * @returns {Promise<{ containerClient: ContainerClient; containerCreateResponse: ContainerCreateResponse }>} Container creation response and the corresponding container client. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.createContainer = function (containerName, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, containerClient, containerCreateResponse, e_1; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-createContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + containerClient = this.getContainerClient(containerName); + return [4 /*yield*/, containerClient.create(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: + containerCreateResponse = _b.sent(); + return [2 /*return*/, { + containerClient: containerClient, + containerCreateResponse: containerCreateResponse + }]; + case 3: + e_1 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_1.message + }); + throw e_1; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Deletes a Blob container. + * + * @param {string} containerName Name of the container to delete. + * @param {ContainerDeleteMethodOptions} [options] Options to configure Container Delete operation. + * @returns {Promise} Container deletion response. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.deleteContainer = function (containerName, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, containerClient, e_2; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-deleteContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + containerClient = this.getContainerClient(containerName); + return [4 /*yield*/, containerClient.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_2 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_2.message + }); + throw e_2; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Gets the properties of a storage account’s Blob service, including properties + * for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties + * + * @param {ServiceGetPropertiesOptions} [options] Options to the Service Get Properties operation. + * @returns {Promise} Response data for the Service Get Properties operation. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.getProperties = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_3; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-getProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.getProperties({ + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_3 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_3.message + }); + throw e_3; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Sets properties for a storage account’s Blob service endpoint, including properties + * for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules and soft delete settings. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties} + * + * @param {BlobServiceProperties} properties + * @param {ServiceSetPropertiesOptions} [options] Options to the Service Set Properties operation. + * @returns {Promise} Response data for the Service Set Properties operation. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.setProperties = function (properties, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_4; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-setProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.setProperties(properties, { + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_4 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_4.message + }); + throw e_4; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Retrieves statistics related to replication for the Blob service. It is only + * available on the secondary location endpoint when read-access geo-redundant + * replication is enabled for the storage account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-stats} + * + * @param {ServiceGetStatisticsOptions} [options] Options to the Service Get Statistics operation. + * @returns {Promise} Response data for the Service Get Statistics operation. * @memberof BlobServiceClient */ - BlobServiceClient.fromConnectionString = function (connectionString, options) { - options = options || {}; - var extractedCreds = extractConnectionStringParts(connectionString); - if (extractedCreds.kind === "AccountConnString") { - { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); - var pipeline = newPipeline(sharedKeyCredential, options); - return new BlobServiceClient(extractedCreds.url, pipeline); - } - } - else if (extractedCreds.kind === "SASConnString") { - var pipeline = newPipeline(new AnonymousCredential(), options); - return new BlobServiceClient(extractedCreds.url + "?" + extractedCreds.accountSas, pipeline); - } - else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); - } + BlobServiceClient.prototype.getStatistics = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_5; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-getStatistics", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.getStatistics({ + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_5 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_5.message + }); + throw e_5; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; /** - * Creates a {@link ContainerClient} object + * The Get Account Information operation returns the sku name and account kind + * for the specified account. + * The Get Account Information operation is available on service versions beginning + * with version 2018-03-28. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information * - * @param {string} containerName A container name - * @returns {ContainerClient} A new ContainerClient object for the given container name. + * @param {ServiceGetAccountInfoOptions} [options] Options to the Service Get Account Info operation. + * @returns {Promise} Response data for the Service Get Account Info operation. * @memberof BlobServiceClient - * - * Example usage: - * - * ```js - * const containerClient = blobServiceClient.getContainerClient(""); - * ``` */ - BlobServiceClient.prototype.getContainerClient = function (containerName) { - return new ContainerClient(appendToURLPath(this.url, encodeURIComponent(containerName)), this.pipeline); + BlobServiceClient.prototype.getAccountInfo = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_6; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-getAccountInfo", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.getAccountInfo({ + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_6 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_6.message + }); + throw e_6; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; /** - * Create a Blob container. + * Returns a list of the containers under the specified account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/list-containers2 * - * @param {string} containerName Name of the container to create. - * @param {ContainerCreateOptions} [options] Options to configure Container Create operation. - * @returns {Promise<{ containerClient: ContainerClient; containerCreateResponse: ContainerCreateResponse }>} Container creation response and the corresponding container client. + * @param {string} [marker] A string value that identifies the portion of + * the list of containers to be returned with the next listing operation. The + * operation returns the NextMarker value within the response body if the + * listing operation did not return all containers remaining to be listed + * with the current page. The NextMarker value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ServiceListContainersSegmentOptions} [options] Options to the Service List Container Segment operation. + * @returns {Promise} Response data for the Service List Container Segment operation. * @memberof BlobServiceClient */ - BlobServiceClient.prototype.createContainer = function (containerName, options) { + BlobServiceClient.prototype.listContainersSegment = function (marker, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, containerClient, containerCreateResponse, e_1; + var _a, span, spanOptions, e_7; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("BlobServiceClient-createContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("BlobServiceClient-listContainersSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - containerClient = this.getContainerClient(containerName); - return [4 /*yield*/, containerClient.create(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: - containerCreateResponse = _b.sent(); - return [2 /*return*/, { - containerClient: containerClient, - containerCreateResponse: containerCreateResponse - }]; + return [4 /*yield*/, this.serviceContext.listContainersSegment(tslib.__assign(tslib.__assign({ abortSignal: options.abortSignal, marker: marker }, options), { include: typeof options.include === "string" ? [options.include] : options.include, spanOptions: spanOptions }))]; + case 2: return [2 /*return*/, _b.sent()]; case 3: - e_1 = _b.sent(); + e_7 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_1.message + message: e_7.message }); - throw e_1; + throw e_7; case 4: span.end(); return [7 /*endfinally*/]; @@ -35500,34 +33795,52 @@ var BlobServiceClient = /** @class */ (function (_super) { }); }; /** - * Deletes a Blob container. + * The Filter Blobs operation enables callers to list blobs across all containers whose tags + * match a given search expression. Filter blobs searches across all containers within a + * storage account but can be scoped within the expression to a single container. * - * @param {string} containerName Name of the container to delete. - * @param {ContainerDeleteMethodOptions} [options] Options to configure Container Delete operation. - * @returns {Promise} Container deletion response. + * @private + * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param {string} [marker] A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the NextMarker value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The NextMarker value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to find blobs by tags. + * @returns {Promise} * @memberof BlobServiceClient */ - BlobServiceClient.prototype.deleteContainer = function (containerName, options) { + BlobServiceClient.prototype.findBlobsByTagsSegment = function (tagFilterSqlExpression, marker, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, containerClient, e_2; + var _a, span, spanOptions, e_8; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("BlobServiceClient-deleteContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("BlobServiceClient-findBlobsByTagsSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - containerClient = this.getContainerClient(containerName); - return [4 /*yield*/, containerClient.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + return [4 /*yield*/, this.serviceContext.filterBlobs({ + abortSignal: options.abortSignal, + where: tagFilterSqlExpression, + marker: marker, + maxPageSize: options.maxPageSize, + spanOptions: spanOptions + })]; case 2: return [2 /*return*/, _b.sent()]; case 3: - e_2 = _b.sent(); + e_8 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_2.message + message: e_8.message }); - throw e_2; + throw e_8; case 4: span.end(); return [7 /*endfinally*/]; @@ -35537,79 +33850,471 @@ var BlobServiceClient = /** @class */ (function (_super) { }); }; /** - * Restore a previously deleted Blob container. - * This API is only functional if Container Soft Delete is enabled for the storage account associated with the container. + * Returns an AsyncIterableIterator for ServiceFindBlobsByTagsSegmentResponse. + * + * @private + * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param {string} [marker] A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the NextMarker value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The NextMarker value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to find blobs by tags. + * @returns {AsyncIterableIterator} + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.findBlobsByTagsSegments = function (tagFilterSqlExpression, marker, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function findBlobsByTagsSegments_1() { + var response; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!(!!marker || marker === undefined)) return [3 /*break*/, 6]; + _a.label = 1; + case 1: return [4 /*yield*/, tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker, options))]; + case 2: + response = _a.sent(); + response.blobs = response.blobs || []; + marker = response.continuationToken; + return [4 /*yield*/, tslib.__await(response)]; + case 3: return [4 /*yield*/, _a.sent()]; + case 4: + _a.sent(); + _a.label = 5; + case 5: + if (marker) return [3 /*break*/, 1]; + _a.label = 6; + case 6: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an AsyncIterableIterator for blobs. + * + * @private + * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to findBlobsByTagsItems. + * @returns {AsyncIterableIterator} + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.findBlobsByTagsItems = function (tagFilterSqlExpression, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function findBlobsByTagsItems_1() { + var marker, _a, _b, segment, e_9_1; + var e_9, _c; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: + _d.trys.push([0, 7, 8, 13]); + _a = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker, options)); + _d.label = 1; + case 1: return [4 /*yield*/, tslib.__await(_a.next())]; + case 2: + if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; + segment = _b.value; + return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs)))]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; + case 4: + _d.sent(); + _d.label = 5; + case 5: return [3 /*break*/, 1]; + case 6: return [3 /*break*/, 13]; + case 7: + e_9_1 = _d.sent(); + e_9 = { error: e_9_1 }; + return [3 /*break*/, 13]; + case 8: + _d.trys.push([8, , 11, 12]); + if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; + return [4 /*yield*/, tslib.__await(_c.call(_a))]; + case 9: + _d.sent(); + _d.label = 10; + case 10: return [3 /*break*/, 12]; + case 11: + if (e_9) throw e_9.error; + return [7 /*endfinally*/]; + case 12: return [7 /*endfinally*/]; + case 13: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an async iterable iterator to find all blobs with specified tag + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the blobs in pages. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties + * + * Example using `for await` syntax: + * + * ```js + * let i = 1; + * for await (const blob of blobServiceClient.findBlobsByTags("tagkey='tagvalue'")) { + * console.log(`Blob ${i++}: ${container.name}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * const iter = blobServiceClient.findBlobsByTags("tagkey='tagvalue'"); + * let blobItem = await iter.next(); + * while (!blobItem.done) { + * console.log(`Blob ${i++}: ${blobItem.value.name}`); + * blobItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 blob names + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * // Passing next marker as continuationToken + * iterator = blobServiceClient + * .findBlobsByTags("tagkey='tagvalue'") + * .byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints blob names + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * ``` + * + * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param {ServiceFindBlobByTagsOptions} [options={}] Options to find blobs by tags. + * @returns {PagedAsyncIterableIterator} + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.findBlobsByTags = function (tagFilterSqlExpression, options) { + var _a; + var _this = this; + if (options === void 0) { options = {}; } + // AsyncIterableIterator to iterate over blobs + var listSegmentOptions = tslib.__assign({}, options); + var iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); + return _a = { + /** + * @member {Promise} [next] The next method, part of the iteration protocol + */ + next: function () { + return iter.next(); + } + }, + /** + * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol + */ + _a[Symbol.asyncIterator] = function () { + return this; + }, + /** + * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time + */ + _a.byPage = function (settings) { + if (settings === void 0) { settings = {}; } + return _this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + }, + _a; + }; + /** + * Returns an AsyncIterableIterator for ServiceListContainersSegmentResponses + * + * @private + * @param {string} [marker] A string value that identifies the portion of + * the list of containers to be returned with the next listing operation. The + * operation returns the NextMarker value within the response body if the + * listing operation did not return all containers remaining to be listed + * with the current page. The NextMarker value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ServiceListContainersSegmentOptions} [options] Options to list containers operation. + * @returns {AsyncIterableIterator} + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.listSegments = function (marker, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listSegments_1() { + var listContainersSegmentResponse; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!(!!marker || marker === undefined)) return [3 /*break*/, 7]; + _a.label = 1; + case 1: return [4 /*yield*/, tslib.__await(this.listContainersSegment(marker, options))]; + case 2: + listContainersSegmentResponse = _a.sent(); + listContainersSegmentResponse.containerItems = + listContainersSegmentResponse.containerItems || []; + marker = listContainersSegmentResponse.continuationToken; + return [4 /*yield*/, tslib.__await(listContainersSegmentResponse)]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_a.sent()])]; + case 4: return [4 /*yield*/, _a.sent()]; + case 5: + _a.sent(); + _a.label = 6; + case 6: + if (marker) return [3 /*break*/, 1]; + _a.label = 7; + case 7: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an AsyncIterableIterator for Container Items + * + * @private + * @param {ServiceListContainersSegmentOptions} [options] Options to list containers operation. + * @returns {AsyncIterableIterator} + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.listItems = function (options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listItems_1() { + var marker, _a, _b, segment, e_10_1; + var e_10, _c; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: + _d.trys.push([0, 7, 8, 13]); + _a = tslib.__asyncValues(this.listSegments(marker, options)); + _d.label = 1; + case 1: return [4 /*yield*/, tslib.__await(_a.next())]; + case 2: + if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; + segment = _b.value; + return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(segment.containerItems)))]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; + case 4: + _d.sent(); + _d.label = 5; + case 5: return [3 /*break*/, 1]; + case 6: return [3 /*break*/, 13]; + case 7: + e_10_1 = _d.sent(); + e_10 = { error: e_10_1 }; + return [3 /*break*/, 13]; + case 8: + _d.trys.push([8, , 11, 12]); + if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; + return [4 /*yield*/, tslib.__await(_c.call(_a))]; + case 9: + _d.sent(); + _d.label = 10; + case 10: return [3 /*break*/, 12]; + case 11: + if (e_10) throw e_10.error; + return [7 /*endfinally*/]; + case 12: return [7 /*endfinally*/]; + case 13: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an async iterable iterator to list all the containers + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the containers in pages. + * + * Example using `for await` syntax: + * + * ```js + * let i = 1; + * for await (const container of blobServiceClient.listContainers()) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * const iter = blobServiceClient.listContainers(); + * let containerItem = await iter.next(); + * while (!containerItem.done) { + * console.log(`Container ${i++}: ${containerItem.value.name}`); + * containerItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of blobServiceClient.listContainers().byPage({ maxPageSize: 20 })) { + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = blobServiceClient.listContainers().byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 container names + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * // Passing next marker as continuationToken + * iterator = blobServiceClient + * .listContainers() + * .byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints 10 container names + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * ``` * - * @param {string} deletedContainerName Name of the previously deleted container. - * @param {string} deletedContainerVersion Version of the previously deleted container, used to uniquely identify the deleted container. - * @returns {Promise} Container deletion response. + * @param {ServiceListContainersOptions} [options={}] Options to list containers. + * @returns {PagedAsyncIterableIterator} An asyncIterableIterator that supports paging. * @memberof BlobServiceClient */ - BlobServiceClient.prototype.undeleteContainer = function (deletedContainerName, deletedContainerVersion, options) { + BlobServiceClient.prototype.listContainers = function (options) { + var _a; + var _this = this; if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, containerClient, containerContext, containerUndeleteResponse, e_3; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-undeleteContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - containerClient = this.getContainerClient(options.destinationContainerName || deletedContainerName); - containerContext = new Container(containerClient["storageClientContext"]); - return [4 /*yield*/, containerContext.restore(tslib.__assign(tslib.__assign({ deletedContainerName: deletedContainerName, - deletedContainerVersion: deletedContainerVersion }, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: - containerUndeleteResponse = _b.sent(); - return [2 /*return*/, { containerClient: containerClient, containerUndeleteResponse: containerUndeleteResponse }]; - case 3: - e_3 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_3.message - }); - throw e_3; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + if (options.prefix === "") { + options.prefix = undefined; + } + // AsyncIterableIterator to iterate over containers + var listSegmentOptions = tslib.__assign(tslib.__assign({}, options), (options.includeMetadata ? { include: "metadata" } : {})); + var iter = this.listItems(listSegmentOptions); + return _a = { + /** + * @member {Promise} [next] The next method, part of the iteration protocol + */ + next: function () { + return iter.next(); } - }); - }); + }, + /** + * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol + */ + _a[Symbol.asyncIterator] = function () { + return this; + }, + /** + * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time + */ + _a.byPage = function (settings) { + if (settings === void 0) { settings = {}; } + return _this.listSegments(settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + }, + _a; }; /** - * Gets the properties of a storage account’s Blob service, including properties - * for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties + * ONLY AVAILABLE WHEN USING BEARER TOKEN AUTHENTICATION (TokenCredential). * - * @param {ServiceGetPropertiesOptions} [options] Options to the Service Get Properties operation. - * @returns {Promise} Response data for the Service Get Properties operation. + * Retrieves a user delegation key for the Blob service. This is only a valid operation when using + * bearer token authentication. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-user-delegation-key + * + * @param {Date} startsOn The start time for the user delegation SAS. Must be within 7 days of the current time + * @param {Date} expiresOn The end time for the user delegation SAS. Must be within 7 days of the current time + * @returns {Promise} * @memberof BlobServiceClient */ - BlobServiceClient.prototype.getProperties = function (options) { + BlobServiceClient.prototype.getUserDelegationKey = function (startsOn, expiresOn, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_4; + var _a, span, spanOptions, response, userDelegationKey, res, e_11; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("BlobServiceClient-getProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("BlobServiceClient-getUserDelegationKey", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getProperties({ + return [4 /*yield*/, this.serviceContext.getUserDelegationKey({ + startsOn: truncatedISO8061Date(startsOn, false), + expiresOn: truncatedISO8061Date(expiresOn, false) + }, { abortSignal: options.abortSignal, spanOptions: spanOptions })]; - case 2: return [2 /*return*/, _b.sent()]; + case 2: + response = _b.sent(); + userDelegationKey = { + signedObjectId: response.signedObjectId, + signedTenantId: response.signedTenantId, + signedStartsOn: new Date(response.signedStartsOn), + signedExpiresOn: new Date(response.signedExpiresOn), + signedService: response.signedService, + signedVersion: response.signedVersion, + value: response.value + }; + res = tslib.__assign({ _response: response._response, requestId: response.requestId, clientRequestId: response.clientRequestId, version: response.version, date: response.date, errorCode: response.errorCode }, userDelegationKey); + return [2 /*return*/, res]; case 3: - e_4 = _b.sent(); + e_11 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_4.message + message: e_11.message }); - throw e_4; + throw e_11; case 4: span.end(); return [7 /*endfinally*/]; @@ -35619,762 +34324,1342 @@ var BlobServiceClient = /** @class */ (function (_super) { }); }; /** - * Sets properties for a storage account’s Blob service endpoint, including properties - * for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules and soft delete settings. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties} + * Creates a BlobBatchClient object to conduct batch operations. * - * @param {BlobServiceProperties} properties - * @param {ServiceSetPropertiesOptions} [options] Options to the Service Set Properties operation. - * @returns {Promise} Response data for the Service Set Properties operation. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch + * + * @returns {BlobBatchClient} A new BlobBatchClient object for this service. * @memberof BlobServiceClient */ - BlobServiceClient.prototype.setProperties = function (properties, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_5; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-setProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.setProperties(properties, { - abortSignal: options.abortSignal, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_5 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_5.message - }); - throw e_5; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + BlobServiceClient.prototype.getBlobBatchClient = function () { + return new BlobBatchClient(this.url, this.pipeline); }; + return BlobServiceClient; +}(StorageClient)); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * This is a helper class to construct a string representing the permissions granted by an AccountSAS. Setting a value + * to true means that any SAS which uses these permissions will grant permissions for that operation. Once all the + * values are set, this should be serialized with toString and set as the permissions field on an + * {@link AccountSASSignatureValues} object. It is possible to construct the permissions string without this class, but + * the order of the permissions is particular and this class guarantees correctness. + * + * @export + * @class AccountSASPermissions + */ +var AccountSASPermissions = /** @class */ (function () { + function AccountSASPermissions() { + /** + * Permission to read resources and list queues and tables granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.read = false; + /** + * Permission to write resources granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.write = false; + /** + * Permission to create blobs and files granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.delete = false; + /** + * Permission to delete versions granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.deleteVersion = false; + /** + * Permission to list blob containers, blobs, shares, directories, and files granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.list = false; + /** + * Permission to add messages, table entities, and append to blobs granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.add = false; + /** + * Permission to create blobs and files granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.create = false; + /** + * Permissions to update messages and table entities granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.update = false; + /** + * Permission to get and delete messages granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.process = false; + /** + * Specfies Tag access granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.tag = false; + /** + * Permission to filter blobs. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.filter = false; + } /** - * Retrieves statistics related to replication for the Blob service. It is only - * available on the secondary location endpoint when read-access geo-redundant - * replication is enabled for the storage account. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-stats} + * Parse initializes the AccountSASPermissions fields from a string. * - * @param {ServiceGetStatisticsOptions} [options] Options to the Service Get Statistics operation. - * @returns {Promise} Response data for the Service Get Statistics operation. - * @memberof BlobServiceClient + * @static + * @param {string} permissions + * @returns {AccountSASPermissions} + * @memberof AccountSASPermissions */ - BlobServiceClient.prototype.getStatistics = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_6; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-getStatistics", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getStatistics({ - abortSignal: options.abortSignal, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_6 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_6.message - }); - throw e_6; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + AccountSASPermissions.parse = function (permissions) { + var accountSASPermissions = new AccountSASPermissions(); + for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { + var c = permissions_1[_i]; + switch (c) { + case "r": + accountSASPermissions.read = true; + break; + case "w": + accountSASPermissions.write = true; + break; + case "d": + accountSASPermissions.delete = true; + break; + case "x": + accountSASPermissions.deleteVersion = true; + break; + case "l": + accountSASPermissions.list = true; + break; + case "a": + accountSASPermissions.add = true; + break; + case "c": + accountSASPermissions.create = true; + break; + case "u": + accountSASPermissions.update = true; + break; + case "p": + accountSASPermissions.process = true; + break; + case "t": + accountSASPermissions.tag = true; + break; + case "f": + accountSASPermissions.filter = true; + break; + default: + throw new RangeError("Invalid permission character: " + c); + } + } + return accountSASPermissions; }; /** - * The Get Account Information operation returns the sku name and account kind - * for the specified account. - * The Get Account Information operation is available on service versions beginning - * with version 2018-03-28. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information + * Produces the SAS permissions string for an Azure Storage account. + * Call this method to set AccountSASSignatureValues Permissions field. * - * @param {ServiceGetAccountInfoOptions} [options] Options to the Service Get Account Info operation. - * @returns {Promise} Response data for the Service Get Account Info operation. - * @memberof BlobServiceClient + * Using this method will guarantee the resource types are in + * an order accepted by the service. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas + * + * @returns {string} + * @memberof AccountSASPermissions */ - BlobServiceClient.prototype.getAccountInfo = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_7; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-getAccountInfo", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getAccountInfo({ - abortSignal: options.abortSignal, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_7 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_7.message - }); - throw e_7; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + AccountSASPermissions.prototype.toString = function () { + // The order of the characters should be as specified here to ensure correctness: + // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas + // Use a string array instead of string concatenating += operator for performance + var permissions = []; + if (this.read) { + permissions.push("r"); + } + if (this.write) { + permissions.push("w"); + } + if (this.delete) { + permissions.push("d"); + } + if (this.deleteVersion) { + permissions.push("x"); + } + if (this.filter) { + permissions.push("f"); + } + if (this.tag) { + permissions.push("t"); + } + if (this.list) { + permissions.push("l"); + } + if (this.add) { + permissions.push("a"); + } + if (this.create) { + permissions.push("c"); + } + if (this.update) { + permissions.push("u"); + } + if (this.process) { + permissions.push("p"); + } + return permissions.join(""); }; + return AccountSASPermissions; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * This is a helper class to construct a string representing the resources accessible by an AccountSAS. Setting a value + * to true means that any SAS which uses these permissions will grant access to that resource type. Once all the + * values are set, this should be serialized with toString and set as the resources field on an + * {@link AccountSASSignatureValues} object. It is possible to construct the resources string without this class, but + * the order of the resources is particular and this class guarantees correctness. + * + * @export + * @class AccountSASResourceTypes + */ +var AccountSASResourceTypes = /** @class */ (function () { + function AccountSASResourceTypes() { + /** + * Permission to access service level APIs granted. + * + * @type {boolean} + * @memberof AccountSASResourceTypes + */ + this.service = false; + /** + * Permission to access container level APIs (Blob Containers, Tables, Queues, File Shares) granted. + * + * @type {boolean} + * @memberof AccountSASResourceTypes + */ + this.container = false; + /** + * Permission to access object level APIs (Blobs, Table Entities, Queue Messages, Files) granted. + * + * @type {boolean} + * @memberof AccountSASResourceTypes + */ + this.object = false; + } /** - * Returns a list of the containers under the specified account. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/list-containers2 + * Creates an {@link AccountSASResourceTypes} from the specified resource types string. This method will throw an + * Error if it encounters a character that does not correspond to a valid resource type. * - * @param {string} [marker] A string value that identifies the portion of - * the list of containers to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all containers remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param {ServiceListContainersSegmentOptions} [options] Options to the Service List Container Segment operation. - * @returns {Promise} Response data for the Service List Container Segment operation. - * @memberof BlobServiceClient + * @static + * @param {string} resourceTypes + * @returns {AccountSASResourceTypes} + * @memberof AccountSASResourceTypes */ - BlobServiceClient.prototype.listContainersSegment = function (marker, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_8; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-listContainersSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.listContainersSegment(tslib.__assign(tslib.__assign({ abortSignal: options.abortSignal, marker: marker }, options), { include: typeof options.include === "string" ? [options.include] : options.include, spanOptions: spanOptions }))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_8 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_8.message - }); - throw e_8; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + AccountSASResourceTypes.parse = function (resourceTypes) { + var accountSASResourceTypes = new AccountSASResourceTypes(); + for (var _i = 0, resourceTypes_1 = resourceTypes; _i < resourceTypes_1.length; _i++) { + var c = resourceTypes_1[_i]; + switch (c) { + case "s": + accountSASResourceTypes.service = true; + break; + case "c": + accountSASResourceTypes.container = true; + break; + case "o": + accountSASResourceTypes.object = true; + break; + default: + throw new RangeError("Invalid resource type: " + c); + } + } + return accountSASResourceTypes; }; /** - * The Filter Blobs operation enables callers to list blobs across all containers whose tags - * match a given search expression. Filter blobs searches across all containers within a - * storage account but can be scoped within the expression to a single container. + * Converts the given resource types to a string. * - * @private - * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param {string} [marker] A string value that identifies the portion of - * the list of blobs to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all blobs remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to find blobs by tags. - * @returns {Promise} - * @memberof BlobServiceClient + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas + * + * @returns {string} + * @memberof AccountSASResourceTypes */ - BlobServiceClient.prototype.findBlobsByTagsSegment = function (tagFilterSqlExpression, marker, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, response, wrappedResponse, e_9; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-findBlobsByTagsSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.filterBlobs({ - abortSignal: options.abortSignal, - where: tagFilterSqlExpression, - marker: marker, - maxPageSize: options.maxPageSize, - spanOptions: spanOptions - })]; - case 2: - response = _b.sent(); - wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, blobs: response.blobs.map(function (blob) { - var _a; - var tagValue = ""; - if (((_a = blob.tags) === null || _a === void 0 ? void 0 : _a.blobTagSet.length) === 1) { - tagValue = blob.tags.blobTagSet[0].value; - } - return tslib.__assign(tslib.__assign({}, blob), { tags: toTags(blob.tags), tagValue: tagValue }); - }) }); - return [2 /*return*/, wrappedResponse]; - case 3: - e_9 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_9.message - }); - throw e_9; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + AccountSASResourceTypes.prototype.toString = function () { + var resourceTypes = []; + if (this.service) { + resourceTypes.push("s"); + } + if (this.container) { + resourceTypes.push("c"); + } + if (this.object) { + resourceTypes.push("o"); + } + return resourceTypes.join(""); }; + return AccountSASResourceTypes; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * This is a helper class to construct a string representing the services accessible by an AccountSAS. Setting a value + * to true means that any SAS which uses these permissions will grant access to that service. Once all the + * values are set, this should be serialized with toString and set as the services field on an + * {@link AccountSASSignatureValues} object. It is possible to construct the services string without this class, but + * the order of the services is particular and this class guarantees correctness. + * + * @export + * @class AccountSASServices + */ +var AccountSASServices = /** @class */ (function () { + function AccountSASServices() { + /** + * Permission to access blob resources granted. + * + * @type {boolean} + * @memberof AccountSASServices + */ + this.blob = false; + /** + * Permission to access file resources granted. + * + * @type {boolean} + * @memberof AccountSASServices + */ + this.file = false; + /** + * Permission to access queue resources granted. + * + * @type {boolean} + * @memberof AccountSASServices + */ + this.queue = false; + /** + * Permission to access table resources granted. + * + * @type {boolean} + * @memberof AccountSASServices + */ + this.table = false; + } /** - * Returns an AsyncIterableIterator for ServiceFindBlobsByTagsSegmentResponse. + * Creates an {@link AccountSASServices} from the specified services string. This method will throw an + * Error if it encounters a character that does not correspond to a valid service. * - * @private - * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param {string} [marker] A string value that identifies the portion of - * the list of blobs to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all blobs remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to find blobs by tags. - * @returns {AsyncIterableIterator} - * @memberof BlobServiceClient + * @static + * @param {string} services + * @returns {AccountSASServices} + * @memberof AccountSASServices */ - BlobServiceClient.prototype.findBlobsByTagsSegments = function (tagFilterSqlExpression, marker, options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function findBlobsByTagsSegments_1() { - var response; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!(!!marker || marker === undefined)) return [3 /*break*/, 6]; - _a.label = 1; - case 1: return [4 /*yield*/, tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker, options))]; - case 2: - response = _a.sent(); - response.blobs = response.blobs || []; - marker = response.continuationToken; - return [4 /*yield*/, tslib.__await(response)]; - case 3: return [4 /*yield*/, _a.sent()]; - case 4: - _a.sent(); - _a.label = 5; - case 5: - if (marker) return [3 /*break*/, 1]; - _a.label = 6; - case 6: return [2 /*return*/]; - } - }); - }); + AccountSASServices.parse = function (services) { + var accountSASServices = new AccountSASServices(); + for (var _i = 0, services_1 = services; _i < services_1.length; _i++) { + var c = services_1[_i]; + switch (c) { + case "b": + accountSASServices.blob = true; + break; + case "f": + accountSASServices.file = true; + break; + case "q": + accountSASServices.queue = true; + break; + case "t": + accountSASServices.table = true; + break; + default: + throw new RangeError("Invalid service character: " + c); + } + } + return accountSASServices; }; /** - * Returns an AsyncIterableIterator for blobs. + * Converts the given services to a string. * - * @private - * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to findBlobsByTagsItems. - * @returns {AsyncIterableIterator} - * @memberof BlobServiceClient + * @returns {string} + * @memberof AccountSASServices */ - BlobServiceClient.prototype.findBlobsByTagsItems = function (tagFilterSqlExpression, options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function findBlobsByTagsItems_1() { - var marker, _a, _b, segment, e_10_1; - var e_10, _c; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _d.trys.push([0, 7, 8, 13]); - _a = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker, options)); - _d.label = 1; - case 1: return [4 /*yield*/, tslib.__await(_a.next())]; - case 2: - if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; - segment = _b.value; - return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs)))]; - case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; - case 4: - _d.sent(); - _d.label = 5; - case 5: return [3 /*break*/, 1]; - case 6: return [3 /*break*/, 13]; - case 7: - e_10_1 = _d.sent(); - e_10 = { error: e_10_1 }; - return [3 /*break*/, 13]; - case 8: - _d.trys.push([8, , 11, 12]); - if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; - return [4 /*yield*/, tslib.__await(_c.call(_a))]; - case 9: - _d.sent(); - _d.label = 10; - case 10: return [3 /*break*/, 12]; - case 11: - if (e_10) throw e_10.error; - return [7 /*endfinally*/]; - case 12: return [7 /*endfinally*/]; - case 13: return [2 /*return*/]; - } - }); - }); + AccountSASServices.prototype.toString = function () { + var services = []; + if (this.blob) { + services.push("b"); + } + if (this.table) { + services.push("t"); + } + if (this.queue) { + services.push("q"); + } + if (this.file) { + services.push("f"); + } + return services.join(""); }; + return AccountSASServices; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * Generate SasIPRange format string. For example: + * + * "8.8.8.8" or "1.1.1.1-255.255.255.255" + * + * @export + * @param {SasIPRange} ipRange + * @returns {string} + */ +function ipRangeToString(ipRange) { + return ipRange.end ? ipRange.start + "-" + ipRange.end : ipRange.start; +} + +// Copyright (c) Microsoft Corporation. All rights reserved. +(function (SASProtocol) { /** - * Returns an async iterable iterator to find all blobs with specified tag - * under the specified account. - * - * .byPage() returns an async iterable iterator to list the blobs in pages. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties - * - * Example using `for await` syntax: - * - * ```js - * let i = 1; - * for await (const blob of blobServiceClient.findBlobsByTags("tagkey='tagvalue'")) { - * console.log(`Blob ${i++}: ${container.name}`); - * } - * ``` - * - * Example using `iter.next()`: - * - * ```js - * let i = 1; - * const iter = blobServiceClient.findBlobsByTags("tagkey='tagvalue'"); - * let blobItem = await iter.next(); - * while (!blobItem.done) { - * console.log(`Blob ${i++}: ${blobItem.value.name}`); - * blobItem = await iter.next(); - * } - * ``` - * - * Example using `byPage()`: - * - * ```js - * // passing optional maxPageSize in the page settings - * let i = 1; - * for await (const response of blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { - * if (response.blobs) { - * for (const blob of response.blobs) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } - * } - * ``` - * - * Example using paging with a marker: - * - * ```js - * let i = 1; - * let iterator = blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); - * let response = (await iterator.next()).value; - * - * // Prints 2 blob names - * if (response.blobs) { - * for (const blob of response.blobs) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } - * - * // Gets next marker - * let marker = response.continuationToken; - * // Passing next marker as continuationToken - * iterator = blobServiceClient - * .findBlobsByTags("tagkey='tagvalue'") - * .byPage({ continuationToken: marker, maxPageSize: 10 }); - * response = (await iterator.next()).value; - * - * // Prints blob names - * if (response.blobs) { - * for (const blob of response.blobs) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } - * ``` + * Protocol that allows HTTPS only + */ + SASProtocol["Https"] = "https"; + /** + * Protocol that allows both HTTPS and HTTP + */ + SASProtocol["HttpsAndHttp"] = "https,http"; +})(exports.SASProtocol || (exports.SASProtocol = {})); +/** + * Represents the components that make up an Azure Storage SAS' query parameters. This type is not constructed directly + * by the user; it is only generated by the {@link AccountSASSignatureValues} and {@link BlobSASSignatureValues} + * types. Once generated, it can be encoded into a {@code String} and appended to a URL directly (though caution should + * be taken here in case there are existing query parameters, which might affect the appropriate means of appending + * these query parameters). + * + * NOTE: Instances of this class are immutable. + * + * @export + * @class SASQueryParameters + */ +var SASQueryParameters = /** @class */ (function () { + /** + * Creates an instance of SASQueryParameters. + * + * @param {string} version Representing the storage version + * @param {string} signature Representing the signature for the SAS token + * @param {string} [permissions] Representing the storage permissions + * @param {string} [services] Representing the storage services being accessed (only for Account SAS) + * @param {string} [resourceTypes] Representing the storage resource types being accessed (only for Account SAS) + * @param {SASProtocol} [protocol] Representing the allowed HTTP protocol(s) + * @param {Date} [startsOn] Representing the start time for this SAS token + * @param {Date} [expiresOn] Representing the expiry time for this SAS token + * @param {SasIPRange} [ipRange] Representing the range of valid IP addresses for this SAS token + * @param {string} [identifier] Representing the signed identifier (only for Service SAS) + * @param {string} [resource] Representing the storage container or blob (only for Service SAS) + * @param {string} [cacheControl] Representing the cache-control header (only for Blob/File Service SAS) + * @param {string} [contentDisposition] Representing the content-disposition header (only for Blob/File Service SAS) + * @param {string} [contentEncoding] Representing the content-encoding header (only for Blob/File Service SAS) + * @param {string} [contentLanguage] Representing the content-language header (only for Blob/File Service SAS) + * @param {string} [contentType] Representing the content-type header (only for Blob/File Service SAS) + * @param {userDelegationKey} [userDelegationKey] Representing the user delegation key properties + * @memberof SASQueryParameters + */ + function SASQueryParameters(version, signature, permissions, services, resourceTypes, protocol, startsOn, expiresOn, ipRange, identifier, resource, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType, userDelegationKey) { + this.version = version; + this.services = services; + this.resourceTypes = resourceTypes; + this.expiresOn = expiresOn; + this.permissions = permissions; + this.protocol = protocol; + this.startsOn = startsOn; + this.ipRangeInner = ipRange; + this.identifier = identifier; + this.resource = resource; + this.signature = signature; + this.cacheControl = cacheControl; + this.contentDisposition = contentDisposition; + this.contentEncoding = contentEncoding; + this.contentLanguage = contentLanguage; + this.contentType = contentType; + if (userDelegationKey) { + this.signedOid = userDelegationKey.signedObjectId; + this.signedTenantId = userDelegationKey.signedTenantId; + this.signedStartsOn = userDelegationKey.signedStartsOn; + this.signedExpiresOn = userDelegationKey.signedExpiresOn; + this.signedService = userDelegationKey.signedService; + this.signedVersion = userDelegationKey.signedVersion; + } + } + Object.defineProperty(SASQueryParameters.prototype, "ipRange", { + /** + * Optional. IP range allowed for this SAS. + * + * @readonly + * @type {(SasIPRange | undefined)} + * @memberof SASQueryParameters + */ + get: function () { + if (this.ipRangeInner) { + return { + end: this.ipRangeInner.end, + start: this.ipRangeInner.start + }; + } + return undefined; + }, + enumerable: false, + configurable: true + }); + /** + * Encodes all SAS query parameters into a string that can be appended to a URL. * - * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param {ServiceFindBlobByTagsOptions} [options={}] Options to find blobs by tags. - * @returns {PagedAsyncIterableIterator} - * @memberof BlobServiceClient + * @returns {string} + * @memberof SASQueryParameters */ - BlobServiceClient.prototype.findBlobsByTags = function (tagFilterSqlExpression, options) { - var _a; - var _this = this; - if (options === void 0) { options = {}; } - // AsyncIterableIterator to iterate over blobs - var listSegmentOptions = tslib.__assign({}, options); - var iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); - return _a = { - /** - * @member {Promise} [next] The next method, part of the iteration protocol - */ - next: function () { - return iter.next(); - } - }, - /** - * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol - */ - _a[Symbol.asyncIterator] = function () { - return this; - }, - /** - * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time - */ - _a.byPage = function (settings) { - if (settings === void 0) { settings = {}; } - return _this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); - }, - _a; + SASQueryParameters.prototype.toString = function () { + var params = [ + "sv", + "ss", + "srt", + "spr", + "st", + "se", + "sip", + "si", + "skoid", + "sktid", + "skt", + "ske", + "sks", + "skv", + "sr", + "sp", + "sig", + "rscc", + "rscd", + "rsce", + "rscl", + "rsct" + ]; + var queries = []; + for (var _i = 0, params_1 = params; _i < params_1.length; _i++) { + var param = params_1[_i]; + switch (param) { + case "sv": + this.tryAppendQueryParameter(queries, param, this.version); + break; + case "ss": + this.tryAppendQueryParameter(queries, param, this.services); + break; + case "srt": + this.tryAppendQueryParameter(queries, param, this.resourceTypes); + break; + case "spr": + this.tryAppendQueryParameter(queries, param, this.protocol); + break; + case "st": + this.tryAppendQueryParameter(queries, param, this.startsOn ? truncatedISO8061Date(this.startsOn, false) : undefined); + break; + case "se": + this.tryAppendQueryParameter(queries, param, this.expiresOn ? truncatedISO8061Date(this.expiresOn, false) : undefined); + break; + case "sip": + this.tryAppendQueryParameter(queries, param, this.ipRange ? ipRangeToString(this.ipRange) : undefined); + break; + case "si": + this.tryAppendQueryParameter(queries, param, this.identifier); + break; + case "skoid": // Signed object ID + this.tryAppendQueryParameter(queries, param, this.signedOid); + break; + case "sktid": // Signed tenant ID + this.tryAppendQueryParameter(queries, param, this.signedTenantId); + break; + case "skt": // Signed key start time + this.tryAppendQueryParameter(queries, param, this.signedStartsOn ? truncatedISO8061Date(this.signedStartsOn, false) : undefined); + break; + case "ske": // Signed key expiry time + this.tryAppendQueryParameter(queries, param, this.signedExpiresOn ? truncatedISO8061Date(this.signedExpiresOn, false) : undefined); + break; + case "sks": // Signed key service + this.tryAppendQueryParameter(queries, param, this.signedService); + break; + case "skv": // Signed key version + this.tryAppendQueryParameter(queries, param, this.signedVersion); + break; + case "sr": + this.tryAppendQueryParameter(queries, param, this.resource); + break; + case "sp": + this.tryAppendQueryParameter(queries, param, this.permissions); + break; + case "sig": + this.tryAppendQueryParameter(queries, param, this.signature); + break; + case "rscc": + this.tryAppendQueryParameter(queries, param, this.cacheControl); + break; + case "rscd": + this.tryAppendQueryParameter(queries, param, this.contentDisposition); + break; + case "rsce": + this.tryAppendQueryParameter(queries, param, this.contentEncoding); + break; + case "rscl": + this.tryAppendQueryParameter(queries, param, this.contentLanguage); + break; + case "rsct": + this.tryAppendQueryParameter(queries, param, this.contentType); + break; + } + } + return queries.join("&"); }; /** - * Returns an AsyncIterableIterator for ServiceListContainersSegmentResponses + * A private helper method used to filter and append query key/value pairs into an array. * * @private - * @param {string} [marker] A string value that identifies the portion of - * the list of containers to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all containers remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param {ServiceListContainersSegmentOptions} [options] Options to list containers operation. - * @returns {AsyncIterableIterator} - * @memberof BlobServiceClient + * @param {string[]} queries + * @param {string} key + * @param {string} [value] + * @returns {void} + * @memberof SASQueryParameters */ - BlobServiceClient.prototype.listSegments = function (marker, options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listSegments_1() { - var listContainersSegmentResponse; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!(!!marker || marker === undefined)) return [3 /*break*/, 7]; - _a.label = 1; - case 1: return [4 /*yield*/, tslib.__await(this.listContainersSegment(marker, options))]; - case 2: - listContainersSegmentResponse = _a.sent(); - listContainersSegmentResponse.containerItems = - listContainersSegmentResponse.containerItems || []; - marker = listContainersSegmentResponse.continuationToken; - return [4 /*yield*/, tslib.__await(listContainersSegmentResponse)]; - case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_a.sent()])]; - case 4: return [4 /*yield*/, _a.sent()]; - case 5: - _a.sent(); - _a.label = 6; - case 6: - if (marker) return [3 /*break*/, 1]; - _a.label = 7; - case 7: return [2 /*return*/]; - } - }); - }); + SASQueryParameters.prototype.tryAppendQueryParameter = function (queries, key, value) { + if (!value) { + return; + } + key = encodeURIComponent(key); + value = encodeURIComponent(value); + if (key.length > 0 && value.length > 0) { + queries.push(key + "=" + value); + } }; + return SASQueryParameters; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * Generates a {@link SASQueryParameters} object which contains all SAS query parameters needed to make an actual + * REST request. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas + * + * @param {AccountSASSignatureValues} accountSASSignatureValues + * @param {StorageSharedKeyCredential} sharedKeyCredential + * @returns {SASQueryParameters} + * @memberof AccountSASSignatureValues + */ +function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { + var version = accountSASSignatureValues.version + ? accountSASSignatureValues.version + : SERVICE_VERSION; + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.deleteVersion && + version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); + } + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.tag && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); + } + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.filter && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 'f' permission."); + } + var parsedPermissions = AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()); + var parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); + var parsedResourceTypes = AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString(); + var stringToSign = [ + sharedKeyCredential.accountName, + parsedPermissions, + parsedServices, + parsedResourceTypes, + accountSASSignatureValues.startsOn + ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) + : "", + truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), + accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", + accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", + version, + "" // Account SAS requires an additional newline character + ].join("\n"); + var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(version, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange); +} + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a blob. Setting + * a value to true means that any SAS which uses these permissions will grant permissions for that operation. Once all + * the values are set, this should be serialized with toString and set as the permissions field on a + * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but + * the order of the permissions is particular and this class guarantees correctness. + * + * @export + * @class BlobSASPermissions + */ +var BlobSASPermissions = /** @class */ (function () { + function BlobSASPermissions() { + /** + * Specifies Read access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.read = false; + /** + * Specifies Add access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.add = false; + /** + * Specifies Create access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.create = false; + /** + * Specifies Write access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.write = false; + /** + * Specifies Delete access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.delete = false; + /** + * Specifies Delete version access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.deleteVersion = false; + /** + * Specfies Tag access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.tag = false; + } /** - * Returns an AsyncIterableIterator for Container Items + * Creates a {@link BlobSASPermissions} from the specified permissions string. This method will throw an + * Error if it encounters a character that does not correspond to a valid permission. * - * @private - * @param {ServiceListContainersSegmentOptions} [options] Options to list containers operation. - * @returns {AsyncIterableIterator} - * @memberof BlobServiceClient + * @static + * @param {string} permissions + * @returns {BlobSASPermissions} + * @memberof BlobSASPermissions */ - BlobServiceClient.prototype.listItems = function (options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listItems_1() { - var marker, _a, _b, segment, e_11_1; - var e_11, _c; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _d.trys.push([0, 7, 8, 13]); - _a = tslib.__asyncValues(this.listSegments(marker, options)); - _d.label = 1; - case 1: return [4 /*yield*/, tslib.__await(_a.next())]; - case 2: - if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; - segment = _b.value; - return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(segment.containerItems)))]; - case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; - case 4: - _d.sent(); - _d.label = 5; - case 5: return [3 /*break*/, 1]; - case 6: return [3 /*break*/, 13]; - case 7: - e_11_1 = _d.sent(); - e_11 = { error: e_11_1 }; - return [3 /*break*/, 13]; - case 8: - _d.trys.push([8, , 11, 12]); - if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; - return [4 /*yield*/, tslib.__await(_c.call(_a))]; - case 9: - _d.sent(); - _d.label = 10; - case 10: return [3 /*break*/, 12]; - case 11: - if (e_11) throw e_11.error; - return [7 /*endfinally*/]; - case 12: return [7 /*endfinally*/]; - case 13: return [2 /*return*/]; - } - }); - }); + BlobSASPermissions.parse = function (permissions) { + var blobSASPermissions = new BlobSASPermissions(); + for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { + var char = permissions_1[_i]; + switch (char) { + case "r": + blobSASPermissions.read = true; + break; + case "a": + blobSASPermissions.add = true; + break; + case "c": + blobSASPermissions.create = true; + break; + case "w": + blobSASPermissions.write = true; + break; + case "d": + blobSASPermissions.delete = true; + break; + case "x": + blobSASPermissions.deleteVersion = true; + break; + case "t": + blobSASPermissions.tag = true; + break; + default: + throw new RangeError("Invalid permission: " + char); + } + } + return blobSASPermissions; }; /** - * Returns an async iterable iterator to list all the containers - * under the specified account. - * - * .byPage() returns an async iterable iterator to list the containers in pages. - * - * Example using `for await` syntax: - * - * ```js - * let i = 1; - * for await (const container of blobServiceClient.listContainers()) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * ``` - * - * Example using `iter.next()`: - * - * ```js - * let i = 1; - * const iter = blobServiceClient.listContainers(); - * let containerItem = await iter.next(); - * while (!containerItem.done) { - * console.log(`Container ${i++}: ${containerItem.value.name}`); - * containerItem = await iter.next(); - * } - * ``` - * - * Example using `byPage()`: - * - * ```js - * // passing optional maxPageSize in the page settings - * let i = 1; - * for await (const response of blobServiceClient.listContainers().byPage({ maxPageSize: 20 })) { - * if (response.containerItems) { - * for (const container of response.containerItems) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * } - * } - * ``` - * - * Example using paging with a marker: - * - * ```js - * let i = 1; - * let iterator = blobServiceClient.listContainers().byPage({ maxPageSize: 2 }); - * let response = (await iterator.next()).value; - * - * // Prints 2 container names - * if (response.containerItems) { - * for (const container of response.containerItems) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * } - * - * // Gets next marker - * let marker = response.continuationToken; - * // Passing next marker as continuationToken - * iterator = blobServiceClient - * .listContainers() - * .byPage({ continuationToken: marker, maxPageSize: 10 }); - * response = (await iterator.next()).value; + * Converts the given permissions to a string. Using this method will guarantee the permissions are in an + * order accepted by the service. * - * // Prints 10 container names - * if (response.containerItems) { - * for (const container of response.containerItems) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * } - * ``` + * @returns {string} A string which represents the BlobSASPermissions + * @memberof BlobSASPermissions + */ + BlobSASPermissions.prototype.toString = function () { + var permissions = []; + if (this.read) { + permissions.push("r"); + } + if (this.add) { + permissions.push("a"); + } + if (this.create) { + permissions.push("c"); + } + if (this.write) { + permissions.push("w"); + } + if (this.delete) { + permissions.push("d"); + } + if (this.deleteVersion) { + permissions.push("x"); + } + if (this.tag) { + permissions.push("t"); + } + return permissions.join(""); + }; + return BlobSASPermissions; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a container. + * Setting a value to true means that any SAS which uses these permissions will grant permissions for that operation. + * Once all the values are set, this should be serialized with toString and set as the permissions field on a + * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but + * the order of the permissions is particular and this class guarantees correctness. + * + * @export + * @class ContainerSASPermissions + */ +var ContainerSASPermissions = /** @class */ (function () { + function ContainerSASPermissions() { + /** + * Specifies Read access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.read = false; + /** + * Specifies Add access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.add = false; + /** + * Specifies Create access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.create = false; + /** + * Specifies Write access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.write = false; + /** + * Specifies Delete access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.delete = false; + /** + * Specifies Delete version access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.deleteVersion = false; + /** + * Specifies List access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.list = false; + /** + * Specfies Tag access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.tag = false; + } + /** + * Creates an {@link ContainerSASPermissions} from the specified permissions string. This method will throw an + * Error if it encounters a character that does not correspond to a valid permission. * - * @param {ServiceListContainersOptions} [options={}] Options to list containers. - * @returns {PagedAsyncIterableIterator} An asyncIterableIterator that supports paging. - * @memberof BlobServiceClient + * @static + * @param {string} permissions + * @returns {ContainerSASPermissions} + * @memberof ContainerSASPermissions */ - BlobServiceClient.prototype.listContainers = function (options) { - var _a; - var _this = this; - if (options === void 0) { options = {}; } - if (options.prefix === "") { - options.prefix = undefined; - } - var include = []; - if (options.includeDeleted) { - include.push("deleted"); - } - if (options.includeMetadata) { - include.push("metadata"); + ContainerSASPermissions.parse = function (permissions) { + var containerSASPermissions = new ContainerSASPermissions(); + for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { + var char = permissions_1[_i]; + switch (char) { + case "r": + containerSASPermissions.read = true; + break; + case "a": + containerSASPermissions.add = true; + break; + case "c": + containerSASPermissions.create = true; + break; + case "w": + containerSASPermissions.write = true; + break; + case "d": + containerSASPermissions.delete = true; + break; + case "l": + containerSASPermissions.list = true; + break; + case "t": + containerSASPermissions.tag = true; + break; + case "x": + containerSASPermissions.deleteVersion = true; + break; + default: + throw new RangeError("Invalid permission " + char); + } } - // AsyncIterableIterator to iterate over containers - var listSegmentOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); - var iter = this.listItems(listSegmentOptions); - return _a = { - /** - * @member {Promise} [next] The next method, part of the iteration protocol - */ - next: function () { - return iter.next(); - } - }, - /** - * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol - */ - _a[Symbol.asyncIterator] = function () { - return this; - }, - /** - * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time - */ - _a.byPage = function (settings) { - if (settings === void 0) { settings = {}; } - return _this.listSegments(settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); - }, - _a; + return containerSASPermissions; }; /** - * ONLY AVAILABLE WHEN USING BEARER TOKEN AUTHENTICATION (TokenCredential). - * - * Retrieves a user delegation key for the Blob service. This is only a valid operation when using - * bearer token authentication. + * Converts the given permissions to a string. Using this method will guarantee the permissions are in an + * order accepted by the service. * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-user-delegation-key + * The order of the characters should be as specified here to ensure correctness. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * - * @param {Date} startsOn The start time for the user delegation SAS. Must be within 7 days of the current time - * @param {Date} expiresOn The end time for the user delegation SAS. Must be within 7 days of the current time - * @returns {Promise} - * @memberof BlobServiceClient + * @returns {string} + * @memberof ContainerSASPermissions */ - BlobServiceClient.prototype.getUserDelegationKey = function (startsOn, expiresOn, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, response, userDelegationKey, res, e_12; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-getUserDelegationKey", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getUserDelegationKey({ - startsOn: truncatedISO8061Date(startsOn, false), - expiresOn: truncatedISO8061Date(expiresOn, false) - }, { - abortSignal: options.abortSignal, - spanOptions: spanOptions - })]; - case 2: - response = _b.sent(); - userDelegationKey = { - signedObjectId: response.signedObjectId, - signedTenantId: response.signedTenantId, - signedStartsOn: new Date(response.signedStartsOn), - signedExpiresOn: new Date(response.signedExpiresOn), - signedService: response.signedService, - signedVersion: response.signedVersion, - value: response.value - }; - res = tslib.__assign({ _response: response._response, requestId: response.requestId, clientRequestId: response.clientRequestId, version: response.version, date: response.date, errorCode: response.errorCode }, userDelegationKey); - return [2 /*return*/, res]; - case 3: - e_12 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_12.message - }); - throw e_12; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + ContainerSASPermissions.prototype.toString = function () { + var permissions = []; + if (this.read) { + permissions.push("r"); + } + if (this.add) { + permissions.push("a"); + } + if (this.create) { + permissions.push("c"); + } + if (this.write) { + permissions.push("w"); + } + if (this.delete) { + permissions.push("d"); + } + if (this.deleteVersion) { + permissions.push("x"); + } + if (this.list) { + permissions.push("l"); + } + if (this.tag) { + permissions.push("t"); + } + return permissions.join(""); }; + return ContainerSASPermissions; +}()); + +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * UserDelegationKeyCredential is only used for generation of user delegation SAS. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas + * + * @export + * @class UserDelegationKeyCredential + */ +var UserDelegationKeyCredential = /** @class */ (function () { /** - * Creates a BlobBatchClient object to conduct batch operations. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch - * - * @returns {BlobBatchClient} A new BlobBatchClient object for this service. - * @memberof BlobServiceClient + * Creates an instance of UserDelegationKeyCredential. + * @param {string} accountName + * @param {UserDelegationKey} userDelegationKey + * @memberof UserDelegationKeyCredential */ - BlobServiceClient.prototype.getBlobBatchClient = function () { - return new BlobBatchClient(this.url, this.pipeline); - }; + function UserDelegationKeyCredential(accountName, userDelegationKey) { + this.accountName = accountName; + this.userDelegationKey = userDelegationKey; + this.key = Buffer.from(userDelegationKey.value, "base64"); + } /** - * Only available for BlobServiceClient constructed with a shared key credential. - * - * Generates a Blob account Shared Access Signature (SAS) URI based on the client properties - * and parameters passed in. The SAS is signed by the shared key credential of the client. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-account-sas + * Generates a hash signature for an HTTP request or for a SAS. * - * @param {Date} expiresOn Optional. The time at which the shared access signature becomes invalid. Default to an hour later if not provided. - * @param {AccountSASPermissions} [permissions=AccountSASPermissions.parse("r")] Specifies the list of permissions to be associated with the SAS. - * @param {string} [resourceTypes="sco"] Specifies the resource types associated with the shared access signature. - * @param {ServiceGenerateAccountSasUrlOptions} [options={}] Optional parameters. - * @returns {string} An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. - * @memberof BlobServiceClient + * @param {string} stringToSign + * @returns {string} + * @memberof UserDelegationKeyCredential */ - BlobServiceClient.prototype.generateAccountSasUrl = function (expiresOn, permissions, resourceTypes, options) { - if (permissions === void 0) { permissions = AccountSASPermissions.parse("r"); } - if (resourceTypes === void 0) { resourceTypes = "sco"; } - if (options === void 0) { options = {}; } - if (!(this.credential instanceof StorageSharedKeyCredential)) { - throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); + UserDelegationKeyCredential.prototype.computeHMACSHA256 = function (stringToSign) { + // console.log(`stringToSign: ${JSON.stringify(stringToSign)}`); + return crypto.createHmac("sha256", this.key) + .update(stringToSign, "utf8") + .digest("base64"); + }; + return UserDelegationKeyCredential; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +function generateBlobSASQueryParameters(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { + var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + var sharedKeyCredential = sharedKeyCredentialOrUserDelegationKey instanceof StorageSharedKeyCredential + ? sharedKeyCredentialOrUserDelegationKey + : undefined; + var userDelegationKeyCredential; + if (sharedKeyCredential === undefined && accountName !== undefined) { + userDelegationKeyCredential = new UserDelegationKeyCredential(accountName, sharedKeyCredentialOrUserDelegationKey); + } + if (sharedKeyCredential === undefined && userDelegationKeyCredential === undefined) { + throw TypeError("Invalid sharedKeyCredential, userDelegationKey or accountName."); + } + // Version 2019-12-12 adds support for the blob tags permission. + // Version 2018-11-09 adds support for the signed resource and signed blob snapshot time fields. + // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas#constructing-the-signature-string + if (version >= "2018-11-09") { + if (sharedKeyCredential !== undefined) { + return generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential); + } + else { + return generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential); } - if (expiresOn === undefined) { - var now = new Date(); - expiresOn = new Date(now.getTime() + 3600 * 1000); + } + if (version >= "2015-04-05") { + if (sharedKeyCredential !== undefined) { + return generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential); } - var sas = generateAccountSASQueryParameters(tslib.__assign({ permissions: permissions, - expiresOn: expiresOn, - resourceTypes: resourceTypes, services: AccountSASServices.parse("b").toString() }, options), this.credential).toString(); - return appendToURLQuery(this.url, sas); - }; - return BlobServiceClient; -}(StorageClient)); + else { + throw new RangeError("'version' must be >= '2018-11-09' when generating user delegation SAS using user delegation key."); + } + } + throw new RangeError("'version' must be >= '2015-04-05'."); +} +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * IMPLEMENTATION FOR API VERSION FROM 2015-04-05 AND BEFORE 2018-11-09. + * + * Creates an instance of SASQueryParameters. + * + * Only accepts required settings needed to create a SAS. For optional settings please + * set corresponding properties directly, such as permissions, startsOn and identifier. + * + * WARNING: When identifier is not provided, permissions and expiresOn are required. + * You MUST assign value to identifier or expiresOn & permissions manually if you initial with + * this constructor. + * + * @param {BlobSASSignatureValues} blobSASSignatureValues + * @param {StorageSharedKeyCredential} sharedKeyCredential + * @returns {SASQueryParameters} + */ +function generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential) { + if (!blobSASSignatureValues.identifier && + !blobSASSignatureValues.permissions && + !blobSASSignatureValues.expiresOn) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); + } + var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + var resource = "c"; + var verifiedPermissions; + if (blobSASSignatureValues.snapshotTime) { + throw RangeError("'version' must be >= '2018-11-09' when provided 'snapshotTime'."); + } + if (blobSASSignatureValues.versionId) { + throw RangeError("'version' must be >= '2019-10-10' when provided 'versionId'."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.deleteVersion && + version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.tag && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); + } + if (blobSASSignatureValues.blobName) { + resource = "b"; + } + // Calling parse and toString guarantees the proper ordering and throws on invalid characters. + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + // Signature is generated on the un-url-encoded values. + var stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn + ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) + : "", + blobSASSignatureValues.expiresOn + ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) + : "", + getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + blobSASSignatureValues.identifier, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + version, + blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", + blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", + blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", + blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", + blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" + ].join("\n"); + var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); +} +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. + * + * Creates an instance of SASQueryParameters. + * + * Only accepts required settings needed to create a SAS. For optional settings please + * set corresponding properties directly, such as permissions, startsOn and identifier. + * + * WARNING: When identifier is not provided, permissions and expiresOn are required. + * You MUST assign value to identifier or expiresOn & permissions manually if you initial with + * this constructor. + * + * @param {BlobSASSignatureValues} blobSASSignatureValues + * @param {StorageSharedKeyCredential} sharedKeyCredential + * @returns {SASQueryParameters} + */ +function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential) { + if (!blobSASSignatureValues.identifier && + !blobSASSignatureValues.permissions && + !blobSASSignatureValues.expiresOn) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); + } + var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + var resource = "c"; + var verifiedPermissions; + if (blobSASSignatureValues.versionId && version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'versionId'."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.deleteVersion && + version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.tag && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); + } + if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.snapshotTime) { + throw RangeError("Must provide 'blobName' when provided 'snapshotTime'."); + } + if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.versionId) { + throw RangeError("Must provide 'blobName' when provided 'versionId'."); + } + var timestamp = blobSASSignatureValues.snapshotTime; + if (blobSASSignatureValues.blobName) { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } + else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } + } + // Calling parse and toString guarantees the proper ordering and throws on invalid characters. + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + // Signature is generated on the un-url-encoded values. + var stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn + ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) + : "", + blobSASSignatureValues.expiresOn + ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) + : "", + getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + blobSASSignatureValues.identifier, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + version, + resource, + timestamp, + blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", + blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", + blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", + blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", + blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" + ].join("\n"); + var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); +} +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. + * + * Creates an instance of SASQueryParameters. + * + * Only accepts required settings needed to create a SAS. For optional settings please + * set corresponding properties directly, such as permissions, startsOn and identifier. + * + * WARNING: identifier will be ignored, permissions and expiresOn are required. + * + * @param {BlobSASSignatureValues} blobSASSignatureValues + * @param {UserDelegationKeyCredential} userDelegationKeyCredential + * @returns {SASQueryParameters} + */ +function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential) { + if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); + } + var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + if (blobSASSignatureValues.versionId && version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'versionId'."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.deleteVersion && + version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.tag && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); + } + var resource = "c"; + var verifiedPermissions; + if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.snapshotTime) { + throw RangeError("Must provide 'blobName' when provided 'snapshotTime'."); + } + if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.versionId) { + throw RangeError("Must provide 'blobName' when provided 'versionId'."); + } + var timestamp = blobSASSignatureValues.snapshotTime; + if (blobSASSignatureValues.blobName) { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } + else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } + } + // Calling parse and toString guarantees the proper ordering and throws on invalid characters. + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + // Signature is generated on the un-url-encoded values. + var stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn + ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) + : "", + blobSASSignatureValues.expiresOn + ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) + : "", + getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + userDelegationKeyCredential.userDelegationKey.signedObjectId, + userDelegationKeyCredential.userDelegationKey.signedTenantId, + userDelegationKeyCredential.userDelegationKey.signedStartsOn + ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) + : "", + userDelegationKeyCredential.userDelegationKey.signedExpiresOn + ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) + : "", + userDelegationKeyCredential.userDelegationKey.signedService, + userDelegationKeyCredential.userDelegationKey.signedVersion, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + version, + resource, + timestamp, + blobSASSignatureValues.cacheControl, + blobSASSignatureValues.contentDisposition, + blobSASSignatureValues.contentEncoding, + blobSASSignatureValues.contentLanguage, + blobSASSignatureValues.contentType + ].join("\n"); + var signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey); +} +function getCanonicalName(accountName, containerName, blobName) { + // Container: "/blob/account/containerName" + // Blob: "/blob/account/containerName/blobName" + var elements = ["/blob/" + accountName + "/" + containerName]; + if (blobName) { + elements.push("/" + blobName); + } + return elements.join(""); +} Object.defineProperty(exports, 'BaseRequestPolicy', { enumerable: true, @@ -36461,20 +35746,10 @@ exports.newPipeline = newPipeline; "use strict"; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; Object.defineProperty(exports, "__esModule", { value: true }); -const path = __importStar(__webpack_require__(622)); -const pathHelper = __importStar(__webpack_require__(972)); -const assert_1 = __importDefault(__webpack_require__(357)); +const assert = __webpack_require__(357); +const path = __webpack_require__(622); +const pathHelper = __webpack_require__(972); const IS_WINDOWS = process.platform === 'win32'; /** * Helper class for parsing paths into segments @@ -36488,7 +35763,7 @@ class Path { this.segments = []; // String if (typeof itemPath === 'string') { - assert_1.default(itemPath, `Parameter 'itemPath' must not be empty`); + assert(itemPath, `Parameter 'itemPath' must not be empty`); // Normalize slashes and trim unnecessary trailing slash itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); // Not rooted @@ -36515,24 +35790,24 @@ class Path { // Array else { // Must not be empty - assert_1.default(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`); + assert(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`); // Each segment for (let i = 0; i < itemPath.length; i++) { let segment = itemPath[i]; // Must not be empty - assert_1.default(segment, `Parameter 'itemPath' must not contain any empty segments`); + assert(segment, `Parameter 'itemPath' must not contain any empty segments`); // Normalize slashes segment = pathHelper.normalizeSeparators(itemPath[i]); // Root segment if (i === 0 && pathHelper.hasRoot(segment)) { segment = pathHelper.safeTrimTrailingSeparator(segment); - assert_1.default(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`); + assert(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`); this.segments.push(segment); } // All other segments else { // Must not contain slash - assert_1.default(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`); + assert(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`); this.segments.push(segment); } } @@ -39468,7 +38743,288 @@ module.exports = require("crypto"); /* 419 */, /* 420 */, /* 421 */, -/* 422 */, +/* 422 */ +/***/ (function(module) { + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global global, define, System, Reflect, Promise */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if ( true && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + + __extends = function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __exportStar = function (m, exports) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; + }; + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, privateMap) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return privateMap.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, privateMap, value) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to set private field on non-instance"); + } + privateMap.set(receiver, value); + return value; + } + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); +}); + + +/***/ }), /* 423 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -40075,31 +39631,20 @@ const utils = __importStar(__webpack_require__(15)); const constants_1 = __webpack_require__(931); function getTarPath(args, compressionMethod) { return __awaiter(this, void 0, void 0, function* () { - switch (process.platform) { - case 'win32': { - const systemTar = `${process.env['windir']}\\System32\\tar.exe`; - if (compressionMethod !== constants_1.CompressionMethod.Gzip) { - // We only use zstandard compression on windows when gnu tar is installed due to - // a bug with compressing large files with bsdtar + zstd - args.push('--force-local'); - } - else if (fs_1.existsSync(systemTar)) { - return systemTar; - } - else if (yield utils.isGnuTarInstalled()) { - args.push('--force-local'); - } - break; + const IS_WINDOWS = process.platform === 'win32'; + if (IS_WINDOWS) { + const systemTar = `${process.env['windir']}\\System32\\tar.exe`; + if (compressionMethod !== constants_1.CompressionMethod.Gzip) { + // We only use zstandard compression on windows when gnu tar is installed due to + // a bug with compressing large files with bsdtar + zstd + args.push('--force-local'); } - case 'darwin': { - const gnuTar = yield io.which('gtar', false); - if (gnuTar) { - return gnuTar; - } - break; + else if (fs_1.existsSync(systemTar)) { + return systemTar; + } + else if (yield utils.isGnuTarInstalled()) { + args.push('--force-local'); } - default: - break; } return yield io.which('tar', true); }); @@ -40184,32 +39729,6 @@ function createTar(archiveFolder, sourceDirectories, compressionMethod) { }); } exports.createTar = createTar; -function listTar(archivePath, compressionMethod) { - return __awaiter(this, void 0, void 0, function* () { - // --d: Decompress. - // --long=#: Enables long distance matching with # bits. - // Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit. - // Using 30 here because we also support 32-bit self-hosted runners. - function getCompressionProgram() { - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return ['--use-compress-program', 'zstd -d --long=30']; - case constants_1.CompressionMethod.ZstdWithoutLong: - return ['--use-compress-program', 'zstd -d']; - default: - return ['-z']; - } - } - const args = [ - ...getCompressionProgram(), - '-tf', - archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), - '-P' - ]; - yield execTar(args, compressionMethod); - }); -} -exports.listTar = listTar; //# sourceMappingURL=tar.js.map /***/ }), @@ -40287,7 +39806,7 @@ __exportStar(__webpack_require__(975), exports); __exportStar(__webpack_require__(70), exports); __exportStar(__webpack_require__(694), exports); __exportStar(__webpack_require__(695), exports); -var context_base_1 = __webpack_require__(459); +var context_base_1 = __webpack_require__(231); Object.defineProperty(exports, "Context", { enumerable: true, get: function () { return context_base_1.Context; } }); var context_1 = __webpack_require__(492); /** Entrypoint for context API */ @@ -42509,35 +42028,7 @@ exports.FetchError = FetchError; /***/ }), -/* 459 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -/*! - * Copyright 2019, OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} -Object.defineProperty(exports, "__esModule", { value: true }); -__export(__webpack_require__(560)); -__export(__webpack_require__(53)); -//# sourceMappingURL=index.js.map - -/***/ }), +/* 459 */, /* 460 */ /***/ (function(module) { @@ -43130,7 +42621,7 @@ exports.getState = getState; */ Object.defineProperty(exports, "__esModule", { value: true }); exports.ContextAPI = void 0; -var context_base_1 = __webpack_require__(459); +var context_base_1 = __webpack_require__(231); var global_utils_1 = __webpack_require__(976); var NOOP_CONTEXT_MANAGER = new context_base_1.NoopContextManager(); /** @@ -45481,90 +44972,7 @@ exports.defaultSetter = defaultSetter; /***/ }), -/* 560 */ -/***/ (function(__unusedmodule, exports) { - -"use strict"; - -/*! - * Copyright 2020, OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Class which stores and manages current context values. All methods which - * update context such as get and delete do not modify an existing context, - * but create a new one with updated values. - */ -class Context { - /** - * Construct a new context which inherits values from an optional parent context. - * - * @param parentContext a context from which to inherit values - */ - constructor(parentContext) { - this._currentContext = parentContext ? new Map(parentContext) : new Map(); - } - /** Get a key to uniquely identify a context value */ - static createKey(description) { - return Symbol(description); - } - /** - * Get a value from the context. - * - * @param key key which identifies a context value - */ - getValue(key) { - return this._currentContext.get(key); - } - /** - * Create a new context which inherits from this context and has - * the given key set to the given value. - * - * @param key context key for which to set the value - * @param value value to set for the given key - */ - setValue(key, value) { - const context = new Context(this._currentContext); - context._currentContext.set(key, value); - return context; - } - /** - * Return a new context which inherits from this context but does - * not contain a value for the given key. - * - * @param key context key for which to clear a value - */ - deleteValue(key) { - const context = new Context(this._currentContext); - context._currentContext.delete(key); - return context; - } -} -exports.Context = Context; -/** The root context is used as the default parent context when there is no active context */ -Context.ROOT_CONTEXT = new Context(); -/** - * This is another identifier to the root context which allows developers to easily search the - * codebase for direct uses of context which need to be removed in later PRs. - * - * It's existence is temporary and it should be removed when all references are fixed. - */ -Context.TODO = Context.ROOT_CONTEXT; -//# sourceMappingURL=context.js.map - -/***/ }), +/* 560 */, /* 561 */, /* 562 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { @@ -45879,15 +45287,8 @@ Object.defineProperty(exports, "__esModule", { value: true }); "use strict"; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; Object.defineProperty(exports, "__esModule", { value: true }); -const pathHelper = __importStar(__webpack_require__(972)); +const pathHelper = __webpack_require__(972); const internal_match_kind_1 = __webpack_require__(327); const IS_WINDOWS = process.platform === 'win32'; /** @@ -45969,15 +45370,8 @@ exports.partialMatch = partialMatch; "use strict"; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; Object.defineProperty(exports, "__esModule", { value: true }); -const core = __importStar(__webpack_require__(470)); +const core = __webpack_require__(470); /** * Returns a copy with defaults filled in. */ @@ -47069,13 +46463,9 @@ function restoreCache(paths, primaryKey, restoreKeys, options) { try { // Download the cache from the cache entry yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); - if (core.isDebug()) { - yield tar_1.listTar(archivePath, compressionMethod); - } const archiveFileSize = utils.getArchiveFileSizeIsBytes(archivePath); core.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); yield tar_1.extractTar(archivePath, compressionMethod); - core.info('Cache restored successfully'); } finally { // Try to delete the archive to save space @@ -47118,9 +46508,6 @@ function saveCache(paths, key, options) { const archivePath = path.join(archiveFolder, utils.getCacheFileName(compressionMethod)); core.debug(`Archive Path: ${archivePath}`); yield tar_1.createTar(archiveFolder, cachePaths, compressionMethod); - if (core.isDebug()) { - yield tar_1.listTar(archivePath, compressionMethod); - } const fileSizeLimit = 5 * 1024 * 1024 * 1024; // 5GB per repo limit const archiveFileSize = utils.getArchiveFileSizeIsBytes(archivePath); core.debug(`File Size: ${archiveFileSize}`); @@ -47221,316 +46608,7 @@ exports.saveCache = saveCache; /***/ }), -/* 640 */ -/***/ (function(module) { - -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global global, define, System, Reflect, Promise */ -var __extends; -var __assign; -var __rest; -var __decorate; -var __param; -var __metadata; -var __awaiter; -var __generator; -var __exportStar; -var __values; -var __read; -var __spread; -var __spreadArrays; -var __spreadArray; -var __await; -var __asyncGenerator; -var __asyncDelegator; -var __asyncValues; -var __makeTemplateObject; -var __importStar; -var __importDefault; -var __classPrivateFieldGet; -var __classPrivateFieldSet; -var __createBinding; -(function (factory) { - var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; - if (typeof define === "function" && define.amd) { - define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); - } - else if ( true && typeof module.exports === "object") { - factory(createExporter(root, createExporter(module.exports))); - } - else { - factory(createExporter(root)); - } - function createExporter(exports, previous) { - if (exports !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports, "__esModule", { value: true }); - } - else { - exports.__esModule = true; - } - } - return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; - } -}) -(function (exporter) { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - - __extends = function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - - __assign = Object.assign || function (t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - - __rest = function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; - - __decorate = function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - - __param = function (paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - }; - - __metadata = function (metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - }; - - __awaiter = function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - - __generator = function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - - __exportStar = function(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); - }; - - __createBinding = Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); - }) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }); - - __values = function (o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - - __read = function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - - /** @deprecated */ - __spread = function () { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; - }; - - /** @deprecated */ - __spreadArrays = function () { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; - }; - - __spreadArray = function (to, from) { - for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) - to[j] = from[i]; - return to; - }; - - __await = function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - - __asyncGenerator = function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - }; - - __asyncDelegator = function (o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } - }; - - __asyncValues = function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } - }; - - __makeTemplateObject = function (cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; - }; - - var __setModuleDefault = Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }; - - __importStar = function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; - }; - - __importDefault = function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - - __classPrivateFieldGet = function (receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - return privateMap.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, privateMap, value) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - privateMap.set(receiver, value); - return value; - }; - - exporter("__extends", __extends); - exporter("__assign", __assign); - exporter("__rest", __rest); - exporter("__decorate", __decorate); - exporter("__param", __param); - exporter("__metadata", __metadata); - exporter("__awaiter", __awaiter); - exporter("__generator", __generator); - exporter("__exportStar", __exportStar); - exporter("__createBinding", __createBinding); - exporter("__values", __values); - exporter("__read", __read); - exporter("__spread", __spread); - exporter("__spreadArrays", __spreadArrays); - exporter("__spreadArray", __spreadArray); - exporter("__await", __await); - exporter("__asyncGenerator", __asyncGenerator); - exporter("__asyncDelegator", __asyncDelegator); - exporter("__asyncValues", __asyncValues); - exporter("__makeTemplateObject", __makeTemplateObject); - exporter("__importStar", __importStar); - exporter("__importDefault", __importDefault); - exporter("__classPrivateFieldGet", __classPrivateFieldGet); - exporter("__classPrivateFieldSet", __classPrivateFieldSet); -}); - - -/***/ }), +/* 640 */, /* 641 */, /* 642 */, /* 643 */, @@ -50502,7 +49580,87 @@ __webpack_require__(71); /***/ }), /* 713 */, /* 714 */, -/* 715 */, +/* 715 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Context = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var Context = /** @class */ (function () { + /** + * Construct a new context which inherits values from an optional parent context. + * + * @param parentContext a context from which to inherit values + */ + function Context(parentContext) { + this._currentContext = parentContext ? new Map(parentContext) : new Map(); + } + /** Get a key to uniquely identify a context value */ + Context.createKey = function (description) { + return Symbol(description); + }; + /** + * Get a value from the context. + * + * @param key key which identifies a context value + */ + Context.prototype.getValue = function (key) { + return this._currentContext.get(key); + }; + /** + * Create a new context which inherits from this context and has + * the given key set to the given value. + * + * @param key context key for which to set the value + * @param value value to set for the given key + */ + Context.prototype.setValue = function (key, value) { + var context = new Context(this._currentContext); + context._currentContext.set(key, value); + return context; + }; + /** + * Return a new context which inherits from this context but does + * not contain a value for the given key. + * + * @param key context key for which to clear a value + */ + Context.prototype.deleteValue = function (key) { + var context = new Context(this._currentContext); + context._currentContext.delete(key); + return context; + }; + /** The root context is used as the default parent context when there is no active context */ + Context.ROOT_CONTEXT = new Context(); + /** + * This is another identifier to the root context which allows developers to easily search the + * codebase for direct uses of context which need to be removed in later PRs. + * + * It's existence is temporary and it should be removed when all references are fixed. + */ + Context.TODO = Context.ROOT_CONTEXT; + return Context; +}()); +exports.Context = Context; +//# sourceMappingURL=context.js.map + +/***/ }), /* 716 */, /* 717 */, /* 718 */, @@ -50713,316 +49871,7 @@ exports.saveCache = saveCache; /***/ }), -/* 725 */ -/***/ (function(module) { - -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global global, define, System, Reflect, Promise */ -var __extends; -var __assign; -var __rest; -var __decorate; -var __param; -var __metadata; -var __awaiter; -var __generator; -var __exportStar; -var __values; -var __read; -var __spread; -var __spreadArrays; -var __spreadArray; -var __await; -var __asyncGenerator; -var __asyncDelegator; -var __asyncValues; -var __makeTemplateObject; -var __importStar; -var __importDefault; -var __classPrivateFieldGet; -var __classPrivateFieldSet; -var __createBinding; -(function (factory) { - var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; - if (typeof define === "function" && define.amd) { - define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); - } - else if ( true && typeof module.exports === "object") { - factory(createExporter(root, createExporter(module.exports))); - } - else { - factory(createExporter(root)); - } - function createExporter(exports, previous) { - if (exports !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports, "__esModule", { value: true }); - } - else { - exports.__esModule = true; - } - } - return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; - } -}) -(function (exporter) { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - - __extends = function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - - __assign = Object.assign || function (t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - - __rest = function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; - - __decorate = function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - - __param = function (paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - }; - - __metadata = function (metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - }; - - __awaiter = function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - - __generator = function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - - __exportStar = function(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); - }; - - __createBinding = Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); - }) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }); - - __values = function (o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - - __read = function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - - /** @deprecated */ - __spread = function () { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; - }; - - /** @deprecated */ - __spreadArrays = function () { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; - }; - - __spreadArray = function (to, from) { - for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) - to[j] = from[i]; - return to; - }; - - __await = function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - - __asyncGenerator = function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - }; - - __asyncDelegator = function (o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } - }; - - __asyncValues = function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } - }; - - __makeTemplateObject = function (cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; - }; - - var __setModuleDefault = Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }; - - __importStar = function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; - }; - - __importDefault = function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - - __classPrivateFieldGet = function (receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - return privateMap.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, privateMap, value) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - privateMap.set(receiver, value); - return value; - }; - - exporter("__extends", __extends); - exporter("__assign", __assign); - exporter("__rest", __rest); - exporter("__decorate", __decorate); - exporter("__param", __param); - exporter("__metadata", __metadata); - exporter("__awaiter", __awaiter); - exporter("__generator", __generator); - exporter("__exportStar", __exportStar); - exporter("__createBinding", __createBinding); - exporter("__values", __values); - exporter("__read", __read); - exporter("__spread", __spread); - exporter("__spreadArrays", __spreadArrays); - exporter("__spreadArray", __spreadArray); - exporter("__await", __await); - exporter("__asyncGenerator", __asyncGenerator); - exporter("__asyncDelegator", __asyncDelegator); - exporter("__asyncValues", __asyncValues); - exporter("__makeTemplateObject", __makeTemplateObject); - exporter("__importStar", __importStar); - exporter("__importDefault", __importDefault); - exporter("__classPrivateFieldGet", __classPrivateFieldGet); - exporter("__classPrivateFieldSet", __classPrivateFieldSet); -}); - - -/***/ }), +/* 725 */, /* 726 */, /* 727 */ /***/ (function(__unusedmodule, exports) { @@ -58073,7 +56922,7 @@ exports.TraceAPI = TraceAPI; Object.defineProperty(exports, '__esModule', { value: true }); -var tslib = __webpack_require__(725); +var tslib = __webpack_require__(422); // Copyright (c) Microsoft Corporation. /** @@ -59027,27 +57876,17 @@ __exportStar(__webpack_require__(764), exports); "use strict"; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; Object.defineProperty(exports, "__esModule", { value: true }); -const os = __importStar(__webpack_require__(87)); -const path = __importStar(__webpack_require__(622)); -const pathHelper = __importStar(__webpack_require__(972)); -const assert_1 = __importDefault(__webpack_require__(357)); +const assert = __webpack_require__(357); +const os = __webpack_require__(87); +const path = __webpack_require__(622); +const pathHelper = __webpack_require__(972); const minimatch_1 = __webpack_require__(93); const internal_match_kind_1 = __webpack_require__(327); const internal_path_1 = __webpack_require__(383); const IS_WINDOWS = process.platform === 'win32'; class Pattern { - constructor(patternOrNegate, segments, homedir) { + constructor(patternOrNegate, segments) { /** * Indicates whether matches should be excluded from the result set */ @@ -59061,9 +57900,9 @@ class Pattern { else { // Convert to pattern segments = segments || []; - assert_1.default(segments.length, `Parameter 'segments' must not empty`); + assert(segments.length, `Parameter 'segments' must not empty`); const root = Pattern.getLiteral(segments[0]); - assert_1.default(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`); + assert(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`); pattern = new internal_path_1.Path(segments).toString().trim(); if (patternOrNegate) { pattern = `!${pattern}`; @@ -59075,7 +57914,7 @@ class Pattern { pattern = pattern.substr(1).trim(); } // Normalize slashes and ensures absolute root - pattern = Pattern.fixupPattern(pattern, homedir); + pattern = Pattern.fixupPattern(pattern); // Segments this.segments = new internal_path_1.Path(pattern).segments; // Trailing slash indicates the pattern should only match directories, not regular files @@ -59112,11 +57951,11 @@ class Pattern { // Normalize slashes itemPath = pathHelper.normalizeSeparators(itemPath); // Append a trailing slash. Otherwise Minimatch will not match the directory immediately - // preceding the globstar. For example, given the pattern `/foo/**`, Minimatch returns + // preceeding the globstar. For example, given the pattern `/foo/**`, Minimatch returns // false for `/foo` but returns true for `/foo/`. Append a trailing slash to handle that quirk. if (!itemPath.endsWith(path.sep)) { // Note, this is safe because the constructor ensures the pattern has an absolute root. - // For example, formats like C: and C:foo on Windows are resolved to an absolute root. + // For example, formats like C: and C:foo on Windows are resolved to an aboslute root. itemPath = `${itemPath}${path.sep}`; } } @@ -59154,15 +57993,15 @@ class Pattern { /** * Normalizes slashes and ensures absolute root */ - static fixupPattern(pattern, homedir) { + static fixupPattern(pattern) { // Empty - assert_1.default(pattern, 'pattern cannot be empty'); + assert(pattern, 'pattern cannot be empty'); // Must not contain `.` segment, unless first segment // Must not contain `..` segment const literalSegments = new internal_path_1.Path(pattern).segments.map(x => Pattern.getLiteral(x)); - assert_1.default(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); + assert(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); // Must not contain globs in root, e.g. Windows UNC path \\foo\b*r - assert_1.default(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); + assert(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); // Normalize slashes pattern = pathHelper.normalizeSeparators(pattern); // Replace leading `.` segment @@ -59171,9 +58010,9 @@ class Pattern { } // Replace leading `~` segment else if (pattern === '~' || pattern.startsWith(`~${path.sep}`)) { - homedir = homedir || os.homedir(); - assert_1.default(homedir, 'Unable to determine HOME directory'); - assert_1.default(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`); + const homedir = os.homedir(); + assert(homedir, 'Unable to determine HOME directory'); + assert(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`); pattern = Pattern.globEscape(homedir) + pattern.substr(1); } // Replace relative drive root, e.g. pattern is C: or C:foo @@ -59269,7 +58108,53 @@ exports.Pattern = Pattern; //# sourceMappingURL=internal-pattern.js.map /***/ }), -/* 924 */, +/* 924 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NoopContextManager = void 0; +var context_1 = __webpack_require__(715); +var NoopContextManager = /** @class */ (function () { + function NoopContextManager() { + } + NoopContextManager.prototype.active = function () { + return context_1.Context.ROOT_CONTEXT; + }; + NoopContextManager.prototype.with = function (context, fn) { + return fn(); + }; + NoopContextManager.prototype.bind = function (target, context) { + return target; + }; + NoopContextManager.prototype.enable = function () { + return this; + }; + NoopContextManager.prototype.disable = function () { + return this; + }; + return NoopContextManager; +}()); +exports.NoopContextManager = NoopContextManager; +//# sourceMappingURL=NoopContextManager.js.map + +/***/ }), /* 925 */, /* 926 */, /* 927 */, @@ -59283,7 +58168,7 @@ Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var tslib = __webpack_require__(966); +var tslib = __webpack_require__(422); var util = _interopDefault(__webpack_require__(669)); var os = __webpack_require__(87); @@ -59948,316 +58833,7 @@ exports.checkBypass = checkBypass; /* 963 */, /* 964 */, /* 965 */, -/* 966 */ -/***/ (function(module) { - -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global global, define, System, Reflect, Promise */ -var __extends; -var __assign; -var __rest; -var __decorate; -var __param; -var __metadata; -var __awaiter; -var __generator; -var __exportStar; -var __values; -var __read; -var __spread; -var __spreadArrays; -var __spreadArray; -var __await; -var __asyncGenerator; -var __asyncDelegator; -var __asyncValues; -var __makeTemplateObject; -var __importStar; -var __importDefault; -var __classPrivateFieldGet; -var __classPrivateFieldSet; -var __createBinding; -(function (factory) { - var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; - if (typeof define === "function" && define.amd) { - define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); - } - else if ( true && typeof module.exports === "object") { - factory(createExporter(root, createExporter(module.exports))); - } - else { - factory(createExporter(root)); - } - function createExporter(exports, previous) { - if (exports !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports, "__esModule", { value: true }); - } - else { - exports.__esModule = true; - } - } - return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; - } -}) -(function (exporter) { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - - __extends = function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - - __assign = Object.assign || function (t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - - __rest = function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; - - __decorate = function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - - __param = function (paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - }; - - __metadata = function (metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - }; - - __awaiter = function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - - __generator = function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - - __exportStar = function(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); - }; - - __createBinding = Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); - }) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }); - - __values = function (o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - - __read = function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - - /** @deprecated */ - __spread = function () { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; - }; - - /** @deprecated */ - __spreadArrays = function () { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; - }; - - __spreadArray = function (to, from) { - for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) - to[j] = from[i]; - return to; - }; - - __await = function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - - __asyncGenerator = function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - }; - - __asyncDelegator = function (o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } - }; - - __asyncValues = function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } - }; - - __makeTemplateObject = function (cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; - }; - - var __setModuleDefault = Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }; - - __importStar = function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; - }; - - __importDefault = function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - - __classPrivateFieldGet = function (receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - return privateMap.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, privateMap, value) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - privateMap.set(receiver, value); - return value; - }; - - exporter("__extends", __extends); - exporter("__assign", __assign); - exporter("__rest", __rest); - exporter("__decorate", __decorate); - exporter("__param", __param); - exporter("__metadata", __metadata); - exporter("__awaiter", __awaiter); - exporter("__generator", __generator); - exporter("__exportStar", __exportStar); - exporter("__createBinding", __createBinding); - exporter("__values", __values); - exporter("__read", __read); - exporter("__spread", __spread); - exporter("__spreadArrays", __spreadArrays); - exporter("__spreadArray", __spreadArray); - exporter("__await", __await); - exporter("__asyncGenerator", __asyncGenerator); - exporter("__asyncDelegator", __asyncDelegator); - exporter("__asyncValues", __asyncValues); - exporter("__makeTemplateObject", __makeTemplateObject); - exporter("__importStar", __importStar); - exporter("__importDefault", __importDefault); - exporter("__classPrivateFieldGet", __classPrivateFieldGet); - exporter("__classPrivateFieldSet", __classPrivateFieldSet); -}); - - -/***/ }), +/* 966 */, /* 967 */, /* 968 */, /* 969 */, @@ -60268,19 +58844,9 @@ var __createBinding; "use strict"; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; Object.defineProperty(exports, "__esModule", { value: true }); -const path = __importStar(__webpack_require__(622)); -const assert_1 = __importDefault(__webpack_require__(357)); +const assert = __webpack_require__(357); +const path = __webpack_require__(622); const IS_WINDOWS = process.platform === 'win32'; /** * Similar to path.dirname except normalizes the path separators and slightly better handling for Windows UNC paths. @@ -60320,8 +58886,8 @@ exports.dirname = dirname; * or `C:` are expanded based on the current working directory. */ function ensureAbsoluteRoot(root, itemPath) { - assert_1.default(root, `ensureAbsoluteRoot parameter 'root' must not be empty`); - assert_1.default(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`); + assert(root, `ensureAbsoluteRoot parameter 'root' must not be empty`); + assert(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`); // Already rooted if (hasAbsoluteRoot(itemPath)) { return itemPath; @@ -60331,7 +58897,7 @@ function ensureAbsoluteRoot(root, itemPath) { // Check for itemPath like C: or C:foo if (itemPath.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)) { let cwd = process.cwd(); - assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); + assert(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); // Drive letter matches cwd? Expand to cwd if (itemPath[0].toUpperCase() === cwd[0].toUpperCase()) { // Drive only, e.g. C: @@ -60356,11 +58922,11 @@ function ensureAbsoluteRoot(root, itemPath) { // Check for itemPath like \ or \foo else if (normalizeSeparators(itemPath).match(/^\\$|^\\[^\\]/)) { const cwd = process.cwd(); - assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); + assert(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); return `${cwd[0]}:\\${itemPath.substr(1)}`; } } - assert_1.default(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`); + assert(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`); // Otherwise ensure root ends with a separator if (root.endsWith('/') || (IS_WINDOWS && root.endsWith('\\'))) { // Intentionally empty @@ -60377,7 +58943,7 @@ exports.ensureAbsoluteRoot = ensureAbsoluteRoot; * `\\hello\share` and `C:\hello` (and using alternate separator). */ function hasAbsoluteRoot(itemPath) { - assert_1.default(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`); + assert(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`); // Normalize separators itemPath = normalizeSeparators(itemPath); // Windows @@ -60394,7 +58960,7 @@ exports.hasAbsoluteRoot = hasAbsoluteRoot; * `\`, `\hello`, `\\hello\share`, `C:`, and `C:\hello` (and using alternate separator). */ function hasRoot(itemPath) { - assert_1.default(itemPath, `isRooted parameter 'itemPath' must not be empty`); + assert(itemPath, `isRooted parameter 'itemPath' must not be empty`); // Normalize separators itemPath = normalizeSeparators(itemPath); // Windows @@ -60750,11 +59316,10 @@ var node_fetch = _interopDefault(__webpack_require__(454)); var abortController = __webpack_require__(106); var FormData = _interopDefault(__webpack_require__(790)); var util = __webpack_require__(669); -var url = __webpack_require__(835); var stream = __webpack_require__(794); -var logger$1 = __webpack_require__(928); var tunnel = __webpack_require__(413); var coreAuth = __webpack_require__(229); +var logger$1 = __webpack_require__(928); var xml2js = __webpack_require__(992); var os = __webpack_require__(87); var coreTracing = __webpack_require__(263); @@ -60769,20 +59334,20 @@ function getHeaderKey(headerName) { return headerName.toLowerCase(); } function isHttpHeadersLike(object) { - if (object && typeof object === "object") { - var castObject = object; - if (typeof castObject.rawHeaders === "function" && - typeof castObject.clone === "function" && - typeof castObject.get === "function" && - typeof castObject.set === "function" && - typeof castObject.contains === "function" && - typeof castObject.remove === "function" && - typeof castObject.headersArray === "function" && - typeof castObject.headerValues === "function" && - typeof castObject.headerNames === "function" && - typeof castObject.toJson === "function") { - return true; - } + if (!object || typeof object !== "object") { + return false; + } + if (typeof object.rawHeaders === "function" && + typeof object.clone === "function" && + typeof object.get === "function" && + typeof object.set === "function" && + typeof object.contains === "function" && + typeof object.remove === "function" && + typeof object.headersArray === "function" && + typeof object.headerValues === "function" && + typeof object.headerNames === "function" && + typeof object.toJson === "function") { + return true; } return false; } @@ -60801,8 +59366,8 @@ var HttpHeaders = /** @class */ (function () { /** * Set a header in this collection with the provided name and value. The name is * case-insensitive. - * @param headerName - The name of the header to set. This value is case-insensitive. - * @param headerValue - The value of the header to set. + * @param headerName The name of the header to set. This value is case-insensitive. + * @param headerValue The value of the header to set. */ HttpHeaders.prototype.set = function (headerName, headerValue) { this._headersMap[getHeaderKey(headerName)] = { @@ -60813,7 +59378,7 @@ var HttpHeaders = /** @class */ (function () { /** * Get the header value for the provided header name, or undefined if no header exists in this * collection with the provided name. - * @param headerName - The name of the header. + * @param headerName The name of the header. */ HttpHeaders.prototype.get = function (headerName) { var header = this._headersMap[getHeaderKey(headerName)]; @@ -60828,7 +59393,7 @@ var HttpHeaders = /** @class */ (function () { /** * Remove the header with the provided headerName. Return whether or not the header existed and * was removed. - * @param headerName - The name of the header to remove. + * @param headerName The name of the header to remove. */ HttpHeaders.prototype.remove = function (headerName) { var result = this.contains(headerName); @@ -60903,14 +59468,14 @@ var HttpHeaders = /** @class */ (function () { // Licensed under the MIT license. /** * Encodes a string in base64 format. - * @param value - The string to encode + * @param value the string to encode */ function encodeString(value) { return Buffer.from(value).toString("base64"); } /** * Encodes a byte array in base64 format. - * @param value - The Uint8Aray to encode + * @param value the Uint8Aray to encode */ function encodeByteArray(value) { // Buffer.from accepts | -- the TypeScript definition is off here @@ -60920,7 +59485,7 @@ function encodeByteArray(value) { } /** * Decodes a base64 string into a byte array. - * @param value - The base64 string to decode + * @param value the base64 string to decode */ function decodeString(value) { return Buffer.from(value, "base64"); @@ -60931,35 +59496,58 @@ function decodeString(value) { var Constants = { /** * The core-http version + * @const + * @type {string} */ - coreHttpVersion: "1.2.3", + coreHttpVersion: "1.1.9", /** * Specifies HTTP. + * + * @const + * @type {string} */ HTTP: "http:", /** * Specifies HTTPS. + * + * @const + * @type {string} */ HTTPS: "https:", /** * Specifies HTTP Proxy. + * + * @const + * @type {string} */ HTTP_PROXY: "HTTP_PROXY", /** * Specifies HTTPS Proxy. + * + * @const + * @type {string} */ HTTPS_PROXY: "HTTPS_PROXY", /** * Specifies NO Proxy. + * + * @const + * @type {string} */ NO_PROXY: "NO_PROXY", /** * Specifies ALL Proxy. + * + * @const + * @type {string} */ ALL_PROXY: "ALL_PROXY", HttpConstants: { /** * Http Verbs + * + * @const + * @enum {string} */ HttpVerbs: { PUT: "PUT", @@ -60980,6 +59568,9 @@ var Constants = { HeaderConstants: { /** * The Authorization header. + * + * @const + * @type {string} */ AUTHORIZATION: "authorization", AUTHORIZATION_SCHEME: "Bearer", @@ -60987,26 +59578,21 @@ var Constants = { * The Retry-After response-header field can be used with a 503 (Service * Unavailable) or 349 (Too Many Requests) responses to indicate how long * the service is expected to be unavailable to the requesting client. + * + * @const + * @type {string} */ RETRY_AFTER: "Retry-After", /** * The UserAgent header. + * + * @const + * @type {string} */ USER_AGENT: "User-Agent" } }; -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * Default key used to access the XML attributes. - */ -var XML_ATTRKEY = "$"; -/** - * Default key used to access the XML value content. - */ -var XML_CHARKEY = "_"; - // Copyright (c) Microsoft Corporation. var validUuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i; /** @@ -61019,8 +59605,8 @@ var isNode = typeof process !== "undefined" && /** * Encodes an URI. * - * @param uri - The URI to be encoded. - * @returns The encoded URI. + * @param {string} uri The URI to be encoded. + * @return {string} The encoded URI. */ function encodeUri(uri) { return encodeURIComponent(uri) @@ -61034,8 +59620,9 @@ function encodeUri(uri) { * Returns a stripped version of the Http Response which only contains body, * headers and the status. * - * @param response - The Http Response - * @returns The stripped version of Http Response. + * @param {HttpOperationResponse} response The Http Response + * + * @return {object} The stripped version of Http Response. */ function stripResponse(response) { var strippedResponse = {}; @@ -61048,8 +59635,9 @@ function stripResponse(response) { * Returns a stripped version of the Http Request that does not contain the * Authorization header. * - * @param request - The Http Request object - * @returns The stripped version of Http Request. + * @param {WebResourceLike} request The Http Request object + * + * @return {WebResourceLike} The stripped version of Http Request. */ function stripRequest(request) { var strippedRequest = request.clone(); @@ -61061,8 +59649,9 @@ function stripRequest(request) { /** * Validates the given uuid as a string * - * @param uuid - The uuid as a string that needs to be validated - * @returns True if the uuid is valid; false otherwise. + * @param {string} uuid The uuid as a string that needs to be validated + * + * @return {boolean} True if the uuid is valid; false otherwise. */ function isValidUuid(uuid) { return validUuidRegex.test(uuid); @@ -61070,7 +59659,7 @@ function isValidUuid(uuid) { /** * Generated UUID * - * @returns RFC4122 v4 UUID. + * @return {string} RFC4122 v4 UUID. */ function generateUuid() { return uuid.v4(); @@ -61079,10 +59668,12 @@ function generateUuid() { * Executes an array of promises sequentially. Inspiration of this method is here: * https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html. An awesome blog on promises! * - * @param promiseFactories - An array of promise factories(A function that return a promise) - * @param kickstart - Input to the first promise that is used to kickstart the promise chain. + * @param {Array} promiseFactories An array of promise factories(A function that return a promise) + * + * @param {any} [kickstart] Input to the first promise that is used to kickstart the promise chain. * If not provided then the promise chain starts with undefined. - * @returns A chain of resolved or rejected promises + * + * @return A chain of resolved or rejected promises */ function executePromisesSequentially(promiseFactories, kickstart) { var result = Promise.resolve(kickstart); @@ -61093,25 +59684,23 @@ function executePromisesSequentially(promiseFactories, kickstart) { } /** * A wrapper for setTimeout that resolves a promise after t milliseconds. - * @param t - The number of milliseconds to be delayed. - * @param value - The value to be resolved with after a timeout of t milliseconds. - * @returns Resolved promise + * @param {number} t The number of milliseconds to be delayed. + * @param {T} value The value to be resolved with after a timeout of t milliseconds. + * @returns {Promise} Resolved promise */ function delay(t, value) { return new Promise(function (resolve) { return setTimeout(function () { return resolve(value); }, t); }); } /** * Converts a Promise to a callback. - * @param promise - The Promise to be converted to a callback - * @returns A function that takes the callback `(cb: Function) => void` + * @param {Promise} promise The Promise to be converted to a callback + * @returns {Function} A function that takes the callback (cb: Function): void * @deprecated generated code should instead depend on responseToBody */ -// eslint-disable-next-line @typescript-eslint/ban-types function promiseToCallback(promise) { if (typeof promise.then !== "function") { throw new Error("The provided input is not a Promise."); } - // eslint-disable-next-line @typescript-eslint/ban-types return function (cb) { promise .then(function (data) { @@ -61126,8 +59715,8 @@ function promiseToCallback(promise) { } /** * Converts a Promise to a service callback. - * @param promise - The Promise of HttpOperationResponse to be converted to a service callback - * @returns A function that takes the service callback (cb: ServiceCallback): void + * @param {Promise} promise - The Promise of HttpOperationResponse to be converted to a service callback + * @returns {Function} A function that takes the service callback (cb: ServiceCallback): void */ function promiseToServiceCallback(promise) { if (typeof promise.then !== "function") { @@ -61151,38 +59740,35 @@ function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) { if (!xmlNamespaceKey || !xmlNamespace) { return _a = {}, _a[elementName] = obj, _a; } - var result = (_b = {}, _b[elementName] = obj, _b); - result[XML_ATTRKEY] = (_c = {}, _c[xmlNamespaceKey] = xmlNamespace, _c); - return result; + return _b = {}, _b[elementName] = obj, _b.$ = (_c = {}, _c[xmlNamespaceKey] = xmlNamespace, _c), _b; } /** * Applies the properties on the prototype of sourceCtors to the prototype of targetCtor - * @param targetCtor - The target object on which the properties need to be applied. - * @param sourceCtors - An array of source objects from which the properties need to be taken. + * @param {object} targetCtor The target object on which the properties need to be applied. + * @param {Array} sourceCtors An array of source objects from which the properties need to be taken. */ -function applyMixins(targetCtorParam, sourceCtors) { - var castTargetCtorParam = targetCtorParam; - sourceCtors.forEach(function (sourceCtor) { - Object.getOwnPropertyNames(sourceCtor.prototype).forEach(function (name) { - castTargetCtorParam.prototype[name] = sourceCtor.prototype[name]; +function applyMixins(targetCtor, sourceCtors) { + sourceCtors.forEach(function (sourceCtors) { + Object.getOwnPropertyNames(sourceCtors.prototype).forEach(function (name) { + targetCtor.prototype[name] = sourceCtors.prototype[name]; }); }); } var validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; /** * Indicates whether the given string is in ISO 8601 format. - * @param value - The value to be validated for ISO 8601 duration format. - * @returns `true` if valid, `false` otherwise. + * @param {string} value The value to be validated for ISO 8601 duration format. + * @return {boolean} `true` if valid, `false` otherwise. */ function isDuration(value) { return validateISODuration.test(value); } /** * Replace all of the instances of searchValue in value with the provided replaceValue. - * @param value - The value to search and replace in. - * @param searchValue - The value to search for in the value argument. - * @param replaceValue - The value to replace searchValue with in the value argument. - * @returns The value where each instance of searchValue was replaced with replacedValue. + * @param {string | undefined} value The value to search and replace in. + * @param {string} searchValue The value to search for in the value argument. + * @param {string} replaceValue The value to replace searchValue with in the value argument. + * @returns {string | undefined} The value where each instance of searchValue was replaced with replacedValue. */ function replaceAll(value, searchValue, replaceValue) { return !value || !searchValue ? value : value.split(searchValue).join(replaceValue || ""); @@ -61190,8 +59776,8 @@ function replaceAll(value, searchValue, replaceValue) { /** * Determines whether the given entity is a basic/primitive type * (string, number, boolean, null, undefined). - * @param value - Any entity - * @returns true is it is primitive type, false otherwise. + * @param {any} value Any entity + * @return {boolean} - true is it is primitive type, false otherwise. */ function isPrimitiveType(value) { return (typeof value !== "object" && typeof value !== "function") || value === null; @@ -61218,34 +59804,32 @@ var Serializer = /** @class */ (function () { throw new Error("\"" + objectName + "\" with value \"" + value + "\" should satisfy the constraint \"" + constraintName + "\": " + constraintValue + "."); }; if (mapper.constraints && value != undefined) { - var valueAsNumber = value; var _a = mapper.constraints, ExclusiveMaximum = _a.ExclusiveMaximum, ExclusiveMinimum = _a.ExclusiveMinimum, InclusiveMaximum = _a.InclusiveMaximum, InclusiveMinimum = _a.InclusiveMinimum, MaxItems = _a.MaxItems, MaxLength = _a.MaxLength, MinItems = _a.MinItems, MinLength = _a.MinLength, MultipleOf = _a.MultipleOf, Pattern = _a.Pattern, UniqueItems = _a.UniqueItems; - if (ExclusiveMaximum != undefined && valueAsNumber >= ExclusiveMaximum) { + if (ExclusiveMaximum != undefined && value >= ExclusiveMaximum) { failValidation("ExclusiveMaximum", ExclusiveMaximum); } - if (ExclusiveMinimum != undefined && valueAsNumber <= ExclusiveMinimum) { + if (ExclusiveMinimum != undefined && value <= ExclusiveMinimum) { failValidation("ExclusiveMinimum", ExclusiveMinimum); } - if (InclusiveMaximum != undefined && valueAsNumber > InclusiveMaximum) { + if (InclusiveMaximum != undefined && value > InclusiveMaximum) { failValidation("InclusiveMaximum", InclusiveMaximum); } - if (InclusiveMinimum != undefined && valueAsNumber < InclusiveMinimum) { + if (InclusiveMinimum != undefined && value < InclusiveMinimum) { failValidation("InclusiveMinimum", InclusiveMinimum); } - var valueAsArray = value; - if (MaxItems != undefined && valueAsArray.length > MaxItems) { + if (MaxItems != undefined && value.length > MaxItems) { failValidation("MaxItems", MaxItems); } - if (MaxLength != undefined && valueAsArray.length > MaxLength) { + if (MaxLength != undefined && value.length > MaxLength) { failValidation("MaxLength", MaxLength); } - if (MinItems != undefined && valueAsArray.length < MinItems) { + if (MinItems != undefined && value.length < MinItems) { failValidation("MinItems", MinItems); } - if (MinLength != undefined && valueAsArray.length < MinLength) { + if (MinLength != undefined && value.length < MinLength) { failValidation("MinLength", MinLength); } - if (MultipleOf != undefined && valueAsNumber % MultipleOf !== 0) { + if (MultipleOf != undefined && value % MultipleOf !== 0) { failValidation("MultipleOf", MultipleOf); } if (Pattern) { @@ -61255,7 +59839,7 @@ var Serializer = /** @class */ (function () { } } if (UniqueItems && - valueAsArray.some(function (item, i, ar) { return ar.indexOf(item) !== i; })) { + value.some(function (item, i, ar) { return ar.indexOf(item) !== i; })) { failValidation("UniqueItems", UniqueItems); } } @@ -61263,20 +59847,15 @@ var Serializer = /** @class */ (function () { /** * Serialize the given object based on its metadata defined in the mapper * - * @param mapper - The mapper which defines the metadata of the serializable object - * @param object - A valid Javascript object to be serialized - * @param objectName - Name of the serialized object - * @param options - additional options to deserialization - * @returns A valid serialized Javascript object + * @param {Mapper} mapper The mapper which defines the metadata of the serializable object + * + * @param {object|string|Array|number|boolean|Date|stream} object A valid Javascript object to be serialized + * + * @param {string} objectName Name of the serialized object + * + * @returns {object|string|Array|number|boolean|Date|stream} A valid serialized Javascript object */ - Serializer.prototype.serialize = function (mapper, object, objectName, options) { - var _a, _b, _c; - if (options === void 0) { options = {}; } - var updatedOptions = { - rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", - includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, - xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY - }; + Serializer.prototype.serialize = function (mapper, object, objectName) { var payload = {}; var mapperType = mapper.type.name; if (!objectName) { @@ -61333,13 +59912,13 @@ var Serializer = /** @class */ (function () { payload = serializeBase64UrlType(objectName, object); } else if (mapperType.match(/^Sequence$/i) !== null) { - payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML)); } else if (mapperType.match(/^Dictionary$/i) !== null) { - payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML)); } else if (mapperType.match(/^Composite$/i) !== null) { - payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML)); } } return payload; @@ -61347,20 +59926,15 @@ var Serializer = /** @class */ (function () { /** * Deserialize the given object based on its metadata defined in the mapper * - * @param mapper - The mapper which defines the metadata of the serializable object - * @param responseBody - A valid Javascript entity to be deserialized - * @param objectName - Name of the deserialized object - * @param options - Controls behavior of XML parser and builder. - * @returns A valid deserialized Javascript object + * @param {object} mapper The mapper which defines the metadata of the serializable object + * + * @param {object|string|Array|number|boolean|Date|stream} responseBody A valid Javascript entity to be deserialized + * + * @param {string} objectName Name of the deserialized object + * + * @returns {object|string|Array|number|boolean|Date|stream} A valid deserialized Javascript object */ - Serializer.prototype.deserialize = function (mapper, responseBody, objectName, options) { - var _a, _b, _c; - if (options === void 0) { options = {}; } - var updatedOptions = { - rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", - includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, - xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY - }; + Serializer.prototype.deserialize = function (mapper, responseBody, objectName) { if (responseBody == undefined) { if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) { // Edge case for empty XML non-wrapped lists. xml2js can't distinguish @@ -61380,20 +59954,17 @@ var Serializer = /** @class */ (function () { objectName = mapper.serializedName; } if (mapperType.match(/^Composite$/i) !== null) { - payload = deserializeCompositeType(this, mapper, responseBody, objectName, updatedOptions); + payload = deserializeCompositeType(this, mapper, responseBody, objectName); } else { if (this.isXML) { - var xmlCharKey = updatedOptions.xmlCharKey; - var castResponseBody = responseBody; /** * If the mapper specifies this as a non-composite type value but the responseBody contains - * both header ("$" i.e., XML_ATTRKEY) and body ("#" i.e., XML_CHARKEY) properties, - * then just reduce the responseBody value to the body ("#" i.e., XML_CHARKEY) property. + * both header ("$") and body ("_") properties, then just reduce the responseBody value to + * the body ("_") property. */ - if (castResponseBody[XML_ATTRKEY] != undefined && - castResponseBody[xmlCharKey] != undefined) { - responseBody = castResponseBody[xmlCharKey]; + if (responseBody["$"] != undefined && responseBody["_"] != undefined) { + responseBody = responseBody["_"]; } } if (mapperType.match(/^Number$/i) !== null) { @@ -61429,10 +60000,10 @@ var Serializer = /** @class */ (function () { payload = base64UrlToByteArray(responseBody); } else if (mapperType.match(/^Sequence$/i) !== null) { - payload = deserializeSequenceType(this, mapper, responseBody, objectName, updatedOptions); + payload = deserializeSequenceType(this, mapper, responseBody, objectName); } else if (mapperType.match(/^Dictionary$/i) !== null) { - payload = deserializeDictionaryType(this, mapper, responseBody, objectName, updatedOptions); + payload = deserializeDictionaryType(this, mapper, responseBody, objectName); } } if (mapper.isConstant) { @@ -61537,7 +60108,7 @@ function serializeBasicTypes(typeName, objectName, value) { objectType !== "function" && !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value) && - !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob)) { + !(typeof Blob === "function" && value instanceof Blob)) { throw new Error(objectName + " must be a string, Blob, ArrayBuffer, ArrayBufferView, or a function returning NodeJS.ReadableStream."); } } @@ -61621,7 +60192,7 @@ function serializeDateTypes(typeName, value, objectName) { } return value; } -function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) { +function serializeSequenceType(serializer, mapper, object, objectName, isXml) { var _a, _b; if (!Array.isArray(object)) { throw new Error(objectName + " must be of type Array."); @@ -61633,19 +60204,16 @@ function serializeSequenceType(serializer, mapper, object, objectName, isXml, op } var tempArray = []; for (var i = 0; i < object.length; i++) { - var serializedValue = serializer.serialize(elementType, object[i], objectName, options); + var serializedValue = serializer.serialize(elementType, object[i], objectName); if (isXml && elementType.xmlNamespace) { var xmlnsKey = elementType.xmlNamespacePrefix ? "xmlns:" + elementType.xmlNamespacePrefix : "xmlns"; if (elementType.type.name === "Composite") { - tempArray[i] = tslib.__assign({}, serializedValue); - tempArray[i][XML_ATTRKEY] = (_a = {}, _a[xmlnsKey] = elementType.xmlNamespace, _a); + tempArray[i] = tslib.__assign(tslib.__assign({}, serializedValue), { $: (_a = {}, _a[xmlnsKey] = elementType.xmlNamespace, _a) }); } else { - tempArray[i] = {}; - tempArray[i][options.xmlCharKey] = serializedValue; - tempArray[i][XML_ATTRKEY] = (_b = {}, _b[xmlnsKey] = elementType.xmlNamespace, _b); + tempArray[i] = { _: serializedValue, $: (_b = {}, _b[xmlnsKey] = elementType.xmlNamespace, _b) }; } } else { @@ -61654,7 +60222,7 @@ function serializeSequenceType(serializer, mapper, object, objectName, isXml, op } return tempArray; } -function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) { +function serializeDictionaryType(serializer, mapper, object, objectName, isXml) { var _a; if (typeof object !== "object") { throw new Error(objectName + " must be of type object."); @@ -61667,24 +60235,22 @@ function serializeDictionaryType(serializer, mapper, object, objectName, isXml, var tempDictionary = {}; for (var _i = 0, _b = Object.keys(object); _i < _b.length; _i++) { var key = _b[_i]; - var serializedValue = serializer.serialize(valueType, object[key], objectName, options); + var serializedValue = serializer.serialize(valueType, object[key], objectName); // If the element needs an XML namespace we need to add it within the $ property - tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options); + tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml); } // Add the namespace to the root element if needed if (isXml && mapper.xmlNamespace) { var xmlnsKey = mapper.xmlNamespacePrefix ? "xmlns:" + mapper.xmlNamespacePrefix : "xmlns"; - var result = tempDictionary; - result[XML_ATTRKEY] = (_a = {}, _a[xmlnsKey] = mapper.xmlNamespace, _a); - return result; + return tslib.__assign(tslib.__assign({}, tempDictionary), { $: (_a = {}, _a[xmlnsKey] = mapper.xmlNamespace, _a) }); } return tempDictionary; } /** * Resolves the additionalProperties property from a referenced mapper - * @param serializer - The serializer containing the entire set of mappers - * @param mapper - The composite mapper to resolve - * @param objectName - Name of the object being serialized + * @param serializer the serializer containing the entire set of mappers + * @param mapper the composite mapper to resolve + * @param objectName name of the object being serialized */ function resolveAdditionalProperties(serializer, mapper, objectName) { var additionalProperties = mapper.type.additionalProperties; @@ -61696,9 +60262,9 @@ function resolveAdditionalProperties(serializer, mapper, objectName) { } /** * Finds the mapper referenced by className - * @param serializer - The serializer containing the entire set of mappers - * @param mapper - The composite mapper to resolve - * @param objectName - Name of the object being serialized + * @param serializer the serializer containing the entire set of mappers + * @param mapper the composite mapper to resolve + * @param objectName name of the object being serialized */ function resolveReferencedMapper(serializer, mapper, objectName) { var className = mapper.type.className; @@ -61709,8 +60275,8 @@ function resolveReferencedMapper(serializer, mapper, objectName) { } /** * Resolves a composite mapper's modelProperties. - * @param serializer - The serializer containing the entire set of mappers - * @param mapper - The composite mapper to resolve + * @param serializer the serializer containing the entire set of mappers + * @param mapper the composite mapper to resolve */ function resolveModelProperties(serializer, mapper, objectName) { var modelProps = mapper.type.modelProperties; @@ -61727,7 +60293,7 @@ function resolveModelProperties(serializer, mapper, objectName) { } return modelProps; } -function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) { +function serializeCompositeType(serializer, mapper, object, objectName, isXml) { var _a, _b; if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { mapper = getPolymorphicMapper(serializer, mapper, object, "clientName"); @@ -61769,7 +60335,7 @@ function serializeCompositeType(serializer, mapper, object, objectName, isXml, o var xmlnsKey = mapper.xmlNamespacePrefix ? "xmlns:" + mapper.xmlNamespacePrefix : "xmlns"; - parentObject[XML_ATTRKEY] = tslib.__assign(tslib.__assign({}, parentObject[XML_ATTRKEY]), (_a = {}, _a[xmlnsKey] = mapper.xmlNamespace, _a)); + parentObject.$ = tslib.__assign(tslib.__assign({}, parentObject.$), (_a = {}, _a[xmlnsKey] = mapper.xmlNamespace, _a)); } var propertyObjectName = propertyMapper.serializedName !== "" ? objectName + "." + propertyMapper.serializedName @@ -61781,15 +60347,15 @@ function serializeCompositeType(serializer, mapper, object, objectName, isXml, o toSerialize == undefined) { toSerialize = mapper.serializedName; } - var serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options); + var serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName); if (serializedValue !== undefined && propName != undefined) { - var value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options); + var value = getXmlObjectValue(propertyMapper, serializedValue, isXml); if (isXml && propertyMapper.xmlIsAttribute) { - // XML_ATTRKEY, i.e., $ is the key attributes are kept under in xml2js. + // $ is the key attributes are kept under in xml2js. // This keeps things simple while preventing name collision // with names in user documents. - parentObject[XML_ATTRKEY] = parentObject[XML_ATTRKEY] || {}; - parentObject[XML_ATTRKEY][propName] = serializedValue; + parentObject.$ = parentObject.$ || {}; + parentObject.$[propName] = serializedValue; } else if (isXml && propertyMapper.xmlIsWrapped) { parentObject[propName] = (_b = {}, _b[propertyMapper.xmlElementName] = value, _b); @@ -61806,7 +60372,7 @@ function serializeCompositeType(serializer, mapper, object, objectName, isXml, o var _loop_1 = function (clientPropName) { var isAdditionalProperty = propNames.every(function (pn) { return pn !== clientPropName; }); if (isAdditionalProperty) { - payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options); + payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]'); } }; for (var clientPropName in object) { @@ -61817,7 +60383,7 @@ function serializeCompositeType(serializer, mapper, object, objectName, isXml, o } return object; } -function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) { +function getXmlObjectValue(propertyMapper, serializedValue, isXml) { var _a; if (!isXml || !propertyMapper.xmlNamespace) { return serializedValue; @@ -61827,24 +60393,14 @@ function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) { : "xmlns"; var xmlNamespace = (_a = {}, _a[xmlnsKey] = propertyMapper.xmlNamespace, _a); if (["Composite"].includes(propertyMapper.type.name)) { - if (serializedValue[XML_ATTRKEY]) { - return serializedValue; - } - else { - var result_1 = tslib.__assign({}, serializedValue); - result_1[XML_ATTRKEY] = xmlNamespace; - return result_1; - } + return tslib.__assign({ $: xmlNamespace }, serializedValue); } - var result = {}; - result[options.xmlCharKey] = serializedValue; - result[XML_ATTRKEY] = xmlNamespace; - return result; + return { _: serializedValue, $: xmlNamespace }; } -function isSpecialXmlProperty(propertyName, options) { - return [XML_ATTRKEY, options.xmlCharKey].includes(propertyName); +function isSpecialXmlProperty(propertyName) { + return ["$", "_"].includes(propertyName); } -function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) { +function deserializeCompositeType(serializer, mapper, responseBody, objectName) { var _a; if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName"); @@ -61868,15 +60424,15 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, for (var _c = 0, _d = Object.keys(responseBody); _c < _d.length; _c++) { var headerKey = _d[_c]; if (headerKey.startsWith(headerCollectionPrefix)) { - dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options); + dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName); } handledPropertyNames.push(headerKey); } instance[key] = dictionary; } else if (serializer.isXML) { - if (propertyMapper.xmlIsAttribute && responseBody[XML_ATTRKEY]) { - instance[key] = serializer.deserialize(propertyMapper, responseBody[XML_ATTRKEY][xmlName], propertyObjectName, options); + if (propertyMapper.xmlIsAttribute && responseBody.$) { + instance[key] = serializer.deserialize(propertyMapper, responseBody.$[xmlName], propertyObjectName); } else { var propertyName = xmlElementName || xmlName || serializedName; @@ -61897,11 +60453,11 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, */ var wrapped = responseBody[xmlName]; var elementList = (_a = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _a !== void 0 ? _a : []; - instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options); + instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName); } else { var property = responseBody[propertyName]; - instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options); + instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName); } } } @@ -61936,10 +60492,10 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, // paging if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") { propertyInstance = responseBody[key]; - instance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); + instance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName); } else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) { - serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); + serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName); instance[key] = serializedValue; } } @@ -61957,7 +60513,7 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, }; for (var responsePropName in responseBody) { if (isAdditionalProperty(responsePropName)) { - instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options); + instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]'); } } } @@ -61966,14 +60522,14 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, var key = _g[_f]; if (instance[key] === undefined && !handledPropertyNames.includes(key) && - !isSpecialXmlProperty(key, options)) { + !isSpecialXmlProperty(key)) { instance[key] = responseBody[key]; } } } return instance; } -function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) { +function deserializeDictionaryType(serializer, mapper, responseBody, objectName) { var value = mapper.type.value; if (!value || typeof value !== "object") { throw new Error("\"value\" metadata for a Dictionary must be defined in the " + @@ -61983,13 +60539,13 @@ function deserializeDictionaryType(serializer, mapper, responseBody, objectName, var tempDictionary = {}; for (var _i = 0, _a = Object.keys(responseBody); _i < _a.length; _i++) { var key = _a[_i]; - tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options); + tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName); } return tempDictionary; } return responseBody; } -function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) { +function deserializeSequenceType(serializer, mapper, responseBody, objectName) { var element = mapper.type.element; if (!element || typeof element !== "object") { throw new Error("element\" metadata for an Array must be defined in the " + @@ -62002,7 +60558,7 @@ function deserializeSequenceType(serializer, mapper, responseBody, objectName, o } var tempArray = []; for (var i = 0; i < responseBody.length; i++) { - tempArray[i] = serializer.deserialize(element, responseBody[i], objectName + "[" + i + "]", options); + tempArray[i] = serializer.deserialize(element, responseBody[i], objectName + "[" + i + "]"); } return tempArray; } @@ -62040,7 +60596,6 @@ function getPolymorphicDiscriminatorSafely(serializer, typeName) { } // TODO: why is this here? function serializeObject(toSerialize) { - var castToSerialize = toSerialize; if (toSerialize == undefined) return undefined; if (toSerialize instanceof Uint8Array) { @@ -62060,7 +60615,7 @@ function serializeObject(toSerialize) { else if (typeof toSerialize === "object") { var dictionary = {}; for (var property in toSerialize) { - dictionary[property] = serializeObject(castToSerialize[property]); + dictionary[property] = serializeObject(toSerialize[property]); } return dictionary; } @@ -62077,7 +60632,6 @@ function strEnum(o) { } return result; } -// eslint-disable-next-line @typescript-eslint/no-redeclare var MapperType = strEnum([ "Base64Url", "Boolean", @@ -62099,17 +60653,17 @@ var MapperType = strEnum([ // Copyright (c) Microsoft Corporation. function isWebResourceLike(object) { - if (object && typeof object === "object") { - var castObject = object; - if (typeof castObject.url === "string" && - typeof castObject.method === "string" && - typeof castObject.headers === "object" && - isHttpHeadersLike(castObject.headers) && - typeof castObject.validateRequestProperties === "function" && - typeof castObject.prepare === "function" && - typeof castObject.clone === "function") { - return true; - } + if (typeof object !== "object") { + return false; + } + if (typeof object.url === "string" && + typeof object.method === "string" && + typeof object.headers === "object" && + isHttpHeadersLike(object.headers) && + typeof object.validateRequestProperties === "function" && + typeof object.prepare === "function" && + typeof object.clone === "function") { + return true; } return false; } @@ -62118,11 +60672,12 @@ function isWebResourceLike(object) { * * This class provides an abstraction over a REST call by being library / implementation agnostic and wrapping the necessary * properties to initiate a request. + * + * @constructor */ var WebResource = /** @class */ (function () { - function WebResource(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, decompressResponse, streamResponseStatusCodes) { + function WebResource(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, decompressResponse) { this.streamResponseBody = streamResponseBody; - this.streamResponseStatusCodes = streamResponseStatusCodes; this.url = url || ""; this.method = method || "GET"; this.headers = isHttpHeadersLike(headers) ? headers : new HttpHeaders(headers); @@ -62154,8 +60709,8 @@ var WebResource = /** @class */ (function () { }; /** * Prepares the request. - * @param options - Options to provide for preparing the request. - * @returns Returns the prepared WebResource (HTTP Request) object that needs to be given to the request pipeline. + * @param {RequestPrepareOptions} options Options to provide for preparing the request. + * @returns {WebResource} Returns the prepared WebResource (HTTP Request) object that needs to be given to the request pipeline. */ WebResource.prototype.prepare = function (options) { if (!options) { @@ -62304,7 +60859,7 @@ var WebResource = /** @class */ (function () { if (!this.headers.get("Content-Type")) { this.headers.set("Content-Type", "application/json; charset=utf-8"); } - // set the request body. request.js automatically sets the Content-Length request header, so we need not set it explicitly + // set the request body. request.js automatically sets the Content-Length request header, so we need not set it explicilty this.body = options.body; if (options.body !== undefined && options.body !== null) { // body as a stream special case. set the body as-is and check for some special request headers specific to sending a stream. @@ -62335,10 +60890,10 @@ var WebResource = /** @class */ (function () { }; /** * Clone this WebResource HTTP request object. - * @returns The clone of this WebResource HTTP request object. + * @returns {WebResource} The clone of this WebResource HTTP request object. */ WebResource.prototype.clone = function () { - var result = new WebResource(this.url, this.method, this.body, this.query, this.headers && this.headers.clone(), this.streamResponseBody, this.withCredentials, this.abortSignal, this.timeout, this.onUploadProgress, this.onDownloadProgress, this.proxySettings, this.keepAlive, this.decompressResponse, this.streamResponseStatusCodes); + var result = new WebResource(this.url, this.method, this.body, this.query, this.headers && this.headers.clone(), this.streamResponseBody, this.withCredentials, this.abortSignal, this.timeout, this.onUploadProgress, this.onDownloadProgress, this.proxySettings, this.keepAlive, this.decompressResponse); if (this.formData) { result.formData = this.formData; } @@ -62385,12 +60940,9 @@ var URLQuery = /** @class */ (function () { * parameterName. */ URLQuery.prototype.set = function (parameterName, parameterValue) { - var caseParameterValue = parameterValue; if (parameterName) { - if (caseParameterValue !== undefined && caseParameterValue !== null) { - var newValue = Array.isArray(caseParameterValue) - ? caseParameterValue - : caseParameterValue.toString(); + if (parameterValue !== undefined && parameterValue !== null) { + var newValue = Array.isArray(parameterValue) ? parameterValue : parameterValue.toString(); this._rawQuery[parameterName] = newValue; } else { @@ -62967,7 +61519,6 @@ var defaultAllowedHeaderNames = [ "x-ms-correlation-request-id", "x-ms-request-id", "client-request-id", - "ms-cv", "return-client-request-id", "traceparent", "Access-Control-Allow-Credentials", @@ -63113,9 +61664,6 @@ var RestError = /** @class */ (function (_super) { return RestError; }(Error)); -// Copyright (c) Microsoft Corporation. -var logger = logger$1.createClientLogger("core-http"); - // Copyright (c) Microsoft Corporation. var ReportTransform = /** @class */ (function (_super) { tslib.__extends(ReportTransform, _super); @@ -63137,12 +61685,10 @@ var FetchHttpClient = /** @class */ (function () { function FetchHttpClient() { } FetchHttpClient.prototype.sendRequest = function (httpRequest) { - var _a; return tslib.__awaiter(this, void 0, void 0, function () { - var abortController$1, abortListener, formData, requestForm_1, appendFormValue, _i, _b, formKey, formValue, j, contentType, body, onUploadProgress, uploadReportStream, platformSpecificRequestInit, requestInit, operationResponse, response, headers, streaming, _c, onDownloadProgress, responseBody, downloadReportStream, length_1, error_1, fetchError, uploadStreamDone, downloadStreamDone; - var _d; - return tslib.__generator(this, function (_e) { - switch (_e.label) { + var abortController$1, abortListener, formData, requestForm_1, appendFormValue, _i, _a, formKey, formValue, j, contentType, body, onUploadProgress, uploadReportStream, platformSpecificRequestInit, requestInit, response, headers, operationResponse, _b, _c, onDownloadProgress, responseBody, downloadReportStream, length_1, error_1, fetchError; + return tslib.__generator(this, function (_d) { + switch (_d.label) { case 0: if (!httpRequest && typeof httpRequest !== "object") { throw new Error("'httpRequest' (WebResourceLike) cannot be null or undefined and must be of type object."); @@ -63172,17 +61718,16 @@ var FetchHttpClient = /** @class */ (function () { if (typeof value === "function") { value = value(); } - if (value && - Object.prototype.hasOwnProperty.call(value, "value") && - Object.prototype.hasOwnProperty.call(value, "options")) { + // eslint-disable-next-line no-prototype-builtins + if (value && value.hasOwnProperty("value") && value.hasOwnProperty("options")) { requestForm_1.append(key, value.value, value.options); } else { requestForm_1.append(key, value); } }; - for (_i = 0, _b = Object.keys(formData); _i < _b.length; _i++) { - formKey = _b[_i]; + for (_i = 0, _a = Object.keys(formData); _i < _a.length; _i++) { + formKey = _a[_i]; formValue = formData[formKey]; if (Array.isArray(formValue)) { for (j = 0; j < formValue.length; j++) { @@ -63224,36 +61769,34 @@ var FetchHttpClient = /** @class */ (function () { } return [4 /*yield*/, this.prepareRequest(httpRequest)]; case 1: - platformSpecificRequestInit = _e.sent(); - requestInit = tslib.__assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method, signal: abortController$1.signal, redirect: "manual" }, platformSpecificRequestInit); - _e.label = 2; + platformSpecificRequestInit = _d.sent(); + requestInit = tslib.__assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method, signal: abortController$1.signal }, platformSpecificRequestInit); + _d.label = 2; case 2: - _e.trys.push([2, 8, 9, 10]); + _d.trys.push([2, 8, 9, 10]); return [4 /*yield*/, this.fetch(httpRequest.url, requestInit)]; case 3: - response = _e.sent(); + response = _d.sent(); headers = parseHeaders(response.headers); - streaming = ((_a = httpRequest.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(response.status)) || - httpRequest.streamResponseBody; - _d = { + _b = { headers: headers, request: httpRequest, status: response.status, - readableStreamBody: streaming + readableStreamBody: httpRequest.streamResponseBody ? response.body : undefined }; - if (!!streaming) return [3 /*break*/, 5]; + if (!!httpRequest.streamResponseBody) return [3 /*break*/, 5]; return [4 /*yield*/, response.text()]; case 4: - _c = _e.sent(); + _c = _d.sent(); return [3 /*break*/, 6]; case 5: _c = undefined; - _e.label = 6; + _d.label = 6; case 6: - operationResponse = (_d.bodyAsText = _c, - _d); + operationResponse = (_b.bodyAsText = _c, + _b); onDownloadProgress = httpRequest.onDownloadProgress; if (onDownloadProgress) { responseBody = response.body || undefined; @@ -63272,10 +61815,10 @@ var FetchHttpClient = /** @class */ (function () { } return [4 /*yield*/, this.processRequest(operationResponse)]; case 7: - _e.sent(); + _d.sent(); return [2 /*return*/, operationResponse]; case 8: - error_1 = _e.sent(); + error_1 = _d.sent(); fetchError = error_1; if (fetchError.code === "ENOTFOUND") { throw new RestError(fetchError.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest); @@ -63287,23 +61830,7 @@ var FetchHttpClient = /** @class */ (function () { case 9: // clean up event listener if (httpRequest.abortSignal && abortListener) { - uploadStreamDone = Promise.resolve(); - if (isReadableStream(body)) { - uploadStreamDone = isStreamComplete(body); - } - downloadStreamDone = Promise.resolve(); - if (isReadableStream(operationResponse === null || operationResponse === void 0 ? void 0 : operationResponse.readableStreamBody)) { - downloadStreamDone = isStreamComplete(operationResponse.readableStreamBody); - } - Promise.all([uploadStreamDone, downloadStreamDone]) - .then(function () { - var _a; - (_a = httpRequest.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener); - return; - }) - .catch(function (e) { - logger.warning("Error when cleaning up abortListener on httpRequest", e); - }); + httpRequest.abortSignal.removeEventListener("abort", abortListener); } return [7 /*endfinally*/]; case 10: return [2 /*return*/]; @@ -63316,13 +61843,6 @@ var FetchHttpClient = /** @class */ (function () { function isReadableStream(body) { return body && typeof body.pipe === "function"; } -function isStreamComplete(stream) { - return new Promise(function (resolve) { - stream.on("close", resolve); - stream.on("end", resolve); - stream.on("error", resolve); - }); -} function parseHeaders(headers) { var httpHeaders = new HttpHeaders(); headers.forEach(function (value, key) { @@ -63529,7 +62049,7 @@ var NodeFetchHttpClient = /** @class */ (function (_super) { /** * Converts an OperationOptions to a RequestOptionsBase * - * @param opts - OperationOptions object to convert to RequestOptionsBase + * @param opts OperationOptions object to convert to RequestOptionsBase */ function operationOptionsToRequestOptionsBase(opts) { var requestOptions = opts.requestOptions, tracingOptions = opts.tracingOptions, additionalOptions = tslib.__rest(opts, ["requestOptions", "tracingOptions"]); @@ -63551,7 +62071,7 @@ var BaseRequestPolicy = /** @class */ (function () { } /** * Get whether or not a log with the provided log level should be logged. - * @param logLevel - The log level of the log that will be logged. + * @param logLevel The log level of the log that will be logged. * @returns Whether or not a log with the provided log level should be logged. */ BaseRequestPolicy.prototype.shouldLog = function (logLevel) { @@ -63560,8 +62080,8 @@ var BaseRequestPolicy = /** @class */ (function () { /** * Attempt to log the provided message to the provided logger. If no logger was provided or if * the log level does not meat the logger's threshold, then nothing will be logged. - * @param logLevel - The log level of this log. - * @param message - The message of this log. + * @param logLevel The log level of this log. + * @param message The message of this log. */ BaseRequestPolicy.prototype.log = function (logLevel, message) { this._options.log(logLevel, message); @@ -63577,7 +62097,7 @@ var RequestPolicyOptions = /** @class */ (function () { } /** * Get whether or not a log with the provided log level should be logged. - * @param logLevel - The log level of the log that will be logged. + * @param logLevel The log level of the log that will be logged. * @returns Whether or not a log with the provided log level should be logged. */ RequestPolicyOptions.prototype.shouldLog = function (logLevel) { @@ -63588,8 +62108,8 @@ var RequestPolicyOptions = /** @class */ (function () { /** * Attempt to log the provided message to the provided logger. If no logger was provided or if * the log level does not meet the logger's threshold, then nothing will be logged. - * @param logLevel - The log level of this log. - * @param message - The message of this log. + * @param logLevel The log level of this log. + * @param message The message of this log. */ RequestPolicyOptions.prototype.log = function (logLevel, message) { if (this._logger && this.shouldLog(logLevel)) { @@ -63599,6 +62119,9 @@ var RequestPolicyOptions = /** @class */ (function () { return RequestPolicyOptions; }()); +// Copyright (c) Microsoft Corporation. +var logger = logger$1.createClientLogger("core-http"); + // Copyright (c) Microsoft Corporation. function logPolicy(loggingOptions) { if (loggingOptions === void 0) { loggingOptions = {}; } @@ -63683,7 +62206,7 @@ var LogPolicy = /** @class */ (function (_super) { // Licensed under the MIT license. /** * Get the path to this parameter's value as a dotted string (a.b.c). - * @param parameter - The parameter to get the path string for. + * @param parameter The parameter to get the path string for. * @returns The path to this parameter's value as a dotted string. */ function getPathStringFromParameter(parameter) { @@ -63704,17 +62227,14 @@ function getPathStringFromParameterPath(parameterPath, mapper) { } // Copyright (c) Microsoft Corporation. -/** - * Gets the list of status codes for streaming responses. - * @internal @hidden - */ -function getStreamResponseStatusCodes(operationSpec) { - var result = new Set(); +function isStreamOperation(operationSpec) { + var result = false; for (var statusCode in operationSpec.responses) { var operationResponse = operationSpec.responses[statusCode]; if (operationResponse.bodyMapper && operationResponse.bodyMapper.type.name === MapperType.Stream) { - result.add(Number(statusCode)); + result = true; + break; } } return result; @@ -63730,12 +62250,13 @@ var xml2jsDefaultOptionsV2 = { trim: false, normalize: false, normalizeTags: false, - attrkey: XML_ATTRKEY, + attrkey: "$", + charkey: "_", explicitArray: true, ignoreAttrs: false, mergeAttrs: false, explicitRoot: true, - validator: undefined, + validator: null, xmlns: false, explicitChildren: false, preserveChildrenOrder: false, @@ -63744,17 +62265,17 @@ var xml2jsDefaultOptionsV2 = { includeWhiteChars: false, async: false, strict: true, - attrNameProcessors: undefined, - attrValueProcessors: undefined, - tagNameProcessors: undefined, - valueProcessors: undefined, + attrNameProcessors: null, + attrValueProcessors: null, + tagNameProcessors: null, + valueProcessors: null, rootName: "root", xmldec: { version: "1.0", encoding: "UTF-8", standalone: true }, - doctype: undefined, + doctype: null, renderOpts: { pretty: true, indent: " ", @@ -63776,27 +62297,23 @@ xml2jsBuilderSettings.renderOpts = { }; /** * Converts given JSON object to XML string - * @param obj - JSON object to be converted into XML string - * @param opts - Options that govern the parsing of given JSON object + * @param obj JSON object to be converted into XML string + * @param opts Options that govern the parsing of given JSON object + * `rootName` indicates the name of the root element in the resulting XML */ function stringifyXML(obj, opts) { - var _a; - if (opts === void 0) { opts = {}; } - xml2jsBuilderSettings.rootName = opts.rootName; - xml2jsBuilderSettings.charkey = (_a = opts.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; + xml2jsBuilderSettings.rootName = (opts || {}).rootName; var builder = new xml2js.Builder(xml2jsBuilderSettings); return builder.buildObject(obj); } /** * Converts given XML string into JSON - * @param str - String containing the XML content to be parsed into JSON - * @param opts - Options that govern the parsing of given xml string + * @param str String containing the XML content to be parsed into JSON + * @param opts Options that govern the parsing of given xml string + * `includeRoot` indicates whether the root element is to be included or not in the output */ function parseXML(str, opts) { - var _a; - if (opts === void 0) { opts = {}; } - xml2jsParserSettings.explicitRoot = !!opts.includeRoot; - xml2jsParserSettings.charkey = (_a = opts.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; + xml2jsParserSettings.explicitRoot = !!(opts && opts.includeRoot); var xmlParser = new xml2js.Parser(xml2jsParserSettings); return new Promise(function (resolve, reject) { if (!str) { @@ -63820,10 +62337,10 @@ function parseXML(str, opts) { * Create a new serialization RequestPolicyCreator that will serialized HTTP request bodies as they * pass through the HTTP pipeline. */ -function deserializationPolicy(deserializationContentTypes, parsingOptions) { +function deserializationPolicy(deserializationContentTypes) { return { create: function (nextPolicy, options) { - return new DeserializationPolicy(nextPolicy, options, deserializationContentTypes, parsingOptions); + return new DeserializationPolicy(nextPolicy, deserializationContentTypes, options); } }; } @@ -63841,25 +62358,22 @@ var DefaultDeserializationOptions = { */ var DeserializationPolicy = /** @class */ (function (_super) { tslib.__extends(DeserializationPolicy, _super); - function DeserializationPolicy(nextPolicy, requestPolicyOptions, deserializationContentTypes, parsingOptions) { - if (parsingOptions === void 0) { parsingOptions = {}; } - var _a; - var _this = _super.call(this, nextPolicy, requestPolicyOptions) || this; + function DeserializationPolicy(nextPolicy, deserializationContentTypes, options) { + var _this = _super.call(this, nextPolicy, options) || this; _this.jsonContentTypes = (deserializationContentTypes && deserializationContentTypes.json) || defaultJsonContentTypes; _this.xmlContentTypes = (deserializationContentTypes && deserializationContentTypes.xml) || defaultXmlContentTypes; - _this.xmlCharKey = (_a = parsingOptions.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; return _this; } DeserializationPolicy.prototype.sendRequest = function (request) { return tslib.__awaiter(this, void 0, void 0, function () { var _this = this; return tslib.__generator(this, function (_a) { - return [2 /*return*/, this._nextPolicy.sendRequest(request).then(function (response) { - return deserializeResponseBody(_this.jsonContentTypes, _this.xmlContentTypes, response, { - xmlCharKey: _this.xmlCharKey - }); + return [2 /*return*/, this._nextPolicy + .sendRequest(request) + .then(function (response) { + return deserializeResponseBody(_this.jsonContentTypes, _this.xmlContentTypes, response); })]; }); }); @@ -63895,15 +62409,8 @@ function shouldDeserializeResponse(parsedResponse) { } return result; } -function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options) { - var _a, _b, _c; - if (options === void 0) { options = {}; } - var updatedOptions = { - rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", - includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, - xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY - }; - return parse(jsonContentTypes, xmlContentTypes, response, updatedOptions).then(function (parsedResponse) { +function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response) { + return parse(jsonContentTypes, xmlContentTypes, response).then(function (parsedResponse) { if (!shouldDeserializeResponse(parsedResponse)) { return parsedResponse; } @@ -63912,13 +62419,54 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, op return parsedResponse; } var responseSpec = getOperationResponse(parsedResponse); - var _a = handleErrorResponse(parsedResponse, operationSpec, responseSpec), error = _a.error, shouldReturnResponse = _a.shouldReturnResponse; - if (error) { + var expectedStatusCodes = Object.keys(operationSpec.responses); + var hasNoExpectedStatusCodes = expectedStatusCodes.length === 0 || + (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"); + var isExpectedStatusCode = hasNoExpectedStatusCodes + ? 200 <= parsedResponse.status && parsedResponse.status < 300 + : !!responseSpec; + // There is no operation response spec for current status code. + // So, treat it as an error case and use the default response spec to deserialize the response. + if (!isExpectedStatusCode) { + var defaultResponseSpec = operationSpec.responses.default; + if (!defaultResponseSpec) { + return parsedResponse; + } + var defaultBodyMapper = defaultResponseSpec.bodyMapper; + var defaultHeadersMapper = defaultResponseSpec.headersMapper; + var initialErrorMessage = isStreamOperation(operationSpec) + ? "Unexpected status code: " + parsedResponse.status + : parsedResponse.bodyAsText; + var error = new RestError(initialErrorMessage, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); + try { + // If error response has a body, try to extract error code & message from it + // Then try to deserialize it using default body mapper + if (parsedResponse.parsedBody) { + var parsedBody = parsedResponse.parsedBody; + var internalError = parsedBody.error || parsedBody; + error.code = internalError.code; + if (internalError.message) { + error.message = internalError.message; + } + if (defaultBodyMapper) { + var valueToDeserialize = parsedBody; + if (operationSpec.isXML && defaultBodyMapper.type.name === MapperType.Sequence) { + valueToDeserialize = + typeof parsedBody === "object" ? parsedBody[defaultBodyMapper.xmlElementName] : []; + } + error.response.parsedBody = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody"); + } + } + // If error response has headers, try to deserialize it using default header mapper + if (parsedResponse.headers && defaultHeadersMapper) { + error.response.parsedHeaders = operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders"); + } + } + catch (defaultError) { + error.message = "Error \"" + defaultError.message + "\" occurred in deserializing the responseBody - \"" + parsedResponse.bodyAsText + "\" for the default response."; + } throw error; } - else if (shouldReturnResponse) { - return parsedResponse; - } // An operation response spec does exist for current status code, so // use it to deserialize the response. if (responseSpec) { @@ -63931,10 +62479,10 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, op : []; } try { - parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options); + parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody"); } - catch (innerError) { - var restError = new RestError("Error " + innerError + " occurred in deserializing the responseBody - " + parsedResponse.bodyAsText, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); + catch (error) { + var restError = new RestError("Error " + error + " occurred in deserializing the responseBody - " + parsedResponse.bodyAsText, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); throw restError; } } @@ -63943,91 +62491,20 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, op parsedResponse.parsedBody = response.status >= 200 && response.status < 300; } if (responseSpec.headersMapper) { - parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders", options); + parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders"); } } return parsedResponse; }); } -function isOperationSpecEmpty(operationSpec) { - var expectedStatusCodes = Object.keys(operationSpec.responses); - return (expectedStatusCodes.length === 0 || - (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default")); -} -function handleErrorResponse(parsedResponse, operationSpec, responseSpec) { - var _a; - var isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300; - var isExpectedStatusCode = isOperationSpecEmpty(operationSpec) - ? isSuccessByStatus - : !!responseSpec; - if (isExpectedStatusCode) { - if (responseSpec) { - if (!responseSpec.isError) { - return { error: null, shouldReturnResponse: false }; - } - } - else { - return { error: null, shouldReturnResponse: false }; - } - } - var errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default; - var streaming = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status)) || - parsedResponse.request.streamResponseBody; - var initialErrorMessage = streaming - ? "Unexpected status code: " + parsedResponse.status - : parsedResponse.bodyAsText; - var error = new RestError(initialErrorMessage, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); - // If the item failed but there's no error spec or default spec to deserialize the error, - // we should fail so we just throw the parsed response - if (!errorResponseSpec) { - throw error; - } - var defaultBodyMapper = errorResponseSpec.bodyMapper; - var defaultHeadersMapper = errorResponseSpec.headersMapper; - try { - // If error response has a body, try to deserialize it using default body mapper. - // Then try to extract error code & message from it - if (parsedResponse.parsedBody) { - var parsedBody = parsedResponse.parsedBody; - var parsedError = void 0; - if (defaultBodyMapper) { - var valueToDeserialize = parsedBody; - if (operationSpec.isXML && defaultBodyMapper.type.name === MapperType.Sequence) { - valueToDeserialize = - typeof parsedBody === "object" ? parsedBody[defaultBodyMapper.xmlElementName] : []; - } - parsedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody"); - } - var internalError = parsedBody.error || parsedError || parsedBody; - error.code = internalError.code; - if (internalError.message) { - error.message = internalError.message; - } - if (defaultBodyMapper) { - error.response.parsedBody = parsedError; - } - } - // If error response has headers, try to deserialize it using default header mapper - if (parsedResponse.headers && defaultHeadersMapper) { - error.response.parsedHeaders = operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders"); - } - } - catch (defaultError) { - error.message = "Error \"" + defaultError.message + "\" occurred in deserializing the responseBody - \"" + parsedResponse.bodyAsText + "\" for the default response."; - } - return { error: error, shouldReturnResponse: false }; -} -function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts) { - var _a; +function parse(jsonContentTypes, xmlContentTypes, operationResponse) { var errorHandler = function (err) { var msg = "Error \"" + err + "\" occurred while parsing the response body - " + operationResponse.bodyAsText + "."; var errCode = err.code || RestError.PARSE_ERROR; var e = new RestError(msg, errCode, operationResponse.status, operationResponse.request, operationResponse); return Promise.reject(e); }; - var streaming = ((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) || - operationResponse.request.streamResponseBody; - if (!streaming && operationResponse.bodyAsText) { + if (!operationResponse.request.streamResponseBody && operationResponse.bodyAsText) { var text_1 = operationResponse.bodyAsText; var contentType = operationResponse.headers.get("Content-Type") || ""; var contentComponents = !contentType @@ -64041,7 +62518,7 @@ function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts) { }).catch(errorHandler); } else if (contentComponents.some(function (component) { return xmlContentTypes.indexOf(component) !== -1; })) { - return parseXML(text_1, opts) + return parseXML(text_1) .then(function (body) { operationResponse.parsedBody = body; return operationResponse; @@ -64066,10 +62543,10 @@ function isNumber(n) { * @internal * Determines if the operation should be retried. * - * @param retryLimit - Specifies the max number of retries. - * @param predicate - Initial chekck on whether to retry based on given responses or errors - * @param retryData - The retry data. - * @returns True if the operation qualifies for a retry; false otherwise. + * @param {number} retryLimit Specifies the max number of retries. + * @param {(response?: HttpOperationResponse, error?: RetryError) => boolean} predicate Initial chekck on whether to retry based on given responses or errors + * @param {RetryData} retryData The retry data. + * @return {boolean} True if the operation qualifies for a retry; false otherwise. */ function shouldRetry(retryLimit, predicate, retryData, response, error) { if (!predicate(response, error)) { @@ -64081,9 +62558,9 @@ function shouldRetry(retryLimit, predicate, retryData, response, error) { * @internal * Updates the retry data for the next attempt. * - * @param retryOptions - specifies retry interval, and its lower bound and upper bound. - * @param retryData - The retry data. - * @param err - The operation"s error, if any. + * @param {RetryPolicyOptions} retryOptions specifies retry interval, and its lower bound and upper bound. + * @param {RetryData} [retryData] The retry data. + * @param {RetryError} [err] The operation"s error, if any. */ function updateRetryData(retryOptions, retryData, err) { if (retryData === void 0) { retryData = { retryCount: 0, retryInterval: 0 }; } @@ -64121,17 +62598,19 @@ var DefaultRetryOptions = { maxRetryDelayInMs: DEFAULT_CLIENT_MAX_RETRY_INTERVAL }; /** + * @class * Instantiates a new "ExponentialRetryPolicyFilter" instance. */ var ExponentialRetryPolicy = /** @class */ (function (_super) { tslib.__extends(ExponentialRetryPolicy, _super); /** - * @param nextPolicy - The next RequestPolicy in the pipeline chain. - * @param options - The options for this RequestPolicy. - * @param retryCount - The client retry count. - * @param retryInterval - The client retry interval, in milliseconds. - * @param minRetryInterval - The minimum retry interval, in milliseconds. - * @param maxRetryInterval - The maximum retry interval, in milliseconds. + * @constructor + * @param {RequestPolicy} nextPolicy The next RequestPolicy in the pipeline chain. + * @param {RequestPolicyOptions} options The options for this RequestPolicy. + * @param {number} [retryCount] The client retry count. + * @param {number} [retryInterval] The client retry interval, in milliseconds. + * @param {number} [minRetryInterval] The minimum retry interval, in milliseconds. + * @param {number} [maxRetryInterval] The maximum retry interval, in milliseconds. */ function ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, maxRetryInterval) { var _this = _super.call(this, nextPolicy, options) || this; @@ -64153,8 +62632,8 @@ var ExponentialRetryPolicy = /** @class */ (function (_super) { }(BaseRequestPolicy)); function retry(policy, request, response, retryData, requestError) { return tslib.__awaiter(this, void 0, void 0, function () { - function shouldPolicyRetry(responseParam) { - var statusCode = responseParam === null || responseParam === void 0 ? void 0 : responseParam.status; + function shouldPolicyRetry(response) { + var statusCode = response === null || response === void 0 ? void 0 : response.status; if (statusCode === undefined || (statusCode < 500 && statusCode !== 408) || statusCode === 501 || @@ -64309,10 +62788,6 @@ var UserAgentPolicy = /** @class */ (function (_super) { }(BaseRequestPolicy)); // Copyright (c) Microsoft Corporation. -/** - * Methods that are allowed to follow redirects 301 and 302 - */ -var allowedRedirect = ["GET", "HEAD"]; var DefaultRedirectOptions = { handleRedirects: true, maxRetries: 20 @@ -64345,11 +62820,7 @@ function handleRedirect(policy, response, currentRetries) { var request = response.request, status = response.status; var locationHeader = response.headers.get("location"); if (locationHeader && - (status === 300 || - (status === 301 && allowedRedirect.includes(request.method)) || - (status === 302 && allowedRedirect.includes(request.method)) || - (status === 303 && request.method === "POST") || - status === 307) && + (status === 300 || status === 307 || (status === 303 && request.method === "POST")) && (!policy.maxRetries || currentRetries < policy.maxRetries)) { var builder = URLBuilder.parse(request.url); builder.setPath(locationHeader); @@ -64358,7 +62829,6 @@ function handleRedirect(policy, response, currentRetries) { // redirected GET request if the redirect url is present in the location header if (status === 303) { request.method = "GET"; - delete request.body; } return policy._nextPolicy .sendRequest(request) @@ -64417,9 +62887,9 @@ function registerIfNeeded(policy, request, response) { } /** * Reuses the headers of the original request and url (if specified). - * @param originalRequest - The original request - * @param reuseUrlToo - Should the url from the original request be reused as well. Default false. - * @returns A new request object with desired headers. + * @param {WebResourceLike} originalRequest The original request + * @param {boolean} reuseUrlToo Should the url from the original request be reused as well. Default false. + * @returns {object} A new request object with desired headers. */ function getRequestEssentials(originalRequest, reuseUrlToo) { if (reuseUrlToo === void 0) { reuseUrlToo = false; } @@ -64437,8 +62907,8 @@ function getRequestEssentials(originalRequest, reuseUrlToo) { /** * Validates the error code and message associated with 409 response status code. If it matches to that of * RP not registered then it returns the name of the RP else returns undefined. - * @param body - The response body received after making the original request. - * @returns The name of the RP if condition is satisfied else undefined. + * @param {string} body The response body received after making the original request. + * @returns {string} The name of the RP if condition is satisfied else undefined. */ function checkRPNotRegisteredError(body) { var result, responseBody; @@ -64465,8 +62935,8 @@ function checkRPNotRegisteredError(body) { /** * Extracts the first part of the URL, just after subscription: * https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ - * @param url - The original request url - * @returns The url prefix as explained above. + * @param {string} url The original request url + * @returns {string} The url prefix as explained above. */ function extractSubscriptionUrl(url) { var result; @@ -64481,12 +62951,12 @@ function extractSubscriptionUrl(url) { } /** * Registers the given provider. - * @param policy - The RPRegistrationPolicy this function is being called against. - * @param urlPrefix - https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ - * @param provider - The provider name to be registered. - * @param originalRequest - The original request sent by the user that returned a 409 response + * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against. + * @param {string} urlPrefix https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ + * @param {string} provider The provider name to be registered. + * @param {WebResourceLike} originalRequest The original request sent by the user that returned a 409 response * with a message that the provider is not registered. - * @param callback - The callback that handles the RP registration + * @param {registrationCallback} callback The callback that handles the RP registration */ function registerRP(policy, urlPrefix, provider, originalRequest) { var postUrl = urlPrefix + "providers/" + provider + "/register?api-version=2016-02-01"; @@ -64504,11 +62974,11 @@ function registerRP(policy, urlPrefix, provider, originalRequest) { /** * Polls the registration status of the provider that was registered. Polling happens at an interval of 30 seconds. * Polling will happen till the registrationState property of the response body is "Registered". - * @param policy - The RPRegistrationPolicy this function is being called against. - * @param url - The request url for polling - * @param originalRequest - The original request sent by the user that returned a 409 response + * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against. + * @param {string} url The request url for polling + * @param {WebResourceLike} originalRequest The original request sent by the user that returned a 409 response * with a message that the provider is not registered. - * @returns True if RP Registration is successful. + * @returns {Promise} True if RP Registration is successful. */ function getRegistrationStatus(policy, url, originalRequest) { var reqOptions = getRequestEssentials(originalRequest); @@ -64575,6 +63045,8 @@ var AccessTokenRefresher = /** @class */ (function () { /** * Returns true if the required milliseconds(defaulted to 30000) have been passed signifying * that we are ready for a new refresh. + * + * @returns {boolean} */ AccessTokenRefresher.prototype.isReady = function () { // We're only ready for a new refresh if the required milliseconds have passed. @@ -64585,6 +63057,7 @@ var AccessTokenRefresher = /** @class */ (function () { * then requests a new token, * then sets this.promise to undefined, * then returns the token. + * @param options getToken options */ AccessTokenRefresher.prototype.getToken = function (options) { return tslib.__awaiter(this, void 0, void 0, function () { @@ -64605,6 +63078,7 @@ var AccessTokenRefresher = /** @class */ (function () { /** * Requests a new token if we're not currently waiting for a new token. * Returns null if the required time between each call hasn't been reached. + * @param options getToken options */ AccessTokenRefresher.prototype.refresh = function (options) { if (!this.promise) { @@ -64616,17 +63090,11 @@ var AccessTokenRefresher = /** @class */ (function () { }()); // Copyright (c) Microsoft Corporation. -/** - * The automated token refresh will only start to happen at the - * expiration date minus the value of timeBetweenRefreshAttemptsInMs, - * which is by default 30 seconds. - */ -var timeBetweenRefreshAttemptsInMs = 30000; /** * Creates a new BearerTokenAuthenticationPolicy factory. * - * @param credential - The TokenCredential implementation that can supply the bearer token. - * @param scopes - The scopes for which the bearer token applies. + * @param credential The TokenCredential implementation that can supply the bearer token. + * @param scopes The scopes for which the bearer token applies. */ function bearerTokenAuthenticationPolicy(credential, scopes) { var tokenCache = new ExpiringAccessTokenCache(); @@ -64637,6 +63105,12 @@ function bearerTokenAuthenticationPolicy(credential, scopes) { } }; } +/** + * The automated token refresh will only start to happen at the + * expiration date minus the value of timeBetweenRefreshAttemptsInMs, + * which is by default 30 seconds. + */ +var timeBetweenRefreshAttemptsInMs = 30000; /** * * Provides a RequestPolicy that can request a token from a TokenCredential @@ -64649,11 +63123,11 @@ var BearerTokenAuthenticationPolicy = /** @class */ (function (_super) { /** * Creates a new BearerTokenAuthenticationPolicy object. * - * @param nextPolicy - The next RequestPolicy in the request pipeline. - * @param options - Options for this RequestPolicy. - * @param credential - The TokenCredential implementation that can supply the bearer token. - * @param scopes - The scopes for which the bearer token applies. - * @param tokenCache - The cache for the most recent AccessToken returned from the TokenCredential. + * @param nextPolicy The next RequestPolicy in the request pipeline. + * @param options Options for this RequestPolicy. + * @param credential The TokenCredential implementation that can supply the bearer token. + * @param scopes The scopes for which the bearer token applies. + * @param tokenCache The cache for the most recent AccessToken returned from the TokenCredential. */ function BearerTokenAuthenticationPolicy(nextPolicy, options, tokenCache, tokenRefresher) { var _this = _super.call(this, nextPolicy, options) || this; @@ -64663,6 +63137,7 @@ var BearerTokenAuthenticationPolicy = /** @class */ (function (_super) { } /** * Applies the Bearer token to the request through the Authorization header. + * @param webResource */ BearerTokenAuthenticationPolicy.prototype.sendRequest = function (webResource) { return tslib.__awaiter(this, void 0, void 0, function () { @@ -64744,10 +63219,14 @@ function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, max }; } /** - * @param retryCount - The client retry count. - * @param retryInterval - The client retry interval, in milliseconds. - * @param minRetryInterval - The minimum retry interval, in milliseconds. - * @param maxRetryInterval - The maximum retry interval, in milliseconds. + * @class + * Instantiates a new "ExponentialRetryPolicyFilter" instance. + * + * @constructor + * @param {number} retryCount The client retry count. + * @param {number} retryInterval The client retry interval, in milliseconds. + * @param {number} minRetryInterval The minimum retry interval, in milliseconds. + * @param {number} maxRetryInterval The maximum retry interval, in milliseconds. */ var SystemErrorRetryPolicy = /** @class */ (function (_super) { tslib.__extends(SystemErrorRetryPolicy, _super); @@ -64785,7 +63264,7 @@ function retry$1(policy, request, operationResponse, err, retryData) { } return false; } - var nestedErr_1; + var err_1; return tslib.__generator(this, function (_a) { switch (_a.label) { case 0: @@ -64799,8 +63278,8 @@ function retry$1(policy, request, operationResponse, err, retryData) { _a.sent(); return [2 /*return*/, policy._nextPolicy.sendRequest(request.clone())]; case 3: - nestedErr_1 = _a.sent(); - return [2 /*return*/, retry$1(policy, request, operationResponse, nestedErr_1, retryData)]; + err_1 = _a.sent(); + return [2 /*return*/, retry$1(policy, request, operationResponse, err_1, retryData)]; case 4: return [3 /*break*/, 6]; case 5: if (err) { @@ -64824,10 +63303,8 @@ function retry$1(policy, request, operationResponse, err, retryData) { })(exports.QueryCollectionFormat || (exports.QueryCollectionFormat = {})); // Copyright (c) Microsoft Corporation. -/** - * @internal - */ -var noProxyList = loadNoProxy(); +var noProxyList = []; +var isNoProxyInitalized = false; var byPassedList = new Map(); function loadEnvironmentProxyValue() { if (!process) { @@ -64838,53 +63315,45 @@ function loadEnvironmentProxyValue() { var httpProxy = getEnvironmentValue(Constants.HTTP_PROXY); return httpsProxy || allProxy || httpProxy; } -// Check whether the host of a given `uri` is in the noProxyList. -// If there's a match, any request sent to the same host won't have the proxy settings set. -// This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210 +// Check whether the given `uri` matches the noProxyList. If it matches, any request sent to that same `uri` won't set the proxy settings. function isBypassed(uri) { - if (noProxyList.length === 0) { - return false; + if (byPassedList.has(uri)) { + return byPassedList.get(uri); } + loadNoProxy(); + var isBypassed = false; var host = URLBuilder.parse(uri).getHost(); - if (byPassedList.has(host)) { - return byPassedList.get(host); - } - var isBypassedFlag = false; for (var _i = 0, noProxyList_1 = noProxyList; _i < noProxyList_1.length; _i++) { - var pattern = noProxyList_1[_i]; - if (pattern[0] === ".") { - // This should match either domain it self or any subdomain or host - // .foo.com will match foo.com it self or *.foo.com - if (host.endsWith(pattern)) { - isBypassedFlag = true; + var proxyString = noProxyList_1[_i]; + if (proxyString[0] === ".") { + if (uri.endsWith(proxyString)) { + isBypassed = true; } else { - if (host.length === pattern.length - 1 && host === pattern.slice(1)) { - isBypassedFlag = true; + if (host === proxyString.slice(1) && host.length === proxyString.length - 1) { + isBypassed = true; } } } else { - if (host === pattern) { - isBypassedFlag = true; + if (host === proxyString) { + isBypassed = true; } } } - byPassedList.set(host, isBypassedFlag); - return isBypassedFlag; + byPassedList.set(uri, isBypassed); + return isBypassed; } -/** - * @internal - */ function loadNoProxy() { + if (isNoProxyInitalized) { + return; + } var noProxy = getEnvironmentValue(Constants.NO_PROXY); if (noProxy) { - return noProxy - .split(",") - .map(function (item) { return item.trim(); }) - .filter(function (item) { return item.length; }); + var list = noProxy.split(","); + noProxyList = list.map(function (item) { return item.trim(); }).filter(function (item) { return item.length; }); } - return []; + isNoProxyInitalized = true; } function getDefaultProxySettings(proxyUrl) { if (!proxyUrl) { @@ -65070,9 +63539,9 @@ var KeepAlivePolicy = /** @class */ (function (_super) { /** * Creates an instance of KeepAlivePolicy. * - * @param nextPolicy - - * @param options - - * @param keepAliveOptions - + * @param {RequestPolicy} nextPolicy + * @param {RequestPolicyOptions} options + * @param {KeepAliveOptions} [keepAliveOptions] */ function KeepAlivePolicy(nextPolicy, options, keepAliveOptions) { var _this = _super.call(this, nextPolicy, options) || this; @@ -65082,8 +63551,9 @@ var KeepAlivePolicy = /** @class */ (function (_super) { /** * Sends out request. * - * @param request - - * @returns + * @param {WebResourceLike} request + * @returns {Promise} + * @memberof KeepAlivePolicy */ KeepAlivePolicy.prototype.sendRequest = function (request) { return tslib.__awaiter(this, void 0, void 0, function () { @@ -65189,8 +63659,8 @@ var DisableResponseDecompressionPolicy = /** @class */ (function (_super) { /** * Creates an instance of DisableResponseDecompressionPolicy. * - * @param nextPolicy - - * @param options - + * @param {RequestPolicy} nextPolicy + * @param {RequestPolicyOptions} options */ // The parent constructor is protected. /* eslint-disable-next-line @typescript-eslint/no-useless-constructor */ @@ -65200,8 +63670,8 @@ var DisableResponseDecompressionPolicy = /** @class */ (function (_super) { /** * Sends out request. * - * @param request - - * @returns + * @param {WebResource} request + * @returns {Promise} */ DisableResponseDecompressionPolicy.prototype.sendRequest = function (request) { return tslib.__awaiter(this, void 0, void 0, function () { @@ -65229,12 +63699,17 @@ var NdJsonPolicy = /** @class */ (function (_super) { tslib.__extends(NdJsonPolicy, _super); /** * Creates an instance of KeepAlivePolicy. + * + * @param nextPolicy + * @param options */ function NdJsonPolicy(nextPolicy, options) { return _super.call(this, nextPolicy, options) || this; } /** * Sends a request. + * + * @param request */ NdJsonPolicy.prototype.sendRequest = function (request) { return tslib.__awaiter(this, void 0, void 0, function () { @@ -65254,24 +63729,17 @@ var NdJsonPolicy = /** @class */ (function (_super) { return NdJsonPolicy; }(BaseRequestPolicy)); -// Copyright (c) Microsoft Corporation. -var cachedHttpClient; -function getCachedDefaultHttpClient() { - if (!cachedHttpClient) { - cachedHttpClient = new NodeFetchHttpClient(); - } - return cachedHttpClient; -} - // Copyright (c) Microsoft Corporation. /** - * ServiceClient sends service requests and receives responses. + * @class + * Initializes a new instance of the ServiceClient. */ var ServiceClient = /** @class */ (function () { /** * The ServiceClient constructor - * @param credentials - The credentials used for authentication with the service. - * @param options - The service client options that govern the behavior of the client. + * @constructor + * @param credentials The credentials used for authentication with the service. + * @param options The service client options that govern the behavior of the client. */ function ServiceClient(credentials, /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options */ @@ -65281,7 +63749,7 @@ var ServiceClient = /** @class */ (function () { options = {}; } this._withCredentials = options.withCredentials || false; - this._httpClient = options.httpClient || getCachedDefaultHttpClient(); + this._httpClient = options.httpClient || new NodeFetchHttpClient(); this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger); var requestPolicyFactories; if (Array.isArray(options.requestPolicyFactories)) { @@ -65302,17 +63770,12 @@ var ServiceClient = /** @class */ (function () { var bearerTokenPolicyFactory = undefined; // eslint-disable-next-line @typescript-eslint/no-this-alias var serviceClient = _this; - var serviceClientOptions = options; return { - create: function (nextPolicy, createOptions) { - var credentialScopes = getCredentialScopes(serviceClientOptions, serviceClient.baseUri); - if (!credentialScopes) { - throw new Error("When using credential, the ServiceClient must contain a baseUri or a credentialScopes in ServiceClientOptions. Unable to create a bearerTokenAuthenticationPolicy"); - } + create: function (nextPolicy, options) { if (bearerTokenPolicyFactory === undefined || bearerTokenPolicyFactory === null) { - bearerTokenPolicyFactory = bearerTokenAuthenticationPolicy(credentials, credentialScopes); + bearerTokenPolicyFactory = bearerTokenAuthenticationPolicy(credentials, (serviceClient.baseUri || "") + "/.default"); } - return bearerTokenPolicyFactory.create(nextPolicy, createOptions); + return bearerTokenPolicyFactory.create(nextPolicy, options); } }; }; @@ -65369,26 +63832,24 @@ var ServiceClient = /** @class */ (function () { }; /** * Send an HTTP request that is populated using the provided OperationSpec. - * @param operationArguments - The arguments that the HTTP request's templated values will be populated from. - * @param operationSpec - The OperationSpec to use to populate the httpRequest. - * @param callback - The callback to call when the response is received. + * @param {OperationArguments} operationArguments The arguments that the HTTP request's templated values will be populated from. + * @param {OperationSpec} operationSpec The OperationSpec to use to populate the httpRequest. + * @param {ServiceCallback} callback The callback to call when the response is received. */ ServiceClient.prototype.sendOperationRequest = function (operationArguments, operationSpec, callback) { - var _a; return tslib.__awaiter(this, void 0, void 0, function () { - var serializerOptions, httpRequest, result, baseUri, requestUrl, _i, _b, urlParameter, urlParameterValue, _c, _d, queryParameter, queryParameterValue, index, item, index, contentType, _e, _f, headerParameter, headerValue, headerCollectionPrefix, _g, _h, key, options, customHeaderName, rawResponse, sendRequestError, error_1, error_2, cb; - return tslib.__generator(this, function (_j) { - switch (_j.label) { + var httpRequest, result, baseUri, requestUrl, _i, _a, urlParameter, urlParameterValue, _b, _c, queryParameter, queryParameterValue, index, item, index, contentType, _d, _e, headerParameter, headerValue, headerCollectionPrefix, _f, _g, key, options, customHeaderName, rawResponse, sendRequestError, error_1, error_2, cb; + return tslib.__generator(this, function (_h) { + switch (_h.label) { case 0: if (typeof operationArguments.options === "function") { callback = operationArguments.options; operationArguments.options = undefined; } - serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; httpRequest = new WebResource(); - _j.label = 1; + _h.label = 1; case 1: - _j.trys.push([1, 6, , 7]); + _h.trys.push([1, 6, , 7]); baseUri = operationSpec.baseUrl || this.baseUri; if (!baseUri) { throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a baseUri string property that contains the base URL to use."); @@ -65400,10 +63861,10 @@ var ServiceClient = /** @class */ (function () { requestUrl.appendPath(operationSpec.path); } if (operationSpec.urlParameters && operationSpec.urlParameters.length > 0) { - for (_i = 0, _b = operationSpec.urlParameters; _i < _b.length; _i++) { - urlParameter = _b[_i]; + for (_i = 0, _a = operationSpec.urlParameters; _i < _a.length; _i++) { + urlParameter = _a[_i]; urlParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, urlParameter, operationSpec.serializer); - urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, getPathStringFromParameter(urlParameter), serializerOptions); + urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, getPathStringFromParameter(urlParameter)); if (!urlParameter.skipEncoding) { urlParameterValue = encodeURIComponent(urlParameterValue); } @@ -65411,17 +63872,16 @@ var ServiceClient = /** @class */ (function () { } } if (operationSpec.queryParameters && operationSpec.queryParameters.length > 0) { - for (_c = 0, _d = operationSpec.queryParameters; _c < _d.length; _c++) { - queryParameter = _d[_c]; + for (_b = 0, _c = operationSpec.queryParameters; _b < _c.length; _b++) { + queryParameter = _c[_b]; queryParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, queryParameter, operationSpec.serializer); if (queryParameterValue !== undefined && queryParameterValue !== null) { - queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter), serializerOptions); + queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter)); if (queryParameter.collectionFormat !== undefined && queryParameter.collectionFormat !== null) { if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Multi) { if (queryParameterValue.length === 0) { - // The collection is empty, no need to try serializing the current queryParam - continue; + queryParameterValue = ""; } else { for (index in queryParameterValue) { @@ -65462,20 +63922,20 @@ var ServiceClient = /** @class */ (function () { } httpRequest.url = requestUrl.toString(); contentType = operationSpec.contentType || this.requestContentType; - if (contentType && operationSpec.requestBody) { + if (contentType) { httpRequest.headers.set("Content-Type", contentType); } if (operationSpec.headerParameters) { - for (_e = 0, _f = operationSpec.headerParameters; _e < _f.length; _e++) { - headerParameter = _f[_e]; + for (_d = 0, _e = operationSpec.headerParameters; _d < _e.length; _d++) { + headerParameter = _e[_d]; headerValue = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer); if (headerValue !== undefined && headerValue !== null) { - headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter), serializerOptions); + headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter)); headerCollectionPrefix = headerParameter.mapper .headerCollectionPrefix; if (headerCollectionPrefix) { - for (_g = 0, _h = Object.keys(headerValue); _g < _h.length; _g++) { - key = _h[_g]; + for (_f = 0, _g = Object.keys(headerValue); _f < _g.length; _f++) { + key = _g[_f]; httpRequest.headers.set(headerCollectionPrefix + key, headerValue[key]); } } @@ -65514,20 +63974,20 @@ var ServiceClient = /** @class */ (function () { } httpRequest.withCredentials = this._withCredentials; serializeRequestBody(this, httpRequest, operationArguments, operationSpec); - if (httpRequest.streamResponseStatusCodes === undefined) { - httpRequest.streamResponseStatusCodes = getStreamResponseStatusCodes(operationSpec); + if (httpRequest.streamResponseBody === undefined || httpRequest.streamResponseBody === null) { + httpRequest.streamResponseBody = isStreamOperation(operationSpec); } rawResponse = void 0; sendRequestError = void 0; - _j.label = 2; + _h.label = 2; case 2: - _j.trys.push([2, 4, , 5]); + _h.trys.push([2, 4, , 5]); return [4 /*yield*/, this.sendRequest(httpRequest)]; case 3: - rawResponse = _j.sent(); + rawResponse = _h.sent(); return [3 /*break*/, 5]; case 4: - error_1 = _j.sent(); + error_1 = _h.sent(); sendRequestError = error_1; return [3 /*break*/, 5]; case 5: @@ -65543,13 +64003,14 @@ var ServiceClient = /** @class */ (function () { } return [3 /*break*/, 7]; case 6: - error_2 = _j.sent(); + error_2 = _h.sent(); result = Promise.reject(error_2); return [3 /*break*/, 7]; case 7: cb = callback; if (cb) { result + // tslint:disable-next-line:no-null-keyword .then(function (res) { return cb(null, res._response.parsedBody, res._response.request, res._response); }) .catch(function (err) { return cb(err); }); } @@ -65561,14 +64022,7 @@ var ServiceClient = /** @class */ (function () { return ServiceClient; }()); function serializeRequestBody(serviceClient, httpRequest, operationArguments, operationSpec) { - var _a, _b, _c, _d, _e, _f; - var serializerOptions = (_b = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions) !== null && _b !== void 0 ? _b : {}; - var updatedOptions = { - rootName: (_c = serializerOptions.rootName) !== null && _c !== void 0 ? _c : "", - includeRoot: (_d = serializerOptions.includeRoot) !== null && _d !== void 0 ? _d : false, - xmlCharKey: (_e = serializerOptions.xmlCharKey) !== null && _e !== void 0 ? _e : XML_CHARKEY - }; - var xmlCharKey = serializerOptions.xmlCharKey; + var _a; if (operationSpec.requestBody && operationSpec.requestBody.mapper) { httpRequest.body = getOperationArgumentValueFromParameter(serviceClient, operationArguments, operationSpec.requestBody, operationSpec.serializer); var bodyMapper = operationSpec.requestBody.mapper; @@ -65577,26 +64031,22 @@ function serializeRequestBody(serviceClient, httpRequest, operationArguments, op try { if ((httpRequest.body !== undefined && httpRequest.body !== null) || required) { var requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody); - httpRequest.body = operationSpec.serializer.serialize(bodyMapper, httpRequest.body, requestBodyParameterPathString, updatedOptions); + httpRequest.body = operationSpec.serializer.serialize(bodyMapper, httpRequest.body, requestBodyParameterPathString); var isStream = typeName === MapperType.Stream; if (operationSpec.isXML) { var xmlnsKey = xmlNamespacePrefix ? "xmlns:" + xmlNamespacePrefix : "xmlns"; - var value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, httpRequest.body, updatedOptions); + var value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, httpRequest.body); if (typeName === MapperType.Sequence) { - httpRequest.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { - rootName: xmlName || serializedName, - xmlCharKey: xmlCharKey - }); + httpRequest.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName }); } else if (!isStream) { httpRequest.body = stringifyXML(value, { - rootName: xmlName || serializedName, - xmlCharKey: xmlCharKey + rootName: xmlName || serializedName }); } } else if (typeName === MapperType.String && - (((_f = operationSpec.contentType) === null || _f === void 0 ? void 0 : _f.match("text/plain")) || operationSpec.mediaType === "text")) { + (((_a = operationSpec.contentType) === null || _a === void 0 ? void 0 : _a.match("text/plain")) || operationSpec.mediaType === "text")) { // the String serializer has validated that request body is a string // so just send the string. return; @@ -65612,12 +64062,12 @@ function serializeRequestBody(serviceClient, httpRequest, operationArguments, op } else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) { httpRequest.formData = {}; - for (var _i = 0, _g = operationSpec.formDataParameters; _i < _g.length; _i++) { - var formDataParameter = _g[_i]; + for (var _i = 0, _b = operationSpec.formDataParameters; _i < _b.length; _i++) { + var formDataParameter = _b[_i]; var formDataParameterValue = getOperationArgumentValueFromParameter(serviceClient, operationArguments, formDataParameter, operationSpec.serializer); if (formDataParameterValue !== undefined && formDataParameterValue !== null) { var formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter); - httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter), updatedOptions); + httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter)); } } } @@ -65625,15 +64075,12 @@ function serializeRequestBody(serviceClient, httpRequest, operationArguments, op /** * Adds an xml namespace to the xml serialized object if needed, otherwise it just returns the value itself */ -function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue, options) { +function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue) { var _a; // Composite and Sequence schemas already got their root namespace set during serialization // We just need to add xmlns to the other schema types if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) { - var result = {}; - result[options.xmlCharKey] = serializedValue; - result[XML_ATTRKEY] = (_a = {}, _a[xmlnsKey] = xmlNamespace, _a); - return result; + return { _: serializedValue, $: (_a = {}, _a[xmlnsKey] = xmlNamespace, _a) }; } return serializedValue; } @@ -65722,12 +64169,10 @@ function getOperationArgumentValueFromParameter(serviceClient, operationArgument return getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameter.parameterPath, parameter.mapper, serializer); } function getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, serializer) { - var _a; var value; if (typeof parameterPath === "string") { parameterPath = [parameterPath]; } - var serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; if (Array.isArray(parameterPath)) { if (parameterPath.length > 0) { if (parameterMapper.isConstant) { @@ -65748,7 +64193,7 @@ function getOperationArgumentValueFromParameterPath(serviceClient, operationArgu } // Serialize just for validation purposes. var parameterPathString = getPathStringFromParameterPath(parameterPath, parameterMapper); - serializer.serialize(parameterMapper, value, parameterPathString, serializerOptions); + serializer.serialize(parameterMapper, value, parameterPathString); } } else { @@ -65761,7 +64206,7 @@ function getOperationArgumentValueFromParameterPath(serviceClient, operationArgu var propertyValue = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, propertyPath, propertyMapper, serializer); // Serialize just for validation purposes. var propertyPathString = getPathStringFromParameterPath(propertyPath, propertyMapper); - serializer.serialize(propertyMapper, propertyValue, propertyPathString, serializerOptions); + serializer.serialize(propertyMapper, propertyValue, propertyPathString); if (propertyValue !== undefined && propertyValue !== null) { if (!value) { value = {}; @@ -65835,46 +64280,6 @@ function flattenResponse(_response, responseSpec) { } return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), _response.parsedBody)); } -function getCredentialScopes(options, baseUri) { - if (options === null || options === void 0 ? void 0 : options.credentialScopes) { - var scopes = options.credentialScopes; - return Array.isArray(scopes) - ? scopes.map(function (scope) { return new url.URL(scope).toString(); }) - : new url.URL(scopes).toString(); - } - if (baseUri) { - return baseUri + "/.default"; - } - return undefined; -} - -// Copyright (c) Microsoft Corporation. -/** - * Creates a function called createSpan to create spans using the global tracer. - * @hidden - * @param spanConfig - The name of the operation being performed. - * @param tracingOptions - The options for the underlying http request. - */ -function createSpanFunction(_a) { - var packagePrefix = _a.packagePrefix, namespace = _a.namespace; - return function (operationName, operationOptions) { - var tracer = coreTracing.getTracer(); - var tracingOptions = operationOptions.tracingOptions || {}; - var spanOptions = tslib.__assign(tslib.__assign({}, tracingOptions.spanOptions), { kind: api.SpanKind.INTERNAL }); - var span = tracer.startSpan(packagePrefix + "." + operationName, spanOptions); - span.setAttribute("az.namespace", namespace); - var newSpanOptions = tracingOptions.spanOptions || {}; - if (span.isRecording()) { - newSpanOptions = tslib.__assign(tslib.__assign({}, tracingOptions.spanOptions), { parent: span.context(), attributes: tslib.__assign(tslib.__assign({}, spanOptions.attributes), { "az.namespace": namespace }) }); - } - var newTracingOptions = tslib.__assign(tslib.__assign({}, tracingOptions), { spanOptions: newSpanOptions }); - var newOperationOptions = tslib.__assign(tslib.__assign({}, operationOptions), { tracingOptions: newTracingOptions }); - return { - span: span, - updatedOptions: newOperationOptions - }; - }; -} // Copyright (c) Microsoft Corporation. var HeaderConstants = Constants.HeaderConstants; @@ -65883,9 +64288,10 @@ var BasicAuthenticationCredentials = /** @class */ (function () { /** * Creates a new BasicAuthenticationCredentials object. * - * @param userName - User name. - * @param password - Password. - * @param authorizationScheme - The authorization scheme. + * @constructor + * @param {string} userName User name. + * @param {string} password Password. + * @param {string} [authorizationScheme] The authorization scheme. */ function BasicAuthenticationCredentials(userName, password, authorizationScheme) { if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME; } @@ -65903,8 +64309,8 @@ var BasicAuthenticationCredentials = /** @class */ (function () { /** * Signs a request with the Authentication header. * - * @param webResource - The WebResourceLike to be signed. - * @returns The signed request object. + * @param {WebResourceLike} webResource The WebResourceLike to be signed. + * @returns {Promise} The signed request object. */ BasicAuthenticationCredentials.prototype.signRequest = function (webResource) { var credentials = this.userName + ":" + this.password; @@ -65923,7 +64329,8 @@ var BasicAuthenticationCredentials = /** @class */ (function () { */ var ApiKeyCredentials = /** @class */ (function () { /** - * @param options - Specifies the options to be provided for auth. Either header or query needs to be provided. + * @constructor + * @param {object} options Specifies the options to be provided for auth. Either header or query needs to be provided. */ function ApiKeyCredentials(options) { if (!options || (options && !options.inHeader && !options.inQuery)) { @@ -65935,8 +64342,8 @@ var ApiKeyCredentials = /** @class */ (function () { /** * Signs a request with the values provided in the inHeader and inQuery parameter. * - * @param webResource - The WebResourceLike to be signed. - * @returns The signed request object. + * @param {WebResourceLike} webResource The WebResourceLike to be signed. + * @returns {Promise} The signed request object. */ ApiKeyCredentials.prototype.signRequest = function (webResource) { if (!webResource) { @@ -65975,7 +64382,8 @@ var TopicCredentials = /** @class */ (function (_super) { /** * Creates a new EventGrid TopicCredentials object. * - * @param topicKey - The EventGrid topic key + * @constructor + * @param {string} topicKey The EventGrid topic key */ function TopicCredentials(topicKey) { var _this = this; @@ -66016,12 +64424,9 @@ exports.TopicCredentials = TopicCredentials; exports.URLBuilder = URLBuilder; exports.URLQuery = URLQuery; exports.WebResource = WebResource; -exports.XML_ATTRKEY = XML_ATTRKEY; -exports.XML_CHARKEY = XML_CHARKEY; exports.applyMixins = applyMixins; exports.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy; exports.createPipelineFromOptions = createPipelineFromOptions; -exports.createSpanFunction = createSpanFunction; exports.delay = delay; exports.deserializationPolicy = deserializationPolicy; exports.deserializeResponseBody = deserializeResponseBody; diff --git a/dist/run/index.js b/dist/run/index.js index f9bfacd67c..f4e2e84e78 100644 --- a/dist/run/index.js +++ b/dist/run/index.js @@ -1483,9 +1483,7 @@ function resolvePaths(patterns) { try { for (var _c = __asyncValues(globber.globGenerator()), _d; _d = yield _c.next(), !_d.done;) { const file = _d.value; - const relativeFile = path - .relative(workspace, file) - .replace(new RegExp(`\\${path.sep}`, 'g'), '/'); + const relativeFile = path.relative(workspace, file); core.debug(`Matched: ${relativeFile}`); // Paths are made relative so the tar entries are all relative to the root of the workspace. paths.push(`${relativeFile}`); @@ -2602,7 +2600,9 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.findLintVersion = exports.stringifyVersion = void 0; const core = __importStar(__webpack_require__(470)); const httpm = __importStar(__webpack_require__(539)); +const fs = __importStar(__webpack_require__(747)); const versionRe = /^v(\d+)\.(\d+)(?:\.(\d+))?$/; +const modVersionRe = /github.com\/golangci\/golangci-lint\sv(.+)/; const parseVersion = (s) => { if (s == "latest" || s == "") { return null; @@ -2617,13 +2617,12 @@ const parseVersion = (s) => { patch: match[3] === undefined ? null : parseInt(match[3]), }; }; -const stringifyVersion = (v) => { +exports.stringifyVersion = (v) => { if (v == null) { return "latest"; } return `v${v.major}.${v.minor}${v.patch !== null ? `.${v.patch}` : ``}`; }; -exports.stringifyVersion = stringifyVersion; const minVersion = { major: 1, minor: 28, @@ -2644,7 +2643,15 @@ const isLessVersion = (a, b) => { return a.minor < b.minor; }; const getRequestedLintVersion = () => { - const requestedLintVersion = core.getInput(`version`); + let requestedLintVersion = core.getInput(`version`); + if (requestedLintVersion == "") { + const content = fs.readFileSync("go.mod", "utf-8"); + const match = content.match(modVersionRe); + if (match) { + requestedLintVersion = match[1]; + core.info(`Found golangci-lint version '${requestedLintVersion}' in go.mod`); + } + } const parsedRequestedLintVersion = parseVersion(requestedLintVersion); if (parsedRequestedLintVersion == null) { return null; @@ -2707,49 +2714,7 @@ exports.findLintVersion = findLintVersion; /***/ }), -/* 53 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -/*! - * Copyright 2019, OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -const context_1 = __webpack_require__(560); -class NoopContextManager { - active() { - return context_1.Context.ROOT_CONTEXT; - } - with(context, fn) { - return fn(); - } - bind(target, context) { - return target; - } - enable() { - return this; - } - disable() { - return this; - } -} -exports.NoopContextManager = NoopContextManager; -//# sourceMappingURL=NoopContextManager.js.map - -/***/ }), +/* 53 */, /* 54 */, /* 55 */, /* 56 */, @@ -4149,7 +4114,7 @@ module.exports = bytesToUuid; Object.defineProperty(exports, '__esModule', { value: true }); -var tslib = __webpack_require__(640); +var tslib = __webpack_require__(422); var listenersMap = new WeakMap(); var abortedMap = new WeakMap(); @@ -4591,12 +4556,9 @@ function uploadChunk(httpClient, resourceUrl, openStream, start, end) { 'Content-Type': 'application/octet-stream', 'Content-Range': getContentRange(start, end) }; - const uploadChunkResponse = yield requestUtils_1.retryHttpClientResponse(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter(this, void 0, void 0, function* () { + yield requestUtils_1.retryHttpClientResponse(`uploadChunk (start: ${start}, end: ${end})`, () => __awaiter(this, void 0, void 0, function* () { return httpClient.sendStream('PATCH', resourceUrl, openStream(), additionalHeaders); })); - if (!requestUtils_1.isSuccessStatusCode(uploadChunkResponse.message.statusCode)) { - throw new Error(`Cache service responded with ${uploadChunkResponse.message.statusCode} during upload chunk.`); - } }); } function uploadFile(httpClient, cacheId, archivePath, options) { @@ -4653,7 +4615,6 @@ function saveCache(cacheId, archivePath, options) { // Commit Cache core.debug('Commiting cache'); const cacheSize = utils.getArchiveFileSizeIsBytes(archivePath); - core.info(`Cache Size: ~${Math.round(cacheSize / (1024 * 1024))} MB (${cacheSize} B)`); const commitCacheResponse = yield commitCache(httpClient, cacheId, cacheSize); if (!requestUtils_1.isSuccessStatusCode(commitCacheResponse.statusCode)) { throw new Error(`Cache service responded with ${commitCacheResponse.statusCode} during commit cache.`); @@ -7521,7 +7482,43 @@ exports.isTokenCredential = isTokenCredential; /***/ }), /* 230 */, -/* 231 */, +/* 231 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +__exportStar(__webpack_require__(328), exports); +__exportStar(__webpack_require__(715), exports); +__exportStar(__webpack_require__(924), exports); +//# sourceMappingURL=index.js.map + +/***/ }), /* 232 */, /* 233 */, /* 234 */, @@ -10088,19 +10085,12 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } }; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; Object.defineProperty(exports, "__esModule", { value: true }); -const core = __importStar(__webpack_require__(470)); -const fs = __importStar(__webpack_require__(747)); -const globOptionsHelper = __importStar(__webpack_require__(601)); -const path = __importStar(__webpack_require__(622)); -const patternHelper = __importStar(__webpack_require__(597)); +const core = __webpack_require__(470); +const fs = __webpack_require__(747); +const globOptionsHelper = __webpack_require__(601); +const path = __webpack_require__(622); +const patternHelper = __webpack_require__(597); const internal_match_kind_1 = __webpack_require__(327); const internal_pattern_1 = __webpack_require__(923); const internal_search_state_1 = __webpack_require__(728); @@ -10899,7 +10889,30 @@ var MatchKind; //# sourceMappingURL=internal-match-kind.js.map /***/ }), -/* 328 */, +/* 328 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map + +/***/ }), /* 329 */, /* 330 */, /* 331 */, @@ -11567,13 +11580,6 @@ var StorageError = { type: { name: "String" } - }, - code: { - xmlName: "Code", - serializedName: "Code", - type: { - name: "String" - } } } } @@ -11934,13 +11940,6 @@ var BlobPropertiesInternal = { type: { name: "String" } - }, - lastAccessedOn: { - xmlName: "LastAccessTime", - serializedName: "LastAccessTime", - type: { - name: "DateTimeRfc1123" - } } } } @@ -12646,70 +12645,6 @@ var JsonTextConfiguration = { } } }; -var ArrowField = { - xmlName: "Field", - serializedName: "ArrowField", - type: { - name: "Composite", - className: "ArrowField", - modelProperties: { - type: { - xmlName: "Type", - required: true, - serializedName: "Type", - type: { - name: "String" - } - }, - name: { - xmlName: "Name", - serializedName: "Name", - type: { - name: "String" - } - }, - precision: { - xmlName: "Precision", - serializedName: "Precision", - type: { - name: "Number" - } - }, - scale: { - xmlName: "Scale", - serializedName: "Scale", - type: { - name: "Number" - } - } - } - } -}; -var ArrowConfiguration = { - serializedName: "ArrowConfiguration", - type: { - name: "Composite", - className: "ArrowConfiguration", - modelProperties: { - schema: { - xmlIsWrapped: true, - xmlName: "Schema", - xmlElementName: "Field", - required: true, - serializedName: "Schema", - type: { - name: "Sequence", - element: { - type: { - name: "Composite", - className: "ArrowField" - } - } - } - } - } - } -}; var ListContainersSegmentResponse = { xmlName: "EnumerationResults", serializedName: "ListContainersSegmentResponse", @@ -12848,12 +12783,12 @@ var FilterBlobItem = { name: "String" } }, - tags: { - xmlName: "Tags", - serializedName: "Tags", + tagValue: { + xmlName: "TagValue", + required: true, + serializedName: "TagValue", type: { - name: "Composite", - className: "BlobTags" + name: "String" } } } @@ -13150,8 +13085,7 @@ var QueryFormat = { name: "Enum", allowedValues: [ "delimited", - "json", - "arrow" + "json" ] } }, @@ -13170,14 +13104,6 @@ var QueryFormat = { name: "Composite", className: "JsonTextConfiguration" } - }, - arrowConfiguration: { - xmlName: "ArrowConfiguration", - serializedName: "ArrowConfiguration", - type: { - name: "Composite", - className: "ArrowConfiguration" - } } } } @@ -13630,12 +13556,6 @@ var ServiceGetAccountInfoHeaders = { ] } }, - isHierarchicalNamespaceEnabled: { - serializedName: "x-ms-is-hns-enabled", - type: { - name: "Boolean" - } - }, errorCode: { serializedName: "x-ms-error-code", type: { @@ -14837,12 +14757,6 @@ var BlobDownloadHeaders = { name: "Boolean" } }, - lastAccessed: { - serializedName: "x-ms-last-access-time", - type: { - name: "DateTimeRfc1123" - } - }, contentCrc64: { serializedName: "x-ms-content-crc64", type: { @@ -15172,12 +15086,6 @@ var BlobGetPropertiesHeaders = { name: "String" } }, - lastAccessed: { - serializedName: "x-ms-last-access-time", - type: { - name: "DateTimeRfc1123" - } - }, errorCode: { serializedName: "x-ms-error-code", type: { @@ -15634,30 +15542,12 @@ var BlockBlobUploadHeaders = { } } }; -var BlockBlobPutBlobFromUrlHeaders = { - serializedName: "blockblob-putblobfromurl-headers", +var BlobUndeleteHeaders = { + serializedName: "blob-undelete-headers", type: { name: "Composite", - className: "BlockBlobPutBlobFromUrlHeaders", + className: "BlobUndeleteHeaders", modelProperties: { - etag: { - serializedName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - contentMD5: { - serializedName: "content-md5", - type: { - name: "ByteArray" - } - }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { @@ -15676,36 +15566,12 @@ var BlockBlobPutBlobFromUrlHeaders = { name: "String" } }, - versionId: { - serializedName: "x-ms-version-id", - type: { - name: "String" - } - }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, - isServerEncrypted: { - serializedName: "x-ms-request-server-encrypted", - type: { - name: "Boolean" - } - }, - encryptionKeySha256: { - serializedName: "x-ms-encryption-key-sha256", - type: { - name: "String" - } - }, - encryptionScope: { - serializedName: "x-ms-encryption-scope", - type: { - name: "String" - } - }, errorCode: { serializedName: "x-ms-error-code", type: { @@ -15715,12 +15581,24 @@ var BlockBlobPutBlobFromUrlHeaders = { } } }; -var BlobUndeleteHeaders = { - serializedName: "blob-undelete-headers", +var BlobSetExpiryHeaders = { + serializedName: "blob-setexpiry-headers", type: { name: "Composite", - className: "BlobUndeleteHeaders", + className: "BlobSetExpiryHeaders", modelProperties: { + etag: { + serializedName: "etag", + type: { + name: "String" + } + }, + lastModified: { + serializedName: "last-modified", + type: { + name: "DateTimeRfc1123" + } + }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { @@ -15754,11 +15632,11 @@ var BlobUndeleteHeaders = { } } }; -var BlobSetExpiryHeaders = { - serializedName: "blob-setexpiry-headers", +var BlobSetHTTPHeadersHeaders = { + serializedName: "blob-sethttpheaders-headers", type: { name: "Composite", - className: "BlobSetExpiryHeaders", + className: "BlobSetHTTPHeadersHeaders", modelProperties: { etag: { serializedName: "etag", @@ -15770,63 +15648,12 @@ var BlobSetExpiryHeaders = { serializedName: "last-modified", type: { name: "DateTimeRfc1123" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - errorCode: { - serializedName: "x-ms-error-code", - type: { - name: "String" - } - } - } - } -}; -var BlobSetHTTPHeadersHeaders = { - serializedName: "blob-sethttpheaders-headers", - type: { - name: "Composite", - className: "BlobSetHTTPHeadersHeaders", - modelProperties: { - etag: { - serializedName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - blobSequenceNumber: { - serializedName: "x-ms-blob-sequence-number", - type: { - name: "Number" + } + }, + blobSequenceNumber: { + serializedName: "x-ms-blob-sequence-number", + type: { + name: "Number" } }, clientRequestId: { @@ -17976,8 +17803,6 @@ var Mappers = /*#__PURE__*/Object.freeze({ __proto__: null, BlobServiceProperties: BlobServiceProperties, BlobServiceStatistics: BlobServiceStatistics, - BlobTag: BlobTag, - BlobTags: BlobTags, ContainerItem: ContainerItem, ContainerProperties: ContainerProperties, CorsRule: CorsRule, @@ -18208,21 +18033,6 @@ var blobContentType = { } } }; -var blobDeleteType = { - parameterPath: [ - "options", - "blobDeleteType" - ], - mapper: { - serializedName: "deletetype", - type: { - name: "Enum", - allowedValues: [ - "Permanent" - ] - } - } -}; var blobSequenceNumber = { parameterPath: [ "options", @@ -18689,18 +18499,6 @@ var copySource = { } } }; -var copySourceBlobProperties = { - parameterPath: [ - "options", - "copySourceBlobProperties" - ], - mapper: { - serializedName: "x-ms-copy-source-blob-properties", - type: { - name: "Boolean" - } - } -}; var defaultEncryptionScope = { parameterPath: [ "options", @@ -19674,7 +19472,7 @@ var version = { required: true, isConstant: true, serializedName: "x-ms-version", - defaultValue: '2020-04-08', + defaultValue: '2019-12-12', type: { name: "String" } @@ -20666,8 +20464,6 @@ var getAccountInfoOperationSpec$1 = { var Mappers$2 = /*#__PURE__*/Object.freeze({ __proto__: null, - ArrowConfiguration: ArrowConfiguration, - ArrowField: ArrowField, BlobAbortCopyFromURLHeaders: BlobAbortCopyFromURLHeaders, BlobAcquireLeaseHeaders: BlobAcquireLeaseHeaders, BlobBreakLeaseHeaders: BlobBreakLeaseHeaders, @@ -20955,8 +20751,7 @@ var deleteMethodOperationSpec$1 = { queryParameters: [ snapshot, versionId, - timeoutInSeconds, - blobDeleteType + timeoutInSeconds ], headerParameters: [ deleteSnapshots, @@ -21672,8 +21467,7 @@ var getTagsOperationSpec = { headerParameters: [ version, requestId, - ifTags, - leaseId0 + ifTags ], responses: { 200: { @@ -21704,8 +21498,7 @@ var setTagsOperationSpec = { transactionalContentMD5, transactionalContentCrc64, requestId, - ifTags, - leaseId0 + ifTags ], requestBody: { parameterPath: [ @@ -22458,7 +22251,6 @@ var Mappers$5 = /*#__PURE__*/Object.freeze({ Block: Block, BlockBlobCommitBlockListHeaders: BlockBlobCommitBlockListHeaders, BlockBlobGetBlockListHeaders: BlockBlobGetBlockListHeaders, - BlockBlobPutBlobFromUrlHeaders: BlockBlobPutBlobFromUrlHeaders, BlockBlobStageBlockFromURLHeaders: BlockBlobStageBlockFromURLHeaders, BlockBlobStageBlockHeaders: BlockBlobStageBlockHeaders, BlockBlobUploadHeaders: BlockBlobUploadHeaders, @@ -22492,13 +22284,6 @@ var BlockBlob = /** @class */ (function () { options: options }, uploadOperationSpec, callback); }; - BlockBlob.prototype.putBlobFromUrl = function (contentLength, copySource, options, callback) { - return this.client.sendOperationRequest({ - contentLength: contentLength, - copySource: copySource, - options: options - }, putBlobFromUrlOperationSpec, callback); - }; BlockBlob.prototype.stageBlock = function (blockId, contentLength, body, options, callback) { return this.client.sendOperationRequest({ blockId: blockId, @@ -22589,61 +22374,6 @@ var uploadOperationSpec = { isXML: true, serializer: serializer$5 }; -var putBlobFromUrlOperationSpec = { - httpMethod: "PUT", - path: "{containerName}/{blob}", - urlParameters: [ - url - ], - queryParameters: [ - timeoutInSeconds - ], - headerParameters: [ - transactionalContentMD5, - contentLength, - metadata, - encryptionScope, - tier0, - version, - requestId, - sourceContentMD5, - blobTagsString, - copySource, - copySourceBlobProperties, - blobType2, - blobContentType, - blobContentEncoding, - blobContentLanguage, - blobContentMD5, - blobCacheControl, - blobContentDisposition, - leaseId0, - encryptionKey, - encryptionKeySha256, - encryptionAlgorithm, - ifModifiedSince, - ifUnmodifiedSince, - ifMatch, - ifNoneMatch, - ifTags, - sourceIfModifiedSince, - sourceIfUnmodifiedSince, - sourceIfMatch, - sourceIfNoneMatch, - sourceIfTags - ], - responses: { - 201: { - headersMapper: BlockBlobPutBlobFromUrlHeaders - }, - default: { - bodyMapper: StorageError, - headersMapper: BlockBlobPutBlobFromUrlHeaders - } - }, - isXML: true, - serializer: serializer$5 -}; var stageBlockOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", @@ -22823,8 +22553,8 @@ var logger = logger$1.createClientLogger("storage-blob"); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -var SDK_VERSION = "12.4.1"; -var SERVICE_VERSION = "2020-04-08"; +var SDK_VERSION = "12.2.1"; +var SERVICE_VERSION = "2019-12-12"; var BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES = 256 * 1024 * 1024; // 256MB var BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES = 4000 * 1024 * 1024; // 4000MB var BLOCK_BLOB_MAX_BLOCKS = 50000; @@ -23220,18 +22950,6 @@ function setURLParameter(url, name, value) { urlParsed.setQueryParameter(name, value); return urlParsed.toString(); } -/** - * Get URL parameter by name. - * - * @export - * @param {string} url - * @param {string} name - * @returns {(string | string[] | undefined)} - */ -function getURLParameter(url, name) { - var urlParsed = coreHttp.URLBuilder.parse(url); - return urlParsed.getQueryParameterValue(name); -} /** * Set URL host. * @@ -23317,26 +23035,6 @@ function getURLQueries(url) { } return queries; } -/** - * Append a string to URL query. - * - * @export - * @param {string} url Source URL string. - * @param {string} queryParts String to be appended to the URL query. - * @returns {string} An updated URL string. - */ -function appendToURLQuery(url, queryParts) { - var urlParsed = coreHttp.URLBuilder.parse(url); - var query = urlParsed.getQuery(); - if (query) { - query += "&" + queryParts; - } - else { - query = queryParts; - } - urlParsed.setQuery(query); - return urlParsed.toString(); -} /** * Rounds a date off to seconds. * @@ -23563,7 +23261,7 @@ function toTags(tags) { * Convert BlobQueryTextConfiguration to QuerySerialization type. * * @export - * @param {(BlobQueryJsonTextConfiguration | BlobQueryCsvTextConfiguration | BlobQueryArrowConfiguration)} [textConfiguration] + * @param {(BlobQueryJsonTextConfiguration | BlobQueryCsvTextConfiguration)} [textConfiguration] * @returns {(QuerySerialization | undefined)} */ function toQuerySerialization(textConfiguration) { @@ -23593,15 +23291,6 @@ function toQuerySerialization(textConfiguration) { } } }; - case "arrow": - return { - format: { - type: "arrow", - arrowConfiguration: { - schema: textConfiguration.schema - } - } - }; default: throw Error("Invalid BlobQueryTextConfiguration."); } @@ -23642,18 +23331,6 @@ function parseObjectReplicationRecord(objectReplicationRecord) { } return orProperties; } -/** - * Attach a TokenCredential to an object. - * - * @export - * @param {T} thing - * @param {TokenCredential} credential - * @returns {T} - */ -function attachCredential(thing, credential) { - thing.credential = credential; - return thing; -} // Copyright (c) Microsoft Corporation. All rights reserved. /** @@ -23898,7 +23575,11 @@ var StorageRetryPolicy = /** @class */ (function (_super) { var retriableError = retriableErrors_1[_i]; if (err.name.toUpperCase().includes(retriableError) || err.message.toUpperCase().includes(retriableError) || - (err.code && err.code.toString().toUpperCase() === retriableError)) { + (err.code && + err.code + .toString() + .toUpperCase() + .includes(retriableError))) { logger.info("RetryPolicy: Network error " + retriableError + " found, will retry."); return true; } @@ -23919,10 +23600,6 @@ var StorageRetryPolicy = /** @class */ (function (_super) { return true; } } - if ((err === null || err === void 0 ? void 0 : err.code) === "PARSE_ERROR" && (err === null || err === void 0 ? void 0 : err.message.startsWith("Error \"Error: Unclosed root tag"))) { - logger.info("RetryPolicy: Incomplete XML response likely due to service timeout, will retry."); - return true; - } return false; }; /** @@ -24182,7 +23859,9 @@ var TelemetryPolicyFactory = /** @class */ (function () { var userAgentInfo = []; { if (telemetry) { - var telemetryString = telemetry.userAgentPrefix || ""; + // FIXME: replace() only replaces the first space. And we have no idea why we need to replace spaces in the first place. + // But fixing this would be a breaking change. Logged an issue here: https://github.com/Azure/azure-sdk-for-js/issues/10793 + var telemetryString = (telemetry.userAgentPrefix || "").replace(" ", ""); if (telemetryString.length > 0 && userAgentInfo.indexOf(telemetryString) === -1) { userAgentInfo.push(telemetryString); } @@ -24285,11 +23964,8 @@ function newPipeline(credential, pipelineOptions) { telemetryPolicy, coreHttp.generateClientRequestIdPolicy(), new StorageBrowserPolicyFactory(), + coreHttp.deserializationPolicy(), new StorageRetryPolicyFactory(pipelineOptions.retryOptions), - // Default deserializationPolicy is provided by protocol layer - // Use customized XML char key of "#" so we could deserialize metadata - // with "_" key - coreHttp.deserializationPolicy(undefined, { xmlCharKey: "#" }), coreHttp.logPolicy({ logger: logger.info, allowedHeaderNames: StorageBlobLoggingAllowedHeaderNames, @@ -24302,12 +23978,13 @@ function newPipeline(credential, pipelineOptions) { factories.push(coreHttp.disableResponseDecompressionPolicy()); } factories.push(coreHttp.isTokenCredential(credential) - ? attachCredential(coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes), credential) + ? coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes) : credential); return new Pipeline(factories, pipelineOptions); } // Copyright (c) Microsoft Corporation. All rights reserved. +var ABORT_ERROR = new abortController.AbortError("The operation was aborted."); /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -24331,9 +24008,36 @@ var RetriableReadableStream = /** @class */ (function (_super) { */ function RetriableReadableStream(source, getter, offset, count, options) { if (options === void 0) { options = {}; } - var _this = _super.call(this, { highWaterMark: options.highWaterMark }) || this; + var _this = _super.call(this) || this; _this.retries = 0; - _this.sourceDataHandler = function (data) { + _this.abortHandler = function () { + _this.source.pause(); + _this.emit("error", ABORT_ERROR); + }; + _this.aborter = options.abortSignal || abortController.AbortSignal.none; + _this.getter = getter; + _this.source = source; + _this.start = offset; + _this.offset = offset; + _this.end = offset + count - 1; + _this.maxRetryRequests = + options.maxRetryRequests && options.maxRetryRequests >= 0 ? options.maxRetryRequests : 0; + _this.onProgress = options.onProgress; + _this.options = options; + _this.aborter.addEventListener("abort", _this.abortHandler); + _this.setSourceDataHandler(); + _this.setSourceEndHandler(); + _this.setSourceErrorHandler(); + return _this; + } + RetriableReadableStream.prototype._read = function () { + if (!this.aborter.aborted) { + this.source.resume(); + } + }; + RetriableReadableStream.prototype.setSourceDataHandler = function () { + var _this = this; + this.source.on("data", function (data) { if (_this.options.doInjectErrorOnce) { _this.options.doInjectErrorOnce = undefined; _this.source.pause(); @@ -24351,19 +24055,18 @@ var RetriableReadableStream = /** @class */ (function (_super) { if (!_this.push(data)) { _this.source.pause(); } - }; - _this.sourceErrorOrEndHandler = function (err) { - if (err && err.name === "AbortError") { - _this.destroy(err); - return; - } + }); + }; + RetriableReadableStream.prototype.setSourceEndHandler = function () { + var _this = this; + this.source.on("end", function () { // console.log( - // `Source stream emits end or error, offset: ${ + // `Source stream emits end, offset: ${ // this.offset // }, dest end : ${this.end}` // ); - _this.removeSourceEventHandlers(); if (_this.offset - 1 === _this.end) { + _this.aborter.removeEventListener("abort", _this.abortHandler); _this.push(null); } else if (_this.offset <= _this.end) { @@ -24375,53 +24078,31 @@ var RetriableReadableStream = /** @class */ (function (_super) { _this.getter(_this.offset) .then(function (newSource) { _this.source = newSource; - _this.setSourceEventHandlers(); + _this.setSourceDataHandler(); + _this.setSourceEndHandler(); + _this.setSourceErrorHandler(); }) .catch(function (error) { - _this.destroy(error); + _this.emit("error", error); }); } else { - _this.destroy(new Error( + _this.emit("error", new Error( // tslint:disable-next-line:max-line-length "Data corruption failure: received less data than required and reached maxRetires limitation. Received data offset: " + (_this .offset - 1) + ", data needed offset: " + _this.end + ", retries: " + _this.retries + ", max retries: " + _this.maxRetryRequests)); } } else { - _this.destroy(new Error("Data corruption failure: Received more data than original request, data needed offset is " + _this.end + ", received offset: " + (_this.offset - 1))); + _this.emit("error", new Error("Data corruption failure: Received more data than original request, data needed offset is " + _this.end + ", received offset: " + (_this.offset - 1))); } - }; - _this.getter = getter; - _this.source = source; - _this.start = offset; - _this.offset = offset; - _this.end = offset + count - 1; - _this.maxRetryRequests = - options.maxRetryRequests && options.maxRetryRequests >= 0 ? options.maxRetryRequests : 0; - _this.onProgress = options.onProgress; - _this.options = options; - _this.setSourceEventHandlers(); - return _this; - } - RetriableReadableStream.prototype._read = function () { - this.source.resume(); - }; - RetriableReadableStream.prototype.setSourceEventHandlers = function () { - this.source.on("data", this.sourceDataHandler); - this.source.on("end", this.sourceErrorOrEndHandler); - this.source.on("error", this.sourceErrorOrEndHandler); - }; - RetriableReadableStream.prototype.removeSourceEventHandlers = function () { - this.source.removeListener("data", this.sourceDataHandler); - this.source.removeListener("end", this.sourceErrorOrEndHandler); - this.source.removeListener("error", this.sourceErrorOrEndHandler); + }); }; - RetriableReadableStream.prototype._destroy = function (error, callback) { - // remove listener from source and release source - this.removeSourceEventHandlers(); - this.source.destroy(); - callback(error === null ? undefined : error); + RetriableReadableStream.prototype.setSourceErrorHandler = function () { + var _this = this; + this.source.on("error", function (error) { + _this.emit("error", error); + }); }; return RetriableReadableStream; }(stream.Readable)); @@ -24897,21 +24578,6 @@ var BlobDownloadResponse = /** @class */ (function () { enumerable: false, configurable: true }); - Object.defineProperty(BlobDownloadResponse.prototype, "lastAccessed", { - /** - * Returns the UTC date and time generated by the service that indicates the time at which the blob was - * last read or written to. - * - * @readonly - * @type {(Date | undefined)} - * @memberof BlobDownloadResponse - */ - get: function () { - return this.originalResponse.lastAccessed; - }, - enumerable: false, - configurable: true - }); Object.defineProperty(BlobDownloadResponse.prototype, "metadata", { /** * A name-value pair @@ -25880,7 +25546,7 @@ var AvroReadable = /** @class */ (function () { }()); // Copyright (c) Microsoft Corporation. -var ABORT_ERROR = new abortController.AbortError("Reading from the avro stream was aborted."); +var ABORT_ERROR$1 = new abortController.AbortError("Reading from the avro stream was aborted."); var AvroReadableFromStream = /** @class */ (function (_super) { tslib.__extends(AvroReadableFromStream, _super); function AvroReadableFromStream(readable) { @@ -25910,7 +25576,7 @@ var AvroReadableFromStream = /** @class */ (function (_super) { var _this = this; return tslib.__generator(this, function (_b) { if ((_a = options.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { - throw ABORT_ERROR; + throw ABORT_ERROR$1; } if (size < 0) { throw new Error("size parameter should be positive: " + size); @@ -25954,7 +25620,7 @@ var AvroReadableFromStream = /** @class */ (function (_super) { }; var abortHandler = function () { cleanUp(); - reject(ABORT_ERROR); + reject(ABORT_ERROR$1); }; _this._readable.on("readable", readableCallback); _this._readable.once("error", rejectCallback); @@ -25992,7 +25658,6 @@ var BlobQuickQueryStream = /** @class */ (function (_super) { function BlobQuickQueryStream(source, options) { if (options === void 0) { options = {}; } var _this = _super.call(this) || this; - _this.avroPaused = true; _this.source = source; _this.onProgress = options.onProgress; _this.onError = options.onError; @@ -26002,31 +25667,29 @@ var BlobQuickQueryStream = /** @class */ (function (_super) { } BlobQuickQueryStream.prototype._read = function () { var _this = this; - if (this.avroPaused) { - this.readInternal().catch(function (err) { - _this.emit("error", err); - }); - } + this.readInternal().catch(function (err) { + _this.emit("error", err); + }); }; BlobQuickQueryStream.prototype.readInternal = function () { + var e_1, _a; return tslib.__awaiter(this, void 0, void 0, function () { - var avroNext, obj, schema, data, bytesScanned, totalBytes, fatal, name_1, description, position; - return tslib.__generator(this, function (_a) { - switch (_a.label) { + var _b, _c, obj, schema, exit, data, bytesScanned, totalBytes, fatal, name_1, description, position, e_1_1; + return tslib.__generator(this, function (_d) { + switch (_d.label) { case 0: - this.avroPaused = false; - _a.label = 1; - case 1: return [4 /*yield*/, this.avroIter.next()]; + _d.trys.push([0, 5, 6, 11]); + _b = tslib.__asyncValues(this.avroIter); + _d.label = 1; + case 1: return [4 /*yield*/, _b.next()]; case 2: - avroNext = _a.sent(); - if (avroNext.done) { - return [3 /*break*/, 4]; - } - obj = avroNext.value; + if (!(_c = _d.sent(), !_c.done)) return [3 /*break*/, 4]; + obj = _c.value; schema = obj.$schema; if (typeof schema !== "string") { throw Error("Missing schema in avro record."); } + exit = false; switch (schema) { case "com.microsoft.azure.storage.queryBlobContents.resultData": data = obj.data; @@ -26034,7 +25697,7 @@ var BlobQuickQueryStream = /** @class */ (function (_super) { throw Error("Invalid data in avro result record."); } if (!this.push(Buffer.from(data))) { - this.avroPaused = true; + exit = true; } break; case "com.microsoft.azure.storage.queryBlobContents.progress": @@ -26085,11 +25748,29 @@ var BlobQuickQueryStream = /** @class */ (function (_super) { default: throw Error("Unknown schema " + schema + " in avro progress record."); } - _a.label = 3; - case 3: - if (!avroNext.done && !this.avroPaused) return [3 /*break*/, 1]; - _a.label = 4; - case 4: return [2 /*return*/]; + if (exit) { + return [3 /*break*/, 4]; + } + _d.label = 3; + case 3: return [3 /*break*/, 1]; + case 4: return [3 /*break*/, 11]; + case 5: + e_1_1 = _d.sent(); + e_1 = { error: e_1_1 }; + return [3 /*break*/, 11]; + case 6: + _d.trys.push([6, , 9, 10]); + if (!(_c && !_c.done && (_a = _b.return))) return [3 /*break*/, 8]; + return [4 /*yield*/, _a.call(_b)]; + case 7: + _d.sent(); + _d.label = 8; + case 8: return [3 /*break*/, 10]; + case 9: + if (e_1) throw e_1.error; + return [7 /*endfinally*/]; + case 10: return [7 /*endfinally*/]; + case 11: return [2 /*return*/]; } }); }); @@ -26901,7 +26582,7 @@ var StorageSharedKeyCredential = /** @class */ (function (_super) { * regenerated. */ var packageName = "azure-storage-blob"; -var packageVersion = "12.4.1"; +var packageVersion = "12.2.1"; var StorageClientContext = /** @class */ (function (_super) { tslib.__extends(StorageClientContext, _super); /** @@ -26923,7 +26604,7 @@ var StorageClientContext = /** @class */ (function (_super) { options.userAgent = packageName + "/" + packageVersion + " " + defaultUserAgent; } _this = _super.call(this, undefined, options) || this; - _this.version = '2020-04-08'; + _this.version = "2019-12-12"; _this.baseUri = "{url}"; _this.requestContentType = "application/json; charset=utf-8"; _this.url = url; @@ -27036,7 +26717,7 @@ function rangeResponseFromModel(response) { * This is the poller returned by {@link BlobClient.beginCopyFromURL}. * This can not be instantiated directly outside of this package. * - * @hidden + * @ignore */ var BlobBeginCopyFromUrlPoller = /** @class */ (function (_super) { tslib.__extends(BlobBeginCopyFromUrlPoller, _super); @@ -27066,7 +26747,7 @@ var BlobBeginCopyFromUrlPoller = /** @class */ (function (_super) { * Note: Intentionally using function expression over arrow function expression * so that the function can be invoked with a different context. * This affects what `this` refers to. - * @hidden + * @ignore */ var cancel = function cancel(options) { if (options === void 0) { options = {}; } @@ -27101,7 +26782,7 @@ var cancel = function cancel(options) { * Note: Intentionally using function expression over arrow function expression * so that the function can be invoked with a different context. * This affects what `this` refers to. - * @hidden + * @ignore */ var update = function update(options) { if (options === void 0) { options = {}; } @@ -27166,7 +26847,7 @@ var update = function update(options) { * Note: Intentionally using function expression over arrow function expression * so that the function can be invoked with a different context. * This affects what `this` refers to. - * @hidden + * @ignore */ var toString = function toString() { return JSON.stringify({ state: this.state }, function (key, value) { @@ -27179,7 +26860,7 @@ var toString = function toString() { }; /** * Creates a poll operation given the provided state. - * @hidden + * @ignore */ function makeBlobBeginCopyFromURLPollOperation(state) { return { @@ -27239,14 +26920,10 @@ var StorageClient = /** @class */ (function () { for (var _i = 0, _a = this.pipeline.factories; _i < _a.length; _i++) { var factory = _a[_i]; if ((coreHttp.isNode && factory instanceof StorageSharedKeyCredential) || - factory instanceof AnonymousCredential) { + factory instanceof AnonymousCredential || + coreHttp.isTokenCredential(factory)) { this.credential = factory; } - else if (coreHttp.isTokenCredential(factory.credential)) { - // Only works if the factory has been attached a "credential" property. - // We do that in newPipeline() when using TokenCredential. - this.credential = factory.credential; - } } // Override protocol layer's default content-type var storageClientContext = this.storageClientContext; @@ -28095,1520 +27772,424 @@ function readStreamToLocalFile(rs, file) { var fsStat = util.promisify(fs.stat); var fsCreateReadStream = fs.createReadStream; -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. /** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a blob. Setting - * a value to true means that any SAS which uses these permissions will grant permissions for that operation. Once all - * the values are set, this should be serialized with toString and set as the permissions field on a - * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but - * the order of the permissions is particular and this class guarantees correctness. + * A BlobClient represents a URL to an Azure Storage blob; the blob may be a block blob, + * append blob, or page blob. * * @export - * @class BlobSASPermissions + * @class BlobClient */ -var BlobSASPermissions = /** @class */ (function () { - function BlobSASPermissions() { - /** - * Specifies Read access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.read = false; - /** - * Specifies Add access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.add = false; - /** - * Specifies Create access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.create = false; - /** - * Specifies Write access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.write = false; - /** - * Specifies Delete access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.delete = false; - /** - * Specifies Delete version access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.deleteVersion = false; - /** - * Specfies Tag access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions - */ - this.tag = false; +var BlobClient = /** @class */ (function (_super) { + tslib.__extends(BlobClient, _super); + function BlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { + var _a; + var _this = this; + options = options || {}; + var pipeline; + var url; + if (credentialOrPipelineOrContainerName instanceof Pipeline) { + // (url: string, pipeline: Pipeline) + url = urlOrConnectionString; + pipeline = credentialOrPipelineOrContainerName; + } + else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || + credentialOrPipelineOrContainerName instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + url = urlOrConnectionString; + options = blobNameOrOptions; + pipeline = newPipeline(credentialOrPipelineOrContainerName, options); + } + else if (!credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName !== "string") { + // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) + // The second parameter is undefined. Use anonymous credential. + url = urlOrConnectionString; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else if (credentialOrPipelineOrContainerName && + typeof credentialOrPipelineOrContainerName === "string" && + blobNameOrOptions && + typeof blobNameOrOptions === "string") { + // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) + var containerName = credentialOrPipelineOrContainerName; + var blobName = blobNameOrOptions; + var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + if (extractedCreds.kind === "AccountConnString") { + { + var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); + options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); + pipeline = newPipeline(sharedKeyCredential, options); + } + } + else if (extractedCreds.kind === "SASConnString") { + url = + appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + + "?" + + extractedCreds.accountSas; + pipeline = newPipeline(new AnonymousCredential(), options); + } + else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + } + else { + throw new Error("Expecting non-empty strings for containerName and blobName parameters"); + } + _this = _super.call(this, url, pipeline) || this; + (_a = _this.getBlobAndContainerNamesFromUrl(), _this._name = _a.blobName, _this._containerName = _a.containerName); + _this.blobContext = new Blob$1(_this.storageClientContext); + return _this; + } + Object.defineProperty(BlobClient.prototype, "name", { /** - * Specifies Move access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions + * The name of the blob. */ - this.move = false; + get: function () { + return this._name; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlobClient.prototype, "containerName", { /** - * Specifies Execute access granted. - * - * @type {boolean} - * @memberof BlobSASPermissions + * The name of the storage container the blob is associated with. */ - this.execute = false; - } + get: function () { + return this._containerName; + }, + enumerable: false, + configurable: true + }); /** - * Creates a {@link BlobSASPermissions} from the specified permissions string. This method will throw an - * Error if it encounters a character that does not correspond to a valid permission. + * Creates a new BlobClient object identical to the source but with the specified snapshot timestamp. + * Provide "" will remove the snapshot and return a Client to the base blob. * - * @static - * @param {string} permissions - * @returns {BlobSASPermissions} - * @memberof BlobSASPermissions + * @param {string} snapshot The snapshot timestamp. + * @returns {BlobClient} A new BlobClient object identical to the source but with the specified snapshot timestamp + * @memberof BlobClient */ - BlobSASPermissions.parse = function (permissions) { - var blobSASPermissions = new BlobSASPermissions(); - for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { - var char = permissions_1[_i]; - switch (char) { - case "r": - blobSASPermissions.read = true; - break; - case "a": - blobSASPermissions.add = true; - break; - case "c": - blobSASPermissions.create = true; - break; - case "w": - blobSASPermissions.write = true; - break; - case "d": - blobSASPermissions.delete = true; - break; - case "x": - blobSASPermissions.deleteVersion = true; - break; - case "t": - blobSASPermissions.tag = true; - break; - case "m": - blobSASPermissions.move = true; - break; - case "e": - blobSASPermissions.execute = true; - break; - default: - throw new RangeError("Invalid permission: " + char); - } - } - return blobSASPermissions; + BlobClient.prototype.withSnapshot = function (snapshot) { + return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); }; /** - * Creates a {@link BlobSASPermissions} from a raw object which contains same keys as it - * and boolean values for them. + * Creates a new BlobClient object pointing to a version of this blob. + * Provide "" will remove the versionId and return a Client to the base blob. * - * @static - * @param {BlobSASPermissionsLike} permissionLike - * @returns {BlobSASPermissions} - * @memberof BlobSASPermissions + * @param {string} versionId The versionId. + * @returns {BlobClient} A new BlobClient object pointing to the version of this blob. + * @memberof BlobClient */ - BlobSASPermissions.from = function (permissionLike) { - var blobSASPermissions = new BlobSASPermissions(); - if (permissionLike.read) { - blobSASPermissions.read = true; - } - if (permissionLike.add) { - blobSASPermissions.add = true; - } - if (permissionLike.create) { - blobSASPermissions.create = true; - } - if (permissionLike.write) { - blobSASPermissions.write = true; - } - if (permissionLike.delete) { - blobSASPermissions.delete = true; - } - if (permissionLike.deleteVersion) { - blobSASPermissions.deleteVersion = true; - } - if (permissionLike.tag) { - blobSASPermissions.tag = true; - } - if (permissionLike.move) { - blobSASPermissions.move = true; - } - if (permissionLike.execute) { - blobSASPermissions.execute = true; - } - return blobSASPermissions; + BlobClient.prototype.withVersion = function (versionId) { + return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.VERSIONID, versionId.length === 0 ? undefined : versionId), this.pipeline); }; /** - * Converts the given permissions to a string. Using this method will guarantee the permissions are in an - * order accepted by the service. + * Creates a AppendBlobClient object. * - * @returns {string} A string which represents the BlobSASPermissions - * @memberof BlobSASPermissions + * @returns {AppendBlobClient} + * @memberof BlobClient */ - BlobSASPermissions.prototype.toString = function () { - var permissions = []; - if (this.read) { - permissions.push("r"); - } - if (this.add) { - permissions.push("a"); - } - if (this.create) { - permissions.push("c"); - } - if (this.write) { - permissions.push("w"); - } - if (this.delete) { - permissions.push("d"); - } - if (this.deleteVersion) { - permissions.push("x"); - } - if (this.tag) { - permissions.push("t"); - } - if (this.move) { - permissions.push("m"); - } - if (this.execute) { - permissions.push("e"); - } - return permissions.join(""); + BlobClient.prototype.getAppendBlobClient = function () { + return new AppendBlobClient(this.url, this.pipeline); }; - return BlobSASPermissions; -}()); - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -/** - * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a container. - * Setting a value to true means that any SAS which uses these permissions will grant permissions for that operation. - * Once all the values are set, this should be serialized with toString and set as the permissions field on a - * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but - * the order of the permissions is particular and this class guarantees correctness. - * - * @export - * @class ContainerSASPermissions - */ -var ContainerSASPermissions = /** @class */ (function () { - function ContainerSASPermissions() { - /** - * Specifies Read access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.read = false; - /** - * Specifies Add access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.add = false; - /** - * Specifies Create access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.create = false; - /** - * Specifies Write access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.write = false; - /** - * Specifies Delete access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.delete = false; - /** - * Specifies Delete version access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.deleteVersion = false; - /** - * Specifies List access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.list = false; - /** - * Specfies Tag access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.tag = false; - /** - * Specifies Move access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.move = false; - /** - * Specifies Execute access granted. - * - * @type {boolean} - * @memberof ContainerSASPermissions - */ - this.execute = false; - } /** - * Creates an {@link ContainerSASPermissions} from the specified permissions string. This method will throw an - * Error if it encounters a character that does not correspond to a valid permission. + * Creates a BlockBlobClient object. * - * @static - * @param {string} permissions - * @returns {ContainerSASPermissions} - * @memberof ContainerSASPermissions + * @returns {BlockBlobClient} + * @memberof BlobClient */ - ContainerSASPermissions.parse = function (permissions) { - var containerSASPermissions = new ContainerSASPermissions(); - for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { - var char = permissions_1[_i]; - switch (char) { - case "r": - containerSASPermissions.read = true; - break; - case "a": - containerSASPermissions.add = true; - break; - case "c": - containerSASPermissions.create = true; - break; - case "w": - containerSASPermissions.write = true; - break; - case "d": - containerSASPermissions.delete = true; - break; - case "l": - containerSASPermissions.list = true; - break; - case "t": - containerSASPermissions.tag = true; - break; - case "x": - containerSASPermissions.deleteVersion = true; - break; - case "m": - containerSASPermissions.move = true; - break; - case "e": - containerSASPermissions.execute = true; - break; - default: - throw new RangeError("Invalid permission " + char); - } - } - return containerSASPermissions; + BlobClient.prototype.getBlockBlobClient = function () { + return new BlockBlobClient(this.url, this.pipeline); }; /** - * Creates a {@link ContainerSASPermissions} from a raw object which contains same keys as it - * and boolean values for them. + * Creates a PageBlobClient object. * - * @static - * @param {ContainerSASPermissionsLike} permissionLike - * @returns {ContainerSASPermissions} - * @memberof ContainerSASPermissions + * @returns {PageBlobClient} + * @memberof BlobClient */ - ContainerSASPermissions.from = function (permissionLike) { - var containerSASPermissions = new ContainerSASPermissions(); - if (permissionLike.read) { - containerSASPermissions.read = true; - } - if (permissionLike.add) { - containerSASPermissions.add = true; - } - if (permissionLike.create) { - containerSASPermissions.create = true; - } - if (permissionLike.write) { - containerSASPermissions.write = true; - } - if (permissionLike.delete) { - containerSASPermissions.delete = true; - } - if (permissionLike.list) { - containerSASPermissions.list = true; - } - if (permissionLike.deleteVersion) { - containerSASPermissions.deleteVersion = true; - } - if (permissionLike.tag) { - containerSASPermissions.tag = true; - } - if (permissionLike.move) { - containerSASPermissions.move = true; - } - if (permissionLike.execute) { - containerSASPermissions.execute = true; - } - return containerSASPermissions; + BlobClient.prototype.getPageBlobClient = function () { + return new PageBlobClient(this.url, this.pipeline); }; /** - * Converts the given permissions to a string. Using this method will guarantee the permissions are in an - * order accepted by the service. + * Reads or downloads a blob from the system, including its metadata and properties. + * You can also call Get Blob to read a snapshot. * - * The order of the characters should be as specified here to ensure correctness. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas + * * In Node.js, data returns in a Readable stream readableStreamBody + * * In browsers, data returns in a promise blobBody * - * @returns {string} - * @memberof ContainerSASPermissions + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob + * + * @param {number} [offset] From which position of the blob to download, >= 0 + * @param {number} [count] How much data to be downloaded, > 0. Will download to the end when undefined + * @param {BlobDownloadOptions} [options] Optional options to Blob Download operation. + * @returns {Promise} + * @memberof BlobClient + * + * Example usage (Node.js): + * + * ```js + * // Download and convert a blob to a string + * const downloadBlockBlobResponse = await blobClient.download(); + * const downloaded = await streamToBuffer(downloadBlockBlobResponse.readableStreamBody); + * console.log("Downloaded blob content:", downloaded.toString()); + * + * async function streamToBuffer(readableStream) { + * return new Promise((resolve, reject) => { + * const chunks = []; + * readableStream.on("data", (data) => { + * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); + * }); + * readableStream.on("end", () => { + * resolve(Buffer.concat(chunks)); + * }); + * readableStream.on("error", reject); + * }); + * } + * ``` + * + * Example usage (browser): + * + * ```js + * // Download and convert a blob to a string + * const downloadBlockBlobResponse = await blobClient.download(); + * const downloaded = await blobToString(await downloadBlockBlobResponse.blobBody); + * console.log( + * "Downloaded blob content", + * downloaded + * ); + * + * async function blobToString(blob: Blob): Promise { + * const fileReader = new FileReader(); + * return new Promise((resolve, reject) => { + * fileReader.onloadend = (ev: any) => { + * resolve(ev.target!.result); + * }; + * fileReader.onerror = reject; + * fileReader.readAsText(blob); + * }); + * } + * ``` */ - ContainerSASPermissions.prototype.toString = function () { - var permissions = []; - if (this.read) { - permissions.push("r"); - } - if (this.add) { - permissions.push("a"); - } - if (this.create) { - permissions.push("c"); - } - if (this.write) { - permissions.push("w"); - } - if (this.delete) { - permissions.push("d"); - } - if (this.deleteVersion) { - permissions.push("x"); - } - if (this.list) { - permissions.push("l"); - } - if (this.tag) { - permissions.push("t"); - } - if (this.move) { - permissions.push("m"); - } - if (this.execute) { - permissions.push("e"); - } - return permissions.join(""); + BlobClient.prototype.download = function (offset, count, options) { + var _a; + if (offset === void 0) { offset = 0; } + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, res_1, wrappedRes, e_1; + var _this = this; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + options.conditions = options.conditions || {}; + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + _b = createSpan("BlobClient-download", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.blobContext.download({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + onDownloadProgress: coreHttp.isNode ? undefined : options.onProgress, + range: offset === 0 && !count ? undefined : rangeToString({ offset: offset, count: count }), + rangeGetContentMD5: options.rangeGetContentMD5, + rangeGetContentCRC64: options.rangeGetContentCrc64, + snapshot: options.snapshot, + cpkInfo: options.customerProvidedKey, + spanOptions: spanOptions + })]; + case 2: + res_1 = _c.sent(); + wrappedRes = tslib.__assign(tslib.__assign({}, res_1), { _response: res_1._response, objectReplicationDestinationPolicyId: res_1.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res_1.objectReplicationRules) }); + // We support retrying when download stream unexpected ends in Node.js runtime + // Following code shouldn't be bundled into browser build, however some + // bundlers may try to bundle following code and "FileReadResponse.ts". + // In this case, "FileDownloadResponse.browser.ts" will be used as a shim of "FileDownloadResponse.ts" + // The config is in package.json "browser" field + if (options.maxRetryRequests === undefined || options.maxRetryRequests < 0) { + // TODO: Default value or make it a required parameter? + options.maxRetryRequests = DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS; + } + if (res_1.contentLength === undefined) { + throw new RangeError("File download response doesn't contain valid content length header"); + } + if (!res_1.etag) { + throw new RangeError("File download response doesn't contain valid etag header"); + } + return [2 /*return*/, new BlobDownloadResponse(wrappedRes, function (start) { return tslib.__awaiter(_this, void 0, void 0, function () { + var updatedOptions; + var _a; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + updatedOptions = { + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ifMatch: options.conditions.ifMatch || res_1.etag, + ifModifiedSince: options.conditions.ifModifiedSince, + ifNoneMatch: options.conditions.ifNoneMatch, + ifUnmodifiedSince: options.conditions.ifUnmodifiedSince, + ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions + }, + range: rangeToString({ + count: offset + res_1.contentLength - start, + offset: start + }), + rangeGetContentMD5: options.rangeGetContentMD5, + rangeGetContentCRC64: options.rangeGetContentCrc64, + snapshot: options.snapshot, + cpkInfo: options.customerProvidedKey + }; + return [4 /*yield*/, this.blobContext.download(tslib.__assign({ abortSignal: options.abortSignal }, updatedOptions))]; + case 1: + // Debug purpose only + // console.log( + // `Read from internal stream, range: ${ + // updatedOptions.range + // }, options: ${JSON.stringify(updatedOptions)}` + // ); + return [2 /*return*/, (_b.sent()).readableStreamBody]; + } + }); + }); }, offset, res_1.contentLength, { + abortSignal: options.abortSignal, + maxRetryRequests: options.maxRetryRequests, + onProgress: options.onProgress + })]; + case 3: + e_1 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_1.message + }); + throw e_1; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; - return ContainerSASPermissions; -}()); - -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * UserDelegationKeyCredential is only used for generation of user delegation SAS. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas - * - * @export - * @class UserDelegationKeyCredential - */ -var UserDelegationKeyCredential = /** @class */ (function () { - /** - * Creates an instance of UserDelegationKeyCredential. - * @param {string} accountName - * @param {UserDelegationKey} userDelegationKey - * @memberof UserDelegationKeyCredential - */ - function UserDelegationKeyCredential(accountName, userDelegationKey) { - this.accountName = accountName; - this.userDelegationKey = userDelegationKey; - this.key = Buffer.from(userDelegationKey.value, "base64"); - } /** - * Generates a hash signature for an HTTP request or for a SAS. + * Returns true if the Azure blob resource represented by this client exists; false otherwise. * - * @param {string} stringToSign - * @returns {string} - * @memberof UserDelegationKeyCredential + * NOTE: use this function with care since an existing blob might be deleted by other clients or + * applications. Vice versa new blobs might be added by other clients or applications after this + * function completes. + * + * @param {BlobExistsOptions} [options] options to Exists operation. + * @returns {Promise} + * @memberof BlobClient */ - UserDelegationKeyCredential.prototype.computeHMACSHA256 = function (stringToSign) { - // console.log(`stringToSign: ${JSON.stringify(stringToSign)}`); - return crypto.createHmac("sha256", this.key) - .update(stringToSign, "utf8") - .digest("base64"); + BlobClient.prototype.exists = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_2; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobClient-exists", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.getProperties({ + abortSignal: options.abortSignal, + customerProvidedKey: options.customerProvidedKey, + conditions: options.conditions, + tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) + })]; + case 2: + _b.sent(); + return [2 /*return*/, true]; + case 3: + e_2 = _b.sent(); + if (e_2.statusCode === 404) { + span.setStatus({ + code: api.CanonicalCode.NOT_FOUND, + message: "Expected exception when checking blob existence" + }); + return [2 /*return*/, false]; + } + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_2.message + }); + throw e_2; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; - return UserDelegationKeyCredential; -}()); - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -/** - * Generate SasIPRange format string. For example: - * - * "8.8.8.8" or "1.1.1.1-255.255.255.255" - * - * @export - * @param {SasIPRange} ipRange - * @returns {string} - */ -function ipRangeToString(ipRange) { - return ipRange.end ? ipRange.start + "-" + ipRange.end : ipRange.start; -} - -// Copyright (c) Microsoft Corporation. All rights reserved. -(function (SASProtocol) { /** - * Protocol that allows HTTPS only + * Returns all user-defined metadata, standard HTTP properties, and system properties + * for the blob. It does not return the content of the blob. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-properties + * + * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if + * they originally contained uppercase characters. This differs from the metadata keys returned by + * the methods of {@link ContainerClient} that list blobs using the `includeMetadata` option, which + * will retain their original casing. + * + * @param {BlobGetPropertiesOptions} [options] Optional options to Get Properties operation. + * @returns {Promise} + * @memberof BlobClient */ - SASProtocol["Https"] = "https"; + BlobClient.prototype.getProperties = function (options) { + var _a; + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _b, span, spanOptions, res, e_3; + return tslib.__generator(this, function (_c) { + switch (_c.label) { + case 0: + _b = createSpan("BlobClient-getProperties", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; + _c.label = 1; + case 1: + _c.trys.push([1, 3, 4, 5]); + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return [4 /*yield*/, this.blobContext.getProperties({ + abortSignal: options.abortSignal, + leaseAccessConditions: options.conditions, + modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), + cpkInfo: options.customerProvidedKey, + spanOptions: spanOptions + })]; + case 2: + res = _c.sent(); + return [2 /*return*/, tslib.__assign(tslib.__assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) })]; + case 3: + e_3 = _c.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_3.message + }); + throw e_3; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; /** - * Protocol that allows both HTTPS and HTTP - */ - SASProtocol["HttpsAndHttp"] = "https,http"; -})(exports.SASProtocol || (exports.SASProtocol = {})); -/** - * Represents the components that make up an Azure Storage SAS' query parameters. This type is not constructed directly - * by the user; it is only generated by the {@link AccountSASSignatureValues} and {@link BlobSASSignatureValues} - * types. Once generated, it can be encoded into a {@code String} and appended to a URL directly (though caution should - * be taken here in case there are existing query parameters, which might affect the appropriate means of appending - * these query parameters). - * - * NOTE: Instances of this class are immutable. - * - * @export - * @class SASQueryParameters - */ -var SASQueryParameters = /** @class */ (function () { - function SASQueryParameters(version, signature, permissionsOrOptions, services, resourceTypes, protocol, startsOn, expiresOn, ipRange, identifier, resource, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType, userDelegationKey, preauthorizedAgentObjectId, correlationId) { - this.version = version; - this.signature = signature; - if (permissionsOrOptions !== undefined && typeof permissionsOrOptions !== "string") { - // SASQueryParametersOptions - this.permissions = permissionsOrOptions.permissions; - this.services = permissionsOrOptions.services; - this.resourceTypes = permissionsOrOptions.resourceTypes; - this.protocol = permissionsOrOptions.protocol; - this.startsOn = permissionsOrOptions.startsOn; - this.expiresOn = permissionsOrOptions.expiresOn; - this.ipRangeInner = permissionsOrOptions.ipRange; - this.identifier = permissionsOrOptions.identifier; - this.resource = permissionsOrOptions.resource; - this.cacheControl = permissionsOrOptions.cacheControl; - this.contentDisposition = permissionsOrOptions.contentDisposition; - this.contentEncoding = permissionsOrOptions.contentEncoding; - this.contentLanguage = permissionsOrOptions.contentLanguage; - this.contentType = permissionsOrOptions.contentType; - if (permissionsOrOptions.userDelegationKey) { - this.signedOid = permissionsOrOptions.userDelegationKey.signedObjectId; - this.signedTenantId = permissionsOrOptions.userDelegationKey.signedTenantId; - this.signedStartsOn = permissionsOrOptions.userDelegationKey.signedStartsOn; - this.signedExpiresOn = permissionsOrOptions.userDelegationKey.signedExpiresOn; - this.signedService = permissionsOrOptions.userDelegationKey.signedService; - this.signedVersion = permissionsOrOptions.userDelegationKey.signedVersion; - this.preauthorizedAgentObjectId = permissionsOrOptions.preauthorizedAgentObjectId; - this.correlationId = permissionsOrOptions.correlationId; - } - } - else { - this.services = services; - this.resourceTypes = resourceTypes; - this.expiresOn = expiresOn; - this.permissions = permissionsOrOptions; - this.protocol = protocol; - this.startsOn = startsOn; - this.ipRangeInner = ipRange; - this.identifier = identifier; - this.resource = resource; - this.cacheControl = cacheControl; - this.contentDisposition = contentDisposition; - this.contentEncoding = contentEncoding; - this.contentLanguage = contentLanguage; - this.contentType = contentType; - if (userDelegationKey) { - this.signedOid = userDelegationKey.signedObjectId; - this.signedTenantId = userDelegationKey.signedTenantId; - this.signedStartsOn = userDelegationKey.signedStartsOn; - this.signedExpiresOn = userDelegationKey.signedExpiresOn; - this.signedService = userDelegationKey.signedService; - this.signedVersion = userDelegationKey.signedVersion; - this.preauthorizedAgentObjectId = preauthorizedAgentObjectId; - this.correlationId = correlationId; - } - } - } - Object.defineProperty(SASQueryParameters.prototype, "ipRange", { - /** - * Optional. IP range allowed for this SAS. - * - * @readonly - * @type {(SasIPRange | undefined)} - * @memberof SASQueryParameters - */ - get: function () { - if (this.ipRangeInner) { - return { - end: this.ipRangeInner.end, - start: this.ipRangeInner.start - }; - } - return undefined; - }, - enumerable: false, - configurable: true - }); - /** - * Encodes all SAS query parameters into a string that can be appended to a URL. - * - * @returns {string} - * @memberof SASQueryParameters - */ - SASQueryParameters.prototype.toString = function () { - var params = [ - "sv", - "ss", - "srt", - "spr", - "st", - "se", - "sip", - "si", - "skoid", - "sktid", - "skt", - "ske", - "sks", - "skv", - "sr", - "sp", - "sig", - "rscc", - "rscd", - "rsce", - "rscl", - "rsct", - "saoid", - "scid" - ]; - var queries = []; - for (var _i = 0, params_1 = params; _i < params_1.length; _i++) { - var param = params_1[_i]; - switch (param) { - case "sv": - this.tryAppendQueryParameter(queries, param, this.version); - break; - case "ss": - this.tryAppendQueryParameter(queries, param, this.services); - break; - case "srt": - this.tryAppendQueryParameter(queries, param, this.resourceTypes); - break; - case "spr": - this.tryAppendQueryParameter(queries, param, this.protocol); - break; - case "st": - this.tryAppendQueryParameter(queries, param, this.startsOn ? truncatedISO8061Date(this.startsOn, false) : undefined); - break; - case "se": - this.tryAppendQueryParameter(queries, param, this.expiresOn ? truncatedISO8061Date(this.expiresOn, false) : undefined); - break; - case "sip": - this.tryAppendQueryParameter(queries, param, this.ipRange ? ipRangeToString(this.ipRange) : undefined); - break; - case "si": - this.tryAppendQueryParameter(queries, param, this.identifier); - break; - case "skoid": // Signed object ID - this.tryAppendQueryParameter(queries, param, this.signedOid); - break; - case "sktid": // Signed tenant ID - this.tryAppendQueryParameter(queries, param, this.signedTenantId); - break; - case "skt": // Signed key start time - this.tryAppendQueryParameter(queries, param, this.signedStartsOn ? truncatedISO8061Date(this.signedStartsOn, false) : undefined); - break; - case "ske": // Signed key expiry time - this.tryAppendQueryParameter(queries, param, this.signedExpiresOn ? truncatedISO8061Date(this.signedExpiresOn, false) : undefined); - break; - case "sks": // Signed key service - this.tryAppendQueryParameter(queries, param, this.signedService); - break; - case "skv": // Signed key version - this.tryAppendQueryParameter(queries, param, this.signedVersion); - break; - case "sr": - this.tryAppendQueryParameter(queries, param, this.resource); - break; - case "sp": - this.tryAppendQueryParameter(queries, param, this.permissions); - break; - case "sig": - this.tryAppendQueryParameter(queries, param, this.signature); - break; - case "rscc": - this.tryAppendQueryParameter(queries, param, this.cacheControl); - break; - case "rscd": - this.tryAppendQueryParameter(queries, param, this.contentDisposition); - break; - case "rsce": - this.tryAppendQueryParameter(queries, param, this.contentEncoding); - break; - case "rscl": - this.tryAppendQueryParameter(queries, param, this.contentLanguage); - break; - case "rsct": - this.tryAppendQueryParameter(queries, param, this.contentType); - break; - case "saoid": - this.tryAppendQueryParameter(queries, param, this.preauthorizedAgentObjectId); - break; - case "scid": - this.tryAppendQueryParameter(queries, param, this.correlationId); - break; - } - } - return queries.join("&"); - }; - /** - * A private helper method used to filter and append query key/value pairs into an array. - * - * @private - * @param {string[]} queries - * @param {string} key - * @param {string} [value] - * @returns {void} - * @memberof SASQueryParameters - */ - SASQueryParameters.prototype.tryAppendQueryParameter = function (queries, key, value) { - if (!value) { - return; - } - key = encodeURIComponent(key); - value = encodeURIComponent(value); - if (key.length > 0 && value.length > 0) { - queries.push(key + "=" + value); - } - }; - return SASQueryParameters; -}()); - -// Copyright (c) Microsoft Corporation. All rights reserved. -function generateBlobSASQueryParameters(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { - var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; - var sharedKeyCredential = sharedKeyCredentialOrUserDelegationKey instanceof StorageSharedKeyCredential - ? sharedKeyCredentialOrUserDelegationKey - : undefined; - var userDelegationKeyCredential; - if (sharedKeyCredential === undefined && accountName !== undefined) { - userDelegationKeyCredential = new UserDelegationKeyCredential(accountName, sharedKeyCredentialOrUserDelegationKey); - } - if (sharedKeyCredential === undefined && userDelegationKeyCredential === undefined) { - throw TypeError("Invalid sharedKeyCredential, userDelegationKey or accountName."); - } - // Version 2019-12-12 adds support for the blob tags permission. - // Version 2018-11-09 adds support for the signed resource and signed blob snapshot time fields. - // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas#constructing-the-signature-string - if (version >= "2018-11-09") { - if (sharedKeyCredential !== undefined) { - return generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential); - } - else { - // Version 2020-02-10 delegation SAS signature construction includes preauthorizedAgentObjectId, agentObjectId, correlationId. - if (version >= "2020-02-10") { - return generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userDelegationKeyCredential); - } - else { - return generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential); - } - } - } - if (version >= "2015-04-05") { - if (sharedKeyCredential !== undefined) { - return generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential); - } - else { - throw new RangeError("'version' must be >= '2018-11-09' when generating user delegation SAS using user delegation key."); - } - } - throw new RangeError("'version' must be >= '2015-04-05'."); -} -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * IMPLEMENTATION FOR API VERSION FROM 2015-04-05 AND BEFORE 2018-11-09. - * - * Creates an instance of SASQueryParameters. - * - * Only accepts required settings needed to create a SAS. For optional settings please - * set corresponding properties directly, such as permissions, startsOn and identifier. - * - * WARNING: When identifier is not provided, permissions and expiresOn are required. - * You MUST assign value to identifier or expiresOn & permissions manually if you initial with - * this constructor. - * - * @param {BlobSASSignatureValues} blobSASSignatureValues - * @param {StorageSharedKeyCredential} sharedKeyCredential - * @returns {SASQueryParameters} - */ -function generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential) { - blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); - if (!blobSASSignatureValues.identifier && - !(blobSASSignatureValues.permissions && blobSASSignatureValues.expiresOn)) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); - } - var resource = "c"; - if (blobSASSignatureValues.blobName) { - resource = "b"; - } - // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; - if (blobSASSignatureValues.permissions) { - if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - else { - verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - } - // Signature is generated on the un-url-encoded values. - var stringToSign = [ - verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn - ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) - : "", - blobSASSignatureValues.expiresOn - ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) - : "", - getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), - blobSASSignatureValues.identifier, - blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", - blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", - blobSASSignatureValues.version, - blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", - blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", - blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", - blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", - blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" - ].join("\n"); - var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); -} -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. - * - * Creates an instance of SASQueryParameters. - * - * Only accepts required settings needed to create a SAS. For optional settings please - * set corresponding properties directly, such as permissions, startsOn and identifier. - * - * WARNING: When identifier is not provided, permissions and expiresOn are required. - * You MUST assign value to identifier or expiresOn & permissions manually if you initial with - * this constructor. - * - * @param {BlobSASSignatureValues} blobSASSignatureValues - * @param {StorageSharedKeyCredential} sharedKeyCredential - * @returns {SASQueryParameters} - */ -function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential) { - blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); - if (!blobSASSignatureValues.identifier && - !(blobSASSignatureValues.permissions && blobSASSignatureValues.expiresOn)) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); - } - var resource = "c"; - var timestamp = blobSASSignatureValues.snapshotTime; - if (blobSASSignatureValues.blobName) { - resource = "b"; - if (blobSASSignatureValues.snapshotTime) { - resource = "bs"; - } - else if (blobSASSignatureValues.versionId) { - resource = "bv"; - timestamp = blobSASSignatureValues.versionId; - } - } - // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; - if (blobSASSignatureValues.permissions) { - if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - else { - verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - } - // Signature is generated on the un-url-encoded values. - var stringToSign = [ - verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn - ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) - : "", - blobSASSignatureValues.expiresOn - ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) - : "", - getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), - blobSASSignatureValues.identifier, - blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", - blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", - blobSASSignatureValues.version, - resource, - timestamp, - blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", - blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", - blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", - blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", - blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" - ].join("\n"); - var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); -} -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. - * - * Creates an instance of SASQueryParameters. - * - * Only accepts required settings needed to create a SAS. For optional settings please - * set corresponding properties directly, such as permissions, startsOn. - * - * WARNING: identifier will be ignored, permissions and expiresOn are required. - * - * @param {BlobSASSignatureValues} blobSASSignatureValues - * @param {UserDelegationKeyCredential} userDelegationKeyCredential - * @returns {SASQueryParameters} - */ -function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential) { - blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); - // Stored access policies are not supported for a user delegation SAS. - if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); - } - var resource = "c"; - var timestamp = blobSASSignatureValues.snapshotTime; - if (blobSASSignatureValues.blobName) { - resource = "b"; - if (blobSASSignatureValues.snapshotTime) { - resource = "bs"; - } - else if (blobSASSignatureValues.versionId) { - resource = "bv"; - timestamp = blobSASSignatureValues.versionId; - } - } - // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; - if (blobSASSignatureValues.permissions) { - if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - else { - verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - } - // Signature is generated on the un-url-encoded values. - var stringToSign = [ - verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn - ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) - : "", - blobSASSignatureValues.expiresOn - ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) - : "", - getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), - userDelegationKeyCredential.userDelegationKey.signedObjectId, - userDelegationKeyCredential.userDelegationKey.signedTenantId, - userDelegationKeyCredential.userDelegationKey.signedStartsOn - ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) - : "", - userDelegationKeyCredential.userDelegationKey.signedExpiresOn - ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) - : "", - userDelegationKeyCredential.userDelegationKey.signedService, - userDelegationKeyCredential.userDelegationKey.signedVersion, - blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", - blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", - blobSASSignatureValues.version, - resource, - timestamp, - blobSASSignatureValues.cacheControl, - blobSASSignatureValues.contentDisposition, - blobSASSignatureValues.contentEncoding, - blobSASSignatureValues.contentLanguage, - blobSASSignatureValues.contentType - ].join("\n"); - var signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey); -} -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * IMPLEMENTATION FOR API VERSION FROM 2020-02-10. - * - * Creates an instance of SASQueryParameters. - * - * Only accepts required settings needed to create a SAS. For optional settings please - * set corresponding properties directly, such as permissions, startsOn. - * - * WARNING: identifier will be ignored, permissions and expiresOn are required. - * - * @param {BlobSASSignatureValues} blobSASSignatureValues - * @param {UserDelegationKeyCredential} userDelegationKeyCredential - * @returns {SASQueryParameters} - */ -function generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userDelegationKeyCredential) { - blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); - // Stored access policies are not supported for a user delegation SAS. - if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { - throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); - } - var resource = "c"; - var timestamp = blobSASSignatureValues.snapshotTime; - if (blobSASSignatureValues.blobName) { - resource = "b"; - if (blobSASSignatureValues.snapshotTime) { - resource = "bs"; - } - else if (blobSASSignatureValues.versionId) { - resource = "bv"; - timestamp = blobSASSignatureValues.versionId; - } - } - // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; - if (blobSASSignatureValues.permissions) { - if (blobSASSignatureValues.blobName) { - verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - else { - verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); - } - } - // Signature is generated on the un-url-encoded values. - var stringToSign = [ - verifiedPermissions ? verifiedPermissions : "", - blobSASSignatureValues.startsOn - ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) - : "", - blobSASSignatureValues.expiresOn - ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) - : "", - getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), - userDelegationKeyCredential.userDelegationKey.signedObjectId, - userDelegationKeyCredential.userDelegationKey.signedTenantId, - userDelegationKeyCredential.userDelegationKey.signedStartsOn - ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) - : "", - userDelegationKeyCredential.userDelegationKey.signedExpiresOn - ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) - : "", - userDelegationKeyCredential.userDelegationKey.signedService, - userDelegationKeyCredential.userDelegationKey.signedVersion, - blobSASSignatureValues.preauthorizedAgentObjectId, - undefined, - blobSASSignatureValues.correlationId, - blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", - blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", - blobSASSignatureValues.version, - resource, - timestamp, - blobSASSignatureValues.cacheControl, - blobSASSignatureValues.contentDisposition, - blobSASSignatureValues.contentEncoding, - blobSASSignatureValues.contentLanguage, - blobSASSignatureValues.contentType - ].join("\n"); - var signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId); -} -function getCanonicalName(accountName, containerName, blobName) { - // Container: "/blob/account/containerName" - // Blob: "/blob/account/containerName/blobName" - var elements = ["/blob/" + accountName + "/" + containerName]; - if (blobName) { - elements.push("/" + blobName); - } - return elements.join(""); -} -function SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues) { - var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; - if (blobSASSignatureValues.snapshotTime && version < "2018-11-09") { - throw RangeError("'version' must be >= '2018-11-09' when providing 'snapshotTime'."); - } - if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.snapshotTime) { - throw RangeError("Must provide 'blobName' when providing 'snapshotTime'."); - } - if (blobSASSignatureValues.versionId && version < "2019-10-10") { - throw RangeError("'version' must be >= '2019-10-10' when providing 'versionId'."); - } - if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.versionId) { - throw RangeError("Must provide 'blobName' when providing 'versionId'."); - } - if (blobSASSignatureValues.permissions && - blobSASSignatureValues.permissions.deleteVersion && - version < "2019-10-10") { - throw RangeError("'version' must be >= '2019-10-10' when providing 'x' permission."); - } - if (blobSASSignatureValues.permissions && - blobSASSignatureValues.permissions.tag && - version < "2019-12-12") { - throw RangeError("'version' must be >= '2019-12-12' when providing 't' permission."); - } - if (version < "2020-02-10" && - blobSASSignatureValues.permissions && - (blobSASSignatureValues.permissions.move || blobSASSignatureValues.permissions.execute)) { - throw RangeError("'version' must be >= '2020-02-10' when providing the 'm' or 'e' permission."); - } - if (version < "2020-02-10" && - (blobSASSignatureValues.preauthorizedAgentObjectId || blobSASSignatureValues.correlationId)) { - throw RangeError("'version' must be >= '2020-02-10' when providing 'preauthorizedAgentObjectId' or 'correlationId'."); - } - blobSASSignatureValues.version = version; - return blobSASSignatureValues; -} - -/** - * A BlobClient represents a URL to an Azure Storage blob; the blob may be a block blob, - * append blob, or page blob. - * - * @export - * @class BlobClient - */ -var BlobClient = /** @class */ (function (_super) { - tslib.__extends(BlobClient, _super); - function BlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { - var _a; - var _this = this; - options = options || {}; - var pipeline; - var url; - if (credentialOrPipelineOrContainerName instanceof Pipeline) { - // (url: string, pipeline: Pipeline) - url = urlOrConnectionString; - pipeline = credentialOrPipelineOrContainerName; - } - else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || - credentialOrPipelineOrContainerName instanceof AnonymousCredential || - coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { - // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) - url = urlOrConnectionString; - options = blobNameOrOptions; - pipeline = newPipeline(credentialOrPipelineOrContainerName, options); - } - else if (!credentialOrPipelineOrContainerName && - typeof credentialOrPipelineOrContainerName !== "string") { - // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) - // The second parameter is undefined. Use anonymous credential. - url = urlOrConnectionString; - pipeline = newPipeline(new AnonymousCredential(), options); - } - else if (credentialOrPipelineOrContainerName && - typeof credentialOrPipelineOrContainerName === "string" && - blobNameOrOptions && - typeof blobNameOrOptions === "string") { - // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) - var containerName = credentialOrPipelineOrContainerName; - var blobName = blobNameOrOptions; - var extractedCreds = extractConnectionStringParts(urlOrConnectionString); - if (extractedCreds.kind === "AccountConnString") { - { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); - options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); - pipeline = newPipeline(sharedKeyCredential, options); - } - } - else if (extractedCreds.kind === "SASConnString") { - url = - appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + - "?" + - extractedCreds.accountSas; - pipeline = newPipeline(new AnonymousCredential(), options); - } - else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); - } - } - else { - throw new Error("Expecting non-empty strings for containerName and blobName parameters"); - } - _this = _super.call(this, url, pipeline) || this; - (_a = _this.getBlobAndContainerNamesFromUrl(), _this._name = _a.blobName, _this._containerName = _a.containerName); - _this.blobContext = new Blob$1(_this.storageClientContext); - _this._snapshot = getURLParameter(_this.url, URLConstants.Parameters.SNAPSHOT); - _this._versionId = getURLParameter(_this.url, URLConstants.Parameters.VERSIONID); - return _this; - } - Object.defineProperty(BlobClient.prototype, "name", { - /** - * The name of the blob. - */ - get: function () { - return this._name; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobClient.prototype, "containerName", { - /** - * The name of the storage container the blob is associated with. - */ - get: function () { - return this._containerName; - }, - enumerable: false, - configurable: true - }); - /** - * Creates a new BlobClient object identical to the source but with the specified snapshot timestamp. - * Provide "" will remove the snapshot and return a Client to the base blob. - * - * @param {string} snapshot The snapshot timestamp. - * @returns {BlobClient} A new BlobClient object identical to the source but with the specified snapshot timestamp - * @memberof BlobClient - */ - BlobClient.prototype.withSnapshot = function (snapshot) { - return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); - }; - /** - * Creates a new BlobClient object pointing to a version of this blob. - * Provide "" will remove the versionId and return a Client to the base blob. - * - * @param {string} versionId The versionId. - * @returns {BlobClient} A new BlobClient object pointing to the version of this blob. - * @memberof BlobClient - */ - BlobClient.prototype.withVersion = function (versionId) { - return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.VERSIONID, versionId.length === 0 ? undefined : versionId), this.pipeline); - }; - /** - * Creates a AppendBlobClient object. - * - * @returns {AppendBlobClient} - * @memberof BlobClient - */ - BlobClient.prototype.getAppendBlobClient = function () { - return new AppendBlobClient(this.url, this.pipeline); - }; - /** - * Creates a BlockBlobClient object. - * - * @returns {BlockBlobClient} - * @memberof BlobClient - */ - BlobClient.prototype.getBlockBlobClient = function () { - return new BlockBlobClient(this.url, this.pipeline); - }; - /** - * Creates a PageBlobClient object. - * - * @returns {PageBlobClient} - * @memberof BlobClient - */ - BlobClient.prototype.getPageBlobClient = function () { - return new PageBlobClient(this.url, this.pipeline); - }; - /** - * Reads or downloads a blob from the system, including its metadata and properties. - * You can also call Get Blob to read a snapshot. - * - * * In Node.js, data returns in a Readable stream readableStreamBody - * * In browsers, data returns in a promise blobBody - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob - * - * @param {number} [offset] From which position of the blob to download, >= 0 - * @param {number} [count] How much data to be downloaded, > 0. Will download to the end when undefined - * @param {BlobDownloadOptions} [options] Optional options to Blob Download operation. - * @returns {Promise} - * @memberof BlobClient - * - * Example usage (Node.js): - * - * ```js - * // Download and convert a blob to a string - * const downloadBlockBlobResponse = await blobClient.download(); - * const downloaded = await streamToBuffer(downloadBlockBlobResponse.readableStreamBody); - * console.log("Downloaded blob content:", downloaded.toString()); - * - * async function streamToBuffer(readableStream) { - * return new Promise((resolve, reject) => { - * const chunks = []; - * readableStream.on("data", (data) => { - * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); - * }); - * readableStream.on("end", () => { - * resolve(Buffer.concat(chunks)); - * }); - * readableStream.on("error", reject); - * }); - * } - * ``` - * - * Example usage (browser): - * - * ```js - * // Download and convert a blob to a string - * const downloadBlockBlobResponse = await blobClient.download(); - * const downloaded = await blobToString(await downloadBlockBlobResponse.blobBody); - * console.log( - * "Downloaded blob content", - * downloaded - * ); - * - * async function blobToString(blob: Blob): Promise { - * const fileReader = new FileReader(); - * return new Promise((resolve, reject) => { - * fileReader.onloadend = (ev: any) => { - * resolve(ev.target!.result); - * }; - * fileReader.onerror = reject; - * fileReader.readAsText(blob); - * }); - * } - * ``` - */ - BlobClient.prototype.download = function (offset, count, options) { - var _a; - if (offset === void 0) { offset = 0; } - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, res_1, wrappedRes, e_1; - var _this = this; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - options.conditions = options.conditions || {}; - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - _b = createSpan("BlobClient-download", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.download({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - onDownloadProgress: coreHttp.isNode ? undefined : options.onProgress, - range: offset === 0 && !count ? undefined : rangeToString({ offset: offset, count: count }), - rangeGetContentMD5: options.rangeGetContentMD5, - rangeGetContentCRC64: options.rangeGetContentCrc64, - snapshot: options.snapshot, - cpkInfo: options.customerProvidedKey, - spanOptions: spanOptions - })]; - case 2: - res_1 = _c.sent(); - wrappedRes = tslib.__assign(tslib.__assign({}, res_1), { _response: res_1._response, objectReplicationDestinationPolicyId: res_1.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res_1.objectReplicationRules) }); - // We support retrying when download stream unexpected ends in Node.js runtime - // Following code shouldn't be bundled into browser build, however some - // bundlers may try to bundle following code and "FileReadResponse.ts". - // In this case, "FileDownloadResponse.browser.ts" will be used as a shim of "FileDownloadResponse.ts" - // The config is in package.json "browser" field - if (options.maxRetryRequests === undefined || options.maxRetryRequests < 0) { - // TODO: Default value or make it a required parameter? - options.maxRetryRequests = DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS; - } - if (res_1.contentLength === undefined) { - throw new RangeError("File download response doesn't contain valid content length header"); - } - if (!res_1.etag) { - throw new RangeError("File download response doesn't contain valid etag header"); - } - return [2 /*return*/, new BlobDownloadResponse(wrappedRes, function (start) { return tslib.__awaiter(_this, void 0, void 0, function () { - var updatedOptions; - var _a; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - updatedOptions = { - leaseAccessConditions: options.conditions, - modifiedAccessConditions: { - ifMatch: options.conditions.ifMatch || res_1.etag, - ifModifiedSince: options.conditions.ifModifiedSince, - ifNoneMatch: options.conditions.ifNoneMatch, - ifUnmodifiedSince: options.conditions.ifUnmodifiedSince, - ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions - }, - range: rangeToString({ - count: offset + res_1.contentLength - start, - offset: start - }), - rangeGetContentMD5: options.rangeGetContentMD5, - rangeGetContentCRC64: options.rangeGetContentCrc64, - snapshot: options.snapshot, - cpkInfo: options.customerProvidedKey - }; - return [4 /*yield*/, this.blobContext.download(tslib.__assign({ abortSignal: options.abortSignal }, updatedOptions))]; - case 1: - // Debug purpose only - // console.log( - // `Read from internal stream, range: ${ - // updatedOptions.range - // }, options: ${JSON.stringify(updatedOptions)}` - // ); - return [2 /*return*/, (_b.sent()).readableStreamBody]; - } - }); - }); }, offset, res_1.contentLength, { - maxRetryRequests: options.maxRetryRequests, - onProgress: options.onProgress - })]; - case 3: - e_1 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_1.message - }); - throw e_1; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; - /** - * Returns true if the Azure blob resource represented by this client exists; false otherwise. - * - * NOTE: use this function with care since an existing blob might be deleted by other clients or - * applications. Vice versa new blobs might be added by other clients or applications after this - * function completes. - * - * @param {BlobExistsOptions} [options] options to Exists operation. - * @returns {Promise} - * @memberof BlobClient - */ - BlobClient.prototype.exists = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_2; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobClient-exists", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.getProperties({ - abortSignal: options.abortSignal, - customerProvidedKey: options.customerProvidedKey, - conditions: options.conditions, - tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) - })]; - case 2: - _b.sent(); - return [2 /*return*/, true]; - case 3: - e_2 = _b.sent(); - if (e_2.statusCode === 404) { - span.setStatus({ - code: api.CanonicalCode.NOT_FOUND, - message: "Expected exception when checking blob existence" - }); - return [2 /*return*/, false]; - } - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_2.message - }); - throw e_2; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; - /** - * Returns all user-defined metadata, standard HTTP properties, and system properties - * for the blob. It does not return the content of the blob. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-properties - * - * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if - * they originally contained uppercase characters. This differs from the metadata keys returned by - * the methods of {@link ContainerClient} that list blobs using the `includeMetadata` option, which - * will retain their original casing. - * - * @param {BlobGetPropertiesOptions} [options] Optional options to Get Properties operation. - * @returns {Promise} - * @memberof BlobClient - */ - BlobClient.prototype.getProperties = function (options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, res, e_3; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-getProperties", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - options.conditions = options.conditions || {}; - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blobContext.getProperties({ - abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, - modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), - cpkInfo: options.customerProvidedKey, - spanOptions: spanOptions - })]; - case 2: - res = _c.sent(); - return [2 /*return*/, tslib.__assign(tslib.__assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) })]; - case 3: - e_3 = _c.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_3.message - }); - throw e_3; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; - /** - * Marks the specified blob or snapshot for deletion. The blob is later deleted - * during garbage collection. Note that in order to delete a blob, you must delete - * all of its snapshots. You can delete both at the same time with the Delete - * Blob operation. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob - * - * @param {BlobDeleteOptions} [options] Optional options to Blob Delete operation. - * @returns {Promise} - * @memberof BlobClient + * Marks the specified blob or snapshot for deletion. The blob is later deleted + * during garbage collection. Note that in order to delete a blob, you must delete + * all of its snapshots. You can delete both at the same time with the Delete + * Blob operation. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob + * + * @param {BlobDeleteOptions} [options] Optional options to Blob Delete operation. + * @returns {Promise} + * @memberof BlobClient */ BlobClient.prototype.delete = function (options) { var _a; @@ -29866,7 +28447,6 @@ var BlobClient = /** @class */ (function (_super) { _c.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.blobContext.setTags({ abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), spanOptions: spanOptions, tags: toBlobTags(tags) @@ -29908,7 +28488,6 @@ var BlobClient = /** @class */ (function (_super) { _c.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.blobContext.getTags({ abortSignal: options.abortSignal, - leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), spanOptions: spanOptions })]; @@ -30476,7 +29055,10 @@ var BlobClient = /** @class */ (function (_super) { // Azure Storage Server will replace "\" with "/" in the blob names // doing the same in the SDK side so that the user doesn't have to replace "\" instances in the blobName blobName = blobName.replace(/\\/g, "/"); - if (!containerName) { + if (!blobName) { + throw new Error("Provided blobName is invalid."); + } + else if (!containerName) { throw new Error("Provided containerName is invalid."); } return { blobName: blobName, containerName: containerName }; @@ -30548,28 +29130,6 @@ var BlobClient = /** @class */ (function (_super) { }); }); }; - /** - * Only available for BlobClient constructed with a shared key credential. - * - * Generates a Blob Service Shared Access Signature (SAS) URI based on the client properties - * and parameters passed in. The SAS is signed by the shared key credential of the client. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas - * - * @param {BlobGenerateSasUrlOptions} options Optional parameters. - * @returns {Promise} The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. - * @memberof BlobClient - */ - BlobClient.prototype.generateSasUrl = function (options) { - var _this = this; - return new Promise(function (resolve) { - if (!(_this.credential instanceof StorageSharedKeyCredential)) { - throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); - } - var sas = generateBlobSASQueryParameters(tslib.__assign({ containerName: _this._containerName, blobName: _this._name, snapshotTime: _this._snapshot, versionId: _this._versionId }, options), _this.credential).toString(); - resolve(appendToURLQuery(_this.url, sas)); - }); - }; return BlobClient; }(StorageClient)); /** @@ -31168,63 +29728,6 @@ var BlockBlobClient = /** @class */ (function (_super) { }); }); }; - /** - * Creates a new Block Blob where the contents of the blob are read from a given URL. - * This API is supported beginning with the 2020-04-08 version. Partial updates - * are not supported with Put Blob from URL; the content of an existing blob is overwritten with - * the content of the new blob. To perform partial updates to a block blob’s contents using a - * source URL, use {@link stageBlockFromURL} and {@link commitBlockList}. - * - * @param {string} sourceURL Specifies the URL of the blob. The value - * may be a URL of up to 2 KB in length that specifies a blob. - * The value should be URL-encoded as it would appear - * in a request URI. The source blob must either be public - * or must be authenticated via a shared access signature. - * If the source blob is public, no authentication is required - * to perform the operation. Here are some examples of source object URLs: - * - https://myaccount.blob.core.windows.net/mycontainer/myblob - * - https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= - * @param {BlockBlobSyncUploadFromURLOptions} [options={}] Optional parameters. - * @returns Promise - * @memberof BlockBlobClient - */ - BlockBlobClient.prototype.syncUploadFromURL = function (sourceURL, options) { - var _a, _b, _c, _d, _e; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _f, span, spanOptions, e_25; - return tslib.__generator(this, function (_g) { - switch (_g.label) { - case 0: - options.conditions = options.conditions || {}; - _f = createSpan("BlockBlobClient-syncUploadFromURL", options.tracingOptions), span = _f.span, spanOptions = _f.spanOptions; - _g.label = 1; - case 1: - _g.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blockBlobContext.putBlobFromUrl(0, sourceURL, tslib.__assign(tslib.__assign({}, options), { leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: options.conditions.tagConditions }), sourceModifiedAccessConditions: { - sourceIfMatch: (_a = options.sourceConditions) === null || _a === void 0 ? void 0 : _a.ifMatch, - sourceIfModifiedSince: (_b = options.sourceConditions) === null || _b === void 0 ? void 0 : _b.ifModifiedSince, - sourceIfNoneMatch: (_c = options.sourceConditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch, - sourceIfUnmodifiedSince: (_d = options.sourceConditions) === null || _d === void 0 ? void 0 : _d.ifUnmodifiedSince, - sourceIfTags: (_e = options.sourceConditions) === null || _e === void 0 ? void 0 : _e.tagConditions - }, cpkInfo: options.customerProvidedKey, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), spanOptions: spanOptions }))]; - case 2: return [2 /*return*/, _g.sent()]; - case 3: - e_25 = _g.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_25.message - }); - throw e_25; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); - }; /** * Uploads the specified block to the block blob's "staging area" to be later * committed by a call to commitBlockList. @@ -31240,7 +29743,7 @@ var BlockBlobClient = /** @class */ (function (_super) { BlockBlobClient.prototype.stageBlock = function (blockId, body, contentLength, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_26; + var _a, span, spanOptions, e_25; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: @@ -31261,12 +29764,12 @@ var BlockBlobClient = /** @class */ (function (_super) { })]; case 2: return [2 /*return*/, _b.sent()]; case 3: - e_26 = _b.sent(); + e_25 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_26.message + message: e_25.message }); - throw e_26; + throw e_25; case 4: span.end(); return [7 /*endfinally*/]; @@ -31301,7 +29804,7 @@ var BlockBlobClient = /** @class */ (function (_super) { if (offset === void 0) { offset = 0; } if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_27; + var _a, span, spanOptions, e_26; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: @@ -31322,12 +29825,12 @@ var BlockBlobClient = /** @class */ (function (_super) { })]; case 2: return [2 /*return*/, _b.sent()]; case 3: - e_27 = _b.sent(); + e_26 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_27.message + message: e_26.message }); - throw e_27; + throw e_26; case 4: span.end(); return [7 /*endfinally*/]; @@ -31353,7 +29856,7 @@ var BlockBlobClient = /** @class */ (function (_super) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, e_28; + var _b, span, spanOptions, e_27; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: @@ -31377,12 +29880,12 @@ var BlockBlobClient = /** @class */ (function (_super) { })]; case 2: return [2 /*return*/, _c.sent()]; case 3: - e_28 = _c.sent(); + e_27 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_28.message + message: e_27.message }); - throw e_28; + throw e_27; case 4: span.end(); return [7 /*endfinally*/]; @@ -31406,7 +29909,7 @@ var BlockBlobClient = /** @class */ (function (_super) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, spanOptions, res, e_29; + var _b, span, spanOptions, res, e_28; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: @@ -31430,12 +29933,12 @@ var BlockBlobClient = /** @class */ (function (_super) { } return [2 /*return*/, res]; case 3: - e_29 = _c.sent(); + e_28 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_29.message + message: e_28.message }); - throw e_29; + throw e_28; case 4: span.end(); return [7 /*endfinally*/]; @@ -31445,56 +29948,6 @@ var BlockBlobClient = /** @class */ (function (_super) { }); }; // High level functions - /** - * Uploads a Buffer(Node.js)/Blob(browsers)/ArrayBuffer/ArrayBufferView object to a BlockBlob. - * - * When data length is no more than the specifiled {@link BlockBlobParallelUploadOptions.maxSingleShotSize} (default is - * {@link BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}), this method will use 1 {@link upload} call to finish the upload. - * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList} - * to commit the block list. - * - * @export - * @param {Buffer | Blob | ArrayBuffer | ArrayBufferView} data Buffer(Node.js), Blob, ArrayBuffer or ArrayBufferView - * @param {BlockBlobParallelUploadOptions} [options] - * @returns {Promise} - * @memberof BlockBlobClient - */ - BlockBlobClient.prototype.uploadData = function (data, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, buffer_1, browserBlob_1; - return tslib.__generator(this, function (_b) { - _a = createSpan("BlockBlobClient-uploadData", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - try { - if (true) { - if (data instanceof Buffer) { - buffer_1 = data; - } - else if (data instanceof ArrayBuffer) { - buffer_1 = Buffer.from(data); - } - else { - data = data; - buffer_1 = Buffer.from(data.buffer, data.byteOffset, data.byteLength); - } - return [2 /*return*/, this.uploadSeekableInternal(function (offset, size) { return buffer_1.slice(offset, offset + size); }, buffer_1.byteLength, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - } - else {} - } - catch (e) { - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e.message - }); - throw e; - } - finally { - span.end(); - } - return [2 /*return*/]; - }); - }); - }; /** * ONLY AVAILABLE IN BROWSERS. * @@ -31504,8 +29957,6 @@ var BlockBlobClient = /** @class */ (function (_super) { * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call * {@link commitBlockList} to commit the block list. * - * @deprecated Use {@link uploadData} instead. - * * @export * @param {Blob | ArrayBuffer | ArrayBufferView} browserData Blob, File, ArrayBuffer or ArrayBufferView * @param {BlockBlobParallelUploadOptions} [options] Options to upload browser data. @@ -31515,7 +29966,7 @@ var BlockBlobClient = /** @class */ (function (_super) { BlockBlobClient.prototype.uploadBrowserData = function (browserData, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, browserBlob_2, e_30; + var _a, span, spanOptions, browserBlob_1, e_29; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: @@ -31523,16 +29974,18 @@ var BlockBlobClient = /** @class */ (function (_super) { _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - browserBlob_2 = new Blob([browserData]); - return [4 /*yield*/, this.uploadSeekableInternal(function (offset, size) { return browserBlob_2.slice(offset, offset + size); }, browserBlob_2.size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + browserBlob_1 = new Blob([browserData]); + return [4 /*yield*/, this.uploadSeekableBlob(function (offset, size) { + return browserBlob_1.slice(offset, offset + size); + }, browserBlob_1.size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: return [2 /*return*/, _b.sent()]; case 3: - e_30 = _b.sent(); + e_29 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_30.message + message: e_29.message }); - throw e_30; + throw e_29; case 4: span.end(); return [7 /*endfinally*/]; @@ -31542,25 +29995,25 @@ var BlockBlobClient = /** @class */ (function (_super) { }); }; /** + * ONLY AVAILABLE IN BROWSERS. * - * Uploads data to block blob. Requires a bodyFactory as the data source, - * which need to return a {@link HttpRequestBody} object with the offset and size provided. + * Uploads a browser {@link Blob} object to block blob. Requires a blobFactory as the data source, + * which need to return a {@link Blob} object with the offset and size provided. * - * When data length is no more than the specifiled {@link BlockBlobParallelUploadOptions.maxSingleShotSize} (default is - * {@link BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}), this method will use 1 {@link upload} call to finish the upload. - * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList} + * When buffer length <= 256MB, this method will use 1 upload call to finish the upload. + * Otherwise, this method will call stageBlock to upload blocks, and finally call commitBlockList * to commit the block list. * - * @param {(offset: number, size: number) => HttpRequestBody} bodyFactory + * @param {(offset: number, size: number) => Blob} blobFactory * @param {number} size size of the data to upload. * @param {BlockBlobParallelUploadOptions} [options] Options to Upload to Block Blob operation. * @returns {Promise} Response data for the Blob Upload operation. * @memberof BlockBlobClient */ - BlockBlobClient.prototype.uploadSeekableInternal = function (bodyFactory, size, options) { + BlockBlobClient.prototype.uploadSeekableBlob = function (blobFactory, size, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, numBlocks_1, blockList_1, blockIDPrefix_1, transferProgress_2, batch, _loop_2, i, e_31; + var _a, span, spanOptions, numBlocks_1, blockList_1, blockIDPrefix_1, transferProgress_2, batch, _loop_2, i, e_30; var _this = this; return tslib.__generator(this, function (_b) { switch (_b.label) { @@ -31595,12 +30048,12 @@ var BlockBlobClient = /** @class */ (function (_super) { if (!options.conditions) { options.conditions = {}; } - _a = createSpan("BlockBlobClient-uploadSeekableInternal", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("BlockBlobClient-UploadSeekableBlob", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 5, 6, 7]); if (!(size <= options.maxSingleShotSize)) return [3 /*break*/, 3]; - return [4 /*yield*/, this.upload(bodyFactory(0, size), size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + return [4 /*yield*/, this.upload(blobFactory(0, size), size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: return [2 /*return*/, _b.sent()]; case 3: numBlocks_1 = Math.floor((size - 1) / options.blockSize) + 1; @@ -31623,7 +30076,7 @@ var BlockBlobClient = /** @class */ (function (_super) { end = i === numBlocks_1 - 1 ? size : start + options.blockSize; contentLength = end - start; blockList_1.push(blockID); - return [4 /*yield*/, this.stageBlock(blockID, bodyFactory(start, contentLength), contentLength, { + return [4 /*yield*/, this.stageBlock(blockID, blobFactory(start, contentLength), contentLength, { abortSignal: options.abortSignal, conditions: options.conditions, encryptionScope: options.encryptionScope, @@ -31652,12 +30105,12 @@ var BlockBlobClient = /** @class */ (function (_super) { _b.sent(); return [2 /*return*/, this.commitBlockList(blockList_1, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 5: - e_31 = _b.sent(); + e_30 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_31.message + message: e_30.message }); - throw e_31; + throw e_30; case 6: span.end(); return [7 /*endfinally*/]; @@ -31683,7 +30136,7 @@ var BlockBlobClient = /** @class */ (function (_super) { BlockBlobClient.prototype.uploadFile = function (filePath, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, size, e_32; + var _a, span, spanOptions, size, e_31; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: @@ -31694,23 +30147,21 @@ var BlockBlobClient = /** @class */ (function (_super) { return [4 /*yield*/, fsStat(filePath)]; case 2: size = (_b.sent()).size; - return [4 /*yield*/, this.uploadSeekableInternal(function (offset, count) { - return function () { - return fsCreateReadStream(filePath, { - autoClose: true, - end: count ? offset + count - 1 : Infinity, - start: offset - }); - }; + return [4 /*yield*/, this.uploadResetableStream(function (offset, count) { + return fsCreateReadStream(filePath, { + autoClose: true, + end: count ? offset + count - 1 : Infinity, + start: offset + }); }, size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 3: return [2 /*return*/, _b.sent()]; case 4: - e_32 = _b.sent(); + e_31 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_32.message + message: e_31.message }); - throw e_32; + throw e_31; case 5: span.end(); return [7 /*endfinally*/]; @@ -31741,7 +30192,7 @@ var BlockBlobClient = /** @class */ (function (_super) { if (maxConcurrency === void 0) { maxConcurrency = 5; } if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, blockNum_1, blockIDPrefix_2, transferProgress_3, blockList_2, scheduler, e_33; + var _a, span, spanOptions, blockNum_1, blockIDPrefix_2, transferProgress_3, blockList_2, scheduler, e_32; var _this = this; return tslib.__generator(this, function (_b) { switch (_b.label) { @@ -31795,16 +30246,142 @@ var BlockBlobClient = /** @class */ (function (_super) { return [4 /*yield*/, this.commitBlockList(blockList_2, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 3: return [2 /*return*/, _b.sent()]; case 4: + e_32 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_32.message + }); + throw e_32; + case 5: + span.end(); + return [7 /*endfinally*/]; + case 6: return [2 /*return*/]; + } + }); + }); + }; + /** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * Accepts a Node.js Readable stream factory, and uploads in blocks to a block blob. + * The Readable stream factory must returns a Node.js Readable stream starting from the offset defined. The offset + * is the offset in the block blob to be uploaded. + * + * When buffer length <= 256MB, this method will use 1 upload call to finish the upload. + * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList} + * to commit the block list. + * + * @export + * @param {(offset: number) => NodeJS.ReadableStream} streamFactory Returns a Node.js Readable stream starting + * from the offset defined + * @param {number} size Size of the block blob + * @param {BlockBlobParallelUploadOptions} [options] Options to Upload to Block Blob operation. + * @returns {(Promise)} Response data for the Blob Upload operation. + * @memberof BlockBlobClient + */ + BlockBlobClient.prototype.uploadResetableStream = function (streamFactory, size, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, numBlocks_2, blockList_3, blockIDPrefix_3, transferProgress_4, batch, _loop_3, i, e_33; + var _this = this; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!options.blockSize) { + options.blockSize = 0; + } + if (options.blockSize < 0 || options.blockSize > BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES) { + throw new RangeError("blockSize option must be >= 0 and <= " + BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES); + } + if (options.maxSingleShotSize !== 0 && !options.maxSingleShotSize) { + options.maxSingleShotSize = BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES; + } + if (options.maxSingleShotSize < 0 || + options.maxSingleShotSize > BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES) { + throw new RangeError("maxSingleShotSize option must be >= 0 and <= " + BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES); + } + if (options.blockSize === 0) { + if (size > BLOCK_BLOB_MAX_BLOCKS * BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES) { + throw new RangeError(size + " is too larger to upload to a block blob."); + } + if (size > options.maxSingleShotSize) { + options.blockSize = Math.ceil(size / BLOCK_BLOB_MAX_BLOCKS); + if (options.blockSize < DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES) { + options.blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; + } + } + } + if (!options.blobHTTPHeaders) { + options.blobHTTPHeaders = {}; + } + if (!options.conditions) { + options.conditions = {}; + } + _a = createSpan("BlockBlobClient-uploadResetableStream", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 6, 7, 8]); + if (!(size <= options.maxSingleShotSize)) return [3 /*break*/, 3]; + return [4 /*yield*/, this.upload(function () { return streamFactory(0); }, size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + numBlocks_2 = Math.floor((size - 1) / options.blockSize) + 1; + if (numBlocks_2 > BLOCK_BLOB_MAX_BLOCKS) { + throw new RangeError("The buffer's size is too big or the BlockSize is too small;" + + ("the number of blocks must be <= " + BLOCK_BLOB_MAX_BLOCKS)); + } + blockList_3 = []; + blockIDPrefix_3 = coreHttp.generateUuid(); + transferProgress_4 = 0; + batch = new Batch(options.concurrency); + _loop_3 = function (i) { + batch.addOperation(function () { return tslib.__awaiter(_this, void 0, void 0, function () { + var blockID, start, end, contentLength; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + blockID = generateBlockID(blockIDPrefix_3, i); + start = options.blockSize * i; + end = i === numBlocks_2 - 1 ? size : start + options.blockSize; + contentLength = end - start; + blockList_3.push(blockID); + return [4 /*yield*/, this.stageBlock(blockID, function () { return streamFactory(start, contentLength); }, contentLength, { + abortSignal: options.abortSignal, + conditions: options.conditions, + encryptionScope: options.encryptionScope, + tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) + })]; + case 1: + _a.sent(); + // Update progress after block is successfully uploaded to server, in case of block trying + transferProgress_4 += contentLength; + if (options.onProgress) { + options.onProgress({ loadedBytes: transferProgress_4 }); + } + return [2 /*return*/]; + } + }); + }); }); + }; + for (i = 0; i < numBlocks_2; i++) { + _loop_3(i); + } + return [4 /*yield*/, batch.do()]; + case 4: + _b.sent(); + return [4 /*yield*/, this.commitBlockList(blockList_3, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 5: return [2 /*return*/, _b.sent()]; + case 6: e_33 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_33.message }); throw e_33; - case 5: + case 7: span.end(); return [7 /*endfinally*/]; - case 6: return [2 /*return*/]; + case 8: return [2 /*return*/]; } }); }); @@ -33953,7 +32530,7 @@ var ContainerClient = /** @class */ (function (_super) { * } * entity = await iter.next(); * } - * ``` + * ```js * * Example using `byPage()`: * @@ -33998,7 +32575,8 @@ var ContainerClient = /** @class */ (function (_super) { * @param {ContainerListBlobsOptions} [options={}] Options to list blobs operation. * @returns {(PagedAsyncIterableIterator< * { kind: "prefix" } & BlobPrefix | { kind: "blob" } & BlobItem, - * ContainerListBlobHierarchySegmentResponse>)} + * ContainerListBlobHierarchySegmentResponse + * >)} * @memberof ContainerClient */ ContainerClient.prototype.listBlobsByHierarchy = function (delimiter, options) { @@ -34100,28 +32678,6 @@ var ContainerClient = /** @class */ (function (_super) { throw new Error("Unable to extract containerName with provided information."); } }; - /** - * Only available for ContainerClient constructed with a shared key credential. - * - * Generates a Blob Container Service Shared Access Signature (SAS) URI based on the client properties - * and parameters passed in. The SAS is signed by the shared key credential of the client. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas - * - * @param {ContainerGenerateSasUrlOptions} options Optional parameters. - * @returns {Promise} The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. - * @memberof ContainerClient - */ - ContainerClient.prototype.generateSasUrl = function (options) { - var _this = this; - return new Promise(function (resolve) { - if (!(_this.credential instanceof StorageSharedKeyCredential)) { - throw new RangeError("Can only generate the SAS when the client is initialized with a shared key credential"); - } - var sas = generateBlobSASQueryParameters(tslib.__assign({ containerName: _this._containerName }, options), _this.credential).toString(); - resolve(appendToURLQuery(_this.url, sas)); - }); - }; return ContainerClient; }(StorageClient)); @@ -34201,7 +32757,8 @@ var BatchResponseParser = /** @class */ (function () { // Parse sub subResponses. for (index = 0; index < subResponseCount; index++) { subResponse = subResponses[index]; - deserializedSubResponse = {}; + deserializedSubResponses[index] = {}; + deserializedSubResponse = deserializedSubResponses[index]; deserializedSubResponse.headers = new coreHttp.HttpHeaders(); responseLines = subResponse.split("" + HTTP_LINE_ENDING); subRespHeaderStartFound = false; @@ -34253,20 +32810,8 @@ var BatchResponseParser = /** @class */ (function () { deserializedSubResponse.bodyAsText += responseLine; } } // Inner for end - // The response will contain the Content-ID header for each corresponding subrequest response to use for tracking. - // The Content-IDs are set to a valid index in the subrequests we sent. In the status code 202 path, we could expect it - // to be 1-1 mapping from the [0, subRequests.size) to the Content-IDs returned. If not, we simply don't return that - // unexpected subResponse in the parsed reponse and we can always look it up in the raw response for debugging purpose. - if (contentId != NOT_FOUND && - Number.isInteger(contentId) && - contentId >= 0 && - contentId < this.subRequests.size && - deserializedSubResponses[contentId] === undefined) { + if (contentId != NOT_FOUND) { deserializedSubResponse._request = this.subRequests.get(contentId); - deserializedSubResponses[contentId] = deserializedSubResponse; - } - else { - logger.error("subResponses[" + index + "] is dropped as the Content-ID is not found or invalid, Content-ID: " + contentId); } if (subRespFailed) { subResponsesFailedCount++; @@ -34604,7 +33149,7 @@ var InnerBatchRequest = /** @class */ (function () { factories[1] = new BatchHeaderFilterPolicyFactory(); // Use batch header filter policy to exclude unnecessary headers if (!isAnonymousCreds) { factories[2] = coreHttp.isTokenCredential(credential) - ? attachCredential(coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes), credential) + ? coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes) : credential; } factories[policyFactoryLength - 1] = new BatchRequestAssemblePolicyFactory(this); // Use batch assemble policy to assemble request and intercept request from going to wire @@ -34707,690 +33252,196 @@ var BatchHeaderFilterPolicy = /** @class */ (function (_super) { request.headers.remove(xMsHeaderName); // The subrequests should not have the x-ms-version header. } return [2 /*return*/, this._nextPolicy.sendRequest(request)]; - }); - }); - }; - return BatchHeaderFilterPolicy; -}(coreHttp.BaseRequestPolicy)); -var BatchHeaderFilterPolicyFactory = /** @class */ (function () { - function BatchHeaderFilterPolicyFactory() { - } - BatchHeaderFilterPolicyFactory.prototype.create = function (nextPolicy, options) { - return new BatchHeaderFilterPolicy(nextPolicy, options); - }; - return BatchHeaderFilterPolicyFactory; -}()); - -// Copyright (c) Microsoft Corporation. All rights reserved. -/** - * A BlobBatchClient allows you to make batched requests to the Azure Storage Blob service. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch - */ -var BlobBatchClient = /** @class */ (function () { - function BlobBatchClient(url, credentialOrPipeline, options) { - var pipeline; - if (credentialOrPipeline instanceof Pipeline) { - pipeline = credentialOrPipeline; - } - else if (!credentialOrPipeline) { - // no credential provided - pipeline = newPipeline(new AnonymousCredential(), options); - } - else { - pipeline = newPipeline(credentialOrPipeline, options); - } - var storageClientContext = new StorageClientContext(url, pipeline.toServiceClientOptions()); - this._serviceContext = new Service(storageClientContext); - } - /** - * Creates a {@link BlobBatch}. - * A BlobBatch represents an aggregated set of operations on blobs. - */ - BlobBatchClient.prototype.createBatch = function () { - return new BlobBatch(); - }; - BlobBatchClient.prototype.deleteBlobs = function (urlsOrBlobClients, credentialOrOptions, options) { - return tslib.__awaiter(this, void 0, void 0, function () { - var batch, _i, urlsOrBlobClients_1, urlOrBlobClient; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - batch = new BlobBatch(); - _i = 0, urlsOrBlobClients_1 = urlsOrBlobClients; - _a.label = 1; - case 1: - if (!(_i < urlsOrBlobClients_1.length)) return [3 /*break*/, 6]; - urlOrBlobClient = urlsOrBlobClients_1[_i]; - if (!(typeof urlOrBlobClient === "string")) return [3 /*break*/, 3]; - return [4 /*yield*/, batch.deleteBlob(urlOrBlobClient, credentialOrOptions, options)]; - case 2: - _a.sent(); - return [3 /*break*/, 5]; - case 3: return [4 /*yield*/, batch.deleteBlob(urlOrBlobClient, credentialOrOptions)]; - case 4: - _a.sent(); - _a.label = 5; - case 5: - _i++; - return [3 /*break*/, 1]; - case 6: return [2 /*return*/, this.submitBatch(batch)]; - } - }); - }); - }; - BlobBatchClient.prototype.setBlobsAccessTier = function (urlsOrBlobClients, credentialOrTier, tierOrOptions, options) { - return tslib.__awaiter(this, void 0, void 0, function () { - var batch, _i, urlsOrBlobClients_2, urlOrBlobClient; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - batch = new BlobBatch(); - _i = 0, urlsOrBlobClients_2 = urlsOrBlobClients; - _a.label = 1; - case 1: - if (!(_i < urlsOrBlobClients_2.length)) return [3 /*break*/, 6]; - urlOrBlobClient = urlsOrBlobClients_2[_i]; - if (!(typeof urlOrBlobClient === "string")) return [3 /*break*/, 3]; - return [4 /*yield*/, batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options)]; - case 2: - _a.sent(); - return [3 /*break*/, 5]; - case 3: return [4 /*yield*/, batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions)]; - case 4: - _a.sent(); - _a.label = 5; - case 5: - _i++; - return [3 /*break*/, 1]; - case 6: return [2 /*return*/, this.submitBatch(batch)]; - } - }); - }); - }; - /** - * Submit batch request which consists of multiple subrequests. - * - * Get `blobBatchClient` and other details before running the snippets. - * `blobServiceClient.getBlobBatchClient()` gives the `blobBatchClient` - * - * Example usage: - * - * ```js - * let batchRequest = new BlobBatch(); - * await batchRequest.deleteBlob(urlInString0, credential0); - * await batchRequest.deleteBlob(urlInString1, credential1, { - * deleteSnapshots: "include" - * }); - * const batchResp = await blobBatchClient.submitBatch(batchRequest); - * console.log(batchResp.subResponsesSucceededCount); - * ``` - * - * Example using a lease: - * - * ```js - * let batchRequest = new BlobBatch(); - * await batchRequest.setBlobAccessTier(blockBlobClient0, "Cool"); - * await batchRequest.setBlobAccessTier(blockBlobClient1, "Cool", { - * conditions: { leaseId: leaseId } - * }); - * const batchResp = await blobBatchClient.submitBatch(batchRequest); - * console.log(batchResp.subResponsesSucceededCount); - * ``` - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch - * - * @param {BlobBatch} batchRequest A set of Delete or SetTier operations. - * @param {BlobBatchSubmitBatchOptionalParams} [options] - * @returns {Promise} - * @memberof BlobBatchClient - */ - BlobBatchClient.prototype.submitBatch = function (batchRequest, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, batchRequestBody, rawBatchResponse, batchResponseParser, responseSummary, res, e_1; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!batchRequest || batchRequest.getSubRequests().size == 0) { - throw new RangeError("Batch request should contain one or more sub requests."); - } - _a = createSpan("BlobBatchClient-submitBatch", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 4, 5, 6]); - batchRequestBody = batchRequest.getHttpRequestBody(); - return [4 /*yield*/, this._serviceContext.submitBatch(batchRequestBody, utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), tslib.__assign(tslib.__assign({}, options), { spanOptions: spanOptions }))]; - case 2: - rawBatchResponse = _b.sent(); - batchResponseParser = new BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests()); - return [4 /*yield*/, batchResponseParser.parseBatchResponse()]; - case 3: - responseSummary = _b.sent(); - res = { - _response: rawBatchResponse._response, - contentType: rawBatchResponse.contentType, - errorCode: rawBatchResponse.errorCode, - requestId: rawBatchResponse.requestId, - clientRequestId: rawBatchResponse.clientRequestId, - version: rawBatchResponse.version, - subResponses: responseSummary.subResponses, - subResponsesSucceededCount: responseSummary.subResponsesSucceededCount, - subResponsesFailedCount: responseSummary.subResponsesFailedCount - }; - return [2 /*return*/, res]; - case 4: - e_1 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_1.message - }); - throw e_1; - case 5: - span.end(); - return [7 /*endfinally*/]; - case 6: return [2 /*return*/]; - } - }); - }); - }; - return BlobBatchClient; -}()); - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * This is a helper class to construct a string representing the permissions granted by an AccountSAS. Setting a value - * to true means that any SAS which uses these permissions will grant permissions for that operation. Once all the - * values are set, this should be serialized with toString and set as the permissions field on an - * {@link AccountSASSignatureValues} object. It is possible to construct the permissions string without this class, but - * the order of the permissions is particular and this class guarantees correctness. - * - * @export - * @class AccountSASPermissions - */ -var AccountSASPermissions = /** @class */ (function () { - function AccountSASPermissions() { - /** - * Permission to read resources and list queues and tables granted. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.read = false; - /** - * Permission to write resources granted. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.write = false; - /** - * Permission to create blobs and files granted. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.delete = false; - /** - * Permission to delete versions granted. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.deleteVersion = false; - /** - * Permission to list blob containers, blobs, shares, directories, and files granted. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.list = false; - /** - * Permission to add messages, table entities, and append to blobs granted. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.add = false; - /** - * Permission to create blobs and files granted. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.create = false; - /** - * Permissions to update messages and table entities granted. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.update = false; - /** - * Permission to get and delete messages granted. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.process = false; - /** - * Specfies Tag access granted. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.tag = false; - /** - * Permission to filter blobs. - * - * @type {boolean} - * @memberof AccountSASPermissions - */ - this.filter = false; - } - /** - * Parse initializes the AccountSASPermissions fields from a string. - * - * @static - * @param {string} permissions - * @returns {AccountSASPermissions} - * @memberof AccountSASPermissions - */ - AccountSASPermissions.parse = function (permissions) { - var accountSASPermissions = new AccountSASPermissions(); - for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { - var c = permissions_1[_i]; - switch (c) { - case "r": - accountSASPermissions.read = true; - break; - case "w": - accountSASPermissions.write = true; - break; - case "d": - accountSASPermissions.delete = true; - break; - case "x": - accountSASPermissions.deleteVersion = true; - break; - case "l": - accountSASPermissions.list = true; - break; - case "a": - accountSASPermissions.add = true; - break; - case "c": - accountSASPermissions.create = true; - break; - case "u": - accountSASPermissions.update = true; - break; - case "p": - accountSASPermissions.process = true; - break; - case "t": - accountSASPermissions.tag = true; - break; - case "f": - accountSASPermissions.filter = true; - break; - default: - throw new RangeError("Invalid permission character: " + c); - } - } - return accountSASPermissions; - }; - /** - * Creates a {@link AccountSASPermissions} from a raw object which contains same keys as it - * and boolean values for them. - * - * @static - * @param {AccountSASPermissionsLike} permissionLike - * @returns {AccountSASPermissions} - * @memberof AccountSASPermissions - */ - AccountSASPermissions.from = function (permissionLike) { - var accountSASPermissions = new AccountSASPermissions(); - if (permissionLike.read) { - accountSASPermissions.read = true; - } - if (permissionLike.write) { - accountSASPermissions.write = true; - } - if (permissionLike.delete) { - accountSASPermissions.delete = true; - } - if (permissionLike.deleteVersion) { - accountSASPermissions.deleteVersion = true; - } - if (permissionLike.filter) { - accountSASPermissions.filter = true; - } - if (permissionLike.tag) { - accountSASPermissions.tag = true; - } - if (permissionLike.list) { - accountSASPermissions.list = true; - } - if (permissionLike.add) { - accountSASPermissions.add = true; - } - if (permissionLike.create) { - accountSASPermissions.create = true; - } - if (permissionLike.update) { - accountSASPermissions.update = true; - } - if (permissionLike.process) { - accountSASPermissions.process = true; - } - return accountSASPermissions; - }; - /** - * Produces the SAS permissions string for an Azure Storage account. - * Call this method to set AccountSASSignatureValues Permissions field. - * - * Using this method will guarantee the resource types are in - * an order accepted by the service. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas - * - * @returns {string} - * @memberof AccountSASPermissions - */ - AccountSASPermissions.prototype.toString = function () { - // The order of the characters should be as specified here to ensure correctness: - // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas - // Use a string array instead of string concatenating += operator for performance - var permissions = []; - if (this.read) { - permissions.push("r"); - } - if (this.write) { - permissions.push("w"); - } - if (this.delete) { - permissions.push("d"); - } - if (this.deleteVersion) { - permissions.push("x"); - } - if (this.filter) { - permissions.push("f"); - } - if (this.tag) { - permissions.push("t"); - } - if (this.list) { - permissions.push("l"); - } - if (this.add) { - permissions.push("a"); - } - if (this.create) { - permissions.push("c"); - } - if (this.update) { - permissions.push("u"); - } - if (this.process) { - permissions.push("p"); - } - return permissions.join(""); - }; - return AccountSASPermissions; -}()); - -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * This is a helper class to construct a string representing the resources accessible by an AccountSAS. Setting a value - * to true means that any SAS which uses these permissions will grant access to that resource type. Once all the - * values are set, this should be serialized with toString and set as the resources field on an - * {@link AccountSASSignatureValues} object. It is possible to construct the resources string without this class, but - * the order of the resources is particular and this class guarantees correctness. - * - * @export - * @class AccountSASResourceTypes - */ -var AccountSASResourceTypes = /** @class */ (function () { - function AccountSASResourceTypes() { - /** - * Permission to access service level APIs granted. - * - * @type {boolean} - * @memberof AccountSASResourceTypes - */ - this.service = false; - /** - * Permission to access container level APIs (Blob Containers, Tables, Queues, File Shares) granted. - * - * @type {boolean} - * @memberof AccountSASResourceTypes - */ - this.container = false; - /** - * Permission to access object level APIs (Blobs, Table Entities, Queue Messages, Files) granted. - * - * @type {boolean} - * @memberof AccountSASResourceTypes - */ - this.object = false; - } - /** - * Creates an {@link AccountSASResourceTypes} from the specified resource types string. This method will throw an - * Error if it encounters a character that does not correspond to a valid resource type. - * - * @static - * @param {string} resourceTypes - * @returns {AccountSASResourceTypes} - * @memberof AccountSASResourceTypes - */ - AccountSASResourceTypes.parse = function (resourceTypes) { - var accountSASResourceTypes = new AccountSASResourceTypes(); - for (var _i = 0, resourceTypes_1 = resourceTypes; _i < resourceTypes_1.length; _i++) { - var c = resourceTypes_1[_i]; - switch (c) { - case "s": - accountSASResourceTypes.service = true; - break; - case "c": - accountSASResourceTypes.container = true; - break; - case "o": - accountSASResourceTypes.object = true; - break; - default: - throw new RangeError("Invalid resource type: " + c); - } - } - return accountSASResourceTypes; + }); + }); }; - /** - * Converts the given resource types to a string. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas - * - * @returns {string} - * @memberof AccountSASResourceTypes - */ - AccountSASResourceTypes.prototype.toString = function () { - var resourceTypes = []; - if (this.service) { - resourceTypes.push("s"); - } - if (this.container) { - resourceTypes.push("c"); - } - if (this.object) { - resourceTypes.push("o"); - } - return resourceTypes.join(""); + return BatchHeaderFilterPolicy; +}(coreHttp.BaseRequestPolicy)); +var BatchHeaderFilterPolicyFactory = /** @class */ (function () { + function BatchHeaderFilterPolicyFactory() { + } + BatchHeaderFilterPolicyFactory.prototype.create = function (nextPolicy, options) { + return new BatchHeaderFilterPolicy(nextPolicy, options); }; - return AccountSASResourceTypes; + return BatchHeaderFilterPolicyFactory; }()); // Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. /** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * This is a helper class to construct a string representing the services accessible by an AccountSAS. Setting a value - * to true means that any SAS which uses these permissions will grant access to that service. Once all the - * values are set, this should be serialized with toString and set as the services field on an - * {@link AccountSASSignatureValues} object. It is possible to construct the services string without this class, but - * the order of the services is particular and this class guarantees correctness. + * A BlobBatchClient allows you to make batched requests to the Azure Storage Blob service. * - * @export - * @class AccountSASServices + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch */ -var AccountSASServices = /** @class */ (function () { - function AccountSASServices() { - /** - * Permission to access blob resources granted. - * - * @type {boolean} - * @memberof AccountSASServices - */ - this.blob = false; - /** - * Permission to access file resources granted. - * - * @type {boolean} - * @memberof AccountSASServices - */ - this.file = false; - /** - * Permission to access queue resources granted. - * - * @type {boolean} - * @memberof AccountSASServices - */ - this.queue = false; - /** - * Permission to access table resources granted. - * - * @type {boolean} - * @memberof AccountSASServices - */ - this.table = false; +var BlobBatchClient = /** @class */ (function () { + function BlobBatchClient(url, credentialOrPipeline, options) { + var pipeline; + if (credentialOrPipeline instanceof Pipeline) { + pipeline = credentialOrPipeline; + } + else if (!credentialOrPipeline) { + // no credential provided + pipeline = newPipeline(new AnonymousCredential(), options); + } + else { + pipeline = newPipeline(credentialOrPipeline, options); + } + var storageClientContext = new StorageClientContext(url, pipeline.toServiceClientOptions()); + this._serviceContext = new Service(storageClientContext); } /** - * Creates an {@link AccountSASServices} from the specified services string. This method will throw an - * Error if it encounters a character that does not correspond to a valid service. - * - * @static - * @param {string} services - * @returns {AccountSASServices} - * @memberof AccountSASServices + * Creates a {@link BlobBatch}. + * A BlobBatch represents an aggregated set of operations on blobs. */ - AccountSASServices.parse = function (services) { - var accountSASServices = new AccountSASServices(); - for (var _i = 0, services_1 = services; _i < services_1.length; _i++) { - var c = services_1[_i]; - switch (c) { - case "b": - accountSASServices.blob = true; - break; - case "f": - accountSASServices.file = true; - break; - case "q": - accountSASServices.queue = true; - break; - case "t": - accountSASServices.table = true; - break; - default: - throw new RangeError("Invalid service character: " + c); - } - } - return accountSASServices; + BlobBatchClient.prototype.createBatch = function () { + return new BlobBatch(); + }; + BlobBatchClient.prototype.deleteBlobs = function (urlsOrBlobClients, credentialOrOptions, options) { + return tslib.__awaiter(this, void 0, void 0, function () { + var batch, _i, urlsOrBlobClients_1, urlOrBlobClient; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + batch = new BlobBatch(); + _i = 0, urlsOrBlobClients_1 = urlsOrBlobClients; + _a.label = 1; + case 1: + if (!(_i < urlsOrBlobClients_1.length)) return [3 /*break*/, 6]; + urlOrBlobClient = urlsOrBlobClients_1[_i]; + if (!(typeof urlOrBlobClient === "string")) return [3 /*break*/, 3]; + return [4 /*yield*/, batch.deleteBlob(urlOrBlobClient, credentialOrOptions, options)]; + case 2: + _a.sent(); + return [3 /*break*/, 5]; + case 3: return [4 /*yield*/, batch.deleteBlob(urlOrBlobClient, credentialOrOptions)]; + case 4: + _a.sent(); + _a.label = 5; + case 5: + _i++; + return [3 /*break*/, 1]; + case 6: return [2 /*return*/, this.submitBatch(batch)]; + } + }); + }); + }; + BlobBatchClient.prototype.setBlobsAccessTier = function (urlsOrBlobClients, credentialOrTier, tierOrOptions, options) { + return tslib.__awaiter(this, void 0, void 0, function () { + var batch, _i, urlsOrBlobClients_2, urlOrBlobClient; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + batch = new BlobBatch(); + _i = 0, urlsOrBlobClients_2 = urlsOrBlobClients; + _a.label = 1; + case 1: + if (!(_i < urlsOrBlobClients_2.length)) return [3 /*break*/, 6]; + urlOrBlobClient = urlsOrBlobClients_2[_i]; + if (!(typeof urlOrBlobClient === "string")) return [3 /*break*/, 3]; + return [4 /*yield*/, batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options)]; + case 2: + _a.sent(); + return [3 /*break*/, 5]; + case 3: return [4 /*yield*/, batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions)]; + case 4: + _a.sent(); + _a.label = 5; + case 5: + _i++; + return [3 /*break*/, 1]; + case 6: return [2 /*return*/, this.submitBatch(batch)]; + } + }); + }); }; /** - * Converts the given services to a string. + * Submit batch request which consists of multiple subrequests. * - * @returns {string} - * @memberof AccountSASServices + * Get `blobBatchClient` and other details before running the snippets. + * `blobServiceClient.getBlobBatchClient()` gives the `blobBatchClient` + * + * Example usage: + * + * ```js + * let batchRequest = new BlobBatch(); + * await batchRequest.deleteBlob(urlInString0, credential0); + * await batchRequest.deleteBlob(urlInString1, credential1, { + * deleteSnapshots: "include" + * }); + * const batchResp = await blobBatchClient.submitBatch(batchRequest); + * console.log(batchResp.subResponsesSucceededCount); + * ``` + * + * Example using a lease: + * + * ```js + * let batchRequest = new BlobBatch(); + * await batchRequest.setBlobAccessTier(blockBlobClient0, "Cool"); + * await batchRequest.setBlobAccessTier(blockBlobClient1, "Cool", { + * conditions: { leaseId: leaseId } + * }); + * const batchResp = await blobBatchClient.submitBatch(batchRequest); + * console.log(batchResp.subResponsesSucceededCount); + * ``` + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch + * + * @param {BlobBatch} batchRequest A set of Delete or SetTier operations. + * @param {BlobBatchSubmitBatchOptionalParams} [options] + * @returns {Promise} + * @memberof BlobBatchClient */ - AccountSASServices.prototype.toString = function () { - var services = []; - if (this.blob) { - services.push("b"); - } - if (this.table) { - services.push("t"); - } - if (this.queue) { - services.push("q"); - } - if (this.file) { - services.push("f"); - } - return services.join(""); + BlobBatchClient.prototype.submitBatch = function (batchRequest, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, batchRequestBody, rawBatchResponse, batchResponseParser, responseSummary, res, e_1; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + if (!batchRequest || batchRequest.getSubRequests().size == 0) { + throw new RangeError("Batch request should contain one or more sub requests."); + } + _a = createSpan("BlobBatchClient-submitBatch", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 4, 5, 6]); + batchRequestBody = batchRequest.getHttpRequestBody(); + return [4 /*yield*/, this._serviceContext.submitBatch(batchRequestBody, utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), tslib.__assign(tslib.__assign({}, options), { spanOptions: spanOptions }))]; + case 2: + rawBatchResponse = _b.sent(); + batchResponseParser = new BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests()); + return [4 /*yield*/, batchResponseParser.parseBatchResponse()]; + case 3: + responseSummary = _b.sent(); + res = { + _response: rawBatchResponse._response, + contentType: rawBatchResponse.contentType, + errorCode: rawBatchResponse.errorCode, + requestId: rawBatchResponse.requestId, + clientRequestId: rawBatchResponse.clientRequestId, + version: rawBatchResponse.version, + subResponses: responseSummary.subResponses, + subResponsesSucceededCount: responseSummary.subResponsesSucceededCount, + subResponsesFailedCount: responseSummary.subResponsesFailedCount + }; + return [2 /*return*/, res]; + case 4: + e_1 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_1.message + }); + throw e_1; + case 5: + span.end(); + return [7 /*endfinally*/]; + case 6: return [2 /*return*/]; + } + }); + }); }; - return AccountSASServices; + return BlobBatchClient; }()); -// Copyright (c) Microsoft Corporation. All rights reserved. -/** - * ONLY AVAILABLE IN NODE.JS RUNTIME. - * - * Generates a {@link SASQueryParameters} object which contains all SAS query parameters needed to make an actual - * REST request. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas - * - * @param {AccountSASSignatureValues} accountSASSignatureValues - * @param {StorageSharedKeyCredential} sharedKeyCredential - * @returns {SASQueryParameters} - * @memberof AccountSASSignatureValues - */ -function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { - var version = accountSASSignatureValues.version - ? accountSASSignatureValues.version - : SERVICE_VERSION; - if (accountSASSignatureValues.permissions && - accountSASSignatureValues.permissions.deleteVersion && - version < "2019-10-10") { - throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); - } - if (accountSASSignatureValues.permissions && - accountSASSignatureValues.permissions.tag && - version < "2019-12-12") { - throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); - } - if (accountSASSignatureValues.permissions && - accountSASSignatureValues.permissions.filter && - version < "2019-12-12") { - throw RangeError("'version' must be >= '2019-12-12' when provided 'f' permission."); - } - var parsedPermissions = AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()); - var parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); - var parsedResourceTypes = AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString(); - var stringToSign = [ - sharedKeyCredential.accountName, - parsedPermissions, - parsedServices, - parsedResourceTypes, - accountSASSignatureValues.startsOn - ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) - : "", - truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), - accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", - accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", - version, - "" // Account SAS requires an additional newline character - ].join("\n"); - var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); - return new SASQueryParameters(version, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange); -} - /** * A BlobServiceClient represents a Client to the Azure Storage Blob service allowing you * to manipulate blob containers. @@ -35421,86 +33472,330 @@ var BlobServiceClient = /** @class */ (function (_super) { } /** * - * Creates an instance of BlobServiceClient from connection string. - * - * @param {string} connectionString Account connection string or a SAS connection string of an Azure storage account. - * [ Note - Account connection string can only be used in NODE.JS runtime. ] - * Account connection string example - - * `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net` - * SAS connection string example - - * `BlobEndpoint=https://myaccount.blob.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString` - * @param {StoragePipelineOptions} [options] Optional. Options to configure the HTTP pipeline. + * Creates an instance of BlobServiceClient from connection string. + * + * @param {string} connectionString Account connection string or a SAS connection string of an Azure storage account. + * [ Note - Account connection string can only be used in NODE.JS runtime. ] + * Account connection string example - + * `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net` + * SAS connection string example - + * `BlobEndpoint=https://myaccount.blob.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString` + * @param {StoragePipelineOptions} [options] Optional. Options to configure the HTTP pipeline. + * @memberof BlobServiceClient + */ + BlobServiceClient.fromConnectionString = function (connectionString, options) { + options = options || {}; + var extractedCreds = extractConnectionStringParts(connectionString); + if (extractedCreds.kind === "AccountConnString") { + { + var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); + var pipeline = newPipeline(sharedKeyCredential, options); + return new BlobServiceClient(extractedCreds.url, pipeline); + } + } + else if (extractedCreds.kind === "SASConnString") { + var pipeline = newPipeline(new AnonymousCredential(), options); + return new BlobServiceClient(extractedCreds.url + "?" + extractedCreds.accountSas, pipeline); + } + else { + throw new Error("Connection string must be either an Account connection string or a SAS connection string"); + } + }; + /** + * Creates a {@link ContainerClient} object + * + * @param {string} containerName A container name + * @returns {ContainerClient} A new ContainerClient object for the given container name. + * @memberof BlobServiceClient + * + * Example usage: + * + * ```js + * const containerClient = blobServiceClient.getContainerClient(""); + * ``` + */ + BlobServiceClient.prototype.getContainerClient = function (containerName) { + return new ContainerClient(appendToURLPath(this.url, encodeURIComponent(containerName)), this.pipeline); + }; + /** + * Create a Blob container. + * + * @param {string} containerName Name of the container to create. + * @param {ContainerCreateOptions} [options] Options to configure Container Create operation. + * @returns {Promise<{ containerClient: ContainerClient; containerCreateResponse: ContainerCreateResponse }>} Container creation response and the corresponding container client. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.createContainer = function (containerName, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, containerClient, containerCreateResponse, e_1; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-createContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + containerClient = this.getContainerClient(containerName); + return [4 /*yield*/, containerClient.create(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: + containerCreateResponse = _b.sent(); + return [2 /*return*/, { + containerClient: containerClient, + containerCreateResponse: containerCreateResponse + }]; + case 3: + e_1 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_1.message + }); + throw e_1; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Deletes a Blob container. + * + * @param {string} containerName Name of the container to delete. + * @param {ContainerDeleteMethodOptions} [options] Options to configure Container Delete operation. + * @returns {Promise} Container deletion response. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.deleteContainer = function (containerName, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, containerClient, e_2; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-deleteContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + containerClient = this.getContainerClient(containerName); + return [4 /*yield*/, containerClient.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_2 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_2.message + }); + throw e_2; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Gets the properties of a storage account’s Blob service, including properties + * for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties + * + * @param {ServiceGetPropertiesOptions} [options] Options to the Service Get Properties operation. + * @returns {Promise} Response data for the Service Get Properties operation. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.getProperties = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_3; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-getProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.getProperties({ + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_3 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_3.message + }); + throw e_3; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Sets properties for a storage account’s Blob service endpoint, including properties + * for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules and soft delete settings. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties} + * + * @param {BlobServiceProperties} properties + * @param {ServiceSetPropertiesOptions} [options] Options to the Service Set Properties operation. + * @returns {Promise} Response data for the Service Set Properties operation. + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.setProperties = function (properties, options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_4; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-setProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.setProperties(properties, { + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_4 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_4.message + }); + throw e_4; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); + }; + /** + * Retrieves statistics related to replication for the Blob service. It is only + * available on the secondary location endpoint when read-access geo-redundant + * replication is enabled for the storage account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-stats} + * + * @param {ServiceGetStatisticsOptions} [options] Options to the Service Get Statistics operation. + * @returns {Promise} Response data for the Service Get Statistics operation. * @memberof BlobServiceClient */ - BlobServiceClient.fromConnectionString = function (connectionString, options) { - options = options || {}; - var extractedCreds = extractConnectionStringParts(connectionString); - if (extractedCreds.kind === "AccountConnString") { - { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); - options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); - var pipeline = newPipeline(sharedKeyCredential, options); - return new BlobServiceClient(extractedCreds.url, pipeline); - } - } - else if (extractedCreds.kind === "SASConnString") { - var pipeline = newPipeline(new AnonymousCredential(), options); - return new BlobServiceClient(extractedCreds.url + "?" + extractedCreds.accountSas, pipeline); - } - else { - throw new Error("Connection string must be either an Account connection string or a SAS connection string"); - } + BlobServiceClient.prototype.getStatistics = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_5; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-getStatistics", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.getStatistics({ + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_5 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_5.message + }); + throw e_5; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; /** - * Creates a {@link ContainerClient} object + * The Get Account Information operation returns the sku name and account kind + * for the specified account. + * The Get Account Information operation is available on service versions beginning + * with version 2018-03-28. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information * - * @param {string} containerName A container name - * @returns {ContainerClient} A new ContainerClient object for the given container name. + * @param {ServiceGetAccountInfoOptions} [options] Options to the Service Get Account Info operation. + * @returns {Promise} Response data for the Service Get Account Info operation. * @memberof BlobServiceClient - * - * Example usage: - * - * ```js - * const containerClient = blobServiceClient.getContainerClient(""); - * ``` */ - BlobServiceClient.prototype.getContainerClient = function (containerName) { - return new ContainerClient(appendToURLPath(this.url, encodeURIComponent(containerName)), this.pipeline); + BlobServiceClient.prototype.getAccountInfo = function (options) { + if (options === void 0) { options = {}; } + return tslib.__awaiter(this, void 0, void 0, function () { + var _a, span, spanOptions, e_6; + return tslib.__generator(this, function (_b) { + switch (_b.label) { + case 0: + _a = createSpan("BlobServiceClient-getAccountInfo", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _b.label = 1; + case 1: + _b.trys.push([1, 3, 4, 5]); + return [4 /*yield*/, this.serviceContext.getAccountInfo({ + abortSignal: options.abortSignal, + spanOptions: spanOptions + })]; + case 2: return [2 /*return*/, _b.sent()]; + case 3: + e_6 = _b.sent(); + span.setStatus({ + code: api.CanonicalCode.UNKNOWN, + message: e_6.message + }); + throw e_6; + case 4: + span.end(); + return [7 /*endfinally*/]; + case 5: return [2 /*return*/]; + } + }); + }); }; /** - * Create a Blob container. + * Returns a list of the containers under the specified account. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/list-containers2 * - * @param {string} containerName Name of the container to create. - * @param {ContainerCreateOptions} [options] Options to configure Container Create operation. - * @returns {Promise<{ containerClient: ContainerClient; containerCreateResponse: ContainerCreateResponse }>} Container creation response and the corresponding container client. + * @param {string} [marker] A string value that identifies the portion of + * the list of containers to be returned with the next listing operation. The + * operation returns the NextMarker value within the response body if the + * listing operation did not return all containers remaining to be listed + * with the current page. The NextMarker value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ServiceListContainersSegmentOptions} [options] Options to the Service List Container Segment operation. + * @returns {Promise} Response data for the Service List Container Segment operation. * @memberof BlobServiceClient */ - BlobServiceClient.prototype.createContainer = function (containerName, options) { + BlobServiceClient.prototype.listContainersSegment = function (marker, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, containerClient, containerCreateResponse, e_1; + var _a, span, spanOptions, e_7; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("BlobServiceClient-createContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("BlobServiceClient-listContainersSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - containerClient = this.getContainerClient(containerName); - return [4 /*yield*/, containerClient.create(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: - containerCreateResponse = _b.sent(); - return [2 /*return*/, { - containerClient: containerClient, - containerCreateResponse: containerCreateResponse - }]; + return [4 /*yield*/, this.serviceContext.listContainersSegment(tslib.__assign(tslib.__assign({ abortSignal: options.abortSignal, marker: marker }, options), { include: typeof options.include === "string" ? [options.include] : options.include, spanOptions: spanOptions }))]; + case 2: return [2 /*return*/, _b.sent()]; case 3: - e_1 = _b.sent(); + e_7 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_1.message + message: e_7.message }); - throw e_1; + throw e_7; case 4: span.end(); return [7 /*endfinally*/]; @@ -35510,34 +33805,52 @@ var BlobServiceClient = /** @class */ (function (_super) { }); }; /** - * Deletes a Blob container. + * The Filter Blobs operation enables callers to list blobs across all containers whose tags + * match a given search expression. Filter blobs searches across all containers within a + * storage account but can be scoped within the expression to a single container. * - * @param {string} containerName Name of the container to delete. - * @param {ContainerDeleteMethodOptions} [options] Options to configure Container Delete operation. - * @returns {Promise} Container deletion response. + * @private + * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param {string} [marker] A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the NextMarker value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The NextMarker value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to find blobs by tags. + * @returns {Promise} * @memberof BlobServiceClient */ - BlobServiceClient.prototype.deleteContainer = function (containerName, options) { + BlobServiceClient.prototype.findBlobsByTagsSegment = function (tagFilterSqlExpression, marker, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, containerClient, e_2; + var _a, span, spanOptions, e_8; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("BlobServiceClient-deleteContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("BlobServiceClient-findBlobsByTagsSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - containerClient = this.getContainerClient(containerName); - return [4 /*yield*/, containerClient.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; + return [4 /*yield*/, this.serviceContext.filterBlobs({ + abortSignal: options.abortSignal, + where: tagFilterSqlExpression, + marker: marker, + maxPageSize: options.maxPageSize, + spanOptions: spanOptions + })]; case 2: return [2 /*return*/, _b.sent()]; case 3: - e_2 = _b.sent(); + e_8 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_2.message + message: e_8.message }); - throw e_2; + throw e_8; case 4: span.end(); return [7 /*endfinally*/]; @@ -35547,79 +33860,471 @@ var BlobServiceClient = /** @class */ (function (_super) { }); }; /** - * Restore a previously deleted Blob container. - * This API is only functional if Container Soft Delete is enabled for the storage account associated with the container. + * Returns an AsyncIterableIterator for ServiceFindBlobsByTagsSegmentResponse. + * + * @private + * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param {string} [marker] A string value that identifies the portion of + * the list of blobs to be returned with the next listing operation. The + * operation returns the NextMarker value within the response body if the + * listing operation did not return all blobs remaining to be listed + * with the current page. The NextMarker value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to find blobs by tags. + * @returns {AsyncIterableIterator} + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.findBlobsByTagsSegments = function (tagFilterSqlExpression, marker, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function findBlobsByTagsSegments_1() { + var response; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!(!!marker || marker === undefined)) return [3 /*break*/, 6]; + _a.label = 1; + case 1: return [4 /*yield*/, tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker, options))]; + case 2: + response = _a.sent(); + response.blobs = response.blobs || []; + marker = response.continuationToken; + return [4 /*yield*/, tslib.__await(response)]; + case 3: return [4 /*yield*/, _a.sent()]; + case 4: + _a.sent(); + _a.label = 5; + case 5: + if (marker) return [3 /*break*/, 1]; + _a.label = 6; + case 6: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an AsyncIterableIterator for blobs. + * + * @private + * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to findBlobsByTagsItems. + * @returns {AsyncIterableIterator} + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.findBlobsByTagsItems = function (tagFilterSqlExpression, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function findBlobsByTagsItems_1() { + var marker, _a, _b, segment, e_9_1; + var e_9, _c; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: + _d.trys.push([0, 7, 8, 13]); + _a = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker, options)); + _d.label = 1; + case 1: return [4 /*yield*/, tslib.__await(_a.next())]; + case 2: + if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; + segment = _b.value; + return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs)))]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; + case 4: + _d.sent(); + _d.label = 5; + case 5: return [3 /*break*/, 1]; + case 6: return [3 /*break*/, 13]; + case 7: + e_9_1 = _d.sent(); + e_9 = { error: e_9_1 }; + return [3 /*break*/, 13]; + case 8: + _d.trys.push([8, , 11, 12]); + if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; + return [4 /*yield*/, tslib.__await(_c.call(_a))]; + case 9: + _d.sent(); + _d.label = 10; + case 10: return [3 /*break*/, 12]; + case 11: + if (e_9) throw e_9.error; + return [7 /*endfinally*/]; + case 12: return [7 /*endfinally*/]; + case 13: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an async iterable iterator to find all blobs with specified tag + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the blobs in pages. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties + * + * Example using `for await` syntax: + * + * ```js + * let i = 1; + * for await (const blob of blobServiceClient.findBlobsByTags("tagkey='tagvalue'")) { + * console.log(`Blob ${i++}: ${container.name}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * const iter = blobServiceClient.findBlobsByTags("tagkey='tagvalue'"); + * let blobItem = await iter.next(); + * while (!blobItem.done) { + * console.log(`Blob ${i++}: ${blobItem.value.name}`); + * blobItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 blob names + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * // Passing next marker as continuationToken + * iterator = blobServiceClient + * .findBlobsByTags("tagkey='tagvalue'") + * .byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints blob names + * if (response.blobs) { + * for (const blob of response.blobs) { + * console.log(`Blob ${i++}: ${blob.name}`); + * } + * } + * ``` + * + * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. + * The given expression must evaluate to true for a blob to be returned in the results. + * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; + * however, only a subset of the OData filter syntax is supported in the Blob service. + * @param {ServiceFindBlobByTagsOptions} [options={}] Options to find blobs by tags. + * @returns {PagedAsyncIterableIterator} + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.findBlobsByTags = function (tagFilterSqlExpression, options) { + var _a; + var _this = this; + if (options === void 0) { options = {}; } + // AsyncIterableIterator to iterate over blobs + var listSegmentOptions = tslib.__assign({}, options); + var iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); + return _a = { + /** + * @member {Promise} [next] The next method, part of the iteration protocol + */ + next: function () { + return iter.next(); + } + }, + /** + * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol + */ + _a[Symbol.asyncIterator] = function () { + return this; + }, + /** + * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time + */ + _a.byPage = function (settings) { + if (settings === void 0) { settings = {}; } + return _this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + }, + _a; + }; + /** + * Returns an AsyncIterableIterator for ServiceListContainersSegmentResponses + * + * @private + * @param {string} [marker] A string value that identifies the portion of + * the list of containers to be returned with the next listing operation. The + * operation returns the NextMarker value within the response body if the + * listing operation did not return all containers remaining to be listed + * with the current page. The NextMarker value can be used as the value for + * the marker parameter in a subsequent call to request the next page of list + * items. The marker value is opaque to the client. + * @param {ServiceListContainersSegmentOptions} [options] Options to list containers operation. + * @returns {AsyncIterableIterator} + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.listSegments = function (marker, options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listSegments_1() { + var listContainersSegmentResponse; + return tslib.__generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!(!!marker || marker === undefined)) return [3 /*break*/, 7]; + _a.label = 1; + case 1: return [4 /*yield*/, tslib.__await(this.listContainersSegment(marker, options))]; + case 2: + listContainersSegmentResponse = _a.sent(); + listContainersSegmentResponse.containerItems = + listContainersSegmentResponse.containerItems || []; + marker = listContainersSegmentResponse.continuationToken; + return [4 /*yield*/, tslib.__await(listContainersSegmentResponse)]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_a.sent()])]; + case 4: return [4 /*yield*/, _a.sent()]; + case 5: + _a.sent(); + _a.label = 6; + case 6: + if (marker) return [3 /*break*/, 1]; + _a.label = 7; + case 7: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an AsyncIterableIterator for Container Items + * + * @private + * @param {ServiceListContainersSegmentOptions} [options] Options to list containers operation. + * @returns {AsyncIterableIterator} + * @memberof BlobServiceClient + */ + BlobServiceClient.prototype.listItems = function (options) { + if (options === void 0) { options = {}; } + return tslib.__asyncGenerator(this, arguments, function listItems_1() { + var marker, _a, _b, segment, e_10_1; + var e_10, _c; + return tslib.__generator(this, function (_d) { + switch (_d.label) { + case 0: + _d.trys.push([0, 7, 8, 13]); + _a = tslib.__asyncValues(this.listSegments(marker, options)); + _d.label = 1; + case 1: return [4 /*yield*/, tslib.__await(_a.next())]; + case 2: + if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; + segment = _b.value; + return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(segment.containerItems)))]; + case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; + case 4: + _d.sent(); + _d.label = 5; + case 5: return [3 /*break*/, 1]; + case 6: return [3 /*break*/, 13]; + case 7: + e_10_1 = _d.sent(); + e_10 = { error: e_10_1 }; + return [3 /*break*/, 13]; + case 8: + _d.trys.push([8, , 11, 12]); + if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; + return [4 /*yield*/, tslib.__await(_c.call(_a))]; + case 9: + _d.sent(); + _d.label = 10; + case 10: return [3 /*break*/, 12]; + case 11: + if (e_10) throw e_10.error; + return [7 /*endfinally*/]; + case 12: return [7 /*endfinally*/]; + case 13: return [2 /*return*/]; + } + }); + }); + }; + /** + * Returns an async iterable iterator to list all the containers + * under the specified account. + * + * .byPage() returns an async iterable iterator to list the containers in pages. + * + * Example using `for await` syntax: + * + * ```js + * let i = 1; + * for await (const container of blobServiceClient.listContainers()) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * ``` + * + * Example using `iter.next()`: + * + * ```js + * let i = 1; + * const iter = blobServiceClient.listContainers(); + * let containerItem = await iter.next(); + * while (!containerItem.done) { + * console.log(`Container ${i++}: ${containerItem.value.name}`); + * containerItem = await iter.next(); + * } + * ``` + * + * Example using `byPage()`: + * + * ```js + * // passing optional maxPageSize in the page settings + * let i = 1; + * for await (const response of blobServiceClient.listContainers().byPage({ maxPageSize: 20 })) { + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * } + * ``` + * + * Example using paging with a marker: + * + * ```js + * let i = 1; + * let iterator = blobServiceClient.listContainers().byPage({ maxPageSize: 2 }); + * let response = (await iterator.next()).value; + * + * // Prints 2 container names + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * + * // Gets next marker + * let marker = response.continuationToken; + * // Passing next marker as continuationToken + * iterator = blobServiceClient + * .listContainers() + * .byPage({ continuationToken: marker, maxPageSize: 10 }); + * response = (await iterator.next()).value; + * + * // Prints 10 container names + * if (response.containerItems) { + * for (const container of response.containerItems) { + * console.log(`Container ${i++}: ${container.name}`); + * } + * } + * ``` * - * @param {string} deletedContainerName Name of the previously deleted container. - * @param {string} deletedContainerVersion Version of the previously deleted container, used to uniquely identify the deleted container. - * @returns {Promise} Container deletion response. + * @param {ServiceListContainersOptions} [options={}] Options to list containers. + * @returns {PagedAsyncIterableIterator} An asyncIterableIterator that supports paging. * @memberof BlobServiceClient */ - BlobServiceClient.prototype.undeleteContainer = function (deletedContainerName, deletedContainerVersion, options) { + BlobServiceClient.prototype.listContainers = function (options) { + var _a; + var _this = this; if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, containerClient, containerContext, containerUndeleteResponse, e_3; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-undeleteContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - containerClient = this.getContainerClient(options.destinationContainerName || deletedContainerName); - containerContext = new Container(containerClient["storageClientContext"]); - return [4 /*yield*/, containerContext.restore(tslib.__assign(tslib.__assign({ deletedContainerName: deletedContainerName, - deletedContainerVersion: deletedContainerVersion }, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; - case 2: - containerUndeleteResponse = _b.sent(); - return [2 /*return*/, { containerClient: containerClient, containerUndeleteResponse: containerUndeleteResponse }]; - case 3: - e_3 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_3.message - }); - throw e_3; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + if (options.prefix === "") { + options.prefix = undefined; + } + // AsyncIterableIterator to iterate over containers + var listSegmentOptions = tslib.__assign(tslib.__assign({}, options), (options.includeMetadata ? { include: "metadata" } : {})); + var iter = this.listItems(listSegmentOptions); + return _a = { + /** + * @member {Promise} [next] The next method, part of the iteration protocol + */ + next: function () { + return iter.next(); } - }); - }); + }, + /** + * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol + */ + _a[Symbol.asyncIterator] = function () { + return this; + }, + /** + * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time + */ + _a.byPage = function (settings) { + if (settings === void 0) { settings = {}; } + return _this.listSegments(settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + }, + _a; }; /** - * Gets the properties of a storage account’s Blob service, including properties - * for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties + * ONLY AVAILABLE WHEN USING BEARER TOKEN AUTHENTICATION (TokenCredential). * - * @param {ServiceGetPropertiesOptions} [options] Options to the Service Get Properties operation. - * @returns {Promise} Response data for the Service Get Properties operation. + * Retrieves a user delegation key for the Blob service. This is only a valid operation when using + * bearer token authentication. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-user-delegation-key + * + * @param {Date} startsOn The start time for the user delegation SAS. Must be within 7 days of the current time + * @param {Date} expiresOn The end time for the user delegation SAS. Must be within 7 days of the current time + * @returns {Promise} * @memberof BlobServiceClient */ - BlobServiceClient.prototype.getProperties = function (options) { + BlobServiceClient.prototype.getUserDelegationKey = function (startsOn, expiresOn, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_4; + var _a, span, spanOptions, response, userDelegationKey, res, e_11; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: - _a = createSpan("BlobServiceClient-getProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; + _a = createSpan("BlobServiceClient-getUserDelegationKey", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getProperties({ + return [4 /*yield*/, this.serviceContext.getUserDelegationKey({ + startsOn: truncatedISO8061Date(startsOn, false), + expiresOn: truncatedISO8061Date(expiresOn, false) + }, { abortSignal: options.abortSignal, spanOptions: spanOptions })]; - case 2: return [2 /*return*/, _b.sent()]; + case 2: + response = _b.sent(); + userDelegationKey = { + signedObjectId: response.signedObjectId, + signedTenantId: response.signedTenantId, + signedStartsOn: new Date(response.signedStartsOn), + signedExpiresOn: new Date(response.signedExpiresOn), + signedService: response.signedService, + signedVersion: response.signedVersion, + value: response.value + }; + res = tslib.__assign({ _response: response._response, requestId: response.requestId, clientRequestId: response.clientRequestId, version: response.version, date: response.date, errorCode: response.errorCode }, userDelegationKey); + return [2 /*return*/, res]; case 3: - e_4 = _b.sent(); + e_11 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, - message: e_4.message + message: e_11.message }); - throw e_4; + throw e_11; case 4: span.end(); return [7 /*endfinally*/]; @@ -35629,762 +34334,1342 @@ var BlobServiceClient = /** @class */ (function (_super) { }); }; /** - * Sets properties for a storage account’s Blob service endpoint, including properties - * for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules and soft delete settings. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties} + * Creates a BlobBatchClient object to conduct batch operations. * - * @param {BlobServiceProperties} properties - * @param {ServiceSetPropertiesOptions} [options] Options to the Service Set Properties operation. - * @returns {Promise} Response data for the Service Set Properties operation. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch + * + * @returns {BlobBatchClient} A new BlobBatchClient object for this service. * @memberof BlobServiceClient */ - BlobServiceClient.prototype.setProperties = function (properties, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_5; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-setProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.setProperties(properties, { - abortSignal: options.abortSignal, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_5 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_5.message - }); - throw e_5; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + BlobServiceClient.prototype.getBlobBatchClient = function () { + return new BlobBatchClient(this.url, this.pipeline); }; + return BlobServiceClient; +}(StorageClient)); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * This is a helper class to construct a string representing the permissions granted by an AccountSAS. Setting a value + * to true means that any SAS which uses these permissions will grant permissions for that operation. Once all the + * values are set, this should be serialized with toString and set as the permissions field on an + * {@link AccountSASSignatureValues} object. It is possible to construct the permissions string without this class, but + * the order of the permissions is particular and this class guarantees correctness. + * + * @export + * @class AccountSASPermissions + */ +var AccountSASPermissions = /** @class */ (function () { + function AccountSASPermissions() { + /** + * Permission to read resources and list queues and tables granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.read = false; + /** + * Permission to write resources granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.write = false; + /** + * Permission to create blobs and files granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.delete = false; + /** + * Permission to delete versions granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.deleteVersion = false; + /** + * Permission to list blob containers, blobs, shares, directories, and files granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.list = false; + /** + * Permission to add messages, table entities, and append to blobs granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.add = false; + /** + * Permission to create blobs and files granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.create = false; + /** + * Permissions to update messages and table entities granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.update = false; + /** + * Permission to get and delete messages granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.process = false; + /** + * Specfies Tag access granted. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.tag = false; + /** + * Permission to filter blobs. + * + * @type {boolean} + * @memberof AccountSASPermissions + */ + this.filter = false; + } /** - * Retrieves statistics related to replication for the Blob service. It is only - * available on the secondary location endpoint when read-access geo-redundant - * replication is enabled for the storage account. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-stats} + * Parse initializes the AccountSASPermissions fields from a string. * - * @param {ServiceGetStatisticsOptions} [options] Options to the Service Get Statistics operation. - * @returns {Promise} Response data for the Service Get Statistics operation. - * @memberof BlobServiceClient + * @static + * @param {string} permissions + * @returns {AccountSASPermissions} + * @memberof AccountSASPermissions */ - BlobServiceClient.prototype.getStatistics = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_6; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-getStatistics", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getStatistics({ - abortSignal: options.abortSignal, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_6 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_6.message - }); - throw e_6; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + AccountSASPermissions.parse = function (permissions) { + var accountSASPermissions = new AccountSASPermissions(); + for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { + var c = permissions_1[_i]; + switch (c) { + case "r": + accountSASPermissions.read = true; + break; + case "w": + accountSASPermissions.write = true; + break; + case "d": + accountSASPermissions.delete = true; + break; + case "x": + accountSASPermissions.deleteVersion = true; + break; + case "l": + accountSASPermissions.list = true; + break; + case "a": + accountSASPermissions.add = true; + break; + case "c": + accountSASPermissions.create = true; + break; + case "u": + accountSASPermissions.update = true; + break; + case "p": + accountSASPermissions.process = true; + break; + case "t": + accountSASPermissions.tag = true; + break; + case "f": + accountSASPermissions.filter = true; + break; + default: + throw new RangeError("Invalid permission character: " + c); + } + } + return accountSASPermissions; }; /** - * The Get Account Information operation returns the sku name and account kind - * for the specified account. - * The Get Account Information operation is available on service versions beginning - * with version 2018-03-28. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information + * Produces the SAS permissions string for an Azure Storage account. + * Call this method to set AccountSASSignatureValues Permissions field. * - * @param {ServiceGetAccountInfoOptions} [options] Options to the Service Get Account Info operation. - * @returns {Promise} Response data for the Service Get Account Info operation. - * @memberof BlobServiceClient + * Using this method will guarantee the resource types are in + * an order accepted by the service. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas + * + * @returns {string} + * @memberof AccountSASPermissions */ - BlobServiceClient.prototype.getAccountInfo = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_7; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-getAccountInfo", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getAccountInfo({ - abortSignal: options.abortSignal, - spanOptions: spanOptions - })]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_7 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_7.message - }); - throw e_7; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + AccountSASPermissions.prototype.toString = function () { + // The order of the characters should be as specified here to ensure correctness: + // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas + // Use a string array instead of string concatenating += operator for performance + var permissions = []; + if (this.read) { + permissions.push("r"); + } + if (this.write) { + permissions.push("w"); + } + if (this.delete) { + permissions.push("d"); + } + if (this.deleteVersion) { + permissions.push("x"); + } + if (this.filter) { + permissions.push("f"); + } + if (this.tag) { + permissions.push("t"); + } + if (this.list) { + permissions.push("l"); + } + if (this.add) { + permissions.push("a"); + } + if (this.create) { + permissions.push("c"); + } + if (this.update) { + permissions.push("u"); + } + if (this.process) { + permissions.push("p"); + } + return permissions.join(""); }; + return AccountSASPermissions; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * This is a helper class to construct a string representing the resources accessible by an AccountSAS. Setting a value + * to true means that any SAS which uses these permissions will grant access to that resource type. Once all the + * values are set, this should be serialized with toString and set as the resources field on an + * {@link AccountSASSignatureValues} object. It is possible to construct the resources string without this class, but + * the order of the resources is particular and this class guarantees correctness. + * + * @export + * @class AccountSASResourceTypes + */ +var AccountSASResourceTypes = /** @class */ (function () { + function AccountSASResourceTypes() { + /** + * Permission to access service level APIs granted. + * + * @type {boolean} + * @memberof AccountSASResourceTypes + */ + this.service = false; + /** + * Permission to access container level APIs (Blob Containers, Tables, Queues, File Shares) granted. + * + * @type {boolean} + * @memberof AccountSASResourceTypes + */ + this.container = false; + /** + * Permission to access object level APIs (Blobs, Table Entities, Queue Messages, Files) granted. + * + * @type {boolean} + * @memberof AccountSASResourceTypes + */ + this.object = false; + } /** - * Returns a list of the containers under the specified account. - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/list-containers2 + * Creates an {@link AccountSASResourceTypes} from the specified resource types string. This method will throw an + * Error if it encounters a character that does not correspond to a valid resource type. * - * @param {string} [marker] A string value that identifies the portion of - * the list of containers to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all containers remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param {ServiceListContainersSegmentOptions} [options] Options to the Service List Container Segment operation. - * @returns {Promise} Response data for the Service List Container Segment operation. - * @memberof BlobServiceClient + * @static + * @param {string} resourceTypes + * @returns {AccountSASResourceTypes} + * @memberof AccountSASResourceTypes */ - BlobServiceClient.prototype.listContainersSegment = function (marker, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, e_8; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-listContainersSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.listContainersSegment(tslib.__assign(tslib.__assign({ abortSignal: options.abortSignal, marker: marker }, options), { include: typeof options.include === "string" ? [options.include] : options.include, spanOptions: spanOptions }))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_8 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_8.message - }); - throw e_8; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + AccountSASResourceTypes.parse = function (resourceTypes) { + var accountSASResourceTypes = new AccountSASResourceTypes(); + for (var _i = 0, resourceTypes_1 = resourceTypes; _i < resourceTypes_1.length; _i++) { + var c = resourceTypes_1[_i]; + switch (c) { + case "s": + accountSASResourceTypes.service = true; + break; + case "c": + accountSASResourceTypes.container = true; + break; + case "o": + accountSASResourceTypes.object = true; + break; + default: + throw new RangeError("Invalid resource type: " + c); + } + } + return accountSASResourceTypes; }; /** - * The Filter Blobs operation enables callers to list blobs across all containers whose tags - * match a given search expression. Filter blobs searches across all containers within a - * storage account but can be scoped within the expression to a single container. + * Converts the given resource types to a string. * - * @private - * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param {string} [marker] A string value that identifies the portion of - * the list of blobs to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all blobs remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to find blobs by tags. - * @returns {Promise} - * @memberof BlobServiceClient + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas + * + * @returns {string} + * @memberof AccountSASResourceTypes */ - BlobServiceClient.prototype.findBlobsByTagsSegment = function (tagFilterSqlExpression, marker, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, response, wrappedResponse, e_9; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-findBlobsByTagsSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.filterBlobs({ - abortSignal: options.abortSignal, - where: tagFilterSqlExpression, - marker: marker, - maxPageSize: options.maxPageSize, - spanOptions: spanOptions - })]; - case 2: - response = _b.sent(); - wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, blobs: response.blobs.map(function (blob) { - var _a; - var tagValue = ""; - if (((_a = blob.tags) === null || _a === void 0 ? void 0 : _a.blobTagSet.length) === 1) { - tagValue = blob.tags.blobTagSet[0].value; - } - return tslib.__assign(tslib.__assign({}, blob), { tags: toTags(blob.tags), tagValue: tagValue }); - }) }); - return [2 /*return*/, wrappedResponse]; - case 3: - e_9 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_9.message - }); - throw e_9; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + AccountSASResourceTypes.prototype.toString = function () { + var resourceTypes = []; + if (this.service) { + resourceTypes.push("s"); + } + if (this.container) { + resourceTypes.push("c"); + } + if (this.object) { + resourceTypes.push("o"); + } + return resourceTypes.join(""); }; + return AccountSASResourceTypes; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * This is a helper class to construct a string representing the services accessible by an AccountSAS. Setting a value + * to true means that any SAS which uses these permissions will grant access to that service. Once all the + * values are set, this should be serialized with toString and set as the services field on an + * {@link AccountSASSignatureValues} object. It is possible to construct the services string without this class, but + * the order of the services is particular and this class guarantees correctness. + * + * @export + * @class AccountSASServices + */ +var AccountSASServices = /** @class */ (function () { + function AccountSASServices() { + /** + * Permission to access blob resources granted. + * + * @type {boolean} + * @memberof AccountSASServices + */ + this.blob = false; + /** + * Permission to access file resources granted. + * + * @type {boolean} + * @memberof AccountSASServices + */ + this.file = false; + /** + * Permission to access queue resources granted. + * + * @type {boolean} + * @memberof AccountSASServices + */ + this.queue = false; + /** + * Permission to access table resources granted. + * + * @type {boolean} + * @memberof AccountSASServices + */ + this.table = false; + } /** - * Returns an AsyncIterableIterator for ServiceFindBlobsByTagsSegmentResponse. + * Creates an {@link AccountSASServices} from the specified services string. This method will throw an + * Error if it encounters a character that does not correspond to a valid service. * - * @private - * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param {string} [marker] A string value that identifies the portion of - * the list of blobs to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all blobs remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to find blobs by tags. - * @returns {AsyncIterableIterator} - * @memberof BlobServiceClient + * @static + * @param {string} services + * @returns {AccountSASServices} + * @memberof AccountSASServices */ - BlobServiceClient.prototype.findBlobsByTagsSegments = function (tagFilterSqlExpression, marker, options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function findBlobsByTagsSegments_1() { - var response; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!(!!marker || marker === undefined)) return [3 /*break*/, 6]; - _a.label = 1; - case 1: return [4 /*yield*/, tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker, options))]; - case 2: - response = _a.sent(); - response.blobs = response.blobs || []; - marker = response.continuationToken; - return [4 /*yield*/, tslib.__await(response)]; - case 3: return [4 /*yield*/, _a.sent()]; - case 4: - _a.sent(); - _a.label = 5; - case 5: - if (marker) return [3 /*break*/, 1]; - _a.label = 6; - case 6: return [2 /*return*/]; - } - }); - }); + AccountSASServices.parse = function (services) { + var accountSASServices = new AccountSASServices(); + for (var _i = 0, services_1 = services; _i < services_1.length; _i++) { + var c = services_1[_i]; + switch (c) { + case "b": + accountSASServices.blob = true; + break; + case "f": + accountSASServices.file = true; + break; + case "q": + accountSASServices.queue = true; + break; + case "t": + accountSASServices.table = true; + break; + default: + throw new RangeError("Invalid service character: " + c); + } + } + return accountSASServices; }; /** - * Returns an AsyncIterableIterator for blobs. + * Converts the given services to a string. * - * @private - * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to findBlobsByTagsItems. - * @returns {AsyncIterableIterator} - * @memberof BlobServiceClient + * @returns {string} + * @memberof AccountSASServices */ - BlobServiceClient.prototype.findBlobsByTagsItems = function (tagFilterSqlExpression, options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function findBlobsByTagsItems_1() { - var marker, _a, _b, segment, e_10_1; - var e_10, _c; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _d.trys.push([0, 7, 8, 13]); - _a = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker, options)); - _d.label = 1; - case 1: return [4 /*yield*/, tslib.__await(_a.next())]; - case 2: - if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; - segment = _b.value; - return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs)))]; - case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; - case 4: - _d.sent(); - _d.label = 5; - case 5: return [3 /*break*/, 1]; - case 6: return [3 /*break*/, 13]; - case 7: - e_10_1 = _d.sent(); - e_10 = { error: e_10_1 }; - return [3 /*break*/, 13]; - case 8: - _d.trys.push([8, , 11, 12]); - if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; - return [4 /*yield*/, tslib.__await(_c.call(_a))]; - case 9: - _d.sent(); - _d.label = 10; - case 10: return [3 /*break*/, 12]; - case 11: - if (e_10) throw e_10.error; - return [7 /*endfinally*/]; - case 12: return [7 /*endfinally*/]; - case 13: return [2 /*return*/]; - } - }); - }); + AccountSASServices.prototype.toString = function () { + var services = []; + if (this.blob) { + services.push("b"); + } + if (this.table) { + services.push("t"); + } + if (this.queue) { + services.push("q"); + } + if (this.file) { + services.push("f"); + } + return services.join(""); }; + return AccountSASServices; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * Generate SasIPRange format string. For example: + * + * "8.8.8.8" or "1.1.1.1-255.255.255.255" + * + * @export + * @param {SasIPRange} ipRange + * @returns {string} + */ +function ipRangeToString(ipRange) { + return ipRange.end ? ipRange.start + "-" + ipRange.end : ipRange.start; +} + +// Copyright (c) Microsoft Corporation. All rights reserved. +(function (SASProtocol) { /** - * Returns an async iterable iterator to find all blobs with specified tag - * under the specified account. - * - * .byPage() returns an async iterable iterator to list the blobs in pages. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties - * - * Example using `for await` syntax: - * - * ```js - * let i = 1; - * for await (const blob of blobServiceClient.findBlobsByTags("tagkey='tagvalue'")) { - * console.log(`Blob ${i++}: ${container.name}`); - * } - * ``` - * - * Example using `iter.next()`: - * - * ```js - * let i = 1; - * const iter = blobServiceClient.findBlobsByTags("tagkey='tagvalue'"); - * let blobItem = await iter.next(); - * while (!blobItem.done) { - * console.log(`Blob ${i++}: ${blobItem.value.name}`); - * blobItem = await iter.next(); - * } - * ``` - * - * Example using `byPage()`: - * - * ```js - * // passing optional maxPageSize in the page settings - * let i = 1; - * for await (const response of blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { - * if (response.blobs) { - * for (const blob of response.blobs) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } - * } - * ``` - * - * Example using paging with a marker: - * - * ```js - * let i = 1; - * let iterator = blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); - * let response = (await iterator.next()).value; - * - * // Prints 2 blob names - * if (response.blobs) { - * for (const blob of response.blobs) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } - * - * // Gets next marker - * let marker = response.continuationToken; - * // Passing next marker as continuationToken - * iterator = blobServiceClient - * .findBlobsByTags("tagkey='tagvalue'") - * .byPage({ continuationToken: marker, maxPageSize: 10 }); - * response = (await iterator.next()).value; - * - * // Prints blob names - * if (response.blobs) { - * for (const blob of response.blobs) { - * console.log(`Blob ${i++}: ${blob.name}`); - * } - * } - * ``` + * Protocol that allows HTTPS only + */ + SASProtocol["Https"] = "https"; + /** + * Protocol that allows both HTTPS and HTTP + */ + SASProtocol["HttpsAndHttp"] = "https,http"; +})(exports.SASProtocol || (exports.SASProtocol = {})); +/** + * Represents the components that make up an Azure Storage SAS' query parameters. This type is not constructed directly + * by the user; it is only generated by the {@link AccountSASSignatureValues} and {@link BlobSASSignatureValues} + * types. Once generated, it can be encoded into a {@code String} and appended to a URL directly (though caution should + * be taken here in case there are existing query parameters, which might affect the appropriate means of appending + * these query parameters). + * + * NOTE: Instances of this class are immutable. + * + * @export + * @class SASQueryParameters + */ +var SASQueryParameters = /** @class */ (function () { + /** + * Creates an instance of SASQueryParameters. + * + * @param {string} version Representing the storage version + * @param {string} signature Representing the signature for the SAS token + * @param {string} [permissions] Representing the storage permissions + * @param {string} [services] Representing the storage services being accessed (only for Account SAS) + * @param {string} [resourceTypes] Representing the storage resource types being accessed (only for Account SAS) + * @param {SASProtocol} [protocol] Representing the allowed HTTP protocol(s) + * @param {Date} [startsOn] Representing the start time for this SAS token + * @param {Date} [expiresOn] Representing the expiry time for this SAS token + * @param {SasIPRange} [ipRange] Representing the range of valid IP addresses for this SAS token + * @param {string} [identifier] Representing the signed identifier (only for Service SAS) + * @param {string} [resource] Representing the storage container or blob (only for Service SAS) + * @param {string} [cacheControl] Representing the cache-control header (only for Blob/File Service SAS) + * @param {string} [contentDisposition] Representing the content-disposition header (only for Blob/File Service SAS) + * @param {string} [contentEncoding] Representing the content-encoding header (only for Blob/File Service SAS) + * @param {string} [contentLanguage] Representing the content-language header (only for Blob/File Service SAS) + * @param {string} [contentType] Representing the content-type header (only for Blob/File Service SAS) + * @param {userDelegationKey} [userDelegationKey] Representing the user delegation key properties + * @memberof SASQueryParameters + */ + function SASQueryParameters(version, signature, permissions, services, resourceTypes, protocol, startsOn, expiresOn, ipRange, identifier, resource, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType, userDelegationKey) { + this.version = version; + this.services = services; + this.resourceTypes = resourceTypes; + this.expiresOn = expiresOn; + this.permissions = permissions; + this.protocol = protocol; + this.startsOn = startsOn; + this.ipRangeInner = ipRange; + this.identifier = identifier; + this.resource = resource; + this.signature = signature; + this.cacheControl = cacheControl; + this.contentDisposition = contentDisposition; + this.contentEncoding = contentEncoding; + this.contentLanguage = contentLanguage; + this.contentType = contentType; + if (userDelegationKey) { + this.signedOid = userDelegationKey.signedObjectId; + this.signedTenantId = userDelegationKey.signedTenantId; + this.signedStartsOn = userDelegationKey.signedStartsOn; + this.signedExpiresOn = userDelegationKey.signedExpiresOn; + this.signedService = userDelegationKey.signedService; + this.signedVersion = userDelegationKey.signedVersion; + } + } + Object.defineProperty(SASQueryParameters.prototype, "ipRange", { + /** + * Optional. IP range allowed for this SAS. + * + * @readonly + * @type {(SasIPRange | undefined)} + * @memberof SASQueryParameters + */ + get: function () { + if (this.ipRangeInner) { + return { + end: this.ipRangeInner.end, + start: this.ipRangeInner.start + }; + } + return undefined; + }, + enumerable: false, + configurable: true + }); + /** + * Encodes all SAS query parameters into a string that can be appended to a URL. * - * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. - * The given expression must evaluate to true for a blob to be returned in the results. - * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; - * however, only a subset of the OData filter syntax is supported in the Blob service. - * @param {ServiceFindBlobByTagsOptions} [options={}] Options to find blobs by tags. - * @returns {PagedAsyncIterableIterator} - * @memberof BlobServiceClient + * @returns {string} + * @memberof SASQueryParameters */ - BlobServiceClient.prototype.findBlobsByTags = function (tagFilterSqlExpression, options) { - var _a; - var _this = this; - if (options === void 0) { options = {}; } - // AsyncIterableIterator to iterate over blobs - var listSegmentOptions = tslib.__assign({}, options); - var iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); - return _a = { - /** - * @member {Promise} [next] The next method, part of the iteration protocol - */ - next: function () { - return iter.next(); - } - }, - /** - * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol - */ - _a[Symbol.asyncIterator] = function () { - return this; - }, - /** - * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time - */ - _a.byPage = function (settings) { - if (settings === void 0) { settings = {}; } - return _this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); - }, - _a; + SASQueryParameters.prototype.toString = function () { + var params = [ + "sv", + "ss", + "srt", + "spr", + "st", + "se", + "sip", + "si", + "skoid", + "sktid", + "skt", + "ske", + "sks", + "skv", + "sr", + "sp", + "sig", + "rscc", + "rscd", + "rsce", + "rscl", + "rsct" + ]; + var queries = []; + for (var _i = 0, params_1 = params; _i < params_1.length; _i++) { + var param = params_1[_i]; + switch (param) { + case "sv": + this.tryAppendQueryParameter(queries, param, this.version); + break; + case "ss": + this.tryAppendQueryParameter(queries, param, this.services); + break; + case "srt": + this.tryAppendQueryParameter(queries, param, this.resourceTypes); + break; + case "spr": + this.tryAppendQueryParameter(queries, param, this.protocol); + break; + case "st": + this.tryAppendQueryParameter(queries, param, this.startsOn ? truncatedISO8061Date(this.startsOn, false) : undefined); + break; + case "se": + this.tryAppendQueryParameter(queries, param, this.expiresOn ? truncatedISO8061Date(this.expiresOn, false) : undefined); + break; + case "sip": + this.tryAppendQueryParameter(queries, param, this.ipRange ? ipRangeToString(this.ipRange) : undefined); + break; + case "si": + this.tryAppendQueryParameter(queries, param, this.identifier); + break; + case "skoid": // Signed object ID + this.tryAppendQueryParameter(queries, param, this.signedOid); + break; + case "sktid": // Signed tenant ID + this.tryAppendQueryParameter(queries, param, this.signedTenantId); + break; + case "skt": // Signed key start time + this.tryAppendQueryParameter(queries, param, this.signedStartsOn ? truncatedISO8061Date(this.signedStartsOn, false) : undefined); + break; + case "ske": // Signed key expiry time + this.tryAppendQueryParameter(queries, param, this.signedExpiresOn ? truncatedISO8061Date(this.signedExpiresOn, false) : undefined); + break; + case "sks": // Signed key service + this.tryAppendQueryParameter(queries, param, this.signedService); + break; + case "skv": // Signed key version + this.tryAppendQueryParameter(queries, param, this.signedVersion); + break; + case "sr": + this.tryAppendQueryParameter(queries, param, this.resource); + break; + case "sp": + this.tryAppendQueryParameter(queries, param, this.permissions); + break; + case "sig": + this.tryAppendQueryParameter(queries, param, this.signature); + break; + case "rscc": + this.tryAppendQueryParameter(queries, param, this.cacheControl); + break; + case "rscd": + this.tryAppendQueryParameter(queries, param, this.contentDisposition); + break; + case "rsce": + this.tryAppendQueryParameter(queries, param, this.contentEncoding); + break; + case "rscl": + this.tryAppendQueryParameter(queries, param, this.contentLanguage); + break; + case "rsct": + this.tryAppendQueryParameter(queries, param, this.contentType); + break; + } + } + return queries.join("&"); }; /** - * Returns an AsyncIterableIterator for ServiceListContainersSegmentResponses + * A private helper method used to filter and append query key/value pairs into an array. * * @private - * @param {string} [marker] A string value that identifies the portion of - * the list of containers to be returned with the next listing operation. The - * operation returns the continuationToken value within the response body if the - * listing operation did not return all containers remaining to be listed - * with the current page. The continuationToken value can be used as the value for - * the marker parameter in a subsequent call to request the next page of list - * items. The marker value is opaque to the client. - * @param {ServiceListContainersSegmentOptions} [options] Options to list containers operation. - * @returns {AsyncIterableIterator} - * @memberof BlobServiceClient + * @param {string[]} queries + * @param {string} key + * @param {string} [value] + * @returns {void} + * @memberof SASQueryParameters */ - BlobServiceClient.prototype.listSegments = function (marker, options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listSegments_1() { - var listContainersSegmentResponse; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!(!!marker || marker === undefined)) return [3 /*break*/, 7]; - _a.label = 1; - case 1: return [4 /*yield*/, tslib.__await(this.listContainersSegment(marker, options))]; - case 2: - listContainersSegmentResponse = _a.sent(); - listContainersSegmentResponse.containerItems = - listContainersSegmentResponse.containerItems || []; - marker = listContainersSegmentResponse.continuationToken; - return [4 /*yield*/, tslib.__await(listContainersSegmentResponse)]; - case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_a.sent()])]; - case 4: return [4 /*yield*/, _a.sent()]; - case 5: - _a.sent(); - _a.label = 6; - case 6: - if (marker) return [3 /*break*/, 1]; - _a.label = 7; - case 7: return [2 /*return*/]; - } - }); - }); + SASQueryParameters.prototype.tryAppendQueryParameter = function (queries, key, value) { + if (!value) { + return; + } + key = encodeURIComponent(key); + value = encodeURIComponent(value); + if (key.length > 0 && value.length > 0) { + queries.push(key + "=" + value); + } }; + return SASQueryParameters; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * Generates a {@link SASQueryParameters} object which contains all SAS query parameters needed to make an actual + * REST request. + * + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas + * + * @param {AccountSASSignatureValues} accountSASSignatureValues + * @param {StorageSharedKeyCredential} sharedKeyCredential + * @returns {SASQueryParameters} + * @memberof AccountSASSignatureValues + */ +function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { + var version = accountSASSignatureValues.version + ? accountSASSignatureValues.version + : SERVICE_VERSION; + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.deleteVersion && + version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); + } + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.tag && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); + } + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.filter && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 'f' permission."); + } + var parsedPermissions = AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()); + var parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); + var parsedResourceTypes = AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString(); + var stringToSign = [ + sharedKeyCredential.accountName, + parsedPermissions, + parsedServices, + parsedResourceTypes, + accountSASSignatureValues.startsOn + ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) + : "", + truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), + accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", + accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", + version, + "" // Account SAS requires an additional newline character + ].join("\n"); + var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(version, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange); +} + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a blob. Setting + * a value to true means that any SAS which uses these permissions will grant permissions for that operation. Once all + * the values are set, this should be serialized with toString and set as the permissions field on a + * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but + * the order of the permissions is particular and this class guarantees correctness. + * + * @export + * @class BlobSASPermissions + */ +var BlobSASPermissions = /** @class */ (function () { + function BlobSASPermissions() { + /** + * Specifies Read access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.read = false; + /** + * Specifies Add access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.add = false; + /** + * Specifies Create access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.create = false; + /** + * Specifies Write access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.write = false; + /** + * Specifies Delete access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.delete = false; + /** + * Specifies Delete version access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.deleteVersion = false; + /** + * Specfies Tag access granted. + * + * @type {boolean} + * @memberof BlobSASPermissions + */ + this.tag = false; + } /** - * Returns an AsyncIterableIterator for Container Items + * Creates a {@link BlobSASPermissions} from the specified permissions string. This method will throw an + * Error if it encounters a character that does not correspond to a valid permission. * - * @private - * @param {ServiceListContainersSegmentOptions} [options] Options to list containers operation. - * @returns {AsyncIterableIterator} - * @memberof BlobServiceClient + * @static + * @param {string} permissions + * @returns {BlobSASPermissions} + * @memberof BlobSASPermissions */ - BlobServiceClient.prototype.listItems = function (options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listItems_1() { - var marker, _a, _b, segment, e_11_1; - var e_11, _c; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _d.trys.push([0, 7, 8, 13]); - _a = tslib.__asyncValues(this.listSegments(marker, options)); - _d.label = 1; - case 1: return [4 /*yield*/, tslib.__await(_a.next())]; - case 2: - if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; - segment = _b.value; - return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(segment.containerItems)))]; - case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; - case 4: - _d.sent(); - _d.label = 5; - case 5: return [3 /*break*/, 1]; - case 6: return [3 /*break*/, 13]; - case 7: - e_11_1 = _d.sent(); - e_11 = { error: e_11_1 }; - return [3 /*break*/, 13]; - case 8: - _d.trys.push([8, , 11, 12]); - if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; - return [4 /*yield*/, tslib.__await(_c.call(_a))]; - case 9: - _d.sent(); - _d.label = 10; - case 10: return [3 /*break*/, 12]; - case 11: - if (e_11) throw e_11.error; - return [7 /*endfinally*/]; - case 12: return [7 /*endfinally*/]; - case 13: return [2 /*return*/]; - } - }); - }); + BlobSASPermissions.parse = function (permissions) { + var blobSASPermissions = new BlobSASPermissions(); + for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { + var char = permissions_1[_i]; + switch (char) { + case "r": + blobSASPermissions.read = true; + break; + case "a": + blobSASPermissions.add = true; + break; + case "c": + blobSASPermissions.create = true; + break; + case "w": + blobSASPermissions.write = true; + break; + case "d": + blobSASPermissions.delete = true; + break; + case "x": + blobSASPermissions.deleteVersion = true; + break; + case "t": + blobSASPermissions.tag = true; + break; + default: + throw new RangeError("Invalid permission: " + char); + } + } + return blobSASPermissions; }; /** - * Returns an async iterable iterator to list all the containers - * under the specified account. - * - * .byPage() returns an async iterable iterator to list the containers in pages. - * - * Example using `for await` syntax: - * - * ```js - * let i = 1; - * for await (const container of blobServiceClient.listContainers()) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * ``` - * - * Example using `iter.next()`: - * - * ```js - * let i = 1; - * const iter = blobServiceClient.listContainers(); - * let containerItem = await iter.next(); - * while (!containerItem.done) { - * console.log(`Container ${i++}: ${containerItem.value.name}`); - * containerItem = await iter.next(); - * } - * ``` - * - * Example using `byPage()`: - * - * ```js - * // passing optional maxPageSize in the page settings - * let i = 1; - * for await (const response of blobServiceClient.listContainers().byPage({ maxPageSize: 20 })) { - * if (response.containerItems) { - * for (const container of response.containerItems) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * } - * } - * ``` - * - * Example using paging with a marker: - * - * ```js - * let i = 1; - * let iterator = blobServiceClient.listContainers().byPage({ maxPageSize: 2 }); - * let response = (await iterator.next()).value; - * - * // Prints 2 container names - * if (response.containerItems) { - * for (const container of response.containerItems) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * } - * - * // Gets next marker - * let marker = response.continuationToken; - * // Passing next marker as continuationToken - * iterator = blobServiceClient - * .listContainers() - * .byPage({ continuationToken: marker, maxPageSize: 10 }); - * response = (await iterator.next()).value; + * Converts the given permissions to a string. Using this method will guarantee the permissions are in an + * order accepted by the service. * - * // Prints 10 container names - * if (response.containerItems) { - * for (const container of response.containerItems) { - * console.log(`Container ${i++}: ${container.name}`); - * } - * } - * ``` + * @returns {string} A string which represents the BlobSASPermissions + * @memberof BlobSASPermissions + */ + BlobSASPermissions.prototype.toString = function () { + var permissions = []; + if (this.read) { + permissions.push("r"); + } + if (this.add) { + permissions.push("a"); + } + if (this.create) { + permissions.push("c"); + } + if (this.write) { + permissions.push("w"); + } + if (this.delete) { + permissions.push("d"); + } + if (this.deleteVersion) { + permissions.push("x"); + } + if (this.tag) { + permissions.push("t"); + } + return permissions.join(""); + }; + return BlobSASPermissions; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a container. + * Setting a value to true means that any SAS which uses these permissions will grant permissions for that operation. + * Once all the values are set, this should be serialized with toString and set as the permissions field on a + * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but + * the order of the permissions is particular and this class guarantees correctness. + * + * @export + * @class ContainerSASPermissions + */ +var ContainerSASPermissions = /** @class */ (function () { + function ContainerSASPermissions() { + /** + * Specifies Read access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.read = false; + /** + * Specifies Add access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.add = false; + /** + * Specifies Create access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.create = false; + /** + * Specifies Write access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.write = false; + /** + * Specifies Delete access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.delete = false; + /** + * Specifies Delete version access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.deleteVersion = false; + /** + * Specifies List access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.list = false; + /** + * Specfies Tag access granted. + * + * @type {boolean} + * @memberof ContainerSASPermissions + */ + this.tag = false; + } + /** + * Creates an {@link ContainerSASPermissions} from the specified permissions string. This method will throw an + * Error if it encounters a character that does not correspond to a valid permission. * - * @param {ServiceListContainersOptions} [options={}] Options to list containers. - * @returns {PagedAsyncIterableIterator} An asyncIterableIterator that supports paging. - * @memberof BlobServiceClient + * @static + * @param {string} permissions + * @returns {ContainerSASPermissions} + * @memberof ContainerSASPermissions */ - BlobServiceClient.prototype.listContainers = function (options) { - var _a; - var _this = this; - if (options === void 0) { options = {}; } - if (options.prefix === "") { - options.prefix = undefined; - } - var include = []; - if (options.includeDeleted) { - include.push("deleted"); - } - if (options.includeMetadata) { - include.push("metadata"); + ContainerSASPermissions.parse = function (permissions) { + var containerSASPermissions = new ContainerSASPermissions(); + for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { + var char = permissions_1[_i]; + switch (char) { + case "r": + containerSASPermissions.read = true; + break; + case "a": + containerSASPermissions.add = true; + break; + case "c": + containerSASPermissions.create = true; + break; + case "w": + containerSASPermissions.write = true; + break; + case "d": + containerSASPermissions.delete = true; + break; + case "l": + containerSASPermissions.list = true; + break; + case "t": + containerSASPermissions.tag = true; + break; + case "x": + containerSASPermissions.deleteVersion = true; + break; + default: + throw new RangeError("Invalid permission " + char); + } } - // AsyncIterableIterator to iterate over containers - var listSegmentOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); - var iter = this.listItems(listSegmentOptions); - return _a = { - /** - * @member {Promise} [next] The next method, part of the iteration protocol - */ - next: function () { - return iter.next(); - } - }, - /** - * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol - */ - _a[Symbol.asyncIterator] = function () { - return this; - }, - /** - * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time - */ - _a.byPage = function (settings) { - if (settings === void 0) { settings = {}; } - return _this.listSegments(settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); - }, - _a; + return containerSASPermissions; }; /** - * ONLY AVAILABLE WHEN USING BEARER TOKEN AUTHENTICATION (TokenCredential). - * - * Retrieves a user delegation key for the Blob service. This is only a valid operation when using - * bearer token authentication. + * Converts the given permissions to a string. Using this method will guarantee the permissions are in an + * order accepted by the service. * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-user-delegation-key + * The order of the characters should be as specified here to ensure correctness. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * - * @param {Date} startsOn The start time for the user delegation SAS. Must be within 7 days of the current time - * @param {Date} expiresOn The end time for the user delegation SAS. Must be within 7 days of the current time - * @returns {Promise} - * @memberof BlobServiceClient + * @returns {string} + * @memberof ContainerSASPermissions */ - BlobServiceClient.prototype.getUserDelegationKey = function (startsOn, expiresOn, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, spanOptions, response, userDelegationKey, res, e_12; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-getUserDelegationKey", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getUserDelegationKey({ - startsOn: truncatedISO8061Date(startsOn, false), - expiresOn: truncatedISO8061Date(expiresOn, false) - }, { - abortSignal: options.abortSignal, - spanOptions: spanOptions - })]; - case 2: - response = _b.sent(); - userDelegationKey = { - signedObjectId: response.signedObjectId, - signedTenantId: response.signedTenantId, - signedStartsOn: new Date(response.signedStartsOn), - signedExpiresOn: new Date(response.signedExpiresOn), - signedService: response.signedService, - signedVersion: response.signedVersion, - value: response.value - }; - res = tslib.__assign({ _response: response._response, requestId: response.requestId, clientRequestId: response.clientRequestId, version: response.version, date: response.date, errorCode: response.errorCode }, userDelegationKey); - return [2 /*return*/, res]; - case 3: - e_12 = _b.sent(); - span.setStatus({ - code: api.CanonicalCode.UNKNOWN, - message: e_12.message - }); - throw e_12; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } - }); - }); + ContainerSASPermissions.prototype.toString = function () { + var permissions = []; + if (this.read) { + permissions.push("r"); + } + if (this.add) { + permissions.push("a"); + } + if (this.create) { + permissions.push("c"); + } + if (this.write) { + permissions.push("w"); + } + if (this.delete) { + permissions.push("d"); + } + if (this.deleteVersion) { + permissions.push("x"); + } + if (this.list) { + permissions.push("l"); + } + if (this.tag) { + permissions.push("t"); + } + return permissions.join(""); }; + return ContainerSASPermissions; +}()); + +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * + * UserDelegationKeyCredential is only used for generation of user delegation SAS. + * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas + * + * @export + * @class UserDelegationKeyCredential + */ +var UserDelegationKeyCredential = /** @class */ (function () { /** - * Creates a BlobBatchClient object to conduct batch operations. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch - * - * @returns {BlobBatchClient} A new BlobBatchClient object for this service. - * @memberof BlobServiceClient + * Creates an instance of UserDelegationKeyCredential. + * @param {string} accountName + * @param {UserDelegationKey} userDelegationKey + * @memberof UserDelegationKeyCredential */ - BlobServiceClient.prototype.getBlobBatchClient = function () { - return new BlobBatchClient(this.url, this.pipeline); - }; + function UserDelegationKeyCredential(accountName, userDelegationKey) { + this.accountName = accountName; + this.userDelegationKey = userDelegationKey; + this.key = Buffer.from(userDelegationKey.value, "base64"); + } /** - * Only available for BlobServiceClient constructed with a shared key credential. - * - * Generates a Blob account Shared Access Signature (SAS) URI based on the client properties - * and parameters passed in. The SAS is signed by the shared key credential of the client. - * - * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-account-sas + * Generates a hash signature for an HTTP request or for a SAS. * - * @param {Date} expiresOn Optional. The time at which the shared access signature becomes invalid. Default to an hour later if not provided. - * @param {AccountSASPermissions} [permissions=AccountSASPermissions.parse("r")] Specifies the list of permissions to be associated with the SAS. - * @param {string} [resourceTypes="sco"] Specifies the resource types associated with the shared access signature. - * @param {ServiceGenerateAccountSasUrlOptions} [options={}] Optional parameters. - * @returns {string} An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. - * @memberof BlobServiceClient + * @param {string} stringToSign + * @returns {string} + * @memberof UserDelegationKeyCredential */ - BlobServiceClient.prototype.generateAccountSasUrl = function (expiresOn, permissions, resourceTypes, options) { - if (permissions === void 0) { permissions = AccountSASPermissions.parse("r"); } - if (resourceTypes === void 0) { resourceTypes = "sco"; } - if (options === void 0) { options = {}; } - if (!(this.credential instanceof StorageSharedKeyCredential)) { - throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); + UserDelegationKeyCredential.prototype.computeHMACSHA256 = function (stringToSign) { + // console.log(`stringToSign: ${JSON.stringify(stringToSign)}`); + return crypto.createHmac("sha256", this.key) + .update(stringToSign, "utf8") + .digest("base64"); + }; + return UserDelegationKeyCredential; +}()); + +// Copyright (c) Microsoft Corporation. All rights reserved. +function generateBlobSASQueryParameters(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { + var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + var sharedKeyCredential = sharedKeyCredentialOrUserDelegationKey instanceof StorageSharedKeyCredential + ? sharedKeyCredentialOrUserDelegationKey + : undefined; + var userDelegationKeyCredential; + if (sharedKeyCredential === undefined && accountName !== undefined) { + userDelegationKeyCredential = new UserDelegationKeyCredential(accountName, sharedKeyCredentialOrUserDelegationKey); + } + if (sharedKeyCredential === undefined && userDelegationKeyCredential === undefined) { + throw TypeError("Invalid sharedKeyCredential, userDelegationKey or accountName."); + } + // Version 2019-12-12 adds support for the blob tags permission. + // Version 2018-11-09 adds support for the signed resource and signed blob snapshot time fields. + // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas#constructing-the-signature-string + if (version >= "2018-11-09") { + if (sharedKeyCredential !== undefined) { + return generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential); + } + else { + return generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential); } - if (expiresOn === undefined) { - var now = new Date(); - expiresOn = new Date(now.getTime() + 3600 * 1000); + } + if (version >= "2015-04-05") { + if (sharedKeyCredential !== undefined) { + return generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential); } - var sas = generateAccountSASQueryParameters(tslib.__assign({ permissions: permissions, - expiresOn: expiresOn, - resourceTypes: resourceTypes, services: AccountSASServices.parse("b").toString() }, options), this.credential).toString(); - return appendToURLQuery(this.url, sas); - }; - return BlobServiceClient; -}(StorageClient)); + else { + throw new RangeError("'version' must be >= '2018-11-09' when generating user delegation SAS using user delegation key."); + } + } + throw new RangeError("'version' must be >= '2015-04-05'."); +} +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * IMPLEMENTATION FOR API VERSION FROM 2015-04-05 AND BEFORE 2018-11-09. + * + * Creates an instance of SASQueryParameters. + * + * Only accepts required settings needed to create a SAS. For optional settings please + * set corresponding properties directly, such as permissions, startsOn and identifier. + * + * WARNING: When identifier is not provided, permissions and expiresOn are required. + * You MUST assign value to identifier or expiresOn & permissions manually if you initial with + * this constructor. + * + * @param {BlobSASSignatureValues} blobSASSignatureValues + * @param {StorageSharedKeyCredential} sharedKeyCredential + * @returns {SASQueryParameters} + */ +function generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential) { + if (!blobSASSignatureValues.identifier && + !blobSASSignatureValues.permissions && + !blobSASSignatureValues.expiresOn) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); + } + var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + var resource = "c"; + var verifiedPermissions; + if (blobSASSignatureValues.snapshotTime) { + throw RangeError("'version' must be >= '2018-11-09' when provided 'snapshotTime'."); + } + if (blobSASSignatureValues.versionId) { + throw RangeError("'version' must be >= '2019-10-10' when provided 'versionId'."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.deleteVersion && + version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.tag && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); + } + if (blobSASSignatureValues.blobName) { + resource = "b"; + } + // Calling parse and toString guarantees the proper ordering and throws on invalid characters. + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + // Signature is generated on the un-url-encoded values. + var stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn + ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) + : "", + blobSASSignatureValues.expiresOn + ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) + : "", + getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + blobSASSignatureValues.identifier, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + version, + blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", + blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", + blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", + blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", + blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" + ].join("\n"); + var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); +} +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. + * + * Creates an instance of SASQueryParameters. + * + * Only accepts required settings needed to create a SAS. For optional settings please + * set corresponding properties directly, such as permissions, startsOn and identifier. + * + * WARNING: When identifier is not provided, permissions and expiresOn are required. + * You MUST assign value to identifier or expiresOn & permissions manually if you initial with + * this constructor. + * + * @param {BlobSASSignatureValues} blobSASSignatureValues + * @param {StorageSharedKeyCredential} sharedKeyCredential + * @returns {SASQueryParameters} + */ +function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential) { + if (!blobSASSignatureValues.identifier && + !blobSASSignatureValues.permissions && + !blobSASSignatureValues.expiresOn) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); + } + var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + var resource = "c"; + var verifiedPermissions; + if (blobSASSignatureValues.versionId && version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'versionId'."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.deleteVersion && + version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.tag && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); + } + if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.snapshotTime) { + throw RangeError("Must provide 'blobName' when provided 'snapshotTime'."); + } + if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.versionId) { + throw RangeError("Must provide 'blobName' when provided 'versionId'."); + } + var timestamp = blobSASSignatureValues.snapshotTime; + if (blobSASSignatureValues.blobName) { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } + else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } + } + // Calling parse and toString guarantees the proper ordering and throws on invalid characters. + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + // Signature is generated on the un-url-encoded values. + var stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn + ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) + : "", + blobSASSignatureValues.expiresOn + ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) + : "", + getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + blobSASSignatureValues.identifier, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + version, + resource, + timestamp, + blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", + blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", + blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", + blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", + blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" + ].join("\n"); + var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); +} +/** + * ONLY AVAILABLE IN NODE.JS RUNTIME. + * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. + * + * Creates an instance of SASQueryParameters. + * + * Only accepts required settings needed to create a SAS. For optional settings please + * set corresponding properties directly, such as permissions, startsOn and identifier. + * + * WARNING: identifier will be ignored, permissions and expiresOn are required. + * + * @param {BlobSASSignatureValues} blobSASSignatureValues + * @param {UserDelegationKeyCredential} userDelegationKeyCredential + * @returns {SASQueryParameters} + */ +function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential) { + if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { + throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); + } + var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + if (blobSASSignatureValues.versionId && version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'versionId'."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.deleteVersion && + version < "2019-10-10") { + throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); + } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.tag && + version < "2019-12-12") { + throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); + } + var resource = "c"; + var verifiedPermissions; + if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.snapshotTime) { + throw RangeError("Must provide 'blobName' when provided 'snapshotTime'."); + } + if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.versionId) { + throw RangeError("Must provide 'blobName' when provided 'versionId'."); + } + var timestamp = blobSASSignatureValues.snapshotTime; + if (blobSASSignatureValues.blobName) { + resource = "b"; + if (blobSASSignatureValues.snapshotTime) { + resource = "bs"; + } + else if (blobSASSignatureValues.versionId) { + resource = "bv"; + timestamp = blobSASSignatureValues.versionId; + } + } + // Calling parse and toString guarantees the proper ordering and throws on invalid characters. + if (blobSASSignatureValues.permissions) { + if (blobSASSignatureValues.blobName) { + verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + else { + verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); + } + } + // Signature is generated on the un-url-encoded values. + var stringToSign = [ + verifiedPermissions ? verifiedPermissions : "", + blobSASSignatureValues.startsOn + ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) + : "", + blobSASSignatureValues.expiresOn + ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) + : "", + getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), + userDelegationKeyCredential.userDelegationKey.signedObjectId, + userDelegationKeyCredential.userDelegationKey.signedTenantId, + userDelegationKeyCredential.userDelegationKey.signedStartsOn + ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) + : "", + userDelegationKeyCredential.userDelegationKey.signedExpiresOn + ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) + : "", + userDelegationKeyCredential.userDelegationKey.signedService, + userDelegationKeyCredential.userDelegationKey.signedVersion, + blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", + blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", + version, + resource, + timestamp, + blobSASSignatureValues.cacheControl, + blobSASSignatureValues.contentDisposition, + blobSASSignatureValues.contentEncoding, + blobSASSignatureValues.contentLanguage, + blobSASSignatureValues.contentType + ].join("\n"); + var signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); + return new SASQueryParameters(version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey); +} +function getCanonicalName(accountName, containerName, blobName) { + // Container: "/blob/account/containerName" + // Blob: "/blob/account/containerName/blobName" + var elements = ["/blob/" + accountName + "/" + containerName]; + if (blobName) { + elements.push("/" + blobName); + } + return elements.join(""); +} Object.defineProperty(exports, 'BaseRequestPolicy', { enumerable: true, @@ -36471,20 +35756,10 @@ exports.newPipeline = newPipeline; "use strict"; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; Object.defineProperty(exports, "__esModule", { value: true }); -const path = __importStar(__webpack_require__(622)); -const pathHelper = __importStar(__webpack_require__(972)); -const assert_1 = __importDefault(__webpack_require__(357)); +const assert = __webpack_require__(357); +const path = __webpack_require__(622); +const pathHelper = __webpack_require__(972); const IS_WINDOWS = process.platform === 'win32'; /** * Helper class for parsing paths into segments @@ -36498,7 +35773,7 @@ class Path { this.segments = []; // String if (typeof itemPath === 'string') { - assert_1.default(itemPath, `Parameter 'itemPath' must not be empty`); + assert(itemPath, `Parameter 'itemPath' must not be empty`); // Normalize slashes and trim unnecessary trailing slash itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); // Not rooted @@ -36525,24 +35800,24 @@ class Path { // Array else { // Must not be empty - assert_1.default(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`); + assert(itemPath.length > 0, `Parameter 'itemPath' must not be an empty array`); // Each segment for (let i = 0; i < itemPath.length; i++) { let segment = itemPath[i]; // Must not be empty - assert_1.default(segment, `Parameter 'itemPath' must not contain any empty segments`); + assert(segment, `Parameter 'itemPath' must not contain any empty segments`); // Normalize slashes segment = pathHelper.normalizeSeparators(itemPath[i]); // Root segment if (i === 0 && pathHelper.hasRoot(segment)) { segment = pathHelper.safeTrimTrailingSeparator(segment); - assert_1.default(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`); + assert(segment === pathHelper.dirname(segment), `Parameter 'itemPath' root segment contains information for multiple segments`); this.segments.push(segment); } // All other segments else { // Must not contain slash - assert_1.default(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`); + assert(!segment.includes(path.sep), `Parameter 'itemPath' contains unexpected path separators`); this.segments.push(segment); } } @@ -39478,7 +38753,288 @@ module.exports = require("crypto"); /* 419 */, /* 420 */, /* 421 */, -/* 422 */, +/* 422 */ +/***/ (function(module) { + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ +/* global global, define, System, Reflect, Promise */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if ( true && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + + __extends = function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __exportStar = function (m, exports) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; + }; + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, privateMap) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return privateMap.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, privateMap, value) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to set private field on non-instance"); + } + privateMap.set(receiver, value); + return value; + } + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); +}); + + +/***/ }), /* 423 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -40085,31 +39641,20 @@ const utils = __importStar(__webpack_require__(15)); const constants_1 = __webpack_require__(931); function getTarPath(args, compressionMethod) { return __awaiter(this, void 0, void 0, function* () { - switch (process.platform) { - case 'win32': { - const systemTar = `${process.env['windir']}\\System32\\tar.exe`; - if (compressionMethod !== constants_1.CompressionMethod.Gzip) { - // We only use zstandard compression on windows when gnu tar is installed due to - // a bug with compressing large files with bsdtar + zstd - args.push('--force-local'); - } - else if (fs_1.existsSync(systemTar)) { - return systemTar; - } - else if (yield utils.isGnuTarInstalled()) { - args.push('--force-local'); - } - break; + const IS_WINDOWS = process.platform === 'win32'; + if (IS_WINDOWS) { + const systemTar = `${process.env['windir']}\\System32\\tar.exe`; + if (compressionMethod !== constants_1.CompressionMethod.Gzip) { + // We only use zstandard compression on windows when gnu tar is installed due to + // a bug with compressing large files with bsdtar + zstd + args.push('--force-local'); } - case 'darwin': { - const gnuTar = yield io.which('gtar', false); - if (gnuTar) { - return gnuTar; - } - break; + else if (fs_1.existsSync(systemTar)) { + return systemTar; + } + else if (yield utils.isGnuTarInstalled()) { + args.push('--force-local'); } - default: - break; } return yield io.which('tar', true); }); @@ -40194,32 +39739,6 @@ function createTar(archiveFolder, sourceDirectories, compressionMethod) { }); } exports.createTar = createTar; -function listTar(archivePath, compressionMethod) { - return __awaiter(this, void 0, void 0, function* () { - // --d: Decompress. - // --long=#: Enables long distance matching with # bits. - // Maximum is 30 (1GB) on 32-bit OS and 31 (2GB) on 64-bit. - // Using 30 here because we also support 32-bit self-hosted runners. - function getCompressionProgram() { - switch (compressionMethod) { - case constants_1.CompressionMethod.Zstd: - return ['--use-compress-program', 'zstd -d --long=30']; - case constants_1.CompressionMethod.ZstdWithoutLong: - return ['--use-compress-program', 'zstd -d']; - default: - return ['-z']; - } - } - const args = [ - ...getCompressionProgram(), - '-tf', - archivePath.replace(new RegExp(`\\${path.sep}`, 'g'), '/'), - '-P' - ]; - yield execTar(args, compressionMethod); - }); -} -exports.listTar = listTar; //# sourceMappingURL=tar.js.map /***/ }), @@ -40297,7 +39816,7 @@ __exportStar(__webpack_require__(975), exports); __exportStar(__webpack_require__(70), exports); __exportStar(__webpack_require__(694), exports); __exportStar(__webpack_require__(695), exports); -var context_base_1 = __webpack_require__(459); +var context_base_1 = __webpack_require__(231); Object.defineProperty(exports, "Context", { enumerable: true, get: function () { return context_base_1.Context; } }); var context_1 = __webpack_require__(492); /** Entrypoint for context API */ @@ -42519,35 +42038,7 @@ exports.FetchError = FetchError; /***/ }), -/* 459 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -/*! - * Copyright 2019, OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function __export(m) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; -} -Object.defineProperty(exports, "__esModule", { value: true }); -__export(__webpack_require__(560)); -__export(__webpack_require__(53)); -//# sourceMappingURL=index.js.map - -/***/ }), +/* 459 */, /* 460 */ /***/ (function(module) { @@ -43140,7 +42631,7 @@ exports.getState = getState; */ Object.defineProperty(exports, "__esModule", { value: true }); exports.ContextAPI = void 0; -var context_base_1 = __webpack_require__(459); +var context_base_1 = __webpack_require__(231); var global_utils_1 = __webpack_require__(976); var NOOP_CONTEXT_MANAGER = new context_base_1.NoopContextManager(); /** @@ -45491,90 +44982,7 @@ exports.defaultSetter = defaultSetter; /***/ }), -/* 560 */ -/***/ (function(__unusedmodule, exports) { - -"use strict"; - -/*! - * Copyright 2020, OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -/** - * Class which stores and manages current context values. All methods which - * update context such as get and delete do not modify an existing context, - * but create a new one with updated values. - */ -class Context { - /** - * Construct a new context which inherits values from an optional parent context. - * - * @param parentContext a context from which to inherit values - */ - constructor(parentContext) { - this._currentContext = parentContext ? new Map(parentContext) : new Map(); - } - /** Get a key to uniquely identify a context value */ - static createKey(description) { - return Symbol(description); - } - /** - * Get a value from the context. - * - * @param key key which identifies a context value - */ - getValue(key) { - return this._currentContext.get(key); - } - /** - * Create a new context which inherits from this context and has - * the given key set to the given value. - * - * @param key context key for which to set the value - * @param value value to set for the given key - */ - setValue(key, value) { - const context = new Context(this._currentContext); - context._currentContext.set(key, value); - return context; - } - /** - * Return a new context which inherits from this context but does - * not contain a value for the given key. - * - * @param key context key for which to clear a value - */ - deleteValue(key) { - const context = new Context(this._currentContext); - context._currentContext.delete(key); - return context; - } -} -exports.Context = Context; -/** The root context is used as the default parent context when there is no active context */ -Context.ROOT_CONTEXT = new Context(); -/** - * This is another identifier to the root context which allows developers to easily search the - * codebase for direct uses of context which need to be removed in later PRs. - * - * It's existence is temporary and it should be removed when all references are fixed. - */ -Context.TODO = Context.ROOT_CONTEXT; -//# sourceMappingURL=context.js.map - -/***/ }), +/* 560 */, /* 561 */, /* 562 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { @@ -45889,15 +45297,8 @@ Object.defineProperty(exports, "__esModule", { value: true }); "use strict"; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; Object.defineProperty(exports, "__esModule", { value: true }); -const pathHelper = __importStar(__webpack_require__(972)); +const pathHelper = __webpack_require__(972); const internal_match_kind_1 = __webpack_require__(327); const IS_WINDOWS = process.platform === 'win32'; /** @@ -45979,15 +45380,8 @@ exports.partialMatch = partialMatch; "use strict"; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; Object.defineProperty(exports, "__esModule", { value: true }); -const core = __importStar(__webpack_require__(470)); +const core = __webpack_require__(470); /** * Returns a copy with defaults filled in. */ @@ -47079,13 +46473,9 @@ function restoreCache(paths, primaryKey, restoreKeys, options) { try { // Download the cache from the cache entry yield cacheHttpClient.downloadCache(cacheEntry.archiveLocation, archivePath, options); - if (core.isDebug()) { - yield tar_1.listTar(archivePath, compressionMethod); - } const archiveFileSize = utils.getArchiveFileSizeIsBytes(archivePath); core.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); yield tar_1.extractTar(archivePath, compressionMethod); - core.info('Cache restored successfully'); } finally { // Try to delete the archive to save space @@ -47128,9 +46518,6 @@ function saveCache(paths, key, options) { const archivePath = path.join(archiveFolder, utils.getCacheFileName(compressionMethod)); core.debug(`Archive Path: ${archivePath}`); yield tar_1.createTar(archiveFolder, cachePaths, compressionMethod); - if (core.isDebug()) { - yield tar_1.listTar(archivePath, compressionMethod); - } const fileSizeLimit = 5 * 1024 * 1024 * 1024; // 5GB per repo limit const archiveFileSize = utils.getArchiveFileSizeIsBytes(archivePath); core.debug(`File Size: ${archiveFileSize}`); @@ -47231,316 +46618,7 @@ exports.saveCache = saveCache; /***/ }), -/* 640 */ -/***/ (function(module) { - -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global global, define, System, Reflect, Promise */ -var __extends; -var __assign; -var __rest; -var __decorate; -var __param; -var __metadata; -var __awaiter; -var __generator; -var __exportStar; -var __values; -var __read; -var __spread; -var __spreadArrays; -var __spreadArray; -var __await; -var __asyncGenerator; -var __asyncDelegator; -var __asyncValues; -var __makeTemplateObject; -var __importStar; -var __importDefault; -var __classPrivateFieldGet; -var __classPrivateFieldSet; -var __createBinding; -(function (factory) { - var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; - if (typeof define === "function" && define.amd) { - define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); - } - else if ( true && typeof module.exports === "object") { - factory(createExporter(root, createExporter(module.exports))); - } - else { - factory(createExporter(root)); - } - function createExporter(exports, previous) { - if (exports !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports, "__esModule", { value: true }); - } - else { - exports.__esModule = true; - } - } - return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; - } -}) -(function (exporter) { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - - __extends = function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - - __assign = Object.assign || function (t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - - __rest = function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; - - __decorate = function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - - __param = function (paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - }; - - __metadata = function (metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - }; - - __awaiter = function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - - __generator = function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - - __exportStar = function(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); - }; - - __createBinding = Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); - }) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }); - - __values = function (o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - - __read = function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - - /** @deprecated */ - __spread = function () { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; - }; - - /** @deprecated */ - __spreadArrays = function () { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; - }; - - __spreadArray = function (to, from) { - for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) - to[j] = from[i]; - return to; - }; - - __await = function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - - __asyncGenerator = function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - }; - - __asyncDelegator = function (o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } - }; - - __asyncValues = function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } - }; - - __makeTemplateObject = function (cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; - }; - - var __setModuleDefault = Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }; - - __importStar = function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; - }; - - __importDefault = function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - - __classPrivateFieldGet = function (receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - return privateMap.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, privateMap, value) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - privateMap.set(receiver, value); - return value; - }; - - exporter("__extends", __extends); - exporter("__assign", __assign); - exporter("__rest", __rest); - exporter("__decorate", __decorate); - exporter("__param", __param); - exporter("__metadata", __metadata); - exporter("__awaiter", __awaiter); - exporter("__generator", __generator); - exporter("__exportStar", __exportStar); - exporter("__createBinding", __createBinding); - exporter("__values", __values); - exporter("__read", __read); - exporter("__spread", __spread); - exporter("__spreadArrays", __spreadArrays); - exporter("__spreadArray", __spreadArray); - exporter("__await", __await); - exporter("__asyncGenerator", __asyncGenerator); - exporter("__asyncDelegator", __asyncDelegator); - exporter("__asyncValues", __asyncValues); - exporter("__makeTemplateObject", __makeTemplateObject); - exporter("__importStar", __importStar); - exporter("__importDefault", __importDefault); - exporter("__classPrivateFieldGet", __classPrivateFieldGet); - exporter("__classPrivateFieldSet", __classPrivateFieldSet); -}); - - -/***/ }), +/* 640 */, /* 641 */, /* 642 */, /* 643 */, @@ -50512,7 +49590,87 @@ __webpack_require__(71); /***/ }), /* 713 */, /* 714 */, -/* 715 */, +/* 715 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Context = void 0; +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var Context = /** @class */ (function () { + /** + * Construct a new context which inherits values from an optional parent context. + * + * @param parentContext a context from which to inherit values + */ + function Context(parentContext) { + this._currentContext = parentContext ? new Map(parentContext) : new Map(); + } + /** Get a key to uniquely identify a context value */ + Context.createKey = function (description) { + return Symbol(description); + }; + /** + * Get a value from the context. + * + * @param key key which identifies a context value + */ + Context.prototype.getValue = function (key) { + return this._currentContext.get(key); + }; + /** + * Create a new context which inherits from this context and has + * the given key set to the given value. + * + * @param key context key for which to set the value + * @param value value to set for the given key + */ + Context.prototype.setValue = function (key, value) { + var context = new Context(this._currentContext); + context._currentContext.set(key, value); + return context; + }; + /** + * Return a new context which inherits from this context but does + * not contain a value for the given key. + * + * @param key context key for which to clear a value + */ + Context.prototype.deleteValue = function (key) { + var context = new Context(this._currentContext); + context._currentContext.delete(key); + return context; + }; + /** The root context is used as the default parent context when there is no active context */ + Context.ROOT_CONTEXT = new Context(); + /** + * This is another identifier to the root context which allows developers to easily search the + * codebase for direct uses of context which need to be removed in later PRs. + * + * It's existence is temporary and it should be removed when all references are fixed. + */ + Context.TODO = Context.ROOT_CONTEXT; + return Context; +}()); +exports.Context = Context; +//# sourceMappingURL=context.js.map + +/***/ }), /* 716 */, /* 717 */, /* 718 */, @@ -50723,316 +49881,7 @@ exports.saveCache = saveCache; /***/ }), -/* 725 */ -/***/ (function(module) { - -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global global, define, System, Reflect, Promise */ -var __extends; -var __assign; -var __rest; -var __decorate; -var __param; -var __metadata; -var __awaiter; -var __generator; -var __exportStar; -var __values; -var __read; -var __spread; -var __spreadArrays; -var __spreadArray; -var __await; -var __asyncGenerator; -var __asyncDelegator; -var __asyncValues; -var __makeTemplateObject; -var __importStar; -var __importDefault; -var __classPrivateFieldGet; -var __classPrivateFieldSet; -var __createBinding; -(function (factory) { - var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; - if (typeof define === "function" && define.amd) { - define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); - } - else if ( true && typeof module.exports === "object") { - factory(createExporter(root, createExporter(module.exports))); - } - else { - factory(createExporter(root)); - } - function createExporter(exports, previous) { - if (exports !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports, "__esModule", { value: true }); - } - else { - exports.__esModule = true; - } - } - return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; - } -}) -(function (exporter) { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - - __extends = function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - - __assign = Object.assign || function (t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - - __rest = function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; - - __decorate = function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - - __param = function (paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - }; - - __metadata = function (metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - }; - - __awaiter = function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - - __generator = function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - - __exportStar = function(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); - }; - - __createBinding = Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); - }) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }); - - __values = function (o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - - __read = function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - - /** @deprecated */ - __spread = function () { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; - }; - - /** @deprecated */ - __spreadArrays = function () { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; - }; - - __spreadArray = function (to, from) { - for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) - to[j] = from[i]; - return to; - }; - - __await = function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - - __asyncGenerator = function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - }; - - __asyncDelegator = function (o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } - }; - - __asyncValues = function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } - }; - - __makeTemplateObject = function (cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; - }; - - var __setModuleDefault = Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }; - - __importStar = function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; - }; - - __importDefault = function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - - __classPrivateFieldGet = function (receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - return privateMap.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, privateMap, value) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - privateMap.set(receiver, value); - return value; - }; - - exporter("__extends", __extends); - exporter("__assign", __assign); - exporter("__rest", __rest); - exporter("__decorate", __decorate); - exporter("__param", __param); - exporter("__metadata", __metadata); - exporter("__awaiter", __awaiter); - exporter("__generator", __generator); - exporter("__exportStar", __exportStar); - exporter("__createBinding", __createBinding); - exporter("__values", __values); - exporter("__read", __read); - exporter("__spread", __spread); - exporter("__spreadArrays", __spreadArrays); - exporter("__spreadArray", __spreadArray); - exporter("__await", __await); - exporter("__asyncGenerator", __asyncGenerator); - exporter("__asyncDelegator", __asyncDelegator); - exporter("__asyncValues", __asyncValues); - exporter("__makeTemplateObject", __makeTemplateObject); - exporter("__importStar", __importStar); - exporter("__importDefault", __importDefault); - exporter("__classPrivateFieldGet", __classPrivateFieldGet); - exporter("__classPrivateFieldSet", __classPrivateFieldSet); -}); - - -/***/ }), +/* 725 */, /* 726 */, /* 727 */ /***/ (function(__unusedmodule, exports) { @@ -58083,7 +56932,7 @@ exports.TraceAPI = TraceAPI; Object.defineProperty(exports, '__esModule', { value: true }); -var tslib = __webpack_require__(725); +var tslib = __webpack_require__(422); // Copyright (c) Microsoft Corporation. /** @@ -59027,27 +57876,17 @@ __exportStar(__webpack_require__(764), exports); "use strict"; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; Object.defineProperty(exports, "__esModule", { value: true }); -const os = __importStar(__webpack_require__(87)); -const path = __importStar(__webpack_require__(622)); -const pathHelper = __importStar(__webpack_require__(972)); -const assert_1 = __importDefault(__webpack_require__(357)); +const assert = __webpack_require__(357); +const os = __webpack_require__(87); +const path = __webpack_require__(622); +const pathHelper = __webpack_require__(972); const minimatch_1 = __webpack_require__(93); const internal_match_kind_1 = __webpack_require__(327); const internal_path_1 = __webpack_require__(383); const IS_WINDOWS = process.platform === 'win32'; class Pattern { - constructor(patternOrNegate, segments, homedir) { + constructor(patternOrNegate, segments) { /** * Indicates whether matches should be excluded from the result set */ @@ -59061,9 +57900,9 @@ class Pattern { else { // Convert to pattern segments = segments || []; - assert_1.default(segments.length, `Parameter 'segments' must not empty`); + assert(segments.length, `Parameter 'segments' must not empty`); const root = Pattern.getLiteral(segments[0]); - assert_1.default(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`); + assert(root && pathHelper.hasAbsoluteRoot(root), `Parameter 'segments' first element must be a root path`); pattern = new internal_path_1.Path(segments).toString().trim(); if (patternOrNegate) { pattern = `!${pattern}`; @@ -59075,7 +57914,7 @@ class Pattern { pattern = pattern.substr(1).trim(); } // Normalize slashes and ensures absolute root - pattern = Pattern.fixupPattern(pattern, homedir); + pattern = Pattern.fixupPattern(pattern); // Segments this.segments = new internal_path_1.Path(pattern).segments; // Trailing slash indicates the pattern should only match directories, not regular files @@ -59112,11 +57951,11 @@ class Pattern { // Normalize slashes itemPath = pathHelper.normalizeSeparators(itemPath); // Append a trailing slash. Otherwise Minimatch will not match the directory immediately - // preceding the globstar. For example, given the pattern `/foo/**`, Minimatch returns + // preceeding the globstar. For example, given the pattern `/foo/**`, Minimatch returns // false for `/foo` but returns true for `/foo/`. Append a trailing slash to handle that quirk. if (!itemPath.endsWith(path.sep)) { // Note, this is safe because the constructor ensures the pattern has an absolute root. - // For example, formats like C: and C:foo on Windows are resolved to an absolute root. + // For example, formats like C: and C:foo on Windows are resolved to an aboslute root. itemPath = `${itemPath}${path.sep}`; } } @@ -59154,15 +57993,15 @@ class Pattern { /** * Normalizes slashes and ensures absolute root */ - static fixupPattern(pattern, homedir) { + static fixupPattern(pattern) { // Empty - assert_1.default(pattern, 'pattern cannot be empty'); + assert(pattern, 'pattern cannot be empty'); // Must not contain `.` segment, unless first segment // Must not contain `..` segment const literalSegments = new internal_path_1.Path(pattern).segments.map(x => Pattern.getLiteral(x)); - assert_1.default(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); + assert(literalSegments.every((x, i) => (x !== '.' || i === 0) && x !== '..'), `Invalid pattern '${pattern}'. Relative pathing '.' and '..' is not allowed.`); // Must not contain globs in root, e.g. Windows UNC path \\foo\b*r - assert_1.default(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); + assert(!pathHelper.hasRoot(pattern) || literalSegments[0], `Invalid pattern '${pattern}'. Root segment must not contain globs.`); // Normalize slashes pattern = pathHelper.normalizeSeparators(pattern); // Replace leading `.` segment @@ -59171,9 +58010,9 @@ class Pattern { } // Replace leading `~` segment else if (pattern === '~' || pattern.startsWith(`~${path.sep}`)) { - homedir = homedir || os.homedir(); - assert_1.default(homedir, 'Unable to determine HOME directory'); - assert_1.default(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`); + const homedir = os.homedir(); + assert(homedir, 'Unable to determine HOME directory'); + assert(pathHelper.hasAbsoluteRoot(homedir), `Expected HOME directory to be a rooted path. Actual '${homedir}'`); pattern = Pattern.globEscape(homedir) + pattern.substr(1); } // Replace relative drive root, e.g. pattern is C: or C:foo @@ -59269,7 +58108,53 @@ exports.Pattern = Pattern; //# sourceMappingURL=internal-pattern.js.map /***/ }), -/* 924 */, +/* 924 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; + +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NoopContextManager = void 0; +var context_1 = __webpack_require__(715); +var NoopContextManager = /** @class */ (function () { + function NoopContextManager() { + } + NoopContextManager.prototype.active = function () { + return context_1.Context.ROOT_CONTEXT; + }; + NoopContextManager.prototype.with = function (context, fn) { + return fn(); + }; + NoopContextManager.prototype.bind = function (target, context) { + return target; + }; + NoopContextManager.prototype.enable = function () { + return this; + }; + NoopContextManager.prototype.disable = function () { + return this; + }; + return NoopContextManager; +}()); +exports.NoopContextManager = NoopContextManager; +//# sourceMappingURL=NoopContextManager.js.map + +/***/ }), /* 925 */, /* 926 */, /* 927 */, @@ -59283,7 +58168,7 @@ Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var tslib = __webpack_require__(966); +var tslib = __webpack_require__(422); var util = _interopDefault(__webpack_require__(669)); var os = __webpack_require__(87); @@ -59948,316 +58833,7 @@ exports.checkBypass = checkBypass; /* 963 */, /* 964 */, /* 965 */, -/* 966 */ -/***/ (function(module) { - -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global global, define, System, Reflect, Promise */ -var __extends; -var __assign; -var __rest; -var __decorate; -var __param; -var __metadata; -var __awaiter; -var __generator; -var __exportStar; -var __values; -var __read; -var __spread; -var __spreadArrays; -var __spreadArray; -var __await; -var __asyncGenerator; -var __asyncDelegator; -var __asyncValues; -var __makeTemplateObject; -var __importStar; -var __importDefault; -var __classPrivateFieldGet; -var __classPrivateFieldSet; -var __createBinding; -(function (factory) { - var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; - if (typeof define === "function" && define.amd) { - define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); - } - else if ( true && typeof module.exports === "object") { - factory(createExporter(root, createExporter(module.exports))); - } - else { - factory(createExporter(root)); - } - function createExporter(exports, previous) { - if (exports !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports, "__esModule", { value: true }); - } - else { - exports.__esModule = true; - } - } - return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; - } -}) -(function (exporter) { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - - __extends = function (d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - - __assign = Object.assign || function (t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - - __rest = function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; - - __decorate = function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - - __param = function (paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - }; - - __metadata = function (metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - }; - - __awaiter = function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - - __generator = function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - - __exportStar = function(m, o) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); - }; - - __createBinding = Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); - }) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }); - - __values = function (o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - - __read = function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - - /** @deprecated */ - __spread = function () { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; - }; - - /** @deprecated */ - __spreadArrays = function () { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; - }; - - __spreadArray = function (to, from) { - for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) - to[j] = from[i]; - return to; - }; - - __await = function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - - __asyncGenerator = function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - }; - - __asyncDelegator = function (o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } - }; - - __asyncValues = function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } - }; - - __makeTemplateObject = function (cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; - }; - - var __setModuleDefault = Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - }) : function(o, v) { - o["default"] = v; - }; - - __importStar = function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; - }; - - __importDefault = function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - - __classPrivateFieldGet = function (receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - return privateMap.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, privateMap, value) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - privateMap.set(receiver, value); - return value; - }; - - exporter("__extends", __extends); - exporter("__assign", __assign); - exporter("__rest", __rest); - exporter("__decorate", __decorate); - exporter("__param", __param); - exporter("__metadata", __metadata); - exporter("__awaiter", __awaiter); - exporter("__generator", __generator); - exporter("__exportStar", __exportStar); - exporter("__createBinding", __createBinding); - exporter("__values", __values); - exporter("__read", __read); - exporter("__spread", __spread); - exporter("__spreadArrays", __spreadArrays); - exporter("__spreadArray", __spreadArray); - exporter("__await", __await); - exporter("__asyncGenerator", __asyncGenerator); - exporter("__asyncDelegator", __asyncDelegator); - exporter("__asyncValues", __asyncValues); - exporter("__makeTemplateObject", __makeTemplateObject); - exporter("__importStar", __importStar); - exporter("__importDefault", __importDefault); - exporter("__classPrivateFieldGet", __classPrivateFieldGet); - exporter("__classPrivateFieldSet", __classPrivateFieldSet); -}); - - -/***/ }), +/* 966 */, /* 967 */, /* 968 */, /* 969 */, @@ -60268,19 +58844,9 @@ var __createBinding; "use strict"; -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; Object.defineProperty(exports, "__esModule", { value: true }); -const path = __importStar(__webpack_require__(622)); -const assert_1 = __importDefault(__webpack_require__(357)); +const assert = __webpack_require__(357); +const path = __webpack_require__(622); const IS_WINDOWS = process.platform === 'win32'; /** * Similar to path.dirname except normalizes the path separators and slightly better handling for Windows UNC paths. @@ -60320,8 +58886,8 @@ exports.dirname = dirname; * or `C:` are expanded based on the current working directory. */ function ensureAbsoluteRoot(root, itemPath) { - assert_1.default(root, `ensureAbsoluteRoot parameter 'root' must not be empty`); - assert_1.default(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`); + assert(root, `ensureAbsoluteRoot parameter 'root' must not be empty`); + assert(itemPath, `ensureAbsoluteRoot parameter 'itemPath' must not be empty`); // Already rooted if (hasAbsoluteRoot(itemPath)) { return itemPath; @@ -60331,7 +58897,7 @@ function ensureAbsoluteRoot(root, itemPath) { // Check for itemPath like C: or C:foo if (itemPath.match(/^[A-Z]:[^\\/]|^[A-Z]:$/i)) { let cwd = process.cwd(); - assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); + assert(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); // Drive letter matches cwd? Expand to cwd if (itemPath[0].toUpperCase() === cwd[0].toUpperCase()) { // Drive only, e.g. C: @@ -60356,11 +58922,11 @@ function ensureAbsoluteRoot(root, itemPath) { // Check for itemPath like \ or \foo else if (normalizeSeparators(itemPath).match(/^\\$|^\\[^\\]/)) { const cwd = process.cwd(); - assert_1.default(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); + assert(cwd.match(/^[A-Z]:\\/i), `Expected current directory to start with an absolute drive root. Actual '${cwd}'`); return `${cwd[0]}:\\${itemPath.substr(1)}`; } } - assert_1.default(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`); + assert(hasAbsoluteRoot(root), `ensureAbsoluteRoot parameter 'root' must have an absolute root`); // Otherwise ensure root ends with a separator if (root.endsWith('/') || (IS_WINDOWS && root.endsWith('\\'))) { // Intentionally empty @@ -60377,7 +58943,7 @@ exports.ensureAbsoluteRoot = ensureAbsoluteRoot; * `\\hello\share` and `C:\hello` (and using alternate separator). */ function hasAbsoluteRoot(itemPath) { - assert_1.default(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`); + assert(itemPath, `hasAbsoluteRoot parameter 'itemPath' must not be empty`); // Normalize separators itemPath = normalizeSeparators(itemPath); // Windows @@ -60394,7 +58960,7 @@ exports.hasAbsoluteRoot = hasAbsoluteRoot; * `\`, `\hello`, `\\hello\share`, `C:`, and `C:\hello` (and using alternate separator). */ function hasRoot(itemPath) { - assert_1.default(itemPath, `isRooted parameter 'itemPath' must not be empty`); + assert(itemPath, `isRooted parameter 'itemPath' must not be empty`); // Normalize separators itemPath = normalizeSeparators(itemPath); // Windows @@ -60750,11 +59316,10 @@ var node_fetch = _interopDefault(__webpack_require__(454)); var abortController = __webpack_require__(106); var FormData = _interopDefault(__webpack_require__(790)); var util = __webpack_require__(669); -var url = __webpack_require__(835); var stream = __webpack_require__(794); -var logger$1 = __webpack_require__(928); var tunnel = __webpack_require__(413); var coreAuth = __webpack_require__(229); +var logger$1 = __webpack_require__(928); var xml2js = __webpack_require__(992); var os = __webpack_require__(87); var coreTracing = __webpack_require__(263); @@ -60769,20 +59334,20 @@ function getHeaderKey(headerName) { return headerName.toLowerCase(); } function isHttpHeadersLike(object) { - if (object && typeof object === "object") { - var castObject = object; - if (typeof castObject.rawHeaders === "function" && - typeof castObject.clone === "function" && - typeof castObject.get === "function" && - typeof castObject.set === "function" && - typeof castObject.contains === "function" && - typeof castObject.remove === "function" && - typeof castObject.headersArray === "function" && - typeof castObject.headerValues === "function" && - typeof castObject.headerNames === "function" && - typeof castObject.toJson === "function") { - return true; - } + if (!object || typeof object !== "object") { + return false; + } + if (typeof object.rawHeaders === "function" && + typeof object.clone === "function" && + typeof object.get === "function" && + typeof object.set === "function" && + typeof object.contains === "function" && + typeof object.remove === "function" && + typeof object.headersArray === "function" && + typeof object.headerValues === "function" && + typeof object.headerNames === "function" && + typeof object.toJson === "function") { + return true; } return false; } @@ -60801,8 +59366,8 @@ var HttpHeaders = /** @class */ (function () { /** * Set a header in this collection with the provided name and value. The name is * case-insensitive. - * @param headerName - The name of the header to set. This value is case-insensitive. - * @param headerValue - The value of the header to set. + * @param headerName The name of the header to set. This value is case-insensitive. + * @param headerValue The value of the header to set. */ HttpHeaders.prototype.set = function (headerName, headerValue) { this._headersMap[getHeaderKey(headerName)] = { @@ -60813,7 +59378,7 @@ var HttpHeaders = /** @class */ (function () { /** * Get the header value for the provided header name, or undefined if no header exists in this * collection with the provided name. - * @param headerName - The name of the header. + * @param headerName The name of the header. */ HttpHeaders.prototype.get = function (headerName) { var header = this._headersMap[getHeaderKey(headerName)]; @@ -60828,7 +59393,7 @@ var HttpHeaders = /** @class */ (function () { /** * Remove the header with the provided headerName. Return whether or not the header existed and * was removed. - * @param headerName - The name of the header to remove. + * @param headerName The name of the header to remove. */ HttpHeaders.prototype.remove = function (headerName) { var result = this.contains(headerName); @@ -60903,14 +59468,14 @@ var HttpHeaders = /** @class */ (function () { // Licensed under the MIT license. /** * Encodes a string in base64 format. - * @param value - The string to encode + * @param value the string to encode */ function encodeString(value) { return Buffer.from(value).toString("base64"); } /** * Encodes a byte array in base64 format. - * @param value - The Uint8Aray to encode + * @param value the Uint8Aray to encode */ function encodeByteArray(value) { // Buffer.from accepts | -- the TypeScript definition is off here @@ -60920,7 +59485,7 @@ function encodeByteArray(value) { } /** * Decodes a base64 string into a byte array. - * @param value - The base64 string to decode + * @param value the base64 string to decode */ function decodeString(value) { return Buffer.from(value, "base64"); @@ -60931,35 +59496,58 @@ function decodeString(value) { var Constants = { /** * The core-http version + * @const + * @type {string} */ - coreHttpVersion: "1.2.3", + coreHttpVersion: "1.1.9", /** * Specifies HTTP. + * + * @const + * @type {string} */ HTTP: "http:", /** * Specifies HTTPS. + * + * @const + * @type {string} */ HTTPS: "https:", /** * Specifies HTTP Proxy. + * + * @const + * @type {string} */ HTTP_PROXY: "HTTP_PROXY", /** * Specifies HTTPS Proxy. + * + * @const + * @type {string} */ HTTPS_PROXY: "HTTPS_PROXY", /** * Specifies NO Proxy. + * + * @const + * @type {string} */ NO_PROXY: "NO_PROXY", /** * Specifies ALL Proxy. + * + * @const + * @type {string} */ ALL_PROXY: "ALL_PROXY", HttpConstants: { /** * Http Verbs + * + * @const + * @enum {string} */ HttpVerbs: { PUT: "PUT", @@ -60980,6 +59568,9 @@ var Constants = { HeaderConstants: { /** * The Authorization header. + * + * @const + * @type {string} */ AUTHORIZATION: "authorization", AUTHORIZATION_SCHEME: "Bearer", @@ -60987,26 +59578,21 @@ var Constants = { * The Retry-After response-header field can be used with a 503 (Service * Unavailable) or 349 (Too Many Requests) responses to indicate how long * the service is expected to be unavailable to the requesting client. + * + * @const + * @type {string} */ RETRY_AFTER: "Retry-After", /** * The UserAgent header. + * + * @const + * @type {string} */ USER_AGENT: "User-Agent" } }; -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * Default key used to access the XML attributes. - */ -var XML_ATTRKEY = "$"; -/** - * Default key used to access the XML value content. - */ -var XML_CHARKEY = "_"; - // Copyright (c) Microsoft Corporation. var validUuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i; /** @@ -61019,8 +59605,8 @@ var isNode = typeof process !== "undefined" && /** * Encodes an URI. * - * @param uri - The URI to be encoded. - * @returns The encoded URI. + * @param {string} uri The URI to be encoded. + * @return {string} The encoded URI. */ function encodeUri(uri) { return encodeURIComponent(uri) @@ -61034,8 +59620,9 @@ function encodeUri(uri) { * Returns a stripped version of the Http Response which only contains body, * headers and the status. * - * @param response - The Http Response - * @returns The stripped version of Http Response. + * @param {HttpOperationResponse} response The Http Response + * + * @return {object} The stripped version of Http Response. */ function stripResponse(response) { var strippedResponse = {}; @@ -61048,8 +59635,9 @@ function stripResponse(response) { * Returns a stripped version of the Http Request that does not contain the * Authorization header. * - * @param request - The Http Request object - * @returns The stripped version of Http Request. + * @param {WebResourceLike} request The Http Request object + * + * @return {WebResourceLike} The stripped version of Http Request. */ function stripRequest(request) { var strippedRequest = request.clone(); @@ -61061,8 +59649,9 @@ function stripRequest(request) { /** * Validates the given uuid as a string * - * @param uuid - The uuid as a string that needs to be validated - * @returns True if the uuid is valid; false otherwise. + * @param {string} uuid The uuid as a string that needs to be validated + * + * @return {boolean} True if the uuid is valid; false otherwise. */ function isValidUuid(uuid) { return validUuidRegex.test(uuid); @@ -61070,7 +59659,7 @@ function isValidUuid(uuid) { /** * Generated UUID * - * @returns RFC4122 v4 UUID. + * @return {string} RFC4122 v4 UUID. */ function generateUuid() { return uuid.v4(); @@ -61079,10 +59668,12 @@ function generateUuid() { * Executes an array of promises sequentially. Inspiration of this method is here: * https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html. An awesome blog on promises! * - * @param promiseFactories - An array of promise factories(A function that return a promise) - * @param kickstart - Input to the first promise that is used to kickstart the promise chain. + * @param {Array} promiseFactories An array of promise factories(A function that return a promise) + * + * @param {any} [kickstart] Input to the first promise that is used to kickstart the promise chain. * If not provided then the promise chain starts with undefined. - * @returns A chain of resolved or rejected promises + * + * @return A chain of resolved or rejected promises */ function executePromisesSequentially(promiseFactories, kickstart) { var result = Promise.resolve(kickstart); @@ -61093,25 +59684,23 @@ function executePromisesSequentially(promiseFactories, kickstart) { } /** * A wrapper for setTimeout that resolves a promise after t milliseconds. - * @param t - The number of milliseconds to be delayed. - * @param value - The value to be resolved with after a timeout of t milliseconds. - * @returns Resolved promise + * @param {number} t The number of milliseconds to be delayed. + * @param {T} value The value to be resolved with after a timeout of t milliseconds. + * @returns {Promise} Resolved promise */ function delay(t, value) { return new Promise(function (resolve) { return setTimeout(function () { return resolve(value); }, t); }); } /** * Converts a Promise to a callback. - * @param promise - The Promise to be converted to a callback - * @returns A function that takes the callback `(cb: Function) => void` + * @param {Promise} promise The Promise to be converted to a callback + * @returns {Function} A function that takes the callback (cb: Function): void * @deprecated generated code should instead depend on responseToBody */ -// eslint-disable-next-line @typescript-eslint/ban-types function promiseToCallback(promise) { if (typeof promise.then !== "function") { throw new Error("The provided input is not a Promise."); } - // eslint-disable-next-line @typescript-eslint/ban-types return function (cb) { promise .then(function (data) { @@ -61126,8 +59715,8 @@ function promiseToCallback(promise) { } /** * Converts a Promise to a service callback. - * @param promise - The Promise of HttpOperationResponse to be converted to a service callback - * @returns A function that takes the service callback (cb: ServiceCallback): void + * @param {Promise} promise - The Promise of HttpOperationResponse to be converted to a service callback + * @returns {Function} A function that takes the service callback (cb: ServiceCallback): void */ function promiseToServiceCallback(promise) { if (typeof promise.then !== "function") { @@ -61151,38 +59740,35 @@ function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) { if (!xmlNamespaceKey || !xmlNamespace) { return _a = {}, _a[elementName] = obj, _a; } - var result = (_b = {}, _b[elementName] = obj, _b); - result[XML_ATTRKEY] = (_c = {}, _c[xmlNamespaceKey] = xmlNamespace, _c); - return result; + return _b = {}, _b[elementName] = obj, _b.$ = (_c = {}, _c[xmlNamespaceKey] = xmlNamespace, _c), _b; } /** * Applies the properties on the prototype of sourceCtors to the prototype of targetCtor - * @param targetCtor - The target object on which the properties need to be applied. - * @param sourceCtors - An array of source objects from which the properties need to be taken. + * @param {object} targetCtor The target object on which the properties need to be applied. + * @param {Array} sourceCtors An array of source objects from which the properties need to be taken. */ -function applyMixins(targetCtorParam, sourceCtors) { - var castTargetCtorParam = targetCtorParam; - sourceCtors.forEach(function (sourceCtor) { - Object.getOwnPropertyNames(sourceCtor.prototype).forEach(function (name) { - castTargetCtorParam.prototype[name] = sourceCtor.prototype[name]; +function applyMixins(targetCtor, sourceCtors) { + sourceCtors.forEach(function (sourceCtors) { + Object.getOwnPropertyNames(sourceCtors.prototype).forEach(function (name) { + targetCtor.prototype[name] = sourceCtors.prototype[name]; }); }); } var validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; /** * Indicates whether the given string is in ISO 8601 format. - * @param value - The value to be validated for ISO 8601 duration format. - * @returns `true` if valid, `false` otherwise. + * @param {string} value The value to be validated for ISO 8601 duration format. + * @return {boolean} `true` if valid, `false` otherwise. */ function isDuration(value) { return validateISODuration.test(value); } /** * Replace all of the instances of searchValue in value with the provided replaceValue. - * @param value - The value to search and replace in. - * @param searchValue - The value to search for in the value argument. - * @param replaceValue - The value to replace searchValue with in the value argument. - * @returns The value where each instance of searchValue was replaced with replacedValue. + * @param {string | undefined} value The value to search and replace in. + * @param {string} searchValue The value to search for in the value argument. + * @param {string} replaceValue The value to replace searchValue with in the value argument. + * @returns {string | undefined} The value where each instance of searchValue was replaced with replacedValue. */ function replaceAll(value, searchValue, replaceValue) { return !value || !searchValue ? value : value.split(searchValue).join(replaceValue || ""); @@ -61190,8 +59776,8 @@ function replaceAll(value, searchValue, replaceValue) { /** * Determines whether the given entity is a basic/primitive type * (string, number, boolean, null, undefined). - * @param value - Any entity - * @returns true is it is primitive type, false otherwise. + * @param {any} value Any entity + * @return {boolean} - true is it is primitive type, false otherwise. */ function isPrimitiveType(value) { return (typeof value !== "object" && typeof value !== "function") || value === null; @@ -61218,34 +59804,32 @@ var Serializer = /** @class */ (function () { throw new Error("\"" + objectName + "\" with value \"" + value + "\" should satisfy the constraint \"" + constraintName + "\": " + constraintValue + "."); }; if (mapper.constraints && value != undefined) { - var valueAsNumber = value; var _a = mapper.constraints, ExclusiveMaximum = _a.ExclusiveMaximum, ExclusiveMinimum = _a.ExclusiveMinimum, InclusiveMaximum = _a.InclusiveMaximum, InclusiveMinimum = _a.InclusiveMinimum, MaxItems = _a.MaxItems, MaxLength = _a.MaxLength, MinItems = _a.MinItems, MinLength = _a.MinLength, MultipleOf = _a.MultipleOf, Pattern = _a.Pattern, UniqueItems = _a.UniqueItems; - if (ExclusiveMaximum != undefined && valueAsNumber >= ExclusiveMaximum) { + if (ExclusiveMaximum != undefined && value >= ExclusiveMaximum) { failValidation("ExclusiveMaximum", ExclusiveMaximum); } - if (ExclusiveMinimum != undefined && valueAsNumber <= ExclusiveMinimum) { + if (ExclusiveMinimum != undefined && value <= ExclusiveMinimum) { failValidation("ExclusiveMinimum", ExclusiveMinimum); } - if (InclusiveMaximum != undefined && valueAsNumber > InclusiveMaximum) { + if (InclusiveMaximum != undefined && value > InclusiveMaximum) { failValidation("InclusiveMaximum", InclusiveMaximum); } - if (InclusiveMinimum != undefined && valueAsNumber < InclusiveMinimum) { + if (InclusiveMinimum != undefined && value < InclusiveMinimum) { failValidation("InclusiveMinimum", InclusiveMinimum); } - var valueAsArray = value; - if (MaxItems != undefined && valueAsArray.length > MaxItems) { + if (MaxItems != undefined && value.length > MaxItems) { failValidation("MaxItems", MaxItems); } - if (MaxLength != undefined && valueAsArray.length > MaxLength) { + if (MaxLength != undefined && value.length > MaxLength) { failValidation("MaxLength", MaxLength); } - if (MinItems != undefined && valueAsArray.length < MinItems) { + if (MinItems != undefined && value.length < MinItems) { failValidation("MinItems", MinItems); } - if (MinLength != undefined && valueAsArray.length < MinLength) { + if (MinLength != undefined && value.length < MinLength) { failValidation("MinLength", MinLength); } - if (MultipleOf != undefined && valueAsNumber % MultipleOf !== 0) { + if (MultipleOf != undefined && value % MultipleOf !== 0) { failValidation("MultipleOf", MultipleOf); } if (Pattern) { @@ -61255,7 +59839,7 @@ var Serializer = /** @class */ (function () { } } if (UniqueItems && - valueAsArray.some(function (item, i, ar) { return ar.indexOf(item) !== i; })) { + value.some(function (item, i, ar) { return ar.indexOf(item) !== i; })) { failValidation("UniqueItems", UniqueItems); } } @@ -61263,20 +59847,15 @@ var Serializer = /** @class */ (function () { /** * Serialize the given object based on its metadata defined in the mapper * - * @param mapper - The mapper which defines the metadata of the serializable object - * @param object - A valid Javascript object to be serialized - * @param objectName - Name of the serialized object - * @param options - additional options to deserialization - * @returns A valid serialized Javascript object + * @param {Mapper} mapper The mapper which defines the metadata of the serializable object + * + * @param {object|string|Array|number|boolean|Date|stream} object A valid Javascript object to be serialized + * + * @param {string} objectName Name of the serialized object + * + * @returns {object|string|Array|number|boolean|Date|stream} A valid serialized Javascript object */ - Serializer.prototype.serialize = function (mapper, object, objectName, options) { - var _a, _b, _c; - if (options === void 0) { options = {}; } - var updatedOptions = { - rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", - includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, - xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY - }; + Serializer.prototype.serialize = function (mapper, object, objectName) { var payload = {}; var mapperType = mapper.type.name; if (!objectName) { @@ -61333,13 +59912,13 @@ var Serializer = /** @class */ (function () { payload = serializeBase64UrlType(objectName, object); } else if (mapperType.match(/^Sequence$/i) !== null) { - payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML)); } else if (mapperType.match(/^Dictionary$/i) !== null) { - payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML)); } else if (mapperType.match(/^Composite$/i) !== null) { - payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); + payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML)); } } return payload; @@ -61347,20 +59926,15 @@ var Serializer = /** @class */ (function () { /** * Deserialize the given object based on its metadata defined in the mapper * - * @param mapper - The mapper which defines the metadata of the serializable object - * @param responseBody - A valid Javascript entity to be deserialized - * @param objectName - Name of the deserialized object - * @param options - Controls behavior of XML parser and builder. - * @returns A valid deserialized Javascript object + * @param {object} mapper The mapper which defines the metadata of the serializable object + * + * @param {object|string|Array|number|boolean|Date|stream} responseBody A valid Javascript entity to be deserialized + * + * @param {string} objectName Name of the deserialized object + * + * @returns {object|string|Array|number|boolean|Date|stream} A valid deserialized Javascript object */ - Serializer.prototype.deserialize = function (mapper, responseBody, objectName, options) { - var _a, _b, _c; - if (options === void 0) { options = {}; } - var updatedOptions = { - rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", - includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, - xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY - }; + Serializer.prototype.deserialize = function (mapper, responseBody, objectName) { if (responseBody == undefined) { if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) { // Edge case for empty XML non-wrapped lists. xml2js can't distinguish @@ -61380,20 +59954,17 @@ var Serializer = /** @class */ (function () { objectName = mapper.serializedName; } if (mapperType.match(/^Composite$/i) !== null) { - payload = deserializeCompositeType(this, mapper, responseBody, objectName, updatedOptions); + payload = deserializeCompositeType(this, mapper, responseBody, objectName); } else { if (this.isXML) { - var xmlCharKey = updatedOptions.xmlCharKey; - var castResponseBody = responseBody; /** * If the mapper specifies this as a non-composite type value but the responseBody contains - * both header ("$" i.e., XML_ATTRKEY) and body ("#" i.e., XML_CHARKEY) properties, - * then just reduce the responseBody value to the body ("#" i.e., XML_CHARKEY) property. + * both header ("$") and body ("_") properties, then just reduce the responseBody value to + * the body ("_") property. */ - if (castResponseBody[XML_ATTRKEY] != undefined && - castResponseBody[xmlCharKey] != undefined) { - responseBody = castResponseBody[xmlCharKey]; + if (responseBody["$"] != undefined && responseBody["_"] != undefined) { + responseBody = responseBody["_"]; } } if (mapperType.match(/^Number$/i) !== null) { @@ -61429,10 +60000,10 @@ var Serializer = /** @class */ (function () { payload = base64UrlToByteArray(responseBody); } else if (mapperType.match(/^Sequence$/i) !== null) { - payload = deserializeSequenceType(this, mapper, responseBody, objectName, updatedOptions); + payload = deserializeSequenceType(this, mapper, responseBody, objectName); } else if (mapperType.match(/^Dictionary$/i) !== null) { - payload = deserializeDictionaryType(this, mapper, responseBody, objectName, updatedOptions); + payload = deserializeDictionaryType(this, mapper, responseBody, objectName); } } if (mapper.isConstant) { @@ -61537,7 +60108,7 @@ function serializeBasicTypes(typeName, objectName, value) { objectType !== "function" && !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value) && - !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob)) { + !(typeof Blob === "function" && value instanceof Blob)) { throw new Error(objectName + " must be a string, Blob, ArrayBuffer, ArrayBufferView, or a function returning NodeJS.ReadableStream."); } } @@ -61621,7 +60192,7 @@ function serializeDateTypes(typeName, value, objectName) { } return value; } -function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) { +function serializeSequenceType(serializer, mapper, object, objectName, isXml) { var _a, _b; if (!Array.isArray(object)) { throw new Error(objectName + " must be of type Array."); @@ -61633,19 +60204,16 @@ function serializeSequenceType(serializer, mapper, object, objectName, isXml, op } var tempArray = []; for (var i = 0; i < object.length; i++) { - var serializedValue = serializer.serialize(elementType, object[i], objectName, options); + var serializedValue = serializer.serialize(elementType, object[i], objectName); if (isXml && elementType.xmlNamespace) { var xmlnsKey = elementType.xmlNamespacePrefix ? "xmlns:" + elementType.xmlNamespacePrefix : "xmlns"; if (elementType.type.name === "Composite") { - tempArray[i] = tslib.__assign({}, serializedValue); - tempArray[i][XML_ATTRKEY] = (_a = {}, _a[xmlnsKey] = elementType.xmlNamespace, _a); + tempArray[i] = tslib.__assign(tslib.__assign({}, serializedValue), { $: (_a = {}, _a[xmlnsKey] = elementType.xmlNamespace, _a) }); } else { - tempArray[i] = {}; - tempArray[i][options.xmlCharKey] = serializedValue; - tempArray[i][XML_ATTRKEY] = (_b = {}, _b[xmlnsKey] = elementType.xmlNamespace, _b); + tempArray[i] = { _: serializedValue, $: (_b = {}, _b[xmlnsKey] = elementType.xmlNamespace, _b) }; } } else { @@ -61654,7 +60222,7 @@ function serializeSequenceType(serializer, mapper, object, objectName, isXml, op } return tempArray; } -function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) { +function serializeDictionaryType(serializer, mapper, object, objectName, isXml) { var _a; if (typeof object !== "object") { throw new Error(objectName + " must be of type object."); @@ -61667,24 +60235,22 @@ function serializeDictionaryType(serializer, mapper, object, objectName, isXml, var tempDictionary = {}; for (var _i = 0, _b = Object.keys(object); _i < _b.length; _i++) { var key = _b[_i]; - var serializedValue = serializer.serialize(valueType, object[key], objectName, options); + var serializedValue = serializer.serialize(valueType, object[key], objectName); // If the element needs an XML namespace we need to add it within the $ property - tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options); + tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml); } // Add the namespace to the root element if needed if (isXml && mapper.xmlNamespace) { var xmlnsKey = mapper.xmlNamespacePrefix ? "xmlns:" + mapper.xmlNamespacePrefix : "xmlns"; - var result = tempDictionary; - result[XML_ATTRKEY] = (_a = {}, _a[xmlnsKey] = mapper.xmlNamespace, _a); - return result; + return tslib.__assign(tslib.__assign({}, tempDictionary), { $: (_a = {}, _a[xmlnsKey] = mapper.xmlNamespace, _a) }); } return tempDictionary; } /** * Resolves the additionalProperties property from a referenced mapper - * @param serializer - The serializer containing the entire set of mappers - * @param mapper - The composite mapper to resolve - * @param objectName - Name of the object being serialized + * @param serializer the serializer containing the entire set of mappers + * @param mapper the composite mapper to resolve + * @param objectName name of the object being serialized */ function resolveAdditionalProperties(serializer, mapper, objectName) { var additionalProperties = mapper.type.additionalProperties; @@ -61696,9 +60262,9 @@ function resolveAdditionalProperties(serializer, mapper, objectName) { } /** * Finds the mapper referenced by className - * @param serializer - The serializer containing the entire set of mappers - * @param mapper - The composite mapper to resolve - * @param objectName - Name of the object being serialized + * @param serializer the serializer containing the entire set of mappers + * @param mapper the composite mapper to resolve + * @param objectName name of the object being serialized */ function resolveReferencedMapper(serializer, mapper, objectName) { var className = mapper.type.className; @@ -61709,8 +60275,8 @@ function resolveReferencedMapper(serializer, mapper, objectName) { } /** * Resolves a composite mapper's modelProperties. - * @param serializer - The serializer containing the entire set of mappers - * @param mapper - The composite mapper to resolve + * @param serializer the serializer containing the entire set of mappers + * @param mapper the composite mapper to resolve */ function resolveModelProperties(serializer, mapper, objectName) { var modelProps = mapper.type.modelProperties; @@ -61727,7 +60293,7 @@ function resolveModelProperties(serializer, mapper, objectName) { } return modelProps; } -function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) { +function serializeCompositeType(serializer, mapper, object, objectName, isXml) { var _a, _b; if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { mapper = getPolymorphicMapper(serializer, mapper, object, "clientName"); @@ -61769,7 +60335,7 @@ function serializeCompositeType(serializer, mapper, object, objectName, isXml, o var xmlnsKey = mapper.xmlNamespacePrefix ? "xmlns:" + mapper.xmlNamespacePrefix : "xmlns"; - parentObject[XML_ATTRKEY] = tslib.__assign(tslib.__assign({}, parentObject[XML_ATTRKEY]), (_a = {}, _a[xmlnsKey] = mapper.xmlNamespace, _a)); + parentObject.$ = tslib.__assign(tslib.__assign({}, parentObject.$), (_a = {}, _a[xmlnsKey] = mapper.xmlNamespace, _a)); } var propertyObjectName = propertyMapper.serializedName !== "" ? objectName + "." + propertyMapper.serializedName @@ -61781,15 +60347,15 @@ function serializeCompositeType(serializer, mapper, object, objectName, isXml, o toSerialize == undefined) { toSerialize = mapper.serializedName; } - var serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options); + var serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName); if (serializedValue !== undefined && propName != undefined) { - var value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options); + var value = getXmlObjectValue(propertyMapper, serializedValue, isXml); if (isXml && propertyMapper.xmlIsAttribute) { - // XML_ATTRKEY, i.e., $ is the key attributes are kept under in xml2js. + // $ is the key attributes are kept under in xml2js. // This keeps things simple while preventing name collision // with names in user documents. - parentObject[XML_ATTRKEY] = parentObject[XML_ATTRKEY] || {}; - parentObject[XML_ATTRKEY][propName] = serializedValue; + parentObject.$ = parentObject.$ || {}; + parentObject.$[propName] = serializedValue; } else if (isXml && propertyMapper.xmlIsWrapped) { parentObject[propName] = (_b = {}, _b[propertyMapper.xmlElementName] = value, _b); @@ -61806,7 +60372,7 @@ function serializeCompositeType(serializer, mapper, object, objectName, isXml, o var _loop_1 = function (clientPropName) { var isAdditionalProperty = propNames.every(function (pn) { return pn !== clientPropName; }); if (isAdditionalProperty) { - payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options); + payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]'); } }; for (var clientPropName in object) { @@ -61817,7 +60383,7 @@ function serializeCompositeType(serializer, mapper, object, objectName, isXml, o } return object; } -function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) { +function getXmlObjectValue(propertyMapper, serializedValue, isXml) { var _a; if (!isXml || !propertyMapper.xmlNamespace) { return serializedValue; @@ -61827,24 +60393,14 @@ function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) { : "xmlns"; var xmlNamespace = (_a = {}, _a[xmlnsKey] = propertyMapper.xmlNamespace, _a); if (["Composite"].includes(propertyMapper.type.name)) { - if (serializedValue[XML_ATTRKEY]) { - return serializedValue; - } - else { - var result_1 = tslib.__assign({}, serializedValue); - result_1[XML_ATTRKEY] = xmlNamespace; - return result_1; - } + return tslib.__assign({ $: xmlNamespace }, serializedValue); } - var result = {}; - result[options.xmlCharKey] = serializedValue; - result[XML_ATTRKEY] = xmlNamespace; - return result; + return { _: serializedValue, $: xmlNamespace }; } -function isSpecialXmlProperty(propertyName, options) { - return [XML_ATTRKEY, options.xmlCharKey].includes(propertyName); +function isSpecialXmlProperty(propertyName) { + return ["$", "_"].includes(propertyName); } -function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) { +function deserializeCompositeType(serializer, mapper, responseBody, objectName) { var _a; if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName"); @@ -61868,15 +60424,15 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, for (var _c = 0, _d = Object.keys(responseBody); _c < _d.length; _c++) { var headerKey = _d[_c]; if (headerKey.startsWith(headerCollectionPrefix)) { - dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options); + dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName); } handledPropertyNames.push(headerKey); } instance[key] = dictionary; } else if (serializer.isXML) { - if (propertyMapper.xmlIsAttribute && responseBody[XML_ATTRKEY]) { - instance[key] = serializer.deserialize(propertyMapper, responseBody[XML_ATTRKEY][xmlName], propertyObjectName, options); + if (propertyMapper.xmlIsAttribute && responseBody.$) { + instance[key] = serializer.deserialize(propertyMapper, responseBody.$[xmlName], propertyObjectName); } else { var propertyName = xmlElementName || xmlName || serializedName; @@ -61897,11 +60453,11 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, */ var wrapped = responseBody[xmlName]; var elementList = (_a = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _a !== void 0 ? _a : []; - instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options); + instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName); } else { var property = responseBody[propertyName]; - instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options); + instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName); } } } @@ -61936,10 +60492,10 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, // paging if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") { propertyInstance = responseBody[key]; - instance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); + instance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName); } else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) { - serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); + serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName); instance[key] = serializedValue; } } @@ -61957,7 +60513,7 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, }; for (var responsePropName in responseBody) { if (isAdditionalProperty(responsePropName)) { - instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options); + instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]'); } } } @@ -61966,14 +60522,14 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, var key = _g[_f]; if (instance[key] === undefined && !handledPropertyNames.includes(key) && - !isSpecialXmlProperty(key, options)) { + !isSpecialXmlProperty(key)) { instance[key] = responseBody[key]; } } } return instance; } -function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) { +function deserializeDictionaryType(serializer, mapper, responseBody, objectName) { var value = mapper.type.value; if (!value || typeof value !== "object") { throw new Error("\"value\" metadata for a Dictionary must be defined in the " + @@ -61983,13 +60539,13 @@ function deserializeDictionaryType(serializer, mapper, responseBody, objectName, var tempDictionary = {}; for (var _i = 0, _a = Object.keys(responseBody); _i < _a.length; _i++) { var key = _a[_i]; - tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options); + tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName); } return tempDictionary; } return responseBody; } -function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) { +function deserializeSequenceType(serializer, mapper, responseBody, objectName) { var element = mapper.type.element; if (!element || typeof element !== "object") { throw new Error("element\" metadata for an Array must be defined in the " + @@ -62002,7 +60558,7 @@ function deserializeSequenceType(serializer, mapper, responseBody, objectName, o } var tempArray = []; for (var i = 0; i < responseBody.length; i++) { - tempArray[i] = serializer.deserialize(element, responseBody[i], objectName + "[" + i + "]", options); + tempArray[i] = serializer.deserialize(element, responseBody[i], objectName + "[" + i + "]"); } return tempArray; } @@ -62040,7 +60596,6 @@ function getPolymorphicDiscriminatorSafely(serializer, typeName) { } // TODO: why is this here? function serializeObject(toSerialize) { - var castToSerialize = toSerialize; if (toSerialize == undefined) return undefined; if (toSerialize instanceof Uint8Array) { @@ -62060,7 +60615,7 @@ function serializeObject(toSerialize) { else if (typeof toSerialize === "object") { var dictionary = {}; for (var property in toSerialize) { - dictionary[property] = serializeObject(castToSerialize[property]); + dictionary[property] = serializeObject(toSerialize[property]); } return dictionary; } @@ -62077,7 +60632,6 @@ function strEnum(o) { } return result; } -// eslint-disable-next-line @typescript-eslint/no-redeclare var MapperType = strEnum([ "Base64Url", "Boolean", @@ -62099,17 +60653,17 @@ var MapperType = strEnum([ // Copyright (c) Microsoft Corporation. function isWebResourceLike(object) { - if (object && typeof object === "object") { - var castObject = object; - if (typeof castObject.url === "string" && - typeof castObject.method === "string" && - typeof castObject.headers === "object" && - isHttpHeadersLike(castObject.headers) && - typeof castObject.validateRequestProperties === "function" && - typeof castObject.prepare === "function" && - typeof castObject.clone === "function") { - return true; - } + if (typeof object !== "object") { + return false; + } + if (typeof object.url === "string" && + typeof object.method === "string" && + typeof object.headers === "object" && + isHttpHeadersLike(object.headers) && + typeof object.validateRequestProperties === "function" && + typeof object.prepare === "function" && + typeof object.clone === "function") { + return true; } return false; } @@ -62118,11 +60672,12 @@ function isWebResourceLike(object) { * * This class provides an abstraction over a REST call by being library / implementation agnostic and wrapping the necessary * properties to initiate a request. + * + * @constructor */ var WebResource = /** @class */ (function () { - function WebResource(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, decompressResponse, streamResponseStatusCodes) { + function WebResource(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, decompressResponse) { this.streamResponseBody = streamResponseBody; - this.streamResponseStatusCodes = streamResponseStatusCodes; this.url = url || ""; this.method = method || "GET"; this.headers = isHttpHeadersLike(headers) ? headers : new HttpHeaders(headers); @@ -62154,8 +60709,8 @@ var WebResource = /** @class */ (function () { }; /** * Prepares the request. - * @param options - Options to provide for preparing the request. - * @returns Returns the prepared WebResource (HTTP Request) object that needs to be given to the request pipeline. + * @param {RequestPrepareOptions} options Options to provide for preparing the request. + * @returns {WebResource} Returns the prepared WebResource (HTTP Request) object that needs to be given to the request pipeline. */ WebResource.prototype.prepare = function (options) { if (!options) { @@ -62304,7 +60859,7 @@ var WebResource = /** @class */ (function () { if (!this.headers.get("Content-Type")) { this.headers.set("Content-Type", "application/json; charset=utf-8"); } - // set the request body. request.js automatically sets the Content-Length request header, so we need not set it explicitly + // set the request body. request.js automatically sets the Content-Length request header, so we need not set it explicilty this.body = options.body; if (options.body !== undefined && options.body !== null) { // body as a stream special case. set the body as-is and check for some special request headers specific to sending a stream. @@ -62335,10 +60890,10 @@ var WebResource = /** @class */ (function () { }; /** * Clone this WebResource HTTP request object. - * @returns The clone of this WebResource HTTP request object. + * @returns {WebResource} The clone of this WebResource HTTP request object. */ WebResource.prototype.clone = function () { - var result = new WebResource(this.url, this.method, this.body, this.query, this.headers && this.headers.clone(), this.streamResponseBody, this.withCredentials, this.abortSignal, this.timeout, this.onUploadProgress, this.onDownloadProgress, this.proxySettings, this.keepAlive, this.decompressResponse, this.streamResponseStatusCodes); + var result = new WebResource(this.url, this.method, this.body, this.query, this.headers && this.headers.clone(), this.streamResponseBody, this.withCredentials, this.abortSignal, this.timeout, this.onUploadProgress, this.onDownloadProgress, this.proxySettings, this.keepAlive, this.decompressResponse); if (this.formData) { result.formData = this.formData; } @@ -62385,12 +60940,9 @@ var URLQuery = /** @class */ (function () { * parameterName. */ URLQuery.prototype.set = function (parameterName, parameterValue) { - var caseParameterValue = parameterValue; if (parameterName) { - if (caseParameterValue !== undefined && caseParameterValue !== null) { - var newValue = Array.isArray(caseParameterValue) - ? caseParameterValue - : caseParameterValue.toString(); + if (parameterValue !== undefined && parameterValue !== null) { + var newValue = Array.isArray(parameterValue) ? parameterValue : parameterValue.toString(); this._rawQuery[parameterName] = newValue; } else { @@ -62967,7 +61519,6 @@ var defaultAllowedHeaderNames = [ "x-ms-correlation-request-id", "x-ms-request-id", "client-request-id", - "ms-cv", "return-client-request-id", "traceparent", "Access-Control-Allow-Credentials", @@ -63113,9 +61664,6 @@ var RestError = /** @class */ (function (_super) { return RestError; }(Error)); -// Copyright (c) Microsoft Corporation. -var logger = logger$1.createClientLogger("core-http"); - // Copyright (c) Microsoft Corporation. var ReportTransform = /** @class */ (function (_super) { tslib.__extends(ReportTransform, _super); @@ -63137,12 +61685,10 @@ var FetchHttpClient = /** @class */ (function () { function FetchHttpClient() { } FetchHttpClient.prototype.sendRequest = function (httpRequest) { - var _a; return tslib.__awaiter(this, void 0, void 0, function () { - var abortController$1, abortListener, formData, requestForm_1, appendFormValue, _i, _b, formKey, formValue, j, contentType, body, onUploadProgress, uploadReportStream, platformSpecificRequestInit, requestInit, operationResponse, response, headers, streaming, _c, onDownloadProgress, responseBody, downloadReportStream, length_1, error_1, fetchError, uploadStreamDone, downloadStreamDone; - var _d; - return tslib.__generator(this, function (_e) { - switch (_e.label) { + var abortController$1, abortListener, formData, requestForm_1, appendFormValue, _i, _a, formKey, formValue, j, contentType, body, onUploadProgress, uploadReportStream, platformSpecificRequestInit, requestInit, response, headers, operationResponse, _b, _c, onDownloadProgress, responseBody, downloadReportStream, length_1, error_1, fetchError; + return tslib.__generator(this, function (_d) { + switch (_d.label) { case 0: if (!httpRequest && typeof httpRequest !== "object") { throw new Error("'httpRequest' (WebResourceLike) cannot be null or undefined and must be of type object."); @@ -63172,17 +61718,16 @@ var FetchHttpClient = /** @class */ (function () { if (typeof value === "function") { value = value(); } - if (value && - Object.prototype.hasOwnProperty.call(value, "value") && - Object.prototype.hasOwnProperty.call(value, "options")) { + // eslint-disable-next-line no-prototype-builtins + if (value && value.hasOwnProperty("value") && value.hasOwnProperty("options")) { requestForm_1.append(key, value.value, value.options); } else { requestForm_1.append(key, value); } }; - for (_i = 0, _b = Object.keys(formData); _i < _b.length; _i++) { - formKey = _b[_i]; + for (_i = 0, _a = Object.keys(formData); _i < _a.length; _i++) { + formKey = _a[_i]; formValue = formData[formKey]; if (Array.isArray(formValue)) { for (j = 0; j < formValue.length; j++) { @@ -63224,36 +61769,34 @@ var FetchHttpClient = /** @class */ (function () { } return [4 /*yield*/, this.prepareRequest(httpRequest)]; case 1: - platformSpecificRequestInit = _e.sent(); - requestInit = tslib.__assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method, signal: abortController$1.signal, redirect: "manual" }, platformSpecificRequestInit); - _e.label = 2; + platformSpecificRequestInit = _d.sent(); + requestInit = tslib.__assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method, signal: abortController$1.signal }, platformSpecificRequestInit); + _d.label = 2; case 2: - _e.trys.push([2, 8, 9, 10]); + _d.trys.push([2, 8, 9, 10]); return [4 /*yield*/, this.fetch(httpRequest.url, requestInit)]; case 3: - response = _e.sent(); + response = _d.sent(); headers = parseHeaders(response.headers); - streaming = ((_a = httpRequest.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(response.status)) || - httpRequest.streamResponseBody; - _d = { + _b = { headers: headers, request: httpRequest, status: response.status, - readableStreamBody: streaming + readableStreamBody: httpRequest.streamResponseBody ? response.body : undefined }; - if (!!streaming) return [3 /*break*/, 5]; + if (!!httpRequest.streamResponseBody) return [3 /*break*/, 5]; return [4 /*yield*/, response.text()]; case 4: - _c = _e.sent(); + _c = _d.sent(); return [3 /*break*/, 6]; case 5: _c = undefined; - _e.label = 6; + _d.label = 6; case 6: - operationResponse = (_d.bodyAsText = _c, - _d); + operationResponse = (_b.bodyAsText = _c, + _b); onDownloadProgress = httpRequest.onDownloadProgress; if (onDownloadProgress) { responseBody = response.body || undefined; @@ -63272,10 +61815,10 @@ var FetchHttpClient = /** @class */ (function () { } return [4 /*yield*/, this.processRequest(operationResponse)]; case 7: - _e.sent(); + _d.sent(); return [2 /*return*/, operationResponse]; case 8: - error_1 = _e.sent(); + error_1 = _d.sent(); fetchError = error_1; if (fetchError.code === "ENOTFOUND") { throw new RestError(fetchError.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest); @@ -63287,23 +61830,7 @@ var FetchHttpClient = /** @class */ (function () { case 9: // clean up event listener if (httpRequest.abortSignal && abortListener) { - uploadStreamDone = Promise.resolve(); - if (isReadableStream(body)) { - uploadStreamDone = isStreamComplete(body); - } - downloadStreamDone = Promise.resolve(); - if (isReadableStream(operationResponse === null || operationResponse === void 0 ? void 0 : operationResponse.readableStreamBody)) { - downloadStreamDone = isStreamComplete(operationResponse.readableStreamBody); - } - Promise.all([uploadStreamDone, downloadStreamDone]) - .then(function () { - var _a; - (_a = httpRequest.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener); - return; - }) - .catch(function (e) { - logger.warning("Error when cleaning up abortListener on httpRequest", e); - }); + httpRequest.abortSignal.removeEventListener("abort", abortListener); } return [7 /*endfinally*/]; case 10: return [2 /*return*/]; @@ -63316,13 +61843,6 @@ var FetchHttpClient = /** @class */ (function () { function isReadableStream(body) { return body && typeof body.pipe === "function"; } -function isStreamComplete(stream) { - return new Promise(function (resolve) { - stream.on("close", resolve); - stream.on("end", resolve); - stream.on("error", resolve); - }); -} function parseHeaders(headers) { var httpHeaders = new HttpHeaders(); headers.forEach(function (value, key) { @@ -63529,7 +62049,7 @@ var NodeFetchHttpClient = /** @class */ (function (_super) { /** * Converts an OperationOptions to a RequestOptionsBase * - * @param opts - OperationOptions object to convert to RequestOptionsBase + * @param opts OperationOptions object to convert to RequestOptionsBase */ function operationOptionsToRequestOptionsBase(opts) { var requestOptions = opts.requestOptions, tracingOptions = opts.tracingOptions, additionalOptions = tslib.__rest(opts, ["requestOptions", "tracingOptions"]); @@ -63551,7 +62071,7 @@ var BaseRequestPolicy = /** @class */ (function () { } /** * Get whether or not a log with the provided log level should be logged. - * @param logLevel - The log level of the log that will be logged. + * @param logLevel The log level of the log that will be logged. * @returns Whether or not a log with the provided log level should be logged. */ BaseRequestPolicy.prototype.shouldLog = function (logLevel) { @@ -63560,8 +62080,8 @@ var BaseRequestPolicy = /** @class */ (function () { /** * Attempt to log the provided message to the provided logger. If no logger was provided or if * the log level does not meat the logger's threshold, then nothing will be logged. - * @param logLevel - The log level of this log. - * @param message - The message of this log. + * @param logLevel The log level of this log. + * @param message The message of this log. */ BaseRequestPolicy.prototype.log = function (logLevel, message) { this._options.log(logLevel, message); @@ -63577,7 +62097,7 @@ var RequestPolicyOptions = /** @class */ (function () { } /** * Get whether or not a log with the provided log level should be logged. - * @param logLevel - The log level of the log that will be logged. + * @param logLevel The log level of the log that will be logged. * @returns Whether or not a log with the provided log level should be logged. */ RequestPolicyOptions.prototype.shouldLog = function (logLevel) { @@ -63588,8 +62108,8 @@ var RequestPolicyOptions = /** @class */ (function () { /** * Attempt to log the provided message to the provided logger. If no logger was provided or if * the log level does not meet the logger's threshold, then nothing will be logged. - * @param logLevel - The log level of this log. - * @param message - The message of this log. + * @param logLevel The log level of this log. + * @param message The message of this log. */ RequestPolicyOptions.prototype.log = function (logLevel, message) { if (this._logger && this.shouldLog(logLevel)) { @@ -63599,6 +62119,9 @@ var RequestPolicyOptions = /** @class */ (function () { return RequestPolicyOptions; }()); +// Copyright (c) Microsoft Corporation. +var logger = logger$1.createClientLogger("core-http"); + // Copyright (c) Microsoft Corporation. function logPolicy(loggingOptions) { if (loggingOptions === void 0) { loggingOptions = {}; } @@ -63683,7 +62206,7 @@ var LogPolicy = /** @class */ (function (_super) { // Licensed under the MIT license. /** * Get the path to this parameter's value as a dotted string (a.b.c). - * @param parameter - The parameter to get the path string for. + * @param parameter The parameter to get the path string for. * @returns The path to this parameter's value as a dotted string. */ function getPathStringFromParameter(parameter) { @@ -63704,17 +62227,14 @@ function getPathStringFromParameterPath(parameterPath, mapper) { } // Copyright (c) Microsoft Corporation. -/** - * Gets the list of status codes for streaming responses. - * @internal @hidden - */ -function getStreamResponseStatusCodes(operationSpec) { - var result = new Set(); +function isStreamOperation(operationSpec) { + var result = false; for (var statusCode in operationSpec.responses) { var operationResponse = operationSpec.responses[statusCode]; if (operationResponse.bodyMapper && operationResponse.bodyMapper.type.name === MapperType.Stream) { - result.add(Number(statusCode)); + result = true; + break; } } return result; @@ -63730,12 +62250,13 @@ var xml2jsDefaultOptionsV2 = { trim: false, normalize: false, normalizeTags: false, - attrkey: XML_ATTRKEY, + attrkey: "$", + charkey: "_", explicitArray: true, ignoreAttrs: false, mergeAttrs: false, explicitRoot: true, - validator: undefined, + validator: null, xmlns: false, explicitChildren: false, preserveChildrenOrder: false, @@ -63744,17 +62265,17 @@ var xml2jsDefaultOptionsV2 = { includeWhiteChars: false, async: false, strict: true, - attrNameProcessors: undefined, - attrValueProcessors: undefined, - tagNameProcessors: undefined, - valueProcessors: undefined, + attrNameProcessors: null, + attrValueProcessors: null, + tagNameProcessors: null, + valueProcessors: null, rootName: "root", xmldec: { version: "1.0", encoding: "UTF-8", standalone: true }, - doctype: undefined, + doctype: null, renderOpts: { pretty: true, indent: " ", @@ -63776,27 +62297,23 @@ xml2jsBuilderSettings.renderOpts = { }; /** * Converts given JSON object to XML string - * @param obj - JSON object to be converted into XML string - * @param opts - Options that govern the parsing of given JSON object + * @param obj JSON object to be converted into XML string + * @param opts Options that govern the parsing of given JSON object + * `rootName` indicates the name of the root element in the resulting XML */ function stringifyXML(obj, opts) { - var _a; - if (opts === void 0) { opts = {}; } - xml2jsBuilderSettings.rootName = opts.rootName; - xml2jsBuilderSettings.charkey = (_a = opts.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; + xml2jsBuilderSettings.rootName = (opts || {}).rootName; var builder = new xml2js.Builder(xml2jsBuilderSettings); return builder.buildObject(obj); } /** * Converts given XML string into JSON - * @param str - String containing the XML content to be parsed into JSON - * @param opts - Options that govern the parsing of given xml string + * @param str String containing the XML content to be parsed into JSON + * @param opts Options that govern the parsing of given xml string + * `includeRoot` indicates whether the root element is to be included or not in the output */ function parseXML(str, opts) { - var _a; - if (opts === void 0) { opts = {}; } - xml2jsParserSettings.explicitRoot = !!opts.includeRoot; - xml2jsParserSettings.charkey = (_a = opts.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; + xml2jsParserSettings.explicitRoot = !!(opts && opts.includeRoot); var xmlParser = new xml2js.Parser(xml2jsParserSettings); return new Promise(function (resolve, reject) { if (!str) { @@ -63820,10 +62337,10 @@ function parseXML(str, opts) { * Create a new serialization RequestPolicyCreator that will serialized HTTP request bodies as they * pass through the HTTP pipeline. */ -function deserializationPolicy(deserializationContentTypes, parsingOptions) { +function deserializationPolicy(deserializationContentTypes) { return { create: function (nextPolicy, options) { - return new DeserializationPolicy(nextPolicy, options, deserializationContentTypes, parsingOptions); + return new DeserializationPolicy(nextPolicy, deserializationContentTypes, options); } }; } @@ -63841,25 +62358,22 @@ var DefaultDeserializationOptions = { */ var DeserializationPolicy = /** @class */ (function (_super) { tslib.__extends(DeserializationPolicy, _super); - function DeserializationPolicy(nextPolicy, requestPolicyOptions, deserializationContentTypes, parsingOptions) { - if (parsingOptions === void 0) { parsingOptions = {}; } - var _a; - var _this = _super.call(this, nextPolicy, requestPolicyOptions) || this; + function DeserializationPolicy(nextPolicy, deserializationContentTypes, options) { + var _this = _super.call(this, nextPolicy, options) || this; _this.jsonContentTypes = (deserializationContentTypes && deserializationContentTypes.json) || defaultJsonContentTypes; _this.xmlContentTypes = (deserializationContentTypes && deserializationContentTypes.xml) || defaultXmlContentTypes; - _this.xmlCharKey = (_a = parsingOptions.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; return _this; } DeserializationPolicy.prototype.sendRequest = function (request) { return tslib.__awaiter(this, void 0, void 0, function () { var _this = this; return tslib.__generator(this, function (_a) { - return [2 /*return*/, this._nextPolicy.sendRequest(request).then(function (response) { - return deserializeResponseBody(_this.jsonContentTypes, _this.xmlContentTypes, response, { - xmlCharKey: _this.xmlCharKey - }); + return [2 /*return*/, this._nextPolicy + .sendRequest(request) + .then(function (response) { + return deserializeResponseBody(_this.jsonContentTypes, _this.xmlContentTypes, response); })]; }); }); @@ -63895,15 +62409,8 @@ function shouldDeserializeResponse(parsedResponse) { } return result; } -function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options) { - var _a, _b, _c; - if (options === void 0) { options = {}; } - var updatedOptions = { - rootName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "", - includeRoot: (_b = options.includeRoot) !== null && _b !== void 0 ? _b : false, - xmlCharKey: (_c = options.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY - }; - return parse(jsonContentTypes, xmlContentTypes, response, updatedOptions).then(function (parsedResponse) { +function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response) { + return parse(jsonContentTypes, xmlContentTypes, response).then(function (parsedResponse) { if (!shouldDeserializeResponse(parsedResponse)) { return parsedResponse; } @@ -63912,13 +62419,54 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, op return parsedResponse; } var responseSpec = getOperationResponse(parsedResponse); - var _a = handleErrorResponse(parsedResponse, operationSpec, responseSpec), error = _a.error, shouldReturnResponse = _a.shouldReturnResponse; - if (error) { + var expectedStatusCodes = Object.keys(operationSpec.responses); + var hasNoExpectedStatusCodes = expectedStatusCodes.length === 0 || + (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"); + var isExpectedStatusCode = hasNoExpectedStatusCodes + ? 200 <= parsedResponse.status && parsedResponse.status < 300 + : !!responseSpec; + // There is no operation response spec for current status code. + // So, treat it as an error case and use the default response spec to deserialize the response. + if (!isExpectedStatusCode) { + var defaultResponseSpec = operationSpec.responses.default; + if (!defaultResponseSpec) { + return parsedResponse; + } + var defaultBodyMapper = defaultResponseSpec.bodyMapper; + var defaultHeadersMapper = defaultResponseSpec.headersMapper; + var initialErrorMessage = isStreamOperation(operationSpec) + ? "Unexpected status code: " + parsedResponse.status + : parsedResponse.bodyAsText; + var error = new RestError(initialErrorMessage, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); + try { + // If error response has a body, try to extract error code & message from it + // Then try to deserialize it using default body mapper + if (parsedResponse.parsedBody) { + var parsedBody = parsedResponse.parsedBody; + var internalError = parsedBody.error || parsedBody; + error.code = internalError.code; + if (internalError.message) { + error.message = internalError.message; + } + if (defaultBodyMapper) { + var valueToDeserialize = parsedBody; + if (operationSpec.isXML && defaultBodyMapper.type.name === MapperType.Sequence) { + valueToDeserialize = + typeof parsedBody === "object" ? parsedBody[defaultBodyMapper.xmlElementName] : []; + } + error.response.parsedBody = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody"); + } + } + // If error response has headers, try to deserialize it using default header mapper + if (parsedResponse.headers && defaultHeadersMapper) { + error.response.parsedHeaders = operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders"); + } + } + catch (defaultError) { + error.message = "Error \"" + defaultError.message + "\" occurred in deserializing the responseBody - \"" + parsedResponse.bodyAsText + "\" for the default response."; + } throw error; } - else if (shouldReturnResponse) { - return parsedResponse; - } // An operation response spec does exist for current status code, so // use it to deserialize the response. if (responseSpec) { @@ -63931,10 +62479,10 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, op : []; } try { - parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options); + parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody"); } - catch (innerError) { - var restError = new RestError("Error " + innerError + " occurred in deserializing the responseBody - " + parsedResponse.bodyAsText, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); + catch (error) { + var restError = new RestError("Error " + error + " occurred in deserializing the responseBody - " + parsedResponse.bodyAsText, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); throw restError; } } @@ -63943,91 +62491,20 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, op parsedResponse.parsedBody = response.status >= 200 && response.status < 300; } if (responseSpec.headersMapper) { - parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders", options); + parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders"); } } return parsedResponse; }); } -function isOperationSpecEmpty(operationSpec) { - var expectedStatusCodes = Object.keys(operationSpec.responses); - return (expectedStatusCodes.length === 0 || - (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default")); -} -function handleErrorResponse(parsedResponse, operationSpec, responseSpec) { - var _a; - var isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300; - var isExpectedStatusCode = isOperationSpecEmpty(operationSpec) - ? isSuccessByStatus - : !!responseSpec; - if (isExpectedStatusCode) { - if (responseSpec) { - if (!responseSpec.isError) { - return { error: null, shouldReturnResponse: false }; - } - } - else { - return { error: null, shouldReturnResponse: false }; - } - } - var errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default; - var streaming = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status)) || - parsedResponse.request.streamResponseBody; - var initialErrorMessage = streaming - ? "Unexpected status code: " + parsedResponse.status - : parsedResponse.bodyAsText; - var error = new RestError(initialErrorMessage, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); - // If the item failed but there's no error spec or default spec to deserialize the error, - // we should fail so we just throw the parsed response - if (!errorResponseSpec) { - throw error; - } - var defaultBodyMapper = errorResponseSpec.bodyMapper; - var defaultHeadersMapper = errorResponseSpec.headersMapper; - try { - // If error response has a body, try to deserialize it using default body mapper. - // Then try to extract error code & message from it - if (parsedResponse.parsedBody) { - var parsedBody = parsedResponse.parsedBody; - var parsedError = void 0; - if (defaultBodyMapper) { - var valueToDeserialize = parsedBody; - if (operationSpec.isXML && defaultBodyMapper.type.name === MapperType.Sequence) { - valueToDeserialize = - typeof parsedBody === "object" ? parsedBody[defaultBodyMapper.xmlElementName] : []; - } - parsedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody"); - } - var internalError = parsedBody.error || parsedError || parsedBody; - error.code = internalError.code; - if (internalError.message) { - error.message = internalError.message; - } - if (defaultBodyMapper) { - error.response.parsedBody = parsedError; - } - } - // If error response has headers, try to deserialize it using default header mapper - if (parsedResponse.headers && defaultHeadersMapper) { - error.response.parsedHeaders = operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders"); - } - } - catch (defaultError) { - error.message = "Error \"" + defaultError.message + "\" occurred in deserializing the responseBody - \"" + parsedResponse.bodyAsText + "\" for the default response."; - } - return { error: error, shouldReturnResponse: false }; -} -function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts) { - var _a; +function parse(jsonContentTypes, xmlContentTypes, operationResponse) { var errorHandler = function (err) { var msg = "Error \"" + err + "\" occurred while parsing the response body - " + operationResponse.bodyAsText + "."; var errCode = err.code || RestError.PARSE_ERROR; var e = new RestError(msg, errCode, operationResponse.status, operationResponse.request, operationResponse); return Promise.reject(e); }; - var streaming = ((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) || - operationResponse.request.streamResponseBody; - if (!streaming && operationResponse.bodyAsText) { + if (!operationResponse.request.streamResponseBody && operationResponse.bodyAsText) { var text_1 = operationResponse.bodyAsText; var contentType = operationResponse.headers.get("Content-Type") || ""; var contentComponents = !contentType @@ -64041,7 +62518,7 @@ function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts) { }).catch(errorHandler); } else if (contentComponents.some(function (component) { return xmlContentTypes.indexOf(component) !== -1; })) { - return parseXML(text_1, opts) + return parseXML(text_1) .then(function (body) { operationResponse.parsedBody = body; return operationResponse; @@ -64066,10 +62543,10 @@ function isNumber(n) { * @internal * Determines if the operation should be retried. * - * @param retryLimit - Specifies the max number of retries. - * @param predicate - Initial chekck on whether to retry based on given responses or errors - * @param retryData - The retry data. - * @returns True if the operation qualifies for a retry; false otherwise. + * @param {number} retryLimit Specifies the max number of retries. + * @param {(response?: HttpOperationResponse, error?: RetryError) => boolean} predicate Initial chekck on whether to retry based on given responses or errors + * @param {RetryData} retryData The retry data. + * @return {boolean} True if the operation qualifies for a retry; false otherwise. */ function shouldRetry(retryLimit, predicate, retryData, response, error) { if (!predicate(response, error)) { @@ -64081,9 +62558,9 @@ function shouldRetry(retryLimit, predicate, retryData, response, error) { * @internal * Updates the retry data for the next attempt. * - * @param retryOptions - specifies retry interval, and its lower bound and upper bound. - * @param retryData - The retry data. - * @param err - The operation"s error, if any. + * @param {RetryPolicyOptions} retryOptions specifies retry interval, and its lower bound and upper bound. + * @param {RetryData} [retryData] The retry data. + * @param {RetryError} [err] The operation"s error, if any. */ function updateRetryData(retryOptions, retryData, err) { if (retryData === void 0) { retryData = { retryCount: 0, retryInterval: 0 }; } @@ -64121,17 +62598,19 @@ var DefaultRetryOptions = { maxRetryDelayInMs: DEFAULT_CLIENT_MAX_RETRY_INTERVAL }; /** + * @class * Instantiates a new "ExponentialRetryPolicyFilter" instance. */ var ExponentialRetryPolicy = /** @class */ (function (_super) { tslib.__extends(ExponentialRetryPolicy, _super); /** - * @param nextPolicy - The next RequestPolicy in the pipeline chain. - * @param options - The options for this RequestPolicy. - * @param retryCount - The client retry count. - * @param retryInterval - The client retry interval, in milliseconds. - * @param minRetryInterval - The minimum retry interval, in milliseconds. - * @param maxRetryInterval - The maximum retry interval, in milliseconds. + * @constructor + * @param {RequestPolicy} nextPolicy The next RequestPolicy in the pipeline chain. + * @param {RequestPolicyOptions} options The options for this RequestPolicy. + * @param {number} [retryCount] The client retry count. + * @param {number} [retryInterval] The client retry interval, in milliseconds. + * @param {number} [minRetryInterval] The minimum retry interval, in milliseconds. + * @param {number} [maxRetryInterval] The maximum retry interval, in milliseconds. */ function ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, maxRetryInterval) { var _this = _super.call(this, nextPolicy, options) || this; @@ -64153,8 +62632,8 @@ var ExponentialRetryPolicy = /** @class */ (function (_super) { }(BaseRequestPolicy)); function retry(policy, request, response, retryData, requestError) { return tslib.__awaiter(this, void 0, void 0, function () { - function shouldPolicyRetry(responseParam) { - var statusCode = responseParam === null || responseParam === void 0 ? void 0 : responseParam.status; + function shouldPolicyRetry(response) { + var statusCode = response === null || response === void 0 ? void 0 : response.status; if (statusCode === undefined || (statusCode < 500 && statusCode !== 408) || statusCode === 501 || @@ -64309,10 +62788,6 @@ var UserAgentPolicy = /** @class */ (function (_super) { }(BaseRequestPolicy)); // Copyright (c) Microsoft Corporation. -/** - * Methods that are allowed to follow redirects 301 and 302 - */ -var allowedRedirect = ["GET", "HEAD"]; var DefaultRedirectOptions = { handleRedirects: true, maxRetries: 20 @@ -64345,11 +62820,7 @@ function handleRedirect(policy, response, currentRetries) { var request = response.request, status = response.status; var locationHeader = response.headers.get("location"); if (locationHeader && - (status === 300 || - (status === 301 && allowedRedirect.includes(request.method)) || - (status === 302 && allowedRedirect.includes(request.method)) || - (status === 303 && request.method === "POST") || - status === 307) && + (status === 300 || status === 307 || (status === 303 && request.method === "POST")) && (!policy.maxRetries || currentRetries < policy.maxRetries)) { var builder = URLBuilder.parse(request.url); builder.setPath(locationHeader); @@ -64358,7 +62829,6 @@ function handleRedirect(policy, response, currentRetries) { // redirected GET request if the redirect url is present in the location header if (status === 303) { request.method = "GET"; - delete request.body; } return policy._nextPolicy .sendRequest(request) @@ -64417,9 +62887,9 @@ function registerIfNeeded(policy, request, response) { } /** * Reuses the headers of the original request and url (if specified). - * @param originalRequest - The original request - * @param reuseUrlToo - Should the url from the original request be reused as well. Default false. - * @returns A new request object with desired headers. + * @param {WebResourceLike} originalRequest The original request + * @param {boolean} reuseUrlToo Should the url from the original request be reused as well. Default false. + * @returns {object} A new request object with desired headers. */ function getRequestEssentials(originalRequest, reuseUrlToo) { if (reuseUrlToo === void 0) { reuseUrlToo = false; } @@ -64437,8 +62907,8 @@ function getRequestEssentials(originalRequest, reuseUrlToo) { /** * Validates the error code and message associated with 409 response status code. If it matches to that of * RP not registered then it returns the name of the RP else returns undefined. - * @param body - The response body received after making the original request. - * @returns The name of the RP if condition is satisfied else undefined. + * @param {string} body The response body received after making the original request. + * @returns {string} The name of the RP if condition is satisfied else undefined. */ function checkRPNotRegisteredError(body) { var result, responseBody; @@ -64465,8 +62935,8 @@ function checkRPNotRegisteredError(body) { /** * Extracts the first part of the URL, just after subscription: * https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ - * @param url - The original request url - * @returns The url prefix as explained above. + * @param {string} url The original request url + * @returns {string} The url prefix as explained above. */ function extractSubscriptionUrl(url) { var result; @@ -64481,12 +62951,12 @@ function extractSubscriptionUrl(url) { } /** * Registers the given provider. - * @param policy - The RPRegistrationPolicy this function is being called against. - * @param urlPrefix - https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ - * @param provider - The provider name to be registered. - * @param originalRequest - The original request sent by the user that returned a 409 response + * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against. + * @param {string} urlPrefix https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ + * @param {string} provider The provider name to be registered. + * @param {WebResourceLike} originalRequest The original request sent by the user that returned a 409 response * with a message that the provider is not registered. - * @param callback - The callback that handles the RP registration + * @param {registrationCallback} callback The callback that handles the RP registration */ function registerRP(policy, urlPrefix, provider, originalRequest) { var postUrl = urlPrefix + "providers/" + provider + "/register?api-version=2016-02-01"; @@ -64504,11 +62974,11 @@ function registerRP(policy, urlPrefix, provider, originalRequest) { /** * Polls the registration status of the provider that was registered. Polling happens at an interval of 30 seconds. * Polling will happen till the registrationState property of the response body is "Registered". - * @param policy - The RPRegistrationPolicy this function is being called against. - * @param url - The request url for polling - * @param originalRequest - The original request sent by the user that returned a 409 response + * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against. + * @param {string} url The request url for polling + * @param {WebResourceLike} originalRequest The original request sent by the user that returned a 409 response * with a message that the provider is not registered. - * @returns True if RP Registration is successful. + * @returns {Promise} True if RP Registration is successful. */ function getRegistrationStatus(policy, url, originalRequest) { var reqOptions = getRequestEssentials(originalRequest); @@ -64575,6 +63045,8 @@ var AccessTokenRefresher = /** @class */ (function () { /** * Returns true if the required milliseconds(defaulted to 30000) have been passed signifying * that we are ready for a new refresh. + * + * @returns {boolean} */ AccessTokenRefresher.prototype.isReady = function () { // We're only ready for a new refresh if the required milliseconds have passed. @@ -64585,6 +63057,7 @@ var AccessTokenRefresher = /** @class */ (function () { * then requests a new token, * then sets this.promise to undefined, * then returns the token. + * @param options getToken options */ AccessTokenRefresher.prototype.getToken = function (options) { return tslib.__awaiter(this, void 0, void 0, function () { @@ -64605,6 +63078,7 @@ var AccessTokenRefresher = /** @class */ (function () { /** * Requests a new token if we're not currently waiting for a new token. * Returns null if the required time between each call hasn't been reached. + * @param options getToken options */ AccessTokenRefresher.prototype.refresh = function (options) { if (!this.promise) { @@ -64616,17 +63090,11 @@ var AccessTokenRefresher = /** @class */ (function () { }()); // Copyright (c) Microsoft Corporation. -/** - * The automated token refresh will only start to happen at the - * expiration date minus the value of timeBetweenRefreshAttemptsInMs, - * which is by default 30 seconds. - */ -var timeBetweenRefreshAttemptsInMs = 30000; /** * Creates a new BearerTokenAuthenticationPolicy factory. * - * @param credential - The TokenCredential implementation that can supply the bearer token. - * @param scopes - The scopes for which the bearer token applies. + * @param credential The TokenCredential implementation that can supply the bearer token. + * @param scopes The scopes for which the bearer token applies. */ function bearerTokenAuthenticationPolicy(credential, scopes) { var tokenCache = new ExpiringAccessTokenCache(); @@ -64637,6 +63105,12 @@ function bearerTokenAuthenticationPolicy(credential, scopes) { } }; } +/** + * The automated token refresh will only start to happen at the + * expiration date minus the value of timeBetweenRefreshAttemptsInMs, + * which is by default 30 seconds. + */ +var timeBetweenRefreshAttemptsInMs = 30000; /** * * Provides a RequestPolicy that can request a token from a TokenCredential @@ -64649,11 +63123,11 @@ var BearerTokenAuthenticationPolicy = /** @class */ (function (_super) { /** * Creates a new BearerTokenAuthenticationPolicy object. * - * @param nextPolicy - The next RequestPolicy in the request pipeline. - * @param options - Options for this RequestPolicy. - * @param credential - The TokenCredential implementation that can supply the bearer token. - * @param scopes - The scopes for which the bearer token applies. - * @param tokenCache - The cache for the most recent AccessToken returned from the TokenCredential. + * @param nextPolicy The next RequestPolicy in the request pipeline. + * @param options Options for this RequestPolicy. + * @param credential The TokenCredential implementation that can supply the bearer token. + * @param scopes The scopes for which the bearer token applies. + * @param tokenCache The cache for the most recent AccessToken returned from the TokenCredential. */ function BearerTokenAuthenticationPolicy(nextPolicy, options, tokenCache, tokenRefresher) { var _this = _super.call(this, nextPolicy, options) || this; @@ -64663,6 +63137,7 @@ var BearerTokenAuthenticationPolicy = /** @class */ (function (_super) { } /** * Applies the Bearer token to the request through the Authorization header. + * @param webResource */ BearerTokenAuthenticationPolicy.prototype.sendRequest = function (webResource) { return tslib.__awaiter(this, void 0, void 0, function () { @@ -64744,10 +63219,14 @@ function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, max }; } /** - * @param retryCount - The client retry count. - * @param retryInterval - The client retry interval, in milliseconds. - * @param minRetryInterval - The minimum retry interval, in milliseconds. - * @param maxRetryInterval - The maximum retry interval, in milliseconds. + * @class + * Instantiates a new "ExponentialRetryPolicyFilter" instance. + * + * @constructor + * @param {number} retryCount The client retry count. + * @param {number} retryInterval The client retry interval, in milliseconds. + * @param {number} minRetryInterval The minimum retry interval, in milliseconds. + * @param {number} maxRetryInterval The maximum retry interval, in milliseconds. */ var SystemErrorRetryPolicy = /** @class */ (function (_super) { tslib.__extends(SystemErrorRetryPolicy, _super); @@ -64785,7 +63264,7 @@ function retry$1(policy, request, operationResponse, err, retryData) { } return false; } - var nestedErr_1; + var err_1; return tslib.__generator(this, function (_a) { switch (_a.label) { case 0: @@ -64799,8 +63278,8 @@ function retry$1(policy, request, operationResponse, err, retryData) { _a.sent(); return [2 /*return*/, policy._nextPolicy.sendRequest(request.clone())]; case 3: - nestedErr_1 = _a.sent(); - return [2 /*return*/, retry$1(policy, request, operationResponse, nestedErr_1, retryData)]; + err_1 = _a.sent(); + return [2 /*return*/, retry$1(policy, request, operationResponse, err_1, retryData)]; case 4: return [3 /*break*/, 6]; case 5: if (err) { @@ -64824,10 +63303,8 @@ function retry$1(policy, request, operationResponse, err, retryData) { })(exports.QueryCollectionFormat || (exports.QueryCollectionFormat = {})); // Copyright (c) Microsoft Corporation. -/** - * @internal - */ -var noProxyList = loadNoProxy(); +var noProxyList = []; +var isNoProxyInitalized = false; var byPassedList = new Map(); function loadEnvironmentProxyValue() { if (!process) { @@ -64838,53 +63315,45 @@ function loadEnvironmentProxyValue() { var httpProxy = getEnvironmentValue(Constants.HTTP_PROXY); return httpsProxy || allProxy || httpProxy; } -// Check whether the host of a given `uri` is in the noProxyList. -// If there's a match, any request sent to the same host won't have the proxy settings set. -// This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210 +// Check whether the given `uri` matches the noProxyList. If it matches, any request sent to that same `uri` won't set the proxy settings. function isBypassed(uri) { - if (noProxyList.length === 0) { - return false; + if (byPassedList.has(uri)) { + return byPassedList.get(uri); } + loadNoProxy(); + var isBypassed = false; var host = URLBuilder.parse(uri).getHost(); - if (byPassedList.has(host)) { - return byPassedList.get(host); - } - var isBypassedFlag = false; for (var _i = 0, noProxyList_1 = noProxyList; _i < noProxyList_1.length; _i++) { - var pattern = noProxyList_1[_i]; - if (pattern[0] === ".") { - // This should match either domain it self or any subdomain or host - // .foo.com will match foo.com it self or *.foo.com - if (host.endsWith(pattern)) { - isBypassedFlag = true; + var proxyString = noProxyList_1[_i]; + if (proxyString[0] === ".") { + if (uri.endsWith(proxyString)) { + isBypassed = true; } else { - if (host.length === pattern.length - 1 && host === pattern.slice(1)) { - isBypassedFlag = true; + if (host === proxyString.slice(1) && host.length === proxyString.length - 1) { + isBypassed = true; } } } else { - if (host === pattern) { - isBypassedFlag = true; + if (host === proxyString) { + isBypassed = true; } } } - byPassedList.set(host, isBypassedFlag); - return isBypassedFlag; + byPassedList.set(uri, isBypassed); + return isBypassed; } -/** - * @internal - */ function loadNoProxy() { + if (isNoProxyInitalized) { + return; + } var noProxy = getEnvironmentValue(Constants.NO_PROXY); if (noProxy) { - return noProxy - .split(",") - .map(function (item) { return item.trim(); }) - .filter(function (item) { return item.length; }); + var list = noProxy.split(","); + noProxyList = list.map(function (item) { return item.trim(); }).filter(function (item) { return item.length; }); } - return []; + isNoProxyInitalized = true; } function getDefaultProxySettings(proxyUrl) { if (!proxyUrl) { @@ -65070,9 +63539,9 @@ var KeepAlivePolicy = /** @class */ (function (_super) { /** * Creates an instance of KeepAlivePolicy. * - * @param nextPolicy - - * @param options - - * @param keepAliveOptions - + * @param {RequestPolicy} nextPolicy + * @param {RequestPolicyOptions} options + * @param {KeepAliveOptions} [keepAliveOptions] */ function KeepAlivePolicy(nextPolicy, options, keepAliveOptions) { var _this = _super.call(this, nextPolicy, options) || this; @@ -65082,8 +63551,9 @@ var KeepAlivePolicy = /** @class */ (function (_super) { /** * Sends out request. * - * @param request - - * @returns + * @param {WebResourceLike} request + * @returns {Promise} + * @memberof KeepAlivePolicy */ KeepAlivePolicy.prototype.sendRequest = function (request) { return tslib.__awaiter(this, void 0, void 0, function () { @@ -65189,8 +63659,8 @@ var DisableResponseDecompressionPolicy = /** @class */ (function (_super) { /** * Creates an instance of DisableResponseDecompressionPolicy. * - * @param nextPolicy - - * @param options - + * @param {RequestPolicy} nextPolicy + * @param {RequestPolicyOptions} options */ // The parent constructor is protected. /* eslint-disable-next-line @typescript-eslint/no-useless-constructor */ @@ -65200,8 +63670,8 @@ var DisableResponseDecompressionPolicy = /** @class */ (function (_super) { /** * Sends out request. * - * @param request - - * @returns + * @param {WebResource} request + * @returns {Promise} */ DisableResponseDecompressionPolicy.prototype.sendRequest = function (request) { return tslib.__awaiter(this, void 0, void 0, function () { @@ -65229,12 +63699,17 @@ var NdJsonPolicy = /** @class */ (function (_super) { tslib.__extends(NdJsonPolicy, _super); /** * Creates an instance of KeepAlivePolicy. + * + * @param nextPolicy + * @param options */ function NdJsonPolicy(nextPolicy, options) { return _super.call(this, nextPolicy, options) || this; } /** * Sends a request. + * + * @param request */ NdJsonPolicy.prototype.sendRequest = function (request) { return tslib.__awaiter(this, void 0, void 0, function () { @@ -65254,24 +63729,17 @@ var NdJsonPolicy = /** @class */ (function (_super) { return NdJsonPolicy; }(BaseRequestPolicy)); -// Copyright (c) Microsoft Corporation. -var cachedHttpClient; -function getCachedDefaultHttpClient() { - if (!cachedHttpClient) { - cachedHttpClient = new NodeFetchHttpClient(); - } - return cachedHttpClient; -} - // Copyright (c) Microsoft Corporation. /** - * ServiceClient sends service requests and receives responses. + * @class + * Initializes a new instance of the ServiceClient. */ var ServiceClient = /** @class */ (function () { /** * The ServiceClient constructor - * @param credentials - The credentials used for authentication with the service. - * @param options - The service client options that govern the behavior of the client. + * @constructor + * @param credentials The credentials used for authentication with the service. + * @param options The service client options that govern the behavior of the client. */ function ServiceClient(credentials, /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options */ @@ -65281,7 +63749,7 @@ var ServiceClient = /** @class */ (function () { options = {}; } this._withCredentials = options.withCredentials || false; - this._httpClient = options.httpClient || getCachedDefaultHttpClient(); + this._httpClient = options.httpClient || new NodeFetchHttpClient(); this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger); var requestPolicyFactories; if (Array.isArray(options.requestPolicyFactories)) { @@ -65302,17 +63770,12 @@ var ServiceClient = /** @class */ (function () { var bearerTokenPolicyFactory = undefined; // eslint-disable-next-line @typescript-eslint/no-this-alias var serviceClient = _this; - var serviceClientOptions = options; return { - create: function (nextPolicy, createOptions) { - var credentialScopes = getCredentialScopes(serviceClientOptions, serviceClient.baseUri); - if (!credentialScopes) { - throw new Error("When using credential, the ServiceClient must contain a baseUri or a credentialScopes in ServiceClientOptions. Unable to create a bearerTokenAuthenticationPolicy"); - } + create: function (nextPolicy, options) { if (bearerTokenPolicyFactory === undefined || bearerTokenPolicyFactory === null) { - bearerTokenPolicyFactory = bearerTokenAuthenticationPolicy(credentials, credentialScopes); + bearerTokenPolicyFactory = bearerTokenAuthenticationPolicy(credentials, (serviceClient.baseUri || "") + "/.default"); } - return bearerTokenPolicyFactory.create(nextPolicy, createOptions); + return bearerTokenPolicyFactory.create(nextPolicy, options); } }; }; @@ -65369,26 +63832,24 @@ var ServiceClient = /** @class */ (function () { }; /** * Send an HTTP request that is populated using the provided OperationSpec. - * @param operationArguments - The arguments that the HTTP request's templated values will be populated from. - * @param operationSpec - The OperationSpec to use to populate the httpRequest. - * @param callback - The callback to call when the response is received. + * @param {OperationArguments} operationArguments The arguments that the HTTP request's templated values will be populated from. + * @param {OperationSpec} operationSpec The OperationSpec to use to populate the httpRequest. + * @param {ServiceCallback} callback The callback to call when the response is received. */ ServiceClient.prototype.sendOperationRequest = function (operationArguments, operationSpec, callback) { - var _a; return tslib.__awaiter(this, void 0, void 0, function () { - var serializerOptions, httpRequest, result, baseUri, requestUrl, _i, _b, urlParameter, urlParameterValue, _c, _d, queryParameter, queryParameterValue, index, item, index, contentType, _e, _f, headerParameter, headerValue, headerCollectionPrefix, _g, _h, key, options, customHeaderName, rawResponse, sendRequestError, error_1, error_2, cb; - return tslib.__generator(this, function (_j) { - switch (_j.label) { + var httpRequest, result, baseUri, requestUrl, _i, _a, urlParameter, urlParameterValue, _b, _c, queryParameter, queryParameterValue, index, item, index, contentType, _d, _e, headerParameter, headerValue, headerCollectionPrefix, _f, _g, key, options, customHeaderName, rawResponse, sendRequestError, error_1, error_2, cb; + return tslib.__generator(this, function (_h) { + switch (_h.label) { case 0: if (typeof operationArguments.options === "function") { callback = operationArguments.options; operationArguments.options = undefined; } - serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; httpRequest = new WebResource(); - _j.label = 1; + _h.label = 1; case 1: - _j.trys.push([1, 6, , 7]); + _h.trys.push([1, 6, , 7]); baseUri = operationSpec.baseUrl || this.baseUri; if (!baseUri) { throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a baseUri string property that contains the base URL to use."); @@ -65400,10 +63861,10 @@ var ServiceClient = /** @class */ (function () { requestUrl.appendPath(operationSpec.path); } if (operationSpec.urlParameters && operationSpec.urlParameters.length > 0) { - for (_i = 0, _b = operationSpec.urlParameters; _i < _b.length; _i++) { - urlParameter = _b[_i]; + for (_i = 0, _a = operationSpec.urlParameters; _i < _a.length; _i++) { + urlParameter = _a[_i]; urlParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, urlParameter, operationSpec.serializer); - urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, getPathStringFromParameter(urlParameter), serializerOptions); + urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, getPathStringFromParameter(urlParameter)); if (!urlParameter.skipEncoding) { urlParameterValue = encodeURIComponent(urlParameterValue); } @@ -65411,17 +63872,16 @@ var ServiceClient = /** @class */ (function () { } } if (operationSpec.queryParameters && operationSpec.queryParameters.length > 0) { - for (_c = 0, _d = operationSpec.queryParameters; _c < _d.length; _c++) { - queryParameter = _d[_c]; + for (_b = 0, _c = operationSpec.queryParameters; _b < _c.length; _b++) { + queryParameter = _c[_b]; queryParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, queryParameter, operationSpec.serializer); if (queryParameterValue !== undefined && queryParameterValue !== null) { - queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter), serializerOptions); + queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter)); if (queryParameter.collectionFormat !== undefined && queryParameter.collectionFormat !== null) { if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Multi) { if (queryParameterValue.length === 0) { - // The collection is empty, no need to try serializing the current queryParam - continue; + queryParameterValue = ""; } else { for (index in queryParameterValue) { @@ -65462,20 +63922,20 @@ var ServiceClient = /** @class */ (function () { } httpRequest.url = requestUrl.toString(); contentType = operationSpec.contentType || this.requestContentType; - if (contentType && operationSpec.requestBody) { + if (contentType) { httpRequest.headers.set("Content-Type", contentType); } if (operationSpec.headerParameters) { - for (_e = 0, _f = operationSpec.headerParameters; _e < _f.length; _e++) { - headerParameter = _f[_e]; + for (_d = 0, _e = operationSpec.headerParameters; _d < _e.length; _d++) { + headerParameter = _e[_d]; headerValue = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer); if (headerValue !== undefined && headerValue !== null) { - headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter), serializerOptions); + headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter)); headerCollectionPrefix = headerParameter.mapper .headerCollectionPrefix; if (headerCollectionPrefix) { - for (_g = 0, _h = Object.keys(headerValue); _g < _h.length; _g++) { - key = _h[_g]; + for (_f = 0, _g = Object.keys(headerValue); _f < _g.length; _f++) { + key = _g[_f]; httpRequest.headers.set(headerCollectionPrefix + key, headerValue[key]); } } @@ -65514,20 +63974,20 @@ var ServiceClient = /** @class */ (function () { } httpRequest.withCredentials = this._withCredentials; serializeRequestBody(this, httpRequest, operationArguments, operationSpec); - if (httpRequest.streamResponseStatusCodes === undefined) { - httpRequest.streamResponseStatusCodes = getStreamResponseStatusCodes(operationSpec); + if (httpRequest.streamResponseBody === undefined || httpRequest.streamResponseBody === null) { + httpRequest.streamResponseBody = isStreamOperation(operationSpec); } rawResponse = void 0; sendRequestError = void 0; - _j.label = 2; + _h.label = 2; case 2: - _j.trys.push([2, 4, , 5]); + _h.trys.push([2, 4, , 5]); return [4 /*yield*/, this.sendRequest(httpRequest)]; case 3: - rawResponse = _j.sent(); + rawResponse = _h.sent(); return [3 /*break*/, 5]; case 4: - error_1 = _j.sent(); + error_1 = _h.sent(); sendRequestError = error_1; return [3 /*break*/, 5]; case 5: @@ -65543,13 +64003,14 @@ var ServiceClient = /** @class */ (function () { } return [3 /*break*/, 7]; case 6: - error_2 = _j.sent(); + error_2 = _h.sent(); result = Promise.reject(error_2); return [3 /*break*/, 7]; case 7: cb = callback; if (cb) { result + // tslint:disable-next-line:no-null-keyword .then(function (res) { return cb(null, res._response.parsedBody, res._response.request, res._response); }) .catch(function (err) { return cb(err); }); } @@ -65561,14 +64022,7 @@ var ServiceClient = /** @class */ (function () { return ServiceClient; }()); function serializeRequestBody(serviceClient, httpRequest, operationArguments, operationSpec) { - var _a, _b, _c, _d, _e, _f; - var serializerOptions = (_b = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions) !== null && _b !== void 0 ? _b : {}; - var updatedOptions = { - rootName: (_c = serializerOptions.rootName) !== null && _c !== void 0 ? _c : "", - includeRoot: (_d = serializerOptions.includeRoot) !== null && _d !== void 0 ? _d : false, - xmlCharKey: (_e = serializerOptions.xmlCharKey) !== null && _e !== void 0 ? _e : XML_CHARKEY - }; - var xmlCharKey = serializerOptions.xmlCharKey; + var _a; if (operationSpec.requestBody && operationSpec.requestBody.mapper) { httpRequest.body = getOperationArgumentValueFromParameter(serviceClient, operationArguments, operationSpec.requestBody, operationSpec.serializer); var bodyMapper = operationSpec.requestBody.mapper; @@ -65577,26 +64031,22 @@ function serializeRequestBody(serviceClient, httpRequest, operationArguments, op try { if ((httpRequest.body !== undefined && httpRequest.body !== null) || required) { var requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody); - httpRequest.body = operationSpec.serializer.serialize(bodyMapper, httpRequest.body, requestBodyParameterPathString, updatedOptions); + httpRequest.body = operationSpec.serializer.serialize(bodyMapper, httpRequest.body, requestBodyParameterPathString); var isStream = typeName === MapperType.Stream; if (operationSpec.isXML) { var xmlnsKey = xmlNamespacePrefix ? "xmlns:" + xmlNamespacePrefix : "xmlns"; - var value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, httpRequest.body, updatedOptions); + var value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, httpRequest.body); if (typeName === MapperType.Sequence) { - httpRequest.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { - rootName: xmlName || serializedName, - xmlCharKey: xmlCharKey - }); + httpRequest.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName }); } else if (!isStream) { httpRequest.body = stringifyXML(value, { - rootName: xmlName || serializedName, - xmlCharKey: xmlCharKey + rootName: xmlName || serializedName }); } } else if (typeName === MapperType.String && - (((_f = operationSpec.contentType) === null || _f === void 0 ? void 0 : _f.match("text/plain")) || operationSpec.mediaType === "text")) { + (((_a = operationSpec.contentType) === null || _a === void 0 ? void 0 : _a.match("text/plain")) || operationSpec.mediaType === "text")) { // the String serializer has validated that request body is a string // so just send the string. return; @@ -65612,12 +64062,12 @@ function serializeRequestBody(serviceClient, httpRequest, operationArguments, op } else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) { httpRequest.formData = {}; - for (var _i = 0, _g = operationSpec.formDataParameters; _i < _g.length; _i++) { - var formDataParameter = _g[_i]; + for (var _i = 0, _b = operationSpec.formDataParameters; _i < _b.length; _i++) { + var formDataParameter = _b[_i]; var formDataParameterValue = getOperationArgumentValueFromParameter(serviceClient, operationArguments, formDataParameter, operationSpec.serializer); if (formDataParameterValue !== undefined && formDataParameterValue !== null) { var formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter); - httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter), updatedOptions); + httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter)); } } } @@ -65625,15 +64075,12 @@ function serializeRequestBody(serviceClient, httpRequest, operationArguments, op /** * Adds an xml namespace to the xml serialized object if needed, otherwise it just returns the value itself */ -function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue, options) { +function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue) { var _a; // Composite and Sequence schemas already got their root namespace set during serialization // We just need to add xmlns to the other schema types if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) { - var result = {}; - result[options.xmlCharKey] = serializedValue; - result[XML_ATTRKEY] = (_a = {}, _a[xmlnsKey] = xmlNamespace, _a); - return result; + return { _: serializedValue, $: (_a = {}, _a[xmlnsKey] = xmlNamespace, _a) }; } return serializedValue; } @@ -65722,12 +64169,10 @@ function getOperationArgumentValueFromParameter(serviceClient, operationArgument return getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameter.parameterPath, parameter.mapper, serializer); } function getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, serializer) { - var _a; var value; if (typeof parameterPath === "string") { parameterPath = [parameterPath]; } - var serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; if (Array.isArray(parameterPath)) { if (parameterPath.length > 0) { if (parameterMapper.isConstant) { @@ -65748,7 +64193,7 @@ function getOperationArgumentValueFromParameterPath(serviceClient, operationArgu } // Serialize just for validation purposes. var parameterPathString = getPathStringFromParameterPath(parameterPath, parameterMapper); - serializer.serialize(parameterMapper, value, parameterPathString, serializerOptions); + serializer.serialize(parameterMapper, value, parameterPathString); } } else { @@ -65761,7 +64206,7 @@ function getOperationArgumentValueFromParameterPath(serviceClient, operationArgu var propertyValue = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, propertyPath, propertyMapper, serializer); // Serialize just for validation purposes. var propertyPathString = getPathStringFromParameterPath(propertyPath, propertyMapper); - serializer.serialize(propertyMapper, propertyValue, propertyPathString, serializerOptions); + serializer.serialize(propertyMapper, propertyValue, propertyPathString); if (propertyValue !== undefined && propertyValue !== null) { if (!value) { value = {}; @@ -65835,46 +64280,6 @@ function flattenResponse(_response, responseSpec) { } return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), _response.parsedBody)); } -function getCredentialScopes(options, baseUri) { - if (options === null || options === void 0 ? void 0 : options.credentialScopes) { - var scopes = options.credentialScopes; - return Array.isArray(scopes) - ? scopes.map(function (scope) { return new url.URL(scope).toString(); }) - : new url.URL(scopes).toString(); - } - if (baseUri) { - return baseUri + "/.default"; - } - return undefined; -} - -// Copyright (c) Microsoft Corporation. -/** - * Creates a function called createSpan to create spans using the global tracer. - * @hidden - * @param spanConfig - The name of the operation being performed. - * @param tracingOptions - The options for the underlying http request. - */ -function createSpanFunction(_a) { - var packagePrefix = _a.packagePrefix, namespace = _a.namespace; - return function (operationName, operationOptions) { - var tracer = coreTracing.getTracer(); - var tracingOptions = operationOptions.tracingOptions || {}; - var spanOptions = tslib.__assign(tslib.__assign({}, tracingOptions.spanOptions), { kind: api.SpanKind.INTERNAL }); - var span = tracer.startSpan(packagePrefix + "." + operationName, spanOptions); - span.setAttribute("az.namespace", namespace); - var newSpanOptions = tracingOptions.spanOptions || {}; - if (span.isRecording()) { - newSpanOptions = tslib.__assign(tslib.__assign({}, tracingOptions.spanOptions), { parent: span.context(), attributes: tslib.__assign(tslib.__assign({}, spanOptions.attributes), { "az.namespace": namespace }) }); - } - var newTracingOptions = tslib.__assign(tslib.__assign({}, tracingOptions), { spanOptions: newSpanOptions }); - var newOperationOptions = tslib.__assign(tslib.__assign({}, operationOptions), { tracingOptions: newTracingOptions }); - return { - span: span, - updatedOptions: newOperationOptions - }; - }; -} // Copyright (c) Microsoft Corporation. var HeaderConstants = Constants.HeaderConstants; @@ -65883,9 +64288,10 @@ var BasicAuthenticationCredentials = /** @class */ (function () { /** * Creates a new BasicAuthenticationCredentials object. * - * @param userName - User name. - * @param password - Password. - * @param authorizationScheme - The authorization scheme. + * @constructor + * @param {string} userName User name. + * @param {string} password Password. + * @param {string} [authorizationScheme] The authorization scheme. */ function BasicAuthenticationCredentials(userName, password, authorizationScheme) { if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME; } @@ -65903,8 +64309,8 @@ var BasicAuthenticationCredentials = /** @class */ (function () { /** * Signs a request with the Authentication header. * - * @param webResource - The WebResourceLike to be signed. - * @returns The signed request object. + * @param {WebResourceLike} webResource The WebResourceLike to be signed. + * @returns {Promise} The signed request object. */ BasicAuthenticationCredentials.prototype.signRequest = function (webResource) { var credentials = this.userName + ":" + this.password; @@ -65923,7 +64329,8 @@ var BasicAuthenticationCredentials = /** @class */ (function () { */ var ApiKeyCredentials = /** @class */ (function () { /** - * @param options - Specifies the options to be provided for auth. Either header or query needs to be provided. + * @constructor + * @param {object} options Specifies the options to be provided for auth. Either header or query needs to be provided. */ function ApiKeyCredentials(options) { if (!options || (options && !options.inHeader && !options.inQuery)) { @@ -65935,8 +64342,8 @@ var ApiKeyCredentials = /** @class */ (function () { /** * Signs a request with the values provided in the inHeader and inQuery parameter. * - * @param webResource - The WebResourceLike to be signed. - * @returns The signed request object. + * @param {WebResourceLike} webResource The WebResourceLike to be signed. + * @returns {Promise} The signed request object. */ ApiKeyCredentials.prototype.signRequest = function (webResource) { if (!webResource) { @@ -65975,7 +64382,8 @@ var TopicCredentials = /** @class */ (function (_super) { /** * Creates a new EventGrid TopicCredentials object. * - * @param topicKey - The EventGrid topic key + * @constructor + * @param {string} topicKey The EventGrid topic key */ function TopicCredentials(topicKey) { var _this = this; @@ -66016,12 +64424,9 @@ exports.TopicCredentials = TopicCredentials; exports.URLBuilder = URLBuilder; exports.URLQuery = URLQuery; exports.WebResource = WebResource; -exports.XML_ATTRKEY = XML_ATTRKEY; -exports.XML_CHARKEY = XML_CHARKEY; exports.applyMixins = applyMixins; exports.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy; exports.createPipelineFromOptions = createPipelineFromOptions; -exports.createSpanFunction = createSpanFunction; exports.delay = delay; exports.deserializationPolicy = deserializationPolicy; exports.deserializeResponseBody = deserializeResponseBody; diff --git a/src/version.ts b/src/version.ts index c06580640d..f9c7d34edc 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1,5 +1,6 @@ import * as core from "@actions/core" import * as httpm from "@actions/http-client" +import * as fs from "fs" // TODO: make a class export type Version = { @@ -9,6 +10,7 @@ export type Version = { } | null const versionRe = /^v(\d+)\.(\d+)(?:\.(\d+))?$/ +const modVersionRe = /github.com\/golangci\/golangci-lint\sv(.+)/ const parseVersion = (s: string): Version => { if (s == "latest" || s == "") { @@ -56,7 +58,17 @@ const isLessVersion = (a: Version, b: Version): boolean => { } const getRequestedLintVersion = (): Version => { - const requestedLintVersion = core.getInput(`version`) + let requestedLintVersion = core.getInput(`version`) + + if (requestedLintVersion == "") { + const content = fs.readFileSync("go.mod", "utf-8") + const match = content.match(modVersionRe) + if (match) { + requestedLintVersion = match[1] + core.info(`Found golangci-lint version '${requestedLintVersion}' in go.mod`) + } + } + const parsedRequestedLintVersion = parseVersion(requestedLintVersion) if (parsedRequestedLintVersion == null) { return null