diff --git a/.licenses/npm/@actions/cache.dep.yml b/.licenses/npm/@actions/cache.dep.yml index 8ff5e01d..c2d23e2e 100644 Binary files a/.licenses/npm/@actions/cache.dep.yml and b/.licenses/npm/@actions/cache.dep.yml differ diff --git a/.licenses/npm/@azure/core-auth.dep.yml b/.licenses/npm/@azure/core-auth.dep.yml index 2b2a8135..830504b6 100644 Binary files a/.licenses/npm/@azure/core-auth.dep.yml and b/.licenses/npm/@azure/core-auth.dep.yml differ diff --git a/.licenses/npm/@azure/core-http.dep.yml b/.licenses/npm/@azure/core-http.dep.yml index f1b9d8cd..6a2bfc5b 100644 Binary files a/.licenses/npm/@azure/core-http.dep.yml and b/.licenses/npm/@azure/core-http.dep.yml differ diff --git a/.licenses/npm/@azure/core-lro.dep.yml b/.licenses/npm/@azure/core-lro.dep.yml index fc3276f4..d454075b 100644 Binary files a/.licenses/npm/@azure/core-lro.dep.yml and b/.licenses/npm/@azure/core-lro.dep.yml differ diff --git a/.licenses/npm/@azure/core-paging.dep.yml b/.licenses/npm/@azure/core-paging.dep.yml index 97cc7d33..72d23ac0 100644 Binary files a/.licenses/npm/@azure/core-paging.dep.yml and b/.licenses/npm/@azure/core-paging.dep.yml differ diff --git a/.licenses/npm/@azure/core-tracing.dep.yml b/.licenses/npm/@azure/core-tracing.dep.yml index 605bff8b..a4649e88 100644 Binary files a/.licenses/npm/@azure/core-tracing.dep.yml and b/.licenses/npm/@azure/core-tracing.dep.yml differ diff --git a/.licenses/npm/@azure/logger.dep.yml b/.licenses/npm/@azure/logger.dep.yml index e25bc860..978e29a3 100644 Binary files a/.licenses/npm/@azure/logger.dep.yml and b/.licenses/npm/@azure/logger.dep.yml differ diff --git a/.licenses/npm/@azure/ms-rest-js.dep.yml b/.licenses/npm/@azure/ms-rest-js.dep.yml index f344b93c..fb2116fc 100644 Binary files a/.licenses/npm/@azure/ms-rest-js.dep.yml and b/.licenses/npm/@azure/ms-rest-js.dep.yml differ diff --git a/.licenses/npm/@azure/storage-blob.dep.yml b/.licenses/npm/@azure/storage-blob.dep.yml index aa36621c..7b187d05 100644 Binary files a/.licenses/npm/@azure/storage-blob.dep.yml and b/.licenses/npm/@azure/storage-blob.dep.yml differ diff --git a/.licenses/npm/@opencensus/web-types.dep.yml b/.licenses/npm/@opencensus/web-types.dep.yml deleted file mode 100644 index 9c2ac253..00000000 Binary files a/.licenses/npm/@opencensus/web-types.dep.yml and /dev/null differ diff --git a/.licenses/npm/@opentelemetry/api.dep.yml b/.licenses/npm/@opentelemetry/api.dep.yml index fe739bcd..5674e022 100644 Binary files a/.licenses/npm/@opentelemetry/api.dep.yml and b/.licenses/npm/@opentelemetry/api.dep.yml differ diff --git a/.licenses/npm/@types/node-fetch.dep.yml b/.licenses/npm/@types/node-fetch.dep.yml index ce6048b7..094ab278 100644 Binary files a/.licenses/npm/@types/node-fetch.dep.yml and b/.licenses/npm/@types/node-fetch.dep.yml differ diff --git a/.licenses/npm/@types/tunnel.dep.yml b/.licenses/npm/@types/tunnel.dep.yml index 59643d46..b3636b02 100644 Binary files a/.licenses/npm/@types/tunnel.dep.yml and b/.licenses/npm/@types/tunnel.dep.yml differ diff --git a/.licenses/npm/form-data-4.0.0.dep.yml b/.licenses/npm/form-data-4.0.0.dep.yml new file mode 100644 index 00000000..ced7212c Binary files /dev/null and b/.licenses/npm/form-data-4.0.0.dep.yml differ diff --git a/.licenses/npm/tslib-2.3.0.dep.yml b/.licenses/npm/tslib-2.3.1.dep.yml similarity index 99% rename from .licenses/npm/tslib-2.3.0.dep.yml rename to .licenses/npm/tslib-2.3.1.dep.yml index e11d4760..09a533dc 100644 Binary files a/.licenses/npm/tslib-2.3.0.dep.yml and b/.licenses/npm/tslib-2.3.1.dep.yml differ diff --git a/dist/cache-save/index.js b/dist/cache-save/index.js index 4d22ce3c..2a86dfeb 100644 --- a/dist/cache-save/index.js +++ b/dist/cache-save/index.js @@ -1041,10 +1041,10 @@ function createTempDirectory() { }); } exports.createTempDirectory = createTempDirectory; -function getArchiveFileSizeIsBytes(filePath) { +function getArchiveFileSizeInBytes(filePath) { return fs.statSync(filePath).size; } -exports.getArchiveFileSizeIsBytes = getArchiveFileSizeIsBytes; +exports.getArchiveFileSizeInBytes = getArchiveFileSizeInBytes; function resolvePaths(patterns) { var e_1, _a; var _b; @@ -1224,7 +1224,8 @@ eval("require")("encoding"); /***/ }), /* 20 */, -/* 21 */ +/* 21 */, +/* 22 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; @@ -1246,16 +1247,24 @@ eval("require")("encoding"); */ Object.defineProperty(exports, "__esModule", { value: true }); exports.PropagationAPI = void 0; +var global_utils_1 = __webpack_require__(525); var NoopTextMapPropagator_1 = __webpack_require__(918); var TextMapPropagator_1 = __webpack_require__(881); -var global_utils_1 = __webpack_require__(525); +var context_helpers_1 = __webpack_require__(483); +var utils_1 = __webpack_require__(112); +var diag_1 = __webpack_require__(118); var API_NAME = 'propagation'; +var NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); /** * Singleton object which represents the entry point to the OpenTelemetry Propagation API */ var PropagationAPI = /** @class */ (function () { /** Empty private constructor prevents end users from constructing a new instance of the API */ function PropagationAPI() { + this.createBaggage = utils_1.createBaggage; + this.getBaggage = context_helpers_1.getBaggage; + this.setBaggage = context_helpers_1.setBaggage; + this.deleteBaggage = context_helpers_1.deleteBaggage; } /** Get the singleton instance of the Propagator API */ PropagationAPI.getInstance = function () { @@ -1265,11 +1274,12 @@ var PropagationAPI = /** @class */ (function () { return this._instance; }; /** - * Set the current propagator. Returns the initialized propagator + * Set the current propagator. + * + * @returns true if the propagator was successfully registered, else false */ PropagationAPI.prototype.setGlobalPropagator = function (propagator) { - global_utils_1.registerGlobal(API_NAME, propagator); - return propagator; + return global_utils_1.registerGlobal(API_NAME, propagator, diag_1.DiagAPI.instance()); }; /** * Inject context into a carrier to be propagated inter-process @@ -1301,560 +1311,16 @@ var PropagationAPI = /** @class */ (function () { }; /** Remove the global propagator */ PropagationAPI.prototype.disable = function () { - global_utils_1.unregisterGlobal(API_NAME); + global_utils_1.unregisterGlobal(API_NAME, diag_1.DiagAPI.instance()); }; PropagationAPI.prototype._getGlobalPropagator = function () { - return global_utils_1.getGlobal(API_NAME) || NoopTextMapPropagator_1.NOOP_TEXT_MAP_PROPAGATOR; + return global_utils_1.getGlobal(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; }; return PropagationAPI; }()); exports.PropagationAPI = PropagationAPI; //# sourceMappingURL=propagation.js.map -/***/ }), -/* 22 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const http = __webpack_require__(605); -const https = __webpack_require__(211); -const pm = __webpack_require__(618); -let tunnel; -var HttpCodes; -(function (HttpCodes) { - HttpCodes[HttpCodes["OK"] = 200] = "OK"; - HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; - HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; - HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; - HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; - HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; - HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; - HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; - HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; - HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; - HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); -var Headers; -(function (Headers) { - Headers["Accept"] = "accept"; - Headers["ContentType"] = "content-type"; -})(Headers = exports.Headers || (exports.Headers = {})); -var MediaTypes; -(function (MediaTypes) { - MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); -/** - * Returns the proxy URL, depending upon the supplied url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ -function getProxyUrl(serverUrl) { - let proxyUrl = pm.getProxyUrl(new URL(serverUrl)); - return proxyUrl ? proxyUrl.href : ''; -} -exports.getProxyUrl = getProxyUrl; -const HttpRedirectCodes = [ - HttpCodes.MovedPermanently, - HttpCodes.ResourceMoved, - HttpCodes.SeeOther, - HttpCodes.TemporaryRedirect, - HttpCodes.PermanentRedirect -]; -const HttpResponseRetryCodes = [ - HttpCodes.BadGateway, - HttpCodes.ServiceUnavailable, - HttpCodes.GatewayTimeout -]; -const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; -const ExponentialBackoffCeiling = 10; -const ExponentialBackoffTimeSlice = 5; -class HttpClientError extends Error { - constructor(message, statusCode) { - super(message); - this.name = 'HttpClientError'; - this.statusCode = statusCode; - Object.setPrototypeOf(this, HttpClientError.prototype); - } -} -exports.HttpClientError = HttpClientError; -class HttpClientResponse { - constructor(message) { - this.message = message; - } - readBody() { - return new Promise(async (resolve, reject) => { - let output = Buffer.alloc(0); - this.message.on('data', (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on('end', () => { - resolve(output.toString()); - }); - }); - } -} -exports.HttpClientResponse = HttpClientResponse; -function isHttps(requestUrl) { - let parsedUrl = new URL(requestUrl); - return parsedUrl.protocol === 'https:'; -} -exports.isHttps = isHttps; -class HttpClient { - constructor(userAgent, handlers, requestOptions) { - this._ignoreSslError = false; - this._allowRedirects = true; - this._allowRedirectDowngrade = false; - this._maxRedirects = 50; - this._allowRetries = false; - this._maxRetries = 1; - this._keepAlive = false; - this._disposed = false; - this.userAgent = userAgent; - this.handlers = handlers || []; - this.requestOptions = requestOptions; - if (requestOptions) { - if (requestOptions.ignoreSslError != null) { - this._ignoreSslError = requestOptions.ignoreSslError; - } - this._socketTimeout = requestOptions.socketTimeout; - if (requestOptions.allowRedirects != null) { - this._allowRedirects = requestOptions.allowRedirects; - } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; - } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); - } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; - } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; - } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; - } - } - } - options(requestUrl, additionalHeaders) { - return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); - } - get(requestUrl, additionalHeaders) { - return this.request('GET', requestUrl, null, additionalHeaders || {}); - } - del(requestUrl, additionalHeaders) { - return this.request('DELETE', requestUrl, null, additionalHeaders || {}); - } - post(requestUrl, data, additionalHeaders) { - return this.request('POST', requestUrl, data, additionalHeaders || {}); - } - patch(requestUrl, data, additionalHeaders) { - return this.request('PATCH', requestUrl, data, additionalHeaders || {}); - } - put(requestUrl, data, additionalHeaders) { - return this.request('PUT', requestUrl, data, additionalHeaders || {}); - } - head(requestUrl, additionalHeaders) { - return this.request('HEAD', requestUrl, null, additionalHeaders || {}); - } - sendStream(verb, requestUrl, stream, additionalHeaders) { - return this.request(verb, requestUrl, stream, additionalHeaders); - } - /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise - */ - async getJson(requestUrl, additionalHeaders = {}) { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - let res = await this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async postJson(requestUrl, obj, additionalHeaders = {}) { - let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - let res = await this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async putJson(requestUrl, obj, additionalHeaders = {}) { - let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - let res = await this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async patchJson(requestUrl, obj, additionalHeaders = {}) { - let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - let res = await this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - /** - * Makes a raw http request. - * All other methods such as get, post, patch, and request ultimately call this. - * Prefer get, del, post and patch - */ - async request(verb, requestUrl, data, headers) { - if (this._disposed) { - throw new Error('Client has already been disposed.'); - } - let parsedUrl = new URL(requestUrl); - let info = this._prepareRequest(verb, parsedUrl, headers); - // Only perform retries on reads since writes may not be idempotent. - let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 - ? this._maxRetries + 1 - : 1; - let numTries = 0; - let response; - while (numTries < maxTries) { - response = await this.requestRaw(info, data); - // Check if it's an authentication challenge - if (response && - response.message && - response.message.statusCode === HttpCodes.Unauthorized) { - let authenticationHandler; - for (let i = 0; i < this.handlers.length; i++) { - if (this.handlers[i].canHandleAuthentication(response)) { - authenticationHandler = this.handlers[i]; - break; - } - } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info, data); - } - else { - // We have received an unauthorized response but have no handlers to handle it. - // Let the response return to the caller. - return response; - } - } - let redirectsRemaining = this._maxRedirects; - while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && - this._allowRedirects && - redirectsRemaining > 0) { - const redirectUrl = response.message.headers['location']; - if (!redirectUrl) { - // if there's no location to redirect to, we won't - break; - } - let parsedRedirectUrl = new URL(redirectUrl); - if (parsedUrl.protocol == 'https:' && - parsedUrl.protocol != parsedRedirectUrl.protocol && - !this._allowRedirectDowngrade) { - throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); - } - // we need to finish reading the response before reassigning response - // which will leak the open socket. - await response.readBody(); - // strip authorization header if redirected to a different hostname - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (let header in headers) { - // header names are case insensitive - if (header.toLowerCase() === 'authorization') { - delete headers[header]; - } - } - } - // let's make the request with the new redirectUrl - info = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = await this.requestRaw(info, data); - redirectsRemaining--; - } - if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) { - // If not a retry code, return immediately instead of retrying - return response; - } - numTries += 1; - if (numTries < maxTries) { - await response.readBody(); - await this._performExponentialBackoff(numTries); - } - } - return response; - } - /** - * Needs to be called if keepAlive is set to true in request options. - */ - dispose() { - if (this._agent) { - this._agent.destroy(); - } - this._disposed = true; - } - /** - * Raw request. - * @param info - * @param data - */ - requestRaw(info, data) { - return new Promise((resolve, reject) => { - let callbackForResult = function (err, res) { - if (err) { - reject(err); - } - resolve(res); - }; - this.requestRawWithCallback(info, data, callbackForResult); - }); - } - /** - * Raw request with callback. - * @param info - * @param data - * @param onResult - */ - requestRawWithCallback(info, data, onResult) { - let socket; - if (typeof data === 'string') { - info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); - } - let callbackCalled = false; - let handleResult = (err, res) => { - if (!callbackCalled) { - callbackCalled = true; - onResult(err, res); - } - }; - let req = info.httpModule.request(info.options, (msg) => { - let res = new HttpClientResponse(msg); - handleResult(null, res); - }); - req.on('socket', sock => { - socket = sock; - }); - // If we ever get disconnected, we want the socket to timeout eventually - req.setTimeout(this._socketTimeout || 3 * 60000, () => { - if (socket) { - socket.end(); - } - handleResult(new Error('Request timeout: ' + info.options.path), null); - }); - req.on('error', function (err) { - // err has statusCode property - // res should have headers - handleResult(err, null); - }); - if (data && typeof data === 'string') { - req.write(data, 'utf8'); - } - if (data && typeof data !== 'string') { - data.on('close', function () { - req.end(); - }); - data.pipe(req); - } - else { - req.end(); - } - } - /** - * Gets an http agent. This function is useful when you need an http agent that handles - * routing through a proxy server - depending upon the url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ - getAgent(serverUrl) { - let parsedUrl = new URL(serverUrl); - return this._getAgent(parsedUrl); - } - _prepareRequest(method, requestUrl, headers) { - const info = {}; - info.parsedUrl = requestUrl; - const usingSsl = info.parsedUrl.protocol === 'https:'; - info.httpModule = usingSsl ? https : http; - const defaultPort = usingSsl ? 443 : 80; - info.options = {}; - info.options.host = info.parsedUrl.hostname; - info.options.port = info.parsedUrl.port - ? parseInt(info.parsedUrl.port) - : defaultPort; - info.options.path = - (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); - info.options.method = method; - info.options.headers = this._mergeHeaders(headers); - if (this.userAgent != null) { - info.options.headers['user-agent'] = this.userAgent; - } - info.options.agent = this._getAgent(info.parsedUrl); - // gives handlers an opportunity to participate - if (this.handlers) { - this.handlers.forEach(handler => { - handler.prepareRequest(info.options); - }); - } - return info; - } - _mergeHeaders(headers) { - const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); - if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); - } - return lowercaseKeys(headers || {}); - } - _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; - } - return additionalHeaders[header] || clientHeader || _default; - } - _getAgent(parsedUrl) { - let agent; - let proxyUrl = pm.getProxyUrl(parsedUrl); - let useProxy = proxyUrl && proxyUrl.hostname; - if (this._keepAlive && useProxy) { - agent = this._proxyAgent; - } - if (this._keepAlive && !useProxy) { - agent = this._agent; - } - // if agent is already assigned use that agent. - if (!!agent) { - return agent; - } - const usingSsl = parsedUrl.protocol === 'https:'; - let maxSockets = 100; - if (!!this.requestOptions) { - maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; - } - if (useProxy) { - // If using proxy, need tunnel - if (!tunnel) { - tunnel = __webpack_require__(413); - } - const agentOptions = { - maxSockets: maxSockets, - keepAlive: this._keepAlive, - proxy: { - ...((proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - }), - host: proxyUrl.hostname, - port: proxyUrl.port - } - }; - let tunnelAgent; - const overHttps = proxyUrl.protocol === 'https:'; - if (usingSsl) { - tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; - } - else { - tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; - } - agent = tunnelAgent(agentOptions); - this._proxyAgent = agent; - } - // if reusing agent across request and tunneling agent isn't assigned create a new agent - if (this._keepAlive && !agent) { - const options = { keepAlive: this._keepAlive, maxSockets: maxSockets }; - agent = usingSsl ? new https.Agent(options) : new http.Agent(options); - this._agent = agent; - } - // if not using private agent and tunnel agent isn't setup then use global agent - if (!agent) { - agent = usingSsl ? https.globalAgent : http.globalAgent; - } - if (usingSsl && this._ignoreSslError) { - // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process - // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options - // we have to cast it to any and change it directly - agent.options = Object.assign(agent.options || {}, { - rejectUnauthorized: false - }); - } - return agent; - } - _performExponentialBackoff(retryNumber) { - retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); - const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise(resolve => setTimeout(() => resolve(), ms)); - } - static dateTimeDeserializer(key, value) { - if (typeof value === 'string') { - let a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } - } - return value; - } - async _processResponse(res, options) { - return new Promise(async (resolve, reject) => { - const statusCode = res.message.statusCode; - const response = { - statusCode: statusCode, - result: null, - headers: {} - }; - // not found leads to null obj returned - if (statusCode == HttpCodes.NotFound) { - resolve(response); - } - let obj; - let contents; - // get the result from the body - try { - contents = await res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, HttpClient.dateTimeDeserializer); - } - else { - obj = JSON.parse(contents); - } - response.result = obj; - } - response.headers = res.message.headers; - } - catch (err) { - // Invalid resource (contents not json); leaving result obj null - } - // note that 3xx redirects are handled by the http layer. - if (statusCode > 299) { - let msg; - // if exception/error in body, attempt to get better error - if (obj && obj.message) { - msg = obj.message; - } - else if (contents && contents.length > 0) { - // it may be the case that the exception is in the body message as string - msg = contents; - } - else { - msg = 'Failed request: (' + statusCode + ')'; - } - let err = new HttpClientError(msg, statusCode); - err.result = response.result; - reject(err); - } - else { - resolve(response); - } - }); - } -} -exports.HttpClient = HttpClient; - - /***/ }), /* 23 */, /* 24 */ @@ -1905,7 +1371,74 @@ module.exports = ["ac","com.ac","edu.ac","gov.ac","net.ac","mil.ac","org.ac","ad /* 51 */, /* 52 */, /* 53 */, -/* 54 */, +/* 54 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * "A request-path path-matches a given cookie-path if at least one of the + * following conditions holds:" + */ +function pathMatch(reqPath, cookiePath) { + // "o The cookie-path and the request-path are identical." + if (cookiePath === reqPath) { + return true; + } + + const idx = reqPath.indexOf(cookiePath); + if (idx === 0) { + // "o The cookie-path is a prefix of the request-path, and the last + // character of the cookie-path is %x2F ("/")." + if (cookiePath.substr(-1) === "/") { + return true; + } + + // " o The cookie-path is a prefix of the request-path, and the first + // character of the request-path that is not included in the cookie- path + // is a %x2F ("/") character." + if (reqPath.substr(cookiePath.length, 1) === "/") { + return true; + } + } + + return false; +} + +exports.pathMatch = pathMatch; + + +/***/ }), /* 55 */, /* 56 */, /* 57 */, @@ -1962,17 +1495,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); //# sourceMappingURL=trace_state.js.map /***/ }), -/* 71 */ -/***/ (function() { - -"use strict"; - -if (typeof Symbol === undefined || !Symbol.asyncIterator) { - Symbol.asyncIterator = Symbol.for("Symbol.asyncIterator"); -} -//# sourceMappingURL=index.js.map - -/***/ }), +/* 71 */, /* 72 */, /* 73 */, /* 74 */, @@ -3528,7 +3051,64 @@ exports.AbortSignal = AbortSignal; /* 109 */, /* 110 */, /* 111 */, -/* 112 */, +/* 112 */ +/***/ (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.baggageEntryMetadataFromString = exports.createBaggage = void 0; +var diag_1 = __webpack_require__(118); +var baggage_impl_1 = __webpack_require__(666); +var symbol_1 = __webpack_require__(561); +var diag = diag_1.DiagAPI.instance(); +/** + * Create a new Baggage with optional entries + * + * @param entries An array of baggage entries the new baggage should contain + */ +function createBaggage(entries) { + if (entries === void 0) { entries = {}; } + return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries))); +} +exports.createBaggage = createBaggage; +/** + * Create a serializable BaggageEntryMetadata object from a string. + * + * @param str string metadata. Format is currently not defined by the spec and has no special meaning. + * + */ +function baggageEntryMetadataFromString(str) { + if (typeof str !== 'string') { + diag.error("Cannot create baggage metadata from unknown type: " + typeof str); + str = ''; + } + return { + __TYPE__: symbol_1.baggageEntryMetadataSymbol, + toString: function () { + return str; + }, + }; +} +exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; +//# sourceMappingURL=utils.js.map + +/***/ }), /* 113 */, /* 114 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { @@ -3553,8 +3133,8 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); const core = __importStar(__webpack_require__(470)); -const http_client_1 = __webpack_require__(22); -const auth_1 = __webpack_require__(733); +const http_client_1 = __webpack_require__(539); +const auth_1 = __webpack_require__(226); const crypto = __importStar(__webpack_require__(417)); const fs = __importStar(__webpack_require__(747)); const url_1 = __webpack_require__(835); @@ -3689,7 +3269,7 @@ function uploadChunk(httpClient, resourceUrl, openStream, start, end) { function uploadFile(httpClient, cacheId, archivePath, options) { return __awaiter(this, void 0, void 0, function* () { // Upload Chunks - const fileSize = fs.statSync(archivePath).size; + const fileSize = utils.getArchiveFileSizeInBytes(archivePath); const resourceUrl = getCacheApiUrl(`caches/${cacheId.toString()}`); const fd = fs.openSync(archivePath, 'r'); const uploadOptions = options_1.getUploadOptions(options); @@ -3739,7 +3319,7 @@ function saveCache(cacheId, archivePath, options) { yield uploadFile(httpClient, cacheId, archivePath, options); // Commit Cache core.debug('Commiting cache'); - const cacheSize = utils.getArchiveFileSizeIsBytes(archivePath); + const cacheSize = utils.getArchiveFileSizeInBytes(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)) { @@ -3777,6 +3357,7 @@ exports.saveCache = saveCache; */ Object.defineProperty(exports, "__esModule", { value: true }); exports.DiagAPI = void 0; +var ComponentLogger_1 = __webpack_require__(362); var logLevelLogger_1 = __webpack_require__(673); var types_1 = __webpack_require__(545); var global_utils_1 = __webpack_require__(525); @@ -3807,7 +3388,7 @@ var DiagAPI = /** @class */ (function () { var self = this; // DiagAPI specific functions self.setLogger = function (logger, logLevel) { - var _a; + var _a, _b; if (logLevel === void 0) { logLevel = types_1.DiagLogLevel.INFO; } if (logger === self) { // There isn't much we can do here. @@ -3815,12 +3396,23 @@ var DiagAPI = /** @class */ (function () { // Try to log to self. If a logger was previously registered it will receive the log. var err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message); - return; + return false; } - global_utils_1.registerGlobal('diag', logLevelLogger_1.createLogLevelDiagLogger(logLevel, logger), true); + var oldLogger = global_utils_1.getGlobal('diag'); + var newLogger = logLevelLogger_1.createLogLevelDiagLogger(logLevel, logger); + // There already is an logger registered. We'll let it know before overwriting it. + if (oldLogger) { + var stack = (_b = new Error().stack) !== null && _b !== void 0 ? _b : ''; + oldLogger.warn("Current logger will be overwritten from " + stack); + newLogger.warn("Current logger will overwrite one already registered from " + stack); + } + return global_utils_1.registerGlobal('diag', newLogger, self, true); }; self.disable = function () { - global_utils_1.unregisterGlobal(API_NAME); + global_utils_1.unregisterGlobal(API_NAME, self); + }; + self.createComponentLogger = function (options) { + return new ComponentLogger_1.DiagComponentLogger(options); }; self.verbose = _logProxy('verbose'); self.debug = _logProxy('debug'); @@ -3860,7 +3452,7 @@ module.exports = require("child_process"); /* 130 */, /* 131 */, /* 132 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ (function(__unusedmodule, exports) { "use strict"; @@ -3880,109 +3472,15 @@ module.exports = require("child_process"); * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); -exports.ROOT_CONTEXT = exports.createContextKey = exports.setBaggage = exports.getBaggage = exports.isInstrumentationSuppressed = exports.unsuppressInstrumentation = exports.suppressInstrumentation = exports.getSpanContext = exports.setSpanContext = exports.setSpan = exports.getSpan = void 0; -var NoopSpan_1 = __webpack_require__(767); -/** - * span key - */ -var SPAN_KEY = createContextKey('OpenTelemetry Context Key SPAN'); -/** - * Shared key for indicating if instrumentation should be suppressed beyond - * this current scope. - */ -var SUPPRESS_INSTRUMENTATION_KEY = createContextKey('OpenTelemetry Context Key SUPPRESS_INSTRUMENTATION'); -/** - * Baggage key - */ -var BAGGAGE_KEY = createContextKey('OpenTelemetry Baggage Key'); -/** - * Return the span if one exists - * - * @param context context to get span from - */ -function getSpan(context) { - return context.getValue(SPAN_KEY) || undefined; -} -exports.getSpan = getSpan; -/** - * Set the span on a context - * - * @param context context to use as parent - * @param span span to set active - */ -function setSpan(context, span) { - return context.setValue(SPAN_KEY, span); -} -exports.setSpan = setSpan; -/** - * Wrap span context in a NoopSpan and set as span in a new - * context - * - * @param context context to set active span on - * @param spanContext span context to be wrapped - */ -function setSpanContext(context, spanContext) { - return setSpan(context, new NoopSpan_1.NoopSpan(spanContext)); -} -exports.setSpanContext = setSpanContext; -/** - * Get the span context of the span if it exists. - * - * @param context context to get values from - */ -function getSpanContext(context) { - var _a; - return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.context(); -} -exports.getSpanContext = getSpanContext; -/** - * Sets value on context to indicate that instrumentation should - * be suppressed beyond this current scope. - * - * @param context context to set the suppress instrumentation value on. - */ -function suppressInstrumentation(context) { - return context.setValue(SUPPRESS_INSTRUMENTATION_KEY, true); -} -exports.suppressInstrumentation = suppressInstrumentation; -/** - * Sets value on context to indicate that instrumentation should - * no-longer be suppressed beyond this current scope. - * - * @param context context to set the suppress instrumentation value on. - */ -function unsuppressInstrumentation(context) { - return context.setValue(SUPPRESS_INSTRUMENTATION_KEY, false); -} -exports.unsuppressInstrumentation = unsuppressInstrumentation; -/** - * Return current suppress instrumentation value for the given context, - * if it exists. - * - * @param context context check for the suppress instrumentation value. - */ -function isInstrumentationSuppressed(context) { - return Boolean(context.getValue(SUPPRESS_INSTRUMENTATION_KEY)); -} -exports.isInstrumentationSuppressed = isInstrumentationSuppressed; -/** - * @param {Context} Context that manage all context values - * @returns {Baggage} Extracted baggage from the context - */ -function getBaggage(context) { - return context.getValue(BAGGAGE_KEY) || undefined; -} -exports.getBaggage = getBaggage; -/** - * @param {Context} Context that manage all context values - * @param {Baggage} baggage that will be set in the actual context - */ -function setBaggage(context, baggage) { - return context.setValue(BAGGAGE_KEY, baggage); -} -exports.setBaggage = setBaggage; +exports.ROOT_CONTEXT = exports.createContextKey = void 0; /** Get a key to uniquely identify a context value */ function createContextKey(description) { + // The specification states that for the same input, multiple calls should + // return different keys. Due to the nature of the JS dependency management + // system, this creates problems where multiple versions of some package + // could hold different keys for the same property. + // + // Therefore, we use Symbol.for which returns the same key for the same input. return Symbol.for(description); } exports.createContextKey = createContextKey; @@ -4383,318 +3881,7 @@ exports.getCacheDirectoryPath = (packageManagerInfo, packageManager) => __awaite /***/ }), -/* 144 */ -/***/ (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, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || from); - }; - - __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, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), 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); -}); - - -/***/ }), +/* 144 */, /* 145 */ /***/ (function(__unusedmodule, exports) { @@ -4780,10 +3967,12 @@ exports.fromPromise = function (fn) { * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); -exports.NOOP_TRACER = exports.NoopTracer = void 0; -var context_1 = __webpack_require__(132); -var NoopSpan_1 = __webpack_require__(767); +exports.NoopTracer = void 0; +var context_1 = __webpack_require__(492); +var context_utils_1 = __webpack_require__(720); +var NonRecordingSpan_1 = __webpack_require__(437); var spancontext_utils_1 = __webpack_require__(629); +var context = context_1.ContextAPI.getInstance(); /** * No-op implementations of {@link Tracer}. */ @@ -4794,17 +3983,41 @@ var NoopTracer = /** @class */ (function () { NoopTracer.prototype.startSpan = function (name, options, context) { var root = Boolean(options === null || options === void 0 ? void 0 : options.root); if (root) { - return new NoopSpan_1.NoopSpan(); + return new NonRecordingSpan_1.NonRecordingSpan(); } - var parentFromContext = context && context_1.getSpanContext(context); + var parentFromContext = context && context_utils_1.getSpanContext(context); if (isSpanContext(parentFromContext) && spancontext_utils_1.isSpanContextValid(parentFromContext)) { - return new NoopSpan_1.NoopSpan(parentFromContext); + return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext); } else { - return new NoopSpan_1.NoopSpan(); + return new NonRecordingSpan_1.NonRecordingSpan(); } }; + NoopTracer.prototype.startActiveSpan = function (name, arg2, arg3, arg4) { + var opts; + var ctx; + var fn; + if (arguments.length < 2) { + return; + } + else if (arguments.length === 2) { + fn = arg2; + } + else if (arguments.length === 3) { + opts = arg2; + fn = arg3; + } + else { + opts = arg2; + ctx = arg3; + fn = arg4; + } + var parentContext = ctx !== null && ctx !== void 0 ? ctx : context.active(); + var span = this.startSpan(name, opts, parentContext); + var contextWithSpanSet = context_utils_1.setSpan(parentContext, span); + return context.with(contextWithSpanSet, fn, undefined, span); + }; return NoopTracer; }()); exports.NoopTracer = NoopTracer; @@ -4814,7 +4027,6 @@ function isSpanContext(spanContext) { typeof spanContext['traceId'] === 'string' && typeof spanContext['traceFlags'] === 'number'); } -exports.NOOP_TRACER = new NoopTracer(); //# sourceMappingURL=NoopTracer.js.map /***/ }), @@ -5049,7 +4261,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); -exports.NOOP_TRACER_PROVIDER = exports.NoopTracerProvider = void 0; +exports.NoopTracerProvider = void 0; var NoopTracer_1 = __webpack_require__(151); /** * An implementation of the {@link TracerProvider} which returns an impotent @@ -5061,18 +4273,40 @@ var NoopTracerProvider = /** @class */ (function () { function NoopTracerProvider() { } NoopTracerProvider.prototype.getTracer = function (_name, _version) { - return NoopTracer_1.NOOP_TRACER; + return new NoopTracer_1.NoopTracer(); }; return NoopTracerProvider; }()); exports.NoopTracerProvider = NoopTracerProvider; -exports.NOOP_TRACER_PROVIDER = new NoopTracerProvider(); //# sourceMappingURL=NoopTracerProvider.js.map /***/ }), /* 163 */, /* 164 */, -/* 165 */, +/* 165 */ +/***/ (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 + +/***/ }), /* 166 */, /* 167 */, /* 168 */, @@ -5091,7 +4325,7 @@ Object.defineProperty(exports, "__esModule", { }); exports.default = void 0; -var _rng = _interopRequireDefault(__webpack_require__(944)); +var _rng = _interopRequireDefault(__webpack_require__(733)); var _stringify = _interopRequireDefault(__webpack_require__(855)); @@ -5563,29 +4797,25 @@ Object.defineProperty(exports, '__esModule', { value: true }); * A static-key-based credential that supports updating * the underlying key value. */ -var AzureKeyCredential = /** @class */ (function () { +class AzureKeyCredential { /** * Create an instance of an AzureKeyCredential for use * with a service client. * * @param key - The initial value of the key to use in authentication */ - function AzureKeyCredential(key) { + constructor(key) { if (!key) { throw new Error("key must be a non-empty string"); } this._key = key; } - Object.defineProperty(AzureKeyCredential.prototype, "key", { - /** - * The value of the key to be used in authentication - */ - get: function () { - return this._key; - }, - enumerable: false, - configurable: true - }); + /** + * The value of the key to be used in authentication + */ + get key() { + return this._key; + } /** * Change the value of the key. * @@ -5594,11 +4824,10 @@ var AzureKeyCredential = /** @class */ (function () { * * @param newKey - The new key value to be used */ - AzureKeyCredential.prototype.update = function (newKey) { + update(newKey) { this._key = newKey; - }; - return AzureKeyCredential; -}()); + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -5621,8 +4850,7 @@ function isObjectWithProperties(thing, properties) { if (!isDefined(thing) || typeof thing !== "object") { return false; } - for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { - var property = properties_1[_i]; + for (const property of properties) { if (!objectHasProperty(thing, property)) { return false; } @@ -5645,7 +4873,7 @@ function objectHasProperty(thing, property) { * A static name/key-based credential that supports updating * the underlying name and key values. */ -var AzureNamedKeyCredential = /** @class */ (function () { +class AzureNamedKeyCredential { /** * Create an instance of an AzureNamedKeyCredential for use * with a service client. @@ -5653,33 +4881,25 @@ var AzureNamedKeyCredential = /** @class */ (function () { * @param name - The initial value of the name to use in authentication. * @param key - The initial value of the key to use in authentication. */ - function AzureNamedKeyCredential(name, key) { + constructor(name, key) { if (!name || !key) { throw new TypeError("name and key must be non-empty strings"); } this._name = name; this._key = key; } - Object.defineProperty(AzureNamedKeyCredential.prototype, "key", { - /** - * The value of the key to be used in authentication. - */ - get: function () { - return this._key; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AzureNamedKeyCredential.prototype, "name", { - /** - * The value of the name to be used in authentication. - */ - get: function () { - return this._name; - }, - enumerable: false, - configurable: true - }); + /** + * The value of the key to be used in authentication. + */ + get key() { + return this._key; + } + /** + * The value of the name to be used in authentication. + */ + get name() { + return this._name; + } /** * Change the value of the key. * @@ -5689,15 +4909,14 @@ var AzureNamedKeyCredential = /** @class */ (function () { * @param newName - The new name value to be used. * @param newKey - The new key value to be used. */ - AzureNamedKeyCredential.prototype.update = function (newName, newKey) { + update(newName, newKey) { if (!newName || !newKey) { throw new TypeError("newName and newKey must be non-empty strings"); } this._name = newName; this._key = newKey; - }; - return AzureNamedKeyCredential; -}()); + } +} /** * Tests an object to determine whether it implements NamedKeyCredential. * @@ -5714,29 +4933,25 @@ function isNamedKeyCredential(credential) { * A static-signature-based credential that supports updating * the underlying signature value. */ -var AzureSASCredential = /** @class */ (function () { +class AzureSASCredential { /** * Create an instance of an AzureSASCredential for use * with a service client. * * @param signature - The initial value of the shared access signature to use in authentication */ - function AzureSASCredential(signature) { + constructor(signature) { if (!signature) { throw new Error("shared access signature must be a non-empty string"); } this._signature = signature; } - Object.defineProperty(AzureSASCredential.prototype, "signature", { - /** - * The value of the shared access signature to be used in authentication - */ - get: function () { - return this._signature; - }, - enumerable: false, - configurable: true - }); + /** + * The value of the shared access signature to be used in authentication + */ + get signature() { + return this._signature; + } /** * Change the value of the signature. * @@ -5745,14 +4960,13 @@ var AzureSASCredential = /** @class */ (function () { * * @param newSignature - The new shared access signature value to be used */ - AzureSASCredential.prototype.update = function (newSignature) { + update(newSignature) { if (!newSignature) { throw new Error("shared access signature must be a non-empty string"); } this._signature = newSignature; - }; - return AzureSASCredential; -}()); + } +} /** * Tests an object to determine whether it implements SASCredential. * @@ -5775,7 +4989,7 @@ function isTokenCredential(credential) { // a ServiceClientCredentials implementor (like TokenClientCredentials // in ms-rest-nodeauth) doesn't get mistaken for a TokenCredential if // it doesn't actually implement TokenCredential also. - var castCredential = credential; + const castCredential = credential; return (castCredential && typeof castCredential.getToken === "function" && (castCredential.signRequest === undefined || castCredential.getToken.length > 0)); @@ -6088,7 +5302,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); const core = __importStar(__webpack_require__(470)); -const http_client_1 = __webpack_require__(22); +const http_client_1 = __webpack_require__(539); const storage_blob_1 = __webpack_require__(373); const buffer = __importStar(__webpack_require__(293)); const fs = __importStar(__webpack_require__(747)); @@ -6231,7 +5445,7 @@ function downloadCacheHttpClient(archiveLocation, archivePath) { const contentLengthHeader = downloadResponse.message.headers['content-length']; if (contentLengthHeader) { const expectedLength = parseInt(contentLengthHeader); - const actualLength = utils.getArchiveFileSizeIsBytes(archivePath); + const actualLength = utils.getArchiveFileSizeInBytes(archivePath); if (actualLength !== expectedLength) { throw new Error(`Incomplete download. Expected file size: ${expectedLength}, actual file size: ${actualLength}`); } @@ -6353,7 +5567,7 @@ exports.downloadCacheStorageSDK = downloadCacheStorageSDK; this.children = []; this.baseURI = null; if (!XMLElement) { - XMLElement = __webpack_require__(701); + XMLElement = __webpack_require__(845); XMLCData = __webpack_require__(657); XMLComment = __webpack_require__(919); XMLDeclaration = __webpack_require__(738); @@ -7101,318 +6315,7 @@ exports.downloadCacheStorageSDK = downloadCacheStorageSDK; /* 259 */, /* 260 */, /* 261 */, -/* 262 */ -/***/ (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, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || from); - }; - - __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, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), 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); -}); - - -/***/ }), +/* 262 */, /* 263 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { @@ -7422,205 +6325,6 @@ var __createBinding; Object.defineProperty(exports, '__esModule', { value: true }); var api = __webpack_require__(440); -var tslib = __webpack_require__(144); - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * A no-op implementation of Span that can safely be used without side-effects. - */ -var NoOpSpan = /** @class */ (function () { - function NoOpSpan() { - } - /** - * Returns the SpanContext associated with this Span. - */ - NoOpSpan.prototype.context = function () { - return { - spanId: "", - traceId: "", - traceFlags: 0 /* NONE */ - }; - }; - /** - * Marks the end of Span execution. - * @param _endTime - The time to use as the Span's end time. Defaults to - * the current time. - */ - NoOpSpan.prototype.end = function (_endTime) { - /* Noop */ - }; - /** - * Sets an attribute on the Span - * @param _key - The attribute key - * @param _value - The attribute value - */ - NoOpSpan.prototype.setAttribute = function (_key, _value) { - return this; - }; - /** - * Sets attributes on the Span - * @param _attributes - The attributes to add - */ - NoOpSpan.prototype.setAttributes = function (_attributes) { - return this; - }; - /** - * Adds an event to the Span - * @param _name - The name of the event - * @param _attributes - The associated attributes to add for this event - */ - NoOpSpan.prototype.addEvent = function (_name, _attributes) { - return this; - }; - /** - * Sets a status on the span. Overrides the default of SpanStatusCode.OK. - * @param _status - The status to set. - */ - NoOpSpan.prototype.setStatus = function (_status) { - return this; - }; - /** - * Updates the name of the Span - * @param _name - the new Span name - */ - NoOpSpan.prototype.updateName = function (_name) { - return this; - }; - /** - * Returns whether this span will be recorded - */ - NoOpSpan.prototype.isRecording = function () { - return false; - }; - /** - * Sets exception as a span event - * @param exception - the exception the only accepted values are string or Error - * @param time - the time to set as Span's event time. If not provided, - * use the current time. - */ - NoOpSpan.prototype.recordException = function (_exception, _time) { - /* do nothing */ - }; - return NoOpSpan; -}()); - -// Copyright (c) Microsoft Corporation. -/** - * A no-op implementation of Tracer that can be used when tracing - * is disabled. - */ -var NoOpTracer = /** @class */ (function () { - function NoOpTracer() { - } - /** - * Starts a new Span. - * @param _name - The name of the span. - * @param _options - The SpanOptions used during Span creation. - */ - NoOpTracer.prototype.startSpan = function (_name, _options) { - return new NoOpSpan(); - }; - /** - * Returns the current Span from the current context, if available. - */ - NoOpTracer.prototype.getCurrentSpan = function () { - return new NoOpSpan(); - }; - /** - * Executes the given function within the context provided by a Span. - * @param _span - The span that provides the context. - * @param fn - The function to be executed. - */ - NoOpTracer.prototype.withSpan = function (_span, fn) { - return fn(); - }; - /** - * Bind a Span as the target's scope - * @param target - An object to bind the scope. - * @param _span - A specific Span to use. Otherwise, use the current one. - */ - NoOpTracer.prototype.bind = function (target, _span) { - return target; - }; - return NoOpTracer; -}()); - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -function getGlobalObject() { - return global; -} - -// Copyright (c) Microsoft Corporation. -// V1 = OpenTelemetry 0.1 -// V2 = OpenTelemetry 0.2 -// V3 = OpenTelemetry 0.6.1 -// V4 = OpenTelemetry 1.0.0-rc.0 -var GLOBAL_TRACER_VERSION = 4; -// preview5 shipped with @azure/core-tracing.tracerCache -// and didn't have smart detection for collisions -var GLOBAL_TRACER_SYMBOL = Symbol.for("@azure/core-tracing.tracerCache3"); -var cache; -function loadTracerCache() { - var globalObj = getGlobalObject(); - var existingCache = globalObj[GLOBAL_TRACER_SYMBOL]; - var setGlobalCache = true; - if (existingCache) { - if (existingCache.version === GLOBAL_TRACER_VERSION) { - cache = existingCache; - } - else { - setGlobalCache = false; - if (existingCache.tracer) { - throw new Error("Two incompatible versions of @azure/core-tracing have been loaded.\n This library is " + GLOBAL_TRACER_VERSION + ", existing is " + existingCache.version + "."); - } - } - } - if (!cache) { - cache = { - tracer: undefined, - version: GLOBAL_TRACER_VERSION - }; - } - if (setGlobalCache) { - globalObj[GLOBAL_TRACER_SYMBOL] = cache; - } -} -function getCache() { - if (!cache) { - loadTracerCache(); - } - return cache; -} - -// Copyright (c) Microsoft Corporation. -var defaultTracer; -function getDefaultTracer() { - if (!defaultTracer) { - defaultTracer = new NoOpTracer(); - } - return defaultTracer; -} -/** - * Sets the global tracer, enabling tracing for the Azure SDK. - * @param tracer - An OpenTelemetry Tracer instance. - */ -function setTracer(tracer) { - var cache = getCache(); - cache.tracer = tracer; -} -/** - * Retrieves the active tracer, or returns a - * no-op implementation if one is not set. - */ -function getTracer() { - var cache = getCache(); - if (!cache.tracer) { - return getDefaultTracer(); - } - return cache.tracer; -} // Copyright (c) Microsoft Corporation. (function (SpanKind) { @@ -7655,7 +6359,7 @@ function getTracer() { * @param context - context to get span from */ function getSpan(context) { - return api.getSpan(context); + return api.trace.getSpan(context); } /** * Set the span on a context @@ -7664,7 +6368,7 @@ function getSpan(context) { * @param span - span to set active */ function setSpan(context, span) { - return api.setSpan(context, span); + return api.trace.setSpan(context, span); } /** * Wrap span context in a NoopSpan and set as span in a new @@ -7674,7 +6378,7 @@ function setSpan(context, span) { * @param spanContext - span context to be wrapped */ function setSpanContext(context, spanContext) { - return api.setSpanContext(context, spanContext); + return api.trace.setSpanContext(context, spanContext); } /** * Get the span context of the span if it exists. @@ -7682,10 +6386,24 @@ function setSpanContext(context, spanContext) { * @param context - context to get values from */ function getSpanContext(context) { - return api.getSpanContext(context); + return api.trace.getSpanContext(context); +} +/** + * Returns true of the given {@link SpanContext} is valid. + * A valid {@link SpanContext} is one which has a valid trace ID and span ID as per the spec. + * + * @param context - the {@link SpanContext} to validate. + * + * @returns true if the {@link SpanContext} is valid, false otherwise. + */ +function isSpanContextValid(context) { + return api.trace.isSpanContextValid(context); +} +function getTracer(name, version) { + return api.trace.getTracer(name || "azure/core-tracing", version); } /** Entrypoint for context API */ -var context = api.context; +const context = api.context; (function (SpanStatusCode) { /** * The default status. @@ -7703,422 +6421,18 @@ var context = api.context; })(exports.SpanStatusCode || (exports.SpanStatusCode = {})); // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * @internal - */ -var OpenCensusTraceStateWrapper = /** @class */ (function () { - function OpenCensusTraceStateWrapper(state) { - this._state = state; +function isTracingDisabled() { + var _a; + if (typeof process === "undefined") { + // not supported in browser for now without polyfills + return false; } - OpenCensusTraceStateWrapper.prototype.get = function (_key) { - throw new Error("Method not implemented."); - }; - OpenCensusTraceStateWrapper.prototype.set = function (_key, _value) { - throw new Error("Method not implemented."); - }; - OpenCensusTraceStateWrapper.prototype.unset = function (_key) { - throw new Error("Method not implemented"); - }; - OpenCensusTraceStateWrapper.prototype.serialize = function () { - return this._state || ""; - }; - return OpenCensusTraceStateWrapper; -}()); - -// Copyright (c) Microsoft Corporation. -/** An enumeration of canonical status codes. */ -var CanonicalCode; -(function (CanonicalCode) { - /** - * Not an error; returned on success - */ - CanonicalCode[CanonicalCode["OK"] = 0] = "OK"; - /** - * Internal errors. Means some invariants expected by underlying - * system has been broken. If you see one of these errors, - * something is very broken. - */ - CanonicalCode[CanonicalCode["INTERNAL"] = 13] = "INTERNAL"; -})(CanonicalCode || (CanonicalCode = {})); -function isWrappedSpan(span) { - return !!span && span.getWrappedSpan !== undefined; + const azureTracingDisabledValue = (_a = process.env.AZURE_TRACING_DISABLED) === null || _a === void 0 ? void 0 : _a.toLowerCase(); + if (azureTracingDisabledValue === "false" || azureTracingDisabledValue === "0") { + return false; + } + return Boolean(azureTracingDisabledValue); } -function isTracer(tracerOrSpan) { - return tracerOrSpan.getWrappedTracer !== undefined; -} -/** - * An implementation of OpenTelemetry Span that wraps an OpenCensus Span. - */ -var OpenCensusSpanWrapper = /** @class */ (function () { - function OpenCensusSpanWrapper(tracerOrSpan, name, options, context$1) { - if (name === void 0) { name = ""; } - if (options === void 0) { options = {}; } - if (isTracer(tracerOrSpan)) { - var span = getSpan(context$1 !== null && context$1 !== void 0 ? context$1 : context.active()); - var parent = isWrappedSpan(span) ? span.getWrappedSpan() : undefined; - this._span = tracerOrSpan.getWrappedTracer().startChildSpan({ - name: name, - childOf: parent - }); - this._span.start(); - if (options.links) { - for (var _i = 0, _a = options.links; _i < _a.length; _i++) { - var link = _a[_i]; - // Since there is no way to set the link relationship, leave it as Unspecified. - this._span.addLink(link.context.traceId, link.context.spanId, 0 /* LinkType.UNSPECIFIED */, link.attributes); - } - } - } - else { - this._span = tracerOrSpan; - } - } - /** - * The underlying OpenCensus Span - */ - OpenCensusSpanWrapper.prototype.getWrappedSpan = function () { - return this._span; - }; - /** - * Marks the end of Span execution. - * @param endTime - The time to use as the Span's end time. Defaults to - * the current time. - */ - OpenCensusSpanWrapper.prototype.end = function (_endTime) { - this._span.end(); - }; - /** - * Returns the SpanContext associated with this Span. - */ - OpenCensusSpanWrapper.prototype.context = function () { - var openCensusSpanContext = this._span.spanContext; - return { - spanId: openCensusSpanContext.spanId, - traceId: openCensusSpanContext.traceId, - traceFlags: openCensusSpanContext.options, - traceState: new OpenCensusTraceStateWrapper(openCensusSpanContext.traceState) - }; - }; - /** - * Sets an attribute on the Span - * @param key - The attribute key - * @param value - The attribute value - */ - OpenCensusSpanWrapper.prototype.setAttribute = function (key, value) { - this._span.addAttribute(key, value); - return this; - }; - /** - * Sets attributes on the Span - * @param attributes - The attributes to add - */ - OpenCensusSpanWrapper.prototype.setAttributes = function (attributes) { - this._span.attributes = attributes; - return this; - }; - /** - * Adds an event to the Span - * @param name - The name of the event - * @param attributes - The associated attributes to add for this event - */ - OpenCensusSpanWrapper.prototype.addEvent = function (_name, _attributes) { - throw new Error("Method not implemented."); - }; - /** - * Sets a status on the span. Overrides the default of SpanStatusCode.OK. - * @param status - The status to set. - */ - OpenCensusSpanWrapper.prototype.setStatus = function (status) { - switch (status.code) { - case exports.SpanStatusCode.ERROR: { - this._span.setStatus(CanonicalCode.INTERNAL, status.message); - break; - } - case exports.SpanStatusCode.OK: { - this._span.setStatus(CanonicalCode.OK, status.message); - break; - } - case exports.SpanStatusCode.UNSET: { - break; - } - } - return this; - }; - /** - * Updates the name of the Span - * @param name - The new Span name - */ - OpenCensusSpanWrapper.prototype.updateName = function (name) { - this._span.name = name; - return this; - }; - /** - * Returns whether this span will be recorded - */ - OpenCensusSpanWrapper.prototype.isRecording = function () { - // NoRecordSpans have an empty traceId - return !!this._span.traceId; - }; - /** - * Sets exception as a span event - * @param exception - the exception the only accepted values are string or Error - * @param time - the time to set as Span's event time. If not provided, - * use the current time. - */ - OpenCensusSpanWrapper.prototype.recordException = function (_exception, _time) { - throw new Error("Method not implemented"); - }; - return OpenCensusSpanWrapper; -}()); - -// Copyright (c) Microsoft Corporation. -/** - * An implementation of OpenTelemetry Tracer that wraps an OpenCensus Tracer. - */ -var OpenCensusTracerWrapper = /** @class */ (function () { - /** - * Create a new wrapper around a given OpenCensus Tracer. - * @param tracer - The OpenCensus Tracer to wrap. - */ - function OpenCensusTracerWrapper(tracer) { - this._tracer = tracer; - } - /** - * The wrapped OpenCensus Tracer - */ - OpenCensusTracerWrapper.prototype.getWrappedTracer = function () { - return this._tracer; - }; - /** - * Starts a new Span. - * @param name - The name of the span. - * @param options - The SpanOptions used during Span creation. - */ - OpenCensusTracerWrapper.prototype.startSpan = function (name, options) { - return new OpenCensusSpanWrapper(this, name, options); - }; - /** - * Returns the current Span from the current context, if available. - */ - OpenCensusTracerWrapper.prototype.getCurrentSpan = function () { - return undefined; - }; - /** - * Executes the given function within the context provided by a Span. - * @param _span - The span that provides the context. - * @param _fn - The function to be executed. - */ - OpenCensusTracerWrapper.prototype.withSpan = function (_span, _fn) { - throw new Error("Method not implemented."); - }; - /** - * Bind a Span as the target's scope - * @param target - An object to bind the scope. - * @param _span - A specific Span to use. Otherwise, use the current one. - */ - OpenCensusTracerWrapper.prototype.bind = function (_target, _span) { - throw new Error("Method not implemented."); - }; - return OpenCensusTracerWrapper; -}()); - -// Copyright (c) Microsoft Corporation. -/** - * A mock span useful for testing. - */ -var TestSpan = /** @class */ (function (_super) { - tslib.__extends(TestSpan, _super); - /** - * Starts a new Span. - * @param parentTracer- The tracer that created this Span - * @param name - The name of the span. - * @param context - The SpanContext this span belongs to - * @param kind - The SpanKind of this Span - * @param parentSpanId - The identifier of the parent Span - * @param startTime - The startTime of the event (defaults to now) - */ - function TestSpan(parentTracer, name, context, kind, parentSpanId, startTime) { - if (startTime === void 0) { startTime = Date.now(); } - var _this = _super.call(this) || this; - _this._tracer = parentTracer; - _this.name = name; - _this.kind = kind; - _this.startTime = startTime; - _this.parentSpanId = parentSpanId; - _this.status = { - code: exports.SpanStatusCode.OK - }; - _this.endCalled = false; - _this._context = context; - _this.attributes = {}; - return _this; - } - /** - * Returns the Tracer that created this Span - */ - TestSpan.prototype.tracer = function () { - return this._tracer; - }; - /** - * Returns the SpanContext associated with this Span. - */ - TestSpan.prototype.context = function () { - return this._context; - }; - /** - * Marks the end of Span execution. - * @param _endTime - The time to use as the Span's end time. Defaults to - * the current time. - */ - TestSpan.prototype.end = function (_endTime) { - this.endCalled = true; - }; - /** - * Sets a status on the span. Overrides the default of SpanStatusCode.OK. - * @param status - The status to set. - */ - TestSpan.prototype.setStatus = function (status) { - this.status = status; - return this; - }; - /** - * Returns whether this span will be recorded - */ - TestSpan.prototype.isRecording = function () { - return true; - }; - /** - * Sets an attribute on the Span - * @param key - The attribute key - * @param value - The attribute value - */ - TestSpan.prototype.setAttribute = function (key, value) { - this.attributes[key] = value; - return this; - }; - /** - * Sets attributes on the Span - * @param attributes - The attributes to add - */ - TestSpan.prototype.setAttributes = function (attributes) { - for (var _i = 0, _a = Object.keys(attributes); _i < _a.length; _i++) { - var key = _a[_i]; - this.attributes[key] = attributes[key]; - } - return this; - }; - return TestSpan; -}(NoOpSpan)); - -// Copyright (c) Microsoft Corporation. -/** - * A mock tracer useful for testing - */ -var TestTracer = /** @class */ (function (_super) { - tslib.__extends(TestTracer, _super); - function TestTracer() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.traceIdCounter = 0; - _this.spanIdCounter = 0; - _this.rootSpans = []; - _this.knownSpans = []; - return _this; - } - TestTracer.prototype.getNextTraceId = function () { - this.traceIdCounter++; - return String(this.traceIdCounter); - }; - TestTracer.prototype.getNextSpanId = function () { - this.spanIdCounter++; - return String(this.spanIdCounter); - }; - /** - * Returns all Spans that were created without a parent - */ - TestTracer.prototype.getRootSpans = function () { - return this.rootSpans; - }; - /** - * Returns all Spans this Tracer knows about - */ - TestTracer.prototype.getKnownSpans = function () { - return this.knownSpans; - }; - /** - * Returns all Spans where end() has not been called - */ - TestTracer.prototype.getActiveSpans = function () { - return this.knownSpans.filter(function (span) { - return !span.endCalled; - }); - }; - /** - * Return all Spans for a particular trace, grouped by their - * parent Span in a tree-like structure - * @param traceId - The traceId to return the graph for - */ - TestTracer.prototype.getSpanGraph = function (traceId) { - var traceSpans = this.knownSpans.filter(function (span) { - return span.context().traceId === traceId; - }); - var roots = []; - var nodeMap = new Map(); - for (var _i = 0, traceSpans_1 = traceSpans; _i < traceSpans_1.length; _i++) { - var span = traceSpans_1[_i]; - var spanId = span.context().spanId; - var node = { - name: span.name, - children: [] - }; - nodeMap.set(spanId, node); - if (span.parentSpanId) { - var parent = nodeMap.get(span.parentSpanId); - if (!parent) { - throw new Error("Span with name " + node.name + " has an unknown parentSpan with id " + span.parentSpanId); - } - parent.children.push(node); - } - else { - roots.push(node); - } - } - return { - roots: roots - }; - }; - /** - * Starts a new Span. - * @param name - The name of the span. - * @param options - The SpanOptions used during Span creation. - */ - TestTracer.prototype.startSpan = function (name, options, context$1) { - var parentContext = getSpanContext(context$1 || context.active()); - var traceId; - var isRootSpan = false; - if (parentContext && parentContext.traceId) { - traceId = parentContext.traceId; - } - else { - traceId = this.getNextTraceId(); - isRootSpan = true; - } - var spanContext = { - traceId: traceId, - spanId: this.getNextSpanId(), - traceFlags: 0 /* NONE */ - }; - var span = new TestSpan(this, name, spanContext, (options === null || options === void 0 ? void 0 : options.kind) || exports.SpanKind.INTERNAL, parentContext ? parentContext.spanId : undefined, options === null || options === void 0 ? void 0 : options.startTime); - this.knownSpans.push(span); - if (isRootSpan) { - this.rootSpans.push(span); - } - return span; - }; - return TestTracer; -}(NoOpTracer)); - -// Copyright (c) Microsoft Corporation. /** * Creates a function that can be used to create spans using the global tracer. * @@ -8139,22 +6453,28 @@ var TestTracer = /** @class */ (function (_super) { */ function createSpanFunction(args) { return function (operationName, operationOptions) { - var tracer = getTracer(); - var tracingOptions = (operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) || {}; - var spanOptions = tslib.__assign({ kind: exports.SpanKind.INTERNAL }, tracingOptions.spanOptions); - var spanName = args.packagePrefix ? args.packagePrefix + "." + operationName : operationName; - var span = tracer.startSpan(spanName, spanOptions, tracingOptions.tracingContext); + const tracer = getTracer(); + const tracingOptions = (operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) || {}; + const spanOptions = Object.assign({ kind: exports.SpanKind.INTERNAL }, tracingOptions.spanOptions); + const spanName = args.packagePrefix ? `${args.packagePrefix}.${operationName}` : operationName; + let span; + if (isTracingDisabled()) { + span = api.trace.wrapSpanContext(api.INVALID_SPAN_CONTEXT); + } + else { + span = tracer.startSpan(spanName, spanOptions, tracingOptions.tracingContext); + } if (args.namespace) { span.setAttribute("az.namespace", args.namespace); } - var newSpanOptions = tracingOptions.spanOptions || {}; + let newSpanOptions = tracingOptions.spanOptions || {}; if (span.isRecording() && args.namespace) { - newSpanOptions = tslib.__assign(tslib.__assign({}, tracingOptions.spanOptions), { attributes: tslib.__assign(tslib.__assign({}, spanOptions.attributes), { "az.namespace": args.namespace }) }); + newSpanOptions = Object.assign(Object.assign({}, tracingOptions.spanOptions), { attributes: Object.assign(Object.assign({}, spanOptions.attributes), { "az.namespace": args.namespace }) }); } - var newTracingOptions = tslib.__assign(tslib.__assign({}, tracingOptions), { spanOptions: newSpanOptions, tracingContext: setSpan(tracingOptions.tracingContext || context.active(), span) }); - var newOperationOptions = tslib.__assign(tslib.__assign({}, operationOptions), { tracingOptions: newTracingOptions }); + const newTracingOptions = Object.assign(Object.assign({}, tracingOptions), { spanOptions: newSpanOptions, tracingContext: setSpan(tracingOptions.tracingContext || context.active(), span) }); + const newOperationOptions = Object.assign(Object.assign({}, operationOptions), { tracingOptions: newTracingOptions }); return { - span: span, + span, updatedOptions: newOperationOptions }; }; @@ -8162,26 +6482,26 @@ function createSpanFunction(args) { // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -var VERSION = "00"; +const VERSION = "00"; /** * Generates a `SpanContext` given a `traceparent` header value. * @param traceParent - Serialized span context data as a `traceparent` header value. * @returns The `SpanContext` generated from the `traceparent` value. */ function extractSpanContextFromTraceParentHeader(traceParentHeader) { - var parts = traceParentHeader.split("-"); + const parts = traceParentHeader.split("-"); if (parts.length !== 4) { return; } - var version = parts[0], traceId = parts[1], spanId = parts[2], traceOptions = parts[3]; + const [version, traceId, spanId, traceOptions] = parts; if (version !== VERSION) { return; } - var traceFlags = parseInt(traceOptions, 16); - var spanContext = { - spanId: spanId, - traceId: traceId, - traceFlags: traceFlags + const traceFlags = parseInt(traceOptions, 16); + const spanContext = { + spanId, + traceId, + traceFlags }; return spanContext; } @@ -8191,7 +6511,7 @@ function extractSpanContextFromTraceParentHeader(traceParentHeader) { * @returns The `spanContext` represented as a `traceparent` value. */ function getTraceParentHeader(spanContext) { - var missingFields = []; + const missingFields = []; if (!spanContext.traceId) { missingFields.push("traceId"); } @@ -8201,19 +6521,13 @@ function getTraceParentHeader(spanContext) { if (missingFields.length) { return; } - var flags = spanContext.traceFlags || 0 /* NONE */; - var hexFlags = flags.toString(16); - var traceFlags = hexFlags.length === 1 ? "0" + hexFlags : hexFlags; + const flags = spanContext.traceFlags || 0 /* NONE */; + const hexFlags = flags.toString(16); + const traceFlags = hexFlags.length === 1 ? `0${hexFlags}` : hexFlags; // https://www.w3.org/TR/trace-context/#traceparent-header-field-values - return VERSION + "-" + spanContext.traceId + "-" + spanContext.spanId + "-" + traceFlags; + return `${VERSION}-${spanContext.traceId}-${spanContext.spanId}-${traceFlags}`; } -exports.NoOpSpan = NoOpSpan; -exports.NoOpTracer = NoOpTracer; -exports.OpenCensusSpanWrapper = OpenCensusSpanWrapper; -exports.OpenCensusTracerWrapper = OpenCensusTracerWrapper; -exports.TestSpan = TestSpan; -exports.TestTracer = TestTracer; exports.context = context; exports.createSpanFunction = createSpanFunction; exports.extractSpanContextFromTraceParentHeader = extractSpanContextFromTraceParentHeader; @@ -8221,9 +6535,9 @@ exports.getSpan = getSpan; exports.getSpanContext = getSpanContext; exports.getTraceParentHeader = getTraceParentHeader; exports.getTracer = getTracer; +exports.isSpanContextValid = isSpanContextValid; exports.setSpan = setSpan; exports.setSpanContext = setSpanContext; -exports.setTracer = setTracer; //# sourceMappingURL=index.js.map @@ -10279,7 +8593,131 @@ function expand(str, isTop) { /* 329 */, /* 330 */, /* 331 */, -/* 332 */ +/* 332 */, +/* 333 */, +/* 334 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +module.exports = +{ + parallel : __webpack_require__(424), + serial : __webpack_require__(91), + serialOrdered : __webpack_require__(892) +}; + + +/***/ }), +/* 335 */, +/* 336 */, +/* 337 */, +/* 338 */ +/***/ (function() { + +"use strict"; + +if (typeof Symbol === undefined || !Symbol.asyncIterator) { + Symbol.asyncIterator = Symbol.for("Symbol.asyncIterator"); +} +//# sourceMappingURL=index.js.map + +/***/ }), +/* 339 */, +/* 340 */ +/***/ (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 }); +exports.SamplingDecision = void 0; +/** + * A sampling decision that determines how a {@link Span} will be recorded + * and collected. + */ +var SamplingDecision; +(function (SamplingDecision) { + /** + * `Span.isRecording() === false`, span will not be recorded and all events + * and attributes will be dropped. + */ + SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD"; + /** + * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} + * MUST NOT be set. + */ + SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD"; + /** + * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} + * MUST be set. + */ + SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; +})(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {})); +//# sourceMappingURL=SamplingResult.js.map + +/***/ }), +/* 341 */, +/* 342 */, +/* 343 */, +/* 344 */, +/* 345 */, +/* 346 */, +/* 347 */ +/***/ (function(module, __unusedexports, __webpack_require__) { + +// Generated by CoffeeScript 1.12.7 +(function() { + var XMLStringWriter, XMLWriterBase, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + XMLWriterBase = __webpack_require__(423); + + module.exports = XMLStringWriter = (function(superClass) { + extend(XMLStringWriter, superClass); + + function XMLStringWriter(options) { + XMLStringWriter.__super__.constructor.call(this, options); + } + + XMLStringWriter.prototype.document = function(doc, options) { + var child, i, len, r, ref; + options = this.filterOptions(options); + r = ''; + ref = doc.children; + for (i = 0, len = ref.length; i < len; i++) { + child = ref[i]; + r += this.writeChildNode(child, options, 0); + } + if (options.pretty && r.slice(-options.newline.length) === options.newline) { + r = r.slice(0, -options.newline.length); + } + return r; + }; + + return XMLStringWriter; + + })(XMLWriterBase); + +}).call(this); + + +/***/ }), +/* 348 */, +/* 349 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; @@ -10315,9 +8753,9 @@ function expand(str, isTop) { */ const { fromCallback } = __webpack_require__(147); -const Store = __webpack_require__(338).Store; -const permuteDomain = __webpack_require__(898).permuteDomain; -const pathMatch = __webpack_require__(348).pathMatch; +const Store = __webpack_require__(627).Store; +const permuteDomain = __webpack_require__(383).permuteDomain; +const pathMatch = __webpack_require__(54).pathMatch; const util = __webpack_require__(669); class MemoryCookieStore extends Store { @@ -10476,269 +8914,6 @@ exports.MemoryCookieStore = MemoryCookieStore; /***/ }), -/* 333 */, -/* 334 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -module.exports = -{ - parallel : __webpack_require__(424), - serial : __webpack_require__(91), - serialOrdered : __webpack_require__(892) -}; - - -/***/ }), -/* 335 */, -/* 336 */, -/* 337 */, -/* 338 */ -/***/ (function(__unusedmodule, exports) { - -"use strict"; -/*! - * Copyright (c) 2015, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of Salesforce.com nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -/*jshint unused:false */ - -class Store { - constructor() { - this.synchronous = false; - } - - findCookie(domain, path, key, cb) { - throw new Error("findCookie is not implemented"); - } - - findCookies(domain, path, allowSpecialUseDomain, cb) { - throw new Error("findCookies is not implemented"); - } - - putCookie(cookie, cb) { - throw new Error("putCookie is not implemented"); - } - - updateCookie(oldCookie, newCookie, cb) { - // recommended default implementation: - // return this.putCookie(newCookie, cb); - throw new Error("updateCookie is not implemented"); - } - - removeCookie(domain, path, key, cb) { - throw new Error("removeCookie is not implemented"); - } - - removeCookies(domain, path, cb) { - throw new Error("removeCookies is not implemented"); - } - - removeAllCookies(cb) { - throw new Error("removeAllCookies is not implemented"); - } - - getAllCookies(cb) { - throw new Error( - "getAllCookies is not implemented (therefore jar cannot be serialized)" - ); - } -} - -exports.Store = Store; - - -/***/ }), -/* 339 */, -/* 340 */ -/***/ (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 }); -exports.SamplingDecision = void 0; -/** - * A sampling decision that determines how a {@link Span} will be recorded - * and collected. - */ -var SamplingDecision; -(function (SamplingDecision) { - /** - * `Span.isRecording() === false`, span will not be recorded and all events - * and attributes will be dropped. - */ - SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD"; - /** - * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} - * MUST NOT be set. - */ - SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD"; - /** - * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} - * MUST be set. - */ - SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; -})(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {})); -//# sourceMappingURL=SamplingResult.js.map - -/***/ }), -/* 341 */, -/* 342 */, -/* 343 */, -/* 344 */, -/* 345 */, -/* 346 */, -/* 347 */ -/***/ (function(module, __unusedexports, __webpack_require__) { - -// Generated by CoffeeScript 1.12.7 -(function() { - var XMLStringWriter, XMLWriterBase, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; - - XMLWriterBase = __webpack_require__(423); - - module.exports = XMLStringWriter = (function(superClass) { - extend(XMLStringWriter, superClass); - - function XMLStringWriter(options) { - XMLStringWriter.__super__.constructor.call(this, options); - } - - XMLStringWriter.prototype.document = function(doc, options) { - var child, i, len, r, ref; - options = this.filterOptions(options); - r = ''; - ref = doc.children; - for (i = 0, len = ref.length; i < len; i++) { - child = ref[i]; - r += this.writeChildNode(child, options, 0); - } - if (options.pretty && r.slice(-options.newline.length) === options.newline) { - r = r.slice(0, -options.newline.length); - } - return r; - }; - - return XMLStringWriter; - - })(XMLWriterBase); - -}).call(this); - - -/***/ }), -/* 348 */ -/***/ (function(__unusedmodule, exports) { - -"use strict"; -/*! - * Copyright (c) 2015, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of Salesforce.com nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * "A request-path path-matches a given cookie-path if at least one of the - * following conditions holds:" - */ -function pathMatch(reqPath, cookiePath) { - // "o The cookie-path and the request-path are identical." - if (cookiePath === reqPath) { - return true; - } - - const idx = reqPath.indexOf(cookiePath); - if (idx === 0) { - // "o The cookie-path is a prefix of the request-path, and the last - // character of the cookie-path is %x2F ("/")." - if (cookiePath.substr(-1) === "/") { - return true; - } - - // " o The cookie-path is a prefix of the request-path, and the first - // character of the request-path that is not included in the cookie- path - // is a %x2F ("/") character." - if (reqPath.substr(cookiePath.length, 1) === "/") { - return true; - } - } - - return false; -} - -exports.pathMatch = pathMatch; - - -/***/ }), -/* 349 */, /* 350 */ /***/ (function(__unusedmodule, exports) { @@ -10795,7 +8970,92 @@ module.exports = require("assert"); /* 359 */, /* 360 */, /* 361 */, -/* 362 */, +/* 362 */ +/***/ (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.DiagComponentLogger = void 0; +var global_utils_1 = __webpack_require__(525); +/** + * Component Logger which is meant to be used as part of any component which + * will add automatically additional namespace in front of the log message. + * It will then forward all message to global diag logger + * @example + * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' }); + * cLogger.debug('test'); + * // @opentelemetry/instrumentation-http test + */ +var DiagComponentLogger = /** @class */ (function () { + function DiagComponentLogger(props) { + this._namespace = props.namespace || 'DiagComponentLogger'; + } + DiagComponentLogger.prototype.debug = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return logProxy('debug', this._namespace, args); + }; + DiagComponentLogger.prototype.error = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return logProxy('error', this._namespace, args); + }; + DiagComponentLogger.prototype.info = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return logProxy('info', this._namespace, args); + }; + DiagComponentLogger.prototype.warn = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return logProxy('warn', this._namespace, args); + }; + DiagComponentLogger.prototype.verbose = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return logProxy('verbose', this._namespace, args); + }; + return DiagComponentLogger; +}()); +exports.DiagComponentLogger = DiagComponentLogger; +function logProxy(funcName, namespace, args) { + var logger = global_utils_1.getGlobal('diag'); + // shortcut if logger not set + if (!logger) { + return; + } + args.unshift(namespace); + return logger[funcName].apply(logger, args); +} +//# sourceMappingURL=ComponentLogger.js.map + +/***/ }), /* 363 */, /* 364 */, /* 365 */, @@ -10835,7 +9095,7 @@ var util = __webpack_require__(669); * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ -var BlobServiceProperties = { +const BlobServiceProperties = { serializedName: "BlobServiceProperties", xmlName: "StorageServiceProperties", type: { @@ -10907,7 +9167,7 @@ var BlobServiceProperties = { } } }; -var Logging = { +const Logging = { serializedName: "Logging", type: { name: "Composite", @@ -10956,7 +9216,7 @@ var Logging = { } } }; -var RetentionPolicy = { +const RetentionPolicy = { serializedName: "RetentionPolicy", type: { name: "Composite", @@ -10983,7 +9243,7 @@ var RetentionPolicy = { } } }; -var Metrics = { +const Metrics = { serializedName: "Metrics", type: { name: "Composite", @@ -11022,7 +9282,7 @@ var Metrics = { } } }; -var CorsRule = { +const CorsRule = { serializedName: "CorsRule", type: { name: "Composite", @@ -11074,7 +9334,7 @@ var CorsRule = { } } }; -var StaticWebsite = { +const StaticWebsite = { serializedName: "StaticWebsite", type: { name: "Composite", @@ -11112,7 +9372,7 @@ var StaticWebsite = { } } }; -var StorageError = { +const StorageError = { serializedName: "StorageError", type: { name: "Composite", @@ -11135,7 +9395,7 @@ var StorageError = { } } }; -var BlobServiceStatistics = { +const BlobServiceStatistics = { serializedName: "BlobServiceStatistics", xmlName: "StorageServiceStats", type: { @@ -11153,7 +9413,7 @@ var BlobServiceStatistics = { } } }; -var GeoReplication = { +const GeoReplication = { serializedName: "GeoReplication", type: { name: "Composite", @@ -11179,7 +9439,7 @@ var GeoReplication = { } } }; -var ListContainersSegmentResponse = { +const ListContainersSegmentResponse = { serializedName: "ListContainersSegmentResponse", xmlName: "EnumerationResults", type: { @@ -11242,7 +9502,7 @@ var ListContainersSegmentResponse = { } } }; -var ContainerItem = { +const ContainerItem = { serializedName: "ContainerItem", xmlName: "Container", type: { @@ -11290,7 +9550,7 @@ var ContainerItem = { } } }; -var ContainerProperties = { +const ContainerProperties = { serializedName: "ContainerProperties", type: { name: "Composite", @@ -11391,11 +9651,18 @@ var ContainerProperties = { type: { name: "Number" } + }, + isImmutableStorageWithVersioningEnabled: { + serializedName: "ImmutableStorageWithVersioningEnabled", + xmlName: "ImmutableStorageWithVersioningEnabled", + type: { + name: "Boolean" + } } } } }; -var KeyInfo = { +const KeyInfo = { serializedName: "KeyInfo", type: { name: "Composite", @@ -11420,7 +9687,7 @@ var KeyInfo = { } } }; -var UserDelegationKey = { +const UserDelegationKey = { serializedName: "UserDelegationKey", type: { name: "Composite", @@ -11485,7 +9752,7 @@ var UserDelegationKey = { } } }; -var FilterBlobSegment = { +const FilterBlobSegment = { serializedName: "FilterBlobSegment", xmlName: "EnumerationResults", type: { @@ -11535,7 +9802,7 @@ var FilterBlobSegment = { } } }; -var FilterBlobItem = { +const FilterBlobItem = { serializedName: "FilterBlobItem", xmlName: "Blob", type: { @@ -11569,7 +9836,7 @@ var FilterBlobItem = { } } }; -var BlobTags = { +const BlobTags = { serializedName: "BlobTags", xmlName: "Tags", type: { @@ -11595,7 +9862,7 @@ var BlobTags = { } } }; -var BlobTag = { +const BlobTag = { serializedName: "BlobTag", xmlName: "Tag", type: { @@ -11621,7 +9888,7 @@ var BlobTag = { } } }; -var SignedIdentifier = { +const SignedIdentifier = { serializedName: "SignedIdentifier", xmlName: "SignedIdentifier", type: { @@ -11647,7 +9914,7 @@ var SignedIdentifier = { } } }; -var AccessPolicy = { +const AccessPolicy = { serializedName: "AccessPolicy", type: { name: "Composite", @@ -11677,7 +9944,7 @@ var AccessPolicy = { } } }; -var ListBlobsFlatSegmentResponse = { +const ListBlobsFlatSegmentResponse = { serializedName: "ListBlobsFlatSegmentResponse", xmlName: "EnumerationResults", type: { @@ -11741,7 +10008,7 @@ var ListBlobsFlatSegmentResponse = { } } }; -var BlobFlatListSegment = { +const BlobFlatListSegment = { serializedName: "BlobFlatListSegment", xmlName: "Blobs", type: { @@ -11766,7 +10033,7 @@ var BlobFlatListSegment = { } } }; -var BlobItemInternal = { +const BlobItemInternal = { serializedName: "BlobItemInternal", xmlName: "Blob", type: { @@ -11842,11 +10109,18 @@ var BlobItemInternal = { name: "Dictionary", value: { type: { name: "String" } } } + }, + hasVersionsOnly: { + serializedName: "HasVersionsOnly", + xmlName: "HasVersionsOnly", + type: { + name: "Boolean" + } } } } }; -var BlobPropertiesInternal = { +const BlobPropertiesInternal = { serializedName: "BlobPropertiesInternal", xmlName: "Properties", type: { @@ -12145,11 +10419,33 @@ var BlobPropertiesInternal = { type: { name: "DateTimeRfc1123" } + }, + immutabilityPolicyExpiresOn: { + serializedName: "ImmutabilityPolicyUntilDate", + xmlName: "ImmutabilityPolicyUntilDate", + type: { + name: "DateTimeRfc1123" + } + }, + immutabilityPolicyMode: { + serializedName: "ImmutabilityPolicyMode", + xmlName: "ImmutabilityPolicyMode", + type: { + name: "Enum", + allowedValues: ["Mutable", "Unlocked", "Locked"] + } + }, + legalHold: { + serializedName: "LegalHold", + xmlName: "LegalHold", + type: { + name: "Boolean" + } } } } }; -var ListBlobsHierarchySegmentResponse = { +const ListBlobsHierarchySegmentResponse = { serializedName: "ListBlobsHierarchySegmentResponse", xmlName: "EnumerationResults", type: { @@ -12220,7 +10516,7 @@ var ListBlobsHierarchySegmentResponse = { } } }; -var BlobHierarchyListSegment = { +const BlobHierarchyListSegment = { serializedName: "BlobHierarchyListSegment", xmlName: "Blobs", type: { @@ -12259,7 +10555,7 @@ var BlobHierarchyListSegment = { } } }; -var BlobPrefix = { +const BlobPrefix = { serializedName: "BlobPrefix", type: { name: "Composite", @@ -12276,47 +10572,7 @@ var BlobPrefix = { } } }; -var DataLakeStorageError = { - serializedName: "DataLakeStorageError", - type: { - name: "Composite", - className: "DataLakeStorageError", - modelProperties: { - dataLakeStorageErrorDetails: { - serializedName: "error", - xmlName: "error", - type: { - name: "Composite", - className: "DataLakeStorageErrorError" - } - } - } - } -}; -var DataLakeStorageErrorError = { - serializedName: "DataLakeStorageErrorError", - type: { - name: "Composite", - className: "DataLakeStorageErrorError", - modelProperties: { - code: { - serializedName: "Code", - xmlName: "Code", - type: { - name: "String" - } - }, - message: { - serializedName: "Message", - xmlName: "Message", - type: { - name: "String" - } - } - } - } -}; -var BlockLookupList = { +const BlockLookupList = { serializedName: "BlockLookupList", xmlName: "BlockList", type: { @@ -12365,7 +10621,7 @@ var BlockLookupList = { } } }; -var BlockList = { +const BlockList = { serializedName: "BlockList", type: { name: "Composite", @@ -12404,7 +10660,7 @@ var BlockList = { } } }; -var Block = { +const Block = { serializedName: "Block", type: { name: "Composite", @@ -12429,7 +10685,7 @@ var Block = { } } }; -var PageList = { +const PageList = { serializedName: "PageList", type: { name: "Composite", @@ -12466,7 +10722,7 @@ var PageList = { } } }; -var PageRange = { +const PageRange = { serializedName: "PageRange", xmlName: "PageRange", type: { @@ -12492,7 +10748,7 @@ var PageRange = { } } }; -var ClearRange = { +const ClearRange = { serializedName: "ClearRange", xmlName: "ClearRange", type: { @@ -12518,7 +10774,7 @@ var ClearRange = { } } }; -var QueryRequest = { +const QueryRequest = { serializedName: "QueryRequest", xmlName: "QueryRequest", type: { @@ -12560,7 +10816,7 @@ var QueryRequest = { } } }; -var QuerySerialization = { +const QuerySerialization = { serializedName: "QuerySerialization", type: { name: "Composite", @@ -12577,7 +10833,7 @@ var QuerySerialization = { } } }; -var QueryFormat = { +const QueryFormat = { serializedName: "QueryFormat", type: { name: "Composite", @@ -12585,10 +10841,11 @@ var QueryFormat = { modelProperties: { type: { serializedName: "Type", + required: true, xmlName: "Type", type: { name: "Enum", - allowedValues: ["delimited", "json", "arrow"] + allowedValues: ["delimited", "json", "arrow", "parquet"] } }, delimitedTextConfiguration: { @@ -12614,11 +10871,18 @@ var QueryFormat = { name: "Composite", className: "ArrowConfiguration" } + }, + parquetTextConfiguration: { + serializedName: "ParquetTextConfiguration", + xmlName: "ParquetTextConfiguration", + type: { + name: "any" + } } } } }; -var DelimitedTextConfiguration = { +const DelimitedTextConfiguration = { serializedName: "DelimitedTextConfiguration", xmlName: "DelimitedTextConfiguration", type: { @@ -12627,7 +10891,6 @@ var DelimitedTextConfiguration = { modelProperties: { columnSeparator: { serializedName: "ColumnSeparator", - required: true, xmlName: "ColumnSeparator", type: { name: "String" @@ -12635,7 +10898,6 @@ var DelimitedTextConfiguration = { }, fieldQuote: { serializedName: "FieldQuote", - required: true, xmlName: "FieldQuote", type: { name: "String" @@ -12643,7 +10905,6 @@ var DelimitedTextConfiguration = { }, recordSeparator: { serializedName: "RecordSeparator", - required: true, xmlName: "RecordSeparator", type: { name: "String" @@ -12651,7 +10912,6 @@ var DelimitedTextConfiguration = { }, escapeChar: { serializedName: "EscapeChar", - required: true, xmlName: "EscapeChar", type: { name: "String" @@ -12659,7 +10919,6 @@ var DelimitedTextConfiguration = { }, headersPresent: { serializedName: "HeadersPresent", - required: true, xmlName: "HasHeaders", type: { name: "Boolean" @@ -12668,7 +10927,7 @@ var DelimitedTextConfiguration = { } } }; -var JsonTextConfiguration = { +const JsonTextConfiguration = { serializedName: "JsonTextConfiguration", xmlName: "JsonTextConfiguration", type: { @@ -12677,7 +10936,6 @@ var JsonTextConfiguration = { modelProperties: { recordSeparator: { serializedName: "RecordSeparator", - required: true, xmlName: "RecordSeparator", type: { name: "String" @@ -12686,7 +10944,7 @@ var JsonTextConfiguration = { } } }; -var ArrowConfiguration = { +const ArrowConfiguration = { serializedName: "ArrowConfiguration", xmlName: "ArrowConfiguration", type: { @@ -12712,7 +10970,7 @@ var ArrowConfiguration = { } } }; -var ArrowField = { +const ArrowField = { serializedName: "ArrowField", xmlName: "Field", type: { @@ -12751,7 +11009,7 @@ var ArrowField = { } } }; -var ServiceSetPropertiesHeaders = { +const ServiceSetPropertiesHeaders = { serializedName: "Service_setPropertiesHeaders", type: { name: "Composite", @@ -12788,7 +11046,7 @@ var ServiceSetPropertiesHeaders = { } } }; -var ServiceSetPropertiesExceptionHeaders = { +const ServiceSetPropertiesExceptionHeaders = { serializedName: "Service_setPropertiesExceptionHeaders", type: { name: "Composite", @@ -12804,7 +11062,7 @@ var ServiceSetPropertiesExceptionHeaders = { } } }; -var ServiceGetPropertiesHeaders = { +const ServiceGetPropertiesHeaders = { serializedName: "Service_getPropertiesHeaders", type: { name: "Composite", @@ -12841,7 +11099,7 @@ var ServiceGetPropertiesHeaders = { } } }; -var ServiceGetPropertiesExceptionHeaders = { +const ServiceGetPropertiesExceptionHeaders = { serializedName: "Service_getPropertiesExceptionHeaders", type: { name: "Composite", @@ -12857,7 +11115,7 @@ var ServiceGetPropertiesExceptionHeaders = { } } }; -var ServiceGetStatisticsHeaders = { +const ServiceGetStatisticsHeaders = { serializedName: "Service_getStatisticsHeaders", type: { name: "Composite", @@ -12901,7 +11159,7 @@ var ServiceGetStatisticsHeaders = { } } }; -var ServiceGetStatisticsExceptionHeaders = { +const ServiceGetStatisticsExceptionHeaders = { serializedName: "Service_getStatisticsExceptionHeaders", type: { name: "Composite", @@ -12917,7 +11175,7 @@ var ServiceGetStatisticsExceptionHeaders = { } } }; -var ServiceListContainersSegmentHeaders = { +const ServiceListContainersSegmentHeaders = { serializedName: "Service_listContainersSegmentHeaders", type: { name: "Composite", @@ -12954,7 +11212,7 @@ var ServiceListContainersSegmentHeaders = { } } }; -var ServiceListContainersSegmentExceptionHeaders = { +const ServiceListContainersSegmentExceptionHeaders = { serializedName: "Service_listContainersSegmentExceptionHeaders", type: { name: "Composite", @@ -12970,7 +11228,7 @@ var ServiceListContainersSegmentExceptionHeaders = { } } }; -var ServiceGetUserDelegationKeyHeaders = { +const ServiceGetUserDelegationKeyHeaders = { serializedName: "Service_getUserDelegationKeyHeaders", type: { name: "Composite", @@ -13014,7 +11272,7 @@ var ServiceGetUserDelegationKeyHeaders = { } } }; -var ServiceGetUserDelegationKeyExceptionHeaders = { +const ServiceGetUserDelegationKeyExceptionHeaders = { serializedName: "Service_getUserDelegationKeyExceptionHeaders", type: { name: "Composite", @@ -13030,7 +11288,7 @@ var ServiceGetUserDelegationKeyExceptionHeaders = { } } }; -var ServiceGetAccountInfoHeaders = { +const ServiceGetAccountInfoHeaders = { serializedName: "Service_getAccountInfoHeaders", type: { name: "Composite", @@ -13109,7 +11367,7 @@ var ServiceGetAccountInfoHeaders = { } } }; -var ServiceGetAccountInfoExceptionHeaders = { +const ServiceGetAccountInfoExceptionHeaders = { serializedName: "Service_getAccountInfoExceptionHeaders", type: { name: "Composite", @@ -13125,7 +11383,7 @@ var ServiceGetAccountInfoExceptionHeaders = { } } }; -var ServiceSubmitBatchHeaders = { +const ServiceSubmitBatchHeaders = { serializedName: "Service_submitBatchHeaders", type: { name: "Composite", @@ -13169,7 +11427,7 @@ var ServiceSubmitBatchHeaders = { } } }; -var ServiceSubmitBatchExceptionHeaders = { +const ServiceSubmitBatchExceptionHeaders = { serializedName: "Service_submitBatchExceptionHeaders", type: { name: "Composite", @@ -13185,7 +11443,7 @@ var ServiceSubmitBatchExceptionHeaders = { } } }; -var ServiceFilterBlobsHeaders = { +const ServiceFilterBlobsHeaders = { serializedName: "Service_filterBlobsHeaders", type: { name: "Composite", @@ -13229,7 +11487,7 @@ var ServiceFilterBlobsHeaders = { } } }; -var ServiceFilterBlobsExceptionHeaders = { +const ServiceFilterBlobsExceptionHeaders = { serializedName: "Service_filterBlobsExceptionHeaders", type: { name: "Composite", @@ -13245,7 +11503,7 @@ var ServiceFilterBlobsExceptionHeaders = { } } }; -var ContainerCreateHeaders = { +const ContainerCreateHeaders = { serializedName: "Container_createHeaders", type: { name: "Composite", @@ -13303,7 +11561,7 @@ var ContainerCreateHeaders = { } } }; -var ContainerCreateExceptionHeaders = { +const ContainerCreateExceptionHeaders = { serializedName: "Container_createExceptionHeaders", type: { name: "Composite", @@ -13319,7 +11577,7 @@ var ContainerCreateExceptionHeaders = { } } }; -var ContainerGetPropertiesHeaders = { +const ContainerGetPropertiesHeaders = { serializedName: "Container_getPropertiesHeaders", type: { name: "Composite", @@ -13442,6 +11700,13 @@ var ContainerGetPropertiesHeaders = { name: "Boolean" } }, + isImmutableStorageWithVersioningEnabled: { + serializedName: "x-ms-immutable-storage-with-versioning-enabled", + xmlName: "x-ms-immutable-storage-with-versioning-enabled", + type: { + name: "Boolean" + } + }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", @@ -13452,7 +11717,7 @@ var ContainerGetPropertiesHeaders = { } } }; -var ContainerGetPropertiesExceptionHeaders = { +const ContainerGetPropertiesExceptionHeaders = { serializedName: "Container_getPropertiesExceptionHeaders", type: { name: "Composite", @@ -13468,7 +11733,7 @@ var ContainerGetPropertiesExceptionHeaders = { } } }; -var ContainerDeleteHeaders = { +const ContainerDeleteHeaders = { serializedName: "Container_deleteHeaders", type: { name: "Composite", @@ -13512,7 +11777,7 @@ var ContainerDeleteHeaders = { } } }; -var ContainerDeleteExceptionHeaders = { +const ContainerDeleteExceptionHeaders = { serializedName: "Container_deleteExceptionHeaders", type: { name: "Composite", @@ -13528,7 +11793,7 @@ var ContainerDeleteExceptionHeaders = { } } }; -var ContainerSetMetadataHeaders = { +const ContainerSetMetadataHeaders = { serializedName: "Container_setMetadataHeaders", type: { name: "Composite", @@ -13586,7 +11851,7 @@ var ContainerSetMetadataHeaders = { } } }; -var ContainerSetMetadataExceptionHeaders = { +const ContainerSetMetadataExceptionHeaders = { serializedName: "Container_setMetadataExceptionHeaders", type: { name: "Composite", @@ -13602,7 +11867,7 @@ var ContainerSetMetadataExceptionHeaders = { } } }; -var ContainerGetAccessPolicyHeaders = { +const ContainerGetAccessPolicyHeaders = { serializedName: "Container_getAccessPolicyHeaders", type: { name: "Composite", @@ -13668,7 +11933,7 @@ var ContainerGetAccessPolicyHeaders = { } } }; -var ContainerGetAccessPolicyExceptionHeaders = { +const ContainerGetAccessPolicyExceptionHeaders = { serializedName: "Container_getAccessPolicyExceptionHeaders", type: { name: "Composite", @@ -13684,7 +11949,7 @@ var ContainerGetAccessPolicyExceptionHeaders = { } } }; -var ContainerSetAccessPolicyHeaders = { +const ContainerSetAccessPolicyHeaders = { serializedName: "Container_setAccessPolicyHeaders", type: { name: "Composite", @@ -13742,7 +12007,7 @@ var ContainerSetAccessPolicyHeaders = { } } }; -var ContainerSetAccessPolicyExceptionHeaders = { +const ContainerSetAccessPolicyExceptionHeaders = { serializedName: "Container_setAccessPolicyExceptionHeaders", type: { name: "Composite", @@ -13758,7 +12023,7 @@ var ContainerSetAccessPolicyExceptionHeaders = { } } }; -var ContainerRestoreHeaders = { +const ContainerRestoreHeaders = { serializedName: "Container_restoreHeaders", type: { name: "Composite", @@ -13802,7 +12067,7 @@ var ContainerRestoreHeaders = { } } }; -var ContainerRestoreExceptionHeaders = { +const ContainerRestoreExceptionHeaders = { serializedName: "Container_restoreExceptionHeaders", type: { name: "Composite", @@ -13818,7 +12083,7 @@ var ContainerRestoreExceptionHeaders = { } } }; -var ContainerRenameHeaders = { +const ContainerRenameHeaders = { serializedName: "Container_renameHeaders", type: { name: "Composite", @@ -13862,7 +12127,7 @@ var ContainerRenameHeaders = { } } }; -var ContainerRenameExceptionHeaders = { +const ContainerRenameExceptionHeaders = { serializedName: "Container_renameExceptionHeaders", type: { name: "Composite", @@ -13878,7 +12143,7 @@ var ContainerRenameExceptionHeaders = { } } }; -var ContainerSubmitBatchHeaders = { +const ContainerSubmitBatchHeaders = { serializedName: "Container_submitBatchHeaders", type: { name: "Composite", @@ -13908,7 +12173,7 @@ var ContainerSubmitBatchHeaders = { } } }; -var ContainerSubmitBatchExceptionHeaders = { +const ContainerSubmitBatchExceptionHeaders = { serializedName: "Container_submitBatchExceptionHeaders", type: { name: "Composite", @@ -13924,7 +12189,7 @@ var ContainerSubmitBatchExceptionHeaders = { } } }; -var ContainerAcquireLeaseHeaders = { +const ContainerAcquireLeaseHeaders = { serializedName: "Container_acquireLeaseHeaders", type: { name: "Composite", @@ -13982,7 +12247,7 @@ var ContainerAcquireLeaseHeaders = { } } }; -var ContainerAcquireLeaseExceptionHeaders = { +const ContainerAcquireLeaseExceptionHeaders = { serializedName: "Container_acquireLeaseExceptionHeaders", type: { name: "Composite", @@ -13998,7 +12263,7 @@ var ContainerAcquireLeaseExceptionHeaders = { } } }; -var ContainerReleaseLeaseHeaders = { +const ContainerReleaseLeaseHeaders = { serializedName: "Container_releaseLeaseHeaders", type: { name: "Composite", @@ -14049,7 +12314,7 @@ var ContainerReleaseLeaseHeaders = { } } }; -var ContainerReleaseLeaseExceptionHeaders = { +const ContainerReleaseLeaseExceptionHeaders = { serializedName: "Container_releaseLeaseExceptionHeaders", type: { name: "Composite", @@ -14065,7 +12330,7 @@ var ContainerReleaseLeaseExceptionHeaders = { } } }; -var ContainerRenewLeaseHeaders = { +const ContainerRenewLeaseHeaders = { serializedName: "Container_renewLeaseHeaders", type: { name: "Composite", @@ -14123,7 +12388,7 @@ var ContainerRenewLeaseHeaders = { } } }; -var ContainerRenewLeaseExceptionHeaders = { +const ContainerRenewLeaseExceptionHeaders = { serializedName: "Container_renewLeaseExceptionHeaders", type: { name: "Composite", @@ -14139,7 +12404,7 @@ var ContainerRenewLeaseExceptionHeaders = { } } }; -var ContainerBreakLeaseHeaders = { +const ContainerBreakLeaseHeaders = { serializedName: "Container_breakLeaseHeaders", type: { name: "Composite", @@ -14197,7 +12462,7 @@ var ContainerBreakLeaseHeaders = { } } }; -var ContainerBreakLeaseExceptionHeaders = { +const ContainerBreakLeaseExceptionHeaders = { serializedName: "Container_breakLeaseExceptionHeaders", type: { name: "Composite", @@ -14213,7 +12478,7 @@ var ContainerBreakLeaseExceptionHeaders = { } } }; -var ContainerChangeLeaseHeaders = { +const ContainerChangeLeaseHeaders = { serializedName: "Container_changeLeaseHeaders", type: { name: "Composite", @@ -14271,7 +12536,7 @@ var ContainerChangeLeaseHeaders = { } } }; -var ContainerChangeLeaseExceptionHeaders = { +const ContainerChangeLeaseExceptionHeaders = { serializedName: "Container_changeLeaseExceptionHeaders", type: { name: "Composite", @@ -14287,7 +12552,7 @@ var ContainerChangeLeaseExceptionHeaders = { } } }; -var ContainerListBlobFlatSegmentHeaders = { +const ContainerListBlobFlatSegmentHeaders = { serializedName: "Container_listBlobFlatSegmentHeaders", type: { name: "Composite", @@ -14338,7 +12603,7 @@ var ContainerListBlobFlatSegmentHeaders = { } } }; -var ContainerListBlobFlatSegmentExceptionHeaders = { +const ContainerListBlobFlatSegmentExceptionHeaders = { serializedName: "Container_listBlobFlatSegmentExceptionHeaders", type: { name: "Composite", @@ -14354,7 +12619,7 @@ var ContainerListBlobFlatSegmentExceptionHeaders = { } } }; -var ContainerListBlobHierarchySegmentHeaders = { +const ContainerListBlobHierarchySegmentHeaders = { serializedName: "Container_listBlobHierarchySegmentHeaders", type: { name: "Composite", @@ -14405,7 +12670,7 @@ var ContainerListBlobHierarchySegmentHeaders = { } } }; -var ContainerListBlobHierarchySegmentExceptionHeaders = { +const ContainerListBlobHierarchySegmentExceptionHeaders = { serializedName: "Container_listBlobHierarchySegmentExceptionHeaders", type: { name: "Composite", @@ -14421,7 +12686,7 @@ var ContainerListBlobHierarchySegmentExceptionHeaders = { } } }; -var ContainerGetAccountInfoHeaders = { +const ContainerGetAccountInfoHeaders = { serializedName: "Container_getAccountInfoHeaders", type: { name: "Composite", @@ -14486,7 +12751,7 @@ var ContainerGetAccountInfoHeaders = { } } }; -var ContainerGetAccountInfoExceptionHeaders = { +const ContainerGetAccountInfoExceptionHeaders = { serializedName: "Container_getAccountInfoExceptionHeaders", type: { name: "Composite", @@ -14502,440 +12767,7 @@ var ContainerGetAccountInfoExceptionHeaders = { } } }; -var DirectoryCreateHeaders = { - serializedName: "Directory_createHeaders", - type: { - name: "Composite", - className: "DirectoryCreateHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - contentLength: { - serializedName: "content-length", - xmlName: "content-length", - type: { - name: "Number" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - } - } - } -}; -var DirectoryCreateExceptionHeaders = { - serializedName: "Directory_createExceptionHeaders", - type: { - name: "Composite", - className: "DirectoryCreateExceptionHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var DirectoryRenameHeaders = { - serializedName: "Directory_renameHeaders", - type: { - name: "Composite", - className: "DirectoryRenameHeaders", - modelProperties: { - marker: { - serializedName: "x-ms-continuation", - xmlName: "x-ms-continuation", - type: { - name: "String" - } - }, - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - contentLength: { - serializedName: "content-length", - xmlName: "content-length", - type: { - name: "Number" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - } - } - } -}; -var DirectoryRenameExceptionHeaders = { - serializedName: "Directory_renameExceptionHeaders", - type: { - name: "Composite", - className: "DirectoryRenameExceptionHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var DirectoryDeleteHeaders = { - serializedName: "Directory_deleteHeaders", - type: { - name: "Composite", - className: "DirectoryDeleteHeaders", - modelProperties: { - marker: { - serializedName: "x-ms-continuation", - xmlName: "x-ms-continuation", - type: { - name: "String" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - } - } - } -}; -var DirectoryDeleteExceptionHeaders = { - serializedName: "Directory_deleteExceptionHeaders", - type: { - name: "Composite", - className: "DirectoryDeleteExceptionHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var DirectorySetAccessControlHeaders = { - serializedName: "Directory_setAccessControlHeaders", - type: { - name: "Composite", - className: "DirectorySetAccessControlHeaders", - modelProperties: { - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var DirectorySetAccessControlExceptionHeaders = { - serializedName: "Directory_setAccessControlExceptionHeaders", - type: { - name: "Composite", - className: "DirectorySetAccessControlExceptionHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var DirectoryGetAccessControlHeaders = { - serializedName: "Directory_getAccessControlHeaders", - type: { - name: "Composite", - className: "DirectoryGetAccessControlHeaders", - modelProperties: { - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - xMsOwner: { - serializedName: "x-ms-owner", - xmlName: "x-ms-owner", - type: { - name: "String" - } - }, - xMsGroup: { - serializedName: "x-ms-group", - xmlName: "x-ms-group", - type: { - name: "String" - } - }, - xMsPermissions: { - serializedName: "x-ms-permissions", - xmlName: "x-ms-permissions", - type: { - name: "String" - } - }, - xMsAcl: { - serializedName: "x-ms-acl", - xmlName: "x-ms-acl", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var DirectoryGetAccessControlExceptionHeaders = { - serializedName: "Directory_getAccessControlExceptionHeaders", - type: { - name: "Composite", - className: "DirectoryGetAccessControlExceptionHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var BlobDownloadHeaders = { +const BlobDownloadHeaders = { serializedName: "Blob_downloadHeaders", type: { name: "Composite", @@ -15229,11 +13061,26 @@ var BlobDownloadHeaders = { name: "DateTimeRfc1123" } }, - contentCrc64: { - serializedName: "x-ms-content-crc64", - xmlName: "x-ms-content-crc64", + immutabilityPolicyExpiresOn: { + serializedName: "x-ms-immutability-policy-until-date", + xmlName: "x-ms-immutability-policy-until-date", type: { - name: "ByteArray" + name: "DateTimeRfc1123" + } + }, + immutabilityPolicyMode: { + serializedName: "x-ms-immutability-policy-mode", + xmlName: "x-ms-immutability-policy-mode", + type: { + name: "Enum", + allowedValues: ["Mutable", "Unlocked", "Locked"] + } + }, + legalHold: { + serializedName: "x-ms-legal-hold", + xmlName: "x-ms-legal-hold", + type: { + name: "Boolean" } }, errorCode: { @@ -15242,11 +13089,18 @@ var BlobDownloadHeaders = { type: { name: "String" } + }, + contentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } } } } }; -var BlobDownloadExceptionHeaders = { +const BlobDownloadExceptionHeaders = { serializedName: "Blob_downloadExceptionHeaders", type: { name: "Composite", @@ -15262,7 +13116,7 @@ var BlobDownloadExceptionHeaders = { } } }; -var BlobGetPropertiesHeaders = { +const BlobGetPropertiesHeaders = { serializedName: "Blob_getPropertiesHeaders", type: { name: "Composite", @@ -15606,6 +13460,28 @@ var BlobGetPropertiesHeaders = { name: "DateTimeRfc1123" } }, + immutabilityPolicyExpiresOn: { + serializedName: "x-ms-immutability-policy-until-date", + xmlName: "x-ms-immutability-policy-until-date", + type: { + name: "DateTimeRfc1123" + } + }, + immutabilityPolicyMode: { + serializedName: "x-ms-immutability-policy-mode", + xmlName: "x-ms-immutability-policy-mode", + type: { + name: "Enum", + allowedValues: ["Mutable", "Unlocked", "Locked"] + } + }, + legalHold: { + serializedName: "x-ms-legal-hold", + xmlName: "x-ms-legal-hold", + type: { + name: "Boolean" + } + }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", @@ -15616,7 +13492,7 @@ var BlobGetPropertiesHeaders = { } } }; -var BlobGetPropertiesExceptionHeaders = { +const BlobGetPropertiesExceptionHeaders = { serializedName: "Blob_getPropertiesExceptionHeaders", type: { name: "Composite", @@ -15632,7 +13508,7 @@ var BlobGetPropertiesExceptionHeaders = { } } }; -var BlobDeleteHeaders = { +const BlobDeleteHeaders = { serializedName: "Blob_deleteHeaders", type: { name: "Composite", @@ -15676,7 +13552,7 @@ var BlobDeleteHeaders = { } } }; -var BlobDeleteExceptionHeaders = { +const BlobDeleteExceptionHeaders = { serializedName: "Blob_deleteExceptionHeaders", type: { name: "Composite", @@ -15692,271 +13568,7 @@ var BlobDeleteExceptionHeaders = { } } }; -var BlobSetAccessControlHeaders = { - serializedName: "Blob_setAccessControlHeaders", - type: { - name: "Composite", - className: "BlobSetAccessControlHeaders", - modelProperties: { - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var BlobSetAccessControlExceptionHeaders = { - serializedName: "Blob_setAccessControlExceptionHeaders", - type: { - name: "Composite", - className: "BlobSetAccessControlExceptionHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var BlobGetAccessControlHeaders = { - serializedName: "Blob_getAccessControlHeaders", - type: { - name: "Composite", - className: "BlobGetAccessControlHeaders", - modelProperties: { - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - xMsOwner: { - serializedName: "x-ms-owner", - xmlName: "x-ms-owner", - type: { - name: "String" - } - }, - xMsGroup: { - serializedName: "x-ms-group", - xmlName: "x-ms-group", - type: { - name: "String" - } - }, - xMsPermissions: { - serializedName: "x-ms-permissions", - xmlName: "x-ms-permissions", - type: { - name: "String" - } - }, - xMsAcl: { - serializedName: "x-ms-acl", - xmlName: "x-ms-acl", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var BlobGetAccessControlExceptionHeaders = { - serializedName: "Blob_getAccessControlExceptionHeaders", - type: { - name: "Composite", - className: "BlobGetAccessControlExceptionHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var BlobRenameHeaders = { - serializedName: "Blob_renameHeaders", - type: { - name: "Composite", - className: "BlobRenameHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - contentLength: { - serializedName: "content-length", - xmlName: "content-length", - type: { - name: "Number" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - } - } - } -}; -var BlobRenameExceptionHeaders = { - serializedName: "Blob_renameExceptionHeaders", - type: { - name: "Composite", - className: "BlobRenameExceptionHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var BlobUndeleteHeaders = { +const BlobUndeleteHeaders = { serializedName: "Blob_undeleteHeaders", type: { name: "Composite", @@ -16000,7 +13612,7 @@ var BlobUndeleteHeaders = { } } }; -var BlobUndeleteExceptionHeaders = { +const BlobUndeleteExceptionHeaders = { serializedName: "Blob_undeleteExceptionHeaders", type: { name: "Composite", @@ -16016,7 +13628,7 @@ var BlobUndeleteExceptionHeaders = { } } }; -var BlobSetExpiryHeaders = { +const BlobSetExpiryHeaders = { serializedName: "Blob_setExpiryHeaders", type: { name: "Composite", @@ -16067,7 +13679,7 @@ var BlobSetExpiryHeaders = { } } }; -var BlobSetExpiryExceptionHeaders = { +const BlobSetExpiryExceptionHeaders = { serializedName: "Blob_setExpiryExceptionHeaders", type: { name: "Composite", @@ -16083,7 +13695,7 @@ var BlobSetExpiryExceptionHeaders = { } } }; -var BlobSetHttpHeadersHeaders = { +const BlobSetHttpHeadersHeaders = { serializedName: "Blob_setHttpHeadersHeaders", type: { name: "Composite", @@ -16148,7 +13760,7 @@ var BlobSetHttpHeadersHeaders = { } } }; -var BlobSetHttpHeadersExceptionHeaders = { +const BlobSetHttpHeadersExceptionHeaders = { serializedName: "Blob_setHttpHeadersExceptionHeaders", type: { name: "Composite", @@ -16164,7 +13776,188 @@ var BlobSetHttpHeadersExceptionHeaders = { } } }; -var BlobSetMetadataHeaders = { +const BlobSetImmutabilityPolicyHeaders = { + serializedName: "Blob_setImmutabilityPolicyHeaders", + type: { + name: "Composite", + className: "BlobSetImmutabilityPolicyHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + immutabilityPolicyExpiry: { + serializedName: "x-ms-immutability-policy-until-date", + xmlName: "x-ms-immutability-policy-until-date", + type: { + name: "DateTimeRfc1123" + } + }, + immutabilityPolicyMode: { + serializedName: "x-ms-immutability-policy-mode", + xmlName: "x-ms-immutability-policy-mode", + type: { + name: "Enum", + allowedValues: ["Mutable", "Unlocked", "Locked"] + } + } + } + } +}; +const BlobSetImmutabilityPolicyExceptionHeaders = { + serializedName: "Blob_setImmutabilityPolicyExceptionHeaders", + type: { + name: "Composite", + className: "BlobSetImmutabilityPolicyExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +const BlobDeleteImmutabilityPolicyHeaders = { + serializedName: "Blob_deleteImmutabilityPolicyHeaders", + type: { + name: "Composite", + className: "BlobDeleteImmutabilityPolicyHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } +}; +const BlobDeleteImmutabilityPolicyExceptionHeaders = { + serializedName: "Blob_deleteImmutabilityPolicyExceptionHeaders", + type: { + name: "Composite", + className: "BlobDeleteImmutabilityPolicyExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +const BlobSetLegalHoldHeaders = { + serializedName: "Blob_setLegalHoldHeaders", + type: { + name: "Composite", + className: "BlobSetLegalHoldHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + legalHold: { + serializedName: "x-ms-legal-hold", + xmlName: "x-ms-legal-hold", + type: { + name: "Boolean" + } + } + } + } +}; +const BlobSetLegalHoldExceptionHeaders = { + serializedName: "Blob_setLegalHoldExceptionHeaders", + type: { + name: "Composite", + className: "BlobSetLegalHoldExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +const BlobSetMetadataHeaders = { serializedName: "Blob_setMetadataHeaders", type: { name: "Composite", @@ -16250,7 +14043,7 @@ var BlobSetMetadataHeaders = { } } }; -var BlobSetMetadataExceptionHeaders = { +const BlobSetMetadataExceptionHeaders = { serializedName: "Blob_setMetadataExceptionHeaders", type: { name: "Composite", @@ -16266,7 +14059,7 @@ var BlobSetMetadataExceptionHeaders = { } } }; -var BlobAcquireLeaseHeaders = { +const BlobAcquireLeaseHeaders = { serializedName: "Blob_acquireLeaseHeaders", type: { name: "Composite", @@ -16324,7 +14117,7 @@ var BlobAcquireLeaseHeaders = { } } }; -var BlobAcquireLeaseExceptionHeaders = { +const BlobAcquireLeaseExceptionHeaders = { serializedName: "Blob_acquireLeaseExceptionHeaders", type: { name: "Composite", @@ -16340,7 +14133,7 @@ var BlobAcquireLeaseExceptionHeaders = { } } }; -var BlobReleaseLeaseHeaders = { +const BlobReleaseLeaseHeaders = { serializedName: "Blob_releaseLeaseHeaders", type: { name: "Composite", @@ -16391,7 +14184,7 @@ var BlobReleaseLeaseHeaders = { } } }; -var BlobReleaseLeaseExceptionHeaders = { +const BlobReleaseLeaseExceptionHeaders = { serializedName: "Blob_releaseLeaseExceptionHeaders", type: { name: "Composite", @@ -16407,7 +14200,7 @@ var BlobReleaseLeaseExceptionHeaders = { } } }; -var BlobRenewLeaseHeaders = { +const BlobRenewLeaseHeaders = { serializedName: "Blob_renewLeaseHeaders", type: { name: "Composite", @@ -16465,7 +14258,7 @@ var BlobRenewLeaseHeaders = { } } }; -var BlobRenewLeaseExceptionHeaders = { +const BlobRenewLeaseExceptionHeaders = { serializedName: "Blob_renewLeaseExceptionHeaders", type: { name: "Composite", @@ -16481,7 +14274,7 @@ var BlobRenewLeaseExceptionHeaders = { } } }; -var BlobChangeLeaseHeaders = { +const BlobChangeLeaseHeaders = { serializedName: "Blob_changeLeaseHeaders", type: { name: "Composite", @@ -16539,7 +14332,7 @@ var BlobChangeLeaseHeaders = { } } }; -var BlobChangeLeaseExceptionHeaders = { +const BlobChangeLeaseExceptionHeaders = { serializedName: "Blob_changeLeaseExceptionHeaders", type: { name: "Composite", @@ -16555,7 +14348,7 @@ var BlobChangeLeaseExceptionHeaders = { } } }; -var BlobBreakLeaseHeaders = { +const BlobBreakLeaseHeaders = { serializedName: "Blob_breakLeaseHeaders", type: { name: "Composite", @@ -16613,7 +14406,7 @@ var BlobBreakLeaseHeaders = { } } }; -var BlobBreakLeaseExceptionHeaders = { +const BlobBreakLeaseExceptionHeaders = { serializedName: "Blob_breakLeaseExceptionHeaders", type: { name: "Composite", @@ -16629,7 +14422,7 @@ var BlobBreakLeaseExceptionHeaders = { } } }; -var BlobCreateSnapshotHeaders = { +const BlobCreateSnapshotHeaders = { serializedName: "Blob_createSnapshotHeaders", type: { name: "Composite", @@ -16708,7 +14501,7 @@ var BlobCreateSnapshotHeaders = { } } }; -var BlobCreateSnapshotExceptionHeaders = { +const BlobCreateSnapshotExceptionHeaders = { serializedName: "Blob_createSnapshotExceptionHeaders", type: { name: "Composite", @@ -16724,7 +14517,7 @@ var BlobCreateSnapshotExceptionHeaders = { } } }; -var BlobStartCopyFromURLHeaders = { +const BlobStartCopyFromURLHeaders = { serializedName: "Blob_startCopyFromURLHeaders", type: { name: "Composite", @@ -16804,7 +14597,7 @@ var BlobStartCopyFromURLHeaders = { } } }; -var BlobStartCopyFromURLExceptionHeaders = { +const BlobStartCopyFromURLExceptionHeaders = { serializedName: "Blob_startCopyFromURLExceptionHeaders", type: { name: "Composite", @@ -16820,7 +14613,7 @@ var BlobStartCopyFromURLExceptionHeaders = { } } }; -var BlobCopyFromURLHeaders = { +const BlobCopyFromURLHeaders = { serializedName: "Blob_copyFromURLHeaders", type: { name: "Composite", @@ -16914,7 +14707,7 @@ var BlobCopyFromURLHeaders = { } } }; -var BlobCopyFromURLExceptionHeaders = { +const BlobCopyFromURLExceptionHeaders = { serializedName: "Blob_copyFromURLExceptionHeaders", type: { name: "Composite", @@ -16930,7 +14723,7 @@ var BlobCopyFromURLExceptionHeaders = { } } }; -var BlobAbortCopyFromURLHeaders = { +const BlobAbortCopyFromURLHeaders = { serializedName: "Blob_abortCopyFromURLHeaders", type: { name: "Composite", @@ -16974,7 +14767,7 @@ var BlobAbortCopyFromURLHeaders = { } } }; -var BlobAbortCopyFromURLExceptionHeaders = { +const BlobAbortCopyFromURLExceptionHeaders = { serializedName: "Blob_abortCopyFromURLExceptionHeaders", type: { name: "Composite", @@ -16990,7 +14783,7 @@ var BlobAbortCopyFromURLExceptionHeaders = { } } }; -var BlobSetTierHeaders = { +const BlobSetTierHeaders = { serializedName: "Blob_setTierHeaders", type: { name: "Composite", @@ -17027,7 +14820,7 @@ var BlobSetTierHeaders = { } } }; -var BlobSetTierExceptionHeaders = { +const BlobSetTierExceptionHeaders = { serializedName: "Blob_setTierExceptionHeaders", type: { name: "Composite", @@ -17043,7 +14836,7 @@ var BlobSetTierExceptionHeaders = { } } }; -var BlobGetAccountInfoHeaders = { +const BlobGetAccountInfoHeaders = { serializedName: "Blob_getAccountInfoHeaders", type: { name: "Composite", @@ -17108,7 +14901,7 @@ var BlobGetAccountInfoHeaders = { } } }; -var BlobGetAccountInfoExceptionHeaders = { +const BlobGetAccountInfoExceptionHeaders = { serializedName: "Blob_getAccountInfoExceptionHeaders", type: { name: "Composite", @@ -17124,7 +14917,7 @@ var BlobGetAccountInfoExceptionHeaders = { } } }; -var BlobQueryHeaders = { +const BlobQueryHeaders = { serializedName: "Blob_queryHeaders", type: { name: "Composite", @@ -17366,24 +15159,24 @@ var BlobQueryHeaders = { name: "ByteArray" } }, - contentCrc64: { - serializedName: "x-ms-content-crc64", - xmlName: "x-ms-content-crc64", - type: { - name: "ByteArray" - } - }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } + }, + contentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } } } } }; -var BlobQueryExceptionHeaders = { +const BlobQueryExceptionHeaders = { serializedName: "Blob_queryExceptionHeaders", type: { name: "Composite", @@ -17399,7 +15192,7 @@ var BlobQueryExceptionHeaders = { } } }; -var BlobGetTagsHeaders = { +const BlobGetTagsHeaders = { serializedName: "Blob_getTagsHeaders", type: { name: "Composite", @@ -17443,7 +15236,7 @@ var BlobGetTagsHeaders = { } } }; -var BlobGetTagsExceptionHeaders = { +const BlobGetTagsExceptionHeaders = { serializedName: "Blob_getTagsExceptionHeaders", type: { name: "Composite", @@ -17459,7 +15252,7 @@ var BlobGetTagsExceptionHeaders = { } } }; -var BlobSetTagsHeaders = { +const BlobSetTagsHeaders = { serializedName: "Blob_setTagsHeaders", type: { name: "Composite", @@ -17503,7 +15296,7 @@ var BlobSetTagsHeaders = { } } }; -var BlobSetTagsExceptionHeaders = { +const BlobSetTagsExceptionHeaders = { serializedName: "Blob_setTagsExceptionHeaders", type: { name: "Composite", @@ -17519,7 +15312,7 @@ var BlobSetTagsExceptionHeaders = { } } }; -var PageBlobCreateHeaders = { +const PageBlobCreateHeaders = { serializedName: "PageBlob_createHeaders", type: { name: "Composite", @@ -17612,7 +15405,7 @@ var PageBlobCreateHeaders = { } } }; -var PageBlobCreateExceptionHeaders = { +const PageBlobCreateExceptionHeaders = { serializedName: "PageBlob_createExceptionHeaders", type: { name: "Composite", @@ -17628,7 +15421,7 @@ var PageBlobCreateExceptionHeaders = { } } }; -var PageBlobUploadPagesHeaders = { +const PageBlobUploadPagesHeaders = { serializedName: "PageBlob_uploadPagesHeaders", type: { name: "Composite", @@ -17728,7 +15521,7 @@ var PageBlobUploadPagesHeaders = { } } }; -var PageBlobUploadPagesExceptionHeaders = { +const PageBlobUploadPagesExceptionHeaders = { serializedName: "PageBlob_uploadPagesExceptionHeaders", type: { name: "Composite", @@ -17744,7 +15537,7 @@ var PageBlobUploadPagesExceptionHeaders = { } } }; -var PageBlobClearPagesHeaders = { +const PageBlobClearPagesHeaders = { serializedName: "PageBlob_clearPagesHeaders", type: { name: "Composite", @@ -17823,7 +15616,7 @@ var PageBlobClearPagesHeaders = { } } }; -var PageBlobClearPagesExceptionHeaders = { +const PageBlobClearPagesExceptionHeaders = { serializedName: "PageBlob_clearPagesExceptionHeaders", type: { name: "Composite", @@ -17839,7 +15632,7 @@ var PageBlobClearPagesExceptionHeaders = { } } }; -var PageBlobUploadPagesFromURLHeaders = { +const PageBlobUploadPagesFromURLHeaders = { serializedName: "PageBlob_uploadPagesFromURLHeaders", type: { name: "Composite", @@ -17932,7 +15725,7 @@ var PageBlobUploadPagesFromURLHeaders = { } } }; -var PageBlobUploadPagesFromURLExceptionHeaders = { +const PageBlobUploadPagesFromURLExceptionHeaders = { serializedName: "PageBlob_uploadPagesFromURLExceptionHeaders", type: { name: "Composite", @@ -17948,7 +15741,7 @@ var PageBlobUploadPagesFromURLExceptionHeaders = { } } }; -var PageBlobGetPageRangesHeaders = { +const PageBlobGetPageRangesHeaders = { serializedName: "PageBlob_getPageRangesHeaders", type: { name: "Composite", @@ -18013,7 +15806,7 @@ var PageBlobGetPageRangesHeaders = { } } }; -var PageBlobGetPageRangesExceptionHeaders = { +const PageBlobGetPageRangesExceptionHeaders = { serializedName: "PageBlob_getPageRangesExceptionHeaders", type: { name: "Composite", @@ -18029,7 +15822,7 @@ var PageBlobGetPageRangesExceptionHeaders = { } } }; -var PageBlobGetPageRangesDiffHeaders = { +const PageBlobGetPageRangesDiffHeaders = { serializedName: "PageBlob_getPageRangesDiffHeaders", type: { name: "Composite", @@ -18094,7 +15887,7 @@ var PageBlobGetPageRangesDiffHeaders = { } } }; -var PageBlobGetPageRangesDiffExceptionHeaders = { +const PageBlobGetPageRangesDiffExceptionHeaders = { serializedName: "PageBlob_getPageRangesDiffExceptionHeaders", type: { name: "Composite", @@ -18110,7 +15903,7 @@ var PageBlobGetPageRangesDiffExceptionHeaders = { } } }; -var PageBlobResizeHeaders = { +const PageBlobResizeHeaders = { serializedName: "PageBlob_resizeHeaders", type: { name: "Composite", @@ -18175,7 +15968,7 @@ var PageBlobResizeHeaders = { } } }; -var PageBlobResizeExceptionHeaders = { +const PageBlobResizeExceptionHeaders = { serializedName: "PageBlob_resizeExceptionHeaders", type: { name: "Composite", @@ -18191,7 +15984,7 @@ var PageBlobResizeExceptionHeaders = { } } }; -var PageBlobUpdateSequenceNumberHeaders = { +const PageBlobUpdateSequenceNumberHeaders = { serializedName: "PageBlob_updateSequenceNumberHeaders", type: { name: "Composite", @@ -18256,7 +16049,7 @@ var PageBlobUpdateSequenceNumberHeaders = { } } }; -var PageBlobUpdateSequenceNumberExceptionHeaders = { +const PageBlobUpdateSequenceNumberExceptionHeaders = { serializedName: "PageBlob_updateSequenceNumberExceptionHeaders", type: { name: "Composite", @@ -18272,7 +16065,7 @@ var PageBlobUpdateSequenceNumberExceptionHeaders = { } } }; -var PageBlobCopyIncrementalHeaders = { +const PageBlobCopyIncrementalHeaders = { serializedName: "PageBlob_copyIncrementalHeaders", type: { name: "Composite", @@ -18345,7 +16138,7 @@ var PageBlobCopyIncrementalHeaders = { } } }; -var PageBlobCopyIncrementalExceptionHeaders = { +const PageBlobCopyIncrementalExceptionHeaders = { serializedName: "PageBlob_copyIncrementalExceptionHeaders", type: { name: "Composite", @@ -18361,7 +16154,7 @@ var PageBlobCopyIncrementalExceptionHeaders = { } } }; -var AppendBlobCreateHeaders = { +const AppendBlobCreateHeaders = { serializedName: "AppendBlob_createHeaders", type: { name: "Composite", @@ -18454,7 +16247,7 @@ var AppendBlobCreateHeaders = { } } }; -var AppendBlobCreateExceptionHeaders = { +const AppendBlobCreateExceptionHeaders = { serializedName: "AppendBlob_createExceptionHeaders", type: { name: "Composite", @@ -18470,7 +16263,7 @@ var AppendBlobCreateExceptionHeaders = { } } }; -var AppendBlobAppendBlockHeaders = { +const AppendBlobAppendBlockHeaders = { serializedName: "AppendBlob_appendBlockHeaders", type: { name: "Composite", @@ -18577,7 +16370,7 @@ var AppendBlobAppendBlockHeaders = { } } }; -var AppendBlobAppendBlockExceptionHeaders = { +const AppendBlobAppendBlockExceptionHeaders = { serializedName: "AppendBlob_appendBlockExceptionHeaders", type: { name: "Composite", @@ -18593,7 +16386,7 @@ var AppendBlobAppendBlockExceptionHeaders = { } } }; -var AppendBlobAppendBlockFromUrlHeaders = { +const AppendBlobAppendBlockFromUrlHeaders = { serializedName: "AppendBlob_appendBlockFromUrlHeaders", type: { name: "Composite", @@ -18693,7 +16486,7 @@ var AppendBlobAppendBlockFromUrlHeaders = { } } }; -var AppendBlobAppendBlockFromUrlExceptionHeaders = { +const AppendBlobAppendBlockFromUrlExceptionHeaders = { serializedName: "AppendBlob_appendBlockFromUrlExceptionHeaders", type: { name: "Composite", @@ -18709,7 +16502,7 @@ var AppendBlobAppendBlockFromUrlExceptionHeaders = { } } }; -var AppendBlobSealHeaders = { +const AppendBlobSealHeaders = { serializedName: "AppendBlob_sealHeaders", type: { name: "Composite", @@ -18767,7 +16560,7 @@ var AppendBlobSealHeaders = { } } }; -var AppendBlobSealExceptionHeaders = { +const AppendBlobSealExceptionHeaders = { serializedName: "AppendBlob_sealExceptionHeaders", type: { name: "Composite", @@ -18783,7 +16576,7 @@ var AppendBlobSealExceptionHeaders = { } } }; -var BlockBlobUploadHeaders = { +const BlockBlobUploadHeaders = { serializedName: "BlockBlob_uploadHeaders", type: { name: "Composite", @@ -18876,7 +16669,7 @@ var BlockBlobUploadHeaders = { } } }; -var BlockBlobUploadExceptionHeaders = { +const BlockBlobUploadExceptionHeaders = { serializedName: "BlockBlob_uploadExceptionHeaders", type: { name: "Composite", @@ -18892,7 +16685,7 @@ var BlockBlobUploadExceptionHeaders = { } } }; -var BlockBlobPutBlobFromUrlHeaders = { +const BlockBlobPutBlobFromUrlHeaders = { serializedName: "BlockBlob_putBlobFromUrlHeaders", type: { name: "Composite", @@ -18985,7 +16778,7 @@ var BlockBlobPutBlobFromUrlHeaders = { } } }; -var BlockBlobPutBlobFromUrlExceptionHeaders = { +const BlockBlobPutBlobFromUrlExceptionHeaders = { serializedName: "BlockBlob_putBlobFromUrlExceptionHeaders", type: { name: "Composite", @@ -19001,7 +16794,7 @@ var BlockBlobPutBlobFromUrlExceptionHeaders = { } } }; -var BlockBlobStageBlockHeaders = { +const BlockBlobStageBlockHeaders = { serializedName: "BlockBlob_stageBlockHeaders", type: { name: "Composite", @@ -19080,7 +16873,7 @@ var BlockBlobStageBlockHeaders = { } } }; -var BlockBlobStageBlockExceptionHeaders = { +const BlockBlobStageBlockExceptionHeaders = { serializedName: "BlockBlob_stageBlockExceptionHeaders", type: { name: "Composite", @@ -19096,7 +16889,7 @@ var BlockBlobStageBlockExceptionHeaders = { } } }; -var BlockBlobStageBlockFromURLHeaders = { +const BlockBlobStageBlockFromURLHeaders = { serializedName: "BlockBlob_stageBlockFromURLHeaders", type: { name: "Composite", @@ -19175,7 +16968,7 @@ var BlockBlobStageBlockFromURLHeaders = { } } }; -var BlockBlobStageBlockFromURLExceptionHeaders = { +const BlockBlobStageBlockFromURLExceptionHeaders = { serializedName: "BlockBlob_stageBlockFromURLExceptionHeaders", type: { name: "Composite", @@ -19191,7 +16984,7 @@ var BlockBlobStageBlockFromURLExceptionHeaders = { } } }; -var BlockBlobCommitBlockListHeaders = { +const BlockBlobCommitBlockListHeaders = { serializedName: "BlockBlob_commitBlockListHeaders", type: { name: "Composite", @@ -19291,7 +17084,7 @@ var BlockBlobCommitBlockListHeaders = { } } }; -var BlockBlobCommitBlockListExceptionHeaders = { +const BlockBlobCommitBlockListExceptionHeaders = { serializedName: "BlockBlob_commitBlockListExceptionHeaders", type: { name: "Composite", @@ -19307,7 +17100,7 @@ var BlockBlobCommitBlockListExceptionHeaders = { } } }; -var BlockBlobGetBlockListHeaders = { +const BlockBlobGetBlockListHeaders = { serializedName: "BlockBlob_getBlockListHeaders", type: { name: "Composite", @@ -19379,7 +17172,7 @@ var BlockBlobGetBlockListHeaders = { } } }; -var BlockBlobGetBlockListExceptionHeaders = { +const BlockBlobGetBlockListExceptionHeaders = { serializedName: "BlockBlob_getBlockListExceptionHeaders", type: { name: "Composite", @@ -19425,8 +17218,6 @@ var Mappers = /*#__PURE__*/Object.freeze({ ListBlobsHierarchySegmentResponse: ListBlobsHierarchySegmentResponse, BlobHierarchyListSegment: BlobHierarchyListSegment, BlobPrefix: BlobPrefix, - DataLakeStorageError: DataLakeStorageError, - DataLakeStorageErrorError: DataLakeStorageErrorError, BlockLookupList: BlockLookupList, BlockList: BlockList, Block: Block, @@ -19490,34 +17281,24 @@ var Mappers = /*#__PURE__*/Object.freeze({ ContainerListBlobHierarchySegmentExceptionHeaders: ContainerListBlobHierarchySegmentExceptionHeaders, ContainerGetAccountInfoHeaders: ContainerGetAccountInfoHeaders, ContainerGetAccountInfoExceptionHeaders: ContainerGetAccountInfoExceptionHeaders, - DirectoryCreateHeaders: DirectoryCreateHeaders, - DirectoryCreateExceptionHeaders: DirectoryCreateExceptionHeaders, - DirectoryRenameHeaders: DirectoryRenameHeaders, - DirectoryRenameExceptionHeaders: DirectoryRenameExceptionHeaders, - DirectoryDeleteHeaders: DirectoryDeleteHeaders, - DirectoryDeleteExceptionHeaders: DirectoryDeleteExceptionHeaders, - DirectorySetAccessControlHeaders: DirectorySetAccessControlHeaders, - DirectorySetAccessControlExceptionHeaders: DirectorySetAccessControlExceptionHeaders, - DirectoryGetAccessControlHeaders: DirectoryGetAccessControlHeaders, - DirectoryGetAccessControlExceptionHeaders: DirectoryGetAccessControlExceptionHeaders, BlobDownloadHeaders: BlobDownloadHeaders, BlobDownloadExceptionHeaders: BlobDownloadExceptionHeaders, BlobGetPropertiesHeaders: BlobGetPropertiesHeaders, BlobGetPropertiesExceptionHeaders: BlobGetPropertiesExceptionHeaders, BlobDeleteHeaders: BlobDeleteHeaders, BlobDeleteExceptionHeaders: BlobDeleteExceptionHeaders, - BlobSetAccessControlHeaders: BlobSetAccessControlHeaders, - BlobSetAccessControlExceptionHeaders: BlobSetAccessControlExceptionHeaders, - BlobGetAccessControlHeaders: BlobGetAccessControlHeaders, - BlobGetAccessControlExceptionHeaders: BlobGetAccessControlExceptionHeaders, - BlobRenameHeaders: BlobRenameHeaders, - BlobRenameExceptionHeaders: BlobRenameExceptionHeaders, BlobUndeleteHeaders: BlobUndeleteHeaders, BlobUndeleteExceptionHeaders: BlobUndeleteExceptionHeaders, BlobSetExpiryHeaders: BlobSetExpiryHeaders, BlobSetExpiryExceptionHeaders: BlobSetExpiryExceptionHeaders, BlobSetHttpHeadersHeaders: BlobSetHttpHeadersHeaders, BlobSetHttpHeadersExceptionHeaders: BlobSetHttpHeadersExceptionHeaders, + BlobSetImmutabilityPolicyHeaders: BlobSetImmutabilityPolicyHeaders, + BlobSetImmutabilityPolicyExceptionHeaders: BlobSetImmutabilityPolicyExceptionHeaders, + BlobDeleteImmutabilityPolicyHeaders: BlobDeleteImmutabilityPolicyHeaders, + BlobDeleteImmutabilityPolicyExceptionHeaders: BlobDeleteImmutabilityPolicyExceptionHeaders, + BlobSetLegalHoldHeaders: BlobSetLegalHoldHeaders, + BlobSetLegalHoldExceptionHeaders: BlobSetLegalHoldExceptionHeaders, BlobSetMetadataHeaders: BlobSetMetadataHeaders, BlobSetMetadataExceptionHeaders: BlobSetMetadataExceptionHeaders, BlobAcquireLeaseHeaders: BlobAcquireLeaseHeaders, @@ -19595,7 +17376,7 @@ var Mappers = /*#__PURE__*/Object.freeze({ * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ -var contentType = { +const contentType = { parameterPath: ["options", "contentType"], mapper: { defaultValue: "application/xml", @@ -19606,11 +17387,11 @@ var contentType = { } } }; -var blobServiceProperties = { +const blobServiceProperties = { parameterPath: "blobServiceProperties", mapper: BlobServiceProperties }; -var accept = { +const accept = { parameterPath: "accept", mapper: { defaultValue: "application/xml", @@ -19621,7 +17402,7 @@ var accept = { } } }; -var url = { +const url = { parameterPath: "url", mapper: { serializedName: "url", @@ -19633,7 +17414,7 @@ var url = { }, skipEncoding: true }; -var restype = { +const restype = { parameterPath: "restype", mapper: { defaultValue: "service", @@ -19644,7 +17425,7 @@ var restype = { } } }; -var comp = { +const comp = { parameterPath: "comp", mapper: { defaultValue: "properties", @@ -19655,7 +17436,7 @@ var comp = { } } }; -var timeoutInSeconds = { +const timeoutInSeconds = { parameterPath: ["options", "timeoutInSeconds"], mapper: { constraints: { @@ -19668,10 +17449,10 @@ var timeoutInSeconds = { } } }; -var version = { +const version = { parameterPath: "version", mapper: { - defaultValue: "2020-08-04", + defaultValue: "2020-10-02", isConstant: true, serializedName: "x-ms-version", type: { @@ -19679,7 +17460,7 @@ var version = { } } }; -var requestId = { +const requestId = { parameterPath: ["options", "requestId"], mapper: { serializedName: "x-ms-client-request-id", @@ -19689,7 +17470,7 @@ var requestId = { } } }; -var accept1 = { +const accept1 = { parameterPath: "accept", mapper: { defaultValue: "application/xml", @@ -19700,7 +17481,7 @@ var accept1 = { } } }; -var comp1 = { +const comp1 = { parameterPath: "comp", mapper: { defaultValue: "stats", @@ -19711,7 +17492,7 @@ var comp1 = { } } }; -var comp2 = { +const comp2 = { parameterPath: "comp", mapper: { defaultValue: "list", @@ -19722,7 +17503,7 @@ var comp2 = { } } }; -var prefix = { +const prefix = { parameterPath: ["options", "prefix"], mapper: { serializedName: "prefix", @@ -19732,7 +17513,7 @@ var prefix = { } } }; -var marker = { +const marker = { parameterPath: ["options", "marker"], mapper: { serializedName: "marker", @@ -19742,7 +17523,7 @@ var marker = { } } }; -var maxPageSize = { +const maxPageSize = { parameterPath: ["options", "maxPageSize"], mapper: { constraints: { @@ -19755,7 +17536,7 @@ var maxPageSize = { } } }; -var include = { +const include = { parameterPath: ["options", "include"], mapper: { serializedName: "include", @@ -19773,11 +17554,11 @@ var include = { }, collectionFormat: coreHttp.QueryCollectionFormat.Csv }; -var keyInfo = { +const keyInfo = { parameterPath: "keyInfo", mapper: KeyInfo }; -var comp3 = { +const comp3 = { parameterPath: "comp", mapper: { defaultValue: "userdelegationkey", @@ -19788,7 +17569,7 @@ var comp3 = { } } }; -var restype1 = { +const restype1 = { parameterPath: "restype", mapper: { defaultValue: "account", @@ -19799,7 +17580,7 @@ var restype1 = { } } }; -var body = { +const body = { parameterPath: "body", mapper: { serializedName: "body", @@ -19810,7 +17591,7 @@ var body = { } } }; -var comp4 = { +const comp4 = { parameterPath: "comp", mapper: { defaultValue: "batch", @@ -19821,7 +17602,7 @@ var comp4 = { } } }; -var contentLength = { +const contentLength = { parameterPath: "contentLength", mapper: { serializedName: "Content-Length", @@ -19832,7 +17613,7 @@ var contentLength = { } } }; -var multipartContentType = { +const multipartContentType = { parameterPath: "multipartContentType", mapper: { serializedName: "Content-Type", @@ -19843,7 +17624,7 @@ var multipartContentType = { } } }; -var comp5 = { +const comp5 = { parameterPath: "comp", mapper: { defaultValue: "blobs", @@ -19854,7 +17635,7 @@ var comp5 = { } } }; -var where = { +const where = { parameterPath: ["options", "where"], mapper: { serializedName: "where", @@ -19864,7 +17645,7 @@ var where = { } } }; -var restype2 = { +const restype2 = { parameterPath: "restype", mapper: { defaultValue: "container", @@ -19875,7 +17656,7 @@ var restype2 = { } } }; -var metadata = { +const metadata = { parameterPath: ["options", "metadata"], mapper: { serializedName: "x-ms-meta", @@ -19887,7 +17668,7 @@ var metadata = { headerCollectionPrefix: "x-ms-meta-" } }; -var access = { +const access = { parameterPath: ["options", "access"], mapper: { serializedName: "x-ms-blob-public-access", @@ -19898,7 +17679,7 @@ var access = { } } }; -var defaultEncryptionScope = { +const defaultEncryptionScope = { parameterPath: [ "options", "containerEncryptionScope", @@ -19912,7 +17693,7 @@ var defaultEncryptionScope = { } } }; -var preventEncryptionScopeOverride = { +const preventEncryptionScopeOverride = { parameterPath: [ "options", "containerEncryptionScope", @@ -19926,7 +17707,7 @@ var preventEncryptionScopeOverride = { } } }; -var leaseId = { +const leaseId = { parameterPath: ["options", "leaseAccessConditions", "leaseId"], mapper: { serializedName: "x-ms-lease-id", @@ -19936,7 +17717,7 @@ var leaseId = { } } }; -var ifModifiedSince = { +const ifModifiedSince = { parameterPath: ["options", "modifiedAccessConditions", "ifModifiedSince"], mapper: { serializedName: "If-Modified-Since", @@ -19946,7 +17727,7 @@ var ifModifiedSince = { } } }; -var ifUnmodifiedSince = { +const ifUnmodifiedSince = { parameterPath: ["options", "modifiedAccessConditions", "ifUnmodifiedSince"], mapper: { serializedName: "If-Unmodified-Since", @@ -19956,7 +17737,7 @@ var ifUnmodifiedSince = { } } }; -var comp6 = { +const comp6 = { parameterPath: "comp", mapper: { defaultValue: "metadata", @@ -19967,7 +17748,7 @@ var comp6 = { } } }; -var comp7 = { +const comp7 = { parameterPath: "comp", mapper: { defaultValue: "acl", @@ -19978,7 +17759,7 @@ var comp7 = { } } }; -var containerAcl = { +const containerAcl = { parameterPath: ["options", "containerAcl"], mapper: { serializedName: "containerAcl", @@ -19996,7 +17777,7 @@ var containerAcl = { } } }; -var comp8 = { +const comp8 = { parameterPath: "comp", mapper: { defaultValue: "undelete", @@ -20007,7 +17788,7 @@ var comp8 = { } } }; -var deletedContainerName = { +const deletedContainerName = { parameterPath: ["options", "deletedContainerName"], mapper: { serializedName: "x-ms-deleted-container-name", @@ -20017,7 +17798,7 @@ var deletedContainerName = { } } }; -var deletedContainerVersion = { +const deletedContainerVersion = { parameterPath: ["options", "deletedContainerVersion"], mapper: { serializedName: "x-ms-deleted-container-version", @@ -20027,7 +17808,7 @@ var deletedContainerVersion = { } } }; -var comp9 = { +const comp9 = { parameterPath: "comp", mapper: { defaultValue: "rename", @@ -20038,7 +17819,7 @@ var comp9 = { } } }; -var sourceContainerName = { +const sourceContainerName = { parameterPath: "sourceContainerName", mapper: { serializedName: "x-ms-source-container-name", @@ -20049,7 +17830,7 @@ var sourceContainerName = { } } }; -var sourceLeaseId = { +const sourceLeaseId = { parameterPath: ["options", "sourceLeaseId"], mapper: { serializedName: "x-ms-source-lease-id", @@ -20059,7 +17840,7 @@ var sourceLeaseId = { } } }; -var comp10 = { +const comp10 = { parameterPath: "comp", mapper: { defaultValue: "lease", @@ -20070,7 +17851,7 @@ var comp10 = { } } }; -var action = { +const action = { parameterPath: "action", mapper: { defaultValue: "acquire", @@ -20081,7 +17862,7 @@ var action = { } } }; -var duration = { +const duration = { parameterPath: ["options", "duration"], mapper: { serializedName: "x-ms-lease-duration", @@ -20091,7 +17872,7 @@ var duration = { } } }; -var proposedLeaseId = { +const proposedLeaseId = { parameterPath: ["options", "proposedLeaseId"], mapper: { serializedName: "x-ms-proposed-lease-id", @@ -20101,7 +17882,7 @@ var proposedLeaseId = { } } }; -var action1 = { +const action1 = { parameterPath: "action", mapper: { defaultValue: "release", @@ -20112,7 +17893,7 @@ var action1 = { } } }; -var leaseId1 = { +const leaseId1 = { parameterPath: "leaseId", mapper: { serializedName: "x-ms-lease-id", @@ -20123,7 +17904,7 @@ var leaseId1 = { } } }; -var action2 = { +const action2 = { parameterPath: "action", mapper: { defaultValue: "renew", @@ -20134,7 +17915,7 @@ var action2 = { } } }; -var action3 = { +const action3 = { parameterPath: "action", mapper: { defaultValue: "break", @@ -20145,7 +17926,7 @@ var action3 = { } } }; -var breakPeriod = { +const breakPeriod = { parameterPath: ["options", "breakPeriod"], mapper: { serializedName: "x-ms-lease-break-period", @@ -20155,7 +17936,7 @@ var breakPeriod = { } } }; -var action4 = { +const action4 = { parameterPath: "action", mapper: { defaultValue: "change", @@ -20166,7 +17947,7 @@ var action4 = { } } }; -var proposedLeaseId1 = { +const proposedLeaseId1 = { parameterPath: "proposedLeaseId", mapper: { serializedName: "x-ms-proposed-lease-id", @@ -20177,7 +17958,7 @@ var proposedLeaseId1 = { } } }; -var include1 = { +const include1 = { parameterPath: ["options", "include"], mapper: { serializedName: "include", @@ -20195,7 +17976,10 @@ var include1 = { "snapshots", "uncommittedblobs", "versions", - "tags" + "tags", + "immutabilitypolicy", + "legalhold", + "deletedwithversions" ] } } @@ -20203,7 +17987,7 @@ var include1 = { }, collectionFormat: coreHttp.QueryCollectionFormat.Csv }; -var delimiter = { +const delimiter = { parameterPath: "delimiter", mapper: { serializedName: "delimiter", @@ -20214,243 +17998,7 @@ var delimiter = { } } }; -var directoryProperties = { - parameterPath: ["options", "directoryProperties"], - mapper: { - serializedName: "x-ms-properties", - xmlName: "x-ms-properties", - type: { - name: "String" - } - } -}; -var posixPermissions = { - parameterPath: ["options", "posixPermissions"], - mapper: { - serializedName: "x-ms-permissions", - xmlName: "x-ms-permissions", - type: { - name: "String" - } - } -}; -var posixUmask = { - parameterPath: ["options", "posixUmask"], - mapper: { - serializedName: "x-ms-umask", - xmlName: "x-ms-umask", - type: { - name: "String" - } - } -}; -var cacheControl = { - parameterPath: ["options", "directoryHttpHeaders", "cacheControl"], - mapper: { - serializedName: "x-ms-cache-control", - xmlName: "x-ms-cache-control", - type: { - name: "String" - } - } -}; -var contentType1 = { - parameterPath: ["options", "directoryHttpHeaders", "contentType"], - mapper: { - serializedName: "x-ms-content-type", - xmlName: "x-ms-content-type", - type: { - name: "String" - } - } -}; -var contentEncoding = { - parameterPath: ["options", "directoryHttpHeaders", "contentEncoding"], - mapper: { - serializedName: "x-ms-content-encoding", - xmlName: "x-ms-content-encoding", - type: { - name: "String" - } - } -}; -var contentLanguage = { - parameterPath: ["options", "directoryHttpHeaders", "contentLanguage"], - mapper: { - serializedName: "x-ms-content-language", - xmlName: "x-ms-content-language", - type: { - name: "String" - } - } -}; -var contentDisposition = { - parameterPath: ["options", "directoryHttpHeaders", "contentDisposition"], - mapper: { - serializedName: "x-ms-content-disposition", - xmlName: "x-ms-content-disposition", - type: { - name: "String" - } - } -}; -var ifMatch = { - parameterPath: ["options", "modifiedAccessConditions", "ifMatch"], - mapper: { - serializedName: "If-Match", - xmlName: "If-Match", - type: { - name: "String" - } - } -}; -var ifNoneMatch = { - parameterPath: ["options", "modifiedAccessConditions", "ifNoneMatch"], - mapper: { - serializedName: "If-None-Match", - xmlName: "If-None-Match", - type: { - name: "String" - } - } -}; -var pathRenameMode = { - parameterPath: ["options", "pathRenameMode"], - mapper: { - serializedName: "mode", - xmlName: "mode", - type: { - name: "Enum", - allowedValues: ["legacy", "posix"] - } - } -}; -var renameSource = { - parameterPath: "renameSource", - mapper: { - serializedName: "x-ms-rename-source", - required: true, - xmlName: "x-ms-rename-source", - type: { - name: "String" - } - } -}; -var sourceIfModifiedSince = { - parameterPath: [ - "options", - "sourceModifiedAccessConditions", - "sourceIfModifiedSince" - ], - mapper: { - serializedName: "x-ms-source-if-modified-since", - xmlName: "x-ms-source-if-modified-since", - type: { - name: "DateTimeRfc1123" - } - } -}; -var sourceIfUnmodifiedSince = { - parameterPath: [ - "options", - "sourceModifiedAccessConditions", - "sourceIfUnmodifiedSince" - ], - mapper: { - serializedName: "x-ms-source-if-unmodified-since", - xmlName: "x-ms-source-if-unmodified-since", - type: { - name: "DateTimeRfc1123" - } - } -}; -var sourceIfMatch = { - parameterPath: ["options", "sourceModifiedAccessConditions", "sourceIfMatch"], - mapper: { - serializedName: "x-ms-source-if-match", - xmlName: "x-ms-source-if-match", - type: { - name: "String" - } - } -}; -var sourceIfNoneMatch = { - parameterPath: [ - "options", - "sourceModifiedAccessConditions", - "sourceIfNoneMatch" - ], - mapper: { - serializedName: "x-ms-source-if-none-match", - xmlName: "x-ms-source-if-none-match", - type: { - name: "String" - } - } -}; -var action5 = { - parameterPath: "action", - mapper: { - defaultValue: "setAccessControl", - isConstant: true, - serializedName: "action", - type: { - name: "String" - } - } -}; -var owner = { - parameterPath: ["options", "owner"], - mapper: { - serializedName: "x-ms-owner", - xmlName: "x-ms-owner", - type: { - name: "String" - } - } -}; -var group = { - parameterPath: ["options", "group"], - mapper: { - serializedName: "x-ms-group", - xmlName: "x-ms-group", - type: { - name: "String" - } - } -}; -var posixAcl = { - parameterPath: ["options", "posixAcl"], - mapper: { - serializedName: "x-ms-acl", - xmlName: "x-ms-acl", - type: { - name: "String" - } - } -}; -var action6 = { - parameterPath: "action", - mapper: { - defaultValue: "getAccessControl", - isConstant: true, - serializedName: "action", - type: { - name: "String" - } - } -}; -var upn = { - parameterPath: ["options", "upn"], - mapper: { - serializedName: "upn", - xmlName: "upn", - type: { - name: "Boolean" - } - } -}; -var snapshot = { +const snapshot = { parameterPath: ["options", "snapshot"], mapper: { serializedName: "snapshot", @@ -20460,7 +18008,7 @@ var snapshot = { } } }; -var versionId = { +const versionId = { parameterPath: ["options", "versionId"], mapper: { serializedName: "versionid", @@ -20470,7 +18018,7 @@ var versionId = { } } }; -var range = { +const range = { parameterPath: ["options", "range"], mapper: { serializedName: "x-ms-range", @@ -20480,7 +18028,7 @@ var range = { } } }; -var rangeGetContentMD5 = { +const rangeGetContentMD5 = { parameterPath: ["options", "rangeGetContentMD5"], mapper: { serializedName: "x-ms-range-get-content-md5", @@ -20490,7 +18038,7 @@ var rangeGetContentMD5 = { } } }; -var rangeGetContentCRC64 = { +const rangeGetContentCRC64 = { parameterPath: ["options", "rangeGetContentCRC64"], mapper: { serializedName: "x-ms-range-get-content-crc64", @@ -20500,7 +18048,7 @@ var rangeGetContentCRC64 = { } } }; -var encryptionKey = { +const encryptionKey = { parameterPath: ["options", "cpkInfo", "encryptionKey"], mapper: { serializedName: "x-ms-encryption-key", @@ -20510,7 +18058,7 @@ var encryptionKey = { } } }; -var encryptionKeySha256 = { +const encryptionKeySha256 = { parameterPath: ["options", "cpkInfo", "encryptionKeySha256"], mapper: { serializedName: "x-ms-encryption-key-sha256", @@ -20520,7 +18068,7 @@ var encryptionKeySha256 = { } } }; -var encryptionAlgorithm = { +const encryptionAlgorithm = { parameterPath: ["options", "encryptionAlgorithm"], mapper: { defaultValue: "AES256", @@ -20531,7 +18079,27 @@ var encryptionAlgorithm = { } } }; -var ifTags = { +const ifMatch = { + parameterPath: ["options", "modifiedAccessConditions", "ifMatch"], + mapper: { + serializedName: "If-Match", + xmlName: "If-Match", + type: { + name: "String" + } + } +}; +const ifNoneMatch = { + parameterPath: ["options", "modifiedAccessConditions", "ifNoneMatch"], + mapper: { + serializedName: "If-None-Match", + xmlName: "If-None-Match", + type: { + name: "String" + } + } +}; +const ifTags = { parameterPath: ["options", "modifiedAccessConditions", "ifTags"], mapper: { serializedName: "x-ms-if-tags", @@ -20541,7 +18109,7 @@ var ifTags = { } } }; -var deleteSnapshots = { +const deleteSnapshots = { parameterPath: ["options", "deleteSnapshots"], mapper: { serializedName: "x-ms-delete-snapshots", @@ -20552,7 +18120,7 @@ var deleteSnapshots = { } } }; -var blobDeleteType = { +const blobDeleteType = { parameterPath: ["options", "blobDeleteType"], mapper: { serializedName: "deletetype", @@ -20562,7 +18130,7 @@ var blobDeleteType = { } } }; -var comp11 = { +const comp11 = { parameterPath: "comp", mapper: { defaultValue: "expiry", @@ -20573,7 +18141,7 @@ var comp11 = { } } }; -var expiryOptions = { +const expiryOptions = { parameterPath: "expiryOptions", mapper: { serializedName: "x-ms-expiry-option", @@ -20584,7 +18152,7 @@ var expiryOptions = { } } }; -var expiresOn = { +const expiresOn = { parameterPath: ["options", "expiresOn"], mapper: { serializedName: "x-ms-expiry-time", @@ -20594,7 +18162,7 @@ var expiresOn = { } } }; -var blobCacheControl = { +const blobCacheControl = { parameterPath: ["options", "blobHttpHeaders", "blobCacheControl"], mapper: { serializedName: "x-ms-blob-cache-control", @@ -20604,7 +18172,7 @@ var blobCacheControl = { } } }; -var blobContentType = { +const blobContentType = { parameterPath: ["options", "blobHttpHeaders", "blobContentType"], mapper: { serializedName: "x-ms-blob-content-type", @@ -20614,7 +18182,7 @@ var blobContentType = { } } }; -var blobContentMD5 = { +const blobContentMD5 = { parameterPath: ["options", "blobHttpHeaders", "blobContentMD5"], mapper: { serializedName: "x-ms-blob-content-md5", @@ -20624,7 +18192,7 @@ var blobContentMD5 = { } } }; -var blobContentEncoding = { +const blobContentEncoding = { parameterPath: ["options", "blobHttpHeaders", "blobContentEncoding"], mapper: { serializedName: "x-ms-blob-content-encoding", @@ -20634,7 +18202,7 @@ var blobContentEncoding = { } } }; -var blobContentLanguage = { +const blobContentLanguage = { parameterPath: ["options", "blobHttpHeaders", "blobContentLanguage"], mapper: { serializedName: "x-ms-blob-content-language", @@ -20644,7 +18212,7 @@ var blobContentLanguage = { } } }; -var blobContentDisposition = { +const blobContentDisposition = { parameterPath: ["options", "blobHttpHeaders", "blobContentDisposition"], mapper: { serializedName: "x-ms-blob-content-disposition", @@ -20654,7 +18222,61 @@ var blobContentDisposition = { } } }; -var encryptionScope = { +const comp12 = { + parameterPath: "comp", + mapper: { + defaultValue: "immutabilityPolicies", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } +}; +const immutabilityPolicyExpiry = { + parameterPath: ["options", "immutabilityPolicyExpiry"], + mapper: { + serializedName: "x-ms-immutability-policy-until-date", + xmlName: "x-ms-immutability-policy-until-date", + type: { + name: "DateTimeRfc1123" + } + } +}; +const immutabilityPolicyMode = { + parameterPath: ["options", "immutabilityPolicyMode"], + mapper: { + serializedName: "x-ms-immutability-policy-mode", + xmlName: "x-ms-immutability-policy-mode", + type: { + name: "Enum", + allowedValues: ["Mutable", "Unlocked", "Locked"] + } + } +}; +const comp13 = { + parameterPath: "comp", + mapper: { + defaultValue: "legalhold", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } +}; +const legalHold = { + parameterPath: "legalHold", + mapper: { + serializedName: "x-ms-legal-hold", + required: true, + xmlName: "x-ms-legal-hold", + type: { + name: "Boolean" + } + } +}; +const encryptionScope = { parameterPath: ["options", "encryptionScope"], mapper: { serializedName: "x-ms-encryption-scope", @@ -20664,7 +18286,7 @@ var encryptionScope = { } } }; -var comp12 = { +const comp14 = { parameterPath: "comp", mapper: { defaultValue: "snapshot", @@ -20675,7 +18297,7 @@ var comp12 = { } } }; -var tier = { +const tier = { parameterPath: ["options", "tier"], mapper: { serializedName: "x-ms-access-tier", @@ -20701,7 +18323,7 @@ var tier = { } } }; -var rehydratePriority = { +const rehydratePriority = { parameterPath: ["options", "rehydratePriority"], mapper: { serializedName: "x-ms-rehydrate-priority", @@ -20712,7 +18334,59 @@ var rehydratePriority = { } } }; -var sourceIfTags = { +const sourceIfModifiedSince = { + parameterPath: [ + "options", + "sourceModifiedAccessConditions", + "sourceIfModifiedSince" + ], + mapper: { + serializedName: "x-ms-source-if-modified-since", + xmlName: "x-ms-source-if-modified-since", + type: { + name: "DateTimeRfc1123" + } + } +}; +const sourceIfUnmodifiedSince = { + parameterPath: [ + "options", + "sourceModifiedAccessConditions", + "sourceIfUnmodifiedSince" + ], + mapper: { + serializedName: "x-ms-source-if-unmodified-since", + xmlName: "x-ms-source-if-unmodified-since", + type: { + name: "DateTimeRfc1123" + } + } +}; +const sourceIfMatch = { + parameterPath: ["options", "sourceModifiedAccessConditions", "sourceIfMatch"], + mapper: { + serializedName: "x-ms-source-if-match", + xmlName: "x-ms-source-if-match", + type: { + name: "String" + } + } +}; +const sourceIfNoneMatch = { + parameterPath: [ + "options", + "sourceModifiedAccessConditions", + "sourceIfNoneMatch" + ], + mapper: { + serializedName: "x-ms-source-if-none-match", + xmlName: "x-ms-source-if-none-match", + type: { + name: "String" + } + } +}; +const sourceIfTags = { parameterPath: ["options", "sourceModifiedAccessConditions", "sourceIfTags"], mapper: { serializedName: "x-ms-source-if-tags", @@ -20722,7 +18396,7 @@ var sourceIfTags = { } } }; -var copySource = { +const copySource = { parameterPath: "copySource", mapper: { serializedName: "x-ms-copy-source", @@ -20733,7 +18407,7 @@ var copySource = { } } }; -var blobTagsString = { +const blobTagsString = { parameterPath: ["options", "blobTagsString"], mapper: { serializedName: "x-ms-tags", @@ -20743,7 +18417,7 @@ var blobTagsString = { } } }; -var sealBlob = { +const sealBlob = { parameterPath: ["options", "sealBlob"], mapper: { serializedName: "x-ms-seal-blob", @@ -20753,7 +18427,17 @@ var sealBlob = { } } }; -var xMsRequiresSync = { +const legalHold1 = { + parameterPath: ["options", "legalHold"], + mapper: { + serializedName: "x-ms-legal-hold", + xmlName: "x-ms-legal-hold", + type: { + name: "Boolean" + } + } +}; +const xMsRequiresSync = { parameterPath: "xMsRequiresSync", mapper: { defaultValue: "true", @@ -20764,7 +18448,7 @@ var xMsRequiresSync = { } } }; -var sourceContentMD5 = { +const sourceContentMD5 = { parameterPath: ["options", "sourceContentMD5"], mapper: { serializedName: "x-ms-source-content-md5", @@ -20774,7 +18458,17 @@ var sourceContentMD5 = { } } }; -var comp13 = { +const copySourceAuthorization = { + parameterPath: ["options", "copySourceAuthorization"], + mapper: { + serializedName: "x-ms-copy-source-authorization", + xmlName: "x-ms-copy-source-authorization", + type: { + name: "String" + } + } +}; +const comp15 = { parameterPath: "comp", mapper: { defaultValue: "copy", @@ -20785,7 +18479,7 @@ var comp13 = { } } }; -var copyActionAbortConstant = { +const copyActionAbortConstant = { parameterPath: "copyActionAbortConstant", mapper: { defaultValue: "abort", @@ -20796,7 +18490,7 @@ var copyActionAbortConstant = { } } }; -var copyId = { +const copyId = { parameterPath: "copyId", mapper: { serializedName: "copyid", @@ -20807,7 +18501,7 @@ var copyId = { } } }; -var comp14 = { +const comp16 = { parameterPath: "comp", mapper: { defaultValue: "tier", @@ -20818,7 +18512,7 @@ var comp14 = { } } }; -var tier1 = { +const tier1 = { parameterPath: "tier", mapper: { serializedName: "x-ms-access-tier", @@ -20845,11 +18539,11 @@ var tier1 = { } } }; -var queryRequest = { +const queryRequest = { parameterPath: ["options", "queryRequest"], mapper: QueryRequest }; -var comp15 = { +const comp17 = { parameterPath: "comp", mapper: { defaultValue: "query", @@ -20860,7 +18554,7 @@ var comp15 = { } } }; -var comp16 = { +const comp18 = { parameterPath: "comp", mapper: { defaultValue: "tags", @@ -20871,11 +18565,11 @@ var comp16 = { } } }; -var tags = { +const tags = { parameterPath: ["options", "tags"], mapper: BlobTags }; -var transactionalContentMD5 = { +const transactionalContentMD5 = { parameterPath: ["options", "transactionalContentMD5"], mapper: { serializedName: "Content-MD5", @@ -20885,7 +18579,7 @@ var transactionalContentMD5 = { } } }; -var transactionalContentCrc64 = { +const transactionalContentCrc64 = { parameterPath: ["options", "transactionalContentCrc64"], mapper: { serializedName: "x-ms-content-crc64", @@ -20895,7 +18589,7 @@ var transactionalContentCrc64 = { } } }; -var blobType = { +const blobType = { parameterPath: "blobType", mapper: { defaultValue: "PageBlob", @@ -20906,7 +18600,7 @@ var blobType = { } } }; -var blobContentLength = { +const blobContentLength = { parameterPath: "blobContentLength", mapper: { serializedName: "x-ms-blob-content-length", @@ -20917,7 +18611,7 @@ var blobContentLength = { } } }; -var blobSequenceNumber = { +const blobSequenceNumber = { parameterPath: ["options", "blobSequenceNumber"], mapper: { serializedName: "x-ms-blob-sequence-number", @@ -20927,7 +18621,7 @@ var blobSequenceNumber = { } } }; -var contentType2 = { +const contentType1 = { parameterPath: ["options", "contentType"], mapper: { defaultValue: "application/octet-stream", @@ -20938,7 +18632,7 @@ var contentType2 = { } } }; -var body1 = { +const body1 = { parameterPath: "body", mapper: { serializedName: "body", @@ -20949,7 +18643,7 @@ var body1 = { } } }; -var accept2 = { +const accept2 = { parameterPath: "accept", mapper: { defaultValue: "application/xml", @@ -20960,7 +18654,7 @@ var accept2 = { } } }; -var comp17 = { +const comp19 = { parameterPath: "comp", mapper: { defaultValue: "page", @@ -20971,7 +18665,7 @@ var comp17 = { } } }; -var pageWrite = { +const pageWrite = { parameterPath: "pageWrite", mapper: { defaultValue: "update", @@ -20982,7 +18676,7 @@ var pageWrite = { } } }; -var ifSequenceNumberLessThanOrEqualTo = { +const ifSequenceNumberLessThanOrEqualTo = { parameterPath: [ "options", "sequenceNumberAccessConditions", @@ -20996,7 +18690,7 @@ var ifSequenceNumberLessThanOrEqualTo = { } } }; -var ifSequenceNumberLessThan = { +const ifSequenceNumberLessThan = { parameterPath: [ "options", "sequenceNumberAccessConditions", @@ -21010,7 +18704,7 @@ var ifSequenceNumberLessThan = { } } }; -var ifSequenceNumberEqualTo = { +const ifSequenceNumberEqualTo = { parameterPath: [ "options", "sequenceNumberAccessConditions", @@ -21024,7 +18718,7 @@ var ifSequenceNumberEqualTo = { } } }; -var pageWrite1 = { +const pageWrite1 = { parameterPath: "pageWrite", mapper: { defaultValue: "clear", @@ -21035,7 +18729,7 @@ var pageWrite1 = { } } }; -var sourceUrl = { +const sourceUrl = { parameterPath: "sourceUrl", mapper: { serializedName: "x-ms-copy-source", @@ -21046,7 +18740,7 @@ var sourceUrl = { } } }; -var sourceRange = { +const sourceRange = { parameterPath: "sourceRange", mapper: { serializedName: "x-ms-source-range", @@ -21057,7 +18751,7 @@ var sourceRange = { } } }; -var sourceContentCrc64 = { +const sourceContentCrc64 = { parameterPath: ["options", "sourceContentCrc64"], mapper: { serializedName: "x-ms-source-content-crc64", @@ -21067,7 +18761,7 @@ var sourceContentCrc64 = { } } }; -var range1 = { +const range1 = { parameterPath: "range", mapper: { serializedName: "x-ms-range", @@ -21078,7 +18772,7 @@ var range1 = { } } }; -var comp18 = { +const comp20 = { parameterPath: "comp", mapper: { defaultValue: "pagelist", @@ -21089,7 +18783,7 @@ var comp18 = { } } }; -var prevsnapshot = { +const prevsnapshot = { parameterPath: ["options", "prevsnapshot"], mapper: { serializedName: "prevsnapshot", @@ -21099,7 +18793,7 @@ var prevsnapshot = { } } }; -var prevSnapshotUrl = { +const prevSnapshotUrl = { parameterPath: ["options", "prevSnapshotUrl"], mapper: { serializedName: "x-ms-previous-snapshot-url", @@ -21109,7 +18803,7 @@ var prevSnapshotUrl = { } } }; -var sequenceNumberAction = { +const sequenceNumberAction = { parameterPath: "sequenceNumberAction", mapper: { serializedName: "x-ms-sequence-number-action", @@ -21121,7 +18815,7 @@ var sequenceNumberAction = { } } }; -var comp19 = { +const comp21 = { parameterPath: "comp", mapper: { defaultValue: "incrementalcopy", @@ -21132,7 +18826,7 @@ var comp19 = { } } }; -var blobType1 = { +const blobType1 = { parameterPath: "blobType", mapper: { defaultValue: "AppendBlob", @@ -21143,7 +18837,7 @@ var blobType1 = { } } }; -var comp20 = { +const comp22 = { parameterPath: "comp", mapper: { defaultValue: "appendblock", @@ -21154,7 +18848,7 @@ var comp20 = { } } }; -var maxSize = { +const maxSize = { parameterPath: ["options", "appendPositionAccessConditions", "maxSize"], mapper: { serializedName: "x-ms-blob-condition-maxsize", @@ -21164,7 +18858,7 @@ var maxSize = { } } }; -var appendPosition = { +const appendPosition = { parameterPath: [ "options", "appendPositionAccessConditions", @@ -21178,7 +18872,7 @@ var appendPosition = { } } }; -var sourceRange1 = { +const sourceRange1 = { parameterPath: ["options", "sourceRange"], mapper: { serializedName: "x-ms-source-range", @@ -21188,7 +18882,7 @@ var sourceRange1 = { } } }; -var comp21 = { +const comp23 = { parameterPath: "comp", mapper: { defaultValue: "seal", @@ -21199,7 +18893,7 @@ var comp21 = { } } }; -var blobType2 = { +const blobType2 = { parameterPath: "blobType", mapper: { defaultValue: "BlockBlob", @@ -21210,7 +18904,7 @@ var blobType2 = { } } }; -var copySourceBlobProperties = { +const copySourceBlobProperties = { parameterPath: ["options", "copySourceBlobProperties"], mapper: { serializedName: "x-ms-copy-source-blob-properties", @@ -21220,7 +18914,7 @@ var copySourceBlobProperties = { } } }; -var comp22 = { +const comp24 = { parameterPath: "comp", mapper: { defaultValue: "block", @@ -21231,7 +18925,7 @@ var comp22 = { } } }; -var blockId = { +const blockId = { parameterPath: "blockId", mapper: { serializedName: "blockid", @@ -21242,11 +18936,11 @@ var blockId = { } } }; -var blocks = { +const blocks = { parameterPath: "blocks", mapper: BlockLookupList }; -var comp23 = { +const comp25 = { parameterPath: "comp", mapper: { defaultValue: "blocklist", @@ -21257,7 +18951,7 @@ var comp23 = { } } }; -var listType = { +const listType = { parameterPath: "listType", mapper: { defaultValue: "committed", @@ -21279,12 +18973,12 @@ var listType = { * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ /** Class representing a Service. */ -var Service = /** @class */ (function () { +class Service { /** * Initialize a new instance of the class Service class. * @param client Reference to the service client */ - function Service(client) { + constructor(client) { this.client = client; } /** @@ -21293,69 +18987,69 @@ var Service = /** @class */ (function () { * @param blobServiceProperties The StorageService properties. * @param options The options parameters. */ - Service.prototype.setProperties = function (blobServiceProperties, options) { - var operationArguments = { - blobServiceProperties: blobServiceProperties, + setProperties(blobServiceProperties, options) { + const operationArguments = { + blobServiceProperties, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setPropertiesOperationSpec); - }; + } /** * gets the properties of a storage account's Blob service, including properties for Storage Analytics * and CORS (Cross-Origin Resource Sharing) rules. * @param options The options parameters. */ - Service.prototype.getProperties = function (options) { - var operationArguments = { + getProperties(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getPropertiesOperationSpec); - }; + } /** * 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. * @param options The options parameters. */ - Service.prototype.getStatistics = function (options) { - var operationArguments = { + getStatistics(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getStatisticsOperationSpec); - }; + } /** * The List Containers Segment operation returns a list of the containers under the specified account * @param options The options parameters. */ - Service.prototype.listContainersSegment = function (options) { - var operationArguments = { + listContainersSegment(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, listContainersSegmentOperationSpec); - }; + } /** * Retrieves a user delegation key for the Blob service. This is only a valid operation when using * bearer token authentication. * @param keyInfo Key information * @param options The options parameters. */ - Service.prototype.getUserDelegationKey = function (keyInfo, options) { - var operationArguments = { - keyInfo: keyInfo, + getUserDelegationKey(keyInfo, options) { + const operationArguments = { + keyInfo, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getUserDelegationKeyOperationSpec); - }; + } /** * Returns the sku name and account kind * @param options The options parameters. */ - Service.prototype.getAccountInfo = function (options) { - var operationArguments = { + getAccountInfo(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getAccountInfoOperationSpec); - }; + } /** * The Batch operation allows multiple API calls to be embedded into a single HTTP request. * @param contentLength The length of the request. @@ -21364,32 +19058,31 @@ var Service = /** @class */ (function () { * @param body Initial data * @param options The options parameters. */ - Service.prototype.submitBatch = function (contentLength, multipartContentType, body, options) { - var operationArguments = { - contentLength: contentLength, - multipartContentType: multipartContentType, - body: body, + submitBatch(contentLength, multipartContentType, body, options) { + const operationArguments = { + contentLength, + multipartContentType, + body, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, submitBatchOperationSpec); - }; + } /** * 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 options The options parameters. */ - Service.prototype.filterBlobs = function (options) { - var operationArguments = { + filterBlobs(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, filterBlobsOperationSpec); - }; - return Service; -}()); + } +} // Operation Specifications -var xmlSerializer = new coreHttp.Serializer(Mappers, /* isXml */ true); -var setPropertiesOperationSpec = { +const xmlSerializer = new coreHttp.Serializer(Mappers, /* isXml */ true); +const setPropertiesOperationSpec = { path: "/", httpMethod: "PUT", responses: { @@ -21419,7 +19112,7 @@ var setPropertiesOperationSpec = { mediaType: "xml", serializer: xmlSerializer }; -var getPropertiesOperationSpec = { +const getPropertiesOperationSpec = { path: "/", httpMethod: "GET", responses: { @@ -21446,7 +19139,7 @@ var getPropertiesOperationSpec = { isXML: true, serializer: xmlSerializer }; -var getStatisticsOperationSpec = { +const getStatisticsOperationSpec = { path: "/", httpMethod: "GET", responses: { @@ -21473,7 +19166,7 @@ var getStatisticsOperationSpec = { isXML: true, serializer: xmlSerializer }; -var listContainersSegmentOperationSpec = { +const listContainersSegmentOperationSpec = { path: "/", httpMethod: "GET", responses: { @@ -21503,7 +19196,7 @@ var listContainersSegmentOperationSpec = { isXML: true, serializer: xmlSerializer }; -var getUserDelegationKeyOperationSpec = { +const getUserDelegationKeyOperationSpec = { path: "/", httpMethod: "POST", responses: { @@ -21534,7 +19227,7 @@ var getUserDelegationKeyOperationSpec = { mediaType: "xml", serializer: xmlSerializer }; -var getAccountInfoOperationSpec = { +const getAccountInfoOperationSpec = { path: "/", httpMethod: "GET", responses: { @@ -21552,7 +19245,7 @@ var getAccountInfoOperationSpec = { isXML: true, serializer: xmlSerializer }; -var submitBatchOperationSpec = { +const submitBatchOperationSpec = { path: "/", httpMethod: "POST", responses: { @@ -21584,7 +19277,7 @@ var submitBatchOperationSpec = { mediaType: "xml", serializer: xmlSerializer }; -var filterBlobsOperationSpec = { +const filterBlobsOperationSpec = { path: "/", httpMethod: "GET", responses: { @@ -21622,12 +19315,12 @@ var filterBlobsOperationSpec = { * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ /** Class representing a Container. */ -var Container = /** @class */ (function () { +class Container { /** * Initialize a new instance of the class Container class. * @param client Reference to the service client */ - function Container(client) { + constructor(client) { this.client = client; } /** @@ -21635,88 +19328,88 @@ var Container = /** @class */ (function () { * exists, the operation fails * @param options The options parameters. */ - Container.prototype.create = function (options) { - var operationArguments = { + create(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, createOperationSpec); - }; + } /** * returns all user-defined metadata and system properties for the specified container. The data * returned does not include the container's list of blobs * @param options The options parameters. */ - Container.prototype.getProperties = function (options) { - var operationArguments = { + getProperties(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getPropertiesOperationSpec$1); - }; + } /** * operation marks the specified container for deletion. The container and any blobs contained within * it are later deleted during garbage collection * @param options The options parameters. */ - Container.prototype.delete = function (options) { - var operationArguments = { + delete(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, deleteOperationSpec); - }; + } /** * operation sets one or more user-defined name-value pairs for the specified container. * @param options The options parameters. */ - Container.prototype.setMetadata = function (options) { - var operationArguments = { + setMetadata(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setMetadataOperationSpec); - }; + } /** * gets the permissions for the specified container. The permissions indicate whether container data * may be accessed publicly. * @param options The options parameters. */ - Container.prototype.getAccessPolicy = function (options) { - var operationArguments = { + getAccessPolicy(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getAccessPolicyOperationSpec); - }; + } /** * sets the permissions for the specified container. The permissions indicate whether blobs in a * container may be accessed publicly. * @param options The options parameters. */ - Container.prototype.setAccessPolicy = function (options) { - var operationArguments = { + setAccessPolicy(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setAccessPolicyOperationSpec); - }; + } /** * Restores a previously-deleted container. * @param options The options parameters. */ - Container.prototype.restore = function (options) { - var operationArguments = { + restore(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, restoreOperationSpec); - }; + } /** * Renames an existing container. * @param sourceContainerName Required. Specifies the name of the container to rename. * @param options The options parameters. */ - Container.prototype.rename = function (sourceContainerName, options) { - var operationArguments = { - sourceContainerName: sourceContainerName, + rename(sourceContainerName, options) { + const operationArguments = { + sourceContainerName, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, renameOperationSpec); - }; + } /** * The Batch operation allows multiple API calls to be embedded into a single HTTP request. * @param contentLength The length of the request. @@ -21725,63 +19418,63 @@ var Container = /** @class */ (function () { * @param body Initial data * @param options The options parameters. */ - Container.prototype.submitBatch = function (contentLength, multipartContentType, body, options) { - var operationArguments = { - contentLength: contentLength, - multipartContentType: multipartContentType, - body: body, + submitBatch(contentLength, multipartContentType, body, options) { + const operationArguments = { + contentLength, + multipartContentType, + body, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, submitBatchOperationSpec$1); - }; + } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param options The options parameters. */ - Container.prototype.acquireLease = function (options) { - var operationArguments = { + acquireLease(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, acquireLeaseOperationSpec); - }; + } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ - Container.prototype.releaseLease = function (leaseId, options) { - var operationArguments = { - leaseId: leaseId, + releaseLease(leaseId, options) { + const operationArguments = { + leaseId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, releaseLeaseOperationSpec); - }; + } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ - Container.prototype.renewLease = function (leaseId, options) { - var operationArguments = { - leaseId: leaseId, + renewLease(leaseId, options) { + const operationArguments = { + leaseId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, renewLeaseOperationSpec); - }; + } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param options The options parameters. */ - Container.prototype.breakLease = function (options) { - var operationArguments = { + breakLease(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, breakLeaseOperationSpec); - }; + } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite @@ -21791,24 +19484,24 @@ var Container = /** @class */ (function () { * (String) for a list of valid GUID string formats. * @param options The options parameters. */ - Container.prototype.changeLease = function (leaseId, proposedLeaseId, options) { - var operationArguments = { - leaseId: leaseId, - proposedLeaseId: proposedLeaseId, + changeLease(leaseId, proposedLeaseId, options) { + const operationArguments = { + leaseId, + proposedLeaseId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, changeLeaseOperationSpec); - }; + } /** * [Update] The List Blobs operation returns a list of the blobs under the specified container * @param options The options parameters. */ - Container.prototype.listBlobFlatSegment = function (options) { - var operationArguments = { + listBlobFlatSegment(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, listBlobFlatSegmentOperationSpec); - }; + } /** * [Update] The List Blobs operation returns a list of the blobs under the specified container * @param delimiter When the request includes this parameter, the operation returns a BlobPrefix @@ -21817,28 +19510,27 @@ var Container = /** @class */ (function () { * character or a string. * @param options The options parameters. */ - Container.prototype.listBlobHierarchySegment = function (delimiter, options) { - var operationArguments = { - delimiter: delimiter, + listBlobHierarchySegment(delimiter, options) { + const operationArguments = { + delimiter, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, listBlobHierarchySegmentOperationSpec); - }; + } /** * Returns the sku name and account kind * @param options The options parameters. */ - Container.prototype.getAccountInfo = function (options) { - var operationArguments = { + getAccountInfo(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getAccountInfoOperationSpec$1); - }; - return Container; -}()); + } +} // Operation Specifications -var xmlSerializer$1 = new coreHttp.Serializer(Mappers, /* isXml */ true); -var createOperationSpec = { +const xmlSerializer$1 = new coreHttp.Serializer(Mappers, /* isXml */ true); +const createOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { @@ -21864,7 +19556,7 @@ var createOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var getPropertiesOperationSpec$1 = { +const getPropertiesOperationSpec$1 = { path: "/{containerName}", httpMethod: "GET", responses: { @@ -21887,7 +19579,7 @@ var getPropertiesOperationSpec$1 = { isXML: true, serializer: xmlSerializer$1 }; -var deleteOperationSpec = { +const deleteOperationSpec = { path: "/{containerName}", httpMethod: "DELETE", responses: { @@ -21912,7 +19604,7 @@ var deleteOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var setMetadataOperationSpec = { +const setMetadataOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { @@ -21941,7 +19633,7 @@ var setMetadataOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var getAccessPolicyOperationSpec = { +const getAccessPolicyOperationSpec = { path: "/{containerName}", httpMethod: "GET", responses: { @@ -21980,7 +19672,7 @@ var getAccessPolicyOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var setAccessPolicyOperationSpec = { +const setAccessPolicyOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { @@ -22014,7 +19706,7 @@ var setAccessPolicyOperationSpec = { mediaType: "xml", serializer: xmlSerializer$1 }; -var restoreOperationSpec = { +const restoreOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { @@ -22042,7 +19734,7 @@ var restoreOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var renameOperationSpec = { +const renameOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { @@ -22070,7 +19762,7 @@ var renameOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var submitBatchOperationSpec$1 = { +const submitBatchOperationSpec$1 = { path: "/{containerName}", httpMethod: "POST", responses: { @@ -22106,7 +19798,7 @@ var submitBatchOperationSpec$1 = { mediaType: "xml", serializer: xmlSerializer$1 }; -var acquireLeaseOperationSpec = { +const acquireLeaseOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { @@ -22137,7 +19829,7 @@ var acquireLeaseOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var releaseLeaseOperationSpec = { +const releaseLeaseOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { @@ -22167,7 +19859,7 @@ var releaseLeaseOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var renewLeaseOperationSpec = { +const renewLeaseOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { @@ -22197,7 +19889,7 @@ var renewLeaseOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var breakLeaseOperationSpec = { +const breakLeaseOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { @@ -22227,7 +19919,7 @@ var breakLeaseOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var changeLeaseOperationSpec = { +const changeLeaseOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { @@ -22258,7 +19950,7 @@ var changeLeaseOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var listBlobFlatSegmentOperationSpec = { +const listBlobFlatSegmentOperationSpec = { path: "/{containerName}", httpMethod: "GET", responses: { @@ -22289,7 +19981,7 @@ var listBlobFlatSegmentOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var listBlobHierarchySegmentOperationSpec = { +const listBlobHierarchySegmentOperationSpec = { path: "/{containerName}", httpMethod: "GET", responses: { @@ -22321,7 +20013,7 @@ var listBlobHierarchySegmentOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var getAccountInfoOperationSpec$1 = { +const getAccountInfoOperationSpec$1 = { path: "/{containerName}", httpMethod: "GET", responses: { @@ -22348,12 +20040,12 @@ var getAccountInfoOperationSpec$1 = { * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ /** Class representing a Blob. */ -var Blob$1 = /** @class */ (function () { +class Blob$1 { /** * Initialize a new instance of the class Blob class. * @param client Reference to the service client */ - function Blob(client) { + constructor(client) { this.client = client; } /** @@ -22361,23 +20053,23 @@ var Blob$1 = /** @class */ (function () { * properties. You can also call Download to read a snapshot. * @param options The options parameters. */ - Blob.prototype.download = function (options) { - var operationArguments = { + download(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, downloadOperationSpec); - }; + } /** * The Get Properties operation returns all user-defined metadata, standard HTTP properties, and system * properties for the blob. It does not return the content of the blob. * @param options The options parameters. */ - Blob.prototype.getProperties = function (options) { - var operationArguments = { + getProperties(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getPropertiesOperationSpec$2); - }; + } /** * If the storage account's soft delete feature is disabled then, when a blob is deleted, it is * permanently removed from the storage account. If the storage account's soft delete feature is @@ -22393,130 +20085,124 @@ var Blob$1 = /** @class */ (function () { * (ResourceNotFound). * @param options The options parameters. */ - Blob.prototype.delete = function (options) { - var operationArguments = { + delete(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, deleteOperationSpec$1); - }; - /** - * Set the owner, group, permissions, or access control list for a blob. - * @param options The options parameters. - */ - Blob.prototype.setAccessControl = function (options) { - var operationArguments = { - options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) - }; - return this.client.sendOperationRequest(operationArguments, setAccessControlOperationSpec); - }; - /** - * Get the owner, group, permissions, or access control list for a blob. - * @param options The options parameters. - */ - Blob.prototype.getAccessControl = function (options) { - var operationArguments = { - options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) - }; - return this.client.sendOperationRequest(operationArguments, getAccessControlOperationSpec); - }; - /** - * Rename a blob/file. By default, the destination is overwritten and if the destination already - * exists and has a lease the lease is broken. This operation supports conditional HTTP requests. For - * more information, see [Specifying Conditional Headers for Blob Service - * Operations](https://docs.microsoft.com/en-us/rest/api/storageservices/specifying-conditional-headers-for-blob-service-operations). - * To fail if the destination already exists, use a conditional request with If-None-Match: "*". - * @param renameSource The file or directory to be renamed. The value must have the following format: - * "/{filesysystem}/{path}". If "x-ms-properties" is specified, the properties will overwrite the - * existing properties; otherwise, the existing properties will be preserved. - * @param options The options parameters. - */ - Blob.prototype.rename = function (renameSource, options) { - var operationArguments = { - renameSource: renameSource, - options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) - }; - return this.client.sendOperationRequest(operationArguments, renameOperationSpec$1); - }; + } /** * Undelete a blob that was previously soft deleted * @param options The options parameters. */ - Blob.prototype.undelete = function (options) { - var operationArguments = { + undelete(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, undeleteOperationSpec); - }; + } /** * Sets the time a blob will expire and be deleted. * @param expiryOptions Required. Indicates mode of the expiry time * @param options The options parameters. */ - Blob.prototype.setExpiry = function (expiryOptions, options) { - var operationArguments = { - expiryOptions: expiryOptions, + setExpiry(expiryOptions, options) { + const operationArguments = { + expiryOptions, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setExpiryOperationSpec); - }; + } /** * The Set HTTP Headers operation sets system properties on the blob * @param options The options parameters. */ - Blob.prototype.setHttpHeaders = function (options) { - var operationArguments = { + setHttpHeaders(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setHttpHeadersOperationSpec); - }; + } + /** + * The Set Immutability Policy operation sets the immutability policy on the blob + * @param options The options parameters. + */ + setImmutabilityPolicy(options) { + const operationArguments = { + options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) + }; + return this.client.sendOperationRequest(operationArguments, setImmutabilityPolicyOperationSpec); + } + /** + * The Delete Immutability Policy operation deletes the immutability policy on the blob + * @param options The options parameters. + */ + deleteImmutabilityPolicy(options) { + const operationArguments = { + options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) + }; + return this.client.sendOperationRequest(operationArguments, deleteImmutabilityPolicyOperationSpec); + } + /** + * The Set Legal Hold operation sets a legal hold on the blob. + * @param legalHold Specified if a legal hold should be set on the blob. + * @param options The options parameters. + */ + setLegalHold(legalHold, options) { + const operationArguments = { + legalHold, + options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) + }; + return this.client.sendOperationRequest(operationArguments, setLegalHoldOperationSpec); + } /** * The Set Blob Metadata operation sets user-defined metadata for the specified blob as one or more * name-value pairs * @param options The options parameters. */ - Blob.prototype.setMetadata = function (options) { - var operationArguments = { + setMetadata(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setMetadataOperationSpec$1); - }; + } /** * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete * operations * @param options The options parameters. */ - Blob.prototype.acquireLease = function (options) { - var operationArguments = { + acquireLease(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, acquireLeaseOperationSpec$1); - }; + } /** * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete * operations * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ - Blob.prototype.releaseLease = function (leaseId, options) { - var operationArguments = { - leaseId: leaseId, + releaseLease(leaseId, options) { + const operationArguments = { + leaseId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, releaseLeaseOperationSpec$1); - }; + } /** * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete * operations * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ - Blob.prototype.renewLease = function (leaseId, options) { - var operationArguments = { - leaseId: leaseId, + renewLease(leaseId, options) { + const operationArguments = { + leaseId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, renewLeaseOperationSpec$1); - }; + } /** * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete * operations @@ -22526,35 +20212,35 @@ var Blob$1 = /** @class */ (function () { * (String) for a list of valid GUID string formats. * @param options The options parameters. */ - Blob.prototype.changeLease = function (leaseId, proposedLeaseId, options) { - var operationArguments = { - leaseId: leaseId, - proposedLeaseId: proposedLeaseId, + changeLease(leaseId, proposedLeaseId, options) { + const operationArguments = { + leaseId, + proposedLeaseId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, changeLeaseOperationSpec$1); - }; + } /** * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete * operations * @param options The options parameters. */ - Blob.prototype.breakLease = function (options) { - var operationArguments = { + breakLease(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, breakLeaseOperationSpec$1); - }; + } /** * The Create Snapshot operation creates a read-only snapshot of a blob * @param options The options parameters. */ - Blob.prototype.createSnapshot = function (options) { - var operationArguments = { + createSnapshot(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, createSnapshotOperationSpec); - }; + } /** * The Start Copy From URL operation copies a blob or an internet resource to a new blob. * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to @@ -22563,13 +20249,13 @@ var Blob$1 = /** @class */ (function () { * access signature. * @param options The options parameters. */ - Blob.prototype.startCopyFromURL = function (copySource, options) { - var operationArguments = { - copySource: copySource, + startCopyFromURL(copySource, options) { + const operationArguments = { + copySource, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, startCopyFromURLOperationSpec); - }; + } /** * The Copy From URL operation copies a blob or an internet resource to a new blob. It will not return * a response until the copy is complete. @@ -22579,13 +20265,13 @@ var Blob$1 = /** @class */ (function () { * access signature. * @param options The options parameters. */ - Blob.prototype.copyFromURL = function (copySource, options) { - var operationArguments = { - copySource: copySource, + copyFromURL(copySource, options) { + const operationArguments = { + copySource, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, copyFromURLOperationSpec); - }; + } /** * The Abort Copy From URL operation aborts a pending Copy From URL operation, and leaves a destination * blob with zero length and full metadata. @@ -22593,13 +20279,13 @@ var Blob$1 = /** @class */ (function () { * operation. * @param options The options parameters. */ - Blob.prototype.abortCopyFromURL = function (copyId, options) { - var operationArguments = { - copyId: copyId, + abortCopyFromURL(copyId, options) { + const operationArguments = { + copyId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, abortCopyFromURLOperationSpec); - }; + } /** * The Set Tier operation sets the tier on a blob. The operation is allowed on a page blob in a premium * storage account and on a block blob in a blob storage account (locally redundant storage only). A @@ -22609,59 +20295,58 @@ var Blob$1 = /** @class */ (function () { * @param tier Indicates the tier to be set on the blob. * @param options The options parameters. */ - Blob.prototype.setTier = function (tier, options) { - var operationArguments = { - tier: tier, + setTier(tier, options) { + const operationArguments = { + tier, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setTierOperationSpec); - }; + } /** * Returns the sku name and account kind * @param options The options parameters. */ - Blob.prototype.getAccountInfo = function (options) { - var operationArguments = { + getAccountInfo(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getAccountInfoOperationSpec$2); - }; + } /** * The Query operation enables users to select/project on blob data by providing simple query * expressions. * @param options The options parameters. */ - Blob.prototype.query = function (options) { - var operationArguments = { + query(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, queryOperationSpec); - }; + } /** * The Get Tags operation enables users to get the tags associated with a blob. * @param options The options parameters. */ - Blob.prototype.getTags = function (options) { - var operationArguments = { + getTags(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getTagsOperationSpec); - }; + } /** * The Set Tags operation enables users to set tags on a blob. * @param options The options parameters. */ - Blob.prototype.setTags = function (options) { - var operationArguments = { + setTags(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setTagsOperationSpec); - }; - return Blob; -}()); + } +} // Operation Specifications -var xmlSerializer$2 = new coreHttp.Serializer(Mappers, /* isXml */ true); -var downloadOperationSpec = { +const xmlSerializer$2 = new coreHttp.Serializer(Mappers, /* isXml */ true); +const downloadOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { @@ -22697,20 +20382,20 @@ var downloadOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, range, rangeGetContentMD5, rangeGetContentCRC64, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags ], isXML: true, serializer: xmlSerializer$2 }; -var getPropertiesOperationSpec$2 = { +const getPropertiesOperationSpec$2 = { path: "/{containerName}/{blob}", httpMethod: "HEAD", responses: { @@ -22735,17 +20420,17 @@ var getPropertiesOperationSpec$2 = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags ], isXML: true, serializer: xmlSerializer$2 }; -var deleteOperationSpec$1 = { +const deleteOperationSpec$1 = { path: "/{containerName}/{blob}", httpMethod: "DELETE", responses: { @@ -22779,110 +20464,7 @@ var deleteOperationSpec$1 = { isXML: true, serializer: xmlSerializer$2 }; -var setAccessControlOperationSpec = { - path: "/{filesystem}/{path}", - httpMethod: "PATCH", - responses: { - 200: { - headersMapper: BlobSetAccessControlHeaders - }, - default: { - bodyMapper: DataLakeStorageError, - headersMapper: BlobSetAccessControlExceptionHeaders - } - }, - queryParameters: [timeoutInSeconds, action5], - urlParameters: [url], - headerParameters: [ - version, - requestId, - accept1, - leaseId, - ifModifiedSince, - ifUnmodifiedSince, - posixPermissions, - ifMatch, - ifNoneMatch, - owner, - group, - posixAcl - ], - isXML: true, - serializer: xmlSerializer$2 -}; -var getAccessControlOperationSpec = { - path: "/{filesystem}/{path}", - httpMethod: "HEAD", - responses: { - 200: { - headersMapper: BlobGetAccessControlHeaders - }, - default: { - bodyMapper: DataLakeStorageError, - headersMapper: BlobGetAccessControlExceptionHeaders - } - }, - queryParameters: [ - timeoutInSeconds, - action6, - upn - ], - urlParameters: [url], - headerParameters: [ - version, - requestId, - accept1, - leaseId, - ifModifiedSince, - ifUnmodifiedSince, - ifMatch, - ifNoneMatch - ], - isXML: true, - serializer: xmlSerializer$2 -}; -var renameOperationSpec$1 = { - path: "/{filesystem}/{path}", - httpMethod: "PUT", - responses: { - 201: { - headersMapper: BlobRenameHeaders - }, - default: { - bodyMapper: DataLakeStorageError, - headersMapper: BlobRenameExceptionHeaders - } - }, - queryParameters: [timeoutInSeconds, pathRenameMode], - urlParameters: [url], - headerParameters: [ - version, - requestId, - accept1, - leaseId, - ifModifiedSince, - ifUnmodifiedSince, - sourceLeaseId, - directoryProperties, - posixPermissions, - posixUmask, - cacheControl, - contentType1, - contentEncoding, - contentLanguage, - contentDisposition, - ifMatch, - ifNoneMatch, - renameSource, - sourceIfModifiedSince, - sourceIfUnmodifiedSince, - sourceIfMatch, - sourceIfNoneMatch - ], - isXML: true, - serializer: xmlSerializer$2 -}; -var undeleteOperationSpec = { +const undeleteOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -22904,7 +20486,7 @@ var undeleteOperationSpec = { isXML: true, serializer: xmlSerializer$2 }; -var setExpiryOperationSpec = { +const setExpiryOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -22928,7 +20510,7 @@ var setExpiryOperationSpec = { isXML: true, serializer: xmlSerializer$2 }; -var setHttpHeadersOperationSpec = { +const setHttpHeadersOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -22962,7 +20544,77 @@ var setHttpHeadersOperationSpec = { isXML: true, serializer: xmlSerializer$2 }; -var setMetadataOperationSpec$1 = { +const setImmutabilityPolicyOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: BlobSetImmutabilityPolicyHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobSetImmutabilityPolicyExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp12], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + ifUnmodifiedSince, + immutabilityPolicyExpiry, + immutabilityPolicyMode + ], + isXML: true, + serializer: xmlSerializer$2 +}; +const deleteImmutabilityPolicyOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "DELETE", + responses: { + 200: { + headersMapper: BlobDeleteImmutabilityPolicyHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobDeleteImmutabilityPolicyExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp12], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1 + ], + isXML: true, + serializer: xmlSerializer$2 +}; +const setLegalHoldOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: BlobSetLegalHoldHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobSetLegalHoldExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp13], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + legalHold + ], + isXML: true, + serializer: xmlSerializer$2 +}; +const setMetadataOperationSpec$1 = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -22984,18 +20636,18 @@ var setMetadataOperationSpec$1 = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, encryptionScope ], isXML: true, serializer: xmlSerializer$2 }; -var acquireLeaseOperationSpec$1 = { +const acquireLeaseOperationSpec$1 = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -23025,7 +20677,7 @@ var acquireLeaseOperationSpec$1 = { isXML: true, serializer: xmlSerializer$2 }; -var releaseLeaseOperationSpec$1 = { +const releaseLeaseOperationSpec$1 = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -23054,7 +20706,7 @@ var releaseLeaseOperationSpec$1 = { isXML: true, serializer: xmlSerializer$2 }; -var renewLeaseOperationSpec$1 = { +const renewLeaseOperationSpec$1 = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -23083,7 +20735,7 @@ var renewLeaseOperationSpec$1 = { isXML: true, serializer: xmlSerializer$2 }; -var changeLeaseOperationSpec$1 = { +const changeLeaseOperationSpec$1 = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -23113,7 +20765,7 @@ var changeLeaseOperationSpec$1 = { isXML: true, serializer: xmlSerializer$2 }; -var breakLeaseOperationSpec$1 = { +const breakLeaseOperationSpec$1 = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -23142,7 +20794,7 @@ var breakLeaseOperationSpec$1 = { isXML: true, serializer: xmlSerializer$2 }; -var createSnapshotOperationSpec = { +const createSnapshotOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -23154,7 +20806,7 @@ var createSnapshotOperationSpec = { headersMapper: BlobCreateSnapshotExceptionHeaders } }, - queryParameters: [timeoutInSeconds, comp12], + queryParameters: [timeoutInSeconds, comp14], urlParameters: [url], headerParameters: [ version, @@ -23164,18 +20816,18 @@ var createSnapshotOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, encryptionScope ], isXML: true, serializer: xmlSerializer$2 }; -var startCopyFromURLOperationSpec = { +const startCopyFromURLOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -23199,22 +20851,25 @@ var startCopyFromURLOperationSpec = { ifUnmodifiedSince, ifMatch, ifNoneMatch, + ifTags, + immutabilityPolicyExpiry, + immutabilityPolicyMode, + tier, + rehydratePriority, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, - ifTags, - tier, - rehydratePriority, sourceIfTags, copySource, blobTagsString, - sealBlob + sealBlob, + legalHold1 ], isXML: true, serializer: xmlSerializer$2 }; -var copyFromURLOperationSpec = { +const copyFromURLOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -23238,21 +20893,25 @@ var copyFromURLOperationSpec = { ifUnmodifiedSince, ifMatch, ifNoneMatch, + ifTags, + immutabilityPolicyExpiry, + immutabilityPolicyMode, + tier, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, - ifTags, - tier, copySource, blobTagsString, + legalHold1, xMsRequiresSync, - sourceContentMD5 + sourceContentMD5, + copySourceAuthorization ], isXML: true, serializer: xmlSerializer$2 }; -var abortCopyFromURLOperationSpec = { +const abortCopyFromURLOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -23266,7 +20925,7 @@ var abortCopyFromURLOperationSpec = { }, queryParameters: [ timeoutInSeconds, - comp13, + comp15, copyId ], urlParameters: [url], @@ -23280,7 +20939,7 @@ var abortCopyFromURLOperationSpec = { isXML: true, serializer: xmlSerializer$2 }; -var setTierOperationSpec = { +const setTierOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -23299,7 +20958,7 @@ var setTierOperationSpec = { timeoutInSeconds, snapshot, versionId, - comp14 + comp16 ], urlParameters: [url], headerParameters: [ @@ -23314,7 +20973,7 @@ var setTierOperationSpec = { isXML: true, serializer: xmlSerializer$2 }; -var getAccountInfoOperationSpec$2 = { +const getAccountInfoOperationSpec$2 = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { @@ -23332,7 +20991,7 @@ var getAccountInfoOperationSpec$2 = { isXML: true, serializer: xmlSerializer$2 }; -var queryOperationSpec = { +const queryOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "POST", responses: { @@ -23359,7 +21018,7 @@ var queryOperationSpec = { queryParameters: [ timeoutInSeconds, snapshot, - comp15 + comp17 ], urlParameters: [url], headerParameters: [ @@ -23370,11 +21029,11 @@ var queryOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags ], isXML: true, @@ -23382,7 +21041,7 @@ var queryOperationSpec = { mediaType: "xml", serializer: xmlSerializer$2 }; -var getTagsOperationSpec = { +const getTagsOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { @@ -23399,7 +21058,7 @@ var getTagsOperationSpec = { timeoutInSeconds, snapshot, versionId, - comp16 + comp18 ], urlParameters: [url], headerParameters: [ @@ -23412,7 +21071,7 @@ var getTagsOperationSpec = { isXML: true, serializer: xmlSerializer$2 }; -var setTagsOperationSpec = { +const setTagsOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -23428,7 +21087,7 @@ var setTagsOperationSpec = { queryParameters: [ timeoutInSeconds, versionId, - comp16 + comp18 ], urlParameters: [url], headerParameters: [ @@ -23455,12 +21114,12 @@ var setTagsOperationSpec = { * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ /** Class representing a PageBlob. */ -var PageBlob = /** @class */ (function () { +class PageBlob { /** * Initialize a new instance of the class PageBlob class. * @param client Reference to the service client */ - function PageBlob(client) { + constructor(client) { this.client = client; } /** @@ -23470,40 +21129,40 @@ var PageBlob = /** @class */ (function () { * page blob size must be aligned to a 512-byte boundary. * @param options The options parameters. */ - PageBlob.prototype.create = function (contentLength, blobContentLength, options) { - var operationArguments = { - contentLength: contentLength, - blobContentLength: blobContentLength, + create(contentLength, blobContentLength, options) { + const operationArguments = { + contentLength, + blobContentLength, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, createOperationSpec$1); - }; + } /** * The Upload Pages operation writes a range of pages to a page blob * @param contentLength The length of the request. * @param body Initial data * @param options The options parameters. */ - PageBlob.prototype.uploadPages = function (contentLength, body, options) { - var operationArguments = { - contentLength: contentLength, - body: body, + uploadPages(contentLength, body, options) { + const operationArguments = { + contentLength, + body, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, uploadPagesOperationSpec); - }; + } /** * The Clear Pages operation clears a set of pages from a page blob * @param contentLength The length of the request. * @param options The options parameters. */ - PageBlob.prototype.clearPages = function (contentLength, options) { - var operationArguments = { - contentLength: contentLength, + clearPages(contentLength, options) { + const operationArguments = { + contentLength, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, clearPagesOperationSpec); - }; + } /** * The Upload Pages operation writes a range of pages to a page blob where the contents are read from a * URL @@ -23515,51 +21174,51 @@ var PageBlob = /** @class */ (function () { * aligned and range-end is required. * @param options The options parameters. */ - PageBlob.prototype.uploadPagesFromURL = function (sourceUrl, sourceRange, contentLength, range, options) { - var operationArguments = { - sourceUrl: sourceUrl, - sourceRange: sourceRange, - contentLength: contentLength, - range: range, + uploadPagesFromURL(sourceUrl, sourceRange, contentLength, range, options) { + const operationArguments = { + sourceUrl, + sourceRange, + contentLength, + range, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, uploadPagesFromURLOperationSpec); - }; + } /** * The Get Page Ranges operation returns the list of valid page ranges for a page blob or snapshot of a * page blob * @param options The options parameters. */ - PageBlob.prototype.getPageRanges = function (options) { - var operationArguments = { + getPageRanges(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getPageRangesOperationSpec); - }; + } /** * The Get Page Ranges Diff operation returns the list of valid page ranges for a page blob that were * changed between target blob and previous snapshot. * @param options The options parameters. */ - PageBlob.prototype.getPageRangesDiff = function (options) { - var operationArguments = { + getPageRangesDiff(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getPageRangesDiffOperationSpec); - }; + } /** * Resize the Blob * @param blobContentLength This header specifies the maximum size for the page blob, up to 1 TB. The * page blob size must be aligned to a 512-byte boundary. * @param options The options parameters. */ - PageBlob.prototype.resize = function (blobContentLength, options) { - var operationArguments = { - blobContentLength: blobContentLength, + resize(blobContentLength, options) { + const operationArguments = { + blobContentLength, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, resizeOperationSpec); - }; + } /** * Update the sequence number of the blob * @param sequenceNumberAction Required if the x-ms-blob-sequence-number header is set for the request. @@ -23567,13 +21226,13 @@ var PageBlob = /** @class */ (function () { * blob's sequence number * @param options The options parameters. */ - PageBlob.prototype.updateSequenceNumber = function (sequenceNumberAction, options) { - var operationArguments = { - sequenceNumberAction: sequenceNumberAction, + updateSequenceNumber(sequenceNumberAction, options) { + const operationArguments = { + sequenceNumberAction, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, updateSequenceNumberOperationSpec); - }; + } /** * The Copy Incremental operation copies a snapshot of the source page blob to a destination page blob. * The snapshot is copied such that only the differential changes between the previously copied @@ -23586,19 +21245,18 @@ var PageBlob = /** @class */ (function () { * access signature. * @param options The options parameters. */ - PageBlob.prototype.copyIncremental = function (copySource, options) { - var operationArguments = { - copySource: copySource, + copyIncremental(copySource, options) { + const operationArguments = { + copySource, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, copyIncrementalOperationSpec); - }; - return PageBlob; -}()); + } +} // Operation Specifications -var xmlSerializer$3 = new coreHttp.Serializer(Mappers, /* isXml */ true); -var serializer = new coreHttp.Serializer(Mappers, /* isXml */ false); -var createOperationSpec$1 = { +const xmlSerializer$3 = new coreHttp.Serializer(Mappers, /* isXml */ true); +const serializer = new coreHttp.Serializer(Mappers, /* isXml */ false); +const createOperationSpec$1 = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -23621,11 +21279,11 @@ var createOperationSpec$1 = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, blobCacheControl, blobContentType, @@ -23633,9 +21291,12 @@ var createOperationSpec$1 = { blobContentEncoding, blobContentLanguage, blobContentDisposition, + immutabilityPolicyExpiry, + immutabilityPolicyMode, encryptionScope, tier, blobTagsString, + legalHold1, blobType, blobContentLength, blobSequenceNumber @@ -23643,7 +21304,7 @@ var createOperationSpec$1 = { isXML: true, serializer: xmlSerializer$3 }; -var uploadPagesOperationSpec = { +const uploadPagesOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -23656,7 +21317,7 @@ var uploadPagesOperationSpec = { } }, requestBody: body1, - queryParameters: [timeoutInSeconds, comp17], + queryParameters: [timeoutInSeconds, comp19], urlParameters: [url], headerParameters: [ version, @@ -23665,17 +21326,17 @@ var uploadPagesOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, range, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, encryptionScope, transactionalContentMD5, transactionalContentCrc64, - contentType2, + contentType1, accept2, pageWrite, ifSequenceNumberLessThanOrEqualTo, @@ -23683,9 +21344,9 @@ var uploadPagesOperationSpec = { ifSequenceNumberEqualTo ], mediaType: "binary", - serializer: serializer + serializer }; -var clearPagesOperationSpec = { +const clearPagesOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -23697,7 +21358,7 @@ var clearPagesOperationSpec = { headersMapper: PageBlobClearPagesExceptionHeaders } }, - queryParameters: [timeoutInSeconds, comp17], + queryParameters: [timeoutInSeconds, comp19], urlParameters: [url], headerParameters: [ version, @@ -23707,12 +21368,12 @@ var clearPagesOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, range, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, encryptionScope, ifSequenceNumberLessThanOrEqualTo, @@ -23723,7 +21384,7 @@ var clearPagesOperationSpec = { isXML: true, serializer: xmlSerializer$3 }; -var uploadPagesFromURLOperationSpec = { +const uploadPagesFromURLOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -23735,7 +21396,7 @@ var uploadPagesFromURLOperationSpec = { headersMapper: PageBlobUploadPagesFromURLExceptionHeaders } }, - queryParameters: [timeoutInSeconds, comp17], + queryParameters: [timeoutInSeconds, comp19], urlParameters: [url], headerParameters: [ version, @@ -23745,18 +21406,19 @@ var uploadPagesFromURLOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, ifMatch, ifNoneMatch, + ifTags, + encryptionScope, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, - encryptionKey, - encryptionKeySha256, - encryptionAlgorithm, - ifTags, - encryptionScope, sourceContentMD5, + copySourceAuthorization, pageWrite, ifSequenceNumberLessThanOrEqualTo, ifSequenceNumberLessThan, @@ -23769,7 +21431,7 @@ var uploadPagesFromURLOperationSpec = { isXML: true, serializer: xmlSerializer$3 }; -var getPageRangesOperationSpec = { +const getPageRangesOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { @@ -23785,7 +21447,7 @@ var getPageRangesOperationSpec = { queryParameters: [ timeoutInSeconds, snapshot, - comp18 + comp20 ], urlParameters: [url], headerParameters: [ @@ -23795,15 +21457,15 @@ var getPageRangesOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, + range, ifMatch, ifNoneMatch, - range, ifTags ], isXML: true, serializer: xmlSerializer$3 }; -var getPageRangesDiffOperationSpec = { +const getPageRangesDiffOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { @@ -23819,7 +21481,7 @@ var getPageRangesDiffOperationSpec = { queryParameters: [ timeoutInSeconds, snapshot, - comp18, + comp20, prevsnapshot ], urlParameters: [url], @@ -23830,16 +21492,16 @@ var getPageRangesDiffOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, + range, ifMatch, ifNoneMatch, - range, ifTags, prevSnapshotUrl ], isXML: true, serializer: xmlSerializer$3 }; -var resizeOperationSpec = { +const resizeOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -23860,11 +21522,11 @@ var resizeOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, encryptionScope, blobContentLength @@ -23872,7 +21534,7 @@ var resizeOperationSpec = { isXML: true, serializer: xmlSerializer$3 }; -var updateSequenceNumberOperationSpec = { +const updateSequenceNumberOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -23902,7 +21564,7 @@ var updateSequenceNumberOperationSpec = { isXML: true, serializer: xmlSerializer$3 }; -var copyIncrementalOperationSpec = { +const copyIncrementalOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -23914,7 +21576,7 @@ var copyIncrementalOperationSpec = { headersMapper: PageBlobCopyIncrementalExceptionHeaders } }, - queryParameters: [timeoutInSeconds, comp19], + queryParameters: [timeoutInSeconds, comp21], urlParameters: [url], headerParameters: [ version, @@ -23939,12 +21601,12 @@ var copyIncrementalOperationSpec = { * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ /** Class representing a AppendBlob. */ -var AppendBlob = /** @class */ (function () { +class AppendBlob { /** * Initialize a new instance of the class AppendBlob class. * @param client Reference to the service client */ - function AppendBlob(client) { + constructor(client) { this.client = client; } /** @@ -23952,13 +21614,13 @@ var AppendBlob = /** @class */ (function () { * @param contentLength The length of the request. * @param options The options parameters. */ - AppendBlob.prototype.create = function (contentLength, options) { - var operationArguments = { - contentLength: contentLength, + create(contentLength, options) { + const operationArguments = { + contentLength, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, createOperationSpec$2); - }; + } /** * The Append Block operation commits a new block of data to the end of an existing append blob. The * Append Block operation is permitted only if the blob was created with x-ms-blob-type set to @@ -23967,14 +21629,14 @@ var AppendBlob = /** @class */ (function () { * @param body Initial data * @param options The options parameters. */ - AppendBlob.prototype.appendBlock = function (contentLength, body, options) { - var operationArguments = { - contentLength: contentLength, - body: body, + appendBlock(contentLength, body, options) { + const operationArguments = { + contentLength, + body, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, appendBlockOperationSpec); - }; + } /** * The Append Block operation commits a new block of data to the end of an existing append blob where * the contents are read from a source url. The Append Block operation is permitted only if the blob @@ -23984,31 +21646,30 @@ var AppendBlob = /** @class */ (function () { * @param contentLength The length of the request. * @param options The options parameters. */ - AppendBlob.prototype.appendBlockFromUrl = function (sourceUrl, contentLength, options) { - var operationArguments = { - sourceUrl: sourceUrl, - contentLength: contentLength, + appendBlockFromUrl(sourceUrl, contentLength, options) { + const operationArguments = { + sourceUrl, + contentLength, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, appendBlockFromUrlOperationSpec); - }; + } /** * The Seal operation seals the Append Blob to make it read-only. Seal is supported only on version * 2019-12-12 version or later. * @param options The options parameters. */ - AppendBlob.prototype.seal = function (options) { - var operationArguments = { + seal(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, sealOperationSpec); - }; - return AppendBlob; -}()); + } +} // Operation Specifications -var xmlSerializer$4 = new coreHttp.Serializer(Mappers, /* isXml */ true); -var serializer$1 = new coreHttp.Serializer(Mappers, /* isXml */ false); -var createOperationSpec$2 = { +const xmlSerializer$4 = new coreHttp.Serializer(Mappers, /* isXml */ true); +const serializer$1 = new coreHttp.Serializer(Mappers, /* isXml */ false); +const createOperationSpec$2 = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -24031,11 +21692,11 @@ var createOperationSpec$2 = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, blobCacheControl, blobContentType, @@ -24043,14 +21704,17 @@ var createOperationSpec$2 = { blobContentEncoding, blobContentLanguage, blobContentDisposition, + immutabilityPolicyExpiry, + immutabilityPolicyMode, encryptionScope, blobTagsString, + legalHold1, blobType1 ], isXML: true, serializer: xmlSerializer$4 }; -var appendBlockOperationSpec = { +const appendBlockOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -24063,7 +21727,7 @@ var appendBlockOperationSpec = { } }, requestBody: body1, - queryParameters: [timeoutInSeconds, comp20], + queryParameters: [timeoutInSeconds, comp22], urlParameters: [url], headerParameters: [ version, @@ -24072,16 +21736,16 @@ var appendBlockOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, encryptionScope, transactionalContentMD5, transactionalContentCrc64, - contentType2, + contentType1, accept2, maxSize, appendPosition @@ -24089,7 +21753,7 @@ var appendBlockOperationSpec = { mediaType: "binary", serializer: serializer$1 }; -var appendBlockFromUrlOperationSpec = { +const appendBlockFromUrlOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -24101,7 +21765,7 @@ var appendBlockFromUrlOperationSpec = { headersMapper: AppendBlobAppendBlockFromUrlExceptionHeaders } }, - queryParameters: [timeoutInSeconds, comp20], + queryParameters: [timeoutInSeconds, comp22], urlParameters: [url], headerParameters: [ version, @@ -24111,18 +21775,19 @@ var appendBlockFromUrlOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, ifMatch, ifNoneMatch, + ifTags, + encryptionScope, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, - encryptionKey, - encryptionKeySha256, - encryptionAlgorithm, - ifTags, - encryptionScope, sourceContentMD5, + copySourceAuthorization, transactionalContentMD5, sourceUrl, sourceContentCrc64, @@ -24133,7 +21798,7 @@ var appendBlockFromUrlOperationSpec = { isXML: true, serializer: xmlSerializer$4 }; -var sealOperationSpec = { +const sealOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -24145,7 +21810,7 @@ var sealOperationSpec = { headersMapper: AppendBlobSealExceptionHeaders } }, - queryParameters: [timeoutInSeconds, comp21], + queryParameters: [timeoutInSeconds, comp23], urlParameters: [url], headerParameters: [ version, @@ -24170,12 +21835,12 @@ var sealOperationSpec = { * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ /** Class representing a BlockBlob. */ -var BlockBlob = /** @class */ (function () { +class BlockBlob { /** * Initialize a new instance of the class BlockBlob class. * @param client Reference to the service client */ - function BlockBlob(client) { + constructor(client) { this.client = client; } /** @@ -24187,14 +21852,14 @@ var BlockBlob = /** @class */ (function () { * @param body Initial data * @param options The options parameters. */ - BlockBlob.prototype.upload = function (contentLength, body, options) { - var operationArguments = { - contentLength: contentLength, - body: body, + upload(contentLength, body, options) { + const operationArguments = { + contentLength, + body, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, uploadOperationSpec); - }; + } /** * The Put Blob from URL operation 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 @@ -24208,14 +21873,14 @@ var BlockBlob = /** @class */ (function () { * access signature. * @param options The options parameters. */ - BlockBlob.prototype.putBlobFromUrl = function (contentLength, copySource, options) { - var operationArguments = { - contentLength: contentLength, - copySource: copySource, + putBlobFromUrl(contentLength, copySource, options) { + const operationArguments = { + contentLength, + copySource, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, putBlobFromUrlOperationSpec); - }; + } /** * The Stage Block operation creates a new block to be committed as part of a blob * @param blockId A valid Base64 string value that identifies the block. Prior to encoding, the string @@ -24225,15 +21890,15 @@ var BlockBlob = /** @class */ (function () { * @param body Initial data * @param options The options parameters. */ - BlockBlob.prototype.stageBlock = function (blockId, contentLength, body, options) { - var operationArguments = { - blockId: blockId, - contentLength: contentLength, - body: body, + stageBlock(blockId, contentLength, body, options) { + const operationArguments = { + blockId, + contentLength, + body, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, stageBlockOperationSpec); - }; + } /** * The Stage Block operation creates a new block to be committed as part of a blob where the contents * are read from a URL. @@ -24244,15 +21909,15 @@ var BlockBlob = /** @class */ (function () { * @param sourceUrl Specify a URL to the copy source. * @param options The options parameters. */ - BlockBlob.prototype.stageBlockFromURL = function (blockId, contentLength, sourceUrl, options) { - var operationArguments = { - blockId: blockId, - contentLength: contentLength, - sourceUrl: sourceUrl, + stageBlockFromURL(blockId, contentLength, sourceUrl, options) { + const operationArguments = { + blockId, + contentLength, + sourceUrl, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, stageBlockFromURLOperationSpec); - }; + } /** * The Commit Block List operation writes a blob by specifying the list of block IDs that make up the * blob. In order to be written as part of a blob, a block must have been successfully written to the @@ -24261,16 +21926,16 @@ var BlockBlob = /** @class */ (function () { * do this by specifying whether to commit a block from the committed block list or from the * uncommitted block list, or to commit the most recently uploaded version of the block, whichever list * it may belong to. - * @param blocks + * @param blocks Blob Blocks. * @param options The options parameters. */ - BlockBlob.prototype.commitBlockList = function (blocks, options) { - var operationArguments = { - blocks: blocks, + commitBlockList(blocks, options) { + const operationArguments = { + blocks, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, commitBlockListOperationSpec); - }; + } /** * The Get Block List operation retrieves the list of blocks that have been uploaded as part of a block * blob @@ -24278,19 +21943,18 @@ var BlockBlob = /** @class */ (function () { * blocks, or both lists together. * @param options The options parameters. */ - BlockBlob.prototype.getBlockList = function (listType, options) { - var operationArguments = { - listType: listType, + getBlockList(listType, options) { + const operationArguments = { + listType, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getBlockListOperationSpec); - }; - return BlockBlob; -}()); + } +} // Operation Specifications -var xmlSerializer$5 = new coreHttp.Serializer(Mappers, /* isXml */ true); -var serializer$2 = new coreHttp.Serializer(Mappers, /* isXml */ false); -var uploadOperationSpec = { +const xmlSerializer$5 = new coreHttp.Serializer(Mappers, /* isXml */ true); +const serializer$2 = new coreHttp.Serializer(Mappers, /* isXml */ false); +const uploadOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -24313,11 +21977,11 @@ var uploadOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, blobCacheControl, blobContentType, @@ -24325,18 +21989,21 @@ var uploadOperationSpec = { blobContentEncoding, blobContentLanguage, blobContentDisposition, + immutabilityPolicyExpiry, + immutabilityPolicyMode, encryptionScope, tier, blobTagsString, + legalHold1, transactionalContentMD5, - contentType2, + contentType1, accept2, blobType2 ], mediaType: "binary", serializer: serializer$2 }; -var putBlobFromUrlOperationSpec = { +const putBlobFromUrlOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -24359,15 +22026,11 @@ var putBlobFromUrlOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, - sourceIfModifiedSince, - sourceIfUnmodifiedSince, - sourceIfMatch, - sourceIfNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, blobCacheControl, blobContentType, @@ -24377,10 +22040,15 @@ var putBlobFromUrlOperationSpec = { blobContentDisposition, encryptionScope, tier, + sourceIfModifiedSince, + sourceIfUnmodifiedSince, + sourceIfMatch, + sourceIfNoneMatch, sourceIfTags, copySource, blobTagsString, sourceContentMD5, + copySourceAuthorization, transactionalContentMD5, blobType2, copySourceBlobProperties @@ -24388,7 +22056,7 @@ var putBlobFromUrlOperationSpec = { isXML: true, serializer: xmlSerializer$5 }; -var stageBlockOperationSpec = { +const stageBlockOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -24403,7 +22071,7 @@ var stageBlockOperationSpec = { requestBody: body1, queryParameters: [ timeoutInSeconds, - comp22, + comp24, blockId ], urlParameters: [url], @@ -24418,13 +22086,13 @@ var stageBlockOperationSpec = { encryptionScope, transactionalContentMD5, transactionalContentCrc64, - contentType2, + contentType1, accept2 ], mediaType: "binary", serializer: serializer$2 }; -var stageBlockFromURLOperationSpec = { +const stageBlockFromURLOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -24438,7 +22106,7 @@ var stageBlockFromURLOperationSpec = { }, queryParameters: [ timeoutInSeconds, - comp22, + comp24, blockId ], urlParameters: [url], @@ -24448,15 +22116,16 @@ var stageBlockFromURLOperationSpec = { accept1, contentLength, leaseId, - sourceIfModifiedSince, - sourceIfUnmodifiedSince, - sourceIfMatch, - sourceIfNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, encryptionScope, + sourceIfModifiedSince, + sourceIfUnmodifiedSince, + sourceIfMatch, + sourceIfNoneMatch, sourceContentMD5, + copySourceAuthorization, sourceUrl, sourceContentCrc64, sourceRange1 @@ -24464,7 +22133,7 @@ var stageBlockFromURLOperationSpec = { isXML: true, serializer: xmlSerializer$5 }; -var commitBlockListOperationSpec = { +const commitBlockListOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -24477,7 +22146,7 @@ var commitBlockListOperationSpec = { } }, requestBody: blocks, - queryParameters: [timeoutInSeconds, comp23], + queryParameters: [timeoutInSeconds, comp25], urlParameters: [url], headerParameters: [ contentType, @@ -24488,11 +22157,11 @@ var commitBlockListOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, blobCacheControl, blobContentType, @@ -24500,9 +22169,12 @@ var commitBlockListOperationSpec = { blobContentEncoding, blobContentLanguage, blobContentDisposition, + immutabilityPolicyExpiry, + immutabilityPolicyMode, encryptionScope, tier, blobTagsString, + legalHold1, transactionalContentMD5, transactionalContentCrc64 ], @@ -24511,7 +22183,7 @@ var commitBlockListOperationSpec = { mediaType: "xml", serializer: xmlSerializer$5 }; -var getBlockListOperationSpec = { +const getBlockListOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { @@ -24527,7 +22199,7 @@ var getBlockListOperationSpec = { queryParameters: [ timeoutInSeconds, snapshot, - comp23, + comp25, listType ], urlParameters: [url], @@ -24546,23 +22218,23 @@ var getBlockListOperationSpec = { /** * The `@azure/logger` configuration for this package. */ -var logger = logger$1.createClientLogger("storage-blob"); +const logger = logger$1.createClientLogger("storage-blob"); // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -var SDK_VERSION = "12.6.0"; -var SERVICE_VERSION = "2020-08-04"; -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; -var DEFAULT_BLOCK_BUFFER_SIZE_BYTES = 8 * 1024 * 1024; // 8MB -var DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES = 4 * 1024 * 1024; // 4MB -var DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS = 5; +const SDK_VERSION = "12.8.0"; +const SERVICE_VERSION = "2020-10-02"; +const BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES = 256 * 1024 * 1024; // 256MB +const BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES = 4000 * 1024 * 1024; // 4000MB +const BLOCK_BLOB_MAX_BLOCKS = 50000; +const DEFAULT_BLOCK_BUFFER_SIZE_BYTES = 8 * 1024 * 1024; // 8MB +const DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES = 4 * 1024 * 1024; // 4MB +const DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS = 5; /** * The OAuth scope to use with Azure Storage. */ -var StorageOAuthScopes = "https://storage.azure.com/.default"; -var URLConstants = { +const StorageOAuthScopes = "https://storage.azure.com/.default"; +const URLConstants = { Parameters: { FORCE_BROWSER_NO_CACHE: "_", SIGNATURE: "sig", @@ -24571,14 +22243,14 @@ var URLConstants = { TIMEOUT: "timeout" } }; -var HTTPURLConnection = { +const HTTPURLConnection = { HTTP_ACCEPTED: 202, HTTP_CONFLICT: 409, HTTP_NOT_FOUND: 404, HTTP_PRECON_FAILED: 412, HTTP_RANGE_NOT_SATISFIABLE: 416 }; -var HeaderConstants = { +const HeaderConstants = { AUTHORIZATION: "Authorization", AUTHORIZATION_SCHEME: "Bearer", CONTENT_ENCODING: "Content-Encoding", @@ -24603,16 +22275,16 @@ var HeaderConstants = { X_MS_ERROR_CODE: "x-ms-error-code", X_MS_VERSION: "x-ms-version" }; -var ETagNone = ""; -var ETagAny = "*"; -var SIZE_1_MB = 1 * 1024 * 1024; -var BATCH_MAX_REQUEST = 256; -var BATCH_MAX_PAYLOAD_IN_BYTES = 4 * SIZE_1_MB; -var HTTP_LINE_ENDING = "\r\n"; -var HTTP_VERSION_1_1 = "HTTP/1.1"; -var EncryptionAlgorithmAES25 = "AES256"; -var DevelopmentConnectionString = "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;"; -var StorageBlobLoggingAllowedHeaderNames = [ +const ETagNone = ""; +const ETagAny = "*"; +const SIZE_1_MB = 1 * 1024 * 1024; +const BATCH_MAX_REQUEST = 256; +const BATCH_MAX_PAYLOAD_IN_BYTES = 4 * SIZE_1_MB; +const HTTP_LINE_ENDING = "\r\n"; +const HTTP_VERSION_1_1 = "HTTP/1.1"; +const EncryptionAlgorithmAES25 = "AES256"; +const DevelopmentConnectionString = `DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;`; +const StorageBlobLoggingAllowedHeaderNames = [ "Access-Control-Allow-Origin", "Cache-Control", "Content-Length", @@ -24708,7 +22380,7 @@ var StorageBlobLoggingAllowedHeaderNames = [ "x-ms-if-tags", "x-ms-source-if-tags" ]; -var StorageBlobLoggingAllowedQueryParameters = [ +const StorageBlobLoggingAllowedQueryParameters = [ "comp", "maxresults", "rscc", @@ -24798,8 +22470,8 @@ var StorageBlobLoggingAllowedQueryParameters = [ * @param url - */ function escapeURLPath(url) { - var urlParsed = coreHttp.URLBuilder.parse(url); - var path = urlParsed.getPath(); + const urlParsed = coreHttp.URLBuilder.parse(url); + let path = urlParsed.getPath(); path = path || "/"; path = escape(path); urlParsed.setPath(path); @@ -24808,12 +22480,11 @@ function escapeURLPath(url) { function getProxyUriFromDevConnString(connectionString) { // Development Connection String // https://docs.microsoft.com/en-us/azure/storage/common/storage-configure-connection-string#connect-to-the-emulator-account-using-the-well-known-account-name-and-key - var proxyUri = ""; + let proxyUri = ""; if (connectionString.search("DevelopmentStorageProxyUri=") !== -1) { // CONNECTION_STRING=UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://myProxyUri - var matchCredentials = connectionString.split(";"); - for (var _i = 0, matchCredentials_1 = matchCredentials; _i < matchCredentials_1.length; _i++) { - var element = matchCredentials_1[_i]; + const matchCredentials = connectionString.split(";"); + for (const element of matchCredentials) { if (element.trim().startsWith("DevelopmentStorageProxyUri=")) { proxyUri = element.trim().match("DevelopmentStorageProxyUri=(.*)")[1]; } @@ -24822,9 +22493,8 @@ function getProxyUriFromDevConnString(connectionString) { return proxyUri; } function getValueInConnString(connectionString, argument) { - var elements = connectionString.split(";"); - for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { - var element = elements_1[_i]; + const elements = connectionString.split(";"); + for (const element of elements) { if (element.trim().startsWith(argument)) { return element.trim().match(argument + "=(.*)")[1]; } @@ -24838,24 +22508,24 @@ function getValueInConnString(connectionString, argument) { * @returns String key value pairs of the storage account's url and credentials. */ function extractConnectionStringParts(connectionString) { - var proxyUri = ""; + let proxyUri = ""; if (connectionString.startsWith("UseDevelopmentStorage=true")) { // Development connection string proxyUri = getProxyUriFromDevConnString(connectionString); connectionString = DevelopmentConnectionString; } // Matching BlobEndpoint in the Account connection string - var blobEndpoint = getValueInConnString(connectionString, "BlobEndpoint"); + let blobEndpoint = getValueInConnString(connectionString, "BlobEndpoint"); // Slicing off '/' at the end if exists // (The methods that use `extractConnectionStringParts` expect the url to not have `/` at the end) blobEndpoint = blobEndpoint.endsWith("/") ? blobEndpoint.slice(0, -1) : blobEndpoint; if (connectionString.search("DefaultEndpointsProtocol=") !== -1 && connectionString.search("AccountKey=") !== -1) { // Account connection string - var defaultEndpointsProtocol = ""; - var accountName = ""; - var accountKey = Buffer.from("accountKey", "base64"); - var endpointSuffix = ""; + let defaultEndpointsProtocol = ""; + let accountName = ""; + let accountKey = Buffer.from("accountKey", "base64"); + let endpointSuffix = ""; // Get account name and key accountName = getValueInConnString(connectionString, "AccountName"); accountKey = Buffer.from(getValueInConnString(connectionString, "AccountKey"), "base64"); @@ -24863,7 +22533,7 @@ function extractConnectionStringParts(connectionString) { // BlobEndpoint is not present in the Account connection string // Can be obtained from `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}` defaultEndpointsProtocol = getValueInConnString(connectionString, "DefaultEndpointsProtocol"); - var protocol = defaultEndpointsProtocol.toLowerCase(); + const protocol = defaultEndpointsProtocol.toLowerCase(); if (protocol !== "https" && protocol !== "http") { throw new Error("Invalid DefaultEndpointsProtocol in the provided Connection String. Expecting 'https' or 'http'"); } @@ -24871,7 +22541,7 @@ function extractConnectionStringParts(connectionString) { if (!endpointSuffix) { throw new Error("Invalid EndpointSuffix in the provided Connection String"); } - blobEndpoint = defaultEndpointsProtocol + "://" + accountName + ".blob." + endpointSuffix; + blobEndpoint = `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; } if (!accountName) { throw new Error("Invalid AccountName in the provided Connection String"); @@ -24882,22 +22552,22 @@ function extractConnectionStringParts(connectionString) { return { kind: "AccountConnString", url: blobEndpoint, - accountName: accountName, - accountKey: accountKey, - proxyUri: proxyUri + accountName, + accountKey, + proxyUri }; } else { // SAS connection string - var accountSas = getValueInConnString(connectionString, "SharedAccessSignature"); - var accountName = getAccountNameFromUrl(blobEndpoint); + const accountSas = getValueInConnString(connectionString, "SharedAccessSignature"); + const accountName = getAccountNameFromUrl(blobEndpoint); if (!blobEndpoint) { throw new Error("Invalid BlobEndpoint in the provided SAS Connection String"); } else if (!accountSas) { throw new Error("Invalid SharedAccessSignature in the provided SAS Connection String"); } - return { kind: "SASConnString", url: blobEndpoint, accountName: accountName, accountSas: accountSas }; + return { kind: "SASConnString", url: blobEndpoint, accountName, accountSas }; } } /** @@ -24921,9 +22591,9 @@ function escape(text) { * @returns An updated URL string */ function appendToURLPath(url, name) { - var urlParsed = coreHttp.URLBuilder.parse(url); - var path = urlParsed.getPath(); - path = path ? (path.endsWith("/") ? "" + path + name : path + "/" + name) : name; + const urlParsed = coreHttp.URLBuilder.parse(url); + let path = urlParsed.getPath(); + path = path ? (path.endsWith("/") ? `${path}${name}` : `${path}/${name}`) : name; urlParsed.setPath(path); return urlParsed.toString(); } @@ -24937,7 +22607,7 @@ function appendToURLPath(url, name) { * @returns An updated URL string */ function setURLParameter(url, name, value) { - var urlParsed = coreHttp.URLBuilder.parse(url); + const urlParsed = coreHttp.URLBuilder.parse(url); urlParsed.setQueryParameter(name, value); return urlParsed.toString(); } @@ -24948,7 +22618,7 @@ function setURLParameter(url, name, value) { * @param name - */ function getURLParameter(url, name) { - var urlParsed = coreHttp.URLBuilder.parse(url); + const urlParsed = coreHttp.URLBuilder.parse(url); return urlParsed.getQueryParameterValue(name); } /** @@ -24959,7 +22629,7 @@ function getURLParameter(url, name) { * @returns An updated URL string */ function setURLHost(url, host) { - var urlParsed = coreHttp.URLBuilder.parse(url); + const urlParsed = coreHttp.URLBuilder.parse(url); urlParsed.setHost(host); return urlParsed.toString(); } @@ -24969,7 +22639,7 @@ function setURLHost(url, host) { * @param url - Source URL string */ function getURLPath(url) { - var urlParsed = coreHttp.URLBuilder.parse(url); + const urlParsed = coreHttp.URLBuilder.parse(url); return urlParsed.getPath(); } /** @@ -24978,7 +22648,7 @@ function getURLPath(url) { * @param url - Source URL string */ function getURLScheme(url) { - var urlParsed = coreHttp.URLBuilder.parse(url); + const urlParsed = coreHttp.URLBuilder.parse(url); return urlParsed.getScheme(); } /** @@ -24987,17 +22657,17 @@ function getURLScheme(url) { * @param url - Source URL string */ function getURLPathAndQuery(url) { - var urlParsed = coreHttp.URLBuilder.parse(url); - var pathString = urlParsed.getPath(); + const urlParsed = coreHttp.URLBuilder.parse(url); + const pathString = urlParsed.getPath(); if (!pathString) { throw new RangeError("Invalid url without valid path."); } - var queryString = urlParsed.getQuery() || ""; + let queryString = urlParsed.getQuery() || ""; queryString = queryString.trim(); - if (queryString != "") { - queryString = queryString.startsWith("?") ? queryString : "?" + queryString; // Ensure query string start with '?' + if (queryString !== "") { + queryString = queryString.startsWith("?") ? queryString : `?${queryString}`; // Ensure query string start with '?' } - return "" + pathString + queryString; + return `${pathString}${queryString}`; } /** * Get URL query key value pairs from an URL string. @@ -25005,24 +22675,23 @@ function getURLPathAndQuery(url) { * @param url - */ function getURLQueries(url) { - var queryString = coreHttp.URLBuilder.parse(url).getQuery(); + let queryString = coreHttp.URLBuilder.parse(url).getQuery(); if (!queryString) { return {}; } queryString = queryString.trim(); queryString = queryString.startsWith("?") ? queryString.substr(1) : queryString; - var querySubStrings = queryString.split("&"); - querySubStrings = querySubStrings.filter(function (value) { - var indexOfEqual = value.indexOf("="); - var lastIndexOfEqual = value.lastIndexOf("="); + let querySubStrings = queryString.split("&"); + querySubStrings = querySubStrings.filter((value) => { + const indexOfEqual = value.indexOf("="); + const lastIndexOfEqual = value.lastIndexOf("="); return (indexOfEqual > 0 && indexOfEqual === lastIndexOfEqual && lastIndexOfEqual < value.length - 1); }); - var queries = {}; - for (var _i = 0, querySubStrings_1 = querySubStrings; _i < querySubStrings_1.length; _i++) { - var querySubString = querySubStrings_1[_i]; - var splitResults = querySubString.split("="); - var key = splitResults[0]; - var value = splitResults[1]; + const queries = {}; + for (const querySubString of querySubStrings) { + const splitResults = querySubString.split("="); + const key = splitResults[0]; + const value = splitResults[1]; queries[key] = value; } return queries; @@ -25035,8 +22704,8 @@ function getURLQueries(url) { * @returns An updated URL string. */ function appendToURLQuery(url, queryParts) { - var urlParsed = coreHttp.URLBuilder.parse(url); - var query = urlParsed.getQuery(); + const urlParsed = coreHttp.URLBuilder.parse(url); + let query = urlParsed.getQuery(); if (query) { query += "&" + queryParts; } @@ -25054,10 +22723,9 @@ function appendToURLQuery(url, queryParts) { * If false, YYYY-MM-DDThh:mm:ssZ will be returned. * @returns Date string in ISO8061 format, with or without 7 milliseconds component */ -function truncatedISO8061Date(date, withMilliseconds) { - if (withMilliseconds === void 0) { withMilliseconds = true; } +function truncatedISO8061Date(date, withMilliseconds = true) { // Date.toISOString() will return like "2018-10-29T06:34:36.139Z" - var dateString = date.toISOString(); + const dateString = date.toISOString(); return withMilliseconds ? dateString.substring(0, dateString.length - 1) + "0000" + "Z" : dateString.substring(0, dateString.length - 5) + "Z"; @@ -25077,14 +22745,14 @@ function base64encode(content) { */ function generateBlockID(blockIDPrefix, blockIndex) { // To generate a 64 bytes base64 string, source string should be 48 - var maxSourceStringLength = 48; + const maxSourceStringLength = 48; // A blob can have a maximum of 100,000 uncommitted blocks at any given time - var maxBlockIndexLength = 6; - var maxAllowedBlockIDPrefixLength = maxSourceStringLength - maxBlockIndexLength; + const maxBlockIndexLength = 6; + const maxAllowedBlockIDPrefixLength = maxSourceStringLength - maxBlockIndexLength; if (blockIDPrefix.length > maxAllowedBlockIDPrefixLength) { blockIDPrefix = blockIDPrefix.slice(0, maxAllowedBlockIDPrefixLength); } - var res = blockIDPrefix + + const res = blockIDPrefix + padStart(blockIndex.toString(), maxSourceStringLength - blockIDPrefix.length, "0"); return base64encode(res); } @@ -25095,29 +22763,26 @@ function generateBlockID(blockIDPrefix, blockIndex) { * @param aborter - * @param abortError - */ -function delay(timeInMs, aborter, abortError) { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - return [2 /*return*/, new Promise(function (resolve, reject) { - var timeout; - var abortHandler = function () { - if (timeout !== undefined) { - clearTimeout(timeout); - } - reject(abortError); - }; - var resolveHandler = function () { - if (aborter !== undefined) { - aborter.removeEventListener("abort", abortHandler); - } - resolve(); - }; - timeout = setTimeout(resolveHandler, timeInMs); - if (aborter !== undefined) { - aborter.addEventListener("abort", abortHandler); - } - })]; - }); +async function delay(timeInMs, aborter, abortError) { + return new Promise((resolve, reject) => { + /* eslint-disable-next-line prefer-const */ + let timeout; + const abortHandler = () => { + if (timeout !== undefined) { + clearTimeout(timeout); + } + reject(abortError); + }; + const resolveHandler = () => { + if (aborter !== undefined) { + aborter.removeEventListener("abort", abortHandler); + } + resolve(); + }; + timeout = setTimeout(resolveHandler, timeInMs); + if (aborter !== undefined) { + aborter.addEventListener("abort", abortHandler); + } }); } /** @@ -25127,10 +22792,8 @@ function delay(timeInMs, aborter, abortError) { * @param targetLength - * @param padString - */ -function padStart(currentString, targetLength, padString) { - if (padString === void 0) { padString = " "; } - // TS doesn't know this code needs to run downlevel sometimes. - // @ts-expect-error +function padStart(currentString, targetLength, padString = " ") { + // @ts-expect-error: TS doesn't know this code needs to run downlevel sometimes if (String.prototype.padStart) { return currentString.padStart(targetLength, padString); } @@ -25161,8 +22824,8 @@ function iEqual(str1, str2) { * @returns with the account name */ function getAccountNameFromUrl(url) { - var parsedUrl = coreHttp.URLBuilder.parse(url); - var accountName; + const parsedUrl = coreHttp.URLBuilder.parse(url); + let accountName; try { if (parsedUrl.getHost().split(".")[1] === "blob") { // `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; @@ -25185,10 +22848,10 @@ function getAccountNameFromUrl(url) { } } function isIpEndpointStyle(parsedUrl) { - if (parsedUrl.getHost() == undefined) { + if (parsedUrl.getHost() === undefined) { return false; } - var host = parsedUrl.getHost() + (parsedUrl.getPort() == undefined ? "" : ":" + parsedUrl.getPort()); + const host = parsedUrl.getHost() + (parsedUrl.getPort() === undefined ? "" : ":" + parsedUrl.getPort()); // Case 1: Ipv6, use a broad regex to find out candidates whose host contains two ':'. // Case 2: localhost(:port), use broad regex to match port part. // Case 3: Ipv4, use broad regex which just check if host contains Ipv4. @@ -25204,11 +22867,11 @@ function toBlobTagsString(tags) { if (tags === undefined) { return undefined; } - var tagPairs = []; - for (var key in tags) { - if (tags.hasOwnProperty(key)) { - var value = tags[key]; - tagPairs.push(encodeURIComponent(key) + "=" + encodeURIComponent(value)); + const tagPairs = []; + for (const key in tags) { + if (Object.prototype.hasOwnProperty.call(tags, key)) { + const value = tags[key]; + tagPairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`); } } return tagPairs.join("&"); @@ -25222,15 +22885,15 @@ function toBlobTags(tags) { if (tags === undefined) { return undefined; } - var res = { + const res = { blobTagSet: [] }; - for (var key in tags) { - if (tags.hasOwnProperty(key)) { - var value = tags[key]; + for (const key in tags) { + if (Object.prototype.hasOwnProperty.call(tags, key)) { + const value = tags[key]; res.blobTagSet.push({ - key: key, - value: value + key, + value }); } } @@ -25245,9 +22908,8 @@ function toTags(tags) { if (tags === undefined) { return undefined; } - var res = {}; - for (var _i = 0, _a = tags.blobTagSet; _i < _a.length; _i++) { - var blobTag = _a[_i]; + const res = {}; + for (const blobTag of tags.blobTagSet) { res[blobTag.key] = blobTag.value; } return res; @@ -25293,6 +22955,12 @@ function toQuerySerialization(textConfiguration) { } } }; + case "parquet": + return { + format: { + type: "parquet" + } + }; default: throw Error("Invalid BlobQueryTextConfiguration."); } @@ -25306,18 +22974,18 @@ function parseObjectReplicationRecord(objectReplicationRecord) { // the policy id should already be stored in the ObjectReplicationDestinationPolicyId. return undefined; } - var orProperties = []; - var _loop_1 = function (key) { - var ids = key.split("_"); - var policyPrefix = "or-"; + const orProperties = []; + for (const key in objectReplicationRecord) { + const ids = key.split("_"); + const policyPrefix = "or-"; if (ids[0].startsWith(policyPrefix)) { ids[0] = ids[0].substring(policyPrefix.length); } - var rule = { + const rule = { ruleId: ids[1], replicationStatus: objectReplicationRecord[key] }; - var policyIndex = orProperties.findIndex(function (policy) { return policy.policyId === ids[0]; }); + const policyIndex = orProperties.findIndex((policy) => policy.policyId === ids[0]); if (policyIndex > -1) { orProperties[policyIndex].rules.push(rule); } @@ -25327,9 +22995,6 @@ function parseObjectReplicationRecord(objectReplicationRecord) { rules: [rule] }); } - }; - for (var key in objectReplicationRecord) { - _loop_1(key); } return orProperties; } @@ -25343,6 +23008,9 @@ function attachCredential(thing, credential) { thing.credential = credential; return thing; } +function httpAuthorizationToString(httpAuthorization) { + return httpAuthorization ? httpAuthorization.scheme + " " + httpAuthorization.value : undefined; +} // Copyright (c) Microsoft Corporation. /** @@ -25356,51 +23024,44 @@ function attachCredential(thing, credential) { * * 3. Remove content-length header to avoid browsers warning */ -var StorageBrowserPolicy = /** @class */ (function (_super) { - tslib.__extends(StorageBrowserPolicy, _super); +class StorageBrowserPolicy extends coreHttp.BaseRequestPolicy { /** * Creates an instance of StorageBrowserPolicy. * @param nextPolicy - * @param options - */ - function StorageBrowserPolicy(nextPolicy, options) { - return _super.call(this, nextPolicy, options) || this; + // The base class has a protected constructor. Adding a public one to enable constructing of this class. + /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ + constructor(nextPolicy, options) { + super(nextPolicy, options); } /** * Sends out request. * * @param request - */ - StorageBrowserPolicy.prototype.sendRequest = function (request) { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - { - return [2 /*return*/, this._nextPolicy.sendRequest(request)]; - } - }); - }); - }; - return StorageBrowserPolicy; -}(coreHttp.BaseRequestPolicy)); + async sendRequest(request) { + { + return this._nextPolicy.sendRequest(request); + } + } +} // Copyright (c) Microsoft Corporation. /** * StorageBrowserPolicyFactory is a factory class helping generating StorageBrowserPolicy objects. */ -var StorageBrowserPolicyFactory = /** @class */ (function () { - function StorageBrowserPolicyFactory() { - } +class StorageBrowserPolicyFactory { /** * Creates a StorageBrowserPolicyFactory object. * * @param nextPolicy - * @param options - */ - StorageBrowserPolicyFactory.prototype.create = function (nextPolicy, options) { + create(nextPolicy, options) { return new StorageBrowserPolicy(nextPolicy, options); - }; - return StorageBrowserPolicyFactory; -}()); + } +} // Copyright (c) Microsoft Corporation. (function (StorageRetryPolicyType) { @@ -25414,7 +23075,7 @@ var StorageBrowserPolicyFactory = /** @class */ (function () { StorageRetryPolicyType[StorageRetryPolicyType["FIXED"] = 1] = "FIXED"; })(exports.StorageRetryPolicyType || (exports.StorageRetryPolicyType = {})); // Default values of StorageRetryOptions -var DEFAULT_RETRY_OPTIONS = { +const DEFAULT_RETRY_OPTIONS = { maxRetryDelayInMs: 120 * 1000, maxTries: 4, retryDelayInMs: 4 * 1000, @@ -25422,12 +23083,11 @@ var DEFAULT_RETRY_OPTIONS = { secondaryHost: "", tryTimeoutInMs: undefined // Use server side default timeout strategy }; -var RETRY_ABORT_ERROR = new abortController.AbortError("The operation was aborted."); +const RETRY_ABORT_ERROR = new abortController.AbortError("The operation was aborted."); /** * Retry policy with exponential retry and linear retry implemented. */ -var StorageRetryPolicy = /** @class */ (function (_super) { - tslib.__extends(StorageRetryPolicy, _super); +class StorageRetryPolicy extends coreHttp.BaseRequestPolicy { /** * Creates an instance of RetryPolicy. * @@ -25435,11 +23095,10 @@ var StorageRetryPolicy = /** @class */ (function (_super) { * @param options - * @param retryOptions - */ - function StorageRetryPolicy(nextPolicy, options, retryOptions) { - if (retryOptions === void 0) { retryOptions = DEFAULT_RETRY_OPTIONS; } - var _this = _super.call(this, nextPolicy, options) || this; + constructor(nextPolicy, options, retryOptions = DEFAULT_RETRY_OPTIONS) { + super(nextPolicy, options); // Initialize retry options - _this.retryOptions = { + this.retryOptions = { retryPolicyType: retryOptions.retryPolicyType ? retryOptions.retryPolicyType : DEFAULT_RETRY_OPTIONS.retryPolicyType, @@ -25461,20 +23120,15 @@ var StorageRetryPolicy = /** @class */ (function (_super) { ? retryOptions.secondaryHost : DEFAULT_RETRY_OPTIONS.secondaryHost }; - return _this; } /** * Sends request. * * @param request - */ - StorageRetryPolicy.prototype.sendRequest = function (request) { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - return [2 /*return*/, this.attemptSendRequest(request, false, 1)]; - }); - }); - }; + async sendRequest(request) { + return this.attemptSendRequest(request, false, 1); + } /** * Decide and perform next retry. Won't mutate request parameter. * @@ -25485,52 +23139,37 @@ var StorageRetryPolicy = /** @class */ (function (_super) { * @param attempt - How many retries has been attempted to performed, starting from 1, which includes * the attempt will be performed by this method call. */ - StorageRetryPolicy.prototype.attemptSendRequest = function (request, secondaryHas404, attempt) { - return tslib.__awaiter(this, void 0, void 0, function () { - var newRequest, isPrimaryRetry, response, err_1; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - newRequest = request.clone(); - isPrimaryRetry = secondaryHas404 || - !this.retryOptions.secondaryHost || - !(request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS") || - attempt % 2 === 1; - if (!isPrimaryRetry) { - newRequest.url = setURLHost(newRequest.url, this.retryOptions.secondaryHost); - } - // Set the server-side timeout query parameter "timeout=[seconds]" - if (this.retryOptions.tryTimeoutInMs) { - newRequest.url = setURLParameter(newRequest.url, URLConstants.Parameters.TIMEOUT, Math.floor(this.retryOptions.tryTimeoutInMs / 1000).toString()); - } - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - logger.info("RetryPolicy: =====> Try=" + attempt + " " + (isPrimaryRetry ? "Primary" : "Secondary")); - return [4 /*yield*/, this._nextPolicy.sendRequest(newRequest)]; - case 2: - response = _a.sent(); - if (!this.shouldRetry(isPrimaryRetry, attempt, response)) { - return [2 /*return*/, response]; - } - secondaryHas404 = secondaryHas404 || (!isPrimaryRetry && response.status === 404); - return [3 /*break*/, 4]; - case 3: - err_1 = _a.sent(); - logger.error("RetryPolicy: Caught error, message: " + err_1.message + ", code: " + err_1.code); - if (!this.shouldRetry(isPrimaryRetry, attempt, response, err_1)) { - throw err_1; - } - return [3 /*break*/, 4]; - case 4: return [4 /*yield*/, this.delay(isPrimaryRetry, attempt, request.abortSignal)]; - case 5: - _a.sent(); - return [4 /*yield*/, this.attemptSendRequest(request, secondaryHas404, ++attempt)]; - case 6: return [2 /*return*/, _a.sent()]; - } - }); - }); - }; + async attemptSendRequest(request, secondaryHas404, attempt) { + const newRequest = request.clone(); + const isPrimaryRetry = secondaryHas404 || + !this.retryOptions.secondaryHost || + !(request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS") || + attempt % 2 === 1; + if (!isPrimaryRetry) { + newRequest.url = setURLHost(newRequest.url, this.retryOptions.secondaryHost); + } + // Set the server-side timeout query parameter "timeout=[seconds]" + if (this.retryOptions.tryTimeoutInMs) { + newRequest.url = setURLParameter(newRequest.url, URLConstants.Parameters.TIMEOUT, Math.floor(this.retryOptions.tryTimeoutInMs / 1000).toString()); + } + let response; + try { + logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`); + response = await this._nextPolicy.sendRequest(newRequest); + if (!this.shouldRetry(isPrimaryRetry, attempt, response)) { + return response; + } + secondaryHas404 = secondaryHas404 || (!isPrimaryRetry && response.status === 404); + } + catch (err) { + logger.error(`RetryPolicy: Caught error, message: ${err.message}, code: ${err.code}`); + if (!this.shouldRetry(isPrimaryRetry, attempt, response, err)) { + throw err; + } + } + await this.delay(isPrimaryRetry, attempt, request.abortSignal); + return this.attemptSendRequest(request, secondaryHas404, ++attempt); + } /** * Decide whether to retry according to last HTTP response and retry counters. * @@ -25539,15 +23178,15 @@ var StorageRetryPolicy = /** @class */ (function (_super) { * @param response - * @param err - */ - StorageRetryPolicy.prototype.shouldRetry = function (isPrimaryRetry, attempt, response, err) { + shouldRetry(isPrimaryRetry, attempt, response, err) { if (attempt >= this.retryOptions.maxTries) { - logger.info("RetryPolicy: Attempt(s) " + attempt + " >= maxTries " + this.retryOptions - .maxTries + ", no further try."); + logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${this.retryOptions + .maxTries}, no further try.`); return false; } // Handle network failures, you may need to customize the list when you implement // your own http client - var retriableErrors = [ + const retriableErrors = [ "ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNREFUSED", @@ -25559,12 +23198,11 @@ var StorageRetryPolicy = /** @class */ (function (_super) { "REQUEST_SEND_ERROR" // For default xhr based http client provided in ms-rest-js ]; if (err) { - for (var _i = 0, retriableErrors_1 = retriableErrors; _i < retriableErrors_1.length; _i++) { - var retriableError = retriableErrors_1[_i]; + for (const retriableError of retriableErrors) { if (err.name.toUpperCase().includes(retriableError) || err.message.toUpperCase().includes(retriableError) || (err.code && err.code.toString().toUpperCase() === retriableError)) { - logger.info("RetryPolicy: Network error " + retriableError + " found, will retry."); + logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`); return true; } } @@ -25573,23 +23211,23 @@ var StorageRetryPolicy = /** @class */ (function (_super) { // the resource was not found. This may be due to replication delay. So, in this // case, we'll never try the secondary again for this operation. if (response || err) { - var statusCode = response ? response.status : err ? err.statusCode : 0; + const statusCode = response ? response.status : err ? err.statusCode : 0; if (!isPrimaryRetry && statusCode === 404) { - logger.info("RetryPolicy: Secondary access with 404, will retry."); + logger.info(`RetryPolicy: Secondary access with 404, will retry.`); return true; } // Server internal error or server timeout if (statusCode === 503 || statusCode === 500) { - logger.info("RetryPolicy: Will retry for status code " + statusCode + "."); + logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`); 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"))) { + 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; - }; + } /** * Delay a calculated time between retries. * @@ -25597,42 +23235,36 @@ var StorageRetryPolicy = /** @class */ (function (_super) { * @param attempt - * @param abortSignal - */ - StorageRetryPolicy.prototype.delay = function (isPrimaryRetry, attempt, abortSignal) { - return tslib.__awaiter(this, void 0, void 0, function () { - var delayTimeInMs; - return tslib.__generator(this, function (_a) { - delayTimeInMs = 0; - if (isPrimaryRetry) { - switch (this.retryOptions.retryPolicyType) { - case exports.StorageRetryPolicyType.EXPONENTIAL: - delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * this.retryOptions.retryDelayInMs, this.retryOptions.maxRetryDelayInMs); - break; - case exports.StorageRetryPolicyType.FIXED: - delayTimeInMs = this.retryOptions.retryDelayInMs; - break; - } - } - else { - delayTimeInMs = Math.random() * 1000; - } - logger.info("RetryPolicy: Delay for " + delayTimeInMs + "ms"); - return [2 /*return*/, delay(delayTimeInMs, abortSignal, RETRY_ABORT_ERROR)]; - }); - }); - }; - return StorageRetryPolicy; -}(coreHttp.BaseRequestPolicy)); + async delay(isPrimaryRetry, attempt, abortSignal) { + let delayTimeInMs = 0; + if (isPrimaryRetry) { + switch (this.retryOptions.retryPolicyType) { + case exports.StorageRetryPolicyType.EXPONENTIAL: + delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * this.retryOptions.retryDelayInMs, this.retryOptions.maxRetryDelayInMs); + break; + case exports.StorageRetryPolicyType.FIXED: + delayTimeInMs = this.retryOptions.retryDelayInMs; + break; + } + } + else { + delayTimeInMs = Math.random() * 1000; + } + logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`); + return delay(delayTimeInMs, abortSignal, RETRY_ABORT_ERROR); + } +} // Copyright (c) Microsoft Corporation. /** * StorageRetryPolicyFactory is a factory class helping generating {@link StorageRetryPolicy} objects. */ -var StorageRetryPolicyFactory = /** @class */ (function () { +class StorageRetryPolicyFactory { /** * Creates an instance of StorageRetryPolicyFactory. * @param retryOptions - */ - function StorageRetryPolicyFactory(retryOptions) { + constructor(retryOptions) { this.retryOptions = retryOptions; } /** @@ -25641,61 +23273,55 @@ var StorageRetryPolicyFactory = /** @class */ (function () { * @param nextPolicy - * @param options - */ - StorageRetryPolicyFactory.prototype.create = function (nextPolicy, options) { + create(nextPolicy, options) { return new StorageRetryPolicy(nextPolicy, options, this.retryOptions); - }; - return StorageRetryPolicyFactory; -}()); + } +} // Copyright (c) Microsoft Corporation. /** * Credential policy used to sign HTTP(S) requests before sending. This is an * abstract class. */ -var CredentialPolicy = /** @class */ (function (_super) { - tslib.__extends(CredentialPolicy, _super); - function CredentialPolicy() { - return _super !== null && _super.apply(this, arguments) || this; - } +class CredentialPolicy extends coreHttp.BaseRequestPolicy { /** * Sends out request. * * @param request - */ - CredentialPolicy.prototype.sendRequest = function (request) { + sendRequest(request) { return this._nextPolicy.sendRequest(this.signRequest(request)); - }; + } /** * Child classes must implement this method with request signing. This method * will be executed in {@link sendRequest}. * * @param request - */ - CredentialPolicy.prototype.signRequest = function (request) { + signRequest(request) { // Child classes must override this method with request signing. This method // will be executed in sendRequest(). return request; - }; - return CredentialPolicy; -}(coreHttp.BaseRequestPolicy)); + } +} // Copyright (c) Microsoft Corporation. /** * AnonymousCredentialPolicy is used with HTTP(S) requests that read public resources * or for use with Shared Access Signatures (SAS). */ -var AnonymousCredentialPolicy = /** @class */ (function (_super) { - tslib.__extends(AnonymousCredentialPolicy, _super); +class AnonymousCredentialPolicy extends CredentialPolicy { /** * Creates an instance of AnonymousCredentialPolicy. * @param nextPolicy - * @param options - */ - function AnonymousCredentialPolicy(nextPolicy, options) { - return _super.call(this, nextPolicy, options) || this; + // The base class has a protected constructor. Adding a public one to enable constructing of this class. + /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ + constructor(nextPolicy, options) { + super(nextPolicy, options); } - return AnonymousCredentialPolicy; -}(CredentialPolicy)); +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -25703,24 +23329,17 @@ var AnonymousCredentialPolicy = /** @class */ (function (_super) { * Credential is an abstract class for Azure Storage HTTP requests signing. This * class will host an credentialPolicyCreator factory which generates CredentialPolicy. */ -var Credential = /** @class */ (function () { - function Credential() { - } +class Credential { /** * Creates a RequestPolicy object. * * @param _nextPolicy - * @param _options - */ - Credential.prototype.create = function ( - // tslint:disable-next-line:variable-name - _nextPolicy, - // tslint:disable-next-line:variable-name - _options) { + create(_nextPolicy, _options) { throw new Error("Method should be implemented in children classes."); - }; - return Credential; -}()); + } +} // Copyright (c) Microsoft Corporation. /** @@ -25729,88 +23348,76 @@ var Credential = /** @class */ (function () { * HTTP(S) requests that read public resources or for use with Shared Access * Signatures (SAS). */ -var AnonymousCredential = /** @class */ (function (_super) { - tslib.__extends(AnonymousCredential, _super); - function AnonymousCredential() { - return _super !== null && _super.apply(this, arguments) || this; - } +class AnonymousCredential extends Credential { /** * Creates an {@link AnonymousCredentialPolicy} object. * * @param nextPolicy - * @param options - */ - AnonymousCredential.prototype.create = function (nextPolicy, options) { + create(nextPolicy, options) { return new AnonymousCredentialPolicy(nextPolicy, options); - }; - return AnonymousCredential; -}(Credential)); + } +} // Copyright (c) Microsoft Corporation. /** * TelemetryPolicy is a policy used to tag user-agent header for every requests. */ -var TelemetryPolicy = /** @class */ (function (_super) { - tslib.__extends(TelemetryPolicy, _super); +class TelemetryPolicy extends coreHttp.BaseRequestPolicy { /** * Creates an instance of TelemetryPolicy. * @param nextPolicy - * @param options - * @param telemetry - */ - function TelemetryPolicy(nextPolicy, options, telemetry) { - var _this = _super.call(this, nextPolicy, options) || this; - _this.telemetry = telemetry; - return _this; + constructor(nextPolicy, options, telemetry) { + super(nextPolicy, options); + this.telemetry = telemetry; } /** * Sends out request. * * @param request - */ - TelemetryPolicy.prototype.sendRequest = function (request) { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - { - if (!request.headers) { - request.headers = new coreHttp.HttpHeaders(); - } - if (!request.headers.get(HeaderConstants.USER_AGENT)) { - request.headers.set(HeaderConstants.USER_AGENT, this.telemetry); - } - } - return [2 /*return*/, this._nextPolicy.sendRequest(request)]; - }); - }); - }; - return TelemetryPolicy; -}(coreHttp.BaseRequestPolicy)); + async sendRequest(request) { + { + if (!request.headers) { + request.headers = new coreHttp.HttpHeaders(); + } + if (!request.headers.get(HeaderConstants.USER_AGENT)) { + request.headers.set(HeaderConstants.USER_AGENT, this.telemetry); + } + } + return this._nextPolicy.sendRequest(request); + } +} // Copyright (c) Microsoft Corporation. /** * TelemetryPolicyFactory is a factory class helping generating {@link TelemetryPolicy} objects. */ -var TelemetryPolicyFactory = /** @class */ (function () { +class TelemetryPolicyFactory { /** * Creates an instance of TelemetryPolicyFactory. * @param telemetry - */ - function TelemetryPolicyFactory(telemetry) { - var userAgentInfo = []; + constructor(telemetry) { + const userAgentInfo = []; { if (telemetry) { - var telemetryString = telemetry.userAgentPrefix || ""; + const telemetryString = telemetry.userAgentPrefix || ""; if (telemetryString.length > 0 && userAgentInfo.indexOf(telemetryString) === -1) { userAgentInfo.push(telemetryString); } } // e.g. azsdk-js-storageblob/10.0.0 - var libInfo = "azsdk-js-storageblob/" + SDK_VERSION; + const libInfo = `azsdk-js-storageblob/${SDK_VERSION}`; if (userAgentInfo.indexOf(libInfo) === -1) { userAgentInfo.push(libInfo); } // e.g. (NODE-VERSION 4.9.1; Windows_NT 10.0.16299) - var runtimeInfo = "(NODE-VERSION " + process.version + "; " + os.type() + " " + os.release() + ")"; + const runtimeInfo = `(NODE-VERSION ${process.version}; ${os.type()} ${os.release()})`; if (userAgentInfo.indexOf(runtimeInfo) === -1) { userAgentInfo.push(runtimeInfo); } @@ -25823,19 +23430,32 @@ var TelemetryPolicyFactory = /** @class */ (function () { * @param nextPolicy - * @param options - */ - TelemetryPolicyFactory.prototype.create = function (nextPolicy, options) { + create(nextPolicy, options) { return new TelemetryPolicy(nextPolicy, options, this.telemetryString); - }; - return TelemetryPolicyFactory; -}()); + } +} // Copyright (c) Microsoft Corporation. -var _defaultHttpClient = new coreHttp.DefaultHttpClient(); +const _defaultHttpClient = new coreHttp.DefaultHttpClient(); function getCachedDefaultHttpClient() { return _defaultHttpClient; } // Copyright (c) Microsoft Corporation. +/** + * A helper to decide if a given argument satisfies the Pipeline contract + * @param pipeline - An argument that may be a Pipeline + * @returns true when the argument satisfies the Pipeline contract + */ +function isPipelineLike(pipeline) { + if (!pipeline || typeof pipeline !== "object") { + return false; + } + const castPipeline = pipeline; + return (Array.isArray(castPipeline.factories) && + typeof castPipeline.options === "object" && + typeof castPipeline.toServiceClientOptions === "function"); +} /** * A Pipeline class containing HTTP request policies. * You can create a default Pipeline by calling {@link newPipeline}. @@ -25844,19 +23464,18 @@ function getCachedDefaultHttpClient() { * Refer to {@link newPipeline} and provided policies before implementing your * customized Pipeline. */ -var Pipeline = /** @class */ (function () { +class Pipeline { /** * Creates an instance of Pipeline. Customize HTTPClient by implementing IHttpClient interface. * * @param factories - * @param options - */ - function Pipeline(factories, options) { - if (options === void 0) { options = {}; } + constructor(factories, options = {}) { this.factories = factories; // when options.httpClient is not specified, passing in a DefaultHttpClient instance to // avoid each client creating its own http client. - this.options = tslib.__assign(tslib.__assign({}, options), { httpClient: options.httpClient || getCachedDefaultHttpClient() }); + this.options = Object.assign(Object.assign({}, options), { httpClient: options.httpClient || getCachedDefaultHttpClient() }); } /** * Transfer Pipeline object to ServiceClientOptions object which is required by @@ -25864,14 +23483,13 @@ var Pipeline = /** @class */ (function () { * * @returns The ServiceClientOptions object from this Pipeline. */ - Pipeline.prototype.toServiceClientOptions = function () { + toServiceClientOptions() { return { httpClient: this.options.httpClient, requestPolicyFactories: this.factories }; - }; - return Pipeline; -}()); + } +} /** * Creates a new Pipeline object with Credential provided. * @@ -25879,16 +23497,15 @@ var Pipeline = /** @class */ (function () { * @param pipelineOptions - Optional. Options. * @returns A new Pipeline object. */ -function newPipeline(credential, pipelineOptions) { - if (pipelineOptions === void 0) { pipelineOptions = {}; } +function newPipeline(credential, pipelineOptions = {}) { if (credential === undefined) { credential = new AnonymousCredential(); } // Order is important. Closer to the API at the top & closer to the network at the bottom. // The credential's policy factory must appear close to the wire so it can sign any // changes made by other factories (like UniqueRequestIDPolicyFactory) - var telemetryPolicy = new TelemetryPolicyFactory(pipelineOptions.userAgentOptions); - var factories = [ + const telemetryPolicy = new TelemetryPolicyFactory(pipelineOptions.userAgentOptions); + const factories = [ coreHttp.tracingPolicy({ userAgent: telemetryPolicy.telemetryString }), coreHttp.keepAlivePolicy(pipelineOptions.keepAliveOptions), telemetryPolicy, @@ -25920,30 +23537,28 @@ function newPipeline(credential, pipelineOptions) { /** * StorageSharedKeyCredentialPolicy is a policy used to sign HTTP request with a shared key. */ -var StorageSharedKeyCredentialPolicy = /** @class */ (function (_super) { - tslib.__extends(StorageSharedKeyCredentialPolicy, _super); +class StorageSharedKeyCredentialPolicy extends CredentialPolicy { /** * Creates an instance of StorageSharedKeyCredentialPolicy. * @param nextPolicy - * @param options - * @param factory - */ - function StorageSharedKeyCredentialPolicy(nextPolicy, options, factory) { - var _this = _super.call(this, nextPolicy, options) || this; - _this.factory = factory; - return _this; + constructor(nextPolicy, options, factory) { + super(nextPolicy, options); + this.factory = factory; } /** * Signs request. * * @param request - */ - StorageSharedKeyCredentialPolicy.prototype.signRequest = function (request) { + signRequest(request) { request.headers.set(HeaderConstants.X_MS_DATE, new Date().toUTCString()); if (request.body && typeof request.body === "string" && request.body.length > 0) { request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); } - var stringToSign = [ + const stringToSign = [ request.method.toUpperCase(), this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LANGUAGE), this.getHeaderValueToSign(request, HeaderConstants.CONTENT_ENCODING), @@ -25960,14 +23575,14 @@ var StorageSharedKeyCredentialPolicy = /** @class */ (function (_super) { "\n" + this.getCanonicalizedHeadersString(request) + this.getCanonicalizedResourceString(request); - var signature = this.factory.computeHMACSHA256(stringToSign); - request.headers.set(HeaderConstants.AUTHORIZATION, "SharedKey " + this.factory.accountName + ":" + signature); + const signature = this.factory.computeHMACSHA256(stringToSign); + request.headers.set(HeaderConstants.AUTHORIZATION, `SharedKey ${this.factory.accountName}:${signature}`); // console.log(`[URL]:${request.url}`); // console.log(`[HEADERS]:${request.headers.toString()}`); // console.log(`[STRING TO SIGN]:${JSON.stringify(stringToSign)}`); // console.log(`[KEY]: ${request.headers.get(HeaderConstants.AUTHORIZATION)}`); return request; - }; + } /** * Retrieve header value according to shared key sign rules. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key @@ -25975,8 +23590,8 @@ var StorageSharedKeyCredentialPolicy = /** @class */ (function (_super) { * @param request - * @param headerName - */ - StorageSharedKeyCredentialPolicy.prototype.getHeaderValueToSign = function (request, headerName) { - var value = request.headers.get(headerName); + getHeaderValueToSign(request, headerName) { + const value = request.headers.get(headerName); if (!value) { return ""; } @@ -25987,7 +23602,7 @@ var StorageSharedKeyCredentialPolicy = /** @class */ (function (_super) { return ""; } return value; - }; + } /** * To construct the CanonicalizedHeaders portion of the signature string, follow these steps: * 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header. @@ -26001,58 +23616,56 @@ var StorageSharedKeyCredentialPolicy = /** @class */ (function (_super) { * * @param request - */ - StorageSharedKeyCredentialPolicy.prototype.getCanonicalizedHeadersString = function (request) { - var headersArray = request.headers.headersArray().filter(function (value) { + getCanonicalizedHeadersString(request) { + let headersArray = request.headers.headersArray().filter((value) => { return value.name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE); }); - headersArray.sort(function (a, b) { + headersArray.sort((a, b) => { return a.name.toLowerCase().localeCompare(b.name.toLowerCase()); }); // Remove duplicate headers - headersArray = headersArray.filter(function (value, index, array) { + headersArray = headersArray.filter((value, index, array) => { if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) { return false; } return true; }); - var canonicalizedHeadersStringToSign = ""; - headersArray.forEach(function (header) { - canonicalizedHeadersStringToSign += header.name + let canonicalizedHeadersStringToSign = ""; + headersArray.forEach((header) => { + canonicalizedHeadersStringToSign += `${header.name .toLowerCase() - .trimRight() + ":" + header.value.trimLeft() + "\n"; + .trimRight()}:${header.value.trimLeft()}\n`; }); return canonicalizedHeadersStringToSign; - }; + } /** * Retrieves the webResource canonicalized resource string. * * @param request - */ - StorageSharedKeyCredentialPolicy.prototype.getCanonicalizedResourceString = function (request) { - var path = getURLPath(request.url) || "/"; - var canonicalizedResourceString = ""; - canonicalizedResourceString += "/" + this.factory.accountName + path; - var queries = getURLQueries(request.url); - var lowercaseQueries = {}; + getCanonicalizedResourceString(request) { + const path = getURLPath(request.url) || "/"; + let canonicalizedResourceString = ""; + canonicalizedResourceString += `/${this.factory.accountName}${path}`; + const queries = getURLQueries(request.url); + const lowercaseQueries = {}; if (queries) { - var queryKeys = []; - for (var key in queries) { - if (queries.hasOwnProperty(key)) { - var lowercaseKey = key.toLowerCase(); + const queryKeys = []; + for (const key in queries) { + if (Object.prototype.hasOwnProperty.call(queries, key)) { + const lowercaseKey = key.toLowerCase(); lowercaseQueries[lowercaseKey] = queries[key]; queryKeys.push(lowercaseKey); } } queryKeys.sort(); - for (var _i = 0, queryKeys_1 = queryKeys; _i < queryKeys_1.length; _i++) { - var key = queryKeys_1[_i]; - canonicalizedResourceString += "\n" + key + ":" + decodeURIComponent(lowercaseQueries[key]); + for (const key of queryKeys) { + canonicalizedResourceString += `\n${key}:${decodeURIComponent(lowercaseQueries[key])}`; } } return canonicalizedResourceString; - }; - return StorageSharedKeyCredentialPolicy; -}(CredentialPolicy)); + } +} // Copyright (c) Microsoft Corporation. /** @@ -26060,18 +23673,16 @@ var StorageSharedKeyCredentialPolicy = /** @class */ (function (_super) { * * StorageSharedKeyCredential for account key authorization of Azure Storage service. */ -var StorageSharedKeyCredential = /** @class */ (function (_super) { - tslib.__extends(StorageSharedKeyCredential, _super); +class StorageSharedKeyCredential extends Credential { /** * Creates an instance of StorageSharedKeyCredential. * @param accountName - * @param accountKey - */ - function StorageSharedKeyCredential(accountName, accountKey) { - var _this = _super.call(this) || this; - _this.accountName = accountName; - _this.accountKey = Buffer.from(accountKey, "base64"); - return _this; + constructor(accountName, accountKey) { + super(); + this.accountName = accountName; + this.accountKey = Buffer.from(accountKey, "base64"); } /** * Creates a StorageSharedKeyCredentialPolicy object. @@ -26079,21 +23690,20 @@ var StorageSharedKeyCredential = /** @class */ (function (_super) { * @param nextPolicy - * @param options - */ - StorageSharedKeyCredential.prototype.create = function (nextPolicy, options) { + create(nextPolicy, options) { return new StorageSharedKeyCredentialPolicy(nextPolicy, options, this); - }; + } /** * Generates a hash signature for an HTTP request or for a SAS. * * @param stringToSign - */ - StorageSharedKeyCredential.prototype.computeHMACSHA256 = function (stringToSign) { + computeHMACSHA256(stringToSign) { return crypto.createHmac("sha256", this.accountKey) .update(stringToSign, "utf8") .digest("base64"); - }; - return StorageSharedKeyCredential; -}(Credential)); + } +} /* * Copyright (c) Microsoft Corporation. @@ -26102,18 +23712,16 @@ var StorageSharedKeyCredential = /** @class */ (function (_super) { * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ -var packageName = "azure-storage-blob"; -var packageVersion = "12.6.0-beta.1"; -var StorageClientContext = /** @class */ (function (_super) { - tslib.__extends(StorageClientContext, _super); +const packageName = "azure-storage-blob"; +const packageVersion = "12.8.0"; +class StorageClientContext extends coreHttp.ServiceClient { /** * Initializes a new instance of the StorageClientContext class. - * @param url The URL of the service account, container, or blob that is the targe of the desired + * @param url The URL of the service account, container, or blob that is the target of the desired * operation. * @param options The parameter options */ - function StorageClientContext(url, options) { - var _this = this; + constructor(url, options) { if (url === undefined) { throw new Error("'url' cannot be null"); } @@ -26122,33 +23730,31 @@ var StorageClientContext = /** @class */ (function (_super) { options = {}; } if (!options.userAgent) { - var defaultUserAgent = coreHttp.getDefaultUserAgentValue(); - options.userAgent = packageName + "/" + packageVersion + " " + defaultUserAgent; + const defaultUserAgent = coreHttp.getDefaultUserAgentValue(); + options.userAgent = `${packageName}/${packageVersion} ${defaultUserAgent}`; } - _this = _super.call(this, undefined, options) || this; - _this.requestContentType = "application/json; charset=utf-8"; - _this.baseUri = options.endpoint || "{url}"; + super(undefined, options); + this.requestContentType = "application/json; charset=utf-8"; + this.baseUri = options.endpoint || "{url}"; // Parameter assignments - _this.url = url; + this.url = url; // Assigning values to Constant parameters - _this.version = options.version || "2020-08-04"; - return _this; + this.version = options.version || "2020-10-02"; } - return StorageClientContext; -}(coreHttp.ServiceClient)); +} // Copyright (c) Microsoft Corporation. /** * A StorageClient represents a based URL class for {@link BlobServiceClient}, {@link ContainerClient} * and etc. */ -var StorageClient = /** @class */ (function () { +class StorageClient { /** * Creates an instance of StorageClient. * @param url - url to resource * @param pipeline - request policy pipeline. */ - function StorageClient(url, pipeline) { + constructor(url, pipeline) { // URL should be encoded and only once, protocol layer shouldn't encode URL again this.url = escapeURLPath(url); this.accountName = getAccountNameFromUrl(url); @@ -26156,8 +23762,7 @@ var StorageClient = /** @class */ (function () { this.storageClientContext = new StorageClientContext(this.url, pipeline.toServiceClientOptions()); this.isHttps = iEqual(getURLScheme(this.url) || "", "https"); this.credential = new AnonymousCredential(); - for (var _i = 0, _a = this.pipeline.factories; _i < _a.length; _i++) { - var factory = _a[_i]; + for (const factory of this.pipeline.factories) { if ((coreHttp.isNode && factory instanceof StorageSharedKeyCredential) || factory instanceof AnonymousCredential) { this.credential = factory; @@ -26169,18 +23774,17 @@ var StorageClient = /** @class */ (function () { } } // Override protocol layer's default content-type - var storageClientContext = this.storageClientContext; + const storageClientContext = this.storageClientContext; storageClientContext.requestContentType = undefined; } - return StorageClient; -}()); +} // Copyright (c) Microsoft Corporation. /** * Creates a span using the global tracer. * @internal */ -var createSpan = coreTracing.createSpanFunction({ +const createSpan = coreTracing.createSpanFunction({ packagePrefix: "Azure.Storage.Blob", namespace: "Microsoft.Storage" }); @@ -26194,6 +23798,7 @@ var createSpan = coreTracing.createSpanFunction({ function convertTracingToRequestOptionsBase(options) { var _a, _b; return { + // By passing spanOptions if they exist at runtime, we're backwards compatible with @azure/core-tracing@preview.13 and earlier. spanOptions: (_a = options === null || options === void 0 ? void 0 : options.tracingOptions) === null || _a === void 0 ? void 0 : _a.spanOptions, tracingContext: (_b = options === null || options === void 0 ? void 0 : options.tracingOptions) === null || _b === void 0 ? void 0 : _b.tracingContext }; @@ -26210,8 +23815,8 @@ function convertTracingToRequestOptionsBase(options) { * {@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. */ -var BlobSASPermissions = /** @class */ (function () { - function BlobSASPermissions() { +class BlobSASPermissions { + constructor() { /** * Specifies Read access granted. */ @@ -26248,6 +23853,10 @@ var BlobSASPermissions = /** @class */ (function () { * Specifies Execute access granted. */ this.execute = false; + /** + * Specifies SetImmutabilityPolicy access granted. + */ + this.setImmutabilityPolicy = false; } /** * Creates a {@link BlobSASPermissions} from the specified permissions string. This method will throw an @@ -26255,10 +23864,9 @@ var BlobSASPermissions = /** @class */ (function () { * * @param permissions - */ - 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]; + static parse(permissions) { + const blobSASPermissions = new BlobSASPermissions(); + for (const char of permissions) { switch (char) { case "r": blobSASPermissions.read = true; @@ -26287,20 +23895,23 @@ var BlobSASPermissions = /** @class */ (function () { case "e": blobSASPermissions.execute = true; break; + case "i": + blobSASPermissions.setImmutabilityPolicy = true; + break; default: - throw new RangeError("Invalid permission: " + char); + throw new RangeError(`Invalid permission: ${char}`); } } return blobSASPermissions; - }; + } /** * Creates a {@link BlobSASPermissions} from a raw object which contains same keys as it * and boolean values for them. * * @param permissionLike - */ - BlobSASPermissions.from = function (permissionLike) { - var blobSASPermissions = new BlobSASPermissions(); + static from(permissionLike) { + const blobSASPermissions = new BlobSASPermissions(); if (permissionLike.read) { blobSASPermissions.read = true; } @@ -26328,16 +23939,19 @@ var BlobSASPermissions = /** @class */ (function () { if (permissionLike.execute) { blobSASPermissions.execute = true; } + if (permissionLike.setImmutabilityPolicy) { + blobSASPermissions.setImmutabilityPolicy = true; + } return blobSASPermissions; - }; + } /** * Converts the given permissions to a string. Using this method will guarantee the permissions are in an * order accepted by the service. * * @returns A string which represents the BlobSASPermissions */ - BlobSASPermissions.prototype.toString = function () { - var permissions = []; + toString() { + const permissions = []; if (this.read) { permissions.push("r"); } @@ -26365,10 +23979,12 @@ var BlobSASPermissions = /** @class */ (function () { if (this.execute) { permissions.push("e"); } + if (this.setImmutabilityPolicy) { + permissions.push("i"); + } return permissions.join(""); - }; - return BlobSASPermissions; -}()); + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -26379,8 +23995,8 @@ var BlobSASPermissions = /** @class */ (function () { * {@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. */ -var ContainerSASPermissions = /** @class */ (function () { - function ContainerSASPermissions() { +class ContainerSASPermissions { + constructor() { /** * Specifies Read access granted. */ @@ -26421,6 +24037,10 @@ var ContainerSASPermissions = /** @class */ (function () { * Specifies Execute access granted. */ this.execute = false; + /** + * Specifies SetImmutabilityPolicy access granted. + */ + this.setImmutabilityPolicy = false; } /** * Creates an {@link ContainerSASPermissions} from the specified permissions string. This method will throw an @@ -26428,10 +24048,9 @@ var ContainerSASPermissions = /** @class */ (function () { * * @param permissions - */ - 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]; + static parse(permissions) { + const containerSASPermissions = new ContainerSASPermissions(); + for (const char of permissions) { switch (char) { case "r": containerSASPermissions.read = true; @@ -26463,20 +24082,23 @@ var ContainerSASPermissions = /** @class */ (function () { case "e": containerSASPermissions.execute = true; break; + case "i": + containerSASPermissions.setImmutabilityPolicy = true; + break; default: - throw new RangeError("Invalid permission " + char); + throw new RangeError(`Invalid permission ${char}`); } } return containerSASPermissions; - }; + } /** * Creates a {@link ContainerSASPermissions} from a raw object which contains same keys as it * and boolean values for them. * * @param permissionLike - */ - ContainerSASPermissions.from = function (permissionLike) { - var containerSASPermissions = new ContainerSASPermissions(); + static from(permissionLike) { + const containerSASPermissions = new ContainerSASPermissions(); if (permissionLike.read) { containerSASPermissions.read = true; } @@ -26507,8 +24129,11 @@ var ContainerSASPermissions = /** @class */ (function () { if (permissionLike.execute) { containerSASPermissions.execute = true; } + if (permissionLike.setImmutabilityPolicy) { + containerSASPermissions.setImmutabilityPolicy = true; + } return containerSASPermissions; - }; + } /** * Converts the given permissions to a string. Using this method will guarantee the permissions are in an * order accepted by the service. @@ -26517,8 +24142,8 @@ var ContainerSASPermissions = /** @class */ (function () { * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * */ - ContainerSASPermissions.prototype.toString = function () { - var permissions = []; + toString() { + const permissions = []; if (this.read) { permissions.push("r"); } @@ -26549,10 +24174,12 @@ var ContainerSASPermissions = /** @class */ (function () { if (this.execute) { permissions.push("e"); } + if (this.setImmutabilityPolicy) { + permissions.push("i"); + } return permissions.join(""); - }; - return ContainerSASPermissions; -}()); + } +} // Copyright (c) Microsoft Corporation. /** @@ -26561,13 +24188,13 @@ var ContainerSASPermissions = /** @class */ (function () { * UserDelegationKeyCredential is only used for generation of user delegation SAS. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas */ -var UserDelegationKeyCredential = /** @class */ (function () { +class UserDelegationKeyCredential { /** * Creates an instance of UserDelegationKeyCredential. * @param accountName - * @param userDelegationKey - */ - function UserDelegationKeyCredential(accountName, userDelegationKey) { + constructor(accountName, userDelegationKey) { this.accountName = accountName; this.userDelegationKey = userDelegationKey; this.key = Buffer.from(userDelegationKey.value, "base64"); @@ -26577,14 +24204,13 @@ var UserDelegationKeyCredential = /** @class */ (function () { * * @param stringToSign - */ - UserDelegationKeyCredential.prototype.computeHMACSHA256 = function (stringToSign) { + computeHMACSHA256(stringToSign) { // console.log(`stringToSign: ${JSON.stringify(stringToSign)}`); return crypto.createHmac("sha256", this.key) .update(stringToSign, "utf8") .digest("base64"); - }; - return UserDelegationKeyCredential; -}()); + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -26596,7 +24222,7 @@ var UserDelegationKeyCredential = /** @class */ (function () { * @param ipRange - */ function ipRangeToString(ipRange) { - return ipRange.end ? ipRange.start + "-" + ipRange.end : ipRange.start; + return ipRange.end ? `${ipRange.start}-${ipRange.end}` : ipRange.start; } // Copyright (c) Microsoft Corporation. @@ -26613,14 +24239,14 @@ function ipRangeToString(ipRange) { /** * 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 + * types. Once generated, it can be encoded into a {@link 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. */ -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) { +class SASQueryParameters { + constructor(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") { @@ -26677,30 +24303,26 @@ var SASQueryParameters = /** @class */ (function () { } } } - Object.defineProperty(SASQueryParameters.prototype, "ipRange", { - /** - * Optional. IP range allowed for this SAS. - * - * @readonly - */ - get: function () { - if (this.ipRangeInner) { - return { - end: this.ipRangeInner.end, - start: this.ipRangeInner.start - }; - } - return undefined; - }, - enumerable: false, - configurable: true - }); + /** + * Optional. IP range allowed for this SAS. + * + * @readonly + */ + get ipRange() { + if (this.ipRangeInner) { + return { + end: this.ipRangeInner.end, + start: this.ipRangeInner.start + }; + } + return undefined; + } /** * Encodes all SAS query parameters into a string that can be appended to a URL. * */ - SASQueryParameters.prototype.toString = function () { - var params = [ + toString() { + const params = [ "sv", "ss", "srt", @@ -26726,9 +24348,8 @@ var SASQueryParameters = /** @class */ (function () { "saoid", "scid" ]; - var queries = []; - for (var _i = 0, params_1 = params; _i < params_1.length; _i++) { - var param = params_1[_i]; + const queries = []; + for (const param of params) { switch (param) { case "sv": this.tryAppendQueryParameter(queries, param, this.version); @@ -26805,7 +24426,7 @@ var SASQueryParameters = /** @class */ (function () { } } return queries.join("&"); - }; + } /** * A private helper method used to filter and append query key/value pairs into an array. * @@ -26813,26 +24434,25 @@ var SASQueryParameters = /** @class */ (function () { * @param key - * @param value - */ - SASQueryParameters.prototype.tryAppendQueryParameter = function (queries, key, value) { + tryAppendQueryParameter(queries, key, value) { if (!value) { return; } key = encodeURIComponent(key); value = encodeURIComponent(value); if (key.length > 0 && value.length > 0) { - queries.push(key + "=" + value); + queries.push(`${key}=${value}`); } - }; - return SASQueryParameters; -}()); + } +} // Copyright (c) Microsoft Corporation. function generateBlobSASQueryParameters(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { - var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; - var sharedKeyCredential = sharedKeyCredentialOrUserDelegationKey instanceof StorageSharedKeyCredential + const version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + const sharedKeyCredential = sharedKeyCredentialOrUserDelegationKey instanceof StorageSharedKeyCredential ? sharedKeyCredentialOrUserDelegationKey : undefined; - var userDelegationKeyCredential; + let userDelegationKeyCredential; if (sharedKeyCredential === undefined && accountName !== undefined) { userDelegationKeyCredential = new UserDelegationKeyCredential(accountName, sharedKeyCredentialOrUserDelegationKey); } @@ -26888,12 +24508,12 @@ function generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKe !(blobSASSignatureValues.permissions && blobSASSignatureValues.expiresOn)) { throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); } - var resource = "c"; + let resource = "c"; if (blobSASSignatureValues.blobName) { resource = "b"; } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; + let verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); @@ -26903,7 +24523,7 @@ function generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKe } } // Signature is generated on the un-url-encoded values. - var stringToSign = [ + const stringToSign = [ verifiedPermissions ? verifiedPermissions : "", blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) @@ -26922,7 +24542,7 @@ function generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKe blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" ].join("\n"); - var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + const 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); } /** @@ -26947,8 +24567,8 @@ function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKe !(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; + let resource = "c"; + let timestamp = blobSASSignatureValues.snapshotTime; if (blobSASSignatureValues.blobName) { resource = "b"; if (blobSASSignatureValues.snapshotTime) { @@ -26960,7 +24580,7 @@ function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKe } } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; + let verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); @@ -26970,7 +24590,7 @@ function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKe } } // Signature is generated on the un-url-encoded values. - var stringToSign = [ + const stringToSign = [ verifiedPermissions ? verifiedPermissions : "", blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) @@ -26991,7 +24611,7 @@ function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKe blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" ].join("\n"); - var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + const 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); } /** @@ -27014,8 +24634,8 @@ function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userD 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; + let resource = "c"; + let timestamp = blobSASSignatureValues.snapshotTime; if (blobSASSignatureValues.blobName) { resource = "b"; if (blobSASSignatureValues.snapshotTime) { @@ -27027,7 +24647,7 @@ function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userD } } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; + let verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); @@ -27037,7 +24657,7 @@ function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userD } } // Signature is generated on the un-url-encoded values. - var stringToSign = [ + const stringToSign = [ verifiedPermissions ? verifiedPermissions : "", blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) @@ -27067,7 +24687,7 @@ function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userD blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType ].join("\n"); - var signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); + const 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); } /** @@ -27090,8 +24710,8 @@ function generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userD 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; + let resource = "c"; + let timestamp = blobSASSignatureValues.snapshotTime; if (blobSASSignatureValues.blobName) { resource = "b"; if (blobSASSignatureValues.snapshotTime) { @@ -27103,7 +24723,7 @@ function generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userD } } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; + let verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); @@ -27113,7 +24733,7 @@ function generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userD } } // Signature is generated on the un-url-encoded values. - var stringToSign = [ + const stringToSign = [ verifiedPermissions ? verifiedPermissions : "", blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) @@ -27146,20 +24766,20 @@ function generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userD blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType ].join("\n"); - var signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); + const 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]; + const elements = [`/blob/${accountName}/${containerName}`]; if (blobName) { - elements.push("/" + blobName); + elements.push(`/${blobName}`); } return elements.join(""); } function SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues) { - var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + const 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'."); } @@ -27172,6 +24792,11 @@ function SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues) { if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.versionId) { throw RangeError("Must provide 'blobName' when providing 'versionId'."); } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.setImmutabilityPolicy && + version < "2020-08-04") { + throw RangeError("'version' must be >= '2020-08-04' when provided 'i' permission."); + } if (blobSASSignatureValues.permissions && blobSASSignatureValues.permissions.deleteVersion && version < "2019-10-10") { @@ -27195,17 +24820,18 @@ function SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues) { return blobSASSignatureValues; } +// Copyright (c) Microsoft Corporation. /** * A client that manages leases for a {@link ContainerClient} or a {@link BlobClient}. */ -var BlobLeaseClient = /** @class */ (function () { +class BlobLeaseClient { /** * Creates an instance of BlobLeaseClient. * @param client - The client to make the lease operation requests. * @param leaseId - Initial proposed lease id. */ - function BlobLeaseClient(client, leaseId) { - var clientContext = new StorageClientContext(client.url, client.pipeline.toServiceClientOptions()); + constructor(client, leaseId) { + const clientContext = new StorageClientContext(client.url, client.pipeline.toServiceClientOptions()); this._url = client.url; if (client.name === undefined) { this._isContainer = true; @@ -27220,30 +24846,22 @@ var BlobLeaseClient = /** @class */ (function () { } this._leaseId = leaseId; } - Object.defineProperty(BlobLeaseClient.prototype, "leaseId", { - /** - * Gets the lease Id. - * - * @readonly - */ - get: function () { - return this._leaseId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobLeaseClient.prototype, "url", { - /** - * Gets the url. - * - * @readonly - */ - get: function () { - return this._url; - }, - enumerable: false, - configurable: true - }); + /** + * Gets the lease Id. + * + * @readonly + */ + get leaseId() { + return this._leaseId; + } + /** + * Gets the url. + * + * @readonly + */ + get url() { + return this._url; + } /** * Establishes and manages a lock on a container for delete operations, or on a blob * for write and delete operations. @@ -27256,41 +24874,29 @@ var BlobLeaseClient = /** @class */ (function () { * @param options - option to configure lease management operations. * @returns Response data for acquire lease operation. */ - BlobLeaseClient.prototype.acquireLease = function (duration, options) { + async acquireLease(duration, options = {}) { var _a, _b, _c, _d, _e, _f; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _g, span, updatedOptions, e_1; - return tslib.__generator(this, function (_h) { - switch (_h.label) { - case 0: - _g = createSpan("BlobLeaseClient-acquireLease", options), span = _g.span, updatedOptions = _g.updatedOptions; - if (this._isContainer && - ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || - (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || - ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); - } - _h.label = 1; - case 1: - _h.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this._containerOrBlobOperation.acquireLease(tslib.__assign({ abortSignal: options.abortSignal, duration: duration, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), proposedLeaseId: this._leaseId }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _h.sent()]; - case 3: - e_1 = _h.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_1.message - }); - throw e_1; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobLeaseClient-acquireLease", options); + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || + ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + try { + return await this._containerOrBlobOperation.acquireLease(Object.assign({ abortSignal: options.abortSignal, duration, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), proposedLeaseId: this._leaseId }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * To change the ID of the lease. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container @@ -27301,44 +24907,31 @@ var BlobLeaseClient = /** @class */ (function () { * @param options - option to configure lease management operations. * @returns Response data for change lease operation. */ - BlobLeaseClient.prototype.changeLease = function (proposedLeaseId, options) { + async changeLease(proposedLeaseId, options = {}) { var _a, _b, _c, _d, _e, _f; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _g, span, updatedOptions, response, e_2; - return tslib.__generator(this, function (_h) { - switch (_h.label) { - case 0: - _g = createSpan("BlobLeaseClient-changeLease", options), span = _g.span, updatedOptions = _g.updatedOptions; - if (this._isContainer && - ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || - (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || - ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); - } - _h.label = 1; - case 1: - _h.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this._containerOrBlobOperation.changeLease(this._leaseId, proposedLeaseId, tslib.__assign({ abortSignal: options.abortSignal, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: - response = _h.sent(); - this._leaseId = proposedLeaseId; - return [2 /*return*/, response]; - case 3: - e_2 = _h.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_2.message - }); - throw e_2; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobLeaseClient-changeLease", options); + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || + ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + try { + const response = await this._containerOrBlobOperation.changeLease(this._leaseId, proposedLeaseId, Object.assign({ abortSignal: options.abortSignal, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + this._leaseId = proposedLeaseId; + return response; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * To free the lease if it is no longer needed so that another client may * immediately acquire a lease against the container or the blob. @@ -27349,41 +24942,29 @@ var BlobLeaseClient = /** @class */ (function () { * @param options - option to configure lease management operations. * @returns Response data for release lease operation. */ - BlobLeaseClient.prototype.releaseLease = function (options) { + async releaseLease(options = {}) { var _a, _b, _c, _d, _e, _f; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _g, span, updatedOptions, e_3; - return tslib.__generator(this, function (_h) { - switch (_h.label) { - case 0: - _g = createSpan("BlobLeaseClient-releaseLease", options), span = _g.span, updatedOptions = _g.updatedOptions; - if (this._isContainer && - ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || - (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || - ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); - } - _h.label = 1; - case 1: - _h.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this._containerOrBlobOperation.releaseLease(this._leaseId, tslib.__assign({ abortSignal: options.abortSignal, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _h.sent()]; - case 3: - e_3 = _h.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_3.message - }); - throw e_3; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobLeaseClient-releaseLease", options); + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || + ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + try { + return await this._containerOrBlobOperation.releaseLease(this._leaseId, Object.assign({ abortSignal: options.abortSignal, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * To renew the lease. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container @@ -27393,41 +24974,29 @@ var BlobLeaseClient = /** @class */ (function () { * @param options - Optional option to configure lease management operations. * @returns Response data for renew lease operation. */ - BlobLeaseClient.prototype.renewLease = function (options) { + async renewLease(options = {}) { var _a, _b, _c, _d, _e, _f; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _g, span, updatedOptions, e_4; - return tslib.__generator(this, function (_h) { - switch (_h.label) { - case 0: - _g = createSpan("BlobLeaseClient-renewLease", options), span = _g.span, updatedOptions = _g.updatedOptions; - if (this._isContainer && - ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || - (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || - ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); - } - _h.label = 1; - case 1: - _h.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this._containerOrBlobOperation.renewLease(this._leaseId, tslib.__assign({ abortSignal: options.abortSignal, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _h.sent()]; - case 3: - e_4 = _h.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_4.message - }); - throw e_4; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobLeaseClient-renewLease", options); + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || + ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + try { + return await this._containerOrBlobOperation.renewLease(this._leaseId, Object.assign({ abortSignal: options.abortSignal, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * To end the lease but ensure that another client cannot acquire a new lease * until the current lease period has expired. @@ -27439,44 +25008,31 @@ var BlobLeaseClient = /** @class */ (function () { * @param options - Optional options to configure lease management operations. * @returns Response data for break lease operation. */ - BlobLeaseClient.prototype.breakLease = function (breakPeriod, options) { + async breakLease(breakPeriod, options = {}) { var _a, _b, _c, _d, _e, _f; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _g, span, updatedOptions, operationOptions, e_5; - return tslib.__generator(this, function (_h) { - switch (_h.label) { - case 0: - _g = createSpan("BlobLeaseClient-breakLease", options), span = _g.span, updatedOptions = _g.updatedOptions; - if (this._isContainer && - ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || - (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || - ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); - } - _h.label = 1; - case 1: - _h.trys.push([1, 3, 4, 5]); - operationOptions = tslib.__assign({ abortSignal: options.abortSignal, breakPeriod: breakPeriod, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)); - return [4 /*yield*/, this._containerOrBlobOperation.breakLease(operationOptions)]; - case 2: return [2 /*return*/, _h.sent()]; - case 3: - e_5 = _h.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_5.message - }); - throw e_5; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobLeaseClient-breakLease", options); + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || + ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + try { + const operationOptions = Object.assign({ abortSignal: options.abortSignal, breakPeriod, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)); + return await this._containerOrBlobOperation.breakLease(operationOptions); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; - return BlobLeaseClient; -}()); + throw e; + } + finally { + span.end(); + } + } +} // Copyright (c) Microsoft Corporation. /** @@ -27484,8 +25040,7 @@ var BlobLeaseClient = /** @class */ (function () { * * A Node.js ReadableStream will internally retry when internal ReadableStream unexpected ends. */ -var RetriableReadableStream = /** @class */ (function (_super) { - tslib.__extends(RetriableReadableStream, _super); +class RetriableReadableStream extends stream.Readable { /** * Creates an instance of RetriableReadableStream. * @@ -27496,32 +25051,31 @@ var RetriableReadableStream = /** @class */ (function (_super) { * @param count - How much data in original data source to read * @param options - */ - function RetriableReadableStream(source, getter, offset, count, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this, { highWaterMark: options.highWaterMark }) || this; - _this.retries = 0; - _this.sourceDataHandler = function (data) { - if (_this.options.doInjectErrorOnce) { - _this.options.doInjectErrorOnce = undefined; - _this.source.pause(); - _this.source.removeAllListeners("data"); - _this.source.emit("end"); + constructor(source, getter, offset, count, options = {}) { + super({ highWaterMark: options.highWaterMark }); + this.retries = 0; + this.sourceDataHandler = (data) => { + if (this.options.doInjectErrorOnce) { + this.options.doInjectErrorOnce = undefined; + this.source.pause(); + this.source.removeAllListeners("data"); + this.source.emit("end"); return; } // console.log( // `Offset: ${this.offset}, Received ${data.length} from internal stream` // ); - _this.offset += data.length; - if (_this.onProgress) { - _this.onProgress({ loadedBytes: _this.offset - _this.start }); + this.offset += data.length; + if (this.onProgress) { + this.onProgress({ loadedBytes: this.offset - this.start }); } - if (!_this.push(data)) { - _this.source.pause(); + if (!this.push(data)) { + this.source.pause(); } }; - _this.sourceErrorOrEndHandler = function (err) { + this.sourceErrorOrEndHandler = (err) => { if (err && err.name === "AbortError") { - _this.destroy(err); + this.destroy(err); return; } // console.log( @@ -27529,69 +25083,66 @@ var RetriableReadableStream = /** @class */ (function (_super) { // this.offset // }, dest end : ${this.end}` // ); - _this.removeSourceEventHandlers(); - if (_this.offset - 1 === _this.end) { - _this.push(null); + this.removeSourceEventHandlers(); + if (this.offset - 1 === this.end) { + this.push(null); } - else if (_this.offset <= _this.end) { + else if (this.offset <= this.end) { // console.log( // `retries: ${this.retries}, max retries: ${this.maxRetries}` // ); - if (_this.retries < _this.maxRetryRequests) { - _this.retries += 1; - _this.getter(_this.offset) - .then(function (newSource) { - _this.source = newSource; - _this.setSourceEventHandlers(); + if (this.retries < this.maxRetryRequests) { + this.retries += 1; + this.getter(this.offset) + .then((newSource) => { + this.source = newSource; + this.setSourceEventHandlers(); + return; }) - .catch(function (error) { - _this.destroy(error); + .catch((error) => { + this.destroy(error); }); } else { - _this.destroy(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)); + this.destroy(new Error(`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.destroy(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 = + 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; + this.onProgress = options.onProgress; + this.options = options; + this.setSourceEventHandlers(); } - RetriableReadableStream.prototype._read = function () { + _read() { this.source.resume(); - }; - RetriableReadableStream.prototype.setSourceEventHandlers = function () { + } + setSourceEventHandlers() { this.source.on("data", this.sourceDataHandler); this.source.on("end", this.sourceErrorOrEndHandler); this.source.on("error", this.sourceErrorOrEndHandler); - }; - RetriableReadableStream.prototype.removeSourceEventHandlers = function () { + } + removeSourceEventHandlers() { this.source.removeListener("data", this.sourceDataHandler); this.source.removeListener("end", this.sourceErrorOrEndHandler); this.source.removeListener("error", this.sourceErrorOrEndHandler); - }; - RetriableReadableStream.prototype._destroy = function (error, callback) { + } + _destroy(error, callback) { // remove listener from source and release source this.removeSourceEventHandlers(); this.source.destroy(); callback(error === null ? undefined : error); - }; - return RetriableReadableStream; -}(stream.Readable)); + } +} // Copyright (c) Microsoft Corporation. /** @@ -27604,7 +25155,7 @@ var RetriableReadableStream = /** @class */ (function (_super) { * The {@link readableStreamBody} stream will retry underlayer, you can just use it as a normal Node.js * Readable stream. */ -var BlobDownloadResponse = /** @class */ (function () { +class BlobDownloadResponse { /** * Creates an instance of BlobDownloadResponse. * @@ -27614,593 +25165,443 @@ var BlobDownloadResponse = /** @class */ (function () { * @param count - * @param options - */ - function BlobDownloadResponse(originalResponse, getter, offset, count, options) { - if (options === void 0) { options = {}; } + constructor(originalResponse, getter, offset, count, options = {}) { this.originalResponse = originalResponse; this.blobDownloadStream = new RetriableReadableStream(this.originalResponse.readableStreamBody, getter, offset, count, options); } - Object.defineProperty(BlobDownloadResponse.prototype, "acceptRanges", { - /** - * Indicates that the service supports - * requests for partial file content. - * - * @readonly - */ - get: function () { - return this.originalResponse.acceptRanges; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "cacheControl", { - /** - * Returns if it was previously specified - * for the file. - * - * @readonly - */ - get: function () { - return this.originalResponse.cacheControl; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "contentDisposition", { - /** - * Returns the value that was specified - * for the 'x-ms-content-disposition' header and specifies how to process the - * response. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentDisposition; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "contentEncoding", { - /** - * Returns the value that was specified - * for the Content-Encoding request header. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentEncoding; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "contentLanguage", { - /** - * Returns the value that was specified - * for the Content-Language request header. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentLanguage; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "blobSequenceNumber", { - /** - * The current sequence number for a - * page blob. This header is not returned for block blobs or append blobs. - * - * @readonly - */ - get: function () { - return this.originalResponse.blobSequenceNumber; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "blobType", { - /** - * The blob's type. Possible values include: - * 'BlockBlob', 'PageBlob', 'AppendBlob'. - * - * @readonly - */ - get: function () { - return this.originalResponse.blobType; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "contentLength", { - /** - * The number of bytes present in the - * response body. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentLength; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "contentMD5", { - /** - * If the file has an MD5 hash and the - * request is to read the full file, this response header is returned so that - * the client can check for message content integrity. If the request is to - * read a specified range and the 'x-ms-range-get-content-md5' is set to - * true, then the request returns an MD5 hash for the range, as long as the - * range size is less than or equal to 4 MB. If neither of these sets of - * conditions is true, then no value is returned for the 'Content-MD5' - * header. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentMD5; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "contentRange", { - /** - * Indicates the range of bytes returned if - * the client requested a subset of the file by setting the Range request - * header. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentRange; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "contentType", { - /** - * The content type specified for the file. - * The default content type is 'application/octet-stream' - * - * @readonly - */ - get: function () { - return this.originalResponse.contentType; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "copyCompletedOn", { - /** - * Conclusion time of the last attempted - * Copy File operation where this file was the destination file. This value - * can specify the time of a completed, aborted, or failed copy attempt. - * - * @readonly - */ - get: function () { - return this.originalResponse.copyCompletedOn; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "copyId", { - /** - * String identifier for the last attempted Copy - * File operation where this file was the destination file. - * - * @readonly - */ - get: function () { - return this.originalResponse.copyId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "copyProgress", { - /** - * Contains the number of bytes copied and - * the total bytes in the source in the last attempted Copy File operation - * where this file was the destination file. Can show between 0 and - * Content-Length bytes copied. - * - * @readonly - */ - get: function () { - return this.originalResponse.copyProgress; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "copySource", { - /** - * URL up to 2KB in length that specifies the - * source file used in the last attempted Copy File operation where this file - * was the destination file. - * - * @readonly - */ - get: function () { - return this.originalResponse.copySource; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "copyStatus", { - /** - * State of the copy operation - * identified by 'x-ms-copy-id'. Possible values include: 'pending', - * 'success', 'aborted', 'failed' - * - * @readonly - */ - get: function () { - return this.originalResponse.copyStatus; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "copyStatusDescription", { - /** - * Only appears when - * x-ms-copy-status is failed or pending. Describes cause of fatal or - * non-fatal copy operation failure. - * - * @readonly - */ - get: function () { - return this.originalResponse.copyStatusDescription; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "leaseDuration", { - /** - * When a blob is leased, - * specifies whether the lease is of infinite or fixed duration. Possible - * values include: 'infinite', 'fixed'. - * - * @readonly - */ - get: function () { - return this.originalResponse.leaseDuration; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "leaseState", { - /** - * Lease state of the blob. Possible - * values include: 'available', 'leased', 'expired', 'breaking', 'broken'. - * - * @readonly - */ - get: function () { - return this.originalResponse.leaseState; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "leaseStatus", { - /** - * The current lease status of the - * blob. Possible values include: 'locked', 'unlocked'. - * - * @readonly - */ - get: function () { - return this.originalResponse.leaseStatus; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "date", { - /** - * A UTC date/time value generated by the service that - * indicates the time at which the response was initiated. - * - * @readonly - */ - get: function () { - return this.originalResponse.date; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "blobCommittedBlockCount", { - /** - * The number of committed blocks - * present in the blob. This header is returned only for append blobs. - * - * @readonly - */ - get: function () { - return this.originalResponse.blobCommittedBlockCount; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "etag", { - /** - * The ETag contains a value that you can use to - * perform operations conditionally, in quotes. - * - * @readonly - */ - get: function () { - return this.originalResponse.etag; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "tagCount", { - /** - * The number of tags associated with the blob - * - * @readonly - */ - get: function () { - return this.originalResponse.tagCount; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "errorCode", { - /** - * The error code. - * - * @readonly - */ - get: function () { - return this.originalResponse.errorCode; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "isServerEncrypted", { - /** - * The value of this header is set to - * true if the file data and application metadata are completely encrypted - * using the specified algorithm. Otherwise, the value is set to false (when - * the file is unencrypted, or if only parts of the file/application metadata - * are encrypted). - * - * @readonly - */ - get: function () { - return this.originalResponse.isServerEncrypted; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "blobContentMD5", { - /** - * If the blob has a MD5 hash, and if - * request contains range header (Range or x-ms-range), this response header - * is returned with the value of the whole blob's MD5 value. This value may - * or may not be equal to the value returned in Content-MD5 header, with the - * latter calculated from the requested range. - * - * @readonly - */ - get: function () { - return this.originalResponse.blobContentMD5; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "lastModified", { - /** - * Returns the date and time the file was last - * modified. Any operation that modifies the file or its properties updates - * the last modified time. - * - * @readonly - */ - get: function () { - return this.originalResponse.lastModified; - }, - 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 - */ - get: function () { - return this.originalResponse.lastAccessed; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "metadata", { - /** - * A name-value pair - * to associate with a file storage object. - * - * @readonly - */ - get: function () { - return this.originalResponse.metadata; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "requestId", { - /** - * This header uniquely identifies the request - * that was made and can be used for troubleshooting the request. - * - * @readonly - */ - get: function () { - return this.originalResponse.requestId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "clientRequestId", { - /** - * If a client request id header is sent in the request, this header will be present in the - * response with the same value. - * - * @readonly - */ - get: function () { - return this.originalResponse.clientRequestId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "version", { - /** - * Indicates the version of the Blob service used - * to execute the request. - * - * @readonly - */ - get: function () { - return this.originalResponse.version; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "versionId", { - /** - * Indicates the versionId of the downloaded blob version. - * - * @readonly - */ - get: function () { - return this.originalResponse.versionId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "isCurrentVersion", { - /** - * Indicates whether version of this blob is a current version. - * - * @readonly - */ - get: function () { - return this.originalResponse.isCurrentVersion; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "encryptionKeySha256", { - /** - * The SHA-256 hash of the encryption key used to encrypt the blob. This value is only returned - * when the blob was encrypted with a customer-provided key. - * - * @readonly - */ - get: function () { - return this.originalResponse.encryptionKeySha256; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "contentCrc64", { - /** - * If the request is to read a specified range and the x-ms-range-get-content-crc64 is set to - * true, then the request returns a crc64 for the range, as long as the range size is less than - * or equal to 4 MB. If both x-ms-range-get-content-crc64 & x-ms-range-get-content-md5 is - * specified in the same request, it will fail with 400(Bad Request) - */ - get: function () { - return this.originalResponse.contentCrc64; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "objectReplicationDestinationPolicyId", { - /** - * Object Replication Policy Id of the destination blob. - * - * @readonly - */ - get: function () { - return this.originalResponse.objectReplicationDestinationPolicyId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "objectReplicationSourceProperties", { - /** - * Parsed Object Replication Policy Id, Rule Id(s) and status of the source blob. - * - * @readonly - */ - get: function () { - return this.originalResponse.objectReplicationSourceProperties; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "isSealed", { - /** - * If this blob has been sealed. - * - * @readonly - */ - get: function () { - return this.originalResponse.isSealed; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "contentAsBlob", { - /** - * The response body as a browser Blob. - * Always undefined in node.js. - * - * @readonly - */ - get: function () { - return this.originalResponse.blobBody; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "readableStreamBody", { - /** - * The response body as a node.js Readable stream. - * Always undefined in the browser. - * - * It will automatically retry when internal read stream unexpected ends. - * - * @readonly - */ - get: function () { - return coreHttp.isNode ? this.blobDownloadStream : undefined; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "_response", { - /** - * The HTTP response. - */ - get: function () { - return this.originalResponse._response; - }, - enumerable: false, - configurable: true - }); - return BlobDownloadResponse; -}()); + /** + * Indicates that the service supports + * requests for partial file content. + * + * @readonly + */ + get acceptRanges() { + return this.originalResponse.acceptRanges; + } + /** + * Returns if it was previously specified + * for the file. + * + * @readonly + */ + get cacheControl() { + return this.originalResponse.cacheControl; + } + /** + * Returns the value that was specified + * for the 'x-ms-content-disposition' header and specifies how to process the + * response. + * + * @readonly + */ + get contentDisposition() { + return this.originalResponse.contentDisposition; + } + /** + * Returns the value that was specified + * for the Content-Encoding request header. + * + * @readonly + */ + get contentEncoding() { + return this.originalResponse.contentEncoding; + } + /** + * Returns the value that was specified + * for the Content-Language request header. + * + * @readonly + */ + get contentLanguage() { + return this.originalResponse.contentLanguage; + } + /** + * The current sequence number for a + * page blob. This header is not returned for block blobs or append blobs. + * + * @readonly + */ + get blobSequenceNumber() { + return this.originalResponse.blobSequenceNumber; + } + /** + * The blob's type. Possible values include: + * 'BlockBlob', 'PageBlob', 'AppendBlob'. + * + * @readonly + */ + get blobType() { + return this.originalResponse.blobType; + } + /** + * The number of bytes present in the + * response body. + * + * @readonly + */ + get contentLength() { + return this.originalResponse.contentLength; + } + /** + * If the file has an MD5 hash and the + * request is to read the full file, this response header is returned so that + * the client can check for message content integrity. If the request is to + * read a specified range and the 'x-ms-range-get-content-md5' is set to + * true, then the request returns an MD5 hash for the range, as long as the + * range size is less than or equal to 4 MB. If neither of these sets of + * conditions is true, then no value is returned for the 'Content-MD5' + * header. + * + * @readonly + */ + get contentMD5() { + return this.originalResponse.contentMD5; + } + /** + * Indicates the range of bytes returned if + * the client requested a subset of the file by setting the Range request + * header. + * + * @readonly + */ + get contentRange() { + return this.originalResponse.contentRange; + } + /** + * The content type specified for the file. + * The default content type is 'application/octet-stream' + * + * @readonly + */ + get contentType() { + return this.originalResponse.contentType; + } + /** + * Conclusion time of the last attempted + * Copy File operation where this file was the destination file. This value + * can specify the time of a completed, aborted, or failed copy attempt. + * + * @readonly + */ + get copyCompletedOn() { + return this.originalResponse.copyCompletedOn; + } + /** + * String identifier for the last attempted Copy + * File operation where this file was the destination file. + * + * @readonly + */ + get copyId() { + return this.originalResponse.copyId; + } + /** + * Contains the number of bytes copied and + * the total bytes in the source in the last attempted Copy File operation + * where this file was the destination file. Can show between 0 and + * Content-Length bytes copied. + * + * @readonly + */ + get copyProgress() { + return this.originalResponse.copyProgress; + } + /** + * URL up to 2KB in length that specifies the + * source file used in the last attempted Copy File operation where this file + * was the destination file. + * + * @readonly + */ + get copySource() { + return this.originalResponse.copySource; + } + /** + * State of the copy operation + * identified by 'x-ms-copy-id'. Possible values include: 'pending', + * 'success', 'aborted', 'failed' + * + * @readonly + */ + get copyStatus() { + return this.originalResponse.copyStatus; + } + /** + * Only appears when + * x-ms-copy-status is failed or pending. Describes cause of fatal or + * non-fatal copy operation failure. + * + * @readonly + */ + get copyStatusDescription() { + return this.originalResponse.copyStatusDescription; + } + /** + * When a blob is leased, + * specifies whether the lease is of infinite or fixed duration. Possible + * values include: 'infinite', 'fixed'. + * + * @readonly + */ + get leaseDuration() { + return this.originalResponse.leaseDuration; + } + /** + * Lease state of the blob. Possible + * values include: 'available', 'leased', 'expired', 'breaking', 'broken'. + * + * @readonly + */ + get leaseState() { + return this.originalResponse.leaseState; + } + /** + * The current lease status of the + * blob. Possible values include: 'locked', 'unlocked'. + * + * @readonly + */ + get leaseStatus() { + return this.originalResponse.leaseStatus; + } + /** + * A UTC date/time value generated by the service that + * indicates the time at which the response was initiated. + * + * @readonly + */ + get date() { + return this.originalResponse.date; + } + /** + * The number of committed blocks + * present in the blob. This header is returned only for append blobs. + * + * @readonly + */ + get blobCommittedBlockCount() { + return this.originalResponse.blobCommittedBlockCount; + } + /** + * The ETag contains a value that you can use to + * perform operations conditionally, in quotes. + * + * @readonly + */ + get etag() { + return this.originalResponse.etag; + } + /** + * The number of tags associated with the blob + * + * @readonly + */ + get tagCount() { + return this.originalResponse.tagCount; + } + /** + * The error code. + * + * @readonly + */ + get errorCode() { + return this.originalResponse.errorCode; + } + /** + * The value of this header is set to + * true if the file data and application metadata are completely encrypted + * using the specified algorithm. Otherwise, the value is set to false (when + * the file is unencrypted, or if only parts of the file/application metadata + * are encrypted). + * + * @readonly + */ + get isServerEncrypted() { + return this.originalResponse.isServerEncrypted; + } + /** + * If the blob has a MD5 hash, and if + * request contains range header (Range or x-ms-range), this response header + * is returned with the value of the whole blob's MD5 value. This value may + * or may not be equal to the value returned in Content-MD5 header, with the + * latter calculated from the requested range. + * + * @readonly + */ + get blobContentMD5() { + return this.originalResponse.blobContentMD5; + } + /** + * Returns the date and time the file was last + * modified. Any operation that modifies the file or its properties updates + * the last modified time. + * + * @readonly + */ + get lastModified() { + return this.originalResponse.lastModified; + } + /** + * 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 + */ + get lastAccessed() { + return this.originalResponse.lastAccessed; + } + /** + * A name-value pair + * to associate with a file storage object. + * + * @readonly + */ + get metadata() { + return this.originalResponse.metadata; + } + /** + * This header uniquely identifies the request + * that was made and can be used for troubleshooting the request. + * + * @readonly + */ + get requestId() { + return this.originalResponse.requestId; + } + /** + * If a client request id header is sent in the request, this header will be present in the + * response with the same value. + * + * @readonly + */ + get clientRequestId() { + return this.originalResponse.clientRequestId; + } + /** + * Indicates the version of the Blob service used + * to execute the request. + * + * @readonly + */ + get version() { + return this.originalResponse.version; + } + /** + * Indicates the versionId of the downloaded blob version. + * + * @readonly + */ + get versionId() { + return this.originalResponse.versionId; + } + /** + * Indicates whether version of this blob is a current version. + * + * @readonly + */ + get isCurrentVersion() { + return this.originalResponse.isCurrentVersion; + } + /** + * The SHA-256 hash of the encryption key used to encrypt the blob. This value is only returned + * when the blob was encrypted with a customer-provided key. + * + * @readonly + */ + get encryptionKeySha256() { + return this.originalResponse.encryptionKeySha256; + } + /** + * If the request is to read a specified range and the x-ms-range-get-content-crc64 is set to + * true, then the request returns a crc64 for the range, as long as the range size is less than + * or equal to 4 MB. If both x-ms-range-get-content-crc64 & x-ms-range-get-content-md5 is + * specified in the same request, it will fail with 400(Bad Request) + */ + get contentCrc64() { + return this.originalResponse.contentCrc64; + } + /** + * Object Replication Policy Id of the destination blob. + * + * @readonly + */ + get objectReplicationDestinationPolicyId() { + return this.originalResponse.objectReplicationDestinationPolicyId; + } + /** + * Parsed Object Replication Policy Id, Rule Id(s) and status of the source blob. + * + * @readonly + */ + get objectReplicationSourceProperties() { + return this.originalResponse.objectReplicationSourceProperties; + } + /** + * If this blob has been sealed. + * + * @readonly + */ + get isSealed() { + return this.originalResponse.isSealed; + } + /** + * UTC date/time value generated by the service that indicates the time at which the blob immutability policy will expire. + * + * @readonly + */ + get immutabilityPolicyExpiresOn() { + return this.originalResponse.immutabilityPolicyExpiresOn; + } + /** + * Indicates immutability policy mode. + * + * @readonly + */ + get immutabilityPolicyMode() { + return this.originalResponse.immutabilityPolicyMode; + } + /** + * Indicates if a legal hold is present on the blob. + * + * @readonly + */ + get legalHold() { + return this.originalResponse.legalHold; + } + /** + * The response body as a browser Blob. + * Always undefined in node.js. + * + * @readonly + */ + get contentAsBlob() { + return this.originalResponse.blobBody; + } + /** + * The response body as a node.js Readable stream. + * Always undefined in the browser. + * + * It will automatically retry when internal read stream unexpected ends. + * + * @readonly + */ + get readableStreamBody() { + return coreHttp.isNode ? this.blobDownloadStream : undefined; + } + /** + * The HTTP response. + */ + get _response() { + return this.originalResponse._response; + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -var AVRO_SYNC_MARKER_SIZE = 16; -var AVRO_INIT_BYTES = new Uint8Array([79, 98, 106, 1]); -var AVRO_CODEC_KEY = "avro.codec"; -var AVRO_SCHEMA_KEY = "avro.schema"; +const AVRO_SYNC_MARKER_SIZE = 16; +const AVRO_INIT_BYTES = new Uint8Array([79, 98, 106, 1]); +const AVRO_CODEC_KEY = "avro.codec"; +const AVRO_SCHEMA_KEY = "avro.schema"; // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -28211,7 +25612,7 @@ function arraysEqual(a, b) { return false; if (a.length != b.length) return false; - for (var i = 0; i < a.length; ++i) { + for (let i = 0; i < a.length; ++i) { if (a[i] !== b[i]) return false; } @@ -28219,9 +25620,8 @@ function arraysEqual(a, b) { } // Copyright (c) Microsoft Corporation. -var AvroParser = /** @class */ (function () { - function AvroParser() { - } +// Licensed under the MIT license. +class AvroParser { /** * Reads a fixed number of bytes from the stream. * @@ -28229,294 +25629,135 @@ var AvroParser = /** @class */ (function () { * @param length - * @param options - */ - AvroParser.readFixedBytes = function (stream, length, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var bytes; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, stream.read(length, { abortSignal: options.abortSignal })]; - case 1: - bytes = _a.sent(); - if (bytes.length != length) { - throw new Error("Hit stream end."); - } - return [2 /*return*/, bytes]; - } - }); - }); - }; + static async readFixedBytes(stream, length, options = {}) { + const bytes = await stream.read(length, { abortSignal: options.abortSignal }); + if (bytes.length != length) { + throw new Error("Hit stream end."); + } + return bytes; + } /** * Reads a single byte from the stream. * * @param stream - * @param options - */ - AvroParser.readByte = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var buf; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, AvroParser.readFixedBytes(stream, 1, options)]; - case 1: - buf = _a.sent(); - return [2 /*return*/, buf[0]]; - } - }); - }); - }; + static async readByte(stream, options = {}) { + const buf = await AvroParser.readFixedBytes(stream, 1, options); + return buf[0]; + } // int and long are stored in variable-length zig-zag coding. // variable-length: https://lucene.apache.org/core/3_5_0/fileformats.html#VInt // zig-zag: https://developers.google.com/protocol-buffers/docs/encoding?csw=1#types - AvroParser.readZigZagLong = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var zigZagEncoded, significanceInBit, byte, haveMoreByte, significanceInFloat, res; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - zigZagEncoded = 0; - significanceInBit = 0; - _a.label = 1; - case 1: return [4 /*yield*/, AvroParser.readByte(stream, options)]; - case 2: - byte = _a.sent(); - haveMoreByte = byte & 0x80; - zigZagEncoded |= (byte & 0x7f) << significanceInBit; - significanceInBit += 7; - _a.label = 3; - case 3: - if (haveMoreByte && significanceInBit < 28) return [3 /*break*/, 1]; - _a.label = 4; - case 4: - if (!haveMoreByte) return [3 /*break*/, 9]; - // Switch to float arithmetic - zigZagEncoded = zigZagEncoded; - significanceInFloat = 268435456; // 2 ** 28. - _a.label = 5; - case 5: return [4 /*yield*/, AvroParser.readByte(stream, options)]; - case 6: - byte = _a.sent(); - zigZagEncoded += (byte & 0x7f) * significanceInFloat; - significanceInFloat *= 128; // 2 ** 7 - _a.label = 7; - case 7: - if (byte & 0x80) return [3 /*break*/, 5]; - _a.label = 8; - case 8: - res = (zigZagEncoded % 2 ? -(zigZagEncoded + 1) : zigZagEncoded) / 2; - if (res < Number.MIN_SAFE_INTEGER || res > Number.MAX_SAFE_INTEGER) { - throw new Error("Integer overflow."); - } - return [2 /*return*/, res]; - case 9: return [2 /*return*/, (zigZagEncoded >> 1) ^ -(zigZagEncoded & 1)]; - } - }); - }); - }; - AvroParser.readLong = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - return [2 /*return*/, AvroParser.readZigZagLong(stream, options)]; - }); - }); - }; - AvroParser.readInt = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - return [2 /*return*/, AvroParser.readZigZagLong(stream, options)]; - }); - }); - }; - AvroParser.readNull = function () { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - return [2 /*return*/, null]; - }); - }); - }; - AvroParser.readBoolean = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var b; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, AvroParser.readByte(stream, options)]; - case 1: - b = _a.sent(); - if (b == 1) { - return [2 /*return*/, true]; - } - else if (b == 0) { - return [2 /*return*/, false]; - } - else { - throw new Error("Byte was not a boolean."); - } - } - }); - }); - }; - AvroParser.readFloat = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var u8arr, view; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, AvroParser.readFixedBytes(stream, 4, options)]; - case 1: - u8arr = _a.sent(); - view = new DataView(u8arr.buffer, u8arr.byteOffset, u8arr.byteLength); - return [2 /*return*/, view.getFloat32(0, true)]; // littleEndian = true - } - }); - }); - }; - AvroParser.readDouble = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var u8arr, view; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, AvroParser.readFixedBytes(stream, 8, options)]; - case 1: - u8arr = _a.sent(); - view = new DataView(u8arr.buffer, u8arr.byteOffset, u8arr.byteLength); - return [2 /*return*/, view.getFloat64(0, true)]; // littleEndian = true - } - }); - }); - }; - AvroParser.readBytes = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var size; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, AvroParser.readLong(stream, options)]; - case 1: - size = _a.sent(); - if (size < 0) { - throw new Error("Bytes size was negative."); - } - return [4 /*yield*/, stream.read(size, { abortSignal: options.abortSignal })]; - case 2: return [2 /*return*/, _a.sent()]; - } - }); - }); - }; - AvroParser.readString = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var u8arr, utf8decoder; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, AvroParser.readBytes(stream, options)]; - case 1: - u8arr = _a.sent(); - // polyfill TextDecoder to be backward compatible with older - // nodejs that doesn't expose TextDecoder as a global variable - if (typeof TextDecoder === "undefined" && "function" !== "undefined") { - global.TextDecoder = __webpack_require__(669).TextDecoder; - } - utf8decoder = new TextDecoder(); - return [2 /*return*/, utf8decoder.decode(u8arr)]; - } - }); - }); - }; - AvroParser.readMapPair = function (stream, readItemMethod, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var key, value; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, AvroParser.readString(stream, options)]; - case 1: - key = _a.sent(); - return [4 /*yield*/, readItemMethod(stream, options)]; - case 2: - value = _a.sent(); - return [2 /*return*/, { key: key, value: value }]; - } - }); - }); - }; - AvroParser.readMap = function (stream, readItemMethod, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var readPairMethod, pairs, dict, _i, pairs_1, pair; - var _this = this; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - readPairMethod = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(_this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, AvroParser.readMapPair(stream, readItemMethod, options)]; - case 1: return [2 /*return*/, _a.sent()]; - } - }); - }); - }; - return [4 /*yield*/, AvroParser.readArray(stream, readPairMethod, options)]; - case 1: - pairs = _a.sent(); - dict = {}; - for (_i = 0, pairs_1 = pairs; _i < pairs_1.length; _i++) { - pair = pairs_1[_i]; - dict[pair.key] = pair.value; - } - return [2 /*return*/, dict]; - } - }); - }); - }; - AvroParser.readArray = function (stream, readItemMethod, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var items, count, item; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - items = []; - return [4 /*yield*/, AvroParser.readLong(stream, options)]; - case 1: - count = _a.sent(); - _a.label = 2; - case 2: - if (!(count != 0)) return [3 /*break*/, 8]; - if (!(count < 0)) return [3 /*break*/, 4]; - // Ignore block sizes - return [4 /*yield*/, AvroParser.readLong(stream, options)]; - case 3: - // Ignore block sizes - _a.sent(); - count = -count; - _a.label = 4; - case 4: - if (!count--) return [3 /*break*/, 6]; - return [4 /*yield*/, readItemMethod(stream, options)]; - case 5: - item = _a.sent(); - items.push(item); - return [3 /*break*/, 4]; - case 6: return [4 /*yield*/, AvroParser.readLong(stream, options)]; - case 7: - count = _a.sent(); - return [3 /*break*/, 2]; - case 8: return [2 /*return*/, items]; - } - }); - }); - }; - return AvroParser; -}()); + static async readZigZagLong(stream, options = {}) { + let zigZagEncoded = 0; + let significanceInBit = 0; + let byte, haveMoreByte, significanceInFloat; + do { + byte = await AvroParser.readByte(stream, options); + haveMoreByte = byte & 0x80; + zigZagEncoded |= (byte & 0x7f) << significanceInBit; + significanceInBit += 7; + } while (haveMoreByte && significanceInBit < 28); // bitwise operation only works for 32-bit integers + if (haveMoreByte) { + // Switch to float arithmetic + zigZagEncoded = zigZagEncoded; + significanceInFloat = 268435456; // 2 ** 28. + do { + byte = await AvroParser.readByte(stream, options); + zigZagEncoded += (byte & 0x7f) * significanceInFloat; + significanceInFloat *= 128; // 2 ** 7 + } while (byte & 0x80); + const res = (zigZagEncoded % 2 ? -(zigZagEncoded + 1) : zigZagEncoded) / 2; + if (res < Number.MIN_SAFE_INTEGER || res > Number.MAX_SAFE_INTEGER) { + throw new Error("Integer overflow."); + } + return res; + } + return (zigZagEncoded >> 1) ^ -(zigZagEncoded & 1); + } + static async readLong(stream, options = {}) { + return AvroParser.readZigZagLong(stream, options); + } + static async readInt(stream, options = {}) { + return AvroParser.readZigZagLong(stream, options); + } + static async readNull() { + return null; + } + static async readBoolean(stream, options = {}) { + const b = await AvroParser.readByte(stream, options); + if (b == 1) { + return true; + } + else if (b == 0) { + return false; + } + else { + throw new Error("Byte was not a boolean."); + } + } + static async readFloat(stream, options = {}) { + const u8arr = await AvroParser.readFixedBytes(stream, 4, options); + const view = new DataView(u8arr.buffer, u8arr.byteOffset, u8arr.byteLength); + return view.getFloat32(0, true); // littleEndian = true + } + static async readDouble(stream, options = {}) { + const u8arr = await AvroParser.readFixedBytes(stream, 8, options); + const view = new DataView(u8arr.buffer, u8arr.byteOffset, u8arr.byteLength); + return view.getFloat64(0, true); // littleEndian = true + } + static async readBytes(stream, options = {}) { + const size = await AvroParser.readLong(stream, options); + if (size < 0) { + throw new Error("Bytes size was negative."); + } + return await stream.read(size, { abortSignal: options.abortSignal }); + } + static async readString(stream, options = {}) { + const u8arr = await AvroParser.readBytes(stream, options); + // polyfill TextDecoder to be backward compatible with older + // nodejs that doesn't expose TextDecoder as a global variable + if (typeof TextDecoder === "undefined" && "function" !== "undefined") { + global.TextDecoder = __webpack_require__(669).TextDecoder; + } + // FUTURE: need TextDecoder polyfill for IE + const utf8decoder = new TextDecoder(); + return utf8decoder.decode(u8arr); + } + static async readMapPair(stream, readItemMethod, options = {}) { + const key = await AvroParser.readString(stream, options); + // FUTURE: this won't work with readFixed (currently not supported) which needs a length as the parameter. + const value = await readItemMethod(stream, options); + return { key, value }; + } + static async readMap(stream, readItemMethod, options = {}) { + const readPairMethod = async (stream, options = {}) => { + return await AvroParser.readMapPair(stream, readItemMethod, options); + }; + const pairs = await AvroParser.readArray(stream, readPairMethod, options); + const dict = {}; + for (const pair of pairs) { + dict[pair.key] = pair.value; + } + return dict; + } + static async readArray(stream, readItemMethod, options = {}) { + const items = []; + for (let count = await AvroParser.readLong(stream, options); count != 0; count = await AvroParser.readLong(stream, options)) { + if (count < 0) { + // Ignore block sizes + await AvroParser.readLong(stream, options); + count = -count; + } + while (count--) { + const item = await readItemMethod(stream, options); + items.push(item); + } + } + return items; + } +} var AvroComplex; (function (AvroComplex) { AvroComplex["RECORD"] = "record"; @@ -28526,13 +25767,11 @@ var AvroComplex; AvroComplex["UNION"] = "union"; AvroComplex["FIXED"] = "fixed"; })(AvroComplex || (AvroComplex = {})); -var AvroType = /** @class */ (function () { - function AvroType() { - } +class AvroType { /** * Determines the AvroType from the Avro Schema. */ - AvroType.fromSchema = function (schema) { + static fromSchema(schema) { if (typeof schema === "string") { return AvroType.fromStringSchema(schema); } @@ -28542,8 +25781,8 @@ var AvroType = /** @class */ (function () { else { return AvroType.fromObjectSchema(schema); } - }; - AvroType.fromStringSchema = function (schema) { + } + static fromStringSchema(schema) { switch (schema) { case AvroPrimitive.NULL: case AvroPrimitive.BOOLEAN: @@ -28555,14 +25794,14 @@ var AvroType = /** @class */ (function () { case AvroPrimitive.STRING: return new AvroPrimitiveType(schema); default: - throw new Error("Unexpected Avro type " + schema); + throw new Error(`Unexpected Avro type ${schema}`); } - }; - AvroType.fromArraySchema = function (schema) { + } + static fromArraySchema(schema) { return new AvroUnionType(schema.map(AvroType.fromSchema)); - }; - AvroType.fromObjectSchema = function (schema) { - var type = schema.type; + } + static fromObjectSchema(schema) { + const type = schema.type; // Primitives can be defined as strings or objects try { return AvroType.fromStringSchema(type); @@ -28571,41 +25810,39 @@ var AvroType = /** @class */ (function () { switch (type) { case AvroComplex.RECORD: if (schema.aliases) { - throw new Error("aliases currently is not supported, schema: " + schema); + throw new Error(`aliases currently is not supported, schema: ${schema}`); } if (!schema.name) { - throw new Error("Required attribute 'name' doesn't exist on schema: " + schema); + throw new Error(`Required attribute 'name' doesn't exist on schema: ${schema}`); } - var fields = {}; + const fields = {}; if (!schema.fields) { - throw new Error("Required attribute 'fields' doesn't exist on schema: " + schema); + throw new Error(`Required attribute 'fields' doesn't exist on schema: ${schema}`); } - for (var _i = 0, _a = schema.fields; _i < _a.length; _i++) { - var field = _a[_i]; + for (const field of schema.fields) { fields[field.name] = AvroType.fromSchema(field.type); } return new AvroRecordType(fields, schema.name); case AvroComplex.ENUM: if (schema.aliases) { - throw new Error("aliases currently is not supported, schema: " + schema); + throw new Error(`aliases currently is not supported, schema: ${schema}`); } if (!schema.symbols) { - throw new Error("Required attribute 'symbols' doesn't exist on schema: " + schema); + throw new Error(`Required attribute 'symbols' doesn't exist on schema: ${schema}`); } return new AvroEnumType(schema.symbols); case AvroComplex.MAP: if (!schema.values) { - throw new Error("Required attribute 'values' doesn't exist on schema: " + schema); + throw new Error(`Required attribute 'values' doesn't exist on schema: ${schema}`); } return new AvroMapType(AvroType.fromSchema(schema.values)); case AvroComplex.ARRAY: // Unused today case AvroComplex.FIXED: // Unused today default: - throw new Error("Unexpected Avro type " + type + " in " + schema); + throw new Error(`Unexpected Avro type ${type} in ${schema}`); } - }; - return AvroType; -}()); + } +} var AvroPrimitive; (function (AvroPrimitive) { AvroPrimitive["NULL"] = "null"; @@ -28617,179 +25854,87 @@ var AvroPrimitive; AvroPrimitive["BYTES"] = "bytes"; AvroPrimitive["STRING"] = "string"; })(AvroPrimitive || (AvroPrimitive = {})); -var AvroPrimitiveType = /** @class */ (function (_super) { - tslib.__extends(AvroPrimitiveType, _super); - function AvroPrimitiveType(primitive) { - var _this = _super.call(this) || this; - _this._primitive = primitive; - return _this; +class AvroPrimitiveType extends AvroType { + constructor(primitive) { + super(); + this._primitive = primitive; } - AvroPrimitiveType.prototype.read = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = this._primitive; - switch (_a) { - case AvroPrimitive.NULL: return [3 /*break*/, 1]; - case AvroPrimitive.BOOLEAN: return [3 /*break*/, 3]; - case AvroPrimitive.INT: return [3 /*break*/, 5]; - case AvroPrimitive.LONG: return [3 /*break*/, 7]; - case AvroPrimitive.FLOAT: return [3 /*break*/, 9]; - case AvroPrimitive.DOUBLE: return [3 /*break*/, 11]; - case AvroPrimitive.BYTES: return [3 /*break*/, 13]; - case AvroPrimitive.STRING: return [3 /*break*/, 15]; - } - return [3 /*break*/, 17]; - case 1: return [4 /*yield*/, AvroParser.readNull()]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: return [4 /*yield*/, AvroParser.readBoolean(stream, options)]; - case 4: return [2 /*return*/, _b.sent()]; - case 5: return [4 /*yield*/, AvroParser.readInt(stream, options)]; - case 6: return [2 /*return*/, _b.sent()]; - case 7: return [4 /*yield*/, AvroParser.readLong(stream, options)]; - case 8: return [2 /*return*/, _b.sent()]; - case 9: return [4 /*yield*/, AvroParser.readFloat(stream, options)]; - case 10: return [2 /*return*/, _b.sent()]; - case 11: return [4 /*yield*/, AvroParser.readDouble(stream, options)]; - case 12: return [2 /*return*/, _b.sent()]; - case 13: return [4 /*yield*/, AvroParser.readBytes(stream, options)]; - case 14: return [2 /*return*/, _b.sent()]; - case 15: return [4 /*yield*/, AvroParser.readString(stream, options)]; - case 16: return [2 /*return*/, _b.sent()]; - case 17: throw new Error("Unknown Avro Primitive"); - } - }); - }); - }; - return AvroPrimitiveType; -}(AvroType)); -var AvroEnumType = /** @class */ (function (_super) { - tslib.__extends(AvroEnumType, _super); - function AvroEnumType(symbols) { - var _this = _super.call(this) || this; - _this._symbols = symbols; - return _this; + async read(stream, options = {}) { + switch (this._primitive) { + case AvroPrimitive.NULL: + return await AvroParser.readNull(); + case AvroPrimitive.BOOLEAN: + return await AvroParser.readBoolean(stream, options); + case AvroPrimitive.INT: + return await AvroParser.readInt(stream, options); + case AvroPrimitive.LONG: + return await AvroParser.readLong(stream, options); + case AvroPrimitive.FLOAT: + return await AvroParser.readFloat(stream, options); + case AvroPrimitive.DOUBLE: + return await AvroParser.readDouble(stream, options); + case AvroPrimitive.BYTES: + return await AvroParser.readBytes(stream, options); + case AvroPrimitive.STRING: + return await AvroParser.readString(stream, options); + default: + throw new Error("Unknown Avro Primitive"); + } } - AvroEnumType.prototype.read = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var value; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, AvroParser.readInt(stream, options)]; - case 1: - value = _a.sent(); - return [2 /*return*/, this._symbols[value]]; - } - }); - }); - }; - return AvroEnumType; -}(AvroType)); -var AvroUnionType = /** @class */ (function (_super) { - tslib.__extends(AvroUnionType, _super); - function AvroUnionType(types) { - var _this = _super.call(this) || this; - _this._types = types; - return _this; +} +class AvroEnumType extends AvroType { + constructor(symbols) { + super(); + this._symbols = symbols; } - AvroUnionType.prototype.read = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var typeIndex; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, AvroParser.readInt(stream, options)]; - case 1: - typeIndex = _a.sent(); - return [4 /*yield*/, this._types[typeIndex].read(stream, options)]; - case 2: return [2 /*return*/, _a.sent()]; - } - }); - }); - }; - return AvroUnionType; -}(AvroType)); -var AvroMapType = /** @class */ (function (_super) { - tslib.__extends(AvroMapType, _super); - function AvroMapType(itemType) { - var _this = _super.call(this) || this; - _this._itemType = itemType; - return _this; + async read(stream, options = {}) { + const value = await AvroParser.readInt(stream, options); + return this._symbols[value]; } - AvroMapType.prototype.read = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var readItemMethod; - var _this = this; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - readItemMethod = function (s, options) { return tslib.__awaiter(_this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this._itemType.read(s, options)]; - case 1: return [2 /*return*/, _a.sent()]; - } - }); - }); }; - return [4 /*yield*/, AvroParser.readMap(stream, readItemMethod, options)]; - case 1: return [2 /*return*/, _a.sent()]; - } - }); - }); - }; - return AvroMapType; -}(AvroType)); -var AvroRecordType = /** @class */ (function (_super) { - tslib.__extends(AvroRecordType, _super); - function AvroRecordType(fields, name) { - var _this = _super.call(this) || this; - _this._fields = fields; - _this._name = name; - return _this; +} +class AvroUnionType extends AvroType { + constructor(types) { + super(); + this._types = types; } - AvroRecordType.prototype.read = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var record, _a, _b, _i, key, _c, _d; - return tslib.__generator(this, function (_e) { - switch (_e.label) { - case 0: - record = {}; - record["$schema"] = this._name; - _a = []; - for (_b in this._fields) - _a.push(_b); - _i = 0; - _e.label = 1; - case 1: - if (!(_i < _a.length)) return [3 /*break*/, 4]; - key = _a[_i]; - if (!this._fields.hasOwnProperty(key)) return [3 /*break*/, 3]; - _c = record; - _d = key; - return [4 /*yield*/, this._fields[key].read(stream, options)]; - case 2: - _c[_d] = _e.sent(); - _e.label = 3; - case 3: - _i++; - return [3 /*break*/, 1]; - case 4: return [2 /*return*/, record]; - } - }); - }); - }; - return AvroRecordType; -}(AvroType)); + async read(stream, options = {}) { + const typeIndex = await AvroParser.readInt(stream, options); + return await this._types[typeIndex].read(stream, options); + } +} +class AvroMapType extends AvroType { + constructor(itemType) { + super(); + this._itemType = itemType; + } + async read(stream, options = {}) { + const readItemMethod = async (s, options) => { + return await this._itemType.read(s, options); + }; + return await AvroParser.readMap(stream, readItemMethod, options); + } +} +class AvroRecordType extends AvroType { + constructor(fields, name) { + super(); + this._fields = fields; + this._name = name; + } + async read(stream, options = {}) { + const record = {}; + record["$schema"] = this._name; + for (const key in this._fields) { + if (this._fields.hasOwnProperty(key)) { + record[key] = await this._fields[key].read(stream, options); + } + } + return record; + } +} // Copyright (c) Microsoft Corporation. -var AvroReader = /** @class */ (function () { - function AvroReader(dataStream, headerStream, currentBlockOffset, indexWithinCurrentBlock) { +class AvroReader { + constructor(dataStream, headerStream, currentBlockOffset, indexWithinCurrentBlock) { this._dataStream = dataStream; this._headerStream = headerStream || dataStream; this._initialized = false; @@ -28797,261 +25942,178 @@ var AvroReader = /** @class */ (function () { this._objectIndex = indexWithinCurrentBlock || 0; this._initialBlockOffset = currentBlockOffset || 0; } - Object.defineProperty(AvroReader.prototype, "blockOffset", { - get: function () { - return this._blockOffset; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AvroReader.prototype, "objectIndex", { - get: function () { - return this._objectIndex; - }, - enumerable: false, - configurable: true - }); - AvroReader.prototype.initialize = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var header, _a, codec, _b, schema, _c, i; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: return [4 /*yield*/, AvroParser.readFixedBytes(this._headerStream, AVRO_INIT_BYTES.length, { - abortSignal: options.abortSignal - })]; - case 1: - header = _d.sent(); - if (!arraysEqual(header, AVRO_INIT_BYTES)) { - throw new Error("Stream is not an Avro file."); - } - // File metadata is written as if defined by the following map schema: - // { "type": "map", "values": "bytes"} - _a = this; - return [4 /*yield*/, AvroParser.readMap(this._headerStream, AvroParser.readString, { - abortSignal: options.abortSignal - })]; - case 2: - // File metadata is written as if defined by the following map schema: - // { "type": "map", "values": "bytes"} - _a._metadata = _d.sent(); - codec = this._metadata[AVRO_CODEC_KEY]; - if (!(codec == undefined || codec == "null")) { - throw new Error("Codecs are not supported"); - } - // The 16-byte, randomly-generated sync marker for this file. - _b = this; - return [4 /*yield*/, AvroParser.readFixedBytes(this._headerStream, AVRO_SYNC_MARKER_SIZE, { - abortSignal: options.abortSignal - })]; - case 3: - // The 16-byte, randomly-generated sync marker for this file. - _b._syncMarker = _d.sent(); - schema = JSON.parse(this._metadata[AVRO_SCHEMA_KEY]); - this._itemType = AvroType.fromSchema(schema); - if (this._blockOffset == 0) { - this._blockOffset = this._initialBlockOffset + this._dataStream.position; - } - _c = this; - return [4 /*yield*/, AvroParser.readLong(this._dataStream, { - abortSignal: options.abortSignal - })]; - case 4: - _c._itemsRemainingInBlock = _d.sent(); - // skip block length - return [4 /*yield*/, AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal })]; - case 5: - // skip block length - _d.sent(); - this._initialized = true; - if (!(this._objectIndex && this._objectIndex > 0)) return [3 /*break*/, 9]; - i = 0; - _d.label = 6; - case 6: - if (!(i < this._objectIndex)) return [3 /*break*/, 9]; - return [4 /*yield*/, this._itemType.read(this._dataStream, { abortSignal: options.abortSignal })]; - case 7: - _d.sent(); - this._itemsRemainingInBlock--; - _d.label = 8; - case 8: - i++; - return [3 /*break*/, 6]; - case 9: return [2 /*return*/]; - } - }); + get blockOffset() { + return this._blockOffset; + } + get objectIndex() { + return this._objectIndex; + } + async initialize(options = {}) { + const header = await AvroParser.readFixedBytes(this._headerStream, AVRO_INIT_BYTES.length, { + abortSignal: options.abortSignal }); - }; - AvroReader.prototype.hasNext = function () { + if (!arraysEqual(header, AVRO_INIT_BYTES)) { + throw new Error("Stream is not an Avro file."); + } + // File metadata is written as if defined by the following map schema: + // { "type": "map", "values": "bytes"} + this._metadata = await AvroParser.readMap(this._headerStream, AvroParser.readString, { + abortSignal: options.abortSignal + }); + // Validate codec + const codec = this._metadata[AVRO_CODEC_KEY]; + if (!(codec == undefined || codec == "null")) { + throw new Error("Codecs are not supported"); + } + // The 16-byte, randomly-generated sync marker for this file. + this._syncMarker = await AvroParser.readFixedBytes(this._headerStream, AVRO_SYNC_MARKER_SIZE, { + abortSignal: options.abortSignal + }); + // Parse the schema + const schema = JSON.parse(this._metadata[AVRO_SCHEMA_KEY]); + this._itemType = AvroType.fromSchema(schema); + if (this._blockOffset == 0) { + this._blockOffset = this._initialBlockOffset + this._dataStream.position; + } + this._itemsRemainingInBlock = await AvroParser.readLong(this._dataStream, { + abortSignal: options.abortSignal + }); + // skip block length + await AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal }); + this._initialized = true; + if (this._objectIndex && this._objectIndex > 0) { + for (let i = 0; i < this._objectIndex; i++) { + await this._itemType.read(this._dataStream, { abortSignal: options.abortSignal }); + this._itemsRemainingInBlock--; + } + } + } + hasNext() { return !this._initialized || this._itemsRemainingInBlock > 0; - }; - AvroReader.prototype.parseObjects = function (options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function parseObjects_1() { - var result, marker, _a, err_1; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!!this._initialized) return [3 /*break*/, 2]; - return [4 /*yield*/, tslib.__await(this.initialize(options))]; - case 1: - _b.sent(); - _b.label = 2; - case 2: - if (!this.hasNext()) return [3 /*break*/, 13]; - return [4 /*yield*/, tslib.__await(this._itemType.read(this._dataStream, { - abortSignal: options.abortSignal - }))]; - case 3: - result = _b.sent(); - this._itemsRemainingInBlock--; - this._objectIndex++; - if (!(this._itemsRemainingInBlock == 0)) return [3 /*break*/, 10]; - return [4 /*yield*/, tslib.__await(AvroParser.readFixedBytes(this._dataStream, AVRO_SYNC_MARKER_SIZE, { - abortSignal: options.abortSignal - }))]; - case 4: - marker = _b.sent(); - this._blockOffset = this._initialBlockOffset + this._dataStream.position; - this._objectIndex = 0; - if (!arraysEqual(this._syncMarker, marker)) { - throw new Error("Stream is not a valid Avro file."); - } - _b.label = 5; - case 5: - _b.trys.push([5, 7, , 8]); - _a = this; - return [4 /*yield*/, tslib.__await(AvroParser.readLong(this._dataStream, { - abortSignal: options.abortSignal - }))]; - case 6: - _a._itemsRemainingInBlock = _b.sent(); - return [3 /*break*/, 8]; - case 7: - err_1 = _b.sent(); + } + parseObjects(options = {}) { + return tslib.__asyncGenerator(this, arguments, function* parseObjects_1() { + if (!this._initialized) { + yield tslib.__await(this.initialize(options)); + } + while (this.hasNext()) { + const result = yield tslib.__await(this._itemType.read(this._dataStream, { + abortSignal: options.abortSignal + })); + this._itemsRemainingInBlock--; + this._objectIndex++; + if (this._itemsRemainingInBlock == 0) { + const marker = yield tslib.__await(AvroParser.readFixedBytes(this._dataStream, AVRO_SYNC_MARKER_SIZE, { + abortSignal: options.abortSignal + })); + this._blockOffset = this._initialBlockOffset + this._dataStream.position; + this._objectIndex = 0; + if (!arraysEqual(this._syncMarker, marker)) { + throw new Error("Stream is not a valid Avro file."); + } + try { + this._itemsRemainingInBlock = yield tslib.__await(AvroParser.readLong(this._dataStream, { + abortSignal: options.abortSignal + })); + } + catch (err) { // We hit the end of the stream. this._itemsRemainingInBlock = 0; - return [3 /*break*/, 8]; - case 8: - if (!(this._itemsRemainingInBlock > 0)) return [3 /*break*/, 10]; + } + if (this._itemsRemainingInBlock > 0) { // Ignore block size - return [4 /*yield*/, tslib.__await(AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal }))]; - case 9: - // Ignore block size - _b.sent(); - _b.label = 10; - case 10: return [4 /*yield*/, tslib.__await(result)]; - case 11: return [4 /*yield*/, _b.sent()]; - case 12: - _b.sent(); - return [3 /*break*/, 2]; - case 13: return [2 /*return*/]; + yield tslib.__await(AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal })); + } } - }); + yield yield tslib.__await(result); + } }); - }; - return AvroReader; -}()); + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -var AvroReadable = /** @class */ (function () { - function AvroReadable() { - } - return AvroReadable; -}()); +class AvroReadable { +} // Copyright (c) Microsoft Corporation. -var ABORT_ERROR = new abortController.AbortError("Reading from the avro stream was aborted."); -var AvroReadableFromStream = /** @class */ (function (_super) { - tslib.__extends(AvroReadableFromStream, _super); - function AvroReadableFromStream(readable) { - var _this = _super.call(this) || this; - _this._readable = readable; - _this._position = 0; - return _this; +const ABORT_ERROR = new abortController.AbortError("Reading from the avro stream was aborted."); +class AvroReadableFromStream extends AvroReadable { + constructor(readable) { + super(); + this._readable = readable; + this._position = 0; } - AvroReadableFromStream.prototype.toUint8Array = function (data) { + toUint8Array(data) { if (typeof data === "string") { return Buffer.from(data); } return data; - }; - Object.defineProperty(AvroReadableFromStream.prototype, "position", { - get: function () { - return this._position; - }, - enumerable: false, - configurable: true - }); - AvroReadableFromStream.prototype.read = function (size, options) { + } + get position() { + return this._position; + } + async read(size, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var chunk; - var _this = this; - return tslib.__generator(this, function (_b) { - if ((_a = options.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { - throw ABORT_ERROR; - } - if (size < 0) { - throw new Error("size parameter should be positive: " + size); - } - if (size === 0) { - return [2 /*return*/, new Uint8Array()]; - } - if (!this._readable.readable) { - throw new Error("Stream no longer readable."); - } - chunk = this._readable.read(size); - if (chunk) { - this._position += chunk.length; - // chunk.length maybe less than desired size if the stream ends. - return [2 /*return*/, this.toUint8Array(chunk)]; - } - else { - // register callback to wait for enough data to read - return [2 /*return*/, new Promise(function (resolve, reject) { - var cleanUp = function () { - _this._readable.removeListener("readable", readableCallback); - _this._readable.removeListener("error", rejectCallback); - _this._readable.removeListener("end", rejectCallback); - _this._readable.removeListener("close", rejectCallback); - if (options.abortSignal) { - options.abortSignal.removeEventListener("abort", abortHandler); - } - }; - var readableCallback = function () { - var chunk = _this._readable.read(size); - if (chunk) { - _this._position += chunk.length; - cleanUp(); - // chunk.length maybe less than desired size if the stream ends. - resolve(_this.toUint8Array(chunk)); - } - }; - var rejectCallback = function () { - cleanUp(); - reject(); - }; - var abortHandler = function () { - cleanUp(); - reject(ABORT_ERROR); - }; - _this._readable.on("readable", readableCallback); - _this._readable.once("error", rejectCallback); - _this._readable.once("end", rejectCallback); - _this._readable.once("close", rejectCallback); - if (options.abortSignal) { - options.abortSignal.addEventListener("abort", abortHandler); - } - })]; + if ((_a = options.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { + throw ABORT_ERROR; + } + if (size < 0) { + throw new Error(`size parameter should be positive: ${size}`); + } + if (size === 0) { + return new Uint8Array(); + } + if (!this._readable.readable) { + throw new Error("Stream no longer readable."); + } + // See if there is already enough data. + const chunk = this._readable.read(size); + if (chunk) { + this._position += chunk.length; + // chunk.length maybe less than desired size if the stream ends. + return this.toUint8Array(chunk); + } + else { + // register callback to wait for enough data to read + return new Promise((resolve, reject) => { + const cleanUp = () => { + this._readable.removeListener("readable", readableCallback); + this._readable.removeListener("error", rejectCallback); + this._readable.removeListener("end", rejectCallback); + this._readable.removeListener("close", rejectCallback); + if (options.abortSignal) { + options.abortSignal.removeEventListener("abort", abortHandler); + } + }; + const readableCallback = () => { + const chunk = this._readable.read(size); + if (chunk) { + this._position += chunk.length; + cleanUp(); + // chunk.length maybe less than desired size if the stream ends. + resolve(this.toUint8Array(chunk)); + } + }; + const rejectCallback = () => { + cleanUp(); + reject(); + }; + const abortHandler = () => { + cleanUp(); + reject(ABORT_ERROR); + }; + this._readable.on("readable", readableCallback); + this._readable.once("error", rejectCallback); + this._readable.once("end", rejectCallback); + this._readable.once("close", rejectCallback); + if (options.abortSignal) { + options.abortSignal.addEventListener("abort", abortHandler); } }); - }); - }; - return AvroReadableFromStream; -}(AvroReadable)); + } + } +} // Copyright (c) Microsoft Corporation. /** @@ -29059,121 +26121,107 @@ var AvroReadableFromStream = /** @class */ (function (_super) { * * A Node.js BlobQuickQueryStream will internally parse avro data stream for blob query. */ -var BlobQuickQueryStream = /** @class */ (function (_super) { - tslib.__extends(BlobQuickQueryStream, _super); +class BlobQuickQueryStream extends stream.Readable { /** * Creates an instance of BlobQuickQueryStream. * * @param source - The current ReadableStream returned from getter * @param options - */ - 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; - _this.avroReader = new AvroReader(new AvroReadableFromStream(_this.source)); - _this.avroIter = _this.avroReader.parseObjects({ abortSignal: options.abortSignal }); - return _this; + constructor(source, options = {}) { + super(); + this.avroPaused = true; + this.source = source; + this.onProgress = options.onProgress; + this.onError = options.onError; + this.avroReader = new AvroReader(new AvroReadableFromStream(this.source)); + this.avroIter = this.avroReader.parseObjects({ abortSignal: options.abortSignal }); } - BlobQuickQueryStream.prototype._read = function () { - var _this = this; + _read() { if (this.avroPaused) { - this.readInternal().catch(function (err) { - _this.emit("error", err); + this.readInternal().catch((err) => { + this.emit("error", err); }); } - }; - BlobQuickQueryStream.prototype.readInternal = function () { - 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) { - case 0: - this.avroPaused = false; - _a.label = 1; - case 1: return [4 /*yield*/, this.avroIter.next()]; - case 2: - avroNext = _a.sent(); - if (avroNext.done) { - return [3 /*break*/, 4]; + } + async readInternal() { + this.avroPaused = false; + let avroNext; + do { + avroNext = await this.avroIter.next(); + if (avroNext.done) { + break; + } + const obj = avroNext.value; + const schema = obj.$schema; + if (typeof schema !== "string") { + throw Error("Missing schema in avro record."); + } + switch (schema) { + case "com.microsoft.azure.storage.queryBlobContents.resultData": + { + const data = obj.data; + if (data instanceof Uint8Array === false) { + throw Error("Invalid data in avro result record."); } - obj = avroNext.value; - schema = obj.$schema; - if (typeof schema !== "string") { - throw Error("Missing schema in avro record."); + if (!this.push(Buffer.from(data))) { + this.avroPaused = true; } - switch (schema) { - case "com.microsoft.azure.storage.queryBlobContents.resultData": - data = obj.data; - if (data instanceof Uint8Array === false) { - throw Error("Invalid data in avro result record."); - } - if (!this.push(Buffer.from(data))) { - this.avroPaused = true; - } - break; - case "com.microsoft.azure.storage.queryBlobContents.progress": - bytesScanned = obj.bytesScanned; - if (typeof bytesScanned !== "number") { - throw Error("Invalid bytesScanned in avro progress record."); - } - if (this.onProgress) { - this.onProgress({ loadedBytes: bytesScanned }); - } - break; - case "com.microsoft.azure.storage.queryBlobContents.end": - if (this.onProgress) { - totalBytes = obj.totalBytes; - if (typeof totalBytes !== "number") { - throw Error("Invalid totalBytes in avro end record."); - } - this.onProgress({ loadedBytes: totalBytes }); - } - this.push(null); - break; - case "com.microsoft.azure.storage.queryBlobContents.error": - if (this.onError) { - fatal = obj.fatal; - if (typeof fatal !== "boolean") { - throw Error("Invalid fatal in avro error record."); - } - name_1 = obj.name; - if (typeof name_1 !== "string") { - throw Error("Invalid name in avro error record."); - } - description = obj.description; - if (typeof description !== "string") { - throw Error("Invalid description in avro error record."); - } - position = obj.position; - if (typeof position !== "number") { - throw Error("Invalid position in avro error record."); - } - this.onError({ - position: position, - name: name_1, - isFatal: fatal, - description: description - }); - } - break; - default: - throw Error("Unknown schema " + schema + " in avro progress record."); + } + break; + case "com.microsoft.azure.storage.queryBlobContents.progress": + { + const bytesScanned = obj.bytesScanned; + if (typeof bytesScanned !== "number") { + throw Error("Invalid bytesScanned 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*/]; - } - }); - }); - }; - return BlobQuickQueryStream; -}(stream.Readable)); + if (this.onProgress) { + this.onProgress({ loadedBytes: bytesScanned }); + } + } + break; + case "com.microsoft.azure.storage.queryBlobContents.end": + if (this.onProgress) { + const totalBytes = obj.totalBytes; + if (typeof totalBytes !== "number") { + throw Error("Invalid totalBytes in avro end record."); + } + this.onProgress({ loadedBytes: totalBytes }); + } + this.push(null); + break; + case "com.microsoft.azure.storage.queryBlobContents.error": + if (this.onError) { + const fatal = obj.fatal; + if (typeof fatal !== "boolean") { + throw Error("Invalid fatal in avro error record."); + } + const name = obj.name; + if (typeof name !== "string") { + throw Error("Invalid name in avro error record."); + } + const description = obj.description; + if (typeof description !== "string") { + throw Error("Invalid description in avro error record."); + } + const position = obj.position; + if (typeof position !== "number") { + throw Error("Invalid position in avro error record."); + } + this.onError({ + position, + name, + isFatal: fatal, + description + }); + } + break; + default: + throw Error(`Unknown schema ${schema} in avro progress record.`); + } + } while (!avroNext.done && !this.avroPaused); + } +} // Copyright (c) Microsoft Corporation. /** @@ -29182,508 +26230,362 @@ var BlobQuickQueryStream = /** @class */ (function (_super) { * BlobQueryResponse implements BlobDownloadResponseModel interface, and in Node.js runtime it will * parse avor data returned by blob query. */ -var BlobQueryResponse = /** @class */ (function () { +class BlobQueryResponse { /** * Creates an instance of BlobQueryResponse. * * @param originalResponse - * @param options - */ - function BlobQueryResponse(originalResponse, options) { - if (options === void 0) { options = {}; } + constructor(originalResponse, options = {}) { this.originalResponse = originalResponse; this.blobDownloadStream = new BlobQuickQueryStream(this.originalResponse.readableStreamBody, options); } - Object.defineProperty(BlobQueryResponse.prototype, "acceptRanges", { - /** - * Indicates that the service supports - * requests for partial file content. - * - * @readonly - */ - get: function () { - return this.originalResponse.acceptRanges; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "cacheControl", { - /** - * Returns if it was previously specified - * for the file. - * - * @readonly - */ - get: function () { - return this.originalResponse.cacheControl; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "contentDisposition", { - /** - * Returns the value that was specified - * for the 'x-ms-content-disposition' header and specifies how to process the - * response. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentDisposition; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "contentEncoding", { - /** - * Returns the value that was specified - * for the Content-Encoding request header. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentEncoding; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "contentLanguage", { - /** - * Returns the value that was specified - * for the Content-Language request header. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentLanguage; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "blobSequenceNumber", { - /** - * The current sequence number for a - * page blob. This header is not returned for block blobs or append blobs. - * - * @readonly - */ - get: function () { - return this.originalResponse.blobSequenceNumber; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "blobType", { - /** - * The blob's type. Possible values include: - * 'BlockBlob', 'PageBlob', 'AppendBlob'. - * - * @readonly - */ - get: function () { - return this.originalResponse.blobType; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "contentLength", { - /** - * The number of bytes present in the - * response body. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentLength; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "contentMD5", { - /** - * If the file has an MD5 hash and the - * request is to read the full file, this response header is returned so that - * the client can check for message content integrity. If the request is to - * read a specified range and the 'x-ms-range-get-content-md5' is set to - * true, then the request returns an MD5 hash for the range, as long as the - * range size is less than or equal to 4 MB. If neither of these sets of - * conditions is true, then no value is returned for the 'Content-MD5' - * header. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentMD5; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "contentRange", { - /** - * Indicates the range of bytes returned if - * the client requested a subset of the file by setting the Range request - * header. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentRange; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "contentType", { - /** - * The content type specified for the file. - * The default content type is 'application/octet-stream' - * - * @readonly - */ - get: function () { - return this.originalResponse.contentType; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "copyCompletedOn", { - /** - * Conclusion time of the last attempted - * Copy File operation where this file was the destination file. This value - * can specify the time of a completed, aborted, or failed copy attempt. - * - * @readonly - */ - get: function () { - return undefined; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "copyId", { - /** - * String identifier for the last attempted Copy - * File operation where this file was the destination file. - * - * @readonly - */ - get: function () { - return this.originalResponse.copyId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "copyProgress", { - /** - * Contains the number of bytes copied and - * the total bytes in the source in the last attempted Copy File operation - * where this file was the destination file. Can show between 0 and - * Content-Length bytes copied. - * - * @readonly - */ - get: function () { - return this.originalResponse.copyProgress; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "copySource", { - /** - * URL up to 2KB in length that specifies the - * source file used in the last attempted Copy File operation where this file - * was the destination file. - * - * @readonly - */ - get: function () { - return this.originalResponse.copySource; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "copyStatus", { - /** - * State of the copy operation - * identified by 'x-ms-copy-id'. Possible values include: 'pending', - * 'success', 'aborted', 'failed' - * - * @readonly - */ - get: function () { - return this.originalResponse.copyStatus; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "copyStatusDescription", { - /** - * Only appears when - * x-ms-copy-status is failed or pending. Describes cause of fatal or - * non-fatal copy operation failure. - * - * @readonly - */ - get: function () { - return this.originalResponse.copyStatusDescription; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "leaseDuration", { - /** - * When a blob is leased, - * specifies whether the lease is of infinite or fixed duration. Possible - * values include: 'infinite', 'fixed'. - * - * @readonly - */ - get: function () { - return this.originalResponse.leaseDuration; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "leaseState", { - /** - * Lease state of the blob. Possible - * values include: 'available', 'leased', 'expired', 'breaking', 'broken'. - * - * @readonly - */ - get: function () { - return this.originalResponse.leaseState; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "leaseStatus", { - /** - * The current lease status of the - * blob. Possible values include: 'locked', 'unlocked'. - * - * @readonly - */ - get: function () { - return this.originalResponse.leaseStatus; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "date", { - /** - * A UTC date/time value generated by the service that - * indicates the time at which the response was initiated. - * - * @readonly - */ - get: function () { - return this.originalResponse.date; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "blobCommittedBlockCount", { - /** - * The number of committed blocks - * present in the blob. This header is returned only for append blobs. - * - * @readonly - */ - get: function () { - return this.originalResponse.blobCommittedBlockCount; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "etag", { - /** - * The ETag contains a value that you can use to - * perform operations conditionally, in quotes. - * - * @readonly - */ - get: function () { - return this.originalResponse.etag; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "errorCode", { - /** - * The error code. - * - * @readonly - */ - get: function () { - return this.originalResponse.errorCode; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "isServerEncrypted", { - /** - * The value of this header is set to - * true if the file data and application metadata are completely encrypted - * using the specified algorithm. Otherwise, the value is set to false (when - * the file is unencrypted, or if only parts of the file/application metadata - * are encrypted). - * - * @readonly - */ - get: function () { - return this.originalResponse.isServerEncrypted; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "blobContentMD5", { - /** - * If the blob has a MD5 hash, and if - * request contains range header (Range or x-ms-range), this response header - * is returned with the value of the whole blob's MD5 value. This value may - * or may not be equal to the value returned in Content-MD5 header, with the - * latter calculated from the requested range. - * - * @readonly - */ - get: function () { - return this.originalResponse.blobContentMD5; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "lastModified", { - /** - * Returns the date and time the file was last - * modified. Any operation that modifies the file or its properties updates - * the last modified time. - * - * @readonly - */ - get: function () { - return this.originalResponse.lastModified; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "metadata", { - /** - * A name-value pair - * to associate with a file storage object. - * - * @readonly - */ - get: function () { - return this.originalResponse.metadata; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "requestId", { - /** - * This header uniquely identifies the request - * that was made and can be used for troubleshooting the request. - * - * @readonly - */ - get: function () { - return this.originalResponse.requestId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "clientRequestId", { - /** - * If a client request id header is sent in the request, this header will be present in the - * response with the same value. - * - * @readonly - */ - get: function () { - return this.originalResponse.clientRequestId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "version", { - /** - * Indicates the version of the File service used - * to execute the request. - * - * @readonly - */ - get: function () { - return this.originalResponse.version; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "encryptionKeySha256", { - /** - * The SHA-256 hash of the encryption key used to encrypt the blob. This value is only returned - * when the blob was encrypted with a customer-provided key. - * - * @readonly - */ - get: function () { - return this.originalResponse.encryptionKeySha256; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "contentCrc64", { - /** - * If the request is to read a specified range and the x-ms-range-get-content-crc64 is set to - * true, then the request returns a crc64 for the range, as long as the range size is less than - * or equal to 4 MB. If both x-ms-range-get-content-crc64 & x-ms-range-get-content-md5 is - * specified in the same request, it will fail with 400(Bad Request) - */ - get: function () { - return this.originalResponse.contentCrc64; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "blobBody", { - /** - * The response body as a browser Blob. - * Always undefined in node.js. - * - * @readonly - */ - get: function () { - return undefined; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "readableStreamBody", { - /** - * The response body as a node.js Readable stream. - * Always undefined in the browser. - * - * It will parse avor data returned by blob query. - * - * @readonly - */ - get: function () { - return coreHttp.isNode ? this.blobDownloadStream : undefined; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "_response", { - /** - * The HTTP response. - */ - get: function () { - return this.originalResponse._response; - }, - enumerable: false, - configurable: true - }); - return BlobQueryResponse; -}()); + /** + * Indicates that the service supports + * requests for partial file content. + * + * @readonly + */ + get acceptRanges() { + return this.originalResponse.acceptRanges; + } + /** + * Returns if it was previously specified + * for the file. + * + * @readonly + */ + get cacheControl() { + return this.originalResponse.cacheControl; + } + /** + * Returns the value that was specified + * for the 'x-ms-content-disposition' header and specifies how to process the + * response. + * + * @readonly + */ + get contentDisposition() { + return this.originalResponse.contentDisposition; + } + /** + * Returns the value that was specified + * for the Content-Encoding request header. + * + * @readonly + */ + get contentEncoding() { + return this.originalResponse.contentEncoding; + } + /** + * Returns the value that was specified + * for the Content-Language request header. + * + * @readonly + */ + get contentLanguage() { + return this.originalResponse.contentLanguage; + } + /** + * The current sequence number for a + * page blob. This header is not returned for block blobs or append blobs. + * + * @readonly + */ + get blobSequenceNumber() { + return this.originalResponse.blobSequenceNumber; + } + /** + * The blob's type. Possible values include: + * 'BlockBlob', 'PageBlob', 'AppendBlob'. + * + * @readonly + */ + get blobType() { + return this.originalResponse.blobType; + } + /** + * The number of bytes present in the + * response body. + * + * @readonly + */ + get contentLength() { + return this.originalResponse.contentLength; + } + /** + * If the file has an MD5 hash and the + * request is to read the full file, this response header is returned so that + * the client can check for message content integrity. If the request is to + * read a specified range and the 'x-ms-range-get-content-md5' is set to + * true, then the request returns an MD5 hash for the range, as long as the + * range size is less than or equal to 4 MB. If neither of these sets of + * conditions is true, then no value is returned for the 'Content-MD5' + * header. + * + * @readonly + */ + get contentMD5() { + return this.originalResponse.contentMD5; + } + /** + * Indicates the range of bytes returned if + * the client requested a subset of the file by setting the Range request + * header. + * + * @readonly + */ + get contentRange() { + return this.originalResponse.contentRange; + } + /** + * The content type specified for the file. + * The default content type is 'application/octet-stream' + * + * @readonly + */ + get contentType() { + return this.originalResponse.contentType; + } + /** + * Conclusion time of the last attempted + * Copy File operation where this file was the destination file. This value + * can specify the time of a completed, aborted, or failed copy attempt. + * + * @readonly + */ + get copyCompletedOn() { + return undefined; + } + /** + * String identifier for the last attempted Copy + * File operation where this file was the destination file. + * + * @readonly + */ + get copyId() { + return this.originalResponse.copyId; + } + /** + * Contains the number of bytes copied and + * the total bytes in the source in the last attempted Copy File operation + * where this file was the destination file. Can show between 0 and + * Content-Length bytes copied. + * + * @readonly + */ + get copyProgress() { + return this.originalResponse.copyProgress; + } + /** + * URL up to 2KB in length that specifies the + * source file used in the last attempted Copy File operation where this file + * was the destination file. + * + * @readonly + */ + get copySource() { + return this.originalResponse.copySource; + } + /** + * State of the copy operation + * identified by 'x-ms-copy-id'. Possible values include: 'pending', + * 'success', 'aborted', 'failed' + * + * @readonly + */ + get copyStatus() { + return this.originalResponse.copyStatus; + } + /** + * Only appears when + * x-ms-copy-status is failed or pending. Describes cause of fatal or + * non-fatal copy operation failure. + * + * @readonly + */ + get copyStatusDescription() { + return this.originalResponse.copyStatusDescription; + } + /** + * When a blob is leased, + * specifies whether the lease is of infinite or fixed duration. Possible + * values include: 'infinite', 'fixed'. + * + * @readonly + */ + get leaseDuration() { + return this.originalResponse.leaseDuration; + } + /** + * Lease state of the blob. Possible + * values include: 'available', 'leased', 'expired', 'breaking', 'broken'. + * + * @readonly + */ + get leaseState() { + return this.originalResponse.leaseState; + } + /** + * The current lease status of the + * blob. Possible values include: 'locked', 'unlocked'. + * + * @readonly + */ + get leaseStatus() { + return this.originalResponse.leaseStatus; + } + /** + * A UTC date/time value generated by the service that + * indicates the time at which the response was initiated. + * + * @readonly + */ + get date() { + return this.originalResponse.date; + } + /** + * The number of committed blocks + * present in the blob. This header is returned only for append blobs. + * + * @readonly + */ + get blobCommittedBlockCount() { + return this.originalResponse.blobCommittedBlockCount; + } + /** + * The ETag contains a value that you can use to + * perform operations conditionally, in quotes. + * + * @readonly + */ + get etag() { + return this.originalResponse.etag; + } + /** + * The error code. + * + * @readonly + */ + get errorCode() { + return this.originalResponse.errorCode; + } + /** + * The value of this header is set to + * true if the file data and application metadata are completely encrypted + * using the specified algorithm. Otherwise, the value is set to false (when + * the file is unencrypted, or if only parts of the file/application metadata + * are encrypted). + * + * @readonly + */ + get isServerEncrypted() { + return this.originalResponse.isServerEncrypted; + } + /** + * If the blob has a MD5 hash, and if + * request contains range header (Range or x-ms-range), this response header + * is returned with the value of the whole blob's MD5 value. This value may + * or may not be equal to the value returned in Content-MD5 header, with the + * latter calculated from the requested range. + * + * @readonly + */ + get blobContentMD5() { + return this.originalResponse.blobContentMD5; + } + /** + * Returns the date and time the file was last + * modified. Any operation that modifies the file or its properties updates + * the last modified time. + * + * @readonly + */ + get lastModified() { + return this.originalResponse.lastModified; + } + /** + * A name-value pair + * to associate with a file storage object. + * + * @readonly + */ + get metadata() { + return this.originalResponse.metadata; + } + /** + * This header uniquely identifies the request + * that was made and can be used for troubleshooting the request. + * + * @readonly + */ + get requestId() { + return this.originalResponse.requestId; + } + /** + * If a client request id header is sent in the request, this header will be present in the + * response with the same value. + * + * @readonly + */ + get clientRequestId() { + return this.originalResponse.clientRequestId; + } + /** + * Indicates the version of the File service used + * to execute the request. + * + * @readonly + */ + get version() { + return this.originalResponse.version; + } + /** + * The SHA-256 hash of the encryption key used to encrypt the blob. This value is only returned + * when the blob was encrypted with a customer-provided key. + * + * @readonly + */ + get encryptionKeySha256() { + return this.originalResponse.encryptionKeySha256; + } + /** + * If the request is to read a specified range and the x-ms-range-get-content-crc64 is set to + * true, then the request returns a crc64 for the range, as long as the range size is less than + * or equal to 4 MB. If both x-ms-range-get-content-crc64 & x-ms-range-get-content-md5 is + * specified in the same request, it will fail with 400(Bad Request) + */ + get contentCrc64() { + return this.originalResponse.contentCrc64; + } + /** + * The response body as a browser Blob. + * Always undefined in node.js. + * + * @readonly + */ + get blobBody() { + return undefined; + } + /** + * The response body as a node.js Readable stream. + * Always undefined in the browser. + * + * It will parse avor data returned by blob query. + * + * @readonly + */ + get readableStreamBody() { + return coreHttp.isNode ? this.blobDownloadStream : undefined; + } + /** + * The HTTP response. + */ + get _response() { + return this.originalResponse._response; + } +} // Copyright (c) Microsoft Corporation. (function (BlockBlobTier) { @@ -29748,7 +26650,7 @@ var BlobQueryResponse = /** @class */ (function () { PremiumPageBlobTier["P80"] = "P80"; })(exports.PremiumPageBlobTier || (exports.PremiumPageBlobTier = {})); function toAccessTier(tier) { - if (tier == undefined) { + if (tier === undefined) { return undefined; } return tier; // No more check if string is a valid AccessTier, and left this to underlay logic to decide(service). @@ -29763,6 +26665,7 @@ function ensureCpkIfSpecified(cpk, isHttps) { } // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** * Function that converts PageRange and ClearRange to a common Range object. * PageRange and ClearRange have start and end while Range offset and count @@ -29770,18 +26673,18 @@ function ensureCpkIfSpecified(cpk, isHttps) { * @param response - Model PageBlob Range response */ function rangeResponseFromModel(response) { - var pageRange = (response._response.parsedBody.pageRange || []).map(function (x) { return ({ + const pageRange = (response._response.parsedBody.pageRange || []).map((x) => ({ offset: x.start, count: x.end - x.start - }); }); - var clearRange = (response._response.parsedBody.clearRange || []).map(function (x) { return ({ + })); + const clearRange = (response._response.parsedBody.clearRange || []).map((x) => ({ offset: x.start, count: x.end - x.start - }); }); - return tslib.__assign(tslib.__assign({}, response), { pageRange: pageRange, - clearRange: clearRange, _response: tslib.__assign(tslib.__assign({}, response._response), { parsedBody: { - pageRange: pageRange, - clearRange: clearRange + })); + return Object.assign(Object.assign({}, response), { pageRange, + clearRange, _response: Object.assign(Object.assign({}, response._response), { parsedBody: { + pageRange, + clearRange } }) }); } @@ -29792,64 +26695,48 @@ function rangeResponseFromModel(response) { * * @hidden */ -var BlobBeginCopyFromUrlPoller = /** @class */ (function (_super) { - tslib.__extends(BlobBeginCopyFromUrlPoller, _super); - function BlobBeginCopyFromUrlPoller(options) { - var _this = this; - var blobClient = options.blobClient, copySource = options.copySource, _a = options.intervalInMs, intervalInMs = _a === void 0 ? 15000 : _a, onProgress = options.onProgress, resumeFrom = options.resumeFrom, startCopyFromURLOptions = options.startCopyFromURLOptions; - var state; +class BlobBeginCopyFromUrlPoller extends coreLro.Poller { + constructor(options) { + const { blobClient, copySource, intervalInMs = 15000, onProgress, resumeFrom, startCopyFromURLOptions } = options; + let state; if (resumeFrom) { state = JSON.parse(resumeFrom).state; } - var operation = makeBlobBeginCopyFromURLPollOperation(tslib.__assign(tslib.__assign({}, state), { blobClient: blobClient, - copySource: copySource, - startCopyFromURLOptions: startCopyFromURLOptions })); - _this = _super.call(this, operation) || this; + const operation = makeBlobBeginCopyFromURLPollOperation(Object.assign(Object.assign({}, state), { blobClient, + copySource, + startCopyFromURLOptions })); + super(operation); if (typeof onProgress === "function") { - _this.onProgress(onProgress); + this.onProgress(onProgress); } - _this.intervalInMs = intervalInMs; - return _this; + this.intervalInMs = intervalInMs; } - BlobBeginCopyFromUrlPoller.prototype.delay = function () { + delay() { return coreHttp.delay(this.intervalInMs); - }; - return BlobBeginCopyFromUrlPoller; -}(coreLro.Poller)); + } +} /** * 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 */ -var cancel = function cancel(options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var state, copyId; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - state = this.state; - copyId = state.copyId; - if (state.isCompleted) { - return [2 /*return*/, makeBlobBeginCopyFromURLPollOperation(state)]; - } - if (!copyId) { - state.isCancelled = true; - return [2 /*return*/, makeBlobBeginCopyFromURLPollOperation(state)]; - } - // if abortCopyFromURL throws, it will bubble up to user's poller.cancelOperation call - return [4 /*yield*/, state.blobClient.abortCopyFromURL(copyId, { - abortSignal: options.abortSignal - })]; - case 1: - // if abortCopyFromURL throws, it will bubble up to user's poller.cancelOperation call - _a.sent(); - state.isCancelled = true; - return [2 /*return*/, makeBlobBeginCopyFromURLPollOperation(state)]; - } - }); +const cancel = async function cancel(options = {}) { + const state = this.state; + const { copyId } = state; + if (state.isCompleted) { + return makeBlobBeginCopyFromURLPollOperation(state); + } + if (!copyId) { + state.isCancelled = true; + return makeBlobBeginCopyFromURLPollOperation(state); + } + // if abortCopyFromURL throws, it will bubble up to user's poller.cancelOperation call + await state.blobClient.abortCopyFromURL(copyId, { + abortSignal: options.abortSignal }); + state.isCancelled = true; + return makeBlobBeginCopyFromURLPollOperation(state); }; /** * Note: Intentionally using function expression over arrow function expression @@ -29857,64 +26744,48 @@ var cancel = function cancel(options) { * This affects what `this` refers to. * @hidden */ -var update = function update(options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var state, blobClient, copySource, startCopyFromURLOptions, result, result, copyStatus, copyProgress, prevCopyProgress, err_1; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - state = this.state; - blobClient = state.blobClient, copySource = state.copySource, startCopyFromURLOptions = state.startCopyFromURLOptions; - if (!!state.isStarted) return [3 /*break*/, 2]; - state.isStarted = true; - return [4 /*yield*/, blobClient.startCopyFromURL(copySource, startCopyFromURLOptions)]; - case 1: - result = _a.sent(); - // copyId is needed to abort - state.copyId = result.copyId; - if (result.copyStatus === "success") { - state.result = result; - state.isCompleted = true; - } - return [3 /*break*/, 6]; - case 2: - if (!!state.isCompleted) return [3 /*break*/, 6]; - _a.label = 3; - case 3: - _a.trys.push([3, 5, , 6]); - return [4 /*yield*/, state.blobClient.getProperties({ abortSignal: options.abortSignal })]; - case 4: - result = _a.sent(); - copyStatus = result.copyStatus, copyProgress = result.copyProgress; - prevCopyProgress = state.copyProgress; - if (copyProgress) { - state.copyProgress = copyProgress; - } - if (copyStatus === "pending" && - copyProgress !== prevCopyProgress && - typeof options.fireProgress === "function") { - // trigger in setTimeout, or swallow error? - options.fireProgress(state); - } - else if (copyStatus === "success") { - state.result = result; - state.isCompleted = true; - } - else if (copyStatus === "failed") { - state.error = new Error("Blob copy failed with reason: \"" + (result.copyStatusDescription || "unknown") + "\""); - state.isCompleted = true; - } - return [3 /*break*/, 6]; - case 5: - err_1 = _a.sent(); - state.error = err_1; - state.isCompleted = true; - return [3 /*break*/, 6]; - case 6: return [2 /*return*/, makeBlobBeginCopyFromURLPollOperation(state)]; +const update = async function update(options = {}) { + const state = this.state; + const { blobClient, copySource, startCopyFromURLOptions } = state; + if (!state.isStarted) { + state.isStarted = true; + const result = await blobClient.startCopyFromURL(copySource, startCopyFromURLOptions); + // copyId is needed to abort + state.copyId = result.copyId; + if (result.copyStatus === "success") { + state.result = result; + state.isCompleted = true; + } + } + else if (!state.isCompleted) { + try { + const result = await state.blobClient.getProperties({ abortSignal: options.abortSignal }); + const { copyStatus, copyProgress } = result; + const prevCopyProgress = state.copyProgress; + if (copyProgress) { + state.copyProgress = copyProgress; } - }); - }); + if (copyStatus === "pending" && + copyProgress !== prevCopyProgress && + typeof options.fireProgress === "function") { + // trigger in setTimeout, or swallow error? + options.fireProgress(state); + } + else if (copyStatus === "success") { + state.result = result; + state.isCompleted = true; + } + else if (copyStatus === "failed") { + state.error = new Error(`Blob copy failed with reason: "${result.copyStatusDescription || "unknown"}"`); + state.isCompleted = true; + } + } + catch (err) { + state.error = err; + state.isCompleted = true; + } + } + return makeBlobBeginCopyFromURLPollOperation(state); }; /** * Note: Intentionally using function expression over arrow function expression @@ -29922,8 +26793,8 @@ var update = function update(options) { * This affects what `this` refers to. * @hidden */ -var toString = function toString() { - return JSON.stringify({ state: this.state }, function (key, value) { +const toString = function toString() { + return JSON.stringify({ state: this.state }, (key, value) => { // remove blobClient from serialized state since a client can't be hydrated from this info. if (key === "blobClient") { return undefined; @@ -29937,10 +26808,10 @@ var toString = function toString() { */ function makeBlobBeginCopyFromURLPollOperation(state) { return { - state: tslib.__assign({}, state), - cancel: cancel, - toString: toString, - update: update + state: Object.assign({}, state), + cancel, + toString, + update }; } @@ -29955,14 +26826,14 @@ function makeBlobBeginCopyFromURLPollOperation(state) { */ function rangeToString(iRange) { if (iRange.offset < 0) { - throw new RangeError("Range.offset cannot be smaller than 0."); + throw new RangeError(`Range.offset cannot be smaller than 0.`); } if (iRange.count && iRange.count <= 0) { - throw new RangeError("Range.count must be larger than 0. Leave it undefined if you want a range from offset to the end."); + throw new RangeError(`Range.count must be larger than 0. Leave it undefined if you want a range from offset to the end.`); } return iRange.count - ? "bytes=" + iRange.offset + "-" + (iRange.offset + iRange.count - 1) - : "bytes=" + iRange.offset + "-"; + ? `bytes=${iRange.offset}-${iRange.offset + iRange.count - 1}` + : `bytes=${iRange.offset}-`; } // Copyright (c) Microsoft Corporation. @@ -29979,13 +26850,12 @@ var BatchStates; * Will stop execute left operations when one of the executed operation throws an error. * But Batch cannot cancel ongoing operations, you need to cancel them by yourself. */ -var Batch = /** @class */ (function () { +class Batch { /** * Creates an instance of Batch. * @param concurrency - */ - function Batch(concurrency) { - if (concurrency === void 0) { concurrency = 5; } + constructor(concurrency = 5) { /** * Number of active operations under execution. */ @@ -30018,69 +26888,53 @@ var Batch = /** @class */ (function () { * * @param operation - */ - Batch.prototype.addOperation = function (operation) { - var _this = this; - this.operations.push(function () { return tslib.__awaiter(_this, void 0, void 0, function () { - var error_1; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - _a.trys.push([0, 2, , 3]); - this.actives++; - return [4 /*yield*/, operation()]; - case 1: - _a.sent(); - this.actives--; - this.completed++; - this.parallelExecute(); - return [3 /*break*/, 3]; - case 2: - error_1 = _a.sent(); - this.emitter.emit("error", error_1); - return [3 /*break*/, 3]; - case 3: return [2 /*return*/]; - } - }); - }); }); - }; + addOperation(operation) { + this.operations.push(async () => { + try { + this.actives++; + await operation(); + this.actives--; + this.completed++; + this.parallelExecute(); + } + catch (error) { + this.emitter.emit("error", error); + } + }); + } /** * Start execute operations in the queue. * */ - Batch.prototype.do = function () { - return tslib.__awaiter(this, void 0, void 0, function () { - var _this = this; - return tslib.__generator(this, function (_a) { - if (this.operations.length === 0) { - return [2 /*return*/, Promise.resolve()]; - } - this.parallelExecute(); - return [2 /*return*/, new Promise(function (resolve, reject) { - _this.emitter.on("finish", resolve); - _this.emitter.on("error", function (error) { - _this.state = BatchStates.Error; - reject(error); - }); - })]; + async do() { + if (this.operations.length === 0) { + return Promise.resolve(); + } + this.parallelExecute(); + return new Promise((resolve, reject) => { + this.emitter.on("finish", resolve); + this.emitter.on("error", (error) => { + this.state = BatchStates.Error; + reject(error); }); }); - }; + } /** * Get next operation to be executed. Return null when reaching ends. * */ - Batch.prototype.nextOperation = function () { + nextOperation() { if (this.offset < this.operations.length) { return this.operations[this.offset++]; } return null; - }; + } /** * Start execute operations. One one the most important difference between * this method with do() is that do() wraps as an sync method. * */ - Batch.prototype.parallelExecute = function () { + parallelExecute() { if (this.state === BatchStates.Error) { return; } @@ -30089,7 +26943,7 @@ var Batch = /** @class */ (function () { return; } while (this.actives < this.concurrency) { - var operation = this.nextOperation(); + const operation = this.nextOperation(); if (operation) { operation(); } @@ -30097,16 +26951,14 @@ var Batch = /** @class */ (function () { return; } } - }; - return Batch; -}()); + } +} // Copyright (c) Microsoft Corporation. /** * This class generates a readable stream from the data in an array of buffers. */ -var BuffersStream = /** @class */ (function (_super) { - tslib.__extends(BuffersStream, _super); +class BuffersStream extends stream.Readable { /** * Creates an instance of BuffersStream that will emit the data * contained in the array of buffers. @@ -30114,46 +26966,44 @@ var BuffersStream = /** @class */ (function (_super) { * @param buffers - Array of buffers containing the data * @param byteLength - The total length of data contained in the buffers */ - function BuffersStream(buffers, byteLength, options) { - var _this = _super.call(this, options) || this; - _this.buffers = buffers; - _this.byteLength = byteLength; - _this.byteOffsetInCurrentBuffer = 0; - _this.bufferIndex = 0; - _this.pushedBytesLength = 0; + constructor(buffers, byteLength, options) { + super(options); + this.buffers = buffers; + this.byteLength = byteLength; + this.byteOffsetInCurrentBuffer = 0; + this.bufferIndex = 0; + this.pushedBytesLength = 0; // check byteLength is no larger than buffers[] total length - var buffersLength = 0; - for (var _i = 0, _a = _this.buffers; _i < _a.length; _i++) { - var buf = _a[_i]; + let buffersLength = 0; + for (const buf of this.buffers) { buffersLength += buf.byteLength; } - if (buffersLength < _this.byteLength) { + if (buffersLength < this.byteLength) { throw new Error("Data size shouldn't be larger than the total length of buffers."); } - return _this; } /** * Internal _read() that will be called when the stream wants to pull more data in. * * @param size - Optional. The size of data to be read */ - BuffersStream.prototype._read = function (size) { + _read(size) { if (this.pushedBytesLength >= this.byteLength) { this.push(null); } if (!size) { size = this.readableHighWaterMark; } - var outBuffers = []; - var i = 0; + const outBuffers = []; + let i = 0; while (i < size && this.pushedBytesLength < this.byteLength) { // The last buffer may be longer than the data it contains. - var remainingDataInAllBuffers = this.byteLength - this.pushedBytesLength; - var remainingCapacityInThisBuffer = this.buffers[this.bufferIndex].byteLength - this.byteOffsetInCurrentBuffer; - var remaining = Math.min(remainingCapacityInThisBuffer, remainingDataInAllBuffers); + const remainingDataInAllBuffers = this.byteLength - this.pushedBytesLength; + const remainingCapacityInThisBuffer = this.buffers[this.bufferIndex].byteLength - this.byteOffsetInCurrentBuffer; + const remaining = Math.min(remainingCapacityInThisBuffer, remainingDataInAllBuffers); if (remaining > size - i) { // chunkSize = size - i - var end = this.byteOffsetInCurrentBuffer + size - i; + const end = this.byteOffsetInCurrentBuffer + size - i; outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end)); this.pushedBytesLength += size - i; this.byteOffsetInCurrentBuffer = end; @@ -30162,7 +27012,7 @@ var BuffersStream = /** @class */ (function (_super) { } else { // chunkSize = remaining - var end = this.byteOffsetInCurrentBuffer + remaining; + const end = this.byteOffsetInCurrentBuffer + remaining; outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end)); if (remaining === remainingCapacityInThisBuffer) { // this.buffers[this.bufferIndex] used up, shift to next one @@ -30182,16 +27032,15 @@ var BuffersStream = /** @class */ (function (_super) { else if (outBuffers.length === 1) { this.push(outBuffers[0]); } - }; - return BuffersStream; -}(stream.Readable)); + } +} // Copyright (c) Microsoft Corporation. /** * maxBufferLength is max size of each buffer in the pooled buffers. */ // Can't use import as Typescript doesn't recognize "buffer". -var maxBufferLength = __webpack_require__(293).constants.MAX_LENGTH; +const maxBufferLength = __webpack_require__(293).constants.MAX_LENGTH; /** * This class provides a buffer container which conceptually has no hard size limit. * It accepts a capacity, an array of input buffers and the total length of input data. @@ -30200,8 +27049,8 @@ var maxBufferLength = __webpack_require__(293).constants.MAX_LENGTH; * Then by calling PooledBuffer.getReadableStream(), you can get a readable stream * assembled from all the data in the internal "buffer". */ -var PooledBuffer = /** @class */ (function () { - function PooledBuffer(capacity, buffers, totalLength) { +class PooledBuffer { + constructor(capacity, buffers, totalLength) { /** * Internal buffers used to keep the data. * Each buffer has a length of the maxBufferLength except last one. @@ -30210,9 +27059,9 @@ var PooledBuffer = /** @class */ (function () { this.capacity = capacity; this._size = 0; // allocate - var bufferNum = Math.ceil(capacity / maxBufferLength); - for (var i = 0; i < bufferNum; i++) { - var len = i === bufferNum - 1 ? capacity % maxBufferLength : maxBufferLength; + const bufferNum = Math.ceil(capacity / maxBufferLength); + for (let i = 0; i < bufferNum; i++) { + let len = i === bufferNum - 1 ? capacity % maxBufferLength : maxBufferLength; if (len === 0) { len = maxBufferLength; } @@ -30222,16 +27071,12 @@ var PooledBuffer = /** @class */ (function () { this.fill(buffers, totalLength); } } - Object.defineProperty(PooledBuffer.prototype, "size", { - /** - * The size of the data contained in the pooled buffers. - */ - get: function () { - return this._size; - }, - enumerable: false, - configurable: true - }); + /** + * The size of the data contained in the pooled buffers. + */ + get size() { + return this._size; + } /** * Fill the internal buffers with data in the input buffers serially * with respect to the total length and the total capacity of the internal buffers. @@ -30241,13 +27086,13 @@ var PooledBuffer = /** @class */ (function () { * @param totalLength - Total length of the data to be filled in. * */ - PooledBuffer.prototype.fill = function (buffers, totalLength) { + fill(buffers, totalLength) { this._size = Math.min(this.capacity, totalLength); - var i = 0, j = 0, targetOffset = 0, sourceOffset = 0, totalCopiedNum = 0; + let i = 0, j = 0, targetOffset = 0, sourceOffset = 0, totalCopiedNum = 0; while (totalCopiedNum < this._size) { - var source = buffers[i]; - var target = this.buffers[j]; - var copiedNum = source.copy(target, targetOffset, sourceOffset); + const source = buffers[i]; + const target = this.buffers[j]; + const copiedNum = source.copy(target, targetOffset, sourceOffset); totalCopiedNum += copiedNum; sourceOffset += copiedNum; targetOffset += copiedNum; @@ -30265,16 +27110,15 @@ var PooledBuffer = /** @class */ (function () { if (buffers.length > 0) { buffers[0] = buffers[0].slice(sourceOffset); } - }; + } /** * Get the readable stream assembled from all the data in the internal buffers. * */ - PooledBuffer.prototype.getReadableStream = function () { + getReadableStream() { return new BuffersStream(this.buffers, this.size); - }; - return PooledBuffer; -}()); + } +} // Copyright (c) Microsoft Corporation. /** @@ -30299,7 +27143,7 @@ var PooledBuffer = /** @class */ (function () { * in this situation, outgoing handlers are blocked. * Outgoing queue shouldn't be empty. */ -var BufferScheduler = /** @class */ (function () { +class BufferScheduler { /** * Creates an instance of BufferScheduler. * @@ -30312,7 +27156,7 @@ var BufferScheduler = /** @class */ (function () { * @param concurrency - Concurrency of executing outgoingHandlers (>0) * @param encoding - [Optional] Encoding of Readable stream when it's a string stream */ - function BufferScheduler(readable, bufferSize, maxBuffers, outgoingHandler, concurrency, encoding) { + constructor(readable, bufferSize, maxBuffers, outgoingHandler, concurrency, encoding) { /** * An internal event emitter. */ @@ -30358,13 +27202,13 @@ var BufferScheduler = /** @class */ (function () { */ this.outgoing = []; if (bufferSize <= 0) { - throw new RangeError("bufferSize must be larger than 0, current is " + bufferSize); + throw new RangeError(`bufferSize must be larger than 0, current is ${bufferSize}`); } if (maxBuffers <= 0) { - throw new RangeError("maxBuffers must be larger than 0, current is " + maxBuffers); + throw new RangeError(`maxBuffers must be larger than 0, current is ${maxBuffers}`); } if (concurrency <= 0) { - throw new RangeError("concurrency must be larger than 0, current is " + concurrency); + throw new RangeError(`concurrency must be larger than 0, current is ${concurrency}`); } this.bufferSize = bufferSize; this.maxBuffers = maxBuffers; @@ -30378,69 +27222,64 @@ var BufferScheduler = /** @class */ (function () { * returns error. * */ - BufferScheduler.prototype.do = function () { - return tslib.__awaiter(this, void 0, void 0, function () { - var _this = this; - return tslib.__generator(this, function (_a) { - return [2 /*return*/, new Promise(function (resolve, reject) { - _this.readable.on("data", function (data) { - data = typeof data === "string" ? Buffer.from(data, _this.encoding) : data; - _this.appendUnresolvedData(data); - if (!_this.resolveData()) { - _this.readable.pause(); - } - }); - _this.readable.on("error", function (err) { - _this.emitter.emit("error", err); - }); - _this.readable.on("end", function () { - _this.isStreamEnd = true; - _this.emitter.emit("checkEnd"); - }); - _this.emitter.on("error", function (err) { - _this.isError = true; - _this.readable.pause(); - reject(err); - }); - _this.emitter.on("checkEnd", function () { - if (_this.outgoing.length > 0) { - _this.triggerOutgoingHandlers(); - return; - } - if (_this.isStreamEnd && _this.executingOutgoingHandlers === 0) { - if (_this.unresolvedLength > 0 && _this.unresolvedLength < _this.bufferSize) { - var buffer_1 = _this.shiftBufferFromUnresolvedDataArray(); - _this.outgoingHandler(function () { return buffer_1.getReadableStream(); }, buffer_1.size, _this.offset) - .then(resolve) - .catch(reject); - } - else if (_this.unresolvedLength >= _this.bufferSize) { - return; - } - else { - resolve(); - } - } - }); - })]; + async do() { + return new Promise((resolve, reject) => { + this.readable.on("data", (data) => { + data = typeof data === "string" ? Buffer.from(data, this.encoding) : data; + this.appendUnresolvedData(data); + if (!this.resolveData()) { + this.readable.pause(); + } + }); + this.readable.on("error", (err) => { + this.emitter.emit("error", err); + }); + this.readable.on("end", () => { + this.isStreamEnd = true; + this.emitter.emit("checkEnd"); + }); + this.emitter.on("error", (err) => { + this.isError = true; + this.readable.pause(); + reject(err); + }); + this.emitter.on("checkEnd", () => { + if (this.outgoing.length > 0) { + this.triggerOutgoingHandlers(); + return; + } + if (this.isStreamEnd && this.executingOutgoingHandlers === 0) { + if (this.unresolvedLength > 0 && this.unresolvedLength < this.bufferSize) { + const buffer = this.shiftBufferFromUnresolvedDataArray(); + this.outgoingHandler(() => buffer.getReadableStream(), buffer.size, this.offset) + .then(resolve) + .catch(reject); + } + else if (this.unresolvedLength >= this.bufferSize) { + return; + } + else { + resolve(); + } + } }); }); - }; + } /** * Insert a new data into unresolved array. * * @param data - */ - BufferScheduler.prototype.appendUnresolvedData = function (data) { + appendUnresolvedData(data) { this.unresolvedDataArray.push(data); this.unresolvedLength += data.length; - }; + } /** * Try to shift a buffer with size in blockSize. The buffer returned may be less * than blockSize when data in unresolvedDataArray is less than bufferSize. * */ - BufferScheduler.prototype.shiftBufferFromUnresolvedDataArray = function (buffer) { + shiftBufferFromUnresolvedDataArray(buffer) { if (!buffer) { buffer = new PooledBuffer(this.bufferSize, this.unresolvedDataArray, this.unresolvedLength); } @@ -30449,7 +27288,7 @@ var BufferScheduler = /** @class */ (function () { } this.unresolvedLength -= buffer.size; return buffer; - }; + } /** * Resolve data in unresolvedDataArray. For every buffer with size in blockSize * shifted, it will try to get (or allocate a buffer) from incoming, and fill it, @@ -30459,9 +27298,9 @@ var BufferScheduler = /** @class */ (function () { * * @returns Return false when buffers in incoming are not enough, else true. */ - BufferScheduler.prototype.resolveData = function () { + resolveData() { while (this.unresolvedLength >= this.bufferSize) { - var buffer = void 0; + let buffer; if (this.incoming.length > 0) { buffer = this.incoming.shift(); this.shiftBufferFromUnresolvedDataArray(buffer); @@ -30480,75 +27319,55 @@ var BufferScheduler = /** @class */ (function () { this.triggerOutgoingHandlers(); } return true; - }; + } /** * Try to trigger a outgoing handler for every buffer in outgoing. Stop when * concurrency reaches. */ - BufferScheduler.prototype.triggerOutgoingHandlers = function () { - return tslib.__awaiter(this, void 0, void 0, function () { - var buffer; - return tslib.__generator(this, function (_a) { - do { - if (this.executingOutgoingHandlers >= this.concurrency) { - return [2 /*return*/]; - } - buffer = this.outgoing.shift(); - if (buffer) { - this.triggerOutgoingHandler(buffer); - } - } while (buffer); - return [2 /*return*/]; - }); - }); - }; + async triggerOutgoingHandlers() { + let buffer; + do { + if (this.executingOutgoingHandlers >= this.concurrency) { + return; + } + buffer = this.outgoing.shift(); + if (buffer) { + this.triggerOutgoingHandler(buffer); + } + } while (buffer); + } /** * Trigger a outgoing handler for a buffer shifted from outgoing. * * @param buffer - */ - BufferScheduler.prototype.triggerOutgoingHandler = function (buffer) { - return tslib.__awaiter(this, void 0, void 0, function () { - var bufferLength, err_1; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - bufferLength = buffer.size; - this.executingOutgoingHandlers++; - this.offset += bufferLength; - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - return [4 /*yield*/, this.outgoingHandler(function () { return buffer.getReadableStream(); }, bufferLength, this.offset - bufferLength)]; - case 2: - _a.sent(); - return [3 /*break*/, 4]; - case 3: - err_1 = _a.sent(); - this.emitter.emit("error", err_1); - return [2 /*return*/]; - case 4: - this.executingOutgoingHandlers--; - this.reuseBuffer(buffer); - this.emitter.emit("checkEnd"); - return [2 /*return*/]; - } - }); - }); - }; + async triggerOutgoingHandler(buffer) { + const bufferLength = buffer.size; + this.executingOutgoingHandlers++; + this.offset += bufferLength; + try { + await this.outgoingHandler(() => buffer.getReadableStream(), bufferLength, this.offset - bufferLength); + } + catch (err) { + this.emitter.emit("error", err); + return; + } + this.executingOutgoingHandlers--; + this.reuseBuffer(buffer); + this.emitter.emit("checkEnd"); + } /** * Return buffer used by outgoing handler into incoming. * * @param buffer - */ - BufferScheduler.prototype.reuseBuffer = function (buffer) { + reuseBuffer(buffer) { this.incoming.push(buffer); if (!this.isError && this.resolveData() && !this.isStreamEnd) { this.readable.resume(); } - }; - return BufferScheduler; -}()); + } +} // Copyright (c) Microsoft Corporation. /** @@ -30560,39 +27379,34 @@ var BufferScheduler = /** @class */ (function () { * @param end - To which position in the buffer to be filled, exclusive * @param encoding - Encoding of the Readable stream */ -function streamToBuffer(stream, buffer, offset, end, encoding) { - return tslib.__awaiter(this, void 0, void 0, function () { - var pos, count; - return tslib.__generator(this, function (_a) { - pos = 0; - count = end - offset; - return [2 /*return*/, new Promise(function (resolve, reject) { - stream.on("readable", function () { - if (pos >= count) { - resolve(); - return; - } - var chunk = stream.read(); - if (!chunk) { - return; - } - if (typeof chunk === "string") { - chunk = Buffer.from(chunk, encoding); - } - // How much data needed in this chunk - var chunkLength = pos + chunk.length > count ? count - pos : chunk.length; - buffer.fill(chunk.slice(0, chunkLength), offset + pos, offset + pos + chunkLength); - pos += chunkLength; - }); - stream.on("end", function () { - if (pos < count) { - reject(new Error("Stream drains before getting enough data needed. Data read: " + pos + ", data need: " + count)); - } - resolve(); - }); - stream.on("error", reject); - })]; +async function streamToBuffer(stream, buffer, offset, end, encoding) { + let pos = 0; // Position in stream + const count = end - offset; // Total amount of data needed in stream + return new Promise((resolve, reject) => { + stream.on("readable", () => { + if (pos >= count) { + resolve(); + return; + } + let chunk = stream.read(); + if (!chunk) { + return; + } + if (typeof chunk === "string") { + chunk = Buffer.from(chunk, encoding); + } + // How much data needed in this chunk + const chunkLength = pos + chunk.length > count ? count - pos : chunk.length; + buffer.fill(chunk.slice(0, chunkLength), offset + pos, offset + pos + chunkLength); + pos += chunkLength; }); + stream.on("end", () => { + if (pos < count) { + reject(new Error(`Stream drains before getting enough data needed. Data read: ${pos}, data need: ${count}`)); + } + resolve(); + }); + stream.on("error", reject); }); } /** @@ -30604,34 +27418,29 @@ function streamToBuffer(stream, buffer, offset, end, encoding) { * @returns with the count of bytes read. * @throws `RangeError` If buffer size is not big enough. */ -function streamToBuffer2(stream, buffer, encoding) { - return tslib.__awaiter(this, void 0, void 0, function () { - var pos, bufferSize; - return tslib.__generator(this, function (_a) { - pos = 0; - bufferSize = buffer.length; - return [2 /*return*/, new Promise(function (resolve, reject) { - stream.on("readable", function () { - var chunk = stream.read(); - if (!chunk) { - return; - } - if (typeof chunk === "string") { - chunk = Buffer.from(chunk, encoding); - } - if (pos + chunk.length > bufferSize) { - reject(new Error("Stream exceeds buffer size. Buffer size: " + bufferSize)); - return; - } - buffer.fill(chunk, pos, pos + chunk.length); - pos += chunk.length; - }); - stream.on("end", function () { - resolve(pos); - }); - stream.on("error", reject); - })]; +async function streamToBuffer2(stream, buffer, encoding) { + let pos = 0; // Position in stream + const bufferSize = buffer.length; + return new Promise((resolve, reject) => { + stream.on("readable", () => { + let chunk = stream.read(); + if (!chunk) { + return; + } + if (typeof chunk === "string") { + chunk = Buffer.from(chunk, encoding); + } + if (pos + chunk.length > bufferSize) { + reject(new Error(`Stream exceeds buffer size. Buffer size: ${bufferSize}`)); + return; + } + buffer.fill(chunk, pos, pos + chunk.length); + pos += chunk.length; }); + stream.on("end", () => { + resolve(pos); + }); + stream.on("error", reject); }); } /** @@ -30642,21 +27451,17 @@ function streamToBuffer2(stream, buffer, encoding) { * @param rs - The read stream. * @param file - Destination file path. */ -function readStreamToLocalFile(rs, file) { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - return [2 /*return*/, new Promise(function (resolve, reject) { - var ws = fs.createWriteStream(file); - rs.on("error", function (err) { - reject(err); - }); - ws.on("error", function (err) { - reject(err); - }); - ws.on("close", resolve); - rs.pipe(ws); - })]; +async function readStreamToLocalFile(rs, file) { + return new Promise((resolve, reject) => { + const ws = fs.createWriteStream(file); + rs.on("error", (err) => { + reject(err); }); + ws.on("error", (err) => { + reject(err); + }); + ws.on("close", resolve); + rs.pipe(ws); }); } /** @@ -30664,22 +27469,22 @@ function readStreamToLocalFile(rs, file) { * * Promisified version of fs.stat(). */ -var fsStat = util.promisify(fs.stat); -var fsCreateReadStream = fs.createReadStream; +const fsStat = util.promisify(fs.stat); +const fsCreateReadStream = fs.createReadStream; /** * A BlobClient represents a URL to an Azure Storage blob; the blob may be a block blob, * append blob, or page blob. */ -var BlobClient = /** @class */ (function (_super) { - tslib.__extends(BlobClient, _super); - function BlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { - var _a; - var _this = this; +class BlobClient extends StorageClient { + constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { options = options || {}; - var pipeline; - var url; - if (credentialOrPipelineOrContainerName instanceof Pipeline) { + let pipeline; + let url; + if (isPipelineLike(credentialOrPipelineOrContainerName)) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; @@ -30704,12 +27509,12 @@ var BlobClient = /** @class */ (function (_super) { blobNameOrOptions && typeof blobNameOrOptions === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) - var containerName = credentialOrPipelineOrContainerName; - var blobName = blobNameOrOptions; - var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + const containerName = credentialOrPipelineOrContainerName; + const blobName = blobNameOrOptions; + const extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + const 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); @@ -30729,33 +27534,27 @@ var BlobClient = /** @class */ (function (_super) { 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; + super(url, pipeline); + ({ + blobName: this._name, + containerName: this._containerName + } = this.getBlobAndContainerNamesFromUrl()); + this.blobContext = new Blob$1(this.storageClientContext); + this._snapshot = getURLParameter(this.url, URLConstants.Parameters.SNAPSHOT); + this._versionId = getURLParameter(this.url, URLConstants.Parameters.VERSIONID); + } + /** + * The name of the blob. + */ + get name() { + return this._name; + } + /** + * The name of the storage container the blob is associated with. + */ + get containerName() { + return this._containerName; } - 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. @@ -30763,9 +27562,9 @@ var BlobClient = /** @class */ (function (_super) { * @param snapshot - The snapshot timestamp. * @returns A new BlobClient object identical to the source but with the specified snapshot timestamp */ - BlobClient.prototype.withSnapshot = function (snapshot) { + withSnapshot(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. @@ -30773,30 +27572,30 @@ var BlobClient = /** @class */ (function (_super) { * @param versionId - The versionId. * @returns A new BlobClient object pointing to the version of this blob. */ - BlobClient.prototype.withVersion = function (versionId) { + withVersion(versionId) { return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.VERSIONID, versionId.length === 0 ? undefined : versionId), this.pipeline); - }; + } /** * Creates a AppendBlobClient object. * */ - BlobClient.prototype.getAppendBlobClient = function () { + getAppendBlobClient() { return new AppendBlobClient(this.url, this.pipeline); - }; + } /** * Creates a BlockBlobClient object. * */ - BlobClient.prototype.getBlockBlobClient = function () { + getBlockBlobClient() { return new BlockBlobClient(this.url, this.pipeline); - }; + } /** * Creates a PageBlobClient object. * */ - BlobClient.prototype.getPageBlobClient = function () { + getPageBlobClient() { 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. @@ -30856,98 +27655,77 @@ var BlobClient = /** @class */ (function (_super) { * } * ``` */ - BlobClient.prototype.download = function (offset, count, options) { + async download(offset = 0, 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, updatedOptions, 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), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.download(tslib.__assign({ 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 }), requestOptions: { - onDownloadProgress: coreHttp.isNode ? undefined : options.onProgress // for Node.js, progress is reported by RetriableReadableStream - }, range: offset === 0 && !count ? undefined : rangeToString({ offset: offset, count: count }), rangeGetContentMD5: options.rangeGetContentMD5, rangeGetContentCRC64: options.rangeGetContentCrc64, snapshot: options.snapshot, cpkInfo: options.customerProvidedKey }, convertTracingToRequestOptionsBase(updatedOptions)))]; - 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: coreTracing.SpanStatusCode.ERROR, - message: e_1.message - }); - throw e_1; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + options.conditions = options.conditions || {}; + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + const { span, updatedOptions } = createSpan("BlobClient-download", options); + try { + const res = await this.blobContext.download(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: { + onDownloadProgress: coreHttp.isNode ? undefined : options.onProgress // for Node.js, progress is reported by RetriableReadableStream + }, range: offset === 0 && !count ? undefined : rangeToString({ offset, count }), rangeGetContentMD5: options.rangeGetContentMD5, rangeGetContentCRC64: options.rangeGetContentCrc64, snapshot: options.snapshot, cpkInfo: options.customerProvidedKey }, convertTracingToRequestOptionsBase(updatedOptions))); + const wrappedRes = Object.assign(Object.assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) }); + // Return browser response immediately + if (false) {} + // 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.contentLength === undefined) { + throw new RangeError(`File download response doesn't contain valid content length header`); + } + if (!res.etag) { + throw new RangeError(`File download response doesn't contain valid etag header`); + } + return new BlobDownloadResponse(wrappedRes, async (start) => { + var _a; + const updatedDownloadOptions = { + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ifMatch: options.conditions.ifMatch || res.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.contentLength - start, + offset: start + }), + rangeGetContentMD5: options.rangeGetContentMD5, + rangeGetContentCRC64: options.rangeGetContentCrc64, + snapshot: options.snapshot, + cpkInfo: options.customerProvidedKey + }; + // Debug purpose only + // console.log( + // `Read from internal stream, range: ${ + // updatedOptions.range + // }, options: ${JSON.stringify(updatedOptions)}` + // ); + return (await this.blobContext.download(Object.assign({ abortSignal: options.abortSignal }, updatedDownloadOptions))).readableStreamBody; + }, offset, res.contentLength, { + maxRetryRequests: options.maxRetryRequests, + onProgress: options.onProgress }); - }); - }; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message + }); + throw e; + } + finally { + span.end(); + } + } /** * Returns true if the Azure blob resource represented by this client exists; false otherwise. * @@ -30957,49 +27735,36 @@ var BlobClient = /** @class */ (function (_super) { * * @param options - options to Exists operation. */ - BlobClient.prototype.exists = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_2; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobClient-exists", options), span = _a.span, updatedOptions = _a.updatedOptions; - _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: updatedOptions.tracingOptions - })]; - case 2: - _b.sent(); - return [2 /*return*/, true]; - case 3: - e_2 = _b.sent(); - if (e_2.statusCode === 404) { - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: "Expected exception when checking blob existence" - }); - return [2 /*return*/, false]; - } - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_2.message - }); - throw e_2; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async exists(options = {}) { + const { span, updatedOptions } = createSpan("BlobClient-exists", options); + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + await this.getProperties({ + abortSignal: options.abortSignal, + customerProvidedKey: options.customerProvidedKey, + conditions: options.conditions, + tracingOptions: updatedOptions.tracingOptions }); - }); - }; + return true; + } + catch (e) { + if (e.statusCode === 404) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: "Expected exception when checking blob existence" + }); + return false; + } + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message + }); + throw e; + } + finally { + span.end(); + } + } /** * Returns all user-defined metadata, standard HTTP properties, and system properties * for the blob. It does not return the content of the blob. @@ -31012,39 +27777,26 @@ var BlobClient = /** @class */ (function (_super) { * * @param options - Optional options to Get Properties operation. */ - BlobClient.prototype.getProperties = function (options) { + async getProperties(options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, res, e_3; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-getProperties", options), span = _b.span, updatedOptions = _b.updatedOptions; - _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(tslib.__assign({ 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 }, convertTracingToRequestOptionsBase(updatedOptions)))]; - 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: coreTracing.SpanStatusCode.ERROR, - message: e_3.message - }); - throw e_3; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobClient-getProperties", options); + try { + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + const res = await this.blobContext.getProperties(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey }, convertTracingToRequestOptionsBase(updatedOptions))); + return Object.assign(Object.assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) }); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * 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 @@ -31054,36 +27806,24 @@ var BlobClient = /** @class */ (function (_super) { * * @param options - Optional options to Blob Delete operation. */ - BlobClient.prototype.delete = function (options) { + async delete(options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_4; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-delete", options), span = _b.span, updatedOptions = _b.updatedOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.delete(tslib.__assign({ abortSignal: options.abortSignal, deleteSnapshots: options.deleteSnapshots, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_4 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_4.message - }); - throw e_4; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobClient-delete", options); + options.conditions = options.conditions || {}; + try { + return await this.blobContext.delete(Object.assign({ abortSignal: options.abortSignal, deleteSnapshots: options.deleteSnapshots, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Marks the specified blob or snapshot for deletion if it exists. The blob is later deleted * during garbage collection. Note that in order to delete a blob, you must delete @@ -31093,45 +27833,32 @@ var BlobClient = /** @class */ (function (_super) { * * @param options - Optional options to Blob Delete operation. */ - BlobClient.prototype.deleteIfExists = function (options) { + async deleteIfExists(options = {}) { var _a, _b; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _c, span, updatedOptions, res, e_5; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _c = createSpan("BlobClient-deleteIfExists", options), span = _c.span, updatedOptions = _c.updatedOptions; - _d.label = 1; - case 1: - _d.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.delete(updatedOptions)]; - case 2: - res = _d.sent(); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable - })]; - case 3: - e_5 = _d.sent(); - if (((_a = e_5.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobNotFound") { - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: "Expected exception when deleting a blob or snapshot only if it exists." - }); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_5.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_5.response })]; - } - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_5.message - }); - throw e_5; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobClient-deleteIfExists", options); + try { + const res = await this.delete(updatedOptions); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable + }); + } + catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobNotFound") { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: "Expected exception when deleting a blob or snapshot only if it exists." + }); + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Restores the contents and metadata of soft deleted blob and any associated * soft deleted snapshots. Undelete Blob is supported only on version 2017-07-29 @@ -31140,34 +27867,22 @@ var BlobClient = /** @class */ (function (_super) { * * @param options - Optional options to Blob Undelete operation. */ - BlobClient.prototype.undelete = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_6; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobClient-undelete", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.undelete(tslib.__assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_6 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_6.message - }); - throw e_6; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async undelete(options = {}) { + const { span, updatedOptions } = createSpan("BlobClient-undelete", options); + try { + return await this.blobContext.undelete(Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Sets system properties on the blob. * @@ -31178,39 +27893,30 @@ var BlobClient = /** @class */ (function (_super) { * @param blobHTTPHeaders - If no value provided, or no value provided for * the specified blob HTTP headers, these blob HTTP * headers without a value will be cleared. + * A common header to set is `blobContentType` + * enabling the browser to provide functionality + * based on file type. * @param options - Optional options to Blob Set HTTP Headers operation. */ - BlobClient.prototype.setHTTPHeaders = function (blobHTTPHeaders, options) { + async setHTTPHeaders(blobHTTPHeaders, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_7; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-setHTTPHeaders", options), span = _b.span, updatedOptions = _b.updatedOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blobContext.setHttpHeaders(tslib.__assign({ abortSignal: options.abortSignal, blobHttpHeaders: blobHTTPHeaders, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_7 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_7.message - }); - throw e_7; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobClient-setHTTPHeaders", options); + options.conditions = options.conditions || {}; + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.blobContext.setHttpHeaders(Object.assign({ abortSignal: options.abortSignal, blobHttpHeaders: blobHTTPHeaders, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Sets user-defined metadata for the specified blob as one or more name-value pairs. * @@ -31222,37 +27928,25 @@ var BlobClient = /** @class */ (function (_super) { * If no value provided the existing metadata will be removed. * @param options - Optional options to Set Metadata operation. */ - BlobClient.prototype.setMetadata = function (metadata, options) { + async setMetadata(metadata, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_8; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-setMetadata", options), span = _b.span, updatedOptions = _b.updatedOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blobContext.setMetadata(tslib.__assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata: metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_8 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_8.message - }); - throw e_8; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobClient-setMetadata", options); + options.conditions = options.conditions || {}; + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.blobContext.setMetadata(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Sets tags on the underlying blob. * A blob can have up to 10 tags. Tag keys must be between 1 and 128 characters. Tag values must be between 0 and 256 characters. @@ -31262,118 +27956,81 @@ var BlobClient = /** @class */ (function (_super) { * @param tags - * @param options - */ - BlobClient.prototype.setTags = function (tags, options) { + async setTags(tags, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_9; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-setTags", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.setTags(tslib.__assign(tslib.__assign({ 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 }) }, convertTracingToRequestOptionsBase(updatedOptions)), { tags: toBlobTags(tags) }))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_9 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_9.message - }); - throw e_9; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobClient-setTags", options); + try { + return await this.blobContext.setTags(Object.assign(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)), { tags: toBlobTags(tags) })); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Gets the tags associated with the underlying blob. * * @param options - */ - BlobClient.prototype.getTags = function (options) { + async getTags(options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, response, wrappedResponse, e_10; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-getTags", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.getTags(tslib.__assign({ 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 }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: - response = _c.sent(); - wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, tags: toTags({ blobTagSet: response.blobTagSet }) || {} }); - return [2 /*return*/, wrappedResponse]; - case 3: - e_10 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_10.message - }); - throw e_10; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobClient-getTags", options); + try { + const response = await this.blobContext.getTags(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, tags: toTags({ blobTagSet: response.blobTagSet }) || {} }); + return wrappedResponse; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Get a {@link BlobLeaseClient} that manages leases on the blob. * * @param proposeLeaseId - Initial proposed lease Id. * @returns A new BlobLeaseClient object for managing leases on the blob. */ - BlobClient.prototype.getBlobLeaseClient = function (proposeLeaseId) { + getBlobLeaseClient(proposeLeaseId) { return new BlobLeaseClient(this, proposeLeaseId); - }; + } /** * Creates a read-only snapshot of a blob. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/snapshot-blob * * @param options - Optional options to the Blob Create Snapshot operation. */ - BlobClient.prototype.createSnapshot = function (options) { + async createSnapshot(options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_11; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-createSnapshot", options), span = _b.span, updatedOptions = _b.updatedOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blobContext.createSnapshot(tslib.__assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_11 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_11.message - }); - throw e_11; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobClient-createSnapshot", options); + options.conditions = options.conditions || {}; + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.blobContext.createSnapshot(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Asynchronously copies a blob to a destination within the storage account. * This method returns a long running operation poller that allows you to wait @@ -31446,57 +28103,25 @@ var BlobClient = /** @class */ (function (_super) { * @param copySource - url to the source Azure Blob/File. * @param options - Optional options to the Blob Start Copy From URL operation. */ - BlobClient.prototype.beginCopyFromURL = function (copySource, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var client, poller; - var _this = this; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - client = { - abortCopyFromURL: function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return _this.abortCopyFromURL.apply(_this, args); - }, - getProperties: function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return _this.getProperties.apply(_this, args); - }, - startCopyFromURL: function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return _this.startCopyFromURL.apply(_this, args); - } - }; - poller = new BlobBeginCopyFromUrlPoller({ - blobClient: client, - copySource: copySource, - intervalInMs: options.intervalInMs, - onProgress: options.onProgress, - resumeFrom: options.resumeFrom, - startCopyFromURLOptions: options - }); - // Trigger the startCopyFromURL call by calling poll. - // Any errors from this method should be surfaced to the user. - return [4 /*yield*/, poller.poll()]; - case 1: - // Trigger the startCopyFromURL call by calling poll. - // Any errors from this method should be surfaced to the user. - _a.sent(); - return [2 /*return*/, poller]; - } - }); + async beginCopyFromURL(copySource, options = {}) { + const client = { + abortCopyFromURL: (...args) => this.abortCopyFromURL(...args), + getProperties: (...args) => this.getProperties(...args), + startCopyFromURL: (...args) => this.startCopyFromURL(...args) + }; + const poller = new BlobBeginCopyFromUrlPoller({ + blobClient: client, + copySource, + intervalInMs: options.intervalInMs, + onProgress: options.onProgress, + resumeFrom: options.resumeFrom, + startCopyFromURLOptions: options }); - }; + // Trigger the startCopyFromURL call by calling poll. + // Any errors from this method should be surfaced to the user. + await poller.poll(); + return poller; + } /** * Aborts a pending asynchronous Copy Blob operation, and leaves a destination blob with zero * length and full metadata. Version 2012-02-12 and newer. @@ -31505,34 +28130,22 @@ var BlobClient = /** @class */ (function (_super) { * @param copyId - Id of the Copy From URL operation. * @param options - Optional options to the Blob Abort Copy From URL operation. */ - BlobClient.prototype.abortCopyFromURL = function (copyId, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_12; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobClient-abortCopyFromURL", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.abortCopyFromURL(copyId, tslib.__assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_12 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_12.message - }); - throw e_12; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async abortCopyFromURL(copyId, options = {}) { + const { span, updatedOptions } = createSpan("BlobClient-abortCopyFromURL", options); + try { + return await this.blobContext.abortCopyFromURL(copyId, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * The synchronous Copy From URL operation copies a blob or an internet resource to a new blob. It will not * return a response until the copy is complete. @@ -31541,42 +28154,30 @@ var BlobClient = /** @class */ (function (_super) { * @param copySource - The source URL to copy from, Shared Access Signature(SAS) maybe needed for authentication * @param options - */ - BlobClient.prototype.syncCopyFromURL = function (copySource, options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_13; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-syncCopyFromURL", options), span = _b.span, updatedOptions = _b.updatedOptions; - options.conditions = options.conditions || {}; - options.sourceConditions = options.sourceConditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.copyFromURL(copySource, tslib.__assign({ abortSignal: options.abortSignal, metadata: options.metadata, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { - sourceIfMatch: options.sourceConditions.ifMatch, - sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, - sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, - sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince - }, sourceContentMD5: options.sourceContentMD5, blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_13 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_13.message - }); - throw e_13; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async syncCopyFromURL(copySource, options = {}) { + var _a, _b, _c; + const { span, updatedOptions } = createSpan("BlobClient-syncCopyFromURL", options); + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + try { + return await this.blobContext.copyFromURL(copySource, Object.assign({ abortSignal: options.abortSignal, metadata: options.metadata, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince + }, sourceContentMD5: options.sourceContentMD5, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), blobTagsString: toBlobTagsString(options.tags), immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, legalHold: options.legalHold }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Sets the tier on a blob. The operation is allowed on a page blob in a premium * storage account and on a block blob in a blob storage account (locally redundant @@ -31588,159 +28189,119 @@ var BlobClient = /** @class */ (function (_super) { * @param tier - The tier to be set on the blob. Valid values are Hot, Cool, or Archive. * @param options - Optional options to the Blob Set Tier operation. */ - BlobClient.prototype.setAccessTier = function (tier, options) { + async setAccessTier(tier, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_14; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-setAccessTier", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.setTier(toAccessTier(tier), tslib.__assign({ 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 }), rehydratePriority: options.rehydratePriority }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_14 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_14.message - }); - throw e_14; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobClient-setAccessTier", options); + try { + return await this.blobContext.setTier(toAccessTier(tier), Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), rehydratePriority: options.rehydratePriority }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; - BlobClient.prototype.downloadToBuffer = function (param1, param2, param3, param4) { - if (param4 === void 0) { param4 = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var buffer, offset, count, options, _a, span, updatedOptions, response, transferProgress_1, batch, _loop_1, off, e_15; - var _this = this; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - offset = 0; - count = 0; - options = param4; - if (param1 instanceof Buffer) { - buffer = param1; - offset = param2 || 0; - count = typeof param3 === "number" ? param3 : 0; - } - else { - offset = typeof param1 === "number" ? param1 : 0; - count = typeof param2 === "number" ? param2 : 0; - options = param3 || {}; - } - _a = createSpan("BlobClient-downloadToBuffer", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 5, 6, 7]); - if (!options.blockSize) { - options.blockSize = 0; - } - if (options.blockSize < 0) { - throw new RangeError("blockSize option must be >= 0"); - } - if (options.blockSize === 0) { - options.blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; - } - if (offset < 0) { - throw new RangeError("offset option must be >= 0"); - } - if (count && count <= 0) { - throw new RangeError("count option must be greater than 0"); - } - if (!options.conditions) { - options.conditions = {}; - } - if (!!count) return [3 /*break*/, 3]; - return [4 /*yield*/, this.getProperties(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) }))]; - case 2: - response = _b.sent(); - count = response.contentLength - offset; - if (count < 0) { - throw new RangeError("offset " + offset + " shouldn't be larger than blob size " + response.contentLength); - } - _b.label = 3; - case 3: - // Allocate the buffer of size = count if the buffer is not provided - if (!buffer) { - try { - buffer = Buffer.alloc(count); - } - catch (error) { - throw new Error("Unable to allocate the buffer of size: " + count + "(in bytes). Please try passing your own buffer to the \"downloadToBuffer\" method or try using other methods like \"download\" or \"downloadToFile\".\t " + error.message); - } - } - if (buffer.length < count) { - throw new RangeError("The buffer's size should be equal to or larger than the request count of bytes: " + count); - } - transferProgress_1 = 0; - batch = new Batch(options.concurrency); - _loop_1 = function (off) { - batch.addOperation(function () { return tslib.__awaiter(_this, void 0, void 0, function () { - var chunkEnd, response, stream; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - chunkEnd = offset + count; - if (off + options.blockSize < chunkEnd) { - chunkEnd = off + options.blockSize; - } - return [4 /*yield*/, this.download(off, chunkEnd - off, { - abortSignal: options.abortSignal, - conditions: options.conditions, - maxRetryRequests: options.maxRetryRequestsPerBlock, - customerProvidedKey: options.customerProvidedKey, - tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) - })]; - case 1: - response = _a.sent(); - stream = response.readableStreamBody; - return [4 /*yield*/, streamToBuffer(stream, buffer, off - offset, chunkEnd - offset)]; - case 2: - _a.sent(); - // Update progress after block is downloaded, in case of block trying - // Could provide finer grained progress updating inside HTTP requests, - // only if convenience layer download try is enabled - transferProgress_1 += chunkEnd - off; - if (options.onProgress) { - options.onProgress({ loadedBytes: transferProgress_1 }); - } - return [2 /*return*/]; - } - }); - }); }); - }; - for (off = offset; off < offset + count; off = off + options.blockSize) { - _loop_1(off); - } - return [4 /*yield*/, batch.do()]; - case 4: - _b.sent(); - return [2 /*return*/, buffer]; - case 5: - e_15 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_15.message - }); - throw e_15; - case 6: - span.end(); - return [7 /*endfinally*/]; - case 7: return [2 /*return*/]; + throw e; + } + finally { + span.end(); + } + } + async downloadToBuffer(param1, param2, param3, param4 = {}) { + let buffer; + let offset = 0; + let count = 0; + let options = param4; + if (param1 instanceof Buffer) { + buffer = param1; + offset = param2 || 0; + count = typeof param3 === "number" ? param3 : 0; + } + else { + offset = typeof param1 === "number" ? param1 : 0; + count = typeof param2 === "number" ? param2 : 0; + options = param3 || {}; + } + const { span, updatedOptions } = createSpan("BlobClient-downloadToBuffer", options); + try { + if (!options.blockSize) { + options.blockSize = 0; + } + if (options.blockSize < 0) { + throw new RangeError("blockSize option must be >= 0"); + } + if (options.blockSize === 0) { + options.blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; + } + if (offset < 0) { + throw new RangeError("offset option must be >= 0"); + } + if (count && count <= 0) { + throw new RangeError("count option must be greater than 0"); + } + if (!options.conditions) { + options.conditions = {}; + } + // Customer doesn't specify length, get it + if (!count) { + const response = await this.getProperties(Object.assign(Object.assign({}, options), { tracingOptions: Object.assign(Object.assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) })); + count = response.contentLength - offset; + if (count < 0) { + throw new RangeError(`offset ${offset} shouldn't be larger than blob size ${response.contentLength}`); } + } + // Allocate the buffer of size = count if the buffer is not provided + if (!buffer) { + try { + buffer = Buffer.alloc(count); + } + catch (error) { + throw new Error(`Unable to allocate the buffer of size: ${count}(in bytes). Please try passing your own buffer to the "downloadToBuffer" method or try using other methods like "download" or "downloadToFile".\t ${error.message}`); + } + } + if (buffer.length < count) { + throw new RangeError(`The buffer's size should be equal to or larger than the request count of bytes: ${count}`); + } + let transferProgress = 0; + const batch = new Batch(options.concurrency); + for (let off = offset; off < offset + count; off = off + options.blockSize) { + batch.addOperation(async () => { + // Exclusive chunk end position + let chunkEnd = offset + count; + if (off + options.blockSize < chunkEnd) { + chunkEnd = off + options.blockSize; + } + const response = await this.download(off, chunkEnd - off, { + abortSignal: options.abortSignal, + conditions: options.conditions, + maxRetryRequests: options.maxRetryRequestsPerBlock, + customerProvidedKey: options.customerProvidedKey, + tracingOptions: Object.assign(Object.assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) + }); + const stream = response.readableStreamBody; + await streamToBuffer(stream, buffer, off - offset, chunkEnd - offset); + // Update progress after block is downloaded, in case of block trying + // Could provide finer grained progress updating inside HTTP requests, + // only if convenience layer download try is enabled + transferProgress += chunkEnd - off; + if (options.onProgress) { + options.onProgress({ loadedBytes: transferProgress }); + } + }); + } + await batch.do(); + return buffer; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -31757,48 +28318,31 @@ var BlobClient = /** @class */ (function (_super) { * content is already read and written into a local file * at the specified path. */ - BlobClient.prototype.downloadToFile = function (filePath, offset, count, options) { - if (offset === void 0) { offset = 0; } - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, response, e_16; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobClient-downloadToFile", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 5, 6, 7]); - return [4 /*yield*/, this.download(offset, count, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) }))]; - case 2: - response = _b.sent(); - if (!response.readableStreamBody) return [3 /*break*/, 4]; - return [4 /*yield*/, readStreamToLocalFile(response.readableStreamBody, filePath)]; - case 3: - _b.sent(); - _b.label = 4; - case 4: - // The stream is no longer accessible so setting it to undefined. - response.blobDownloadStream = undefined; - return [2 /*return*/, response]; - case 5: - e_16 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_16.message - }); - throw e_16; - case 6: - span.end(); - return [7 /*endfinally*/]; - case 7: return [2 /*return*/]; - } + async downloadToFile(filePath, offset = 0, count, options = {}) { + const { span, updatedOptions } = createSpan("BlobClient-downloadToFile", options); + try { + const response = await this.download(offset, count, Object.assign(Object.assign({}, options), { tracingOptions: Object.assign(Object.assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) })); + if (response.readableStreamBody) { + await readStreamToLocalFile(response.readableStreamBody, filePath); + } + // The stream is no longer accessible so setting it to undefined. + response.blobDownloadStream = undefined; + return response; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; - BlobClient.prototype.getBlobAndContainerNamesFromUrl = function () { - var containerName; - var blobName; + throw e; + } + finally { + span.end(); + } + } + getBlobAndContainerNamesFromUrl() { + let containerName; + let blobName; try { // URL may look like the following // "https://myaccount.blob.core.windows.net/mycontainer/blob?sasString"; @@ -31807,11 +28351,11 @@ var BlobClient = /** @class */ (function (_super) { // "https://myaccount.blob.core.windows.net/mycontainer/blob/a.txt"; // IPv4/IPv6 address hosts, Endpoints - `http://127.0.0.1:10000/devstoreaccount1/containername/blob` // http://localhost:10001/devstoreaccount1/containername/blob - var parsedUrl = coreHttp.URLBuilder.parse(this.url); + const parsedUrl = coreHttp.URLBuilder.parse(this.url); if (parsedUrl.getHost().split(".")[1] === "blob") { // "https://myaccount.blob.core.windows.net/containername/blob". // .getPath() -> /containername/blob - var pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); + const pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); containerName = pathComponents[1]; blobName = pathComponents[3]; } @@ -31819,14 +28363,14 @@ var BlobClient = /** @class */ (function (_super) { // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/containername/blob // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/containername/blob // .getPath() -> /devstoreaccount1/containername/blob - var pathComponents = parsedUrl.getPath().match("/([^/]*)/([^/]*)(/(.*))?"); + const pathComponents = parsedUrl.getPath().match("/([^/]*)/([^/]*)(/(.*))?"); containerName = pathComponents[2]; blobName = pathComponents[4]; } else { // "https://customdomain.com/containername/blob". // .getPath() -> /containername/blob - var pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); + const pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); containerName = pathComponents[1]; blobName = pathComponents[3]; } @@ -31839,12 +28383,12 @@ var BlobClient = /** @class */ (function (_super) { if (!containerName) { throw new Error("Provided containerName is invalid."); } - return { blobName: blobName, containerName: containerName }; + return { blobName, containerName }; } catch (error) { throw new Error("Unable to extract blobName and containerName with provided information."); } - }; + } /** * Asynchronously copies a blob to a destination within the storage account. * In version 2012-02-12 and later, the source for a Copy Blob operation can be @@ -31858,43 +28402,31 @@ var BlobClient = /** @class */ (function (_super) { * @param copySource - url to the source Azure Blob/File. * @param options - Optional options to the Blob Start Copy From URL operation. */ - BlobClient.prototype.startCopyFromURL = function (copySource, options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_17; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-startCopyFromURL", options), span = _b.span, updatedOptions = _b.updatedOptions; - options.conditions = options.conditions || {}; - options.sourceConditions = options.sourceConditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.startCopyFromURL(copySource, tslib.__assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { - sourceIfMatch: options.sourceConditions.ifMatch, - sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, - sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, - sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince, - sourceIfTags: options.sourceConditions.tagConditions - }, rehydratePriority: options.rehydratePriority, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), sealBlob: options.sealBlob }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_17 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_17.message - }); - throw e_17; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async startCopyFromURL(copySource, options = {}) { + var _a, _b, _c; + const { span, updatedOptions } = createSpan("BlobClient-startCopyFromURL", options); + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + try { + return await this.blobContext.startCopyFromURL(copySource, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince, + sourceIfTags: options.sourceConditions.tagConditions + }, immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, legalHold: options.legalHold, rehydratePriority: options.rehydratePriority, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), sealBlob: options.sealBlob }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Only available for BlobClient constructed with a shared key credential. * @@ -31906,31 +28438,93 @@ var BlobClient = /** @class */ (function (_super) { * @param options - Optional parameters. * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ - BlobClient.prototype.generateSasUrl = function (options) { - var _this = this; - return new Promise(function (resolve) { - if (!(_this.credential instanceof StorageSharedKeyCredential)) { + generateSasUrl(options) { + return new Promise((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)); + const sas = generateBlobSASQueryParameters(Object.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)); + } + /** + * Delete the immutablility policy on the blob. + * + * @param options - Optional options to delete immutability policy on the blob. + */ + async deleteImmutabilityPolicy(options) { + const { span, updatedOptions } = createSpan("BlobClient-deleteImmutabilityPolicy", options); + try { + return await this.blobContext.deleteImmutabilityPolicy(Object.assign({ abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message + }); + throw e; + } + finally { + span.end(); + } + } + /** + * Set immutablility policy on the blob. + * + * @param options - Optional options to set immutability policy on the blob. + */ + async setImmutabilityPolicy(immutabilityPolicy, options) { + const { span, updatedOptions } = createSpan("BlobClient-setImmutabilityPolicy", options); + try { + return await this.blobContext.setImmutabilityPolicy(Object.assign({ abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal, immutabilityPolicyExpiry: immutabilityPolicy.expiriesOn, immutabilityPolicyMode: immutabilityPolicy.policyMode, modifiedAccessConditions: options === null || options === void 0 ? void 0 : options.modifiedAccessCondition }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message + }); + throw e; + } + finally { + span.end(); + } + } + /** + * Set legal hold on the blob. + * + * @param options - Optional options to set legal hold on the blob. + */ + async setLegalHold(legalHoldEnabled, options) { + const { span, updatedOptions } = createSpan("BlobClient-setLegalHold", options); + try { + return await this.blobContext.setLegalHold(legalHoldEnabled, Object.assign({ abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message + }); + throw e; + } + finally { + span.end(); + } + } +} /** * AppendBlobClient defines a set of operations applicable to append blobs. */ -var AppendBlobClient = /** @class */ (function (_super) { - tslib.__extends(AppendBlobClient, _super); - function AppendBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { - var _this = this; +class AppendBlobClient extends BlobClient { + constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); - var pipeline; - var url; + let pipeline; + let url; options = options || {}; - if (credentialOrPipelineOrContainerName instanceof Pipeline) { + if (isPipelineLike(credentialOrPipelineOrContainerName)) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; @@ -31955,12 +28549,12 @@ var AppendBlobClient = /** @class */ (function (_super) { blobNameOrOptions && typeof blobNameOrOptions === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) - var containerName = credentialOrPipelineOrContainerName; - var blobName = blobNameOrOptions; - var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + const containerName = credentialOrPipelineOrContainerName; + const blobName = blobNameOrOptions; + const extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + const 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); @@ -31980,9 +28574,8 @@ var AppendBlobClient = /** @class */ (function (_super) { else { throw new Error("Expecting non-empty strings for containerName and blobName parameters"); } - _this = _super.call(this, url, pipeline) || this; - _this.appendBlobContext = new AppendBlob(_this.storageClientContext); - return _this; + super(url, pipeline); + this.appendBlobContext = new AppendBlob(this.storageClientContext); } /** * Creates a new AppendBlobClient object identical to the source but with the @@ -31992,9 +28585,9 @@ var AppendBlobClient = /** @class */ (function (_super) { * @param snapshot - The snapshot timestamp. * @returns A new AppendBlobClient object identical to the source but with the specified snapshot timestamp. */ - AppendBlobClient.prototype.withSnapshot = function (snapshot) { + withSnapshot(snapshot) { return new AppendBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); - }; + } /** * Creates a 0-length append blob. Call AppendBlock to append data to an append blob. * @see https://docs.microsoft.com/rest/api/storageservices/put-blob @@ -32009,37 +28602,25 @@ var AppendBlobClient = /** @class */ (function (_super) { * await appendBlobClient.create(); * ``` */ - AppendBlobClient.prototype.create = function (options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_18; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("AppendBlobClient-create", options), span = _b.span, updatedOptions = _b.updatedOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.appendBlobContext.create(0, tslib.__assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_18 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_18.message - }); - throw e_18; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async create(options = {}) { + var _a, _b, _c; + const { span, updatedOptions } = createSpan("AppendBlobClient-create", options); + options.conditions = options.conditions || {}; + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.appendBlobContext.create(0, Object.assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, legalHold: options.legalHold, blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Creates a 0-length append blob. Call AppendBlock to append data to an append blob. * If the blob with the same name already exists, the content of the existing blob will remain unchanged. @@ -32047,81 +28628,56 @@ var AppendBlobClient = /** @class */ (function (_super) { * * @param options - */ - AppendBlobClient.prototype.createIfNotExists = function (options) { + async createIfNotExists(options = {}) { var _a, _b; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _c, span, updatedOptions, conditions, res, e_19; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _c = createSpan("AppendBlobClient-createIfNotExists", options), span = _c.span, updatedOptions = _c.updatedOptions; - conditions = { ifNoneMatch: ETagAny }; - _d.label = 1; - case 1: - _d.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.create(tslib.__assign(tslib.__assign({}, updatedOptions), { conditions: conditions }))]; - case 2: - res = _d.sent(); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable - })]; - case 3: - e_19 = _d.sent(); - if (((_a = e_19.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: "Expected exception when creating a blob only if it does not already exist." - }); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_19.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_19.response })]; - } - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_19.message - }); - throw e_19; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("AppendBlobClient-createIfNotExists", options); + const conditions = { ifNoneMatch: ETagAny }; + try { + const res = await this.create(Object.assign(Object.assign({}, updatedOptions), { conditions })); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable + }); + } + catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: "Expected exception when creating a blob only if it does not already exist." + }); + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Seals the append blob, making it read only. * * @param options - */ - AppendBlobClient.prototype.seal = function (options) { + async seal(options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_20; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("AppendBlobClient-seal", options), span = _b.span, updatedOptions = _b.updatedOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.appendBlobContext.seal(tslib.__assign({ abortSignal: options.abortSignal, appendPositionAccessConditions: options.conditions, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_20 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_20.message - }); - throw e_20; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("AppendBlobClient-seal", options); + options.conditions = options.conditions || {}; + try { + return await this.appendBlobContext.seal(Object.assign({ abortSignal: options.abortSignal, appendPositionAccessConditions: options.conditions, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Commits a new block of data to the end of the existing append blob. * @see https://docs.microsoft.com/rest/api/storageservices/append-block @@ -32146,39 +28702,27 @@ var AppendBlobClient = /** @class */ (function (_super) { * await existingAppendBlobClient.appendBlock(content, content.length); * ``` */ - AppendBlobClient.prototype.appendBlock = function (body, contentLength, options) { + async appendBlock(body, contentLength, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_21; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("AppendBlobClient-appendBlock", options), span = _b.span, updatedOptions = _b.updatedOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.appendBlobContext.appendBlock(contentLength, body, tslib.__assign({ abortSignal: options.abortSignal, appendPositionAccessConditions: options.conditions, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: { - onUploadProgress: options.onProgress - }, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_21 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_21.message - }); - throw e_21; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("AppendBlobClient-appendBlock", options); + options.conditions = options.conditions || {}; + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.appendBlobContext.appendBlock(contentLength, body, Object.assign({ abortSignal: options.abortSignal, appendPositionAccessConditions: options.conditions, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: { + onUploadProgress: options.onProgress + }, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * The Append Block operation commits a new block of data to the end of an existing append blob * where the contents are read from a source url. @@ -32193,58 +28737,46 @@ var AppendBlobClient = /** @class */ (function (_super) { * @param count - Number of bytes to be appended as a block * @param options - */ - AppendBlobClient.prototype.appendBlockFromURL = function (sourceURL, sourceOffset, count, options) { + async appendBlockFromURL(sourceURL, sourceOffset, count, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_22; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("AppendBlobClient-appendBlockFromURL", options), span = _b.span, updatedOptions = _b.updatedOptions; - options.conditions = options.conditions || {}; - options.sourceConditions = options.sourceConditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.appendBlobContext.appendBlockFromUrl(sourceURL, 0, tslib.__assign({ abortSignal: options.abortSignal, sourceRange: rangeToString({ offset: sourceOffset, count: count }), sourceContentMD5: options.sourceContentMD5, sourceContentCrc64: options.sourceContentCrc64, leaseAccessConditions: options.conditions, appendPositionAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { - sourceIfMatch: options.sourceConditions.ifMatch, - sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, - sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, - sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince - }, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_22 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_22.message - }); - throw e_22; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("AppendBlobClient-appendBlockFromURL", options); + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.appendBlobContext.appendBlockFromUrl(sourceURL, 0, Object.assign({ abortSignal: options.abortSignal, sourceRange: rangeToString({ offset: sourceOffset, count }), sourceContentMD5: options.sourceContentMD5, sourceContentCrc64: options.sourceContentCrc64, leaseAccessConditions: options.conditions, appendPositionAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince + }, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; - return AppendBlobClient; -}(BlobClient)); + throw e; + } + finally { + span.end(); + } + } +} /** * BlockBlobClient defines a set of operations applicable to block blobs. */ -var BlockBlobClient = /** @class */ (function (_super) { - tslib.__extends(BlockBlobClient, _super); - function BlockBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { - var _this = this; +class BlockBlobClient extends BlobClient { + constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); - var pipeline; - var url; + let pipeline; + let url; options = options || {}; - if (credentialOrPipelineOrContainerName instanceof Pipeline) { + if (isPipelineLike(credentialOrPipelineOrContainerName)) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; @@ -32269,12 +28801,12 @@ var BlockBlobClient = /** @class */ (function (_super) { blobNameOrOptions && typeof blobNameOrOptions === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) - var containerName = credentialOrPipelineOrContainerName; - var blobName = blobNameOrOptions; - var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + const containerName = credentialOrPipelineOrContainerName; + const blobName = blobNameOrOptions; + const extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + const 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); @@ -32294,10 +28826,9 @@ var BlockBlobClient = /** @class */ (function (_super) { else { throw new Error("Expecting non-empty strings for containerName and blobName parameters"); } - _this = _super.call(this, url, pipeline) || this; - _this.blockBlobContext = new BlockBlob(_this.storageClientContext); - _this._blobContext = new Blob$1(_this.storageClientContext); - return _this; + super(url, pipeline); + this.blockBlobContext = new BlockBlob(this.storageClientContext); + this._blobContext = new Blob$1(this.storageClientContext); } /** * Creates a new BlockBlobClient object identical to the source but with the @@ -32307,9 +28838,9 @@ var BlockBlobClient = /** @class */ (function (_super) { * @param snapshot - The snapshot timestamp. * @returns A new BlockBlobClient object identical to the source but with the specified snapshot timestamp. */ - BlockBlobClient.prototype.withSnapshot = function (snapshot) { + withSnapshot(snapshot) { return new BlockBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); - }; + } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -32340,47 +28871,35 @@ var BlockBlobClient = /** @class */ (function (_super) { * @param query - * @param options - */ - BlockBlobClient.prototype.query = function (query, options) { + async query(query, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, response, e_23; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - _b = createSpan("BlockBlobClient-query", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this._blobContext.query(tslib.__assign({ abortSignal: options.abortSignal, queryRequest: { - queryType: "SQL", - expression: query, - inputSerialization: toQuerySerialization(options.inputTextConfiguration), - outputSerialization: toQuerySerialization(options.outputTextConfiguration) - }, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: - response = _c.sent(); - return [2 /*return*/, new BlobQueryResponse(response, { - abortSignal: options.abortSignal, - onProgress: options.onProgress, - onError: options.onError - })]; - case 3: - e_23 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_23.message - }); - throw e_23; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + const { span, updatedOptions } = createSpan("BlockBlobClient-query", options); + try { + if (false) {} + const response = await this._blobContext.query(Object.assign({ abortSignal: options.abortSignal, queryRequest: { + queryType: "SQL", + expression: query, + inputSerialization: toQuerySerialization(options.inputTextConfiguration), + outputSerialization: toQuerySerialization(options.outputTextConfiguration) + }, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + return new BlobQueryResponse(response, { + abortSignal: options.abortSignal, + onProgress: options.onProgress, + onError: options.onError }); - }); - }; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message + }); + throw e; + } + finally { + span.end(); + } + } /** * Creates a new block blob, or updates the content of an existing block blob. * Updating an existing block blob overwrites any existing metadata on the blob. @@ -32408,39 +28927,27 @@ var BlockBlobClient = /** @class */ (function (_super) { * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); * ``` */ - BlockBlobClient.prototype.upload = function (body, contentLength, options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_24; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _b = createSpan("BlockBlobClient-upload", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blockBlobContext.upload(contentLength, body, tslib.__assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: { - onUploadProgress: options.onProgress - }, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_24 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_24.message - }); - throw e_24; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async upload(body, contentLength, options = {}) { + var _a, _b, _c; + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("BlockBlobClient-upload", options); + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.blockBlobContext.upload(contentLength, body, Object.assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: { + onUploadProgress: options.onProgress + }, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, legalHold: options.legalHold, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * 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 @@ -32459,43 +28966,31 @@ var BlockBlobClient = /** @class */ (function (_super) { * - https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= * @param options - Optional parameters. */ - BlockBlobClient.prototype.syncUploadFromURL = function (sourceURL, options) { + async syncUploadFromURL(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, updatedOptions, e_25; - return tslib.__generator(this, function (_g) { - switch (_g.label) { - case 0: - options.conditions = options.conditions || {}; - _f = createSpan("BlockBlobClient-syncUploadFromURL", options), span = _f.span, updatedOptions = _f.updatedOptions; - _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(tslib.__assign({}, options), { blobHttpHeaders: options.blobHTTPHeaders, 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) }), convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _g.sent()]; - case 3: - e_25 = _g.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_25.message - }); - throw e_25; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("BlockBlobClient-syncUploadFromURL", options); + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.blockBlobContext.putBlobFromUrl(0, sourceURL, Object.assign(Object.assign(Object.assign({}, options), { blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.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, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags) }), convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Uploads the specified block to the block blob's "staging area" to be later * committed by a call to commitBlockList. @@ -32507,37 +29002,25 @@ var BlockBlobClient = /** @class */ (function (_super) { * @param options - Options to the Block Blob Stage Block operation. * @returns Response data for the Block Blob Stage Block operation. */ - 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, updatedOptions, e_26; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlockBlobClient-stageBlock", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blockBlobContext.stageBlock(blockId, contentLength, body, tslib.__assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, requestOptions: { - onUploadProgress: options.onProgress - }, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_26 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_26.message - }); - throw e_26; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async stageBlock(blockId, body, contentLength, options = {}) { + const { span, updatedOptions } = createSpan("BlockBlobClient-stageBlock", options); + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.blockBlobContext.stageBlock(blockId, contentLength, body, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, requestOptions: { + onUploadProgress: options.onProgress + }, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * The Stage Block From URL operation creates a new block to be committed as part * of a blob where the contents are read from a URL. @@ -32559,36 +29042,23 @@ var BlockBlobClient = /** @class */ (function (_super) { * @param options - Options to the Block Blob Stage Block From URL operation. * @returns Response data for the Block Blob Stage Block From URL operation. */ - BlockBlobClient.prototype.stageBlockFromURL = function (blockId, sourceURL, offset, count, options) { - if (offset === void 0) { offset = 0; } - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_27; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlockBlobClient-stageBlockFromURL", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blockBlobContext.stageBlockFromURL(blockId, 0, sourceURL, tslib.__assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, sourceContentMD5: options.sourceContentMD5, sourceContentCrc64: options.sourceContentCrc64, sourceRange: offset === 0 && !count ? undefined : rangeToString({ offset: offset, count: count }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_27 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_27.message - }); - throw e_27; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async stageBlockFromURL(blockId, sourceURL, offset = 0, count, options = {}) { + const { span, updatedOptions } = createSpan("BlockBlobClient-stageBlockFromURL", options); + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.blockBlobContext.stageBlockFromURL(blockId, 0, sourceURL, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, sourceContentMD5: options.sourceContentMD5, sourceContentCrc64: options.sourceContentCrc64, sourceRange: offset === 0 && !count ? undefined : rangeToString({ offset, count }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Writes a blob by specifying the list of block IDs that make up the blob. * In order to be written as part of a blob, a block must have been successfully written @@ -32601,37 +29071,25 @@ var BlockBlobClient = /** @class */ (function (_super) { * @param options - Options to the Block Blob Commit Block List operation. * @returns Response data for the Block Blob Commit Block List operation. */ - BlockBlobClient.prototype.commitBlockList = function (blocks, options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_28; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _b = createSpan("BlockBlobClient-commitBlockList", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blockBlobContext.commitBlockList({ latest: blocks }, tslib.__assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_28 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_28.message - }); - throw e_28; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async commitBlockList(blocks, options = {}) { + var _a, _b, _c; + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("BlockBlobClient-commitBlockList", options); + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.blockBlobContext.commitBlockList({ latest: blocks }, Object.assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, legalHold: options.legalHold, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Returns the list of blocks that have been uploaded as part of a block blob * using the specified block list filter. @@ -32642,43 +29100,30 @@ var BlockBlobClient = /** @class */ (function (_super) { * @param options - Options to the Block Blob Get Block List operation. * @returns Response data for the Block Blob Get Block List operation. */ - BlockBlobClient.prototype.getBlockList = function (listType, options) { + async getBlockList(listType, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, res, e_29; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlockBlobClient-getBlockList", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blockBlobContext.getBlockList(listType, tslib.__assign({ 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 }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: - res = _c.sent(); - if (!res.committedBlocks) { - res.committedBlocks = []; - } - if (!res.uncommittedBlocks) { - res.uncommittedBlocks = []; - } - return [2 /*return*/, res]; - case 3: - e_29 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_29.message - }); - throw e_29; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlockBlobClient-getBlockList", options); + try { + const res = await this.blockBlobContext.getBlockList(listType, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + if (!res.committedBlocks) { + res.committedBlocks = []; + } + if (!res.uncommittedBlocks) { + res.uncommittedBlocks = []; + } + return res; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } // High level functions /** * Uploads a Buffer(Node.js)/Blob(browsers)/ArrayBuffer/ArrayBufferView object to a BlockBlob. @@ -32688,45 +29133,43 @@ 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. * + * A common {@link BlockBlobParallelUploadOptions.blobHTTPHeaders} option to set is + * `blobContentType`, enabling the browser to provide + * functionality based on file type. + * * @param data - Buffer(Node.js), Blob, ArrayBuffer or ArrayBufferView * @param options - */ - BlockBlobClient.prototype.uploadData = function (data, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, buffer_1, browserBlob_1; - return tslib.__generator(this, function (_b) { - _a = createSpan("BlockBlobClient-uploadData", options), span = _a.span, updatedOptions = _a.updatedOptions; - 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, updatedOptions)]; - } - else {} + async uploadData(data, options = {}) { + const { span, updatedOptions } = createSpan("BlockBlobClient-uploadData", options); + try { + if (true) { + let buffer; + if (data instanceof Buffer) { + buffer = data; } - catch (e) { - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e.message - }); - throw e; + else if (data instanceof ArrayBuffer) { + buffer = Buffer.from(data); } - finally { - span.end(); + else { + data = data; + buffer = Buffer.from(data.buffer, data.byteOffset, data.byteLength); } - return [2 /*return*/]; + return this.uploadSeekableInternal((offset, size) => buffer.slice(offset, offset + size), buffer.byteLength, updatedOptions); + } + else {} + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * ONLY AVAILABLE IN BROWSERS. * @@ -32736,41 +29179,33 @@ 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. * + * A common {@link BlockBlobParallelUploadOptions.blobHTTPHeaders} option to set is + * `blobContentType`, enabling the browser to provide + * functionality based on file type. + * * @deprecated Use {@link uploadData} instead. * * @param browserData - Blob, File, ArrayBuffer or ArrayBufferView * @param options - Options to upload browser data. * @returns Response data for the Blob Upload operation. */ - BlockBlobClient.prototype.uploadBrowserData = function (browserData, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, browserBlob_2, e_30; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlockBlobClient-uploadBrowserData", options), span = _a.span, updatedOptions = _a.updatedOptions; - _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, updatedOptions)]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_30 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_30.message - }); - throw e_30; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async uploadBrowserData(browserData, options = {}) { + const { span, updatedOptions } = createSpan("BlockBlobClient-uploadBrowserData", options); + try { + const browserBlob = new Blob([browserData]); + return await this.uploadSeekableInternal((offset, size) => browserBlob.slice(offset, offset + size), browserBlob.size, updatedOptions); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * * Uploads data to block blob. Requires a bodyFactory as the data source, @@ -32786,115 +29221,88 @@ var BlockBlobClient = /** @class */ (function (_super) { * @param options - Options to Upload to Block Blob operation. * @returns Response data for the Blob Upload operation. */ - BlockBlobClient.prototype.uploadSeekableInternal = function (bodyFactory, size, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, numBlocks_1, blockList_1, blockIDPrefix_1, transferProgress_2, batch, _loop_2, i, e_31; - 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_STAGE_BLOCK_BYTES * BLOCK_BLOB_MAX_BLOCKS) { - 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-uploadSeekableInternal", options), span = _a.span, updatedOptions = _a.updatedOptions; - _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, updatedOptions)]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - numBlocks_1 = Math.floor((size - 1) / options.blockSize) + 1; - if (numBlocks_1 > 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_1 = []; - blockIDPrefix_1 = coreHttp.generateUuid(); - transferProgress_2 = 0; - batch = new Batch(options.concurrency); - _loop_2 = 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_1, i); - start = options.blockSize * i; - 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, { - abortSignal: options.abortSignal, - conditions: options.conditions, - encryptionScope: options.encryptionScope, - tracingOptions: updatedOptions.tracingOptions - })]; - case 1: - _a.sent(); - // Update progress after block is successfully uploaded to server, in case of block trying - // TODO: Hook with convenience layer progress event in finer level - transferProgress_2 += contentLength; - if (options.onProgress) { - options.onProgress({ - loadedBytes: transferProgress_2 - }); - } - return [2 /*return*/]; - } - }); - }); }); - }; - for (i = 0; i < numBlocks_1; i++) { - _loop_2(i); - } - return [4 /*yield*/, batch.do()]; - case 4: - _b.sent(); - return [2 /*return*/, this.commitBlockList(blockList_1, updatedOptions)]; - case 5: - e_31 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_31.message - }); - throw e_31; - case 6: - span.end(); - return [7 /*endfinally*/]; - case 7: return [2 /*return*/]; + async uploadSeekableInternal(bodyFactory, size, options = {}) { + 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_STAGE_BLOCK_BYTES * BLOCK_BLOB_MAX_BLOCKS) { + 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 = {}; + } + const { span, updatedOptions } = createSpan("BlockBlobClient-uploadSeekableInternal", options); + try { + if (size <= options.maxSingleShotSize) { + return await this.upload(bodyFactory(0, size), size, updatedOptions); + } + const numBlocks = Math.floor((size - 1) / options.blockSize) + 1; + if (numBlocks > 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}`); + } + const blockList = []; + const blockIDPrefix = coreHttp.generateUuid(); + let transferProgress = 0; + const batch = new Batch(options.concurrency); + for (let i = 0; i < numBlocks; i++) { + batch.addOperation(async () => { + const blockID = generateBlockID(blockIDPrefix, i); + const start = options.blockSize * i; + const end = i === numBlocks - 1 ? size : start + options.blockSize; + const contentLength = end - start; + blockList.push(blockID); + await this.stageBlock(blockID, bodyFactory(start, contentLength), contentLength, { + abortSignal: options.abortSignal, + conditions: options.conditions, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + }); + // Update progress after block is successfully uploaded to server, in case of block trying + // TODO: Hook with convenience layer progress event in finer level + transferProgress += contentLength; + if (options.onProgress) { + options.onProgress({ + loadedBytes: transferProgress + }); + } + }); + } + await batch.do(); + return this.commitBlockList(blockList, updatedOptions); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -32908,45 +29316,29 @@ var BlockBlobClient = /** @class */ (function (_super) { * @param options - Options to Upload to Block Blob operation. * @returns Response data for the Blob Upload operation. */ - BlockBlobClient.prototype.uploadFile = function (filePath, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, size, e_32; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlockBlobClient-uploadFile", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 4, 5, 6]); - 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 - }); - }; - }, size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) }))]; - case 3: return [2 /*return*/, _b.sent()]; - case 4: - e_32 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_32.message - }); - throw e_32; - case 5: - span.end(); - return [7 /*endfinally*/]; - case 6: return [2 /*return*/]; - } + async uploadFile(filePath, options = {}) { + const { span, updatedOptions } = createSpan("BlockBlobClient-uploadFile", options); + try { + const size = (await fsStat(filePath)).size; + return await this.uploadSeekableInternal((offset, count) => { + return () => fsCreateReadStream(filePath, { + autoClose: true, + end: count ? offset + count - 1 : Infinity, + start: offset + }); + }, size, Object.assign(Object.assign({}, options), { tracingOptions: Object.assign(Object.assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) })); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -32963,94 +29355,68 @@ var BlockBlobClient = /** @class */ (function (_super) { * @param options - Options to Upload Stream to Block Blob operation. * @returns Response data for the Blob Upload operation. */ - BlockBlobClient.prototype.uploadStream = function (stream, bufferSize, maxConcurrency, options) { - if (bufferSize === void 0) { bufferSize = DEFAULT_BLOCK_BUFFER_SIZE_BYTES; } - if (maxConcurrency === void 0) { maxConcurrency = 5; } - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, blockNum_1, blockIDPrefix_2, transferProgress_3, blockList_2, scheduler, e_33; - var _this = this; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!options.blobHTTPHeaders) { - options.blobHTTPHeaders = {}; - } - if (!options.conditions) { - options.conditions = {}; - } - _a = createSpan("BlockBlobClient-uploadStream", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 4, 5, 6]); - blockNum_1 = 0; - blockIDPrefix_2 = coreHttp.generateUuid(); - transferProgress_3 = 0; - blockList_2 = []; - scheduler = new BufferScheduler(stream, bufferSize, maxConcurrency, function (body, length) { return tslib.__awaiter(_this, void 0, void 0, function () { - var blockID; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - blockID = generateBlockID(blockIDPrefix_2, blockNum_1); - blockList_2.push(blockID); - blockNum_1++; - return [4 /*yield*/, this.stageBlock(blockID, body, length, { - conditions: options.conditions, - encryptionScope: options.encryptionScope, - tracingOptions: updatedOptions.tracingOptions - })]; - case 1: - _a.sent(); - // Update progress after block is successfully uploaded to server, in case of block trying - transferProgress_3 += length; - if (options.onProgress) { - options.onProgress({ loadedBytes: transferProgress_3 }); - } - return [2 /*return*/]; - } - }); - }); }, - // concurrency should set a smaller value than maxConcurrency, which is helpful to - // reduce the possibility when a outgoing handler waits for stream data, in - // this situation, outgoing handlers are blocked. - // Outgoing queue shouldn't be empty. - Math.ceil((maxConcurrency / 4) * 3)); - return [4 /*yield*/, scheduler.do()]; - case 2: - _b.sent(); - return [4 /*yield*/, this.commitBlockList(blockList_2, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) }))]; - case 3: return [2 /*return*/, _b.sent()]; - case 4: - e_33 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_33.message - }); - throw e_33; - case 5: - span.end(); - return [7 /*endfinally*/]; - case 6: return [2 /*return*/]; + async uploadStream(stream, bufferSize = DEFAULT_BLOCK_BUFFER_SIZE_BYTES, maxConcurrency = 5, options = {}) { + if (!options.blobHTTPHeaders) { + options.blobHTTPHeaders = {}; + } + if (!options.conditions) { + options.conditions = {}; + } + const { span, updatedOptions } = createSpan("BlockBlobClient-uploadStream", options); + try { + let blockNum = 0; + const blockIDPrefix = coreHttp.generateUuid(); + let transferProgress = 0; + const blockList = []; + const scheduler = new BufferScheduler(stream, bufferSize, maxConcurrency, async (body, length) => { + const blockID = generateBlockID(blockIDPrefix, blockNum); + blockList.push(blockID); + blockNum++; + await this.stageBlock(blockID, body, length, { + conditions: options.conditions, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + }); + // Update progress after block is successfully uploaded to server, in case of block trying + transferProgress += length; + if (options.onProgress) { + options.onProgress({ loadedBytes: transferProgress }); } + }, + // concurrency should set a smaller value than maxConcurrency, which is helpful to + // reduce the possibility when a outgoing handler waits for stream data, in + // this situation, outgoing handlers are blocked. + // Outgoing queue shouldn't be empty. + Math.ceil((maxConcurrency / 4) * 3)); + await scheduler.do(); + return await this.commitBlockList(blockList, Object.assign(Object.assign({}, options), { tracingOptions: Object.assign(Object.assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) })); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; - return BlockBlobClient; -}(BlobClient)); + throw e; + } + finally { + span.end(); + } + } +} /** * PageBlobClient defines a set of operations applicable to page blobs. */ -var PageBlobClient = /** @class */ (function (_super) { - tslib.__extends(PageBlobClient, _super); - function PageBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { - var _this = this; +class PageBlobClient extends BlobClient { + constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); - var pipeline; - var url; + let pipeline; + let url; options = options || {}; - if (credentialOrPipelineOrContainerName instanceof Pipeline) { + if (isPipelineLike(credentialOrPipelineOrContainerName)) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; @@ -33075,12 +29441,12 @@ var PageBlobClient = /** @class */ (function (_super) { blobNameOrOptions && typeof blobNameOrOptions === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) - var containerName = credentialOrPipelineOrContainerName; - var blobName = blobNameOrOptions; - var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + const containerName = credentialOrPipelineOrContainerName; + const blobName = blobNameOrOptions; + const extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + const 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); @@ -33100,9 +29466,8 @@ var PageBlobClient = /** @class */ (function (_super) { else { throw new Error("Expecting non-empty strings for containerName and blobName parameters"); } - _this = _super.call(this, url, pipeline) || this; - _this.pageBlobContext = new PageBlob(_this.storageClientContext); - return _this; + super(url, pipeline); + this.pageBlobContext = new PageBlob(this.storageClientContext); } /** * Creates a new PageBlobClient object identical to the source but with the @@ -33112,9 +29477,9 @@ var PageBlobClient = /** @class */ (function (_super) { * @param snapshot - The snapshot timestamp. * @returns A new PageBlobClient object identical to the source but with the specified snapshot timestamp. */ - PageBlobClient.prototype.withSnapshot = function (snapshot) { + withSnapshot(snapshot) { return new PageBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); - }; + } /** * Creates a page blob of the specified length. Call uploadPages to upload data * data to a page blob. @@ -33124,37 +29489,25 @@ var PageBlobClient = /** @class */ (function (_super) { * @param options - Options to the Page Blob Create operation. * @returns Response data for the Page Blob Create operation. */ - PageBlobClient.prototype.create = function (size, options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_34; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-create", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.pageBlobContext.create(0, size, tslib.__assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, blobSequenceNumber: options.blobSequenceNumber, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_34 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_34.message - }); - throw e_34; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async create(size, options = {}) { + var _a, _b, _c; + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("PageBlobClient-create", options); + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.pageBlobContext.create(0, size, Object.assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, blobSequenceNumber: options.blobSequenceNumber, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, legalHold: options.legalHold, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Creates a page blob of the specified length. Call uploadPages to upload data * data to a page blob. If the blob with the same name already exists, the content @@ -33164,46 +29517,33 @@ var PageBlobClient = /** @class */ (function (_super) { * @param size - size of the page blob. * @param options - */ - PageBlobClient.prototype.createIfNotExists = function (size, options) { + async createIfNotExists(size, options = {}) { var _a, _b; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _c, span, updatedOptions, conditions, res, e_35; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _c = createSpan("PageBlobClient-createIfNotExists", options), span = _c.span, updatedOptions = _c.updatedOptions; - _d.label = 1; - case 1: - _d.trys.push([1, 3, 4, 5]); - conditions = { ifNoneMatch: ETagAny }; - return [4 /*yield*/, this.create(size, tslib.__assign(tslib.__assign({}, options), { conditions: conditions, tracingOptions: updatedOptions.tracingOptions }))]; - case 2: - res = _d.sent(); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable - })]; - case 3: - e_35 = _d.sent(); - if (((_a = e_35.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: "Expected exception when creating a blob only if it does not already exist." - }); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_35.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_35.response })]; - } - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_35.message - }); - throw e_35; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("PageBlobClient-createIfNotExists", options); + try { + const conditions = { ifNoneMatch: ETagAny }; + const res = await this.create(size, Object.assign(Object.assign({}, options), { conditions, tracingOptions: updatedOptions.tracingOptions })); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable + }); + } + catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: "Expected exception when creating a blob only if it does not already exist." + }); + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Writes 1 or more pages to the page blob. The start and end offsets must be a multiple of 512. * @see https://docs.microsoft.com/rest/api/storageservices/put-page @@ -33214,39 +29554,27 @@ var PageBlobClient = /** @class */ (function (_super) { * @param options - Options to the Page Blob Upload Pages operation. * @returns Response data for the Page Blob Upload Pages operation. */ - PageBlobClient.prototype.uploadPages = function (body, offset, count, options) { + async uploadPages(body, offset, count, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_36; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-uploadPages", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.pageBlobContext.uploadPages(count, body, tslib.__assign({ 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 }), requestOptions: { - onUploadProgress: options.onProgress - }, range: rangeToString({ offset: offset, count: count }), sequenceNumberAccessConditions: options.conditions, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_36 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_36.message - }); - throw e_36; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("PageBlobClient-uploadPages", options); + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.pageBlobContext.uploadPages(count, body, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: { + onUploadProgress: options.onProgress + }, range: rangeToString({ offset, count }), sequenceNumberAccessConditions: options.conditions, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * The Upload Pages operation writes a range of pages to a page blob where the * contents are read from a URL. @@ -33258,43 +29586,31 @@ var PageBlobClient = /** @class */ (function (_super) { * @param count - Number of bytes to be uploaded from source page blob * @param options - */ - PageBlobClient.prototype.uploadPagesFromURL = function (sourceURL, sourceOffset, destOffset, count, options) { + async uploadPagesFromURL(sourceURL, sourceOffset, destOffset, count, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_37; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - options.sourceConditions = options.sourceConditions || {}; - _b = createSpan("PageBlobClient-uploadPagesFromURL", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.pageBlobContext.uploadPagesFromURL(sourceURL, rangeToString({ offset: sourceOffset, count: count }), 0, rangeToString({ offset: destOffset, count: count }), tslib.__assign({ abortSignal: options.abortSignal, sourceContentMD5: options.sourceContentMD5, sourceContentCrc64: options.sourceContentCrc64, leaseAccessConditions: options.conditions, sequenceNumberAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { - sourceIfMatch: options.sourceConditions.ifMatch, - sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, - sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, - sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince - }, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_37 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_37.message - }); - throw e_37; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + const { span, updatedOptions } = createSpan("PageBlobClient-uploadPagesFromURL", options); + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.pageBlobContext.uploadPagesFromURL(sourceURL, rangeToString({ offset: sourceOffset, count }), 0, rangeToString({ offset: destOffset, count }), Object.assign({ abortSignal: options.abortSignal, sourceContentMD5: options.sourceContentMD5, sourceContentCrc64: options.sourceContentCrc64, leaseAccessConditions: options.conditions, sequenceNumberAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince + }, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Frees the specified pages from the page blob. * @see https://docs.microsoft.com/rest/api/storageservices/put-page @@ -33304,37 +29620,24 @@ var PageBlobClient = /** @class */ (function (_super) { * @param options - Options to the Page Blob Clear Pages operation. * @returns Response data for the Page Blob Clear Pages operation. */ - PageBlobClient.prototype.clearPages = function (offset, count, options) { + async clearPages(offset = 0, 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, updatedOptions, e_38; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-clearPages", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext.clearPages(0, tslib.__assign({ 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 }), range: rangeToString({ offset: offset, count: count }), sequenceNumberAccessConditions: options.conditions, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_38 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_38.message - }); - throw e_38; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("PageBlobClient-clearPages", options); + try { + return await this.pageBlobContext.clearPages(0, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), range: rangeToString({ offset, count }), sequenceNumberAccessConditions: options.conditions, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Returns the list of valid page ranges for a page blob or snapshot of a page blob. * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges @@ -33344,39 +29647,26 @@ var PageBlobClient = /** @class */ (function (_super) { * @param options - Options to the Page Blob Get Ranges operation. * @returns Response data for the Page Blob Get Ranges operation. */ - PageBlobClient.prototype.getPageRanges = function (offset, count, options) { + async getPageRanges(offset = 0, 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, updatedOptions, e_39; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-getPageRanges", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext - .getPageRanges(tslib.__assign({ 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 }), range: rangeToString({ offset: offset, count: count }) }, convertTracingToRequestOptionsBase(updatedOptions))) - .then(rangeResponseFromModel)]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_39 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_39.message - }); - throw e_39; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("PageBlobClient-getPageRanges", options); + try { + return await this.pageBlobContext + .getPageRanges(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), range: rangeToString({ offset, count }) }, convertTracingToRequestOptionsBase(updatedOptions))) + .then(rangeResponseFromModel); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Gets the collection of page ranges that differ between a specified snapshot and this page blob. * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges @@ -33387,38 +29677,26 @@ var PageBlobClient = /** @class */ (function (_super) { * @param options - Options to the Page Blob Get Page Ranges Diff operation. * @returns Response data for the Page Blob Get Page Range Diff operation. */ - PageBlobClient.prototype.getPageRangesDiff = function (offset, count, prevSnapshot, options) { + async getPageRangesDiff(offset, count, prevSnapshot, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_40; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-getPageRangesDiff", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext - .getPageRangesDiff(tslib.__assign({ 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 }), prevsnapshot: prevSnapshot, range: rangeToString({ offset: offset, count: count }) }, convertTracingToRequestOptionsBase(updatedOptions))) - .then(rangeResponseFromModel)]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_40 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_40.message - }); - throw e_40; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("PageBlobClient-getPageRangesDiff", options); + try { + return await this.pageBlobContext + .getPageRangesDiff(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), prevsnapshot: prevSnapshot, range: rangeToString({ offset, count }) }, convertTracingToRequestOptionsBase(updatedOptions))) + .then(rangeResponseFromModel); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Gets the collection of page ranges that differ between a specified snapshot and this page blob for managed disks. * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges @@ -33429,38 +29707,26 @@ var PageBlobClient = /** @class */ (function (_super) { * @param options - Options to the Page Blob Get Page Ranges Diff operation. * @returns Response data for the Page Blob Get Page Range Diff operation. */ - PageBlobClient.prototype.getPageRangesDiffForManagedDisks = function (offset, count, prevSnapshotUrl, options) { + async getPageRangesDiffForManagedDisks(offset, count, prevSnapshotUrl, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_41; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-GetPageRangesDiffForManagedDisks", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext - .getPageRangesDiff(tslib.__assign({ 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 }), prevSnapshotUrl: prevSnapshotUrl, range: rangeToString({ offset: offset, count: count }) }, convertTracingToRequestOptionsBase(updatedOptions))) - .then(rangeResponseFromModel)]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_41 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_41.message - }); - throw e_41; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("PageBlobClient-GetPageRangesDiffForManagedDisks", options); + try { + return await this.pageBlobContext + .getPageRangesDiff(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), prevSnapshotUrl, range: rangeToString({ offset, count }) }, convertTracingToRequestOptionsBase(updatedOptions))) + .then(rangeResponseFromModel); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Resizes the page blob to the specified size (which must be a multiple of 512). * @see https://docs.microsoft.com/rest/api/storageservices/set-blob-properties @@ -33469,36 +29735,24 @@ var PageBlobClient = /** @class */ (function (_super) { * @param options - Options to the Page Blob Resize operation. * @returns Response data for the Page Blob Resize operation. */ - PageBlobClient.prototype.resize = function (size, options) { + async resize(size, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_42; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-resize", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext.resize(size, tslib.__assign({ 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 }), encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_42 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_42.message - }); - throw e_42; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("PageBlobClient-resize", options); + try { + return await this.pageBlobContext.resize(size, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Sets a page blob's sequence number. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties @@ -33508,36 +29762,24 @@ var PageBlobClient = /** @class */ (function (_super) { * @param options - Options to the Page Blob Update Sequence Number operation. * @returns Response data for the Page Blob Update Sequence Number operation. */ - PageBlobClient.prototype.updateSequenceNumber = function (sequenceNumberAction, sequenceNumber, options) { + async updateSequenceNumber(sequenceNumberAction, sequenceNumber, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_43; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-updateSequenceNumber", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext.updateSequenceNumber(sequenceNumberAction, tslib.__assign({ abortSignal: options.abortSignal, blobSequenceNumber: sequenceNumber, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_43 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_43.message - }); - throw e_43; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("PageBlobClient-updateSequenceNumber", options); + try { + return await this.pageBlobContext.updateSequenceNumber(sequenceNumberAction, Object.assign({ abortSignal: options.abortSignal, blobSequenceNumber: sequenceNumber, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Begins an operation to start an incremental copy from one page blob's snapshot to this page blob. * The snapshot is copied such that only the differential changes between the previously @@ -33551,69 +29793,46 @@ var PageBlobClient = /** @class */ (function (_super) { * @param options - Options to the Page Blob Copy Incremental operation. * @returns Response data for the Page Blob Copy Incremental operation. */ - PageBlobClient.prototype.startCopyIncremental = function (copySource, options) { + async startCopyIncremental(copySource, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_44; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("PageBlobClient-startCopyIncremental", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext.copyIncremental(copySource, tslib.__assign({ abortSignal: options.abortSignal, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_44 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_44.message - }); - throw e_44; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("PageBlobClient-startCopyIncremental", options); + try { + return await this.pageBlobContext.copyIncremental(copySource, Object.assign({ abortSignal: options.abortSignal, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; - return PageBlobClient; -}(BlobClient)); + throw e; + } + finally { + span.end(); + } + } +} // Copyright (c) Microsoft Corporation. -function getBodyAsText(batchResponse) { - return tslib.__awaiter(this, void 0, void 0, function () { - var buffer, responseLength; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - buffer = Buffer.alloc(BATCH_MAX_PAYLOAD_IN_BYTES); - return [4 /*yield*/, streamToBuffer2(batchResponse.readableStreamBody, buffer)]; - case 1: - responseLength = _a.sent(); - // Slice the buffer to trim the empty ending. - buffer = buffer.slice(0, responseLength); - return [2 /*return*/, buffer.toString()]; - } - }); - }); +async function getBodyAsText(batchResponse) { + let buffer = Buffer.alloc(BATCH_MAX_PAYLOAD_IN_BYTES); + const responseLength = await streamToBuffer2(batchResponse.readableStreamBody, buffer); + // Slice the buffer to trim the empty ending. + buffer = buffer.slice(0, responseLength); + return buffer.toString(); } function utf8ByteLength(str) { return Buffer.byteLength(str); } // Copyright (c) Microsoft Corporation. -var HTTP_HEADER_DELIMITER = ": "; -var SPACE_DELIMITER = " "; -var NOT_FOUND = -1; +const HTTP_HEADER_DELIMITER = ": "; +const SPACE_DELIMITER = " "; +const NOT_FOUND = -1; /** * Util class for parsing batch response. */ -var BatchResponseParser = /** @class */ (function () { - function BatchResponseParser(batchResponse, subRequests) { +class BatchResponseParser { + constructor(batchResponse, subRequests) { if (!batchResponse || !batchResponse.contentType) { // In special case(reported), server may return invalid content-type which could not be parsed. throw new RangeError("batchResponse is malformed or doesn't contain valid content-type."); @@ -33625,129 +29844,119 @@ var BatchResponseParser = /** @class */ (function () { this.batchResponse = batchResponse; this.subRequests = subRequests; this.responseBatchBoundary = this.batchResponse.contentType.split("=")[1]; - this.perResponsePrefix = "--" + this.responseBatchBoundary + HTTP_LINE_ENDING; - this.batchResponseEnding = "--" + this.responseBatchBoundary + "--"; + this.perResponsePrefix = `--${this.responseBatchBoundary}${HTTP_LINE_ENDING}`; + this.batchResponseEnding = `--${this.responseBatchBoundary}--`; } // For example of response, please refer to https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#response - BatchResponseParser.prototype.parseBatchResponse = function () { - return tslib.__awaiter(this, void 0, void 0, function () { - var responseBodyAsText, subResponses, subResponseCount, deserializedSubResponses, subResponsesSucceededCount, subResponsesFailedCount, index, subResponse, deserializedSubResponse, responseLines, subRespHeaderStartFound, subRespHeaderEndFound, subRespFailed, contentId, _i, responseLines_1, responseLine, tokens, tokens; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - // When logic reach here, suppose batch request has already succeeded with 202, so we can further parse - // sub request's response. - if (this.batchResponse._response.status != HTTPURLConnection.HTTP_ACCEPTED) { - throw new Error("Invalid state: batch request failed with status: '" + this.batchResponse._response.status + "'."); - } - return [4 /*yield*/, getBodyAsText(this.batchResponse)]; - case 1: - responseBodyAsText = _a.sent(); - subResponses = responseBodyAsText - .split(this.batchResponseEnding)[0] // string after ending is useless - .split(this.perResponsePrefix) - .slice(1); - subResponseCount = subResponses.length; - // Defensive coding in case of potential error parsing. - // Note: subResponseCount == 1 is special case where sub request is invalid. - // We try to prevent such cases through early validation, e.g. validate sub request count >= 1. - // While in unexpected sub request invalid case, we allow sub response to be parsed and return to user. - if (subResponseCount != this.subRequests.size && subResponseCount != 1) { - throw new Error("Invalid state: sub responses' count is not equal to sub requests' count."); - } - deserializedSubResponses = new Array(subResponseCount); - subResponsesSucceededCount = 0; - subResponsesFailedCount = 0; - // Parse sub subResponses. - for (index = 0; index < subResponseCount; index++) { - subResponse = subResponses[index]; - deserializedSubResponse = {}; - deserializedSubResponse.headers = new coreHttp.HttpHeaders(); - responseLines = subResponse.split("" + HTTP_LINE_ENDING); - subRespHeaderStartFound = false; - subRespHeaderEndFound = false; - subRespFailed = false; - contentId = NOT_FOUND; - for (_i = 0, responseLines_1 = responseLines; _i < responseLines_1.length; _i++) { - responseLine = responseLines_1[_i]; - if (!subRespHeaderStartFound) { - // Convention line to indicate content ID - if (responseLine.startsWith(HeaderConstants.CONTENT_ID)) { - contentId = parseInt(responseLine.split(HTTP_HEADER_DELIMITER)[1]); - } - // Http version line with status code indicates the start of sub request's response. - // Example: HTTP/1.1 202 Accepted - if (responseLine.startsWith(HTTP_VERSION_1_1)) { - subRespHeaderStartFound = true; - tokens = responseLine.split(SPACE_DELIMITER); - deserializedSubResponse.status = parseInt(tokens[1]); - deserializedSubResponse.statusMessage = tokens.slice(2).join(SPACE_DELIMITER); - } - continue; // Skip convention headers not specifically for sub request i.e. Content-Type: application/http and Content-ID: * - } - if (responseLine.trim() === "") { - // Sub response's header start line already found, and the first empty line indicates header end line found. - if (!subRespHeaderEndFound) { - subRespHeaderEndFound = true; - } - continue; // Skip empty line - } - // Note: when code reach here, it indicates subRespHeaderStartFound == true - if (!subRespHeaderEndFound) { - if (responseLine.indexOf(HTTP_HEADER_DELIMITER) === -1) { - // Defensive coding to prevent from missing valuable lines. - throw new Error("Invalid state: find non-empty line '" + responseLine + "' without HTTP header delimiter '" + HTTP_HEADER_DELIMITER + "'."); - } - tokens = responseLine.split(HTTP_HEADER_DELIMITER); - deserializedSubResponse.headers.set(tokens[0], tokens[1]); - if (tokens[0] === HeaderConstants.X_MS_ERROR_CODE) { - deserializedSubResponse.errorCode = tokens[1]; - subRespFailed = true; - } - } - else { - // Assemble body of sub response. - if (!deserializedSubResponse.bodyAsText) { - deserializedSubResponse.bodyAsText = ""; - } - 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) { - 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++; - } - else { - subResponsesSucceededCount++; - } - } - return [2 /*return*/, { - subResponses: deserializedSubResponses, - subResponsesSucceededCount: subResponsesSucceededCount, - subResponsesFailedCount: subResponsesFailedCount - }]; + async parseBatchResponse() { + // When logic reach here, suppose batch request has already succeeded with 202, so we can further parse + // sub request's response. + if (this.batchResponse._response.status !== HTTPURLConnection.HTTP_ACCEPTED) { + throw new Error(`Invalid state: batch request failed with status: '${this.batchResponse._response.status}'.`); + } + const responseBodyAsText = await getBodyAsText(this.batchResponse); + const subResponses = responseBodyAsText + .split(this.batchResponseEnding)[0] // string after ending is useless + .split(this.perResponsePrefix) + .slice(1); // string before first response boundary is useless + const subResponseCount = subResponses.length; + // Defensive coding in case of potential error parsing. + // Note: subResponseCount == 1 is special case where sub request is invalid. + // We try to prevent such cases through early validation, e.g. validate sub request count >= 1. + // While in unexpected sub request invalid case, we allow sub response to be parsed and return to user. + if (subResponseCount !== this.subRequests.size && subResponseCount !== 1) { + throw new Error("Invalid state: sub responses' count is not equal to sub requests' count."); + } + const deserializedSubResponses = new Array(subResponseCount); + let subResponsesSucceededCount = 0; + let subResponsesFailedCount = 0; + // Parse sub subResponses. + for (let index = 0; index < subResponseCount; index++) { + const subResponse = subResponses[index]; + const deserializedSubResponse = {}; + deserializedSubResponse.headers = new coreHttp.HttpHeaders(); + const responseLines = subResponse.split(`${HTTP_LINE_ENDING}`); + let subRespHeaderStartFound = false; + let subRespHeaderEndFound = false; + let subRespFailed = false; + let contentId = NOT_FOUND; + for (const responseLine of responseLines) { + if (!subRespHeaderStartFound) { + // Convention line to indicate content ID + if (responseLine.startsWith(HeaderConstants.CONTENT_ID)) { + contentId = parseInt(responseLine.split(HTTP_HEADER_DELIMITER)[1]); + } + // Http version line with status code indicates the start of sub request's response. + // Example: HTTP/1.1 202 Accepted + if (responseLine.startsWith(HTTP_VERSION_1_1)) { + subRespHeaderStartFound = true; + const tokens = responseLine.split(SPACE_DELIMITER); + deserializedSubResponse.status = parseInt(tokens[1]); + deserializedSubResponse.statusMessage = tokens.slice(2).join(SPACE_DELIMITER); + } + continue; // Skip convention headers not specifically for sub request i.e. Content-Type: application/http and Content-ID: * } - }); - }); - }; - return BatchResponseParser; -}()); + if (responseLine.trim() === "") { + // Sub response's header start line already found, and the first empty line indicates header end line found. + if (!subRespHeaderEndFound) { + subRespHeaderEndFound = true; + } + continue; // Skip empty line + } + // Note: when code reach here, it indicates subRespHeaderStartFound == true + if (!subRespHeaderEndFound) { + if (responseLine.indexOf(HTTP_HEADER_DELIMITER) === -1) { + // Defensive coding to prevent from missing valuable lines. + throw new Error(`Invalid state: find non-empty line '${responseLine}' without HTTP header delimiter '${HTTP_HEADER_DELIMITER}'.`); + } + // Parse headers of sub response. + const tokens = responseLine.split(HTTP_HEADER_DELIMITER); + deserializedSubResponse.headers.set(tokens[0], tokens[1]); + if (tokens[0] === HeaderConstants.X_MS_ERROR_CODE) { + deserializedSubResponse.errorCode = tokens[1]; + subRespFailed = true; + } + } + else { + // Assemble body of sub response. + if (!deserializedSubResponse.bodyAsText) { + deserializedSubResponse.bodyAsText = ""; + } + 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) { + 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++; + } + else { + subResponsesSucceededCount++; + } + } + return { + subResponses: deserializedSubResponses, + subResponsesSucceededCount: subResponsesSucceededCount, + subResponsesFailedCount: subResponsesFailedCount + }; + } +} // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. var MutexLockStatus; (function (MutexLockStatus) { MutexLockStatus[MutexLockStatus["LOCKED"] = 0] = "LOCKED"; @@ -33756,82 +29965,68 @@ var MutexLockStatus; /** * An async mutex lock. */ -var Mutex = /** @class */ (function () { - function Mutex() { - } +class Mutex { /** * Lock for a specific key. If the lock has been acquired by another customer, then * will wait until getting the lock. * * @param key - lock key */ - Mutex.lock = function (key) { - return tslib.__awaiter(this, void 0, void 0, function () { - var _this = this; - return tslib.__generator(this, function (_a) { - return [2 /*return*/, new Promise(function (resolve) { - if (_this.keys[key] === undefined || _this.keys[key] === MutexLockStatus.UNLOCKED) { - _this.keys[key] = MutexLockStatus.LOCKED; - resolve(); - } - else { - _this.onUnlockEvent(key, function () { - _this.keys[key] = MutexLockStatus.LOCKED; - resolve(); - }); - } - })]; - }); + static async lock(key) { + return new Promise((resolve) => { + if (this.keys[key] === undefined || this.keys[key] === MutexLockStatus.UNLOCKED) { + this.keys[key] = MutexLockStatus.LOCKED; + resolve(); + } + else { + this.onUnlockEvent(key, () => { + this.keys[key] = MutexLockStatus.LOCKED; + resolve(); + }); + } }); - }; + } /** * Unlock a key. * * @param key - */ - Mutex.unlock = function (key) { - return tslib.__awaiter(this, void 0, void 0, function () { - var _this = this; - return tslib.__generator(this, function (_a) { - return [2 /*return*/, new Promise(function (resolve) { - if (_this.keys[key] === MutexLockStatus.LOCKED) { - _this.emitUnlockEvent(key); - } - delete _this.keys[key]; - resolve(); - })]; - }); + static async unlock(key) { + return new Promise((resolve) => { + if (this.keys[key] === MutexLockStatus.LOCKED) { + this.emitUnlockEvent(key); + } + delete this.keys[key]; + resolve(); }); - }; - Mutex.onUnlockEvent = function (key, handler) { + } + static onUnlockEvent(key, handler) { if (this.listeners[key] === undefined) { this.listeners[key] = [handler]; } else { this.listeners[key].push(handler); } - }; - Mutex.emitUnlockEvent = function (key) { - var _this = this; + } + static emitUnlockEvent(key) { if (this.listeners[key] !== undefined && this.listeners[key].length > 0) { - var handler_1 = this.listeners[key].shift(); - setImmediate(function () { - handler_1.call(_this); + const handler = this.listeners[key].shift(); + setImmediate(() => { + handler.call(this); }); } - }; - Mutex.keys = {}; - Mutex.listeners = {}; - return Mutex; -}()); + } +} +Mutex.keys = {}; +Mutex.listeners = {}; // Copyright (c) Microsoft Corporation. /** * A BlobBatch represents an aggregated set of operations on blobs. * Currently, only `delete` and `setAccessTier` are supported. */ -var BlobBatch = /** @class */ (function () { - function BlobBatch() { +class BlobBatch { + constructor() { this.batch = "batch"; this.batchRequest = new InnerBatchRequest(); } @@ -33840,203 +30035,151 @@ var BlobBatch = /** @class */ (function () { * The value must be multipart/mixed with a batch boundary. * Example: multipart/mixed; boundary=batch_a81786c8-e301-4e42-a729-a32ca24ae252 */ - BlobBatch.prototype.getMultiPartContentType = function () { + getMultiPartContentType() { return this.batchRequest.getMultipartContentType(); - }; + } /** * Get assembled HTTP request body for sub requests. */ - BlobBatch.prototype.getHttpRequestBody = function () { + getHttpRequestBody() { return this.batchRequest.getHttpRequestBody(); - }; + } /** * Get sub requests that are added into the batch request. */ - BlobBatch.prototype.getSubRequests = function () { + getSubRequests() { return this.batchRequest.getSubRequests(); - }; - BlobBatch.prototype.addSubRequestInternal = function (subRequest, assembleSubRequestFunc) { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, Mutex.lock(this.batch)]; - case 1: - _a.sent(); - _a.label = 2; - case 2: - _a.trys.push([2, , 4, 6]); - this.batchRequest.preAddSubRequest(subRequest); - return [4 /*yield*/, assembleSubRequestFunc()]; - case 3: - _a.sent(); - this.batchRequest.postAddSubRequest(subRequest); - return [3 /*break*/, 6]; - case 4: return [4 /*yield*/, Mutex.unlock(this.batch)]; - case 5: - _a.sent(); - return [7 /*endfinally*/]; - case 6: return [2 /*return*/]; - } - }); - }); - }; - BlobBatch.prototype.setBatchType = function (batchType) { + } + async addSubRequestInternal(subRequest, assembleSubRequestFunc) { + await Mutex.lock(this.batch); + try { + this.batchRequest.preAddSubRequest(subRequest); + await assembleSubRequestFunc(); + this.batchRequest.postAddSubRequest(subRequest); + } + finally { + await Mutex.unlock(this.batch); + } + } + setBatchType(batchType) { if (!this.batchType) { this.batchType = batchType; } if (this.batchType !== batchType) { - throw new RangeError("BlobBatch only supports one operation type per batch and it already is being used for " + this.batchType + " operations."); + throw new RangeError(`BlobBatch only supports one operation type per batch and it already is being used for ${this.batchType} operations.`); } - }; - BlobBatch.prototype.deleteBlob = function (urlOrBlobClient, credentialOrOptions, options) { - return tslib.__awaiter(this, void 0, void 0, function () { - var url, credential, _a, span, updatedOptions, e_1; - var _this = this; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (typeof urlOrBlobClient === "string" && - ((coreHttp.isNode && credentialOrOptions instanceof StorageSharedKeyCredential) || - credentialOrOptions instanceof AnonymousCredential || - coreHttp.isTokenCredential(credentialOrOptions))) { - // First overload - url = urlOrBlobClient; - credential = credentialOrOptions; - } - else if (urlOrBlobClient instanceof BlobClient) { - // Second overload - url = urlOrBlobClient.url; - credential = urlOrBlobClient.credential; - options = credentialOrOptions; - } - else { - throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); - } - if (!options) { - options = {}; - } - _a = createSpan("BatchDeleteRequest-addSubRequest", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - this.setBatchType("delete"); - return [4 /*yield*/, this.addSubRequestInternal({ - url: url, - credential: credential - }, function () { return tslib.__awaiter(_this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, new BlobClient(url, this.batchRequest.createPipeline(credential)).delete(updatedOptions)]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); })]; - case 2: - _b.sent(); - return [3 /*break*/, 5]; - case 3: - e_1 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_1.message - }); - throw e_1; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + } + async deleteBlob(urlOrBlobClient, credentialOrOptions, options) { + let url; + let credential; + if (typeof urlOrBlobClient === "string" && + ((coreHttp.isNode && credentialOrOptions instanceof StorageSharedKeyCredential) || + credentialOrOptions instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrOptions))) { + // First overload + url = urlOrBlobClient; + credential = credentialOrOptions; + } + else if (urlOrBlobClient instanceof BlobClient) { + // Second overload + url = urlOrBlobClient.url; + credential = urlOrBlobClient.credential; + options = credentialOrOptions; + } + else { + throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + } + if (!options) { + options = {}; + } + const { span, updatedOptions } = createSpan("BatchDeleteRequest-addSubRequest", options); + try { + this.setBatchType("delete"); + await this.addSubRequestInternal({ + url: url, + credential: credential + }, async () => { + await new BlobClient(url, this.batchRequest.createPipeline(credential)).delete(updatedOptions); }); - }); - }; - BlobBatch.prototype.setBlobAccessTier = function (urlOrBlobClient, credentialOrTier, tierOrOptions, options) { - return tslib.__awaiter(this, void 0, void 0, function () { - var url, credential, tier, _a, span, updatedOptions, e_2; - var _this = this; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (typeof urlOrBlobClient === "string" && - ((coreHttp.isNode && credentialOrTier instanceof StorageSharedKeyCredential) || - credentialOrTier instanceof AnonymousCredential || - coreHttp.isTokenCredential(credentialOrTier))) { - // First overload - url = urlOrBlobClient; - credential = credentialOrTier; - tier = tierOrOptions; - } - else if (urlOrBlobClient instanceof BlobClient) { - // Second overload - url = urlOrBlobClient.url; - credential = urlOrBlobClient.credential; - tier = credentialOrTier; - options = tierOrOptions; - } - else { - throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); - } - if (!options) { - options = {}; - } - _a = createSpan("BatchSetTierRequest-addSubRequest", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - this.setBatchType("setAccessTier"); - return [4 /*yield*/, this.addSubRequestInternal({ - url: url, - credential: credential - }, function () { return tslib.__awaiter(_this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, new BlobClient(url, this.batchRequest.createPipeline(credential)).setAccessTier(tier, updatedOptions)]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); })]; - case 2: - _b.sent(); - return [3 /*break*/, 5]; - case 3: - e_2 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_2.message - }); - throw e_2; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; - return BlobBatch; -}()); + throw e; + } + finally { + span.end(); + } + } + async setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options) { + let url; + let credential; + let tier; + if (typeof urlOrBlobClient === "string" && + ((coreHttp.isNode && credentialOrTier instanceof StorageSharedKeyCredential) || + credentialOrTier instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrTier))) { + // First overload + url = urlOrBlobClient; + credential = credentialOrTier; + tier = tierOrOptions; + } + else if (urlOrBlobClient instanceof BlobClient) { + // Second overload + url = urlOrBlobClient.url; + credential = urlOrBlobClient.credential; + tier = credentialOrTier; + options = tierOrOptions; + } + else { + throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + } + if (!options) { + options = {}; + } + const { span, updatedOptions } = createSpan("BatchSetTierRequest-addSubRequest", options); + try { + this.setBatchType("setAccessTier"); + await this.addSubRequestInternal({ + url: url, + credential: credential + }, async () => { + await new BlobClient(url, this.batchRequest.createPipeline(credential)).setAccessTier(tier, updatedOptions); + }); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message + }); + throw e; + } + finally { + span.end(); + } + } +} /** * Inner batch request class which is responsible for assembling and serializing sub requests. * See https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#request-body for how requests are assembled. */ -var InnerBatchRequest = /** @class */ (function () { - function InnerBatchRequest() { +class InnerBatchRequest { + constructor() { this.operationCount = 0; this.body = ""; - var tempGuid = coreHttp.generateUuid(); + const tempGuid = coreHttp.generateUuid(); // batch_{batchid} - this.boundary = "batch_" + tempGuid; + this.boundary = `batch_${tempGuid}`; // --batch_{batchid} // Content-Type: application/http // Content-Transfer-Encoding: binary - this.subRequestPrefix = "--" + this.boundary + HTTP_LINE_ENDING + HeaderConstants.CONTENT_TYPE + ": application/http" + HTTP_LINE_ENDING + HeaderConstants.CONTENT_TRANSFER_ENCODING + ": binary"; + this.subRequestPrefix = `--${this.boundary}${HTTP_LINE_ENDING}${HeaderConstants.CONTENT_TYPE}: application/http${HTTP_LINE_ENDING}${HeaderConstants.CONTENT_TRANSFER_ENCODING}: binary`; // multipart/mixed; boundary=batch_{batchid} - this.multipartContentType = "multipart/mixed; boundary=" + this.boundary; + this.multipartContentType = `multipart/mixed; boundary=${this.boundary}`; // --batch_{batchid}-- - this.batchRequestEnding = "--" + this.boundary + "--"; + this.batchRequestEnding = `--${this.boundary}--`; this.subRequests = new Map(); } /** @@ -34046,10 +30189,10 @@ var InnerBatchRequest = /** @class */ (function () { * and intercept request from going to wire. * @param credential - Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the `@azure/identity` package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used. */ - InnerBatchRequest.prototype.createPipeline = function (credential) { - var isAnonymousCreds = credential instanceof AnonymousCredential; - var policyFactoryLength = 3 + (isAnonymousCreds ? 0 : 1); // [deserializationPolicy, BatchHeaderFilterPolicyFactory, (Optional)Credential, BatchRequestAssemblePolicyFactory] - var factories = new Array(policyFactoryLength); + createPipeline(credential) { + const isAnonymousCreds = credential instanceof AnonymousCredential; + const policyFactoryLength = 3 + (isAnonymousCreds ? 0 : 1); // [deserializationPolicy, BatchHeaderFilterPolicyFactory, (Optional)Credential, BatchRequestAssemblePolicyFactory] + const factories = new Array(policyFactoryLength); factories[0] = coreHttp.deserializationPolicy(); // Default deserializationPolicy is provided by protocol layer factories[1] = new BatchHeaderFilterPolicyFactory(); // Use batch header filter policy to exclude unnecessary headers if (!isAnonymousCreds) { @@ -34059,117 +30202,94 @@ var InnerBatchRequest = /** @class */ (function () { } factories[policyFactoryLength - 1] = new BatchRequestAssemblePolicyFactory(this); // Use batch assemble policy to assemble request and intercept request from going to wire return new Pipeline(factories, {}); - }; - InnerBatchRequest.prototype.appendSubRequestToBody = function (request) { + } + appendSubRequestToBody(request) { // Start to assemble sub request this.body += [ this.subRequestPrefix, - HeaderConstants.CONTENT_ID + ": " + this.operationCount, + `${HeaderConstants.CONTENT_ID}: ${this.operationCount}`, "", - request.method.toString() + " " + getURLPathAndQuery(request.url) + " " + HTTP_VERSION_1_1 + HTTP_LINE_ENDING // sub request start line with method + `${request.method.toString()} ${getURLPathAndQuery(request.url)} ${HTTP_VERSION_1_1}${HTTP_LINE_ENDING}` // sub request start line with method ].join(HTTP_LINE_ENDING); - for (var _i = 0, _a = request.headers.headersArray(); _i < _a.length; _i++) { - var header = _a[_i]; - this.body += header.name + ": " + header.value + HTTP_LINE_ENDING; + for (const header of request.headers.headersArray()) { + this.body += `${header.name}: ${header.value}${HTTP_LINE_ENDING}`; } this.body += HTTP_LINE_ENDING; // sub request's headers need be ending with an empty line // No body to assemble for current batch request support // End to assemble sub request - }; - InnerBatchRequest.prototype.preAddSubRequest = function (subRequest) { + } + preAddSubRequest(subRequest) { if (this.operationCount >= BATCH_MAX_REQUEST) { - throw new RangeError("Cannot exceed " + BATCH_MAX_REQUEST + " sub requests in a single batch"); + throw new RangeError(`Cannot exceed ${BATCH_MAX_REQUEST} sub requests in a single batch`); } // Fast fail if url for sub request is invalid - var path = getURLPath(subRequest.url); - if (!path || path == "") { - throw new RangeError("Invalid url for sub request: '" + subRequest.url + "'"); + const path = getURLPath(subRequest.url); + if (!path || path === "") { + throw new RangeError(`Invalid url for sub request: '${subRequest.url}'`); } - }; - InnerBatchRequest.prototype.postAddSubRequest = function (subRequest) { + } + postAddSubRequest(subRequest) { this.subRequests.set(this.operationCount, subRequest); this.operationCount++; - }; + } // Return the http request body with assembling the ending line to the sub request body. - InnerBatchRequest.prototype.getHttpRequestBody = function () { - return "" + this.body + this.batchRequestEnding + HTTP_LINE_ENDING; - }; - InnerBatchRequest.prototype.getMultipartContentType = function () { + getHttpRequestBody() { + return `${this.body}${this.batchRequestEnding}${HTTP_LINE_ENDING}`; + } + getMultipartContentType() { return this.multipartContentType; - }; - InnerBatchRequest.prototype.getSubRequests = function () { + } + getSubRequests() { return this.subRequests; - }; - return InnerBatchRequest; -}()); -var BatchRequestAssemblePolicy = /** @class */ (function (_super) { - tslib.__extends(BatchRequestAssemblePolicy, _super); - function BatchRequestAssemblePolicy(batchRequest, nextPolicy, options) { - var _this = _super.call(this, nextPolicy, options) || this; - _this.dummyResponse = { + } +} +class BatchRequestAssemblePolicy extends coreHttp.BaseRequestPolicy { + constructor(batchRequest, nextPolicy, options) { + super(nextPolicy, options); + this.dummyResponse = { request: new coreHttp.WebResource(), status: 200, headers: new coreHttp.HttpHeaders() }; - _this.batchRequest = batchRequest; - return _this; - } - BatchRequestAssemblePolicy.prototype.sendRequest = function (request) { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.batchRequest.appendSubRequestToBody(request)]; - case 1: - _a.sent(); - return [2 /*return*/, this.dummyResponse]; // Intercept request from going to wire - } - }); - }); - }; - return BatchRequestAssemblePolicy; -}(coreHttp.BaseRequestPolicy)); -var BatchRequestAssemblePolicyFactory = /** @class */ (function () { - function BatchRequestAssemblePolicyFactory(batchRequest) { this.batchRequest = batchRequest; } - BatchRequestAssemblePolicyFactory.prototype.create = function (nextPolicy, options) { + async sendRequest(request) { + await this.batchRequest.appendSubRequestToBody(request); + return this.dummyResponse; // Intercept request from going to wire + } +} +class BatchRequestAssemblePolicyFactory { + constructor(batchRequest) { + this.batchRequest = batchRequest; + } + create(nextPolicy, options) { return new BatchRequestAssemblePolicy(this.batchRequest, nextPolicy, options); - }; - return BatchRequestAssemblePolicyFactory; -}()); -var BatchHeaderFilterPolicy = /** @class */ (function (_super) { - tslib.__extends(BatchHeaderFilterPolicy, _super); - function BatchHeaderFilterPolicy(nextPolicy, options) { - return _super.call(this, nextPolicy, options) || this; } - BatchHeaderFilterPolicy.prototype.sendRequest = function (request) { - return tslib.__awaiter(this, void 0, void 0, function () { - var xMsHeaderName, _i, _a, header; - return tslib.__generator(this, function (_b) { - xMsHeaderName = ""; - for (_i = 0, _a = request.headers.headersArray(); _i < _a.length; _i++) { - header = _a[_i]; - if (iEqual(header.name, HeaderConstants.X_MS_VERSION)) { - xMsHeaderName = header.name; - } - } - if (xMsHeaderName !== "") { - 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() { +} +class BatchHeaderFilterPolicy extends coreHttp.BaseRequestPolicy { + // The base class has a protected constructor. Adding a public one to enable constructing of this class. + /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ + constructor(nextPolicy, options) { + super(nextPolicy, options); } - BatchHeaderFilterPolicyFactory.prototype.create = function (nextPolicy, options) { + async sendRequest(request) { + let xMsHeaderName = ""; + for (const header of request.headers.headersArray()) { + if (iEqual(header.name, HeaderConstants.X_MS_VERSION)) { + xMsHeaderName = header.name; + } + } + if (xMsHeaderName !== "") { + request.headers.remove(xMsHeaderName); // The subrequests should not have the x-ms-version header. + } + return this._nextPolicy.sendRequest(request); + } +} +class BatchHeaderFilterPolicyFactory { + create(nextPolicy, options) { return new BatchHeaderFilterPolicy(nextPolicy, options); - }; - return BatchHeaderFilterPolicyFactory; -}()); + } +} // Copyright (c) Microsoft Corporation. /** @@ -34177,10 +30297,13 @@ var BatchHeaderFilterPolicyFactory = /** @class */ (function () { * * @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) { +class BlobBatchClient { + constructor(url, credentialOrPipeline, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { + let pipeline; + if (isPipelineLike(credentialOrPipeline)) { pipeline = credentialOrPipeline; } else if (!credentialOrPipeline) { @@ -34190,8 +30313,8 @@ var BlobBatchClient = /** @class */ (function () { else { pipeline = newPipeline(credentialOrPipeline, options); } - var storageClientContext = new StorageClientContext(url, pipeline.toServiceClientOptions()); - var path = getURLPath(url); + const storageClientContext = new StorageClientContext(url, pipeline.toServiceClientOptions()); + const path = getURLPath(url); if (path && path !== "/") { // Container scoped. this.serviceOrContainerContext = new Container(storageClientContext); @@ -34204,67 +30327,39 @@ var BlobBatchClient = /** @class */ (function () { * Creates a {@link BlobBatch}. * A BlobBatch represents an aggregated set of operations on blobs. */ - BlobBatchClient.prototype.createBatch = function () { + createBatch() { 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)]; - } - }); - }); - }; + } + async deleteBlobs(urlsOrBlobClients, credentialOrOptions, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { + const batch = new BlobBatch(); + for (const urlOrBlobClient of urlsOrBlobClients) { + if (typeof urlOrBlobClient === "string") { + await batch.deleteBlob(urlOrBlobClient, credentialOrOptions, options); + } + else { + await batch.deleteBlob(urlOrBlobClient, credentialOrOptions); + } + } + return this.submitBatch(batch); + } + async setBlobsAccessTier(urlsOrBlobClients, credentialOrTier, tierOrOptions, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { + const batch = new BlobBatch(); + for (const urlOrBlobClient of urlsOrBlobClients) { + if (typeof urlOrBlobClient === "string") { + await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options); + } + else { + await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions); + } + } + return this.submitBatch(batch); + } /** * Submit batch request which consists of multiple subrequests. * @@ -34300,69 +30395,56 @@ var BlobBatchClient = /** @class */ (function () { * @param batchRequest - A set of Delete or SetTier operations. * @param options - */ - BlobBatchClient.prototype.submitBatch = function (batchRequest, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, 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), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 4, 5, 6]); - batchRequestBody = batchRequest.getHttpRequestBody(); - return [4 /*yield*/, this.serviceOrContainerContext.submitBatch(utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), batchRequestBody, tslib.__assign(tslib.__assign({}, options), convertTracingToRequestOptionsBase(updatedOptions)))]; - 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: coreTracing.SpanStatusCode.ERROR, - message: e_1.message - }); - throw e_1; - case 5: - span.end(); - return [7 /*endfinally*/]; - case 6: return [2 /*return*/]; - } + async submitBatch(batchRequest, options = {}) { + if (!batchRequest || batchRequest.getSubRequests().size === 0) { + throw new RangeError("Batch request should contain one or more sub requests."); + } + const { span, updatedOptions } = createSpan("BlobBatchClient-submitBatch", options); + try { + const batchRequestBody = batchRequest.getHttpRequestBody(); + // ServiceSubmitBatchResponseModel and ContainerSubmitBatchResponse are compatible for now. + const rawBatchResponse = await this.serviceOrContainerContext.submitBatch(utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), batchRequestBody, Object.assign(Object.assign({}, options), convertTracingToRequestOptionsBase(updatedOptions))); + // Parse the sub responses result, if logic reaches here(i.e. the batch request succeeded with status code 202). + const batchResponseParser = new BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests()); + const responseSummary = await batchResponseParser.parseBatchResponse(); + const 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 res; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; - return BlobBatchClient; -}()); + throw e; + } + finally { + span.end(); + } + } +} /** * A ContainerClient represents a URL to the Azure Storage container allowing you to manipulate its blobs. */ -var ContainerClient = /** @class */ (function (_super) { - tslib.__extends(ContainerClient, _super); - function ContainerClient(urlOrConnectionString, credentialOrPipelineOrContainerName, options) { - var _this = this; - var pipeline; - var url; +class ContainerClient extends StorageClient { + constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { + let pipeline; + let url; options = options || {}; - if (credentialOrPipelineOrContainerName instanceof Pipeline) { + if (isPipelineLike(credentialOrPipelineOrContainerName)) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; @@ -34384,11 +30466,11 @@ var ContainerClient = /** @class */ (function (_super) { else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) - var containerName = credentialOrPipelineOrContainerName; - var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + const containerName = credentialOrPipelineOrContainerName; + const extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); url = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)); options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); pipeline = newPipeline(sharedKeyCredential, options); @@ -34408,21 +30490,16 @@ var ContainerClient = /** @class */ (function (_super) { else { throw new Error("Expecting non-empty strings for containerName parameter"); } - _this = _super.call(this, url, pipeline) || this; - _this._containerName = _this.getContainerNameFromUrl(); - _this.containerContext = new Container(_this.storageClientContext); - return _this; + super(url, pipeline); + this._containerName = this.getContainerNameFromUrl(); + this.containerContext = new Container(this.storageClientContext); + } + /** + * The name of the container. + */ + get containerName() { + return this._containerName; } - Object.defineProperty(ContainerClient.prototype, "containerName", { - /** - * The name of the container. - */ - get: function () { - return this._containerName; - }, - enumerable: false, - configurable: true - }); /** * Creates a new container under the specified account. If the container with * the same name already exists, the operation fails. @@ -34439,37 +30516,24 @@ var ContainerClient = /** @class */ (function (_super) { * console.log("Container was created successfully", createContainerResponse.requestId); * ``` */ - ContainerClient.prototype.create = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_1; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("ContainerClient-create", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.create(tslib.__assign(tslib.__assign({}, options), convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: - // Spread operator in destructuring assignments, - // this will filter out unwanted properties from the response object into result object - return [2 /*return*/, _b.sent()]; - case 3: - e_1 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_1.message - }); - throw e_1; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async create(options = {}) { + const { span, updatedOptions } = createSpan("ContainerClient-create", options); + try { + // Spread operator in destructuring assignments, + // this will filter out unwanted properties from the response object into result object + return await this.containerContext.create(Object.assign(Object.assign({}, options), convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Creates a new container under the specified account. If the container with * the same name already exists, it is not changed. @@ -34477,45 +30541,32 @@ var ContainerClient = /** @class */ (function (_super) { * * @param options - */ - ContainerClient.prototype.createIfNotExists = function (options) { + async createIfNotExists(options = {}) { var _a, _b; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _c, span, updatedOptions, res, e_2; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _c = createSpan("ContainerClient-createIfNotExists", options), span = _c.span, updatedOptions = _c.updatedOptions; - _d.label = 1; - case 1: - _d.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.create(updatedOptions)]; - case 2: - res = _d.sent(); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable - })]; - case 3: - e_2 = _d.sent(); - if (((_a = e_2.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerAlreadyExists") { - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: "Expected exception when creating a container only if it does not already exist." - }); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_2.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_2.response })]; - } - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_2.message - }); - throw e_2; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("ContainerClient-createIfNotExists", options); + try { + const res = await this.create(updatedOptions); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable + }); + } + catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerAlreadyExists") { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: "Expected exception when creating a container only if it does not already exist." + }); + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Returns true if the Azure container resource represented by this client exists; false otherwise. * @@ -34525,63 +30576,50 @@ var ContainerClient = /** @class */ (function (_super) { * * @param options - */ - ContainerClient.prototype.exists = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_3; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("ContainerClient-exists", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.getProperties({ - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - })]; - case 2: - _b.sent(); - return [2 /*return*/, true]; - case 3: - e_3 = _b.sent(); - if (e_3.statusCode === 404) { - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: "Expected exception when checking container existence" - }); - return [2 /*return*/, false]; - } - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_3.message - }); - throw e_3; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async exists(options = {}) { + const { span, updatedOptions } = createSpan("ContainerClient-exists", options); + try { + await this.getProperties({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions }); - }); - }; + return true; + } + catch (e) { + if (e.statusCode === 404) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: "Expected exception when checking container existence" + }); + return false; + } + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message + }); + throw e; + } + finally { + span.end(); + } + } /** * Creates a {@link BlobClient} * * @param blobName - A blob name * @returns A new BlobClient object for the given blob name. */ - ContainerClient.prototype.getBlobClient = function (blobName) { + getBlobClient(blobName) { return new BlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); - }; + } /** * Creates an {@link AppendBlobClient} * * @param blobName - An append blob name */ - ContainerClient.prototype.getAppendBlobClient = function (blobName) { + getAppendBlobClient(blobName) { return new AppendBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); - }; + } /** * Creates a {@link BlockBlobClient} * @@ -34597,17 +30635,17 @@ var ContainerClient = /** @class */ (function (_super) { * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); * ``` */ - ContainerClient.prototype.getBlockBlobClient = function (blobName) { + getBlockBlobClient(blobName) { return new BlockBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); - }; + } /** * Creates a {@link PageBlobClient} * * @param blobName - A page blob name */ - ContainerClient.prototype.getPageBlobClient = function (blobName) { + getPageBlobClient(blobName) { return new PageBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); - }; + } /** * Returns all user-defined metadata and system properties for the specified * container. The data returned does not include the container's list of blobs. @@ -34620,37 +30658,25 @@ var ContainerClient = /** @class */ (function (_super) { * * @param options - Options to Container Get Properties operation. */ - ContainerClient.prototype.getProperties = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_4; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!options.conditions) { - options.conditions = {}; - } - _a = createSpan("ContainerClient-getProperties", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.getProperties(tslib.__assign(tslib.__assign({ abortSignal: options.abortSignal }, options.conditions), convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_4 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_4.message - }); - throw e_4; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async getProperties(options = {}) { + if (!options.conditions) { + options.conditions = {}; + } + const { span, updatedOptions } = createSpan("ContainerClient-getProperties", options); + try { + return await this.containerContext.getProperties(Object.assign(Object.assign({ abortSignal: options.abortSignal }, options.conditions), convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Marks the specified container for deletion. The container and any blobs * contained within it are later deleted during garbage collection. @@ -34658,37 +30684,25 @@ var ContainerClient = /** @class */ (function (_super) { * * @param options - Options to Container Delete operation. */ - ContainerClient.prototype.delete = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_5; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!options.conditions) { - options.conditions = {}; - } - _a = createSpan("ContainerClient-delete", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.delete(tslib.__assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_5 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_5.message - }); - throw e_5; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async delete(options = {}) { + if (!options.conditions) { + options.conditions = {}; + } + const { span, updatedOptions } = createSpan("ContainerClient-delete", options); + try { + return await this.containerContext.delete(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Marks the specified container for deletion if it exists. The container and any blobs * contained within it are later deleted during garbage collection. @@ -34696,45 +30710,32 @@ var ContainerClient = /** @class */ (function (_super) { * * @param options - Options to Container Delete operation. */ - ContainerClient.prototype.deleteIfExists = function (options) { + async deleteIfExists(options = {}) { var _a, _b; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _c, span, updatedOptions, res, e_6; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _c = createSpan("ContainerClient-deleteIfExists", options), span = _c.span, updatedOptions = _c.updatedOptions; - _d.label = 1; - case 1: - _d.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.delete(updatedOptions)]; - case 2: - res = _d.sent(); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable - })]; - case 3: - e_6 = _d.sent(); - if (((_a = e_6.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerNotFound") { - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: "Expected exception when deleting a container only if it exists." - }); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_6.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_6.response })]; - } - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_6.message - }); - throw e_6; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("ContainerClient-deleteIfExists", options); + try { + const res = await this.delete(updatedOptions); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable + }); + } + catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerNotFound") { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: "Expected exception when deleting a container only if it exists." + }); + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Sets one or more user-defined name-value pairs for the specified container. * @@ -34747,40 +30748,28 @@ var ContainerClient = /** @class */ (function (_super) { * If no value provided the existing metadata will be removed. * @param options - Options to Container Set Metadata operation. */ - ContainerClient.prototype.setMetadata = function (metadata, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_7; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!options.conditions) { - options.conditions = {}; - } - if (options.conditions.ifUnmodifiedSince) { - throw new RangeError("the IfUnmodifiedSince must have their default values because they are ignored by the blob service"); - } - _a = createSpan("ContainerClient-setMetadata", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.setMetadata(tslib.__assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata: metadata, modifiedAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_7 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_7.message - }); - throw e_7; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async setMetadata(metadata, options = {}) { + if (!options.conditions) { + options.conditions = {}; + } + if (options.conditions.ifUnmodifiedSince) { + throw new RangeError("the IfUnmodifiedSince must have their default values because they are ignored by the blob service"); + } + const { span, updatedOptions } = createSpan("ContainerClient-setMetadata", options); + try { + return await this.containerContext.setMetadata(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata, modifiedAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Gets the permissions for the specified container. The permissions indicate * whether container data may be accessed publicly. @@ -34792,70 +30781,56 @@ var ContainerClient = /** @class */ (function (_super) { * * @param options - Options to Container Get Access Policy operation. */ - ContainerClient.prototype.getAccessPolicy = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, response, res, _i, response_1, identifier, accessPolicy, e_8; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!options.conditions) { - options.conditions = {}; - } - _a = createSpan("ContainerClient-getAccessPolicy", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.getAccessPolicy(tslib.__assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: - response = _b.sent(); - res = { - _response: response._response, - blobPublicAccess: response.blobPublicAccess, - date: response.date, - etag: response.etag, - errorCode: response.errorCode, - lastModified: response.lastModified, - requestId: response.requestId, - clientRequestId: response.clientRequestId, - signedIdentifiers: [], - version: response.version - }; - for (_i = 0, response_1 = response; _i < response_1.length; _i++) { - identifier = response_1[_i]; - accessPolicy = undefined; - if (identifier.accessPolicy) { - accessPolicy = { - permissions: identifier.accessPolicy.permissions - }; - if (identifier.accessPolicy.expiresOn) { - accessPolicy.expiresOn = new Date(identifier.accessPolicy.expiresOn); - } - if (identifier.accessPolicy.startsOn) { - accessPolicy.startsOn = new Date(identifier.accessPolicy.startsOn); - } - } - res.signedIdentifiers.push({ - accessPolicy: accessPolicy, - id: identifier.id - }); - } - return [2 /*return*/, res]; - case 3: - e_8 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_8.message - }); - throw e_8; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + async getAccessPolicy(options = {}) { + if (!options.conditions) { + options.conditions = {}; + } + const { span, updatedOptions } = createSpan("ContainerClient-getAccessPolicy", options); + try { + const response = await this.containerContext.getAccessPolicy(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions))); + const res = { + _response: response._response, + blobPublicAccess: response.blobPublicAccess, + date: response.date, + etag: response.etag, + errorCode: response.errorCode, + lastModified: response.lastModified, + requestId: response.requestId, + clientRequestId: response.clientRequestId, + signedIdentifiers: [], + version: response.version + }; + for (const identifier of response) { + let accessPolicy = undefined; + if (identifier.accessPolicy) { + accessPolicy = { + permissions: identifier.accessPolicy.permissions + }; + if (identifier.accessPolicy.expiresOn) { + accessPolicy.expiresOn = new Date(identifier.accessPolicy.expiresOn); + } + if (identifier.accessPolicy.startsOn) { + accessPolicy.startsOn = new Date(identifier.accessPolicy.startsOn); + } } + res.signedIdentifiers.push({ + accessPolicy, + id: identifier.id + }); + } + return res; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Sets the permissions for the specified container. The permissions indicate * whether blobs in a container may be accessed publicly. @@ -34873,60 +30848,47 @@ var ContainerClient = /** @class */ (function (_super) { * @param containerAcl - Array of elements each having a unique Id and details of the access policy. * @param options - Options to Container Set Access Policy operation. */ - ContainerClient.prototype.setAccessPolicy = function (access, containerAcl, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, acl, _i, _b, identifier, e_9; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _a = createSpan("ContainerClient-setAccessPolicy", options), span = _a.span, updatedOptions = _a.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - acl = []; - for (_i = 0, _b = containerAcl || []; _i < _b.length; _i++) { - identifier = _b[_i]; - acl.push({ - accessPolicy: { - expiresOn: identifier.accessPolicy.expiresOn - ? truncatedISO8061Date(identifier.accessPolicy.expiresOn) - : "", - permissions: identifier.accessPolicy.permissions, - startsOn: identifier.accessPolicy.startsOn - ? truncatedISO8061Date(identifier.accessPolicy.startsOn) - : "" - }, - id: identifier.id - }); - } - return [4 /*yield*/, this.containerContext.setAccessPolicy(tslib.__assign({ abortSignal: options.abortSignal, access: access, containerAcl: acl, leaseAccessConditions: options.conditions, modifiedAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_9 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_9.message - }); - throw e_9; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async setAccessPolicy(access, containerAcl, options = {}) { + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("ContainerClient-setAccessPolicy", options); + try { + const acl = []; + for (const identifier of containerAcl || []) { + acl.push({ + accessPolicy: { + expiresOn: identifier.accessPolicy.expiresOn + ? truncatedISO8061Date(identifier.accessPolicy.expiresOn) + : "", + permissions: identifier.accessPolicy.permissions, + startsOn: identifier.accessPolicy.startsOn + ? truncatedISO8061Date(identifier.accessPolicy.startsOn) + : "" + }, + id: identifier.id + }); + } + return await this.containerContext.setAccessPolicy(Object.assign({ abortSignal: options.abortSignal, access, containerAcl: acl, leaseAccessConditions: options.conditions, modifiedAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Get a {@link BlobLeaseClient} that manages leases on the container. * * @param proposeLeaseId - Initial proposed lease Id. * @returns A new BlobLeaseClient object for managing leases on the container. */ - ContainerClient.prototype.getBlobLeaseClient = function (proposeLeaseId) { + getBlobLeaseClient(proposeLeaseId) { return new BlobLeaseClient(this, proposeLeaseId); - }; + } /** * Creates a new block blob, or updates the content of an existing block blob. * @@ -34949,40 +30911,27 @@ var ContainerClient = /** @class */ (function (_super) { * @param options - Options to configure the Block Blob Upload operation. * @returns Block Blob upload response data and the corresponding BlockBlobClient instance. */ - ContainerClient.prototype.uploadBlockBlob = function (blobName, body, contentLength, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, blockBlobClient, response, e_10; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("ContainerClient-uploadBlockBlob", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - blockBlobClient = this.getBlockBlobClient(blobName); - return [4 /*yield*/, blockBlobClient.upload(body, contentLength, updatedOptions)]; - case 2: - response = _b.sent(); - return [2 /*return*/, { - blockBlobClient: blockBlobClient, - response: response - }]; - case 3: - e_10 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_10.message - }); - throw e_10; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async uploadBlockBlob(blobName, body, contentLength, options = {}) { + const { span, updatedOptions } = createSpan("ContainerClient-uploadBlockBlob", options); + try { + const blockBlobClient = this.getBlockBlobClient(blobName); + const response = await blockBlobClient.upload(body, contentLength, updatedOptions); + return { + blockBlobClient, + response + }; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * 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 @@ -34994,38 +30943,26 @@ var ContainerClient = /** @class */ (function (_super) { * @param options - Options to Blob Delete operation. * @returns Block blob deletion response data. */ - ContainerClient.prototype.deleteBlob = function (blobName, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, blobClient, e_11; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("ContainerClient-deleteBlob", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - blobClient = this.getBlobClient(blobName); - if (options.versionId) { - blobClient = blobClient.withVersion(options.versionId); - } - return [4 /*yield*/, blobClient.delete(updatedOptions)]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_11 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_11.message - }); - throw e_11; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async deleteBlob(blobName, options = {}) { + const { span, updatedOptions } = createSpan("ContainerClient-deleteBlob", options); + try { + let blobClient = this.getBlobClient(blobName); + if (options.versionId) { + blobClient = blobClient.withVersion(options.versionId); + } + return await blobClient.delete(updatedOptions); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * listBlobFlatSegment returns a single segment of blobs starting from the * specified Marker. Use an empty Marker to start enumeration from the beginning. @@ -35036,40 +30973,27 @@ var ContainerClient = /** @class */ (function (_super) { * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. * @param options - Options to Container List Blob Flat Segment operation. */ - ContainerClient.prototype.listBlobFlatSegment = function (marker, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, response, wrappedResponse, e_12; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("ContainerClient-listBlobFlatSegment", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.listBlobFlatSegment(tslib.__assign(tslib.__assign({ marker: marker }, options), convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: - response = _b.sent(); - wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, segment: tslib.__assign(tslib.__assign({}, response.segment), { blobItems: response.segment.blobItems.map(function (blobItemInteral) { - var blobItem = tslib.__assign(tslib.__assign({}, blobItemInteral), { tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) }); - return blobItem; - }) }) }); - return [2 /*return*/, wrappedResponse]; - case 3: - e_12 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_12.message - }); - throw e_12; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async listBlobFlatSegment(marker, options = {}) { + const { span, updatedOptions } = createSpan("ContainerClient-listBlobFlatSegment", options); + try { + const response = await this.containerContext.listBlobFlatSegment(Object.assign(Object.assign({ marker }, options), convertTracingToRequestOptionsBase(updatedOptions))); + const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, segment: Object.assign(Object.assign({}, response.segment), { blobItems: response.segment.blobItems.map((blobItemInteral) => { + const blobItem = Object.assign(Object.assign({}, blobItemInteral), { tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) }); + return blobItem; + }) }) }); + return wrappedResponse; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * listBlobHierarchySegment returns a single segment of blobs starting from * the specified Marker. Use an empty Marker to start enumeration from the @@ -35081,40 +31005,27 @@ var ContainerClient = /** @class */ (function (_super) { * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. * @param options - Options to Container List Blob Hierarchy Segment operation. */ - ContainerClient.prototype.listBlobHierarchySegment = function (delimiter, marker, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, response, wrappedResponse, e_13; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("ContainerClient-listBlobHierarchySegment", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.listBlobHierarchySegment(delimiter, tslib.__assign(tslib.__assign({ marker: marker }, options), convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: - response = _b.sent(); - wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, segment: tslib.__assign(tslib.__assign({}, response.segment), { blobItems: response.segment.blobItems.map(function (blobItemInteral) { - var blobItem = tslib.__assign(tslib.__assign({}, blobItemInteral), { tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) }); - return blobItem; - }) }) }); - return [2 /*return*/, wrappedResponse]; - case 3: - e_13 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_13.message - }); - throw e_13; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async listBlobHierarchySegment(delimiter, marker, options = {}) { + const { span, updatedOptions } = createSpan("ContainerClient-listBlobHierarchySegment", options); + try { + const response = await this.containerContext.listBlobHierarchySegment(delimiter, Object.assign(Object.assign({ marker }, options), convertTracingToRequestOptionsBase(updatedOptions))); + const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, segment: Object.assign(Object.assign({}, response.segment), { blobItems: response.segment.blobItems.map((blobItemInteral) => { + const blobItem = Object.assign(Object.assign({}, blobItemInteral), { tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) }); + return blobItem; + }) }) }); + return wrappedResponse; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Returns an AsyncIterableIterator for ContainerListBlobFlatSegmentResponse * @@ -35127,81 +31038,42 @@ var ContainerClient = /** @class */ (function (_super) { * items. The marker value is opaque to the client. * @param options - Options to list blobs operation. */ - ContainerClient.prototype.listSegments = function (marker, options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listSegments_1() { - var listBlobsFlatSegmentResponse; - 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.listBlobFlatSegment(marker, options))]; - case 2: - listBlobsFlatSegmentResponse = _a.sent(); - marker = listBlobsFlatSegmentResponse.continuationToken; - return [4 /*yield*/, tslib.__await(listBlobsFlatSegmentResponse)]; - 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*/]; - } - }); + listSegments(marker, options = {}) { + return tslib.__asyncGenerator(this, arguments, function* listSegments_1() { + let listBlobsFlatSegmentResponse; + if (!!marker || marker === undefined) { + do { + listBlobsFlatSegmentResponse = yield tslib.__await(this.listBlobFlatSegment(marker, options)); + marker = listBlobsFlatSegmentResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(listBlobsFlatSegmentResponse)); + } while (marker); + } }); - }; + } /** * Returns an AsyncIterableIterator of {@link BlobItem} objects * * @param options - Options to list blobs operation. */ - ContainerClient.prototype.listItems = function (options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listItems_1() { - var marker, _a, _b, listBlobsFlatSegmentResponse, e_14_1; - var e_14, _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]; - listBlobsFlatSegmentResponse = _b.value; - return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(listBlobsFlatSegmentResponse.segment.blobItems)))]; - 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_14_1 = _d.sent(); - e_14 = { error: e_14_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_14) throw e_14.error; - return [7 /*endfinally*/]; - case 12: return [7 /*endfinally*/]; - case 13: return [2 /*return*/]; + listItems(options = {}) { + return tslib.__asyncGenerator(this, arguments, function* listItems_1() { + var e_1, _a; + let marker; + try { + for (var _b = tslib.__asyncValues(this.listSegments(marker, options)), _c; _c = yield tslib.__await(_b.next()), !_c.done;) { + const listBlobsFlatSegmentResponse = _c.value; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(listBlobsFlatSegmentResponse.segment.blobItems))); } - }); + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) yield tslib.__await(_a.call(_b)); + } + finally { if (e_1) throw e_1.error; } + } }); - }; + } /** * Returns an async iterable iterator to list all the blobs * under the specified account. @@ -35272,11 +31144,8 @@ var ContainerClient = /** @class */ (function (_super) { * @param options - Options to list blobs. * @returns An asyncIterableIterator that supports paging. */ - ContainerClient.prototype.listBlobsFlat = function (options) { - var _a; - var _this = this; - if (options === void 0) { options = {}; } - var include = []; + listBlobsFlat(options = {}) { + const include = []; if (options.includeCopy) { include.push("copy"); } @@ -35298,35 +31167,42 @@ var ContainerClient = /** @class */ (function (_super) { if (options.includeTags) { include.push("tags"); } + if (options.includeDeletedWithVersions) { + include.push("deletedwithversions"); + } + if (options.includeImmutabilityPolicy) { + include.push("immutabilitypolicy"); + } + if (options.includeLegalHold) { + include.push("legalhold"); + } if (options.prefix === "") { options.prefix = undefined; } - var updatedOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); + const updatedOptions = Object.assign(Object.assign({}, options), (include.length > 0 ? { include: include } : {})); // AsyncIterableIterator to iterate over blobs - var iter = this.listItems(updatedOptions); - return _a = { - /** - * The next method, part of the iteration protocol - */ - next: function () { - return iter.next(); - } + const iter = this.listItems(updatedOptions); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ - _a[Symbol.asyncIterator] = function () { + [Symbol.asyncIterator]() { return this; }, /** * 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 }, updatedOptions)); - }, - _a; - }; + byPage: (settings = {}) => { + return this.listSegments(settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); + } + }; + } /** * Returns an AsyncIterableIterator for ContainerListBlobHierarchySegmentResponse * @@ -35340,106 +31216,51 @@ var ContainerClient = /** @class */ (function (_super) { * items. The marker value is opaque to the client. * @param options - Options to list blobs operation. */ - ContainerClient.prototype.listHierarchySegments = function (delimiter, marker, options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listHierarchySegments_1() { - var listBlobsHierarchySegmentResponse; - 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.listBlobHierarchySegment(delimiter, marker, options))]; - case 2: - listBlobsHierarchySegmentResponse = _a.sent(); - marker = listBlobsHierarchySegmentResponse.continuationToken; - return [4 /*yield*/, tslib.__await(listBlobsHierarchySegmentResponse)]; - 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*/]; - } - }); + listHierarchySegments(delimiter, marker, options = {}) { + return tslib.__asyncGenerator(this, arguments, function* listHierarchySegments_1() { + let listBlobsHierarchySegmentResponse; + if (!!marker || marker === undefined) { + do { + listBlobsHierarchySegmentResponse = yield tslib.__await(this.listBlobHierarchySegment(delimiter, marker, options)); + marker = listBlobsHierarchySegmentResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(listBlobsHierarchySegmentResponse)); + } while (marker); + } }); - }; + } /** * Returns an AsyncIterableIterator for {@link BlobPrefix} and {@link BlobItem} objects. * * @param delimiter - The character or string used to define the virtual hierarchy * @param options - Options to list blobs operation. */ - ContainerClient.prototype.listItemsByHierarchy = function (delimiter, options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listItemsByHierarchy_1() { - var marker, _a, _b, listBlobsHierarchySegmentResponse, segment, _i, _c, prefix, _d, _e, blob, e_15_1; - var e_15, _f; - return tslib.__generator(this, function (_g) { - switch (_g.label) { - case 0: - _g.trys.push([0, 14, 15, 20]); - _a = tslib.__asyncValues(this.listHierarchySegments(delimiter, marker, options)); - _g.label = 1; - case 1: return [4 /*yield*/, tslib.__await(_a.next())]; - case 2: - if (!(_b = _g.sent(), !_b.done)) return [3 /*break*/, 13]; - listBlobsHierarchySegmentResponse = _b.value; - segment = listBlobsHierarchySegmentResponse.segment; - if (!segment.blobPrefixes) return [3 /*break*/, 7]; - _i = 0, _c = segment.blobPrefixes; - _g.label = 3; - case 3: - if (!(_i < _c.length)) return [3 /*break*/, 7]; - prefix = _c[_i]; - return [4 /*yield*/, tslib.__await(tslib.__assign({ kind: "prefix" }, prefix))]; - case 4: return [4 /*yield*/, _g.sent()]; - case 5: - _g.sent(); - _g.label = 6; - case 6: - _i++; - return [3 /*break*/, 3]; - case 7: - _d = 0, _e = segment.blobItems; - _g.label = 8; - case 8: - if (!(_d < _e.length)) return [3 /*break*/, 12]; - blob = _e[_d]; - return [4 /*yield*/, tslib.__await(tslib.__assign({ kind: "blob" }, blob))]; - case 9: return [4 /*yield*/, _g.sent()]; - case 10: - _g.sent(); - _g.label = 11; - case 11: - _d++; - return [3 /*break*/, 8]; - case 12: return [3 /*break*/, 1]; - case 13: return [3 /*break*/, 20]; - case 14: - e_15_1 = _g.sent(); - e_15 = { error: e_15_1 }; - return [3 /*break*/, 20]; - case 15: - _g.trys.push([15, , 18, 19]); - if (!(_b && !_b.done && (_f = _a.return))) return [3 /*break*/, 17]; - return [4 /*yield*/, tslib.__await(_f.call(_a))]; - case 16: - _g.sent(); - _g.label = 17; - case 17: return [3 /*break*/, 19]; - case 18: - if (e_15) throw e_15.error; - return [7 /*endfinally*/]; - case 19: return [7 /*endfinally*/]; - case 20: return [2 /*return*/]; + listItemsByHierarchy(delimiter, options = {}) { + return tslib.__asyncGenerator(this, arguments, function* listItemsByHierarchy_1() { + var e_2, _a; + let marker; + try { + for (var _b = tslib.__asyncValues(this.listHierarchySegments(delimiter, marker, options)), _c; _c = yield tslib.__await(_b.next()), !_c.done;) { + const listBlobsHierarchySegmentResponse = _c.value; + const segment = listBlobsHierarchySegmentResponse.segment; + if (segment.blobPrefixes) { + for (const prefix of segment.blobPrefixes) { + yield yield tslib.__await(Object.assign({ kind: "prefix" }, prefix)); + } + } + for (const blob of segment.blobItems) { + yield yield tslib.__await(Object.assign({ kind: "blob" }, blob)); + } } - }); + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) yield tslib.__await(_a.call(_b)); + } + finally { if (e_2) throw e_2.error; } + } }); - }; + } /** * Returns an async iterable iterator to list all the blobs by hierarchy. * under the specified account. @@ -35516,14 +31337,11 @@ var ContainerClient = /** @class */ (function (_super) { * @param delimiter - The character or string used to define the virtual hierarchy * @param options - Options to list blobs operation. */ - ContainerClient.prototype.listBlobsByHierarchy = function (delimiter, options) { - var _a; - var _this = this; - if (options === void 0) { options = {}; } + listBlobsByHierarchy(delimiter, options = {}) { if (delimiter === "") { throw new RangeError("delimiter should contain one or more characters"); } - var include = []; + const include = []; if (options.includeCopy) { include.push("copy"); } @@ -35545,48 +31363,51 @@ var ContainerClient = /** @class */ (function (_super) { if (options.includeTags) { include.push("tags"); } + if (options.includeDeletedWithVersions) { + include.push("deletedwithversions"); + } + if (options.includeImmutabilityPolicy) { + include.push("immutabilitypolicy"); + } + if (options.includeLegalHold) { + include.push("legalhold"); + } if (options.prefix === "") { options.prefix = undefined; } - var updatedOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); + const updatedOptions = Object.assign(Object.assign({}, options), (include.length > 0 ? { include: include } : {})); // AsyncIterableIterator to iterate over blob prefixes and blobs - var iter = this.listItemsByHierarchy(delimiter, updatedOptions); - return _a = { - /** - * The next method, part of the iteration protocol - */ - next: function () { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - return [2 /*return*/, iter.next()]; - }); - }); - } + const iter = this.listItemsByHierarchy(delimiter, updatedOptions); + return { + /** + * The next method, part of the iteration protocol + */ + async next() { + return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ - _a[Symbol.asyncIterator] = function () { + [Symbol.asyncIterator]() { return this; }, /** * Return an AsyncIterableIterator that works a page at a time */ - _a.byPage = function (settings) { - if (settings === void 0) { settings = {}; } - return _this.listHierarchySegments(delimiter, settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); - }, - _a; - }; - ContainerClient.prototype.getContainerNameFromUrl = function () { - var containerName; + byPage: (settings = {}) => { + return this.listHierarchySegments(delimiter, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); + } + }; + } + getContainerNameFromUrl() { + let containerName; try { // URL may look like the following // "https://myaccount.blob.core.windows.net/mycontainer?sasString"; // "https://myaccount.blob.core.windows.net/mycontainer"; // IPv4/IPv6 address hosts, Endpoints - `http://127.0.0.1:10000/devstoreaccount1/containername` // http://localhost:10001/devstoreaccount1/containername - var parsedUrl = coreHttp.URLBuilder.parse(this.url); + const parsedUrl = coreHttp.URLBuilder.parse(this.url); if (parsedUrl.getHost().split(".")[1] === "blob") { // "https://myaccount.blob.core.windows.net/containername". // "https://customdomain.com/containername". @@ -35614,7 +31435,7 @@ var ContainerClient = /** @class */ (function (_super) { catch (error) { throw new Error("Unable to extract containerName with provided information."); } - }; + } /** * Only available for ContainerClient constructed with a shared key credential. * @@ -35626,16 +31447,15 @@ var ContainerClient = /** @class */ (function (_super) { * @param options - Optional parameters. * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ - ContainerClient.prototype.generateSasUrl = function (options) { - var _this = this; - return new Promise(function (resolve) { - if (!(_this.credential instanceof StorageSharedKeyCredential)) { + generateSasUrl(options) { + return new Promise((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)); + const sas = generateBlobSASQueryParameters(Object.assign({ containerName: this._containerName }, options), this.credential).toString(); + resolve(appendToURLQuery(this.url, sas)); }); - }; + } /** * Creates a BlobBatchClient object to conduct batch operations. * @@ -35643,11 +31463,10 @@ var ContainerClient = /** @class */ (function (_super) { * * @returns A new BlobBatchClient object for this container. */ - ContainerClient.prototype.getBlobBatchClient = function () { + getBlobBatchClient() { return new BlobBatchClient(this.url, this.pipeline); - }; - return ContainerClient; -}(StorageClient)); + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -35660,8 +31479,8 @@ var ContainerClient = /** @class */ (function (_super) { * {@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. */ -var AccountSASPermissions = /** @class */ (function () { - function AccountSASPermissions() { +class AccountSASPermissions { + constructor() { /** * Permission to read resources and list queues and tables granted. */ @@ -35706,16 +31525,19 @@ var AccountSASPermissions = /** @class */ (function () { * Permission to filter blobs. */ this.filter = false; + /** + * Permission to set immutability policy. + */ + this.setImmutabilityPolicy = false; } /** * Parse initializes the AccountSASPermissions fields from a string. * * @param permissions - */ - 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]; + static parse(permissions) { + const accountSASPermissions = new AccountSASPermissions(); + for (const c of permissions) { switch (c) { case "r": accountSASPermissions.read = true; @@ -35750,20 +31572,23 @@ var AccountSASPermissions = /** @class */ (function () { case "f": accountSASPermissions.filter = true; break; + case "i": + accountSASPermissions.setImmutabilityPolicy = true; + break; default: - throw new RangeError("Invalid permission character: " + c); + 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. * * @param permissionLike - */ - AccountSASPermissions.from = function (permissionLike) { - var accountSASPermissions = new AccountSASPermissions(); + static from(permissionLike) { + const accountSASPermissions = new AccountSASPermissions(); if (permissionLike.read) { accountSASPermissions.read = true; } @@ -35797,8 +31622,11 @@ var AccountSASPermissions = /** @class */ (function () { if (permissionLike.process) { accountSASPermissions.process = true; } + if (permissionLike.setImmutabilityPolicy) { + accountSASPermissions.setImmutabilityPolicy = true; + } return accountSASPermissions; - }; + } /** * Produces the SAS permissions string for an Azure Storage account. * Call this method to set AccountSASSignatureValues Permissions field. @@ -35809,11 +31637,11 @@ var AccountSASPermissions = /** @class */ (function () { * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas * */ - AccountSASPermissions.prototype.toString = function () { + toString() { // 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 = []; + const permissions = []; if (this.read) { permissions.push("r"); } @@ -35847,10 +31675,12 @@ var AccountSASPermissions = /** @class */ (function () { if (this.process) { permissions.push("p"); } + if (this.setImmutabilityPolicy) { + permissions.push("i"); + } return permissions.join(""); - }; - return AccountSASPermissions; -}()); + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -35863,8 +31693,8 @@ var AccountSASPermissions = /** @class */ (function () { * {@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. */ -var AccountSASResourceTypes = /** @class */ (function () { - function AccountSASResourceTypes() { +class AccountSASResourceTypes { + constructor() { /** * Permission to access service level APIs granted. */ @@ -35884,10 +31714,9 @@ var AccountSASResourceTypes = /** @class */ (function () { * * @param resourceTypes - */ - 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]; + static parse(resourceTypes) { + const accountSASResourceTypes = new AccountSASResourceTypes(); + for (const c of resourceTypes) { switch (c) { case "s": accountSASResourceTypes.service = true; @@ -35899,19 +31728,19 @@ var AccountSASResourceTypes = /** @class */ (function () { accountSASResourceTypes.object = true; break; default: - throw new RangeError("Invalid resource type: " + c); + 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 * */ - AccountSASResourceTypes.prototype.toString = function () { - var resourceTypes = []; + toString() { + const resourceTypes = []; if (this.service) { resourceTypes.push("s"); } @@ -35922,9 +31751,8 @@ var AccountSASResourceTypes = /** @class */ (function () { resourceTypes.push("o"); } return resourceTypes.join(""); - }; - return AccountSASResourceTypes; -}()); + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -35937,8 +31765,8 @@ var AccountSASResourceTypes = /** @class */ (function () { * {@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. */ -var AccountSASServices = /** @class */ (function () { - function AccountSASServices() { +class AccountSASServices { + constructor() { /** * Permission to access blob resources granted. */ @@ -35962,10 +31790,9 @@ var AccountSASServices = /** @class */ (function () { * * @param services - */ - 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]; + static parse(services) { + const accountSASServices = new AccountSASServices(); + for (const c of services) { switch (c) { case "b": accountSASServices.blob = true; @@ -35980,17 +31807,17 @@ var AccountSASServices = /** @class */ (function () { accountSASServices.table = true; break; default: - throw new RangeError("Invalid service character: " + c); + throw new RangeError(`Invalid service character: ${c}`); } } return accountSASServices; - }; + } /** * Converts the given services to a string. * */ - AccountSASServices.prototype.toString = function () { - var services = []; + toString() { + const services = []; if (this.blob) { services.push("b"); } @@ -36004,9 +31831,8 @@ var AccountSASServices = /** @class */ (function () { services.push("f"); } return services.join(""); - }; - return AccountSASServices; -}()); + } +} // Copyright (c) Microsoft Corporation. /** @@ -36021,9 +31847,14 @@ var AccountSASServices = /** @class */ (function () { * @param sharedKeyCredential - */ function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { - var version = accountSASSignatureValues.version + const version = accountSASSignatureValues.version ? accountSASSignatureValues.version : SERVICE_VERSION; + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.setImmutabilityPolicy && + version < "2020-08-04") { + throw RangeError("'version' must be >= '2020-08-04' when provided 'i' permission."); + } if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.deleteVersion && version < "2019-10-10") { @@ -36039,10 +31870,10 @@ function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyC 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 = [ + const parsedPermissions = AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()); + const parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); + const parsedResourceTypes = AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString(); + const stringToSign = [ sharedKeyCredential.accountName, parsedPermissions, parsedServices, @@ -36056,7 +31887,7 @@ function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyC version, "" // Account SAS requires an additional newline character ].join("\n"); - var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); return new SASQueryParameters(version, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange); } @@ -36064,12 +31895,13 @@ function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyC * A BlobServiceClient represents a Client to the Azure Storage Blob service allowing you * to manipulate blob containers. */ -var BlobServiceClient = /** @class */ (function (_super) { - tslib.__extends(BlobServiceClient, _super); - function BlobServiceClient(url, credentialOrPipeline, options) { - var _this = this; - var pipeline; - if (credentialOrPipeline instanceof Pipeline) { +class BlobServiceClient extends StorageClient { + constructor(url, credentialOrPipeline, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { + let pipeline; + if (isPipelineLike(credentialOrPipeline)) { pipeline = credentialOrPipeline; } else if ((coreHttp.isNode && credentialOrPipeline instanceof StorageSharedKeyCredential) || @@ -36081,9 +31913,8 @@ var BlobServiceClient = /** @class */ (function (_super) { // The second parameter is undefined. Use anonymous credential pipeline = newPipeline(new AnonymousCredential(), options); } - _this = _super.call(this, url, pipeline) || this; - _this.serviceContext = new Service(_this.storageClientContext); - return _this; + super(url, pipeline); + this.serviceContext = new Service(this.storageClientContext); } /** * @@ -36097,25 +31928,28 @@ var BlobServiceClient = /** @class */ (function (_super) { * `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 options - Optional. Options to configure the HTTP pipeline. */ - BlobServiceClient.fromConnectionString = function (connectionString, options) { + static fromConnectionString(connectionString, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { options = options || {}; - var extractedCreds = extractConnectionStringParts(connectionString); + const extractedCreds = extractConnectionStringParts(connectionString); if (extractedCreds.kind === "AccountConnString") { { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); - var pipeline = newPipeline(sharedKeyCredential, options); + const pipeline = newPipeline(sharedKeyCredential, options); return new BlobServiceClient(extractedCreds.url, pipeline); } } else if (extractedCreds.kind === "SASConnString") { - var pipeline = newPipeline(new AnonymousCredential(), options); + const 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 * @@ -36128,9 +31962,9 @@ var BlobServiceClient = /** @class */ (function (_super) { * const containerClient = blobServiceClient.getContainerClient(""); * ``` */ - BlobServiceClient.prototype.getContainerClient = function (containerName) { + getContainerClient(containerName) { return new ContainerClient(appendToURLPath(this.url, encodeURIComponent(containerName)), this.pipeline); - }; + } /** * Create a Blob container. * @@ -36138,40 +31972,27 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param options - Options to configure Container Create operation. * @returns Container creation response and the corresponding container client. */ - BlobServiceClient.prototype.createContainer = function (containerName, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, containerClient, containerCreateResponse, e_1; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-createContainer", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - containerClient = this.getContainerClient(containerName); - return [4 /*yield*/, containerClient.create(updatedOptions)]; - case 2: - containerCreateResponse = _b.sent(); - return [2 /*return*/, { - containerClient: containerClient, - containerCreateResponse: containerCreateResponse - }]; - case 3: - e_1 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_1.message - }); - throw e_1; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async createContainer(containerName, options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-createContainer", options); + try { + const containerClient = this.getContainerClient(containerName); + const containerCreateResponse = await containerClient.create(updatedOptions); + return { + containerClient, + containerCreateResponse + }; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Deletes a Blob container. * @@ -36179,35 +32000,23 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param options - Options to configure Container Delete operation. * @returns Container deletion response. */ - BlobServiceClient.prototype.deleteContainer = function (containerName, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, containerClient, e_2; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-deleteContainer", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - containerClient = this.getContainerClient(containerName); - return [4 /*yield*/, containerClient.delete(updatedOptions)]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_2 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_2.message - }); - throw e_2; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async deleteContainer(containerName, options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-deleteContainer", options); + try { + const containerClient = this.getContainerClient(containerName); + return await containerClient.delete(updatedOptions); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * 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. @@ -36217,39 +32026,27 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param options - Options to configure Container Restore operation. * @returns Container deletion response. */ - BlobServiceClient.prototype.undeleteContainer = function (deletedContainerName, deletedContainerVersion, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, containerClient, containerContext, containerUndeleteResponse, e_3; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-undeleteContainer", options), span = _a.span, updatedOptions = _a.updatedOptions; - _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({ deletedContainerName: deletedContainerName, - deletedContainerVersion: deletedContainerVersion }, updatedOptions))]; - case 2: - containerUndeleteResponse = _b.sent(); - return [2 /*return*/, { containerClient: containerClient, containerUndeleteResponse: containerUndeleteResponse }]; - case 3: - e_3 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_3.message - }); - throw e_3; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async undeleteContainer(deletedContainerName, deletedContainerVersion, options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-undeleteContainer", options); + try { + const containerClient = this.getContainerClient(options.destinationContainerName || deletedContainerName); + // Hack to access a protected member. + const containerContext = new Container(containerClient["storageClientContext"]); + const containerUndeleteResponse = await containerContext.restore(Object.assign({ deletedContainerName, + deletedContainerVersion }, updatedOptions)); + return { containerClient, containerUndeleteResponse }; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Rename an existing Blob Container. * @@ -36257,40 +32054,29 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param destinationContainerName - The new name of the container. * @param options - Options to configure Container Rename operation. */ + /* eslint-disable-next-line @typescript-eslint/ban-ts-comment */ // @ts-ignore Need to hide this interface for now. Make it public and turn on the live tests for it when the service is ready. - BlobServiceClient.prototype.renameContainer = function (sourceContainerName, destinationContainerName, options) { + async renameContainer(sourceContainerName, destinationContainerName, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, containerClient, containerContext, containerRenameResponse, e_4; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobServiceClient-renameContainer", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - containerClient = this.getContainerClient(destinationContainerName); - containerContext = new Container(containerClient["storageClientContext"]); - return [4 /*yield*/, containerContext.rename(sourceContainerName, tslib.__assign(tslib.__assign({}, updatedOptions), { sourceLeaseId: (_a = options.sourceCondition) === null || _a === void 0 ? void 0 : _a.leaseId }))]; - case 2: - containerRenameResponse = _c.sent(); - return [2 /*return*/, { containerClient: containerClient, containerRenameResponse: containerRenameResponse }]; - case 3: - e_4 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_4.message - }); - throw e_4; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobServiceClient-renameContainer", options); + try { + const containerClient = this.getContainerClient(destinationContainerName); + // Hack to access a protected member. + const containerContext = new Container(containerClient["storageClientContext"]); + const containerRenameResponse = await containerContext.rename(sourceContainerName, Object.assign(Object.assign({}, updatedOptions), { sourceLeaseId: (_a = options.sourceCondition) === null || _a === void 0 ? void 0 : _a.leaseId })); + return { containerClient, containerRenameResponse }; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Gets the properties of a storage account’s Blob service, including properties * for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. @@ -36299,34 +32085,22 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param options - Options to the Service Get Properties operation. * @returns Response data for the Service Get Properties operation. */ - BlobServiceClient.prototype.getProperties = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_5; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-getProperties", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getProperties(tslib.__assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_5 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_5.message - }); - throw e_5; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async getProperties(options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-getProperties", options); + try { + return await this.serviceContext.getProperties(Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * 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. @@ -36336,34 +32110,22 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param options - Options to the Service Set Properties operation. * @returns Response data for the Service Set Properties operation. */ - BlobServiceClient.prototype.setProperties = function (properties, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_6; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-setProperties", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.setProperties(properties, tslib.__assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_6 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_6.message - }); - throw e_6; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async setProperties(properties, options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-setProperties", options); + try { + return await this.serviceContext.setProperties(properties, Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Retrieves statistics related to replication for the Blob service. It is only * available on the secondary location endpoint when read-access geo-redundant @@ -36373,34 +32135,22 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param options - Options to the Service Get Statistics operation. * @returns Response data for the Service Get Statistics operation. */ - BlobServiceClient.prototype.getStatistics = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_7; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-getStatistics", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getStatistics(tslib.__assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_7 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_7.message - }); - throw e_7; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async getStatistics(options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-getStatistics", options); + try { + return await this.serviceContext.getStatistics(Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * The Get Account Information operation returns the sku name and account kind * for the specified account. @@ -36411,34 +32161,22 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param options - Options to the Service Get Account Info operation. * @returns Response data for the Service Get Account Info operation. */ - BlobServiceClient.prototype.getAccountInfo = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_8; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-getAccountInfo", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getAccountInfo(tslib.__assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_8 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_8.message - }); - throw e_8; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async getAccountInfo(options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-getAccountInfo", options); + try { + return await this.serviceContext.getAccountInfo(Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Returns a list of the containers under the specified account. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/list-containers2 @@ -36453,34 +32191,22 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param options - Options to the Service List Container Segment operation. * @returns Response data for the Service List Container Segment operation. */ - BlobServiceClient.prototype.listContainersSegment = function (marker, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_9; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-listContainersSegment", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.listContainersSegment(tslib.__assign(tslib.__assign(tslib.__assign({ abortSignal: options.abortSignal, marker: marker }, options), { include: typeof options.include === "string" ? [options.include] : options.include }), convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_9 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_9.message - }); - throw e_9; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async listContainersSegment(marker, options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-listContainersSegment", options); + try { + return await this.serviceContext.listContainersSegment(Object.assign(Object.assign(Object.assign({ abortSignal: options.abortSignal, marker }, options), { include: typeof options.include === "string" ? [options.include] : options.include }), convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * 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 @@ -36499,44 +32225,31 @@ var BlobServiceClient = /** @class */ (function (_super) { * items. The marker value is opaque to the client. * @param options - Options to find blobs by tags. */ - BlobServiceClient.prototype.findBlobsByTagsSegment = function (tagFilterSqlExpression, marker, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, response, wrappedResponse, e_10; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-findBlobsByTagsSegment", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.filterBlobs(tslib.__assign({ abortSignal: options.abortSignal, where: tagFilterSqlExpression, marker: marker, maxPageSize: options.maxPageSize }, convertTracingToRequestOptionsBase(updatedOptions)))]; - 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_10 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_10.message - }); - throw e_10; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async findBlobsByTagsSegment(tagFilterSqlExpression, marker, options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-findBlobsByTagsSegment", options); + try { + const response = await this.serviceContext.filterBlobs(Object.assign({ abortSignal: options.abortSignal, where: tagFilterSqlExpression, marker, maxPageSize: options.maxPageSize }, convertTracingToRequestOptionsBase(updatedOptions))); + const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, blobs: response.blobs.map((blob) => { + var _a; + let tagValue = ""; + if (((_a = blob.tags) === null || _a === void 0 ? void 0 : _a.blobTagSet.length) === 1) { + tagValue = blob.tags.blobTagSet[0].value; + } + return Object.assign(Object.assign({}, blob), { tags: toTags(blob.tags), tagValue }); + }) }); + return wrappedResponse; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Returns an AsyncIterableIterator for ServiceFindBlobsByTagsSegmentResponse. * @@ -36553,33 +32266,19 @@ var BlobServiceClient = /** @class */ (function (_super) { * items. The marker value is opaque to the client. * @param options - Options to find blobs by tags. */ - 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*/]; - } - }); + findBlobsByTagsSegments(tagFilterSqlExpression, marker, options = {}) { + return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsSegments_1() { + let response; + if (!!marker || marker === undefined) { + do { + response = yield tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker, options)); + response.blobs = response.blobs || []; + marker = response.continuationToken; + yield yield tslib.__await(response); + } while (marker); + } }); - }; + } /** * Returns an AsyncIterableIterator for blobs. * @@ -36589,49 +32288,25 @@ var BlobServiceClient = /** @class */ (function (_super) { * however, only a subset of the OData filter syntax is supported in the Blob service. * @param options - Options to findBlobsByTagsItems. */ - 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_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.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_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*/]; + findBlobsByTagsItems(tagFilterSqlExpression, options = {}) { + return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsItems_1() { + var e_1, _a; + let marker; + try { + for (var _b = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker, options)), _c; _c = yield tslib.__await(_b.next()), !_c.done;) { + const segment = _c.value; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs))); } - }); + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) yield tslib.__await(_a.call(_b)); + } + finally { if (e_1) throw e_1.error; } + } }); - }; + } /** * Returns an async iterable iterator to find all blobs with specified tag * under the specified account. @@ -36711,36 +32386,31 @@ var BlobServiceClient = /** @class */ (function (_super) { * however, only a subset of the OData filter syntax is supported in the Blob service. * @param options - Options to find blobs by tags. */ - BlobServiceClient.prototype.findBlobsByTags = function (tagFilterSqlExpression, options) { - var _a; - var _this = this; - if (options === void 0) { options = {}; } + findBlobsByTags(tagFilterSqlExpression, options = {}) { // AsyncIterableIterator to iterate over blobs - var listSegmentOptions = tslib.__assign({}, options); - var iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); - return _a = { - /** - * The next method, part of the iteration protocol - */ - next: function () { - return iter.next(); - } + const listSegmentOptions = Object.assign({}, options); + const iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ - _a[Symbol.asyncIterator] = function () { + [Symbol.asyncIterator]() { return this; }, /** * 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; - }; + byPage: (settings = {}) => { + return this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + } + }; + } /** * Returns an AsyncIterableIterator for ServiceListContainersSegmentResponses * @@ -36753,83 +32423,44 @@ var BlobServiceClient = /** @class */ (function (_super) { * items. The marker value is opaque to the client. * @param options - Options to list containers operation. */ - 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*/]; - } - }); + listSegments(marker, options = {}) { + return tslib.__asyncGenerator(this, arguments, function* listSegments_1() { + let listContainersSegmentResponse; + if (!!marker || marker === undefined) { + do { + listContainersSegmentResponse = yield tslib.__await(this.listContainersSegment(marker, options)); + listContainersSegmentResponse.containerItems = + listContainersSegmentResponse.containerItems || []; + marker = listContainersSegmentResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(listContainersSegmentResponse)); + } while (marker); + } }); - }; + } /** * Returns an AsyncIterableIterator for Container Items * * @param options - Options to list containers operation. */ - BlobServiceClient.prototype.listItems = function (options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listItems_1() { - var marker, _a, _b, segment, e_12_1; - var e_12, _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_12_1 = _d.sent(); - e_12 = { error: e_12_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_12) throw e_12.error; - return [7 /*endfinally*/]; - case 12: return [7 /*endfinally*/]; - case 13: return [2 /*return*/]; + listItems(options = {}) { + return tslib.__asyncGenerator(this, arguments, function* listItems_1() { + var e_2, _a; + let marker; + try { + for (var _b = tslib.__asyncValues(this.listSegments(marker, options)), _c; _c = yield tslib.__await(_b.next()), !_c.done;) { + const segment = _c.value; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.containerItems))); } - }); + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) yield tslib.__await(_a.call(_b)); + } + finally { if (e_2) throw e_2.error; } + } }); - }; + } /** * Returns an async iterable iterator to list all the containers * under the specified account. @@ -36904,14 +32535,11 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param options - Options to list containers. * @returns An asyncIterableIterator that supports paging. */ - BlobServiceClient.prototype.listContainers = function (options) { - var _a; - var _this = this; - if (options === void 0) { options = {}; } + listContainers(options = {}) { if (options.prefix === "") { options.prefix = undefined; } - var include = []; + const include = []; if (options.includeDeleted) { include.push("deleted"); } @@ -36919,31 +32547,29 @@ var BlobServiceClient = /** @class */ (function (_super) { include.push("metadata"); } // AsyncIterableIterator to iterate over containers - var listSegmentOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); - var iter = this.listItems(listSegmentOptions); - return _a = { - /** - * The next method, part of the iteration protocol - */ - next: function () { - return iter.next(); - } + const listSegmentOptions = Object.assign(Object.assign({}, options), (include.length > 0 ? { include } : {})); + const iter = this.listItems(listSegmentOptions); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ - _a[Symbol.asyncIterator] = function () { + [Symbol.asyncIterator]() { return this; }, /** * 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; - }; + byPage: (settings = {}) => { + return this.listSegments(settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + } + }; + } /** * ONLY AVAILABLE WHEN USING BEARER TOKEN AUTHENTICATION (TokenCredential). * @@ -36955,49 +32581,36 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param startsOn - The start time for the user delegation SAS. Must be within 7 days of the current time * @param expiresOn - The end time for the user delegation SAS. Must be within 7 days of the current time */ - BlobServiceClient.prototype.getUserDelegationKey = function (startsOn, expiresOn, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, response, userDelegationKey, res, e_13; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-getUserDelegationKey", options), span = _a.span, updatedOptions = _a.updatedOptions; - _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) - }, tslib.__assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions)))]; - 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_13 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_13.message - }); - throw e_13; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async getUserDelegationKey(startsOn, expiresOn, options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-getUserDelegationKey", options); + try { + const response = await this.serviceContext.getUserDelegationKey({ + startsOn: truncatedISO8061Date(startsOn, false), + expiresOn: truncatedISO8061Date(expiresOn, false) + }, Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); + const 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 + }; + const res = Object.assign({ _response: response._response, requestId: response.requestId, clientRequestId: response.clientRequestId, version: response.version, date: response.date, errorCode: response.errorCode }, userDelegationKey); + return res; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Creates a BlobBatchClient object to conduct batch operations. * @@ -37005,9 +32618,9 @@ var BlobServiceClient = /** @class */ (function (_super) { * * @returns A new BlobBatchClient object for this service. */ - BlobServiceClient.prototype.getBlobBatchClient = function () { + getBlobBatchClient() { return new BlobBatchClient(this.url, this.pipeline); - }; + } /** * Only available for BlobServiceClient constructed with a shared key credential. * @@ -37022,24 +32635,20 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param options - Optional parameters. * @returns An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ - 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 = {}; } + generateAccountSasUrl(expiresOn, permissions = AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) { if (!(this.credential instanceof StorageSharedKeyCredential)) { throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); } if (expiresOn === undefined) { - var now = new Date(); + const now = new Date(); expiresOn = new Date(now.getTime() + 3600 * 1000); } - var sas = generateAccountSASQueryParameters(tslib.__assign({ permissions: permissions, - expiresOn: expiresOn, - resourceTypes: resourceTypes, services: AccountSASServices.parse("b").toString() }, options), this.credential).toString(); + const sas = generateAccountSASQueryParameters(Object.assign({ permissions, + expiresOn, + resourceTypes, services: AccountSASServices.parse("b").toString() }, options), this.credential).toString(); return appendToURLQuery(this.url, sas); - }; - return BlobServiceClient; -}(StorageClient)); + } +} Object.defineProperty(exports, 'BaseRequestPolicy', { enumerable: true, @@ -37106,6 +32715,7 @@ exports.StorageSharedKeyCredential = StorageSharedKeyCredential; exports.StorageSharedKeyCredentialPolicy = StorageSharedKeyCredentialPolicy; exports.generateAccountSASQueryParameters = generateAccountSASQueryParameters; exports.generateBlobSASQueryParameters = generateBlobSASQueryParameters; +exports.isPipelineLike = isPipelineLike; exports.logger = logger; exports.newPipeline = newPipeline; //# sourceMappingURL=index.js.map @@ -37121,33 +32731,7 @@ exports.newPipeline = newPipeline; /* 380 */, /* 381 */, /* 382 */, -/* 383 */, -/* 384 */ -/***/ (function(__unusedmodule, exports) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SearchState = void 0; -class SearchState { - constructor(path, level) { - this.path = path; - this.level = level; - } -} -exports.SearchState = SearchState; -//# sourceMappingURL=internal-search-state.js.map - -/***/ }), -/* 385 */, -/* 386 */, -/* 387 */, -/* 388 */, -/* 389 */, -/* 390 */, -/* 391 */, -/* 392 */, -/* 393 */ +/* 383 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; @@ -37182,1649 +32766,74 @@ exports.SearchState = SearchState; * POSSIBILITY OF SUCH DAMAGE. */ -const punycode = __webpack_require__(815); -const urlParse = __webpack_require__(835).parse; -const util = __webpack_require__(669); -const pubsuffix = __webpack_require__(562); -const Store = __webpack_require__(338).Store; -const MemoryCookieStore = __webpack_require__(332).MemoryCookieStore; -const pathMatch = __webpack_require__(348).pathMatch; -const VERSION = __webpack_require__(460); -const { fromCallback } = __webpack_require__(147); +const pubsuffix = __webpack_require__(519); -// From RFC6265 S4.1.1 -// note that it excludes \x3B ";" -const COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/; - -const CONTROL_CHARS = /[\x00-\x1F]/; - -// From Chromium // '\r', '\n' and '\0' should be treated as a terminator in -// the "relaxed" mode, see: -// https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60 -const TERMINATORS = ["\n", "\r", "\0"]; - -// RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"' -// Note ';' is \x3B -const PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/; - -// date-time parsing constants (RFC6265 S5.1.1) - -const DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/; - -const MONTH_TO_NUM = { - jan: 0, - feb: 1, - mar: 2, - apr: 3, - may: 4, - jun: 5, - jul: 6, - aug: 7, - sep: 8, - oct: 9, - nov: 10, - dec: 11 -}; - -const MAX_TIME = 2147483647000; // 31-bit max -const MIN_TIME = 0; // 31-bit min -const SAME_SITE_CONTEXT_VAL_ERR = - 'Invalid sameSiteContext option for getCookies(); expected one of "strict", "lax", or "none"'; - -function checkSameSiteContext(value) { - const context = String(value).toLowerCase(); - if (context === "none" || context === "lax" || context === "strict") { - return context; - } else { - return null; - } -} - -const PrefixSecurityEnum = Object.freeze({ - SILENT: "silent", - STRICT: "strict", - DISABLED: "unsafe-disabled" -}); - -// Dumped from ip-regex@4.0.0, with the following changes: -// * all capturing groups converted to non-capturing -- "(?:)" -// * support for IPv6 Scoped Literal ("%eth1") removed -// * lowercase hexadecimal only -var IP_REGEX_LOWERCASE =/(?:^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$)|(?:^(?:(?:[a-f\d]{1,4}:){7}(?:[a-f\d]{1,4}|:)|(?:[a-f\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|:[a-f\d]{1,4}|:)|(?:[a-f\d]{1,4}:){5}(?::(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,2}|:)|(?:[a-f\d]{1,4}:){4}(?:(?::[a-f\d]{1,4}){0,1}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,3}|:)|(?:[a-f\d]{1,4}:){3}(?:(?::[a-f\d]{1,4}){0,2}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,4}|:)|(?:[a-f\d]{1,4}:){2}(?:(?::[a-f\d]{1,4}){0,3}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,5}|:)|(?:[a-f\d]{1,4}:){1}(?:(?::[a-f\d]{1,4}){0,4}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,6}|:)|(?::(?:(?::[a-f\d]{1,4}){0,5}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,7}|:)))$)/; - -/* - * Parses a Natural number (i.e., non-negative integer) with either the - * *DIGIT ( non-digit *OCTET ) - * or - * *DIGIT - * grammar (RFC6265 S5.1.1). - * - * The "trailingOK" boolean controls if the grammar accepts a - * "( non-digit *OCTET )" trailer. - */ -function parseDigits(token, minDigits, maxDigits, trailingOK) { - let count = 0; - while (count < token.length) { - const c = token.charCodeAt(count); - // "non-digit = %x00-2F / %x3A-FF" - if (c <= 0x2f || c >= 0x3a) { - break; - } - count++; - } - - // constrain to a minimum and maximum number of digits. - if (count < minDigits || count > maxDigits) { - return null; - } - - if (!trailingOK && count != token.length) { - return null; - } - - return parseInt(token.substr(0, count), 10); -} - -function parseTime(token) { - const parts = token.split(":"); - const result = [0, 0, 0]; - - /* RF6256 S5.1.1: - * time = hms-time ( non-digit *OCTET ) - * hms-time = time-field ":" time-field ":" time-field - * time-field = 1*2DIGIT - */ - - if (parts.length !== 3) { - return null; - } - - for (let i = 0; i < 3; i++) { - // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be - // followed by "( non-digit *OCTET )" so therefore the last time-field can - // have a trailer - const trailingOK = i == 2; - const num = parseDigits(parts[i], 1, 2, trailingOK); - if (num === null) { - return null; - } - result[i] = num; - } - - return result; -} - -function parseMonth(token) { - token = String(token) - .substr(0, 3) - .toLowerCase(); - const num = MONTH_TO_NUM[token]; - return num >= 0 ? num : null; -} - -/* - * RFC6265 S5.1.1 date parser (see RFC for full grammar) - */ -function parseDate(str) { - if (!str) { - return; - } - - /* RFC6265 S5.1.1: - * 2. Process each date-token sequentially in the order the date-tokens - * appear in the cookie-date - */ - const tokens = str.split(DATE_DELIM); - if (!tokens) { - return; - } - - let hour = null; - let minute = null; - let second = null; - let dayOfMonth = null; - let month = null; - let year = null; - - for (let i = 0; i < tokens.length; i++) { - const token = tokens[i].trim(); - if (!token.length) { - continue; - } - - let result; - - /* 2.1. If the found-time flag is not set and the token matches the time - * production, set the found-time flag and set the hour- value, - * minute-value, and second-value to the numbers denoted by the digits in - * the date-token, respectively. Skip the remaining sub-steps and continue - * to the next date-token. - */ - if (second === null) { - result = parseTime(token); - if (result) { - hour = result[0]; - minute = result[1]; - second = result[2]; - continue; - } - } - - /* 2.2. If the found-day-of-month flag is not set and the date-token matches - * the day-of-month production, set the found-day-of- month flag and set - * the day-of-month-value to the number denoted by the date-token. Skip - * the remaining sub-steps and continue to the next date-token. - */ - if (dayOfMonth === null) { - // "day-of-month = 1*2DIGIT ( non-digit *OCTET )" - result = parseDigits(token, 1, 2, true); - if (result !== null) { - dayOfMonth = result; - continue; - } - } - - /* 2.3. If the found-month flag is not set and the date-token matches the - * month production, set the found-month flag and set the month-value to - * the month denoted by the date-token. Skip the remaining sub-steps and - * continue to the next date-token. - */ - if (month === null) { - result = parseMonth(token); - if (result !== null) { - month = result; - continue; - } - } - - /* 2.4. If the found-year flag is not set and the date-token matches the - * year production, set the found-year flag and set the year-value to the - * number denoted by the date-token. Skip the remaining sub-steps and - * continue to the next date-token. - */ - if (year === null) { - // "year = 2*4DIGIT ( non-digit *OCTET )" - result = parseDigits(token, 2, 4, true); - if (result !== null) { - year = result; - /* From S5.1.1: - * 3. If the year-value is greater than or equal to 70 and less - * than or equal to 99, increment the year-value by 1900. - * 4. If the year-value is greater than or equal to 0 and less - * than or equal to 69, increment the year-value by 2000. - */ - if (year >= 70 && year <= 99) { - year += 1900; - } else if (year >= 0 && year <= 69) { - year += 2000; - } - } - } - } - - /* RFC 6265 S5.1.1 - * "5. Abort these steps and fail to parse the cookie-date if: - * * at least one of the found-day-of-month, found-month, found- - * year, or found-time flags is not set, - * * the day-of-month-value is less than 1 or greater than 31, - * * the year-value is less than 1601, - * * the hour-value is greater than 23, - * * the minute-value is greater than 59, or - * * the second-value is greater than 59. - * (Note that leap seconds cannot be represented in this syntax.)" - * - * So, in order as above: - */ - if ( - dayOfMonth === null || - month === null || - year === null || - second === null || - dayOfMonth < 1 || - dayOfMonth > 31 || - year < 1601 || - hour > 23 || - minute > 59 || - second > 59 - ) { - return; - } - - return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second)); -} - -function formatDate(date) { - return date.toUTCString(); -} - -// S5.1.2 Canonicalized Host Names -function canonicalDomain(str) { - if (str == null) { - return null; - } - str = str.trim().replace(/^\./, ""); // S4.1.2.3 & S5.2.3: ignore leading . - - // convert to IDN if any non-ASCII characters - if (punycode && /[^\u0001-\u007f]/.test(str)) { - str = punycode.toASCII(str); - } - - return str.toLowerCase(); -} - -// S5.1.3 Domain Matching -function domainMatch(str, domStr, canonicalize) { - if (str == null || domStr == null) { - return null; - } - if (canonicalize !== false) { - str = canonicalDomain(str); - domStr = canonicalDomain(domStr); - } - - /* - * S5.1.3: - * "A string domain-matches a given domain string if at least one of the - * following conditions hold:" - * - * " o The domain string and the string are identical. (Note that both the - * domain string and the string will have been canonicalized to lower case at - * this point)" - */ - if (str == domStr) { - return true; - } - - /* " o All of the following [three] conditions hold:" */ - - /* "* The domain string is a suffix of the string" */ - const idx = str.indexOf(domStr); - if (idx <= 0) { - return false; // it's a non-match (-1) or prefix (0) - } - - // next, check it's a proper suffix - // e.g., "a.b.c".indexOf("b.c") === 2 - // 5 === 3+2 - if (str.length !== domStr.length + idx) { - return false; // it's not a suffix - } - - /* " * The last character of the string that is not included in the - * domain string is a %x2E (".") character." */ - if (str.substr(idx-1,1) !== '.') { - return false; // doesn't align on "." - } - - /* " * The string is a host name (i.e., not an IP address)." */ - if (IP_REGEX_LOWERCASE.test(str)) { - return false; // it's an IP address - } - - return true; -} - -// RFC6265 S5.1.4 Paths and Path-Match - -/* - * "The user agent MUST use an algorithm equivalent to the following algorithm - * to compute the default-path of a cookie:" - * - * Assumption: the path (and not query part or absolute uri) is passed in. - */ -function defaultPath(path) { - // "2. If the uri-path is empty or if the first character of the uri-path is not - // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps. - if (!path || path.substr(0, 1) !== "/") { - return "/"; - } - - // "3. If the uri-path contains no more than one %x2F ("/") character, output - // %x2F ("/") and skip the remaining step." - if (path === "/") { - return path; - } - - const rightSlash = path.lastIndexOf("/"); - if (rightSlash === 0) { - return "/"; - } - - // "4. Output the characters of the uri-path from the first character up to, - // but not including, the right-most %x2F ("/")." - return path.slice(0, rightSlash); -} - -function trimTerminator(str) { - for (let t = 0; t < TERMINATORS.length; t++) { - const terminatorIdx = str.indexOf(TERMINATORS[t]); - if (terminatorIdx !== -1) { - str = str.substr(0, terminatorIdx); - } - } - - return str; -} - -function parseCookiePair(cookiePair, looseMode) { - cookiePair = trimTerminator(cookiePair); - - let firstEq = cookiePair.indexOf("="); - if (looseMode) { - if (firstEq === 0) { - // '=' is immediately at start - cookiePair = cookiePair.substr(1); - firstEq = cookiePair.indexOf("="); // might still need to split on '=' - } - } else { - // non-loose mode - if (firstEq <= 0) { - // no '=' or is at start - return; // needs to have non-empty "cookie-name" - } - } - - let cookieName, cookieValue; - if (firstEq <= 0) { - cookieName = ""; - cookieValue = cookiePair.trim(); - } else { - cookieName = cookiePair.substr(0, firstEq).trim(); - cookieValue = cookiePair.substr(firstEq + 1).trim(); - } - - if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) { - return; - } - - const c = new Cookie(); - c.key = cookieName; - c.value = cookieValue; - return c; -} - -function parse(str, options) { - if (!options || typeof options !== "object") { - options = {}; - } - str = str.trim(); - - // We use a regex to parse the "name-value-pair" part of S5.2 - const firstSemi = str.indexOf(";"); // S5.2 step 1 - const cookiePair = firstSemi === -1 ? str : str.substr(0, firstSemi); - const c = parseCookiePair(cookiePair, !!options.loose); - if (!c) { - return; - } - - if (firstSemi === -1) { - return c; - } - - // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string - // (including the %x3B (";") in question)." plus later on in the same section - // "discard the first ";" and trim". - const unparsed = str.slice(firstSemi + 1).trim(); - - // "If the unparsed-attributes string is empty, skip the rest of these - // steps." - if (unparsed.length === 0) { - return c; - } - - /* - * S5.2 says that when looping over the items "[p]rocess the attribute-name - * and attribute-value according to the requirements in the following - * subsections" for every item. Plus, for many of the individual attributes - * in S5.3 it says to use the "attribute-value of the last attribute in the - * cookie-attribute-list". Therefore, in this implementation, we overwrite - * the previous value. - */ - const cookie_avs = unparsed.split(";"); - while (cookie_avs.length) { - const av = cookie_avs.shift().trim(); - if (av.length === 0) { - // happens if ";;" appears - continue; - } - const av_sep = av.indexOf("="); - let av_key, av_value; - - if (av_sep === -1) { - av_key = av; - av_value = null; +// Gives the permutation of all possible domainMatch()es of a given domain. The +// array is in shortest-to-longest order. Handy for indexing. +const SPECIAL_USE_DOMAINS = ["local"]; // RFC 6761 +function permuteDomain(domain, allowSpecialUseDomain) { + let pubSuf = null; + if (allowSpecialUseDomain) { + const domainParts = domain.split("."); + if (SPECIAL_USE_DOMAINS.includes(domainParts[domainParts.length - 1])) { + pubSuf = `${domainParts[domainParts.length - 2]}.${ + domainParts[domainParts.length - 1] + }`; } else { - av_key = av.substr(0, av_sep); - av_value = av.substr(av_sep + 1); - } - - av_key = av_key.trim().toLowerCase(); - - if (av_value) { - av_value = av_value.trim(); - } - - switch (av_key) { - case "expires": // S5.2.1 - if (av_value) { - const exp = parseDate(av_value); - // "If the attribute-value failed to parse as a cookie date, ignore the - // cookie-av." - if (exp) { - // over and underflow not realistically a concern: V8's getTime() seems to - // store something larger than a 32-bit time_t (even with 32-bit node) - c.expires = exp; - } - } - break; - - case "max-age": // S5.2.2 - if (av_value) { - // "If the first character of the attribute-value is not a DIGIT or a "-" - // character ...[or]... If the remainder of attribute-value contains a - // non-DIGIT character, ignore the cookie-av." - if (/^-?[0-9]+$/.test(av_value)) { - const delta = parseInt(av_value, 10); - // "If delta-seconds is less than or equal to zero (0), let expiry-time - // be the earliest representable date and time." - c.setMaxAge(delta); - } - } - break; - - case "domain": // S5.2.3 - // "If the attribute-value is empty, the behavior is undefined. However, - // the user agent SHOULD ignore the cookie-av entirely." - if (av_value) { - // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E - // (".") character." - const domain = av_value.trim().replace(/^\./, ""); - if (domain) { - // "Convert the cookie-domain to lower case." - c.domain = domain.toLowerCase(); - } - } - break; - - case "path": // S5.2.4 - /* - * "If the attribute-value is empty or if the first character of the - * attribute-value is not %x2F ("/"): - * Let cookie-path be the default-path. - * Otherwise: - * Let cookie-path be the attribute-value." - * - * We'll represent the default-path as null since it depends on the - * context of the parsing. - */ - c.path = av_value && av_value[0] === "/" ? av_value : null; - break; - - case "secure": // S5.2.5 - /* - * "If the attribute-name case-insensitively matches the string "Secure", - * the user agent MUST append an attribute to the cookie-attribute-list - * with an attribute-name of Secure and an empty attribute-value." - */ - c.secure = true; - break; - - case "httponly": // S5.2.6 -- effectively the same as 'secure' - c.httpOnly = true; - break; - - case "samesite": // RFC6265bis-02 S5.3.7 - const enforcement = av_value ? av_value.toLowerCase() : ""; - switch (enforcement) { - case "strict": - c.sameSite = "strict"; - break; - case "lax": - c.sameSite = "lax"; - break; - default: - // RFC6265bis-02 S5.3.7 step 1: - // "If cookie-av's attribute-value is not a case-insensitive match - // for "Strict" or "Lax", ignore the "cookie-av"." - // This effectively sets it to 'none' from the prototype. - break; - } - break; - - default: - c.extensions = c.extensions || []; - c.extensions.push(av); - break; - } - } - - return c; -} - -/** - * If the cookie-name begins with a case-sensitive match for the - * string "__Secure-", abort these steps and ignore the cookie - * entirely unless the cookie's secure-only-flag is true. - * @param cookie - * @returns boolean - */ -function isSecurePrefixConditionMet(cookie) { - return !cookie.key.startsWith("__Secure-") || cookie.secure; -} - -/** - * If the cookie-name begins with a case-sensitive match for the - * string "__Host-", abort these steps and ignore the cookie - * entirely unless the cookie meets all the following criteria: - * 1. The cookie's secure-only-flag is true. - * 2. The cookie's host-only-flag is true. - * 3. The cookie-attribute-list contains an attribute with an - * attribute-name of "Path", and the cookie's path is "/". - * @param cookie - * @returns boolean - */ -function isHostPrefixConditionMet(cookie) { - return ( - !cookie.key.startsWith("__Host-") || - (cookie.secure && - cookie.hostOnly && - cookie.path != null && - cookie.path === "/") - ); -} - -// avoid the V8 deoptimization monster! -function jsonParse(str) { - let obj; - try { - obj = JSON.parse(str); - } catch (e) { - return e; - } - return obj; -} - -function fromJSON(str) { - if (!str) { - return null; - } - - let obj; - if (typeof str === "string") { - obj = jsonParse(str); - if (obj instanceof Error) { - return null; + pubSuf = pubsuffix.getPublicSuffix(domain); } } else { - // assume it's an Object - obj = str; + pubSuf = pubsuffix.getPublicSuffix(domain); } - const c = new Cookie(); - for (let i = 0; i < Cookie.serializableProperties.length; i++) { - const prop = Cookie.serializableProperties[i]; - if (obj[prop] === undefined || obj[prop] === cookieDefaults[prop]) { - continue; // leave as prototype default - } - - if (prop === "expires" || prop === "creation" || prop === "lastAccessed") { - if (obj[prop] === null) { - c[prop] = null; - } else { - c[prop] = obj[prop] == "Infinity" ? "Infinity" : new Date(obj[prop]); - } - } else { - c[prop] = obj[prop]; - } + if (!pubSuf) { + return null; + } + if (pubSuf == domain) { + return [domain]; } - return c; -} - -/* Section 5.4 part 2: - * "* Cookies with longer paths are listed before cookies with - * shorter paths. - * - * * Among cookies that have equal-length path fields, cookies with - * earlier creation-times are listed before cookies with later - * creation-times." - */ - -function cookieCompare(a, b) { - let cmp = 0; - - // descending for length: b CMP a - const aPathLen = a.path ? a.path.length : 0; - const bPathLen = b.path ? b.path.length : 0; - cmp = bPathLen - aPathLen; - if (cmp !== 0) { - return cmp; + const prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com" + const parts = prefix.split(".").reverse(); + let cur = pubSuf; + const permutations = [cur]; + while (parts.length) { + cur = `${parts.shift()}.${cur}`; + permutations.push(cur); } - - // ascending for time: a CMP b - const aTime = a.creation ? a.creation.getTime() : MAX_TIME; - const bTime = b.creation ? b.creation.getTime() : MAX_TIME; - cmp = aTime - bTime; - if (cmp !== 0) { - return cmp; - } - - // break ties for the same millisecond (precision of JavaScript's clock) - cmp = a.creationIndex - b.creationIndex; - - return cmp; -} - -// Gives the permutation of all possible pathMatch()es of a given path. The -// array is in longest-to-shortest order. Handy for indexing. -function permutePath(path) { - if (path === "/") { - return ["/"]; - } - const permutations = [path]; - while (path.length > 1) { - const lindex = path.lastIndexOf("/"); - if (lindex === 0) { - break; - } - path = path.substr(0, lindex); - permutations.push(path); - } - permutations.push("/"); return permutations; } -function getCookieContext(url) { - if (url instanceof Object) { - return url; - } - // NOTE: decodeURI will throw on malformed URIs (see GH-32). - // Therefore, we will just skip decoding for such URIs. - try { - url = decodeURI(url); - } catch (err) { - // Silently swallow error - } - - return urlParse(url); -} - -const cookieDefaults = { - // the order in which the RFC has them: - key: "", - value: "", - expires: "Infinity", - maxAge: null, - domain: null, - path: null, - secure: false, - httpOnly: false, - extensions: null, - // set by the CookieJar: - hostOnly: null, - pathIsDefault: null, - creation: null, - lastAccessed: null, - sameSite: "none" -}; - -class Cookie { - constructor(options = {}) { - if (util.inspect.custom) { - this[util.inspect.custom] = this.inspect; - } - - Object.assign(this, cookieDefaults, options); - this.creation = this.creation || new Date(); - - // used to break creation ties in cookieCompare(): - Object.defineProperty(this, "creationIndex", { - configurable: false, - enumerable: false, // important for assert.deepEqual checks - writable: true, - value: ++Cookie.cookiesCreated - }); - } - - inspect() { - const now = Date.now(); - const hostOnly = this.hostOnly != null ? this.hostOnly : "?"; - const createAge = this.creation - ? `${now - this.creation.getTime()}ms` - : "?"; - const accessAge = this.lastAccessed - ? `${now - this.lastAccessed.getTime()}ms` - : "?"; - return `Cookie="${this.toString()}; hostOnly=${hostOnly}; aAge=${accessAge}; cAge=${createAge}"`; - } - - toJSON() { - const obj = {}; - - for (const prop of Cookie.serializableProperties) { - if (this[prop] === cookieDefaults[prop]) { - continue; // leave as prototype default - } - - if ( - prop === "expires" || - prop === "creation" || - prop === "lastAccessed" - ) { - if (this[prop] === null) { - obj[prop] = null; - } else { - obj[prop] = - this[prop] == "Infinity" // intentionally not === - ? "Infinity" - : this[prop].toISOString(); - } - } else if (prop === "maxAge") { - if (this[prop] !== null) { - // again, intentionally not === - obj[prop] = - this[prop] == Infinity || this[prop] == -Infinity - ? this[prop].toString() - : this[prop]; - } - } else { - if (this[prop] !== cookieDefaults[prop]) { - obj[prop] = this[prop]; - } - } - } - - return obj; - } - - clone() { - return fromJSON(this.toJSON()); - } - - validate() { - if (!COOKIE_OCTETS.test(this.value)) { - return false; - } - if ( - this.expires != Infinity && - !(this.expires instanceof Date) && - !parseDate(this.expires) - ) { - return false; - } - if (this.maxAge != null && this.maxAge <= 0) { - return false; // "Max-Age=" non-zero-digit *DIGIT - } - if (this.path != null && !PATH_VALUE.test(this.path)) { - return false; - } - - const cdomain = this.cdomain(); - if (cdomain) { - if (cdomain.match(/\.$/)) { - return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this - } - const suffix = pubsuffix.getPublicSuffix(cdomain); - if (suffix == null) { - // it's a public suffix - return false; - } - } - return true; - } - - setExpires(exp) { - if (exp instanceof Date) { - this.expires = exp; - } else { - this.expires = parseDate(exp) || "Infinity"; - } - } - - setMaxAge(age) { - if (age === Infinity || age === -Infinity) { - this.maxAge = age.toString(); // so JSON.stringify() works - } else { - this.maxAge = age; - } - } - - cookieString() { - let val = this.value; - if (val == null) { - val = ""; - } - if (this.key === "") { - return val; - } - return `${this.key}=${val}`; - } - - // gives Set-Cookie header format - toString() { - let str = this.cookieString(); - - if (this.expires != Infinity) { - if (this.expires instanceof Date) { - str += `; Expires=${formatDate(this.expires)}`; - } else { - str += `; Expires=${this.expires}`; - } - } - - if (this.maxAge != null && this.maxAge != Infinity) { - str += `; Max-Age=${this.maxAge}`; - } - - if (this.domain && !this.hostOnly) { - str += `; Domain=${this.domain}`; - } - if (this.path) { - str += `; Path=${this.path}`; - } - - if (this.secure) { - str += "; Secure"; - } - if (this.httpOnly) { - str += "; HttpOnly"; - } - if (this.sameSite && this.sameSite !== "none") { - const ssCanon = Cookie.sameSiteCanonical[this.sameSite.toLowerCase()]; - str += `; SameSite=${ssCanon ? ssCanon : this.sameSite}`; - } - if (this.extensions) { - this.extensions.forEach(ext => { - str += `; ${ext}`; - }); - } - - return str; - } - - // TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie() - // elsewhere) - // S5.3 says to give the "latest representable date" for which we use Infinity - // For "expired" we use 0 - TTL(now) { - /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires - * attribute, the Max-Age attribute has precedence and controls the - * expiration date of the cookie. - * (Concurs with S5.3 step 3) - */ - if (this.maxAge != null) { - return this.maxAge <= 0 ? 0 : this.maxAge * 1000; - } - - let expires = this.expires; - if (expires != Infinity) { - if (!(expires instanceof Date)) { - expires = parseDate(expires) || Infinity; - } - - if (expires == Infinity) { - return Infinity; - } - - return expires.getTime() - (now || Date.now()); - } - - return Infinity; - } - - // expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() - // elsewhere) - expiryTime(now) { - if (this.maxAge != null) { - const relativeTo = now || this.creation || new Date(); - const age = this.maxAge <= 0 ? -Infinity : this.maxAge * 1000; - return relativeTo.getTime() + age; - } - - if (this.expires == Infinity) { - return Infinity; - } - return this.expires.getTime(); - } - - // expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() - // elsewhere), except it returns a Date - expiryDate(now) { - const millisec = this.expiryTime(now); - if (millisec == Infinity) { - return new Date(MAX_TIME); - } else if (millisec == -Infinity) { - return new Date(MIN_TIME); - } else { - return new Date(millisec); - } - } - - // This replaces the "persistent-flag" parts of S5.3 step 3 - isPersistent() { - return this.maxAge != null || this.expires != Infinity; - } - - // Mostly S5.1.2 and S5.2.3: - canonicalizedDomain() { - if (this.domain == null) { - return null; - } - return canonicalDomain(this.domain); - } - - cdomain() { - return this.canonicalizedDomain(); - } -} - -Cookie.cookiesCreated = 0; -Cookie.parse = parse; -Cookie.fromJSON = fromJSON; -Cookie.serializableProperties = Object.keys(cookieDefaults); -Cookie.sameSiteLevel = { - strict: 3, - lax: 2, - none: 1 -}; - -Cookie.sameSiteCanonical = { - strict: "Strict", - lax: "Lax" -}; - -function getNormalizedPrefixSecurity(prefixSecurity) { - if (prefixSecurity != null) { - const normalizedPrefixSecurity = prefixSecurity.toLowerCase(); - /* The three supported options */ - switch (normalizedPrefixSecurity) { - case PrefixSecurityEnum.STRICT: - case PrefixSecurityEnum.SILENT: - case PrefixSecurityEnum.DISABLED: - return normalizedPrefixSecurity; - } - } - /* Default is SILENT */ - return PrefixSecurityEnum.SILENT; -} - -class CookieJar { - constructor(store, options = { rejectPublicSuffixes: true }) { - if (typeof options === "boolean") { - options = { rejectPublicSuffixes: options }; - } - this.rejectPublicSuffixes = options.rejectPublicSuffixes; - this.enableLooseMode = !!options.looseMode; - this.allowSpecialUseDomain = !!options.allowSpecialUseDomain; - this.store = store || new MemoryCookieStore(); - this.prefixSecurity = getNormalizedPrefixSecurity(options.prefixSecurity); - this._cloneSync = syncWrap("clone"); - this._importCookiesSync = syncWrap("_importCookies"); - this.getCookiesSync = syncWrap("getCookies"); - this.getCookieStringSync = syncWrap("getCookieString"); - this.getSetCookieStringsSync = syncWrap("getSetCookieStrings"); - this.removeAllCookiesSync = syncWrap("removeAllCookies"); - this.setCookieSync = syncWrap("setCookie"); - this.serializeSync = syncWrap("serialize"); - } - - setCookie(cookie, url, options, cb) { - let err; - const context = getCookieContext(url); - if (typeof options === "function") { - cb = options; - options = {}; - } - - const host = canonicalDomain(context.hostname); - const loose = options.loose || this.enableLooseMode; - - let sameSiteContext = null; - if (options.sameSiteContext) { - sameSiteContext = checkSameSiteContext(options.sameSiteContext); - if (!sameSiteContext) { - return cb(new Error(SAME_SITE_CONTEXT_VAL_ERR)); - } - } - - // S5.3 step 1 - if (typeof cookie === "string" || cookie instanceof String) { - cookie = Cookie.parse(cookie, { loose: loose }); - if (!cookie) { - err = new Error("Cookie failed to parse"); - return cb(options.ignoreError ? null : err); - } - } else if (!(cookie instanceof Cookie)) { - // If you're seeing this error, and are passing in a Cookie object, - // it *might* be a Cookie object from another loaded version of tough-cookie. - err = new Error( - "First argument to setCookie must be a Cookie object or string" - ); - return cb(options.ignoreError ? null : err); - } - - // S5.3 step 2 - const now = options.now || new Date(); // will assign later to save effort in the face of errors - - // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie() - - // S5.3 step 4: NOOP; domain is null by default - - // S5.3 step 5: public suffixes - if (this.rejectPublicSuffixes && cookie.domain) { - const suffix = pubsuffix.getPublicSuffix(cookie.cdomain()); - if (suffix == null) { - // e.g. "com" - err = new Error("Cookie has domain set to a public suffix"); - return cb(options.ignoreError ? null : err); - } - } - - // S5.3 step 6: - if (cookie.domain) { - if (!domainMatch(host, cookie.cdomain(), false)) { - err = new Error( - `Cookie not in this host's domain. Cookie:${cookie.cdomain()} Request:${host}` - ); - return cb(options.ignoreError ? null : err); - } - - if (cookie.hostOnly == null) { - // don't reset if already set - cookie.hostOnly = false; - } - } else { - cookie.hostOnly = true; - cookie.domain = host; - } - - //S5.2.4 If the attribute-value is empty or if the first character of the - //attribute-value is not %x2F ("/"): - //Let cookie-path be the default-path. - if (!cookie.path || cookie.path[0] !== "/") { - cookie.path = defaultPath(context.pathname); - cookie.pathIsDefault = true; - } - - // S5.3 step 8: NOOP; secure attribute - // S5.3 step 9: NOOP; httpOnly attribute - - // S5.3 step 10 - if (options.http === false && cookie.httpOnly) { - err = new Error("Cookie is HttpOnly and this isn't an HTTP API"); - return cb(options.ignoreError ? null : err); - } - - // 6252bis-02 S5.4 Step 13 & 14: - if (cookie.sameSite !== "none" && sameSiteContext) { - // "If the cookie's "same-site-flag" is not "None", and the cookie - // is being set from a context whose "site for cookies" is not an - // exact match for request-uri's host's registered domain, then - // abort these steps and ignore the newly created cookie entirely." - if (sameSiteContext === "none") { - err = new Error( - "Cookie is SameSite but this is a cross-origin request" - ); - return cb(options.ignoreError ? null : err); - } - } - - /* 6265bis-02 S5.4 Steps 15 & 16 */ - const ignoreErrorForPrefixSecurity = - this.prefixSecurity === PrefixSecurityEnum.SILENT; - const prefixSecurityDisabled = - this.prefixSecurity === PrefixSecurityEnum.DISABLED; - /* If prefix checking is not disabled ...*/ - if (!prefixSecurityDisabled) { - let errorFound = false; - let errorMsg; - /* Check secure prefix condition */ - if (!isSecurePrefixConditionMet(cookie)) { - errorFound = true; - errorMsg = "Cookie has __Secure prefix but Secure attribute is not set"; - } else if (!isHostPrefixConditionMet(cookie)) { - /* Check host prefix condition */ - errorFound = true; - errorMsg = - "Cookie has __Host prefix but either Secure or HostOnly attribute is not set or Path is not '/'"; - } - if (errorFound) { - return cb( - options.ignoreError || ignoreErrorForPrefixSecurity - ? null - : new Error(errorMsg) - ); - } - } - - const store = this.store; - - if (!store.updateCookie) { - store.updateCookie = function(oldCookie, newCookie, cb) { - this.putCookie(newCookie, cb); - }; - } - - function withCookie(err, oldCookie) { - if (err) { - return cb(err); - } - - const next = function(err) { - if (err) { - return cb(err); - } else { - cb(null, cookie); - } - }; - - if (oldCookie) { - // S5.3 step 11 - "If the cookie store contains a cookie with the same name, - // domain, and path as the newly created cookie:" - if (options.http === false && oldCookie.httpOnly) { - // step 11.2 - err = new Error("old Cookie is HttpOnly and this isn't an HTTP API"); - return cb(options.ignoreError ? null : err); - } - cookie.creation = oldCookie.creation; // step 11.3 - cookie.creationIndex = oldCookie.creationIndex; // preserve tie-breaker - cookie.lastAccessed = now; - // Step 11.4 (delete cookie) is implied by just setting the new one: - store.updateCookie(oldCookie, cookie, next); // step 12 - } else { - cookie.creation = cookie.lastAccessed = now; - store.putCookie(cookie, next); // step 12 - } - } - - store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie); - } - - // RFC6365 S5.4 - getCookies(url, options, cb) { - const context = getCookieContext(url); - if (typeof options === "function") { - cb = options; - options = {}; - } - - const host = canonicalDomain(context.hostname); - const path = context.pathname || "/"; - - let secure = options.secure; - if ( - secure == null && - context.protocol && - (context.protocol == "https:" || context.protocol == "wss:") - ) { - secure = true; - } - - let sameSiteLevel = 0; - if (options.sameSiteContext) { - const sameSiteContext = checkSameSiteContext(options.sameSiteContext); - sameSiteLevel = Cookie.sameSiteLevel[sameSiteContext]; - if (!sameSiteLevel) { - return cb(new Error(SAME_SITE_CONTEXT_VAL_ERR)); - } - } - - let http = options.http; - if (http == null) { - http = true; - } - - const now = options.now || Date.now(); - const expireCheck = options.expire !== false; - const allPaths = !!options.allPaths; - const store = this.store; - - function matchingCookie(c) { - // "Either: - // The cookie's host-only-flag is true and the canonicalized - // request-host is identical to the cookie's domain. - // Or: - // The cookie's host-only-flag is false and the canonicalized - // request-host domain-matches the cookie's domain." - if (c.hostOnly) { - if (c.domain != host) { - return false; - } - } else { - if (!domainMatch(host, c.domain, false)) { - return false; - } - } - - // "The request-uri's path path-matches the cookie's path." - if (!allPaths && !pathMatch(path, c.path)) { - return false; - } - - // "If the cookie's secure-only-flag is true, then the request-uri's - // scheme must denote a "secure" protocol" - if (c.secure && !secure) { - return false; - } - - // "If the cookie's http-only-flag is true, then exclude the cookie if the - // cookie-string is being generated for a "non-HTTP" API" - if (c.httpOnly && !http) { - return false; - } - - // RFC6265bis-02 S5.3.7 - if (sameSiteLevel) { - const cookieLevel = Cookie.sameSiteLevel[c.sameSite || "none"]; - if (cookieLevel > sameSiteLevel) { - // only allow cookies at or below the request level - return false; - } - } - - // deferred from S5.3 - // non-RFC: allow retention of expired cookies by choice - if (expireCheck && c.expiryTime() <= now) { - store.removeCookie(c.domain, c.path, c.key, () => {}); // result ignored - return false; - } - - return true; - } - - store.findCookies( - host, - allPaths ? null : path, - this.allowSpecialUseDomain, - (err, cookies) => { - if (err) { - return cb(err); - } - - cookies = cookies.filter(matchingCookie); - - // sorting of S5.4 part 2 - if (options.sort !== false) { - cookies = cookies.sort(cookieCompare); - } - - // S5.4 part 3 - const now = new Date(); - for (const cookie of cookies) { - cookie.lastAccessed = now; - } - // TODO persist lastAccessed - - cb(null, cookies); - } - ); - } - - getCookieString(...args) { - const cb = args.pop(); - const next = function(err, cookies) { - if (err) { - cb(err); - } else { - cb( - null, - cookies - .sort(cookieCompare) - .map(c => c.cookieString()) - .join("; ") - ); - } - }; - args.push(next); - this.getCookies.apply(this, args); - } - - getSetCookieStrings(...args) { - const cb = args.pop(); - const next = function(err, cookies) { - if (err) { - cb(err); - } else { - cb( - null, - cookies.map(c => { - return c.toString(); - }) - ); - } - }; - args.push(next); - this.getCookies.apply(this, args); - } - - serialize(cb) { - let type = this.store.constructor.name; - if (type === "Object") { - type = null; - } - - // update README.md "Serialization Format" if you change this, please! - const serialized = { - // The version of tough-cookie that serialized this jar. Generally a good - // practice since future versions can make data import decisions based on - // known past behavior. When/if this matters, use `semver`. - version: `tough-cookie@${VERSION}`, - - // add the store type, to make humans happy: - storeType: type, - - // CookieJar configuration: - rejectPublicSuffixes: !!this.rejectPublicSuffixes, - - // this gets filled from getAllCookies: - cookies: [] - }; - - if ( - !( - this.store.getAllCookies && - typeof this.store.getAllCookies === "function" - ) - ) { - return cb( - new Error( - "store does not support getAllCookies and cannot be serialized" - ) - ); - } - - this.store.getAllCookies((err, cookies) => { - if (err) { - return cb(err); - } - - serialized.cookies = cookies.map(cookie => { - // convert to serialized 'raw' cookies - cookie = cookie instanceof Cookie ? cookie.toJSON() : cookie; - - // Remove the index so new ones get assigned during deserialization - delete cookie.creationIndex; - - return cookie; - }); - - return cb(null, serialized); - }); - } - - toJSON() { - return this.serializeSync(); - } - - // use the class method CookieJar.deserialize instead of calling this directly - _importCookies(serialized, cb) { - let cookies = serialized.cookies; - if (!cookies || !Array.isArray(cookies)) { - return cb(new Error("serialized jar has no cookies array")); - } - cookies = cookies.slice(); // do not modify the original - - const putNext = err => { - if (err) { - return cb(err); - } - - if (!cookies.length) { - return cb(err, this); - } - - let cookie; - try { - cookie = fromJSON(cookies.shift()); - } catch (e) { - return cb(e); - } - - if (cookie === null) { - return putNext(null); // skip this cookie - } - - this.store.putCookie(cookie, putNext); - }; - - putNext(); - } - - clone(newStore, cb) { - if (arguments.length === 1) { - cb = newStore; - newStore = null; - } - - this.serialize((err, serialized) => { - if (err) { - return cb(err); - } - CookieJar.deserialize(serialized, newStore, cb); - }); - } - - cloneSync(newStore) { - if (arguments.length === 0) { - return this._cloneSync(); - } - if (!newStore.synchronous) { - throw new Error( - "CookieJar clone destination store is not synchronous; use async API instead." - ); - } - return this._cloneSync(newStore); - } - - removeAllCookies(cb) { - const store = this.store; - - // Check that the store implements its own removeAllCookies(). The default - // implementation in Store will immediately call the callback with a "not - // implemented" Error. - if ( - typeof store.removeAllCookies === "function" && - store.removeAllCookies !== Store.prototype.removeAllCookies - ) { - return store.removeAllCookies(cb); - } - - store.getAllCookies((err, cookies) => { - if (err) { - return cb(err); - } - - if (cookies.length === 0) { - return cb(null); - } - - let completedCount = 0; - const removeErrors = []; - - function removeCookieCb(removeErr) { - if (removeErr) { - removeErrors.push(removeErr); - } - - completedCount++; - - if (completedCount === cookies.length) { - return cb(removeErrors.length ? removeErrors[0] : null); - } - } - - cookies.forEach(cookie => { - store.removeCookie( - cookie.domain, - cookie.path, - cookie.key, - removeCookieCb - ); - }); - }); - } - - static deserialize(strOrObj, store, cb) { - if (arguments.length !== 3) { - // store is optional - cb = store; - store = null; - } - - let serialized; - if (typeof strOrObj === "string") { - serialized = jsonParse(strOrObj); - if (serialized instanceof Error) { - return cb(serialized); - } - } else { - serialized = strOrObj; - } - - const jar = new CookieJar(store, serialized.rejectPublicSuffixes); - jar._importCookies(serialized, err => { - if (err) { - return cb(err); - } - cb(null, jar); - }); - } - - static deserializeSync(strOrObj, store) { - const serialized = - typeof strOrObj === "string" ? JSON.parse(strOrObj) : strOrObj; - const jar = new CookieJar(store, serialized.rejectPublicSuffixes); - - // catch this mistake early: - if (!jar.store.synchronous) { - throw new Error( - "CookieJar store is not synchronous; use async API instead." - ); - } - - jar._importCookiesSync(serialized); - return jar; - } -} -CookieJar.fromJSON = CookieJar.deserializeSync; - -[ - "_importCookies", - "clone", - "getCookies", - "getCookieString", - "getSetCookieStrings", - "removeAllCookies", - "serialize", - "setCookie" -].forEach(name => { - CookieJar.prototype[name] = fromCallback(CookieJar.prototype[name]); -}); -CookieJar.deserialize = fromCallback(CookieJar.deserialize); - -// Use a closure to provide a true imperative API for synchronous stores. -function syncWrap(method) { - return function(...args) { - if (!this.store.synchronous) { - throw new Error( - "CookieJar store is not synchronous; use async API instead." - ); - } - - let syncErr, syncResult; - this[method](...args, (err, result) => { - syncErr = err; - syncResult = result; - }); - - if (syncErr) { - throw syncErr; - } - return syncResult; - }; -} - -exports.version = VERSION; -exports.CookieJar = CookieJar; -exports.Cookie = Cookie; -exports.Store = Store; -exports.MemoryCookieStore = MemoryCookieStore; -exports.parseDate = parseDate; -exports.formatDate = formatDate; -exports.parse = parse; -exports.fromJSON = fromJSON; -exports.domainMatch = domainMatch; -exports.defaultPath = defaultPath; -exports.pathMatch = pathMatch; -exports.getPublicSuffix = pubsuffix.getPublicSuffix; -exports.cookieCompare = cookieCompare; -exports.permuteDomain = __webpack_require__(898).permuteDomain; -exports.permutePath = permutePath; -exports.canonicalDomain = canonicalDomain; -exports.PrefixSecurityEnum = PrefixSecurityEnum; +exports.permuteDomain = permuteDomain; /***/ }), +/* 384 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; + +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SearchState = void 0; +class SearchState { + constructor(path, level) { + this.path = path; + this.level = level; + } +} +exports.SearchState = SearchState; +//# sourceMappingURL=internal-search-state.js.map + +/***/ }), +/* 385 */, +/* 386 */, +/* 387 */, +/* 388 */, +/* 389 */, +/* 390 */, +/* 391 */, +/* 392 */, +/* 393 */, /* 394 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { @@ -38849,6 +32858,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.ProxyTracerProvider = void 0; var ProxyTracer_1 = __webpack_require__(398); var NoopTracerProvider_1 = __webpack_require__(162); +var NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); /** * Tracer provider which provides {@link ProxyTracer}s. * @@ -38869,7 +32879,7 @@ var ProxyTracerProvider = /** @class */ (function () { }; ProxyTracerProvider.prototype.getDelegate = function () { var _a; - return (_a = this._delegate) !== null && _a !== void 0 ? _a : NoopTracerProvider_1.NOOP_TRACER_PROVIDER; + return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER; }; /** * Set the delegate tracer provider @@ -38913,6 +32923,7 @@ exports.ProxyTracerProvider = ProxyTracerProvider; Object.defineProperty(exports, "__esModule", { value: true }); exports.ProxyTracer = void 0; var NoopTracer_1 = __webpack_require__(151); +var NOOP_TRACER = new NoopTracer_1.NoopTracer(); /** * Proxy tracer provided by the proxy tracer provider */ @@ -38925,6 +32936,10 @@ var ProxyTracer = /** @class */ (function () { ProxyTracer.prototype.startSpan = function (name, options, context) { return this._getTracer().startSpan(name, options, context); }; + ProxyTracer.prototype.startActiveSpan = function (_name, _options, _context, _fn) { + var tracer = this._getTracer(); + return Reflect.apply(tracer.startActiveSpan, tracer, arguments); + }; /** * Try to get a tracer from the proxy tracer provider. * If the proxy tracer provider has no delegate, return a noop tracer. @@ -38935,7 +32950,7 @@ var ProxyTracer = /** @class */ (function () { } var tracer = this._provider.getDelegateTracer(this.name, this.version); if (!tracer) { - return NoopTracer_1.NOOP_TRACER; + return NOOP_TRACER; } this._delegate = tracer; return this._delegate; @@ -39001,7 +33016,7 @@ module.exports = require("crypto"); XMLComment = __webpack_require__(919); - XMLElement = __webpack_require__(701); + XMLElement = __webpack_require__(845); XMLRaw = __webpack_require__(660); @@ -39484,12 +33499,10 @@ function parallel(list, iterator, callback) * See the License for the specific language governing permissions and * limitations under the License. */ -var __spreadArrays = (this && this.__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; +var __spreadArray = (this && this.__spreadArray) || function (to, from) { + for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) + to[j] = from[i]; + return to; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.NoopContextManager = void 0; @@ -39505,9 +33518,9 @@ var NoopContextManager = /** @class */ (function () { for (var _i = 3; _i < arguments.length; _i++) { args[_i - 3] = arguments[_i]; } - return fn.call.apply(fn, __spreadArrays([thisArg], args)); + return fn.call.apply(fn, __spreadArray([thisArg], args)); }; - NoopContextManager.prototype.bind = function (target, _context) { + NoopContextManager.prototype.bind = function (_context, target) { return target; }; NoopContextManager.prototype.enable = function () { @@ -39797,9 +33810,111 @@ exports.listTar = listTar; //# sourceMappingURL=tar.js.map /***/ }), -/* 435 */, +/* 435 */ +/***/ (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.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; +var trace_flags_1 = __webpack_require__(975); +exports.INVALID_SPANID = '0000000000000000'; +exports.INVALID_TRACEID = '00000000000000000000000000000000'; +exports.INVALID_SPAN_CONTEXT = { + traceId: exports.INVALID_TRACEID, + spanId: exports.INVALID_SPANID, + traceFlags: trace_flags_1.TraceFlags.NONE, +}; +//# sourceMappingURL=invalid-span-constants.js.map + +/***/ }), /* 436 */, -/* 437 */, +/* 437 */ +/***/ (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.NonRecordingSpan = void 0; +var invalid_span_constants_1 = __webpack_require__(435); +/** + * The NonRecordingSpan is the default {@link Span} that is used when no Span + * implementation is available. All operations are no-op including context + * propagation. + */ +var NonRecordingSpan = /** @class */ (function () { + function NonRecordingSpan(_spanContext) { + if (_spanContext === void 0) { _spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT; } + this._spanContext = _spanContext; + } + // Returns a SpanContext. + NonRecordingSpan.prototype.spanContext = function () { + return this._spanContext; + }; + // By default does nothing + NonRecordingSpan.prototype.setAttribute = function (_key, _value) { + return this; + }; + // By default does nothing + NonRecordingSpan.prototype.setAttributes = function (_attributes) { + return this; + }; + // By default does nothing + NonRecordingSpan.prototype.addEvent = function (_name, _attributes) { + return this; + }; + // By default does nothing + NonRecordingSpan.prototype.setStatus = function (_status) { + return this; + }; + // By default does nothing + NonRecordingSpan.prototype.updateName = function (_name) { + return this; + }; + // By default does nothing + NonRecordingSpan.prototype.end = function (_endTime) { }; + // isRecording always returns false for NonRecordingSpan. + NonRecordingSpan.prototype.isRecording = function () { + return false; + }; + // By default does nothing + NonRecordingSpan.prototype.recordException = function (_exception, _time) { }; + return NonRecordingSpan; +}()); +exports.NonRecordingSpan = NonRecordingSpan; +//# sourceMappingURL=NonRecordingSpan.js.map + +/***/ }), /* 438 */, /* 439 */, /* 440 */ @@ -39833,19 +33948,16 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); -exports.diag = exports.propagation = exports.trace = exports.context = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; -__exportStar(__webpack_require__(792), exports); +exports.diag = exports.propagation = exports.trace = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.baggageEntryMetadataFromString = void 0; +__exportStar(__webpack_require__(880), exports); +var utils_1 = __webpack_require__(112); +Object.defineProperty(exports, "baggageEntryMetadataFromString", { enumerable: true, get: function () { return utils_1.baggageEntryMetadataFromString; } }); __exportStar(__webpack_require__(452), exports); __exportStar(__webpack_require__(158), exports); __exportStar(__webpack_require__(893), exports); -__exportStar(__webpack_require__(918), exports); __exportStar(__webpack_require__(881), exports); __exportStar(__webpack_require__(906), exports); -__exportStar(__webpack_require__(727), exports); -__exportStar(__webpack_require__(851), exports); __exportStar(__webpack_require__(95), exports); -__exportStar(__webpack_require__(151), exports); -__exportStar(__webpack_require__(162), exports); __exportStar(__webpack_require__(398), exports); __exportStar(__webpack_require__(394), exports); __exportStar(__webpack_require__(781), exports); @@ -39855,28 +33967,27 @@ __exportStar(__webpack_require__(670), exports); __exportStar(__webpack_require__(586), exports); __exportStar(__webpack_require__(220), exports); __exportStar(__webpack_require__(932), exports); -__exportStar(__webpack_require__(839), exports); __exportStar(__webpack_require__(975), exports); __exportStar(__webpack_require__(70), exports); __exportStar(__webpack_require__(694), exports); __exportStar(__webpack_require__(695), exports); var spancontext_utils_1 = __webpack_require__(629); -Object.defineProperty(exports, "INVALID_SPANID", { enumerable: true, get: function () { return spancontext_utils_1.INVALID_SPANID; } }); -Object.defineProperty(exports, "INVALID_TRACEID", { enumerable: true, get: function () { return spancontext_utils_1.INVALID_TRACEID; } }); -Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", { enumerable: true, get: function () { return spancontext_utils_1.INVALID_SPAN_CONTEXT; } }); Object.defineProperty(exports, "isSpanContextValid", { enumerable: true, get: function () { return spancontext_utils_1.isSpanContextValid; } }); Object.defineProperty(exports, "isValidTraceId", { enumerable: true, get: function () { return spancontext_utils_1.isValidTraceId; } }); Object.defineProperty(exports, "isValidSpanId", { enumerable: true, get: function () { return spancontext_utils_1.isValidSpanId; } }); +var invalid_span_constants_1 = __webpack_require__(435); +Object.defineProperty(exports, "INVALID_SPANID", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPANID; } }); +Object.defineProperty(exports, "INVALID_TRACEID", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_TRACEID; } }); +Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPAN_CONTEXT; } }); __exportStar(__webpack_require__(132), exports); -__exportStar(__webpack_require__(425), exports); -__exportStar(__webpack_require__(845), exports); +__exportStar(__webpack_require__(165), exports); var context_1 = __webpack_require__(492); /** Entrypoint for context API */ exports.context = context_1.ContextAPI.getInstance(); var trace_1 = __webpack_require__(875); /** Entrypoint for trace API */ exports.trace = trace_1.TraceAPI.getInstance(); -var propagation_1 = __webpack_require__(21); +var propagation_1 = __webpack_require__(22); /** Entrypoint for propagation API */ exports.propagation = propagation_1.PropagationAPI.getInstance(); var diag_1 = __webpack_require__(118); @@ -41836,8 +35947,7 @@ exports.FetchError = FetchError; /***/ }), -/* 459 */, -/* 460 */ +/* 459 */ /***/ (function(module) { // generated by genversion @@ -41845,6 +35955,7 @@ module.exports = '4.0.0' /***/ }), +/* 460 */, /* 461 */, /* 462 */, /* 463 */ @@ -42477,7 +36588,65 @@ exports.getIDToken = getIDToken; /* 480 */, /* 481 */, /* 482 */, -/* 483 */, +/* 483 */ +/***/ (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.deleteBaggage = exports.setBaggage = exports.getBaggage = void 0; +var context_1 = __webpack_require__(132); +/** + * Baggage key + */ +var BAGGAGE_KEY = context_1.createContextKey('OpenTelemetry Baggage Key'); +/** + * Retrieve the current baggage from the given context + * + * @param {Context} Context that manage all context values + * @returns {Baggage} Extracted baggage from the context + */ +function getBaggage(context) { + return context.getValue(BAGGAGE_KEY) || undefined; +} +exports.getBaggage = getBaggage; +/** + * Store a baggage in the given context + * + * @param {Context} Context that manage all context values + * @param {Baggage} baggage that will be set in the actual context + */ +function setBaggage(context, baggage) { + return context.setValue(BAGGAGE_KEY, baggage); +} +exports.setBaggage = setBaggage; +/** + * Delete the baggage stored in the given context + * + * @param {Context} Context that manage all context values + */ +function deleteBaggage(context) { + return context.deleteValue(BAGGAGE_KEY); +} +exports.deleteBaggage = deleteBaggage; +//# sourceMappingURL=context-helpers.js.map + +/***/ }), /* 484 */, /* 485 */, /* 486 */, @@ -42573,17 +36742,16 @@ module.exports = function nodeRNG() { * See the License for the specific language governing permissions and * limitations under the License. */ -var __spreadArrays = (this && this.__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; +var __spreadArray = (this && this.__spreadArray) || function (to, from) { + for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) + to[j] = from[i]; + return to; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ContextAPI = void 0; var NoopContextManager_1 = __webpack_require__(425); var global_utils_1 = __webpack_require__(525); +var diag_1 = __webpack_require__(118); var API_NAME = 'context'; var NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); /** @@ -42601,11 +36769,12 @@ var ContextAPI = /** @class */ (function () { return this._instance; }; /** - * Set the current context manager. Returns the initialized context manager + * Set the current context manager. + * + * @returns true if the context manager was successfully registered, else false */ ContextAPI.prototype.setGlobalContextManager = function (contextManager) { - global_utils_1.registerGlobal(API_NAME, contextManager); - return contextManager; + return global_utils_1.registerGlobal(API_NAME, contextManager, diag_1.DiagAPI.instance()); }; /** * Get the currently active context @@ -42627,17 +36796,16 @@ var ContextAPI = /** @class */ (function () { for (var _i = 3; _i < arguments.length; _i++) { args[_i - 3] = arguments[_i]; } - return (_a = this._getContextManager()).with.apply(_a, __spreadArrays([context, fn, thisArg], args)); + return (_a = this._getContextManager()).with.apply(_a, __spreadArray([context, fn, thisArg], args)); }; /** * Bind a context to a target function or event emitter * - * @param target function or event emitter to bind * @param context context to bind to the event emitter or function. Defaults to the currently active context + * @param target function or event emitter to bind */ - ContextAPI.prototype.bind = function (target, context) { - if (context === void 0) { context = this.active(); } - return this._getContextManager().bind(target, context); + ContextAPI.prototype.bind = function (context, target) { + return this._getContextManager().bind(context, target); }; ContextAPI.prototype._getContextManager = function () { return global_utils_1.getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER; @@ -42645,7 +36813,7 @@ var ContextAPI = /** @class */ (function () { /** Disable and remove the global context manager */ ContextAPI.prototype.disable = function () { this._getContextManager().disable(); - global_utils_1.unregisterGlobal(API_NAME); + global_utils_1.unregisterGlobal(API_NAME, diag_1.DiagAPI.instance()); }; return ContextAPI; }()); @@ -42706,10 +36874,79 @@ function defer(fn) "use strict"; + +Object.defineProperty(exports, '__esModule', { value: true }); + +__webpack_require__(338); +var tslib = __webpack_require__(671); + // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -__webpack_require__(71); +/** + * returns an async iterator that iterates over results. It also has a `byPage` + * method that returns pages of items at once. + * + * @param pagedResult - an object that specifies how to get pages. + * @returns a paged async iterator that iterates over results. + */ +function getPagedAsyncIterator(pagedResult) { + var _a; + const iter = getItemAsyncIterator(pagedResult); + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: (_a = pagedResult === null || pagedResult === void 0 ? void 0 : pagedResult.byPage) !== null && _a !== void 0 ? _a : ((settings) => { + return getPageAsyncIterator(pagedResult, settings === null || settings === void 0 ? void 0 : settings.maxPageSize); + }) + }; +} +function getItemAsyncIterator(pagedResult, maxPageSize) { + return tslib.__asyncGenerator(this, arguments, function* getItemAsyncIterator_1() { + var e_1, _a; + const pages = getPageAsyncIterator(pagedResult, maxPageSize); + const firstVal = yield tslib.__await(pages.next()); + // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is + if (!Array.isArray(firstVal.value)) { + yield yield tslib.__await(firstVal.value); + // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(pages))); + } + else { + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(firstVal.value))); + try { + for (var pages_1 = tslib.__asyncValues(pages), pages_1_1; pages_1_1 = yield tslib.__await(pages_1.next()), !pages_1_1.done;) { + const page = pages_1_1.value; + // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, + // it must be the case that `TPage = TElement[]` + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(page))); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (pages_1_1 && !pages_1_1.done && (_a = pages_1.return)) yield tslib.__await(_a.call(pages_1)); + } + finally { if (e_1) throw e_1.error; } + } + } + }); +} +function getPageAsyncIterator(pagedResult, maxPageSize) { + return tslib.__asyncGenerator(this, arguments, function* getPageAsyncIterator_1() { + let response = yield tslib.__await(pagedResult.getPage(pagedResult.firstPageLink, maxPageSize)); + yield yield tslib.__await(response.page); + while (response.nextPageLink) { + response = yield tslib.__await(pagedResult.getPage(response.nextPageLink, maxPageSize)); + yield yield tslib.__await(response.page); + } + }); +} + +exports.getPagedAsyncIterator = getPagedAsyncIterator; +//# sourceMappingURL=index.js.map /***/ }), @@ -42763,7 +37000,51 @@ module.exports = {"application/1d-interleaved-parityfec":{"source":"iana"},"appl /* 516 */, /* 517 */, /* 518 */, -/* 519 */, +/* 519 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2018, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +const psl = __webpack_require__(750); + +function getPublicSuffix(domain) { + return psl.get(domain); +} + +exports.getPublicSuffix = getPublicSuffix; + + +/***/ }), /* 520 */, /* 521 */, /* 522 */, @@ -42860,33 +37141,33 @@ module.exports = {"application/1d-interleaved-parityfec":{"source":"iana"},"appl */ Object.defineProperty(exports, "__esModule", { value: true }); exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0; -var __1 = __webpack_require__(440); var platform_1 = __webpack_require__(910); var version_1 = __webpack_require__(830); var semver_1 = __webpack_require__(987); var major = version_1.VERSION.split('.')[0]; -var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("io.opentelemetry.js.api." + major); +var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major); var _global = platform_1._globalThis; -function registerGlobal(type, instance, allowOverride) { +function registerGlobal(type, instance, diag, allowOverride) { var _a; if (allowOverride === void 0) { allowOverride = false; } - _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { + var api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { version: version_1.VERSION, - }; - var api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; + }); if (!allowOverride && api[type]) { // already registered an API of this type var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type); - __1.diag.error(err.stack || err.message); - return; + diag.error(err.stack || err.message); + return false; } if (api.version !== version_1.VERSION) { // All registered APIs must be of the same version exactly var err = new Error('@opentelemetry/api: All API registration versions must match'); - __1.diag.error(err.stack || err.message); - return; + diag.error(err.stack || err.message); + return false; } api[type] = instance; + diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + version_1.VERSION + "."); + return true; } exports.registerGlobal = registerGlobal; function getGlobal(type) { @@ -42898,7 +37179,8 @@ function getGlobal(type) { return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; } exports.getGlobal = getGlobal; -function unregisterGlobal(type) { +function unregisterGlobal(type, diag) { + diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + version_1.VERSION + "."); var api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; if (api) { delete api[type]; @@ -44103,51 +38385,7 @@ exports.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); //# sourceMappingURL=symbol.js.map /***/ }), -/* 562 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; -/*! - * Copyright (c) 2018, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of Salesforce.com nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -const psl = __webpack_require__(750); - -function getPublicSuffix(domain) { - return psl.get(domain); -} - -exports.getPublicSuffix = getPublicSuffix; - - -/***/ }), +/* 562 */, /* 563 */, /* 564 */, /* 565 */, @@ -44413,76 +38651,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); /* 596 */, /* 597 */, /* 598 */, -/* 599 */ -/***/ (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 }); -exports.BaggageImpl = void 0; -var BaggageImpl = /** @class */ (function () { - function BaggageImpl(entries) { - this._entries = entries ? new Map(entries) : new Map(); - } - BaggageImpl.prototype.getEntry = function (key) { - var entry = this._entries.get(key); - if (!entry) { - return undefined; - } - return Object.assign({}, entry); - }; - BaggageImpl.prototype.getAllEntries = function () { - return Array.from(this._entries.entries()).map(function (_a) { - var k = _a[0], v = _a[1]; - return [k, v]; - }); - }; - BaggageImpl.prototype.setEntry = function (key, entry) { - var newBaggage = new BaggageImpl(this._entries); - newBaggage._entries.set(key, entry); - return newBaggage; - }; - BaggageImpl.prototype.removeEntry = function (key) { - var newBaggage = new BaggageImpl(this._entries); - newBaggage._entries.delete(key); - return newBaggage; - }; - BaggageImpl.prototype.removeEntries = function () { - var keys = []; - for (var _i = 0; _i < arguments.length; _i++) { - keys[_i] = arguments[_i]; - } - var newBaggage = new BaggageImpl(this._entries); - for (var _a = 0, keys_1 = keys; _a < keys_1.length; _a++) { - var key = keys_1[_a]; - newBaggage._entries.delete(key); - } - return newBaggage; - }; - BaggageImpl.prototype.clear = function () { - return new BaggageImpl(); - }; - return BaggageImpl; -}()); -exports.BaggageImpl = BaggageImpl; -//# sourceMappingURL=baggage.js.map - -/***/ }), +/* 599 */, /* 600 */, /* 601 */, /* 602 */ @@ -44750,7 +38919,7 @@ Object.defineProperty(exports, "__esModule", { }); exports.default = void 0; -var _rng = _interopRequireDefault(__webpack_require__(944)); +var _rng = _interopRequireDefault(__webpack_require__(733)); var _stringify = _interopRequireDefault(__webpack_require__(855)); @@ -45021,7 +39190,7 @@ var __createBinding; ar[i] = from[i]; } } - return to.concat(ar || from); + return to.concat(ar || Array.prototype.slice.call(from)); }; __await = function (v) { @@ -45160,70 +39329,7 @@ exports.default = _default; /***/ }), /* 617 */, -/* 618 */ -/***/ (function(__unusedmodule, exports) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -function getProxyUrl(reqUrl) { - let usingSsl = reqUrl.protocol === 'https:'; - let proxyUrl; - if (checkBypass(reqUrl)) { - return proxyUrl; - } - let proxyVar; - if (usingSsl) { - proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY']; - } - else { - proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY']; - } - if (proxyVar) { - proxyUrl = new URL(proxyVar); - } - return proxyUrl; -} -exports.getProxyUrl = getProxyUrl; -function checkBypass(reqUrl) { - if (!reqUrl.hostname) { - return false; - } - let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; - if (!noProxy) { - return false; - } - // Determine the request port - let reqPort; - if (reqUrl.port) { - reqPort = Number(reqUrl.port); - } - else if (reqUrl.protocol === 'http:') { - reqPort = 80; - } - else if (reqUrl.protocol === 'https:') { - reqPort = 443; - } - // Format the request hostname and hostname with port - let upperReqHosts = [reqUrl.hostname.toUpperCase()]; - if (typeof reqPort === 'number') { - upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); - } - // Compare request host against noproxy - for (let upperNoProxyItem of noProxy - .split(',') - .map(x => x.trim().toUpperCase()) - .filter(x => x)) { - if (upperReqHosts.some(x => x === upperNoProxyItem)) { - return true; - } - } - return false; -} -exports.checkBypass = checkBypass; - - -/***/ }), +/* 618 */, /* 619 */, /* 620 */, /* 621 */ @@ -45302,7 +39408,89 @@ module.exports = require("path"); /* 624 */, /* 625 */, /* 626 */, -/* 627 */, +/* 627 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/*jshint unused:false */ + +class Store { + constructor() { + this.synchronous = false; + } + + findCookie(domain, path, key, cb) { + throw new Error("findCookie is not implemented"); + } + + findCookies(domain, path, allowSpecialUseDomain, cb) { + throw new Error("findCookies is not implemented"); + } + + putCookie(cookie, cb) { + throw new Error("putCookie is not implemented"); + } + + updateCookie(oldCookie, newCookie, cb) { + // recommended default implementation: + // return this.putCookie(newCookie, cb); + throw new Error("updateCookie is not implemented"); + } + + removeCookie(domain, path, key, cb) { + throw new Error("removeCookie is not implemented"); + } + + removeCookies(domain, path, cb) { + throw new Error("removeCookies is not implemented"); + } + + removeAllCookies(cb) { + throw new Error("removeAllCookies is not implemented"); + } + + getAllCookies(cb) { + throw new Error( + "getAllCookies is not implemented (therefore jar cannot be serialized)" + ); + } +} + +exports.Store = Store; + + +/***/ }), /* 628 */, /* 629 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { @@ -45310,23 +39498,32 @@ module.exports = require("path"); "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.isSpanContextValid = exports.isValidSpanId = exports.isValidTraceId = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; -var trace_flags_1 = __webpack_require__(975); +exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = exports.isValidTraceId = 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 invalid_span_constants_1 = __webpack_require__(435); +var NonRecordingSpan_1 = __webpack_require__(437); var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; -exports.INVALID_SPANID = '0000000000000000'; -exports.INVALID_TRACEID = '00000000000000000000000000000000'; -exports.INVALID_SPAN_CONTEXT = { - traceId: exports.INVALID_TRACEID, - spanId: exports.INVALID_SPANID, - traceFlags: trace_flags_1.TraceFlags.NONE, -}; function isValidTraceId(traceId) { - return VALID_TRACEID_REGEX.test(traceId) && traceId !== exports.INVALID_TRACEID; + return VALID_TRACEID_REGEX.test(traceId) && traceId !== invalid_span_constants_1.INVALID_TRACEID; } exports.isValidTraceId = isValidTraceId; function isValidSpanId(spanId) { - return VALID_SPANID_REGEX.test(spanId) && spanId !== exports.INVALID_SPANID; + return VALID_SPANID_REGEX.test(spanId) && spanId !== invalid_span_constants_1.INVALID_SPANID; } exports.isValidSpanId = isValidSpanId; /** @@ -45337,6 +39534,16 @@ function isSpanContextValid(spanContext) { return (isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId)); } exports.isSpanContextValid = isSpanContextValid; +/** + * Wrap the given {@link SpanContext} in a new non-recording {@link Span} + * + * @param spanContext span context to be wrapped + * @returns a new non-recording {@link Span} with the provided context + */ +function wrapSpanContext(spanContext) { + return new NonRecordingSpan_1.NonRecordingSpan(spanContext); +} +exports.wrapSpanContext = wrapSpanContext; //# sourceMappingURL=spancontext-utils.js.map /***/ }), @@ -45654,7 +39861,7 @@ var __createBinding; ar[i] = from[i]; } } - return to.concat(ar || from); + return to.concat(ar || Array.prototype.slice.call(from)); }; __await = function (v) { @@ -47326,30 +41533,7 @@ var __createBinding; /***/ }), -/* 646 */ -/***/ (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=Entry.js.map - -/***/ }), +/* 646 */, /* 647 */, /* 648 */, /* 649 */, @@ -47755,7 +41939,76 @@ exports.safeTrimTrailingSeparator = safeTrimTrailingSeparator; /* 663 */, /* 664 */, /* 665 */, -/* 666 */, +/* 666 */ +/***/ (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 }); +exports.BaggageImpl = void 0; +var BaggageImpl = /** @class */ (function () { + function BaggageImpl(entries) { + this._entries = entries ? new Map(entries) : new Map(); + } + BaggageImpl.prototype.getEntry = function (key) { + var entry = this._entries.get(key); + if (!entry) { + return undefined; + } + return Object.assign({}, entry); + }; + BaggageImpl.prototype.getAllEntries = function () { + return Array.from(this._entries.entries()).map(function (_a) { + var k = _a[0], v = _a[1]; + return [k, v]; + }); + }; + BaggageImpl.prototype.setEntry = function (key, entry) { + var newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.set(key, entry); + return newBaggage; + }; + BaggageImpl.prototype.removeEntry = function (key) { + var newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.delete(key); + return newBaggage; + }; + BaggageImpl.prototype.removeEntries = function () { + var keys = []; + for (var _i = 0; _i < arguments.length; _i++) { + keys[_i] = arguments[_i]; + } + var newBaggage = new BaggageImpl(this._entries); + for (var _a = 0, keys_1 = keys; _a < keys_1.length; _a++) { + var key = keys_1[_a]; + newBaggage._entries.delete(key); + } + return newBaggage; + }; + BaggageImpl.prototype.clear = function () { + return new BaggageImpl(); + }; + return BaggageImpl; +}()); +exports.BaggageImpl = BaggageImpl; +//# sourceMappingURL=baggage-impl.js.map + +/***/ }), /* 667 */, /* 668 */, /* 669 */ @@ -47816,7 +42069,318 @@ var SpanKind; //# sourceMappingURL=span_kind.js.map /***/ }), -/* 671 */, +/* 671 */ +/***/ (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, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + + __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, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), 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); +}); + + +/***/ }), /* 672 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { @@ -48233,7 +42797,7 @@ function restoreCache(paths, primaryKey, restoreKeys, options) { if (core.isDebug()) { yield tar_1.listTar(archivePath, compressionMethod); } - const archiveFileSize = utils.getArchiveFileSizeIsBytes(archivePath); + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); core.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); yield tar_1.extractTar(archivePath, compressionMethod); core.info('Cache restored successfully'); @@ -48278,18 +42842,29 @@ function saveCache(paths, key, options) { const archiveFolder = yield utils.createTempDirectory(); 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); + try { + yield tar_1.createTar(archiveFolder, cachePaths, compressionMethod); + if (core.isDebug()) { + yield tar_1.listTar(archivePath, compressionMethod); + } + const fileSizeLimit = 10 * 1024 * 1024 * 1024; // 10GB per repo limit + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core.debug(`File Size: ${archiveFileSize}`); + if (archiveFileSize > fileSizeLimit) { + throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); + } + core.debug(`Saving Cache (ID: ${cacheId})`); + yield cacheHttpClient.saveCache(cacheId, archivePath, options); } - const fileSizeLimit = 5 * 1024 * 1024 * 1024; // 5GB per repo limit - const archiveFileSize = utils.getArchiveFileSizeIsBytes(archivePath); - core.debug(`File Size: ${archiveFileSize}`); - if (archiveFileSize > fileSizeLimit) { - throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 5GB limit, not saving cache.`); + finally { + // Try to delete the archive to save space + try { + yield utils.unlinkFile(archivePath); + } + catch (error) { + core.debug(`Failed to delete archive: ${error}`); + } } - core.debug(`Saving Cache (ID: ${cacheId})`); - yield cacheHttpClient.saveCache(cacheId, archivePath, options); return cacheId; }); } @@ -48352,306 +42927,1680 @@ Object.defineProperty(exports, "__esModule", { value: true }); /* 699 */, /* 700 */, /* 701 */ -/***/ (function(module, __unusedexports, __webpack_require__) { +/***/ (function(__unusedmodule, exports, __webpack_require__) { -// Generated by CoffeeScript 1.12.7 -(function() { - var NodeType, XMLAttribute, XMLElement, XMLNamedNodeMap, XMLNode, getValue, isFunction, isObject, ref, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; +"use strict"; +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ - ref = __webpack_require__(582), isObject = ref.isObject, isFunction = ref.isFunction, getValue = ref.getValue; +const punycode = __webpack_require__(815); +const urlParse = __webpack_require__(835).parse; +const util = __webpack_require__(669); +const pubsuffix = __webpack_require__(519); +const Store = __webpack_require__(627).Store; +const MemoryCookieStore = __webpack_require__(349).MemoryCookieStore; +const pathMatch = __webpack_require__(54).pathMatch; +const VERSION = __webpack_require__(459); +const { fromCallback } = __webpack_require__(147); - XMLNode = __webpack_require__(257); +// From RFC6265 S4.1.1 +// note that it excludes \x3B ";" +const COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/; - NodeType = __webpack_require__(683); +const CONTROL_CHARS = /[\x00-\x1F]/; - XMLAttribute = __webpack_require__(884); +// From Chromium // '\r', '\n' and '\0' should be treated as a terminator in +// the "relaxed" mode, see: +// https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60 +const TERMINATORS = ["\n", "\r", "\0"]; - XMLNamedNodeMap = __webpack_require__(451); +// RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"' +// Note ';' is \x3B +const PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/; - module.exports = XMLElement = (function(superClass) { - extend(XMLElement, superClass); +// date-time parsing constants (RFC6265 S5.1.1) - function XMLElement(parent, name, attributes) { - var child, j, len, ref1; - XMLElement.__super__.constructor.call(this, parent); - if (name == null) { - throw new Error("Missing element name. " + this.debugInfo()); +const DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/; + +const MONTH_TO_NUM = { + jan: 0, + feb: 1, + mar: 2, + apr: 3, + may: 4, + jun: 5, + jul: 6, + aug: 7, + sep: 8, + oct: 9, + nov: 10, + dec: 11 +}; + +const MAX_TIME = 2147483647000; // 31-bit max +const MIN_TIME = 0; // 31-bit min +const SAME_SITE_CONTEXT_VAL_ERR = + 'Invalid sameSiteContext option for getCookies(); expected one of "strict", "lax", or "none"'; + +function checkSameSiteContext(value) { + const context = String(value).toLowerCase(); + if (context === "none" || context === "lax" || context === "strict") { + return context; + } else { + return null; + } +} + +const PrefixSecurityEnum = Object.freeze({ + SILENT: "silent", + STRICT: "strict", + DISABLED: "unsafe-disabled" +}); + +// Dumped from ip-regex@4.0.0, with the following changes: +// * all capturing groups converted to non-capturing -- "(?:)" +// * support for IPv6 Scoped Literal ("%eth1") removed +// * lowercase hexadecimal only +var IP_REGEX_LOWERCASE =/(?:^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$)|(?:^(?:(?:[a-f\d]{1,4}:){7}(?:[a-f\d]{1,4}|:)|(?:[a-f\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|:[a-f\d]{1,4}|:)|(?:[a-f\d]{1,4}:){5}(?::(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,2}|:)|(?:[a-f\d]{1,4}:){4}(?:(?::[a-f\d]{1,4}){0,1}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,3}|:)|(?:[a-f\d]{1,4}:){3}(?:(?::[a-f\d]{1,4}){0,2}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,4}|:)|(?:[a-f\d]{1,4}:){2}(?:(?::[a-f\d]{1,4}){0,3}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,5}|:)|(?:[a-f\d]{1,4}:){1}(?:(?::[a-f\d]{1,4}){0,4}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,6}|:)|(?::(?:(?::[a-f\d]{1,4}){0,5}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,7}|:)))$)/; + +/* + * Parses a Natural number (i.e., non-negative integer) with either the + * *DIGIT ( non-digit *OCTET ) + * or + * *DIGIT + * grammar (RFC6265 S5.1.1). + * + * The "trailingOK" boolean controls if the grammar accepts a + * "( non-digit *OCTET )" trailer. + */ +function parseDigits(token, minDigits, maxDigits, trailingOK) { + let count = 0; + while (count < token.length) { + const c = token.charCodeAt(count); + // "non-digit = %x00-2F / %x3A-FF" + if (c <= 0x2f || c >= 0x3a) { + break; + } + count++; + } + + // constrain to a minimum and maximum number of digits. + if (count < minDigits || count > maxDigits) { + return null; + } + + if (!trailingOK && count != token.length) { + return null; + } + + return parseInt(token.substr(0, count), 10); +} + +function parseTime(token) { + const parts = token.split(":"); + const result = [0, 0, 0]; + + /* RF6256 S5.1.1: + * time = hms-time ( non-digit *OCTET ) + * hms-time = time-field ":" time-field ":" time-field + * time-field = 1*2DIGIT + */ + + if (parts.length !== 3) { + return null; + } + + for (let i = 0; i < 3; i++) { + // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be + // followed by "( non-digit *OCTET )" so therefore the last time-field can + // have a trailer + const trailingOK = i == 2; + const num = parseDigits(parts[i], 1, 2, trailingOK); + if (num === null) { + return null; + } + result[i] = num; + } + + return result; +} + +function parseMonth(token) { + token = String(token) + .substr(0, 3) + .toLowerCase(); + const num = MONTH_TO_NUM[token]; + return num >= 0 ? num : null; +} + +/* + * RFC6265 S5.1.1 date parser (see RFC for full grammar) + */ +function parseDate(str) { + if (!str) { + return; + } + + /* RFC6265 S5.1.1: + * 2. Process each date-token sequentially in the order the date-tokens + * appear in the cookie-date + */ + const tokens = str.split(DATE_DELIM); + if (!tokens) { + return; + } + + let hour = null; + let minute = null; + let second = null; + let dayOfMonth = null; + let month = null; + let year = null; + + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i].trim(); + if (!token.length) { + continue; + } + + let result; + + /* 2.1. If the found-time flag is not set and the token matches the time + * production, set the found-time flag and set the hour- value, + * minute-value, and second-value to the numbers denoted by the digits in + * the date-token, respectively. Skip the remaining sub-steps and continue + * to the next date-token. + */ + if (second === null) { + result = parseTime(token); + if (result) { + hour = result[0]; + minute = result[1]; + second = result[2]; + continue; } - this.name = this.stringify.name(name); - this.type = NodeType.Element; - this.attribs = {}; - this.schemaTypeInfo = null; - if (attributes != null) { - this.attribute(attributes); + } + + /* 2.2. If the found-day-of-month flag is not set and the date-token matches + * the day-of-month production, set the found-day-of- month flag and set + * the day-of-month-value to the number denoted by the date-token. Skip + * the remaining sub-steps and continue to the next date-token. + */ + if (dayOfMonth === null) { + // "day-of-month = 1*2DIGIT ( non-digit *OCTET )" + result = parseDigits(token, 1, 2, true); + if (result !== null) { + dayOfMonth = result; + continue; } - if (parent.type === NodeType.Document) { - this.isRoot = true; - this.documentObject = parent; - parent.rootObject = this; - if (parent.children) { - ref1 = parent.children; - for (j = 0, len = ref1.length; j < len; j++) { - child = ref1[j]; - if (child.type === NodeType.DocType) { - child.name = this.name; - break; - } + } + + /* 2.3. If the found-month flag is not set and the date-token matches the + * month production, set the found-month flag and set the month-value to + * the month denoted by the date-token. Skip the remaining sub-steps and + * continue to the next date-token. + */ + if (month === null) { + result = parseMonth(token); + if (result !== null) { + month = result; + continue; + } + } + + /* 2.4. If the found-year flag is not set and the date-token matches the + * year production, set the found-year flag and set the year-value to the + * number denoted by the date-token. Skip the remaining sub-steps and + * continue to the next date-token. + */ + if (year === null) { + // "year = 2*4DIGIT ( non-digit *OCTET )" + result = parseDigits(token, 2, 4, true); + if (result !== null) { + year = result; + /* From S5.1.1: + * 3. If the year-value is greater than or equal to 70 and less + * than or equal to 99, increment the year-value by 1900. + * 4. If the year-value is greater than or equal to 0 and less + * than or equal to 69, increment the year-value by 2000. + */ + if (year >= 70 && year <= 99) { + year += 1900; + } else if (year >= 0 && year <= 69) { + year += 2000; + } + } + } + } + + /* RFC 6265 S5.1.1 + * "5. Abort these steps and fail to parse the cookie-date if: + * * at least one of the found-day-of-month, found-month, found- + * year, or found-time flags is not set, + * * the day-of-month-value is less than 1 or greater than 31, + * * the year-value is less than 1601, + * * the hour-value is greater than 23, + * * the minute-value is greater than 59, or + * * the second-value is greater than 59. + * (Note that leap seconds cannot be represented in this syntax.)" + * + * So, in order as above: + */ + if ( + dayOfMonth === null || + month === null || + year === null || + second === null || + dayOfMonth < 1 || + dayOfMonth > 31 || + year < 1601 || + hour > 23 || + minute > 59 || + second > 59 + ) { + return; + } + + return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second)); +} + +function formatDate(date) { + return date.toUTCString(); +} + +// S5.1.2 Canonicalized Host Names +function canonicalDomain(str) { + if (str == null) { + return null; + } + str = str.trim().replace(/^\./, ""); // S4.1.2.3 & S5.2.3: ignore leading . + + // convert to IDN if any non-ASCII characters + if (punycode && /[^\u0001-\u007f]/.test(str)) { + str = punycode.toASCII(str); + } + + return str.toLowerCase(); +} + +// S5.1.3 Domain Matching +function domainMatch(str, domStr, canonicalize) { + if (str == null || domStr == null) { + return null; + } + if (canonicalize !== false) { + str = canonicalDomain(str); + domStr = canonicalDomain(domStr); + } + + /* + * S5.1.3: + * "A string domain-matches a given domain string if at least one of the + * following conditions hold:" + * + * " o The domain string and the string are identical. (Note that both the + * domain string and the string will have been canonicalized to lower case at + * this point)" + */ + if (str == domStr) { + return true; + } + + /* " o All of the following [three] conditions hold:" */ + + /* "* The domain string is a suffix of the string" */ + const idx = str.indexOf(domStr); + if (idx <= 0) { + return false; // it's a non-match (-1) or prefix (0) + } + + // next, check it's a proper suffix + // e.g., "a.b.c".indexOf("b.c") === 2 + // 5 === 3+2 + if (str.length !== domStr.length + idx) { + return false; // it's not a suffix + } + + /* " * The last character of the string that is not included in the + * domain string is a %x2E (".") character." */ + if (str.substr(idx-1,1) !== '.') { + return false; // doesn't align on "." + } + + /* " * The string is a host name (i.e., not an IP address)." */ + if (IP_REGEX_LOWERCASE.test(str)) { + return false; // it's an IP address + } + + return true; +} + +// RFC6265 S5.1.4 Paths and Path-Match + +/* + * "The user agent MUST use an algorithm equivalent to the following algorithm + * to compute the default-path of a cookie:" + * + * Assumption: the path (and not query part or absolute uri) is passed in. + */ +function defaultPath(path) { + // "2. If the uri-path is empty or if the first character of the uri-path is not + // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps. + if (!path || path.substr(0, 1) !== "/") { + return "/"; + } + + // "3. If the uri-path contains no more than one %x2F ("/") character, output + // %x2F ("/") and skip the remaining step." + if (path === "/") { + return path; + } + + const rightSlash = path.lastIndexOf("/"); + if (rightSlash === 0) { + return "/"; + } + + // "4. Output the characters of the uri-path from the first character up to, + // but not including, the right-most %x2F ("/")." + return path.slice(0, rightSlash); +} + +function trimTerminator(str) { + for (let t = 0; t < TERMINATORS.length; t++) { + const terminatorIdx = str.indexOf(TERMINATORS[t]); + if (terminatorIdx !== -1) { + str = str.substr(0, terminatorIdx); + } + } + + return str; +} + +function parseCookiePair(cookiePair, looseMode) { + cookiePair = trimTerminator(cookiePair); + + let firstEq = cookiePair.indexOf("="); + if (looseMode) { + if (firstEq === 0) { + // '=' is immediately at start + cookiePair = cookiePair.substr(1); + firstEq = cookiePair.indexOf("="); // might still need to split on '=' + } + } else { + // non-loose mode + if (firstEq <= 0) { + // no '=' or is at start + return; // needs to have non-empty "cookie-name" + } + } + + let cookieName, cookieValue; + if (firstEq <= 0) { + cookieName = ""; + cookieValue = cookiePair.trim(); + } else { + cookieName = cookiePair.substr(0, firstEq).trim(); + cookieValue = cookiePair.substr(firstEq + 1).trim(); + } + + if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) { + return; + } + + const c = new Cookie(); + c.key = cookieName; + c.value = cookieValue; + return c; +} + +function parse(str, options) { + if (!options || typeof options !== "object") { + options = {}; + } + str = str.trim(); + + // We use a regex to parse the "name-value-pair" part of S5.2 + const firstSemi = str.indexOf(";"); // S5.2 step 1 + const cookiePair = firstSemi === -1 ? str : str.substr(0, firstSemi); + const c = parseCookiePair(cookiePair, !!options.loose); + if (!c) { + return; + } + + if (firstSemi === -1) { + return c; + } + + // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string + // (including the %x3B (";") in question)." plus later on in the same section + // "discard the first ";" and trim". + const unparsed = str.slice(firstSemi + 1).trim(); + + // "If the unparsed-attributes string is empty, skip the rest of these + // steps." + if (unparsed.length === 0) { + return c; + } + + /* + * S5.2 says that when looping over the items "[p]rocess the attribute-name + * and attribute-value according to the requirements in the following + * subsections" for every item. Plus, for many of the individual attributes + * in S5.3 it says to use the "attribute-value of the last attribute in the + * cookie-attribute-list". Therefore, in this implementation, we overwrite + * the previous value. + */ + const cookie_avs = unparsed.split(";"); + while (cookie_avs.length) { + const av = cookie_avs.shift().trim(); + if (av.length === 0) { + // happens if ";;" appears + continue; + } + const av_sep = av.indexOf("="); + let av_key, av_value; + + if (av_sep === -1) { + av_key = av; + av_value = null; + } else { + av_key = av.substr(0, av_sep); + av_value = av.substr(av_sep + 1); + } + + av_key = av_key.trim().toLowerCase(); + + if (av_value) { + av_value = av_value.trim(); + } + + switch (av_key) { + case "expires": // S5.2.1 + if (av_value) { + const exp = parseDate(av_value); + // "If the attribute-value failed to parse as a cookie date, ignore the + // cookie-av." + if (exp) { + // over and underflow not realistically a concern: V8's getTime() seems to + // store something larger than a 32-bit time_t (even with 32-bit node) + c.expires = exp; } } + break; + + case "max-age": // S5.2.2 + if (av_value) { + // "If the first character of the attribute-value is not a DIGIT or a "-" + // character ...[or]... If the remainder of attribute-value contains a + // non-DIGIT character, ignore the cookie-av." + if (/^-?[0-9]+$/.test(av_value)) { + const delta = parseInt(av_value, 10); + // "If delta-seconds is less than or equal to zero (0), let expiry-time + // be the earliest representable date and time." + c.setMaxAge(delta); + } + } + break; + + case "domain": // S5.2.3 + // "If the attribute-value is empty, the behavior is undefined. However, + // the user agent SHOULD ignore the cookie-av entirely." + if (av_value) { + // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E + // (".") character." + const domain = av_value.trim().replace(/^\./, ""); + if (domain) { + // "Convert the cookie-domain to lower case." + c.domain = domain.toLowerCase(); + } + } + break; + + case "path": // S5.2.4 + /* + * "If the attribute-value is empty or if the first character of the + * attribute-value is not %x2F ("/"): + * Let cookie-path be the default-path. + * Otherwise: + * Let cookie-path be the attribute-value." + * + * We'll represent the default-path as null since it depends on the + * context of the parsing. + */ + c.path = av_value && av_value[0] === "/" ? av_value : null; + break; + + case "secure": // S5.2.5 + /* + * "If the attribute-name case-insensitively matches the string "Secure", + * the user agent MUST append an attribute to the cookie-attribute-list + * with an attribute-name of Secure and an empty attribute-value." + */ + c.secure = true; + break; + + case "httponly": // S5.2.6 -- effectively the same as 'secure' + c.httpOnly = true; + break; + + case "samesite": // RFC6265bis-02 S5.3.7 + const enforcement = av_value ? av_value.toLowerCase() : ""; + switch (enforcement) { + case "strict": + c.sameSite = "strict"; + break; + case "lax": + c.sameSite = "lax"; + break; + default: + // RFC6265bis-02 S5.3.7 step 1: + // "If cookie-av's attribute-value is not a case-insensitive match + // for "Strict" or "Lax", ignore the "cookie-av"." + // This effectively sets it to 'none' from the prototype. + break; + } + break; + + default: + c.extensions = c.extensions || []; + c.extensions.push(av); + break; + } + } + + return c; +} + +/** + * If the cookie-name begins with a case-sensitive match for the + * string "__Secure-", abort these steps and ignore the cookie + * entirely unless the cookie's secure-only-flag is true. + * @param cookie + * @returns boolean + */ +function isSecurePrefixConditionMet(cookie) { + return !cookie.key.startsWith("__Secure-") || cookie.secure; +} + +/** + * If the cookie-name begins with a case-sensitive match for the + * string "__Host-", abort these steps and ignore the cookie + * entirely unless the cookie meets all the following criteria: + * 1. The cookie's secure-only-flag is true. + * 2. The cookie's host-only-flag is true. + * 3. The cookie-attribute-list contains an attribute with an + * attribute-name of "Path", and the cookie's path is "/". + * @param cookie + * @returns boolean + */ +function isHostPrefixConditionMet(cookie) { + return ( + !cookie.key.startsWith("__Host-") || + (cookie.secure && + cookie.hostOnly && + cookie.path != null && + cookie.path === "/") + ); +} + +// avoid the V8 deoptimization monster! +function jsonParse(str) { + let obj; + try { + obj = JSON.parse(str); + } catch (e) { + return e; + } + return obj; +} + +function fromJSON(str) { + if (!str) { + return null; + } + + let obj; + if (typeof str === "string") { + obj = jsonParse(str); + if (obj instanceof Error) { + return null; + } + } else { + // assume it's an Object + obj = str; + } + + const c = new Cookie(); + for (let i = 0; i < Cookie.serializableProperties.length; i++) { + const prop = Cookie.serializableProperties[i]; + if (obj[prop] === undefined || obj[prop] === cookieDefaults[prop]) { + continue; // leave as prototype default + } + + if (prop === "expires" || prop === "creation" || prop === "lastAccessed") { + if (obj[prop] === null) { + c[prop] = null; + } else { + c[prop] = obj[prop] == "Infinity" ? "Infinity" : new Date(obj[prop]); + } + } else { + c[prop] = obj[prop]; + } + } + + return c; +} + +/* Section 5.4 part 2: + * "* Cookies with longer paths are listed before cookies with + * shorter paths. + * + * * Among cookies that have equal-length path fields, cookies with + * earlier creation-times are listed before cookies with later + * creation-times." + */ + +function cookieCompare(a, b) { + let cmp = 0; + + // descending for length: b CMP a + const aPathLen = a.path ? a.path.length : 0; + const bPathLen = b.path ? b.path.length : 0; + cmp = bPathLen - aPathLen; + if (cmp !== 0) { + return cmp; + } + + // ascending for time: a CMP b + const aTime = a.creation ? a.creation.getTime() : MAX_TIME; + const bTime = b.creation ? b.creation.getTime() : MAX_TIME; + cmp = aTime - bTime; + if (cmp !== 0) { + return cmp; + } + + // break ties for the same millisecond (precision of JavaScript's clock) + cmp = a.creationIndex - b.creationIndex; + + return cmp; +} + +// Gives the permutation of all possible pathMatch()es of a given path. The +// array is in longest-to-shortest order. Handy for indexing. +function permutePath(path) { + if (path === "/") { + return ["/"]; + } + const permutations = [path]; + while (path.length > 1) { + const lindex = path.lastIndexOf("/"); + if (lindex === 0) { + break; + } + path = path.substr(0, lindex); + permutations.push(path); + } + permutations.push("/"); + return permutations; +} + +function getCookieContext(url) { + if (url instanceof Object) { + return url; + } + // NOTE: decodeURI will throw on malformed URIs (see GH-32). + // Therefore, we will just skip decoding for such URIs. + try { + url = decodeURI(url); + } catch (err) { + // Silently swallow error + } + + return urlParse(url); +} + +const cookieDefaults = { + // the order in which the RFC has them: + key: "", + value: "", + expires: "Infinity", + maxAge: null, + domain: null, + path: null, + secure: false, + httpOnly: false, + extensions: null, + // set by the CookieJar: + hostOnly: null, + pathIsDefault: null, + creation: null, + lastAccessed: null, + sameSite: "none" +}; + +class Cookie { + constructor(options = {}) { + if (util.inspect.custom) { + this[util.inspect.custom] = this.inspect; + } + + Object.assign(this, cookieDefaults, options); + this.creation = this.creation || new Date(); + + // used to break creation ties in cookieCompare(): + Object.defineProperty(this, "creationIndex", { + configurable: false, + enumerable: false, // important for assert.deepEqual checks + writable: true, + value: ++Cookie.cookiesCreated + }); + } + + inspect() { + const now = Date.now(); + const hostOnly = this.hostOnly != null ? this.hostOnly : "?"; + const createAge = this.creation + ? `${now - this.creation.getTime()}ms` + : "?"; + const accessAge = this.lastAccessed + ? `${now - this.lastAccessed.getTime()}ms` + : "?"; + return `Cookie="${this.toString()}; hostOnly=${hostOnly}; aAge=${accessAge}; cAge=${createAge}"`; + } + + toJSON() { + const obj = {}; + + for (const prop of Cookie.serializableProperties) { + if (this[prop] === cookieDefaults[prop]) { + continue; // leave as prototype default + } + + if ( + prop === "expires" || + prop === "creation" || + prop === "lastAccessed" + ) { + if (this[prop] === null) { + obj[prop] = null; + } else { + obj[prop] = + this[prop] == "Infinity" // intentionally not === + ? "Infinity" + : this[prop].toISOString(); + } + } else if (prop === "maxAge") { + if (this[prop] !== null) { + // again, intentionally not === + obj[prop] = + this[prop] == Infinity || this[prop] == -Infinity + ? this[prop].toString() + : this[prop]; + } + } else { + if (this[prop] !== cookieDefaults[prop]) { + obj[prop] = this[prop]; + } } } - Object.defineProperty(XMLElement.prototype, 'tagName', { - get: function() { - return this.name; - } - }); + return obj; + } - Object.defineProperty(XMLElement.prototype, 'namespaceURI', { - get: function() { - return ''; - } - }); + clone() { + return fromJSON(this.toJSON()); + } - Object.defineProperty(XMLElement.prototype, 'prefix', { - get: function() { - return ''; - } - }); + validate() { + if (!COOKIE_OCTETS.test(this.value)) { + return false; + } + if ( + this.expires != Infinity && + !(this.expires instanceof Date) && + !parseDate(this.expires) + ) { + return false; + } + if (this.maxAge != null && this.maxAge <= 0) { + return false; // "Max-Age=" non-zero-digit *DIGIT + } + if (this.path != null && !PATH_VALUE.test(this.path)) { + return false; + } - Object.defineProperty(XMLElement.prototype, 'localName', { - get: function() { - return this.name; + const cdomain = this.cdomain(); + if (cdomain) { + if (cdomain.match(/\.$/)) { + return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this } - }); + const suffix = pubsuffix.getPublicSuffix(cdomain); + if (suffix == null) { + // it's a public suffix + return false; + } + } + return true; + } - Object.defineProperty(XMLElement.prototype, 'id', { - get: function() { - throw new Error("This DOM method is not implemented." + this.debugInfo()); - } - }); + setExpires(exp) { + if (exp instanceof Date) { + this.expires = exp; + } else { + this.expires = parseDate(exp) || "Infinity"; + } + } - Object.defineProperty(XMLElement.prototype, 'className', { - get: function() { - throw new Error("This DOM method is not implemented." + this.debugInfo()); - } - }); + setMaxAge(age) { + if (age === Infinity || age === -Infinity) { + this.maxAge = age.toString(); // so JSON.stringify() works + } else { + this.maxAge = age; + } + } - Object.defineProperty(XMLElement.prototype, 'classList', { - get: function() { - throw new Error("This DOM method is not implemented." + this.debugInfo()); - } - }); + cookieString() { + let val = this.value; + if (val == null) { + val = ""; + } + if (this.key === "") { + return val; + } + return `${this.key}=${val}`; + } - Object.defineProperty(XMLElement.prototype, 'attributes', { - get: function() { - if (!this.attributeMap || !this.attributeMap.nodes) { - this.attributeMap = new XMLNamedNodeMap(this.attribs); - } - return this.attributeMap; - } - }); + // gives Set-Cookie header format + toString() { + let str = this.cookieString(); - XMLElement.prototype.clone = function() { - var att, attName, clonedSelf, ref1; - clonedSelf = Object.create(this); - if (clonedSelf.isRoot) { - clonedSelf.documentObject = null; + if (this.expires != Infinity) { + if (this.expires instanceof Date) { + str += `; Expires=${formatDate(this.expires)}`; + } else { + str += `; Expires=${this.expires}`; } - clonedSelf.attribs = {}; - ref1 = this.attribs; - for (attName in ref1) { - if (!hasProp.call(ref1, attName)) continue; - att = ref1[attName]; - clonedSelf.attribs[attName] = att.clone(); - } - clonedSelf.children = []; - this.children.forEach(function(child) { - var clonedChild; - clonedChild = child.clone(); - clonedChild.parent = clonedSelf; - return clonedSelf.children.push(clonedChild); + } + + if (this.maxAge != null && this.maxAge != Infinity) { + str += `; Max-Age=${this.maxAge}`; + } + + if (this.domain && !this.hostOnly) { + str += `; Domain=${this.domain}`; + } + if (this.path) { + str += `; Path=${this.path}`; + } + + if (this.secure) { + str += "; Secure"; + } + if (this.httpOnly) { + str += "; HttpOnly"; + } + if (this.sameSite && this.sameSite !== "none") { + const ssCanon = Cookie.sameSiteCanonical[this.sameSite.toLowerCase()]; + str += `; SameSite=${ssCanon ? ssCanon : this.sameSite}`; + } + if (this.extensions) { + this.extensions.forEach(ext => { + str += `; ${ext}`; }); - return clonedSelf; - }; + } - XMLElement.prototype.attribute = function(name, value) { - var attName, attValue; - if (name != null) { - name = getValue(name); + return str; + } + + // TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie() + // elsewhere) + // S5.3 says to give the "latest representable date" for which we use Infinity + // For "expired" we use 0 + TTL(now) { + /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires + * attribute, the Max-Age attribute has precedence and controls the + * expiration date of the cookie. + * (Concurs with S5.3 step 3) + */ + if (this.maxAge != null) { + return this.maxAge <= 0 ? 0 : this.maxAge * 1000; + } + + let expires = this.expires; + if (expires != Infinity) { + if (!(expires instanceof Date)) { + expires = parseDate(expires) || Infinity; } - if (isObject(name)) { - for (attName in name) { - if (!hasProp.call(name, attName)) continue; - attValue = name[attName]; - this.attribute(attName, attValue); + + if (expires == Infinity) { + return Infinity; + } + + return expires.getTime() - (now || Date.now()); + } + + return Infinity; + } + + // expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() + // elsewhere) + expiryTime(now) { + if (this.maxAge != null) { + const relativeTo = now || this.creation || new Date(); + const age = this.maxAge <= 0 ? -Infinity : this.maxAge * 1000; + return relativeTo.getTime() + age; + } + + if (this.expires == Infinity) { + return Infinity; + } + return this.expires.getTime(); + } + + // expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() + // elsewhere), except it returns a Date + expiryDate(now) { + const millisec = this.expiryTime(now); + if (millisec == Infinity) { + return new Date(MAX_TIME); + } else if (millisec == -Infinity) { + return new Date(MIN_TIME); + } else { + return new Date(millisec); + } + } + + // This replaces the "persistent-flag" parts of S5.3 step 3 + isPersistent() { + return this.maxAge != null || this.expires != Infinity; + } + + // Mostly S5.1.2 and S5.2.3: + canonicalizedDomain() { + if (this.domain == null) { + return null; + } + return canonicalDomain(this.domain); + } + + cdomain() { + return this.canonicalizedDomain(); + } +} + +Cookie.cookiesCreated = 0; +Cookie.parse = parse; +Cookie.fromJSON = fromJSON; +Cookie.serializableProperties = Object.keys(cookieDefaults); +Cookie.sameSiteLevel = { + strict: 3, + lax: 2, + none: 1 +}; + +Cookie.sameSiteCanonical = { + strict: "Strict", + lax: "Lax" +}; + +function getNormalizedPrefixSecurity(prefixSecurity) { + if (prefixSecurity != null) { + const normalizedPrefixSecurity = prefixSecurity.toLowerCase(); + /* The three supported options */ + switch (normalizedPrefixSecurity) { + case PrefixSecurityEnum.STRICT: + case PrefixSecurityEnum.SILENT: + case PrefixSecurityEnum.DISABLED: + return normalizedPrefixSecurity; + } + } + /* Default is SILENT */ + return PrefixSecurityEnum.SILENT; +} + +class CookieJar { + constructor(store, options = { rejectPublicSuffixes: true }) { + if (typeof options === "boolean") { + options = { rejectPublicSuffixes: options }; + } + this.rejectPublicSuffixes = options.rejectPublicSuffixes; + this.enableLooseMode = !!options.looseMode; + this.allowSpecialUseDomain = !!options.allowSpecialUseDomain; + this.store = store || new MemoryCookieStore(); + this.prefixSecurity = getNormalizedPrefixSecurity(options.prefixSecurity); + this._cloneSync = syncWrap("clone"); + this._importCookiesSync = syncWrap("_importCookies"); + this.getCookiesSync = syncWrap("getCookies"); + this.getCookieStringSync = syncWrap("getCookieString"); + this.getSetCookieStringsSync = syncWrap("getSetCookieStrings"); + this.removeAllCookiesSync = syncWrap("removeAllCookies"); + this.setCookieSync = syncWrap("setCookie"); + this.serializeSync = syncWrap("serialize"); + } + + setCookie(cookie, url, options, cb) { + let err; + const context = getCookieContext(url); + if (typeof options === "function") { + cb = options; + options = {}; + } + + const host = canonicalDomain(context.hostname); + const loose = options.loose || this.enableLooseMode; + + let sameSiteContext = null; + if (options.sameSiteContext) { + sameSiteContext = checkSameSiteContext(options.sameSiteContext); + if (!sameSiteContext) { + return cb(new Error(SAME_SITE_CONTEXT_VAL_ERR)); + } + } + + // S5.3 step 1 + if (typeof cookie === "string" || cookie instanceof String) { + cookie = Cookie.parse(cookie, { loose: loose }); + if (!cookie) { + err = new Error("Cookie failed to parse"); + return cb(options.ignoreError ? null : err); + } + } else if (!(cookie instanceof Cookie)) { + // If you're seeing this error, and are passing in a Cookie object, + // it *might* be a Cookie object from another loaded version of tough-cookie. + err = new Error( + "First argument to setCookie must be a Cookie object or string" + ); + return cb(options.ignoreError ? null : err); + } + + // S5.3 step 2 + const now = options.now || new Date(); // will assign later to save effort in the face of errors + + // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie() + + // S5.3 step 4: NOOP; domain is null by default + + // S5.3 step 5: public suffixes + if (this.rejectPublicSuffixes && cookie.domain) { + const suffix = pubsuffix.getPublicSuffix(cookie.cdomain()); + if (suffix == null) { + // e.g. "com" + err = new Error("Cookie has domain set to a public suffix"); + return cb(options.ignoreError ? null : err); + } + } + + // S5.3 step 6: + if (cookie.domain) { + if (!domainMatch(host, cookie.cdomain(), false)) { + err = new Error( + `Cookie not in this host's domain. Cookie:${cookie.cdomain()} Request:${host}` + ); + return cb(options.ignoreError ? null : err); + } + + if (cookie.hostOnly == null) { + // don't reset if already set + cookie.hostOnly = false; + } + } else { + cookie.hostOnly = true; + cookie.domain = host; + } + + //S5.2.4 If the attribute-value is empty or if the first character of the + //attribute-value is not %x2F ("/"): + //Let cookie-path be the default-path. + if (!cookie.path || cookie.path[0] !== "/") { + cookie.path = defaultPath(context.pathname); + cookie.pathIsDefault = true; + } + + // S5.3 step 8: NOOP; secure attribute + // S5.3 step 9: NOOP; httpOnly attribute + + // S5.3 step 10 + if (options.http === false && cookie.httpOnly) { + err = new Error("Cookie is HttpOnly and this isn't an HTTP API"); + return cb(options.ignoreError ? null : err); + } + + // 6252bis-02 S5.4 Step 13 & 14: + if (cookie.sameSite !== "none" && sameSiteContext) { + // "If the cookie's "same-site-flag" is not "None", and the cookie + // is being set from a context whose "site for cookies" is not an + // exact match for request-uri's host's registered domain, then + // abort these steps and ignore the newly created cookie entirely." + if (sameSiteContext === "none") { + err = new Error( + "Cookie is SameSite but this is a cross-origin request" + ); + return cb(options.ignoreError ? null : err); + } + } + + /* 6265bis-02 S5.4 Steps 15 & 16 */ + const ignoreErrorForPrefixSecurity = + this.prefixSecurity === PrefixSecurityEnum.SILENT; + const prefixSecurityDisabled = + this.prefixSecurity === PrefixSecurityEnum.DISABLED; + /* If prefix checking is not disabled ...*/ + if (!prefixSecurityDisabled) { + let errorFound = false; + let errorMsg; + /* Check secure prefix condition */ + if (!isSecurePrefixConditionMet(cookie)) { + errorFound = true; + errorMsg = "Cookie has __Secure prefix but Secure attribute is not set"; + } else if (!isHostPrefixConditionMet(cookie)) { + /* Check host prefix condition */ + errorFound = true; + errorMsg = + "Cookie has __Host prefix but either Secure or HostOnly attribute is not set or Path is not '/'"; + } + if (errorFound) { + return cb( + options.ignoreError || ignoreErrorForPrefixSecurity + ? null + : new Error(errorMsg) + ); + } + } + + const store = this.store; + + if (!store.updateCookie) { + store.updateCookie = function(oldCookie, newCookie, cb) { + this.putCookie(newCookie, cb); + }; + } + + function withCookie(err, oldCookie) { + if (err) { + return cb(err); + } + + const next = function(err) { + if (err) { + return cb(err); + } else { + cb(null, cookie); + } + }; + + if (oldCookie) { + // S5.3 step 11 - "If the cookie store contains a cookie with the same name, + // domain, and path as the newly created cookie:" + if (options.http === false && oldCookie.httpOnly) { + // step 11.2 + err = new Error("old Cookie is HttpOnly and this isn't an HTTP API"); + return cb(options.ignoreError ? null : err); + } + cookie.creation = oldCookie.creation; // step 11.3 + cookie.creationIndex = oldCookie.creationIndex; // preserve tie-breaker + cookie.lastAccessed = now; + // Step 11.4 (delete cookie) is implied by just setting the new one: + store.updateCookie(oldCookie, cookie, next); // step 12 + } else { + cookie.creation = cookie.lastAccessed = now; + store.putCookie(cookie, next); // step 12 + } + } + + store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie); + } + + // RFC6365 S5.4 + getCookies(url, options, cb) { + const context = getCookieContext(url); + if (typeof options === "function") { + cb = options; + options = {}; + } + + const host = canonicalDomain(context.hostname); + const path = context.pathname || "/"; + + let secure = options.secure; + if ( + secure == null && + context.protocol && + (context.protocol == "https:" || context.protocol == "wss:") + ) { + secure = true; + } + + let sameSiteLevel = 0; + if (options.sameSiteContext) { + const sameSiteContext = checkSameSiteContext(options.sameSiteContext); + sameSiteLevel = Cookie.sameSiteLevel[sameSiteContext]; + if (!sameSiteLevel) { + return cb(new Error(SAME_SITE_CONTEXT_VAL_ERR)); + } + } + + let http = options.http; + if (http == null) { + http = true; + } + + const now = options.now || Date.now(); + const expireCheck = options.expire !== false; + const allPaths = !!options.allPaths; + const store = this.store; + + function matchingCookie(c) { + // "Either: + // The cookie's host-only-flag is true and the canonicalized + // request-host is identical to the cookie's domain. + // Or: + // The cookie's host-only-flag is false and the canonicalized + // request-host domain-matches the cookie's domain." + if (c.hostOnly) { + if (c.domain != host) { + return false; } } else { - if (isFunction(value)) { - value = value.apply(); - } - if (this.options.keepNullAttributes && (value == null)) { - this.attribs[name] = new XMLAttribute(this, name, ""); - } else if (value != null) { - this.attribs[name] = new XMLAttribute(this, name, value); - } - } - return this; - }; - - XMLElement.prototype.removeAttribute = function(name) { - var attName, j, len; - if (name == null) { - throw new Error("Missing attribute name. " + this.debugInfo()); - } - name = getValue(name); - if (Array.isArray(name)) { - for (j = 0, len = name.length; j < len; j++) { - attName = name[j]; - delete this.attribs[attName]; - } - } else { - delete this.attribs[name]; - } - return this; - }; - - XMLElement.prototype.toString = function(options) { - return this.options.writer.element(this, this.options.writer.filterOptions(options)); - }; - - XMLElement.prototype.att = function(name, value) { - return this.attribute(name, value); - }; - - XMLElement.prototype.a = function(name, value) { - return this.attribute(name, value); - }; - - XMLElement.prototype.getAttribute = function(name) { - if (this.attribs.hasOwnProperty(name)) { - return this.attribs[name].value; - } else { - return null; - } - }; - - XMLElement.prototype.setAttribute = function(name, value) { - throw new Error("This DOM method is not implemented." + this.debugInfo()); - }; - - XMLElement.prototype.getAttributeNode = function(name) { - if (this.attribs.hasOwnProperty(name)) { - return this.attribs[name]; - } else { - return null; - } - }; - - XMLElement.prototype.setAttributeNode = function(newAttr) { - throw new Error("This DOM method is not implemented." + this.debugInfo()); - }; - - XMLElement.prototype.removeAttributeNode = function(oldAttr) { - throw new Error("This DOM method is not implemented." + this.debugInfo()); - }; - - XMLElement.prototype.getElementsByTagName = function(name) { - throw new Error("This DOM method is not implemented." + this.debugInfo()); - }; - - XMLElement.prototype.getAttributeNS = function(namespaceURI, localName) { - throw new Error("This DOM method is not implemented." + this.debugInfo()); - }; - - XMLElement.prototype.setAttributeNS = function(namespaceURI, qualifiedName, value) { - throw new Error("This DOM method is not implemented." + this.debugInfo()); - }; - - XMLElement.prototype.removeAttributeNS = function(namespaceURI, localName) { - throw new Error("This DOM method is not implemented." + this.debugInfo()); - }; - - XMLElement.prototype.getAttributeNodeNS = function(namespaceURI, localName) { - throw new Error("This DOM method is not implemented." + this.debugInfo()); - }; - - XMLElement.prototype.setAttributeNodeNS = function(newAttr) { - throw new Error("This DOM method is not implemented." + this.debugInfo()); - }; - - XMLElement.prototype.getElementsByTagNameNS = function(namespaceURI, localName) { - throw new Error("This DOM method is not implemented." + this.debugInfo()); - }; - - XMLElement.prototype.hasAttribute = function(name) { - return this.attribs.hasOwnProperty(name); - }; - - XMLElement.prototype.hasAttributeNS = function(namespaceURI, localName) { - throw new Error("This DOM method is not implemented." + this.debugInfo()); - }; - - XMLElement.prototype.setIdAttribute = function(name, isId) { - if (this.attribs.hasOwnProperty(name)) { - return this.attribs[name].isId; - } else { - return isId; - } - }; - - XMLElement.prototype.setIdAttributeNS = function(namespaceURI, localName, isId) { - throw new Error("This DOM method is not implemented." + this.debugInfo()); - }; - - XMLElement.prototype.setIdAttributeNode = function(idAttr, isId) { - throw new Error("This DOM method is not implemented." + this.debugInfo()); - }; - - XMLElement.prototype.getElementsByTagName = function(tagname) { - throw new Error("This DOM method is not implemented." + this.debugInfo()); - }; - - XMLElement.prototype.getElementsByTagNameNS = function(namespaceURI, localName) { - throw new Error("This DOM method is not implemented." + this.debugInfo()); - }; - - XMLElement.prototype.getElementsByClassName = function(classNames) { - throw new Error("This DOM method is not implemented." + this.debugInfo()); - }; - - XMLElement.prototype.isEqualNode = function(node) { - var i, j, ref1; - if (!XMLElement.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) { - return false; - } - if (node.namespaceURI !== this.namespaceURI) { - return false; - } - if (node.prefix !== this.prefix) { - return false; - } - if (node.localName !== this.localName) { - return false; - } - if (node.attribs.length !== this.attribs.length) { - return false; - } - for (i = j = 0, ref1 = this.attribs.length - 1; 0 <= ref1 ? j <= ref1 : j >= ref1; i = 0 <= ref1 ? ++j : --j) { - if (!this.attribs[i].isEqualNode(node.attribs[i])) { + if (!domainMatch(host, c.domain, false)) { return false; } } + + // "The request-uri's path path-matches the cookie's path." + if (!allPaths && !pathMatch(path, c.path)) { + return false; + } + + // "If the cookie's secure-only-flag is true, then the request-uri's + // scheme must denote a "secure" protocol" + if (c.secure && !secure) { + return false; + } + + // "If the cookie's http-only-flag is true, then exclude the cookie if the + // cookie-string is being generated for a "non-HTTP" API" + if (c.httpOnly && !http) { + return false; + } + + // RFC6265bis-02 S5.3.7 + if (sameSiteLevel) { + const cookieLevel = Cookie.sameSiteLevel[c.sameSite || "none"]; + if (cookieLevel > sameSiteLevel) { + // only allow cookies at or below the request level + return false; + } + } + + // deferred from S5.3 + // non-RFC: allow retention of expired cookies by choice + if (expireCheck && c.expiryTime() <= now) { + store.removeCookie(c.domain, c.path, c.key, () => {}); // result ignored + return false; + } + return true; + } + + store.findCookies( + host, + allPaths ? null : path, + this.allowSpecialUseDomain, + (err, cookies) => { + if (err) { + return cb(err); + } + + cookies = cookies.filter(matchingCookie); + + // sorting of S5.4 part 2 + if (options.sort !== false) { + cookies = cookies.sort(cookieCompare); + } + + // S5.4 part 3 + const now = new Date(); + for (const cookie of cookies) { + cookie.lastAccessed = now; + } + // TODO persist lastAccessed + + cb(null, cookies); + } + ); + } + + getCookieString(...args) { + const cb = args.pop(); + const next = function(err, cookies) { + if (err) { + cb(err); + } else { + cb( + null, + cookies + .sort(cookieCompare) + .map(c => c.cookieString()) + .join("; ") + ); + } + }; + args.push(next); + this.getCookies.apply(this, args); + } + + getSetCookieStrings(...args) { + const cb = args.pop(); + const next = function(err, cookies) { + if (err) { + cb(err); + } else { + cb( + null, + cookies.map(c => { + return c.toString(); + }) + ); + } + }; + args.push(next); + this.getCookies.apply(this, args); + } + + serialize(cb) { + let type = this.store.constructor.name; + if (type === "Object") { + type = null; + } + + // update README.md "Serialization Format" if you change this, please! + const serialized = { + // The version of tough-cookie that serialized this jar. Generally a good + // practice since future versions can make data import decisions based on + // known past behavior. When/if this matters, use `semver`. + version: `tough-cookie@${VERSION}`, + + // add the store type, to make humans happy: + storeType: type, + + // CookieJar configuration: + rejectPublicSuffixes: !!this.rejectPublicSuffixes, + + // this gets filled from getAllCookies: + cookies: [] }; - return XMLElement; + if ( + !( + this.store.getAllCookies && + typeof this.store.getAllCookies === "function" + ) + ) { + return cb( + new Error( + "store does not support getAllCookies and cannot be serialized" + ) + ); + } - })(XMLNode); + this.store.getAllCookies((err, cookies) => { + if (err) { + return cb(err); + } -}).call(this); + serialized.cookies = cookies.map(cookie => { + // convert to serialized 'raw' cookies + cookie = cookie instanceof Cookie ? cookie.toJSON() : cookie; + + // Remove the index so new ones get assigned during deserialization + delete cookie.creationIndex; + + return cookie; + }); + + return cb(null, serialized); + }); + } + + toJSON() { + return this.serializeSync(); + } + + // use the class method CookieJar.deserialize instead of calling this directly + _importCookies(serialized, cb) { + let cookies = serialized.cookies; + if (!cookies || !Array.isArray(cookies)) { + return cb(new Error("serialized jar has no cookies array")); + } + cookies = cookies.slice(); // do not modify the original + + const putNext = err => { + if (err) { + return cb(err); + } + + if (!cookies.length) { + return cb(err, this); + } + + let cookie; + try { + cookie = fromJSON(cookies.shift()); + } catch (e) { + return cb(e); + } + + if (cookie === null) { + return putNext(null); // skip this cookie + } + + this.store.putCookie(cookie, putNext); + }; + + putNext(); + } + + clone(newStore, cb) { + if (arguments.length === 1) { + cb = newStore; + newStore = null; + } + + this.serialize((err, serialized) => { + if (err) { + return cb(err); + } + CookieJar.deserialize(serialized, newStore, cb); + }); + } + + cloneSync(newStore) { + if (arguments.length === 0) { + return this._cloneSync(); + } + if (!newStore.synchronous) { + throw new Error( + "CookieJar clone destination store is not synchronous; use async API instead." + ); + } + return this._cloneSync(newStore); + } + + removeAllCookies(cb) { + const store = this.store; + + // Check that the store implements its own removeAllCookies(). The default + // implementation in Store will immediately call the callback with a "not + // implemented" Error. + if ( + typeof store.removeAllCookies === "function" && + store.removeAllCookies !== Store.prototype.removeAllCookies + ) { + return store.removeAllCookies(cb); + } + + store.getAllCookies((err, cookies) => { + if (err) { + return cb(err); + } + + if (cookies.length === 0) { + return cb(null); + } + + let completedCount = 0; + const removeErrors = []; + + function removeCookieCb(removeErr) { + if (removeErr) { + removeErrors.push(removeErr); + } + + completedCount++; + + if (completedCount === cookies.length) { + return cb(removeErrors.length ? removeErrors[0] : null); + } + } + + cookies.forEach(cookie => { + store.removeCookie( + cookie.domain, + cookie.path, + cookie.key, + removeCookieCb + ); + }); + }); + } + + static deserialize(strOrObj, store, cb) { + if (arguments.length !== 3) { + // store is optional + cb = store; + store = null; + } + + let serialized; + if (typeof strOrObj === "string") { + serialized = jsonParse(strOrObj); + if (serialized instanceof Error) { + return cb(serialized); + } + } else { + serialized = strOrObj; + } + + const jar = new CookieJar(store, serialized.rejectPublicSuffixes); + jar._importCookies(serialized, err => { + if (err) { + return cb(err); + } + cb(null, jar); + }); + } + + static deserializeSync(strOrObj, store) { + const serialized = + typeof strOrObj === "string" ? JSON.parse(strOrObj) : strOrObj; + const jar = new CookieJar(store, serialized.rejectPublicSuffixes); + + // catch this mistake early: + if (!jar.store.synchronous) { + throw new Error( + "CookieJar store is not synchronous; use async API instead." + ); + } + + jar._importCookiesSync(serialized); + return jar; + } +} +CookieJar.fromJSON = CookieJar.deserializeSync; + +[ + "_importCookies", + "clone", + "getCookies", + "getCookieString", + "getSetCookieStrings", + "removeAllCookies", + "serialize", + "setCookie" +].forEach(name => { + CookieJar.prototype[name] = fromCallback(CookieJar.prototype[name]); +}); +CookieJar.deserialize = fromCallback(CookieJar.deserialize); + +// Use a closure to provide a true imperative API for synchronous stores. +function syncWrap(method) { + return function(...args) { + if (!this.store.synchronous) { + throw new Error( + "CookieJar store is not synchronous; use async API instead." + ); + } + + let syncErr, syncResult; + this[method](...args, (err, result) => { + syncErr = err; + syncResult = result; + }); + + if (syncErr) { + throw syncErr; + } + return syncResult; + }; +} + +exports.version = VERSION; +exports.CookieJar = CookieJar; +exports.Cookie = Cookie; +exports.Store = Store; +exports.MemoryCookieStore = MemoryCookieStore; +exports.parseDate = parseDate; +exports.formatDate = formatDate; +exports.parse = parse; +exports.fromJSON = fromJSON; +exports.domainMatch = domainMatch; +exports.defaultPath = defaultPath; +exports.pathMatch = pathMatch; +exports.getPublicSuffix = pubsuffix.getPublicSuffix; +exports.cookieCompare = cookieCompare; +exports.permuteDomain = __webpack_require__(383).permuteDomain; +exports.permutePath = permutePath; +exports.canonicalDomain = canonicalDomain; +exports.PrefixSecurityEnum = PrefixSecurityEnum; /***/ }), @@ -48747,7 +44696,86 @@ Object.defineProperty(exports, "__esModule", { value: true }); /* 717 */, /* 718 */, /* 719 */, -/* 720 */, +/* 720 */ +/***/ (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.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getSpan = void 0; +var context_1 = __webpack_require__(132); +var NonRecordingSpan_1 = __webpack_require__(437); +/** + * span key + */ +var SPAN_KEY = context_1.createContextKey('OpenTelemetry Context Key SPAN'); +/** + * Return the span if one exists + * + * @param context context to get span from + */ +function getSpan(context) { + return context.getValue(SPAN_KEY) || undefined; +} +exports.getSpan = getSpan; +/** + * Set the span on a context + * + * @param context context to use as parent + * @param span span to set active + */ +function setSpan(context, span) { + return context.setValue(SPAN_KEY, span); +} +exports.setSpan = setSpan; +/** + * Remove current span stored in the context + * + * @param context context to delete span from + */ +function deleteSpan(context) { + return context.deleteValue(SPAN_KEY); +} +exports.deleteSpan = deleteSpan; +/** + * Wrap span context in a NoopSpan and set as span in a new + * context + * + * @param context context to set active span on + * @param spanContext span context to be wrapped + */ +function setSpanContext(context, spanContext) { + return setSpan(context, new NonRecordingSpan_1.NonRecordingSpan(spanContext)); +} +exports.setSpanContext = setSpanContext; +/** + * Get the span context of the span if it exists. + * + * @param context context to get values from + */ +function getSpanContext(context) { + var _a; + return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext(); +} +exports.getSpanContext = getSpanContext; +//# sourceMappingURL=context-utils.js.map + +/***/ }), /* 721 */, /* 722 */, /* 723 */, @@ -48773,411 +44801,42 @@ Object.defineProperty(exports, "__esModule", { value: true }); /***/ }), -/* 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, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || from); - }; - - __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, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), 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) { - -"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=Event.js.map - -/***/ }), +/* 727 */, /* 728 */, /* 729 */, /* 730 */, /* 731 */, /* 732 */, /* 733 */ -/***/ (function(__unusedmodule, exports) { +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -class BasicCredentialHandler { - constructor(username, password) { - this.username = username; - this.password = password; - } - prepareRequest(options) { - options.headers['Authorization'] = - 'Basic ' + - Buffer.from(this.username + ':' + this.password).toString('base64'); - } - // This handler cannot handle 401 - canHandleAuthentication(response) { - return false; - } - handleAuthentication(httpClient, requestInfo, objs) { - return null; - } -} -exports.BasicCredentialHandler = BasicCredentialHandler; -class BearerCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - options.headers['Authorization'] = 'Bearer ' + this.token; - } - // This handler cannot handle 401 - canHandleAuthentication(response) { - return false; - } - handleAuthentication(httpClient, requestInfo, objs) { - return null; - } -} -exports.BearerCredentialHandler = BearerCredentialHandler; -class PersonalAccessTokenCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - options.headers['Authorization'] = - 'Basic ' + Buffer.from('PAT:' + this.token).toString('base64'); - } - // This handler cannot handle 401 - canHandleAuthentication(response) { - return false; - } - handleAuthentication(httpClient, requestInfo, objs) { - return null; - } -} -exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rng; + +var _crypto = _interopRequireDefault(__webpack_require__(417)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate + +let poolPtr = rnds8Pool.length; + +function rng() { + if (poolPtr > rnds8Pool.length - 16) { + _crypto.default.randomFillSync(rnds8Pool); + + poolPtr = 0; + } + + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} /***/ }), /* 734 */, @@ -49907,77 +45566,7 @@ module.exports = function(dst, src) { /***/ }), -/* 767 */ -/***/ (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.NoopSpan = void 0; -var spancontext_utils_1 = __webpack_require__(629); -/** - * The NoopSpan is the default {@link Span} that is used when no Span - * implementation is available. All operations are no-op including context - * propagation. - */ -var NoopSpan = /** @class */ (function () { - function NoopSpan(_spanContext) { - if (_spanContext === void 0) { _spanContext = spancontext_utils_1.INVALID_SPAN_CONTEXT; } - this._spanContext = _spanContext; - } - // Returns a SpanContext. - NoopSpan.prototype.context = function () { - return this._spanContext; - }; - // By default does nothing - NoopSpan.prototype.setAttribute = function (_key, _value) { - return this; - }; - // By default does nothing - NoopSpan.prototype.setAttributes = function (_attributes) { - return this; - }; - // By default does nothing - NoopSpan.prototype.addEvent = function (_name, _attributes) { - return this; - }; - // By default does nothing - NoopSpan.prototype.setStatus = function (_status) { - return this; - }; - // By default does nothing - NoopSpan.prototype.updateName = function (_name) { - return this; - }; - // By default does nothing - NoopSpan.prototype.end = function (_endTime) { }; - // isRecording always returns false for noopSpan. - NoopSpan.prototype.isRecording = function () { - return false; - }; - // By default does nothing - NoopSpan.prototype.recordException = function (_exception, _time) { }; - return NoopSpan; -}()); -exports.NoopSpan = NoopSpan; -//# sourceMappingURL=NoopSpan.js.map - -/***/ }), +/* 767 */, /* 768 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -49992,7 +45581,7 @@ exports.NoopSpan = NoopSpan; XMLDocument = __webpack_require__(559); - XMLElement = __webpack_require__(701); + XMLElement = __webpack_require__(845); XMLCData = __webpack_require__(657); @@ -50773,6 +46362,7 @@ var http = __webpack_require__(605); var https = __webpack_require__(211); var parseUrl = __webpack_require__(835).parse; var fs = __webpack_require__(747); +var Stream = __webpack_require__(794).Stream; var mime = __webpack_require__(779); var asynckit = __webpack_require__(334); var populate = __webpack_require__(766); @@ -50868,8 +46458,8 @@ FormData.prototype._trackLength = function(header, value, options) { Buffer.byteLength(header) + FormData.LINE_BREAK.length; - // empty or either doesn't have path or not an http response - if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) )) { + // empty or either doesn't have path or not an http response or not a stream + if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) { return; } @@ -51224,13 +46814,15 @@ FormData.prototype.submit = function(params, cb) { // get content length and fire away this.getLength(function(err, length) { - if (err) { + if (err && err !== 'Unknown stream') { this._error(err); return; } // add content length - request.setHeader('Content-Length', length); + if (length) { + request.setHeader('Content-Length', length); + } this.pipe(request); if (cb) { @@ -51345,74 +46937,7 @@ FormData.prototype.toString = function () { /***/ }), -/* 792 */ -/***/ (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" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.baggageEntryMetadataFromString = exports.createBaggage = void 0; -var baggage_1 = __webpack_require__(599); -var symbol_1 = __webpack_require__(561); -__exportStar(__webpack_require__(938), exports); -__exportStar(__webpack_require__(646), exports); -/** - * Create a new Baggage with optional entries - * - * @param entries An array of baggage entries the new baggage should contain - */ -function createBaggage(entries) { - if (entries === void 0) { entries = {}; } - return new baggage_1.BaggageImpl(new Map(Object.entries(entries))); -} -exports.createBaggage = createBaggage; -/** - * Create a serializable BaggageEntryMetadata object from a string. - * - * @param str string metadata. Format is currently not defined by the spec and has no special meaning. - * - */ -function baggageEntryMetadataFromString(str) { - if (typeof str !== 'string') { - // @TODO log diagnostic - str = ''; - } - return { - __TYPE__: symbol_1.baggageEntryMetadataSymbol, - toString: function () { - return str; - }, - }; -} -exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; -//# sourceMappingURL=index.js.map - -/***/ }), +/* 792 */, /* 793 */, /* 794 */ /***/ (function(module) { @@ -51616,7 +47141,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); const core = __importStar(__webpack_require__(470)); -const http_client_1 = __webpack_require__(22); +const http_client_1 = __webpack_require__(539); const constants_1 = __webpack_require__(931); function isSuccessStatusCode(statusCode) { if (!statusCode) { @@ -51744,7 +47269,7 @@ exports.retryHttpClientResponse = retryHttpClientResponse; Object.defineProperty(exports, "__esModule", { value: true }); exports.VERSION = void 0; // this is autogenerated file, see scripts/version-update.js -exports.VERSION = '1.0.0-rc.0'; +exports.VERSION = '1.0.3'; //# sourceMappingURL=version.js.map /***/ }), @@ -51761,57 +47286,314 @@ module.exports = require("url"); /* 836 */, /* 837 */, /* 838 */, -/* 839 */ -/***/ (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=TimedEvent.js.map - -/***/ }), +/* 839 */, /* 840 */, /* 841 */, /* 842 */, /* 843 */, /* 844 */, /* 845 */ -/***/ (function(__unusedmodule, exports) { +/***/ (function(module, __unusedexports, __webpack_require__) { -"use strict"; +// Generated by CoffeeScript 1.12.7 +(function() { + var NodeType, XMLAttribute, XMLElement, XMLNamedNodeMap, XMLNode, getValue, isFunction, isObject, ref, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; + + ref = __webpack_require__(582), isObject = ref.isObject, isFunction = ref.isFunction, getValue = ref.getValue; + + XMLNode = __webpack_require__(257); + + NodeType = __webpack_require__(683); + + XMLAttribute = __webpack_require__(884); + + XMLNamedNodeMap = __webpack_require__(451); + + module.exports = XMLElement = (function(superClass) { + extend(XMLElement, superClass); + + function XMLElement(parent, name, attributes) { + var child, j, len, ref1; + XMLElement.__super__.constructor.call(this, parent); + if (name == null) { + throw new Error("Missing element name. " + this.debugInfo()); + } + this.name = this.stringify.name(name); + this.type = NodeType.Element; + this.attribs = {}; + this.schemaTypeInfo = null; + if (attributes != null) { + this.attribute(attributes); + } + if (parent.type === NodeType.Document) { + this.isRoot = true; + this.documentObject = parent; + parent.rootObject = this; + if (parent.children) { + ref1 = parent.children; + for (j = 0, len = ref1.length; j < len; j++) { + child = ref1[j]; + if (child.type === NodeType.DocType) { + child.name = this.name; + break; + } + } + } + } + } + + Object.defineProperty(XMLElement.prototype, 'tagName', { + get: function() { + return this.name; + } + }); + + Object.defineProperty(XMLElement.prototype, 'namespaceURI', { + get: function() { + return ''; + } + }); + + Object.defineProperty(XMLElement.prototype, 'prefix', { + get: function() { + return ''; + } + }); + + Object.defineProperty(XMLElement.prototype, 'localName', { + get: function() { + return this.name; + } + }); + + Object.defineProperty(XMLElement.prototype, 'id', { + get: function() { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + } + }); + + Object.defineProperty(XMLElement.prototype, 'className', { + get: function() { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + } + }); + + Object.defineProperty(XMLElement.prototype, 'classList', { + get: function() { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + } + }); + + Object.defineProperty(XMLElement.prototype, 'attributes', { + get: function() { + if (!this.attributeMap || !this.attributeMap.nodes) { + this.attributeMap = new XMLNamedNodeMap(this.attribs); + } + return this.attributeMap; + } + }); + + XMLElement.prototype.clone = function() { + var att, attName, clonedSelf, ref1; + clonedSelf = Object.create(this); + if (clonedSelf.isRoot) { + clonedSelf.documentObject = null; + } + clonedSelf.attribs = {}; + ref1 = this.attribs; + for (attName in ref1) { + if (!hasProp.call(ref1, attName)) continue; + att = ref1[attName]; + clonedSelf.attribs[attName] = att.clone(); + } + clonedSelf.children = []; + this.children.forEach(function(child) { + var clonedChild; + clonedChild = child.clone(); + clonedChild.parent = clonedSelf; + return clonedSelf.children.push(clonedChild); + }); + return clonedSelf; + }; + + XMLElement.prototype.attribute = function(name, value) { + var attName, attValue; + if (name != null) { + name = getValue(name); + } + if (isObject(name)) { + for (attName in name) { + if (!hasProp.call(name, attName)) continue; + attValue = name[attName]; + this.attribute(attName, attValue); + } + } else { + if (isFunction(value)) { + value = value.apply(); + } + if (this.options.keepNullAttributes && (value == null)) { + this.attribs[name] = new XMLAttribute(this, name, ""); + } else if (value != null) { + this.attribs[name] = new XMLAttribute(this, name, value); + } + } + return this; + }; + + XMLElement.prototype.removeAttribute = function(name) { + var attName, j, len; + if (name == null) { + throw new Error("Missing attribute name. " + this.debugInfo()); + } + name = getValue(name); + if (Array.isArray(name)) { + for (j = 0, len = name.length; j < len; j++) { + attName = name[j]; + delete this.attribs[attName]; + } + } else { + delete this.attribs[name]; + } + return this; + }; + + XMLElement.prototype.toString = function(options) { + return this.options.writer.element(this, this.options.writer.filterOptions(options)); + }; + + XMLElement.prototype.att = function(name, value) { + return this.attribute(name, value); + }; + + XMLElement.prototype.a = function(name, value) { + return this.attribute(name, value); + }; + + XMLElement.prototype.getAttribute = function(name) { + if (this.attribs.hasOwnProperty(name)) { + return this.attribs[name].value; + } else { + return null; + } + }; + + XMLElement.prototype.setAttribute = function(name, value) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getAttributeNode = function(name) { + if (this.attribs.hasOwnProperty(name)) { + return this.attribs[name]; + } else { + return null; + } + }; + + XMLElement.prototype.setAttributeNode = function(newAttr) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.removeAttributeNode = function(oldAttr) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getElementsByTagName = function(name) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getAttributeNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.setAttributeNS = function(namespaceURI, qualifiedName, value) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.removeAttributeNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getAttributeNodeNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.setAttributeNodeNS = function(newAttr) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getElementsByTagNameNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.hasAttribute = function(name) { + return this.attribs.hasOwnProperty(name); + }; + + XMLElement.prototype.hasAttributeNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.setIdAttribute = function(name, isId) { + if (this.attribs.hasOwnProperty(name)) { + return this.attribs[name].isId; + } else { + return isId; + } + }; + + XMLElement.prototype.setIdAttributeNS = function(namespaceURI, localName, isId) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.setIdAttributeNode = function(idAttr, isId) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getElementsByTagName = function(tagname) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getElementsByTagNameNS = function(namespaceURI, localName) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.getElementsByClassName = function(classNames) { + throw new Error("This DOM method is not implemented." + this.debugInfo()); + }; + + XMLElement.prototype.isEqualNode = function(node) { + var i, j, ref1; + if (!XMLElement.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) { + return false; + } + if (node.namespaceURI !== this.namespaceURI) { + return false; + } + if (node.prefix !== this.prefix) { + return false; + } + if (node.localName !== this.localName) { + return false; + } + if (node.attribs.length !== this.attribs.length) { + return false; + } + for (i = j = 0, ref1 = this.attribs.length - 1; 0 <= ref1 ? j <= ref1 : j >= ref1; i = 0 <= ref1 ? ++j : --j) { + if (!this.attribs[i].isEqualNode(node.attribs[i])) { + return false; + } + } + return true; + }; + + return XMLElement; + + })(XMLNode); + +}).call(this); -/* - * 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 /***/ }), /* 846 */, @@ -51819,30 +47601,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); /* 848 */, /* 849 */, /* 850 */, -/* 851 */ -/***/ (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=link_context.js.map - -/***/ }), +/* 851 */, /* 852 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -52371,7 +48130,7 @@ var __createBinding; ar[i] = from[i]; } } - return to.concat(ar || from); + return to.concat(ar || Array.prototype.slice.call(from)); }; __await = function (v) { @@ -52499,9 +48258,11 @@ var __createBinding; */ Object.defineProperty(exports, "__esModule", { value: true }); exports.TraceAPI = void 0; +var global_utils_1 = __webpack_require__(525); var ProxyTracerProvider_1 = __webpack_require__(394); var spancontext_utils_1 = __webpack_require__(629); -var global_utils_1 = __webpack_require__(525); +var context_utils_1 = __webpack_require__(720); +var diag_1 = __webpack_require__(118); var API_NAME = 'trace'; /** * Singleton object which represents the entry point to the OpenTelemetry Tracing API @@ -52510,7 +48271,13 @@ var TraceAPI = /** @class */ (function () { /** Empty private constructor prevents end users from constructing a new instance of the API */ function TraceAPI() { this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); + this.wrapSpanContext = spancontext_utils_1.wrapSpanContext; this.isSpanContextValid = spancontext_utils_1.isSpanContextValid; + this.deleteSpan = context_utils_1.deleteSpan; + this.getSpan = context_utils_1.getSpan; + this.getSpanContext = context_utils_1.getSpanContext; + this.setSpan = context_utils_1.setSpan; + this.setSpanContext = context_utils_1.setSpanContext; } /** Get the singleton instance of the Trace API */ TraceAPI.getInstance = function () { @@ -52520,12 +48287,16 @@ var TraceAPI = /** @class */ (function () { return this._instance; }; /** - * Set the current global tracer. Returns the initialized global tracer provider + * Set the current global tracer. + * + * @returns true if the tracer provider was successfully registered, else false */ TraceAPI.prototype.setGlobalTracerProvider = function (provider) { - this._proxyTracerProvider.setDelegate(provider); - global_utils_1.registerGlobal(API_NAME, this._proxyTracerProvider); - return this._proxyTracerProvider; + var success = global_utils_1.registerGlobal(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance()); + if (success) { + this._proxyTracerProvider.setDelegate(provider); + } + return success; }; /** * Returns the global tracer provider. @@ -52541,7 +48312,7 @@ var TraceAPI = /** @class */ (function () { }; /** Remove the global tracer provider */ TraceAPI.prototype.disable = function () { - global_utils_1.unregisterGlobal(API_NAME); + global_utils_1.unregisterGlobal(API_NAME, diag_1.DiagAPI.instance()); this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); }; return TraceAPI; @@ -52554,7 +48325,30 @@ exports.TraceAPI = TraceAPI; /* 877 */, /* 878 */, /* 879 */, -/* 880 */, +/* 880 */ +/***/ (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 + +/***/ }), /* 881 */ /***/ (function(__unusedmodule, exports) { @@ -53112,48 +48906,36 @@ exports.defaultTextMapSetter = { /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; -/*! - * Copyright (c) Microsoft and contributors. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. - * - * Azure Core LRO SDK for JavaScript - 1.0.5 - */ Object.defineProperty(exports, '__esModule', { value: true }); -var tslib = __webpack_require__(725); +var logger$1 = __webpack_require__(928); // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** * When a poller is manually stopped through the `stopPolling` method, * the poller will be rejected with an instance of the PollerStoppedError. */ -var PollerStoppedError = /** @class */ (function (_super) { - tslib.__extends(PollerStoppedError, _super); - function PollerStoppedError(message) { - var _this = _super.call(this, message) || this; - _this.name = "PollerStoppedError"; - Object.setPrototypeOf(_this, PollerStoppedError.prototype); - return _this; +class PollerStoppedError extends Error { + constructor(message) { + super(message); + this.name = "PollerStoppedError"; + Object.setPrototypeOf(this, PollerStoppedError.prototype); } - return PollerStoppedError; -}(Error)); +} /** * When a poller is cancelled through the `cancelOperation` method, * the poller will be rejected with an instance of the PollerCancelledError. */ -var PollerCancelledError = /** @class */ (function (_super) { - tslib.__extends(PollerCancelledError, _super); - function PollerCancelledError(message) { - var _this = _super.call(this, message) || this; - _this.name = "PollerCancelledError"; - Object.setPrototypeOf(_this, PollerCancelledError.prototype); - return _this; +class PollerCancelledError extends Error { + constructor(message) { + super(message); + this.name = "PollerCancelledError"; + Object.setPrototypeOf(this, PollerCancelledError.prototype); } - return PollerCancelledError; -}(Error)); +} /** * A class that represents the definition of a program that polls through consecutive requests * until it reaches a state of completion. @@ -53216,7 +48998,7 @@ var PollerCancelledError = /** @class */ (function (_super) { * */ // eslint-disable-next-line no-use-before-define -var Poller = /** @class */ (function () { +class Poller { /** * A poller needs to be initialized by passing in at least the basic properties of the `PollOperation`. * @@ -53282,19 +49064,18 @@ var Poller = /** @class */ (function () { * * @param operation - Must contain the basic properties of `PollOperation`. */ - function Poller(operation) { - var _this = this; + constructor(operation) { this.stopped = true; this.pollProgressCallbacks = []; this.operation = operation; - this.promise = new Promise(function (resolve, reject) { - _this.resolve = resolve; - _this.reject = reject; + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; }); // This prevents the UnhandledPromiseRejectionWarning in node.js from being thrown. // The above warning would get thrown if `poller.poll` is called, it returns an error, // and pullUntilDone did not have a .catch or await try/catch on it's return value. - this.promise.catch(function () { + this.promise.catch(() => { /* intentionally blank */ }); } @@ -53303,29 +49084,15 @@ var Poller = /** @class */ (function () { * Starts a loop that will break only if the poller is done * or if the poller is stopped. */ - Poller.prototype.startPolling = function () { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - if (this.stopped) { - this.stopped = false; - } - _a.label = 1; - case 1: - if (!(!this.isStopped() && !this.isDone())) return [3 /*break*/, 4]; - return [4 /*yield*/, this.poll()]; - case 2: - _a.sent(); - return [4 /*yield*/, this.delay()]; - case 3: - _a.sent(); - return [3 /*break*/, 1]; - case 4: return [2 /*return*/]; - } - }); - }); - }; + async startPolling() { + if (this.stopped) { + this.stopped = false; + } + while (!this.isStopped() && !this.isDone()) { + await this.poll(); + await this.delay(); + } + } /** * @internal * pollOnce does one polling, by calling to the update method of the underlying @@ -53335,44 +49102,31 @@ var Poller = /** @class */ (function () { * * @param options - Optional properties passed to the operation's update method. */ - Poller.prototype.pollOnce = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, e_1; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 3, , 4]); - if (!!this.isDone()) return [3 /*break*/, 2]; - _a = this; - return [4 /*yield*/, this.operation.update({ - abortSignal: options.abortSignal, - fireProgress: this.fireProgress.bind(this) - })]; - case 1: - _a.operation = _b.sent(); - if (this.isDone() && this.resolve) { - // If the poller has finished polling, this means we now have a result. - // However, it can be the case that TResult is instantiated to void, so - // we are not expecting a result anyway. To assert that we might not - // have a result eventually after finishing polling, we cast the result - // to TResult. - this.resolve(this.operation.state.result); - } - _b.label = 2; - case 2: return [3 /*break*/, 4]; - case 3: - e_1 = _b.sent(); - this.operation.state.error = e_1; - if (this.reject) { - this.reject(e_1); - } - throw e_1; - case 4: return [2 /*return*/]; + async pollOnce(options = {}) { + try { + if (!this.isDone()) { + this.operation = await this.operation.update({ + abortSignal: options.abortSignal, + fireProgress: this.fireProgress.bind(this) + }); + if (this.isDone() && this.resolve) { + // If the poller has finished polling, this means we now have a result. + // However, it can be the case that TResult is instantiated to void, so + // we are not expecting a result anyway. To assert that we might not + // have a result eventually after finishing polling, we cast the result + // to TResult. + this.resolve(this.operation.state.result); } - }); - }); - }; + } + } + catch (e) { + this.operation.state.error = e; + if (this.reject) { + this.reject(e); + } + throw e; + } + } /** * @internal * fireProgress calls the functions passed in via onProgress the method of the poller. @@ -53382,36 +49136,22 @@ var Poller = /** @class */ (function () { * * @param state - The current operation state. */ - Poller.prototype.fireProgress = function (state) { - for (var _i = 0, _a = this.pollProgressCallbacks; _i < _a.length; _i++) { - var callback = _a[_i]; + fireProgress(state) { + for (const callback of this.pollProgressCallbacks) { callback(state); } - }; + } /** * @internal * Invokes the underlying operation's cancel method, and rejects the * pollUntilDone promise. */ - Poller.prototype.cancelOnce = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = this; - return [4 /*yield*/, this.operation.cancel(options)]; - case 1: - _a.operation = _b.sent(); - if (this.reject) { - this.reject(new PollerCancelledError("Poller cancelled")); - } - return [2 /*return*/]; - } - }); - }); - }; + async cancelOnce(options = {}) { + this.operation = await this.operation.cancel(options); + if (this.reject) { + this.reject(new PollerCancelledError("Poller cancelled")); + } + } /** * Returns a promise that will resolve once a single polling request finishes. * It does this by calling the update method of the Poller's operation. @@ -53420,68 +49160,61 @@ var Poller = /** @class */ (function () { * * @param options - Optional properties passed to the operation's update method. */ - Poller.prototype.poll = function (options) { - var _this = this; - if (options === void 0) { options = {}; } + poll(options = {}) { if (!this.pollOncePromise) { this.pollOncePromise = this.pollOnce(options); - var clearPollOncePromise = function () { - _this.pollOncePromise = undefined; + const clearPollOncePromise = () => { + this.pollOncePromise = undefined; }; this.pollOncePromise.then(clearPollOncePromise, clearPollOncePromise).catch(this.reject); } return this.pollOncePromise; - }; + } /** * Returns a promise that will resolve once the underlying operation is completed. */ - Poller.prototype.pollUntilDone = function () { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - if (this.stopped) { - this.startPolling().catch(this.reject); - } - return [2 /*return*/, this.promise]; - }); - }); - }; + async pollUntilDone() { + if (this.stopped) { + this.startPolling().catch(this.reject); + } + return this.promise; + } /** * Invokes the provided callback after each polling is completed, * sending the current state of the poller's operation. * * It returns a method that can be used to stop receiving updates on the given callback function. */ - Poller.prototype.onProgress = function (callback) { - var _this = this; + onProgress(callback) { this.pollProgressCallbacks.push(callback); - return function () { - _this.pollProgressCallbacks = _this.pollProgressCallbacks.filter(function (c) { return c !== callback; }); + return () => { + this.pollProgressCallbacks = this.pollProgressCallbacks.filter((c) => c !== callback); }; - }; + } /** * Returns true if the poller has finished polling. */ - Poller.prototype.isDone = function () { - var state = this.operation.state; + isDone() { + const state = this.operation.state; return Boolean(state.isCompleted || state.isCancelled || state.error); - }; + } /** * Stops the poller from continuing to poll. */ - Poller.prototype.stopPolling = function () { + stopPolling() { if (!this.stopped) { this.stopped = true; if (this.reject) { this.reject(new PollerStoppedError("This poller is already stopped")); } } - }; + } /** * Returns true if the poller is stopped. */ - Poller.prototype.isStopped = function () { + isStopped() { return this.stopped; - }; + } /** * Attempts to cancel the underlying operation. * @@ -53491,8 +49224,7 @@ var Poller = /** @class */ (function () { * * @param options - Optional properties passed to the operation's update method. */ - Poller.prototype.cancelOperation = function (options) { - if (options === void 0) { options = {}; } + cancelOperation(options = {}) { if (!this.stopped) { this.stopped = true; } @@ -53503,7 +49235,7 @@ var Poller = /** @class */ (function () { throw new Error("A cancel request is currently pending"); } return this.cancelPromise; - }; + } /** * Returns the state of the operation. * @@ -53552,29 +49284,379 @@ var Poller = /** @class */ (function () { * `../test/utils/testPoller.ts` * and look for the getOperationState implementation. */ - Poller.prototype.getOperationState = function () { + getOperationState() { return this.operation.state; - }; + } /** * Returns the result value of the operation, * regardless of the state of the poller. * It can return undefined or an incomplete form of the final TResult value * depending on the implementation. */ - Poller.prototype.getResult = function () { - var state = this.operation.state; + getResult() { + const state = this.operation.state; return state.result; - }; + } /** * Returns a serialized version of the poller's operation * by invoking the operation's toString method. */ - Poller.prototype.toString = function () { + toString() { return this.operation.toString(); - }; - return Poller; -}()); + } +} +// Copyright (c) Microsoft Corporation. +/** + * The `@azure/logger` configuration for this package. + * @internal + */ +const logger = logger$1.createClientLogger("core-lro"); + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Detects where the continuation token is and returns it. Notice that azure-asyncoperation + * must be checked first before the other location headers because there are scenarios + * where both azure-asyncoperation and location could be present in the same response but + * azure-asyncoperation should be the one to use for polling. + */ +function getPollingUrl(rawResponse, defaultPath) { + var _a, _b, _c; + return ((_c = (_b = (_a = getAzureAsyncOperation(rawResponse)) !== null && _a !== void 0 ? _a : getLocation(rawResponse)) !== null && _b !== void 0 ? _b : getOperationLocation(rawResponse)) !== null && _c !== void 0 ? _c : defaultPath); +} +function getLocation(rawResponse) { + return rawResponse.headers["location"]; +} +function getOperationLocation(rawResponse) { + return rawResponse.headers["operation-location"]; +} +function getAzureAsyncOperation(rawResponse) { + return rawResponse.headers["azure-asyncoperation"]; +} +function inferLroMode(requestPath, requestMethod, rawResponse) { + if (getAzureAsyncOperation(rawResponse) !== undefined) { + return { + mode: "AzureAsync", + resourceLocation: requestMethod === "PUT" + ? requestPath + : requestMethod === "POST" + ? getLocation(rawResponse) + : undefined + }; + } + else if (getLocation(rawResponse) !== undefined || + getOperationLocation(rawResponse) !== undefined) { + return { + mode: "Location" + }; + } + else if (["PUT", "PATCH"].includes(requestMethod)) { + return { + mode: "Body" + }; + } + return {}; +} +class SimpleRestError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "RestError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, SimpleRestError.prototype); + } +} +function isUnexpectedInitialResponse(rawResponse) { + const code = rawResponse.statusCode; + if (![203, 204, 202, 201, 200, 500].includes(code)) { + throw new SimpleRestError(`Received unexpected HTTP status code ${code} in the initial response. This may indicate a server issue.`, code); + } + return false; +} +function isUnexpectedPollingResponse(rawResponse) { + const code = rawResponse.statusCode; + if (![202, 201, 200, 500].includes(code)) { + throw new SimpleRestError(`Received unexpected HTTP status code ${code} while polling. This may indicate a server issue.`, code); + } + return false; +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +const successStates = ["succeeded"]; +const failureStates = ["failed", "canceled", "cancelled"]; + +// Copyright (c) Microsoft Corporation. +function getResponseStatus(rawResponse) { + var _a; + const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; + return typeof status === "string" ? status.toLowerCase() : "succeeded"; +} +function isAzureAsyncPollingDone(rawResponse) { + const state = getResponseStatus(rawResponse); + if (isUnexpectedPollingResponse(rawResponse) || failureStates.includes(state)) { + throw new Error(`The long running operation has failed. The provisioning state: ${state}.`); + } + return successStates.includes(state); +} +/** + * Sends a request to the URI of the provisioned resource if needed. + */ +async function sendFinalRequest(lro, resourceLocation, lroResourceLocationConfig) { + switch (lroResourceLocationConfig) { + case "original-uri": + return lro.sendPollRequest(lro.requestPath); + case "azure-async-operation": + return undefined; + case "location": + default: + return lro.sendPollRequest(resourceLocation !== null && resourceLocation !== void 0 ? resourceLocation : lro.requestPath); + } +} +function processAzureAsyncOperationResult(lro, resourceLocation, lroResourceLocationConfig) { + return (response) => { + if (isAzureAsyncPollingDone(response.rawResponse)) { + if (resourceLocation === undefined) { + return Object.assign(Object.assign({}, response), { done: true }); + } + else { + return Object.assign(Object.assign({}, response), { done: false, next: async () => { + const finalResponse = await sendFinalRequest(lro, resourceLocation, lroResourceLocationConfig); + return Object.assign(Object.assign({}, (finalResponse !== null && finalResponse !== void 0 ? finalResponse : response)), { done: true }); + } }); + } + } + return Object.assign(Object.assign({}, response), { done: false }); + }; +} + +// Copyright (c) Microsoft Corporation. +function getProvisioningState(rawResponse) { + var _a, _b; + const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; + const state = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState; + return typeof state === "string" ? state.toLowerCase() : "succeeded"; +} +function isBodyPollingDone(rawResponse) { + const state = getProvisioningState(rawResponse); + if (isUnexpectedPollingResponse(rawResponse) || failureStates.includes(state)) { + throw new Error(`The long running operation has failed. The provisioning state: ${state}.`); + } + return successStates.includes(state); +} +/** + * Creates a polling strategy based on BodyPolling which uses the provisioning state + * from the result to determine the current operation state + */ +function processBodyPollingOperationResult(response) { + return Object.assign(Object.assign({}, response), { done: isBodyPollingDone(response.rawResponse) }); +} + +// Copyright (c) Microsoft Corporation. +function isLocationPollingDone(rawResponse) { + return !isUnexpectedPollingResponse(rawResponse) && rawResponse.statusCode !== 202; +} +function processLocationPollingOperationResult(response) { + return Object.assign(Object.assign({}, response), { done: isLocationPollingDone(response.rawResponse) }); +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +function processPassthroughOperationResult(response) { + return Object.assign(Object.assign({}, response), { done: true }); +} + +// Copyright (c) Microsoft Corporation. +/** + * creates a stepping function that maps an LRO state to another. + */ +function createGetLroStatusFromResponse(lroPrimitives, config, lroResourceLocationConfig) { + switch (config.mode) { + case "AzureAsync": { + return processAzureAsyncOperationResult(lroPrimitives, config.resourceLocation, lroResourceLocationConfig); + } + case "Location": { + return processLocationPollingOperationResult; + } + case "Body": { + return processBodyPollingOperationResult; + } + default: { + return processPassthroughOperationResult; + } + } +} +/** + * Creates a polling operation. + */ +function createPoll(lroPrimitives) { + return async (path, pollerConfig, getLroStatusFromResponse) => { + const response = await lroPrimitives.sendPollRequest(path); + const retryAfter = response.rawResponse.headers["retry-after"]; + if (retryAfter !== undefined) { + const retryAfterInMs = parseInt(retryAfter); + pollerConfig.intervalInMs = isNaN(retryAfterInMs) + ? calculatePollingIntervalFromDate(new Date(retryAfter), pollerConfig.intervalInMs) + : retryAfterInMs; + } + return getLroStatusFromResponse(response); + }; +} +function calculatePollingIntervalFromDate(retryAfterDate, defaultIntervalInMs) { + const timeNow = Math.floor(new Date().getTime()); + const retryAfterTime = retryAfterDate.getTime(); + if (timeNow < retryAfterTime) { + return retryAfterTime - timeNow; + } + return defaultIntervalInMs; +} +/** + * Creates a callback to be used to initialize the polling operation state. + * @param state - of the polling operation + * @param operationSpec - of the LRO + * @param callback - callback to be called when the operation is done + * @returns callback that initializes the state of the polling operation + */ +function createInitializeState(state, requestPath, requestMethod) { + return (response) => { + if (isUnexpectedInitialResponse(response.rawResponse)) + ; + state.initialRawResponse = response.rawResponse; + state.isStarted = true; + state.pollingURL = getPollingUrl(state.initialRawResponse, requestPath); + state.config = inferLroMode(requestPath, requestMethod, state.initialRawResponse); + /** short circuit polling if body polling is done in the initial request */ + if (state.config.mode === undefined || + (state.config.mode === "Body" && isBodyPollingDone(state.initialRawResponse))) { + state.result = response.flatResponse; + state.isCompleted = true; + } + logger.verbose(`LRO: initial state: ${JSON.stringify(state)}`); + return Boolean(state.isCompleted); + }; +} + +// Copyright (c) Microsoft Corporation. +class GenericPollOperation { + constructor(state, lro, lroResourceLocationConfig, processResult, updateState, isDone) { + this.state = state; + this.lro = lro; + this.lroResourceLocationConfig = lroResourceLocationConfig; + this.processResult = processResult; + this.updateState = updateState; + this.isDone = isDone; + } + setPollerConfig(pollerConfig) { + this.pollerConfig = pollerConfig; + } + /** + * General update function for LROPoller, the general process is as follows + * 1. Check initial operation result to determine the strategy to use + * - Strategies: Location, Azure-AsyncOperation, Original Uri + * 2. Check if the operation result has a terminal state + * - Terminal state will be determined by each strategy + * 2.1 If it is terminal state Check if a final GET request is required, if so + * send final GET request and return result from operation. If no final GET + * is required, just return the result from operation. + * - Determining what to call for final request is responsibility of each strategy + * 2.2 If it is not terminal state, call the polling operation and go to step 1 + * - Determining what to call for polling is responsibility of each strategy + * - Strategies will always use the latest URI for polling if provided otherwise + * the last known one + */ + async update(options) { + var _a, _b, _c; + const state = this.state; + let lastResponse = undefined; + if (!state.isStarted) { + const initializeState = createInitializeState(state, this.lro.requestPath, this.lro.requestMethod); + lastResponse = await this.lro.sendInitialRequest(); + initializeState(lastResponse); + } + if (!state.isCompleted) { + if (!this.poll || !this.getLroStatusFromResponse) { + if (!state.config) { + throw new Error("Bad state: LRO mode is undefined. Please check if the serialized state is well-formed."); + } + const isDone = this.isDone; + this.getLroStatusFromResponse = isDone + ? (response) => (Object.assign(Object.assign({}, response), { done: isDone(response.flatResponse, this.state) })) + : createGetLroStatusFromResponse(this.lro, state.config, this.lroResourceLocationConfig); + this.poll = createPoll(this.lro); + } + if (!state.pollingURL) { + throw new Error("Bad state: polling URL is undefined. Please check if the serialized state is well-formed."); + } + const currentState = await this.poll(state.pollingURL, this.pollerConfig, this.getLroStatusFromResponse); + logger.verbose(`LRO: polling response: ${JSON.stringify(currentState.rawResponse)}`); + if (currentState.done) { + state.result = this.processResult + ? this.processResult(currentState.flatResponse, state) + : currentState.flatResponse; + state.isCompleted = true; + } + else { + this.poll = (_a = currentState.next) !== null && _a !== void 0 ? _a : this.poll; + state.pollingURL = getPollingUrl(currentState.rawResponse, state.pollingURL); + } + lastResponse = currentState; + } + logger.verbose(`LRO: current state: ${JSON.stringify(state)}`); + if (lastResponse) { + (_b = this.updateState) === null || _b === void 0 ? void 0 : _b.call(this, state, lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.rawResponse); + } + else { + logger.error(`LRO: no response was received`); + } + (_c = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _c === void 0 ? void 0 : _c.call(options, state); + return this; + } + async cancel() { + this.state.isCancelled = true; + return this; + } + /** + * Serializes the Poller operation. + */ + toString() { + return JSON.stringify({ + state: this.state + }); + } +} + +// Copyright (c) Microsoft Corporation. +function deserializeState(serializedState) { + try { + return JSON.parse(serializedState).state; + } + catch (e) { + throw new Error(`LroEngine: Unable to deserialize state: ${serializedState}`); + } +} +/** + * The LRO Engine, a class that performs polling. + */ +class LroEngine extends Poller { + constructor(lro, options) { + const { intervalInMs = 2000, resumeFrom } = options || {}; + const state = resumeFrom + ? deserializeState(resumeFrom) + : {}; + const operation = new GenericPollOperation(state, lro, options === null || options === void 0 ? void 0 : options.lroResourceLocationConfig, options === null || options === void 0 ? void 0 : options.processResult, options === null || options === void 0 ? void 0 : options.updateState, options === null || options === void 0 ? void 0 : options.isDone); + super(operation); + this.config = { intervalInMs: intervalInMs }; + operation.setPollerConfig(this.config); + } + /** + * The method used by the poller to wait before attempting to update its operation. + */ + delay() { + return new Promise((resolve) => setTimeout(() => resolve(), this.config.intervalInMs)); + } +} + +exports.LroEngine = LroEngine; exports.Poller = Poller; exports.PollerCancelledError = PollerCancelledError; exports.PollerStoppedError = PollerStoppedError; @@ -53723,83 +49805,7 @@ var isArray = Array.isArray || function (xs) { /***/ }), /* 897 */, -/* 898 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; -/*! - * Copyright (c) 2015, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of Salesforce.com nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -const pubsuffix = __webpack_require__(562); - -// Gives the permutation of all possible domainMatch()es of a given domain. The -// array is in shortest-to-longest order. Handy for indexing. -const SPECIAL_USE_DOMAINS = ["local"]; // RFC 6761 -function permuteDomain(domain, allowSpecialUseDomain) { - let pubSuf = null; - if (allowSpecialUseDomain) { - const domainParts = domain.split("."); - if (SPECIAL_USE_DOMAINS.includes(domainParts[domainParts.length - 1])) { - pubSuf = `${domainParts[domainParts.length - 2]}.${ - domainParts[domainParts.length - 1] - }`; - } else { - pubSuf = pubsuffix.getPublicSuffix(domain); - } - } else { - pubSuf = pubsuffix.getPublicSuffix(domain); - } - - if (!pubSuf) { - return null; - } - if (pubSuf == domain) { - return [domain]; - } - - const prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com" - const parts = prefix.split(".").reverse(); - let cur = pubSuf; - const permutations = [cur]; - while (parts.length) { - cur = `${parts.shift()}.${cur}`; - permutations.push(cur); - } - return permutations; -} - -exports.permuteDomain = permuteDomain; - - -/***/ }), +/* 898 */, /* 899 */, /* 900 */, /* 901 */, @@ -53939,7 +49945,7 @@ __exportStar(__webpack_require__(764), exports); * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); -exports.NOOP_TEXT_MAP_PROPAGATOR = exports.NoopTextMapPropagator = void 0; +exports.NoopTextMapPropagator = void 0; /** * No-op implementations of {@link TextMapPropagator}. */ @@ -53958,7 +49964,6 @@ var NoopTextMapPropagator = /** @class */ (function () { return NoopTextMapPropagator; }()); exports.NoopTextMapPropagator = NoopTextMapPropagator; -exports.NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator(); //# sourceMappingURL=NoopTextMapPropagator.js.map /***/ }), @@ -54022,143 +50027,92 @@ Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var tslib = __webpack_require__(262); var util = _interopDefault(__webpack_require__(669)); var os = __webpack_require__(87); // Copyright (c) Microsoft Corporation. -function log(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - process.stderr.write("" + util.format.apply(util, tslib.__spread([message], args)) + os.EOL); +function log(message, ...args) { + process.stderr.write(`${util.format(message, ...args)}${os.EOL}`); } // Copyright (c) Microsoft Corporation. -var debugEnvVariable = (typeof process !== "undefined" && process.env && process.env.DEBUG) || undefined; -var enabledString; -var enabledNamespaces = []; -var skippedNamespaces = []; -var debuggers = []; +const debugEnvVariable = (typeof process !== "undefined" && process.env && process.env.DEBUG) || undefined; +let enabledString; +let enabledNamespaces = []; +let skippedNamespaces = []; +const debuggers = []; if (debugEnvVariable) { enable(debugEnvVariable); } -var debugObj = Object.assign(function (namespace) { +const debugObj = Object.assign((namespace) => { return createDebugger(namespace); }, { - enable: enable, - enabled: enabled, - disable: disable, - log: log + enable, + enabled, + disable, + log }); function enable(namespaces) { - var e_1, _a, e_2, _b; enabledString = namespaces; enabledNamespaces = []; skippedNamespaces = []; - var wildcard = /\*/g; - var namespaceList = namespaces.split(",").map(function (ns) { return ns.trim().replace(wildcard, ".*?"); }); - try { - for (var namespaceList_1 = tslib.__values(namespaceList), namespaceList_1_1 = namespaceList_1.next(); !namespaceList_1_1.done; namespaceList_1_1 = namespaceList_1.next()) { - var ns = namespaceList_1_1.value; - if (ns.startsWith("-")) { - skippedNamespaces.push(new RegExp("^" + ns.substr(1) + "$")); - } - else { - enabledNamespaces.push(new RegExp("^" + ns + "$")); - } + const wildcard = /\*/g; + const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); + for (const ns of namespaceList) { + if (ns.startsWith("-")) { + skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); + } + else { + enabledNamespaces.push(new RegExp(`^${ns}$`)); } } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (namespaceList_1_1 && !namespaceList_1_1.done && (_a = namespaceList_1.return)) _a.call(namespaceList_1); - } - finally { if (e_1) throw e_1.error; } - } - try { - for (var debuggers_1 = tslib.__values(debuggers), debuggers_1_1 = debuggers_1.next(); !debuggers_1_1.done; debuggers_1_1 = debuggers_1.next()) { - var instance = debuggers_1_1.value; - instance.enabled = enabled(instance.namespace); - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (debuggers_1_1 && !debuggers_1_1.done && (_b = debuggers_1.return)) _b.call(debuggers_1); - } - finally { if (e_2) throw e_2.error; } + for (const instance of debuggers) { + instance.enabled = enabled(instance.namespace); } } function enabled(namespace) { - var e_3, _a, e_4, _b; if (namespace.endsWith("*")) { return true; } - try { - for (var skippedNamespaces_1 = tslib.__values(skippedNamespaces), skippedNamespaces_1_1 = skippedNamespaces_1.next(); !skippedNamespaces_1_1.done; skippedNamespaces_1_1 = skippedNamespaces_1.next()) { - var skipped = skippedNamespaces_1_1.value; - if (skipped.test(namespace)) { - return false; - } + for (const skipped of skippedNamespaces) { + if (skipped.test(namespace)) { + return false; } } - catch (e_3_1) { e_3 = { error: e_3_1 }; } - finally { - try { - if (skippedNamespaces_1_1 && !skippedNamespaces_1_1.done && (_a = skippedNamespaces_1.return)) _a.call(skippedNamespaces_1); + for (const enabledNamespace of enabledNamespaces) { + if (enabledNamespace.test(namespace)) { + return true; } - finally { if (e_3) throw e_3.error; } - } - try { - for (var enabledNamespaces_1 = tslib.__values(enabledNamespaces), enabledNamespaces_1_1 = enabledNamespaces_1.next(); !enabledNamespaces_1_1.done; enabledNamespaces_1_1 = enabledNamespaces_1.next()) { - var enabledNamespace = enabledNamespaces_1_1.value; - if (enabledNamespace.test(namespace)) { - return true; - } - } - } - catch (e_4_1) { e_4 = { error: e_4_1 }; } - finally { - try { - if (enabledNamespaces_1_1 && !enabledNamespaces_1_1.done && (_b = enabledNamespaces_1.return)) _b.call(enabledNamespaces_1); - } - finally { if (e_4) throw e_4.error; } } return false; } function disable() { - var result = enabledString || ""; + const result = enabledString || ""; enable(""); return result; } function createDebugger(namespace) { - var newDebugger = Object.assign(debug, { + const newDebugger = Object.assign(debug, { enabled: enabled(namespace), - destroy: destroy, + destroy, log: debugObj.log, - namespace: namespace, - extend: extend + namespace, + extend }); - function debug() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } + function debug(...args) { if (!newDebugger.enabled) { return; } if (args.length > 0) { - args[0] = namespace + " " + args[0]; + args[0] = `${namespace} ${args[0]}`; } - newDebugger.log.apply(newDebugger, tslib.__spread(args)); + newDebugger.log(...args); } debuggers.push(newDebugger); return newDebugger; } function destroy() { - var index = debuggers.indexOf(this); + const index = debuggers.indexOf(this); if (index >= 0) { debuggers.splice(index, 1); return true; @@ -54166,36 +50120,32 @@ function destroy() { return false; } function extend(namespace) { - var newDebugger = createDebugger(this.namespace + ":" + namespace); + const newDebugger = createDebugger(`${this.namespace}:${namespace}`); newDebugger.log = this.log; return newDebugger; } // Copyright (c) Microsoft Corporation. -var registeredLoggers = new Set(); -var logLevelFromEnv = (typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL) || undefined; -var azureLogLevel; +const registeredLoggers = new Set(); +const logLevelFromEnv = (typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL) || undefined; +let azureLogLevel; /** * The AzureLogger provides a mechanism for overriding where logs are output to. * By default, logs are sent to stderr. * Override the `log` method to redirect logs to another location. */ -var AzureLogger = debugObj("azure"); -AzureLogger.log = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - debugObj.log.apply(debugObj, tslib.__spread(args)); +const AzureLogger = debugObj("azure"); +AzureLogger.log = (...args) => { + debugObj.log(...args); }; -var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; +const AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; if (logLevelFromEnv) { // avoid calling setLogLevel because we don't want a mis-set environment variable to crash if (isAzureLogLevel(logLevelFromEnv)) { setLogLevel(logLevelFromEnv); } else { - console.error("AZURE_LOG_LEVEL set to unknown log level '" + logLevelFromEnv + "'; logging is not enabled. Acceptable values: " + AZURE_LOG_LEVELS.join(", ") + "."); + console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); } } /** @@ -54208,27 +50158,16 @@ if (logLevelFromEnv) { * - error */ function setLogLevel(level) { - var e_1, _a; if (level && !isAzureLogLevel(level)) { - throw new Error("Unknown log level '" + level + "'. Acceptable values: " + AZURE_LOG_LEVELS.join(",")); + throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); } azureLogLevel = level; - var enabledNamespaces = []; - try { - for (var registeredLoggers_1 = tslib.__values(registeredLoggers), registeredLoggers_1_1 = registeredLoggers_1.next(); !registeredLoggers_1_1.done; registeredLoggers_1_1 = registeredLoggers_1.next()) { - var logger = registeredLoggers_1_1.value; - if (shouldEnable(logger)) { - enabledNamespaces.push(logger.namespace); - } + const enabledNamespaces = []; + for (const logger of registeredLoggers) { + if (shouldEnable(logger)) { + enabledNamespaces.push(logger.namespace); } } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (registeredLoggers_1_1 && !registeredLoggers_1_1.done && (_a = registeredLoggers_1.return)) _a.call(registeredLoggers_1); - } - finally { if (e_1) throw e_1.error; } - } debugObj.enable(enabledNamespaces.join(",")); } /** @@ -54237,7 +50176,7 @@ function setLogLevel(level) { function getLogLevel() { return azureLogLevel; } -var levelMap = { +const levelMap = { verbose: 400, info: 300, warning: 200, @@ -54249,7 +50188,7 @@ var levelMap = { * @hidden */ function createClientLogger(namespace) { - var clientRootLogger = AzureLogger.extend(namespace); + const clientRootLogger = AzureLogger.extend(namespace); patchLogMethod(AzureLogger, clientRootLogger); return { error: createLogger(clientRootLogger, "error"), @@ -54259,21 +50198,17 @@ function createClientLogger(namespace) { }; } function patchLogMethod(parent, child) { - child.log = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - parent.log.apply(parent, tslib.__spread(args)); + child.log = (...args) => { + parent.log(...args); }; } function createLogger(parent, level) { - var logger = Object.assign(parent.extend(level), { - level: level + const logger = Object.assign(parent.extend(level), { + level }); patchLogMethod(parent, logger); if (shouldEnable(logger)) { - var enabledNamespaces = debugObj.disable(); + const enabledNamespaces = debugObj.disable(); debugObj.enable(enabledNamespaces + "," + logger.namespace); } registeredLoggers.add(logger); @@ -54365,30 +50300,7 @@ var SpanStatusCode; /* 935 */, /* 936 */, /* 937 */, -/* 938 */ -/***/ (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=Baggage.js.map - -/***/ }), +/* 938 */, /* 939 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -54428,36 +50340,7 @@ function terminator(callback) /* 941 */, /* 942 */, /* 943 */, -/* 944 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = rng; - -var _crypto = _interopRequireDefault(__webpack_require__(417)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate - -let poolPtr = rnds8Pool.length; - -function rng() { - if (poolPtr > rnds8Pool.length - 16) { - _crypto.default.randomFillSync(rnds8Pool); - - poolPtr = 0; - } - - return rnds8Pool.slice(poolPtr, poolPtr += 16); -} - -/***/ }), +/* 944 */, /* 945 */, /* 946 */, /* 947 */, @@ -55044,7 +50927,7 @@ exports.getExecOutput = getExecOutput; Object.defineProperty(exports, "__esModule", { value: true }); exports.isCompatible = exports._makeCompatibilityCheck = void 0; var version_1 = __webpack_require__(830); -var re = /^(\d+)\.(\d+)\.(\d+)(?:-(.*))?$/; +var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; /** * Create a function to test an API version to see if it is compatible with the provided ownVersion. * @@ -55073,7 +50956,14 @@ function _makeCompatibilityCheck(ownVersion) { major: +myVersionMatch[1], minor: +myVersionMatch[2], patch: +myVersionMatch[3], + prerelease: myVersionMatch[4], }; + // if ownVersion has a prerelease tag, versions must match exactly + if (ownVersionParsed.prerelease != null) { + return function isExactmatch(globalVersion) { + return globalVersion === ownVersion; + }; + } function _reject(v) { rejectedVersions.add(v); return false; @@ -55099,7 +50989,12 @@ function _makeCompatibilityCheck(ownVersion) { major: +globalVersionMatch[1], minor: +globalVersionMatch[2], patch: +globalVersionMatch[3], + prerelease: globalVersionMatch[4], }; + // if globalVersion has a prerelease tag, versions must match exactly + if (globalVersionParsed.prerelease != null) { + return _reject(globalVersion); + } // major versions must match if (ownVersionParsed.major !== globalVersionParsed.major) { return _reject(globalVersion); @@ -55202,9 +51097,8 @@ Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var tslib = __webpack_require__(865); var uuid = __webpack_require__(585); -var tough = __webpack_require__(393); +var tough = __webpack_require__(701); var http = __webpack_require__(605); var https = __webpack_require__(211); var node_fetch = _interopDefault(__webpack_require__(454)); @@ -55215,11 +51109,12 @@ var url = __webpack_require__(835); var stream = __webpack_require__(794); var logger$1 = __webpack_require__(928); var tunnel = __webpack_require__(413); +var tslib = __webpack_require__(865); var coreAuth = __webpack_require__(229); var xml2js = __webpack_require__(992); var os = __webpack_require__(87); var coreTracing = __webpack_require__(263); -__webpack_require__(71); +__webpack_require__(338); // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -55231,7 +51126,7 @@ function getHeaderKey(headerName) { } function isHttpHeadersLike(object) { if (object && typeof object === "object") { - var castObject = object; + const castObject = object; if (typeof castObject.rawHeaders === "function" && typeof castObject.clone === "function" && typeof castObject.get === "function" && @@ -55250,11 +51145,11 @@ function isHttpHeadersLike(object) { /** * A collection of HTTP header key/value pairs. */ -var HttpHeaders = /** @class */ (function () { - function HttpHeaders(rawHeaders) { +class HttpHeaders { + constructor(rawHeaders) { this._headersMap = {}; if (rawHeaders) { - for (var headerName in rawHeaders) { + for (const headerName in rawHeaders) { this.set(headerName, rawHeaders[headerName]); } } @@ -55265,100 +51160,104 @@ var HttpHeaders = /** @class */ (function () { * @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) { + set(headerName, headerValue) { this._headersMap[getHeaderKey(headerName)] = { name: headerName, value: headerValue.toString() }; - }; + } /** * 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. */ - HttpHeaders.prototype.get = function (headerName) { - var header = this._headersMap[getHeaderKey(headerName)]; + get(headerName) { + const header = this._headersMap[getHeaderKey(headerName)]; return !header ? undefined : header.value; - }; + } /** * Get whether or not this header collection contains a header entry for the provided header name. */ - HttpHeaders.prototype.contains = function (headerName) { + contains(headerName) { return !!this._headersMap[getHeaderKey(headerName)]; - }; + } /** * 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. */ - HttpHeaders.prototype.remove = function (headerName) { - var result = this.contains(headerName); + remove(headerName) { + const result = this.contains(headerName); delete this._headersMap[getHeaderKey(headerName)]; return result; - }; + } /** * Get the headers that are contained this collection as an object. */ - HttpHeaders.prototype.rawHeaders = function () { - var result = {}; - for (var headerKey in this._headersMap) { - var header = this._headersMap[headerKey]; + rawHeaders() { + const result = {}; + for (const headerKey in this._headersMap) { + const header = this._headersMap[headerKey]; result[header.name.toLowerCase()] = header.value; } return result; - }; + } /** * Get the headers that are contained in this collection as an array. */ - HttpHeaders.prototype.headersArray = function () { - var headers = []; - for (var headerKey in this._headersMap) { + headersArray() { + const headers = []; + for (const headerKey in this._headersMap) { headers.push(this._headersMap[headerKey]); } return headers; - }; + } /** * Get the header names that are contained in this collection. */ - HttpHeaders.prototype.headerNames = function () { - var headerNames = []; - var headers = this.headersArray(); - for (var i = 0; i < headers.length; ++i) { + headerNames() { + const headerNames = []; + const headers = this.headersArray(); + for (let i = 0; i < headers.length; ++i) { headerNames.push(headers[i].name); } return headerNames; - }; + } /** * Get the header values that are contained in this collection. */ - HttpHeaders.prototype.headerValues = function () { - var headerValues = []; - var headers = this.headersArray(); - for (var i = 0; i < headers.length; ++i) { + headerValues() { + const headerValues = []; + const headers = this.headersArray(); + for (let i = 0; i < headers.length; ++i) { headerValues.push(headers[i].value); } return headerValues; - }; + } /** * Get the JSON object representation of this HTTP header collection. */ - HttpHeaders.prototype.toJson = function () { + toJson() { return this.rawHeaders(); - }; + } /** * Get the string representation of this HTTP header collection. */ - HttpHeaders.prototype.toString = function () { + toString() { return JSON.stringify(this.toJson()); - }; + } /** * Create a deep clone/copy of this HttpHeaders collection. */ - HttpHeaders.prototype.clone = function () { - return new HttpHeaders(this.rawHeaders()); - }; - return HttpHeaders; -}()); + clone() { + const resultPreservingCasing = {}; + for (const headerKey in this._headersMap) { + const header = this._headersMap[headerKey]; + resultPreservingCasing[header.name] = header.value; + } + return new HttpHeaders(resultPreservingCasing); + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -55376,7 +51275,7 @@ function encodeString(value) { function encodeByteArray(value) { // Buffer.from accepts | -- the TypeScript definition is off here // https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length - var bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer); + const bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer); return bufferValue.toString("base64"); } /** @@ -55389,11 +51288,11 @@ function decodeString(value) { // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -var Constants = { +const Constants = { /** * The core-http version */ - coreHttpVersion: "1.2.6", + coreHttpVersion: "2.2.2", /** * Specifies HTTP. */ @@ -55432,7 +51331,8 @@ var Constants = { PATCH: "PATCH" }, StatusCodes: { - TooManyRequests: 429 + TooManyRequests: 429, + ServiceUnavailable: 503 } }, /** @@ -55462,18 +51362,18 @@ var Constants = { /** * Default key used to access the XML attributes. */ -var XML_ATTRKEY = "$"; +const XML_ATTRKEY = "$"; /** * Default key used to access the XML value content. */ -var XML_CHARKEY = "_"; +const 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; +const 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; /** * A constant that indicates whether the environment is node.js or browser based. */ -var isNode = typeof process !== "undefined" && +const isNode = typeof process !== "undefined" && !!process.version && !!process.versions && !!process.versions.node; @@ -55499,7 +51399,7 @@ function encodeUri(uri) { * @returns The stripped version of Http Response. */ function stripResponse(response) { - var strippedResponse = {}; + const strippedResponse = {}; strippedResponse.body = response.bodyAsText; strippedResponse.headers = response.headers; strippedResponse.status = response.status; @@ -55513,7 +51413,7 @@ function stripResponse(response) { * @returns The stripped version of Http Request. */ function stripRequest(request) { - var strippedRequest = request.clone(); + const strippedRequest = request.clone(); if (strippedRequest.headers) { strippedRequest.headers.remove("authorization"); } @@ -55546,21 +51446,12 @@ function generateUuid() { * @returns A chain of resolved or rejected promises */ function executePromisesSequentially(promiseFactories, kickstart) { - var result = Promise.resolve(kickstart); - promiseFactories.forEach(function (promiseFactory) { + let result = Promise.resolve(kickstart); + promiseFactories.forEach((promiseFactory) => { result = result.then(promiseFactory); }); return result; } -/** - * 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 - */ -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 @@ -55573,13 +51464,13 @@ function promiseToCallback(promise) { throw new Error("The provided input is not a Promise."); } // eslint-disable-next-line @typescript-eslint/ban-types - return function (cb) { + return (cb) => { promise - .then(function (data) { + .then((data) => { // eslint-disable-next-line promise/no-callback-in-promise return cb(undefined, data); }) - .catch(function (err) { + .catch((err) => { // eslint-disable-next-line promise/no-callback-in-promise cb(err); }); @@ -55594,26 +51485,25 @@ function promiseToServiceCallback(promise) { if (typeof promise.then !== "function") { throw new Error("The provided input is not a Promise."); } - return function (cb) { + return (cb) => { promise - .then(function (data) { + .then((data) => { return process.nextTick(cb, undefined, data.parsedBody, data.request, data); }) - .catch(function (err) { + .catch((err) => { process.nextTick(cb, err); }); }; } function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) { - var _a, _b, _c; if (!Array.isArray(obj)) { obj = [obj]; } if (!xmlNamespaceKey || !xmlNamespace) { - return _a = {}, _a[elementName] = obj, _a; + return { [elementName]: obj }; } - var result = (_b = {}, _b[elementName] = obj, _b); - result[XML_ATTRKEY] = (_c = {}, _c[xmlNamespaceKey] = xmlNamespace, _c); + const result = { [elementName]: obj }; + result[XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace }; return result; } /** @@ -55622,14 +51512,14 @@ function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) { * @param 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) { + const castTargetCtorParam = targetCtorParam; + sourceCtors.forEach((sourceCtor) => { + Object.getOwnPropertyNames(sourceCtor.prototype).forEach((name) => { castTargetCtorParam.prototype[name] = sourceCtor.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)?)?$/; +const 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. @@ -55679,19 +51569,18 @@ function isObject(input) { } // Copyright (c) Microsoft Corporation. -var Serializer = /** @class */ (function () { - function Serializer(modelMappers, isXML) { - if (modelMappers === void 0) { modelMappers = {}; } +class Serializer { + constructor(modelMappers = {}, isXML) { this.modelMappers = modelMappers; this.isXML = isXML; } - Serializer.prototype.validateConstraints = function (mapper, value, objectName) { - var failValidation = function (constraintName, constraintValue) { - throw new Error("\"" + objectName + "\" with value \"" + value + "\" should satisfy the constraint \"" + constraintName + "\": " + constraintValue + "."); + validateConstraints(mapper, value, objectName) { + const failValidation = (constraintName, constraintValue) => { + 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; + const valueAsNumber = value; + const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems } = mapper.constraints; if (ExclusiveMaximum != undefined && valueAsNumber >= ExclusiveMaximum) { failValidation("ExclusiveMaximum", ExclusiveMaximum); } @@ -55704,7 +51593,7 @@ var Serializer = /** @class */ (function () { if (InclusiveMinimum != undefined && valueAsNumber < InclusiveMinimum) { failValidation("InclusiveMinimum", InclusiveMinimum); } - var valueAsArray = value; + const valueAsArray = value; if (MaxItems != undefined && valueAsArray.length > MaxItems) { failValidation("MaxItems", MaxItems); } @@ -55721,17 +51610,17 @@ var Serializer = /** @class */ (function () { failValidation("MultipleOf", MultipleOf); } if (Pattern) { - var pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern; + const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern; if (typeof value !== "string" || value.match(pattern) === null) { failValidation("Pattern", Pattern); } } if (UniqueItems && - valueAsArray.some(function (item, i, ar) { return ar.indexOf(item) !== i; })) { + valueAsArray.some((item, i, ar) => ar.indexOf(item) !== i)) { failValidation("UniqueItems", UniqueItems); } } - }; + } /** * Serialize the given object based on its metadata defined in the mapper * @@ -55741,16 +51630,15 @@ var Serializer = /** @class */ (function () { * @param options - additional options to deserialization * @returns A valid serialized Javascript object */ - Serializer.prototype.serialize = function (mapper, object, objectName, options) { + serialize(mapper, object, objectName, options = {}) { var _a, _b, _c; - if (options === void 0) { options = {}; } - var updatedOptions = { + const 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 }; - var payload = {}; - var mapperType = mapper.type.name; + let payload = {}; + const mapperType = mapper.type.name; if (!objectName) { objectName = mapper.serializedName; } @@ -55769,15 +51657,15 @@ var Serializer = /** @class */ (function () { // true || null | undefined/null // false || X | undefined // undefined || X | undefined/null - var required = mapper.required, nullable = mapper.nullable; + const { required, nullable } = mapper; if (required && nullable && object === undefined) { - throw new Error(objectName + " cannot be undefined."); + throw new Error(`${objectName} cannot be undefined.`); } if (required && !nullable && object == undefined) { - throw new Error(objectName + " cannot be null or undefined."); + throw new Error(`${objectName} cannot be null or undefined.`); } if (!required && nullable === false && object === null) { - throw new Error(objectName + " cannot be null."); + throw new Error(`${objectName} cannot be null.`); } if (object == undefined) { payload = object; @@ -55792,7 +51680,7 @@ var Serializer = /** @class */ (function () { payload = serializeBasicTypes(mapperType, objectName, object); } else if (mapperType.match(/^Enum$/i) !== null) { - var enumMapper = mapper; + const enumMapper = mapper; payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object); } else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) { @@ -55815,7 +51703,7 @@ var Serializer = /** @class */ (function () { } } return payload; - }; + } /** * Deserialize the given object based on its metadata defined in the mapper * @@ -55825,10 +51713,9 @@ var Serializer = /** @class */ (function () { * @param options - Controls behavior of XML parser and builder. * @returns A valid deserialized Javascript object */ - Serializer.prototype.deserialize = function (mapper, responseBody, objectName, options) { + deserialize(mapper, responseBody, objectName, options = {}) { var _a, _b, _c; - if (options === void 0) { options = {}; } - var updatedOptions = { + const 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 @@ -55846,8 +51733,8 @@ var Serializer = /** @class */ (function () { } return responseBody; } - var payload; - var mapperType = mapper.type.name; + let payload; + const mapperType = mapper.type.name; if (!objectName) { objectName = mapper.serializedName; } @@ -55856,8 +51743,8 @@ var Serializer = /** @class */ (function () { } else { if (this.isXML) { - var xmlCharKey = updatedOptions.xmlCharKey; - var castResponseBody = responseBody; + const xmlCharKey = updatedOptions.xmlCharKey; + const 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, @@ -55911,11 +51798,10 @@ var Serializer = /** @class */ (function () { payload = mapper.defaultValue; } return payload; - }; - return Serializer; -}()); + } +} function trimEnd(str, ch) { - var len = str.length; + let len = str.length; while (len - 1 >= 0 && str[len - 1] === ch) { --len; } @@ -55926,10 +51812,10 @@ function bufferToBase64Url(buffer) { return undefined; } if (!(buffer instanceof Uint8Array)) { - throw new Error("Please provide an input of type Uint8Array for converting to Base64Url."); + throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`); } // Uint8Array to Base64. - var str = encodeByteArray(buffer); + const str = encodeByteArray(buffer); // Base64 to Base64Url. return trimEnd(str, "=") .replace(/\+/g, "-") @@ -55948,12 +51834,11 @@ function base64UrlToByteArray(str) { return decodeString(str); } function splitSerializeName(prop) { - var classes = []; - var partialclass = ""; + const classes = []; + let partialclass = ""; if (prop) { - var subwords = prop.split("."); - for (var _i = 0, subwords_1 = subwords; _i < subwords_1.length; _i++) { - var item = subwords_1[_i]; + const subwords = prop.split("."); + for (const item of subwords) { if (item.charAt(item.length - 1) === "\\") { partialclass += item.substr(0, item.length - 1) + "."; } @@ -55985,32 +51870,32 @@ function serializeBasicTypes(typeName, objectName, value) { if (value !== null && value !== undefined) { if (typeName.match(/^Number$/i) !== null) { if (typeof value !== "number") { - throw new Error(objectName + " with value " + value + " must be of type number."); + throw new Error(`${objectName} with value ${value} must be of type number.`); } } else if (typeName.match(/^String$/i) !== null) { if (typeof value.valueOf() !== "string") { - throw new Error(objectName + " with value \"" + value + "\" must be of type string."); + throw new Error(`${objectName} with value "${value}" must be of type string.`); } } else if (typeName.match(/^Uuid$/i) !== null) { if (!(typeof value.valueOf() === "string" && isValidUuid(value))) { - throw new Error(objectName + " with value \"" + value + "\" must be of type string and a valid uuid."); + throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`); } } else if (typeName.match(/^Boolean$/i) !== null) { if (typeof value !== "boolean") { - throw new Error(objectName + " with value " + value + " must be of type boolean."); + throw new Error(`${objectName} with value ${value} must be of type boolean.`); } } else if (typeName.match(/^Stream$/i) !== null) { - var objectType = typeof value; + const objectType = typeof value; if (objectType !== "string" && objectType !== "function" && !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value) && !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob)) { - throw new Error(objectName + " must be a string, Blob, ArrayBuffer, ArrayBufferView, or a function returning NodeJS.ReadableStream."); + throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, or a function returning NodeJS.ReadableStream.`); } } } @@ -56018,34 +51903,34 @@ function serializeBasicTypes(typeName, objectName, value) { } function serializeEnumType(objectName, allowedValues, value) { if (!allowedValues) { - throw new Error("Please provide a set of allowedValues to validate " + objectName + " as an Enum Type."); + throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`); } - var isPresent = allowedValues.some(function (item) { + const isPresent = allowedValues.some((item) => { if (typeof item.valueOf() === "string") { return item.toLowerCase() === value.toLowerCase(); } return item === value; }); if (!isPresent) { - throw new Error(value + " is not a valid value for " + objectName + ". The valid values are: " + JSON.stringify(allowedValues) + "."); + throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`); } return value; } function serializeByteArrayType(objectName, value) { - var returnValue = ""; + let returnValue = ""; if (value != undefined) { if (!(value instanceof Uint8Array)) { - throw new Error(objectName + " must be of type Uint8Array."); + throw new Error(`${objectName} must be of type Uint8Array.`); } returnValue = encodeByteArray(value); } return returnValue; } function serializeBase64UrlType(objectName, value) { - var returnValue = ""; + let returnValue = ""; if (value != undefined) { if (!(value instanceof Uint8Array)) { - throw new Error(objectName + " must be of type Uint8Array."); + throw new Error(`${objectName} must be of type Uint8Array.`); } returnValue = bufferToBase64Url(value) || ""; } @@ -56056,7 +51941,7 @@ function serializeDateTypes(typeName, value, objectName) { if (typeName.match(/^Date$/i) !== null) { if (!(value instanceof Date || (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { - throw new Error(objectName + " must be an instanceof Date or a string in ISO8601 format."); + throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); } value = value instanceof Date @@ -56066,58 +51951,57 @@ function serializeDateTypes(typeName, value, objectName) { else if (typeName.match(/^DateTime$/i) !== null) { if (!(value instanceof Date || (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { - throw new Error(objectName + " must be an instanceof Date or a string in ISO8601 format."); + throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); } value = value instanceof Date ? value.toISOString() : new Date(value).toISOString(); } else if (typeName.match(/^DateTimeRfc1123$/i) !== null) { if (!(value instanceof Date || (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { - throw new Error(objectName + " must be an instanceof Date or a string in RFC-1123 format."); + throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`); } value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString(); } else if (typeName.match(/^UnixTime$/i) !== null) { if (!(value instanceof Date || (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { - throw new Error(objectName + " must be an instanceof Date or a string in RFC-1123/ISO8601 format " + - "for it to be serialized in UnixTime/Epoch format."); + throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format ` + + `for it to be serialized in UnixTime/Epoch format.`); } value = dateToUnixTime(value); } else if (typeName.match(/^TimeSpan$/i) !== null) { if (!isDuration(value)) { - throw new Error(objectName + " must be a string in ISO 8601 format. Instead was \"" + value + "\"."); + throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`); } } } return value; } function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) { - var _a, _b; if (!Array.isArray(object)) { - throw new Error(objectName + " must be of type Array."); + throw new Error(`${objectName} must be of type Array.`); } - var elementType = mapper.type.element; + const elementType = mapper.type.element; if (!elementType || typeof elementType !== "object") { - throw new Error("element\" metadata for an Array must be defined in the " + - ("mapper and it must of type \"object\" in " + objectName + ".")); + throw new Error(`element" metadata for an Array must be defined in the ` + + `mapper and it must of type "object" in ${objectName}.`); } - var tempArray = []; - for (var i = 0; i < object.length; i++) { - var serializedValue = serializer.serialize(elementType, object[i], objectName, options); + const tempArray = []; + for (let i = 0; i < object.length; i++) { + const serializedValue = serializer.serialize(elementType, object[i], objectName, options); if (isXml && elementType.xmlNamespace) { - var xmlnsKey = elementType.xmlNamespacePrefix - ? "xmlns:" + elementType.xmlNamespacePrefix + const 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] = Object.assign({}, serializedValue); + tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; } else { tempArray[i] = {}; tempArray[i][options.xmlCharKey] = serializedValue; - tempArray[i][XML_ATTRKEY] = (_b = {}, _b[xmlnsKey] = elementType.xmlNamespace, _b); + tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; } } else { @@ -56127,27 +52011,25 @@ function serializeSequenceType(serializer, mapper, object, objectName, isXml, op return tempArray; } function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) { - var _a; if (typeof object !== "object") { - throw new Error(objectName + " must be of type object."); + throw new Error(`${objectName} must be of type object.`); } - var valueType = mapper.type.value; + const valueType = mapper.type.value; if (!valueType || typeof valueType !== "object") { - throw new Error("\"value\" metadata for a Dictionary must be defined in the " + - ("mapper and it must of type \"object\" in " + objectName + ".")); + throw new Error(`"value" metadata for a Dictionary must be defined in the ` + + `mapper and it must of type "object" in ${objectName}.`); } - 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); + const tempDictionary = {}; + for (const key of Object.keys(object)) { + const serializedValue = serializer.serialize(valueType, object[key], objectName, options); // If the element needs an XML namespace we need to add it within the $ property tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options); } // 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); + const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns"; + const result = tempDictionary; + result[XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace }; return result; } return tempDictionary; @@ -56159,9 +52041,9 @@ function serializeDictionaryType(serializer, mapper, object, objectName, isXml, * @param objectName - Name of the object being serialized */ function resolveAdditionalProperties(serializer, mapper, objectName) { - var additionalProperties = mapper.type.additionalProperties; + const additionalProperties = mapper.type.additionalProperties; if (!additionalProperties && mapper.type.className) { - var modelMapper = resolveReferencedMapper(serializer, mapper, objectName); + const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); return modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.additionalProperties; } return additionalProperties; @@ -56173,9 +52055,9 @@ function resolveAdditionalProperties(serializer, mapper, objectName) { * @param objectName - Name of the object being serialized */ function resolveReferencedMapper(serializer, mapper, objectName) { - var className = mapper.type.className; + const className = mapper.type.className; if (!className) { - throw new Error("Class name for model \"" + objectName + "\" is not provided in the mapper \"" + JSON.stringify(mapper, undefined, 2) + "\"."); + throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, undefined, 2)}".`); } return serializer.modelMappers[className]; } @@ -56185,36 +52067,34 @@ function resolveReferencedMapper(serializer, mapper, objectName) { * @param mapper - The composite mapper to resolve */ function resolveModelProperties(serializer, mapper, objectName) { - var modelProps = mapper.type.modelProperties; + let modelProps = mapper.type.modelProperties; if (!modelProps) { - var modelMapper = resolveReferencedMapper(serializer, mapper, objectName); + const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); if (!modelMapper) { - throw new Error("mapper() cannot be null or undefined for model \"" + mapper.type.className + "\"."); + throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`); } modelProps = modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.modelProperties; if (!modelProps) { - throw new Error("modelProperties cannot be null or undefined in the " + - ("mapper \"" + JSON.stringify(modelMapper) + "\" of type \"" + mapper.type.className + "\" for object \"" + objectName + "\".")); + throw new Error(`modelProperties cannot be null or undefined in the ` + + `mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`); } } return modelProps; } function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) { - var _a, _b; if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { mapper = getPolymorphicMapper(serializer, mapper, object, "clientName"); } if (object != undefined) { - var payload = {}; - var modelProps = resolveModelProperties(serializer, mapper, objectName); - for (var _i = 0, _c = Object.keys(modelProps); _i < _c.length; _i++) { - var key = _c[_i]; - var propertyMapper = modelProps[key]; + const payload = {}; + const modelProps = resolveModelProperties(serializer, mapper, objectName); + for (const key of Object.keys(modelProps)) { + const propertyMapper = modelProps[key]; if (propertyMapper.readOnly) { continue; } - var propName = void 0; - var parentObject = payload; + let propName; + let parentObject = payload; if (serializer.isXML) { if (propertyMapper.xmlIsWrapped) { propName = propertyMapper.xmlName; @@ -56224,11 +52104,10 @@ function serializeCompositeType(serializer, mapper, object, objectName, isXml, o } } else { - var paths = splitSerializeName(propertyMapper.serializedName); + const paths = splitSerializeName(propertyMapper.serializedName); propName = paths.pop(); - for (var _d = 0, paths_1 = paths; _d < paths_1.length; _d++) { - var pathName = paths_1[_d]; - var childObject = parentObject[pathName]; + for (const pathName of paths) { + const childObject = parentObject[pathName]; if (childObject == undefined && (object[key] != undefined || propertyMapper.defaultValue !== undefined)) { parentObject[pathName] = {}; @@ -56238,24 +52117,24 @@ function serializeCompositeType(serializer, mapper, object, objectName, isXml, o } if (parentObject != undefined) { if (isXml && mapper.xmlNamespace) { - var xmlnsKey = mapper.xmlNamespacePrefix - ? "xmlns:" + mapper.xmlNamespacePrefix + const xmlnsKey = mapper.xmlNamespacePrefix + ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns"; - parentObject[XML_ATTRKEY] = tslib.__assign(tslib.__assign({}, parentObject[XML_ATTRKEY]), (_a = {}, _a[xmlnsKey] = mapper.xmlNamespace, _a)); + parentObject[XML_ATTRKEY] = Object.assign(Object.assign({}, parentObject[XML_ATTRKEY]), { [xmlnsKey]: mapper.xmlNamespace }); } - var propertyObjectName = propertyMapper.serializedName !== "" + const propertyObjectName = propertyMapper.serializedName !== "" ? objectName + "." + propertyMapper.serializedName : objectName; - var toSerialize = object[key]; - var polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); + let toSerialize = object[key]; + const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); if (polymorphicDiscriminator && polymorphicDiscriminator.clientName === key && toSerialize == undefined) { toSerialize = mapper.serializedName; } - var serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options); + const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options); if (serializedValue !== undefined && propName != undefined) { - var value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options); + const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options); if (isXml && propertyMapper.xmlIsAttribute) { // XML_ATTRKEY, i.e., $ is the key attributes are kept under in xml2js. // This keeps things simple while preventing name collision @@ -56264,7 +52143,7 @@ function serializeCompositeType(serializer, mapper, object, objectName, isXml, o parentObject[XML_ATTRKEY][propName] = serializedValue; } else if (isXml && propertyMapper.xmlIsWrapped) { - parentObject[propName] = (_b = {}, _b[propertyMapper.xmlElementName] = value, _b); + parentObject[propName] = { [propertyMapper.xmlElementName]: value }; } else { parentObject[propName] = value; @@ -56272,17 +52151,14 @@ function serializeCompositeType(serializer, mapper, object, objectName, isXml, o } } } - var additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName); + const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName); if (additionalPropertiesMapper) { - var propNames = Object.keys(modelProps); - var _loop_1 = function (clientPropName) { - var isAdditionalProperty = propNames.every(function (pn) { return pn !== clientPropName; }); + const propNames = Object.keys(modelProps); + for (const clientPropName in object) { + const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName); if (isAdditionalProperty) { payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options); } - }; - for (var clientPropName in object) { - _loop_1(clientPropName); } } return payload; @@ -56290,25 +52166,24 @@ function serializeCompositeType(serializer, mapper, object, objectName, isXml, o return object; } function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) { - var _a; if (!isXml || !propertyMapper.xmlNamespace) { return serializedValue; } - var xmlnsKey = propertyMapper.xmlNamespacePrefix - ? "xmlns:" + propertyMapper.xmlNamespacePrefix + const xmlnsKey = propertyMapper.xmlNamespacePrefix + ? `xmlns:${propertyMapper.xmlNamespacePrefix}` : "xmlns"; - var xmlNamespace = (_a = {}, _a[xmlnsKey] = propertyMapper.xmlNamespace, _a); + const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace }; 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; + const result = Object.assign({}, serializedValue); + result[XML_ATTRKEY] = xmlNamespace; + return result; } } - var result = {}; + const result = {}; result[options.xmlCharKey] = serializedValue; result[XML_ATTRKEY] = xmlNamespace; return result; @@ -56321,24 +52196,22 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName"); } - var modelProps = resolveModelProperties(serializer, mapper, objectName); - var instance = {}; - var handledPropertyNames = []; - for (var _i = 0, _b = Object.keys(modelProps); _i < _b.length; _i++) { - var key = _b[_i]; - var propertyMapper = modelProps[key]; - var paths = splitSerializeName(modelProps[key].serializedName); + const modelProps = resolveModelProperties(serializer, mapper, objectName); + let instance = {}; + const handledPropertyNames = []; + for (const key of Object.keys(modelProps)) { + const propertyMapper = modelProps[key]; + const paths = splitSerializeName(modelProps[key].serializedName); handledPropertyNames.push(paths[0]); - var serializedName = propertyMapper.serializedName, xmlName = propertyMapper.xmlName, xmlElementName = propertyMapper.xmlElementName; - var propertyObjectName = objectName; + const { serializedName, xmlName, xmlElementName } = propertyMapper; + let propertyObjectName = objectName; if (serializedName !== "" && serializedName !== undefined) { propertyObjectName = objectName + "." + serializedName; } - var headerCollectionPrefix = propertyMapper.headerCollectionPrefix; + const headerCollectionPrefix = propertyMapper.headerCollectionPrefix; if (headerCollectionPrefix) { - var dictionary = {}; - for (var _c = 0, _d = Object.keys(responseBody); _c < _d.length; _c++) { - var headerKey = _d[_c]; + const dictionary = {}; + for (const headerKey of Object.keys(responseBody)) { if (headerKey.startsWith(headerCollectionPrefix)) { dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options); } @@ -56351,7 +52224,7 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, instance[key] = serializer.deserialize(propertyMapper, responseBody[XML_ATTRKEY][xmlName], propertyObjectName, options); } else { - var propertyName = xmlElementName || xmlName || serializedName; + const propertyName = xmlElementName || xmlName || serializedName; if (propertyMapper.xmlIsWrapped) { /* a list of wrapped by For the xml example below @@ -56367,29 +52240,28 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, } xmlName is "Cors" and xmlElementName is"CorsRule". */ - var wrapped = responseBody[xmlName]; - var elementList = (_a = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _a !== void 0 ? _a : []; + const wrapped = responseBody[xmlName]; + const elementList = (_a = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _a !== void 0 ? _a : []; instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options); } else { - var property = responseBody[propertyName]; + const property = responseBody[propertyName]; instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options); } } } else { // deserialize the property if it is present in the provided responseBody instance - var propertyInstance = void 0; - var res = responseBody; + let propertyInstance; + let res = responseBody; // traversing the object step by step. - for (var _e = 0, paths_2 = paths; _e < paths_2.length; _e++) { - var item = paths_2[_e]; + for (const item of paths) { if (!res) break; res = res[item]; } propertyInstance = res; - var polymorphicDiscriminator = mapper.type.polymorphicDiscriminator; + const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator; // checking that the model property name (key)(ex: "fishtype") and the // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype") // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type") @@ -56404,15 +52276,14 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, propertyInstance == undefined) { propertyInstance = mapper.serializedName; } - var serializedValue = void 0; + let serializedValue; // paging if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") { propertyInstance = responseBody[key]; - var arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); + const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); // Copy over any properties that have already been added into the instance, where they do // not exist on the newly de-serialized array - for (var _f = 0, _g = Object.entries(instance); _f < _g.length; _f++) { - var _h = _g[_f], k = _h[0], v = _h[1]; + for (const [k, v] of Object.entries(instance)) { if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) { arrayInstance[k] = v; } @@ -56425,26 +52296,25 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, } } } - var additionalPropertiesMapper = mapper.type.additionalProperties; + const additionalPropertiesMapper = mapper.type.additionalProperties; if (additionalPropertiesMapper) { - var isAdditionalProperty = function (responsePropName) { - for (var clientPropName in modelProps) { - var paths = splitSerializeName(modelProps[clientPropName].serializedName); + const isAdditionalProperty = (responsePropName) => { + for (const clientPropName in modelProps) { + const paths = splitSerializeName(modelProps[clientPropName].serializedName); if (paths[0] === responsePropName) { return false; } } return true; }; - for (var responsePropName in responseBody) { + for (const responsePropName in responseBody) { if (isAdditionalProperty(responsePropName)) { instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options); } } } else if (responseBody) { - for (var _j = 0, _k = Object.keys(responseBody); _j < _k.length; _j++) { - var key = _k[_j]; + for (const key of Object.keys(responseBody)) { if (instance[key] === undefined && !handledPropertyNames.includes(key) && !isSpecialXmlProperty(key, options)) { @@ -56455,15 +52325,14 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, return instance; } function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) { - var value = mapper.type.value; + const value = mapper.type.value; if (!value || typeof value !== "object") { - throw new Error("\"value\" metadata for a Dictionary must be defined in the " + - ("mapper and it must of type \"object\" in " + objectName)); + throw new Error(`"value" metadata for a Dictionary must be defined in the ` + + `mapper and it must of type "object" in ${objectName}`); } if (responseBody) { - var tempDictionary = {}; - for (var _i = 0, _a = Object.keys(responseBody); _i < _a.length; _i++) { - var key = _a[_i]; + const tempDictionary = {}; + for (const key of Object.keys(responseBody)) { tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options); } return tempDictionary; @@ -56471,36 +52340,36 @@ function deserializeDictionaryType(serializer, mapper, responseBody, objectName, return responseBody; } function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) { - var element = mapper.type.element; + const element = mapper.type.element; if (!element || typeof element !== "object") { - throw new Error("element\" metadata for an Array must be defined in the " + - ("mapper and it must of type \"object\" in " + objectName)); + throw new Error(`element" metadata for an Array must be defined in the ` + + `mapper and it must of type "object" in ${objectName}`); } if (responseBody) { if (!Array.isArray(responseBody)) { // xml2js will interpret a single element array as just the element, so force it to be an array responseBody = [responseBody]; } - var tempArray = []; - for (var i = 0; i < responseBody.length; i++) { - tempArray[i] = serializer.deserialize(element, responseBody[i], objectName + "[" + i + "]", options); + const tempArray = []; + for (let i = 0; i < responseBody.length; i++) { + tempArray[i] = serializer.deserialize(element, responseBody[i], `${objectName}[${i}]`, options); } return tempArray; } return responseBody; } function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) { - var polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); + const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); if (polymorphicDiscriminator) { - var discriminatorName = polymorphicDiscriminator[polymorphicPropertyName]; + const discriminatorName = polymorphicDiscriminator[polymorphicPropertyName]; if (discriminatorName != undefined) { - var discriminatorValue = object[discriminatorName]; + const discriminatorValue = object[discriminatorName]; if (discriminatorValue != undefined) { - var typeName = mapper.type.uberParent || mapper.type.className; - var indexDiscriminator = discriminatorValue === typeName + const typeName = mapper.type.uberParent || mapper.type.className; + const indexDiscriminator = discriminatorValue === typeName ? discriminatorValue : typeName + "." + discriminatorValue; - var polymorphicMapper = serializer.modelMappers.discriminators[indexDiscriminator]; + const polymorphicMapper = serializer.modelMappers.discriminators[indexDiscriminator]; if (polymorphicMapper) { mapper = polymorphicMapper; } @@ -56521,7 +52390,7 @@ function getPolymorphicDiscriminatorSafely(serializer, typeName) { } // TODO: why is this here? function serializeObject(toSerialize) { - var castToSerialize = toSerialize; + const castToSerialize = toSerialize; if (toSerialize == undefined) return undefined; if (toSerialize instanceof Uint8Array) { @@ -56532,15 +52401,15 @@ function serializeObject(toSerialize) { return toSerialize.toISOString(); } else if (Array.isArray(toSerialize)) { - var array = []; - for (var i = 0; i < toSerialize.length; i++) { + const array = []; + for (let i = 0; i < toSerialize.length; i++) { array.push(serializeObject(toSerialize[i])); } return array; } else if (typeof toSerialize === "object") { - var dictionary = {}; - for (var property in toSerialize) { + const dictionary = {}; + for (const property in toSerialize) { dictionary[property] = serializeObject(castToSerialize[property]); } return dictionary; @@ -56551,15 +52420,14 @@ function serializeObject(toSerialize) { * Utility function to create a K:V from a list of strings */ function strEnum(o) { - var result = {}; - for (var _i = 0, o_1 = o; _i < o_1.length; _i++) { - var key = o_1[_i]; + const result = {}; + for (const key of o) { result[key] = key; } return result; } // eslint-disable-next-line @typescript-eslint/no-redeclare -var MapperType = strEnum([ +const MapperType = strEnum([ "Base64Url", "Boolean", "ByteArray", @@ -56581,7 +52449,7 @@ var MapperType = strEnum([ // Copyright (c) Microsoft Corporation. function isWebResourceLike(object) { if (object && typeof object === "object") { - var castObject = object; + const castObject = object; if (typeof castObject.url === "string" && typeof castObject.method === "string" && typeof castObject.headers === "object" && @@ -56600,8 +52468,8 @@ 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. */ -var WebResource = /** @class */ (function () { - function WebResource(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, decompressResponse, streamResponseStatusCodes) { +class WebResource { + constructor(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, decompressResponse, streamResponseStatusCodes) { this.streamResponseBody = streamResponseBody; this.streamResponseStatusCodes = streamResponseStatusCodes; this.url = url || ""; @@ -56625,20 +52493,20 @@ var WebResource = /** @class */ (function () { * headers["accept-language"] are defined. It will throw an error if one of the above * mentioned properties are not defined. */ - WebResource.prototype.validateRequestProperties = function () { + validateRequestProperties() { if (!this.method) { throw new Error("WebResource.method is required."); } if (!this.url) { throw new Error("WebResource.url is required."); } - }; + } /** * 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. */ - WebResource.prototype.prepare = function (options) { + prepare(options) { if (!options) { throw new Error("options object is required"); } @@ -56667,7 +52535,7 @@ var WebResource = /** @class */ (function () { } // set the method if (options.method) { - var validMethods = ["GET", "PUT", "HEAD", "DELETE", "OPTIONS", "POST", "PATCH", "TRACE"]; + const validMethods = ["GET", "PUT", "HEAD", "DELETE", "OPTIONS", "POST", "PATCH", "TRACE"]; if (validMethods.indexOf(options.method.toUpperCase()) === -1) { throw new Error('The provided method "' + options.method + @@ -56678,70 +52546,70 @@ var WebResource = /** @class */ (function () { this.method = options.method.toUpperCase(); // construct the url if path template is provided if (options.pathTemplate) { - var pathTemplate_1 = options.pathTemplate, pathParameters_1 = options.pathParameters; - if (typeof pathTemplate_1 !== "string") { + const { pathTemplate, pathParameters } = options; + if (typeof pathTemplate !== "string") { throw new Error('options.pathTemplate must be of type "string".'); } if (!options.baseUrl) { options.baseUrl = "https://management.azure.com"; } - var baseUrl = options.baseUrl; - var url_1 = baseUrl + + const baseUrl = options.baseUrl; + let url = baseUrl + (baseUrl.endsWith("/") ? "" : "/") + - (pathTemplate_1.startsWith("/") ? pathTemplate_1.slice(1) : pathTemplate_1); - var segments = url_1.match(/({[\w-]*\s*[\w-]*})/gi); + (pathTemplate.startsWith("/") ? pathTemplate.slice(1) : pathTemplate); + const segments = url.match(/({[\w-]*\s*[\w-]*})/gi); if (segments && segments.length) { - if (!pathParameters_1) { - throw new Error("pathTemplate: " + pathTemplate_1 + " has been provided. Hence, options.pathParameters must also be provided."); + if (!pathParameters) { + throw new Error(`pathTemplate: ${pathTemplate} has been provided. Hence, options.pathParameters must also be provided.`); } segments.forEach(function (item) { - var pathParamName = item.slice(1, -1); - var pathParam = pathParameters_1[pathParamName]; + const pathParamName = item.slice(1, -1); + const pathParam = pathParameters[pathParamName]; if (pathParam === null || pathParam === undefined || !(typeof pathParam === "string" || typeof pathParam === "object")) { - var stringifiedPathParameters = JSON.stringify(pathParameters_1, undefined, 2); - throw new Error("pathTemplate: " + pathTemplate_1 + " contains the path parameter " + pathParamName + - (" however, it is not present in parameters: " + stringifiedPathParameters + ".") + - ("The value of the path parameter can either be a \"string\" of the form { " + pathParamName + ": \"some sample value\" } or ") + - ("it can be an \"object\" of the form { \"" + pathParamName + "\": { value: \"some sample value\", skipUrlEncoding: true } }.")); + const stringifiedPathParameters = JSON.stringify(pathParameters, undefined, 2); + throw new Error(`pathTemplate: ${pathTemplate} contains the path parameter ${pathParamName}` + + ` however, it is not present in parameters: ${stringifiedPathParameters}.` + + `The value of the path parameter can either be a "string" of the form { ${pathParamName}: "some sample value" } or ` + + `it can be an "object" of the form { "${pathParamName}": { value: "some sample value", skipUrlEncoding: true } }.`); } if (typeof pathParam.valueOf() === "string") { - url_1 = url_1.replace(item, encodeURIComponent(pathParam)); + url = url.replace(item, encodeURIComponent(pathParam)); } if (typeof pathParam.valueOf() === "object") { if (!pathParam.value) { - throw new Error("options.pathParameters[" + pathParamName + "] is of type \"object\" but it does not contain a \"value\" property."); + throw new Error(`options.pathParameters[${pathParamName}] is of type "object" but it does not contain a "value" property.`); } if (pathParam.skipUrlEncoding) { - url_1 = url_1.replace(item, pathParam.value); + url = url.replace(item, pathParam.value); } else { - url_1 = url_1.replace(item, encodeURIComponent(pathParam.value)); + url = url.replace(item, encodeURIComponent(pathParam.value)); } } }); } - this.url = url_1; + this.url = url; } // append query parameters to the url if they are provided. They can be provided with pathTemplate or url option. if (options.queryParameters) { - var queryParameters = options.queryParameters; + const queryParameters = options.queryParameters; if (typeof queryParameters !== "object") { - throw new Error("options.queryParameters must be of type object. It should be a JSON object " + - "of \"query-parameter-name\" as the key and the \"query-parameter-value\" as the value. " + - "The \"query-parameter-value\" may be fo type \"string\" or an \"object\" of the form { value: \"query-parameter-value\", skipUrlEncoding: true }."); + throw new Error(`options.queryParameters must be of type object. It should be a JSON object ` + + `of "query-parameter-name" as the key and the "query-parameter-value" as the value. ` + + `The "query-parameter-value" may be fo type "string" or an "object" of the form { value: "query-parameter-value", skipUrlEncoding: true }.`); } // append question mark if it is not present in the url if (this.url && this.url.indexOf("?") === -1) { this.url += "?"; } // construct queryString - var queryParams = []; + const queryParams = []; // We need to populate this.query as a dictionary if the request is being used for Sway's validateRequest(). this.query = {}; - for (var queryParamName in queryParameters) { - var queryParam = queryParameters[queryParamName]; + for (const queryParamName in queryParameters) { + const queryParam = queryParameters[queryParamName]; if (queryParam) { if (typeof queryParam === "string") { queryParams.push(queryParamName + "=" + encodeURIComponent(queryParam)); @@ -56749,7 +52617,7 @@ var WebResource = /** @class */ (function () { } else if (typeof queryParam === "object") { if (!queryParam.value) { - throw new Error("options.queryParameters[" + queryParamName + "] is of type \"object\" but it does not contain a \"value\" property."); + throw new Error(`options.queryParameters[${queryParamName}] is of type "object" but it does not contain a "value" property.`); } if (queryParam.skipUrlEncoding) { queryParams.push(queryParamName + "=" + queryParam.value); @@ -56767,9 +52635,8 @@ var WebResource = /** @class */ (function () { } // add headers to the request if they are provided if (options.headers) { - var headers = options.headers; - for (var _i = 0, _a = Object.keys(options.headers); _i < _a.length; _i++) { - var headerName = _a[_i]; + const headers = options.headers; + for (const headerName of Object.keys(options.headers)) { this.headers.set(headerName, headers[headerName]); } } @@ -56816,13 +52683,13 @@ var WebResource = /** @class */ (function () { this.onDownloadProgress = options.onDownloadProgress; this.onUploadProgress = options.onUploadProgress; return this; - }; + } /** * Clone this WebResource HTTP request object. * @returns 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); + clone() { + const 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); if (this.formData) { result.formData = this.formData; } @@ -56836,43 +52703,42 @@ var WebResource = /** @class */ (function () { result.operationResponseGetter = this.operationResponseGetter; } return result; - }; - return WebResource; -}()); + } +} // Copyright (c) Microsoft Corporation. -var custom = util.inspect.custom; +const custom = util.inspect.custom; // Copyright (c) Microsoft Corporation. /** * A class that handles the query portion of a URLBuilder. */ -var URLQuery = /** @class */ (function () { - function URLQuery() { +class URLQuery { + constructor() { this._rawQuery = {}; } /** * Get whether or not there any query parameters in this URLQuery. */ - URLQuery.prototype.any = function () { + any() { return Object.keys(this._rawQuery).length > 0; - }; + } /** * Get the keys of the query string. */ - URLQuery.prototype.keys = function () { + keys() { return Object.keys(this._rawQuery); - }; + } /** * Set a query parameter with the provided name and value. If the parameterValue is undefined or * empty, then this will attempt to remove an existing query parameter with the provided * parameterName. */ - URLQuery.prototype.set = function (parameterName, parameterValue) { - var caseParameterValue = parameterValue; + set(parameterName, parameterValue) { + const caseParameterValue = parameterValue; if (parameterName) { if (caseParameterValue !== undefined && caseParameterValue !== null) { - var newValue = Array.isArray(caseParameterValue) + const newValue = Array.isArray(caseParameterValue) ? caseParameterValue : caseParameterValue.toString(); this._rawQuery[parameterName] = newValue; @@ -56881,52 +52747,51 @@ var URLQuery = /** @class */ (function () { delete this._rawQuery[parameterName]; } } - }; + } /** * Get the value of the query parameter with the provided name. If no parameter exists with the * provided parameter name, then undefined will be returned. */ - URLQuery.prototype.get = function (parameterName) { + get(parameterName) { return parameterName ? this._rawQuery[parameterName] : undefined; - }; + } /** * Get the string representation of this query. The return value will not start with a "?". */ - URLQuery.prototype.toString = function () { - var result = ""; - for (var parameterName in this._rawQuery) { + toString() { + let result = ""; + for (const parameterName in this._rawQuery) { if (result) { result += "&"; } - var parameterValue = this._rawQuery[parameterName]; + const parameterValue = this._rawQuery[parameterName]; if (Array.isArray(parameterValue)) { - var parameterStrings = []; - for (var _i = 0, parameterValue_1 = parameterValue; _i < parameterValue_1.length; _i++) { - var parameterValueElement = parameterValue_1[_i]; - parameterStrings.push(parameterName + "=" + parameterValueElement); + const parameterStrings = []; + for (const parameterValueElement of parameterValue) { + parameterStrings.push(`${parameterName}=${parameterValueElement}`); } result += parameterStrings.join("&"); } else { - result += parameterName + "=" + parameterValue; + result += `${parameterName}=${parameterValue}`; } } return result; - }; + } /** * Parse a URLQuery from the provided text. */ - URLQuery.parse = function (text) { - var result = new URLQuery(); + static parse(text) { + const result = new URLQuery(); if (text) { if (text.startsWith("?")) { text = text.substring(1); } - var currentState = "ParameterName"; - var parameterName = ""; - var parameterValue = ""; - for (var i = 0; i < text.length; ++i) { - var currentCharacter = text[i]; + let currentState = "ParameterName"; + let parameterName = ""; + let parameterValue = ""; + for (let i = 0; i < text.length; ++i) { + const currentCharacter = text[i]; switch (currentState) { case "ParameterName": switch (currentCharacter) { @@ -56964,81 +52829,78 @@ var URLQuery = /** @class */ (function () { } } return result; - }; - return URLQuery; -}()); + } +} /** * A class that handles creating, modifying, and parsing URLs. */ -var URLBuilder = /** @class */ (function () { - function URLBuilder() { - } +class URLBuilder { /** * Set the scheme/protocol for this URL. If the provided scheme contains other parts of a URL * (such as a host, port, path, or query), those parts will be added to this URL as well. */ - URLBuilder.prototype.setScheme = function (scheme) { + setScheme(scheme) { if (!scheme) { this._scheme = undefined; } else { this.set(scheme, "SCHEME"); } - }; + } /** * Get the scheme that has been set in this URL. */ - URLBuilder.prototype.getScheme = function () { + getScheme() { return this._scheme; - }; + } /** * Set the host for this URL. If the provided host contains other parts of a URL (such as a * port, path, or query), those parts will be added to this URL as well. */ - URLBuilder.prototype.setHost = function (host) { + setHost(host) { if (!host) { this._host = undefined; } else { this.set(host, "SCHEME_OR_HOST"); } - }; + } /** * Get the host that has been set in this URL. */ - URLBuilder.prototype.getHost = function () { + getHost() { return this._host; - }; + } /** * Set the port for this URL. If the provided port contains other parts of a URL (such as a * path or query), those parts will be added to this URL as well. */ - URLBuilder.prototype.setPort = function (port) { + setPort(port) { if (port === undefined || port === null || port === "") { this._port = undefined; } else { this.set(port.toString(), "PORT"); } - }; + } /** * Get the port that has been set in this URL. */ - URLBuilder.prototype.getPort = function () { + getPort() { return this._port; - }; + } /** * Set the path for this URL. If the provided path contains a query, then it will be added to * this URL as well. */ - URLBuilder.prototype.setPath = function (path) { + setPath(path) { if (!path) { this._path = undefined; } else { - var schemeIndex = path.indexOf("://"); + const schemeIndex = path.indexOf("://"); if (schemeIndex !== -1) { - var schemeStart = path.lastIndexOf("/", schemeIndex); + const schemeStart = path.lastIndexOf("/", schemeIndex); // Make sure to only grab the URL part of the path before setting the state back to SCHEME // this will handle cases such as "/a/b/c/https://microsoft.com" => "https://microsoft.com" this.set(schemeStart === -1 ? path : path.substr(schemeStart + 1), "SCHEME"); @@ -57047,14 +52909,14 @@ var URLBuilder = /** @class */ (function () { this.set(path, "PATH"); } } - }; + } /** * Append the provided path to this URL's existing path. If the provided path contains a query, * then it will be added to this URL as well. */ - URLBuilder.prototype.appendPath = function (path) { + appendPath(path) { if (path) { - var currentPath = this.getPath(); + let currentPath = this.getPath(); if (currentPath) { if (!currentPath.endsWith("/")) { currentPath += "/"; @@ -57066,58 +52928,58 @@ var URLBuilder = /** @class */ (function () { } this.set(path, "PATH"); } - }; + } /** * Get the path that has been set in this URL. */ - URLBuilder.prototype.getPath = function () { + getPath() { return this._path; - }; + } /** * Set the query in this URL. */ - URLBuilder.prototype.setQuery = function (query) { + setQuery(query) { if (!query) { this._query = undefined; } else { this._query = URLQuery.parse(query); } - }; + } /** * Set a query parameter with the provided name and value in this URL's query. If the provided * query parameter value is undefined or empty, then the query parameter will be removed if it * existed. */ - URLBuilder.prototype.setQueryParameter = function (queryParameterName, queryParameterValue) { + setQueryParameter(queryParameterName, queryParameterValue) { if (queryParameterName) { if (!this._query) { this._query = new URLQuery(); } this._query.set(queryParameterName, queryParameterValue); } - }; + } /** * Get the value of the query parameter with the provided query parameter name. If no query * parameter exists with the provided name, then undefined will be returned. */ - URLBuilder.prototype.getQueryParameterValue = function (queryParameterName) { + getQueryParameterValue(queryParameterName) { return this._query ? this._query.get(queryParameterName) : undefined; - }; + } /** * Get the query in this URL. */ - URLBuilder.prototype.getQuery = function () { + getQuery() { return this._query ? this._query.toString() : undefined; - }; + } /** * Set the parts of this URL by parsing the provided text using the provided startState. */ - URLBuilder.prototype.set = function (text, startState) { - var tokenizer = new URLTokenizer(text, startState); + set(text, startState) { + const tokenizer = new URLTokenizer(text, startState); while (tokenizer.next()) { - var token = tokenizer.current(); - var tokenPath = void 0; + const token = tokenizer.current(); + let tokenPath; if (token) { switch (token.type) { case "SCHEME": @@ -57139,21 +53001,21 @@ var URLBuilder = /** @class */ (function () { this._query = URLQuery.parse(token.text); break; default: - throw new Error("Unrecognized URLTokenType: " + token.type); + throw new Error(`Unrecognized URLTokenType: ${token.type}`); } } } - }; - URLBuilder.prototype.toString = function () { - var result = ""; + } + toString() { + let result = ""; if (this._scheme) { - result += this._scheme + "://"; + result += `${this._scheme}://`; } if (this._host) { result += this._host; } if (this._port) { - result += ":" + this._port; + result += `:${this._port}`; } if (this._path) { if (!this._path.startsWith("/")) { @@ -57162,15 +53024,15 @@ var URLBuilder = /** @class */ (function () { result += this._path; } if (this._query && this._query.any()) { - result += "?" + this._query.toString(); + result += `?${this._query.toString()}`; } return result; - }; + } /** * If the provided searchValue is found in this URLBuilder, then replace it with the provided * replaceValue. */ - URLBuilder.prototype.replaceAll = function (searchValue, replaceValue) { + replaceAll(searchValue, replaceValue) { if (searchValue) { this.setScheme(replaceAll(this.getScheme(), searchValue, replaceValue)); this.setHost(replaceAll(this.getHost(), searchValue, replaceValue)); @@ -57178,42 +53040,40 @@ var URLBuilder = /** @class */ (function () { this.setPath(replaceAll(this.getPath(), searchValue, replaceValue)); this.setQuery(replaceAll(this.getQuery(), searchValue, replaceValue)); } - }; - URLBuilder.parse = function (text) { - var result = new URLBuilder(); + } + static parse(text) { + const result = new URLBuilder(); result.set(text, "SCHEME_OR_HOST"); return result; - }; - return URLBuilder; -}()); -var URLToken = /** @class */ (function () { - function URLToken(text, type) { + } +} +class URLToken { + constructor(text, type) { this.text = text; this.type = type; } - URLToken.scheme = function (text) { + static scheme(text) { return new URLToken(text, "SCHEME"); - }; - URLToken.host = function (text) { + } + static host(text) { return new URLToken(text, "HOST"); - }; - URLToken.port = function (text) { + } + static port(text) { return new URLToken(text, "PORT"); - }; - URLToken.path = function (text) { + } + static path(text) { return new URLToken(text, "PATH"); - }; - URLToken.query = function (text) { + } + static query(text) { return new URLToken(text, "QUERY"); - }; - return URLToken; -}()); + } +} /** * Get whether or not the provided character (single character string) is an alphanumeric (letter or * digit) character. */ function isAlphaNumericCharacter(character) { - var characterCode = character.charCodeAt(0); + const characterCode = character.charCodeAt(0); return ((48 /* '0' */ <= characterCode && characterCode <= 57) /* '9' */ || (65 /* 'A' */ <= characterCode && characterCode <= 90) /* 'Z' */ || (97 /* 'a' */ <= characterCode && characterCode <= 122) /* 'z' */); @@ -57221,8 +53081,8 @@ function isAlphaNumericCharacter(character) { /** * A class that tokenizes URL strings. */ -var URLTokenizer = /** @class */ (function () { - function URLTokenizer(_text, state) { +class URLTokenizer { + constructor(_text, state) { this._text = _text; this._textLength = _text ? _text.length : 0; this._currentState = state !== undefined && state !== null ? state : "SCHEME_OR_HOST"; @@ -57232,13 +53092,13 @@ var URLTokenizer = /** @class */ (function () { * Get the current URLToken this URLTokenizer is pointing at, or undefined if the URLTokenizer * hasn't started or has finished tokenizing. */ - URLTokenizer.prototype.current = function () { + current() { return this._currentToken; - }; + } /** * Advance to the next URLToken and return whether or not a URLToken was found. */ - URLTokenizer.prototype.next = function () { + next() { if (!hasCurrentCharacter(this)) { this._currentToken = undefined; } @@ -57263,18 +53123,17 @@ var URLTokenizer = /** @class */ (function () { nextQuery(this); break; default: - throw new Error("Unrecognized URLTokenizerState: " + this._currentState); + throw new Error(`Unrecognized URLTokenizerState: ${this._currentState}`); } } return !!this._currentToken; - }; - return URLTokenizer; -}()); + } +} /** * Read the remaining characters from this Tokenizer's character stream. */ function readRemaining(tokenizer) { - var result = ""; + let result = ""; if (tokenizer._currentIndex < tokenizer._textLength) { result = tokenizer._text.substring(tokenizer._currentIndex); tokenizer._currentIndex = tokenizer._textLength; @@ -57310,7 +53169,7 @@ function nextCharacter(tokenizer, step) { * Tokenizer's stream of characters. */ function peekCharacters(tokenizer, charactersToPeek) { - var endIndex = tokenizer._currentIndex + charactersToPeek; + let endIndex = tokenizer._currentIndex + charactersToPeek; if (tokenizer._textLength < endIndex) { endIndex = tokenizer._textLength; } @@ -57321,9 +53180,9 @@ function peekCharacters(tokenizer, charactersToPeek) { * is false when provided the current character. */ function readWhile(tokenizer, condition) { - var result = ""; + let result = ""; while (hasCurrentCharacter(tokenizer)) { - var currentCharacter = getCurrentCharacter(tokenizer); + const currentCharacter = getCurrentCharacter(tokenizer); if (!condition(currentCharacter)) { break; } @@ -57339,21 +53198,17 @@ function readWhile(tokenizer, condition) { * character stream is reached. */ function readWhileLetterOrDigit(tokenizer) { - return readWhile(tokenizer, function (character) { return isAlphaNumericCharacter(character); }); + return readWhile(tokenizer, (character) => isAlphaNumericCharacter(character)); } /** * Read characters from this Tokenizer until one of the provided terminating characters is read or * the end of the character stream is reached. */ -function readUntilCharacter(tokenizer) { - var terminatingCharacters = []; - for (var _i = 1; _i < arguments.length; _i++) { - terminatingCharacters[_i - 1] = arguments[_i]; - } - return readWhile(tokenizer, function (character) { return terminatingCharacters.indexOf(character) === -1; }); +function readUntilCharacter(tokenizer, ...terminatingCharacters) { + return readWhile(tokenizer, (character) => terminatingCharacters.indexOf(character) === -1); } function nextScheme(tokenizer) { - var scheme = readWhileLetterOrDigit(tokenizer); + const scheme = readWhileLetterOrDigit(tokenizer); tokenizer._currentToken = URLToken.scheme(scheme); if (!hasCurrentCharacter(tokenizer)) { tokenizer._currentState = "DONE"; @@ -57363,7 +53218,7 @@ function nextScheme(tokenizer) { } } function nextSchemeOrHost(tokenizer) { - var schemeOrHost = readUntilCharacter(tokenizer, ":", "/", "?"); + const schemeOrHost = readUntilCharacter(tokenizer, ":", "/", "?"); if (!hasCurrentCharacter(tokenizer)) { tokenizer._currentToken = URLToken.host(schemeOrHost); tokenizer._currentState = "DONE"; @@ -57392,7 +53247,7 @@ function nextHost(tokenizer) { if (peekCharacters(tokenizer, 3) === "://") { nextCharacter(tokenizer, 3); } - var host = readUntilCharacter(tokenizer, ":", "/", "?"); + const host = readUntilCharacter(tokenizer, ":", "/", "?"); tokenizer._currentToken = URLToken.host(host); if (!hasCurrentCharacter(tokenizer)) { tokenizer._currentState = "DONE"; @@ -57411,7 +53266,7 @@ function nextPort(tokenizer) { if (getCurrentCharacter(tokenizer) === ":") { nextCharacter(tokenizer); } - var port = readUntilCharacter(tokenizer, "/", "?"); + const port = readUntilCharacter(tokenizer, "/", "?"); tokenizer._currentToken = URLToken.port(port); if (!hasCurrentCharacter(tokenizer)) { tokenizer._currentState = "DONE"; @@ -57424,7 +53279,7 @@ function nextPort(tokenizer) { } } function nextPath(tokenizer) { - var path = readUntilCharacter(tokenizer, "?"); + const path = readUntilCharacter(tokenizer, "?"); tokenizer._currentToken = URLToken.path(path); if (!hasCurrentCharacter(tokenizer)) { tokenizer._currentState = "DONE"; @@ -57437,14 +53292,14 @@ function nextQuery(tokenizer) { if (getCurrentCharacter(tokenizer) === "?") { nextCharacter(tokenizer); } - var query = readRemaining(tokenizer); + const query = readRemaining(tokenizer); tokenizer._currentToken = URLToken.query(query); tokenizer._currentState = "DONE"; } // Copyright (c) Microsoft Corporation. -var RedactedString = "REDACTED"; -var defaultAllowedHeaderNames = [ +const RedactedString = "REDACTED"; +const defaultAllowedHeaderNames = [ "x-ms-client-request-id", "x-ms-return-client-request-id", "x-ms-useragent", @@ -57484,35 +53339,33 @@ var defaultAllowedHeaderNames = [ "Transfer-Encoding", "User-Agent" ]; -var defaultAllowedQueryParameters = ["api-version"]; -var Sanitizer = /** @class */ (function () { - function Sanitizer(_a) { - var _b = _a === void 0 ? {} : _a, _c = _b.allowedHeaderNames, allowedHeaderNames = _c === void 0 ? [] : _c, _d = _b.allowedQueryParameters, allowedQueryParameters = _d === void 0 ? [] : _d; +const defaultAllowedQueryParameters = ["api-version"]; +class Sanitizer { + constructor({ allowedHeaderNames = [], allowedQueryParameters = [] } = {}) { allowedHeaderNames = Array.isArray(allowedHeaderNames) ? defaultAllowedHeaderNames.concat(allowedHeaderNames) : defaultAllowedHeaderNames; allowedQueryParameters = Array.isArray(allowedQueryParameters) ? defaultAllowedQueryParameters.concat(allowedQueryParameters) : defaultAllowedQueryParameters; - this.allowedHeaderNames = new Set(allowedHeaderNames.map(function (n) { return n.toLowerCase(); })); - this.allowedQueryParameters = new Set(allowedQueryParameters.map(function (p) { return p.toLowerCase(); })); + this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); + this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); } - Sanitizer.prototype.sanitize = function (obj) { - var _this = this; - var seen = new Set(); - return JSON.stringify(obj, function (key, value) { + sanitize(obj) { + const seen = new Set(); + return JSON.stringify(obj, (key, value) => { // Ensure Errors include their interesting non-enumerable members if (value instanceof Error) { - return tslib.__assign(tslib.__assign({}, value), { name: value.name, message: value.message }); + return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); } if (key === "_headersMap") { - return _this.sanitizeHeaders(value); + return this.sanitizeHeaders(value); } else if (key === "url") { - return _this.sanitizeUrl(value); + return this.sanitizeUrl(value); } else if (key === "query") { - return _this.sanitizeQuery(value); + return this.sanitizeQuery(value); } else if (key === "body") { // Don't log the request body @@ -57535,20 +53388,19 @@ var Sanitizer = /** @class */ (function () { } return value; }, 2); - }; - Sanitizer.prototype.sanitizeHeaders = function (value) { - return this.sanitizeObject(value, this.allowedHeaderNames, function (v, k) { return v[k].value; }); - }; - Sanitizer.prototype.sanitizeQuery = function (value) { - return this.sanitizeObject(value, this.allowedQueryParameters, function (v, k) { return v[k]; }); - }; - Sanitizer.prototype.sanitizeObject = function (value, allowedKeys, accessor) { + } + sanitizeHeaders(value) { + return this.sanitizeObject(value, this.allowedHeaderNames, (v, k) => v[k].value); + } + sanitizeQuery(value) { + return this.sanitizeObject(value, this.allowedQueryParameters, (v, k) => v[k]); + } + sanitizeObject(value, allowedKeys, accessor) { if (typeof value !== "object" || value === null) { return value; } - var sanitized = {}; - for (var _i = 0, _a = Object.keys(value); _i < _a.length; _i++) { - var k = _a[_i]; + const sanitized = {}; + for (const k of Object.keys(value)) { if (allowedKeys.has(k.toLowerCase())) { sanitized[k] = accessor(value, k); } @@ -57557,267 +53409,233 @@ var Sanitizer = /** @class */ (function () { } } return sanitized; - }; - Sanitizer.prototype.sanitizeUrl = function (value) { + } + sanitizeUrl(value) { if (typeof value !== "string" || value === null) { return value; } - var urlBuilder = URLBuilder.parse(value); - var queryString = urlBuilder.getQuery(); + const urlBuilder = URLBuilder.parse(value); + const queryString = urlBuilder.getQuery(); if (!queryString) { return value; } - var query = URLQuery.parse(queryString); - for (var _i = 0, _a = query.keys(); _i < _a.length; _i++) { - var k = _a[_i]; + const query = URLQuery.parse(queryString); + for (const k of query.keys()) { if (!this.allowedQueryParameters.has(k.toLowerCase())) { query.set(k, RedactedString); } } urlBuilder.setQuery(query.toString()); return urlBuilder.toString(); - }; - return Sanitizer; -}()); + } +} // Copyright (c) Microsoft Corporation. -var errorSanitizer = new Sanitizer(); -var RestError = /** @class */ (function (_super) { - tslib.__extends(RestError, _super); - function RestError(message, code, statusCode, request, response) { - var _this = _super.call(this, message) || this; - _this.name = "RestError"; - _this.code = code; - _this.statusCode = statusCode; - _this.request = request; - _this.response = response; - Object.setPrototypeOf(_this, RestError.prototype); - return _this; +const errorSanitizer = new Sanitizer(); +class RestError extends Error { + constructor(message, code, statusCode, request, response) { + super(message); + this.name = "RestError"; + this.code = code; + this.statusCode = statusCode; + this.request = request; + this.response = response; + Object.setPrototypeOf(this, RestError.prototype); } /** * Logging method for util.inspect in Node */ - RestError.prototype[custom] = function () { - return "RestError: " + this.message + " \n " + errorSanitizer.sanitize(this); - }; - RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; - RestError.PARSE_ERROR = "PARSE_ERROR"; - 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); - function ReportTransform(progressCallback) { - var _this = _super.call(this) || this; - _this.progressCallback = progressCallback; - _this.loadedBytes = 0; - return _this; + [custom]() { + return `RestError: ${this.message} \n ${errorSanitizer.sanitize(this)}`; } - ReportTransform.prototype._transform = function (chunk, _encoding, callback) { +} +RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; +RestError.PARSE_ERROR = "PARSE_ERROR"; + +// Copyright (c) Microsoft Corporation. +const logger = logger$1.createClientLogger("core-http"); + +// Copyright (c) Microsoft Corporation. +class ReportTransform extends stream.Transform { + constructor(progressCallback) { + super(); + this.progressCallback = progressCallback; + this.loadedBytes = 0; + } + _transform(chunk, _encoding, callback) { this.push(chunk); this.loadedBytes += chunk.length; this.progressCallback({ loadedBytes: this.loadedBytes }); callback(undefined); - }; - return ReportTransform; -}(stream.Transform)); -var FetchHttpClient = /** @class */ (function () { - function FetchHttpClient() { } - FetchHttpClient.prototype.sendRequest = function (httpRequest) { +} +class FetchHttpClient { + async sendRequest(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) { - case 0: - if (!httpRequest && typeof httpRequest !== "object") { - throw new Error("'httpRequest' (WebResourceLike) cannot be null or undefined and must be of type object."); - } - abortController$1 = new abortController.AbortController(); - if (httpRequest.abortSignal) { - if (httpRequest.abortSignal.aborted) { - throw new abortController.AbortError("The operation was aborted."); - } - abortListener = function (event) { - if (event.type === "abort") { - abortController$1.abort(); - } - }; - httpRequest.abortSignal.addEventListener("abort", abortListener); - } - if (httpRequest.timeout) { - setTimeout(function () { - abortController$1.abort(); - }, httpRequest.timeout); - } - if (httpRequest.formData) { - formData = httpRequest.formData; - requestForm_1 = new FormData(); - appendFormValue = function (key, value) { - // value function probably returns a stream so we can provide a fresh stream on each retry - if (typeof value === "function") { - value = value(); - } - if (value && - Object.prototype.hasOwnProperty.call(value, "value") && - Object.prototype.hasOwnProperty.call(value, "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]; - formValue = formData[formKey]; - if (Array.isArray(formValue)) { - for (j = 0; j < formValue.length; j++) { - appendFormValue(formKey, formValue[j]); - } - } - else { - appendFormValue(formKey, formValue); - } - } - httpRequest.body = requestForm_1; - httpRequest.formData = undefined; - contentType = httpRequest.headers.get("Content-Type"); - if (contentType && contentType.indexOf("multipart/form-data") !== -1) { - if (typeof requestForm_1.getBoundary === "function") { - httpRequest.headers.set("Content-Type", "multipart/form-data; boundary=" + requestForm_1.getBoundary()); - } - else { - // browser will automatically apply a suitable content-type header - httpRequest.headers.remove("Content-Type"); - } - } - } - body = httpRequest.body - ? typeof httpRequest.body === "function" - ? httpRequest.body() - : httpRequest.body - : undefined; - if (httpRequest.onUploadProgress && httpRequest.body) { - onUploadProgress = httpRequest.onUploadProgress; - uploadReportStream = new ReportTransform(onUploadProgress); - if (isReadableStream(body)) { - body.pipe(uploadReportStream); - } - else { - uploadReportStream.end(body); - } - body = uploadReportStream; - } - 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; - case 2: - _e.trys.push([2, 8, 9, 10]); - return [4 /*yield*/, this.fetch(httpRequest.url, requestInit)]; - case 3: - response = _e.sent(); - headers = parseHeaders(response.headers); - streaming = ((_a = httpRequest.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(response.status)) || - httpRequest.streamResponseBody; - _d = { - headers: headers, - request: httpRequest, - status: response.status, - readableStreamBody: streaming - ? response.body - : undefined - }; - if (!!streaming) return [3 /*break*/, 5]; - return [4 /*yield*/, response.text()]; - case 4: - _c = _e.sent(); - return [3 /*break*/, 6]; - case 5: - _c = undefined; - _e.label = 6; - case 6: - operationResponse = (_d.bodyAsText = _c, - _d); - onDownloadProgress = httpRequest.onDownloadProgress; - if (onDownloadProgress) { - responseBody = response.body || undefined; - if (isReadableStream(responseBody)) { - downloadReportStream = new ReportTransform(onDownloadProgress); - responseBody.pipe(downloadReportStream); - operationResponse.readableStreamBody = downloadReportStream; - } - else { - length_1 = parseInt(headers.get("Content-Length")) || undefined; - if (length_1) { - // Calling callback for non-stream response for consistency with browser - onDownloadProgress({ loadedBytes: length_1 }); - } - } - } - return [4 /*yield*/, this.processRequest(operationResponse)]; - case 7: - _e.sent(); - return [2 /*return*/, operationResponse]; - case 8: - error_1 = _e.sent(); - fetchError = error_1; - if (fetchError.code === "ENOTFOUND") { - throw new RestError(fetchError.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest); - } - else if (fetchError.type === "aborted") { - throw new abortController.AbortError("The operation was aborted."); - } - throw fetchError; - 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); - }); - } - return [7 /*endfinally*/]; - case 10: return [2 /*return*/]; + if (!httpRequest && typeof httpRequest !== "object") { + throw new Error("'httpRequest' (WebResourceLike) cannot be null or undefined and must be of type object."); + } + const abortController$1 = new abortController.AbortController(); + let abortListener; + if (httpRequest.abortSignal) { + if (httpRequest.abortSignal.aborted) { + throw new abortController.AbortError("The operation was aborted."); + } + abortListener = (event) => { + if (event.type === "abort") { + abortController$1.abort(); } - }); - }); - }; - return FetchHttpClient; -}()); + }; + httpRequest.abortSignal.addEventListener("abort", abortListener); + } + if (httpRequest.timeout) { + setTimeout(() => { + abortController$1.abort(); + }, httpRequest.timeout); + } + if (httpRequest.formData) { + const formData = httpRequest.formData; + const requestForm = new FormData(); + const appendFormValue = (key, value) => { + // value function probably returns a stream so we can provide a fresh stream on each retry + if (typeof value === "function") { + value = value(); + } + if (value && + Object.prototype.hasOwnProperty.call(value, "value") && + Object.prototype.hasOwnProperty.call(value, "options")) { + requestForm.append(key, value.value, value.options); + } + else { + requestForm.append(key, value); + } + }; + for (const formKey of Object.keys(formData)) { + const formValue = formData[formKey]; + if (Array.isArray(formValue)) { + for (let j = 0; j < formValue.length; j++) { + appendFormValue(formKey, formValue[j]); + } + } + else { + appendFormValue(formKey, formValue); + } + } + httpRequest.body = requestForm; + httpRequest.formData = undefined; + const contentType = httpRequest.headers.get("Content-Type"); + if (contentType && contentType.indexOf("multipart/form-data") !== -1) { + if (typeof requestForm.getBoundary === "function") { + httpRequest.headers.set("Content-Type", `multipart/form-data; boundary=${requestForm.getBoundary()}`); + } + else { + // browser will automatically apply a suitable content-type header + httpRequest.headers.remove("Content-Type"); + } + } + } + let body = httpRequest.body + ? typeof httpRequest.body === "function" + ? httpRequest.body() + : httpRequest.body + : undefined; + if (httpRequest.onUploadProgress && httpRequest.body) { + const onUploadProgress = httpRequest.onUploadProgress; + const uploadReportStream = new ReportTransform(onUploadProgress); + if (isReadableStream(body)) { + body.pipe(uploadReportStream); + } + else { + uploadReportStream.end(body); + } + body = uploadReportStream; + } + const platformSpecificRequestInit = await this.prepareRequest(httpRequest); + const requestInit = Object.assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method, signal: abortController$1.signal, redirect: "manual" }, platformSpecificRequestInit); + let operationResponse; + try { + const response = await this.fetch(httpRequest.url, requestInit); + const headers = parseHeaders(response.headers); + const streaming = ((_a = httpRequest.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(response.status)) || + httpRequest.streamResponseBody; + operationResponse = { + headers: headers, + request: httpRequest, + status: response.status, + readableStreamBody: streaming + ? response.body + : undefined, + bodyAsText: !streaming ? await response.text() : undefined + }; + const onDownloadProgress = httpRequest.onDownloadProgress; + if (onDownloadProgress) { + const responseBody = response.body || undefined; + if (isReadableStream(responseBody)) { + const downloadReportStream = new ReportTransform(onDownloadProgress); + responseBody.pipe(downloadReportStream); + operationResponse.readableStreamBody = downloadReportStream; + } + else { + const length = parseInt(headers.get("Content-Length")) || undefined; + if (length) { + // Calling callback for non-stream response for consistency with browser + onDownloadProgress({ loadedBytes: length }); + } + } + } + await this.processRequest(operationResponse); + return operationResponse; + } + catch (error) { + const fetchError = error; + if (fetchError.code === "ENOTFOUND") { + throw new RestError(fetchError.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest); + } + else if (fetchError.type === "aborted") { + throw new abortController.AbortError("The operation was aborted."); + } + throw fetchError; + } + finally { + // clean up event listener + if (httpRequest.abortSignal && abortListener) { + let uploadStreamDone = Promise.resolve(); + if (isReadableStream(body)) { + uploadStreamDone = isStreamComplete(body); + } + let downloadStreamDone = Promise.resolve(); + if (isReadableStream(operationResponse === null || operationResponse === void 0 ? void 0 : operationResponse.readableStreamBody)) { + downloadStreamDone = isStreamComplete(operationResponse.readableStreamBody, abortController$1); + } + Promise.all([uploadStreamDone, downloadStreamDone]) + .then(() => { + var _a; + (_a = httpRequest.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener); + return; + }) + .catch((e) => { + logger.warning("Error when cleaning up abortListener on httpRequest", e); + }); + } + } + } +} 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 isStreamComplete(stream, aborter) { + return new Promise((resolve) => { + stream.once("close", () => { + aborter === null || aborter === void 0 ? void 0 : aborter.abort(); + resolve(); + }); + stream.once("end", resolve); + stream.once("error", resolve); }); } function parseHeaders(headers) { - var httpHeaders = new HttpHeaders(); - headers.forEach(function (value, key) { + const httpHeaders = new HttpHeaders(); + headers.forEach((value, key) => { httpHeaders.set(key, value); }); return httpHeaders; @@ -57825,14 +53643,14 @@ function parseHeaders(headers) { // Copyright (c) Microsoft Corporation. function createProxyAgent(requestUrl, proxySettings, headers) { - var host = URLBuilder.parse(proxySettings.host).getHost(); + const host = URLBuilder.parse(proxySettings.host).getHost(); if (!host) { throw new Error("Expecting a non-empty host in proxy settings."); } if (!isValidPort(proxySettings.port)) { throw new Error("Expecting a valid port number in the range of [0, 65535] in proxy settings."); } - var tunnelOptions = { + const tunnelOptions = { proxy: { host: host, port: proxySettings.port, @@ -57840,18 +53658,21 @@ function createProxyAgent(requestUrl, proxySettings, headers) { } }; if (proxySettings.username && proxySettings.password) { - tunnelOptions.proxy.proxyAuth = proxySettings.username + ":" + proxySettings.password; + tunnelOptions.proxy.proxyAuth = `${proxySettings.username}:${proxySettings.password}`; } - var isRequestHttps = isUrlHttps(requestUrl); - var isProxyHttps = isUrlHttps(proxySettings.host); - var proxyAgent = { + else if (proxySettings.username) { + tunnelOptions.proxy.proxyAuth = `${proxySettings.username}`; + } + const isRequestHttps = isUrlHttps(requestUrl); + const isProxyHttps = isUrlHttps(proxySettings.host); + const proxyAgent = { isHttps: isRequestHttps, agent: createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) }; return proxyAgent; } function isUrlHttps(url) { - var urlScheme = URLBuilder.parse(url).getScheme() || ""; + const urlScheme = URLBuilder.parse(url).getScheme() || ""; return urlScheme.toLowerCase() === "https"; } function createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) { @@ -57878,41 +53699,45 @@ function isValidPort(port) { function getCachedAgent(isHttps, agentCache) { return isHttps ? agentCache.httpsAgent : agentCache.httpAgent; } -var NodeFetchHttpClient = /** @class */ (function (_super) { - tslib.__extends(NodeFetchHttpClient, _super); - function NodeFetchHttpClient() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.proxyAgents = {}; - _this.keepAliveAgents = {}; - _this.cookieJar = new tough.CookieJar(undefined, { looseMode: true }); - return _this; +class NodeFetchHttpClient extends FetchHttpClient { + constructor() { + super(...arguments); + // a mapping of proxy settings string `${host}:${port}:${username}:${password}` to agent + this.proxyAgentMap = new Map(); + this.keepAliveAgents = {}; + this.cookieJar = new tough.CookieJar(undefined, { looseMode: true }); } - NodeFetchHttpClient.prototype.getOrCreateAgent = function (httpRequest) { - var isHttps = isUrlHttps(httpRequest.url); + getOrCreateAgent(httpRequest) { + var _a; + const isHttps = isUrlHttps(httpRequest.url); // At the moment, proxy settings and keepAlive are mutually // exclusive because the 'tunnel' library currently lacks the // ability to create a proxy with keepAlive turned on. if (httpRequest.proxySettings) { - var agent = getCachedAgent(isHttps, this.proxyAgents); + const { host, port, username, password } = httpRequest.proxySettings; + const key = `${host}:${port}:${username}:${password}`; + const proxyAgents = (_a = this.proxyAgentMap.get(key)) !== null && _a !== void 0 ? _a : {}; + let agent = getCachedAgent(isHttps, proxyAgents); if (agent) { return agent; } - var tunnel = createProxyAgent(httpRequest.url, httpRequest.proxySettings, httpRequest.headers); + const tunnel = createProxyAgent(httpRequest.url, httpRequest.proxySettings, httpRequest.headers); agent = tunnel.agent; if (tunnel.isHttps) { - this.proxyAgents.httpsAgent = tunnel.agent; + proxyAgents.httpsAgent = tunnel.agent; } else { - this.proxyAgents.httpAgent = tunnel.agent; + proxyAgents.httpAgent = tunnel.agent; } + this.proxyAgentMap.set(key, proxyAgents); return agent; } else if (httpRequest.keepAlive) { - var agent = getCachedAgent(isHttps, this.keepAliveAgents); + let agent = getCachedAgent(isHttps, this.keepAliveAgents); if (agent) { return agent; } - var agentOptions = { + const agentOptions = { keepAlive: httpRequest.keepAlive }; if (isHttps) { @@ -57926,77 +53751,49 @@ var NodeFetchHttpClient = /** @class */ (function (_super) { else { return isHttps ? https.globalAgent : http.globalAgent; } - }; + } // eslint-disable-next-line @azure/azure-sdk/ts-apisurface-standardized-verbs - NodeFetchHttpClient.prototype.fetch = function (input, init) { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - return [2 /*return*/, node_fetch(input, init)]; + async fetch(input, init) { + return node_fetch(input, init); + } + async prepareRequest(httpRequest) { + const requestInit = {}; + if (this.cookieJar && !httpRequest.headers.get("Cookie")) { + const cookieString = await new Promise((resolve, reject) => { + this.cookieJar.getCookieString(httpRequest.url, (err, cookie) => { + if (err) { + reject(err); + } + else { + resolve(cookie); + } + }); }); - }); - }; - NodeFetchHttpClient.prototype.prepareRequest = function (httpRequest) { - return tslib.__awaiter(this, void 0, void 0, function () { - var requestInit, cookieString; - var _this = this; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - requestInit = {}; - if (!(this.cookieJar && !httpRequest.headers.get("Cookie"))) return [3 /*break*/, 2]; - return [4 /*yield*/, new Promise(function (resolve, reject) { - _this.cookieJar.getCookieString(httpRequest.url, function (err, cookie) { - if (err) { - reject(err); - } - else { - resolve(cookie); - } - }); - })]; - case 1: - cookieString = _a.sent(); - httpRequest.headers.set("Cookie", cookieString); - _a.label = 2; - case 2: - // Set the http(s) agent - requestInit.agent = this.getOrCreateAgent(httpRequest); - requestInit.compress = httpRequest.decompressResponse; - return [2 /*return*/, requestInit]; - } - }); - }); - }; - NodeFetchHttpClient.prototype.processRequest = function (operationResponse) { - return tslib.__awaiter(this, void 0, void 0, function () { - var setCookieHeader_1; - var _this = this; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!this.cookieJar) return [3 /*break*/, 2]; - setCookieHeader_1 = operationResponse.headers.get("Set-Cookie"); - if (!(setCookieHeader_1 !== undefined)) return [3 /*break*/, 2]; - return [4 /*yield*/, new Promise(function (resolve, reject) { - _this.cookieJar.setCookie(setCookieHeader_1, operationResponse.request.url, { ignoreError: true }, function (err) { - if (err) { - reject(err); - } - else { - resolve(); - } - }); - })]; - case 1: - _a.sent(); - _a.label = 2; - case 2: return [2 /*return*/]; - } - }); - }); - }; - return NodeFetchHttpClient; -}(FetchHttpClient)); + httpRequest.headers.set("Cookie", cookieString); + } + // Set the http(s) agent + requestInit.agent = this.getOrCreateAgent(httpRequest); + requestInit.compress = httpRequest.decompressResponse; + return requestInit; + } + async processRequest(operationResponse) { + if (this.cookieJar) { + const setCookieHeader = operationResponse.headers.get("Set-Cookie"); + if (setCookieHeader !== undefined) { + await new Promise((resolve, reject) => { + this.cookieJar.setCookie(setCookieHeader, operationResponse.request.url, { ignoreError: true }, (err) => { + if (err) { + reject(err); + } + else { + resolve(); + } + }); + }); + } + } + } +} // Copyright (c) Microsoft Corporation. (function (HttpPipelineLogLevel) { @@ -58024,21 +53821,23 @@ var NodeFetchHttpClient = /** @class */ (function (_super) { * @param opts - OperationOptions object to convert to RequestOptionsBase */ function operationOptionsToRequestOptionsBase(opts) { - var requestOptions = opts.requestOptions, tracingOptions = opts.tracingOptions, additionalOptions = tslib.__rest(opts, ["requestOptions", "tracingOptions"]); - var result = additionalOptions; + var _a; + const { requestOptions, tracingOptions } = opts, additionalOptions = tslib.__rest(opts, ["requestOptions", "tracingOptions"]); + let result = additionalOptions; if (requestOptions) { - result = tslib.__assign(tslib.__assign({}, result), requestOptions); + result = Object.assign(Object.assign({}, result), requestOptions); } if (tracingOptions) { - result.spanOptions = tracingOptions.spanOptions; result.tracingContext = tracingOptions.tracingContext; + // By passing spanOptions if they exist at runtime, we're backwards compatible with @azure/core-tracing@preview.13 and earlier. + result.spanOptions = (_a = tracingOptions) === null || _a === void 0 ? void 0 : _a.spanOptions; } return result; } // Copyright (c) Microsoft Corporation. -var BaseRequestPolicy = /** @class */ (function () { - function BaseRequestPolicy(_nextPolicy, _options) { +class BaseRequestPolicy { + constructor(_nextPolicy, _options) { this._nextPolicy = _nextPolicy; this._options = _options; } @@ -58047,25 +53846,24 @@ var BaseRequestPolicy = /** @class */ (function () { * @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) { + shouldLog(logLevel) { return this._options.shouldLog(logLevel); - }; + } /** * 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. */ - BaseRequestPolicy.prototype.log = function (logLevel, message) { + log(logLevel, message) { this._options.log(logLevel, message); - }; - return BaseRequestPolicy; -}()); + } +} /** * Optional properties that can be used when creating a RequestPolicy. */ -var RequestPolicyOptions = /** @class */ (function () { - function RequestPolicyOptions(_logger) { +class RequestPolicyOptions { + constructor(_logger) { this._logger = _logger; } /** @@ -58073,104 +53871,89 @@ var RequestPolicyOptions = /** @class */ (function () { * @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) { + shouldLog(logLevel) { return (!!this._logger && logLevel !== exports.HttpPipelineLogLevel.OFF && logLevel <= this._logger.minimumLogLevel); - }; + } /** * 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. */ - RequestPolicyOptions.prototype.log = function (logLevel, message) { + log(logLevel, message) { if (this._logger && this.shouldLog(logLevel)) { this._logger.log(logLevel, message); } - }; - return RequestPolicyOptions; -}()); + } +} // Copyright (c) Microsoft Corporation. -function logPolicy(loggingOptions) { - if (loggingOptions === void 0) { loggingOptions = {}; } +function logPolicy(loggingOptions = {}) { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new LogPolicy(nextPolicy, options, loggingOptions); } }; } -var LogPolicy = /** @class */ (function (_super) { - tslib.__extends(LogPolicy, _super); - function LogPolicy(nextPolicy, options, _a) { - var _b = _a === void 0 ? {} : _a, _c = _b.logger, logger$1 = _c === void 0 ? logger.info : _c, _d = _b.allowedHeaderNames, allowedHeaderNames = _d === void 0 ? [] : _d, _e = _b.allowedQueryParameters, allowedQueryParameters = _e === void 0 ? [] : _e; - var _this = _super.call(this, nextPolicy, options) || this; - _this.logger = logger$1; - _this.sanitizer = new Sanitizer({ allowedHeaderNames: allowedHeaderNames, allowedQueryParameters: allowedQueryParameters }); - return _this; +class LogPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, { logger: logger$1 = logger.info, allowedHeaderNames = [], allowedQueryParameters = [] } = {}) { + super(nextPolicy, options); + this.logger = logger$1; + this.sanitizer = new Sanitizer({ allowedHeaderNames, allowedQueryParameters }); } - Object.defineProperty(LogPolicy.prototype, "allowedHeaderNames", { - /** - * Header names whose values will be logged when logging is enabled. Defaults to - * Date, traceparent, x-ms-client-request-id, and x-ms-request id. Any headers - * specified in this field will be added to that list. Any other values will - * be written to logs as "REDACTED". - * @deprecated Pass these into the constructor instead. - */ - get: function () { - return this.sanitizer.allowedHeaderNames; - }, - /** - * Header names whose values will be logged when logging is enabled. Defaults to - * Date, traceparent, x-ms-client-request-id, and x-ms-request id. Any headers - * specified in this field will be added to that list. Any other values will - * be written to logs as "REDACTED". - * @deprecated Pass these into the constructor instead. - */ - set: function (allowedHeaderNames) { - this.sanitizer.allowedHeaderNames = allowedHeaderNames; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(LogPolicy.prototype, "allowedQueryParameters", { - /** - * Query string names whose values will be logged when logging is enabled. By default no - * query string values are logged. - * @deprecated Pass these into the constructor instead. - */ - get: function () { - return this.sanitizer.allowedQueryParameters; - }, - /** - * Query string names whose values will be logged when logging is enabled. By default no - * query string values are logged. - * @deprecated Pass these into the constructor instead. - */ - set: function (allowedQueryParameters) { - this.sanitizer.allowedQueryParameters = allowedQueryParameters; - }, - enumerable: false, - configurable: true - }); - LogPolicy.prototype.sendRequest = function (request) { - var _this = this; + /** + * Header names whose values will be logged when logging is enabled. Defaults to + * Date, traceparent, x-ms-client-request-id, and x-ms-request id. Any headers + * specified in this field will be added to that list. Any other values will + * be written to logs as "REDACTED". + * @deprecated Pass these into the constructor instead. + */ + get allowedHeaderNames() { + return this.sanitizer.allowedHeaderNames; + } + /** + * Header names whose values will be logged when logging is enabled. Defaults to + * Date, traceparent, x-ms-client-request-id, and x-ms-request id. Any headers + * specified in this field will be added to that list. Any other values will + * be written to logs as "REDACTED". + * @deprecated Pass these into the constructor instead. + */ + set allowedHeaderNames(allowedHeaderNames) { + this.sanitizer.allowedHeaderNames = allowedHeaderNames; + } + /** + * Query string names whose values will be logged when logging is enabled. By default no + * query string values are logged. + * @deprecated Pass these into the constructor instead. + */ + get allowedQueryParameters() { + return this.sanitizer.allowedQueryParameters; + } + /** + * Query string names whose values will be logged when logging is enabled. By default no + * query string values are logged. + * @deprecated Pass these into the constructor instead. + */ + set allowedQueryParameters(allowedQueryParameters) { + this.sanitizer.allowedQueryParameters = allowedQueryParameters; + } + sendRequest(request) { if (!this.logger.enabled) return this._nextPolicy.sendRequest(request); this.logRequest(request); - return this._nextPolicy.sendRequest(request).then(function (response) { return _this.logResponse(response); }); - }; - LogPolicy.prototype.logRequest = function (request) { - this.logger("Request: " + this.sanitizer.sanitize(request)); - }; - LogPolicy.prototype.logResponse = function (response) { - this.logger("Response status code: " + response.status); - this.logger("Headers: " + this.sanitizer.sanitize(response.headers)); + return this._nextPolicy.sendRequest(request).then((response) => this.logResponse(response)); + } + logRequest(request) { + this.logger(`Request: ${this.sanitizer.sanitize(request)}`); + } + logResponse(response) { + this.logger(`Response status code: ${response.status}`); + this.logger(`Headers: ${this.sanitizer.sanitize(response.headers)}`); return response; - }; - return LogPolicy; -}(BaseRequestPolicy)); + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -58183,7 +53966,7 @@ function getPathStringFromParameter(parameter) { return getPathStringFromParameterPath(parameter.parameterPath, parameter.mapper); } function getPathStringFromParameterPath(parameterPath, mapper) { - var result; + let result; if (typeof parameterPath === "string") { result = parameterPath; } @@ -58202,9 +53985,9 @@ function getPathStringFromParameterPath(parameterPath, mapper) { * @internal */ function getStreamResponseStatusCodes(operationSpec) { - var result = new Set(); - for (var statusCode in operationSpec.responses) { - var operationResponse = operationSpec.responses[statusCode]; + const result = new Set(); + for (const statusCode in operationSpec.responses) { + const operationResponse = operationSpec.responses[statusCode]; if (operationResponse.bodyMapper && operationResponse.bodyMapper.type.name === MapperType.Stream) { result.add(Number(statusCode)); @@ -58218,7 +54001,7 @@ function getStreamResponseStatusCodes(operationSpec) { // by the xm2js library is mutable. See https://github.com/Leonidas-from-XIV/node-xml2js/issues/536 // By creating a new copy of the settings each time we instantiate the parser, // we are safeguarding against the possibility of the default settings being mutated elsewhere unintentionally. -var xml2jsDefaultOptionsV2 = { +const xml2jsDefaultOptionsV2 = { explicitCharkey: false, trim: false, normalize: false, @@ -58259,10 +54042,10 @@ var xml2jsDefaultOptionsV2 = { cdata: false }; // The xml2js settings for general XML parsing operations. -var xml2jsParserSettings = Object.assign({}, xml2jsDefaultOptionsV2); +const xml2jsParserSettings = Object.assign({}, xml2jsDefaultOptionsV2); xml2jsParserSettings.explicitArray = false; // The xml2js settings for general XML building operations. -var xml2jsBuilderSettings = Object.assign({}, xml2jsDefaultOptionsV2); +const xml2jsBuilderSettings = Object.assign({}, xml2jsDefaultOptionsV2); xml2jsBuilderSettings.explicitArray = false; xml2jsBuilderSettings.renderOpts = { pretty: false @@ -58272,12 +54055,11 @@ xml2jsBuilderSettings.renderOpts = { * @param obj - JSON object to be converted into XML string * @param opts - Options that govern the parsing of given JSON object */ -function stringifyXML(obj, opts) { +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; - var builder = new xml2js.Builder(xml2jsBuilderSettings); + const builder = new xml2js.Builder(xml2jsBuilderSettings); return builder.buildObject(obj); } /** @@ -58285,18 +54067,17 @@ function stringifyXML(obj, opts) { * @param str - String containing the XML content to be parsed into JSON * @param opts - Options that govern the parsing of given xml string */ -function parseXML(str, opts) { +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; - var xmlParser = new xml2js.Parser(xml2jsParserSettings); - return new Promise(function (resolve, reject) { + const xmlParser = new xml2js.Parser(xml2jsParserSettings); + return new Promise((resolve, reject) => { if (!str) { reject(new Error("Document is empty")); } else { - xmlParser.parseString(str, function (err, res) { + xmlParser.parseString(str, (err, res) => { if (err) { reject(err); } @@ -58315,14 +54096,14 @@ function parseXML(str, opts) { */ function deserializationPolicy(deserializationContentTypes, parsingOptions) { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new DeserializationPolicy(nextPolicy, options, deserializationContentTypes, parsingOptions); } }; } -var defaultJsonContentTypes = ["application/json", "text/json"]; -var defaultXmlContentTypes = ["application/xml", "application/atom+xml"]; -var DefaultDeserializationOptions = { +const defaultJsonContentTypes = ["application/json", "text/json"]; +const defaultXmlContentTypes = ["application/xml", "application/atom+xml"]; +const DefaultDeserializationOptions = { expectedContentTypes: { json: defaultJsonContentTypes, xml: defaultXmlContentTypes @@ -58332,39 +54113,28 @@ var DefaultDeserializationOptions = { * A RequestPolicy that will deserialize HTTP response bodies and headers as they pass through the * HTTP pipeline. */ -var DeserializationPolicy = /** @class */ (function (_super) { - tslib.__extends(DeserializationPolicy, _super); - function DeserializationPolicy(nextPolicy, requestPolicyOptions, deserializationContentTypes, parsingOptions) { - if (parsingOptions === void 0) { parsingOptions = {}; } +class DeserializationPolicy extends BaseRequestPolicy { + constructor(nextPolicy, requestPolicyOptions, deserializationContentTypes, parsingOptions = {}) { var _a; - var _this = _super.call(this, nextPolicy, requestPolicyOptions) || this; - _this.jsonContentTypes = + super(nextPolicy, requestPolicyOptions); + this.jsonContentTypes = (deserializationContentTypes && deserializationContentTypes.json) || defaultJsonContentTypes; - _this.xmlContentTypes = + this.xmlContentTypes = (deserializationContentTypes && deserializationContentTypes.xml) || defaultXmlContentTypes; - _this.xmlCharKey = (_a = parsingOptions.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; - return _this; + this.xmlCharKey = (_a = parsingOptions.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; } - 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 DeserializationPolicy; -}(BaseRequestPolicy)); + async sendRequest(request) { + return this._nextPolicy.sendRequest(request).then((response) => deserializeResponseBody(this.jsonContentTypes, this.xmlContentTypes, response, { + xmlCharKey: this.xmlCharKey + })); + } +} function getOperationResponse(parsedResponse) { - var result; - var request = parsedResponse.request; - var operationSpec = request.operationSpec; + let result; + const request = parsedResponse.request; + const operationSpec = request.operationSpec; if (operationSpec) { - var operationResponseGetter = request.operationResponseGetter; + const operationResponseGetter = request.operationResponseGetter; if (!operationResponseGetter) { result = operationSpec.responses[parsedResponse.status]; } @@ -58375,8 +54145,8 @@ function getOperationResponse(parsedResponse) { return result; } function shouldDeserializeResponse(parsedResponse) { - var shouldDeserialize = parsedResponse.request.shouldDeserialize; - var result; + const shouldDeserialize = parsedResponse.request.shouldDeserialize; + let result; if (shouldDeserialize === undefined) { result = true; } @@ -58388,24 +54158,23 @@ function shouldDeserializeResponse(parsedResponse) { } return result; } -function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options) { +function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options = {}) { var _a, _b, _c; - if (options === void 0) { options = {}; } - var updatedOptions = { + const 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) { + return parse(jsonContentTypes, xmlContentTypes, response, updatedOptions).then((parsedResponse) => { if (!shouldDeserializeResponse(parsedResponse)) { return parsedResponse; } - var operationSpec = parsedResponse.request.operationSpec; + const operationSpec = parsedResponse.request.operationSpec; if (!operationSpec || !operationSpec.responses) { return parsedResponse; } - var responseSpec = getOperationResponse(parsedResponse); - var _a = handleErrorResponse(parsedResponse, operationSpec, responseSpec), error = _a.error, shouldReturnResponse = _a.shouldReturnResponse; + const responseSpec = getOperationResponse(parsedResponse); + const { error, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec); if (error) { throw error; } @@ -58416,7 +54185,7 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, op // use it to deserialize the response. if (responseSpec) { if (responseSpec.bodyMapper) { - var valueToDeserialize = parsedResponse.parsedBody; + let valueToDeserialize = parsedResponse.parsedBody; if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperType.Sequence) { valueToDeserialize = typeof valueToDeserialize === "object" @@ -58427,7 +54196,7 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, op parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options); } catch (innerError) { - var restError = new RestError("Error " + innerError + " occurred in deserializing the responseBody - " + parsedResponse.bodyAsText, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); + const restError = new RestError(`Error ${innerError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); throw restError; } } @@ -58443,14 +54212,14 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, op }); } function isOperationSpecEmpty(operationSpec) { - var expectedStatusCodes = Object.keys(operationSpec.responses); + const 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) + const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300; + const isExpectedStatusCode = isOperationSpecEmpty(operationSpec) ? isSuccessByStatus : !!responseSpec; if (isExpectedStatusCode) { @@ -58463,35 +54232,35 @@ function handleErrorResponse(parsedResponse, operationSpec, responseSpec) { 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)) || + const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default; + const 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 + const initialErrorMessage = streaming + ? `Unexpected status code: ${parsedResponse.status}` : parsedResponse.bodyAsText; - var error = new RestError(initialErrorMessage, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); + const 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; + const defaultBodyMapper = errorResponseSpec.bodyMapper; + const 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; + const parsedBody = parsedResponse.parsedBody; + let parsedError; if (defaultBodyMapper) { - var valueToDeserialize = parsedBody; + let 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; + const internalError = parsedBody.error || parsedError || parsedBody; error.code = internalError.code; if (internalError.message) { error.message = internalError.message; @@ -58506,36 +54275,36 @@ function handleErrorResponse(parsedResponse, operationSpec, responseSpec) { } } catch (defaultError) { - error.message = "Error \"" + defaultError.message + "\" occurred in deserializing the responseBody - \"" + parsedResponse.bodyAsText + "\" for the default response."; + error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`; } - return { error: error, shouldReturnResponse: false }; + return { error, shouldReturnResponse: false }; } function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts) { var _a; - 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); + const errorHandler = (err) => { + const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`; + const errCode = err.code || RestError.PARSE_ERROR; + const 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)) || + const streaming = ((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) || operationResponse.request.streamResponseBody; if (!streaming && operationResponse.bodyAsText) { - var text_1 = operationResponse.bodyAsText; - var contentType = operationResponse.headers.get("Content-Type") || ""; - var contentComponents = !contentType + const text = operationResponse.bodyAsText; + const contentType = operationResponse.headers.get("Content-Type") || ""; + const contentComponents = !contentType ? [] - : contentType.split(";").map(function (component) { return component.toLowerCase(); }); + : contentType.split(";").map((component) => component.toLowerCase()); if (contentComponents.length === 0 || - contentComponents.some(function (component) { return jsonContentTypes.indexOf(component) !== -1; })) { - return new Promise(function (resolve) { - operationResponse.parsedBody = JSON.parse(text_1); + contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) { + return new Promise((resolve) => { + operationResponse.parsedBody = JSON.parse(text); resolve(operationResponse); }).catch(errorHandler); } - else if (contentComponents.some(function (component) { return xmlContentTypes.indexOf(component) !== -1; })) { - return parseXML(text_1, opts) - .then(function (body) { + else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) { + return parseXML(text, opts) + .then((body) => { operationResponse.parsedBody = body; return operationResponse; }) @@ -58547,11 +54316,11 @@ function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts) { // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -var DEFAULT_CLIENT_RETRY_COUNT = 3; +const DEFAULT_CLIENT_RETRY_COUNT = 3; // intervals are in ms -var DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30; -var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90; -var DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3; +const DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30; +const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90; +const DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3; function isNumber(n) { return typeof n === "number"; } @@ -58578,8 +54347,7 @@ function shouldRetry(retryLimit, predicate, retryData, response, error) { * @param retryData - The retry data. * @param err - The operation"s error, if any. */ -function updateRetryData(retryOptions, retryData, err) { - if (retryData === void 0) { retryData = { retryCount: 0, retryInterval: 0 }; } +function updateRetryData(retryOptions, retryData = { retryCount: 0, retryInterval: 0 }, err) { if (err) { if (retryData.error) { err.innerError = retryData.error; @@ -58589,18 +54357,72 @@ function updateRetryData(retryOptions, retryData, err) { // Adjust retry count retryData.retryCount++; // Adjust retry interval - var incrementDelta = Math.pow(2, retryData.retryCount - 1) - 1; - var boundedRandDelta = retryOptions.retryInterval * 0.8 + + let incrementDelta = Math.pow(2, retryData.retryCount - 1) - 1; + const boundedRandDelta = retryOptions.retryInterval * 0.8 + Math.floor(Math.random() * (retryOptions.retryInterval * 0.4)); incrementDelta *= boundedRandDelta; retryData.retryInterval = Math.min(retryOptions.minRetryInterval + incrementDelta, retryOptions.maxRetryInterval); return retryData; } +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Helper TypeGuard that checks if the value is not null or undefined. + * @param thing - Anything + * @internal + */ +function isDefined(thing) { + return typeof thing !== "undefined" && thing !== null; +} + +// Copyright (c) Microsoft Corporation. +const StandardAbortMessage = "The operation was aborted."; +/** + * A wrapper for setTimeout that resolves a promise after delayInMs milliseconds. + * @param delayInMs - The number of milliseconds to be delayed. + * @param value - The value to be resolved with after a timeout of t milliseconds. + * @param options - The options for delay - currently abort options + * @param abortSignal - The abortSignal associated with containing operation. + * @param abortErrorMsg - The abort error message associated with containing operation. + * @returns - Resolved promise + */ +function delay(delayInMs, value, options) { + return new Promise((resolve, reject) => { + let timer = undefined; + let onAborted = undefined; + const rejectOnAbort = () => { + return reject(new abortController.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage)); + }; + const removeListeners = () => { + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) { + options.abortSignal.removeEventListener("abort", onAborted); + } + }; + onAborted = () => { + if (isDefined(timer)) { + clearTimeout(timer); + } + removeListeners(); + return rejectOnAbort(); + }; + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) { + return rejectOnAbort(); + } + timer = setTimeout(() => { + removeListeners(); + resolve(value); + }, delayInMs); + if (options === null || options === void 0 ? void 0 : options.abortSignal) { + options.abortSignal.addEventListener("abort", onAborted); + } + }); +} + // Copyright (c) Microsoft Corporation. function exponentialRetryPolicy(retryCount, retryInterval, maxRetryInterval) { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, maxRetryInterval); } }; @@ -58608,7 +54430,7 @@ function exponentialRetryPolicy(retryCount, retryInterval, maxRetryInterval) { (function (RetryMode) { RetryMode[RetryMode["Exponential"] = 0] = "Exponential"; })(exports.RetryMode || (exports.RetryMode = {})); -var DefaultRetryOptions = { +const DefaultRetryOptions = { maxRetries: DEFAULT_CLIENT_RETRY_COUNT, retryDelayInMs: DEFAULT_CLIENT_RETRY_INTERVAL, maxRetryDelayInMs: DEFAULT_CLIENT_MAX_RETRY_INTERVAL @@ -58616,8 +54438,7 @@ var DefaultRetryOptions = { /** * Instantiates a new "ExponentialRetryPolicyFilter" instance. */ -var ExponentialRetryPolicy = /** @class */ (function (_super) { - tslib.__extends(ExponentialRetryPolicy, _super); +class ExponentialRetryPolicy extends BaseRequestPolicy { /** * @param nextPolicy - The next RequestPolicy in the pipeline chain. * @param options - The options for this RequestPolicy. @@ -58626,217 +54447,188 @@ var ExponentialRetryPolicy = /** @class */ (function (_super) { * @param minRetryInterval - The minimum retry interval, in milliseconds. * @param maxRetryInterval - The maximum retry interval, in milliseconds. */ - function ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, maxRetryInterval) { - var _this = _super.call(this, nextPolicy, options) || this; - _this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT; - _this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL; - _this.maxRetryInterval = isNumber(maxRetryInterval) + constructor(nextPolicy, options, retryCount, retryInterval, maxRetryInterval) { + super(nextPolicy, options); + this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT; + this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL; + this.maxRetryInterval = isNumber(maxRetryInterval) ? maxRetryInterval : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; - return _this; } - ExponentialRetryPolicy.prototype.sendRequest = function (request) { - var _this = this; + sendRequest(request) { return this._nextPolicy .sendRequest(request.clone()) - .then(function (response) { return retry(_this, request, response); }) - .catch(function (error) { return retry(_this, request, error.response, undefined, error); }); - }; - return ExponentialRetryPolicy; -}(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; - if (statusCode === undefined || - (statusCode < 500 && statusCode !== 408) || - statusCode === 501 || - statusCode === 505) { - return false; - } - return true; + .then((response) => retry(this, request, response)) + .catch((error) => retry(this, request, error.response, undefined, error)); + } +} +async function retry(policy, request, response, retryData, requestError) { + function shouldPolicyRetry(responseParam) { + const statusCode = responseParam === null || responseParam === void 0 ? void 0 : responseParam.status; + if (statusCode === 503 && (response === null || response === void 0 ? void 0 : response.headers.get(Constants.HeaderConstants.RETRY_AFTER))) { + return false; } - var isAborted, res, err_1, err; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - retryData = updateRetryData({ - retryInterval: policy.retryInterval, - minRetryInterval: 0, - maxRetryInterval: policy.maxRetryInterval - }, retryData, requestError); - isAborted = request.abortSignal && request.abortSignal.aborted; - if (!(!isAborted && shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, response))) return [3 /*break*/, 6]; - logger.info("Retrying request in " + retryData.retryInterval); - _a.label = 1; - case 1: - _a.trys.push([1, 4, , 5]); - return [4 /*yield*/, delay(retryData.retryInterval)]; - case 2: - _a.sent(); - return [4 /*yield*/, policy._nextPolicy.sendRequest(request.clone())]; - case 3: - res = _a.sent(); - return [2 /*return*/, retry(policy, request, res, retryData)]; - case 4: - err_1 = _a.sent(); - return [2 /*return*/, retry(policy, request, response, retryData, err_1)]; - case 5: return [3 /*break*/, 7]; - case 6: - if (isAborted || requestError || !response) { - err = retryData.error || - new RestError("Failed to send the request.", RestError.REQUEST_SEND_ERROR, response && response.status, response && response.request, response); - throw err; - } - else { - return [2 /*return*/, response]; - } - case 7: return [2 /*return*/]; - } - }); - }); + if (statusCode === undefined || + (statusCode < 500 && statusCode !== 408) || + statusCode === 501 || + statusCode === 505) { + return false; + } + return true; + } + retryData = updateRetryData({ + retryInterval: policy.retryInterval, + minRetryInterval: 0, + maxRetryInterval: policy.maxRetryInterval + }, retryData, requestError); + const isAborted = request.abortSignal && request.abortSignal.aborted; + if (!isAborted && shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, response)) { + logger.info(`Retrying request in ${retryData.retryInterval}`); + try { + await delay(retryData.retryInterval); + const res = await policy._nextPolicy.sendRequest(request.clone()); + return retry(policy, request, res, retryData); + } + catch (err) { + return retry(policy, request, response, retryData, err); + } + } + else if (isAborted || requestError || !response) { + // If the operation failed in the end, return all errors instead of just the last one + const err = retryData.error || + new RestError("Failed to send the request.", RestError.REQUEST_SEND_ERROR, response && response.status, response && response.request, response); + throw err; + } + else { + return response; + } } // Copyright (c) Microsoft Corporation. -function generateClientRequestIdPolicy(requestIdHeaderName) { - if (requestIdHeaderName === void 0) { requestIdHeaderName = "x-ms-client-request-id"; } +function generateClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new GenerateClientRequestIdPolicy(nextPolicy, options, requestIdHeaderName); } }; } -var GenerateClientRequestIdPolicy = /** @class */ (function (_super) { - tslib.__extends(GenerateClientRequestIdPolicy, _super); - function GenerateClientRequestIdPolicy(nextPolicy, options, _requestIdHeaderName) { - var _this = _super.call(this, nextPolicy, options) || this; - _this._requestIdHeaderName = _requestIdHeaderName; - return _this; +class GenerateClientRequestIdPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, _requestIdHeaderName) { + super(nextPolicy, options); + this._requestIdHeaderName = _requestIdHeaderName; } - GenerateClientRequestIdPolicy.prototype.sendRequest = function (request) { + sendRequest(request) { if (!request.headers.contains(this._requestIdHeaderName)) { request.headers.set(this._requestIdHeaderName, request.requestId); } return this._nextPolicy.sendRequest(request); - }; - return GenerateClientRequestIdPolicy; -}(BaseRequestPolicy)); + } +} // Copyright (c) Microsoft Corporation. function getDefaultUserAgentKey() { return Constants.HeaderConstants.USER_AGENT; } function getPlatformSpecificData() { - var runtimeInfo = { + const runtimeInfo = { key: "Node", value: process.version }; - var osInfo = { + const osInfo = { key: "OS", - value: "(" + os.arch() + "-" + os.type() + "-" + os.release() + ")" + value: `(${os.arch()}-${os.type()}-${os.release()})` }; return [runtimeInfo, osInfo]; } // Copyright (c) Microsoft Corporation. function getRuntimeInfo() { - var msRestRuntime = { + const msRestRuntime = { key: "core-http", value: Constants.coreHttpVersion }; return [msRestRuntime]; } -function getUserAgentString(telemetryInfo, keySeparator, valueSeparator) { - if (keySeparator === void 0) { keySeparator = " "; } - if (valueSeparator === void 0) { valueSeparator = "/"; } +function getUserAgentString(telemetryInfo, keySeparator = " ", valueSeparator = "/") { return telemetryInfo - .map(function (info) { - var value = info.value ? "" + valueSeparator + info.value : ""; - return "" + info.key + value; + .map((info) => { + const value = info.value ? `${valueSeparator}${info.value}` : ""; + return `${info.key}${value}`; }) .join(keySeparator); } -var getDefaultUserAgentHeaderName = getDefaultUserAgentKey; +const getDefaultUserAgentHeaderName = getDefaultUserAgentKey; function getDefaultUserAgentValue() { - var runtimeInfo = getRuntimeInfo(); - var platformSpecificData = getPlatformSpecificData(); - var userAgent = getUserAgentString(runtimeInfo.concat(platformSpecificData)); + const runtimeInfo = getRuntimeInfo(); + const platformSpecificData = getPlatformSpecificData(); + const userAgent = getUserAgentString(runtimeInfo.concat(platformSpecificData)); return userAgent; } function userAgentPolicy(userAgentData) { - var key = !userAgentData || userAgentData.key === undefined || userAgentData.key === null + const key = !userAgentData || userAgentData.key === undefined || userAgentData.key === null ? getDefaultUserAgentKey() : userAgentData.key; - var value = !userAgentData || userAgentData.value === undefined || userAgentData.value === null + const value = !userAgentData || userAgentData.value === undefined || userAgentData.value === null ? getDefaultUserAgentValue() : userAgentData.value; return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new UserAgentPolicy(nextPolicy, options, key, value); } }; } -var UserAgentPolicy = /** @class */ (function (_super) { - tslib.__extends(UserAgentPolicy, _super); - function UserAgentPolicy(_nextPolicy, _options, headerKey, headerValue) { - var _this = _super.call(this, _nextPolicy, _options) || this; - _this._nextPolicy = _nextPolicy; - _this._options = _options; - _this.headerKey = headerKey; - _this.headerValue = headerValue; - return _this; +class UserAgentPolicy extends BaseRequestPolicy { + constructor(_nextPolicy, _options, headerKey, headerValue) { + super(_nextPolicy, _options); + this._nextPolicy = _nextPolicy; + this._options = _options; + this.headerKey = headerKey; + this.headerValue = headerValue; } - UserAgentPolicy.prototype.sendRequest = function (request) { + sendRequest(request) { this.addUserAgentHeader(request); return this._nextPolicy.sendRequest(request); - }; - UserAgentPolicy.prototype.addUserAgentHeader = function (request) { + } + addUserAgentHeader(request) { if (!request.headers) { request.headers = new HttpHeaders(); } if (!request.headers.get(this.headerKey) && this.headerValue) { request.headers.set(this.headerKey, this.headerValue); } - }; - return UserAgentPolicy; -}(BaseRequestPolicy)); + } +} // Copyright (c) Microsoft Corporation. /** * Methods that are allowed to follow redirects 301 and 302 */ -var allowedRedirect = ["GET", "HEAD"]; -var DefaultRedirectOptions = { +const allowedRedirect = ["GET", "HEAD"]; +const DefaultRedirectOptions = { handleRedirects: true, maxRetries: 20 }; -function redirectPolicy(maximumRetries) { - if (maximumRetries === void 0) { maximumRetries = 20; } +function redirectPolicy(maximumRetries = 20) { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new RedirectPolicy(nextPolicy, options, maximumRetries); } }; } -var RedirectPolicy = /** @class */ (function (_super) { - tslib.__extends(RedirectPolicy, _super); - function RedirectPolicy(nextPolicy, options, maxRetries) { - if (maxRetries === void 0) { maxRetries = 20; } - var _this = _super.call(this, nextPolicy, options) || this; - _this.maxRetries = maxRetries; - return _this; +class RedirectPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, maxRetries = 20) { + super(nextPolicy, options); + this.maxRetries = maxRetries; } - RedirectPolicy.prototype.sendRequest = function (request) { - var _this = this; + sendRequest(request) { return this._nextPolicy .sendRequest(request) - .then(function (response) { return handleRedirect(_this, response, 0); }); - }; - return RedirectPolicy; -}(BaseRequestPolicy)); + .then((response) => handleRedirect(this, response, 0)); + } +} function handleRedirect(policy, response, currentRetries) { - var request = response.request, status = response.status; - var locationHeader = response.headers.get("location"); + const { request, status } = response; + const locationHeader = response.headers.get("location"); if (locationHeader && (status === 300 || (status === 301 && allowedRedirect.includes(request.method)) || @@ -58844,7 +54636,7 @@ function handleRedirect(policy, response, currentRetries) { (status === 303 && request.method === "POST") || status === 307) && (!policy.maxRetries || currentRetries < policy.maxRetries)) { - var builder = URLBuilder.parse(request.url); + const builder = URLBuilder.parse(request.url); builder.setPath(locationHeader); request.url = builder.toString(); // POST request with Status code 303 should be converted into a @@ -58855,47 +54647,41 @@ function handleRedirect(policy, response, currentRetries) { } return policy._nextPolicy .sendRequest(request) - .then(function (res) { return handleRedirect(policy, res, currentRetries + 1); }); + .then((res) => handleRedirect(policy, res, currentRetries + 1)); } return Promise.resolve(response); } // Copyright (c) Microsoft Corporation. -function rpRegistrationPolicy(retryTimeout) { - if (retryTimeout === void 0) { retryTimeout = 30; } +function rpRegistrationPolicy(retryTimeout = 30) { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new RPRegistrationPolicy(nextPolicy, options, retryTimeout); } }; } -var RPRegistrationPolicy = /** @class */ (function (_super) { - tslib.__extends(RPRegistrationPolicy, _super); - function RPRegistrationPolicy(nextPolicy, options, _retryTimeout) { - if (_retryTimeout === void 0) { _retryTimeout = 30; } - var _this = _super.call(this, nextPolicy, options) || this; - _this._retryTimeout = _retryTimeout; - return _this; +class RPRegistrationPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, _retryTimeout = 30) { + super(nextPolicy, options); + this._retryTimeout = _retryTimeout; } - RPRegistrationPolicy.prototype.sendRequest = function (request) { - var _this = this; + sendRequest(request) { return this._nextPolicy .sendRequest(request.clone()) - .then(function (response) { return registerIfNeeded(_this, request, response); }); - }; - return RPRegistrationPolicy; -}(BaseRequestPolicy)); + .then((response) => registerIfNeeded(this, request, response)); + } +} function registerIfNeeded(policy, request, response) { if (response.status === 409) { - var rpName = checkRPNotRegisteredError(response.bodyAsText); + const rpName = checkRPNotRegisteredError(response.bodyAsText); if (rpName) { - var urlPrefix = extractSubscriptionUrl(request.url); + const urlPrefix = extractSubscriptionUrl(request.url); return (registerRP(policy, urlPrefix, rpName, request) // Autoregistration of ${provider} failed for some reason. We will not return this error // instead will return the initial response with 409 status code back to the user. // do nothing here as we are returning the original response at the end of this method. - .catch(function () { return false; }) - .then(function (registrationStatus) { + .catch(() => false) + .then((registrationStatus) => { if (registrationStatus) { // Retry the original request. We have to change the x-ms-client-request-id // otherwise Azure endpoint will return the initial 409 (cached) response. @@ -58914,9 +54700,8 @@ function registerIfNeeded(policy, request, response) { * @param reuseUrlToo - Should the url from the original request be reused as well. Default false. * @returns A new request object with desired headers. */ -function getRequestEssentials(originalRequest, reuseUrlToo) { - if (reuseUrlToo === void 0) { reuseUrlToo = false; } - var reqOptions = originalRequest.clone(); +function getRequestEssentials(originalRequest, reuseUrlToo = false) { + const reqOptions = originalRequest.clone(); if (reuseUrlToo) { reqOptions.url = originalRequest.url; } @@ -58934,7 +54719,7 @@ function getRequestEssentials(originalRequest, reuseUrlToo) { * @returns The name of the RP if condition is satisfied else undefined. */ function checkRPNotRegisteredError(body) { - var result, responseBody; + let result, responseBody; if (body) { try { responseBody = JSON.parse(body); @@ -58947,7 +54732,7 @@ function checkRPNotRegisteredError(body) { responseBody.error.message && responseBody.error.code && responseBody.error.code === "MissingSubscriptionRegistration") { - var matchRes = responseBody.error.message.match(/.*'(.*)'/i); + const matchRes = responseBody.error.message.match(/.*'(.*)'/i); if (matchRes) { result = matchRes.pop(); } @@ -58962,13 +54747,13 @@ function checkRPNotRegisteredError(body) { * @returns The url prefix as explained above. */ function extractSubscriptionUrl(url) { - var result; - var matchRes = url.match(/.*\/subscriptions\/[a-f0-9-]+\//gi); + let result; + const matchRes = url.match(/.*\/subscriptions\/[a-f0-9-]+\//gi); if (matchRes && matchRes[0]) { result = matchRes[0]; } else { - throw new Error("Unable to extract subscriptionId from the given url - " + url + "."); + throw new Error(`Unable to extract subscriptionId from the given url - ${url}.`); } return result; } @@ -58979,20 +54764,18 @@ function extractSubscriptionUrl(url) { * @param provider - The provider name to be registered. * @param 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 */ -function registerRP(policy, urlPrefix, provider, originalRequest) { - var postUrl = urlPrefix + "providers/" + provider + "/register?api-version=2016-02-01"; - var getUrl = urlPrefix + "providers/" + provider + "?api-version=2016-02-01"; - var reqOptions = getRequestEssentials(originalRequest); +async function registerRP(policy, urlPrefix, provider, originalRequest) { + const postUrl = `${urlPrefix}providers/${provider}/register?api-version=2016-02-01`; + const getUrl = `${urlPrefix}providers/${provider}?api-version=2016-02-01`; + const reqOptions = getRequestEssentials(originalRequest); reqOptions.method = "POST"; reqOptions.url = postUrl; - return policy._nextPolicy.sendRequest(reqOptions).then(function (response) { - if (response.status !== 200) { - throw new Error("Autoregistration of " + provider + " failed. Please try registering manually."); - } - return getRegistrationStatus(policy, getUrl, originalRequest); - }); + const response = await policy._nextPolicy.sendRequest(reqOptions); + if (response.status !== 200) { + throw new Error(`Autoregistration of ${provider} failed. Please try registering manually.`); + } + return getRegistrationStatus(policy, getUrl, originalRequest); } /** * Polls the registration status of the provider that was registered. Polling happens at an interval of 30 seconds. @@ -59003,25 +54786,24 @@ function registerRP(policy, urlPrefix, provider, originalRequest) { * with a message that the provider is not registered. * @returns True if RP Registration is successful. */ -function getRegistrationStatus(policy, url, originalRequest) { - var reqOptions = getRequestEssentials(originalRequest); +async function getRegistrationStatus(policy, url, originalRequest) { + const reqOptions = getRequestEssentials(originalRequest); reqOptions.url = url; reqOptions.method = "GET"; - return policy._nextPolicy.sendRequest(reqOptions).then(function (res) { - var obj = res.parsedBody; - if (res.parsedBody && obj.registrationState && obj.registrationState === "Registered") { - return true; - } - else { - return delay(policy._retryTimeout * 1000) - .then(function () { return getRegistrationStatus(policy, url, originalRequest); }); - } - }); + const res = await policy._nextPolicy.sendRequest(reqOptions); + const obj = res.parsedBody; + if (res.parsedBody && obj.registrationState && obj.registrationState === "Registered") { + return true; + } + else { + await delay(policy._retryTimeout * 1000); + return getRegistrationStatus(policy, url, originalRequest); + } } // Copyright (c) Microsoft Corporation. // Default options for the cycler if none are provided -var DEFAULT_CYCLER_OPTIONS = { +const DEFAULT_CYCLER_OPTIONS = { forcedRefreshWindowInMs: 1000, retryIntervalInMs: 3000, refreshWindowInMs: 1000 * 60 * 2 // Start refreshing 2m before expiry @@ -59039,59 +54821,33 @@ var DEFAULT_CYCLER_OPTIONS = { * throwing an exception * @returns - a promise that, if it resolves, will resolve with an access token */ -function beginRefresh(getAccessToken, retryIntervalInMs, timeoutInMs) { - return tslib.__awaiter(this, void 0, void 0, function () { - // This wrapper handles exceptions gracefully as long as we haven't exceeded - // the timeout. - function tryGetAccessToken() { - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, finalToken; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!(Date.now() < timeoutInMs)) return [3 /*break*/, 5]; - _b.label = 1; - case 1: - _b.trys.push([1, 3, , 4]); - return [4 /*yield*/, getAccessToken()]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - _a = _b.sent(); - return [2 /*return*/, null]; - case 4: return [3 /*break*/, 7]; - case 5: return [4 /*yield*/, getAccessToken()]; - case 6: - finalToken = _b.sent(); - // Timeout is up, so throw if it's still null - if (finalToken === null) { - throw new Error("Failed to refresh access token."); - } - return [2 /*return*/, finalToken]; - case 7: return [2 /*return*/]; - } - }); - }); - } - var token; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, tryGetAccessToken()]; - case 1: - token = _a.sent(); - _a.label = 2; - case 2: - if (!(token === null)) return [3 /*break*/, 5]; - return [4 /*yield*/, delay(retryIntervalInMs)]; - case 3: - _a.sent(); - return [4 /*yield*/, tryGetAccessToken()]; - case 4: - token = _a.sent(); - return [3 /*break*/, 2]; - case 5: return [2 /*return*/, token]; +async function beginRefresh(getAccessToken, retryIntervalInMs, timeoutInMs) { + // This wrapper handles exceptions gracefully as long as we haven't exceeded + // the timeout. + async function tryGetAccessToken() { + if (Date.now() < timeoutInMs) { + try { + return await getAccessToken(); } - }); - }); + catch (_a) { + return null; + } + } + else { + const finalToken = await getAccessToken(); + // Timeout is up, so throw if it's still null + if (finalToken === null) { + throw new Error("Failed to refresh access token."); + } + return finalToken; + } + } + let token = await tryGetAccessToken(); + while (token === null) { + await delay(retryIntervalInMs); + token = await tryGetAccessToken(); + } + return token; } /** * Creates a token cycler from a credential, scopes, and optional settings. @@ -59109,15 +54865,14 @@ function beginRefresh(getAccessToken, retryIntervalInMs, timeoutInMs) { * @returns - a function that reliably produces a valid access token */ function createTokenCycler(credential, scopes, tokenCyclerOptions) { - var _this = this; - var refreshWorker = null; - var token = null; - var options = tslib.__assign(tslib.__assign({}, DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); + let refreshWorker = null; + let token = null; + const options = Object.assign(Object.assign({}, DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); /** * This little holder defines several predicates that we use to construct * the rules of refreshing the token. */ - var cycler = { + const cycler = { /** * Produces true if a refresh job is currently in progress. */ @@ -59149,20 +54904,18 @@ function createTokenCycler(credential, scopes, tokenCyclerOptions) { var _a; if (!cycler.isRefreshing) { // We bind `scopes` here to avoid passing it around a lot - var tryGetAccessToken = function () { - return credential.getToken(scopes, getTokenOptions); - }; + const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); // Take advantage of promise chaining to insert an assignment to `token` // before the refresh can be considered done. refreshWorker = beginRefresh(tryGetAccessToken, options.retryIntervalInMs, // If we don't have a token, then we should timeout immediately (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now()) - .then(function (_token) { + .then((_token) => { refreshWorker = null; token = _token; return token; }) - .catch(function (reason) { + .catch((reason) => { // We also should reset the refresher if we enter a failed state. All // existing awaiters will throw, but subsequent requests will start a // new retry chain. @@ -59173,25 +54926,23 @@ function createTokenCycler(credential, scopes, tokenCyclerOptions) { } return refreshWorker; } - return function (tokenOptions) { return tslib.__awaiter(_this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - // - // Simple rules: - // - If we MUST refresh, then return the refresh task, blocking - // the pipeline until a token is available. - // - If we SHOULD refresh, then run refresh but don't return it - // (we can still use the cached token). - // - Return the token, since it's fine if we didn't return in - // step 1. - // - if (cycler.mustRefresh) - return [2 /*return*/, refresh(tokenOptions)]; - if (cycler.shouldRefresh) { - refresh(tokenOptions); - } - return [2 /*return*/, token]; - }); - }); }; + return async (tokenOptions) => { + // + // Simple rules: + // - If we MUST refresh, then return the refresh task, blocking + // the pipeline until a token is available. + // - If we SHOULD refresh, then run refresh but don't return it + // (we can still use the cached token). + // - Return the token, since it's fine if we didn't return in + // step 1. + // + if (cycler.mustRefresh) + return refresh(tokenOptions); + if (cycler.shouldRefresh) { + refresh(tokenOptions); + } + return token; + }; } // #endregion /** @@ -59203,36 +54954,27 @@ function createTokenCycler(credential, scopes, tokenCyclerOptions) { */ function bearerTokenAuthenticationPolicy(credential, scopes) { // This simple function encapsulates the entire process of reliably retrieving the token - var getToken = createTokenCycler(credential, scopes /* , options */); - var BearerTokenAuthenticationPolicy = /** @class */ (function (_super) { - tslib.__extends(BearerTokenAuthenticationPolicy, _super); - function BearerTokenAuthenticationPolicy(nextPolicy, options) { - return _super.call(this, nextPolicy, options) || this; + const getToken = createTokenCycler(credential, scopes /* , options */); + class BearerTokenAuthenticationPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options) { + super(nextPolicy, options); } - BearerTokenAuthenticationPolicy.prototype.sendRequest = function (webResource) { - return tslib.__awaiter(this, void 0, void 0, function () { - var token; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, getToken({ - abortSignal: webResource.abortSignal, - tracingOptions: { - spanOptions: webResource.spanOptions, - tracingContext: webResource.tracingContext - } - })]; - case 1: - token = (_a.sent()).token; - webResource.headers.set(Constants.HeaderConstants.AUTHORIZATION, "Bearer " + token); - return [2 /*return*/, this._nextPolicy.sendRequest(webResource)]; - } - }); + async sendRequest(webResource) { + if (!webResource.url.toLowerCase().startsWith("https://")) { + throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); + } + const { token } = await getToken({ + abortSignal: webResource.abortSignal, + tracingOptions: { + tracingContext: webResource.tracingContext + } }); - }; - return BearerTokenAuthenticationPolicy; - }(BaseRequestPolicy)); + webResource.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${token}`); + return this._nextPolicy.sendRequest(webResource); + } + } return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new BearerTokenAuthenticationPolicy(nextPolicy, options); } }; @@ -59241,7 +54983,7 @@ function bearerTokenAuthenticationPolicy(credential, scopes) { // Copyright (c) Microsoft Corporation. function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval); } }; @@ -59252,69 +54994,55 @@ function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, max * @param minRetryInterval - The minimum retry interval, in milliseconds. * @param maxRetryInterval - The maximum retry interval, in milliseconds. */ -var SystemErrorRetryPolicy = /** @class */ (function (_super) { - tslib.__extends(SystemErrorRetryPolicy, _super); - function SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) { - var _this = _super.call(this, nextPolicy, options) || this; - _this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT; - _this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL; - _this.minRetryInterval = isNumber(minRetryInterval) +class SystemErrorRetryPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) { + super(nextPolicy, options); + this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT; + this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL; + this.minRetryInterval = isNumber(minRetryInterval) ? minRetryInterval : DEFAULT_CLIENT_MIN_RETRY_INTERVAL; - _this.maxRetryInterval = isNumber(maxRetryInterval) + this.maxRetryInterval = isNumber(maxRetryInterval) ? maxRetryInterval : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; - return _this; } - SystemErrorRetryPolicy.prototype.sendRequest = function (request) { - var _this = this; + sendRequest(request) { return this._nextPolicy .sendRequest(request.clone()) - .catch(function (error) { return retry$1(_this, request, error.response, error); }); - }; - return SystemErrorRetryPolicy; -}(BaseRequestPolicy)); -function retry$1(policy, request, operationResponse, err, retryData) { - return tslib.__awaiter(this, void 0, void 0, function () { - function shouldPolicyRetry(_response, error) { - if (error && - error.code && - (error.code === "ETIMEDOUT" || - error.code === "ESOCKETTIMEDOUT" || - error.code === "ECONNREFUSED" || - error.code === "ECONNRESET" || - error.code === "ENOENT")) { - return true; - } - return false; + .catch((error) => retry$1(this, request, error.response, error)); + } +} +async function retry$1(policy, request, operationResponse, err, retryData) { + retryData = updateRetryData(policy, retryData, err); + function shouldPolicyRetry(_response, error) { + if (error && + error.code && + (error.code === "ETIMEDOUT" || + error.code === "ESOCKETTIMEDOUT" || + error.code === "ECONNREFUSED" || + error.code === "ECONNRESET" || + error.code === "ENOENT")) { + return true; } - var nestedErr_1; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - retryData = updateRetryData(policy, retryData, err); - if (!shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, operationResponse, err)) return [3 /*break*/, 5]; - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - return [4 /*yield*/, delay(retryData.retryInterval)]; - case 2: - _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)]; - case 4: return [3 /*break*/, 6]; - case 5: - if (err) { - // If the operation failed in the end, return all errors instead of just the last one - return [2 /*return*/, Promise.reject(retryData.error)]; - } - return [2 /*return*/, operationResponse]; - case 6: return [2 /*return*/]; - } - }); - }); + return false; + } + if (shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, operationResponse, err)) { + // If previous operation ended with an error and the policy allows a retry, do that + try { + await delay(retryData.retryInterval); + return policy._nextPolicy.sendRequest(request.clone()); + } + catch (nestedErr) { + return retry$1(policy, request, operationResponse, nestedErr, retryData); + } + } + else { + if (err) { + // If the operation failed in the end, return all errors instead of just the last one + return Promise.reject(retryData.error); + } + return operationResponse; + } } // Copyright (c) Microsoft Corporation. @@ -59328,34 +55056,37 @@ function retry$1(policy, request, operationResponse, err, retryData) { // Copyright (c) Microsoft Corporation. /** + * Stores the patterns specified in NO_PROXY environment variable. * @internal */ -var noProxyList = []; -var noProxyListLoaded = false; -var byPassedList = new Map(); +const globalNoProxyList = []; +let noProxyListLoaded = false; +/** A cache of whether a host should bypass the proxy. */ +const globalBypassedMap = new Map(); function loadEnvironmentProxyValue() { if (!process) { return undefined; } - var httpsProxy = getEnvironmentValue(Constants.HTTPS_PROXY); - var allProxy = getEnvironmentValue(Constants.ALL_PROXY); - var httpProxy = getEnvironmentValue(Constants.HTTP_PROXY); + const httpsProxy = getEnvironmentValue(Constants.HTTPS_PROXY); + const allProxy = getEnvironmentValue(Constants.ALL_PROXY); + const 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 -function isBypassed(uri) { +/** + * Check whether the host of a given `uri` matches any pattern in the no proxy list. + * If there's a match, any request sent to the same host shouldn'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 + */ +function isBypassed(uri, noProxyList, bypassedMap) { if (noProxyList.length === 0) { return false; } - var host = URLBuilder.parse(uri).getHost(); - if (byPassedList.has(host)) { - return byPassedList.get(host); + const host = URLBuilder.parse(uri).getHost(); + if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { + return bypassedMap.get(host); } - var isBypassedFlag = false; - for (var _i = 0, noProxyList_1 = noProxyList; _i < noProxyList_1.length; _i++) { - var pattern = noProxyList_1[_i]; + let isBypassedFlag = false; + for (const pattern of noProxyList) { 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 @@ -59374,20 +55105,20 @@ function isBypassed(uri) { } } } - byPassedList.set(host, isBypassedFlag); + bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); return isBypassedFlag; } /** * @internal */ function loadNoProxy() { - var noProxy = getEnvironmentValue(Constants.NO_PROXY); + const noProxy = getEnvironmentValue(Constants.NO_PROXY); noProxyListLoaded = true; if (noProxy) { return noProxy .split(",") - .map(function (item) { return item.trim(); }) - .filter(function (item) { return item.length; }); + .map((item) => item.trim()) + .filter((item) => item.length); } return []; } @@ -59398,174 +55129,184 @@ function getDefaultProxySettings(proxyUrl) { return undefined; } } - var _a = extractAuthFromUrl(proxyUrl), username = _a.username, password = _a.password, urlWithoutAuth = _a.urlWithoutAuth; - var parsedUrl = URLBuilder.parse(urlWithoutAuth); - var schema = parsedUrl.getScheme() ? parsedUrl.getScheme() + "://" : ""; + const { username, password, urlWithoutAuth } = extractAuthFromUrl(proxyUrl); + const parsedUrl = URLBuilder.parse(urlWithoutAuth); + const schema = parsedUrl.getScheme() ? parsedUrl.getScheme() + "://" : ""; return { host: schema + parsedUrl.getHost(), port: Number.parseInt(parsedUrl.getPort() || "80"), - username: username, - password: password + username, + password }; } -function proxyPolicy(proxySettings) { +/** + * A policy that allows one to apply proxy settings to all requests. + * If not passed static settings, they will be retrieved from the HTTPS_PROXY + * or HTTP_PROXY environment variables. + * @param proxySettings - ProxySettings to use on each request. + * @param options - additional settings, for example, custom NO_PROXY patterns + */ +function proxyPolicy(proxySettings, options) { if (!proxySettings) { proxySettings = getDefaultProxySettings(); } if (!noProxyListLoaded) { - noProxyList.push.apply(noProxyList, loadNoProxy()); + globalNoProxyList.push(...loadNoProxy()); } return { - create: function (nextPolicy, options) { - return new ProxyPolicy(nextPolicy, options, proxySettings); + create: (nextPolicy, requestPolicyOptions) => { + return new ProxyPolicy(nextPolicy, requestPolicyOptions, proxySettings, options === null || options === void 0 ? void 0 : options.customNoProxyList); } }; } function extractAuthFromUrl(url) { - var atIndex = url.indexOf("@"); + const atIndex = url.indexOf("@"); if (atIndex === -1) { return { urlWithoutAuth: url }; } - var schemeIndex = url.indexOf("://"); - var authStart = schemeIndex !== -1 ? schemeIndex + 3 : 0; - var auth = url.substring(authStart, atIndex); - var colonIndex = auth.indexOf(":"); - var hasPassword = colonIndex !== -1; - var username = hasPassword ? auth.substring(0, colonIndex) : auth; - var password = hasPassword ? auth.substring(colonIndex + 1) : undefined; - var urlWithoutAuth = url.substring(0, authStart) + url.substring(atIndex + 1); + const schemeIndex = url.indexOf("://"); + const authStart = schemeIndex !== -1 ? schemeIndex + 3 : 0; + const auth = url.substring(authStart, atIndex); + const colonIndex = auth.indexOf(":"); + const hasPassword = colonIndex !== -1; + const username = hasPassword ? auth.substring(0, colonIndex) : auth; + const password = hasPassword ? auth.substring(colonIndex + 1) : undefined; + const urlWithoutAuth = url.substring(0, authStart) + url.substring(atIndex + 1); return { - username: username, - password: password, - urlWithoutAuth: urlWithoutAuth + username, + password, + urlWithoutAuth }; } -var ProxyPolicy = /** @class */ (function (_super) { - tslib.__extends(ProxyPolicy, _super); - function ProxyPolicy(nextPolicy, options, proxySettings) { - var _this = _super.call(this, nextPolicy, options) || this; - _this.proxySettings = proxySettings; - return _this; +class ProxyPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, proxySettings, customNoProxyList) { + super(nextPolicy, options); + this.proxySettings = proxySettings; + this.customNoProxyList = customNoProxyList; } - ProxyPolicy.prototype.sendRequest = function (request) { - if (!request.proxySettings && !isBypassed(request.url)) { + sendRequest(request) { + var _a; + if (!request.proxySettings && + !isBypassed(request.url, (_a = this.customNoProxyList) !== null && _a !== void 0 ? _a : globalNoProxyList, this.customNoProxyList ? undefined : globalBypassedMap)) { request.proxySettings = this.proxySettings; } return this._nextPolicy.sendRequest(request); - }; - return ProxyPolicy; -}(BaseRequestPolicy)); + } +} // Copyright (c) Microsoft Corporation. -var StatusCodes = Constants.HttpConstants.StatusCodes; +// Licensed under the MIT license. +/** + * Maximum number of retries for the throttling retry policy + */ +const DEFAULT_CLIENT_MAX_RETRY_COUNT = 3; + +// Copyright (c) Microsoft Corporation. +const StatusCodes = Constants.HttpConstants.StatusCodes; function throttlingRetryPolicy() { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new ThrottlingRetryPolicy(nextPolicy, options); } }; } +const StandardAbortMessage$1 = "The operation was aborted."; /** * To learn more, please refer to * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits, * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors */ -var ThrottlingRetryPolicy = /** @class */ (function (_super) { - tslib.__extends(ThrottlingRetryPolicy, _super); - function ThrottlingRetryPolicy(nextPolicy, options, _handleResponse) { - var _this = _super.call(this, nextPolicy, options) || this; - _this._handleResponse = _handleResponse || _this._defaultResponseHandler; - return _this; +class ThrottlingRetryPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, _handleResponse) { + super(nextPolicy, options); + this.numberOfRetries = 0; + this._handleResponse = _handleResponse || this._defaultResponseHandler; } - ThrottlingRetryPolicy.prototype.sendRequest = function (httpRequest) { - return tslib.__awaiter(this, void 0, void 0, function () { - var _this = this; - return tslib.__generator(this, function (_a) { - return [2 /*return*/, this._nextPolicy.sendRequest(httpRequest.clone()).then(function (response) { - if (response.status !== StatusCodes.TooManyRequests) { - return response; - } - else { - return _this._handleResponse(httpRequest, response); - } - })]; - }); - }); - }; - ThrottlingRetryPolicy.prototype._defaultResponseHandler = function (httpRequest, httpResponse) { - return tslib.__awaiter(this, void 0, void 0, function () { - var retryAfterHeader, delayInMs; - var _this = this; - return tslib.__generator(this, function (_a) { - retryAfterHeader = httpResponse.headers.get(Constants.HeaderConstants.RETRY_AFTER); - if (retryAfterHeader) { - delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader); - if (delayInMs) { - return [2 /*return*/, delay(delayInMs).then(function (_) { return _this._nextPolicy.sendRequest(httpRequest); })]; - } + async sendRequest(httpRequest) { + const response = await this._nextPolicy.sendRequest(httpRequest.clone()); + if (response.status !== StatusCodes.TooManyRequests && + response.status !== StatusCodes.ServiceUnavailable) { + return response; + } + else { + return this._handleResponse(httpRequest, response); + } + } + async _defaultResponseHandler(httpRequest, httpResponse) { + var _a; + const retryAfterHeader = httpResponse.headers.get(Constants.HeaderConstants.RETRY_AFTER); + if (retryAfterHeader) { + const delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader); + if (delayInMs) { + this.numberOfRetries += 1; + await delay(delayInMs, undefined, { + abortSignal: httpRequest.abortSignal, + abortErrorMsg: StandardAbortMessage$1 + }); + if ((_a = httpRequest.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { + throw new abortController.AbortError(StandardAbortMessage$1); } - return [2 /*return*/, httpResponse]; - }); - }); - }; - ThrottlingRetryPolicy.parseRetryAfterHeader = function (headerValue) { - var retryAfterInSeconds = Number(headerValue); + if (this.numberOfRetries < DEFAULT_CLIENT_MAX_RETRY_COUNT) { + return this.sendRequest(httpRequest); + } + else { + return this._nextPolicy.sendRequest(httpRequest); + } + } + } + return httpResponse; + } + static parseRetryAfterHeader(headerValue) { + const retryAfterInSeconds = Number(headerValue); if (Number.isNaN(retryAfterInSeconds)) { return ThrottlingRetryPolicy.parseDateRetryAfterHeader(headerValue); } else { return retryAfterInSeconds * 1000; } - }; - ThrottlingRetryPolicy.parseDateRetryAfterHeader = function (headerValue) { + } + static parseDateRetryAfterHeader(headerValue) { try { - var now = Date.now(); - var date = Date.parse(headerValue); - var diff = date - now; + const now = Date.now(); + const date = Date.parse(headerValue); + const diff = date - now; return Number.isNaN(diff) ? undefined : diff; } catch (error) { return undefined; } - }; - return ThrottlingRetryPolicy; -}(BaseRequestPolicy)); + } +} // Copyright (c) Microsoft Corporation. function signingPolicy(authenticationProvider) { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new SigningPolicy(nextPolicy, options, authenticationProvider); } }; } -var SigningPolicy = /** @class */ (function (_super) { - tslib.__extends(SigningPolicy, _super); - function SigningPolicy(nextPolicy, options, authenticationProvider) { - var _this = _super.call(this, nextPolicy, options) || this; - _this.authenticationProvider = authenticationProvider; - return _this; +class SigningPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, authenticationProvider) { + super(nextPolicy, options); + this.authenticationProvider = authenticationProvider; } - SigningPolicy.prototype.signRequest = function (request) { + signRequest(request) { return this.authenticationProvider.signRequest(request); - }; - SigningPolicy.prototype.sendRequest = function (request) { - var _this = this; - return this.signRequest(request).then(function (nextRequest) { - return _this._nextPolicy.sendRequest(nextRequest); - }); - }; - return SigningPolicy; -}(BaseRequestPolicy)); + } + sendRequest(request) { + return this.signRequest(request).then((nextRequest) => this._nextPolicy.sendRequest(nextRequest)); + } +} // Copyright (c) Microsoft Corporation. -var DefaultKeepAliveOptions = { +const DefaultKeepAliveOptions = { enable: true }; function keepAlivePolicy(keepAliveOptions) { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new KeepAlivePolicy(nextPolicy, options, keepAliveOptions || DefaultKeepAliveOptions); } }; @@ -59573,8 +55314,7 @@ function keepAlivePolicy(keepAliveOptions) { /** * KeepAlivePolicy is a policy used to control keep alive settings for every request. */ -var KeepAlivePolicy = /** @class */ (function (_super) { - tslib.__extends(KeepAlivePolicy, _super); +class KeepAlivePolicy extends BaseRequestPolicy { /** * Creates an instance of KeepAlivePolicy. * @@ -59582,10 +55322,9 @@ var KeepAlivePolicy = /** @class */ (function (_super) { * @param options - * @param keepAliveOptions - */ - function KeepAlivePolicy(nextPolicy, options, keepAliveOptions) { - var _this = _super.call(this, nextPolicy, options) || this; - _this.keepAliveOptions = keepAliveOptions; - return _this; + constructor(nextPolicy, options, keepAliveOptions) { + super(nextPolicy, options); + this.keepAliveOptions = keepAliveOptions; } /** * Sends out request. @@ -59593,104 +55332,126 @@ var KeepAlivePolicy = /** @class */ (function (_super) { * @param request - * @returns */ - KeepAlivePolicy.prototype.sendRequest = function (request) { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - request.keepAlive = this.keepAliveOptions.enable; - return [2 /*return*/, this._nextPolicy.sendRequest(request)]; - }); - }); - }; - return KeepAlivePolicy; -}(BaseRequestPolicy)); + async sendRequest(request) { + request.keepAlive = this.keepAliveOptions.enable; + return this._nextPolicy.sendRequest(request); + } +} // Copyright (c) Microsoft Corporation. -var createSpan = coreTracing.createSpanFunction({ +const createSpan = coreTracing.createSpanFunction({ packagePrefix: "", namespace: "" }); -function tracingPolicy(tracingOptions) { - if (tracingOptions === void 0) { tracingOptions = {}; } +function tracingPolicy(tracingOptions = {}) { return { - create: function (nextPolicy, options) { + create(nextPolicy, options) { return new TracingPolicy(nextPolicy, options, tracingOptions); } }; } -var TracingPolicy = /** @class */ (function (_super) { - tslib.__extends(TracingPolicy, _super); - function TracingPolicy(nextPolicy, options, tracingOptions) { - var _this = _super.call(this, nextPolicy, options) || this; - _this.userAgent = tracingOptions.userAgent; - return _this; +class TracingPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, tracingOptions) { + super(nextPolicy, options); + this.userAgent = tracingOptions.userAgent; } - TracingPolicy.prototype.sendRequest = function (request) { - return tslib.__awaiter(this, void 0, void 0, function () { - var path, span, spanContext, traceParentHeader, traceState, response, serviceRequestId, err_1; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!request.tracingContext) { - return [2 /*return*/, this._nextPolicy.sendRequest(request)]; - } - path = URLBuilder.parse(request.url).getPath() || "/"; - span = createSpan(path, { - tracingOptions: { - spanOptions: tslib.__assign(tslib.__assign({}, request.spanOptions), { kind: coreTracing.SpanKind.CLIENT }), - tracingContext: request.tracingContext - } - }).span; - span.setAttributes({ - "http.method": request.method, - "http.url": request.url, - requestId: request.requestId - }); - if (this.userAgent) { - span.setAttribute("http.user_agent", this.userAgent); - } - _a.label = 1; - case 1: - _a.trys.push([1, 3, 4, 5]); - spanContext = span.context(); - traceParentHeader = coreTracing.getTraceParentHeader(spanContext); - if (traceParentHeader) { - request.headers.set("traceparent", traceParentHeader); - traceState = spanContext.traceState && spanContext.traceState.serialize(); - // if tracestate is set, traceparent MUST be set, so only set tracestate after traceparent - if (traceState) { - request.headers.set("tracestate", traceState); - } - } - return [4 /*yield*/, this._nextPolicy.sendRequest(request)]; - case 2: - response = _a.sent(); - span.setAttribute("http.status_code", response.status); - serviceRequestId = response.headers.get("x-ms-request-id"); - if (serviceRequestId) { - span.setAttribute("serviceRequestId", serviceRequestId); - } - span.setStatus({ - code: coreTracing.SpanStatusCode.OK - }); - return [2 /*return*/, response]; - case 3: - err_1 = _a.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: err_1.message - }); - span.setAttribute("http.status_code", err_1.statusCode); - throw err_1; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + async sendRequest(request) { + if (!request.tracingContext) { + return this._nextPolicy.sendRequest(request); + } + const span = this.tryCreateSpan(request); + if (!span) { + return this._nextPolicy.sendRequest(request); + } + try { + const response = await this._nextPolicy.sendRequest(request); + this.tryProcessResponse(span, response); + return response; + } + catch (err) { + this.tryProcessError(span, err); + throw err; + } + } + tryCreateSpan(request) { + var _a; + try { + const path = URLBuilder.parse(request.url).getPath() || "/"; + // Passing spanOptions as part of tracingOptions to maintain compatibility @azure/core-tracing@preview.13 and earlier. + // We can pass this as a separate parameter once we upgrade to the latest core-tracing. + const { span } = createSpan(path, { + tracingOptions: { + spanOptions: Object.assign(Object.assign({}, request.spanOptions), { kind: coreTracing.SpanKind.CLIENT }), + tracingContext: request.tracingContext } }); - }); - }; - return TracingPolicy; -}(BaseRequestPolicy)); + // If the span is not recording, don't do any more work. + if (!span.isRecording()) { + span.end(); + return undefined; + } + const namespaceFromContext = (_a = request.tracingContext) === null || _a === void 0 ? void 0 : _a.getValue(Symbol.for("az.namespace")); + if (typeof namespaceFromContext === "string") { + span.setAttribute("az.namespace", namespaceFromContext); + } + span.setAttributes({ + "http.method": request.method, + "http.url": request.url, + requestId: request.requestId + }); + if (this.userAgent) { + span.setAttribute("http.user_agent", this.userAgent); + } + // set headers + const spanContext = span.spanContext(); + const traceParentHeader = coreTracing.getTraceParentHeader(spanContext); + if (traceParentHeader && coreTracing.isSpanContextValid(spanContext)) { + request.headers.set("traceparent", traceParentHeader); + const traceState = spanContext.traceState && spanContext.traceState.serialize(); + // if tracestate is set, traceparent MUST be set, so only set tracestate after traceparent + if (traceState) { + request.headers.set("tracestate", traceState); + } + } + return span; + } + catch (error) { + logger.warning(`Skipping creating a tracing span due to an error: ${error.message}`); + return undefined; + } + } + tryProcessError(span, err) { + try { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: err.message + }); + if (err.statusCode) { + span.setAttribute("http.status_code", err.statusCode); + } + span.end(); + } + catch (error) { + logger.warning(`Skipping tracing span processing due to an error: ${error.message}`); + } + } + tryProcessResponse(span, response) { + try { + span.setAttribute("http.status_code", response.status); + const serviceRequestId = response.headers.get("x-ms-request-id"); + if (serviceRequestId) { + span.setAttribute("serviceRequestId", serviceRequestId); + } + span.setStatus({ + code: coreTracing.SpanStatusCode.OK + }); + span.end(); + } + catch (error) { + logger.warning(`Skipping tracing span processing due to an error: ${error.message}`); + } + } +} // Copyright (c) Microsoft Corporation. /** @@ -59699,7 +55460,7 @@ var TracingPolicy = /** @class */ (function (_super) { */ function disableResponseDecompressionPolicy() { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new DisableResponseDecompressionPolicy(nextPolicy, options); } }; @@ -59708,8 +55469,7 @@ function disableResponseDecompressionPolicy() { * A policy to disable response decompression according to Accept-Encoding header * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding */ -var DisableResponseDecompressionPolicy = /** @class */ (function (_super) { - tslib.__extends(DisableResponseDecompressionPolicy, _super); +class DisableResponseDecompressionPolicy extends BaseRequestPolicy { /** * Creates an instance of DisableResponseDecompressionPolicy. * @@ -59718,8 +55478,8 @@ var DisableResponseDecompressionPolicy = /** @class */ (function (_super) { */ // The parent constructor is protected. /* eslint-disable-next-line @typescript-eslint/no-useless-constructor */ - function DisableResponseDecompressionPolicy(nextPolicy, options) { - return _super.call(this, nextPolicy, options) || this; + constructor(nextPolicy, options) { + super(nextPolicy, options); } /** * Sends out request. @@ -59727,21 +55487,16 @@ var DisableResponseDecompressionPolicy = /** @class */ (function (_super) { * @param request - * @returns */ - DisableResponseDecompressionPolicy.prototype.sendRequest = function (request) { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - request.decompressResponse = false; - return [2 /*return*/, this._nextPolicy.sendRequest(request)]; - }); - }); - }; - return DisableResponseDecompressionPolicy; -}(BaseRequestPolicy)); + async sendRequest(request) { + request.decompressResponse = false; + return this._nextPolicy.sendRequest(request); + } +} // Copyright (c) Microsoft Corporation. function ndJsonPolicy() { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new NdJsonPolicy(nextPolicy, options); } }; @@ -59749,37 +55504,30 @@ function ndJsonPolicy() { /** * NdJsonPolicy that formats a JSON array as newline-delimited JSON */ -var NdJsonPolicy = /** @class */ (function (_super) { - tslib.__extends(NdJsonPolicy, _super); +class NdJsonPolicy extends BaseRequestPolicy { /** * Creates an instance of KeepAlivePolicy. */ - function NdJsonPolicy(nextPolicy, options) { - return _super.call(this, nextPolicy, options) || this; + constructor(nextPolicy, options) { + super(nextPolicy, options); } /** * Sends a request. */ - NdJsonPolicy.prototype.sendRequest = function (request) { - return tslib.__awaiter(this, void 0, void 0, function () { - var body; - return tslib.__generator(this, function (_a) { - // There currently isn't a good way to bypass the serializer - if (typeof request.body === "string" && request.body.startsWith("[")) { - body = JSON.parse(request.body); - if (Array.isArray(body)) { - request.body = body.map(function (item) { return JSON.stringify(item) + "\n"; }).join(""); - } - } - return [2 /*return*/, this._nextPolicy.sendRequest(request)]; - }); - }); - }; - return NdJsonPolicy; -}(BaseRequestPolicy)); + async sendRequest(request) { + // There currently isn't a good way to bypass the serializer + if (typeof request.body === "string" && request.body.startsWith("[")) { + const body = JSON.parse(request.body); + if (Array.isArray(body)) { + request.body = body.map((item) => JSON.stringify(item) + "\n").join(""); + } + } + return this._nextPolicy.sendRequest(request); + } +} // Copyright (c) Microsoft Corporation. -var cachedHttpClient; +let cachedHttpClient; function getCachedDefaultHttpClient() { if (!cachedHttpClient) { cachedHttpClient = new NodeFetchHttpClient(); @@ -59791,29 +55539,28 @@ function getCachedDefaultHttpClient() { /** * ServiceClient sends service requests and receives responses. */ -var ServiceClient = /** @class */ (function () { +class ServiceClient { /** * 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. */ - function ServiceClient(credentials, + constructor(credentials, /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options */ options) { - var _this = this; if (!options) { options = {}; } this._withCredentials = options.withCredentials || false; this._httpClient = options.httpClient || getCachedDefaultHttpClient(); this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger); - var requestPolicyFactories; + let requestPolicyFactories; if (Array.isArray(options.requestPolicyFactories)) { logger.info("ServiceClient: using custom request policies"); requestPolicyFactories = options.requestPolicyFactories; } else { - var authPolicyFactory = undefined; + let authPolicyFactory = undefined; if (coreAuth.isTokenCredential(credentials)) { logger.info("ServiceClient: creating bearer token authentication policy from provided credentials"); // Create a wrapped RequestPolicyFactory here so that we can provide the @@ -59822,16 +55569,16 @@ var ServiceClient = /** @class */ (function () { // implementations do not set baseUri until after ServiceClient's constructor // is finished, leaving baseUri empty at the time when it is needed to // build the correct scope name. - var wrappedPolicyFactory = function () { - var bearerTokenPolicyFactory = undefined; + const wrappedPolicyFactory = () => { + let bearerTokenPolicyFactory = undefined; // eslint-disable-next-line @typescript-eslint/no-this-alias - var serviceClient = _this; - var serviceClientOptions = options; + const serviceClient = this; + const serviceClientOptions = options; return { - create: function (nextPolicy, createOptions) { - var credentialScopes = getCredentialScopes(serviceClientOptions, serviceClient.baseUri); + create(nextPolicy, createOptions) { + const 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"); + throw new Error(`When using credential, the ServiceClient must contain a baseUri or a credentialScopes in ServiceClientOptions. Unable to create a bearerTokenAuthenticationPolicy`); } if (bearerTokenPolicyFactory === undefined || bearerTokenPolicyFactory === null) { bearerTokenPolicyFactory = bearerTokenAuthenticationPolicy(credentials, credentialScopes); @@ -59854,7 +55601,7 @@ var ServiceClient = /** @class */ (function () { if (options.requestPolicyFactories) { // options.requestPolicyFactories can also be a function that manipulates // the default requestPolicyFactories array - var newRequestPolicyFactories = options.requestPolicyFactories(requestPolicyFactories); + const newRequestPolicyFactories = options.requestPolicyFactories(requestPolicyFactories); if (newRequestPolicyFactories) { requestPolicyFactories = newRequestPolicyFactories; } @@ -59865,11 +55612,11 @@ var ServiceClient = /** @class */ (function () { /** * Send the provided httpRequest. */ - ServiceClient.prototype.sendRequest = function (options) { + sendRequest(options) { if (options === null || options === undefined || typeof options !== "object") { throw new Error("options cannot be null or undefined and it must be of type object."); } - var httpRequest; + let httpRequest; try { if (isWebResourceLike(options)) { options.validateRequestProperties(); @@ -59883,242 +55630,221 @@ var ServiceClient = /** @class */ (function () { catch (error) { return Promise.reject(error); } - var httpPipeline = this._httpClient; + let httpPipeline = this._httpClient; if (this._requestPolicyFactories && this._requestPolicyFactories.length > 0) { - for (var i = this._requestPolicyFactories.length - 1; i >= 0; --i) { + for (let i = this._requestPolicyFactories.length - 1; i >= 0; --i) { httpPipeline = this._requestPolicyFactories[i].create(httpPipeline, this._requestPolicyOptions); } } return httpPipeline.sendRequest(httpRequest); - }; + } /** * 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. */ - ServiceClient.prototype.sendOperationRequest = function (operationArguments, operationSpec, callback) { + async sendOperationRequest(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) { - 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; - case 1: - _j.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."); - } - httpRequest.method = operationSpec.httpMethod; - httpRequest.operationSpec = operationSpec; - requestUrl = URLBuilder.parse(baseUri); - if (operationSpec.path) { - requestUrl.appendPath(operationSpec.path); - } - if (operationSpec.urlParameters && operationSpec.urlParameters.length > 0) { - for (_i = 0, _b = operationSpec.urlParameters; _i < _b.length; _i++) { - urlParameter = _b[_i]; - urlParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, urlParameter, operationSpec.serializer); - urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, getPathStringFromParameter(urlParameter), serializerOptions); - if (!urlParameter.skipEncoding) { - urlParameterValue = encodeURIComponent(urlParameterValue); + if (typeof operationArguments.options === "function") { + callback = operationArguments.options; + operationArguments.options = undefined; + } + const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; + const httpRequest = new WebResource(); + let result; + try { + const 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."); + } + httpRequest.method = operationSpec.httpMethod; + httpRequest.operationSpec = operationSpec; + const requestUrl = URLBuilder.parse(baseUri); + if (operationSpec.path) { + requestUrl.appendPath(operationSpec.path); + } + if (operationSpec.urlParameters && operationSpec.urlParameters.length > 0) { + for (const urlParameter of operationSpec.urlParameters) { + let urlParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, urlParameter, operationSpec.serializer); + urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, getPathStringFromParameter(urlParameter), serializerOptions); + if (!urlParameter.skipEncoding) { + urlParameterValue = encodeURIComponent(urlParameterValue); + } + requestUrl.replaceAll(`{${urlParameter.mapper.serializedName || getPathStringFromParameter(urlParameter)}}`, urlParameterValue); + } + } + if (operationSpec.queryParameters && operationSpec.queryParameters.length > 0) { + for (const queryParameter of operationSpec.queryParameters) { + let queryParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, queryParameter, operationSpec.serializer); + if (queryParameterValue !== undefined && queryParameterValue !== null) { + queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter), serializerOptions); + 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; } - requestUrl.replaceAll("{" + (urlParameter.mapper.serializedName || getPathStringFromParameter(urlParameter)) + "}", urlParameterValue); - } - } - if (operationSpec.queryParameters && operationSpec.queryParameters.length > 0) { - for (_c = 0, _d = operationSpec.queryParameters; _c < _d.length; _c++) { - queryParameter = _d[_c]; - queryParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, queryParameter, operationSpec.serializer); - if (queryParameterValue !== undefined && queryParameterValue !== null) { - queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter), serializerOptions); - 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; - } - else { - for (index in queryParameterValue) { - item = queryParameterValue[index]; - queryParameterValue[index] = - item === undefined || item === null ? "" : item.toString(); - } - } - } - else if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Ssv || - queryParameter.collectionFormat === exports.QueryCollectionFormat.Tsv) { - queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat); - } - } - if (!queryParameter.skipEncoding) { - if (Array.isArray(queryParameterValue)) { - for (index in queryParameterValue) { - if (queryParameterValue[index] !== undefined && - queryParameterValue[index] !== null) { - queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]); - } - } - } - else { - queryParameterValue = encodeURIComponent(queryParameterValue); - } - } - if (queryParameter.collectionFormat !== undefined && - queryParameter.collectionFormat !== null && - queryParameter.collectionFormat !== exports.QueryCollectionFormat.Multi && - queryParameter.collectionFormat !== exports.QueryCollectionFormat.Ssv && - queryParameter.collectionFormat !== exports.QueryCollectionFormat.Tsv) { - queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat); - } - requestUrl.setQueryParameter(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue); - } - } - } - httpRequest.url = requestUrl.toString(); - contentType = operationSpec.contentType || this.requestContentType; - if (contentType && operationSpec.requestBody) { - httpRequest.headers.set("Content-Type", contentType); - } - if (operationSpec.headerParameters) { - for (_e = 0, _f = operationSpec.headerParameters; _e < _f.length; _e++) { - headerParameter = _f[_e]; - headerValue = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer); - if (headerValue !== undefined && headerValue !== null) { - headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter), serializerOptions); - headerCollectionPrefix = headerParameter.mapper - .headerCollectionPrefix; - if (headerCollectionPrefix) { - for (_g = 0, _h = Object.keys(headerValue); _g < _h.length; _g++) { - key = _h[_g]; - httpRequest.headers.set(headerCollectionPrefix + key, headerValue[key]); - } - } - else { - httpRequest.headers.set(headerParameter.mapper.serializedName || - getPathStringFromParameter(headerParameter), headerValue); + else { + for (const index in queryParameterValue) { + const item = queryParameterValue[index]; + queryParameterValue[index] = + item === undefined || item === null ? "" : item.toString(); } } } + else if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Ssv || + queryParameter.collectionFormat === exports.QueryCollectionFormat.Tsv) { + queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat); + } } - options = operationArguments.options; - if (options) { - if (options.customHeaders) { - for (customHeaderName in options.customHeaders) { - httpRequest.headers.set(customHeaderName, options.customHeaders[customHeaderName]); + if (!queryParameter.skipEncoding) { + if (Array.isArray(queryParameterValue)) { + for (const index in queryParameterValue) { + if (queryParameterValue[index] !== undefined && + queryParameterValue[index] !== null) { + queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]); + } } } - if (options.abortSignal) { - httpRequest.abortSignal = options.abortSignal; - } - if (options.timeout) { - httpRequest.timeout = options.timeout; - } - if (options.onUploadProgress) { - httpRequest.onUploadProgress = options.onUploadProgress; - } - if (options.onDownloadProgress) { - httpRequest.onDownloadProgress = options.onDownloadProgress; - } - if (options.spanOptions) { - httpRequest.spanOptions = options.spanOptions; - } - if (options.tracingContext) { - httpRequest.tracingContext = options.tracingContext; - } - if (options.shouldDeserialize !== undefined && options.shouldDeserialize !== null) { - httpRequest.shouldDeserialize = options.shouldDeserialize; + else { + queryParameterValue = encodeURIComponent(queryParameterValue); } } - httpRequest.withCredentials = this._withCredentials; - serializeRequestBody(this, httpRequest, operationArguments, operationSpec); - if (httpRequest.streamResponseStatusCodes === undefined) { - httpRequest.streamResponseStatusCodes = getStreamResponseStatusCodes(operationSpec); + if (queryParameter.collectionFormat !== undefined && + queryParameter.collectionFormat !== null && + queryParameter.collectionFormat !== exports.QueryCollectionFormat.Multi && + queryParameter.collectionFormat !== exports.QueryCollectionFormat.Ssv && + queryParameter.collectionFormat !== exports.QueryCollectionFormat.Tsv) { + queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat); } - rawResponse = void 0; - sendRequestError = void 0; - _j.label = 2; - case 2: - _j.trys.push([2, 4, , 5]); - return [4 /*yield*/, this.sendRequest(httpRequest)]; - case 3: - rawResponse = _j.sent(); - return [3 /*break*/, 5]; - case 4: - error_1 = _j.sent(); - sendRequestError = error_1; - return [3 /*break*/, 5]; - case 5: - if (sendRequestError) { - if (sendRequestError.response) { - sendRequestError.details = flattenResponse(sendRequestError.response, operationSpec.responses[sendRequestError.statusCode] || - operationSpec.responses["default"]); + requestUrl.setQueryParameter(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue); + } + } + } + httpRequest.url = requestUrl.toString(); + const contentType = operationSpec.contentType || this.requestContentType; + if (contentType && operationSpec.requestBody) { + httpRequest.headers.set("Content-Type", contentType); + } + if (operationSpec.headerParameters) { + for (const headerParameter of operationSpec.headerParameters) { + let headerValue = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer); + if (headerValue !== undefined && headerValue !== null) { + headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter), serializerOptions); + const headerCollectionPrefix = headerParameter.mapper + .headerCollectionPrefix; + if (headerCollectionPrefix) { + for (const key of Object.keys(headerValue)) { + httpRequest.headers.set(headerCollectionPrefix + key, headerValue[key]); } - result = Promise.reject(sendRequestError); } else { - result = Promise.resolve(flattenResponse(rawResponse, operationSpec.responses[rawResponse.status])); + httpRequest.headers.set(headerParameter.mapper.serializedName || + getPathStringFromParameter(headerParameter), headerValue); } - return [3 /*break*/, 7]; - case 6: - error_2 = _j.sent(); - result = Promise.reject(error_2); - return [3 /*break*/, 7]; - case 7: - cb = callback; - if (cb) { - result - .then(function (res) { return cb(null, res._response.parsedBody, res._response.request, res._response); }) - .catch(function (err) { return cb(err); }); - } - return [2 /*return*/, result]; + } } - }); - }); - }; - return ServiceClient; -}()); + } + const options = operationArguments.options; + if (options) { + if (options.customHeaders) { + for (const customHeaderName in options.customHeaders) { + httpRequest.headers.set(customHeaderName, options.customHeaders[customHeaderName]); + } + } + if (options.abortSignal) { + httpRequest.abortSignal = options.abortSignal; + } + if (options.timeout) { + httpRequest.timeout = options.timeout; + } + if (options.onUploadProgress) { + httpRequest.onUploadProgress = options.onUploadProgress; + } + if (options.onDownloadProgress) { + httpRequest.onDownloadProgress = options.onDownloadProgress; + } + if (options.spanOptions) { + // By passing spanOptions if they exist at runtime, we're backwards compatible with @azure/core-tracing@preview.13 and earlier. + httpRequest.spanOptions = options.spanOptions; + } + if (options.tracingContext) { + httpRequest.tracingContext = options.tracingContext; + } + if (options.shouldDeserialize !== undefined && options.shouldDeserialize !== null) { + httpRequest.shouldDeserialize = options.shouldDeserialize; + } + } + httpRequest.withCredentials = this._withCredentials; + serializeRequestBody(this, httpRequest, operationArguments, operationSpec); + if (httpRequest.streamResponseStatusCodes === undefined) { + httpRequest.streamResponseStatusCodes = getStreamResponseStatusCodes(operationSpec); + } + let rawResponse; + let sendRequestError; + try { + rawResponse = await this.sendRequest(httpRequest); + } + catch (error) { + sendRequestError = error; + } + if (sendRequestError) { + if (sendRequestError.response) { + sendRequestError.details = flattenResponse(sendRequestError.response, operationSpec.responses[sendRequestError.statusCode] || + operationSpec.responses["default"]); + } + result = Promise.reject(sendRequestError); + } + else { + result = Promise.resolve(flattenResponse(rawResponse, operationSpec.responses[rawResponse.status])); + } + } + catch (error) { + result = Promise.reject(error); + } + const cb = callback; + if (cb) { + result + .then((res) => cb(null, res._response.parsedBody, res._response.request, res._response)) + .catch((err) => cb(err)); + } + return result; + } +} 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 = { + const serializerOptions = (_b = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions) !== null && _b !== void 0 ? _b : {}; + const 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; + const xmlCharKey = serializerOptions.xmlCharKey; if (operationSpec.requestBody && operationSpec.requestBody.mapper) { httpRequest.body = getOperationArgumentValueFromParameter(serviceClient, operationArguments, operationSpec.requestBody, operationSpec.serializer); - var bodyMapper = operationSpec.requestBody.mapper; - var required = bodyMapper.required, xmlName = bodyMapper.xmlName, xmlElementName = bodyMapper.xmlElementName, serializedName = bodyMapper.serializedName, xmlNamespace = bodyMapper.xmlNamespace, xmlNamespacePrefix = bodyMapper.xmlNamespacePrefix; - var typeName = bodyMapper.type.name; + const bodyMapper = operationSpec.requestBody.mapper; + const { required, xmlName, xmlElementName, serializedName, xmlNamespace, xmlNamespacePrefix } = bodyMapper; + const typeName = bodyMapper.type.name; try { if ((httpRequest.body !== undefined && httpRequest.body !== null) || required) { - var requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody); + const requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody); httpRequest.body = operationSpec.serializer.serialize(bodyMapper, httpRequest.body, requestBodyParameterPathString, updatedOptions); - var isStream = typeName === MapperType.Stream; + const isStream = typeName === MapperType.Stream; if (operationSpec.isXML) { - var xmlnsKey = xmlNamespacePrefix ? "xmlns:" + xmlNamespacePrefix : "xmlns"; - var value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, httpRequest.body, updatedOptions); + const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns"; + const value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, httpRequest.body, updatedOptions); if (typeName === MapperType.Sequence) { httpRequest.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName, - xmlCharKey: xmlCharKey + xmlCharKey }); } else if (!isStream) { httpRequest.body = stringifyXML(value, { rootName: xmlName || serializedName, - xmlCharKey: xmlCharKey + xmlCharKey }); } } @@ -60134,16 +55860,15 @@ function serializeRequestBody(serviceClient, httpRequest, operationArguments, op } } catch (error) { - throw new Error("Error \"" + error.message + "\" occurred in serializing the payload - " + JSON.stringify(serializedName, undefined, " ") + "."); + throw new Error(`Error "${error.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, undefined, " ")}.`); } } 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]; - var formDataParameterValue = getOperationArgumentValueFromParameter(serviceClient, operationArguments, formDataParameter, operationSpec.serializer); + for (const formDataParameter of operationSpec.formDataParameters) { + const formDataParameterValue = getOperationArgumentValueFromParameter(serviceClient, operationArguments, formDataParameter, operationSpec.serializer); if (formDataParameterValue !== undefined && formDataParameterValue !== null) { - var formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter); + const formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter); httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter), updatedOptions); } } @@ -60153,19 +55878,18 @@ 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) { - 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 = {}; + const result = {}; result[options.xmlCharKey] = serializedValue; - result[XML_ATTRKEY] = (_a = {}, _a[xmlnsKey] = xmlNamespace, _a); + result[XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace }; return result; } return serializedValue; } function getValueOrFunctionResult(value, defaultValueCreator) { - var result; + let result; if (typeof value === "string") { result = value; } @@ -60178,15 +55902,15 @@ function getValueOrFunctionResult(value, defaultValueCreator) { return result; } function createDefaultRequestPolicyFactories(authPolicyFactory, options) { - var factories = []; + const factories = []; if (options.generateClientRequestIdHeader) { factories.push(generateClientRequestIdPolicy(options.clientRequestIdHeaderName)); } if (authPolicyFactory) { factories.push(authPolicyFactory); } - var userAgentHeaderName = getValueOrFunctionResult(options.userAgentHeaderName, getDefaultUserAgentHeaderName); - var userAgentHeaderValue = getValueOrFunctionResult(options.userAgent, getDefaultUserAgentValue); + const userAgentHeaderName = getValueOrFunctionResult(options.userAgentHeaderName, getDefaultUserAgentHeaderName); + const userAgentHeaderValue = getValueOrFunctionResult(options.userAgent, getDefaultUserAgentValue); if (userAgentHeaderName && userAgentHeaderValue) { factories.push(userAgentPolicy({ key: userAgentHeaderName, value: userAgentHeaderValue })); } @@ -60198,37 +55922,37 @@ function createDefaultRequestPolicyFactories(authPolicyFactory, options) { factories.push(throttlingRetryPolicy()); } factories.push(deserializationPolicy(options.deserializationContentTypes)); - { + if (isNode) { factories.push(proxyPolicy(options.proxySettings)); } factories.push(logPolicy({ logger: logger.info })); return factories; } function createPipelineFromOptions(pipelineOptions, authPolicyFactory) { - var requestPolicyFactories = []; + const requestPolicyFactories = []; if (pipelineOptions.sendStreamingJson) { requestPolicyFactories.push(ndJsonPolicy()); } - var userAgentValue = undefined; + let userAgentValue = undefined; if (pipelineOptions.userAgentOptions && pipelineOptions.userAgentOptions.userAgentPrefix) { - var userAgentInfo = []; + const userAgentInfo = []; userAgentInfo.push(pipelineOptions.userAgentOptions.userAgentPrefix); // Add the default user agent value if it isn't already specified // by the userAgentPrefix option. - var defaultUserAgentInfo = getDefaultUserAgentValue(); + const defaultUserAgentInfo = getDefaultUserAgentValue(); if (userAgentInfo.indexOf(defaultUserAgentInfo) === -1) { userAgentInfo.push(defaultUserAgentInfo); } userAgentValue = userAgentInfo.join(" "); } - var keepAliveOptions = tslib.__assign(tslib.__assign({}, DefaultKeepAliveOptions), pipelineOptions.keepAliveOptions); - var retryOptions = tslib.__assign(tslib.__assign({}, DefaultRetryOptions), pipelineOptions.retryOptions); - var redirectOptions = tslib.__assign(tslib.__assign({}, DefaultRedirectOptions), pipelineOptions.redirectOptions); - { + const keepAliveOptions = Object.assign(Object.assign({}, DefaultKeepAliveOptions), pipelineOptions.keepAliveOptions); + const retryOptions = Object.assign(Object.assign({}, DefaultRetryOptions), pipelineOptions.retryOptions); + const redirectOptions = Object.assign(Object.assign({}, DefaultRedirectOptions), pipelineOptions.redirectOptions); + if (isNode) { requestPolicyFactories.push(proxyPolicy(pipelineOptions.proxyOptions)); } - var deserializationOptions = tslib.__assign(tslib.__assign({}, DefaultDeserializationOptions), pipelineOptions.deserializationOptions); - var loggingOptions = tslib.__assign({}, pipelineOptions.loggingOptions); + const deserializationOptions = Object.assign(Object.assign({}, DefaultDeserializationOptions), pipelineOptions.deserializationOptions); + const loggingOptions = Object.assign({}, pipelineOptions.loggingOptions); requestPolicyFactories.push(tracingPolicy({ userAgent: userAgentValue }), keepAlivePolicy(keepAliveOptions), userAgentPolicy({ value: userAgentValue }), generateClientRequestIdPolicy(), deserializationPolicy(deserializationOptions.expectedContentTypes), throttlingRetryPolicy(), systemErrorRetryPolicy(), exponentialRetryPolicy(retryOptions.maxRetries, retryOptions.retryDelayInMs, retryOptions.maxRetryDelayInMs)); if (redirectOptions.handleRedirects) { requestPolicyFactories.push(redirectPolicy(redirectOptions.maxRetries)); @@ -60242,7 +55966,7 @@ function createPipelineFromOptions(pipelineOptions, authPolicyFactory) { } return { httpClient: pipelineOptions.httpClient, - requestPolicyFactories: requestPolicyFactories + requestPolicyFactories }; } function getOperationArgumentValueFromParameter(serviceClient, operationArguments, parameter, serializer) { @@ -60250,22 +55974,22 @@ function getOperationArgumentValueFromParameter(serviceClient, operationArgument } function getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, serializer) { var _a; - var value; + let value; if (typeof parameterPath === "string") { parameterPath = [parameterPath]; } - var serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; + const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; if (Array.isArray(parameterPath)) { if (parameterPath.length > 0) { if (parameterMapper.isConstant) { value = parameterMapper.defaultValue; } else { - var propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath); + let propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath); if (!propertySearchResult.propertyFound) { propertySearchResult = getPropertyFromParameterPath(serviceClient, parameterPath); } - var useDefaultValue = false; + let useDefaultValue = false; if (!propertySearchResult.propertyFound) { useDefaultValue = parameterMapper.required || @@ -60274,7 +55998,7 @@ function getOperationArgumentValueFromParameterPath(serviceClient, operationArgu value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue; } // Serialize just for validation purposes. - var parameterPathString = getPathStringFromParameterPath(parameterPath, parameterMapper); + const parameterPathString = getPathStringFromParameterPath(parameterPath, parameterMapper); serializer.serialize(parameterMapper, value, parameterPathString, serializerOptions); } } @@ -60282,12 +56006,12 @@ function getOperationArgumentValueFromParameterPath(serviceClient, operationArgu if (parameterMapper.required) { value = {}; } - for (var propertyName in parameterPath) { - var propertyMapper = parameterMapper.type.modelProperties[propertyName]; - var propertyPath = parameterPath[propertyName]; - var propertyValue = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, propertyPath, propertyMapper, serializer); + for (const propertyName in parameterPath) { + const propertyMapper = parameterMapper.type.modelProperties[propertyName]; + const propertyPath = parameterPath[propertyName]; + const propertyValue = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, propertyPath, propertyMapper, serializer); // Serialize just for validation purposes. - var propertyPathString = getPathStringFromParameterPath(propertyPath, propertyMapper); + const propertyPathString = getPathStringFromParameterPath(propertyPath, propertyMapper); serializer.serialize(propertyMapper, propertyValue, propertyPathString, serializerOptions); if (propertyValue !== undefined && propertyValue !== null) { if (!value) { @@ -60300,10 +56024,10 @@ function getOperationArgumentValueFromParameterPath(serviceClient, operationArgu return value; } function getPropertyFromParameterPath(parent, parameterPath) { - var result = { propertyFound: false }; - var i = 0; + const result = { propertyFound: false }; + let i = 0; for (; i < parameterPath.length; ++i) { - var parameterPathPart = parameterPath[i]; + const parameterPathPart = parameterPath[i]; // Make sure to check inherited properties too, so don't use hasOwnProperty(). if (parent !== undefined && parent !== null && parameterPathPart in parent) { parent = parent[parameterPathPart]; @@ -60319,31 +56043,29 @@ function getPropertyFromParameterPath(parent, parameterPath) { return result; } function flattenResponse(_response, responseSpec) { - var parsedHeaders = _response.parsedHeaders; - var bodyMapper = responseSpec && responseSpec.bodyMapper; - var addOperationResponse = function (obj) { + const parsedHeaders = _response.parsedHeaders; + const bodyMapper = responseSpec && responseSpec.bodyMapper; + const addOperationResponse = (obj) => { return Object.defineProperty(obj, "_response", { value: _response }); }; if (bodyMapper) { - var typeName = bodyMapper.type.name; + const typeName = bodyMapper.type.name; if (typeName === "Stream") { - return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), { blobBody: _response.blobBody, readableStreamBody: _response.readableStreamBody })); + return addOperationResponse(Object.assign(Object.assign({}, parsedHeaders), { blobBody: _response.blobBody, readableStreamBody: _response.readableStreamBody })); } - var modelProperties_1 = (typeName === "Composite" && bodyMapper.type.modelProperties) || {}; - var isPageableResponse = Object.keys(modelProperties_1).some(function (k) { return modelProperties_1[k].serializedName === ""; }); + const modelProperties = (typeName === "Composite" && bodyMapper.type.modelProperties) || {}; + const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === ""); if (typeName === "Sequence" || isPageableResponse) { - var arrayResponse = tslib.__spreadArray([], (_response.parsedBody || [])); - for (var _i = 0, _a = Object.keys(modelProperties_1); _i < _a.length; _i++) { - var key = _a[_i]; - if (modelProperties_1[key].serializedName) { + const arrayResponse = [...(_response.parsedBody || [])]; + for (const key of Object.keys(modelProperties)) { + if (modelProperties[key].serializedName) { arrayResponse[key] = _response.parsedBody[key]; } } if (parsedHeaders) { - for (var _b = 0, _c = Object.keys(parsedHeaders); _b < _c.length; _b++) { - var key = _c[_b]; + for (const key of Object.keys(parsedHeaders)) { arrayResponse[key] = parsedHeaders[key]; } } @@ -60351,26 +56073,26 @@ function flattenResponse(_response, responseSpec) { return arrayResponse; } if (typeName === "Composite" || typeName === "Dictionary") { - return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), _response.parsedBody)); + return addOperationResponse(Object.assign(Object.assign({}, parsedHeaders), _response.parsedBody)); } } if (bodyMapper || _response.request.method === "HEAD" || isPrimitiveType(_response.parsedBody)) { // primitive body types and HEAD booleans - return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), { body: _response.parsedBody })); + return addOperationResponse(Object.assign(Object.assign({}, parsedHeaders), { body: _response.parsedBody })); } - return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), _response.parsedBody)); + return addOperationResponse(Object.assign(Object.assign({}, parsedHeaders), _response.parsedBody)); } function getCredentialScopes(options, baseUri) { if (options === null || options === void 0 ? void 0 : options.credentialScopes) { - var scopes = options.credentialScopes; + const scopes = options.credentialScopes; return Array.isArray(scopes) - ? scopes.map(function (scope) { return new url.URL(scope).toString(); }) + ? scopes.map((scope) => new url.URL(scope).toString()) : new url.URL(scopes).toString(); } if (baseUri) { - return baseUri + "/.default"; + return `${baseUri}/.default`; } return undefined; } @@ -60394,7 +56116,7 @@ function createSpanFunction(args) { /** * Defines the default token refresh buffer duration. */ -var TokenRefreshBufferMs = 2 * 60 * 1000; // 2 Minutes +const TokenRefreshBufferMs = 2 * 60 * 1000; // 2 Minutes /** * Provides an {@link AccessTokenCache} implementation which clears * the cached {@link AccessToken}'s after the expiresOnTimestamp has @@ -60402,38 +56124,36 @@ var TokenRefreshBufferMs = 2 * 60 * 1000; // 2 Minutes * * @deprecated No longer used in the bearer authorization policy. */ -var ExpiringAccessTokenCache = /** @class */ (function () { +class ExpiringAccessTokenCache { /** * Constructs an instance of {@link ExpiringAccessTokenCache} with * an optional expiration buffer time. */ - function ExpiringAccessTokenCache(tokenRefreshBufferMs) { - if (tokenRefreshBufferMs === void 0) { tokenRefreshBufferMs = TokenRefreshBufferMs; } + constructor(tokenRefreshBufferMs = TokenRefreshBufferMs) { this.cachedToken = undefined; this.tokenRefreshBufferMs = tokenRefreshBufferMs; } - ExpiringAccessTokenCache.prototype.setCachedToken = function (accessToken) { + setCachedToken(accessToken) { this.cachedToken = accessToken; - }; - ExpiringAccessTokenCache.prototype.getCachedToken = function () { + } + getCachedToken() { if (this.cachedToken && Date.now() + this.tokenRefreshBufferMs >= this.cachedToken.expiresOnTimestamp) { this.cachedToken = undefined; } return this.cachedToken; - }; - return ExpiringAccessTokenCache; -}()); + } +} // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** * Helps the core-http token authentication policies with requesting a new token if we're not currently waiting for a new token. * * @deprecated No longer used in the bearer authorization policy. */ -var AccessTokenRefresher = /** @class */ (function () { - function AccessTokenRefresher(credential, scopes, requiredMillisecondsBeforeNewRefresh) { - if (requiredMillisecondsBeforeNewRefresh === void 0) { requiredMillisecondsBeforeNewRefresh = 30000; } +class AccessTokenRefresher { + constructor(credential, scopes, requiredMillisecondsBeforeNewRefresh = 30000) { this.credential = credential; this.scopes = scopes; this.requiredMillisecondsBeforeNewRefresh = requiredMillisecondsBeforeNewRefresh; @@ -60443,49 +56163,38 @@ 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. */ - AccessTokenRefresher.prototype.isReady = function () { + isReady() { // We're only ready for a new refresh if the required milliseconds have passed. return (!this.lastCalled || Date.now() - this.lastCalled > this.requiredMillisecondsBeforeNewRefresh); - }; + } /** * Stores the time in which it is called, * then requests a new token, * then sets this.promise to undefined, * then returns the token. */ - AccessTokenRefresher.prototype.getToken = function (options) { - return tslib.__awaiter(this, void 0, void 0, function () { - var token; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - this.lastCalled = Date.now(); - return [4 /*yield*/, this.credential.getToken(this.scopes, options)]; - case 1: - token = _a.sent(); - this.promise = undefined; - return [2 /*return*/, token || undefined]; - } - }); - }); - }; + async getToken(options) { + this.lastCalled = Date.now(); + const token = await this.credential.getToken(this.scopes, options); + this.promise = undefined; + return token || undefined; + } /** * 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. */ - AccessTokenRefresher.prototype.refresh = function (options) { + refresh(options) { if (!this.promise) { this.promise = this.getToken(options); } return this.promise; - }; - return AccessTokenRefresher; -}()); + } +} // Copyright (c) Microsoft Corporation. -var HeaderConstants = Constants.HeaderConstants; -var DEFAULT_AUTHORIZATION_SCHEME = "Basic"; -var BasicAuthenticationCredentials = /** @class */ (function () { +const HeaderConstants = Constants.HeaderConstants; +const DEFAULT_AUTHORIZATION_SCHEME = "Basic"; +class BasicAuthenticationCredentials { /** * Creates a new BasicAuthenticationCredentials object. * @@ -60493,8 +56202,7 @@ var BasicAuthenticationCredentials = /** @class */ (function () { * @param password - Password. * @param authorizationScheme - The authorization scheme. */ - function BasicAuthenticationCredentials(userName, password, authorizationScheme) { - if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME; } + constructor(userName, password, authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME) { this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME; if (userName === null || userName === undefined || typeof userName.valueOf() !== "string") { throw new Error("userName cannot be null or undefined and must be of type string."); @@ -60512,28 +56220,27 @@ var BasicAuthenticationCredentials = /** @class */ (function () { * @param webResource - The WebResourceLike to be signed. * @returns The signed request object. */ - BasicAuthenticationCredentials.prototype.signRequest = function (webResource) { - var credentials = this.userName + ":" + this.password; - var encodedCredentials = this.authorizationScheme + " " + encodeString(credentials); + signRequest(webResource) { + const credentials = `${this.userName}:${this.password}`; + const encodedCredentials = `${this.authorizationScheme} ${encodeString(credentials)}`; if (!webResource.headers) webResource.headers = new HttpHeaders(); webResource.headers.set(HeaderConstants.AUTHORIZATION, encodedCredentials); return Promise.resolve(webResource); - }; - return BasicAuthenticationCredentials; -}()); + } +} // Copyright (c) Microsoft Corporation. /** * Authenticates to a service using an API key. */ -var ApiKeyCredentials = /** @class */ (function () { +class ApiKeyCredentials { /** * @param options - Specifies the options to be provided for auth. Either header or query needs to be provided. */ - function ApiKeyCredentials(options) { + constructor(options) { if (!options || (options && !options.inHeader && !options.inQuery)) { - throw new Error("options cannot be null or undefined. Either \"inHeader\" or \"inQuery\" property of the options object needs to be provided."); + throw new Error(`options cannot be null or undefined. Either "inHeader" or "inQuery" property of the options object needs to be provided.`); } this.inHeader = options.inHeader; this.inQuery = options.inQuery; @@ -60544,60 +56251,55 @@ var ApiKeyCredentials = /** @class */ (function () { * @param webResource - The WebResourceLike to be signed. * @returns The signed request object. */ - ApiKeyCredentials.prototype.signRequest = function (webResource) { + signRequest(webResource) { if (!webResource) { - return Promise.reject(new Error("webResource cannot be null or undefined and must be of type \"object\".")); + return Promise.reject(new Error(`webResource cannot be null or undefined and must be of type "object".`)); } if (this.inHeader) { if (!webResource.headers) { webResource.headers = new HttpHeaders(); } - for (var headerName in this.inHeader) { + for (const headerName in this.inHeader) { webResource.headers.set(headerName, this.inHeader[headerName]); } } if (this.inQuery) { if (!webResource.url) { - return Promise.reject(new Error("url cannot be null in the request object.")); + return Promise.reject(new Error(`url cannot be null in the request object.`)); } if (webResource.url.indexOf("?") < 0) { webResource.url += "?"; } - for (var key in this.inQuery) { + for (const key in this.inQuery) { if (!webResource.url.endsWith("?")) { webResource.url += "&"; } - webResource.url += key + "=" + this.inQuery[key]; + webResource.url += `${key}=${this.inQuery[key]}`; } } return Promise.resolve(webResource); - }; - return ApiKeyCredentials; -}()); + } +} // Copyright (c) Microsoft Corporation. -var TopicCredentials = /** @class */ (function (_super) { - tslib.__extends(TopicCredentials, _super); +class TopicCredentials extends ApiKeyCredentials { /** * Creates a new EventGrid TopicCredentials object. * * @param topicKey - The EventGrid topic key */ - function TopicCredentials(topicKey) { - var _this = this; + constructor(topicKey) { if (!topicKey || (topicKey && typeof topicKey !== "string")) { throw new Error("topicKey cannot be null or undefined and must be of type string."); } - var options = { + const options = { inHeader: { "aeg-sas-key": topicKey } }; - _this = _super.call(this, options) || this; - return _this; + super(options); } - return TopicCredentials; -}(ApiKeyCredentials)); +} Object.defineProperty(exports, 'isTokenCredential', { enumerable: true, diff --git a/dist/setup/index.js b/dist/setup/index.js index 7e637f09..1dc2f2f5 100644 --- a/dist/setup/index.js +++ b/dist/setup/index.js @@ -1280,10 +1280,10 @@ function createTempDirectory() { }); } exports.createTempDirectory = createTempDirectory; -function getArchiveFileSizeIsBytes(filePath) { +function getArchiveFileSizeInBytes(filePath) { return fs.statSync(filePath).size; } -exports.getArchiveFileSizeIsBytes = getArchiveFileSizeIsBytes; +exports.getArchiveFileSizeInBytes = getArchiveFileSizeInBytes; function resolvePaths(patterns) { var e_1, _a; var _b; @@ -1506,7 +1506,8 @@ exports.checkBypass = checkBypass; /***/ }), -/* 21 */ +/* 21 */, +/* 22 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; @@ -1528,16 +1529,24 @@ exports.checkBypass = checkBypass; */ Object.defineProperty(exports, "__esModule", { value: true }); exports.PropagationAPI = void 0; +var global_utils_1 = __webpack_require__(525); var NoopTextMapPropagator_1 = __webpack_require__(918); var TextMapPropagator_1 = __webpack_require__(875); -var global_utils_1 = __webpack_require__(525); +var context_helpers_1 = __webpack_require__(483); +var utils_1 = __webpack_require__(112); +var diag_1 = __webpack_require__(387); var API_NAME = 'propagation'; +var NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); /** * Singleton object which represents the entry point to the OpenTelemetry Propagation API */ var PropagationAPI = /** @class */ (function () { /** Empty private constructor prevents end users from constructing a new instance of the API */ function PropagationAPI() { + this.createBaggage = utils_1.createBaggage; + this.getBaggage = context_helpers_1.getBaggage; + this.setBaggage = context_helpers_1.setBaggage; + this.deleteBaggage = context_helpers_1.deleteBaggage; } /** Get the singleton instance of the Propagator API */ PropagationAPI.getInstance = function () { @@ -1547,11 +1556,12 @@ var PropagationAPI = /** @class */ (function () { return this._instance; }; /** - * Set the current propagator. Returns the initialized propagator + * Set the current propagator. + * + * @returns true if the propagator was successfully registered, else false */ PropagationAPI.prototype.setGlobalPropagator = function (propagator) { - global_utils_1.registerGlobal(API_NAME, propagator); - return propagator; + return global_utils_1.registerGlobal(API_NAME, propagator, diag_1.DiagAPI.instance()); }; /** * Inject context into a carrier to be propagated inter-process @@ -1583,560 +1593,16 @@ var PropagationAPI = /** @class */ (function () { }; /** Remove the global propagator */ PropagationAPI.prototype.disable = function () { - global_utils_1.unregisterGlobal(API_NAME); + global_utils_1.unregisterGlobal(API_NAME, diag_1.DiagAPI.instance()); }; PropagationAPI.prototype._getGlobalPropagator = function () { - return global_utils_1.getGlobal(API_NAME) || NoopTextMapPropagator_1.NOOP_TEXT_MAP_PROPAGATOR; + return global_utils_1.getGlobal(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; }; return PropagationAPI; }()); exports.PropagationAPI = PropagationAPI; //# sourceMappingURL=propagation.js.map -/***/ }), -/* 22 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -const http = __webpack_require__(605); -const https = __webpack_require__(211); -const pm = __webpack_require__(618); -let tunnel; -var HttpCodes; -(function (HttpCodes) { - HttpCodes[HttpCodes["OK"] = 200] = "OK"; - HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; - HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; - HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; - HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; - HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; - HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; - HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; - HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; - HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; - HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); -var Headers; -(function (Headers) { - Headers["Accept"] = "accept"; - Headers["ContentType"] = "content-type"; -})(Headers = exports.Headers || (exports.Headers = {})); -var MediaTypes; -(function (MediaTypes) { - MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); -/** - * Returns the proxy URL, depending upon the supplied url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ -function getProxyUrl(serverUrl) { - let proxyUrl = pm.getProxyUrl(new URL(serverUrl)); - return proxyUrl ? proxyUrl.href : ''; -} -exports.getProxyUrl = getProxyUrl; -const HttpRedirectCodes = [ - HttpCodes.MovedPermanently, - HttpCodes.ResourceMoved, - HttpCodes.SeeOther, - HttpCodes.TemporaryRedirect, - HttpCodes.PermanentRedirect -]; -const HttpResponseRetryCodes = [ - HttpCodes.BadGateway, - HttpCodes.ServiceUnavailable, - HttpCodes.GatewayTimeout -]; -const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; -const ExponentialBackoffCeiling = 10; -const ExponentialBackoffTimeSlice = 5; -class HttpClientError extends Error { - constructor(message, statusCode) { - super(message); - this.name = 'HttpClientError'; - this.statusCode = statusCode; - Object.setPrototypeOf(this, HttpClientError.prototype); - } -} -exports.HttpClientError = HttpClientError; -class HttpClientResponse { - constructor(message) { - this.message = message; - } - readBody() { - return new Promise(async (resolve, reject) => { - let output = Buffer.alloc(0); - this.message.on('data', (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on('end', () => { - resolve(output.toString()); - }); - }); - } -} -exports.HttpClientResponse = HttpClientResponse; -function isHttps(requestUrl) { - let parsedUrl = new URL(requestUrl); - return parsedUrl.protocol === 'https:'; -} -exports.isHttps = isHttps; -class HttpClient { - constructor(userAgent, handlers, requestOptions) { - this._ignoreSslError = false; - this._allowRedirects = true; - this._allowRedirectDowngrade = false; - this._maxRedirects = 50; - this._allowRetries = false; - this._maxRetries = 1; - this._keepAlive = false; - this._disposed = false; - this.userAgent = userAgent; - this.handlers = handlers || []; - this.requestOptions = requestOptions; - if (requestOptions) { - if (requestOptions.ignoreSslError != null) { - this._ignoreSslError = requestOptions.ignoreSslError; - } - this._socketTimeout = requestOptions.socketTimeout; - if (requestOptions.allowRedirects != null) { - this._allowRedirects = requestOptions.allowRedirects; - } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; - } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); - } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; - } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; - } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; - } - } - } - options(requestUrl, additionalHeaders) { - return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); - } - get(requestUrl, additionalHeaders) { - return this.request('GET', requestUrl, null, additionalHeaders || {}); - } - del(requestUrl, additionalHeaders) { - return this.request('DELETE', requestUrl, null, additionalHeaders || {}); - } - post(requestUrl, data, additionalHeaders) { - return this.request('POST', requestUrl, data, additionalHeaders || {}); - } - patch(requestUrl, data, additionalHeaders) { - return this.request('PATCH', requestUrl, data, additionalHeaders || {}); - } - put(requestUrl, data, additionalHeaders) { - return this.request('PUT', requestUrl, data, additionalHeaders || {}); - } - head(requestUrl, additionalHeaders) { - return this.request('HEAD', requestUrl, null, additionalHeaders || {}); - } - sendStream(verb, requestUrl, stream, additionalHeaders) { - return this.request(verb, requestUrl, stream, additionalHeaders); - } - /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise - */ - async getJson(requestUrl, additionalHeaders = {}) { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - let res = await this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async postJson(requestUrl, obj, additionalHeaders = {}) { - let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - let res = await this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async putJson(requestUrl, obj, additionalHeaders = {}) { - let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - let res = await this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - async patchJson(requestUrl, obj, additionalHeaders = {}) { - let data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - let res = await this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - } - /** - * Makes a raw http request. - * All other methods such as get, post, patch, and request ultimately call this. - * Prefer get, del, post and patch - */ - async request(verb, requestUrl, data, headers) { - if (this._disposed) { - throw new Error('Client has already been disposed.'); - } - let parsedUrl = new URL(requestUrl); - let info = this._prepareRequest(verb, parsedUrl, headers); - // Only perform retries on reads since writes may not be idempotent. - let maxTries = this._allowRetries && RetryableHttpVerbs.indexOf(verb) != -1 - ? this._maxRetries + 1 - : 1; - let numTries = 0; - let response; - while (numTries < maxTries) { - response = await this.requestRaw(info, data); - // Check if it's an authentication challenge - if (response && - response.message && - response.message.statusCode === HttpCodes.Unauthorized) { - let authenticationHandler; - for (let i = 0; i < this.handlers.length; i++) { - if (this.handlers[i].canHandleAuthentication(response)) { - authenticationHandler = this.handlers[i]; - break; - } - } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info, data); - } - else { - // We have received an unauthorized response but have no handlers to handle it. - // Let the response return to the caller. - return response; - } - } - let redirectsRemaining = this._maxRedirects; - while (HttpRedirectCodes.indexOf(response.message.statusCode) != -1 && - this._allowRedirects && - redirectsRemaining > 0) { - const redirectUrl = response.message.headers['location']; - if (!redirectUrl) { - // if there's no location to redirect to, we won't - break; - } - let parsedRedirectUrl = new URL(redirectUrl); - if (parsedUrl.protocol == 'https:' && - parsedUrl.protocol != parsedRedirectUrl.protocol && - !this._allowRedirectDowngrade) { - throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); - } - // we need to finish reading the response before reassigning response - // which will leak the open socket. - await response.readBody(); - // strip authorization header if redirected to a different hostname - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (let header in headers) { - // header names are case insensitive - if (header.toLowerCase() === 'authorization') { - delete headers[header]; - } - } - } - // let's make the request with the new redirectUrl - info = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = await this.requestRaw(info, data); - redirectsRemaining--; - } - if (HttpResponseRetryCodes.indexOf(response.message.statusCode) == -1) { - // If not a retry code, return immediately instead of retrying - return response; - } - numTries += 1; - if (numTries < maxTries) { - await response.readBody(); - await this._performExponentialBackoff(numTries); - } - } - return response; - } - /** - * Needs to be called if keepAlive is set to true in request options. - */ - dispose() { - if (this._agent) { - this._agent.destroy(); - } - this._disposed = true; - } - /** - * Raw request. - * @param info - * @param data - */ - requestRaw(info, data) { - return new Promise((resolve, reject) => { - let callbackForResult = function (err, res) { - if (err) { - reject(err); - } - resolve(res); - }; - this.requestRawWithCallback(info, data, callbackForResult); - }); - } - /** - * Raw request with callback. - * @param info - * @param data - * @param onResult - */ - requestRawWithCallback(info, data, onResult) { - let socket; - if (typeof data === 'string') { - info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); - } - let callbackCalled = false; - let handleResult = (err, res) => { - if (!callbackCalled) { - callbackCalled = true; - onResult(err, res); - } - }; - let req = info.httpModule.request(info.options, (msg) => { - let res = new HttpClientResponse(msg); - handleResult(null, res); - }); - req.on('socket', sock => { - socket = sock; - }); - // If we ever get disconnected, we want the socket to timeout eventually - req.setTimeout(this._socketTimeout || 3 * 60000, () => { - if (socket) { - socket.end(); - } - handleResult(new Error('Request timeout: ' + info.options.path), null); - }); - req.on('error', function (err) { - // err has statusCode property - // res should have headers - handleResult(err, null); - }); - if (data && typeof data === 'string') { - req.write(data, 'utf8'); - } - if (data && typeof data !== 'string') { - data.on('close', function () { - req.end(); - }); - data.pipe(req); - } - else { - req.end(); - } - } - /** - * Gets an http agent. This function is useful when you need an http agent that handles - * routing through a proxy server - depending upon the url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ - getAgent(serverUrl) { - let parsedUrl = new URL(serverUrl); - return this._getAgent(parsedUrl); - } - _prepareRequest(method, requestUrl, headers) { - const info = {}; - info.parsedUrl = requestUrl; - const usingSsl = info.parsedUrl.protocol === 'https:'; - info.httpModule = usingSsl ? https : http; - const defaultPort = usingSsl ? 443 : 80; - info.options = {}; - info.options.host = info.parsedUrl.hostname; - info.options.port = info.parsedUrl.port - ? parseInt(info.parsedUrl.port) - : defaultPort; - info.options.path = - (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); - info.options.method = method; - info.options.headers = this._mergeHeaders(headers); - if (this.userAgent != null) { - info.options.headers['user-agent'] = this.userAgent; - } - info.options.agent = this._getAgent(info.parsedUrl); - // gives handlers an opportunity to participate - if (this.handlers) { - this.handlers.forEach(handler => { - handler.prepareRequest(info.options); - }); - } - return info; - } - _mergeHeaders(headers) { - const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); - if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers)); - } - return lowercaseKeys(headers || {}); - } - _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - const lowercaseKeys = obj => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; - } - return additionalHeaders[header] || clientHeader || _default; - } - _getAgent(parsedUrl) { - let agent; - let proxyUrl = pm.getProxyUrl(parsedUrl); - let useProxy = proxyUrl && proxyUrl.hostname; - if (this._keepAlive && useProxy) { - agent = this._proxyAgent; - } - if (this._keepAlive && !useProxy) { - agent = this._agent; - } - // if agent is already assigned use that agent. - if (!!agent) { - return agent; - } - const usingSsl = parsedUrl.protocol === 'https:'; - let maxSockets = 100; - if (!!this.requestOptions) { - maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; - } - if (useProxy) { - // If using proxy, need tunnel - if (!tunnel) { - tunnel = __webpack_require__(413); - } - const agentOptions = { - maxSockets: maxSockets, - keepAlive: this._keepAlive, - proxy: { - ...((proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - }), - host: proxyUrl.hostname, - port: proxyUrl.port - } - }; - let tunnelAgent; - const overHttps = proxyUrl.protocol === 'https:'; - if (usingSsl) { - tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; - } - else { - tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; - } - agent = tunnelAgent(agentOptions); - this._proxyAgent = agent; - } - // if reusing agent across request and tunneling agent isn't assigned create a new agent - if (this._keepAlive && !agent) { - const options = { keepAlive: this._keepAlive, maxSockets: maxSockets }; - agent = usingSsl ? new https.Agent(options) : new http.Agent(options); - this._agent = agent; - } - // if not using private agent and tunnel agent isn't setup then use global agent - if (!agent) { - agent = usingSsl ? https.globalAgent : http.globalAgent; - } - if (usingSsl && this._ignoreSslError) { - // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process - // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options - // we have to cast it to any and change it directly - agent.options = Object.assign(agent.options || {}, { - rejectUnauthorized: false - }); - } - return agent; - } - _performExponentialBackoff(retryNumber) { - retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); - const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise(resolve => setTimeout(() => resolve(), ms)); - } - static dateTimeDeserializer(key, value) { - if (typeof value === 'string') { - let a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } - } - return value; - } - async _processResponse(res, options) { - return new Promise(async (resolve, reject) => { - const statusCode = res.message.statusCode; - const response = { - statusCode: statusCode, - result: null, - headers: {} - }; - // not found leads to null obj returned - if (statusCode == HttpCodes.NotFound) { - resolve(response); - } - let obj; - let contents; - // get the result from the body - try { - contents = await res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, HttpClient.dateTimeDeserializer); - } - else { - obj = JSON.parse(contents); - } - response.result = obj; - } - response.headers = res.message.headers; - } - catch (err) { - // Invalid resource (contents not json); leaving result obj null - } - // note that 3xx redirects are handled by the http layer. - if (statusCode > 299) { - let msg; - // if exception/error in body, attempt to get better error - if (obj && obj.message) { - msg = obj.message; - } - else if (contents && contents.length > 0) { - // it may be the case that the exception is in the body message as string - msg = contents; - } - else { - msg = 'Failed request: (' + statusCode + ')'; - } - let err = new HttpClientError(msg, statusCode); - err.result = response.result; - reject(err); - } - else { - resolve(response); - } - }); - } -} -exports.HttpClient = HttpClient; - - /***/ }), /* 23 */, /* 24 */ @@ -4008,7 +3474,74 @@ module.exports = ["ac","com.ac","edu.ac","gov.ac","net.ac","mil.ac","org.ac","ad /* 51 */, /* 52 */, /* 53 */, -/* 54 */, +/* 54 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * "A request-path path-matches a given cookie-path if at least one of the + * following conditions holds:" + */ +function pathMatch(reqPath, cookiePath) { + // "o The cookie-path and the request-path are identical." + if (cookiePath === reqPath) { + return true; + } + + const idx = reqPath.indexOf(cookiePath); + if (idx === 0) { + // "o The cookie-path is a prefix of the request-path, and the last + // character of the cookie-path is %x2F ("/")." + if (cookiePath.substr(-1) === "/") { + return true; + } + + // " o The cookie-path is a prefix of the request-path, and the first + // character of the request-path that is not included in the cookie- path + // is a %x2F ("/") character." + if (reqPath.substr(cookiePath.length, 1) === "/") { + return true; + } + } + + return false; +} + +exports.pathMatch = pathMatch; + + +/***/ }), /* 55 */, /* 56 */, /* 57 */, @@ -4120,20 +3653,128 @@ Object.defineProperty(exports, "__esModule", { value: true }); //# sourceMappingURL=trace_state.js.map /***/ }), -/* 71 */ -/***/ (function() { +/* 71 */, +/* 72 */, +/* 73 */, +/* 74 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; -if (typeof Symbol === undefined || !Symbol.asyncIterator) { - Symbol.asyncIterator = Symbol.for("Symbol.asyncIterator"); +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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Path = void 0; +const path = __importStar(__webpack_require__(622)); +const pathHelper = __importStar(__webpack_require__(972)); +const assert_1 = __importDefault(__webpack_require__(357)); +const IS_WINDOWS = process.platform === 'win32'; +/** + * Helper class for parsing paths into segments + */ +class Path { + /** + * Constructs a Path + * @param itemPath Path or array of segments + */ + constructor(itemPath) { + this.segments = []; + // String + if (typeof itemPath === 'string') { + assert_1.default(itemPath, `Parameter 'itemPath' must not be empty`); + // Normalize slashes and trim unnecessary trailing slash + itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); + // Not rooted + if (!pathHelper.hasRoot(itemPath)) { + this.segments = itemPath.split(path.sep); + } + // Rooted + else { + // Add all segments, while not at the root + let remaining = itemPath; + let dir = pathHelper.dirname(remaining); + while (dir !== remaining) { + // Add the segment + const basename = path.basename(remaining); + this.segments.unshift(basename); + // Truncate the last segment + remaining = dir; + dir = pathHelper.dirname(remaining); + } + // Remainder is the root + this.segments.unshift(remaining); + } + } + // Array + else { + // Must not be empty + assert_1.default(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`); + // 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`); + 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`); + this.segments.push(segment); + } + } + } + } + /** + * Converts the path to it's string representation + */ + toString() { + // First segment + let result = this.segments[0]; + // All others + let skipSlash = result.endsWith(path.sep) || (IS_WINDOWS && /^[A-Z]:$/i.test(result)); + for (let i = 1; i < this.segments.length; i++) { + if (skipSlash) { + skipSlash = false; + } + else { + result += path.sep; + } + result += this.segments[i]; + } + return result; + } } -//# sourceMappingURL=index.js.map +exports.Path = Path; +//# sourceMappingURL=internal-path.js.map /***/ }), -/* 72 */, -/* 73 */, -/* 74 */, /* 75 */, /* 76 */, /* 77 */, @@ -5733,7 +5374,64 @@ module.exports._enoent = enoent; /* 109 */, /* 110 */, /* 111 */, -/* 112 */, +/* 112 */ +/***/ (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.baggageEntryMetadataFromString = exports.createBaggage = void 0; +var diag_1 = __webpack_require__(387); +var baggage_impl_1 = __webpack_require__(666); +var symbol_1 = __webpack_require__(561); +var diag = diag_1.DiagAPI.instance(); +/** + * Create a new Baggage with optional entries + * + * @param entries An array of baggage entries the new baggage should contain + */ +function createBaggage(entries) { + if (entries === void 0) { entries = {}; } + return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries))); +} +exports.createBaggage = createBaggage; +/** + * Create a serializable BaggageEntryMetadata object from a string. + * + * @param str string metadata. Format is currently not defined by the spec and has no special meaning. + * + */ +function baggageEntryMetadataFromString(str) { + if (typeof str !== 'string') { + diag.error("Cannot create baggage metadata from unknown type: " + typeof str); + str = ''; + } + return { + __TYPE__: symbol_1.baggageEntryMetadataSymbol, + toString: function () { + return str; + }, + }; +} +exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; +//# sourceMappingURL=utils.js.map + +/***/ }), /* 113 */, /* 114 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { @@ -5758,8 +5456,8 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); const core = __importStar(__webpack_require__(470)); -const http_client_1 = __webpack_require__(22); -const auth_1 = __webpack_require__(733); +const http_client_1 = __webpack_require__(539); +const auth_1 = __webpack_require__(226); const crypto = __importStar(__webpack_require__(417)); const fs = __importStar(__webpack_require__(747)); const url_1 = __webpack_require__(835); @@ -5894,7 +5592,7 @@ function uploadChunk(httpClient, resourceUrl, openStream, start, end) { function uploadFile(httpClient, cacheId, archivePath, options) { return __awaiter(this, void 0, void 0, function* () { // Upload Chunks - const fileSize = fs.statSync(archivePath).size; + const fileSize = utils.getArchiveFileSizeInBytes(archivePath); const resourceUrl = getCacheApiUrl(`caches/${cacheId.toString()}`); const fd = fs.openSync(archivePath, 'r'); const uploadOptions = options_1.getUploadOptions(options); @@ -5944,7 +5642,7 @@ function saveCache(cacheId, archivePath, options) { yield uploadFile(httpClient, cacheId, archivePath, options); // Commit Cache core.debug('Commiting cache'); - const cacheSize = utils.getArchiveFileSizeIsBytes(archivePath); + const cacheSize = utils.getArchiveFileSizeInBytes(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)) { @@ -7025,7 +6723,7 @@ function resolveVersionInput() { /***/ }), /* 132 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { +/***/ (function(__unusedmodule, exports) { "use strict"; @@ -7045,109 +6743,15 @@ function resolveVersionInput() { * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); -exports.ROOT_CONTEXT = exports.createContextKey = exports.setBaggage = exports.getBaggage = exports.isInstrumentationSuppressed = exports.unsuppressInstrumentation = exports.suppressInstrumentation = exports.getSpanContext = exports.setSpanContext = exports.setSpan = exports.getSpan = void 0; -var NoopSpan_1 = __webpack_require__(767); -/** - * span key - */ -var SPAN_KEY = createContextKey('OpenTelemetry Context Key SPAN'); -/** - * Shared key for indicating if instrumentation should be suppressed beyond - * this current scope. - */ -var SUPPRESS_INSTRUMENTATION_KEY = createContextKey('OpenTelemetry Context Key SUPPRESS_INSTRUMENTATION'); -/** - * Baggage key - */ -var BAGGAGE_KEY = createContextKey('OpenTelemetry Baggage Key'); -/** - * Return the span if one exists - * - * @param context context to get span from - */ -function getSpan(context) { - return context.getValue(SPAN_KEY) || undefined; -} -exports.getSpan = getSpan; -/** - * Set the span on a context - * - * @param context context to use as parent - * @param span span to set active - */ -function setSpan(context, span) { - return context.setValue(SPAN_KEY, span); -} -exports.setSpan = setSpan; -/** - * Wrap span context in a NoopSpan and set as span in a new - * context - * - * @param context context to set active span on - * @param spanContext span context to be wrapped - */ -function setSpanContext(context, spanContext) { - return setSpan(context, new NoopSpan_1.NoopSpan(spanContext)); -} -exports.setSpanContext = setSpanContext; -/** - * Get the span context of the span if it exists. - * - * @param context context to get values from - */ -function getSpanContext(context) { - var _a; - return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.context(); -} -exports.getSpanContext = getSpanContext; -/** - * Sets value on context to indicate that instrumentation should - * be suppressed beyond this current scope. - * - * @param context context to set the suppress instrumentation value on. - */ -function suppressInstrumentation(context) { - return context.setValue(SUPPRESS_INSTRUMENTATION_KEY, true); -} -exports.suppressInstrumentation = suppressInstrumentation; -/** - * Sets value on context to indicate that instrumentation should - * no-longer be suppressed beyond this current scope. - * - * @param context context to set the suppress instrumentation value on. - */ -function unsuppressInstrumentation(context) { - return context.setValue(SUPPRESS_INSTRUMENTATION_KEY, false); -} -exports.unsuppressInstrumentation = unsuppressInstrumentation; -/** - * Return current suppress instrumentation value for the given context, - * if it exists. - * - * @param context context check for the suppress instrumentation value. - */ -function isInstrumentationSuppressed(context) { - return Boolean(context.getValue(SUPPRESS_INSTRUMENTATION_KEY)); -} -exports.isInstrumentationSuppressed = isInstrumentationSuppressed; -/** - * @param {Context} Context that manage all context values - * @returns {Baggage} Extracted baggage from the context - */ -function getBaggage(context) { - return context.getValue(BAGGAGE_KEY) || undefined; -} -exports.getBaggage = getBaggage; -/** - * @param {Context} Context that manage all context values - * @param {Baggage} baggage that will be set in the actual context - */ -function setBaggage(context, baggage) { - return context.setValue(BAGGAGE_KEY, baggage); -} -exports.setBaggage = setBaggage; +exports.ROOT_CONTEXT = exports.createContextKey = void 0; /** Get a key to uniquely identify a context value */ function createContextKey(description) { + // The specification states that for the same input, multiple calls should + // return different keys. Due to the nature of the JS dependency management + // system, this creates problems where multiple versions of some package + // could hold different keys for the same property. + // + // Therefore, we use Symbol.for which returns the same key for the same input. return Symbol.for(description); } exports.createContextKey = createContextKey; @@ -7502,318 +7106,7 @@ function withAuthorizationPrefix(authorization) { /***/ }), -/* 144 */ -/***/ (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, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || from); - }; - - __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, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), 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); -}); - - -/***/ }), +/* 144 */, /* 145 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -7942,10 +7235,12 @@ function paginatePlugin(octokit) { * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); -exports.NOOP_TRACER = exports.NoopTracer = void 0; -var context_1 = __webpack_require__(132); -var NoopSpan_1 = __webpack_require__(767); +exports.NoopTracer = void 0; +var context_1 = __webpack_require__(492); +var context_utils_1 = __webpack_require__(720); +var NonRecordingSpan_1 = __webpack_require__(437); var spancontext_utils_1 = __webpack_require__(629); +var context = context_1.ContextAPI.getInstance(); /** * No-op implementations of {@link Tracer}. */ @@ -7956,17 +7251,41 @@ var NoopTracer = /** @class */ (function () { NoopTracer.prototype.startSpan = function (name, options, context) { var root = Boolean(options === null || options === void 0 ? void 0 : options.root); if (root) { - return new NoopSpan_1.NoopSpan(); + return new NonRecordingSpan_1.NonRecordingSpan(); } - var parentFromContext = context && context_1.getSpanContext(context); + var parentFromContext = context && context_utils_1.getSpanContext(context); if (isSpanContext(parentFromContext) && spancontext_utils_1.isSpanContextValid(parentFromContext)) { - return new NoopSpan_1.NoopSpan(parentFromContext); + return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext); } else { - return new NoopSpan_1.NoopSpan(); + return new NonRecordingSpan_1.NonRecordingSpan(); } }; + NoopTracer.prototype.startActiveSpan = function (name, arg2, arg3, arg4) { + var opts; + var ctx; + var fn; + if (arguments.length < 2) { + return; + } + else if (arguments.length === 2) { + fn = arg2; + } + else if (arguments.length === 3) { + opts = arg2; + fn = arg3; + } + else { + opts = arg2; + ctx = arg3; + fn = arg4; + } + var parentContext = ctx !== null && ctx !== void 0 ? ctx : context.active(); + var span = this.startSpan(name, opts, parentContext); + var contextWithSpanSet = context_utils_1.setSpan(parentContext, span); + return context.with(contextWithSpanSet, fn, undefined, span); + }; return NoopTracer; }()); exports.NoopTracer = NoopTracer; @@ -7976,7 +7295,6 @@ function isSpanContext(spanContext) { typeof spanContext['traceId'] === 'string' && typeof spanContext['traceFlags'] === 'number'); } -exports.NOOP_TRACER = new NoopTracer(); //# sourceMappingURL=NoopTracer.js.map /***/ }), @@ -8278,7 +7596,7 @@ exports.getDownloadOptions = getDownloadOptions; * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); -exports.NOOP_TRACER_PROVIDER = exports.NoopTracerProvider = void 0; +exports.NoopTracerProvider = void 0; var NoopTracer_1 = __webpack_require__(151); /** * An implementation of the {@link TracerProvider} which returns an impotent @@ -8290,12 +7608,11 @@ var NoopTracerProvider = /** @class */ (function () { function NoopTracerProvider() { } NoopTracerProvider.prototype.getTracer = function (_name, _version) { - return NoopTracer_1.NOOP_TRACER; + return new NoopTracer_1.NoopTracer(); }; return NoopTracerProvider; }()); exports.NoopTracerProvider = NoopTracerProvider; -exports.NOOP_TRACER_PROVIDER = new NoopTracerProvider(); //# sourceMappingURL=NoopTracerProvider.js.map /***/ }), @@ -8411,7 +7728,7 @@ Object.defineProperty(exports, "__esModule", { }); exports.default = void 0; -var _rng = _interopRequireDefault(__webpack_require__(944)); +var _rng = _interopRequireDefault(__webpack_require__(733)); var _stringify = _interopRequireDefault(__webpack_require__(164)); @@ -8939,7 +8256,7 @@ const pathHelper = __importStar(__webpack_require__(972)); const assert_1 = __importDefault(__webpack_require__(357)); const minimatch_1 = __webpack_require__(93); const internal_match_kind_1 = __webpack_require__(327); -const internal_path_1 = __webpack_require__(383); +const internal_path_1 = __webpack_require__(74); const IS_WINDOWS = process.platform === 'win32'; class Pattern { constructor(patternOrNegate, isImplicitPattern = false, segments, homedir) { @@ -9248,29 +8565,25 @@ Object.defineProperty(exports, '__esModule', { value: true }); * A static-key-based credential that supports updating * the underlying key value. */ -var AzureKeyCredential = /** @class */ (function () { +class AzureKeyCredential { /** * Create an instance of an AzureKeyCredential for use * with a service client. * * @param key - The initial value of the key to use in authentication */ - function AzureKeyCredential(key) { + constructor(key) { if (!key) { throw new Error("key must be a non-empty string"); } this._key = key; } - Object.defineProperty(AzureKeyCredential.prototype, "key", { - /** - * The value of the key to be used in authentication - */ - get: function () { - return this._key; - }, - enumerable: false, - configurable: true - }); + /** + * The value of the key to be used in authentication + */ + get key() { + return this._key; + } /** * Change the value of the key. * @@ -9279,11 +8592,10 @@ var AzureKeyCredential = /** @class */ (function () { * * @param newKey - The new key value to be used */ - AzureKeyCredential.prototype.update = function (newKey) { + update(newKey) { this._key = newKey; - }; - return AzureKeyCredential; -}()); + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -9306,8 +8618,7 @@ function isObjectWithProperties(thing, properties) { if (!isDefined(thing) || typeof thing !== "object") { return false; } - for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) { - var property = properties_1[_i]; + for (const property of properties) { if (!objectHasProperty(thing, property)) { return false; } @@ -9330,7 +8641,7 @@ function objectHasProperty(thing, property) { * A static name/key-based credential that supports updating * the underlying name and key values. */ -var AzureNamedKeyCredential = /** @class */ (function () { +class AzureNamedKeyCredential { /** * Create an instance of an AzureNamedKeyCredential for use * with a service client. @@ -9338,33 +8649,25 @@ var AzureNamedKeyCredential = /** @class */ (function () { * @param name - The initial value of the name to use in authentication. * @param key - The initial value of the key to use in authentication. */ - function AzureNamedKeyCredential(name, key) { + constructor(name, key) { if (!name || !key) { throw new TypeError("name and key must be non-empty strings"); } this._name = name; this._key = key; } - Object.defineProperty(AzureNamedKeyCredential.prototype, "key", { - /** - * The value of the key to be used in authentication. - */ - get: function () { - return this._key; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AzureNamedKeyCredential.prototype, "name", { - /** - * The value of the name to be used in authentication. - */ - get: function () { - return this._name; - }, - enumerable: false, - configurable: true - }); + /** + * The value of the key to be used in authentication. + */ + get key() { + return this._key; + } + /** + * The value of the name to be used in authentication. + */ + get name() { + return this._name; + } /** * Change the value of the key. * @@ -9374,15 +8677,14 @@ var AzureNamedKeyCredential = /** @class */ (function () { * @param newName - The new name value to be used. * @param newKey - The new key value to be used. */ - AzureNamedKeyCredential.prototype.update = function (newName, newKey) { + update(newName, newKey) { if (!newName || !newKey) { throw new TypeError("newName and newKey must be non-empty strings"); } this._name = newName; this._key = newKey; - }; - return AzureNamedKeyCredential; -}()); + } +} /** * Tests an object to determine whether it implements NamedKeyCredential. * @@ -9399,29 +8701,25 @@ function isNamedKeyCredential(credential) { * A static-signature-based credential that supports updating * the underlying signature value. */ -var AzureSASCredential = /** @class */ (function () { +class AzureSASCredential { /** * Create an instance of an AzureSASCredential for use * with a service client. * * @param signature - The initial value of the shared access signature to use in authentication */ - function AzureSASCredential(signature) { + constructor(signature) { if (!signature) { throw new Error("shared access signature must be a non-empty string"); } this._signature = signature; } - Object.defineProperty(AzureSASCredential.prototype, "signature", { - /** - * The value of the shared access signature to be used in authentication - */ - get: function () { - return this._signature; - }, - enumerable: false, - configurable: true - }); + /** + * The value of the shared access signature to be used in authentication + */ + get signature() { + return this._signature; + } /** * Change the value of the signature. * @@ -9430,14 +8728,13 @@ var AzureSASCredential = /** @class */ (function () { * * @param newSignature - The new shared access signature value to be used */ - AzureSASCredential.prototype.update = function (newSignature) { + update(newSignature) { if (!newSignature) { throw new Error("shared access signature must be a non-empty string"); } this._signature = newSignature; - }; - return AzureSASCredential; -}()); + } +} /** * Tests an object to determine whether it implements SASCredential. * @@ -9460,7 +8757,7 @@ function isTokenCredential(credential) { // a ServiceClientCredentials implementor (like TokenClientCredentials // in ms-rest-nodeauth) doesn't get mistaken for a TokenCredential if // it doesn't actually implement TokenCredential also. - var castCredential = credential; + const castCredential = credential; return (castCredential && typeof castCredential.getToken === "function" && (castCredential.signRequest === undefined || castCredential.getToken.length > 0)); @@ -9741,7 +9038,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); const core = __importStar(__webpack_require__(470)); -const http_client_1 = __webpack_require__(22); +const http_client_1 = __webpack_require__(539); const constants_1 = __webpack_require__(931); function isSuccessStatusCode(statusCode) { if (!statusCode) { @@ -9882,7 +9179,7 @@ var __importStar = (this && this.__importStar) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); const core = __importStar(__webpack_require__(470)); -const http_client_1 = __webpack_require__(22); +const http_client_1 = __webpack_require__(539); const storage_blob_1 = __webpack_require__(373); const buffer = __importStar(__webpack_require__(407)); const fs = __importStar(__webpack_require__(747)); @@ -10025,7 +9322,7 @@ function downloadCacheHttpClient(archiveLocation, archivePath) { const contentLengthHeader = downloadResponse.message.headers['content-length']; if (contentLengthHeader) { const expectedLength = parseInt(contentLengthHeader); - const actualLength = utils.getArchiveFileSizeIsBytes(archivePath); + const actualLength = utils.getArchiveFileSizeInBytes(archivePath); if (actualLength !== expectedLength) { throw new Error(`Incomplete download. Expected file size: ${expectedLength}, actual file size: ${actualLength}`); } @@ -11117,205 +10414,6 @@ exports.Context = Context; Object.defineProperty(exports, '__esModule', { value: true }); var api = __webpack_require__(440); -var tslib = __webpack_require__(144); - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * A no-op implementation of Span that can safely be used without side-effects. - */ -var NoOpSpan = /** @class */ (function () { - function NoOpSpan() { - } - /** - * Returns the SpanContext associated with this Span. - */ - NoOpSpan.prototype.context = function () { - return { - spanId: "", - traceId: "", - traceFlags: 0 /* NONE */ - }; - }; - /** - * Marks the end of Span execution. - * @param _endTime - The time to use as the Span's end time. Defaults to - * the current time. - */ - NoOpSpan.prototype.end = function (_endTime) { - /* Noop */ - }; - /** - * Sets an attribute on the Span - * @param _key - The attribute key - * @param _value - The attribute value - */ - NoOpSpan.prototype.setAttribute = function (_key, _value) { - return this; - }; - /** - * Sets attributes on the Span - * @param _attributes - The attributes to add - */ - NoOpSpan.prototype.setAttributes = function (_attributes) { - return this; - }; - /** - * Adds an event to the Span - * @param _name - The name of the event - * @param _attributes - The associated attributes to add for this event - */ - NoOpSpan.prototype.addEvent = function (_name, _attributes) { - return this; - }; - /** - * Sets a status on the span. Overrides the default of SpanStatusCode.OK. - * @param _status - The status to set. - */ - NoOpSpan.prototype.setStatus = function (_status) { - return this; - }; - /** - * Updates the name of the Span - * @param _name - the new Span name - */ - NoOpSpan.prototype.updateName = function (_name) { - return this; - }; - /** - * Returns whether this span will be recorded - */ - NoOpSpan.prototype.isRecording = function () { - return false; - }; - /** - * Sets exception as a span event - * @param exception - the exception the only accepted values are string or Error - * @param time - the time to set as Span's event time. If not provided, - * use the current time. - */ - NoOpSpan.prototype.recordException = function (_exception, _time) { - /* do nothing */ - }; - return NoOpSpan; -}()); - -// Copyright (c) Microsoft Corporation. -/** - * A no-op implementation of Tracer that can be used when tracing - * is disabled. - */ -var NoOpTracer = /** @class */ (function () { - function NoOpTracer() { - } - /** - * Starts a new Span. - * @param _name - The name of the span. - * @param _options - The SpanOptions used during Span creation. - */ - NoOpTracer.prototype.startSpan = function (_name, _options) { - return new NoOpSpan(); - }; - /** - * Returns the current Span from the current context, if available. - */ - NoOpTracer.prototype.getCurrentSpan = function () { - return new NoOpSpan(); - }; - /** - * Executes the given function within the context provided by a Span. - * @param _span - The span that provides the context. - * @param fn - The function to be executed. - */ - NoOpTracer.prototype.withSpan = function (_span, fn) { - return fn(); - }; - /** - * Bind a Span as the target's scope - * @param target - An object to bind the scope. - * @param _span - A specific Span to use. Otherwise, use the current one. - */ - NoOpTracer.prototype.bind = function (target, _span) { - return target; - }; - return NoOpTracer; -}()); - -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -function getGlobalObject() { - return global; -} - -// Copyright (c) Microsoft Corporation. -// V1 = OpenTelemetry 0.1 -// V2 = OpenTelemetry 0.2 -// V3 = OpenTelemetry 0.6.1 -// V4 = OpenTelemetry 1.0.0-rc.0 -var GLOBAL_TRACER_VERSION = 4; -// preview5 shipped with @azure/core-tracing.tracerCache -// and didn't have smart detection for collisions -var GLOBAL_TRACER_SYMBOL = Symbol.for("@azure/core-tracing.tracerCache3"); -var cache; -function loadTracerCache() { - var globalObj = getGlobalObject(); - var existingCache = globalObj[GLOBAL_TRACER_SYMBOL]; - var setGlobalCache = true; - if (existingCache) { - if (existingCache.version === GLOBAL_TRACER_VERSION) { - cache = existingCache; - } - else { - setGlobalCache = false; - if (existingCache.tracer) { - throw new Error("Two incompatible versions of @azure/core-tracing have been loaded.\n This library is " + GLOBAL_TRACER_VERSION + ", existing is " + existingCache.version + "."); - } - } - } - if (!cache) { - cache = { - tracer: undefined, - version: GLOBAL_TRACER_VERSION - }; - } - if (setGlobalCache) { - globalObj[GLOBAL_TRACER_SYMBOL] = cache; - } -} -function getCache() { - if (!cache) { - loadTracerCache(); - } - return cache; -} - -// Copyright (c) Microsoft Corporation. -var defaultTracer; -function getDefaultTracer() { - if (!defaultTracer) { - defaultTracer = new NoOpTracer(); - } - return defaultTracer; -} -/** - * Sets the global tracer, enabling tracing for the Azure SDK. - * @param tracer - An OpenTelemetry Tracer instance. - */ -function setTracer(tracer) { - var cache = getCache(); - cache.tracer = tracer; -} -/** - * Retrieves the active tracer, or returns a - * no-op implementation if one is not set. - */ -function getTracer() { - var cache = getCache(); - if (!cache.tracer) { - return getDefaultTracer(); - } - return cache.tracer; -} // Copyright (c) Microsoft Corporation. (function (SpanKind) { @@ -11350,7 +10448,7 @@ function getTracer() { * @param context - context to get span from */ function getSpan(context) { - return api.getSpan(context); + return api.trace.getSpan(context); } /** * Set the span on a context @@ -11359,7 +10457,7 @@ function getSpan(context) { * @param span - span to set active */ function setSpan(context, span) { - return api.setSpan(context, span); + return api.trace.setSpan(context, span); } /** * Wrap span context in a NoopSpan and set as span in a new @@ -11369,7 +10467,7 @@ function setSpan(context, span) { * @param spanContext - span context to be wrapped */ function setSpanContext(context, spanContext) { - return api.setSpanContext(context, spanContext); + return api.trace.setSpanContext(context, spanContext); } /** * Get the span context of the span if it exists. @@ -11377,10 +10475,24 @@ function setSpanContext(context, spanContext) { * @param context - context to get values from */ function getSpanContext(context) { - return api.getSpanContext(context); + return api.trace.getSpanContext(context); +} +/** + * Returns true of the given {@link SpanContext} is valid. + * A valid {@link SpanContext} is one which has a valid trace ID and span ID as per the spec. + * + * @param context - the {@link SpanContext} to validate. + * + * @returns true if the {@link SpanContext} is valid, false otherwise. + */ +function isSpanContextValid(context) { + return api.trace.isSpanContextValid(context); +} +function getTracer(name, version) { + return api.trace.getTracer(name || "azure/core-tracing", version); } /** Entrypoint for context API */ -var context = api.context; +const context = api.context; (function (SpanStatusCode) { /** * The default status. @@ -11398,422 +10510,18 @@ var context = api.context; })(exports.SpanStatusCode || (exports.SpanStatusCode = {})); // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * @internal - */ -var OpenCensusTraceStateWrapper = /** @class */ (function () { - function OpenCensusTraceStateWrapper(state) { - this._state = state; +function isTracingDisabled() { + var _a; + if (typeof process === "undefined") { + // not supported in browser for now without polyfills + return false; } - OpenCensusTraceStateWrapper.prototype.get = function (_key) { - throw new Error("Method not implemented."); - }; - OpenCensusTraceStateWrapper.prototype.set = function (_key, _value) { - throw new Error("Method not implemented."); - }; - OpenCensusTraceStateWrapper.prototype.unset = function (_key) { - throw new Error("Method not implemented"); - }; - OpenCensusTraceStateWrapper.prototype.serialize = function () { - return this._state || ""; - }; - return OpenCensusTraceStateWrapper; -}()); - -// Copyright (c) Microsoft Corporation. -/** An enumeration of canonical status codes. */ -var CanonicalCode; -(function (CanonicalCode) { - /** - * Not an error; returned on success - */ - CanonicalCode[CanonicalCode["OK"] = 0] = "OK"; - /** - * Internal errors. Means some invariants expected by underlying - * system has been broken. If you see one of these errors, - * something is very broken. - */ - CanonicalCode[CanonicalCode["INTERNAL"] = 13] = "INTERNAL"; -})(CanonicalCode || (CanonicalCode = {})); -function isWrappedSpan(span) { - return !!span && span.getWrappedSpan !== undefined; + const azureTracingDisabledValue = (_a = process.env.AZURE_TRACING_DISABLED) === null || _a === void 0 ? void 0 : _a.toLowerCase(); + if (azureTracingDisabledValue === "false" || azureTracingDisabledValue === "0") { + return false; + } + return Boolean(azureTracingDisabledValue); } -function isTracer(tracerOrSpan) { - return tracerOrSpan.getWrappedTracer !== undefined; -} -/** - * An implementation of OpenTelemetry Span that wraps an OpenCensus Span. - */ -var OpenCensusSpanWrapper = /** @class */ (function () { - function OpenCensusSpanWrapper(tracerOrSpan, name, options, context$1) { - if (name === void 0) { name = ""; } - if (options === void 0) { options = {}; } - if (isTracer(tracerOrSpan)) { - var span = getSpan(context$1 !== null && context$1 !== void 0 ? context$1 : context.active()); - var parent = isWrappedSpan(span) ? span.getWrappedSpan() : undefined; - this._span = tracerOrSpan.getWrappedTracer().startChildSpan({ - name: name, - childOf: parent - }); - this._span.start(); - if (options.links) { - for (var _i = 0, _a = options.links; _i < _a.length; _i++) { - var link = _a[_i]; - // Since there is no way to set the link relationship, leave it as Unspecified. - this._span.addLink(link.context.traceId, link.context.spanId, 0 /* LinkType.UNSPECIFIED */, link.attributes); - } - } - } - else { - this._span = tracerOrSpan; - } - } - /** - * The underlying OpenCensus Span - */ - OpenCensusSpanWrapper.prototype.getWrappedSpan = function () { - return this._span; - }; - /** - * Marks the end of Span execution. - * @param endTime - The time to use as the Span's end time. Defaults to - * the current time. - */ - OpenCensusSpanWrapper.prototype.end = function (_endTime) { - this._span.end(); - }; - /** - * Returns the SpanContext associated with this Span. - */ - OpenCensusSpanWrapper.prototype.context = function () { - var openCensusSpanContext = this._span.spanContext; - return { - spanId: openCensusSpanContext.spanId, - traceId: openCensusSpanContext.traceId, - traceFlags: openCensusSpanContext.options, - traceState: new OpenCensusTraceStateWrapper(openCensusSpanContext.traceState) - }; - }; - /** - * Sets an attribute on the Span - * @param key - The attribute key - * @param value - The attribute value - */ - OpenCensusSpanWrapper.prototype.setAttribute = function (key, value) { - this._span.addAttribute(key, value); - return this; - }; - /** - * Sets attributes on the Span - * @param attributes - The attributes to add - */ - OpenCensusSpanWrapper.prototype.setAttributes = function (attributes) { - this._span.attributes = attributes; - return this; - }; - /** - * Adds an event to the Span - * @param name - The name of the event - * @param attributes - The associated attributes to add for this event - */ - OpenCensusSpanWrapper.prototype.addEvent = function (_name, _attributes) { - throw new Error("Method not implemented."); - }; - /** - * Sets a status on the span. Overrides the default of SpanStatusCode.OK. - * @param status - The status to set. - */ - OpenCensusSpanWrapper.prototype.setStatus = function (status) { - switch (status.code) { - case exports.SpanStatusCode.ERROR: { - this._span.setStatus(CanonicalCode.INTERNAL, status.message); - break; - } - case exports.SpanStatusCode.OK: { - this._span.setStatus(CanonicalCode.OK, status.message); - break; - } - case exports.SpanStatusCode.UNSET: { - break; - } - } - return this; - }; - /** - * Updates the name of the Span - * @param name - The new Span name - */ - OpenCensusSpanWrapper.prototype.updateName = function (name) { - this._span.name = name; - return this; - }; - /** - * Returns whether this span will be recorded - */ - OpenCensusSpanWrapper.prototype.isRecording = function () { - // NoRecordSpans have an empty traceId - return !!this._span.traceId; - }; - /** - * Sets exception as a span event - * @param exception - the exception the only accepted values are string or Error - * @param time - the time to set as Span's event time. If not provided, - * use the current time. - */ - OpenCensusSpanWrapper.prototype.recordException = function (_exception, _time) { - throw new Error("Method not implemented"); - }; - return OpenCensusSpanWrapper; -}()); - -// Copyright (c) Microsoft Corporation. -/** - * An implementation of OpenTelemetry Tracer that wraps an OpenCensus Tracer. - */ -var OpenCensusTracerWrapper = /** @class */ (function () { - /** - * Create a new wrapper around a given OpenCensus Tracer. - * @param tracer - The OpenCensus Tracer to wrap. - */ - function OpenCensusTracerWrapper(tracer) { - this._tracer = tracer; - } - /** - * The wrapped OpenCensus Tracer - */ - OpenCensusTracerWrapper.prototype.getWrappedTracer = function () { - return this._tracer; - }; - /** - * Starts a new Span. - * @param name - The name of the span. - * @param options - The SpanOptions used during Span creation. - */ - OpenCensusTracerWrapper.prototype.startSpan = function (name, options) { - return new OpenCensusSpanWrapper(this, name, options); - }; - /** - * Returns the current Span from the current context, if available. - */ - OpenCensusTracerWrapper.prototype.getCurrentSpan = function () { - return undefined; - }; - /** - * Executes the given function within the context provided by a Span. - * @param _span - The span that provides the context. - * @param _fn - The function to be executed. - */ - OpenCensusTracerWrapper.prototype.withSpan = function (_span, _fn) { - throw new Error("Method not implemented."); - }; - /** - * Bind a Span as the target's scope - * @param target - An object to bind the scope. - * @param _span - A specific Span to use. Otherwise, use the current one. - */ - OpenCensusTracerWrapper.prototype.bind = function (_target, _span) { - throw new Error("Method not implemented."); - }; - return OpenCensusTracerWrapper; -}()); - -// Copyright (c) Microsoft Corporation. -/** - * A mock span useful for testing. - */ -var TestSpan = /** @class */ (function (_super) { - tslib.__extends(TestSpan, _super); - /** - * Starts a new Span. - * @param parentTracer- The tracer that created this Span - * @param name - The name of the span. - * @param context - The SpanContext this span belongs to - * @param kind - The SpanKind of this Span - * @param parentSpanId - The identifier of the parent Span - * @param startTime - The startTime of the event (defaults to now) - */ - function TestSpan(parentTracer, name, context, kind, parentSpanId, startTime) { - if (startTime === void 0) { startTime = Date.now(); } - var _this = _super.call(this) || this; - _this._tracer = parentTracer; - _this.name = name; - _this.kind = kind; - _this.startTime = startTime; - _this.parentSpanId = parentSpanId; - _this.status = { - code: exports.SpanStatusCode.OK - }; - _this.endCalled = false; - _this._context = context; - _this.attributes = {}; - return _this; - } - /** - * Returns the Tracer that created this Span - */ - TestSpan.prototype.tracer = function () { - return this._tracer; - }; - /** - * Returns the SpanContext associated with this Span. - */ - TestSpan.prototype.context = function () { - return this._context; - }; - /** - * Marks the end of Span execution. - * @param _endTime - The time to use as the Span's end time. Defaults to - * the current time. - */ - TestSpan.prototype.end = function (_endTime) { - this.endCalled = true; - }; - /** - * Sets a status on the span. Overrides the default of SpanStatusCode.OK. - * @param status - The status to set. - */ - TestSpan.prototype.setStatus = function (status) { - this.status = status; - return this; - }; - /** - * Returns whether this span will be recorded - */ - TestSpan.prototype.isRecording = function () { - return true; - }; - /** - * Sets an attribute on the Span - * @param key - The attribute key - * @param value - The attribute value - */ - TestSpan.prototype.setAttribute = function (key, value) { - this.attributes[key] = value; - return this; - }; - /** - * Sets attributes on the Span - * @param attributes - The attributes to add - */ - TestSpan.prototype.setAttributes = function (attributes) { - for (var _i = 0, _a = Object.keys(attributes); _i < _a.length; _i++) { - var key = _a[_i]; - this.attributes[key] = attributes[key]; - } - return this; - }; - return TestSpan; -}(NoOpSpan)); - -// Copyright (c) Microsoft Corporation. -/** - * A mock tracer useful for testing - */ -var TestTracer = /** @class */ (function (_super) { - tslib.__extends(TestTracer, _super); - function TestTracer() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.traceIdCounter = 0; - _this.spanIdCounter = 0; - _this.rootSpans = []; - _this.knownSpans = []; - return _this; - } - TestTracer.prototype.getNextTraceId = function () { - this.traceIdCounter++; - return String(this.traceIdCounter); - }; - TestTracer.prototype.getNextSpanId = function () { - this.spanIdCounter++; - return String(this.spanIdCounter); - }; - /** - * Returns all Spans that were created without a parent - */ - TestTracer.prototype.getRootSpans = function () { - return this.rootSpans; - }; - /** - * Returns all Spans this Tracer knows about - */ - TestTracer.prototype.getKnownSpans = function () { - return this.knownSpans; - }; - /** - * Returns all Spans where end() has not been called - */ - TestTracer.prototype.getActiveSpans = function () { - return this.knownSpans.filter(function (span) { - return !span.endCalled; - }); - }; - /** - * Return all Spans for a particular trace, grouped by their - * parent Span in a tree-like structure - * @param traceId - The traceId to return the graph for - */ - TestTracer.prototype.getSpanGraph = function (traceId) { - var traceSpans = this.knownSpans.filter(function (span) { - return span.context().traceId === traceId; - }); - var roots = []; - var nodeMap = new Map(); - for (var _i = 0, traceSpans_1 = traceSpans; _i < traceSpans_1.length; _i++) { - var span = traceSpans_1[_i]; - var spanId = span.context().spanId; - var node = { - name: span.name, - children: [] - }; - nodeMap.set(spanId, node); - if (span.parentSpanId) { - var parent = nodeMap.get(span.parentSpanId); - if (!parent) { - throw new Error("Span with name " + node.name + " has an unknown parentSpan with id " + span.parentSpanId); - } - parent.children.push(node); - } - else { - roots.push(node); - } - } - return { - roots: roots - }; - }; - /** - * Starts a new Span. - * @param name - The name of the span. - * @param options - The SpanOptions used during Span creation. - */ - TestTracer.prototype.startSpan = function (name, options, context$1) { - var parentContext = getSpanContext(context$1 || context.active()); - var traceId; - var isRootSpan = false; - if (parentContext && parentContext.traceId) { - traceId = parentContext.traceId; - } - else { - traceId = this.getNextTraceId(); - isRootSpan = true; - } - var spanContext = { - traceId: traceId, - spanId: this.getNextSpanId(), - traceFlags: 0 /* NONE */ - }; - var span = new TestSpan(this, name, spanContext, (options === null || options === void 0 ? void 0 : options.kind) || exports.SpanKind.INTERNAL, parentContext ? parentContext.spanId : undefined, options === null || options === void 0 ? void 0 : options.startTime); - this.knownSpans.push(span); - if (isRootSpan) { - this.rootSpans.push(span); - } - return span; - }; - return TestTracer; -}(NoOpTracer)); - -// Copyright (c) Microsoft Corporation. /** * Creates a function that can be used to create spans using the global tracer. * @@ -11834,22 +10542,28 @@ var TestTracer = /** @class */ (function (_super) { */ function createSpanFunction(args) { return function (operationName, operationOptions) { - var tracer = getTracer(); - var tracingOptions = (operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) || {}; - var spanOptions = tslib.__assign({ kind: exports.SpanKind.INTERNAL }, tracingOptions.spanOptions); - var spanName = args.packagePrefix ? args.packagePrefix + "." + operationName : operationName; - var span = tracer.startSpan(spanName, spanOptions, tracingOptions.tracingContext); + const tracer = getTracer(); + const tracingOptions = (operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) || {}; + const spanOptions = Object.assign({ kind: exports.SpanKind.INTERNAL }, tracingOptions.spanOptions); + const spanName = args.packagePrefix ? `${args.packagePrefix}.${operationName}` : operationName; + let span; + if (isTracingDisabled()) { + span = api.trace.wrapSpanContext(api.INVALID_SPAN_CONTEXT); + } + else { + span = tracer.startSpan(spanName, spanOptions, tracingOptions.tracingContext); + } if (args.namespace) { span.setAttribute("az.namespace", args.namespace); } - var newSpanOptions = tracingOptions.spanOptions || {}; + let newSpanOptions = tracingOptions.spanOptions || {}; if (span.isRecording() && args.namespace) { - newSpanOptions = tslib.__assign(tslib.__assign({}, tracingOptions.spanOptions), { attributes: tslib.__assign(tslib.__assign({}, spanOptions.attributes), { "az.namespace": args.namespace }) }); + newSpanOptions = Object.assign(Object.assign({}, tracingOptions.spanOptions), { attributes: Object.assign(Object.assign({}, spanOptions.attributes), { "az.namespace": args.namespace }) }); } - var newTracingOptions = tslib.__assign(tslib.__assign({}, tracingOptions), { spanOptions: newSpanOptions, tracingContext: setSpan(tracingOptions.tracingContext || context.active(), span) }); - var newOperationOptions = tslib.__assign(tslib.__assign({}, operationOptions), { tracingOptions: newTracingOptions }); + const newTracingOptions = Object.assign(Object.assign({}, tracingOptions), { spanOptions: newSpanOptions, tracingContext: setSpan(tracingOptions.tracingContext || context.active(), span) }); + const newOperationOptions = Object.assign(Object.assign({}, operationOptions), { tracingOptions: newTracingOptions }); return { - span: span, + span, updatedOptions: newOperationOptions }; }; @@ -11857,26 +10571,26 @@ function createSpanFunction(args) { // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -var VERSION = "00"; +const VERSION = "00"; /** * Generates a `SpanContext` given a `traceparent` header value. * @param traceParent - Serialized span context data as a `traceparent` header value. * @returns The `SpanContext` generated from the `traceparent` value. */ function extractSpanContextFromTraceParentHeader(traceParentHeader) { - var parts = traceParentHeader.split("-"); + const parts = traceParentHeader.split("-"); if (parts.length !== 4) { return; } - var version = parts[0], traceId = parts[1], spanId = parts[2], traceOptions = parts[3]; + const [version, traceId, spanId, traceOptions] = parts; if (version !== VERSION) { return; } - var traceFlags = parseInt(traceOptions, 16); - var spanContext = { - spanId: spanId, - traceId: traceId, - traceFlags: traceFlags + const traceFlags = parseInt(traceOptions, 16); + const spanContext = { + spanId, + traceId, + traceFlags }; return spanContext; } @@ -11886,7 +10600,7 @@ function extractSpanContextFromTraceParentHeader(traceParentHeader) { * @returns The `spanContext` represented as a `traceparent` value. */ function getTraceParentHeader(spanContext) { - var missingFields = []; + const missingFields = []; if (!spanContext.traceId) { missingFields.push("traceId"); } @@ -11896,19 +10610,13 @@ function getTraceParentHeader(spanContext) { if (missingFields.length) { return; } - var flags = spanContext.traceFlags || 0 /* NONE */; - var hexFlags = flags.toString(16); - var traceFlags = hexFlags.length === 1 ? "0" + hexFlags : hexFlags; + const flags = spanContext.traceFlags || 0 /* NONE */; + const hexFlags = flags.toString(16); + const traceFlags = hexFlags.length === 1 ? `0${hexFlags}` : hexFlags; // https://www.w3.org/TR/trace-context/#traceparent-header-field-values - return VERSION + "-" + spanContext.traceId + "-" + spanContext.spanId + "-" + traceFlags; + return `${VERSION}-${spanContext.traceId}-${spanContext.spanId}-${traceFlags}`; } -exports.NoOpSpan = NoOpSpan; -exports.NoOpTracer = NoOpTracer; -exports.OpenCensusSpanWrapper = OpenCensusSpanWrapper; -exports.OpenCensusTracerWrapper = OpenCensusTracerWrapper; -exports.TestSpan = TestSpan; -exports.TestTracer = TestTracer; exports.context = context; exports.createSpanFunction = createSpanFunction; exports.extractSpanContextFromTraceParentHeader = extractSpanContextFromTraceParentHeader; @@ -11916,9 +10624,9 @@ exports.getSpan = getSpan; exports.getSpanContext = getSpanContext; exports.getTraceParentHeader = getTraceParentHeader; exports.getTracer = getTracer; +exports.isSpanContextValid = isSpanContextValid; exports.setSpan = setSpan; exports.setSpanContext = setSpanContext; -exports.setTracer = setTracer; //# sourceMappingURL=index.js.map @@ -14451,51 +13159,7 @@ isStream.transform = function (stream) { /***/ }), -/* 324 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; -/*! - * Copyright (c) 2018, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of Salesforce.com nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -const psl = __webpack_require__(750); - -function getPublicSuffix(domain) { - return psl.get(domain); -} - -exports.getPublicSuffix = getPublicSuffix; - - -/***/ }), +/* 324 */, /* 325 */, /* 326 */, /* 327 */ @@ -14526,203 +13190,7 @@ var MatchKind; /* 329 */, /* 330 */, /* 331 */, -/* 332 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; -/*! - * Copyright (c) 2015, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of Salesforce.com nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -const { fromCallback } = __webpack_require__(147); -const Store = __webpack_require__(338).Store; -const permuteDomain = __webpack_require__(898).permuteDomain; -const pathMatch = __webpack_require__(678).pathMatch; -const util = __webpack_require__(669); - -class MemoryCookieStore extends Store { - constructor() { - super(); - this.synchronous = true; - this.idx = {}; - if (util.inspect.custom) { - this[util.inspect.custom] = this.inspect; - } - } - - inspect() { - return `{ idx: ${util.inspect(this.idx, false, 2)} }`; - } - - findCookie(domain, path, key, cb) { - if (!this.idx[domain]) { - return cb(null, undefined); - } - if (!this.idx[domain][path]) { - return cb(null, undefined); - } - return cb(null, this.idx[domain][path][key] || null); - } - findCookies(domain, path, allowSpecialUseDomain, cb) { - const results = []; - if (typeof allowSpecialUseDomain === "function") { - cb = allowSpecialUseDomain; - allowSpecialUseDomain = false; - } - if (!domain) { - return cb(null, []); - } - - let pathMatcher; - if (!path) { - // null means "all paths" - pathMatcher = function matchAll(domainIndex) { - for (const curPath in domainIndex) { - const pathIndex = domainIndex[curPath]; - for (const key in pathIndex) { - results.push(pathIndex[key]); - } - } - }; - } else { - pathMatcher = function matchRFC(domainIndex) { - //NOTE: we should use path-match algorithm from S5.1.4 here - //(see : https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/canonical_cookie.cc#L299) - Object.keys(domainIndex).forEach(cookiePath => { - if (pathMatch(path, cookiePath)) { - const pathIndex = domainIndex[cookiePath]; - for (const key in pathIndex) { - results.push(pathIndex[key]); - } - } - }); - }; - } - - const domains = permuteDomain(domain, allowSpecialUseDomain) || [domain]; - const idx = this.idx; - domains.forEach(curDomain => { - const domainIndex = idx[curDomain]; - if (!domainIndex) { - return; - } - pathMatcher(domainIndex); - }); - - cb(null, results); - } - - putCookie(cookie, cb) { - if (!this.idx[cookie.domain]) { - this.idx[cookie.domain] = {}; - } - if (!this.idx[cookie.domain][cookie.path]) { - this.idx[cookie.domain][cookie.path] = {}; - } - this.idx[cookie.domain][cookie.path][cookie.key] = cookie; - cb(null); - } - updateCookie(oldCookie, newCookie, cb) { - // updateCookie() may avoid updating cookies that are identical. For example, - // lastAccessed may not be important to some stores and an equality - // comparison could exclude that field. - this.putCookie(newCookie, cb); - } - removeCookie(domain, path, key, cb) { - if ( - this.idx[domain] && - this.idx[domain][path] && - this.idx[domain][path][key] - ) { - delete this.idx[domain][path][key]; - } - cb(null); - } - removeCookies(domain, path, cb) { - if (this.idx[domain]) { - if (path) { - delete this.idx[domain][path]; - } else { - delete this.idx[domain]; - } - } - return cb(null); - } - removeAllCookies(cb) { - this.idx = {}; - return cb(null); - } - getAllCookies(cb) { - const cookies = []; - const idx = this.idx; - - const domains = Object.keys(idx); - domains.forEach(domain => { - const paths = Object.keys(idx[domain]); - paths.forEach(path => { - const keys = Object.keys(idx[domain][path]); - keys.forEach(key => { - if (key !== null) { - cookies.push(idx[domain][path][key]); - } - }); - }); - }); - - // Sort by creationIndex so deserializing retains the creation order. - // When implementing your own store, this SHOULD retain the order too - cookies.sort((a, b) => { - return (a.creationIndex || 0) - (b.creationIndex || 0); - }); - - cb(null, cookies); - } -} - -[ - "findCookie", - "findCookies", - "putCookie", - "updateCookie", - "removeCookie", - "removeCookies", - "removeAllCookies", - "getAllCookies" -].forEach(name => { - MemoryCookieStore[name] = fromCallback(MemoryCookieStore.prototype[name]); -}); - -exports.MemoryCookieStore = MemoryCookieStore; - - -/***/ }), +/* 332 */, /* 333 */, /* 334 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -14754,86 +13222,14 @@ function hasLastPage (link) { /***/ }), /* 337 */, /* 338 */ -/***/ (function(__unusedmodule, exports) { +/***/ (function() { "use strict"; -/*! - * Copyright (c) 2015, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of Salesforce.com nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ -/*jshint unused:false */ - -class Store { - constructor() { - this.synchronous = false; - } - - findCookie(domain, path, key, cb) { - throw new Error("findCookie is not implemented"); - } - - findCookies(domain, path, allowSpecialUseDomain, cb) { - throw new Error("findCookies is not implemented"); - } - - putCookie(cookie, cb) { - throw new Error("putCookie is not implemented"); - } - - updateCookie(oldCookie, newCookie, cb) { - // recommended default implementation: - // return this.putCookie(newCookie, cb); - throw new Error("updateCookie is not implemented"); - } - - removeCookie(domain, path, key, cb) { - throw new Error("removeCookie is not implemented"); - } - - removeCookies(domain, path, cb) { - throw new Error("removeCookies is not implemented"); - } - - removeAllCookies(cb) { - throw new Error("removeAllCookies is not implemented"); - } - - getAllCookies(cb) { - throw new Error( - "getAllCookies is not implemented (therefore jar cannot be serialized)" - ); - } +if (typeof Symbol === undefined || !Symbol.asyncIterator) { + Symbol.asyncIterator = Symbol.for("Symbol.asyncIterator"); } - -exports.Store = Store; - +//# sourceMappingURL=index.js.map /***/ }), /* 339 */, @@ -15216,7 +13612,92 @@ module.exports = require("assert"); /* 359 */, /* 360 */, /* 361 */, -/* 362 */, +/* 362 */ +/***/ (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.DiagComponentLogger = void 0; +var global_utils_1 = __webpack_require__(525); +/** + * Component Logger which is meant to be used as part of any component which + * will add automatically additional namespace in front of the log message. + * It will then forward all message to global diag logger + * @example + * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' }); + * cLogger.debug('test'); + * // @opentelemetry/instrumentation-http test + */ +var DiagComponentLogger = /** @class */ (function () { + function DiagComponentLogger(props) { + this._namespace = props.namespace || 'DiagComponentLogger'; + } + DiagComponentLogger.prototype.debug = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return logProxy('debug', this._namespace, args); + }; + DiagComponentLogger.prototype.error = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return logProxy('error', this._namespace, args); + }; + DiagComponentLogger.prototype.info = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return logProxy('info', this._namespace, args); + }; + DiagComponentLogger.prototype.warn = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return logProxy('warn', this._namespace, args); + }; + DiagComponentLogger.prototype.verbose = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return logProxy('verbose', this._namespace, args); + }; + return DiagComponentLogger; +}()); +exports.DiagComponentLogger = DiagComponentLogger; +function logProxy(funcName, namespace, args) { + var logger = global_utils_1.getGlobal('diag'); + // shortcut if logger not set + if (!logger) { + return; + } + args.unshift(namespace); + return logger[funcName].apply(logger, args); +} +//# sourceMappingURL=ComponentLogger.js.map + +/***/ }), /* 363 */ /***/ (function(module) { @@ -15347,7 +13828,7 @@ var util = __webpack_require__(669); * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ -var BlobServiceProperties = { +const BlobServiceProperties = { serializedName: "BlobServiceProperties", xmlName: "StorageServiceProperties", type: { @@ -15419,7 +13900,7 @@ var BlobServiceProperties = { } } }; -var Logging = { +const Logging = { serializedName: "Logging", type: { name: "Composite", @@ -15468,7 +13949,7 @@ var Logging = { } } }; -var RetentionPolicy = { +const RetentionPolicy = { serializedName: "RetentionPolicy", type: { name: "Composite", @@ -15495,7 +13976,7 @@ var RetentionPolicy = { } } }; -var Metrics = { +const Metrics = { serializedName: "Metrics", type: { name: "Composite", @@ -15534,7 +14015,7 @@ var Metrics = { } } }; -var CorsRule = { +const CorsRule = { serializedName: "CorsRule", type: { name: "Composite", @@ -15586,7 +14067,7 @@ var CorsRule = { } } }; -var StaticWebsite = { +const StaticWebsite = { serializedName: "StaticWebsite", type: { name: "Composite", @@ -15624,7 +14105,7 @@ var StaticWebsite = { } } }; -var StorageError = { +const StorageError = { serializedName: "StorageError", type: { name: "Composite", @@ -15647,7 +14128,7 @@ var StorageError = { } } }; -var BlobServiceStatistics = { +const BlobServiceStatistics = { serializedName: "BlobServiceStatistics", xmlName: "StorageServiceStats", type: { @@ -15665,7 +14146,7 @@ var BlobServiceStatistics = { } } }; -var GeoReplication = { +const GeoReplication = { serializedName: "GeoReplication", type: { name: "Composite", @@ -15691,7 +14172,7 @@ var GeoReplication = { } } }; -var ListContainersSegmentResponse = { +const ListContainersSegmentResponse = { serializedName: "ListContainersSegmentResponse", xmlName: "EnumerationResults", type: { @@ -15754,7 +14235,7 @@ var ListContainersSegmentResponse = { } } }; -var ContainerItem = { +const ContainerItem = { serializedName: "ContainerItem", xmlName: "Container", type: { @@ -15802,7 +14283,7 @@ var ContainerItem = { } } }; -var ContainerProperties = { +const ContainerProperties = { serializedName: "ContainerProperties", type: { name: "Composite", @@ -15903,11 +14384,18 @@ var ContainerProperties = { type: { name: "Number" } + }, + isImmutableStorageWithVersioningEnabled: { + serializedName: "ImmutableStorageWithVersioningEnabled", + xmlName: "ImmutableStorageWithVersioningEnabled", + type: { + name: "Boolean" + } } } } }; -var KeyInfo = { +const KeyInfo = { serializedName: "KeyInfo", type: { name: "Composite", @@ -15932,7 +14420,7 @@ var KeyInfo = { } } }; -var UserDelegationKey = { +const UserDelegationKey = { serializedName: "UserDelegationKey", type: { name: "Composite", @@ -15997,7 +14485,7 @@ var UserDelegationKey = { } } }; -var FilterBlobSegment = { +const FilterBlobSegment = { serializedName: "FilterBlobSegment", xmlName: "EnumerationResults", type: { @@ -16047,7 +14535,7 @@ var FilterBlobSegment = { } } }; -var FilterBlobItem = { +const FilterBlobItem = { serializedName: "FilterBlobItem", xmlName: "Blob", type: { @@ -16081,7 +14569,7 @@ var FilterBlobItem = { } } }; -var BlobTags = { +const BlobTags = { serializedName: "BlobTags", xmlName: "Tags", type: { @@ -16107,7 +14595,7 @@ var BlobTags = { } } }; -var BlobTag = { +const BlobTag = { serializedName: "BlobTag", xmlName: "Tag", type: { @@ -16133,7 +14621,7 @@ var BlobTag = { } } }; -var SignedIdentifier = { +const SignedIdentifier = { serializedName: "SignedIdentifier", xmlName: "SignedIdentifier", type: { @@ -16159,7 +14647,7 @@ var SignedIdentifier = { } } }; -var AccessPolicy = { +const AccessPolicy = { serializedName: "AccessPolicy", type: { name: "Composite", @@ -16189,7 +14677,7 @@ var AccessPolicy = { } } }; -var ListBlobsFlatSegmentResponse = { +const ListBlobsFlatSegmentResponse = { serializedName: "ListBlobsFlatSegmentResponse", xmlName: "EnumerationResults", type: { @@ -16253,7 +14741,7 @@ var ListBlobsFlatSegmentResponse = { } } }; -var BlobFlatListSegment = { +const BlobFlatListSegment = { serializedName: "BlobFlatListSegment", xmlName: "Blobs", type: { @@ -16278,7 +14766,7 @@ var BlobFlatListSegment = { } } }; -var BlobItemInternal = { +const BlobItemInternal = { serializedName: "BlobItemInternal", xmlName: "Blob", type: { @@ -16354,11 +14842,18 @@ var BlobItemInternal = { name: "Dictionary", value: { type: { name: "String" } } } + }, + hasVersionsOnly: { + serializedName: "HasVersionsOnly", + xmlName: "HasVersionsOnly", + type: { + name: "Boolean" + } } } } }; -var BlobPropertiesInternal = { +const BlobPropertiesInternal = { serializedName: "BlobPropertiesInternal", xmlName: "Properties", type: { @@ -16657,11 +15152,33 @@ var BlobPropertiesInternal = { type: { name: "DateTimeRfc1123" } + }, + immutabilityPolicyExpiresOn: { + serializedName: "ImmutabilityPolicyUntilDate", + xmlName: "ImmutabilityPolicyUntilDate", + type: { + name: "DateTimeRfc1123" + } + }, + immutabilityPolicyMode: { + serializedName: "ImmutabilityPolicyMode", + xmlName: "ImmutabilityPolicyMode", + type: { + name: "Enum", + allowedValues: ["Mutable", "Unlocked", "Locked"] + } + }, + legalHold: { + serializedName: "LegalHold", + xmlName: "LegalHold", + type: { + name: "Boolean" + } } } } }; -var ListBlobsHierarchySegmentResponse = { +const ListBlobsHierarchySegmentResponse = { serializedName: "ListBlobsHierarchySegmentResponse", xmlName: "EnumerationResults", type: { @@ -16732,7 +15249,7 @@ var ListBlobsHierarchySegmentResponse = { } } }; -var BlobHierarchyListSegment = { +const BlobHierarchyListSegment = { serializedName: "BlobHierarchyListSegment", xmlName: "Blobs", type: { @@ -16771,7 +15288,7 @@ var BlobHierarchyListSegment = { } } }; -var BlobPrefix = { +const BlobPrefix = { serializedName: "BlobPrefix", type: { name: "Composite", @@ -16788,47 +15305,7 @@ var BlobPrefix = { } } }; -var DataLakeStorageError = { - serializedName: "DataLakeStorageError", - type: { - name: "Composite", - className: "DataLakeStorageError", - modelProperties: { - dataLakeStorageErrorDetails: { - serializedName: "error", - xmlName: "error", - type: { - name: "Composite", - className: "DataLakeStorageErrorError" - } - } - } - } -}; -var DataLakeStorageErrorError = { - serializedName: "DataLakeStorageErrorError", - type: { - name: "Composite", - className: "DataLakeStorageErrorError", - modelProperties: { - code: { - serializedName: "Code", - xmlName: "Code", - type: { - name: "String" - } - }, - message: { - serializedName: "Message", - xmlName: "Message", - type: { - name: "String" - } - } - } - } -}; -var BlockLookupList = { +const BlockLookupList = { serializedName: "BlockLookupList", xmlName: "BlockList", type: { @@ -16877,7 +15354,7 @@ var BlockLookupList = { } } }; -var BlockList = { +const BlockList = { serializedName: "BlockList", type: { name: "Composite", @@ -16916,7 +15393,7 @@ var BlockList = { } } }; -var Block = { +const Block = { serializedName: "Block", type: { name: "Composite", @@ -16941,7 +15418,7 @@ var Block = { } } }; -var PageList = { +const PageList = { serializedName: "PageList", type: { name: "Composite", @@ -16978,7 +15455,7 @@ var PageList = { } } }; -var PageRange = { +const PageRange = { serializedName: "PageRange", xmlName: "PageRange", type: { @@ -17004,7 +15481,7 @@ var PageRange = { } } }; -var ClearRange = { +const ClearRange = { serializedName: "ClearRange", xmlName: "ClearRange", type: { @@ -17030,7 +15507,7 @@ var ClearRange = { } } }; -var QueryRequest = { +const QueryRequest = { serializedName: "QueryRequest", xmlName: "QueryRequest", type: { @@ -17072,7 +15549,7 @@ var QueryRequest = { } } }; -var QuerySerialization = { +const QuerySerialization = { serializedName: "QuerySerialization", type: { name: "Composite", @@ -17089,7 +15566,7 @@ var QuerySerialization = { } } }; -var QueryFormat = { +const QueryFormat = { serializedName: "QueryFormat", type: { name: "Composite", @@ -17097,10 +15574,11 @@ var QueryFormat = { modelProperties: { type: { serializedName: "Type", + required: true, xmlName: "Type", type: { name: "Enum", - allowedValues: ["delimited", "json", "arrow"] + allowedValues: ["delimited", "json", "arrow", "parquet"] } }, delimitedTextConfiguration: { @@ -17126,11 +15604,18 @@ var QueryFormat = { name: "Composite", className: "ArrowConfiguration" } + }, + parquetTextConfiguration: { + serializedName: "ParquetTextConfiguration", + xmlName: "ParquetTextConfiguration", + type: { + name: "any" + } } } } }; -var DelimitedTextConfiguration = { +const DelimitedTextConfiguration = { serializedName: "DelimitedTextConfiguration", xmlName: "DelimitedTextConfiguration", type: { @@ -17139,7 +15624,6 @@ var DelimitedTextConfiguration = { modelProperties: { columnSeparator: { serializedName: "ColumnSeparator", - required: true, xmlName: "ColumnSeparator", type: { name: "String" @@ -17147,7 +15631,6 @@ var DelimitedTextConfiguration = { }, fieldQuote: { serializedName: "FieldQuote", - required: true, xmlName: "FieldQuote", type: { name: "String" @@ -17155,7 +15638,6 @@ var DelimitedTextConfiguration = { }, recordSeparator: { serializedName: "RecordSeparator", - required: true, xmlName: "RecordSeparator", type: { name: "String" @@ -17163,7 +15645,6 @@ var DelimitedTextConfiguration = { }, escapeChar: { serializedName: "EscapeChar", - required: true, xmlName: "EscapeChar", type: { name: "String" @@ -17171,7 +15652,6 @@ var DelimitedTextConfiguration = { }, headersPresent: { serializedName: "HeadersPresent", - required: true, xmlName: "HasHeaders", type: { name: "Boolean" @@ -17180,7 +15660,7 @@ var DelimitedTextConfiguration = { } } }; -var JsonTextConfiguration = { +const JsonTextConfiguration = { serializedName: "JsonTextConfiguration", xmlName: "JsonTextConfiguration", type: { @@ -17189,7 +15669,6 @@ var JsonTextConfiguration = { modelProperties: { recordSeparator: { serializedName: "RecordSeparator", - required: true, xmlName: "RecordSeparator", type: { name: "String" @@ -17198,7 +15677,7 @@ var JsonTextConfiguration = { } } }; -var ArrowConfiguration = { +const ArrowConfiguration = { serializedName: "ArrowConfiguration", xmlName: "ArrowConfiguration", type: { @@ -17224,7 +15703,7 @@ var ArrowConfiguration = { } } }; -var ArrowField = { +const ArrowField = { serializedName: "ArrowField", xmlName: "Field", type: { @@ -17263,7 +15742,7 @@ var ArrowField = { } } }; -var ServiceSetPropertiesHeaders = { +const ServiceSetPropertiesHeaders = { serializedName: "Service_setPropertiesHeaders", type: { name: "Composite", @@ -17300,7 +15779,7 @@ var ServiceSetPropertiesHeaders = { } } }; -var ServiceSetPropertiesExceptionHeaders = { +const ServiceSetPropertiesExceptionHeaders = { serializedName: "Service_setPropertiesExceptionHeaders", type: { name: "Composite", @@ -17316,7 +15795,7 @@ var ServiceSetPropertiesExceptionHeaders = { } } }; -var ServiceGetPropertiesHeaders = { +const ServiceGetPropertiesHeaders = { serializedName: "Service_getPropertiesHeaders", type: { name: "Composite", @@ -17353,7 +15832,7 @@ var ServiceGetPropertiesHeaders = { } } }; -var ServiceGetPropertiesExceptionHeaders = { +const ServiceGetPropertiesExceptionHeaders = { serializedName: "Service_getPropertiesExceptionHeaders", type: { name: "Composite", @@ -17369,7 +15848,7 @@ var ServiceGetPropertiesExceptionHeaders = { } } }; -var ServiceGetStatisticsHeaders = { +const ServiceGetStatisticsHeaders = { serializedName: "Service_getStatisticsHeaders", type: { name: "Composite", @@ -17413,7 +15892,7 @@ var ServiceGetStatisticsHeaders = { } } }; -var ServiceGetStatisticsExceptionHeaders = { +const ServiceGetStatisticsExceptionHeaders = { serializedName: "Service_getStatisticsExceptionHeaders", type: { name: "Composite", @@ -17429,7 +15908,7 @@ var ServiceGetStatisticsExceptionHeaders = { } } }; -var ServiceListContainersSegmentHeaders = { +const ServiceListContainersSegmentHeaders = { serializedName: "Service_listContainersSegmentHeaders", type: { name: "Composite", @@ -17466,7 +15945,7 @@ var ServiceListContainersSegmentHeaders = { } } }; -var ServiceListContainersSegmentExceptionHeaders = { +const ServiceListContainersSegmentExceptionHeaders = { serializedName: "Service_listContainersSegmentExceptionHeaders", type: { name: "Composite", @@ -17482,7 +15961,7 @@ var ServiceListContainersSegmentExceptionHeaders = { } } }; -var ServiceGetUserDelegationKeyHeaders = { +const ServiceGetUserDelegationKeyHeaders = { serializedName: "Service_getUserDelegationKeyHeaders", type: { name: "Composite", @@ -17526,7 +16005,7 @@ var ServiceGetUserDelegationKeyHeaders = { } } }; -var ServiceGetUserDelegationKeyExceptionHeaders = { +const ServiceGetUserDelegationKeyExceptionHeaders = { serializedName: "Service_getUserDelegationKeyExceptionHeaders", type: { name: "Composite", @@ -17542,7 +16021,7 @@ var ServiceGetUserDelegationKeyExceptionHeaders = { } } }; -var ServiceGetAccountInfoHeaders = { +const ServiceGetAccountInfoHeaders = { serializedName: "Service_getAccountInfoHeaders", type: { name: "Composite", @@ -17621,7 +16100,7 @@ var ServiceGetAccountInfoHeaders = { } } }; -var ServiceGetAccountInfoExceptionHeaders = { +const ServiceGetAccountInfoExceptionHeaders = { serializedName: "Service_getAccountInfoExceptionHeaders", type: { name: "Composite", @@ -17637,7 +16116,7 @@ var ServiceGetAccountInfoExceptionHeaders = { } } }; -var ServiceSubmitBatchHeaders = { +const ServiceSubmitBatchHeaders = { serializedName: "Service_submitBatchHeaders", type: { name: "Composite", @@ -17681,7 +16160,7 @@ var ServiceSubmitBatchHeaders = { } } }; -var ServiceSubmitBatchExceptionHeaders = { +const ServiceSubmitBatchExceptionHeaders = { serializedName: "Service_submitBatchExceptionHeaders", type: { name: "Composite", @@ -17697,7 +16176,7 @@ var ServiceSubmitBatchExceptionHeaders = { } } }; -var ServiceFilterBlobsHeaders = { +const ServiceFilterBlobsHeaders = { serializedName: "Service_filterBlobsHeaders", type: { name: "Composite", @@ -17741,7 +16220,7 @@ var ServiceFilterBlobsHeaders = { } } }; -var ServiceFilterBlobsExceptionHeaders = { +const ServiceFilterBlobsExceptionHeaders = { serializedName: "Service_filterBlobsExceptionHeaders", type: { name: "Composite", @@ -17757,7 +16236,7 @@ var ServiceFilterBlobsExceptionHeaders = { } } }; -var ContainerCreateHeaders = { +const ContainerCreateHeaders = { serializedName: "Container_createHeaders", type: { name: "Composite", @@ -17815,7 +16294,7 @@ var ContainerCreateHeaders = { } } }; -var ContainerCreateExceptionHeaders = { +const ContainerCreateExceptionHeaders = { serializedName: "Container_createExceptionHeaders", type: { name: "Composite", @@ -17831,7 +16310,7 @@ var ContainerCreateExceptionHeaders = { } } }; -var ContainerGetPropertiesHeaders = { +const ContainerGetPropertiesHeaders = { serializedName: "Container_getPropertiesHeaders", type: { name: "Composite", @@ -17954,6 +16433,13 @@ var ContainerGetPropertiesHeaders = { name: "Boolean" } }, + isImmutableStorageWithVersioningEnabled: { + serializedName: "x-ms-immutable-storage-with-versioning-enabled", + xmlName: "x-ms-immutable-storage-with-versioning-enabled", + type: { + name: "Boolean" + } + }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", @@ -17964,7 +16450,7 @@ var ContainerGetPropertiesHeaders = { } } }; -var ContainerGetPropertiesExceptionHeaders = { +const ContainerGetPropertiesExceptionHeaders = { serializedName: "Container_getPropertiesExceptionHeaders", type: { name: "Composite", @@ -17980,7 +16466,7 @@ var ContainerGetPropertiesExceptionHeaders = { } } }; -var ContainerDeleteHeaders = { +const ContainerDeleteHeaders = { serializedName: "Container_deleteHeaders", type: { name: "Composite", @@ -18024,7 +16510,7 @@ var ContainerDeleteHeaders = { } } }; -var ContainerDeleteExceptionHeaders = { +const ContainerDeleteExceptionHeaders = { serializedName: "Container_deleteExceptionHeaders", type: { name: "Composite", @@ -18040,7 +16526,7 @@ var ContainerDeleteExceptionHeaders = { } } }; -var ContainerSetMetadataHeaders = { +const ContainerSetMetadataHeaders = { serializedName: "Container_setMetadataHeaders", type: { name: "Composite", @@ -18098,7 +16584,7 @@ var ContainerSetMetadataHeaders = { } } }; -var ContainerSetMetadataExceptionHeaders = { +const ContainerSetMetadataExceptionHeaders = { serializedName: "Container_setMetadataExceptionHeaders", type: { name: "Composite", @@ -18114,7 +16600,7 @@ var ContainerSetMetadataExceptionHeaders = { } } }; -var ContainerGetAccessPolicyHeaders = { +const ContainerGetAccessPolicyHeaders = { serializedName: "Container_getAccessPolicyHeaders", type: { name: "Composite", @@ -18180,7 +16666,7 @@ var ContainerGetAccessPolicyHeaders = { } } }; -var ContainerGetAccessPolicyExceptionHeaders = { +const ContainerGetAccessPolicyExceptionHeaders = { serializedName: "Container_getAccessPolicyExceptionHeaders", type: { name: "Composite", @@ -18196,7 +16682,7 @@ var ContainerGetAccessPolicyExceptionHeaders = { } } }; -var ContainerSetAccessPolicyHeaders = { +const ContainerSetAccessPolicyHeaders = { serializedName: "Container_setAccessPolicyHeaders", type: { name: "Composite", @@ -18254,7 +16740,7 @@ var ContainerSetAccessPolicyHeaders = { } } }; -var ContainerSetAccessPolicyExceptionHeaders = { +const ContainerSetAccessPolicyExceptionHeaders = { serializedName: "Container_setAccessPolicyExceptionHeaders", type: { name: "Composite", @@ -18270,7 +16756,7 @@ var ContainerSetAccessPolicyExceptionHeaders = { } } }; -var ContainerRestoreHeaders = { +const ContainerRestoreHeaders = { serializedName: "Container_restoreHeaders", type: { name: "Composite", @@ -18314,7 +16800,7 @@ var ContainerRestoreHeaders = { } } }; -var ContainerRestoreExceptionHeaders = { +const ContainerRestoreExceptionHeaders = { serializedName: "Container_restoreExceptionHeaders", type: { name: "Composite", @@ -18330,7 +16816,7 @@ var ContainerRestoreExceptionHeaders = { } } }; -var ContainerRenameHeaders = { +const ContainerRenameHeaders = { serializedName: "Container_renameHeaders", type: { name: "Composite", @@ -18374,7 +16860,7 @@ var ContainerRenameHeaders = { } } }; -var ContainerRenameExceptionHeaders = { +const ContainerRenameExceptionHeaders = { serializedName: "Container_renameExceptionHeaders", type: { name: "Composite", @@ -18390,7 +16876,7 @@ var ContainerRenameExceptionHeaders = { } } }; -var ContainerSubmitBatchHeaders = { +const ContainerSubmitBatchHeaders = { serializedName: "Container_submitBatchHeaders", type: { name: "Composite", @@ -18420,7 +16906,7 @@ var ContainerSubmitBatchHeaders = { } } }; -var ContainerSubmitBatchExceptionHeaders = { +const ContainerSubmitBatchExceptionHeaders = { serializedName: "Container_submitBatchExceptionHeaders", type: { name: "Composite", @@ -18436,7 +16922,7 @@ var ContainerSubmitBatchExceptionHeaders = { } } }; -var ContainerAcquireLeaseHeaders = { +const ContainerAcquireLeaseHeaders = { serializedName: "Container_acquireLeaseHeaders", type: { name: "Composite", @@ -18494,7 +16980,7 @@ var ContainerAcquireLeaseHeaders = { } } }; -var ContainerAcquireLeaseExceptionHeaders = { +const ContainerAcquireLeaseExceptionHeaders = { serializedName: "Container_acquireLeaseExceptionHeaders", type: { name: "Composite", @@ -18510,7 +16996,7 @@ var ContainerAcquireLeaseExceptionHeaders = { } } }; -var ContainerReleaseLeaseHeaders = { +const ContainerReleaseLeaseHeaders = { serializedName: "Container_releaseLeaseHeaders", type: { name: "Composite", @@ -18561,7 +17047,7 @@ var ContainerReleaseLeaseHeaders = { } } }; -var ContainerReleaseLeaseExceptionHeaders = { +const ContainerReleaseLeaseExceptionHeaders = { serializedName: "Container_releaseLeaseExceptionHeaders", type: { name: "Composite", @@ -18577,7 +17063,7 @@ var ContainerReleaseLeaseExceptionHeaders = { } } }; -var ContainerRenewLeaseHeaders = { +const ContainerRenewLeaseHeaders = { serializedName: "Container_renewLeaseHeaders", type: { name: "Composite", @@ -18635,7 +17121,7 @@ var ContainerRenewLeaseHeaders = { } } }; -var ContainerRenewLeaseExceptionHeaders = { +const ContainerRenewLeaseExceptionHeaders = { serializedName: "Container_renewLeaseExceptionHeaders", type: { name: "Composite", @@ -18651,7 +17137,7 @@ var ContainerRenewLeaseExceptionHeaders = { } } }; -var ContainerBreakLeaseHeaders = { +const ContainerBreakLeaseHeaders = { serializedName: "Container_breakLeaseHeaders", type: { name: "Composite", @@ -18709,7 +17195,7 @@ var ContainerBreakLeaseHeaders = { } } }; -var ContainerBreakLeaseExceptionHeaders = { +const ContainerBreakLeaseExceptionHeaders = { serializedName: "Container_breakLeaseExceptionHeaders", type: { name: "Composite", @@ -18725,7 +17211,7 @@ var ContainerBreakLeaseExceptionHeaders = { } } }; -var ContainerChangeLeaseHeaders = { +const ContainerChangeLeaseHeaders = { serializedName: "Container_changeLeaseHeaders", type: { name: "Composite", @@ -18783,7 +17269,7 @@ var ContainerChangeLeaseHeaders = { } } }; -var ContainerChangeLeaseExceptionHeaders = { +const ContainerChangeLeaseExceptionHeaders = { serializedName: "Container_changeLeaseExceptionHeaders", type: { name: "Composite", @@ -18799,7 +17285,7 @@ var ContainerChangeLeaseExceptionHeaders = { } } }; -var ContainerListBlobFlatSegmentHeaders = { +const ContainerListBlobFlatSegmentHeaders = { serializedName: "Container_listBlobFlatSegmentHeaders", type: { name: "Composite", @@ -18850,7 +17336,7 @@ var ContainerListBlobFlatSegmentHeaders = { } } }; -var ContainerListBlobFlatSegmentExceptionHeaders = { +const ContainerListBlobFlatSegmentExceptionHeaders = { serializedName: "Container_listBlobFlatSegmentExceptionHeaders", type: { name: "Composite", @@ -18866,7 +17352,7 @@ var ContainerListBlobFlatSegmentExceptionHeaders = { } } }; -var ContainerListBlobHierarchySegmentHeaders = { +const ContainerListBlobHierarchySegmentHeaders = { serializedName: "Container_listBlobHierarchySegmentHeaders", type: { name: "Composite", @@ -18917,7 +17403,7 @@ var ContainerListBlobHierarchySegmentHeaders = { } } }; -var ContainerListBlobHierarchySegmentExceptionHeaders = { +const ContainerListBlobHierarchySegmentExceptionHeaders = { serializedName: "Container_listBlobHierarchySegmentExceptionHeaders", type: { name: "Composite", @@ -18933,7 +17419,7 @@ var ContainerListBlobHierarchySegmentExceptionHeaders = { } } }; -var ContainerGetAccountInfoHeaders = { +const ContainerGetAccountInfoHeaders = { serializedName: "Container_getAccountInfoHeaders", type: { name: "Composite", @@ -18998,7 +17484,7 @@ var ContainerGetAccountInfoHeaders = { } } }; -var ContainerGetAccountInfoExceptionHeaders = { +const ContainerGetAccountInfoExceptionHeaders = { serializedName: "Container_getAccountInfoExceptionHeaders", type: { name: "Composite", @@ -19014,440 +17500,7 @@ var ContainerGetAccountInfoExceptionHeaders = { } } }; -var DirectoryCreateHeaders = { - serializedName: "Directory_createHeaders", - type: { - name: "Composite", - className: "DirectoryCreateHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - contentLength: { - serializedName: "content-length", - xmlName: "content-length", - type: { - name: "Number" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - } - } - } -}; -var DirectoryCreateExceptionHeaders = { - serializedName: "Directory_createExceptionHeaders", - type: { - name: "Composite", - className: "DirectoryCreateExceptionHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var DirectoryRenameHeaders = { - serializedName: "Directory_renameHeaders", - type: { - name: "Composite", - className: "DirectoryRenameHeaders", - modelProperties: { - marker: { - serializedName: "x-ms-continuation", - xmlName: "x-ms-continuation", - type: { - name: "String" - } - }, - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - contentLength: { - serializedName: "content-length", - xmlName: "content-length", - type: { - name: "Number" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - } - } - } -}; -var DirectoryRenameExceptionHeaders = { - serializedName: "Directory_renameExceptionHeaders", - type: { - name: "Composite", - className: "DirectoryRenameExceptionHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var DirectoryDeleteHeaders = { - serializedName: "Directory_deleteHeaders", - type: { - name: "Composite", - className: "DirectoryDeleteHeaders", - modelProperties: { - marker: { - serializedName: "x-ms-continuation", - xmlName: "x-ms-continuation", - type: { - name: "String" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - } - } - } -}; -var DirectoryDeleteExceptionHeaders = { - serializedName: "Directory_deleteExceptionHeaders", - type: { - name: "Composite", - className: "DirectoryDeleteExceptionHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var DirectorySetAccessControlHeaders = { - serializedName: "Directory_setAccessControlHeaders", - type: { - name: "Composite", - className: "DirectorySetAccessControlHeaders", - modelProperties: { - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var DirectorySetAccessControlExceptionHeaders = { - serializedName: "Directory_setAccessControlExceptionHeaders", - type: { - name: "Composite", - className: "DirectorySetAccessControlExceptionHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var DirectoryGetAccessControlHeaders = { - serializedName: "Directory_getAccessControlHeaders", - type: { - name: "Composite", - className: "DirectoryGetAccessControlHeaders", - modelProperties: { - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - xMsOwner: { - serializedName: "x-ms-owner", - xmlName: "x-ms-owner", - type: { - name: "String" - } - }, - xMsGroup: { - serializedName: "x-ms-group", - xmlName: "x-ms-group", - type: { - name: "String" - } - }, - xMsPermissions: { - serializedName: "x-ms-permissions", - xmlName: "x-ms-permissions", - type: { - name: "String" - } - }, - xMsAcl: { - serializedName: "x-ms-acl", - xmlName: "x-ms-acl", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var DirectoryGetAccessControlExceptionHeaders = { - serializedName: "Directory_getAccessControlExceptionHeaders", - type: { - name: "Composite", - className: "DirectoryGetAccessControlExceptionHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var BlobDownloadHeaders = { +const BlobDownloadHeaders = { serializedName: "Blob_downloadHeaders", type: { name: "Composite", @@ -19741,11 +17794,26 @@ var BlobDownloadHeaders = { name: "DateTimeRfc1123" } }, - contentCrc64: { - serializedName: "x-ms-content-crc64", - xmlName: "x-ms-content-crc64", + immutabilityPolicyExpiresOn: { + serializedName: "x-ms-immutability-policy-until-date", + xmlName: "x-ms-immutability-policy-until-date", type: { - name: "ByteArray" + name: "DateTimeRfc1123" + } + }, + immutabilityPolicyMode: { + serializedName: "x-ms-immutability-policy-mode", + xmlName: "x-ms-immutability-policy-mode", + type: { + name: "Enum", + allowedValues: ["Mutable", "Unlocked", "Locked"] + } + }, + legalHold: { + serializedName: "x-ms-legal-hold", + xmlName: "x-ms-legal-hold", + type: { + name: "Boolean" } }, errorCode: { @@ -19754,11 +17822,18 @@ var BlobDownloadHeaders = { type: { name: "String" } + }, + contentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } } } } }; -var BlobDownloadExceptionHeaders = { +const BlobDownloadExceptionHeaders = { serializedName: "Blob_downloadExceptionHeaders", type: { name: "Composite", @@ -19774,7 +17849,7 @@ var BlobDownloadExceptionHeaders = { } } }; -var BlobGetPropertiesHeaders = { +const BlobGetPropertiesHeaders = { serializedName: "Blob_getPropertiesHeaders", type: { name: "Composite", @@ -20118,6 +18193,28 @@ var BlobGetPropertiesHeaders = { name: "DateTimeRfc1123" } }, + immutabilityPolicyExpiresOn: { + serializedName: "x-ms-immutability-policy-until-date", + xmlName: "x-ms-immutability-policy-until-date", + type: { + name: "DateTimeRfc1123" + } + }, + immutabilityPolicyMode: { + serializedName: "x-ms-immutability-policy-mode", + xmlName: "x-ms-immutability-policy-mode", + type: { + name: "Enum", + allowedValues: ["Mutable", "Unlocked", "Locked"] + } + }, + legalHold: { + serializedName: "x-ms-legal-hold", + xmlName: "x-ms-legal-hold", + type: { + name: "Boolean" + } + }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", @@ -20128,7 +18225,7 @@ var BlobGetPropertiesHeaders = { } } }; -var BlobGetPropertiesExceptionHeaders = { +const BlobGetPropertiesExceptionHeaders = { serializedName: "Blob_getPropertiesExceptionHeaders", type: { name: "Composite", @@ -20144,7 +18241,7 @@ var BlobGetPropertiesExceptionHeaders = { } } }; -var BlobDeleteHeaders = { +const BlobDeleteHeaders = { serializedName: "Blob_deleteHeaders", type: { name: "Composite", @@ -20188,7 +18285,7 @@ var BlobDeleteHeaders = { } } }; -var BlobDeleteExceptionHeaders = { +const BlobDeleteExceptionHeaders = { serializedName: "Blob_deleteExceptionHeaders", type: { name: "Composite", @@ -20204,271 +18301,7 @@ var BlobDeleteExceptionHeaders = { } } }; -var BlobSetAccessControlHeaders = { - serializedName: "Blob_setAccessControlHeaders", - type: { - name: "Composite", - className: "BlobSetAccessControlHeaders", - modelProperties: { - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var BlobSetAccessControlExceptionHeaders = { - serializedName: "Blob_setAccessControlExceptionHeaders", - type: { - name: "Composite", - className: "BlobSetAccessControlExceptionHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var BlobGetAccessControlHeaders = { - serializedName: "Blob_getAccessControlHeaders", - type: { - name: "Composite", - className: "BlobGetAccessControlHeaders", - modelProperties: { - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - }, - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - xMsOwner: { - serializedName: "x-ms-owner", - xmlName: "x-ms-owner", - type: { - name: "String" - } - }, - xMsGroup: { - serializedName: "x-ms-group", - xmlName: "x-ms-group", - type: { - name: "String" - } - }, - xMsPermissions: { - serializedName: "x-ms-permissions", - xmlName: "x-ms-permissions", - type: { - name: "String" - } - }, - xMsAcl: { - serializedName: "x-ms-acl", - xmlName: "x-ms-acl", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var BlobGetAccessControlExceptionHeaders = { - serializedName: "Blob_getAccessControlExceptionHeaders", - type: { - name: "Composite", - className: "BlobGetAccessControlExceptionHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var BlobRenameHeaders = { - serializedName: "Blob_renameHeaders", - type: { - name: "Composite", - className: "BlobRenameHeaders", - modelProperties: { - etag: { - serializedName: "etag", - xmlName: "etag", - type: { - name: "String" - } - }, - lastModified: { - serializedName: "last-modified", - xmlName: "last-modified", - type: { - name: "DateTimeRfc1123" - } - }, - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - }, - contentLength: { - serializedName: "content-length", - xmlName: "content-length", - type: { - name: "Number" - } - }, - date: { - serializedName: "date", - xmlName: "date", - type: { - name: "DateTimeRfc1123" - } - } - } - } -}; -var BlobRenameExceptionHeaders = { - serializedName: "Blob_renameExceptionHeaders", - type: { - name: "Composite", - className: "BlobRenameExceptionHeaders", - modelProperties: { - clientRequestId: { - serializedName: "x-ms-client-request-id", - xmlName: "x-ms-client-request-id", - type: { - name: "String" - } - }, - requestId: { - serializedName: "x-ms-request-id", - xmlName: "x-ms-request-id", - type: { - name: "String" - } - }, - version: { - serializedName: "x-ms-version", - xmlName: "x-ms-version", - type: { - name: "String" - } - } - } - } -}; -var BlobUndeleteHeaders = { +const BlobUndeleteHeaders = { serializedName: "Blob_undeleteHeaders", type: { name: "Composite", @@ -20512,7 +18345,7 @@ var BlobUndeleteHeaders = { } } }; -var BlobUndeleteExceptionHeaders = { +const BlobUndeleteExceptionHeaders = { serializedName: "Blob_undeleteExceptionHeaders", type: { name: "Composite", @@ -20528,7 +18361,7 @@ var BlobUndeleteExceptionHeaders = { } } }; -var BlobSetExpiryHeaders = { +const BlobSetExpiryHeaders = { serializedName: "Blob_setExpiryHeaders", type: { name: "Composite", @@ -20579,7 +18412,7 @@ var BlobSetExpiryHeaders = { } } }; -var BlobSetExpiryExceptionHeaders = { +const BlobSetExpiryExceptionHeaders = { serializedName: "Blob_setExpiryExceptionHeaders", type: { name: "Composite", @@ -20595,7 +18428,7 @@ var BlobSetExpiryExceptionHeaders = { } } }; -var BlobSetHttpHeadersHeaders = { +const BlobSetHttpHeadersHeaders = { serializedName: "Blob_setHttpHeadersHeaders", type: { name: "Composite", @@ -20660,7 +18493,7 @@ var BlobSetHttpHeadersHeaders = { } } }; -var BlobSetHttpHeadersExceptionHeaders = { +const BlobSetHttpHeadersExceptionHeaders = { serializedName: "Blob_setHttpHeadersExceptionHeaders", type: { name: "Composite", @@ -20676,7 +18509,188 @@ var BlobSetHttpHeadersExceptionHeaders = { } } }; -var BlobSetMetadataHeaders = { +const BlobSetImmutabilityPolicyHeaders = { + serializedName: "Blob_setImmutabilityPolicyHeaders", + type: { + name: "Composite", + className: "BlobSetImmutabilityPolicyHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + immutabilityPolicyExpiry: { + serializedName: "x-ms-immutability-policy-until-date", + xmlName: "x-ms-immutability-policy-until-date", + type: { + name: "DateTimeRfc1123" + } + }, + immutabilityPolicyMode: { + serializedName: "x-ms-immutability-policy-mode", + xmlName: "x-ms-immutability-policy-mode", + type: { + name: "Enum", + allowedValues: ["Mutable", "Unlocked", "Locked"] + } + } + } + } +}; +const BlobSetImmutabilityPolicyExceptionHeaders = { + serializedName: "Blob_setImmutabilityPolicyExceptionHeaders", + type: { + name: "Composite", + className: "BlobSetImmutabilityPolicyExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +const BlobDeleteImmutabilityPolicyHeaders = { + serializedName: "Blob_deleteImmutabilityPolicyHeaders", + type: { + name: "Composite", + className: "BlobDeleteImmutabilityPolicyHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + } + } + } +}; +const BlobDeleteImmutabilityPolicyExceptionHeaders = { + serializedName: "Blob_deleteImmutabilityPolicyExceptionHeaders", + type: { + name: "Composite", + className: "BlobDeleteImmutabilityPolicyExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +const BlobSetLegalHoldHeaders = { + serializedName: "Blob_setLegalHoldHeaders", + type: { + name: "Composite", + className: "BlobSetLegalHoldHeaders", + modelProperties: { + clientRequestId: { + serializedName: "x-ms-client-request-id", + xmlName: "x-ms-client-request-id", + type: { + name: "String" + } + }, + requestId: { + serializedName: "x-ms-request-id", + xmlName: "x-ms-request-id", + type: { + name: "String" + } + }, + version: { + serializedName: "x-ms-version", + xmlName: "x-ms-version", + type: { + name: "String" + } + }, + date: { + serializedName: "date", + xmlName: "date", + type: { + name: "DateTimeRfc1123" + } + }, + legalHold: { + serializedName: "x-ms-legal-hold", + xmlName: "x-ms-legal-hold", + type: { + name: "Boolean" + } + } + } + } +}; +const BlobSetLegalHoldExceptionHeaders = { + serializedName: "Blob_setLegalHoldExceptionHeaders", + type: { + name: "Composite", + className: "BlobSetLegalHoldExceptionHeaders", + modelProperties: { + errorCode: { + serializedName: "x-ms-error-code", + xmlName: "x-ms-error-code", + type: { + name: "String" + } + } + } + } +}; +const BlobSetMetadataHeaders = { serializedName: "Blob_setMetadataHeaders", type: { name: "Composite", @@ -20762,7 +18776,7 @@ var BlobSetMetadataHeaders = { } } }; -var BlobSetMetadataExceptionHeaders = { +const BlobSetMetadataExceptionHeaders = { serializedName: "Blob_setMetadataExceptionHeaders", type: { name: "Composite", @@ -20778,7 +18792,7 @@ var BlobSetMetadataExceptionHeaders = { } } }; -var BlobAcquireLeaseHeaders = { +const BlobAcquireLeaseHeaders = { serializedName: "Blob_acquireLeaseHeaders", type: { name: "Composite", @@ -20836,7 +18850,7 @@ var BlobAcquireLeaseHeaders = { } } }; -var BlobAcquireLeaseExceptionHeaders = { +const BlobAcquireLeaseExceptionHeaders = { serializedName: "Blob_acquireLeaseExceptionHeaders", type: { name: "Composite", @@ -20852,7 +18866,7 @@ var BlobAcquireLeaseExceptionHeaders = { } } }; -var BlobReleaseLeaseHeaders = { +const BlobReleaseLeaseHeaders = { serializedName: "Blob_releaseLeaseHeaders", type: { name: "Composite", @@ -20903,7 +18917,7 @@ var BlobReleaseLeaseHeaders = { } } }; -var BlobReleaseLeaseExceptionHeaders = { +const BlobReleaseLeaseExceptionHeaders = { serializedName: "Blob_releaseLeaseExceptionHeaders", type: { name: "Composite", @@ -20919,7 +18933,7 @@ var BlobReleaseLeaseExceptionHeaders = { } } }; -var BlobRenewLeaseHeaders = { +const BlobRenewLeaseHeaders = { serializedName: "Blob_renewLeaseHeaders", type: { name: "Composite", @@ -20977,7 +18991,7 @@ var BlobRenewLeaseHeaders = { } } }; -var BlobRenewLeaseExceptionHeaders = { +const BlobRenewLeaseExceptionHeaders = { serializedName: "Blob_renewLeaseExceptionHeaders", type: { name: "Composite", @@ -20993,7 +19007,7 @@ var BlobRenewLeaseExceptionHeaders = { } } }; -var BlobChangeLeaseHeaders = { +const BlobChangeLeaseHeaders = { serializedName: "Blob_changeLeaseHeaders", type: { name: "Composite", @@ -21051,7 +19065,7 @@ var BlobChangeLeaseHeaders = { } } }; -var BlobChangeLeaseExceptionHeaders = { +const BlobChangeLeaseExceptionHeaders = { serializedName: "Blob_changeLeaseExceptionHeaders", type: { name: "Composite", @@ -21067,7 +19081,7 @@ var BlobChangeLeaseExceptionHeaders = { } } }; -var BlobBreakLeaseHeaders = { +const BlobBreakLeaseHeaders = { serializedName: "Blob_breakLeaseHeaders", type: { name: "Composite", @@ -21125,7 +19139,7 @@ var BlobBreakLeaseHeaders = { } } }; -var BlobBreakLeaseExceptionHeaders = { +const BlobBreakLeaseExceptionHeaders = { serializedName: "Blob_breakLeaseExceptionHeaders", type: { name: "Composite", @@ -21141,7 +19155,7 @@ var BlobBreakLeaseExceptionHeaders = { } } }; -var BlobCreateSnapshotHeaders = { +const BlobCreateSnapshotHeaders = { serializedName: "Blob_createSnapshotHeaders", type: { name: "Composite", @@ -21220,7 +19234,7 @@ var BlobCreateSnapshotHeaders = { } } }; -var BlobCreateSnapshotExceptionHeaders = { +const BlobCreateSnapshotExceptionHeaders = { serializedName: "Blob_createSnapshotExceptionHeaders", type: { name: "Composite", @@ -21236,7 +19250,7 @@ var BlobCreateSnapshotExceptionHeaders = { } } }; -var BlobStartCopyFromURLHeaders = { +const BlobStartCopyFromURLHeaders = { serializedName: "Blob_startCopyFromURLHeaders", type: { name: "Composite", @@ -21316,7 +19330,7 @@ var BlobStartCopyFromURLHeaders = { } } }; -var BlobStartCopyFromURLExceptionHeaders = { +const BlobStartCopyFromURLExceptionHeaders = { serializedName: "Blob_startCopyFromURLExceptionHeaders", type: { name: "Composite", @@ -21332,7 +19346,7 @@ var BlobStartCopyFromURLExceptionHeaders = { } } }; -var BlobCopyFromURLHeaders = { +const BlobCopyFromURLHeaders = { serializedName: "Blob_copyFromURLHeaders", type: { name: "Composite", @@ -21426,7 +19440,7 @@ var BlobCopyFromURLHeaders = { } } }; -var BlobCopyFromURLExceptionHeaders = { +const BlobCopyFromURLExceptionHeaders = { serializedName: "Blob_copyFromURLExceptionHeaders", type: { name: "Composite", @@ -21442,7 +19456,7 @@ var BlobCopyFromURLExceptionHeaders = { } } }; -var BlobAbortCopyFromURLHeaders = { +const BlobAbortCopyFromURLHeaders = { serializedName: "Blob_abortCopyFromURLHeaders", type: { name: "Composite", @@ -21486,7 +19500,7 @@ var BlobAbortCopyFromURLHeaders = { } } }; -var BlobAbortCopyFromURLExceptionHeaders = { +const BlobAbortCopyFromURLExceptionHeaders = { serializedName: "Blob_abortCopyFromURLExceptionHeaders", type: { name: "Composite", @@ -21502,7 +19516,7 @@ var BlobAbortCopyFromURLExceptionHeaders = { } } }; -var BlobSetTierHeaders = { +const BlobSetTierHeaders = { serializedName: "Blob_setTierHeaders", type: { name: "Composite", @@ -21539,7 +19553,7 @@ var BlobSetTierHeaders = { } } }; -var BlobSetTierExceptionHeaders = { +const BlobSetTierExceptionHeaders = { serializedName: "Blob_setTierExceptionHeaders", type: { name: "Composite", @@ -21555,7 +19569,7 @@ var BlobSetTierExceptionHeaders = { } } }; -var BlobGetAccountInfoHeaders = { +const BlobGetAccountInfoHeaders = { serializedName: "Blob_getAccountInfoHeaders", type: { name: "Composite", @@ -21620,7 +19634,7 @@ var BlobGetAccountInfoHeaders = { } } }; -var BlobGetAccountInfoExceptionHeaders = { +const BlobGetAccountInfoExceptionHeaders = { serializedName: "Blob_getAccountInfoExceptionHeaders", type: { name: "Composite", @@ -21636,7 +19650,7 @@ var BlobGetAccountInfoExceptionHeaders = { } } }; -var BlobQueryHeaders = { +const BlobQueryHeaders = { serializedName: "Blob_queryHeaders", type: { name: "Composite", @@ -21878,24 +19892,24 @@ var BlobQueryHeaders = { name: "ByteArray" } }, - contentCrc64: { - serializedName: "x-ms-content-crc64", - xmlName: "x-ms-content-crc64", - type: { - name: "ByteArray" - } - }, errorCode: { serializedName: "x-ms-error-code", xmlName: "x-ms-error-code", type: { name: "String" } + }, + contentCrc64: { + serializedName: "x-ms-content-crc64", + xmlName: "x-ms-content-crc64", + type: { + name: "ByteArray" + } } } } }; -var BlobQueryExceptionHeaders = { +const BlobQueryExceptionHeaders = { serializedName: "Blob_queryExceptionHeaders", type: { name: "Composite", @@ -21911,7 +19925,7 @@ var BlobQueryExceptionHeaders = { } } }; -var BlobGetTagsHeaders = { +const BlobGetTagsHeaders = { serializedName: "Blob_getTagsHeaders", type: { name: "Composite", @@ -21955,7 +19969,7 @@ var BlobGetTagsHeaders = { } } }; -var BlobGetTagsExceptionHeaders = { +const BlobGetTagsExceptionHeaders = { serializedName: "Blob_getTagsExceptionHeaders", type: { name: "Composite", @@ -21971,7 +19985,7 @@ var BlobGetTagsExceptionHeaders = { } } }; -var BlobSetTagsHeaders = { +const BlobSetTagsHeaders = { serializedName: "Blob_setTagsHeaders", type: { name: "Composite", @@ -22015,7 +20029,7 @@ var BlobSetTagsHeaders = { } } }; -var BlobSetTagsExceptionHeaders = { +const BlobSetTagsExceptionHeaders = { serializedName: "Blob_setTagsExceptionHeaders", type: { name: "Composite", @@ -22031,7 +20045,7 @@ var BlobSetTagsExceptionHeaders = { } } }; -var PageBlobCreateHeaders = { +const PageBlobCreateHeaders = { serializedName: "PageBlob_createHeaders", type: { name: "Composite", @@ -22124,7 +20138,7 @@ var PageBlobCreateHeaders = { } } }; -var PageBlobCreateExceptionHeaders = { +const PageBlobCreateExceptionHeaders = { serializedName: "PageBlob_createExceptionHeaders", type: { name: "Composite", @@ -22140,7 +20154,7 @@ var PageBlobCreateExceptionHeaders = { } } }; -var PageBlobUploadPagesHeaders = { +const PageBlobUploadPagesHeaders = { serializedName: "PageBlob_uploadPagesHeaders", type: { name: "Composite", @@ -22240,7 +20254,7 @@ var PageBlobUploadPagesHeaders = { } } }; -var PageBlobUploadPagesExceptionHeaders = { +const PageBlobUploadPagesExceptionHeaders = { serializedName: "PageBlob_uploadPagesExceptionHeaders", type: { name: "Composite", @@ -22256,7 +20270,7 @@ var PageBlobUploadPagesExceptionHeaders = { } } }; -var PageBlobClearPagesHeaders = { +const PageBlobClearPagesHeaders = { serializedName: "PageBlob_clearPagesHeaders", type: { name: "Composite", @@ -22335,7 +20349,7 @@ var PageBlobClearPagesHeaders = { } } }; -var PageBlobClearPagesExceptionHeaders = { +const PageBlobClearPagesExceptionHeaders = { serializedName: "PageBlob_clearPagesExceptionHeaders", type: { name: "Composite", @@ -22351,7 +20365,7 @@ var PageBlobClearPagesExceptionHeaders = { } } }; -var PageBlobUploadPagesFromURLHeaders = { +const PageBlobUploadPagesFromURLHeaders = { serializedName: "PageBlob_uploadPagesFromURLHeaders", type: { name: "Composite", @@ -22444,7 +20458,7 @@ var PageBlobUploadPagesFromURLHeaders = { } } }; -var PageBlobUploadPagesFromURLExceptionHeaders = { +const PageBlobUploadPagesFromURLExceptionHeaders = { serializedName: "PageBlob_uploadPagesFromURLExceptionHeaders", type: { name: "Composite", @@ -22460,7 +20474,7 @@ var PageBlobUploadPagesFromURLExceptionHeaders = { } } }; -var PageBlobGetPageRangesHeaders = { +const PageBlobGetPageRangesHeaders = { serializedName: "PageBlob_getPageRangesHeaders", type: { name: "Composite", @@ -22525,7 +20539,7 @@ var PageBlobGetPageRangesHeaders = { } } }; -var PageBlobGetPageRangesExceptionHeaders = { +const PageBlobGetPageRangesExceptionHeaders = { serializedName: "PageBlob_getPageRangesExceptionHeaders", type: { name: "Composite", @@ -22541,7 +20555,7 @@ var PageBlobGetPageRangesExceptionHeaders = { } } }; -var PageBlobGetPageRangesDiffHeaders = { +const PageBlobGetPageRangesDiffHeaders = { serializedName: "PageBlob_getPageRangesDiffHeaders", type: { name: "Composite", @@ -22606,7 +20620,7 @@ var PageBlobGetPageRangesDiffHeaders = { } } }; -var PageBlobGetPageRangesDiffExceptionHeaders = { +const PageBlobGetPageRangesDiffExceptionHeaders = { serializedName: "PageBlob_getPageRangesDiffExceptionHeaders", type: { name: "Composite", @@ -22622,7 +20636,7 @@ var PageBlobGetPageRangesDiffExceptionHeaders = { } } }; -var PageBlobResizeHeaders = { +const PageBlobResizeHeaders = { serializedName: "PageBlob_resizeHeaders", type: { name: "Composite", @@ -22687,7 +20701,7 @@ var PageBlobResizeHeaders = { } } }; -var PageBlobResizeExceptionHeaders = { +const PageBlobResizeExceptionHeaders = { serializedName: "PageBlob_resizeExceptionHeaders", type: { name: "Composite", @@ -22703,7 +20717,7 @@ var PageBlobResizeExceptionHeaders = { } } }; -var PageBlobUpdateSequenceNumberHeaders = { +const PageBlobUpdateSequenceNumberHeaders = { serializedName: "PageBlob_updateSequenceNumberHeaders", type: { name: "Composite", @@ -22768,7 +20782,7 @@ var PageBlobUpdateSequenceNumberHeaders = { } } }; -var PageBlobUpdateSequenceNumberExceptionHeaders = { +const PageBlobUpdateSequenceNumberExceptionHeaders = { serializedName: "PageBlob_updateSequenceNumberExceptionHeaders", type: { name: "Composite", @@ -22784,7 +20798,7 @@ var PageBlobUpdateSequenceNumberExceptionHeaders = { } } }; -var PageBlobCopyIncrementalHeaders = { +const PageBlobCopyIncrementalHeaders = { serializedName: "PageBlob_copyIncrementalHeaders", type: { name: "Composite", @@ -22857,7 +20871,7 @@ var PageBlobCopyIncrementalHeaders = { } } }; -var PageBlobCopyIncrementalExceptionHeaders = { +const PageBlobCopyIncrementalExceptionHeaders = { serializedName: "PageBlob_copyIncrementalExceptionHeaders", type: { name: "Composite", @@ -22873,7 +20887,7 @@ var PageBlobCopyIncrementalExceptionHeaders = { } } }; -var AppendBlobCreateHeaders = { +const AppendBlobCreateHeaders = { serializedName: "AppendBlob_createHeaders", type: { name: "Composite", @@ -22966,7 +20980,7 @@ var AppendBlobCreateHeaders = { } } }; -var AppendBlobCreateExceptionHeaders = { +const AppendBlobCreateExceptionHeaders = { serializedName: "AppendBlob_createExceptionHeaders", type: { name: "Composite", @@ -22982,7 +20996,7 @@ var AppendBlobCreateExceptionHeaders = { } } }; -var AppendBlobAppendBlockHeaders = { +const AppendBlobAppendBlockHeaders = { serializedName: "AppendBlob_appendBlockHeaders", type: { name: "Composite", @@ -23089,7 +21103,7 @@ var AppendBlobAppendBlockHeaders = { } } }; -var AppendBlobAppendBlockExceptionHeaders = { +const AppendBlobAppendBlockExceptionHeaders = { serializedName: "AppendBlob_appendBlockExceptionHeaders", type: { name: "Composite", @@ -23105,7 +21119,7 @@ var AppendBlobAppendBlockExceptionHeaders = { } } }; -var AppendBlobAppendBlockFromUrlHeaders = { +const AppendBlobAppendBlockFromUrlHeaders = { serializedName: "AppendBlob_appendBlockFromUrlHeaders", type: { name: "Composite", @@ -23205,7 +21219,7 @@ var AppendBlobAppendBlockFromUrlHeaders = { } } }; -var AppendBlobAppendBlockFromUrlExceptionHeaders = { +const AppendBlobAppendBlockFromUrlExceptionHeaders = { serializedName: "AppendBlob_appendBlockFromUrlExceptionHeaders", type: { name: "Composite", @@ -23221,7 +21235,7 @@ var AppendBlobAppendBlockFromUrlExceptionHeaders = { } } }; -var AppendBlobSealHeaders = { +const AppendBlobSealHeaders = { serializedName: "AppendBlob_sealHeaders", type: { name: "Composite", @@ -23279,7 +21293,7 @@ var AppendBlobSealHeaders = { } } }; -var AppendBlobSealExceptionHeaders = { +const AppendBlobSealExceptionHeaders = { serializedName: "AppendBlob_sealExceptionHeaders", type: { name: "Composite", @@ -23295,7 +21309,7 @@ var AppendBlobSealExceptionHeaders = { } } }; -var BlockBlobUploadHeaders = { +const BlockBlobUploadHeaders = { serializedName: "BlockBlob_uploadHeaders", type: { name: "Composite", @@ -23388,7 +21402,7 @@ var BlockBlobUploadHeaders = { } } }; -var BlockBlobUploadExceptionHeaders = { +const BlockBlobUploadExceptionHeaders = { serializedName: "BlockBlob_uploadExceptionHeaders", type: { name: "Composite", @@ -23404,7 +21418,7 @@ var BlockBlobUploadExceptionHeaders = { } } }; -var BlockBlobPutBlobFromUrlHeaders = { +const BlockBlobPutBlobFromUrlHeaders = { serializedName: "BlockBlob_putBlobFromUrlHeaders", type: { name: "Composite", @@ -23497,7 +21511,7 @@ var BlockBlobPutBlobFromUrlHeaders = { } } }; -var BlockBlobPutBlobFromUrlExceptionHeaders = { +const BlockBlobPutBlobFromUrlExceptionHeaders = { serializedName: "BlockBlob_putBlobFromUrlExceptionHeaders", type: { name: "Composite", @@ -23513,7 +21527,7 @@ var BlockBlobPutBlobFromUrlExceptionHeaders = { } } }; -var BlockBlobStageBlockHeaders = { +const BlockBlobStageBlockHeaders = { serializedName: "BlockBlob_stageBlockHeaders", type: { name: "Composite", @@ -23592,7 +21606,7 @@ var BlockBlobStageBlockHeaders = { } } }; -var BlockBlobStageBlockExceptionHeaders = { +const BlockBlobStageBlockExceptionHeaders = { serializedName: "BlockBlob_stageBlockExceptionHeaders", type: { name: "Composite", @@ -23608,7 +21622,7 @@ var BlockBlobStageBlockExceptionHeaders = { } } }; -var BlockBlobStageBlockFromURLHeaders = { +const BlockBlobStageBlockFromURLHeaders = { serializedName: "BlockBlob_stageBlockFromURLHeaders", type: { name: "Composite", @@ -23687,7 +21701,7 @@ var BlockBlobStageBlockFromURLHeaders = { } } }; -var BlockBlobStageBlockFromURLExceptionHeaders = { +const BlockBlobStageBlockFromURLExceptionHeaders = { serializedName: "BlockBlob_stageBlockFromURLExceptionHeaders", type: { name: "Composite", @@ -23703,7 +21717,7 @@ var BlockBlobStageBlockFromURLExceptionHeaders = { } } }; -var BlockBlobCommitBlockListHeaders = { +const BlockBlobCommitBlockListHeaders = { serializedName: "BlockBlob_commitBlockListHeaders", type: { name: "Composite", @@ -23803,7 +21817,7 @@ var BlockBlobCommitBlockListHeaders = { } } }; -var BlockBlobCommitBlockListExceptionHeaders = { +const BlockBlobCommitBlockListExceptionHeaders = { serializedName: "BlockBlob_commitBlockListExceptionHeaders", type: { name: "Composite", @@ -23819,7 +21833,7 @@ var BlockBlobCommitBlockListExceptionHeaders = { } } }; -var BlockBlobGetBlockListHeaders = { +const BlockBlobGetBlockListHeaders = { serializedName: "BlockBlob_getBlockListHeaders", type: { name: "Composite", @@ -23891,7 +21905,7 @@ var BlockBlobGetBlockListHeaders = { } } }; -var BlockBlobGetBlockListExceptionHeaders = { +const BlockBlobGetBlockListExceptionHeaders = { serializedName: "BlockBlob_getBlockListExceptionHeaders", type: { name: "Composite", @@ -23937,8 +21951,6 @@ var Mappers = /*#__PURE__*/Object.freeze({ ListBlobsHierarchySegmentResponse: ListBlobsHierarchySegmentResponse, BlobHierarchyListSegment: BlobHierarchyListSegment, BlobPrefix: BlobPrefix, - DataLakeStorageError: DataLakeStorageError, - DataLakeStorageErrorError: DataLakeStorageErrorError, BlockLookupList: BlockLookupList, BlockList: BlockList, Block: Block, @@ -24002,34 +22014,24 @@ var Mappers = /*#__PURE__*/Object.freeze({ ContainerListBlobHierarchySegmentExceptionHeaders: ContainerListBlobHierarchySegmentExceptionHeaders, ContainerGetAccountInfoHeaders: ContainerGetAccountInfoHeaders, ContainerGetAccountInfoExceptionHeaders: ContainerGetAccountInfoExceptionHeaders, - DirectoryCreateHeaders: DirectoryCreateHeaders, - DirectoryCreateExceptionHeaders: DirectoryCreateExceptionHeaders, - DirectoryRenameHeaders: DirectoryRenameHeaders, - DirectoryRenameExceptionHeaders: DirectoryRenameExceptionHeaders, - DirectoryDeleteHeaders: DirectoryDeleteHeaders, - DirectoryDeleteExceptionHeaders: DirectoryDeleteExceptionHeaders, - DirectorySetAccessControlHeaders: DirectorySetAccessControlHeaders, - DirectorySetAccessControlExceptionHeaders: DirectorySetAccessControlExceptionHeaders, - DirectoryGetAccessControlHeaders: DirectoryGetAccessControlHeaders, - DirectoryGetAccessControlExceptionHeaders: DirectoryGetAccessControlExceptionHeaders, BlobDownloadHeaders: BlobDownloadHeaders, BlobDownloadExceptionHeaders: BlobDownloadExceptionHeaders, BlobGetPropertiesHeaders: BlobGetPropertiesHeaders, BlobGetPropertiesExceptionHeaders: BlobGetPropertiesExceptionHeaders, BlobDeleteHeaders: BlobDeleteHeaders, BlobDeleteExceptionHeaders: BlobDeleteExceptionHeaders, - BlobSetAccessControlHeaders: BlobSetAccessControlHeaders, - BlobSetAccessControlExceptionHeaders: BlobSetAccessControlExceptionHeaders, - BlobGetAccessControlHeaders: BlobGetAccessControlHeaders, - BlobGetAccessControlExceptionHeaders: BlobGetAccessControlExceptionHeaders, - BlobRenameHeaders: BlobRenameHeaders, - BlobRenameExceptionHeaders: BlobRenameExceptionHeaders, BlobUndeleteHeaders: BlobUndeleteHeaders, BlobUndeleteExceptionHeaders: BlobUndeleteExceptionHeaders, BlobSetExpiryHeaders: BlobSetExpiryHeaders, BlobSetExpiryExceptionHeaders: BlobSetExpiryExceptionHeaders, BlobSetHttpHeadersHeaders: BlobSetHttpHeadersHeaders, BlobSetHttpHeadersExceptionHeaders: BlobSetHttpHeadersExceptionHeaders, + BlobSetImmutabilityPolicyHeaders: BlobSetImmutabilityPolicyHeaders, + BlobSetImmutabilityPolicyExceptionHeaders: BlobSetImmutabilityPolicyExceptionHeaders, + BlobDeleteImmutabilityPolicyHeaders: BlobDeleteImmutabilityPolicyHeaders, + BlobDeleteImmutabilityPolicyExceptionHeaders: BlobDeleteImmutabilityPolicyExceptionHeaders, + BlobSetLegalHoldHeaders: BlobSetLegalHoldHeaders, + BlobSetLegalHoldExceptionHeaders: BlobSetLegalHoldExceptionHeaders, BlobSetMetadataHeaders: BlobSetMetadataHeaders, BlobSetMetadataExceptionHeaders: BlobSetMetadataExceptionHeaders, BlobAcquireLeaseHeaders: BlobAcquireLeaseHeaders, @@ -24107,7 +22109,7 @@ var Mappers = /*#__PURE__*/Object.freeze({ * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ -var contentType = { +const contentType = { parameterPath: ["options", "contentType"], mapper: { defaultValue: "application/xml", @@ -24118,11 +22120,11 @@ var contentType = { } } }; -var blobServiceProperties = { +const blobServiceProperties = { parameterPath: "blobServiceProperties", mapper: BlobServiceProperties }; -var accept = { +const accept = { parameterPath: "accept", mapper: { defaultValue: "application/xml", @@ -24133,7 +22135,7 @@ var accept = { } } }; -var url = { +const url = { parameterPath: "url", mapper: { serializedName: "url", @@ -24145,7 +22147,7 @@ var url = { }, skipEncoding: true }; -var restype = { +const restype = { parameterPath: "restype", mapper: { defaultValue: "service", @@ -24156,7 +22158,7 @@ var restype = { } } }; -var comp = { +const comp = { parameterPath: "comp", mapper: { defaultValue: "properties", @@ -24167,7 +22169,7 @@ var comp = { } } }; -var timeoutInSeconds = { +const timeoutInSeconds = { parameterPath: ["options", "timeoutInSeconds"], mapper: { constraints: { @@ -24180,10 +22182,10 @@ var timeoutInSeconds = { } } }; -var version = { +const version = { parameterPath: "version", mapper: { - defaultValue: "2020-08-04", + defaultValue: "2020-10-02", isConstant: true, serializedName: "x-ms-version", type: { @@ -24191,7 +22193,7 @@ var version = { } } }; -var requestId = { +const requestId = { parameterPath: ["options", "requestId"], mapper: { serializedName: "x-ms-client-request-id", @@ -24201,7 +22203,7 @@ var requestId = { } } }; -var accept1 = { +const accept1 = { parameterPath: "accept", mapper: { defaultValue: "application/xml", @@ -24212,7 +22214,7 @@ var accept1 = { } } }; -var comp1 = { +const comp1 = { parameterPath: "comp", mapper: { defaultValue: "stats", @@ -24223,7 +22225,7 @@ var comp1 = { } } }; -var comp2 = { +const comp2 = { parameterPath: "comp", mapper: { defaultValue: "list", @@ -24234,7 +22236,7 @@ var comp2 = { } } }; -var prefix = { +const prefix = { parameterPath: ["options", "prefix"], mapper: { serializedName: "prefix", @@ -24244,7 +22246,7 @@ var prefix = { } } }; -var marker = { +const marker = { parameterPath: ["options", "marker"], mapper: { serializedName: "marker", @@ -24254,7 +22256,7 @@ var marker = { } } }; -var maxPageSize = { +const maxPageSize = { parameterPath: ["options", "maxPageSize"], mapper: { constraints: { @@ -24267,7 +22269,7 @@ var maxPageSize = { } } }; -var include = { +const include = { parameterPath: ["options", "include"], mapper: { serializedName: "include", @@ -24285,11 +22287,11 @@ var include = { }, collectionFormat: coreHttp.QueryCollectionFormat.Csv }; -var keyInfo = { +const keyInfo = { parameterPath: "keyInfo", mapper: KeyInfo }; -var comp3 = { +const comp3 = { parameterPath: "comp", mapper: { defaultValue: "userdelegationkey", @@ -24300,7 +22302,7 @@ var comp3 = { } } }; -var restype1 = { +const restype1 = { parameterPath: "restype", mapper: { defaultValue: "account", @@ -24311,7 +22313,7 @@ var restype1 = { } } }; -var body = { +const body = { parameterPath: "body", mapper: { serializedName: "body", @@ -24322,7 +22324,7 @@ var body = { } } }; -var comp4 = { +const comp4 = { parameterPath: "comp", mapper: { defaultValue: "batch", @@ -24333,7 +22335,7 @@ var comp4 = { } } }; -var contentLength = { +const contentLength = { parameterPath: "contentLength", mapper: { serializedName: "Content-Length", @@ -24344,7 +22346,7 @@ var contentLength = { } } }; -var multipartContentType = { +const multipartContentType = { parameterPath: "multipartContentType", mapper: { serializedName: "Content-Type", @@ -24355,7 +22357,7 @@ var multipartContentType = { } } }; -var comp5 = { +const comp5 = { parameterPath: "comp", mapper: { defaultValue: "blobs", @@ -24366,7 +22368,7 @@ var comp5 = { } } }; -var where = { +const where = { parameterPath: ["options", "where"], mapper: { serializedName: "where", @@ -24376,7 +22378,7 @@ var where = { } } }; -var restype2 = { +const restype2 = { parameterPath: "restype", mapper: { defaultValue: "container", @@ -24387,7 +22389,7 @@ var restype2 = { } } }; -var metadata = { +const metadata = { parameterPath: ["options", "metadata"], mapper: { serializedName: "x-ms-meta", @@ -24399,7 +22401,7 @@ var metadata = { headerCollectionPrefix: "x-ms-meta-" } }; -var access = { +const access = { parameterPath: ["options", "access"], mapper: { serializedName: "x-ms-blob-public-access", @@ -24410,7 +22412,7 @@ var access = { } } }; -var defaultEncryptionScope = { +const defaultEncryptionScope = { parameterPath: [ "options", "containerEncryptionScope", @@ -24424,7 +22426,7 @@ var defaultEncryptionScope = { } } }; -var preventEncryptionScopeOverride = { +const preventEncryptionScopeOverride = { parameterPath: [ "options", "containerEncryptionScope", @@ -24438,7 +22440,7 @@ var preventEncryptionScopeOverride = { } } }; -var leaseId = { +const leaseId = { parameterPath: ["options", "leaseAccessConditions", "leaseId"], mapper: { serializedName: "x-ms-lease-id", @@ -24448,7 +22450,7 @@ var leaseId = { } } }; -var ifModifiedSince = { +const ifModifiedSince = { parameterPath: ["options", "modifiedAccessConditions", "ifModifiedSince"], mapper: { serializedName: "If-Modified-Since", @@ -24458,7 +22460,7 @@ var ifModifiedSince = { } } }; -var ifUnmodifiedSince = { +const ifUnmodifiedSince = { parameterPath: ["options", "modifiedAccessConditions", "ifUnmodifiedSince"], mapper: { serializedName: "If-Unmodified-Since", @@ -24468,7 +22470,7 @@ var ifUnmodifiedSince = { } } }; -var comp6 = { +const comp6 = { parameterPath: "comp", mapper: { defaultValue: "metadata", @@ -24479,7 +22481,7 @@ var comp6 = { } } }; -var comp7 = { +const comp7 = { parameterPath: "comp", mapper: { defaultValue: "acl", @@ -24490,7 +22492,7 @@ var comp7 = { } } }; -var containerAcl = { +const containerAcl = { parameterPath: ["options", "containerAcl"], mapper: { serializedName: "containerAcl", @@ -24508,7 +22510,7 @@ var containerAcl = { } } }; -var comp8 = { +const comp8 = { parameterPath: "comp", mapper: { defaultValue: "undelete", @@ -24519,7 +22521,7 @@ var comp8 = { } } }; -var deletedContainerName = { +const deletedContainerName = { parameterPath: ["options", "deletedContainerName"], mapper: { serializedName: "x-ms-deleted-container-name", @@ -24529,7 +22531,7 @@ var deletedContainerName = { } } }; -var deletedContainerVersion = { +const deletedContainerVersion = { parameterPath: ["options", "deletedContainerVersion"], mapper: { serializedName: "x-ms-deleted-container-version", @@ -24539,7 +22541,7 @@ var deletedContainerVersion = { } } }; -var comp9 = { +const comp9 = { parameterPath: "comp", mapper: { defaultValue: "rename", @@ -24550,7 +22552,7 @@ var comp9 = { } } }; -var sourceContainerName = { +const sourceContainerName = { parameterPath: "sourceContainerName", mapper: { serializedName: "x-ms-source-container-name", @@ -24561,7 +22563,7 @@ var sourceContainerName = { } } }; -var sourceLeaseId = { +const sourceLeaseId = { parameterPath: ["options", "sourceLeaseId"], mapper: { serializedName: "x-ms-source-lease-id", @@ -24571,7 +22573,7 @@ var sourceLeaseId = { } } }; -var comp10 = { +const comp10 = { parameterPath: "comp", mapper: { defaultValue: "lease", @@ -24582,7 +22584,7 @@ var comp10 = { } } }; -var action = { +const action = { parameterPath: "action", mapper: { defaultValue: "acquire", @@ -24593,7 +22595,7 @@ var action = { } } }; -var duration = { +const duration = { parameterPath: ["options", "duration"], mapper: { serializedName: "x-ms-lease-duration", @@ -24603,7 +22605,7 @@ var duration = { } } }; -var proposedLeaseId = { +const proposedLeaseId = { parameterPath: ["options", "proposedLeaseId"], mapper: { serializedName: "x-ms-proposed-lease-id", @@ -24613,7 +22615,7 @@ var proposedLeaseId = { } } }; -var action1 = { +const action1 = { parameterPath: "action", mapper: { defaultValue: "release", @@ -24624,7 +22626,7 @@ var action1 = { } } }; -var leaseId1 = { +const leaseId1 = { parameterPath: "leaseId", mapper: { serializedName: "x-ms-lease-id", @@ -24635,7 +22637,7 @@ var leaseId1 = { } } }; -var action2 = { +const action2 = { parameterPath: "action", mapper: { defaultValue: "renew", @@ -24646,7 +22648,7 @@ var action2 = { } } }; -var action3 = { +const action3 = { parameterPath: "action", mapper: { defaultValue: "break", @@ -24657,7 +22659,7 @@ var action3 = { } } }; -var breakPeriod = { +const breakPeriod = { parameterPath: ["options", "breakPeriod"], mapper: { serializedName: "x-ms-lease-break-period", @@ -24667,7 +22669,7 @@ var breakPeriod = { } } }; -var action4 = { +const action4 = { parameterPath: "action", mapper: { defaultValue: "change", @@ -24678,7 +22680,7 @@ var action4 = { } } }; -var proposedLeaseId1 = { +const proposedLeaseId1 = { parameterPath: "proposedLeaseId", mapper: { serializedName: "x-ms-proposed-lease-id", @@ -24689,7 +22691,7 @@ var proposedLeaseId1 = { } } }; -var include1 = { +const include1 = { parameterPath: ["options", "include"], mapper: { serializedName: "include", @@ -24707,7 +22709,10 @@ var include1 = { "snapshots", "uncommittedblobs", "versions", - "tags" + "tags", + "immutabilitypolicy", + "legalhold", + "deletedwithversions" ] } } @@ -24715,7 +22720,7 @@ var include1 = { }, collectionFormat: coreHttp.QueryCollectionFormat.Csv }; -var delimiter = { +const delimiter = { parameterPath: "delimiter", mapper: { serializedName: "delimiter", @@ -24726,243 +22731,7 @@ var delimiter = { } } }; -var directoryProperties = { - parameterPath: ["options", "directoryProperties"], - mapper: { - serializedName: "x-ms-properties", - xmlName: "x-ms-properties", - type: { - name: "String" - } - } -}; -var posixPermissions = { - parameterPath: ["options", "posixPermissions"], - mapper: { - serializedName: "x-ms-permissions", - xmlName: "x-ms-permissions", - type: { - name: "String" - } - } -}; -var posixUmask = { - parameterPath: ["options", "posixUmask"], - mapper: { - serializedName: "x-ms-umask", - xmlName: "x-ms-umask", - type: { - name: "String" - } - } -}; -var cacheControl = { - parameterPath: ["options", "directoryHttpHeaders", "cacheControl"], - mapper: { - serializedName: "x-ms-cache-control", - xmlName: "x-ms-cache-control", - type: { - name: "String" - } - } -}; -var contentType1 = { - parameterPath: ["options", "directoryHttpHeaders", "contentType"], - mapper: { - serializedName: "x-ms-content-type", - xmlName: "x-ms-content-type", - type: { - name: "String" - } - } -}; -var contentEncoding = { - parameterPath: ["options", "directoryHttpHeaders", "contentEncoding"], - mapper: { - serializedName: "x-ms-content-encoding", - xmlName: "x-ms-content-encoding", - type: { - name: "String" - } - } -}; -var contentLanguage = { - parameterPath: ["options", "directoryHttpHeaders", "contentLanguage"], - mapper: { - serializedName: "x-ms-content-language", - xmlName: "x-ms-content-language", - type: { - name: "String" - } - } -}; -var contentDisposition = { - parameterPath: ["options", "directoryHttpHeaders", "contentDisposition"], - mapper: { - serializedName: "x-ms-content-disposition", - xmlName: "x-ms-content-disposition", - type: { - name: "String" - } - } -}; -var ifMatch = { - parameterPath: ["options", "modifiedAccessConditions", "ifMatch"], - mapper: { - serializedName: "If-Match", - xmlName: "If-Match", - type: { - name: "String" - } - } -}; -var ifNoneMatch = { - parameterPath: ["options", "modifiedAccessConditions", "ifNoneMatch"], - mapper: { - serializedName: "If-None-Match", - xmlName: "If-None-Match", - type: { - name: "String" - } - } -}; -var pathRenameMode = { - parameterPath: ["options", "pathRenameMode"], - mapper: { - serializedName: "mode", - xmlName: "mode", - type: { - name: "Enum", - allowedValues: ["legacy", "posix"] - } - } -}; -var renameSource = { - parameterPath: "renameSource", - mapper: { - serializedName: "x-ms-rename-source", - required: true, - xmlName: "x-ms-rename-source", - type: { - name: "String" - } - } -}; -var sourceIfModifiedSince = { - parameterPath: [ - "options", - "sourceModifiedAccessConditions", - "sourceIfModifiedSince" - ], - mapper: { - serializedName: "x-ms-source-if-modified-since", - xmlName: "x-ms-source-if-modified-since", - type: { - name: "DateTimeRfc1123" - } - } -}; -var sourceIfUnmodifiedSince = { - parameterPath: [ - "options", - "sourceModifiedAccessConditions", - "sourceIfUnmodifiedSince" - ], - mapper: { - serializedName: "x-ms-source-if-unmodified-since", - xmlName: "x-ms-source-if-unmodified-since", - type: { - name: "DateTimeRfc1123" - } - } -}; -var sourceIfMatch = { - parameterPath: ["options", "sourceModifiedAccessConditions", "sourceIfMatch"], - mapper: { - serializedName: "x-ms-source-if-match", - xmlName: "x-ms-source-if-match", - type: { - name: "String" - } - } -}; -var sourceIfNoneMatch = { - parameterPath: [ - "options", - "sourceModifiedAccessConditions", - "sourceIfNoneMatch" - ], - mapper: { - serializedName: "x-ms-source-if-none-match", - xmlName: "x-ms-source-if-none-match", - type: { - name: "String" - } - } -}; -var action5 = { - parameterPath: "action", - mapper: { - defaultValue: "setAccessControl", - isConstant: true, - serializedName: "action", - type: { - name: "String" - } - } -}; -var owner = { - parameterPath: ["options", "owner"], - mapper: { - serializedName: "x-ms-owner", - xmlName: "x-ms-owner", - type: { - name: "String" - } - } -}; -var group = { - parameterPath: ["options", "group"], - mapper: { - serializedName: "x-ms-group", - xmlName: "x-ms-group", - type: { - name: "String" - } - } -}; -var posixAcl = { - parameterPath: ["options", "posixAcl"], - mapper: { - serializedName: "x-ms-acl", - xmlName: "x-ms-acl", - type: { - name: "String" - } - } -}; -var action6 = { - parameterPath: "action", - mapper: { - defaultValue: "getAccessControl", - isConstant: true, - serializedName: "action", - type: { - name: "String" - } - } -}; -var upn = { - parameterPath: ["options", "upn"], - mapper: { - serializedName: "upn", - xmlName: "upn", - type: { - name: "Boolean" - } - } -}; -var snapshot = { +const snapshot = { parameterPath: ["options", "snapshot"], mapper: { serializedName: "snapshot", @@ -24972,7 +22741,7 @@ var snapshot = { } } }; -var versionId = { +const versionId = { parameterPath: ["options", "versionId"], mapper: { serializedName: "versionid", @@ -24982,7 +22751,7 @@ var versionId = { } } }; -var range = { +const range = { parameterPath: ["options", "range"], mapper: { serializedName: "x-ms-range", @@ -24992,7 +22761,7 @@ var range = { } } }; -var rangeGetContentMD5 = { +const rangeGetContentMD5 = { parameterPath: ["options", "rangeGetContentMD5"], mapper: { serializedName: "x-ms-range-get-content-md5", @@ -25002,7 +22771,7 @@ var rangeGetContentMD5 = { } } }; -var rangeGetContentCRC64 = { +const rangeGetContentCRC64 = { parameterPath: ["options", "rangeGetContentCRC64"], mapper: { serializedName: "x-ms-range-get-content-crc64", @@ -25012,7 +22781,7 @@ var rangeGetContentCRC64 = { } } }; -var encryptionKey = { +const encryptionKey = { parameterPath: ["options", "cpkInfo", "encryptionKey"], mapper: { serializedName: "x-ms-encryption-key", @@ -25022,7 +22791,7 @@ var encryptionKey = { } } }; -var encryptionKeySha256 = { +const encryptionKeySha256 = { parameterPath: ["options", "cpkInfo", "encryptionKeySha256"], mapper: { serializedName: "x-ms-encryption-key-sha256", @@ -25032,7 +22801,7 @@ var encryptionKeySha256 = { } } }; -var encryptionAlgorithm = { +const encryptionAlgorithm = { parameterPath: ["options", "encryptionAlgorithm"], mapper: { defaultValue: "AES256", @@ -25043,7 +22812,27 @@ var encryptionAlgorithm = { } } }; -var ifTags = { +const ifMatch = { + parameterPath: ["options", "modifiedAccessConditions", "ifMatch"], + mapper: { + serializedName: "If-Match", + xmlName: "If-Match", + type: { + name: "String" + } + } +}; +const ifNoneMatch = { + parameterPath: ["options", "modifiedAccessConditions", "ifNoneMatch"], + mapper: { + serializedName: "If-None-Match", + xmlName: "If-None-Match", + type: { + name: "String" + } + } +}; +const ifTags = { parameterPath: ["options", "modifiedAccessConditions", "ifTags"], mapper: { serializedName: "x-ms-if-tags", @@ -25053,7 +22842,7 @@ var ifTags = { } } }; -var deleteSnapshots = { +const deleteSnapshots = { parameterPath: ["options", "deleteSnapshots"], mapper: { serializedName: "x-ms-delete-snapshots", @@ -25064,7 +22853,7 @@ var deleteSnapshots = { } } }; -var blobDeleteType = { +const blobDeleteType = { parameterPath: ["options", "blobDeleteType"], mapper: { serializedName: "deletetype", @@ -25074,7 +22863,7 @@ var blobDeleteType = { } } }; -var comp11 = { +const comp11 = { parameterPath: "comp", mapper: { defaultValue: "expiry", @@ -25085,7 +22874,7 @@ var comp11 = { } } }; -var expiryOptions = { +const expiryOptions = { parameterPath: "expiryOptions", mapper: { serializedName: "x-ms-expiry-option", @@ -25096,7 +22885,7 @@ var expiryOptions = { } } }; -var expiresOn = { +const expiresOn = { parameterPath: ["options", "expiresOn"], mapper: { serializedName: "x-ms-expiry-time", @@ -25106,7 +22895,7 @@ var expiresOn = { } } }; -var blobCacheControl = { +const blobCacheControl = { parameterPath: ["options", "blobHttpHeaders", "blobCacheControl"], mapper: { serializedName: "x-ms-blob-cache-control", @@ -25116,7 +22905,7 @@ var blobCacheControl = { } } }; -var blobContentType = { +const blobContentType = { parameterPath: ["options", "blobHttpHeaders", "blobContentType"], mapper: { serializedName: "x-ms-blob-content-type", @@ -25126,7 +22915,7 @@ var blobContentType = { } } }; -var blobContentMD5 = { +const blobContentMD5 = { parameterPath: ["options", "blobHttpHeaders", "blobContentMD5"], mapper: { serializedName: "x-ms-blob-content-md5", @@ -25136,7 +22925,7 @@ var blobContentMD5 = { } } }; -var blobContentEncoding = { +const blobContentEncoding = { parameterPath: ["options", "blobHttpHeaders", "blobContentEncoding"], mapper: { serializedName: "x-ms-blob-content-encoding", @@ -25146,7 +22935,7 @@ var blobContentEncoding = { } } }; -var blobContentLanguage = { +const blobContentLanguage = { parameterPath: ["options", "blobHttpHeaders", "blobContentLanguage"], mapper: { serializedName: "x-ms-blob-content-language", @@ -25156,7 +22945,7 @@ var blobContentLanguage = { } } }; -var blobContentDisposition = { +const blobContentDisposition = { parameterPath: ["options", "blobHttpHeaders", "blobContentDisposition"], mapper: { serializedName: "x-ms-blob-content-disposition", @@ -25166,7 +22955,61 @@ var blobContentDisposition = { } } }; -var encryptionScope = { +const comp12 = { + parameterPath: "comp", + mapper: { + defaultValue: "immutabilityPolicies", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } +}; +const immutabilityPolicyExpiry = { + parameterPath: ["options", "immutabilityPolicyExpiry"], + mapper: { + serializedName: "x-ms-immutability-policy-until-date", + xmlName: "x-ms-immutability-policy-until-date", + type: { + name: "DateTimeRfc1123" + } + } +}; +const immutabilityPolicyMode = { + parameterPath: ["options", "immutabilityPolicyMode"], + mapper: { + serializedName: "x-ms-immutability-policy-mode", + xmlName: "x-ms-immutability-policy-mode", + type: { + name: "Enum", + allowedValues: ["Mutable", "Unlocked", "Locked"] + } + } +}; +const comp13 = { + parameterPath: "comp", + mapper: { + defaultValue: "legalhold", + isConstant: true, + serializedName: "comp", + type: { + name: "String" + } + } +}; +const legalHold = { + parameterPath: "legalHold", + mapper: { + serializedName: "x-ms-legal-hold", + required: true, + xmlName: "x-ms-legal-hold", + type: { + name: "Boolean" + } + } +}; +const encryptionScope = { parameterPath: ["options", "encryptionScope"], mapper: { serializedName: "x-ms-encryption-scope", @@ -25176,7 +23019,7 @@ var encryptionScope = { } } }; -var comp12 = { +const comp14 = { parameterPath: "comp", mapper: { defaultValue: "snapshot", @@ -25187,7 +23030,7 @@ var comp12 = { } } }; -var tier = { +const tier = { parameterPath: ["options", "tier"], mapper: { serializedName: "x-ms-access-tier", @@ -25213,7 +23056,7 @@ var tier = { } } }; -var rehydratePriority = { +const rehydratePriority = { parameterPath: ["options", "rehydratePriority"], mapper: { serializedName: "x-ms-rehydrate-priority", @@ -25224,7 +23067,59 @@ var rehydratePriority = { } } }; -var sourceIfTags = { +const sourceIfModifiedSince = { + parameterPath: [ + "options", + "sourceModifiedAccessConditions", + "sourceIfModifiedSince" + ], + mapper: { + serializedName: "x-ms-source-if-modified-since", + xmlName: "x-ms-source-if-modified-since", + type: { + name: "DateTimeRfc1123" + } + } +}; +const sourceIfUnmodifiedSince = { + parameterPath: [ + "options", + "sourceModifiedAccessConditions", + "sourceIfUnmodifiedSince" + ], + mapper: { + serializedName: "x-ms-source-if-unmodified-since", + xmlName: "x-ms-source-if-unmodified-since", + type: { + name: "DateTimeRfc1123" + } + } +}; +const sourceIfMatch = { + parameterPath: ["options", "sourceModifiedAccessConditions", "sourceIfMatch"], + mapper: { + serializedName: "x-ms-source-if-match", + xmlName: "x-ms-source-if-match", + type: { + name: "String" + } + } +}; +const sourceIfNoneMatch = { + parameterPath: [ + "options", + "sourceModifiedAccessConditions", + "sourceIfNoneMatch" + ], + mapper: { + serializedName: "x-ms-source-if-none-match", + xmlName: "x-ms-source-if-none-match", + type: { + name: "String" + } + } +}; +const sourceIfTags = { parameterPath: ["options", "sourceModifiedAccessConditions", "sourceIfTags"], mapper: { serializedName: "x-ms-source-if-tags", @@ -25234,7 +23129,7 @@ var sourceIfTags = { } } }; -var copySource = { +const copySource = { parameterPath: "copySource", mapper: { serializedName: "x-ms-copy-source", @@ -25245,7 +23140,7 @@ var copySource = { } } }; -var blobTagsString = { +const blobTagsString = { parameterPath: ["options", "blobTagsString"], mapper: { serializedName: "x-ms-tags", @@ -25255,7 +23150,7 @@ var blobTagsString = { } } }; -var sealBlob = { +const sealBlob = { parameterPath: ["options", "sealBlob"], mapper: { serializedName: "x-ms-seal-blob", @@ -25265,7 +23160,17 @@ var sealBlob = { } } }; -var xMsRequiresSync = { +const legalHold1 = { + parameterPath: ["options", "legalHold"], + mapper: { + serializedName: "x-ms-legal-hold", + xmlName: "x-ms-legal-hold", + type: { + name: "Boolean" + } + } +}; +const xMsRequiresSync = { parameterPath: "xMsRequiresSync", mapper: { defaultValue: "true", @@ -25276,7 +23181,7 @@ var xMsRequiresSync = { } } }; -var sourceContentMD5 = { +const sourceContentMD5 = { parameterPath: ["options", "sourceContentMD5"], mapper: { serializedName: "x-ms-source-content-md5", @@ -25286,7 +23191,17 @@ var sourceContentMD5 = { } } }; -var comp13 = { +const copySourceAuthorization = { + parameterPath: ["options", "copySourceAuthorization"], + mapper: { + serializedName: "x-ms-copy-source-authorization", + xmlName: "x-ms-copy-source-authorization", + type: { + name: "String" + } + } +}; +const comp15 = { parameterPath: "comp", mapper: { defaultValue: "copy", @@ -25297,7 +23212,7 @@ var comp13 = { } } }; -var copyActionAbortConstant = { +const copyActionAbortConstant = { parameterPath: "copyActionAbortConstant", mapper: { defaultValue: "abort", @@ -25308,7 +23223,7 @@ var copyActionAbortConstant = { } } }; -var copyId = { +const copyId = { parameterPath: "copyId", mapper: { serializedName: "copyid", @@ -25319,7 +23234,7 @@ var copyId = { } } }; -var comp14 = { +const comp16 = { parameterPath: "comp", mapper: { defaultValue: "tier", @@ -25330,7 +23245,7 @@ var comp14 = { } } }; -var tier1 = { +const tier1 = { parameterPath: "tier", mapper: { serializedName: "x-ms-access-tier", @@ -25357,11 +23272,11 @@ var tier1 = { } } }; -var queryRequest = { +const queryRequest = { parameterPath: ["options", "queryRequest"], mapper: QueryRequest }; -var comp15 = { +const comp17 = { parameterPath: "comp", mapper: { defaultValue: "query", @@ -25372,7 +23287,7 @@ var comp15 = { } } }; -var comp16 = { +const comp18 = { parameterPath: "comp", mapper: { defaultValue: "tags", @@ -25383,11 +23298,11 @@ var comp16 = { } } }; -var tags = { +const tags = { parameterPath: ["options", "tags"], mapper: BlobTags }; -var transactionalContentMD5 = { +const transactionalContentMD5 = { parameterPath: ["options", "transactionalContentMD5"], mapper: { serializedName: "Content-MD5", @@ -25397,7 +23312,7 @@ var transactionalContentMD5 = { } } }; -var transactionalContentCrc64 = { +const transactionalContentCrc64 = { parameterPath: ["options", "transactionalContentCrc64"], mapper: { serializedName: "x-ms-content-crc64", @@ -25407,7 +23322,7 @@ var transactionalContentCrc64 = { } } }; -var blobType = { +const blobType = { parameterPath: "blobType", mapper: { defaultValue: "PageBlob", @@ -25418,7 +23333,7 @@ var blobType = { } } }; -var blobContentLength = { +const blobContentLength = { parameterPath: "blobContentLength", mapper: { serializedName: "x-ms-blob-content-length", @@ -25429,7 +23344,7 @@ var blobContentLength = { } } }; -var blobSequenceNumber = { +const blobSequenceNumber = { parameterPath: ["options", "blobSequenceNumber"], mapper: { serializedName: "x-ms-blob-sequence-number", @@ -25439,7 +23354,7 @@ var blobSequenceNumber = { } } }; -var contentType2 = { +const contentType1 = { parameterPath: ["options", "contentType"], mapper: { defaultValue: "application/octet-stream", @@ -25450,7 +23365,7 @@ var contentType2 = { } } }; -var body1 = { +const body1 = { parameterPath: "body", mapper: { serializedName: "body", @@ -25461,7 +23376,7 @@ var body1 = { } } }; -var accept2 = { +const accept2 = { parameterPath: "accept", mapper: { defaultValue: "application/xml", @@ -25472,7 +23387,7 @@ var accept2 = { } } }; -var comp17 = { +const comp19 = { parameterPath: "comp", mapper: { defaultValue: "page", @@ -25483,7 +23398,7 @@ var comp17 = { } } }; -var pageWrite = { +const pageWrite = { parameterPath: "pageWrite", mapper: { defaultValue: "update", @@ -25494,7 +23409,7 @@ var pageWrite = { } } }; -var ifSequenceNumberLessThanOrEqualTo = { +const ifSequenceNumberLessThanOrEqualTo = { parameterPath: [ "options", "sequenceNumberAccessConditions", @@ -25508,7 +23423,7 @@ var ifSequenceNumberLessThanOrEqualTo = { } } }; -var ifSequenceNumberLessThan = { +const ifSequenceNumberLessThan = { parameterPath: [ "options", "sequenceNumberAccessConditions", @@ -25522,7 +23437,7 @@ var ifSequenceNumberLessThan = { } } }; -var ifSequenceNumberEqualTo = { +const ifSequenceNumberEqualTo = { parameterPath: [ "options", "sequenceNumberAccessConditions", @@ -25536,7 +23451,7 @@ var ifSequenceNumberEqualTo = { } } }; -var pageWrite1 = { +const pageWrite1 = { parameterPath: "pageWrite", mapper: { defaultValue: "clear", @@ -25547,7 +23462,7 @@ var pageWrite1 = { } } }; -var sourceUrl = { +const sourceUrl = { parameterPath: "sourceUrl", mapper: { serializedName: "x-ms-copy-source", @@ -25558,7 +23473,7 @@ var sourceUrl = { } } }; -var sourceRange = { +const sourceRange = { parameterPath: "sourceRange", mapper: { serializedName: "x-ms-source-range", @@ -25569,7 +23484,7 @@ var sourceRange = { } } }; -var sourceContentCrc64 = { +const sourceContentCrc64 = { parameterPath: ["options", "sourceContentCrc64"], mapper: { serializedName: "x-ms-source-content-crc64", @@ -25579,7 +23494,7 @@ var sourceContentCrc64 = { } } }; -var range1 = { +const range1 = { parameterPath: "range", mapper: { serializedName: "x-ms-range", @@ -25590,7 +23505,7 @@ var range1 = { } } }; -var comp18 = { +const comp20 = { parameterPath: "comp", mapper: { defaultValue: "pagelist", @@ -25601,7 +23516,7 @@ var comp18 = { } } }; -var prevsnapshot = { +const prevsnapshot = { parameterPath: ["options", "prevsnapshot"], mapper: { serializedName: "prevsnapshot", @@ -25611,7 +23526,7 @@ var prevsnapshot = { } } }; -var prevSnapshotUrl = { +const prevSnapshotUrl = { parameterPath: ["options", "prevSnapshotUrl"], mapper: { serializedName: "x-ms-previous-snapshot-url", @@ -25621,7 +23536,7 @@ var prevSnapshotUrl = { } } }; -var sequenceNumberAction = { +const sequenceNumberAction = { parameterPath: "sequenceNumberAction", mapper: { serializedName: "x-ms-sequence-number-action", @@ -25633,7 +23548,7 @@ var sequenceNumberAction = { } } }; -var comp19 = { +const comp21 = { parameterPath: "comp", mapper: { defaultValue: "incrementalcopy", @@ -25644,7 +23559,7 @@ var comp19 = { } } }; -var blobType1 = { +const blobType1 = { parameterPath: "blobType", mapper: { defaultValue: "AppendBlob", @@ -25655,7 +23570,7 @@ var blobType1 = { } } }; -var comp20 = { +const comp22 = { parameterPath: "comp", mapper: { defaultValue: "appendblock", @@ -25666,7 +23581,7 @@ var comp20 = { } } }; -var maxSize = { +const maxSize = { parameterPath: ["options", "appendPositionAccessConditions", "maxSize"], mapper: { serializedName: "x-ms-blob-condition-maxsize", @@ -25676,7 +23591,7 @@ var maxSize = { } } }; -var appendPosition = { +const appendPosition = { parameterPath: [ "options", "appendPositionAccessConditions", @@ -25690,7 +23605,7 @@ var appendPosition = { } } }; -var sourceRange1 = { +const sourceRange1 = { parameterPath: ["options", "sourceRange"], mapper: { serializedName: "x-ms-source-range", @@ -25700,7 +23615,7 @@ var sourceRange1 = { } } }; -var comp21 = { +const comp23 = { parameterPath: "comp", mapper: { defaultValue: "seal", @@ -25711,7 +23626,7 @@ var comp21 = { } } }; -var blobType2 = { +const blobType2 = { parameterPath: "blobType", mapper: { defaultValue: "BlockBlob", @@ -25722,7 +23637,7 @@ var blobType2 = { } } }; -var copySourceBlobProperties = { +const copySourceBlobProperties = { parameterPath: ["options", "copySourceBlobProperties"], mapper: { serializedName: "x-ms-copy-source-blob-properties", @@ -25732,7 +23647,7 @@ var copySourceBlobProperties = { } } }; -var comp22 = { +const comp24 = { parameterPath: "comp", mapper: { defaultValue: "block", @@ -25743,7 +23658,7 @@ var comp22 = { } } }; -var blockId = { +const blockId = { parameterPath: "blockId", mapper: { serializedName: "blockid", @@ -25754,11 +23669,11 @@ var blockId = { } } }; -var blocks = { +const blocks = { parameterPath: "blocks", mapper: BlockLookupList }; -var comp23 = { +const comp25 = { parameterPath: "comp", mapper: { defaultValue: "blocklist", @@ -25769,7 +23684,7 @@ var comp23 = { } } }; -var listType = { +const listType = { parameterPath: "listType", mapper: { defaultValue: "committed", @@ -25791,12 +23706,12 @@ var listType = { * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ /** Class representing a Service. */ -var Service = /** @class */ (function () { +class Service { /** * Initialize a new instance of the class Service class. * @param client Reference to the service client */ - function Service(client) { + constructor(client) { this.client = client; } /** @@ -25805,69 +23720,69 @@ var Service = /** @class */ (function () { * @param blobServiceProperties The StorageService properties. * @param options The options parameters. */ - Service.prototype.setProperties = function (blobServiceProperties, options) { - var operationArguments = { - blobServiceProperties: blobServiceProperties, + setProperties(blobServiceProperties, options) { + const operationArguments = { + blobServiceProperties, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setPropertiesOperationSpec); - }; + } /** * gets the properties of a storage account's Blob service, including properties for Storage Analytics * and CORS (Cross-Origin Resource Sharing) rules. * @param options The options parameters. */ - Service.prototype.getProperties = function (options) { - var operationArguments = { + getProperties(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getPropertiesOperationSpec); - }; + } /** * 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. * @param options The options parameters. */ - Service.prototype.getStatistics = function (options) { - var operationArguments = { + getStatistics(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getStatisticsOperationSpec); - }; + } /** * The List Containers Segment operation returns a list of the containers under the specified account * @param options The options parameters. */ - Service.prototype.listContainersSegment = function (options) { - var operationArguments = { + listContainersSegment(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, listContainersSegmentOperationSpec); - }; + } /** * Retrieves a user delegation key for the Blob service. This is only a valid operation when using * bearer token authentication. * @param keyInfo Key information * @param options The options parameters. */ - Service.prototype.getUserDelegationKey = function (keyInfo, options) { - var operationArguments = { - keyInfo: keyInfo, + getUserDelegationKey(keyInfo, options) { + const operationArguments = { + keyInfo, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getUserDelegationKeyOperationSpec); - }; + } /** * Returns the sku name and account kind * @param options The options parameters. */ - Service.prototype.getAccountInfo = function (options) { - var operationArguments = { + getAccountInfo(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getAccountInfoOperationSpec); - }; + } /** * The Batch operation allows multiple API calls to be embedded into a single HTTP request. * @param contentLength The length of the request. @@ -25876,32 +23791,31 @@ var Service = /** @class */ (function () { * @param body Initial data * @param options The options parameters. */ - Service.prototype.submitBatch = function (contentLength, multipartContentType, body, options) { - var operationArguments = { - contentLength: contentLength, - multipartContentType: multipartContentType, - body: body, + submitBatch(contentLength, multipartContentType, body, options) { + const operationArguments = { + contentLength, + multipartContentType, + body, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, submitBatchOperationSpec); - }; + } /** * 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 options The options parameters. */ - Service.prototype.filterBlobs = function (options) { - var operationArguments = { + filterBlobs(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, filterBlobsOperationSpec); - }; - return Service; -}()); + } +} // Operation Specifications -var xmlSerializer = new coreHttp.Serializer(Mappers, /* isXml */ true); -var setPropertiesOperationSpec = { +const xmlSerializer = new coreHttp.Serializer(Mappers, /* isXml */ true); +const setPropertiesOperationSpec = { path: "/", httpMethod: "PUT", responses: { @@ -25931,7 +23845,7 @@ var setPropertiesOperationSpec = { mediaType: "xml", serializer: xmlSerializer }; -var getPropertiesOperationSpec = { +const getPropertiesOperationSpec = { path: "/", httpMethod: "GET", responses: { @@ -25958,7 +23872,7 @@ var getPropertiesOperationSpec = { isXML: true, serializer: xmlSerializer }; -var getStatisticsOperationSpec = { +const getStatisticsOperationSpec = { path: "/", httpMethod: "GET", responses: { @@ -25985,7 +23899,7 @@ var getStatisticsOperationSpec = { isXML: true, serializer: xmlSerializer }; -var listContainersSegmentOperationSpec = { +const listContainersSegmentOperationSpec = { path: "/", httpMethod: "GET", responses: { @@ -26015,7 +23929,7 @@ var listContainersSegmentOperationSpec = { isXML: true, serializer: xmlSerializer }; -var getUserDelegationKeyOperationSpec = { +const getUserDelegationKeyOperationSpec = { path: "/", httpMethod: "POST", responses: { @@ -26046,7 +23960,7 @@ var getUserDelegationKeyOperationSpec = { mediaType: "xml", serializer: xmlSerializer }; -var getAccountInfoOperationSpec = { +const getAccountInfoOperationSpec = { path: "/", httpMethod: "GET", responses: { @@ -26064,7 +23978,7 @@ var getAccountInfoOperationSpec = { isXML: true, serializer: xmlSerializer }; -var submitBatchOperationSpec = { +const submitBatchOperationSpec = { path: "/", httpMethod: "POST", responses: { @@ -26096,7 +24010,7 @@ var submitBatchOperationSpec = { mediaType: "xml", serializer: xmlSerializer }; -var filterBlobsOperationSpec = { +const filterBlobsOperationSpec = { path: "/", httpMethod: "GET", responses: { @@ -26134,12 +24048,12 @@ var filterBlobsOperationSpec = { * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ /** Class representing a Container. */ -var Container = /** @class */ (function () { +class Container { /** * Initialize a new instance of the class Container class. * @param client Reference to the service client */ - function Container(client) { + constructor(client) { this.client = client; } /** @@ -26147,88 +24061,88 @@ var Container = /** @class */ (function () { * exists, the operation fails * @param options The options parameters. */ - Container.prototype.create = function (options) { - var operationArguments = { + create(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, createOperationSpec); - }; + } /** * returns all user-defined metadata and system properties for the specified container. The data * returned does not include the container's list of blobs * @param options The options parameters. */ - Container.prototype.getProperties = function (options) { - var operationArguments = { + getProperties(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getPropertiesOperationSpec$1); - }; + } /** * operation marks the specified container for deletion. The container and any blobs contained within * it are later deleted during garbage collection * @param options The options parameters. */ - Container.prototype.delete = function (options) { - var operationArguments = { + delete(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, deleteOperationSpec); - }; + } /** * operation sets one or more user-defined name-value pairs for the specified container. * @param options The options parameters. */ - Container.prototype.setMetadata = function (options) { - var operationArguments = { + setMetadata(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setMetadataOperationSpec); - }; + } /** * gets the permissions for the specified container. The permissions indicate whether container data * may be accessed publicly. * @param options The options parameters. */ - Container.prototype.getAccessPolicy = function (options) { - var operationArguments = { + getAccessPolicy(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getAccessPolicyOperationSpec); - }; + } /** * sets the permissions for the specified container. The permissions indicate whether blobs in a * container may be accessed publicly. * @param options The options parameters. */ - Container.prototype.setAccessPolicy = function (options) { - var operationArguments = { + setAccessPolicy(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setAccessPolicyOperationSpec); - }; + } /** * Restores a previously-deleted container. * @param options The options parameters. */ - Container.prototype.restore = function (options) { - var operationArguments = { + restore(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, restoreOperationSpec); - }; + } /** * Renames an existing container. * @param sourceContainerName Required. Specifies the name of the container to rename. * @param options The options parameters. */ - Container.prototype.rename = function (sourceContainerName, options) { - var operationArguments = { - sourceContainerName: sourceContainerName, + rename(sourceContainerName, options) { + const operationArguments = { + sourceContainerName, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, renameOperationSpec); - }; + } /** * The Batch operation allows multiple API calls to be embedded into a single HTTP request. * @param contentLength The length of the request. @@ -26237,63 +24151,63 @@ var Container = /** @class */ (function () { * @param body Initial data * @param options The options parameters. */ - Container.prototype.submitBatch = function (contentLength, multipartContentType, body, options) { - var operationArguments = { - contentLength: contentLength, - multipartContentType: multipartContentType, - body: body, + submitBatch(contentLength, multipartContentType, body, options) { + const operationArguments = { + contentLength, + multipartContentType, + body, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, submitBatchOperationSpec$1); - }; + } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param options The options parameters. */ - Container.prototype.acquireLease = function (options) { - var operationArguments = { + acquireLease(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, acquireLeaseOperationSpec); - }; + } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ - Container.prototype.releaseLease = function (leaseId, options) { - var operationArguments = { - leaseId: leaseId, + releaseLease(leaseId, options) { + const operationArguments = { + leaseId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, releaseLeaseOperationSpec); - }; + } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ - Container.prototype.renewLease = function (leaseId, options) { - var operationArguments = { - leaseId: leaseId, + renewLease(leaseId, options) { + const operationArguments = { + leaseId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, renewLeaseOperationSpec); - }; + } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite * @param options The options parameters. */ - Container.prototype.breakLease = function (options) { - var operationArguments = { + breakLease(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, breakLeaseOperationSpec); - }; + } /** * [Update] establishes and manages a lock on a container for delete operations. The lock duration can * be 15 to 60 seconds, or can be infinite @@ -26303,24 +24217,24 @@ var Container = /** @class */ (function () { * (String) for a list of valid GUID string formats. * @param options The options parameters. */ - Container.prototype.changeLease = function (leaseId, proposedLeaseId, options) { - var operationArguments = { - leaseId: leaseId, - proposedLeaseId: proposedLeaseId, + changeLease(leaseId, proposedLeaseId, options) { + const operationArguments = { + leaseId, + proposedLeaseId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, changeLeaseOperationSpec); - }; + } /** * [Update] The List Blobs operation returns a list of the blobs under the specified container * @param options The options parameters. */ - Container.prototype.listBlobFlatSegment = function (options) { - var operationArguments = { + listBlobFlatSegment(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, listBlobFlatSegmentOperationSpec); - }; + } /** * [Update] The List Blobs operation returns a list of the blobs under the specified container * @param delimiter When the request includes this parameter, the operation returns a BlobPrefix @@ -26329,28 +24243,27 @@ var Container = /** @class */ (function () { * character or a string. * @param options The options parameters. */ - Container.prototype.listBlobHierarchySegment = function (delimiter, options) { - var operationArguments = { - delimiter: delimiter, + listBlobHierarchySegment(delimiter, options) { + const operationArguments = { + delimiter, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, listBlobHierarchySegmentOperationSpec); - }; + } /** * Returns the sku name and account kind * @param options The options parameters. */ - Container.prototype.getAccountInfo = function (options) { - var operationArguments = { + getAccountInfo(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getAccountInfoOperationSpec$1); - }; - return Container; -}()); + } +} // Operation Specifications -var xmlSerializer$1 = new coreHttp.Serializer(Mappers, /* isXml */ true); -var createOperationSpec = { +const xmlSerializer$1 = new coreHttp.Serializer(Mappers, /* isXml */ true); +const createOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { @@ -26376,7 +24289,7 @@ var createOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var getPropertiesOperationSpec$1 = { +const getPropertiesOperationSpec$1 = { path: "/{containerName}", httpMethod: "GET", responses: { @@ -26399,7 +24312,7 @@ var getPropertiesOperationSpec$1 = { isXML: true, serializer: xmlSerializer$1 }; -var deleteOperationSpec = { +const deleteOperationSpec = { path: "/{containerName}", httpMethod: "DELETE", responses: { @@ -26424,7 +24337,7 @@ var deleteOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var setMetadataOperationSpec = { +const setMetadataOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { @@ -26453,7 +24366,7 @@ var setMetadataOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var getAccessPolicyOperationSpec = { +const getAccessPolicyOperationSpec = { path: "/{containerName}", httpMethod: "GET", responses: { @@ -26492,7 +24405,7 @@ var getAccessPolicyOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var setAccessPolicyOperationSpec = { +const setAccessPolicyOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { @@ -26526,7 +24439,7 @@ var setAccessPolicyOperationSpec = { mediaType: "xml", serializer: xmlSerializer$1 }; -var restoreOperationSpec = { +const restoreOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { @@ -26554,7 +24467,7 @@ var restoreOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var renameOperationSpec = { +const renameOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { @@ -26582,7 +24495,7 @@ var renameOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var submitBatchOperationSpec$1 = { +const submitBatchOperationSpec$1 = { path: "/{containerName}", httpMethod: "POST", responses: { @@ -26618,7 +24531,7 @@ var submitBatchOperationSpec$1 = { mediaType: "xml", serializer: xmlSerializer$1 }; -var acquireLeaseOperationSpec = { +const acquireLeaseOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { @@ -26649,7 +24562,7 @@ var acquireLeaseOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var releaseLeaseOperationSpec = { +const releaseLeaseOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { @@ -26679,7 +24592,7 @@ var releaseLeaseOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var renewLeaseOperationSpec = { +const renewLeaseOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { @@ -26709,7 +24622,7 @@ var renewLeaseOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var breakLeaseOperationSpec = { +const breakLeaseOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { @@ -26739,7 +24652,7 @@ var breakLeaseOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var changeLeaseOperationSpec = { +const changeLeaseOperationSpec = { path: "/{containerName}", httpMethod: "PUT", responses: { @@ -26770,7 +24683,7 @@ var changeLeaseOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var listBlobFlatSegmentOperationSpec = { +const listBlobFlatSegmentOperationSpec = { path: "/{containerName}", httpMethod: "GET", responses: { @@ -26801,7 +24714,7 @@ var listBlobFlatSegmentOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var listBlobHierarchySegmentOperationSpec = { +const listBlobHierarchySegmentOperationSpec = { path: "/{containerName}", httpMethod: "GET", responses: { @@ -26833,7 +24746,7 @@ var listBlobHierarchySegmentOperationSpec = { isXML: true, serializer: xmlSerializer$1 }; -var getAccountInfoOperationSpec$1 = { +const getAccountInfoOperationSpec$1 = { path: "/{containerName}", httpMethod: "GET", responses: { @@ -26860,12 +24773,12 @@ var getAccountInfoOperationSpec$1 = { * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ /** Class representing a Blob. */ -var Blob$1 = /** @class */ (function () { +class Blob$1 { /** * Initialize a new instance of the class Blob class. * @param client Reference to the service client */ - function Blob(client) { + constructor(client) { this.client = client; } /** @@ -26873,23 +24786,23 @@ var Blob$1 = /** @class */ (function () { * properties. You can also call Download to read a snapshot. * @param options The options parameters. */ - Blob.prototype.download = function (options) { - var operationArguments = { + download(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, downloadOperationSpec); - }; + } /** * The Get Properties operation returns all user-defined metadata, standard HTTP properties, and system * properties for the blob. It does not return the content of the blob. * @param options The options parameters. */ - Blob.prototype.getProperties = function (options) { - var operationArguments = { + getProperties(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getPropertiesOperationSpec$2); - }; + } /** * If the storage account's soft delete feature is disabled then, when a blob is deleted, it is * permanently removed from the storage account. If the storage account's soft delete feature is @@ -26905,130 +24818,124 @@ var Blob$1 = /** @class */ (function () { * (ResourceNotFound). * @param options The options parameters. */ - Blob.prototype.delete = function (options) { - var operationArguments = { + delete(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, deleteOperationSpec$1); - }; - /** - * Set the owner, group, permissions, or access control list for a blob. - * @param options The options parameters. - */ - Blob.prototype.setAccessControl = function (options) { - var operationArguments = { - options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) - }; - return this.client.sendOperationRequest(operationArguments, setAccessControlOperationSpec); - }; - /** - * Get the owner, group, permissions, or access control list for a blob. - * @param options The options parameters. - */ - Blob.prototype.getAccessControl = function (options) { - var operationArguments = { - options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) - }; - return this.client.sendOperationRequest(operationArguments, getAccessControlOperationSpec); - }; - /** - * Rename a blob/file. By default, the destination is overwritten and if the destination already - * exists and has a lease the lease is broken. This operation supports conditional HTTP requests. For - * more information, see [Specifying Conditional Headers for Blob Service - * Operations](https://docs.microsoft.com/en-us/rest/api/storageservices/specifying-conditional-headers-for-blob-service-operations). - * To fail if the destination already exists, use a conditional request with If-None-Match: "*". - * @param renameSource The file or directory to be renamed. The value must have the following format: - * "/{filesysystem}/{path}". If "x-ms-properties" is specified, the properties will overwrite the - * existing properties; otherwise, the existing properties will be preserved. - * @param options The options parameters. - */ - Blob.prototype.rename = function (renameSource, options) { - var operationArguments = { - renameSource: renameSource, - options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) - }; - return this.client.sendOperationRequest(operationArguments, renameOperationSpec$1); - }; + } /** * Undelete a blob that was previously soft deleted * @param options The options parameters. */ - Blob.prototype.undelete = function (options) { - var operationArguments = { + undelete(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, undeleteOperationSpec); - }; + } /** * Sets the time a blob will expire and be deleted. * @param expiryOptions Required. Indicates mode of the expiry time * @param options The options parameters. */ - Blob.prototype.setExpiry = function (expiryOptions, options) { - var operationArguments = { - expiryOptions: expiryOptions, + setExpiry(expiryOptions, options) { + const operationArguments = { + expiryOptions, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setExpiryOperationSpec); - }; + } /** * The Set HTTP Headers operation sets system properties on the blob * @param options The options parameters. */ - Blob.prototype.setHttpHeaders = function (options) { - var operationArguments = { + setHttpHeaders(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setHttpHeadersOperationSpec); - }; + } + /** + * The Set Immutability Policy operation sets the immutability policy on the blob + * @param options The options parameters. + */ + setImmutabilityPolicy(options) { + const operationArguments = { + options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) + }; + return this.client.sendOperationRequest(operationArguments, setImmutabilityPolicyOperationSpec); + } + /** + * The Delete Immutability Policy operation deletes the immutability policy on the blob + * @param options The options parameters. + */ + deleteImmutabilityPolicy(options) { + const operationArguments = { + options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) + }; + return this.client.sendOperationRequest(operationArguments, deleteImmutabilityPolicyOperationSpec); + } + /** + * The Set Legal Hold operation sets a legal hold on the blob. + * @param legalHold Specified if a legal hold should be set on the blob. + * @param options The options parameters. + */ + setLegalHold(legalHold, options) { + const operationArguments = { + legalHold, + options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) + }; + return this.client.sendOperationRequest(operationArguments, setLegalHoldOperationSpec); + } /** * The Set Blob Metadata operation sets user-defined metadata for the specified blob as one or more * name-value pairs * @param options The options parameters. */ - Blob.prototype.setMetadata = function (options) { - var operationArguments = { + setMetadata(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setMetadataOperationSpec$1); - }; + } /** * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete * operations * @param options The options parameters. */ - Blob.prototype.acquireLease = function (options) { - var operationArguments = { + acquireLease(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, acquireLeaseOperationSpec$1); - }; + } /** * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete * operations * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ - Blob.prototype.releaseLease = function (leaseId, options) { - var operationArguments = { - leaseId: leaseId, + releaseLease(leaseId, options) { + const operationArguments = { + leaseId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, releaseLeaseOperationSpec$1); - }; + } /** * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete * operations * @param leaseId Specifies the current lease ID on the resource. * @param options The options parameters. */ - Blob.prototype.renewLease = function (leaseId, options) { - var operationArguments = { - leaseId: leaseId, + renewLease(leaseId, options) { + const operationArguments = { + leaseId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, renewLeaseOperationSpec$1); - }; + } /** * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete * operations @@ -27038,35 +24945,35 @@ var Blob$1 = /** @class */ (function () { * (String) for a list of valid GUID string formats. * @param options The options parameters. */ - Blob.prototype.changeLease = function (leaseId, proposedLeaseId, options) { - var operationArguments = { - leaseId: leaseId, - proposedLeaseId: proposedLeaseId, + changeLease(leaseId, proposedLeaseId, options) { + const operationArguments = { + leaseId, + proposedLeaseId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, changeLeaseOperationSpec$1); - }; + } /** * [Update] The Lease Blob operation establishes and manages a lock on a blob for write and delete * operations * @param options The options parameters. */ - Blob.prototype.breakLease = function (options) { - var operationArguments = { + breakLease(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, breakLeaseOperationSpec$1); - }; + } /** * The Create Snapshot operation creates a read-only snapshot of a blob * @param options The options parameters. */ - Blob.prototype.createSnapshot = function (options) { - var operationArguments = { + createSnapshot(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, createSnapshotOperationSpec); - }; + } /** * The Start Copy From URL operation copies a blob or an internet resource to a new blob. * @param copySource Specifies the name of the source page blob snapshot. This value is a URL of up to @@ -27075,13 +24982,13 @@ var Blob$1 = /** @class */ (function () { * access signature. * @param options The options parameters. */ - Blob.prototype.startCopyFromURL = function (copySource, options) { - var operationArguments = { - copySource: copySource, + startCopyFromURL(copySource, options) { + const operationArguments = { + copySource, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, startCopyFromURLOperationSpec); - }; + } /** * The Copy From URL operation copies a blob or an internet resource to a new blob. It will not return * a response until the copy is complete. @@ -27091,13 +24998,13 @@ var Blob$1 = /** @class */ (function () { * access signature. * @param options The options parameters. */ - Blob.prototype.copyFromURL = function (copySource, options) { - var operationArguments = { - copySource: copySource, + copyFromURL(copySource, options) { + const operationArguments = { + copySource, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, copyFromURLOperationSpec); - }; + } /** * The Abort Copy From URL operation aborts a pending Copy From URL operation, and leaves a destination * blob with zero length and full metadata. @@ -27105,13 +25012,13 @@ var Blob$1 = /** @class */ (function () { * operation. * @param options The options parameters. */ - Blob.prototype.abortCopyFromURL = function (copyId, options) { - var operationArguments = { - copyId: copyId, + abortCopyFromURL(copyId, options) { + const operationArguments = { + copyId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, abortCopyFromURLOperationSpec); - }; + } /** * The Set Tier operation sets the tier on a blob. The operation is allowed on a page blob in a premium * storage account and on a block blob in a blob storage account (locally redundant storage only). A @@ -27121,59 +25028,58 @@ var Blob$1 = /** @class */ (function () { * @param tier Indicates the tier to be set on the blob. * @param options The options parameters. */ - Blob.prototype.setTier = function (tier, options) { - var operationArguments = { - tier: tier, + setTier(tier, options) { + const operationArguments = { + tier, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setTierOperationSpec); - }; + } /** * Returns the sku name and account kind * @param options The options parameters. */ - Blob.prototype.getAccountInfo = function (options) { - var operationArguments = { + getAccountInfo(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getAccountInfoOperationSpec$2); - }; + } /** * The Query operation enables users to select/project on blob data by providing simple query * expressions. * @param options The options parameters. */ - Blob.prototype.query = function (options) { - var operationArguments = { + query(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, queryOperationSpec); - }; + } /** * The Get Tags operation enables users to get the tags associated with a blob. * @param options The options parameters. */ - Blob.prototype.getTags = function (options) { - var operationArguments = { + getTags(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getTagsOperationSpec); - }; + } /** * The Set Tags operation enables users to set tags on a blob. * @param options The options parameters. */ - Blob.prototype.setTags = function (options) { - var operationArguments = { + setTags(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, setTagsOperationSpec); - }; - return Blob; -}()); + } +} // Operation Specifications -var xmlSerializer$2 = new coreHttp.Serializer(Mappers, /* isXml */ true); -var downloadOperationSpec = { +const xmlSerializer$2 = new coreHttp.Serializer(Mappers, /* isXml */ true); +const downloadOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { @@ -27209,20 +25115,20 @@ var downloadOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, range, rangeGetContentMD5, rangeGetContentCRC64, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags ], isXML: true, serializer: xmlSerializer$2 }; -var getPropertiesOperationSpec$2 = { +const getPropertiesOperationSpec$2 = { path: "/{containerName}/{blob}", httpMethod: "HEAD", responses: { @@ -27247,17 +25153,17 @@ var getPropertiesOperationSpec$2 = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags ], isXML: true, serializer: xmlSerializer$2 }; -var deleteOperationSpec$1 = { +const deleteOperationSpec$1 = { path: "/{containerName}/{blob}", httpMethod: "DELETE", responses: { @@ -27291,110 +25197,7 @@ var deleteOperationSpec$1 = { isXML: true, serializer: xmlSerializer$2 }; -var setAccessControlOperationSpec = { - path: "/{filesystem}/{path}", - httpMethod: "PATCH", - responses: { - 200: { - headersMapper: BlobSetAccessControlHeaders - }, - default: { - bodyMapper: DataLakeStorageError, - headersMapper: BlobSetAccessControlExceptionHeaders - } - }, - queryParameters: [timeoutInSeconds, action5], - urlParameters: [url], - headerParameters: [ - version, - requestId, - accept1, - leaseId, - ifModifiedSince, - ifUnmodifiedSince, - posixPermissions, - ifMatch, - ifNoneMatch, - owner, - group, - posixAcl - ], - isXML: true, - serializer: xmlSerializer$2 -}; -var getAccessControlOperationSpec = { - path: "/{filesystem}/{path}", - httpMethod: "HEAD", - responses: { - 200: { - headersMapper: BlobGetAccessControlHeaders - }, - default: { - bodyMapper: DataLakeStorageError, - headersMapper: BlobGetAccessControlExceptionHeaders - } - }, - queryParameters: [ - timeoutInSeconds, - action6, - upn - ], - urlParameters: [url], - headerParameters: [ - version, - requestId, - accept1, - leaseId, - ifModifiedSince, - ifUnmodifiedSince, - ifMatch, - ifNoneMatch - ], - isXML: true, - serializer: xmlSerializer$2 -}; -var renameOperationSpec$1 = { - path: "/{filesystem}/{path}", - httpMethod: "PUT", - responses: { - 201: { - headersMapper: BlobRenameHeaders - }, - default: { - bodyMapper: DataLakeStorageError, - headersMapper: BlobRenameExceptionHeaders - } - }, - queryParameters: [timeoutInSeconds, pathRenameMode], - urlParameters: [url], - headerParameters: [ - version, - requestId, - accept1, - leaseId, - ifModifiedSince, - ifUnmodifiedSince, - sourceLeaseId, - directoryProperties, - posixPermissions, - posixUmask, - cacheControl, - contentType1, - contentEncoding, - contentLanguage, - contentDisposition, - ifMatch, - ifNoneMatch, - renameSource, - sourceIfModifiedSince, - sourceIfUnmodifiedSince, - sourceIfMatch, - sourceIfNoneMatch - ], - isXML: true, - serializer: xmlSerializer$2 -}; -var undeleteOperationSpec = { +const undeleteOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -27416,7 +25219,7 @@ var undeleteOperationSpec = { isXML: true, serializer: xmlSerializer$2 }; -var setExpiryOperationSpec = { +const setExpiryOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -27440,7 +25243,7 @@ var setExpiryOperationSpec = { isXML: true, serializer: xmlSerializer$2 }; -var setHttpHeadersOperationSpec = { +const setHttpHeadersOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -27474,7 +25277,77 @@ var setHttpHeadersOperationSpec = { isXML: true, serializer: xmlSerializer$2 }; -var setMetadataOperationSpec$1 = { +const setImmutabilityPolicyOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: BlobSetImmutabilityPolicyHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobSetImmutabilityPolicyExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp12], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + ifUnmodifiedSince, + immutabilityPolicyExpiry, + immutabilityPolicyMode + ], + isXML: true, + serializer: xmlSerializer$2 +}; +const deleteImmutabilityPolicyOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "DELETE", + responses: { + 200: { + headersMapper: BlobDeleteImmutabilityPolicyHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobDeleteImmutabilityPolicyExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp12], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1 + ], + isXML: true, + serializer: xmlSerializer$2 +}; +const setLegalHoldOperationSpec = { + path: "/{containerName}/{blob}", + httpMethod: "PUT", + responses: { + 200: { + headersMapper: BlobSetLegalHoldHeaders + }, + default: { + bodyMapper: StorageError, + headersMapper: BlobSetLegalHoldExceptionHeaders + } + }, + queryParameters: [timeoutInSeconds, comp13], + urlParameters: [url], + headerParameters: [ + version, + requestId, + accept1, + legalHold + ], + isXML: true, + serializer: xmlSerializer$2 +}; +const setMetadataOperationSpec$1 = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -27496,18 +25369,18 @@ var setMetadataOperationSpec$1 = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, encryptionScope ], isXML: true, serializer: xmlSerializer$2 }; -var acquireLeaseOperationSpec$1 = { +const acquireLeaseOperationSpec$1 = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -27537,7 +25410,7 @@ var acquireLeaseOperationSpec$1 = { isXML: true, serializer: xmlSerializer$2 }; -var releaseLeaseOperationSpec$1 = { +const releaseLeaseOperationSpec$1 = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -27566,7 +25439,7 @@ var releaseLeaseOperationSpec$1 = { isXML: true, serializer: xmlSerializer$2 }; -var renewLeaseOperationSpec$1 = { +const renewLeaseOperationSpec$1 = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -27595,7 +25468,7 @@ var renewLeaseOperationSpec$1 = { isXML: true, serializer: xmlSerializer$2 }; -var changeLeaseOperationSpec$1 = { +const changeLeaseOperationSpec$1 = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -27625,7 +25498,7 @@ var changeLeaseOperationSpec$1 = { isXML: true, serializer: xmlSerializer$2 }; -var breakLeaseOperationSpec$1 = { +const breakLeaseOperationSpec$1 = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -27654,7 +25527,7 @@ var breakLeaseOperationSpec$1 = { isXML: true, serializer: xmlSerializer$2 }; -var createSnapshotOperationSpec = { +const createSnapshotOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -27666,7 +25539,7 @@ var createSnapshotOperationSpec = { headersMapper: BlobCreateSnapshotExceptionHeaders } }, - queryParameters: [timeoutInSeconds, comp12], + queryParameters: [timeoutInSeconds, comp14], urlParameters: [url], headerParameters: [ version, @@ -27676,18 +25549,18 @@ var createSnapshotOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, encryptionScope ], isXML: true, serializer: xmlSerializer$2 }; -var startCopyFromURLOperationSpec = { +const startCopyFromURLOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -27711,22 +25584,25 @@ var startCopyFromURLOperationSpec = { ifUnmodifiedSince, ifMatch, ifNoneMatch, + ifTags, + immutabilityPolicyExpiry, + immutabilityPolicyMode, + tier, + rehydratePriority, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, - ifTags, - tier, - rehydratePriority, sourceIfTags, copySource, blobTagsString, - sealBlob + sealBlob, + legalHold1 ], isXML: true, serializer: xmlSerializer$2 }; -var copyFromURLOperationSpec = { +const copyFromURLOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -27750,21 +25626,25 @@ var copyFromURLOperationSpec = { ifUnmodifiedSince, ifMatch, ifNoneMatch, + ifTags, + immutabilityPolicyExpiry, + immutabilityPolicyMode, + tier, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, - ifTags, - tier, copySource, blobTagsString, + legalHold1, xMsRequiresSync, - sourceContentMD5 + sourceContentMD5, + copySourceAuthorization ], isXML: true, serializer: xmlSerializer$2 }; -var abortCopyFromURLOperationSpec = { +const abortCopyFromURLOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -27778,7 +25658,7 @@ var abortCopyFromURLOperationSpec = { }, queryParameters: [ timeoutInSeconds, - comp13, + comp15, copyId ], urlParameters: [url], @@ -27792,7 +25672,7 @@ var abortCopyFromURLOperationSpec = { isXML: true, serializer: xmlSerializer$2 }; -var setTierOperationSpec = { +const setTierOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -27811,7 +25691,7 @@ var setTierOperationSpec = { timeoutInSeconds, snapshot, versionId, - comp14 + comp16 ], urlParameters: [url], headerParameters: [ @@ -27826,7 +25706,7 @@ var setTierOperationSpec = { isXML: true, serializer: xmlSerializer$2 }; -var getAccountInfoOperationSpec$2 = { +const getAccountInfoOperationSpec$2 = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { @@ -27844,7 +25724,7 @@ var getAccountInfoOperationSpec$2 = { isXML: true, serializer: xmlSerializer$2 }; -var queryOperationSpec = { +const queryOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "POST", responses: { @@ -27871,7 +25751,7 @@ var queryOperationSpec = { queryParameters: [ timeoutInSeconds, snapshot, - comp15 + comp17 ], urlParameters: [url], headerParameters: [ @@ -27882,11 +25762,11 @@ var queryOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags ], isXML: true, @@ -27894,7 +25774,7 @@ var queryOperationSpec = { mediaType: "xml", serializer: xmlSerializer$2 }; -var getTagsOperationSpec = { +const getTagsOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { @@ -27911,7 +25791,7 @@ var getTagsOperationSpec = { timeoutInSeconds, snapshot, versionId, - comp16 + comp18 ], urlParameters: [url], headerParameters: [ @@ -27924,7 +25804,7 @@ var getTagsOperationSpec = { isXML: true, serializer: xmlSerializer$2 }; -var setTagsOperationSpec = { +const setTagsOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -27940,7 +25820,7 @@ var setTagsOperationSpec = { queryParameters: [ timeoutInSeconds, versionId, - comp16 + comp18 ], urlParameters: [url], headerParameters: [ @@ -27967,12 +25847,12 @@ var setTagsOperationSpec = { * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ /** Class representing a PageBlob. */ -var PageBlob = /** @class */ (function () { +class PageBlob { /** * Initialize a new instance of the class PageBlob class. * @param client Reference to the service client */ - function PageBlob(client) { + constructor(client) { this.client = client; } /** @@ -27982,40 +25862,40 @@ var PageBlob = /** @class */ (function () { * page blob size must be aligned to a 512-byte boundary. * @param options The options parameters. */ - PageBlob.prototype.create = function (contentLength, blobContentLength, options) { - var operationArguments = { - contentLength: contentLength, - blobContentLength: blobContentLength, + create(contentLength, blobContentLength, options) { + const operationArguments = { + contentLength, + blobContentLength, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, createOperationSpec$1); - }; + } /** * The Upload Pages operation writes a range of pages to a page blob * @param contentLength The length of the request. * @param body Initial data * @param options The options parameters. */ - PageBlob.prototype.uploadPages = function (contentLength, body, options) { - var operationArguments = { - contentLength: contentLength, - body: body, + uploadPages(contentLength, body, options) { + const operationArguments = { + contentLength, + body, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, uploadPagesOperationSpec); - }; + } /** * The Clear Pages operation clears a set of pages from a page blob * @param contentLength The length of the request. * @param options The options parameters. */ - PageBlob.prototype.clearPages = function (contentLength, options) { - var operationArguments = { - contentLength: contentLength, + clearPages(contentLength, options) { + const operationArguments = { + contentLength, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, clearPagesOperationSpec); - }; + } /** * The Upload Pages operation writes a range of pages to a page blob where the contents are read from a * URL @@ -28027,51 +25907,51 @@ var PageBlob = /** @class */ (function () { * aligned and range-end is required. * @param options The options parameters. */ - PageBlob.prototype.uploadPagesFromURL = function (sourceUrl, sourceRange, contentLength, range, options) { - var operationArguments = { - sourceUrl: sourceUrl, - sourceRange: sourceRange, - contentLength: contentLength, - range: range, + uploadPagesFromURL(sourceUrl, sourceRange, contentLength, range, options) { + const operationArguments = { + sourceUrl, + sourceRange, + contentLength, + range, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, uploadPagesFromURLOperationSpec); - }; + } /** * The Get Page Ranges operation returns the list of valid page ranges for a page blob or snapshot of a * page blob * @param options The options parameters. */ - PageBlob.prototype.getPageRanges = function (options) { - var operationArguments = { + getPageRanges(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getPageRangesOperationSpec); - }; + } /** * The Get Page Ranges Diff operation returns the list of valid page ranges for a page blob that were * changed between target blob and previous snapshot. * @param options The options parameters. */ - PageBlob.prototype.getPageRangesDiff = function (options) { - var operationArguments = { + getPageRangesDiff(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getPageRangesDiffOperationSpec); - }; + } /** * Resize the Blob * @param blobContentLength This header specifies the maximum size for the page blob, up to 1 TB. The * page blob size must be aligned to a 512-byte boundary. * @param options The options parameters. */ - PageBlob.prototype.resize = function (blobContentLength, options) { - var operationArguments = { - blobContentLength: blobContentLength, + resize(blobContentLength, options) { + const operationArguments = { + blobContentLength, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, resizeOperationSpec); - }; + } /** * Update the sequence number of the blob * @param sequenceNumberAction Required if the x-ms-blob-sequence-number header is set for the request. @@ -28079,13 +25959,13 @@ var PageBlob = /** @class */ (function () { * blob's sequence number * @param options The options parameters. */ - PageBlob.prototype.updateSequenceNumber = function (sequenceNumberAction, options) { - var operationArguments = { - sequenceNumberAction: sequenceNumberAction, + updateSequenceNumber(sequenceNumberAction, options) { + const operationArguments = { + sequenceNumberAction, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, updateSequenceNumberOperationSpec); - }; + } /** * The Copy Incremental operation copies a snapshot of the source page blob to a destination page blob. * The snapshot is copied such that only the differential changes between the previously copied @@ -28098,19 +25978,18 @@ var PageBlob = /** @class */ (function () { * access signature. * @param options The options parameters. */ - PageBlob.prototype.copyIncremental = function (copySource, options) { - var operationArguments = { - copySource: copySource, + copyIncremental(copySource, options) { + const operationArguments = { + copySource, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, copyIncrementalOperationSpec); - }; - return PageBlob; -}()); + } +} // Operation Specifications -var xmlSerializer$3 = new coreHttp.Serializer(Mappers, /* isXml */ true); -var serializer = new coreHttp.Serializer(Mappers, /* isXml */ false); -var createOperationSpec$1 = { +const xmlSerializer$3 = new coreHttp.Serializer(Mappers, /* isXml */ true); +const serializer = new coreHttp.Serializer(Mappers, /* isXml */ false); +const createOperationSpec$1 = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -28133,11 +26012,11 @@ var createOperationSpec$1 = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, blobCacheControl, blobContentType, @@ -28145,9 +26024,12 @@ var createOperationSpec$1 = { blobContentEncoding, blobContentLanguage, blobContentDisposition, + immutabilityPolicyExpiry, + immutabilityPolicyMode, encryptionScope, tier, blobTagsString, + legalHold1, blobType, blobContentLength, blobSequenceNumber @@ -28155,7 +26037,7 @@ var createOperationSpec$1 = { isXML: true, serializer: xmlSerializer$3 }; -var uploadPagesOperationSpec = { +const uploadPagesOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -28168,7 +26050,7 @@ var uploadPagesOperationSpec = { } }, requestBody: body1, - queryParameters: [timeoutInSeconds, comp17], + queryParameters: [timeoutInSeconds, comp19], urlParameters: [url], headerParameters: [ version, @@ -28177,17 +26059,17 @@ var uploadPagesOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, range, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, encryptionScope, transactionalContentMD5, transactionalContentCrc64, - contentType2, + contentType1, accept2, pageWrite, ifSequenceNumberLessThanOrEqualTo, @@ -28195,9 +26077,9 @@ var uploadPagesOperationSpec = { ifSequenceNumberEqualTo ], mediaType: "binary", - serializer: serializer + serializer }; -var clearPagesOperationSpec = { +const clearPagesOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -28209,7 +26091,7 @@ var clearPagesOperationSpec = { headersMapper: PageBlobClearPagesExceptionHeaders } }, - queryParameters: [timeoutInSeconds, comp17], + queryParameters: [timeoutInSeconds, comp19], urlParameters: [url], headerParameters: [ version, @@ -28219,12 +26101,12 @@ var clearPagesOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, range, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, encryptionScope, ifSequenceNumberLessThanOrEqualTo, @@ -28235,7 +26117,7 @@ var clearPagesOperationSpec = { isXML: true, serializer: xmlSerializer$3 }; -var uploadPagesFromURLOperationSpec = { +const uploadPagesFromURLOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -28247,7 +26129,7 @@ var uploadPagesFromURLOperationSpec = { headersMapper: PageBlobUploadPagesFromURLExceptionHeaders } }, - queryParameters: [timeoutInSeconds, comp17], + queryParameters: [timeoutInSeconds, comp19], urlParameters: [url], headerParameters: [ version, @@ -28257,18 +26139,19 @@ var uploadPagesFromURLOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, ifMatch, ifNoneMatch, + ifTags, + encryptionScope, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, - encryptionKey, - encryptionKeySha256, - encryptionAlgorithm, - ifTags, - encryptionScope, sourceContentMD5, + copySourceAuthorization, pageWrite, ifSequenceNumberLessThanOrEqualTo, ifSequenceNumberLessThan, @@ -28281,7 +26164,7 @@ var uploadPagesFromURLOperationSpec = { isXML: true, serializer: xmlSerializer$3 }; -var getPageRangesOperationSpec = { +const getPageRangesOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { @@ -28297,7 +26180,7 @@ var getPageRangesOperationSpec = { queryParameters: [ timeoutInSeconds, snapshot, - comp18 + comp20 ], urlParameters: [url], headerParameters: [ @@ -28307,15 +26190,15 @@ var getPageRangesOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, + range, ifMatch, ifNoneMatch, - range, ifTags ], isXML: true, serializer: xmlSerializer$3 }; -var getPageRangesDiffOperationSpec = { +const getPageRangesDiffOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { @@ -28331,7 +26214,7 @@ var getPageRangesDiffOperationSpec = { queryParameters: [ timeoutInSeconds, snapshot, - comp18, + comp20, prevsnapshot ], urlParameters: [url], @@ -28342,16 +26225,16 @@ var getPageRangesDiffOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, + range, ifMatch, ifNoneMatch, - range, ifTags, prevSnapshotUrl ], isXML: true, serializer: xmlSerializer$3 }; -var resizeOperationSpec = { +const resizeOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -28372,11 +26255,11 @@ var resizeOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, encryptionScope, blobContentLength @@ -28384,7 +26267,7 @@ var resizeOperationSpec = { isXML: true, serializer: xmlSerializer$3 }; -var updateSequenceNumberOperationSpec = { +const updateSequenceNumberOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -28414,7 +26297,7 @@ var updateSequenceNumberOperationSpec = { isXML: true, serializer: xmlSerializer$3 }; -var copyIncrementalOperationSpec = { +const copyIncrementalOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -28426,7 +26309,7 @@ var copyIncrementalOperationSpec = { headersMapper: PageBlobCopyIncrementalExceptionHeaders } }, - queryParameters: [timeoutInSeconds, comp19], + queryParameters: [timeoutInSeconds, comp21], urlParameters: [url], headerParameters: [ version, @@ -28451,12 +26334,12 @@ var copyIncrementalOperationSpec = { * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ /** Class representing a AppendBlob. */ -var AppendBlob = /** @class */ (function () { +class AppendBlob { /** * Initialize a new instance of the class AppendBlob class. * @param client Reference to the service client */ - function AppendBlob(client) { + constructor(client) { this.client = client; } /** @@ -28464,13 +26347,13 @@ var AppendBlob = /** @class */ (function () { * @param contentLength The length of the request. * @param options The options parameters. */ - AppendBlob.prototype.create = function (contentLength, options) { - var operationArguments = { - contentLength: contentLength, + create(contentLength, options) { + const operationArguments = { + contentLength, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, createOperationSpec$2); - }; + } /** * The Append Block operation commits a new block of data to the end of an existing append blob. The * Append Block operation is permitted only if the blob was created with x-ms-blob-type set to @@ -28479,14 +26362,14 @@ var AppendBlob = /** @class */ (function () { * @param body Initial data * @param options The options parameters. */ - AppendBlob.prototype.appendBlock = function (contentLength, body, options) { - var operationArguments = { - contentLength: contentLength, - body: body, + appendBlock(contentLength, body, options) { + const operationArguments = { + contentLength, + body, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, appendBlockOperationSpec); - }; + } /** * The Append Block operation commits a new block of data to the end of an existing append blob where * the contents are read from a source url. The Append Block operation is permitted only if the blob @@ -28496,31 +26379,30 @@ var AppendBlob = /** @class */ (function () { * @param contentLength The length of the request. * @param options The options parameters. */ - AppendBlob.prototype.appendBlockFromUrl = function (sourceUrl, contentLength, options) { - var operationArguments = { - sourceUrl: sourceUrl, - contentLength: contentLength, + appendBlockFromUrl(sourceUrl, contentLength, options) { + const operationArguments = { + sourceUrl, + contentLength, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, appendBlockFromUrlOperationSpec); - }; + } /** * The Seal operation seals the Append Blob to make it read-only. Seal is supported only on version * 2019-12-12 version or later. * @param options The options parameters. */ - AppendBlob.prototype.seal = function (options) { - var operationArguments = { + seal(options) { + const operationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, sealOperationSpec); - }; - return AppendBlob; -}()); + } +} // Operation Specifications -var xmlSerializer$4 = new coreHttp.Serializer(Mappers, /* isXml */ true); -var serializer$1 = new coreHttp.Serializer(Mappers, /* isXml */ false); -var createOperationSpec$2 = { +const xmlSerializer$4 = new coreHttp.Serializer(Mappers, /* isXml */ true); +const serializer$1 = new coreHttp.Serializer(Mappers, /* isXml */ false); +const createOperationSpec$2 = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -28543,11 +26425,11 @@ var createOperationSpec$2 = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, blobCacheControl, blobContentType, @@ -28555,14 +26437,17 @@ var createOperationSpec$2 = { blobContentEncoding, blobContentLanguage, blobContentDisposition, + immutabilityPolicyExpiry, + immutabilityPolicyMode, encryptionScope, blobTagsString, + legalHold1, blobType1 ], isXML: true, serializer: xmlSerializer$4 }; -var appendBlockOperationSpec = { +const appendBlockOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -28575,7 +26460,7 @@ var appendBlockOperationSpec = { } }, requestBody: body1, - queryParameters: [timeoutInSeconds, comp20], + queryParameters: [timeoutInSeconds, comp22], urlParameters: [url], headerParameters: [ version, @@ -28584,16 +26469,16 @@ var appendBlockOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, encryptionScope, transactionalContentMD5, transactionalContentCrc64, - contentType2, + contentType1, accept2, maxSize, appendPosition @@ -28601,7 +26486,7 @@ var appendBlockOperationSpec = { mediaType: "binary", serializer: serializer$1 }; -var appendBlockFromUrlOperationSpec = { +const appendBlockFromUrlOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -28613,7 +26498,7 @@ var appendBlockFromUrlOperationSpec = { headersMapper: AppendBlobAppendBlockFromUrlExceptionHeaders } }, - queryParameters: [timeoutInSeconds, comp20], + queryParameters: [timeoutInSeconds, comp22], urlParameters: [url], headerParameters: [ version, @@ -28623,18 +26508,19 @@ var appendBlockFromUrlOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, + encryptionKey, + encryptionKeySha256, + encryptionAlgorithm, ifMatch, ifNoneMatch, + ifTags, + encryptionScope, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, - encryptionKey, - encryptionKeySha256, - encryptionAlgorithm, - ifTags, - encryptionScope, sourceContentMD5, + copySourceAuthorization, transactionalContentMD5, sourceUrl, sourceContentCrc64, @@ -28645,7 +26531,7 @@ var appendBlockFromUrlOperationSpec = { isXML: true, serializer: xmlSerializer$4 }; -var sealOperationSpec = { +const sealOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -28657,7 +26543,7 @@ var sealOperationSpec = { headersMapper: AppendBlobSealExceptionHeaders } }, - queryParameters: [timeoutInSeconds, comp21], + queryParameters: [timeoutInSeconds, comp23], urlParameters: [url], headerParameters: [ version, @@ -28682,12 +26568,12 @@ var sealOperationSpec = { * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ /** Class representing a BlockBlob. */ -var BlockBlob = /** @class */ (function () { +class BlockBlob { /** * Initialize a new instance of the class BlockBlob class. * @param client Reference to the service client */ - function BlockBlob(client) { + constructor(client) { this.client = client; } /** @@ -28699,14 +26585,14 @@ var BlockBlob = /** @class */ (function () { * @param body Initial data * @param options The options parameters. */ - BlockBlob.prototype.upload = function (contentLength, body, options) { - var operationArguments = { - contentLength: contentLength, - body: body, + upload(contentLength, body, options) { + const operationArguments = { + contentLength, + body, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, uploadOperationSpec); - }; + } /** * The Put Blob from URL operation 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 @@ -28720,14 +26606,14 @@ var BlockBlob = /** @class */ (function () { * access signature. * @param options The options parameters. */ - BlockBlob.prototype.putBlobFromUrl = function (contentLength, copySource, options) { - var operationArguments = { - contentLength: contentLength, - copySource: copySource, + putBlobFromUrl(contentLength, copySource, options) { + const operationArguments = { + contentLength, + copySource, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, putBlobFromUrlOperationSpec); - }; + } /** * The Stage Block operation creates a new block to be committed as part of a blob * @param blockId A valid Base64 string value that identifies the block. Prior to encoding, the string @@ -28737,15 +26623,15 @@ var BlockBlob = /** @class */ (function () { * @param body Initial data * @param options The options parameters. */ - BlockBlob.prototype.stageBlock = function (blockId, contentLength, body, options) { - var operationArguments = { - blockId: blockId, - contentLength: contentLength, - body: body, + stageBlock(blockId, contentLength, body, options) { + const operationArguments = { + blockId, + contentLength, + body, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, stageBlockOperationSpec); - }; + } /** * The Stage Block operation creates a new block to be committed as part of a blob where the contents * are read from a URL. @@ -28756,15 +26642,15 @@ var BlockBlob = /** @class */ (function () { * @param sourceUrl Specify a URL to the copy source. * @param options The options parameters. */ - BlockBlob.prototype.stageBlockFromURL = function (blockId, contentLength, sourceUrl, options) { - var operationArguments = { - blockId: blockId, - contentLength: contentLength, - sourceUrl: sourceUrl, + stageBlockFromURL(blockId, contentLength, sourceUrl, options) { + const operationArguments = { + blockId, + contentLength, + sourceUrl, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, stageBlockFromURLOperationSpec); - }; + } /** * The Commit Block List operation writes a blob by specifying the list of block IDs that make up the * blob. In order to be written as part of a blob, a block must have been successfully written to the @@ -28773,16 +26659,16 @@ var BlockBlob = /** @class */ (function () { * do this by specifying whether to commit a block from the committed block list or from the * uncommitted block list, or to commit the most recently uploaded version of the block, whichever list * it may belong to. - * @param blocks + * @param blocks Blob Blocks. * @param options The options parameters. */ - BlockBlob.prototype.commitBlockList = function (blocks, options) { - var operationArguments = { - blocks: blocks, + commitBlockList(blocks, options) { + const operationArguments = { + blocks, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, commitBlockListOperationSpec); - }; + } /** * The Get Block List operation retrieves the list of blocks that have been uploaded as part of a block * blob @@ -28790,19 +26676,18 @@ var BlockBlob = /** @class */ (function () { * blocks, or both lists together. * @param options The options parameters. */ - BlockBlob.prototype.getBlockList = function (listType, options) { - var operationArguments = { - listType: listType, + getBlockList(listType, options) { + const operationArguments = { + listType, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest(operationArguments, getBlockListOperationSpec); - }; - return BlockBlob; -}()); + } +} // Operation Specifications -var xmlSerializer$5 = new coreHttp.Serializer(Mappers, /* isXml */ true); -var serializer$2 = new coreHttp.Serializer(Mappers, /* isXml */ false); -var uploadOperationSpec = { +const xmlSerializer$5 = new coreHttp.Serializer(Mappers, /* isXml */ true); +const serializer$2 = new coreHttp.Serializer(Mappers, /* isXml */ false); +const uploadOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -28825,11 +26710,11 @@ var uploadOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, blobCacheControl, blobContentType, @@ -28837,18 +26722,21 @@ var uploadOperationSpec = { blobContentEncoding, blobContentLanguage, blobContentDisposition, + immutabilityPolicyExpiry, + immutabilityPolicyMode, encryptionScope, tier, blobTagsString, + legalHold1, transactionalContentMD5, - contentType2, + contentType1, accept2, blobType2 ], mediaType: "binary", serializer: serializer$2 }; -var putBlobFromUrlOperationSpec = { +const putBlobFromUrlOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -28871,15 +26759,11 @@ var putBlobFromUrlOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, - sourceIfModifiedSince, - sourceIfUnmodifiedSince, - sourceIfMatch, - sourceIfNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, blobCacheControl, blobContentType, @@ -28889,10 +26773,15 @@ var putBlobFromUrlOperationSpec = { blobContentDisposition, encryptionScope, tier, + sourceIfModifiedSince, + sourceIfUnmodifiedSince, + sourceIfMatch, + sourceIfNoneMatch, sourceIfTags, copySource, blobTagsString, sourceContentMD5, + copySourceAuthorization, transactionalContentMD5, blobType2, copySourceBlobProperties @@ -28900,7 +26789,7 @@ var putBlobFromUrlOperationSpec = { isXML: true, serializer: xmlSerializer$5 }; -var stageBlockOperationSpec = { +const stageBlockOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -28915,7 +26804,7 @@ var stageBlockOperationSpec = { requestBody: body1, queryParameters: [ timeoutInSeconds, - comp22, + comp24, blockId ], urlParameters: [url], @@ -28930,13 +26819,13 @@ var stageBlockOperationSpec = { encryptionScope, transactionalContentMD5, transactionalContentCrc64, - contentType2, + contentType1, accept2 ], mediaType: "binary", serializer: serializer$2 }; -var stageBlockFromURLOperationSpec = { +const stageBlockFromURLOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -28950,7 +26839,7 @@ var stageBlockFromURLOperationSpec = { }, queryParameters: [ timeoutInSeconds, - comp22, + comp24, blockId ], urlParameters: [url], @@ -28960,15 +26849,16 @@ var stageBlockFromURLOperationSpec = { accept1, contentLength, leaseId, - sourceIfModifiedSince, - sourceIfUnmodifiedSince, - sourceIfMatch, - sourceIfNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, encryptionScope, + sourceIfModifiedSince, + sourceIfUnmodifiedSince, + sourceIfMatch, + sourceIfNoneMatch, sourceContentMD5, + copySourceAuthorization, sourceUrl, sourceContentCrc64, sourceRange1 @@ -28976,7 +26866,7 @@ var stageBlockFromURLOperationSpec = { isXML: true, serializer: xmlSerializer$5 }; -var commitBlockListOperationSpec = { +const commitBlockListOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "PUT", responses: { @@ -28989,7 +26879,7 @@ var commitBlockListOperationSpec = { } }, requestBody: blocks, - queryParameters: [timeoutInSeconds, comp23], + queryParameters: [timeoutInSeconds, comp25], urlParameters: [url], headerParameters: [ contentType, @@ -29000,11 +26890,11 @@ var commitBlockListOperationSpec = { leaseId, ifModifiedSince, ifUnmodifiedSince, - ifMatch, - ifNoneMatch, encryptionKey, encryptionKeySha256, encryptionAlgorithm, + ifMatch, + ifNoneMatch, ifTags, blobCacheControl, blobContentType, @@ -29012,9 +26902,12 @@ var commitBlockListOperationSpec = { blobContentEncoding, blobContentLanguage, blobContentDisposition, + immutabilityPolicyExpiry, + immutabilityPolicyMode, encryptionScope, tier, blobTagsString, + legalHold1, transactionalContentMD5, transactionalContentCrc64 ], @@ -29023,7 +26916,7 @@ var commitBlockListOperationSpec = { mediaType: "xml", serializer: xmlSerializer$5 }; -var getBlockListOperationSpec = { +const getBlockListOperationSpec = { path: "/{containerName}/{blob}", httpMethod: "GET", responses: { @@ -29039,7 +26932,7 @@ var getBlockListOperationSpec = { queryParameters: [ timeoutInSeconds, snapshot, - comp23, + comp25, listType ], urlParameters: [url], @@ -29058,23 +26951,23 @@ var getBlockListOperationSpec = { /** * The `@azure/logger` configuration for this package. */ -var logger = logger$1.createClientLogger("storage-blob"); +const logger = logger$1.createClientLogger("storage-blob"); // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -var SDK_VERSION = "12.6.0"; -var SERVICE_VERSION = "2020-08-04"; -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; -var DEFAULT_BLOCK_BUFFER_SIZE_BYTES = 8 * 1024 * 1024; // 8MB -var DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES = 4 * 1024 * 1024; // 4MB -var DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS = 5; +const SDK_VERSION = "12.8.0"; +const SERVICE_VERSION = "2020-10-02"; +const BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES = 256 * 1024 * 1024; // 256MB +const BLOCK_BLOB_MAX_STAGE_BLOCK_BYTES = 4000 * 1024 * 1024; // 4000MB +const BLOCK_BLOB_MAX_BLOCKS = 50000; +const DEFAULT_BLOCK_BUFFER_SIZE_BYTES = 8 * 1024 * 1024; // 8MB +const DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES = 4 * 1024 * 1024; // 4MB +const DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS = 5; /** * The OAuth scope to use with Azure Storage. */ -var StorageOAuthScopes = "https://storage.azure.com/.default"; -var URLConstants = { +const StorageOAuthScopes = "https://storage.azure.com/.default"; +const URLConstants = { Parameters: { FORCE_BROWSER_NO_CACHE: "_", SIGNATURE: "sig", @@ -29083,14 +26976,14 @@ var URLConstants = { TIMEOUT: "timeout" } }; -var HTTPURLConnection = { +const HTTPURLConnection = { HTTP_ACCEPTED: 202, HTTP_CONFLICT: 409, HTTP_NOT_FOUND: 404, HTTP_PRECON_FAILED: 412, HTTP_RANGE_NOT_SATISFIABLE: 416 }; -var HeaderConstants = { +const HeaderConstants = { AUTHORIZATION: "Authorization", AUTHORIZATION_SCHEME: "Bearer", CONTENT_ENCODING: "Content-Encoding", @@ -29115,16 +27008,16 @@ var HeaderConstants = { X_MS_ERROR_CODE: "x-ms-error-code", X_MS_VERSION: "x-ms-version" }; -var ETagNone = ""; -var ETagAny = "*"; -var SIZE_1_MB = 1 * 1024 * 1024; -var BATCH_MAX_REQUEST = 256; -var BATCH_MAX_PAYLOAD_IN_BYTES = 4 * SIZE_1_MB; -var HTTP_LINE_ENDING = "\r\n"; -var HTTP_VERSION_1_1 = "HTTP/1.1"; -var EncryptionAlgorithmAES25 = "AES256"; -var DevelopmentConnectionString = "DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;"; -var StorageBlobLoggingAllowedHeaderNames = [ +const ETagNone = ""; +const ETagAny = "*"; +const SIZE_1_MB = 1 * 1024 * 1024; +const BATCH_MAX_REQUEST = 256; +const BATCH_MAX_PAYLOAD_IN_BYTES = 4 * SIZE_1_MB; +const HTTP_LINE_ENDING = "\r\n"; +const HTTP_VERSION_1_1 = "HTTP/1.1"; +const EncryptionAlgorithmAES25 = "AES256"; +const DevelopmentConnectionString = `DefaultEndpointsProtocol=http;AccountName=devstoreaccount1;AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==;BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;`; +const StorageBlobLoggingAllowedHeaderNames = [ "Access-Control-Allow-Origin", "Cache-Control", "Content-Length", @@ -29220,7 +27113,7 @@ var StorageBlobLoggingAllowedHeaderNames = [ "x-ms-if-tags", "x-ms-source-if-tags" ]; -var StorageBlobLoggingAllowedQueryParameters = [ +const StorageBlobLoggingAllowedQueryParameters = [ "comp", "maxresults", "rscc", @@ -29310,8 +27203,8 @@ var StorageBlobLoggingAllowedQueryParameters = [ * @param url - */ function escapeURLPath(url) { - var urlParsed = coreHttp.URLBuilder.parse(url); - var path = urlParsed.getPath(); + const urlParsed = coreHttp.URLBuilder.parse(url); + let path = urlParsed.getPath(); path = path || "/"; path = escape(path); urlParsed.setPath(path); @@ -29320,12 +27213,11 @@ function escapeURLPath(url) { function getProxyUriFromDevConnString(connectionString) { // Development Connection String // https://docs.microsoft.com/en-us/azure/storage/common/storage-configure-connection-string#connect-to-the-emulator-account-using-the-well-known-account-name-and-key - var proxyUri = ""; + let proxyUri = ""; if (connectionString.search("DevelopmentStorageProxyUri=") !== -1) { // CONNECTION_STRING=UseDevelopmentStorage=true;DevelopmentStorageProxyUri=http://myProxyUri - var matchCredentials = connectionString.split(";"); - for (var _i = 0, matchCredentials_1 = matchCredentials; _i < matchCredentials_1.length; _i++) { - var element = matchCredentials_1[_i]; + const matchCredentials = connectionString.split(";"); + for (const element of matchCredentials) { if (element.trim().startsWith("DevelopmentStorageProxyUri=")) { proxyUri = element.trim().match("DevelopmentStorageProxyUri=(.*)")[1]; } @@ -29334,9 +27226,8 @@ function getProxyUriFromDevConnString(connectionString) { return proxyUri; } function getValueInConnString(connectionString, argument) { - var elements = connectionString.split(";"); - for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) { - var element = elements_1[_i]; + const elements = connectionString.split(";"); + for (const element of elements) { if (element.trim().startsWith(argument)) { return element.trim().match(argument + "=(.*)")[1]; } @@ -29350,24 +27241,24 @@ function getValueInConnString(connectionString, argument) { * @returns String key value pairs of the storage account's url and credentials. */ function extractConnectionStringParts(connectionString) { - var proxyUri = ""; + let proxyUri = ""; if (connectionString.startsWith("UseDevelopmentStorage=true")) { // Development connection string proxyUri = getProxyUriFromDevConnString(connectionString); connectionString = DevelopmentConnectionString; } // Matching BlobEndpoint in the Account connection string - var blobEndpoint = getValueInConnString(connectionString, "BlobEndpoint"); + let blobEndpoint = getValueInConnString(connectionString, "BlobEndpoint"); // Slicing off '/' at the end if exists // (The methods that use `extractConnectionStringParts` expect the url to not have `/` at the end) blobEndpoint = blobEndpoint.endsWith("/") ? blobEndpoint.slice(0, -1) : blobEndpoint; if (connectionString.search("DefaultEndpointsProtocol=") !== -1 && connectionString.search("AccountKey=") !== -1) { // Account connection string - var defaultEndpointsProtocol = ""; - var accountName = ""; - var accountKey = Buffer.from("accountKey", "base64"); - var endpointSuffix = ""; + let defaultEndpointsProtocol = ""; + let accountName = ""; + let accountKey = Buffer.from("accountKey", "base64"); + let endpointSuffix = ""; // Get account name and key accountName = getValueInConnString(connectionString, "AccountName"); accountKey = Buffer.from(getValueInConnString(connectionString, "AccountKey"), "base64"); @@ -29375,7 +27266,7 @@ function extractConnectionStringParts(connectionString) { // BlobEndpoint is not present in the Account connection string // Can be obtained from `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}` defaultEndpointsProtocol = getValueInConnString(connectionString, "DefaultEndpointsProtocol"); - var protocol = defaultEndpointsProtocol.toLowerCase(); + const protocol = defaultEndpointsProtocol.toLowerCase(); if (protocol !== "https" && protocol !== "http") { throw new Error("Invalid DefaultEndpointsProtocol in the provided Connection String. Expecting 'https' or 'http'"); } @@ -29383,7 +27274,7 @@ function extractConnectionStringParts(connectionString) { if (!endpointSuffix) { throw new Error("Invalid EndpointSuffix in the provided Connection String"); } - blobEndpoint = defaultEndpointsProtocol + "://" + accountName + ".blob." + endpointSuffix; + blobEndpoint = `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; } if (!accountName) { throw new Error("Invalid AccountName in the provided Connection String"); @@ -29394,22 +27285,22 @@ function extractConnectionStringParts(connectionString) { return { kind: "AccountConnString", url: blobEndpoint, - accountName: accountName, - accountKey: accountKey, - proxyUri: proxyUri + accountName, + accountKey, + proxyUri }; } else { // SAS connection string - var accountSas = getValueInConnString(connectionString, "SharedAccessSignature"); - var accountName = getAccountNameFromUrl(blobEndpoint); + const accountSas = getValueInConnString(connectionString, "SharedAccessSignature"); + const accountName = getAccountNameFromUrl(blobEndpoint); if (!blobEndpoint) { throw new Error("Invalid BlobEndpoint in the provided SAS Connection String"); } else if (!accountSas) { throw new Error("Invalid SharedAccessSignature in the provided SAS Connection String"); } - return { kind: "SASConnString", url: blobEndpoint, accountName: accountName, accountSas: accountSas }; + return { kind: "SASConnString", url: blobEndpoint, accountName, accountSas }; } } /** @@ -29433,9 +27324,9 @@ function escape(text) { * @returns An updated URL string */ function appendToURLPath(url, name) { - var urlParsed = coreHttp.URLBuilder.parse(url); - var path = urlParsed.getPath(); - path = path ? (path.endsWith("/") ? "" + path + name : path + "/" + name) : name; + const urlParsed = coreHttp.URLBuilder.parse(url); + let path = urlParsed.getPath(); + path = path ? (path.endsWith("/") ? `${path}${name}` : `${path}/${name}`) : name; urlParsed.setPath(path); return urlParsed.toString(); } @@ -29449,7 +27340,7 @@ function appendToURLPath(url, name) { * @returns An updated URL string */ function setURLParameter(url, name, value) { - var urlParsed = coreHttp.URLBuilder.parse(url); + const urlParsed = coreHttp.URLBuilder.parse(url); urlParsed.setQueryParameter(name, value); return urlParsed.toString(); } @@ -29460,7 +27351,7 @@ function setURLParameter(url, name, value) { * @param name - */ function getURLParameter(url, name) { - var urlParsed = coreHttp.URLBuilder.parse(url); + const urlParsed = coreHttp.URLBuilder.parse(url); return urlParsed.getQueryParameterValue(name); } /** @@ -29471,7 +27362,7 @@ function getURLParameter(url, name) { * @returns An updated URL string */ function setURLHost(url, host) { - var urlParsed = coreHttp.URLBuilder.parse(url); + const urlParsed = coreHttp.URLBuilder.parse(url); urlParsed.setHost(host); return urlParsed.toString(); } @@ -29481,7 +27372,7 @@ function setURLHost(url, host) { * @param url - Source URL string */ function getURLPath(url) { - var urlParsed = coreHttp.URLBuilder.parse(url); + const urlParsed = coreHttp.URLBuilder.parse(url); return urlParsed.getPath(); } /** @@ -29490,7 +27381,7 @@ function getURLPath(url) { * @param url - Source URL string */ function getURLScheme(url) { - var urlParsed = coreHttp.URLBuilder.parse(url); + const urlParsed = coreHttp.URLBuilder.parse(url); return urlParsed.getScheme(); } /** @@ -29499,17 +27390,17 @@ function getURLScheme(url) { * @param url - Source URL string */ function getURLPathAndQuery(url) { - var urlParsed = coreHttp.URLBuilder.parse(url); - var pathString = urlParsed.getPath(); + const urlParsed = coreHttp.URLBuilder.parse(url); + const pathString = urlParsed.getPath(); if (!pathString) { throw new RangeError("Invalid url without valid path."); } - var queryString = urlParsed.getQuery() || ""; + let queryString = urlParsed.getQuery() || ""; queryString = queryString.trim(); - if (queryString != "") { - queryString = queryString.startsWith("?") ? queryString : "?" + queryString; // Ensure query string start with '?' + if (queryString !== "") { + queryString = queryString.startsWith("?") ? queryString : `?${queryString}`; // Ensure query string start with '?' } - return "" + pathString + queryString; + return `${pathString}${queryString}`; } /** * Get URL query key value pairs from an URL string. @@ -29517,24 +27408,23 @@ function getURLPathAndQuery(url) { * @param url - */ function getURLQueries(url) { - var queryString = coreHttp.URLBuilder.parse(url).getQuery(); + let queryString = coreHttp.URLBuilder.parse(url).getQuery(); if (!queryString) { return {}; } queryString = queryString.trim(); queryString = queryString.startsWith("?") ? queryString.substr(1) : queryString; - var querySubStrings = queryString.split("&"); - querySubStrings = querySubStrings.filter(function (value) { - var indexOfEqual = value.indexOf("="); - var lastIndexOfEqual = value.lastIndexOf("="); + let querySubStrings = queryString.split("&"); + querySubStrings = querySubStrings.filter((value) => { + const indexOfEqual = value.indexOf("="); + const lastIndexOfEqual = value.lastIndexOf("="); return (indexOfEqual > 0 && indexOfEqual === lastIndexOfEqual && lastIndexOfEqual < value.length - 1); }); - var queries = {}; - for (var _i = 0, querySubStrings_1 = querySubStrings; _i < querySubStrings_1.length; _i++) { - var querySubString = querySubStrings_1[_i]; - var splitResults = querySubString.split("="); - var key = splitResults[0]; - var value = splitResults[1]; + const queries = {}; + for (const querySubString of querySubStrings) { + const splitResults = querySubString.split("="); + const key = splitResults[0]; + const value = splitResults[1]; queries[key] = value; } return queries; @@ -29547,8 +27437,8 @@ function getURLQueries(url) { * @returns An updated URL string. */ function appendToURLQuery(url, queryParts) { - var urlParsed = coreHttp.URLBuilder.parse(url); - var query = urlParsed.getQuery(); + const urlParsed = coreHttp.URLBuilder.parse(url); + let query = urlParsed.getQuery(); if (query) { query += "&" + queryParts; } @@ -29566,10 +27456,9 @@ function appendToURLQuery(url, queryParts) { * If false, YYYY-MM-DDThh:mm:ssZ will be returned. * @returns Date string in ISO8061 format, with or without 7 milliseconds component */ -function truncatedISO8061Date(date, withMilliseconds) { - if (withMilliseconds === void 0) { withMilliseconds = true; } +function truncatedISO8061Date(date, withMilliseconds = true) { // Date.toISOString() will return like "2018-10-29T06:34:36.139Z" - var dateString = date.toISOString(); + const dateString = date.toISOString(); return withMilliseconds ? dateString.substring(0, dateString.length - 1) + "0000" + "Z" : dateString.substring(0, dateString.length - 5) + "Z"; @@ -29589,14 +27478,14 @@ function base64encode(content) { */ function generateBlockID(blockIDPrefix, blockIndex) { // To generate a 64 bytes base64 string, source string should be 48 - var maxSourceStringLength = 48; + const maxSourceStringLength = 48; // A blob can have a maximum of 100,000 uncommitted blocks at any given time - var maxBlockIndexLength = 6; - var maxAllowedBlockIDPrefixLength = maxSourceStringLength - maxBlockIndexLength; + const maxBlockIndexLength = 6; + const maxAllowedBlockIDPrefixLength = maxSourceStringLength - maxBlockIndexLength; if (blockIDPrefix.length > maxAllowedBlockIDPrefixLength) { blockIDPrefix = blockIDPrefix.slice(0, maxAllowedBlockIDPrefixLength); } - var res = blockIDPrefix + + const res = blockIDPrefix + padStart(blockIndex.toString(), maxSourceStringLength - blockIDPrefix.length, "0"); return base64encode(res); } @@ -29607,29 +27496,26 @@ function generateBlockID(blockIDPrefix, blockIndex) { * @param aborter - * @param abortError - */ -function delay(timeInMs, aborter, abortError) { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - return [2 /*return*/, new Promise(function (resolve, reject) { - var timeout; - var abortHandler = function () { - if (timeout !== undefined) { - clearTimeout(timeout); - } - reject(abortError); - }; - var resolveHandler = function () { - if (aborter !== undefined) { - aborter.removeEventListener("abort", abortHandler); - } - resolve(); - }; - timeout = setTimeout(resolveHandler, timeInMs); - if (aborter !== undefined) { - aborter.addEventListener("abort", abortHandler); - } - })]; - }); +async function delay(timeInMs, aborter, abortError) { + return new Promise((resolve, reject) => { + /* eslint-disable-next-line prefer-const */ + let timeout; + const abortHandler = () => { + if (timeout !== undefined) { + clearTimeout(timeout); + } + reject(abortError); + }; + const resolveHandler = () => { + if (aborter !== undefined) { + aborter.removeEventListener("abort", abortHandler); + } + resolve(); + }; + timeout = setTimeout(resolveHandler, timeInMs); + if (aborter !== undefined) { + aborter.addEventListener("abort", abortHandler); + } }); } /** @@ -29639,10 +27525,8 @@ function delay(timeInMs, aborter, abortError) { * @param targetLength - * @param padString - */ -function padStart(currentString, targetLength, padString) { - if (padString === void 0) { padString = " "; } - // TS doesn't know this code needs to run downlevel sometimes. - // @ts-expect-error +function padStart(currentString, targetLength, padString = " ") { + // @ts-expect-error: TS doesn't know this code needs to run downlevel sometimes if (String.prototype.padStart) { return currentString.padStart(targetLength, padString); } @@ -29673,8 +27557,8 @@ function iEqual(str1, str2) { * @returns with the account name */ function getAccountNameFromUrl(url) { - var parsedUrl = coreHttp.URLBuilder.parse(url); - var accountName; + const parsedUrl = coreHttp.URLBuilder.parse(url); + let accountName; try { if (parsedUrl.getHost().split(".")[1] === "blob") { // `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; @@ -29697,10 +27581,10 @@ function getAccountNameFromUrl(url) { } } function isIpEndpointStyle(parsedUrl) { - if (parsedUrl.getHost() == undefined) { + if (parsedUrl.getHost() === undefined) { return false; } - var host = parsedUrl.getHost() + (parsedUrl.getPort() == undefined ? "" : ":" + parsedUrl.getPort()); + const host = parsedUrl.getHost() + (parsedUrl.getPort() === undefined ? "" : ":" + parsedUrl.getPort()); // Case 1: Ipv6, use a broad regex to find out candidates whose host contains two ':'. // Case 2: localhost(:port), use broad regex to match port part. // Case 3: Ipv4, use broad regex which just check if host contains Ipv4. @@ -29716,11 +27600,11 @@ function toBlobTagsString(tags) { if (tags === undefined) { return undefined; } - var tagPairs = []; - for (var key in tags) { - if (tags.hasOwnProperty(key)) { - var value = tags[key]; - tagPairs.push(encodeURIComponent(key) + "=" + encodeURIComponent(value)); + const tagPairs = []; + for (const key in tags) { + if (Object.prototype.hasOwnProperty.call(tags, key)) { + const value = tags[key]; + tagPairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`); } } return tagPairs.join("&"); @@ -29734,15 +27618,15 @@ function toBlobTags(tags) { if (tags === undefined) { return undefined; } - var res = { + const res = { blobTagSet: [] }; - for (var key in tags) { - if (tags.hasOwnProperty(key)) { - var value = tags[key]; + for (const key in tags) { + if (Object.prototype.hasOwnProperty.call(tags, key)) { + const value = tags[key]; res.blobTagSet.push({ - key: key, - value: value + key, + value }); } } @@ -29757,9 +27641,8 @@ function toTags(tags) { if (tags === undefined) { return undefined; } - var res = {}; - for (var _i = 0, _a = tags.blobTagSet; _i < _a.length; _i++) { - var blobTag = _a[_i]; + const res = {}; + for (const blobTag of tags.blobTagSet) { res[blobTag.key] = blobTag.value; } return res; @@ -29805,6 +27688,12 @@ function toQuerySerialization(textConfiguration) { } } }; + case "parquet": + return { + format: { + type: "parquet" + } + }; default: throw Error("Invalid BlobQueryTextConfiguration."); } @@ -29818,18 +27707,18 @@ function parseObjectReplicationRecord(objectReplicationRecord) { // the policy id should already be stored in the ObjectReplicationDestinationPolicyId. return undefined; } - var orProperties = []; - var _loop_1 = function (key) { - var ids = key.split("_"); - var policyPrefix = "or-"; + const orProperties = []; + for (const key in objectReplicationRecord) { + const ids = key.split("_"); + const policyPrefix = "or-"; if (ids[0].startsWith(policyPrefix)) { ids[0] = ids[0].substring(policyPrefix.length); } - var rule = { + const rule = { ruleId: ids[1], replicationStatus: objectReplicationRecord[key] }; - var policyIndex = orProperties.findIndex(function (policy) { return policy.policyId === ids[0]; }); + const policyIndex = orProperties.findIndex((policy) => policy.policyId === ids[0]); if (policyIndex > -1) { orProperties[policyIndex].rules.push(rule); } @@ -29839,9 +27728,6 @@ function parseObjectReplicationRecord(objectReplicationRecord) { rules: [rule] }); } - }; - for (var key in objectReplicationRecord) { - _loop_1(key); } return orProperties; } @@ -29855,6 +27741,9 @@ function attachCredential(thing, credential) { thing.credential = credential; return thing; } +function httpAuthorizationToString(httpAuthorization) { + return httpAuthorization ? httpAuthorization.scheme + " " + httpAuthorization.value : undefined; +} // Copyright (c) Microsoft Corporation. /** @@ -29868,51 +27757,44 @@ function attachCredential(thing, credential) { * * 3. Remove content-length header to avoid browsers warning */ -var StorageBrowserPolicy = /** @class */ (function (_super) { - tslib.__extends(StorageBrowserPolicy, _super); +class StorageBrowserPolicy extends coreHttp.BaseRequestPolicy { /** * Creates an instance of StorageBrowserPolicy. * @param nextPolicy - * @param options - */ - function StorageBrowserPolicy(nextPolicy, options) { - return _super.call(this, nextPolicy, options) || this; + // The base class has a protected constructor. Adding a public one to enable constructing of this class. + /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ + constructor(nextPolicy, options) { + super(nextPolicy, options); } /** * Sends out request. * * @param request - */ - StorageBrowserPolicy.prototype.sendRequest = function (request) { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - { - return [2 /*return*/, this._nextPolicy.sendRequest(request)]; - } - }); - }); - }; - return StorageBrowserPolicy; -}(coreHttp.BaseRequestPolicy)); + async sendRequest(request) { + { + return this._nextPolicy.sendRequest(request); + } + } +} // Copyright (c) Microsoft Corporation. /** * StorageBrowserPolicyFactory is a factory class helping generating StorageBrowserPolicy objects. */ -var StorageBrowserPolicyFactory = /** @class */ (function () { - function StorageBrowserPolicyFactory() { - } +class StorageBrowserPolicyFactory { /** * Creates a StorageBrowserPolicyFactory object. * * @param nextPolicy - * @param options - */ - StorageBrowserPolicyFactory.prototype.create = function (nextPolicy, options) { + create(nextPolicy, options) { return new StorageBrowserPolicy(nextPolicy, options); - }; - return StorageBrowserPolicyFactory; -}()); + } +} // Copyright (c) Microsoft Corporation. (function (StorageRetryPolicyType) { @@ -29926,7 +27808,7 @@ var StorageBrowserPolicyFactory = /** @class */ (function () { StorageRetryPolicyType[StorageRetryPolicyType["FIXED"] = 1] = "FIXED"; })(exports.StorageRetryPolicyType || (exports.StorageRetryPolicyType = {})); // Default values of StorageRetryOptions -var DEFAULT_RETRY_OPTIONS = { +const DEFAULT_RETRY_OPTIONS = { maxRetryDelayInMs: 120 * 1000, maxTries: 4, retryDelayInMs: 4 * 1000, @@ -29934,12 +27816,11 @@ var DEFAULT_RETRY_OPTIONS = { secondaryHost: "", tryTimeoutInMs: undefined // Use server side default timeout strategy }; -var RETRY_ABORT_ERROR = new abortController.AbortError("The operation was aborted."); +const RETRY_ABORT_ERROR = new abortController.AbortError("The operation was aborted."); /** * Retry policy with exponential retry and linear retry implemented. */ -var StorageRetryPolicy = /** @class */ (function (_super) { - tslib.__extends(StorageRetryPolicy, _super); +class StorageRetryPolicy extends coreHttp.BaseRequestPolicy { /** * Creates an instance of RetryPolicy. * @@ -29947,11 +27828,10 @@ var StorageRetryPolicy = /** @class */ (function (_super) { * @param options - * @param retryOptions - */ - function StorageRetryPolicy(nextPolicy, options, retryOptions) { - if (retryOptions === void 0) { retryOptions = DEFAULT_RETRY_OPTIONS; } - var _this = _super.call(this, nextPolicy, options) || this; + constructor(nextPolicy, options, retryOptions = DEFAULT_RETRY_OPTIONS) { + super(nextPolicy, options); // Initialize retry options - _this.retryOptions = { + this.retryOptions = { retryPolicyType: retryOptions.retryPolicyType ? retryOptions.retryPolicyType : DEFAULT_RETRY_OPTIONS.retryPolicyType, @@ -29973,20 +27853,15 @@ var StorageRetryPolicy = /** @class */ (function (_super) { ? retryOptions.secondaryHost : DEFAULT_RETRY_OPTIONS.secondaryHost }; - return _this; } /** * Sends request. * * @param request - */ - StorageRetryPolicy.prototype.sendRequest = function (request) { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - return [2 /*return*/, this.attemptSendRequest(request, false, 1)]; - }); - }); - }; + async sendRequest(request) { + return this.attemptSendRequest(request, false, 1); + } /** * Decide and perform next retry. Won't mutate request parameter. * @@ -29997,52 +27872,37 @@ var StorageRetryPolicy = /** @class */ (function (_super) { * @param attempt - How many retries has been attempted to performed, starting from 1, which includes * the attempt will be performed by this method call. */ - StorageRetryPolicy.prototype.attemptSendRequest = function (request, secondaryHas404, attempt) { - return tslib.__awaiter(this, void 0, void 0, function () { - var newRequest, isPrimaryRetry, response, err_1; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - newRequest = request.clone(); - isPrimaryRetry = secondaryHas404 || - !this.retryOptions.secondaryHost || - !(request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS") || - attempt % 2 === 1; - if (!isPrimaryRetry) { - newRequest.url = setURLHost(newRequest.url, this.retryOptions.secondaryHost); - } - // Set the server-side timeout query parameter "timeout=[seconds]" - if (this.retryOptions.tryTimeoutInMs) { - newRequest.url = setURLParameter(newRequest.url, URLConstants.Parameters.TIMEOUT, Math.floor(this.retryOptions.tryTimeoutInMs / 1000).toString()); - } - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - logger.info("RetryPolicy: =====> Try=" + attempt + " " + (isPrimaryRetry ? "Primary" : "Secondary")); - return [4 /*yield*/, this._nextPolicy.sendRequest(newRequest)]; - case 2: - response = _a.sent(); - if (!this.shouldRetry(isPrimaryRetry, attempt, response)) { - return [2 /*return*/, response]; - } - secondaryHas404 = secondaryHas404 || (!isPrimaryRetry && response.status === 404); - return [3 /*break*/, 4]; - case 3: - err_1 = _a.sent(); - logger.error("RetryPolicy: Caught error, message: " + err_1.message + ", code: " + err_1.code); - if (!this.shouldRetry(isPrimaryRetry, attempt, response, err_1)) { - throw err_1; - } - return [3 /*break*/, 4]; - case 4: return [4 /*yield*/, this.delay(isPrimaryRetry, attempt, request.abortSignal)]; - case 5: - _a.sent(); - return [4 /*yield*/, this.attemptSendRequest(request, secondaryHas404, ++attempt)]; - case 6: return [2 /*return*/, _a.sent()]; - } - }); - }); - }; + async attemptSendRequest(request, secondaryHas404, attempt) { + const newRequest = request.clone(); + const isPrimaryRetry = secondaryHas404 || + !this.retryOptions.secondaryHost || + !(request.method === "GET" || request.method === "HEAD" || request.method === "OPTIONS") || + attempt % 2 === 1; + if (!isPrimaryRetry) { + newRequest.url = setURLHost(newRequest.url, this.retryOptions.secondaryHost); + } + // Set the server-side timeout query parameter "timeout=[seconds]" + if (this.retryOptions.tryTimeoutInMs) { + newRequest.url = setURLParameter(newRequest.url, URLConstants.Parameters.TIMEOUT, Math.floor(this.retryOptions.tryTimeoutInMs / 1000).toString()); + } + let response; + try { + logger.info(`RetryPolicy: =====> Try=${attempt} ${isPrimaryRetry ? "Primary" : "Secondary"}`); + response = await this._nextPolicy.sendRequest(newRequest); + if (!this.shouldRetry(isPrimaryRetry, attempt, response)) { + return response; + } + secondaryHas404 = secondaryHas404 || (!isPrimaryRetry && response.status === 404); + } + catch (err) { + logger.error(`RetryPolicy: Caught error, message: ${err.message}, code: ${err.code}`); + if (!this.shouldRetry(isPrimaryRetry, attempt, response, err)) { + throw err; + } + } + await this.delay(isPrimaryRetry, attempt, request.abortSignal); + return this.attemptSendRequest(request, secondaryHas404, ++attempt); + } /** * Decide whether to retry according to last HTTP response and retry counters. * @@ -30051,15 +27911,15 @@ var StorageRetryPolicy = /** @class */ (function (_super) { * @param response - * @param err - */ - StorageRetryPolicy.prototype.shouldRetry = function (isPrimaryRetry, attempt, response, err) { + shouldRetry(isPrimaryRetry, attempt, response, err) { if (attempt >= this.retryOptions.maxTries) { - logger.info("RetryPolicy: Attempt(s) " + attempt + " >= maxTries " + this.retryOptions - .maxTries + ", no further try."); + logger.info(`RetryPolicy: Attempt(s) ${attempt} >= maxTries ${this.retryOptions + .maxTries}, no further try.`); return false; } // Handle network failures, you may need to customize the list when you implement // your own http client - var retriableErrors = [ + const retriableErrors = [ "ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNREFUSED", @@ -30071,12 +27931,11 @@ var StorageRetryPolicy = /** @class */ (function (_super) { "REQUEST_SEND_ERROR" // For default xhr based http client provided in ms-rest-js ]; if (err) { - for (var _i = 0, retriableErrors_1 = retriableErrors; _i < retriableErrors_1.length; _i++) { - var retriableError = retriableErrors_1[_i]; + for (const retriableError of retriableErrors) { if (err.name.toUpperCase().includes(retriableError) || err.message.toUpperCase().includes(retriableError) || (err.code && err.code.toString().toUpperCase() === retriableError)) { - logger.info("RetryPolicy: Network error " + retriableError + " found, will retry."); + logger.info(`RetryPolicy: Network error ${retriableError} found, will retry.`); return true; } } @@ -30085,23 +27944,23 @@ var StorageRetryPolicy = /** @class */ (function (_super) { // the resource was not found. This may be due to replication delay. So, in this // case, we'll never try the secondary again for this operation. if (response || err) { - var statusCode = response ? response.status : err ? err.statusCode : 0; + const statusCode = response ? response.status : err ? err.statusCode : 0; if (!isPrimaryRetry && statusCode === 404) { - logger.info("RetryPolicy: Secondary access with 404, will retry."); + logger.info(`RetryPolicy: Secondary access with 404, will retry.`); return true; } // Server internal error or server timeout if (statusCode === 503 || statusCode === 500) { - logger.info("RetryPolicy: Will retry for status code " + statusCode + "."); + logger.info(`RetryPolicy: Will retry for status code ${statusCode}.`); 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"))) { + 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; - }; + } /** * Delay a calculated time between retries. * @@ -30109,42 +27968,36 @@ var StorageRetryPolicy = /** @class */ (function (_super) { * @param attempt - * @param abortSignal - */ - StorageRetryPolicy.prototype.delay = function (isPrimaryRetry, attempt, abortSignal) { - return tslib.__awaiter(this, void 0, void 0, function () { - var delayTimeInMs; - return tslib.__generator(this, function (_a) { - delayTimeInMs = 0; - if (isPrimaryRetry) { - switch (this.retryOptions.retryPolicyType) { - case exports.StorageRetryPolicyType.EXPONENTIAL: - delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * this.retryOptions.retryDelayInMs, this.retryOptions.maxRetryDelayInMs); - break; - case exports.StorageRetryPolicyType.FIXED: - delayTimeInMs = this.retryOptions.retryDelayInMs; - break; - } - } - else { - delayTimeInMs = Math.random() * 1000; - } - logger.info("RetryPolicy: Delay for " + delayTimeInMs + "ms"); - return [2 /*return*/, delay(delayTimeInMs, abortSignal, RETRY_ABORT_ERROR)]; - }); - }); - }; - return StorageRetryPolicy; -}(coreHttp.BaseRequestPolicy)); + async delay(isPrimaryRetry, attempt, abortSignal) { + let delayTimeInMs = 0; + if (isPrimaryRetry) { + switch (this.retryOptions.retryPolicyType) { + case exports.StorageRetryPolicyType.EXPONENTIAL: + delayTimeInMs = Math.min((Math.pow(2, attempt - 1) - 1) * this.retryOptions.retryDelayInMs, this.retryOptions.maxRetryDelayInMs); + break; + case exports.StorageRetryPolicyType.FIXED: + delayTimeInMs = this.retryOptions.retryDelayInMs; + break; + } + } + else { + delayTimeInMs = Math.random() * 1000; + } + logger.info(`RetryPolicy: Delay for ${delayTimeInMs}ms`); + return delay(delayTimeInMs, abortSignal, RETRY_ABORT_ERROR); + } +} // Copyright (c) Microsoft Corporation. /** * StorageRetryPolicyFactory is a factory class helping generating {@link StorageRetryPolicy} objects. */ -var StorageRetryPolicyFactory = /** @class */ (function () { +class StorageRetryPolicyFactory { /** * Creates an instance of StorageRetryPolicyFactory. * @param retryOptions - */ - function StorageRetryPolicyFactory(retryOptions) { + constructor(retryOptions) { this.retryOptions = retryOptions; } /** @@ -30153,61 +28006,55 @@ var StorageRetryPolicyFactory = /** @class */ (function () { * @param nextPolicy - * @param options - */ - StorageRetryPolicyFactory.prototype.create = function (nextPolicy, options) { + create(nextPolicy, options) { return new StorageRetryPolicy(nextPolicy, options, this.retryOptions); - }; - return StorageRetryPolicyFactory; -}()); + } +} // Copyright (c) Microsoft Corporation. /** * Credential policy used to sign HTTP(S) requests before sending. This is an * abstract class. */ -var CredentialPolicy = /** @class */ (function (_super) { - tslib.__extends(CredentialPolicy, _super); - function CredentialPolicy() { - return _super !== null && _super.apply(this, arguments) || this; - } +class CredentialPolicy extends coreHttp.BaseRequestPolicy { /** * Sends out request. * * @param request - */ - CredentialPolicy.prototype.sendRequest = function (request) { + sendRequest(request) { return this._nextPolicy.sendRequest(this.signRequest(request)); - }; + } /** * Child classes must implement this method with request signing. This method * will be executed in {@link sendRequest}. * * @param request - */ - CredentialPolicy.prototype.signRequest = function (request) { + signRequest(request) { // Child classes must override this method with request signing. This method // will be executed in sendRequest(). return request; - }; - return CredentialPolicy; -}(coreHttp.BaseRequestPolicy)); + } +} // Copyright (c) Microsoft Corporation. /** * AnonymousCredentialPolicy is used with HTTP(S) requests that read public resources * or for use with Shared Access Signatures (SAS). */ -var AnonymousCredentialPolicy = /** @class */ (function (_super) { - tslib.__extends(AnonymousCredentialPolicy, _super); +class AnonymousCredentialPolicy extends CredentialPolicy { /** * Creates an instance of AnonymousCredentialPolicy. * @param nextPolicy - * @param options - */ - function AnonymousCredentialPolicy(nextPolicy, options) { - return _super.call(this, nextPolicy, options) || this; + // The base class has a protected constructor. Adding a public one to enable constructing of this class. + /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ + constructor(nextPolicy, options) { + super(nextPolicy, options); } - return AnonymousCredentialPolicy; -}(CredentialPolicy)); +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -30215,24 +28062,17 @@ var AnonymousCredentialPolicy = /** @class */ (function (_super) { * Credential is an abstract class for Azure Storage HTTP requests signing. This * class will host an credentialPolicyCreator factory which generates CredentialPolicy. */ -var Credential = /** @class */ (function () { - function Credential() { - } +class Credential { /** * Creates a RequestPolicy object. * * @param _nextPolicy - * @param _options - */ - Credential.prototype.create = function ( - // tslint:disable-next-line:variable-name - _nextPolicy, - // tslint:disable-next-line:variable-name - _options) { + create(_nextPolicy, _options) { throw new Error("Method should be implemented in children classes."); - }; - return Credential; -}()); + } +} // Copyright (c) Microsoft Corporation. /** @@ -30241,88 +28081,76 @@ var Credential = /** @class */ (function () { * HTTP(S) requests that read public resources or for use with Shared Access * Signatures (SAS). */ -var AnonymousCredential = /** @class */ (function (_super) { - tslib.__extends(AnonymousCredential, _super); - function AnonymousCredential() { - return _super !== null && _super.apply(this, arguments) || this; - } +class AnonymousCredential extends Credential { /** * Creates an {@link AnonymousCredentialPolicy} object. * * @param nextPolicy - * @param options - */ - AnonymousCredential.prototype.create = function (nextPolicy, options) { + create(nextPolicy, options) { return new AnonymousCredentialPolicy(nextPolicy, options); - }; - return AnonymousCredential; -}(Credential)); + } +} // Copyright (c) Microsoft Corporation. /** * TelemetryPolicy is a policy used to tag user-agent header for every requests. */ -var TelemetryPolicy = /** @class */ (function (_super) { - tslib.__extends(TelemetryPolicy, _super); +class TelemetryPolicy extends coreHttp.BaseRequestPolicy { /** * Creates an instance of TelemetryPolicy. * @param nextPolicy - * @param options - * @param telemetry - */ - function TelemetryPolicy(nextPolicy, options, telemetry) { - var _this = _super.call(this, nextPolicy, options) || this; - _this.telemetry = telemetry; - return _this; + constructor(nextPolicy, options, telemetry) { + super(nextPolicy, options); + this.telemetry = telemetry; } /** * Sends out request. * * @param request - */ - TelemetryPolicy.prototype.sendRequest = function (request) { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - { - if (!request.headers) { - request.headers = new coreHttp.HttpHeaders(); - } - if (!request.headers.get(HeaderConstants.USER_AGENT)) { - request.headers.set(HeaderConstants.USER_AGENT, this.telemetry); - } - } - return [2 /*return*/, this._nextPolicy.sendRequest(request)]; - }); - }); - }; - return TelemetryPolicy; -}(coreHttp.BaseRequestPolicy)); + async sendRequest(request) { + { + if (!request.headers) { + request.headers = new coreHttp.HttpHeaders(); + } + if (!request.headers.get(HeaderConstants.USER_AGENT)) { + request.headers.set(HeaderConstants.USER_AGENT, this.telemetry); + } + } + return this._nextPolicy.sendRequest(request); + } +} // Copyright (c) Microsoft Corporation. /** * TelemetryPolicyFactory is a factory class helping generating {@link TelemetryPolicy} objects. */ -var TelemetryPolicyFactory = /** @class */ (function () { +class TelemetryPolicyFactory { /** * Creates an instance of TelemetryPolicyFactory. * @param telemetry - */ - function TelemetryPolicyFactory(telemetry) { - var userAgentInfo = []; + constructor(telemetry) { + const userAgentInfo = []; { if (telemetry) { - var telemetryString = telemetry.userAgentPrefix || ""; + const telemetryString = telemetry.userAgentPrefix || ""; if (telemetryString.length > 0 && userAgentInfo.indexOf(telemetryString) === -1) { userAgentInfo.push(telemetryString); } } // e.g. azsdk-js-storageblob/10.0.0 - var libInfo = "azsdk-js-storageblob/" + SDK_VERSION; + const libInfo = `azsdk-js-storageblob/${SDK_VERSION}`; if (userAgentInfo.indexOf(libInfo) === -1) { userAgentInfo.push(libInfo); } // e.g. (NODE-VERSION 4.9.1; Windows_NT 10.0.16299) - var runtimeInfo = "(NODE-VERSION " + process.version + "; " + os.type() + " " + os.release() + ")"; + const runtimeInfo = `(NODE-VERSION ${process.version}; ${os.type()} ${os.release()})`; if (userAgentInfo.indexOf(runtimeInfo) === -1) { userAgentInfo.push(runtimeInfo); } @@ -30335,19 +28163,32 @@ var TelemetryPolicyFactory = /** @class */ (function () { * @param nextPolicy - * @param options - */ - TelemetryPolicyFactory.prototype.create = function (nextPolicy, options) { + create(nextPolicy, options) { return new TelemetryPolicy(nextPolicy, options, this.telemetryString); - }; - return TelemetryPolicyFactory; -}()); + } +} // Copyright (c) Microsoft Corporation. -var _defaultHttpClient = new coreHttp.DefaultHttpClient(); +const _defaultHttpClient = new coreHttp.DefaultHttpClient(); function getCachedDefaultHttpClient() { return _defaultHttpClient; } // Copyright (c) Microsoft Corporation. +/** + * A helper to decide if a given argument satisfies the Pipeline contract + * @param pipeline - An argument that may be a Pipeline + * @returns true when the argument satisfies the Pipeline contract + */ +function isPipelineLike(pipeline) { + if (!pipeline || typeof pipeline !== "object") { + return false; + } + const castPipeline = pipeline; + return (Array.isArray(castPipeline.factories) && + typeof castPipeline.options === "object" && + typeof castPipeline.toServiceClientOptions === "function"); +} /** * A Pipeline class containing HTTP request policies. * You can create a default Pipeline by calling {@link newPipeline}. @@ -30356,19 +28197,18 @@ function getCachedDefaultHttpClient() { * Refer to {@link newPipeline} and provided policies before implementing your * customized Pipeline. */ -var Pipeline = /** @class */ (function () { +class Pipeline { /** * Creates an instance of Pipeline. Customize HTTPClient by implementing IHttpClient interface. * * @param factories - * @param options - */ - function Pipeline(factories, options) { - if (options === void 0) { options = {}; } + constructor(factories, options = {}) { this.factories = factories; // when options.httpClient is not specified, passing in a DefaultHttpClient instance to // avoid each client creating its own http client. - this.options = tslib.__assign(tslib.__assign({}, options), { httpClient: options.httpClient || getCachedDefaultHttpClient() }); + this.options = Object.assign(Object.assign({}, options), { httpClient: options.httpClient || getCachedDefaultHttpClient() }); } /** * Transfer Pipeline object to ServiceClientOptions object which is required by @@ -30376,14 +28216,13 @@ var Pipeline = /** @class */ (function () { * * @returns The ServiceClientOptions object from this Pipeline. */ - Pipeline.prototype.toServiceClientOptions = function () { + toServiceClientOptions() { return { httpClient: this.options.httpClient, requestPolicyFactories: this.factories }; - }; - return Pipeline; -}()); + } +} /** * Creates a new Pipeline object with Credential provided. * @@ -30391,16 +28230,15 @@ var Pipeline = /** @class */ (function () { * @param pipelineOptions - Optional. Options. * @returns A new Pipeline object. */ -function newPipeline(credential, pipelineOptions) { - if (pipelineOptions === void 0) { pipelineOptions = {}; } +function newPipeline(credential, pipelineOptions = {}) { if (credential === undefined) { credential = new AnonymousCredential(); } // Order is important. Closer to the API at the top & closer to the network at the bottom. // The credential's policy factory must appear close to the wire so it can sign any // changes made by other factories (like UniqueRequestIDPolicyFactory) - var telemetryPolicy = new TelemetryPolicyFactory(pipelineOptions.userAgentOptions); - var factories = [ + const telemetryPolicy = new TelemetryPolicyFactory(pipelineOptions.userAgentOptions); + const factories = [ coreHttp.tracingPolicy({ userAgent: telemetryPolicy.telemetryString }), coreHttp.keepAlivePolicy(pipelineOptions.keepAliveOptions), telemetryPolicy, @@ -30432,30 +28270,28 @@ function newPipeline(credential, pipelineOptions) { /** * StorageSharedKeyCredentialPolicy is a policy used to sign HTTP request with a shared key. */ -var StorageSharedKeyCredentialPolicy = /** @class */ (function (_super) { - tslib.__extends(StorageSharedKeyCredentialPolicy, _super); +class StorageSharedKeyCredentialPolicy extends CredentialPolicy { /** * Creates an instance of StorageSharedKeyCredentialPolicy. * @param nextPolicy - * @param options - * @param factory - */ - function StorageSharedKeyCredentialPolicy(nextPolicy, options, factory) { - var _this = _super.call(this, nextPolicy, options) || this; - _this.factory = factory; - return _this; + constructor(nextPolicy, options, factory) { + super(nextPolicy, options); + this.factory = factory; } /** * Signs request. * * @param request - */ - StorageSharedKeyCredentialPolicy.prototype.signRequest = function (request) { + signRequest(request) { request.headers.set(HeaderConstants.X_MS_DATE, new Date().toUTCString()); if (request.body && typeof request.body === "string" && request.body.length > 0) { request.headers.set(HeaderConstants.CONTENT_LENGTH, Buffer.byteLength(request.body)); } - var stringToSign = [ + const stringToSign = [ request.method.toUpperCase(), this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LANGUAGE), this.getHeaderValueToSign(request, HeaderConstants.CONTENT_ENCODING), @@ -30472,14 +28308,14 @@ var StorageSharedKeyCredentialPolicy = /** @class */ (function (_super) { "\n" + this.getCanonicalizedHeadersString(request) + this.getCanonicalizedResourceString(request); - var signature = this.factory.computeHMACSHA256(stringToSign); - request.headers.set(HeaderConstants.AUTHORIZATION, "SharedKey " + this.factory.accountName + ":" + signature); + const signature = this.factory.computeHMACSHA256(stringToSign); + request.headers.set(HeaderConstants.AUTHORIZATION, `SharedKey ${this.factory.accountName}:${signature}`); // console.log(`[URL]:${request.url}`); // console.log(`[HEADERS]:${request.headers.toString()}`); // console.log(`[STRING TO SIGN]:${JSON.stringify(stringToSign)}`); // console.log(`[KEY]: ${request.headers.get(HeaderConstants.AUTHORIZATION)}`); return request; - }; + } /** * Retrieve header value according to shared key sign rules. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key @@ -30487,8 +28323,8 @@ var StorageSharedKeyCredentialPolicy = /** @class */ (function (_super) { * @param request - * @param headerName - */ - StorageSharedKeyCredentialPolicy.prototype.getHeaderValueToSign = function (request, headerName) { - var value = request.headers.get(headerName); + getHeaderValueToSign(request, headerName) { + const value = request.headers.get(headerName); if (!value) { return ""; } @@ -30499,7 +28335,7 @@ var StorageSharedKeyCredentialPolicy = /** @class */ (function (_super) { return ""; } return value; - }; + } /** * To construct the CanonicalizedHeaders portion of the signature string, follow these steps: * 1. Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header. @@ -30513,58 +28349,56 @@ var StorageSharedKeyCredentialPolicy = /** @class */ (function (_super) { * * @param request - */ - StorageSharedKeyCredentialPolicy.prototype.getCanonicalizedHeadersString = function (request) { - var headersArray = request.headers.headersArray().filter(function (value) { + getCanonicalizedHeadersString(request) { + let headersArray = request.headers.headersArray().filter((value) => { return value.name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE); }); - headersArray.sort(function (a, b) { + headersArray.sort((a, b) => { return a.name.toLowerCase().localeCompare(b.name.toLowerCase()); }); // Remove duplicate headers - headersArray = headersArray.filter(function (value, index, array) { + headersArray = headersArray.filter((value, index, array) => { if (index > 0 && value.name.toLowerCase() === array[index - 1].name.toLowerCase()) { return false; } return true; }); - var canonicalizedHeadersStringToSign = ""; - headersArray.forEach(function (header) { - canonicalizedHeadersStringToSign += header.name + let canonicalizedHeadersStringToSign = ""; + headersArray.forEach((header) => { + canonicalizedHeadersStringToSign += `${header.name .toLowerCase() - .trimRight() + ":" + header.value.trimLeft() + "\n"; + .trimRight()}:${header.value.trimLeft()}\n`; }); return canonicalizedHeadersStringToSign; - }; + } /** * Retrieves the webResource canonicalized resource string. * * @param request - */ - StorageSharedKeyCredentialPolicy.prototype.getCanonicalizedResourceString = function (request) { - var path = getURLPath(request.url) || "/"; - var canonicalizedResourceString = ""; - canonicalizedResourceString += "/" + this.factory.accountName + path; - var queries = getURLQueries(request.url); - var lowercaseQueries = {}; + getCanonicalizedResourceString(request) { + const path = getURLPath(request.url) || "/"; + let canonicalizedResourceString = ""; + canonicalizedResourceString += `/${this.factory.accountName}${path}`; + const queries = getURLQueries(request.url); + const lowercaseQueries = {}; if (queries) { - var queryKeys = []; - for (var key in queries) { - if (queries.hasOwnProperty(key)) { - var lowercaseKey = key.toLowerCase(); + const queryKeys = []; + for (const key in queries) { + if (Object.prototype.hasOwnProperty.call(queries, key)) { + const lowercaseKey = key.toLowerCase(); lowercaseQueries[lowercaseKey] = queries[key]; queryKeys.push(lowercaseKey); } } queryKeys.sort(); - for (var _i = 0, queryKeys_1 = queryKeys; _i < queryKeys_1.length; _i++) { - var key = queryKeys_1[_i]; - canonicalizedResourceString += "\n" + key + ":" + decodeURIComponent(lowercaseQueries[key]); + for (const key of queryKeys) { + canonicalizedResourceString += `\n${key}:${decodeURIComponent(lowercaseQueries[key])}`; } } return canonicalizedResourceString; - }; - return StorageSharedKeyCredentialPolicy; -}(CredentialPolicy)); + } +} // Copyright (c) Microsoft Corporation. /** @@ -30572,18 +28406,16 @@ var StorageSharedKeyCredentialPolicy = /** @class */ (function (_super) { * * StorageSharedKeyCredential for account key authorization of Azure Storage service. */ -var StorageSharedKeyCredential = /** @class */ (function (_super) { - tslib.__extends(StorageSharedKeyCredential, _super); +class StorageSharedKeyCredential extends Credential { /** * Creates an instance of StorageSharedKeyCredential. * @param accountName - * @param accountKey - */ - function StorageSharedKeyCredential(accountName, accountKey) { - var _this = _super.call(this) || this; - _this.accountName = accountName; - _this.accountKey = Buffer.from(accountKey, "base64"); - return _this; + constructor(accountName, accountKey) { + super(); + this.accountName = accountName; + this.accountKey = Buffer.from(accountKey, "base64"); } /** * Creates a StorageSharedKeyCredentialPolicy object. @@ -30591,21 +28423,20 @@ var StorageSharedKeyCredential = /** @class */ (function (_super) { * @param nextPolicy - * @param options - */ - StorageSharedKeyCredential.prototype.create = function (nextPolicy, options) { + create(nextPolicy, options) { return new StorageSharedKeyCredentialPolicy(nextPolicy, options, this); - }; + } /** * Generates a hash signature for an HTTP request or for a SAS. * * @param stringToSign - */ - StorageSharedKeyCredential.prototype.computeHMACSHA256 = function (stringToSign) { + computeHMACSHA256(stringToSign) { return crypto.createHmac("sha256", this.accountKey) .update(stringToSign, "utf8") .digest("base64"); - }; - return StorageSharedKeyCredential; -}(Credential)); + } +} /* * Copyright (c) Microsoft Corporation. @@ -30614,18 +28445,16 @@ var StorageSharedKeyCredential = /** @class */ (function (_super) { * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ -var packageName = "azure-storage-blob"; -var packageVersion = "12.6.0-beta.1"; -var StorageClientContext = /** @class */ (function (_super) { - tslib.__extends(StorageClientContext, _super); +const packageName = "azure-storage-blob"; +const packageVersion = "12.8.0"; +class StorageClientContext extends coreHttp.ServiceClient { /** * Initializes a new instance of the StorageClientContext class. - * @param url The URL of the service account, container, or blob that is the targe of the desired + * @param url The URL of the service account, container, or blob that is the target of the desired * operation. * @param options The parameter options */ - function StorageClientContext(url, options) { - var _this = this; + constructor(url, options) { if (url === undefined) { throw new Error("'url' cannot be null"); } @@ -30634,33 +28463,31 @@ var StorageClientContext = /** @class */ (function (_super) { options = {}; } if (!options.userAgent) { - var defaultUserAgent = coreHttp.getDefaultUserAgentValue(); - options.userAgent = packageName + "/" + packageVersion + " " + defaultUserAgent; + const defaultUserAgent = coreHttp.getDefaultUserAgentValue(); + options.userAgent = `${packageName}/${packageVersion} ${defaultUserAgent}`; } - _this = _super.call(this, undefined, options) || this; - _this.requestContentType = "application/json; charset=utf-8"; - _this.baseUri = options.endpoint || "{url}"; + super(undefined, options); + this.requestContentType = "application/json; charset=utf-8"; + this.baseUri = options.endpoint || "{url}"; // Parameter assignments - _this.url = url; + this.url = url; // Assigning values to Constant parameters - _this.version = options.version || "2020-08-04"; - return _this; + this.version = options.version || "2020-10-02"; } - return StorageClientContext; -}(coreHttp.ServiceClient)); +} // Copyright (c) Microsoft Corporation. /** * A StorageClient represents a based URL class for {@link BlobServiceClient}, {@link ContainerClient} * and etc. */ -var StorageClient = /** @class */ (function () { +class StorageClient { /** * Creates an instance of StorageClient. * @param url - url to resource * @param pipeline - request policy pipeline. */ - function StorageClient(url, pipeline) { + constructor(url, pipeline) { // URL should be encoded and only once, protocol layer shouldn't encode URL again this.url = escapeURLPath(url); this.accountName = getAccountNameFromUrl(url); @@ -30668,8 +28495,7 @@ var StorageClient = /** @class */ (function () { this.storageClientContext = new StorageClientContext(this.url, pipeline.toServiceClientOptions()); this.isHttps = iEqual(getURLScheme(this.url) || "", "https"); this.credential = new AnonymousCredential(); - for (var _i = 0, _a = this.pipeline.factories; _i < _a.length; _i++) { - var factory = _a[_i]; + for (const factory of this.pipeline.factories) { if ((coreHttp.isNode && factory instanceof StorageSharedKeyCredential) || factory instanceof AnonymousCredential) { this.credential = factory; @@ -30681,18 +28507,17 @@ var StorageClient = /** @class */ (function () { } } // Override protocol layer's default content-type - var storageClientContext = this.storageClientContext; + const storageClientContext = this.storageClientContext; storageClientContext.requestContentType = undefined; } - return StorageClient; -}()); +} // Copyright (c) Microsoft Corporation. /** * Creates a span using the global tracer. * @internal */ -var createSpan = coreTracing.createSpanFunction({ +const createSpan = coreTracing.createSpanFunction({ packagePrefix: "Azure.Storage.Blob", namespace: "Microsoft.Storage" }); @@ -30706,6 +28531,7 @@ var createSpan = coreTracing.createSpanFunction({ function convertTracingToRequestOptionsBase(options) { var _a, _b; return { + // By passing spanOptions if they exist at runtime, we're backwards compatible with @azure/core-tracing@preview.13 and earlier. spanOptions: (_a = options === null || options === void 0 ? void 0 : options.tracingOptions) === null || _a === void 0 ? void 0 : _a.spanOptions, tracingContext: (_b = options === null || options === void 0 ? void 0 : options.tracingOptions) === null || _b === void 0 ? void 0 : _b.tracingContext }; @@ -30722,8 +28548,8 @@ function convertTracingToRequestOptionsBase(options) { * {@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. */ -var BlobSASPermissions = /** @class */ (function () { - function BlobSASPermissions() { +class BlobSASPermissions { + constructor() { /** * Specifies Read access granted. */ @@ -30760,6 +28586,10 @@ var BlobSASPermissions = /** @class */ (function () { * Specifies Execute access granted. */ this.execute = false; + /** + * Specifies SetImmutabilityPolicy access granted. + */ + this.setImmutabilityPolicy = false; } /** * Creates a {@link BlobSASPermissions} from the specified permissions string. This method will throw an @@ -30767,10 +28597,9 @@ var BlobSASPermissions = /** @class */ (function () { * * @param permissions - */ - 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]; + static parse(permissions) { + const blobSASPermissions = new BlobSASPermissions(); + for (const char of permissions) { switch (char) { case "r": blobSASPermissions.read = true; @@ -30799,20 +28628,23 @@ var BlobSASPermissions = /** @class */ (function () { case "e": blobSASPermissions.execute = true; break; + case "i": + blobSASPermissions.setImmutabilityPolicy = true; + break; default: - throw new RangeError("Invalid permission: " + char); + throw new RangeError(`Invalid permission: ${char}`); } } return blobSASPermissions; - }; + } /** * Creates a {@link BlobSASPermissions} from a raw object which contains same keys as it * and boolean values for them. * * @param permissionLike - */ - BlobSASPermissions.from = function (permissionLike) { - var blobSASPermissions = new BlobSASPermissions(); + static from(permissionLike) { + const blobSASPermissions = new BlobSASPermissions(); if (permissionLike.read) { blobSASPermissions.read = true; } @@ -30840,16 +28672,19 @@ var BlobSASPermissions = /** @class */ (function () { if (permissionLike.execute) { blobSASPermissions.execute = true; } + if (permissionLike.setImmutabilityPolicy) { + blobSASPermissions.setImmutabilityPolicy = true; + } return blobSASPermissions; - }; + } /** * Converts the given permissions to a string. Using this method will guarantee the permissions are in an * order accepted by the service. * * @returns A string which represents the BlobSASPermissions */ - BlobSASPermissions.prototype.toString = function () { - var permissions = []; + toString() { + const permissions = []; if (this.read) { permissions.push("r"); } @@ -30877,10 +28712,12 @@ var BlobSASPermissions = /** @class */ (function () { if (this.execute) { permissions.push("e"); } + if (this.setImmutabilityPolicy) { + permissions.push("i"); + } return permissions.join(""); - }; - return BlobSASPermissions; -}()); + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -30891,8 +28728,8 @@ var BlobSASPermissions = /** @class */ (function () { * {@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. */ -var ContainerSASPermissions = /** @class */ (function () { - function ContainerSASPermissions() { +class ContainerSASPermissions { + constructor() { /** * Specifies Read access granted. */ @@ -30933,6 +28770,10 @@ var ContainerSASPermissions = /** @class */ (function () { * Specifies Execute access granted. */ this.execute = false; + /** + * Specifies SetImmutabilityPolicy access granted. + */ + this.setImmutabilityPolicy = false; } /** * Creates an {@link ContainerSASPermissions} from the specified permissions string. This method will throw an @@ -30940,10 +28781,9 @@ var ContainerSASPermissions = /** @class */ (function () { * * @param permissions - */ - 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]; + static parse(permissions) { + const containerSASPermissions = new ContainerSASPermissions(); + for (const char of permissions) { switch (char) { case "r": containerSASPermissions.read = true; @@ -30975,20 +28815,23 @@ var ContainerSASPermissions = /** @class */ (function () { case "e": containerSASPermissions.execute = true; break; + case "i": + containerSASPermissions.setImmutabilityPolicy = true; + break; default: - throw new RangeError("Invalid permission " + char); + throw new RangeError(`Invalid permission ${char}`); } } return containerSASPermissions; - }; + } /** * Creates a {@link ContainerSASPermissions} from a raw object which contains same keys as it * and boolean values for them. * * @param permissionLike - */ - ContainerSASPermissions.from = function (permissionLike) { - var containerSASPermissions = new ContainerSASPermissions(); + static from(permissionLike) { + const containerSASPermissions = new ContainerSASPermissions(); if (permissionLike.read) { containerSASPermissions.read = true; } @@ -31019,8 +28862,11 @@ var ContainerSASPermissions = /** @class */ (function () { if (permissionLike.execute) { containerSASPermissions.execute = true; } + if (permissionLike.setImmutabilityPolicy) { + containerSASPermissions.setImmutabilityPolicy = true; + } return containerSASPermissions; - }; + } /** * Converts the given permissions to a string. Using this method will guarantee the permissions are in an * order accepted by the service. @@ -31029,8 +28875,8 @@ var ContainerSASPermissions = /** @class */ (function () { * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * */ - ContainerSASPermissions.prototype.toString = function () { - var permissions = []; + toString() { + const permissions = []; if (this.read) { permissions.push("r"); } @@ -31061,10 +28907,12 @@ var ContainerSASPermissions = /** @class */ (function () { if (this.execute) { permissions.push("e"); } + if (this.setImmutabilityPolicy) { + permissions.push("i"); + } return permissions.join(""); - }; - return ContainerSASPermissions; -}()); + } +} // Copyright (c) Microsoft Corporation. /** @@ -31073,13 +28921,13 @@ var ContainerSASPermissions = /** @class */ (function () { * UserDelegationKeyCredential is only used for generation of user delegation SAS. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas */ -var UserDelegationKeyCredential = /** @class */ (function () { +class UserDelegationKeyCredential { /** * Creates an instance of UserDelegationKeyCredential. * @param accountName - * @param userDelegationKey - */ - function UserDelegationKeyCredential(accountName, userDelegationKey) { + constructor(accountName, userDelegationKey) { this.accountName = accountName; this.userDelegationKey = userDelegationKey; this.key = Buffer.from(userDelegationKey.value, "base64"); @@ -31089,14 +28937,13 @@ var UserDelegationKeyCredential = /** @class */ (function () { * * @param stringToSign - */ - UserDelegationKeyCredential.prototype.computeHMACSHA256 = function (stringToSign) { + computeHMACSHA256(stringToSign) { // console.log(`stringToSign: ${JSON.stringify(stringToSign)}`); return crypto.createHmac("sha256", this.key) .update(stringToSign, "utf8") .digest("base64"); - }; - return UserDelegationKeyCredential; -}()); + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -31108,7 +28955,7 @@ var UserDelegationKeyCredential = /** @class */ (function () { * @param ipRange - */ function ipRangeToString(ipRange) { - return ipRange.end ? ipRange.start + "-" + ipRange.end : ipRange.start; + return ipRange.end ? `${ipRange.start}-${ipRange.end}` : ipRange.start; } // Copyright (c) Microsoft Corporation. @@ -31125,14 +28972,14 @@ function ipRangeToString(ipRange) { /** * 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 + * types. Once generated, it can be encoded into a {@link 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. */ -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) { +class SASQueryParameters { + constructor(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") { @@ -31189,30 +29036,26 @@ var SASQueryParameters = /** @class */ (function () { } } } - Object.defineProperty(SASQueryParameters.prototype, "ipRange", { - /** - * Optional. IP range allowed for this SAS. - * - * @readonly - */ - get: function () { - if (this.ipRangeInner) { - return { - end: this.ipRangeInner.end, - start: this.ipRangeInner.start - }; - } - return undefined; - }, - enumerable: false, - configurable: true - }); + /** + * Optional. IP range allowed for this SAS. + * + * @readonly + */ + get ipRange() { + if (this.ipRangeInner) { + return { + end: this.ipRangeInner.end, + start: this.ipRangeInner.start + }; + } + return undefined; + } /** * Encodes all SAS query parameters into a string that can be appended to a URL. * */ - SASQueryParameters.prototype.toString = function () { - var params = [ + toString() { + const params = [ "sv", "ss", "srt", @@ -31238,9 +29081,8 @@ var SASQueryParameters = /** @class */ (function () { "saoid", "scid" ]; - var queries = []; - for (var _i = 0, params_1 = params; _i < params_1.length; _i++) { - var param = params_1[_i]; + const queries = []; + for (const param of params) { switch (param) { case "sv": this.tryAppendQueryParameter(queries, param, this.version); @@ -31317,7 +29159,7 @@ var SASQueryParameters = /** @class */ (function () { } } return queries.join("&"); - }; + } /** * A private helper method used to filter and append query key/value pairs into an array. * @@ -31325,26 +29167,25 @@ var SASQueryParameters = /** @class */ (function () { * @param key - * @param value - */ - SASQueryParameters.prototype.tryAppendQueryParameter = function (queries, key, value) { + tryAppendQueryParameter(queries, key, value) { if (!value) { return; } key = encodeURIComponent(key); value = encodeURIComponent(value); if (key.length > 0 && value.length > 0) { - queries.push(key + "=" + value); + queries.push(`${key}=${value}`); } - }; - return SASQueryParameters; -}()); + } +} // Copyright (c) Microsoft Corporation. function generateBlobSASQueryParameters(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { - var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; - var sharedKeyCredential = sharedKeyCredentialOrUserDelegationKey instanceof StorageSharedKeyCredential + const version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + const sharedKeyCredential = sharedKeyCredentialOrUserDelegationKey instanceof StorageSharedKeyCredential ? sharedKeyCredentialOrUserDelegationKey : undefined; - var userDelegationKeyCredential; + let userDelegationKeyCredential; if (sharedKeyCredential === undefined && accountName !== undefined) { userDelegationKeyCredential = new UserDelegationKeyCredential(accountName, sharedKeyCredentialOrUserDelegationKey); } @@ -31400,12 +29241,12 @@ function generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKe !(blobSASSignatureValues.permissions && blobSASSignatureValues.expiresOn)) { throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); } - var resource = "c"; + let resource = "c"; if (blobSASSignatureValues.blobName) { resource = "b"; } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; + let verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); @@ -31415,7 +29256,7 @@ function generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKe } } // Signature is generated on the un-url-encoded values. - var stringToSign = [ + const stringToSign = [ verifiedPermissions ? verifiedPermissions : "", blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) @@ -31434,7 +29275,7 @@ function generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKe blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" ].join("\n"); - var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + const 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); } /** @@ -31459,8 +29300,8 @@ function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKe !(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; + let resource = "c"; + let timestamp = blobSASSignatureValues.snapshotTime; if (blobSASSignatureValues.blobName) { resource = "b"; if (blobSASSignatureValues.snapshotTime) { @@ -31472,7 +29313,7 @@ function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKe } } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; + let verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); @@ -31482,7 +29323,7 @@ function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKe } } // Signature is generated on the un-url-encoded values. - var stringToSign = [ + const stringToSign = [ verifiedPermissions ? verifiedPermissions : "", blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) @@ -31503,7 +29344,7 @@ function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKe blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" ].join("\n"); - var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + const 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); } /** @@ -31526,8 +29367,8 @@ function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userD 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; + let resource = "c"; + let timestamp = blobSASSignatureValues.snapshotTime; if (blobSASSignatureValues.blobName) { resource = "b"; if (blobSASSignatureValues.snapshotTime) { @@ -31539,7 +29380,7 @@ function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userD } } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; + let verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); @@ -31549,7 +29390,7 @@ function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userD } } // Signature is generated on the un-url-encoded values. - var stringToSign = [ + const stringToSign = [ verifiedPermissions ? verifiedPermissions : "", blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) @@ -31579,7 +29420,7 @@ function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userD blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType ].join("\n"); - var signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); + const 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); } /** @@ -31602,8 +29443,8 @@ function generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userD 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; + let resource = "c"; + let timestamp = blobSASSignatureValues.snapshotTime; if (blobSASSignatureValues.blobName) { resource = "b"; if (blobSASSignatureValues.snapshotTime) { @@ -31615,7 +29456,7 @@ function generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userD } } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. - var verifiedPermissions; + let verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); @@ -31625,7 +29466,7 @@ function generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userD } } // Signature is generated on the un-url-encoded values. - var stringToSign = [ + const stringToSign = [ verifiedPermissions ? verifiedPermissions : "", blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) @@ -31658,20 +29499,20 @@ function generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userD blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType ].join("\n"); - var signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); + const 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]; + const elements = [`/blob/${accountName}/${containerName}`]; if (blobName) { - elements.push("/" + blobName); + elements.push(`/${blobName}`); } return elements.join(""); } function SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues) { - var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; + const 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'."); } @@ -31684,6 +29525,11 @@ function SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues) { if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.versionId) { throw RangeError("Must provide 'blobName' when providing 'versionId'."); } + if (blobSASSignatureValues.permissions && + blobSASSignatureValues.permissions.setImmutabilityPolicy && + version < "2020-08-04") { + throw RangeError("'version' must be >= '2020-08-04' when provided 'i' permission."); + } if (blobSASSignatureValues.permissions && blobSASSignatureValues.permissions.deleteVersion && version < "2019-10-10") { @@ -31707,17 +29553,18 @@ function SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues) { return blobSASSignatureValues; } +// Copyright (c) Microsoft Corporation. /** * A client that manages leases for a {@link ContainerClient} or a {@link BlobClient}. */ -var BlobLeaseClient = /** @class */ (function () { +class BlobLeaseClient { /** * Creates an instance of BlobLeaseClient. * @param client - The client to make the lease operation requests. * @param leaseId - Initial proposed lease id. */ - function BlobLeaseClient(client, leaseId) { - var clientContext = new StorageClientContext(client.url, client.pipeline.toServiceClientOptions()); + constructor(client, leaseId) { + const clientContext = new StorageClientContext(client.url, client.pipeline.toServiceClientOptions()); this._url = client.url; if (client.name === undefined) { this._isContainer = true; @@ -31732,30 +29579,22 @@ var BlobLeaseClient = /** @class */ (function () { } this._leaseId = leaseId; } - Object.defineProperty(BlobLeaseClient.prototype, "leaseId", { - /** - * Gets the lease Id. - * - * @readonly - */ - get: function () { - return this._leaseId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobLeaseClient.prototype, "url", { - /** - * Gets the url. - * - * @readonly - */ - get: function () { - return this._url; - }, - enumerable: false, - configurable: true - }); + /** + * Gets the lease Id. + * + * @readonly + */ + get leaseId() { + return this._leaseId; + } + /** + * Gets the url. + * + * @readonly + */ + get url() { + return this._url; + } /** * Establishes and manages a lock on a container for delete operations, or on a blob * for write and delete operations. @@ -31768,41 +29607,29 @@ var BlobLeaseClient = /** @class */ (function () { * @param options - option to configure lease management operations. * @returns Response data for acquire lease operation. */ - BlobLeaseClient.prototype.acquireLease = function (duration, options) { + async acquireLease(duration, options = {}) { var _a, _b, _c, _d, _e, _f; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _g, span, updatedOptions, e_1; - return tslib.__generator(this, function (_h) { - switch (_h.label) { - case 0: - _g = createSpan("BlobLeaseClient-acquireLease", options), span = _g.span, updatedOptions = _g.updatedOptions; - if (this._isContainer && - ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || - (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || - ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); - } - _h.label = 1; - case 1: - _h.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this._containerOrBlobOperation.acquireLease(tslib.__assign({ abortSignal: options.abortSignal, duration: duration, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), proposedLeaseId: this._leaseId }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _h.sent()]; - case 3: - e_1 = _h.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_1.message - }); - throw e_1; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobLeaseClient-acquireLease", options); + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || + ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + try { + return await this._containerOrBlobOperation.acquireLease(Object.assign({ abortSignal: options.abortSignal, duration, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), proposedLeaseId: this._leaseId }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * To change the ID of the lease. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container @@ -31813,44 +29640,31 @@ var BlobLeaseClient = /** @class */ (function () { * @param options - option to configure lease management operations. * @returns Response data for change lease operation. */ - BlobLeaseClient.prototype.changeLease = function (proposedLeaseId, options) { + async changeLease(proposedLeaseId, options = {}) { var _a, _b, _c, _d, _e, _f; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _g, span, updatedOptions, response, e_2; - return tslib.__generator(this, function (_h) { - switch (_h.label) { - case 0: - _g = createSpan("BlobLeaseClient-changeLease", options), span = _g.span, updatedOptions = _g.updatedOptions; - if (this._isContainer && - ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || - (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || - ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); - } - _h.label = 1; - case 1: - _h.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this._containerOrBlobOperation.changeLease(this._leaseId, proposedLeaseId, tslib.__assign({ abortSignal: options.abortSignal, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: - response = _h.sent(); - this._leaseId = proposedLeaseId; - return [2 /*return*/, response]; - case 3: - e_2 = _h.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_2.message - }); - throw e_2; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobLeaseClient-changeLease", options); + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || + ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + try { + const response = await this._containerOrBlobOperation.changeLease(this._leaseId, proposedLeaseId, Object.assign({ abortSignal: options.abortSignal, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + this._leaseId = proposedLeaseId; + return response; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * To free the lease if it is no longer needed so that another client may * immediately acquire a lease against the container or the blob. @@ -31861,41 +29675,29 @@ var BlobLeaseClient = /** @class */ (function () { * @param options - option to configure lease management operations. * @returns Response data for release lease operation. */ - BlobLeaseClient.prototype.releaseLease = function (options) { + async releaseLease(options = {}) { var _a, _b, _c, _d, _e, _f; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _g, span, updatedOptions, e_3; - return tslib.__generator(this, function (_h) { - switch (_h.label) { - case 0: - _g = createSpan("BlobLeaseClient-releaseLease", options), span = _g.span, updatedOptions = _g.updatedOptions; - if (this._isContainer && - ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || - (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || - ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); - } - _h.label = 1; - case 1: - _h.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this._containerOrBlobOperation.releaseLease(this._leaseId, tslib.__assign({ abortSignal: options.abortSignal, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _h.sent()]; - case 3: - e_3 = _h.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_3.message - }); - throw e_3; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobLeaseClient-releaseLease", options); + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || + ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + try { + return await this._containerOrBlobOperation.releaseLease(this._leaseId, Object.assign({ abortSignal: options.abortSignal, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * To renew the lease. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container @@ -31905,41 +29707,29 @@ var BlobLeaseClient = /** @class */ (function () { * @param options - Optional option to configure lease management operations. * @returns Response data for renew lease operation. */ - BlobLeaseClient.prototype.renewLease = function (options) { + async renewLease(options = {}) { var _a, _b, _c, _d, _e, _f; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _g, span, updatedOptions, e_4; - return tslib.__generator(this, function (_h) { - switch (_h.label) { - case 0: - _g = createSpan("BlobLeaseClient-renewLease", options), span = _g.span, updatedOptions = _g.updatedOptions; - if (this._isContainer && - ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || - (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || - ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); - } - _h.label = 1; - case 1: - _h.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this._containerOrBlobOperation.renewLease(this._leaseId, tslib.__assign({ abortSignal: options.abortSignal, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _h.sent()]; - case 3: - e_4 = _h.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_4.message - }); - throw e_4; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobLeaseClient-renewLease", options); + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || + ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + try { + return await this._containerOrBlobOperation.renewLease(this._leaseId, Object.assign({ abortSignal: options.abortSignal, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * To end the lease but ensure that another client cannot acquire a new lease * until the current lease period has expired. @@ -31951,44 +29741,31 @@ var BlobLeaseClient = /** @class */ (function () { * @param options - Optional options to configure lease management operations. * @returns Response data for break lease operation. */ - BlobLeaseClient.prototype.breakLease = function (breakPeriod, options) { + async breakLease(breakPeriod, options = {}) { var _a, _b, _c, _d, _e, _f; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _g, span, updatedOptions, operationOptions, e_5; - return tslib.__generator(this, function (_h) { - switch (_h.label) { - case 0: - _g = createSpan("BlobLeaseClient-breakLease", options), span = _g.span, updatedOptions = _g.updatedOptions; - if (this._isContainer && - ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || - (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || - ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { - throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); - } - _h.label = 1; - case 1: - _h.trys.push([1, 3, 4, 5]); - operationOptions = tslib.__assign({ abortSignal: options.abortSignal, breakPeriod: breakPeriod, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)); - return [4 /*yield*/, this._containerOrBlobOperation.breakLease(operationOptions)]; - case 2: return [2 /*return*/, _h.sent()]; - case 3: - e_5 = _h.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_5.message - }); - throw e_5; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobLeaseClient-breakLease", options); + if (this._isContainer && + ((((_a = options.conditions) === null || _a === void 0 ? void 0 : _a.ifMatch) && ((_b = options.conditions) === null || _b === void 0 ? void 0 : _b.ifMatch) !== ETagNone) || + (((_c = options.conditions) === null || _c === void 0 ? void 0 : _c.ifNoneMatch) && ((_d = options.conditions) === null || _d === void 0 ? void 0 : _d.ifNoneMatch) !== ETagNone) || + ((_e = options.conditions) === null || _e === void 0 ? void 0 : _e.tagConditions))) { + throw new RangeError("The IfMatch, IfNoneMatch and tags access conditions are ignored by the service. Values other than undefined or their default values are not acceptable."); + } + try { + const operationOptions = Object.assign({ abortSignal: options.abortSignal, breakPeriod, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)); + return await this._containerOrBlobOperation.breakLease(operationOptions); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; - return BlobLeaseClient; -}()); + throw e; + } + finally { + span.end(); + } + } +} // Copyright (c) Microsoft Corporation. /** @@ -31996,8 +29773,7 @@ var BlobLeaseClient = /** @class */ (function () { * * A Node.js ReadableStream will internally retry when internal ReadableStream unexpected ends. */ -var RetriableReadableStream = /** @class */ (function (_super) { - tslib.__extends(RetriableReadableStream, _super); +class RetriableReadableStream extends stream.Readable { /** * Creates an instance of RetriableReadableStream. * @@ -32008,32 +29784,31 @@ var RetriableReadableStream = /** @class */ (function (_super) { * @param count - How much data in original data source to read * @param options - */ - function RetriableReadableStream(source, getter, offset, count, options) { - if (options === void 0) { options = {}; } - var _this = _super.call(this, { highWaterMark: options.highWaterMark }) || this; - _this.retries = 0; - _this.sourceDataHandler = function (data) { - if (_this.options.doInjectErrorOnce) { - _this.options.doInjectErrorOnce = undefined; - _this.source.pause(); - _this.source.removeAllListeners("data"); - _this.source.emit("end"); + constructor(source, getter, offset, count, options = {}) { + super({ highWaterMark: options.highWaterMark }); + this.retries = 0; + this.sourceDataHandler = (data) => { + if (this.options.doInjectErrorOnce) { + this.options.doInjectErrorOnce = undefined; + this.source.pause(); + this.source.removeAllListeners("data"); + this.source.emit("end"); return; } // console.log( // `Offset: ${this.offset}, Received ${data.length} from internal stream` // ); - _this.offset += data.length; - if (_this.onProgress) { - _this.onProgress({ loadedBytes: _this.offset - _this.start }); + this.offset += data.length; + if (this.onProgress) { + this.onProgress({ loadedBytes: this.offset - this.start }); } - if (!_this.push(data)) { - _this.source.pause(); + if (!this.push(data)) { + this.source.pause(); } }; - _this.sourceErrorOrEndHandler = function (err) { + this.sourceErrorOrEndHandler = (err) => { if (err && err.name === "AbortError") { - _this.destroy(err); + this.destroy(err); return; } // console.log( @@ -32041,69 +29816,66 @@ var RetriableReadableStream = /** @class */ (function (_super) { // this.offset // }, dest end : ${this.end}` // ); - _this.removeSourceEventHandlers(); - if (_this.offset - 1 === _this.end) { - _this.push(null); + this.removeSourceEventHandlers(); + if (this.offset - 1 === this.end) { + this.push(null); } - else if (_this.offset <= _this.end) { + else if (this.offset <= this.end) { // console.log( // `retries: ${this.retries}, max retries: ${this.maxRetries}` // ); - if (_this.retries < _this.maxRetryRequests) { - _this.retries += 1; - _this.getter(_this.offset) - .then(function (newSource) { - _this.source = newSource; - _this.setSourceEventHandlers(); + if (this.retries < this.maxRetryRequests) { + this.retries += 1; + this.getter(this.offset) + .then((newSource) => { + this.source = newSource; + this.setSourceEventHandlers(); + return; }) - .catch(function (error) { - _this.destroy(error); + .catch((error) => { + this.destroy(error); }); } else { - _this.destroy(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)); + this.destroy(new Error(`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.destroy(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 = + 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; + this.onProgress = options.onProgress; + this.options = options; + this.setSourceEventHandlers(); } - RetriableReadableStream.prototype._read = function () { + _read() { this.source.resume(); - }; - RetriableReadableStream.prototype.setSourceEventHandlers = function () { + } + setSourceEventHandlers() { this.source.on("data", this.sourceDataHandler); this.source.on("end", this.sourceErrorOrEndHandler); this.source.on("error", this.sourceErrorOrEndHandler); - }; - RetriableReadableStream.prototype.removeSourceEventHandlers = function () { + } + removeSourceEventHandlers() { this.source.removeListener("data", this.sourceDataHandler); this.source.removeListener("end", this.sourceErrorOrEndHandler); this.source.removeListener("error", this.sourceErrorOrEndHandler); - }; - RetriableReadableStream.prototype._destroy = function (error, callback) { + } + _destroy(error, callback) { // remove listener from source and release source this.removeSourceEventHandlers(); this.source.destroy(); callback(error === null ? undefined : error); - }; - return RetriableReadableStream; -}(stream.Readable)); + } +} // Copyright (c) Microsoft Corporation. /** @@ -32116,7 +29888,7 @@ var RetriableReadableStream = /** @class */ (function (_super) { * The {@link readableStreamBody} stream will retry underlayer, you can just use it as a normal Node.js * Readable stream. */ -var BlobDownloadResponse = /** @class */ (function () { +class BlobDownloadResponse { /** * Creates an instance of BlobDownloadResponse. * @@ -32126,593 +29898,443 @@ var BlobDownloadResponse = /** @class */ (function () { * @param count - * @param options - */ - function BlobDownloadResponse(originalResponse, getter, offset, count, options) { - if (options === void 0) { options = {}; } + constructor(originalResponse, getter, offset, count, options = {}) { this.originalResponse = originalResponse; this.blobDownloadStream = new RetriableReadableStream(this.originalResponse.readableStreamBody, getter, offset, count, options); } - Object.defineProperty(BlobDownloadResponse.prototype, "acceptRanges", { - /** - * Indicates that the service supports - * requests for partial file content. - * - * @readonly - */ - get: function () { - return this.originalResponse.acceptRanges; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "cacheControl", { - /** - * Returns if it was previously specified - * for the file. - * - * @readonly - */ - get: function () { - return this.originalResponse.cacheControl; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "contentDisposition", { - /** - * Returns the value that was specified - * for the 'x-ms-content-disposition' header and specifies how to process the - * response. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentDisposition; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "contentEncoding", { - /** - * Returns the value that was specified - * for the Content-Encoding request header. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentEncoding; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "contentLanguage", { - /** - * Returns the value that was specified - * for the Content-Language request header. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentLanguage; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "blobSequenceNumber", { - /** - * The current sequence number for a - * page blob. This header is not returned for block blobs or append blobs. - * - * @readonly - */ - get: function () { - return this.originalResponse.blobSequenceNumber; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "blobType", { - /** - * The blob's type. Possible values include: - * 'BlockBlob', 'PageBlob', 'AppendBlob'. - * - * @readonly - */ - get: function () { - return this.originalResponse.blobType; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "contentLength", { - /** - * The number of bytes present in the - * response body. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentLength; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "contentMD5", { - /** - * If the file has an MD5 hash and the - * request is to read the full file, this response header is returned so that - * the client can check for message content integrity. If the request is to - * read a specified range and the 'x-ms-range-get-content-md5' is set to - * true, then the request returns an MD5 hash for the range, as long as the - * range size is less than or equal to 4 MB. If neither of these sets of - * conditions is true, then no value is returned for the 'Content-MD5' - * header. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentMD5; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "contentRange", { - /** - * Indicates the range of bytes returned if - * the client requested a subset of the file by setting the Range request - * header. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentRange; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "contentType", { - /** - * The content type specified for the file. - * The default content type is 'application/octet-stream' - * - * @readonly - */ - get: function () { - return this.originalResponse.contentType; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "copyCompletedOn", { - /** - * Conclusion time of the last attempted - * Copy File operation where this file was the destination file. This value - * can specify the time of a completed, aborted, or failed copy attempt. - * - * @readonly - */ - get: function () { - return this.originalResponse.copyCompletedOn; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "copyId", { - /** - * String identifier for the last attempted Copy - * File operation where this file was the destination file. - * - * @readonly - */ - get: function () { - return this.originalResponse.copyId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "copyProgress", { - /** - * Contains the number of bytes copied and - * the total bytes in the source in the last attempted Copy File operation - * where this file was the destination file. Can show between 0 and - * Content-Length bytes copied. - * - * @readonly - */ - get: function () { - return this.originalResponse.copyProgress; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "copySource", { - /** - * URL up to 2KB in length that specifies the - * source file used in the last attempted Copy File operation where this file - * was the destination file. - * - * @readonly - */ - get: function () { - return this.originalResponse.copySource; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "copyStatus", { - /** - * State of the copy operation - * identified by 'x-ms-copy-id'. Possible values include: 'pending', - * 'success', 'aborted', 'failed' - * - * @readonly - */ - get: function () { - return this.originalResponse.copyStatus; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "copyStatusDescription", { - /** - * Only appears when - * x-ms-copy-status is failed or pending. Describes cause of fatal or - * non-fatal copy operation failure. - * - * @readonly - */ - get: function () { - return this.originalResponse.copyStatusDescription; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "leaseDuration", { - /** - * When a blob is leased, - * specifies whether the lease is of infinite or fixed duration. Possible - * values include: 'infinite', 'fixed'. - * - * @readonly - */ - get: function () { - return this.originalResponse.leaseDuration; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "leaseState", { - /** - * Lease state of the blob. Possible - * values include: 'available', 'leased', 'expired', 'breaking', 'broken'. - * - * @readonly - */ - get: function () { - return this.originalResponse.leaseState; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "leaseStatus", { - /** - * The current lease status of the - * blob. Possible values include: 'locked', 'unlocked'. - * - * @readonly - */ - get: function () { - return this.originalResponse.leaseStatus; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "date", { - /** - * A UTC date/time value generated by the service that - * indicates the time at which the response was initiated. - * - * @readonly - */ - get: function () { - return this.originalResponse.date; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "blobCommittedBlockCount", { - /** - * The number of committed blocks - * present in the blob. This header is returned only for append blobs. - * - * @readonly - */ - get: function () { - return this.originalResponse.blobCommittedBlockCount; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "etag", { - /** - * The ETag contains a value that you can use to - * perform operations conditionally, in quotes. - * - * @readonly - */ - get: function () { - return this.originalResponse.etag; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "tagCount", { - /** - * The number of tags associated with the blob - * - * @readonly - */ - get: function () { - return this.originalResponse.tagCount; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "errorCode", { - /** - * The error code. - * - * @readonly - */ - get: function () { - return this.originalResponse.errorCode; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "isServerEncrypted", { - /** - * The value of this header is set to - * true if the file data and application metadata are completely encrypted - * using the specified algorithm. Otherwise, the value is set to false (when - * the file is unencrypted, or if only parts of the file/application metadata - * are encrypted). - * - * @readonly - */ - get: function () { - return this.originalResponse.isServerEncrypted; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "blobContentMD5", { - /** - * If the blob has a MD5 hash, and if - * request contains range header (Range or x-ms-range), this response header - * is returned with the value of the whole blob's MD5 value. This value may - * or may not be equal to the value returned in Content-MD5 header, with the - * latter calculated from the requested range. - * - * @readonly - */ - get: function () { - return this.originalResponse.blobContentMD5; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "lastModified", { - /** - * Returns the date and time the file was last - * modified. Any operation that modifies the file or its properties updates - * the last modified time. - * - * @readonly - */ - get: function () { - return this.originalResponse.lastModified; - }, - 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 - */ - get: function () { - return this.originalResponse.lastAccessed; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "metadata", { - /** - * A name-value pair - * to associate with a file storage object. - * - * @readonly - */ - get: function () { - return this.originalResponse.metadata; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "requestId", { - /** - * This header uniquely identifies the request - * that was made and can be used for troubleshooting the request. - * - * @readonly - */ - get: function () { - return this.originalResponse.requestId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "clientRequestId", { - /** - * If a client request id header is sent in the request, this header will be present in the - * response with the same value. - * - * @readonly - */ - get: function () { - return this.originalResponse.clientRequestId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "version", { - /** - * Indicates the version of the Blob service used - * to execute the request. - * - * @readonly - */ - get: function () { - return this.originalResponse.version; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "versionId", { - /** - * Indicates the versionId of the downloaded blob version. - * - * @readonly - */ - get: function () { - return this.originalResponse.versionId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "isCurrentVersion", { - /** - * Indicates whether version of this blob is a current version. - * - * @readonly - */ - get: function () { - return this.originalResponse.isCurrentVersion; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "encryptionKeySha256", { - /** - * The SHA-256 hash of the encryption key used to encrypt the blob. This value is only returned - * when the blob was encrypted with a customer-provided key. - * - * @readonly - */ - get: function () { - return this.originalResponse.encryptionKeySha256; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "contentCrc64", { - /** - * If the request is to read a specified range and the x-ms-range-get-content-crc64 is set to - * true, then the request returns a crc64 for the range, as long as the range size is less than - * or equal to 4 MB. If both x-ms-range-get-content-crc64 & x-ms-range-get-content-md5 is - * specified in the same request, it will fail with 400(Bad Request) - */ - get: function () { - return this.originalResponse.contentCrc64; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "objectReplicationDestinationPolicyId", { - /** - * Object Replication Policy Id of the destination blob. - * - * @readonly - */ - get: function () { - return this.originalResponse.objectReplicationDestinationPolicyId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "objectReplicationSourceProperties", { - /** - * Parsed Object Replication Policy Id, Rule Id(s) and status of the source blob. - * - * @readonly - */ - get: function () { - return this.originalResponse.objectReplicationSourceProperties; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "isSealed", { - /** - * If this blob has been sealed. - * - * @readonly - */ - get: function () { - return this.originalResponse.isSealed; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "contentAsBlob", { - /** - * The response body as a browser Blob. - * Always undefined in node.js. - * - * @readonly - */ - get: function () { - return this.originalResponse.blobBody; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "readableStreamBody", { - /** - * The response body as a node.js Readable stream. - * Always undefined in the browser. - * - * It will automatically retry when internal read stream unexpected ends. - * - * @readonly - */ - get: function () { - return coreHttp.isNode ? this.blobDownloadStream : undefined; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobDownloadResponse.prototype, "_response", { - /** - * The HTTP response. - */ - get: function () { - return this.originalResponse._response; - }, - enumerable: false, - configurable: true - }); - return BlobDownloadResponse; -}()); + /** + * Indicates that the service supports + * requests for partial file content. + * + * @readonly + */ + get acceptRanges() { + return this.originalResponse.acceptRanges; + } + /** + * Returns if it was previously specified + * for the file. + * + * @readonly + */ + get cacheControl() { + return this.originalResponse.cacheControl; + } + /** + * Returns the value that was specified + * for the 'x-ms-content-disposition' header and specifies how to process the + * response. + * + * @readonly + */ + get contentDisposition() { + return this.originalResponse.contentDisposition; + } + /** + * Returns the value that was specified + * for the Content-Encoding request header. + * + * @readonly + */ + get contentEncoding() { + return this.originalResponse.contentEncoding; + } + /** + * Returns the value that was specified + * for the Content-Language request header. + * + * @readonly + */ + get contentLanguage() { + return this.originalResponse.contentLanguage; + } + /** + * The current sequence number for a + * page blob. This header is not returned for block blobs or append blobs. + * + * @readonly + */ + get blobSequenceNumber() { + return this.originalResponse.blobSequenceNumber; + } + /** + * The blob's type. Possible values include: + * 'BlockBlob', 'PageBlob', 'AppendBlob'. + * + * @readonly + */ + get blobType() { + return this.originalResponse.blobType; + } + /** + * The number of bytes present in the + * response body. + * + * @readonly + */ + get contentLength() { + return this.originalResponse.contentLength; + } + /** + * If the file has an MD5 hash and the + * request is to read the full file, this response header is returned so that + * the client can check for message content integrity. If the request is to + * read a specified range and the 'x-ms-range-get-content-md5' is set to + * true, then the request returns an MD5 hash for the range, as long as the + * range size is less than or equal to 4 MB. If neither of these sets of + * conditions is true, then no value is returned for the 'Content-MD5' + * header. + * + * @readonly + */ + get contentMD5() { + return this.originalResponse.contentMD5; + } + /** + * Indicates the range of bytes returned if + * the client requested a subset of the file by setting the Range request + * header. + * + * @readonly + */ + get contentRange() { + return this.originalResponse.contentRange; + } + /** + * The content type specified for the file. + * The default content type is 'application/octet-stream' + * + * @readonly + */ + get contentType() { + return this.originalResponse.contentType; + } + /** + * Conclusion time of the last attempted + * Copy File operation where this file was the destination file. This value + * can specify the time of a completed, aborted, or failed copy attempt. + * + * @readonly + */ + get copyCompletedOn() { + return this.originalResponse.copyCompletedOn; + } + /** + * String identifier for the last attempted Copy + * File operation where this file was the destination file. + * + * @readonly + */ + get copyId() { + return this.originalResponse.copyId; + } + /** + * Contains the number of bytes copied and + * the total bytes in the source in the last attempted Copy File operation + * where this file was the destination file. Can show between 0 and + * Content-Length bytes copied. + * + * @readonly + */ + get copyProgress() { + return this.originalResponse.copyProgress; + } + /** + * URL up to 2KB in length that specifies the + * source file used in the last attempted Copy File operation where this file + * was the destination file. + * + * @readonly + */ + get copySource() { + return this.originalResponse.copySource; + } + /** + * State of the copy operation + * identified by 'x-ms-copy-id'. Possible values include: 'pending', + * 'success', 'aborted', 'failed' + * + * @readonly + */ + get copyStatus() { + return this.originalResponse.copyStatus; + } + /** + * Only appears when + * x-ms-copy-status is failed or pending. Describes cause of fatal or + * non-fatal copy operation failure. + * + * @readonly + */ + get copyStatusDescription() { + return this.originalResponse.copyStatusDescription; + } + /** + * When a blob is leased, + * specifies whether the lease is of infinite or fixed duration. Possible + * values include: 'infinite', 'fixed'. + * + * @readonly + */ + get leaseDuration() { + return this.originalResponse.leaseDuration; + } + /** + * Lease state of the blob. Possible + * values include: 'available', 'leased', 'expired', 'breaking', 'broken'. + * + * @readonly + */ + get leaseState() { + return this.originalResponse.leaseState; + } + /** + * The current lease status of the + * blob. Possible values include: 'locked', 'unlocked'. + * + * @readonly + */ + get leaseStatus() { + return this.originalResponse.leaseStatus; + } + /** + * A UTC date/time value generated by the service that + * indicates the time at which the response was initiated. + * + * @readonly + */ + get date() { + return this.originalResponse.date; + } + /** + * The number of committed blocks + * present in the blob. This header is returned only for append blobs. + * + * @readonly + */ + get blobCommittedBlockCount() { + return this.originalResponse.blobCommittedBlockCount; + } + /** + * The ETag contains a value that you can use to + * perform operations conditionally, in quotes. + * + * @readonly + */ + get etag() { + return this.originalResponse.etag; + } + /** + * The number of tags associated with the blob + * + * @readonly + */ + get tagCount() { + return this.originalResponse.tagCount; + } + /** + * The error code. + * + * @readonly + */ + get errorCode() { + return this.originalResponse.errorCode; + } + /** + * The value of this header is set to + * true if the file data and application metadata are completely encrypted + * using the specified algorithm. Otherwise, the value is set to false (when + * the file is unencrypted, or if only parts of the file/application metadata + * are encrypted). + * + * @readonly + */ + get isServerEncrypted() { + return this.originalResponse.isServerEncrypted; + } + /** + * If the blob has a MD5 hash, and if + * request contains range header (Range or x-ms-range), this response header + * is returned with the value of the whole blob's MD5 value. This value may + * or may not be equal to the value returned in Content-MD5 header, with the + * latter calculated from the requested range. + * + * @readonly + */ + get blobContentMD5() { + return this.originalResponse.blobContentMD5; + } + /** + * Returns the date and time the file was last + * modified. Any operation that modifies the file or its properties updates + * the last modified time. + * + * @readonly + */ + get lastModified() { + return this.originalResponse.lastModified; + } + /** + * 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 + */ + get lastAccessed() { + return this.originalResponse.lastAccessed; + } + /** + * A name-value pair + * to associate with a file storage object. + * + * @readonly + */ + get metadata() { + return this.originalResponse.metadata; + } + /** + * This header uniquely identifies the request + * that was made and can be used for troubleshooting the request. + * + * @readonly + */ + get requestId() { + return this.originalResponse.requestId; + } + /** + * If a client request id header is sent in the request, this header will be present in the + * response with the same value. + * + * @readonly + */ + get clientRequestId() { + return this.originalResponse.clientRequestId; + } + /** + * Indicates the version of the Blob service used + * to execute the request. + * + * @readonly + */ + get version() { + return this.originalResponse.version; + } + /** + * Indicates the versionId of the downloaded blob version. + * + * @readonly + */ + get versionId() { + return this.originalResponse.versionId; + } + /** + * Indicates whether version of this blob is a current version. + * + * @readonly + */ + get isCurrentVersion() { + return this.originalResponse.isCurrentVersion; + } + /** + * The SHA-256 hash of the encryption key used to encrypt the blob. This value is only returned + * when the blob was encrypted with a customer-provided key. + * + * @readonly + */ + get encryptionKeySha256() { + return this.originalResponse.encryptionKeySha256; + } + /** + * If the request is to read a specified range and the x-ms-range-get-content-crc64 is set to + * true, then the request returns a crc64 for the range, as long as the range size is less than + * or equal to 4 MB. If both x-ms-range-get-content-crc64 & x-ms-range-get-content-md5 is + * specified in the same request, it will fail with 400(Bad Request) + */ + get contentCrc64() { + return this.originalResponse.contentCrc64; + } + /** + * Object Replication Policy Id of the destination blob. + * + * @readonly + */ + get objectReplicationDestinationPolicyId() { + return this.originalResponse.objectReplicationDestinationPolicyId; + } + /** + * Parsed Object Replication Policy Id, Rule Id(s) and status of the source blob. + * + * @readonly + */ + get objectReplicationSourceProperties() { + return this.originalResponse.objectReplicationSourceProperties; + } + /** + * If this blob has been sealed. + * + * @readonly + */ + get isSealed() { + return this.originalResponse.isSealed; + } + /** + * UTC date/time value generated by the service that indicates the time at which the blob immutability policy will expire. + * + * @readonly + */ + get immutabilityPolicyExpiresOn() { + return this.originalResponse.immutabilityPolicyExpiresOn; + } + /** + * Indicates immutability policy mode. + * + * @readonly + */ + get immutabilityPolicyMode() { + return this.originalResponse.immutabilityPolicyMode; + } + /** + * Indicates if a legal hold is present on the blob. + * + * @readonly + */ + get legalHold() { + return this.originalResponse.legalHold; + } + /** + * The response body as a browser Blob. + * Always undefined in node.js. + * + * @readonly + */ + get contentAsBlob() { + return this.originalResponse.blobBody; + } + /** + * The response body as a node.js Readable stream. + * Always undefined in the browser. + * + * It will automatically retry when internal read stream unexpected ends. + * + * @readonly + */ + get readableStreamBody() { + return coreHttp.isNode ? this.blobDownloadStream : undefined; + } + /** + * The HTTP response. + */ + get _response() { + return this.originalResponse._response; + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -var AVRO_SYNC_MARKER_SIZE = 16; -var AVRO_INIT_BYTES = new Uint8Array([79, 98, 106, 1]); -var AVRO_CODEC_KEY = "avro.codec"; -var AVRO_SCHEMA_KEY = "avro.schema"; +const AVRO_SYNC_MARKER_SIZE = 16; +const AVRO_INIT_BYTES = new Uint8Array([79, 98, 106, 1]); +const AVRO_CODEC_KEY = "avro.codec"; +const AVRO_SCHEMA_KEY = "avro.schema"; // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -32723,7 +30345,7 @@ function arraysEqual(a, b) { return false; if (a.length != b.length) return false; - for (var i = 0; i < a.length; ++i) { + for (let i = 0; i < a.length; ++i) { if (a[i] !== b[i]) return false; } @@ -32731,9 +30353,8 @@ function arraysEqual(a, b) { } // Copyright (c) Microsoft Corporation. -var AvroParser = /** @class */ (function () { - function AvroParser() { - } +// Licensed under the MIT license. +class AvroParser { /** * Reads a fixed number of bytes from the stream. * @@ -32741,294 +30362,135 @@ var AvroParser = /** @class */ (function () { * @param length - * @param options - */ - AvroParser.readFixedBytes = function (stream, length, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var bytes; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, stream.read(length, { abortSignal: options.abortSignal })]; - case 1: - bytes = _a.sent(); - if (bytes.length != length) { - throw new Error("Hit stream end."); - } - return [2 /*return*/, bytes]; - } - }); - }); - }; + static async readFixedBytes(stream, length, options = {}) { + const bytes = await stream.read(length, { abortSignal: options.abortSignal }); + if (bytes.length != length) { + throw new Error("Hit stream end."); + } + return bytes; + } /** * Reads a single byte from the stream. * * @param stream - * @param options - */ - AvroParser.readByte = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var buf; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, AvroParser.readFixedBytes(stream, 1, options)]; - case 1: - buf = _a.sent(); - return [2 /*return*/, buf[0]]; - } - }); - }); - }; + static async readByte(stream, options = {}) { + const buf = await AvroParser.readFixedBytes(stream, 1, options); + return buf[0]; + } // int and long are stored in variable-length zig-zag coding. // variable-length: https://lucene.apache.org/core/3_5_0/fileformats.html#VInt // zig-zag: https://developers.google.com/protocol-buffers/docs/encoding?csw=1#types - AvroParser.readZigZagLong = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var zigZagEncoded, significanceInBit, byte, haveMoreByte, significanceInFloat, res; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - zigZagEncoded = 0; - significanceInBit = 0; - _a.label = 1; - case 1: return [4 /*yield*/, AvroParser.readByte(stream, options)]; - case 2: - byte = _a.sent(); - haveMoreByte = byte & 0x80; - zigZagEncoded |= (byte & 0x7f) << significanceInBit; - significanceInBit += 7; - _a.label = 3; - case 3: - if (haveMoreByte && significanceInBit < 28) return [3 /*break*/, 1]; - _a.label = 4; - case 4: - if (!haveMoreByte) return [3 /*break*/, 9]; - // Switch to float arithmetic - zigZagEncoded = zigZagEncoded; - significanceInFloat = 268435456; // 2 ** 28. - _a.label = 5; - case 5: return [4 /*yield*/, AvroParser.readByte(stream, options)]; - case 6: - byte = _a.sent(); - zigZagEncoded += (byte & 0x7f) * significanceInFloat; - significanceInFloat *= 128; // 2 ** 7 - _a.label = 7; - case 7: - if (byte & 0x80) return [3 /*break*/, 5]; - _a.label = 8; - case 8: - res = (zigZagEncoded % 2 ? -(zigZagEncoded + 1) : zigZagEncoded) / 2; - if (res < Number.MIN_SAFE_INTEGER || res > Number.MAX_SAFE_INTEGER) { - throw new Error("Integer overflow."); - } - return [2 /*return*/, res]; - case 9: return [2 /*return*/, (zigZagEncoded >> 1) ^ -(zigZagEncoded & 1)]; - } - }); - }); - }; - AvroParser.readLong = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - return [2 /*return*/, AvroParser.readZigZagLong(stream, options)]; - }); - }); - }; - AvroParser.readInt = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - return [2 /*return*/, AvroParser.readZigZagLong(stream, options)]; - }); - }); - }; - AvroParser.readNull = function () { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - return [2 /*return*/, null]; - }); - }); - }; - AvroParser.readBoolean = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var b; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, AvroParser.readByte(stream, options)]; - case 1: - b = _a.sent(); - if (b == 1) { - return [2 /*return*/, true]; - } - else if (b == 0) { - return [2 /*return*/, false]; - } - else { - throw new Error("Byte was not a boolean."); - } - } - }); - }); - }; - AvroParser.readFloat = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var u8arr, view; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, AvroParser.readFixedBytes(stream, 4, options)]; - case 1: - u8arr = _a.sent(); - view = new DataView(u8arr.buffer, u8arr.byteOffset, u8arr.byteLength); - return [2 /*return*/, view.getFloat32(0, true)]; // littleEndian = true - } - }); - }); - }; - AvroParser.readDouble = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var u8arr, view; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, AvroParser.readFixedBytes(stream, 8, options)]; - case 1: - u8arr = _a.sent(); - view = new DataView(u8arr.buffer, u8arr.byteOffset, u8arr.byteLength); - return [2 /*return*/, view.getFloat64(0, true)]; // littleEndian = true - } - }); - }); - }; - AvroParser.readBytes = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var size; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, AvroParser.readLong(stream, options)]; - case 1: - size = _a.sent(); - if (size < 0) { - throw new Error("Bytes size was negative."); - } - return [4 /*yield*/, stream.read(size, { abortSignal: options.abortSignal })]; - case 2: return [2 /*return*/, _a.sent()]; - } - }); - }); - }; - AvroParser.readString = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var u8arr, utf8decoder; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, AvroParser.readBytes(stream, options)]; - case 1: - u8arr = _a.sent(); - // polyfill TextDecoder to be backward compatible with older - // nodejs that doesn't expose TextDecoder as a global variable - if (typeof TextDecoder === "undefined" && "function" !== "undefined") { - global.TextDecoder = __webpack_require__(669).TextDecoder; - } - utf8decoder = new TextDecoder(); - return [2 /*return*/, utf8decoder.decode(u8arr)]; - } - }); - }); - }; - AvroParser.readMapPair = function (stream, readItemMethod, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var key, value; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, AvroParser.readString(stream, options)]; - case 1: - key = _a.sent(); - return [4 /*yield*/, readItemMethod(stream, options)]; - case 2: - value = _a.sent(); - return [2 /*return*/, { key: key, value: value }]; - } - }); - }); - }; - AvroParser.readMap = function (stream, readItemMethod, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var readPairMethod, pairs, dict, _i, pairs_1, pair; - var _this = this; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - readPairMethod = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(_this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, AvroParser.readMapPair(stream, readItemMethod, options)]; - case 1: return [2 /*return*/, _a.sent()]; - } - }); - }); - }; - return [4 /*yield*/, AvroParser.readArray(stream, readPairMethod, options)]; - case 1: - pairs = _a.sent(); - dict = {}; - for (_i = 0, pairs_1 = pairs; _i < pairs_1.length; _i++) { - pair = pairs_1[_i]; - dict[pair.key] = pair.value; - } - return [2 /*return*/, dict]; - } - }); - }); - }; - AvroParser.readArray = function (stream, readItemMethod, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var items, count, item; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - items = []; - return [4 /*yield*/, AvroParser.readLong(stream, options)]; - case 1: - count = _a.sent(); - _a.label = 2; - case 2: - if (!(count != 0)) return [3 /*break*/, 8]; - if (!(count < 0)) return [3 /*break*/, 4]; - // Ignore block sizes - return [4 /*yield*/, AvroParser.readLong(stream, options)]; - case 3: - // Ignore block sizes - _a.sent(); - count = -count; - _a.label = 4; - case 4: - if (!count--) return [3 /*break*/, 6]; - return [4 /*yield*/, readItemMethod(stream, options)]; - case 5: - item = _a.sent(); - items.push(item); - return [3 /*break*/, 4]; - case 6: return [4 /*yield*/, AvroParser.readLong(stream, options)]; - case 7: - count = _a.sent(); - return [3 /*break*/, 2]; - case 8: return [2 /*return*/, items]; - } - }); - }); - }; - return AvroParser; -}()); + static async readZigZagLong(stream, options = {}) { + let zigZagEncoded = 0; + let significanceInBit = 0; + let byte, haveMoreByte, significanceInFloat; + do { + byte = await AvroParser.readByte(stream, options); + haveMoreByte = byte & 0x80; + zigZagEncoded |= (byte & 0x7f) << significanceInBit; + significanceInBit += 7; + } while (haveMoreByte && significanceInBit < 28); // bitwise operation only works for 32-bit integers + if (haveMoreByte) { + // Switch to float arithmetic + zigZagEncoded = zigZagEncoded; + significanceInFloat = 268435456; // 2 ** 28. + do { + byte = await AvroParser.readByte(stream, options); + zigZagEncoded += (byte & 0x7f) * significanceInFloat; + significanceInFloat *= 128; // 2 ** 7 + } while (byte & 0x80); + const res = (zigZagEncoded % 2 ? -(zigZagEncoded + 1) : zigZagEncoded) / 2; + if (res < Number.MIN_SAFE_INTEGER || res > Number.MAX_SAFE_INTEGER) { + throw new Error("Integer overflow."); + } + return res; + } + return (zigZagEncoded >> 1) ^ -(zigZagEncoded & 1); + } + static async readLong(stream, options = {}) { + return AvroParser.readZigZagLong(stream, options); + } + static async readInt(stream, options = {}) { + return AvroParser.readZigZagLong(stream, options); + } + static async readNull() { + return null; + } + static async readBoolean(stream, options = {}) { + const b = await AvroParser.readByte(stream, options); + if (b == 1) { + return true; + } + else if (b == 0) { + return false; + } + else { + throw new Error("Byte was not a boolean."); + } + } + static async readFloat(stream, options = {}) { + const u8arr = await AvroParser.readFixedBytes(stream, 4, options); + const view = new DataView(u8arr.buffer, u8arr.byteOffset, u8arr.byteLength); + return view.getFloat32(0, true); // littleEndian = true + } + static async readDouble(stream, options = {}) { + const u8arr = await AvroParser.readFixedBytes(stream, 8, options); + const view = new DataView(u8arr.buffer, u8arr.byteOffset, u8arr.byteLength); + return view.getFloat64(0, true); // littleEndian = true + } + static async readBytes(stream, options = {}) { + const size = await AvroParser.readLong(stream, options); + if (size < 0) { + throw new Error("Bytes size was negative."); + } + return await stream.read(size, { abortSignal: options.abortSignal }); + } + static async readString(stream, options = {}) { + const u8arr = await AvroParser.readBytes(stream, options); + // polyfill TextDecoder to be backward compatible with older + // nodejs that doesn't expose TextDecoder as a global variable + if (typeof TextDecoder === "undefined" && "function" !== "undefined") { + global.TextDecoder = __webpack_require__(669).TextDecoder; + } + // FUTURE: need TextDecoder polyfill for IE + const utf8decoder = new TextDecoder(); + return utf8decoder.decode(u8arr); + } + static async readMapPair(stream, readItemMethod, options = {}) { + const key = await AvroParser.readString(stream, options); + // FUTURE: this won't work with readFixed (currently not supported) which needs a length as the parameter. + const value = await readItemMethod(stream, options); + return { key, value }; + } + static async readMap(stream, readItemMethod, options = {}) { + const readPairMethod = async (stream, options = {}) => { + return await AvroParser.readMapPair(stream, readItemMethod, options); + }; + const pairs = await AvroParser.readArray(stream, readPairMethod, options); + const dict = {}; + for (const pair of pairs) { + dict[pair.key] = pair.value; + } + return dict; + } + static async readArray(stream, readItemMethod, options = {}) { + const items = []; + for (let count = await AvroParser.readLong(stream, options); count != 0; count = await AvroParser.readLong(stream, options)) { + if (count < 0) { + // Ignore block sizes + await AvroParser.readLong(stream, options); + count = -count; + } + while (count--) { + const item = await readItemMethod(stream, options); + items.push(item); + } + } + return items; + } +} var AvroComplex; (function (AvroComplex) { AvroComplex["RECORD"] = "record"; @@ -33038,13 +30500,11 @@ var AvroComplex; AvroComplex["UNION"] = "union"; AvroComplex["FIXED"] = "fixed"; })(AvroComplex || (AvroComplex = {})); -var AvroType = /** @class */ (function () { - function AvroType() { - } +class AvroType { /** * Determines the AvroType from the Avro Schema. */ - AvroType.fromSchema = function (schema) { + static fromSchema(schema) { if (typeof schema === "string") { return AvroType.fromStringSchema(schema); } @@ -33054,8 +30514,8 @@ var AvroType = /** @class */ (function () { else { return AvroType.fromObjectSchema(schema); } - }; - AvroType.fromStringSchema = function (schema) { + } + static fromStringSchema(schema) { switch (schema) { case AvroPrimitive.NULL: case AvroPrimitive.BOOLEAN: @@ -33067,14 +30527,14 @@ var AvroType = /** @class */ (function () { case AvroPrimitive.STRING: return new AvroPrimitiveType(schema); default: - throw new Error("Unexpected Avro type " + schema); + throw new Error(`Unexpected Avro type ${schema}`); } - }; - AvroType.fromArraySchema = function (schema) { + } + static fromArraySchema(schema) { return new AvroUnionType(schema.map(AvroType.fromSchema)); - }; - AvroType.fromObjectSchema = function (schema) { - var type = schema.type; + } + static fromObjectSchema(schema) { + const type = schema.type; // Primitives can be defined as strings or objects try { return AvroType.fromStringSchema(type); @@ -33083,41 +30543,39 @@ var AvroType = /** @class */ (function () { switch (type) { case AvroComplex.RECORD: if (schema.aliases) { - throw new Error("aliases currently is not supported, schema: " + schema); + throw new Error(`aliases currently is not supported, schema: ${schema}`); } if (!schema.name) { - throw new Error("Required attribute 'name' doesn't exist on schema: " + schema); + throw new Error(`Required attribute 'name' doesn't exist on schema: ${schema}`); } - var fields = {}; + const fields = {}; if (!schema.fields) { - throw new Error("Required attribute 'fields' doesn't exist on schema: " + schema); + throw new Error(`Required attribute 'fields' doesn't exist on schema: ${schema}`); } - for (var _i = 0, _a = schema.fields; _i < _a.length; _i++) { - var field = _a[_i]; + for (const field of schema.fields) { fields[field.name] = AvroType.fromSchema(field.type); } return new AvroRecordType(fields, schema.name); case AvroComplex.ENUM: if (schema.aliases) { - throw new Error("aliases currently is not supported, schema: " + schema); + throw new Error(`aliases currently is not supported, schema: ${schema}`); } if (!schema.symbols) { - throw new Error("Required attribute 'symbols' doesn't exist on schema: " + schema); + throw new Error(`Required attribute 'symbols' doesn't exist on schema: ${schema}`); } return new AvroEnumType(schema.symbols); case AvroComplex.MAP: if (!schema.values) { - throw new Error("Required attribute 'values' doesn't exist on schema: " + schema); + throw new Error(`Required attribute 'values' doesn't exist on schema: ${schema}`); } return new AvroMapType(AvroType.fromSchema(schema.values)); case AvroComplex.ARRAY: // Unused today case AvroComplex.FIXED: // Unused today default: - throw new Error("Unexpected Avro type " + type + " in " + schema); + throw new Error(`Unexpected Avro type ${type} in ${schema}`); } - }; - return AvroType; -}()); + } +} var AvroPrimitive; (function (AvroPrimitive) { AvroPrimitive["NULL"] = "null"; @@ -33129,179 +30587,87 @@ var AvroPrimitive; AvroPrimitive["BYTES"] = "bytes"; AvroPrimitive["STRING"] = "string"; })(AvroPrimitive || (AvroPrimitive = {})); -var AvroPrimitiveType = /** @class */ (function (_super) { - tslib.__extends(AvroPrimitiveType, _super); - function AvroPrimitiveType(primitive) { - var _this = _super.call(this) || this; - _this._primitive = primitive; - return _this; +class AvroPrimitiveType extends AvroType { + constructor(primitive) { + super(); + this._primitive = primitive; } - AvroPrimitiveType.prototype.read = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = this._primitive; - switch (_a) { - case AvroPrimitive.NULL: return [3 /*break*/, 1]; - case AvroPrimitive.BOOLEAN: return [3 /*break*/, 3]; - case AvroPrimitive.INT: return [3 /*break*/, 5]; - case AvroPrimitive.LONG: return [3 /*break*/, 7]; - case AvroPrimitive.FLOAT: return [3 /*break*/, 9]; - case AvroPrimitive.DOUBLE: return [3 /*break*/, 11]; - case AvroPrimitive.BYTES: return [3 /*break*/, 13]; - case AvroPrimitive.STRING: return [3 /*break*/, 15]; - } - return [3 /*break*/, 17]; - case 1: return [4 /*yield*/, AvroParser.readNull()]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: return [4 /*yield*/, AvroParser.readBoolean(stream, options)]; - case 4: return [2 /*return*/, _b.sent()]; - case 5: return [4 /*yield*/, AvroParser.readInt(stream, options)]; - case 6: return [2 /*return*/, _b.sent()]; - case 7: return [4 /*yield*/, AvroParser.readLong(stream, options)]; - case 8: return [2 /*return*/, _b.sent()]; - case 9: return [4 /*yield*/, AvroParser.readFloat(stream, options)]; - case 10: return [2 /*return*/, _b.sent()]; - case 11: return [4 /*yield*/, AvroParser.readDouble(stream, options)]; - case 12: return [2 /*return*/, _b.sent()]; - case 13: return [4 /*yield*/, AvroParser.readBytes(stream, options)]; - case 14: return [2 /*return*/, _b.sent()]; - case 15: return [4 /*yield*/, AvroParser.readString(stream, options)]; - case 16: return [2 /*return*/, _b.sent()]; - case 17: throw new Error("Unknown Avro Primitive"); - } - }); - }); - }; - return AvroPrimitiveType; -}(AvroType)); -var AvroEnumType = /** @class */ (function (_super) { - tslib.__extends(AvroEnumType, _super); - function AvroEnumType(symbols) { - var _this = _super.call(this) || this; - _this._symbols = symbols; - return _this; + async read(stream, options = {}) { + switch (this._primitive) { + case AvroPrimitive.NULL: + return await AvroParser.readNull(); + case AvroPrimitive.BOOLEAN: + return await AvroParser.readBoolean(stream, options); + case AvroPrimitive.INT: + return await AvroParser.readInt(stream, options); + case AvroPrimitive.LONG: + return await AvroParser.readLong(stream, options); + case AvroPrimitive.FLOAT: + return await AvroParser.readFloat(stream, options); + case AvroPrimitive.DOUBLE: + return await AvroParser.readDouble(stream, options); + case AvroPrimitive.BYTES: + return await AvroParser.readBytes(stream, options); + case AvroPrimitive.STRING: + return await AvroParser.readString(stream, options); + default: + throw new Error("Unknown Avro Primitive"); + } } - AvroEnumType.prototype.read = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var value; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, AvroParser.readInt(stream, options)]; - case 1: - value = _a.sent(); - return [2 /*return*/, this._symbols[value]]; - } - }); - }); - }; - return AvroEnumType; -}(AvroType)); -var AvroUnionType = /** @class */ (function (_super) { - tslib.__extends(AvroUnionType, _super); - function AvroUnionType(types) { - var _this = _super.call(this) || this; - _this._types = types; - return _this; +} +class AvroEnumType extends AvroType { + constructor(symbols) { + super(); + this._symbols = symbols; } - AvroUnionType.prototype.read = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var typeIndex; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, AvroParser.readInt(stream, options)]; - case 1: - typeIndex = _a.sent(); - return [4 /*yield*/, this._types[typeIndex].read(stream, options)]; - case 2: return [2 /*return*/, _a.sent()]; - } - }); - }); - }; - return AvroUnionType; -}(AvroType)); -var AvroMapType = /** @class */ (function (_super) { - tslib.__extends(AvroMapType, _super); - function AvroMapType(itemType) { - var _this = _super.call(this) || this; - _this._itemType = itemType; - return _this; + async read(stream, options = {}) { + const value = await AvroParser.readInt(stream, options); + return this._symbols[value]; } - AvroMapType.prototype.read = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var readItemMethod; - var _this = this; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - readItemMethod = function (s, options) { return tslib.__awaiter(_this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this._itemType.read(s, options)]; - case 1: return [2 /*return*/, _a.sent()]; - } - }); - }); }; - return [4 /*yield*/, AvroParser.readMap(stream, readItemMethod, options)]; - case 1: return [2 /*return*/, _a.sent()]; - } - }); - }); - }; - return AvroMapType; -}(AvroType)); -var AvroRecordType = /** @class */ (function (_super) { - tslib.__extends(AvroRecordType, _super); - function AvroRecordType(fields, name) { - var _this = _super.call(this) || this; - _this._fields = fields; - _this._name = name; - return _this; +} +class AvroUnionType extends AvroType { + constructor(types) { + super(); + this._types = types; } - AvroRecordType.prototype.read = function (stream, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var record, _a, _b, _i, key, _c, _d; - return tslib.__generator(this, function (_e) { - switch (_e.label) { - case 0: - record = {}; - record["$schema"] = this._name; - _a = []; - for (_b in this._fields) - _a.push(_b); - _i = 0; - _e.label = 1; - case 1: - if (!(_i < _a.length)) return [3 /*break*/, 4]; - key = _a[_i]; - if (!this._fields.hasOwnProperty(key)) return [3 /*break*/, 3]; - _c = record; - _d = key; - return [4 /*yield*/, this._fields[key].read(stream, options)]; - case 2: - _c[_d] = _e.sent(); - _e.label = 3; - case 3: - _i++; - return [3 /*break*/, 1]; - case 4: return [2 /*return*/, record]; - } - }); - }); - }; - return AvroRecordType; -}(AvroType)); + async read(stream, options = {}) { + const typeIndex = await AvroParser.readInt(stream, options); + return await this._types[typeIndex].read(stream, options); + } +} +class AvroMapType extends AvroType { + constructor(itemType) { + super(); + this._itemType = itemType; + } + async read(stream, options = {}) { + const readItemMethod = async (s, options) => { + return await this._itemType.read(s, options); + }; + return await AvroParser.readMap(stream, readItemMethod, options); + } +} +class AvroRecordType extends AvroType { + constructor(fields, name) { + super(); + this._fields = fields; + this._name = name; + } + async read(stream, options = {}) { + const record = {}; + record["$schema"] = this._name; + for (const key in this._fields) { + if (this._fields.hasOwnProperty(key)) { + record[key] = await this._fields[key].read(stream, options); + } + } + return record; + } +} // Copyright (c) Microsoft Corporation. -var AvroReader = /** @class */ (function () { - function AvroReader(dataStream, headerStream, currentBlockOffset, indexWithinCurrentBlock) { +class AvroReader { + constructor(dataStream, headerStream, currentBlockOffset, indexWithinCurrentBlock) { this._dataStream = dataStream; this._headerStream = headerStream || dataStream; this._initialized = false; @@ -33309,261 +30675,178 @@ var AvroReader = /** @class */ (function () { this._objectIndex = indexWithinCurrentBlock || 0; this._initialBlockOffset = currentBlockOffset || 0; } - Object.defineProperty(AvroReader.prototype, "blockOffset", { - get: function () { - return this._blockOffset; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AvroReader.prototype, "objectIndex", { - get: function () { - return this._objectIndex; - }, - enumerable: false, - configurable: true - }); - AvroReader.prototype.initialize = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var header, _a, codec, _b, schema, _c, i; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: return [4 /*yield*/, AvroParser.readFixedBytes(this._headerStream, AVRO_INIT_BYTES.length, { - abortSignal: options.abortSignal - })]; - case 1: - header = _d.sent(); - if (!arraysEqual(header, AVRO_INIT_BYTES)) { - throw new Error("Stream is not an Avro file."); - } - // File metadata is written as if defined by the following map schema: - // { "type": "map", "values": "bytes"} - _a = this; - return [4 /*yield*/, AvroParser.readMap(this._headerStream, AvroParser.readString, { - abortSignal: options.abortSignal - })]; - case 2: - // File metadata is written as if defined by the following map schema: - // { "type": "map", "values": "bytes"} - _a._metadata = _d.sent(); - codec = this._metadata[AVRO_CODEC_KEY]; - if (!(codec == undefined || codec == "null")) { - throw new Error("Codecs are not supported"); - } - // The 16-byte, randomly-generated sync marker for this file. - _b = this; - return [4 /*yield*/, AvroParser.readFixedBytes(this._headerStream, AVRO_SYNC_MARKER_SIZE, { - abortSignal: options.abortSignal - })]; - case 3: - // The 16-byte, randomly-generated sync marker for this file. - _b._syncMarker = _d.sent(); - schema = JSON.parse(this._metadata[AVRO_SCHEMA_KEY]); - this._itemType = AvroType.fromSchema(schema); - if (this._blockOffset == 0) { - this._blockOffset = this._initialBlockOffset + this._dataStream.position; - } - _c = this; - return [4 /*yield*/, AvroParser.readLong(this._dataStream, { - abortSignal: options.abortSignal - })]; - case 4: - _c._itemsRemainingInBlock = _d.sent(); - // skip block length - return [4 /*yield*/, AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal })]; - case 5: - // skip block length - _d.sent(); - this._initialized = true; - if (!(this._objectIndex && this._objectIndex > 0)) return [3 /*break*/, 9]; - i = 0; - _d.label = 6; - case 6: - if (!(i < this._objectIndex)) return [3 /*break*/, 9]; - return [4 /*yield*/, this._itemType.read(this._dataStream, { abortSignal: options.abortSignal })]; - case 7: - _d.sent(); - this._itemsRemainingInBlock--; - _d.label = 8; - case 8: - i++; - return [3 /*break*/, 6]; - case 9: return [2 /*return*/]; - } - }); + get blockOffset() { + return this._blockOffset; + } + get objectIndex() { + return this._objectIndex; + } + async initialize(options = {}) { + const header = await AvroParser.readFixedBytes(this._headerStream, AVRO_INIT_BYTES.length, { + abortSignal: options.abortSignal }); - }; - AvroReader.prototype.hasNext = function () { + if (!arraysEqual(header, AVRO_INIT_BYTES)) { + throw new Error("Stream is not an Avro file."); + } + // File metadata is written as if defined by the following map schema: + // { "type": "map", "values": "bytes"} + this._metadata = await AvroParser.readMap(this._headerStream, AvroParser.readString, { + abortSignal: options.abortSignal + }); + // Validate codec + const codec = this._metadata[AVRO_CODEC_KEY]; + if (!(codec == undefined || codec == "null")) { + throw new Error("Codecs are not supported"); + } + // The 16-byte, randomly-generated sync marker for this file. + this._syncMarker = await AvroParser.readFixedBytes(this._headerStream, AVRO_SYNC_MARKER_SIZE, { + abortSignal: options.abortSignal + }); + // Parse the schema + const schema = JSON.parse(this._metadata[AVRO_SCHEMA_KEY]); + this._itemType = AvroType.fromSchema(schema); + if (this._blockOffset == 0) { + this._blockOffset = this._initialBlockOffset + this._dataStream.position; + } + this._itemsRemainingInBlock = await AvroParser.readLong(this._dataStream, { + abortSignal: options.abortSignal + }); + // skip block length + await AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal }); + this._initialized = true; + if (this._objectIndex && this._objectIndex > 0) { + for (let i = 0; i < this._objectIndex; i++) { + await this._itemType.read(this._dataStream, { abortSignal: options.abortSignal }); + this._itemsRemainingInBlock--; + } + } + } + hasNext() { return !this._initialized || this._itemsRemainingInBlock > 0; - }; - AvroReader.prototype.parseObjects = function (options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function parseObjects_1() { - var result, marker, _a, err_1; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!!this._initialized) return [3 /*break*/, 2]; - return [4 /*yield*/, tslib.__await(this.initialize(options))]; - case 1: - _b.sent(); - _b.label = 2; - case 2: - if (!this.hasNext()) return [3 /*break*/, 13]; - return [4 /*yield*/, tslib.__await(this._itemType.read(this._dataStream, { - abortSignal: options.abortSignal - }))]; - case 3: - result = _b.sent(); - this._itemsRemainingInBlock--; - this._objectIndex++; - if (!(this._itemsRemainingInBlock == 0)) return [3 /*break*/, 10]; - return [4 /*yield*/, tslib.__await(AvroParser.readFixedBytes(this._dataStream, AVRO_SYNC_MARKER_SIZE, { - abortSignal: options.abortSignal - }))]; - case 4: - marker = _b.sent(); - this._blockOffset = this._initialBlockOffset + this._dataStream.position; - this._objectIndex = 0; - if (!arraysEqual(this._syncMarker, marker)) { - throw new Error("Stream is not a valid Avro file."); - } - _b.label = 5; - case 5: - _b.trys.push([5, 7, , 8]); - _a = this; - return [4 /*yield*/, tslib.__await(AvroParser.readLong(this._dataStream, { - abortSignal: options.abortSignal - }))]; - case 6: - _a._itemsRemainingInBlock = _b.sent(); - return [3 /*break*/, 8]; - case 7: - err_1 = _b.sent(); + } + parseObjects(options = {}) { + return tslib.__asyncGenerator(this, arguments, function* parseObjects_1() { + if (!this._initialized) { + yield tslib.__await(this.initialize(options)); + } + while (this.hasNext()) { + const result = yield tslib.__await(this._itemType.read(this._dataStream, { + abortSignal: options.abortSignal + })); + this._itemsRemainingInBlock--; + this._objectIndex++; + if (this._itemsRemainingInBlock == 0) { + const marker = yield tslib.__await(AvroParser.readFixedBytes(this._dataStream, AVRO_SYNC_MARKER_SIZE, { + abortSignal: options.abortSignal + })); + this._blockOffset = this._initialBlockOffset + this._dataStream.position; + this._objectIndex = 0; + if (!arraysEqual(this._syncMarker, marker)) { + throw new Error("Stream is not a valid Avro file."); + } + try { + this._itemsRemainingInBlock = yield tslib.__await(AvroParser.readLong(this._dataStream, { + abortSignal: options.abortSignal + })); + } + catch (err) { // We hit the end of the stream. this._itemsRemainingInBlock = 0; - return [3 /*break*/, 8]; - case 8: - if (!(this._itemsRemainingInBlock > 0)) return [3 /*break*/, 10]; + } + if (this._itemsRemainingInBlock > 0) { // Ignore block size - return [4 /*yield*/, tslib.__await(AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal }))]; - case 9: - // Ignore block size - _b.sent(); - _b.label = 10; - case 10: return [4 /*yield*/, tslib.__await(result)]; - case 11: return [4 /*yield*/, _b.sent()]; - case 12: - _b.sent(); - return [3 /*break*/, 2]; - case 13: return [2 /*return*/]; + yield tslib.__await(AvroParser.readLong(this._dataStream, { abortSignal: options.abortSignal })); + } } - }); + yield yield tslib.__await(result); + } }); - }; - return AvroReader; -}()); + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -var AvroReadable = /** @class */ (function () { - function AvroReadable() { - } - return AvroReadable; -}()); +class AvroReadable { +} // Copyright (c) Microsoft Corporation. -var ABORT_ERROR = new abortController.AbortError("Reading from the avro stream was aborted."); -var AvroReadableFromStream = /** @class */ (function (_super) { - tslib.__extends(AvroReadableFromStream, _super); - function AvroReadableFromStream(readable) { - var _this = _super.call(this) || this; - _this._readable = readable; - _this._position = 0; - return _this; +const ABORT_ERROR = new abortController.AbortError("Reading from the avro stream was aborted."); +class AvroReadableFromStream extends AvroReadable { + constructor(readable) { + super(); + this._readable = readable; + this._position = 0; } - AvroReadableFromStream.prototype.toUint8Array = function (data) { + toUint8Array(data) { if (typeof data === "string") { return Buffer.from(data); } return data; - }; - Object.defineProperty(AvroReadableFromStream.prototype, "position", { - get: function () { - return this._position; - }, - enumerable: false, - configurable: true - }); - AvroReadableFromStream.prototype.read = function (size, options) { + } + get position() { + return this._position; + } + async read(size, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var chunk; - var _this = this; - return tslib.__generator(this, function (_b) { - if ((_a = options.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { - throw ABORT_ERROR; - } - if (size < 0) { - throw new Error("size parameter should be positive: " + size); - } - if (size === 0) { - return [2 /*return*/, new Uint8Array()]; - } - if (!this._readable.readable) { - throw new Error("Stream no longer readable."); - } - chunk = this._readable.read(size); - if (chunk) { - this._position += chunk.length; - // chunk.length maybe less than desired size if the stream ends. - return [2 /*return*/, this.toUint8Array(chunk)]; - } - else { - // register callback to wait for enough data to read - return [2 /*return*/, new Promise(function (resolve, reject) { - var cleanUp = function () { - _this._readable.removeListener("readable", readableCallback); - _this._readable.removeListener("error", rejectCallback); - _this._readable.removeListener("end", rejectCallback); - _this._readable.removeListener("close", rejectCallback); - if (options.abortSignal) { - options.abortSignal.removeEventListener("abort", abortHandler); - } - }; - var readableCallback = function () { - var chunk = _this._readable.read(size); - if (chunk) { - _this._position += chunk.length; - cleanUp(); - // chunk.length maybe less than desired size if the stream ends. - resolve(_this.toUint8Array(chunk)); - } - }; - var rejectCallback = function () { - cleanUp(); - reject(); - }; - var abortHandler = function () { - cleanUp(); - reject(ABORT_ERROR); - }; - _this._readable.on("readable", readableCallback); - _this._readable.once("error", rejectCallback); - _this._readable.once("end", rejectCallback); - _this._readable.once("close", rejectCallback); - if (options.abortSignal) { - options.abortSignal.addEventListener("abort", abortHandler); - } - })]; + if ((_a = options.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { + throw ABORT_ERROR; + } + if (size < 0) { + throw new Error(`size parameter should be positive: ${size}`); + } + if (size === 0) { + return new Uint8Array(); + } + if (!this._readable.readable) { + throw new Error("Stream no longer readable."); + } + // See if there is already enough data. + const chunk = this._readable.read(size); + if (chunk) { + this._position += chunk.length; + // chunk.length maybe less than desired size if the stream ends. + return this.toUint8Array(chunk); + } + else { + // register callback to wait for enough data to read + return new Promise((resolve, reject) => { + const cleanUp = () => { + this._readable.removeListener("readable", readableCallback); + this._readable.removeListener("error", rejectCallback); + this._readable.removeListener("end", rejectCallback); + this._readable.removeListener("close", rejectCallback); + if (options.abortSignal) { + options.abortSignal.removeEventListener("abort", abortHandler); + } + }; + const readableCallback = () => { + const chunk = this._readable.read(size); + if (chunk) { + this._position += chunk.length; + cleanUp(); + // chunk.length maybe less than desired size if the stream ends. + resolve(this.toUint8Array(chunk)); + } + }; + const rejectCallback = () => { + cleanUp(); + reject(); + }; + const abortHandler = () => { + cleanUp(); + reject(ABORT_ERROR); + }; + this._readable.on("readable", readableCallback); + this._readable.once("error", rejectCallback); + this._readable.once("end", rejectCallback); + this._readable.once("close", rejectCallback); + if (options.abortSignal) { + options.abortSignal.addEventListener("abort", abortHandler); } }); - }); - }; - return AvroReadableFromStream; -}(AvroReadable)); + } + } +} // Copyright (c) Microsoft Corporation. /** @@ -33571,121 +30854,107 @@ var AvroReadableFromStream = /** @class */ (function (_super) { * * A Node.js BlobQuickQueryStream will internally parse avro data stream for blob query. */ -var BlobQuickQueryStream = /** @class */ (function (_super) { - tslib.__extends(BlobQuickQueryStream, _super); +class BlobQuickQueryStream extends stream.Readable { /** * Creates an instance of BlobQuickQueryStream. * * @param source - The current ReadableStream returned from getter * @param options - */ - 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; - _this.avroReader = new AvroReader(new AvroReadableFromStream(_this.source)); - _this.avroIter = _this.avroReader.parseObjects({ abortSignal: options.abortSignal }); - return _this; + constructor(source, options = {}) { + super(); + this.avroPaused = true; + this.source = source; + this.onProgress = options.onProgress; + this.onError = options.onError; + this.avroReader = new AvroReader(new AvroReadableFromStream(this.source)); + this.avroIter = this.avroReader.parseObjects({ abortSignal: options.abortSignal }); } - BlobQuickQueryStream.prototype._read = function () { - var _this = this; + _read() { if (this.avroPaused) { - this.readInternal().catch(function (err) { - _this.emit("error", err); + this.readInternal().catch((err) => { + this.emit("error", err); }); } - }; - BlobQuickQueryStream.prototype.readInternal = function () { - 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) { - case 0: - this.avroPaused = false; - _a.label = 1; - case 1: return [4 /*yield*/, this.avroIter.next()]; - case 2: - avroNext = _a.sent(); - if (avroNext.done) { - return [3 /*break*/, 4]; + } + async readInternal() { + this.avroPaused = false; + let avroNext; + do { + avroNext = await this.avroIter.next(); + if (avroNext.done) { + break; + } + const obj = avroNext.value; + const schema = obj.$schema; + if (typeof schema !== "string") { + throw Error("Missing schema in avro record."); + } + switch (schema) { + case "com.microsoft.azure.storage.queryBlobContents.resultData": + { + const data = obj.data; + if (data instanceof Uint8Array === false) { + throw Error("Invalid data in avro result record."); } - obj = avroNext.value; - schema = obj.$schema; - if (typeof schema !== "string") { - throw Error("Missing schema in avro record."); + if (!this.push(Buffer.from(data))) { + this.avroPaused = true; } - switch (schema) { - case "com.microsoft.azure.storage.queryBlobContents.resultData": - data = obj.data; - if (data instanceof Uint8Array === false) { - throw Error("Invalid data in avro result record."); - } - if (!this.push(Buffer.from(data))) { - this.avroPaused = true; - } - break; - case "com.microsoft.azure.storage.queryBlobContents.progress": - bytesScanned = obj.bytesScanned; - if (typeof bytesScanned !== "number") { - throw Error("Invalid bytesScanned in avro progress record."); - } - if (this.onProgress) { - this.onProgress({ loadedBytes: bytesScanned }); - } - break; - case "com.microsoft.azure.storage.queryBlobContents.end": - if (this.onProgress) { - totalBytes = obj.totalBytes; - if (typeof totalBytes !== "number") { - throw Error("Invalid totalBytes in avro end record."); - } - this.onProgress({ loadedBytes: totalBytes }); - } - this.push(null); - break; - case "com.microsoft.azure.storage.queryBlobContents.error": - if (this.onError) { - fatal = obj.fatal; - if (typeof fatal !== "boolean") { - throw Error("Invalid fatal in avro error record."); - } - name_1 = obj.name; - if (typeof name_1 !== "string") { - throw Error("Invalid name in avro error record."); - } - description = obj.description; - if (typeof description !== "string") { - throw Error("Invalid description in avro error record."); - } - position = obj.position; - if (typeof position !== "number") { - throw Error("Invalid position in avro error record."); - } - this.onError({ - position: position, - name: name_1, - isFatal: fatal, - description: description - }); - } - break; - default: - throw Error("Unknown schema " + schema + " in avro progress record."); + } + break; + case "com.microsoft.azure.storage.queryBlobContents.progress": + { + const bytesScanned = obj.bytesScanned; + if (typeof bytesScanned !== "number") { + throw Error("Invalid bytesScanned 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*/]; - } - }); - }); - }; - return BlobQuickQueryStream; -}(stream.Readable)); + if (this.onProgress) { + this.onProgress({ loadedBytes: bytesScanned }); + } + } + break; + case "com.microsoft.azure.storage.queryBlobContents.end": + if (this.onProgress) { + const totalBytes = obj.totalBytes; + if (typeof totalBytes !== "number") { + throw Error("Invalid totalBytes in avro end record."); + } + this.onProgress({ loadedBytes: totalBytes }); + } + this.push(null); + break; + case "com.microsoft.azure.storage.queryBlobContents.error": + if (this.onError) { + const fatal = obj.fatal; + if (typeof fatal !== "boolean") { + throw Error("Invalid fatal in avro error record."); + } + const name = obj.name; + if (typeof name !== "string") { + throw Error("Invalid name in avro error record."); + } + const description = obj.description; + if (typeof description !== "string") { + throw Error("Invalid description in avro error record."); + } + const position = obj.position; + if (typeof position !== "number") { + throw Error("Invalid position in avro error record."); + } + this.onError({ + position, + name, + isFatal: fatal, + description + }); + } + break; + default: + throw Error(`Unknown schema ${schema} in avro progress record.`); + } + } while (!avroNext.done && !this.avroPaused); + } +} // Copyright (c) Microsoft Corporation. /** @@ -33694,508 +30963,362 @@ var BlobQuickQueryStream = /** @class */ (function (_super) { * BlobQueryResponse implements BlobDownloadResponseModel interface, and in Node.js runtime it will * parse avor data returned by blob query. */ -var BlobQueryResponse = /** @class */ (function () { +class BlobQueryResponse { /** * Creates an instance of BlobQueryResponse. * * @param originalResponse - * @param options - */ - function BlobQueryResponse(originalResponse, options) { - if (options === void 0) { options = {}; } + constructor(originalResponse, options = {}) { this.originalResponse = originalResponse; this.blobDownloadStream = new BlobQuickQueryStream(this.originalResponse.readableStreamBody, options); } - Object.defineProperty(BlobQueryResponse.prototype, "acceptRanges", { - /** - * Indicates that the service supports - * requests for partial file content. - * - * @readonly - */ - get: function () { - return this.originalResponse.acceptRanges; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "cacheControl", { - /** - * Returns if it was previously specified - * for the file. - * - * @readonly - */ - get: function () { - return this.originalResponse.cacheControl; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "contentDisposition", { - /** - * Returns the value that was specified - * for the 'x-ms-content-disposition' header and specifies how to process the - * response. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentDisposition; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "contentEncoding", { - /** - * Returns the value that was specified - * for the Content-Encoding request header. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentEncoding; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "contentLanguage", { - /** - * Returns the value that was specified - * for the Content-Language request header. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentLanguage; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "blobSequenceNumber", { - /** - * The current sequence number for a - * page blob. This header is not returned for block blobs or append blobs. - * - * @readonly - */ - get: function () { - return this.originalResponse.blobSequenceNumber; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "blobType", { - /** - * The blob's type. Possible values include: - * 'BlockBlob', 'PageBlob', 'AppendBlob'. - * - * @readonly - */ - get: function () { - return this.originalResponse.blobType; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "contentLength", { - /** - * The number of bytes present in the - * response body. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentLength; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "contentMD5", { - /** - * If the file has an MD5 hash and the - * request is to read the full file, this response header is returned so that - * the client can check for message content integrity. If the request is to - * read a specified range and the 'x-ms-range-get-content-md5' is set to - * true, then the request returns an MD5 hash for the range, as long as the - * range size is less than or equal to 4 MB. If neither of these sets of - * conditions is true, then no value is returned for the 'Content-MD5' - * header. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentMD5; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "contentRange", { - /** - * Indicates the range of bytes returned if - * the client requested a subset of the file by setting the Range request - * header. - * - * @readonly - */ - get: function () { - return this.originalResponse.contentRange; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "contentType", { - /** - * The content type specified for the file. - * The default content type is 'application/octet-stream' - * - * @readonly - */ - get: function () { - return this.originalResponse.contentType; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "copyCompletedOn", { - /** - * Conclusion time of the last attempted - * Copy File operation where this file was the destination file. This value - * can specify the time of a completed, aborted, or failed copy attempt. - * - * @readonly - */ - get: function () { - return undefined; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "copyId", { - /** - * String identifier for the last attempted Copy - * File operation where this file was the destination file. - * - * @readonly - */ - get: function () { - return this.originalResponse.copyId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "copyProgress", { - /** - * Contains the number of bytes copied and - * the total bytes in the source in the last attempted Copy File operation - * where this file was the destination file. Can show between 0 and - * Content-Length bytes copied. - * - * @readonly - */ - get: function () { - return this.originalResponse.copyProgress; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "copySource", { - /** - * URL up to 2KB in length that specifies the - * source file used in the last attempted Copy File operation where this file - * was the destination file. - * - * @readonly - */ - get: function () { - return this.originalResponse.copySource; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "copyStatus", { - /** - * State of the copy operation - * identified by 'x-ms-copy-id'. Possible values include: 'pending', - * 'success', 'aborted', 'failed' - * - * @readonly - */ - get: function () { - return this.originalResponse.copyStatus; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "copyStatusDescription", { - /** - * Only appears when - * x-ms-copy-status is failed or pending. Describes cause of fatal or - * non-fatal copy operation failure. - * - * @readonly - */ - get: function () { - return this.originalResponse.copyStatusDescription; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "leaseDuration", { - /** - * When a blob is leased, - * specifies whether the lease is of infinite or fixed duration. Possible - * values include: 'infinite', 'fixed'. - * - * @readonly - */ - get: function () { - return this.originalResponse.leaseDuration; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "leaseState", { - /** - * Lease state of the blob. Possible - * values include: 'available', 'leased', 'expired', 'breaking', 'broken'. - * - * @readonly - */ - get: function () { - return this.originalResponse.leaseState; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "leaseStatus", { - /** - * The current lease status of the - * blob. Possible values include: 'locked', 'unlocked'. - * - * @readonly - */ - get: function () { - return this.originalResponse.leaseStatus; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "date", { - /** - * A UTC date/time value generated by the service that - * indicates the time at which the response was initiated. - * - * @readonly - */ - get: function () { - return this.originalResponse.date; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "blobCommittedBlockCount", { - /** - * The number of committed blocks - * present in the blob. This header is returned only for append blobs. - * - * @readonly - */ - get: function () { - return this.originalResponse.blobCommittedBlockCount; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "etag", { - /** - * The ETag contains a value that you can use to - * perform operations conditionally, in quotes. - * - * @readonly - */ - get: function () { - return this.originalResponse.etag; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "errorCode", { - /** - * The error code. - * - * @readonly - */ - get: function () { - return this.originalResponse.errorCode; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "isServerEncrypted", { - /** - * The value of this header is set to - * true if the file data and application metadata are completely encrypted - * using the specified algorithm. Otherwise, the value is set to false (when - * the file is unencrypted, or if only parts of the file/application metadata - * are encrypted). - * - * @readonly - */ - get: function () { - return this.originalResponse.isServerEncrypted; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "blobContentMD5", { - /** - * If the blob has a MD5 hash, and if - * request contains range header (Range or x-ms-range), this response header - * is returned with the value of the whole blob's MD5 value. This value may - * or may not be equal to the value returned in Content-MD5 header, with the - * latter calculated from the requested range. - * - * @readonly - */ - get: function () { - return this.originalResponse.blobContentMD5; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "lastModified", { - /** - * Returns the date and time the file was last - * modified. Any operation that modifies the file or its properties updates - * the last modified time. - * - * @readonly - */ - get: function () { - return this.originalResponse.lastModified; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "metadata", { - /** - * A name-value pair - * to associate with a file storage object. - * - * @readonly - */ - get: function () { - return this.originalResponse.metadata; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "requestId", { - /** - * This header uniquely identifies the request - * that was made and can be used for troubleshooting the request. - * - * @readonly - */ - get: function () { - return this.originalResponse.requestId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "clientRequestId", { - /** - * If a client request id header is sent in the request, this header will be present in the - * response with the same value. - * - * @readonly - */ - get: function () { - return this.originalResponse.clientRequestId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "version", { - /** - * Indicates the version of the File service used - * to execute the request. - * - * @readonly - */ - get: function () { - return this.originalResponse.version; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "encryptionKeySha256", { - /** - * The SHA-256 hash of the encryption key used to encrypt the blob. This value is only returned - * when the blob was encrypted with a customer-provided key. - * - * @readonly - */ - get: function () { - return this.originalResponse.encryptionKeySha256; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "contentCrc64", { - /** - * If the request is to read a specified range and the x-ms-range-get-content-crc64 is set to - * true, then the request returns a crc64 for the range, as long as the range size is less than - * or equal to 4 MB. If both x-ms-range-get-content-crc64 & x-ms-range-get-content-md5 is - * specified in the same request, it will fail with 400(Bad Request) - */ - get: function () { - return this.originalResponse.contentCrc64; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "blobBody", { - /** - * The response body as a browser Blob. - * Always undefined in node.js. - * - * @readonly - */ - get: function () { - return undefined; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "readableStreamBody", { - /** - * The response body as a node.js Readable stream. - * Always undefined in the browser. - * - * It will parse avor data returned by blob query. - * - * @readonly - */ - get: function () { - return coreHttp.isNode ? this.blobDownloadStream : undefined; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlobQueryResponse.prototype, "_response", { - /** - * The HTTP response. - */ - get: function () { - return this.originalResponse._response; - }, - enumerable: false, - configurable: true - }); - return BlobQueryResponse; -}()); + /** + * Indicates that the service supports + * requests for partial file content. + * + * @readonly + */ + get acceptRanges() { + return this.originalResponse.acceptRanges; + } + /** + * Returns if it was previously specified + * for the file. + * + * @readonly + */ + get cacheControl() { + return this.originalResponse.cacheControl; + } + /** + * Returns the value that was specified + * for the 'x-ms-content-disposition' header and specifies how to process the + * response. + * + * @readonly + */ + get contentDisposition() { + return this.originalResponse.contentDisposition; + } + /** + * Returns the value that was specified + * for the Content-Encoding request header. + * + * @readonly + */ + get contentEncoding() { + return this.originalResponse.contentEncoding; + } + /** + * Returns the value that was specified + * for the Content-Language request header. + * + * @readonly + */ + get contentLanguage() { + return this.originalResponse.contentLanguage; + } + /** + * The current sequence number for a + * page blob. This header is not returned for block blobs or append blobs. + * + * @readonly + */ + get blobSequenceNumber() { + return this.originalResponse.blobSequenceNumber; + } + /** + * The blob's type. Possible values include: + * 'BlockBlob', 'PageBlob', 'AppendBlob'. + * + * @readonly + */ + get blobType() { + return this.originalResponse.blobType; + } + /** + * The number of bytes present in the + * response body. + * + * @readonly + */ + get contentLength() { + return this.originalResponse.contentLength; + } + /** + * If the file has an MD5 hash and the + * request is to read the full file, this response header is returned so that + * the client can check for message content integrity. If the request is to + * read a specified range and the 'x-ms-range-get-content-md5' is set to + * true, then the request returns an MD5 hash for the range, as long as the + * range size is less than or equal to 4 MB. If neither of these sets of + * conditions is true, then no value is returned for the 'Content-MD5' + * header. + * + * @readonly + */ + get contentMD5() { + return this.originalResponse.contentMD5; + } + /** + * Indicates the range of bytes returned if + * the client requested a subset of the file by setting the Range request + * header. + * + * @readonly + */ + get contentRange() { + return this.originalResponse.contentRange; + } + /** + * The content type specified for the file. + * The default content type is 'application/octet-stream' + * + * @readonly + */ + get contentType() { + return this.originalResponse.contentType; + } + /** + * Conclusion time of the last attempted + * Copy File operation where this file was the destination file. This value + * can specify the time of a completed, aborted, or failed copy attempt. + * + * @readonly + */ + get copyCompletedOn() { + return undefined; + } + /** + * String identifier for the last attempted Copy + * File operation where this file was the destination file. + * + * @readonly + */ + get copyId() { + return this.originalResponse.copyId; + } + /** + * Contains the number of bytes copied and + * the total bytes in the source in the last attempted Copy File operation + * where this file was the destination file. Can show between 0 and + * Content-Length bytes copied. + * + * @readonly + */ + get copyProgress() { + return this.originalResponse.copyProgress; + } + /** + * URL up to 2KB in length that specifies the + * source file used in the last attempted Copy File operation where this file + * was the destination file. + * + * @readonly + */ + get copySource() { + return this.originalResponse.copySource; + } + /** + * State of the copy operation + * identified by 'x-ms-copy-id'. Possible values include: 'pending', + * 'success', 'aborted', 'failed' + * + * @readonly + */ + get copyStatus() { + return this.originalResponse.copyStatus; + } + /** + * Only appears when + * x-ms-copy-status is failed or pending. Describes cause of fatal or + * non-fatal copy operation failure. + * + * @readonly + */ + get copyStatusDescription() { + return this.originalResponse.copyStatusDescription; + } + /** + * When a blob is leased, + * specifies whether the lease is of infinite or fixed duration. Possible + * values include: 'infinite', 'fixed'. + * + * @readonly + */ + get leaseDuration() { + return this.originalResponse.leaseDuration; + } + /** + * Lease state of the blob. Possible + * values include: 'available', 'leased', 'expired', 'breaking', 'broken'. + * + * @readonly + */ + get leaseState() { + return this.originalResponse.leaseState; + } + /** + * The current lease status of the + * blob. Possible values include: 'locked', 'unlocked'. + * + * @readonly + */ + get leaseStatus() { + return this.originalResponse.leaseStatus; + } + /** + * A UTC date/time value generated by the service that + * indicates the time at which the response was initiated. + * + * @readonly + */ + get date() { + return this.originalResponse.date; + } + /** + * The number of committed blocks + * present in the blob. This header is returned only for append blobs. + * + * @readonly + */ + get blobCommittedBlockCount() { + return this.originalResponse.blobCommittedBlockCount; + } + /** + * The ETag contains a value that you can use to + * perform operations conditionally, in quotes. + * + * @readonly + */ + get etag() { + return this.originalResponse.etag; + } + /** + * The error code. + * + * @readonly + */ + get errorCode() { + return this.originalResponse.errorCode; + } + /** + * The value of this header is set to + * true if the file data and application metadata are completely encrypted + * using the specified algorithm. Otherwise, the value is set to false (when + * the file is unencrypted, or if only parts of the file/application metadata + * are encrypted). + * + * @readonly + */ + get isServerEncrypted() { + return this.originalResponse.isServerEncrypted; + } + /** + * If the blob has a MD5 hash, and if + * request contains range header (Range or x-ms-range), this response header + * is returned with the value of the whole blob's MD5 value. This value may + * or may not be equal to the value returned in Content-MD5 header, with the + * latter calculated from the requested range. + * + * @readonly + */ + get blobContentMD5() { + return this.originalResponse.blobContentMD5; + } + /** + * Returns the date and time the file was last + * modified. Any operation that modifies the file or its properties updates + * the last modified time. + * + * @readonly + */ + get lastModified() { + return this.originalResponse.lastModified; + } + /** + * A name-value pair + * to associate with a file storage object. + * + * @readonly + */ + get metadata() { + return this.originalResponse.metadata; + } + /** + * This header uniquely identifies the request + * that was made and can be used for troubleshooting the request. + * + * @readonly + */ + get requestId() { + return this.originalResponse.requestId; + } + /** + * If a client request id header is sent in the request, this header will be present in the + * response with the same value. + * + * @readonly + */ + get clientRequestId() { + return this.originalResponse.clientRequestId; + } + /** + * Indicates the version of the File service used + * to execute the request. + * + * @readonly + */ + get version() { + return this.originalResponse.version; + } + /** + * The SHA-256 hash of the encryption key used to encrypt the blob. This value is only returned + * when the blob was encrypted with a customer-provided key. + * + * @readonly + */ + get encryptionKeySha256() { + return this.originalResponse.encryptionKeySha256; + } + /** + * If the request is to read a specified range and the x-ms-range-get-content-crc64 is set to + * true, then the request returns a crc64 for the range, as long as the range size is less than + * or equal to 4 MB. If both x-ms-range-get-content-crc64 & x-ms-range-get-content-md5 is + * specified in the same request, it will fail with 400(Bad Request) + */ + get contentCrc64() { + return this.originalResponse.contentCrc64; + } + /** + * The response body as a browser Blob. + * Always undefined in node.js. + * + * @readonly + */ + get blobBody() { + return undefined; + } + /** + * The response body as a node.js Readable stream. + * Always undefined in the browser. + * + * It will parse avor data returned by blob query. + * + * @readonly + */ + get readableStreamBody() { + return coreHttp.isNode ? this.blobDownloadStream : undefined; + } + /** + * The HTTP response. + */ + get _response() { + return this.originalResponse._response; + } +} // Copyright (c) Microsoft Corporation. (function (BlockBlobTier) { @@ -34260,7 +31383,7 @@ var BlobQueryResponse = /** @class */ (function () { PremiumPageBlobTier["P80"] = "P80"; })(exports.PremiumPageBlobTier || (exports.PremiumPageBlobTier = {})); function toAccessTier(tier) { - if (tier == undefined) { + if (tier === undefined) { return undefined; } return tier; // No more check if string is a valid AccessTier, and left this to underlay logic to decide(service). @@ -34275,6 +31398,7 @@ function ensureCpkIfSpecified(cpk, isHttps) { } // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** * Function that converts PageRange and ClearRange to a common Range object. * PageRange and ClearRange have start and end while Range offset and count @@ -34282,18 +31406,18 @@ function ensureCpkIfSpecified(cpk, isHttps) { * @param response - Model PageBlob Range response */ function rangeResponseFromModel(response) { - var pageRange = (response._response.parsedBody.pageRange || []).map(function (x) { return ({ + const pageRange = (response._response.parsedBody.pageRange || []).map((x) => ({ offset: x.start, count: x.end - x.start - }); }); - var clearRange = (response._response.parsedBody.clearRange || []).map(function (x) { return ({ + })); + const clearRange = (response._response.parsedBody.clearRange || []).map((x) => ({ offset: x.start, count: x.end - x.start - }); }); - return tslib.__assign(tslib.__assign({}, response), { pageRange: pageRange, - clearRange: clearRange, _response: tslib.__assign(tslib.__assign({}, response._response), { parsedBody: { - pageRange: pageRange, - clearRange: clearRange + })); + return Object.assign(Object.assign({}, response), { pageRange, + clearRange, _response: Object.assign(Object.assign({}, response._response), { parsedBody: { + pageRange, + clearRange } }) }); } @@ -34304,64 +31428,48 @@ function rangeResponseFromModel(response) { * * @hidden */ -var BlobBeginCopyFromUrlPoller = /** @class */ (function (_super) { - tslib.__extends(BlobBeginCopyFromUrlPoller, _super); - function BlobBeginCopyFromUrlPoller(options) { - var _this = this; - var blobClient = options.blobClient, copySource = options.copySource, _a = options.intervalInMs, intervalInMs = _a === void 0 ? 15000 : _a, onProgress = options.onProgress, resumeFrom = options.resumeFrom, startCopyFromURLOptions = options.startCopyFromURLOptions; - var state; +class BlobBeginCopyFromUrlPoller extends coreLro.Poller { + constructor(options) { + const { blobClient, copySource, intervalInMs = 15000, onProgress, resumeFrom, startCopyFromURLOptions } = options; + let state; if (resumeFrom) { state = JSON.parse(resumeFrom).state; } - var operation = makeBlobBeginCopyFromURLPollOperation(tslib.__assign(tslib.__assign({}, state), { blobClient: blobClient, - copySource: copySource, - startCopyFromURLOptions: startCopyFromURLOptions })); - _this = _super.call(this, operation) || this; + const operation = makeBlobBeginCopyFromURLPollOperation(Object.assign(Object.assign({}, state), { blobClient, + copySource, + startCopyFromURLOptions })); + super(operation); if (typeof onProgress === "function") { - _this.onProgress(onProgress); + this.onProgress(onProgress); } - _this.intervalInMs = intervalInMs; - return _this; + this.intervalInMs = intervalInMs; } - BlobBeginCopyFromUrlPoller.prototype.delay = function () { + delay() { return coreHttp.delay(this.intervalInMs); - }; - return BlobBeginCopyFromUrlPoller; -}(coreLro.Poller)); + } +} /** * 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 */ -var cancel = function cancel(options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var state, copyId; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - state = this.state; - copyId = state.copyId; - if (state.isCompleted) { - return [2 /*return*/, makeBlobBeginCopyFromURLPollOperation(state)]; - } - if (!copyId) { - state.isCancelled = true; - return [2 /*return*/, makeBlobBeginCopyFromURLPollOperation(state)]; - } - // if abortCopyFromURL throws, it will bubble up to user's poller.cancelOperation call - return [4 /*yield*/, state.blobClient.abortCopyFromURL(copyId, { - abortSignal: options.abortSignal - })]; - case 1: - // if abortCopyFromURL throws, it will bubble up to user's poller.cancelOperation call - _a.sent(); - state.isCancelled = true; - return [2 /*return*/, makeBlobBeginCopyFromURLPollOperation(state)]; - } - }); +const cancel = async function cancel(options = {}) { + const state = this.state; + const { copyId } = state; + if (state.isCompleted) { + return makeBlobBeginCopyFromURLPollOperation(state); + } + if (!copyId) { + state.isCancelled = true; + return makeBlobBeginCopyFromURLPollOperation(state); + } + // if abortCopyFromURL throws, it will bubble up to user's poller.cancelOperation call + await state.blobClient.abortCopyFromURL(copyId, { + abortSignal: options.abortSignal }); + state.isCancelled = true; + return makeBlobBeginCopyFromURLPollOperation(state); }; /** * Note: Intentionally using function expression over arrow function expression @@ -34369,64 +31477,48 @@ var cancel = function cancel(options) { * This affects what `this` refers to. * @hidden */ -var update = function update(options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var state, blobClient, copySource, startCopyFromURLOptions, result, result, copyStatus, copyProgress, prevCopyProgress, err_1; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - state = this.state; - blobClient = state.blobClient, copySource = state.copySource, startCopyFromURLOptions = state.startCopyFromURLOptions; - if (!!state.isStarted) return [3 /*break*/, 2]; - state.isStarted = true; - return [4 /*yield*/, blobClient.startCopyFromURL(copySource, startCopyFromURLOptions)]; - case 1: - result = _a.sent(); - // copyId is needed to abort - state.copyId = result.copyId; - if (result.copyStatus === "success") { - state.result = result; - state.isCompleted = true; - } - return [3 /*break*/, 6]; - case 2: - if (!!state.isCompleted) return [3 /*break*/, 6]; - _a.label = 3; - case 3: - _a.trys.push([3, 5, , 6]); - return [4 /*yield*/, state.blobClient.getProperties({ abortSignal: options.abortSignal })]; - case 4: - result = _a.sent(); - copyStatus = result.copyStatus, copyProgress = result.copyProgress; - prevCopyProgress = state.copyProgress; - if (copyProgress) { - state.copyProgress = copyProgress; - } - if (copyStatus === "pending" && - copyProgress !== prevCopyProgress && - typeof options.fireProgress === "function") { - // trigger in setTimeout, or swallow error? - options.fireProgress(state); - } - else if (copyStatus === "success") { - state.result = result; - state.isCompleted = true; - } - else if (copyStatus === "failed") { - state.error = new Error("Blob copy failed with reason: \"" + (result.copyStatusDescription || "unknown") + "\""); - state.isCompleted = true; - } - return [3 /*break*/, 6]; - case 5: - err_1 = _a.sent(); - state.error = err_1; - state.isCompleted = true; - return [3 /*break*/, 6]; - case 6: return [2 /*return*/, makeBlobBeginCopyFromURLPollOperation(state)]; +const update = async function update(options = {}) { + const state = this.state; + const { blobClient, copySource, startCopyFromURLOptions } = state; + if (!state.isStarted) { + state.isStarted = true; + const result = await blobClient.startCopyFromURL(copySource, startCopyFromURLOptions); + // copyId is needed to abort + state.copyId = result.copyId; + if (result.copyStatus === "success") { + state.result = result; + state.isCompleted = true; + } + } + else if (!state.isCompleted) { + try { + const result = await state.blobClient.getProperties({ abortSignal: options.abortSignal }); + const { copyStatus, copyProgress } = result; + const prevCopyProgress = state.copyProgress; + if (copyProgress) { + state.copyProgress = copyProgress; } - }); - }); + if (copyStatus === "pending" && + copyProgress !== prevCopyProgress && + typeof options.fireProgress === "function") { + // trigger in setTimeout, or swallow error? + options.fireProgress(state); + } + else if (copyStatus === "success") { + state.result = result; + state.isCompleted = true; + } + else if (copyStatus === "failed") { + state.error = new Error(`Blob copy failed with reason: "${result.copyStatusDescription || "unknown"}"`); + state.isCompleted = true; + } + } + catch (err) { + state.error = err; + state.isCompleted = true; + } + } + return makeBlobBeginCopyFromURLPollOperation(state); }; /** * Note: Intentionally using function expression over arrow function expression @@ -34434,8 +31526,8 @@ var update = function update(options) { * This affects what `this` refers to. * @hidden */ -var toString = function toString() { - return JSON.stringify({ state: this.state }, function (key, value) { +const toString = function toString() { + return JSON.stringify({ state: this.state }, (key, value) => { // remove blobClient from serialized state since a client can't be hydrated from this info. if (key === "blobClient") { return undefined; @@ -34449,10 +31541,10 @@ var toString = function toString() { */ function makeBlobBeginCopyFromURLPollOperation(state) { return { - state: tslib.__assign({}, state), - cancel: cancel, - toString: toString, - update: update + state: Object.assign({}, state), + cancel, + toString, + update }; } @@ -34467,14 +31559,14 @@ function makeBlobBeginCopyFromURLPollOperation(state) { */ function rangeToString(iRange) { if (iRange.offset < 0) { - throw new RangeError("Range.offset cannot be smaller than 0."); + throw new RangeError(`Range.offset cannot be smaller than 0.`); } if (iRange.count && iRange.count <= 0) { - throw new RangeError("Range.count must be larger than 0. Leave it undefined if you want a range from offset to the end."); + throw new RangeError(`Range.count must be larger than 0. Leave it undefined if you want a range from offset to the end.`); } return iRange.count - ? "bytes=" + iRange.offset + "-" + (iRange.offset + iRange.count - 1) - : "bytes=" + iRange.offset + "-"; + ? `bytes=${iRange.offset}-${iRange.offset + iRange.count - 1}` + : `bytes=${iRange.offset}-`; } // Copyright (c) Microsoft Corporation. @@ -34491,13 +31583,12 @@ var BatchStates; * Will stop execute left operations when one of the executed operation throws an error. * But Batch cannot cancel ongoing operations, you need to cancel them by yourself. */ -var Batch = /** @class */ (function () { +class Batch { /** * Creates an instance of Batch. * @param concurrency - */ - function Batch(concurrency) { - if (concurrency === void 0) { concurrency = 5; } + constructor(concurrency = 5) { /** * Number of active operations under execution. */ @@ -34530,69 +31621,53 @@ var Batch = /** @class */ (function () { * * @param operation - */ - Batch.prototype.addOperation = function (operation) { - var _this = this; - this.operations.push(function () { return tslib.__awaiter(_this, void 0, void 0, function () { - var error_1; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - _a.trys.push([0, 2, , 3]); - this.actives++; - return [4 /*yield*/, operation()]; - case 1: - _a.sent(); - this.actives--; - this.completed++; - this.parallelExecute(); - return [3 /*break*/, 3]; - case 2: - error_1 = _a.sent(); - this.emitter.emit("error", error_1); - return [3 /*break*/, 3]; - case 3: return [2 /*return*/]; - } - }); - }); }); - }; + addOperation(operation) { + this.operations.push(async () => { + try { + this.actives++; + await operation(); + this.actives--; + this.completed++; + this.parallelExecute(); + } + catch (error) { + this.emitter.emit("error", error); + } + }); + } /** * Start execute operations in the queue. * */ - Batch.prototype.do = function () { - return tslib.__awaiter(this, void 0, void 0, function () { - var _this = this; - return tslib.__generator(this, function (_a) { - if (this.operations.length === 0) { - return [2 /*return*/, Promise.resolve()]; - } - this.parallelExecute(); - return [2 /*return*/, new Promise(function (resolve, reject) { - _this.emitter.on("finish", resolve); - _this.emitter.on("error", function (error) { - _this.state = BatchStates.Error; - reject(error); - }); - })]; + async do() { + if (this.operations.length === 0) { + return Promise.resolve(); + } + this.parallelExecute(); + return new Promise((resolve, reject) => { + this.emitter.on("finish", resolve); + this.emitter.on("error", (error) => { + this.state = BatchStates.Error; + reject(error); }); }); - }; + } /** * Get next operation to be executed. Return null when reaching ends. * */ - Batch.prototype.nextOperation = function () { + nextOperation() { if (this.offset < this.operations.length) { return this.operations[this.offset++]; } return null; - }; + } /** * Start execute operations. One one the most important difference between * this method with do() is that do() wraps as an sync method. * */ - Batch.prototype.parallelExecute = function () { + parallelExecute() { if (this.state === BatchStates.Error) { return; } @@ -34601,7 +31676,7 @@ var Batch = /** @class */ (function () { return; } while (this.actives < this.concurrency) { - var operation = this.nextOperation(); + const operation = this.nextOperation(); if (operation) { operation(); } @@ -34609,16 +31684,14 @@ var Batch = /** @class */ (function () { return; } } - }; - return Batch; -}()); + } +} // Copyright (c) Microsoft Corporation. /** * This class generates a readable stream from the data in an array of buffers. */ -var BuffersStream = /** @class */ (function (_super) { - tslib.__extends(BuffersStream, _super); +class BuffersStream extends stream.Readable { /** * Creates an instance of BuffersStream that will emit the data * contained in the array of buffers. @@ -34626,46 +31699,44 @@ var BuffersStream = /** @class */ (function (_super) { * @param buffers - Array of buffers containing the data * @param byteLength - The total length of data contained in the buffers */ - function BuffersStream(buffers, byteLength, options) { - var _this = _super.call(this, options) || this; - _this.buffers = buffers; - _this.byteLength = byteLength; - _this.byteOffsetInCurrentBuffer = 0; - _this.bufferIndex = 0; - _this.pushedBytesLength = 0; + constructor(buffers, byteLength, options) { + super(options); + this.buffers = buffers; + this.byteLength = byteLength; + this.byteOffsetInCurrentBuffer = 0; + this.bufferIndex = 0; + this.pushedBytesLength = 0; // check byteLength is no larger than buffers[] total length - var buffersLength = 0; - for (var _i = 0, _a = _this.buffers; _i < _a.length; _i++) { - var buf = _a[_i]; + let buffersLength = 0; + for (const buf of this.buffers) { buffersLength += buf.byteLength; } - if (buffersLength < _this.byteLength) { + if (buffersLength < this.byteLength) { throw new Error("Data size shouldn't be larger than the total length of buffers."); } - return _this; } /** * Internal _read() that will be called when the stream wants to pull more data in. * * @param size - Optional. The size of data to be read */ - BuffersStream.prototype._read = function (size) { + _read(size) { if (this.pushedBytesLength >= this.byteLength) { this.push(null); } if (!size) { size = this.readableHighWaterMark; } - var outBuffers = []; - var i = 0; + const outBuffers = []; + let i = 0; while (i < size && this.pushedBytesLength < this.byteLength) { // The last buffer may be longer than the data it contains. - var remainingDataInAllBuffers = this.byteLength - this.pushedBytesLength; - var remainingCapacityInThisBuffer = this.buffers[this.bufferIndex].byteLength - this.byteOffsetInCurrentBuffer; - var remaining = Math.min(remainingCapacityInThisBuffer, remainingDataInAllBuffers); + const remainingDataInAllBuffers = this.byteLength - this.pushedBytesLength; + const remainingCapacityInThisBuffer = this.buffers[this.bufferIndex].byteLength - this.byteOffsetInCurrentBuffer; + const remaining = Math.min(remainingCapacityInThisBuffer, remainingDataInAllBuffers); if (remaining > size - i) { // chunkSize = size - i - var end = this.byteOffsetInCurrentBuffer + size - i; + const end = this.byteOffsetInCurrentBuffer + size - i; outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end)); this.pushedBytesLength += size - i; this.byteOffsetInCurrentBuffer = end; @@ -34674,7 +31745,7 @@ var BuffersStream = /** @class */ (function (_super) { } else { // chunkSize = remaining - var end = this.byteOffsetInCurrentBuffer + remaining; + const end = this.byteOffsetInCurrentBuffer + remaining; outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end)); if (remaining === remainingCapacityInThisBuffer) { // this.buffers[this.bufferIndex] used up, shift to next one @@ -34694,16 +31765,15 @@ var BuffersStream = /** @class */ (function (_super) { else if (outBuffers.length === 1) { this.push(outBuffers[0]); } - }; - return BuffersStream; -}(stream.Readable)); + } +} // Copyright (c) Microsoft Corporation. /** * maxBufferLength is max size of each buffer in the pooled buffers. */ // Can't use import as Typescript doesn't recognize "buffer". -var maxBufferLength = __webpack_require__(407).constants.MAX_LENGTH; +const maxBufferLength = __webpack_require__(407).constants.MAX_LENGTH; /** * This class provides a buffer container which conceptually has no hard size limit. * It accepts a capacity, an array of input buffers and the total length of input data. @@ -34712,8 +31782,8 @@ var maxBufferLength = __webpack_require__(407).constants.MAX_LENGTH; * Then by calling PooledBuffer.getReadableStream(), you can get a readable stream * assembled from all the data in the internal "buffer". */ -var PooledBuffer = /** @class */ (function () { - function PooledBuffer(capacity, buffers, totalLength) { +class PooledBuffer { + constructor(capacity, buffers, totalLength) { /** * Internal buffers used to keep the data. * Each buffer has a length of the maxBufferLength except last one. @@ -34722,9 +31792,9 @@ var PooledBuffer = /** @class */ (function () { this.capacity = capacity; this._size = 0; // allocate - var bufferNum = Math.ceil(capacity / maxBufferLength); - for (var i = 0; i < bufferNum; i++) { - var len = i === bufferNum - 1 ? capacity % maxBufferLength : maxBufferLength; + const bufferNum = Math.ceil(capacity / maxBufferLength); + for (let i = 0; i < bufferNum; i++) { + let len = i === bufferNum - 1 ? capacity % maxBufferLength : maxBufferLength; if (len === 0) { len = maxBufferLength; } @@ -34734,16 +31804,12 @@ var PooledBuffer = /** @class */ (function () { this.fill(buffers, totalLength); } } - Object.defineProperty(PooledBuffer.prototype, "size", { - /** - * The size of the data contained in the pooled buffers. - */ - get: function () { - return this._size; - }, - enumerable: false, - configurable: true - }); + /** + * The size of the data contained in the pooled buffers. + */ + get size() { + return this._size; + } /** * Fill the internal buffers with data in the input buffers serially * with respect to the total length and the total capacity of the internal buffers. @@ -34753,13 +31819,13 @@ var PooledBuffer = /** @class */ (function () { * @param totalLength - Total length of the data to be filled in. * */ - PooledBuffer.prototype.fill = function (buffers, totalLength) { + fill(buffers, totalLength) { this._size = Math.min(this.capacity, totalLength); - var i = 0, j = 0, targetOffset = 0, sourceOffset = 0, totalCopiedNum = 0; + let i = 0, j = 0, targetOffset = 0, sourceOffset = 0, totalCopiedNum = 0; while (totalCopiedNum < this._size) { - var source = buffers[i]; - var target = this.buffers[j]; - var copiedNum = source.copy(target, targetOffset, sourceOffset); + const source = buffers[i]; + const target = this.buffers[j]; + const copiedNum = source.copy(target, targetOffset, sourceOffset); totalCopiedNum += copiedNum; sourceOffset += copiedNum; targetOffset += copiedNum; @@ -34777,16 +31843,15 @@ var PooledBuffer = /** @class */ (function () { if (buffers.length > 0) { buffers[0] = buffers[0].slice(sourceOffset); } - }; + } /** * Get the readable stream assembled from all the data in the internal buffers. * */ - PooledBuffer.prototype.getReadableStream = function () { + getReadableStream() { return new BuffersStream(this.buffers, this.size); - }; - return PooledBuffer; -}()); + } +} // Copyright (c) Microsoft Corporation. /** @@ -34811,7 +31876,7 @@ var PooledBuffer = /** @class */ (function () { * in this situation, outgoing handlers are blocked. * Outgoing queue shouldn't be empty. */ -var BufferScheduler = /** @class */ (function () { +class BufferScheduler { /** * Creates an instance of BufferScheduler. * @@ -34824,7 +31889,7 @@ var BufferScheduler = /** @class */ (function () { * @param concurrency - Concurrency of executing outgoingHandlers (>0) * @param encoding - [Optional] Encoding of Readable stream when it's a string stream */ - function BufferScheduler(readable, bufferSize, maxBuffers, outgoingHandler, concurrency, encoding) { + constructor(readable, bufferSize, maxBuffers, outgoingHandler, concurrency, encoding) { /** * An internal event emitter. */ @@ -34870,13 +31935,13 @@ var BufferScheduler = /** @class */ (function () { */ this.outgoing = []; if (bufferSize <= 0) { - throw new RangeError("bufferSize must be larger than 0, current is " + bufferSize); + throw new RangeError(`bufferSize must be larger than 0, current is ${bufferSize}`); } if (maxBuffers <= 0) { - throw new RangeError("maxBuffers must be larger than 0, current is " + maxBuffers); + throw new RangeError(`maxBuffers must be larger than 0, current is ${maxBuffers}`); } if (concurrency <= 0) { - throw new RangeError("concurrency must be larger than 0, current is " + concurrency); + throw new RangeError(`concurrency must be larger than 0, current is ${concurrency}`); } this.bufferSize = bufferSize; this.maxBuffers = maxBuffers; @@ -34890,69 +31955,64 @@ var BufferScheduler = /** @class */ (function () { * returns error. * */ - BufferScheduler.prototype.do = function () { - return tslib.__awaiter(this, void 0, void 0, function () { - var _this = this; - return tslib.__generator(this, function (_a) { - return [2 /*return*/, new Promise(function (resolve, reject) { - _this.readable.on("data", function (data) { - data = typeof data === "string" ? Buffer.from(data, _this.encoding) : data; - _this.appendUnresolvedData(data); - if (!_this.resolveData()) { - _this.readable.pause(); - } - }); - _this.readable.on("error", function (err) { - _this.emitter.emit("error", err); - }); - _this.readable.on("end", function () { - _this.isStreamEnd = true; - _this.emitter.emit("checkEnd"); - }); - _this.emitter.on("error", function (err) { - _this.isError = true; - _this.readable.pause(); - reject(err); - }); - _this.emitter.on("checkEnd", function () { - if (_this.outgoing.length > 0) { - _this.triggerOutgoingHandlers(); - return; - } - if (_this.isStreamEnd && _this.executingOutgoingHandlers === 0) { - if (_this.unresolvedLength > 0 && _this.unresolvedLength < _this.bufferSize) { - var buffer_1 = _this.shiftBufferFromUnresolvedDataArray(); - _this.outgoingHandler(function () { return buffer_1.getReadableStream(); }, buffer_1.size, _this.offset) - .then(resolve) - .catch(reject); - } - else if (_this.unresolvedLength >= _this.bufferSize) { - return; - } - else { - resolve(); - } - } - }); - })]; + async do() { + return new Promise((resolve, reject) => { + this.readable.on("data", (data) => { + data = typeof data === "string" ? Buffer.from(data, this.encoding) : data; + this.appendUnresolvedData(data); + if (!this.resolveData()) { + this.readable.pause(); + } + }); + this.readable.on("error", (err) => { + this.emitter.emit("error", err); + }); + this.readable.on("end", () => { + this.isStreamEnd = true; + this.emitter.emit("checkEnd"); + }); + this.emitter.on("error", (err) => { + this.isError = true; + this.readable.pause(); + reject(err); + }); + this.emitter.on("checkEnd", () => { + if (this.outgoing.length > 0) { + this.triggerOutgoingHandlers(); + return; + } + if (this.isStreamEnd && this.executingOutgoingHandlers === 0) { + if (this.unresolvedLength > 0 && this.unresolvedLength < this.bufferSize) { + const buffer = this.shiftBufferFromUnresolvedDataArray(); + this.outgoingHandler(() => buffer.getReadableStream(), buffer.size, this.offset) + .then(resolve) + .catch(reject); + } + else if (this.unresolvedLength >= this.bufferSize) { + return; + } + else { + resolve(); + } + } }); }); - }; + } /** * Insert a new data into unresolved array. * * @param data - */ - BufferScheduler.prototype.appendUnresolvedData = function (data) { + appendUnresolvedData(data) { this.unresolvedDataArray.push(data); this.unresolvedLength += data.length; - }; + } /** * Try to shift a buffer with size in blockSize. The buffer returned may be less * than blockSize when data in unresolvedDataArray is less than bufferSize. * */ - BufferScheduler.prototype.shiftBufferFromUnresolvedDataArray = function (buffer) { + shiftBufferFromUnresolvedDataArray(buffer) { if (!buffer) { buffer = new PooledBuffer(this.bufferSize, this.unresolvedDataArray, this.unresolvedLength); } @@ -34961,7 +32021,7 @@ var BufferScheduler = /** @class */ (function () { } this.unresolvedLength -= buffer.size; return buffer; - }; + } /** * Resolve data in unresolvedDataArray. For every buffer with size in blockSize * shifted, it will try to get (or allocate a buffer) from incoming, and fill it, @@ -34971,9 +32031,9 @@ var BufferScheduler = /** @class */ (function () { * * @returns Return false when buffers in incoming are not enough, else true. */ - BufferScheduler.prototype.resolveData = function () { + resolveData() { while (this.unresolvedLength >= this.bufferSize) { - var buffer = void 0; + let buffer; if (this.incoming.length > 0) { buffer = this.incoming.shift(); this.shiftBufferFromUnresolvedDataArray(buffer); @@ -34992,75 +32052,55 @@ var BufferScheduler = /** @class */ (function () { this.triggerOutgoingHandlers(); } return true; - }; + } /** * Try to trigger a outgoing handler for every buffer in outgoing. Stop when * concurrency reaches. */ - BufferScheduler.prototype.triggerOutgoingHandlers = function () { - return tslib.__awaiter(this, void 0, void 0, function () { - var buffer; - return tslib.__generator(this, function (_a) { - do { - if (this.executingOutgoingHandlers >= this.concurrency) { - return [2 /*return*/]; - } - buffer = this.outgoing.shift(); - if (buffer) { - this.triggerOutgoingHandler(buffer); - } - } while (buffer); - return [2 /*return*/]; - }); - }); - }; + async triggerOutgoingHandlers() { + let buffer; + do { + if (this.executingOutgoingHandlers >= this.concurrency) { + return; + } + buffer = this.outgoing.shift(); + if (buffer) { + this.triggerOutgoingHandler(buffer); + } + } while (buffer); + } /** * Trigger a outgoing handler for a buffer shifted from outgoing. * * @param buffer - */ - BufferScheduler.prototype.triggerOutgoingHandler = function (buffer) { - return tslib.__awaiter(this, void 0, void 0, function () { - var bufferLength, err_1; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - bufferLength = buffer.size; - this.executingOutgoingHandlers++; - this.offset += bufferLength; - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - return [4 /*yield*/, this.outgoingHandler(function () { return buffer.getReadableStream(); }, bufferLength, this.offset - bufferLength)]; - case 2: - _a.sent(); - return [3 /*break*/, 4]; - case 3: - err_1 = _a.sent(); - this.emitter.emit("error", err_1); - return [2 /*return*/]; - case 4: - this.executingOutgoingHandlers--; - this.reuseBuffer(buffer); - this.emitter.emit("checkEnd"); - return [2 /*return*/]; - } - }); - }); - }; + async triggerOutgoingHandler(buffer) { + const bufferLength = buffer.size; + this.executingOutgoingHandlers++; + this.offset += bufferLength; + try { + await this.outgoingHandler(() => buffer.getReadableStream(), bufferLength, this.offset - bufferLength); + } + catch (err) { + this.emitter.emit("error", err); + return; + } + this.executingOutgoingHandlers--; + this.reuseBuffer(buffer); + this.emitter.emit("checkEnd"); + } /** * Return buffer used by outgoing handler into incoming. * * @param buffer - */ - BufferScheduler.prototype.reuseBuffer = function (buffer) { + reuseBuffer(buffer) { this.incoming.push(buffer); if (!this.isError && this.resolveData() && !this.isStreamEnd) { this.readable.resume(); } - }; - return BufferScheduler; -}()); + } +} // Copyright (c) Microsoft Corporation. /** @@ -35072,39 +32112,34 @@ var BufferScheduler = /** @class */ (function () { * @param end - To which position in the buffer to be filled, exclusive * @param encoding - Encoding of the Readable stream */ -function streamToBuffer(stream, buffer, offset, end, encoding) { - return tslib.__awaiter(this, void 0, void 0, function () { - var pos, count; - return tslib.__generator(this, function (_a) { - pos = 0; - count = end - offset; - return [2 /*return*/, new Promise(function (resolve, reject) { - stream.on("readable", function () { - if (pos >= count) { - resolve(); - return; - } - var chunk = stream.read(); - if (!chunk) { - return; - } - if (typeof chunk === "string") { - chunk = Buffer.from(chunk, encoding); - } - // How much data needed in this chunk - var chunkLength = pos + chunk.length > count ? count - pos : chunk.length; - buffer.fill(chunk.slice(0, chunkLength), offset + pos, offset + pos + chunkLength); - pos += chunkLength; - }); - stream.on("end", function () { - if (pos < count) { - reject(new Error("Stream drains before getting enough data needed. Data read: " + pos + ", data need: " + count)); - } - resolve(); - }); - stream.on("error", reject); - })]; +async function streamToBuffer(stream, buffer, offset, end, encoding) { + let pos = 0; // Position in stream + const count = end - offset; // Total amount of data needed in stream + return new Promise((resolve, reject) => { + stream.on("readable", () => { + if (pos >= count) { + resolve(); + return; + } + let chunk = stream.read(); + if (!chunk) { + return; + } + if (typeof chunk === "string") { + chunk = Buffer.from(chunk, encoding); + } + // How much data needed in this chunk + const chunkLength = pos + chunk.length > count ? count - pos : chunk.length; + buffer.fill(chunk.slice(0, chunkLength), offset + pos, offset + pos + chunkLength); + pos += chunkLength; }); + stream.on("end", () => { + if (pos < count) { + reject(new Error(`Stream drains before getting enough data needed. Data read: ${pos}, data need: ${count}`)); + } + resolve(); + }); + stream.on("error", reject); }); } /** @@ -35116,34 +32151,29 @@ function streamToBuffer(stream, buffer, offset, end, encoding) { * @returns with the count of bytes read. * @throws `RangeError` If buffer size is not big enough. */ -function streamToBuffer2(stream, buffer, encoding) { - return tslib.__awaiter(this, void 0, void 0, function () { - var pos, bufferSize; - return tslib.__generator(this, function (_a) { - pos = 0; - bufferSize = buffer.length; - return [2 /*return*/, new Promise(function (resolve, reject) { - stream.on("readable", function () { - var chunk = stream.read(); - if (!chunk) { - return; - } - if (typeof chunk === "string") { - chunk = Buffer.from(chunk, encoding); - } - if (pos + chunk.length > bufferSize) { - reject(new Error("Stream exceeds buffer size. Buffer size: " + bufferSize)); - return; - } - buffer.fill(chunk, pos, pos + chunk.length); - pos += chunk.length; - }); - stream.on("end", function () { - resolve(pos); - }); - stream.on("error", reject); - })]; +async function streamToBuffer2(stream, buffer, encoding) { + let pos = 0; // Position in stream + const bufferSize = buffer.length; + return new Promise((resolve, reject) => { + stream.on("readable", () => { + let chunk = stream.read(); + if (!chunk) { + return; + } + if (typeof chunk === "string") { + chunk = Buffer.from(chunk, encoding); + } + if (pos + chunk.length > bufferSize) { + reject(new Error(`Stream exceeds buffer size. Buffer size: ${bufferSize}`)); + return; + } + buffer.fill(chunk, pos, pos + chunk.length); + pos += chunk.length; }); + stream.on("end", () => { + resolve(pos); + }); + stream.on("error", reject); }); } /** @@ -35154,21 +32184,17 @@ function streamToBuffer2(stream, buffer, encoding) { * @param rs - The read stream. * @param file - Destination file path. */ -function readStreamToLocalFile(rs, file) { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - return [2 /*return*/, new Promise(function (resolve, reject) { - var ws = fs.createWriteStream(file); - rs.on("error", function (err) { - reject(err); - }); - ws.on("error", function (err) { - reject(err); - }); - ws.on("close", resolve); - rs.pipe(ws); - })]; +async function readStreamToLocalFile(rs, file) { + return new Promise((resolve, reject) => { + const ws = fs.createWriteStream(file); + rs.on("error", (err) => { + reject(err); }); + ws.on("error", (err) => { + reject(err); + }); + ws.on("close", resolve); + rs.pipe(ws); }); } /** @@ -35176,22 +32202,22 @@ function readStreamToLocalFile(rs, file) { * * Promisified version of fs.stat(). */ -var fsStat = util.promisify(fs.stat); -var fsCreateReadStream = fs.createReadStream; +const fsStat = util.promisify(fs.stat); +const fsCreateReadStream = fs.createReadStream; /** * A BlobClient represents a URL to an Azure Storage blob; the blob may be a block blob, * append blob, or page blob. */ -var BlobClient = /** @class */ (function (_super) { - tslib.__extends(BlobClient, _super); - function BlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { - var _a; - var _this = this; +class BlobClient extends StorageClient { + constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { options = options || {}; - var pipeline; - var url; - if (credentialOrPipelineOrContainerName instanceof Pipeline) { + let pipeline; + let url; + if (isPipelineLike(credentialOrPipelineOrContainerName)) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; @@ -35216,12 +32242,12 @@ var BlobClient = /** @class */ (function (_super) { blobNameOrOptions && typeof blobNameOrOptions === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) - var containerName = credentialOrPipelineOrContainerName; - var blobName = blobNameOrOptions; - var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + const containerName = credentialOrPipelineOrContainerName; + const blobName = blobNameOrOptions; + const extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + const 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); @@ -35241,33 +32267,27 @@ var BlobClient = /** @class */ (function (_super) { 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; + super(url, pipeline); + ({ + blobName: this._name, + containerName: this._containerName + } = this.getBlobAndContainerNamesFromUrl()); + this.blobContext = new Blob$1(this.storageClientContext); + this._snapshot = getURLParameter(this.url, URLConstants.Parameters.SNAPSHOT); + this._versionId = getURLParameter(this.url, URLConstants.Parameters.VERSIONID); + } + /** + * The name of the blob. + */ + get name() { + return this._name; + } + /** + * The name of the storage container the blob is associated with. + */ + get containerName() { + return this._containerName; } - 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. @@ -35275,9 +32295,9 @@ var BlobClient = /** @class */ (function (_super) { * @param snapshot - The snapshot timestamp. * @returns A new BlobClient object identical to the source but with the specified snapshot timestamp */ - BlobClient.prototype.withSnapshot = function (snapshot) { + withSnapshot(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. @@ -35285,30 +32305,30 @@ var BlobClient = /** @class */ (function (_super) { * @param versionId - The versionId. * @returns A new BlobClient object pointing to the version of this blob. */ - BlobClient.prototype.withVersion = function (versionId) { + withVersion(versionId) { return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.VERSIONID, versionId.length === 0 ? undefined : versionId), this.pipeline); - }; + } /** * Creates a AppendBlobClient object. * */ - BlobClient.prototype.getAppendBlobClient = function () { + getAppendBlobClient() { return new AppendBlobClient(this.url, this.pipeline); - }; + } /** * Creates a BlockBlobClient object. * */ - BlobClient.prototype.getBlockBlobClient = function () { + getBlockBlobClient() { return new BlockBlobClient(this.url, this.pipeline); - }; + } /** * Creates a PageBlobClient object. * */ - BlobClient.prototype.getPageBlobClient = function () { + getPageBlobClient() { 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. @@ -35368,98 +32388,77 @@ var BlobClient = /** @class */ (function (_super) { * } * ``` */ - BlobClient.prototype.download = function (offset, count, options) { + async download(offset = 0, 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, updatedOptions, 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), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.download(tslib.__assign({ 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 }), requestOptions: { - onDownloadProgress: coreHttp.isNode ? undefined : options.onProgress // for Node.js, progress is reported by RetriableReadableStream - }, range: offset === 0 && !count ? undefined : rangeToString({ offset: offset, count: count }), rangeGetContentMD5: options.rangeGetContentMD5, rangeGetContentCRC64: options.rangeGetContentCrc64, snapshot: options.snapshot, cpkInfo: options.customerProvidedKey }, convertTracingToRequestOptionsBase(updatedOptions)))]; - 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: coreTracing.SpanStatusCode.ERROR, - message: e_1.message - }); - throw e_1; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + options.conditions = options.conditions || {}; + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + const { span, updatedOptions } = createSpan("BlobClient-download", options); + try { + const res = await this.blobContext.download(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: { + onDownloadProgress: coreHttp.isNode ? undefined : options.onProgress // for Node.js, progress is reported by RetriableReadableStream + }, range: offset === 0 && !count ? undefined : rangeToString({ offset, count }), rangeGetContentMD5: options.rangeGetContentMD5, rangeGetContentCRC64: options.rangeGetContentCrc64, snapshot: options.snapshot, cpkInfo: options.customerProvidedKey }, convertTracingToRequestOptionsBase(updatedOptions))); + const wrappedRes = Object.assign(Object.assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) }); + // Return browser response immediately + if (false) {} + // 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.contentLength === undefined) { + throw new RangeError(`File download response doesn't contain valid content length header`); + } + if (!res.etag) { + throw new RangeError(`File download response doesn't contain valid etag header`); + } + return new BlobDownloadResponse(wrappedRes, async (start) => { + var _a; + const updatedDownloadOptions = { + leaseAccessConditions: options.conditions, + modifiedAccessConditions: { + ifMatch: options.conditions.ifMatch || res.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.contentLength - start, + offset: start + }), + rangeGetContentMD5: options.rangeGetContentMD5, + rangeGetContentCRC64: options.rangeGetContentCrc64, + snapshot: options.snapshot, + cpkInfo: options.customerProvidedKey + }; + // Debug purpose only + // console.log( + // `Read from internal stream, range: ${ + // updatedOptions.range + // }, options: ${JSON.stringify(updatedOptions)}` + // ); + return (await this.blobContext.download(Object.assign({ abortSignal: options.abortSignal }, updatedDownloadOptions))).readableStreamBody; + }, offset, res.contentLength, { + maxRetryRequests: options.maxRetryRequests, + onProgress: options.onProgress }); - }); - }; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message + }); + throw e; + } + finally { + span.end(); + } + } /** * Returns true if the Azure blob resource represented by this client exists; false otherwise. * @@ -35469,49 +32468,36 @@ var BlobClient = /** @class */ (function (_super) { * * @param options - options to Exists operation. */ - BlobClient.prototype.exists = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_2; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobClient-exists", options), span = _a.span, updatedOptions = _a.updatedOptions; - _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: updatedOptions.tracingOptions - })]; - case 2: - _b.sent(); - return [2 /*return*/, true]; - case 3: - e_2 = _b.sent(); - if (e_2.statusCode === 404) { - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: "Expected exception when checking blob existence" - }); - return [2 /*return*/, false]; - } - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_2.message - }); - throw e_2; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async exists(options = {}) { + const { span, updatedOptions } = createSpan("BlobClient-exists", options); + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + await this.getProperties({ + abortSignal: options.abortSignal, + customerProvidedKey: options.customerProvidedKey, + conditions: options.conditions, + tracingOptions: updatedOptions.tracingOptions }); - }); - }; + return true; + } + catch (e) { + if (e.statusCode === 404) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: "Expected exception when checking blob existence" + }); + return false; + } + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message + }); + throw e; + } + finally { + span.end(); + } + } /** * Returns all user-defined metadata, standard HTTP properties, and system properties * for the blob. It does not return the content of the blob. @@ -35524,39 +32510,26 @@ var BlobClient = /** @class */ (function (_super) { * * @param options - Optional options to Get Properties operation. */ - BlobClient.prototype.getProperties = function (options) { + async getProperties(options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, res, e_3; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-getProperties", options), span = _b.span, updatedOptions = _b.updatedOptions; - _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(tslib.__assign({ 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 }, convertTracingToRequestOptionsBase(updatedOptions)))]; - 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: coreTracing.SpanStatusCode.ERROR, - message: e_3.message - }); - throw e_3; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobClient-getProperties", options); + try { + options.conditions = options.conditions || {}; + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + const res = await this.blobContext.getProperties(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey }, convertTracingToRequestOptionsBase(updatedOptions))); + return Object.assign(Object.assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) }); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * 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 @@ -35566,36 +32539,24 @@ var BlobClient = /** @class */ (function (_super) { * * @param options - Optional options to Blob Delete operation. */ - BlobClient.prototype.delete = function (options) { + async delete(options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_4; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-delete", options), span = _b.span, updatedOptions = _b.updatedOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.delete(tslib.__assign({ abortSignal: options.abortSignal, deleteSnapshots: options.deleteSnapshots, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_4 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_4.message - }); - throw e_4; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobClient-delete", options); + options.conditions = options.conditions || {}; + try { + return await this.blobContext.delete(Object.assign({ abortSignal: options.abortSignal, deleteSnapshots: options.deleteSnapshots, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Marks the specified blob or snapshot for deletion if it exists. The blob is later deleted * during garbage collection. Note that in order to delete a blob, you must delete @@ -35605,45 +32566,32 @@ var BlobClient = /** @class */ (function (_super) { * * @param options - Optional options to Blob Delete operation. */ - BlobClient.prototype.deleteIfExists = function (options) { + async deleteIfExists(options = {}) { var _a, _b; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _c, span, updatedOptions, res, e_5; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _c = createSpan("BlobClient-deleteIfExists", options), span = _c.span, updatedOptions = _c.updatedOptions; - _d.label = 1; - case 1: - _d.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.delete(updatedOptions)]; - case 2: - res = _d.sent(); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable - })]; - case 3: - e_5 = _d.sent(); - if (((_a = e_5.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobNotFound") { - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: "Expected exception when deleting a blob or snapshot only if it exists." - }); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_5.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_5.response })]; - } - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_5.message - }); - throw e_5; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobClient-deleteIfExists", options); + try { + const res = await this.delete(updatedOptions); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable + }); + } + catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobNotFound") { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: "Expected exception when deleting a blob or snapshot only if it exists." + }); + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Restores the contents and metadata of soft deleted blob and any associated * soft deleted snapshots. Undelete Blob is supported only on version 2017-07-29 @@ -35652,34 +32600,22 @@ var BlobClient = /** @class */ (function (_super) { * * @param options - Optional options to Blob Undelete operation. */ - BlobClient.prototype.undelete = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_6; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobClient-undelete", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.undelete(tslib.__assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_6 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_6.message - }); - throw e_6; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async undelete(options = {}) { + const { span, updatedOptions } = createSpan("BlobClient-undelete", options); + try { + return await this.blobContext.undelete(Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Sets system properties on the blob. * @@ -35690,39 +32626,30 @@ var BlobClient = /** @class */ (function (_super) { * @param blobHTTPHeaders - If no value provided, or no value provided for * the specified blob HTTP headers, these blob HTTP * headers without a value will be cleared. + * A common header to set is `blobContentType` + * enabling the browser to provide functionality + * based on file type. * @param options - Optional options to Blob Set HTTP Headers operation. */ - BlobClient.prototype.setHTTPHeaders = function (blobHTTPHeaders, options) { + async setHTTPHeaders(blobHTTPHeaders, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_7; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-setHTTPHeaders", options), span = _b.span, updatedOptions = _b.updatedOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blobContext.setHttpHeaders(tslib.__assign({ abortSignal: options.abortSignal, blobHttpHeaders: blobHTTPHeaders, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_7 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_7.message - }); - throw e_7; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobClient-setHTTPHeaders", options); + options.conditions = options.conditions || {}; + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.blobContext.setHttpHeaders(Object.assign({ abortSignal: options.abortSignal, blobHttpHeaders: blobHTTPHeaders, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Sets user-defined metadata for the specified blob as one or more name-value pairs. * @@ -35734,37 +32661,25 @@ var BlobClient = /** @class */ (function (_super) { * If no value provided the existing metadata will be removed. * @param options - Optional options to Set Metadata operation. */ - BlobClient.prototype.setMetadata = function (metadata, options) { + async setMetadata(metadata, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_8; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-setMetadata", options), span = _b.span, updatedOptions = _b.updatedOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blobContext.setMetadata(tslib.__assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata: metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_8 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_8.message - }); - throw e_8; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobClient-setMetadata", options); + options.conditions = options.conditions || {}; + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.blobContext.setMetadata(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Sets tags on the underlying blob. * A blob can have up to 10 tags. Tag keys must be between 1 and 128 characters. Tag values must be between 0 and 256 characters. @@ -35774,118 +32689,81 @@ var BlobClient = /** @class */ (function (_super) { * @param tags - * @param options - */ - BlobClient.prototype.setTags = function (tags, options) { + async setTags(tags, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_9; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-setTags", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.setTags(tslib.__assign(tslib.__assign({ 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 }) }, convertTracingToRequestOptionsBase(updatedOptions)), { tags: toBlobTags(tags) }))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_9 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_9.message - }); - throw e_9; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobClient-setTags", options); + try { + return await this.blobContext.setTags(Object.assign(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)), { tags: toBlobTags(tags) })); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Gets the tags associated with the underlying blob. * * @param options - */ - BlobClient.prototype.getTags = function (options) { + async getTags(options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, response, wrappedResponse, e_10; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-getTags", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.getTags(tslib.__assign({ 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 }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: - response = _c.sent(); - wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, tags: toTags({ blobTagSet: response.blobTagSet }) || {} }); - return [2 /*return*/, wrappedResponse]; - case 3: - e_10 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_10.message - }); - throw e_10; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobClient-getTags", options); + try { + const response = await this.blobContext.getTags(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, tags: toTags({ blobTagSet: response.blobTagSet }) || {} }); + return wrappedResponse; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Get a {@link BlobLeaseClient} that manages leases on the blob. * * @param proposeLeaseId - Initial proposed lease Id. * @returns A new BlobLeaseClient object for managing leases on the blob. */ - BlobClient.prototype.getBlobLeaseClient = function (proposeLeaseId) { + getBlobLeaseClient(proposeLeaseId) { return new BlobLeaseClient(this, proposeLeaseId); - }; + } /** * Creates a read-only snapshot of a blob. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/snapshot-blob * * @param options - Optional options to the Blob Create Snapshot operation. */ - BlobClient.prototype.createSnapshot = function (options) { + async createSnapshot(options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_11; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-createSnapshot", options), span = _b.span, updatedOptions = _b.updatedOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blobContext.createSnapshot(tslib.__assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_11 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_11.message - }); - throw e_11; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobClient-createSnapshot", options); + options.conditions = options.conditions || {}; + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.blobContext.createSnapshot(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Asynchronously copies a blob to a destination within the storage account. * This method returns a long running operation poller that allows you to wait @@ -35958,57 +32836,25 @@ var BlobClient = /** @class */ (function (_super) { * @param copySource - url to the source Azure Blob/File. * @param options - Optional options to the Blob Start Copy From URL operation. */ - BlobClient.prototype.beginCopyFromURL = function (copySource, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var client, poller; - var _this = this; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - client = { - abortCopyFromURL: function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return _this.abortCopyFromURL.apply(_this, args); - }, - getProperties: function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return _this.getProperties.apply(_this, args); - }, - startCopyFromURL: function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return _this.startCopyFromURL.apply(_this, args); - } - }; - poller = new BlobBeginCopyFromUrlPoller({ - blobClient: client, - copySource: copySource, - intervalInMs: options.intervalInMs, - onProgress: options.onProgress, - resumeFrom: options.resumeFrom, - startCopyFromURLOptions: options - }); - // Trigger the startCopyFromURL call by calling poll. - // Any errors from this method should be surfaced to the user. - return [4 /*yield*/, poller.poll()]; - case 1: - // Trigger the startCopyFromURL call by calling poll. - // Any errors from this method should be surfaced to the user. - _a.sent(); - return [2 /*return*/, poller]; - } - }); + async beginCopyFromURL(copySource, options = {}) { + const client = { + abortCopyFromURL: (...args) => this.abortCopyFromURL(...args), + getProperties: (...args) => this.getProperties(...args), + startCopyFromURL: (...args) => this.startCopyFromURL(...args) + }; + const poller = new BlobBeginCopyFromUrlPoller({ + blobClient: client, + copySource, + intervalInMs: options.intervalInMs, + onProgress: options.onProgress, + resumeFrom: options.resumeFrom, + startCopyFromURLOptions: options }); - }; + // Trigger the startCopyFromURL call by calling poll. + // Any errors from this method should be surfaced to the user. + await poller.poll(); + return poller; + } /** * Aborts a pending asynchronous Copy Blob operation, and leaves a destination blob with zero * length and full metadata. Version 2012-02-12 and newer. @@ -36017,34 +32863,22 @@ var BlobClient = /** @class */ (function (_super) { * @param copyId - Id of the Copy From URL operation. * @param options - Optional options to the Blob Abort Copy From URL operation. */ - BlobClient.prototype.abortCopyFromURL = function (copyId, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_12; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobClient-abortCopyFromURL", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.abortCopyFromURL(copyId, tslib.__assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_12 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_12.message - }); - throw e_12; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async abortCopyFromURL(copyId, options = {}) { + const { span, updatedOptions } = createSpan("BlobClient-abortCopyFromURL", options); + try { + return await this.blobContext.abortCopyFromURL(copyId, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * The synchronous Copy From URL operation copies a blob or an internet resource to a new blob. It will not * return a response until the copy is complete. @@ -36053,42 +32887,30 @@ var BlobClient = /** @class */ (function (_super) { * @param copySource - The source URL to copy from, Shared Access Signature(SAS) maybe needed for authentication * @param options - */ - BlobClient.prototype.syncCopyFromURL = function (copySource, options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_13; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-syncCopyFromURL", options), span = _b.span, updatedOptions = _b.updatedOptions; - options.conditions = options.conditions || {}; - options.sourceConditions = options.sourceConditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.copyFromURL(copySource, tslib.__assign({ abortSignal: options.abortSignal, metadata: options.metadata, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { - sourceIfMatch: options.sourceConditions.ifMatch, - sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, - sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, - sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince - }, sourceContentMD5: options.sourceContentMD5, blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_13 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_13.message - }); - throw e_13; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async syncCopyFromURL(copySource, options = {}) { + var _a, _b, _c; + const { span, updatedOptions } = createSpan("BlobClient-syncCopyFromURL", options); + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + try { + return await this.blobContext.copyFromURL(copySource, Object.assign({ abortSignal: options.abortSignal, metadata: options.metadata, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince + }, sourceContentMD5: options.sourceContentMD5, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), blobTagsString: toBlobTagsString(options.tags), immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, legalHold: options.legalHold }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Sets the tier on a blob. The operation is allowed on a page blob in a premium * storage account and on a block blob in a blob storage account (locally redundant @@ -36100,159 +32922,119 @@ var BlobClient = /** @class */ (function (_super) { * @param tier - The tier to be set on the blob. Valid values are Hot, Cool, or Archive. * @param options - Optional options to the Blob Set Tier operation. */ - BlobClient.prototype.setAccessTier = function (tier, options) { + async setAccessTier(tier, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_14; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-setAccessTier", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.setTier(toAccessTier(tier), tslib.__assign({ 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 }), rehydratePriority: options.rehydratePriority }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_14 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_14.message - }); - throw e_14; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobClient-setAccessTier", options); + try { + return await this.blobContext.setTier(toAccessTier(tier), Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), rehydratePriority: options.rehydratePriority }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; - BlobClient.prototype.downloadToBuffer = function (param1, param2, param3, param4) { - if (param4 === void 0) { param4 = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var buffer, offset, count, options, _a, span, updatedOptions, response, transferProgress_1, batch, _loop_1, off, e_15; - var _this = this; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - offset = 0; - count = 0; - options = param4; - if (param1 instanceof Buffer) { - buffer = param1; - offset = param2 || 0; - count = typeof param3 === "number" ? param3 : 0; - } - else { - offset = typeof param1 === "number" ? param1 : 0; - count = typeof param2 === "number" ? param2 : 0; - options = param3 || {}; - } - _a = createSpan("BlobClient-downloadToBuffer", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 5, 6, 7]); - if (!options.blockSize) { - options.blockSize = 0; - } - if (options.blockSize < 0) { - throw new RangeError("blockSize option must be >= 0"); - } - if (options.blockSize === 0) { - options.blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; - } - if (offset < 0) { - throw new RangeError("offset option must be >= 0"); - } - if (count && count <= 0) { - throw new RangeError("count option must be greater than 0"); - } - if (!options.conditions) { - options.conditions = {}; - } - if (!!count) return [3 /*break*/, 3]; - return [4 /*yield*/, this.getProperties(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) }))]; - case 2: - response = _b.sent(); - count = response.contentLength - offset; - if (count < 0) { - throw new RangeError("offset " + offset + " shouldn't be larger than blob size " + response.contentLength); - } - _b.label = 3; - case 3: - // Allocate the buffer of size = count if the buffer is not provided - if (!buffer) { - try { - buffer = Buffer.alloc(count); - } - catch (error) { - throw new Error("Unable to allocate the buffer of size: " + count + "(in bytes). Please try passing your own buffer to the \"downloadToBuffer\" method or try using other methods like \"download\" or \"downloadToFile\".\t " + error.message); - } - } - if (buffer.length < count) { - throw new RangeError("The buffer's size should be equal to or larger than the request count of bytes: " + count); - } - transferProgress_1 = 0; - batch = new Batch(options.concurrency); - _loop_1 = function (off) { - batch.addOperation(function () { return tslib.__awaiter(_this, void 0, void 0, function () { - var chunkEnd, response, stream; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - chunkEnd = offset + count; - if (off + options.blockSize < chunkEnd) { - chunkEnd = off + options.blockSize; - } - return [4 /*yield*/, this.download(off, chunkEnd - off, { - abortSignal: options.abortSignal, - conditions: options.conditions, - maxRetryRequests: options.maxRetryRequestsPerBlock, - customerProvidedKey: options.customerProvidedKey, - tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) - })]; - case 1: - response = _a.sent(); - stream = response.readableStreamBody; - return [4 /*yield*/, streamToBuffer(stream, buffer, off - offset, chunkEnd - offset)]; - case 2: - _a.sent(); - // Update progress after block is downloaded, in case of block trying - // Could provide finer grained progress updating inside HTTP requests, - // only if convenience layer download try is enabled - transferProgress_1 += chunkEnd - off; - if (options.onProgress) { - options.onProgress({ loadedBytes: transferProgress_1 }); - } - return [2 /*return*/]; - } - }); - }); }); - }; - for (off = offset; off < offset + count; off = off + options.blockSize) { - _loop_1(off); - } - return [4 /*yield*/, batch.do()]; - case 4: - _b.sent(); - return [2 /*return*/, buffer]; - case 5: - e_15 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_15.message - }); - throw e_15; - case 6: - span.end(); - return [7 /*endfinally*/]; - case 7: return [2 /*return*/]; + throw e; + } + finally { + span.end(); + } + } + async downloadToBuffer(param1, param2, param3, param4 = {}) { + let buffer; + let offset = 0; + let count = 0; + let options = param4; + if (param1 instanceof Buffer) { + buffer = param1; + offset = param2 || 0; + count = typeof param3 === "number" ? param3 : 0; + } + else { + offset = typeof param1 === "number" ? param1 : 0; + count = typeof param2 === "number" ? param2 : 0; + options = param3 || {}; + } + const { span, updatedOptions } = createSpan("BlobClient-downloadToBuffer", options); + try { + if (!options.blockSize) { + options.blockSize = 0; + } + if (options.blockSize < 0) { + throw new RangeError("blockSize option must be >= 0"); + } + if (options.blockSize === 0) { + options.blockSize = DEFAULT_BLOB_DOWNLOAD_BLOCK_BYTES; + } + if (offset < 0) { + throw new RangeError("offset option must be >= 0"); + } + if (count && count <= 0) { + throw new RangeError("count option must be greater than 0"); + } + if (!options.conditions) { + options.conditions = {}; + } + // Customer doesn't specify length, get it + if (!count) { + const response = await this.getProperties(Object.assign(Object.assign({}, options), { tracingOptions: Object.assign(Object.assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) })); + count = response.contentLength - offset; + if (count < 0) { + throw new RangeError(`offset ${offset} shouldn't be larger than blob size ${response.contentLength}`); } + } + // Allocate the buffer of size = count if the buffer is not provided + if (!buffer) { + try { + buffer = Buffer.alloc(count); + } + catch (error) { + throw new Error(`Unable to allocate the buffer of size: ${count}(in bytes). Please try passing your own buffer to the "downloadToBuffer" method or try using other methods like "download" or "downloadToFile".\t ${error.message}`); + } + } + if (buffer.length < count) { + throw new RangeError(`The buffer's size should be equal to or larger than the request count of bytes: ${count}`); + } + let transferProgress = 0; + const batch = new Batch(options.concurrency); + for (let off = offset; off < offset + count; off = off + options.blockSize) { + batch.addOperation(async () => { + // Exclusive chunk end position + let chunkEnd = offset + count; + if (off + options.blockSize < chunkEnd) { + chunkEnd = off + options.blockSize; + } + const response = await this.download(off, chunkEnd - off, { + abortSignal: options.abortSignal, + conditions: options.conditions, + maxRetryRequests: options.maxRetryRequestsPerBlock, + customerProvidedKey: options.customerProvidedKey, + tracingOptions: Object.assign(Object.assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) + }); + const stream = response.readableStreamBody; + await streamToBuffer(stream, buffer, off - offset, chunkEnd - offset); + // Update progress after block is downloaded, in case of block trying + // Could provide finer grained progress updating inside HTTP requests, + // only if convenience layer download try is enabled + transferProgress += chunkEnd - off; + if (options.onProgress) { + options.onProgress({ loadedBytes: transferProgress }); + } + }); + } + await batch.do(); + return buffer; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -36269,48 +33051,31 @@ var BlobClient = /** @class */ (function (_super) { * content is already read and written into a local file * at the specified path. */ - BlobClient.prototype.downloadToFile = function (filePath, offset, count, options) { - if (offset === void 0) { offset = 0; } - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, response, e_16; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobClient-downloadToFile", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 5, 6, 7]); - return [4 /*yield*/, this.download(offset, count, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) }))]; - case 2: - response = _b.sent(); - if (!response.readableStreamBody) return [3 /*break*/, 4]; - return [4 /*yield*/, readStreamToLocalFile(response.readableStreamBody, filePath)]; - case 3: - _b.sent(); - _b.label = 4; - case 4: - // The stream is no longer accessible so setting it to undefined. - response.blobDownloadStream = undefined; - return [2 /*return*/, response]; - case 5: - e_16 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_16.message - }); - throw e_16; - case 6: - span.end(); - return [7 /*endfinally*/]; - case 7: return [2 /*return*/]; - } + async downloadToFile(filePath, offset = 0, count, options = {}) { + const { span, updatedOptions } = createSpan("BlobClient-downloadToFile", options); + try { + const response = await this.download(offset, count, Object.assign(Object.assign({}, options), { tracingOptions: Object.assign(Object.assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) })); + if (response.readableStreamBody) { + await readStreamToLocalFile(response.readableStreamBody, filePath); + } + // The stream is no longer accessible so setting it to undefined. + response.blobDownloadStream = undefined; + return response; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; - BlobClient.prototype.getBlobAndContainerNamesFromUrl = function () { - var containerName; - var blobName; + throw e; + } + finally { + span.end(); + } + } + getBlobAndContainerNamesFromUrl() { + let containerName; + let blobName; try { // URL may look like the following // "https://myaccount.blob.core.windows.net/mycontainer/blob?sasString"; @@ -36319,11 +33084,11 @@ var BlobClient = /** @class */ (function (_super) { // "https://myaccount.blob.core.windows.net/mycontainer/blob/a.txt"; // IPv4/IPv6 address hosts, Endpoints - `http://127.0.0.1:10000/devstoreaccount1/containername/blob` // http://localhost:10001/devstoreaccount1/containername/blob - var parsedUrl = coreHttp.URLBuilder.parse(this.url); + const parsedUrl = coreHttp.URLBuilder.parse(this.url); if (parsedUrl.getHost().split(".")[1] === "blob") { // "https://myaccount.blob.core.windows.net/containername/blob". // .getPath() -> /containername/blob - var pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); + const pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); containerName = pathComponents[1]; blobName = pathComponents[3]; } @@ -36331,14 +33096,14 @@ var BlobClient = /** @class */ (function (_super) { // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/containername/blob // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/containername/blob // .getPath() -> /devstoreaccount1/containername/blob - var pathComponents = parsedUrl.getPath().match("/([^/]*)/([^/]*)(/(.*))?"); + const pathComponents = parsedUrl.getPath().match("/([^/]*)/([^/]*)(/(.*))?"); containerName = pathComponents[2]; blobName = pathComponents[4]; } else { // "https://customdomain.com/containername/blob". // .getPath() -> /containername/blob - var pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); + const pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); containerName = pathComponents[1]; blobName = pathComponents[3]; } @@ -36351,12 +33116,12 @@ var BlobClient = /** @class */ (function (_super) { if (!containerName) { throw new Error("Provided containerName is invalid."); } - return { blobName: blobName, containerName: containerName }; + return { blobName, containerName }; } catch (error) { throw new Error("Unable to extract blobName and containerName with provided information."); } - }; + } /** * Asynchronously copies a blob to a destination within the storage account. * In version 2012-02-12 and later, the source for a Copy Blob operation can be @@ -36370,43 +33135,31 @@ var BlobClient = /** @class */ (function (_super) { * @param copySource - url to the source Azure Blob/File. * @param options - Optional options to the Blob Start Copy From URL operation. */ - BlobClient.prototype.startCopyFromURL = function (copySource, options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_17; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobClient-startCopyFromURL", options), span = _b.span, updatedOptions = _b.updatedOptions; - options.conditions = options.conditions || {}; - options.sourceConditions = options.sourceConditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blobContext.startCopyFromURL(copySource, tslib.__assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { - sourceIfMatch: options.sourceConditions.ifMatch, - sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, - sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, - sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince, - sourceIfTags: options.sourceConditions.tagConditions - }, rehydratePriority: options.rehydratePriority, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), sealBlob: options.sealBlob }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_17 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_17.message - }); - throw e_17; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async startCopyFromURL(copySource, options = {}) { + var _a, _b, _c; + const { span, updatedOptions } = createSpan("BlobClient-startCopyFromURL", options); + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + try { + return await this.blobContext.startCopyFromURL(copySource, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince, + sourceIfTags: options.sourceConditions.tagConditions + }, immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, legalHold: options.legalHold, rehydratePriority: options.rehydratePriority, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), sealBlob: options.sealBlob }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Only available for BlobClient constructed with a shared key credential. * @@ -36418,31 +33171,93 @@ var BlobClient = /** @class */ (function (_super) { * @param options - Optional parameters. * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ - BlobClient.prototype.generateSasUrl = function (options) { - var _this = this; - return new Promise(function (resolve) { - if (!(_this.credential instanceof StorageSharedKeyCredential)) { + generateSasUrl(options) { + return new Promise((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)); + const sas = generateBlobSASQueryParameters(Object.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)); + } + /** + * Delete the immutablility policy on the blob. + * + * @param options - Optional options to delete immutability policy on the blob. + */ + async deleteImmutabilityPolicy(options) { + const { span, updatedOptions } = createSpan("BlobClient-deleteImmutabilityPolicy", options); + try { + return await this.blobContext.deleteImmutabilityPolicy(Object.assign({ abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message + }); + throw e; + } + finally { + span.end(); + } + } + /** + * Set immutablility policy on the blob. + * + * @param options - Optional options to set immutability policy on the blob. + */ + async setImmutabilityPolicy(immutabilityPolicy, options) { + const { span, updatedOptions } = createSpan("BlobClient-setImmutabilityPolicy", options); + try { + return await this.blobContext.setImmutabilityPolicy(Object.assign({ abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal, immutabilityPolicyExpiry: immutabilityPolicy.expiriesOn, immutabilityPolicyMode: immutabilityPolicy.policyMode, modifiedAccessConditions: options === null || options === void 0 ? void 0 : options.modifiedAccessCondition }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message + }); + throw e; + } + finally { + span.end(); + } + } + /** + * Set legal hold on the blob. + * + * @param options - Optional options to set legal hold on the blob. + */ + async setLegalHold(legalHoldEnabled, options) { + const { span, updatedOptions } = createSpan("BlobClient-setLegalHold", options); + try { + return await this.blobContext.setLegalHold(legalHoldEnabled, Object.assign({ abortSignal: options === null || options === void 0 ? void 0 : options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message + }); + throw e; + } + finally { + span.end(); + } + } +} /** * AppendBlobClient defines a set of operations applicable to append blobs. */ -var AppendBlobClient = /** @class */ (function (_super) { - tslib.__extends(AppendBlobClient, _super); - function AppendBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { - var _this = this; +class AppendBlobClient extends BlobClient { + constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); - var pipeline; - var url; + let pipeline; + let url; options = options || {}; - if (credentialOrPipelineOrContainerName instanceof Pipeline) { + if (isPipelineLike(credentialOrPipelineOrContainerName)) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; @@ -36467,12 +33282,12 @@ var AppendBlobClient = /** @class */ (function (_super) { blobNameOrOptions && typeof blobNameOrOptions === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) - var containerName = credentialOrPipelineOrContainerName; - var blobName = blobNameOrOptions; - var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + const containerName = credentialOrPipelineOrContainerName; + const blobName = blobNameOrOptions; + const extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + const 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); @@ -36492,9 +33307,8 @@ var AppendBlobClient = /** @class */ (function (_super) { else { throw new Error("Expecting non-empty strings for containerName and blobName parameters"); } - _this = _super.call(this, url, pipeline) || this; - _this.appendBlobContext = new AppendBlob(_this.storageClientContext); - return _this; + super(url, pipeline); + this.appendBlobContext = new AppendBlob(this.storageClientContext); } /** * Creates a new AppendBlobClient object identical to the source but with the @@ -36504,9 +33318,9 @@ var AppendBlobClient = /** @class */ (function (_super) { * @param snapshot - The snapshot timestamp. * @returns A new AppendBlobClient object identical to the source but with the specified snapshot timestamp. */ - AppendBlobClient.prototype.withSnapshot = function (snapshot) { + withSnapshot(snapshot) { return new AppendBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); - }; + } /** * Creates a 0-length append blob. Call AppendBlock to append data to an append blob. * @see https://docs.microsoft.com/rest/api/storageservices/put-blob @@ -36521,37 +33335,25 @@ var AppendBlobClient = /** @class */ (function (_super) { * await appendBlobClient.create(); * ``` */ - AppendBlobClient.prototype.create = function (options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_18; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("AppendBlobClient-create", options), span = _b.span, updatedOptions = _b.updatedOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.appendBlobContext.create(0, tslib.__assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_18 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_18.message - }); - throw e_18; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async create(options = {}) { + var _a, _b, _c; + const { span, updatedOptions } = createSpan("AppendBlobClient-create", options); + options.conditions = options.conditions || {}; + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.appendBlobContext.create(0, Object.assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, legalHold: options.legalHold, blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Creates a 0-length append blob. Call AppendBlock to append data to an append blob. * If the blob with the same name already exists, the content of the existing blob will remain unchanged. @@ -36559,81 +33361,56 @@ var AppendBlobClient = /** @class */ (function (_super) { * * @param options - */ - AppendBlobClient.prototype.createIfNotExists = function (options) { + async createIfNotExists(options = {}) { var _a, _b; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _c, span, updatedOptions, conditions, res, e_19; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _c = createSpan("AppendBlobClient-createIfNotExists", options), span = _c.span, updatedOptions = _c.updatedOptions; - conditions = { ifNoneMatch: ETagAny }; - _d.label = 1; - case 1: - _d.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.create(tslib.__assign(tslib.__assign({}, updatedOptions), { conditions: conditions }))]; - case 2: - res = _d.sent(); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable - })]; - case 3: - e_19 = _d.sent(); - if (((_a = e_19.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: "Expected exception when creating a blob only if it does not already exist." - }); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_19.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_19.response })]; - } - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_19.message - }); - throw e_19; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("AppendBlobClient-createIfNotExists", options); + const conditions = { ifNoneMatch: ETagAny }; + try { + const res = await this.create(Object.assign(Object.assign({}, updatedOptions), { conditions })); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable + }); + } + catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: "Expected exception when creating a blob only if it does not already exist." + }); + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Seals the append blob, making it read only. * * @param options - */ - AppendBlobClient.prototype.seal = function (options) { + async seal(options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_20; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("AppendBlobClient-seal", options), span = _b.span, updatedOptions = _b.updatedOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.appendBlobContext.seal(tslib.__assign({ abortSignal: options.abortSignal, appendPositionAccessConditions: options.conditions, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_20 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_20.message - }); - throw e_20; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("AppendBlobClient-seal", options); + options.conditions = options.conditions || {}; + try { + return await this.appendBlobContext.seal(Object.assign({ abortSignal: options.abortSignal, appendPositionAccessConditions: options.conditions, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Commits a new block of data to the end of the existing append blob. * @see https://docs.microsoft.com/rest/api/storageservices/append-block @@ -36658,39 +33435,27 @@ var AppendBlobClient = /** @class */ (function (_super) { * await existingAppendBlobClient.appendBlock(content, content.length); * ``` */ - AppendBlobClient.prototype.appendBlock = function (body, contentLength, options) { + async appendBlock(body, contentLength, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_21; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("AppendBlobClient-appendBlock", options), span = _b.span, updatedOptions = _b.updatedOptions; - options.conditions = options.conditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.appendBlobContext.appendBlock(contentLength, body, tslib.__assign({ abortSignal: options.abortSignal, appendPositionAccessConditions: options.conditions, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: { - onUploadProgress: options.onProgress - }, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_21 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_21.message - }); - throw e_21; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("AppendBlobClient-appendBlock", options); + options.conditions = options.conditions || {}; + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.appendBlobContext.appendBlock(contentLength, body, Object.assign({ abortSignal: options.abortSignal, appendPositionAccessConditions: options.conditions, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: { + onUploadProgress: options.onProgress + }, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * The Append Block operation commits a new block of data to the end of an existing append blob * where the contents are read from a source url. @@ -36705,58 +33470,46 @@ var AppendBlobClient = /** @class */ (function (_super) { * @param count - Number of bytes to be appended as a block * @param options - */ - AppendBlobClient.prototype.appendBlockFromURL = function (sourceURL, sourceOffset, count, options) { + async appendBlockFromURL(sourceURL, sourceOffset, count, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_22; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("AppendBlobClient-appendBlockFromURL", options), span = _b.span, updatedOptions = _b.updatedOptions; - options.conditions = options.conditions || {}; - options.sourceConditions = options.sourceConditions || {}; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.appendBlobContext.appendBlockFromUrl(sourceURL, 0, tslib.__assign({ abortSignal: options.abortSignal, sourceRange: rangeToString({ offset: sourceOffset, count: count }), sourceContentMD5: options.sourceContentMD5, sourceContentCrc64: options.sourceContentCrc64, leaseAccessConditions: options.conditions, appendPositionAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { - sourceIfMatch: options.sourceConditions.ifMatch, - sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, - sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, - sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince - }, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_22 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_22.message - }); - throw e_22; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("AppendBlobClient-appendBlockFromURL", options); + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.appendBlobContext.appendBlockFromUrl(sourceURL, 0, Object.assign({ abortSignal: options.abortSignal, sourceRange: rangeToString({ offset: sourceOffset, count }), sourceContentMD5: options.sourceContentMD5, sourceContentCrc64: options.sourceContentCrc64, leaseAccessConditions: options.conditions, appendPositionAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince + }, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; - return AppendBlobClient; -}(BlobClient)); + throw e; + } + finally { + span.end(); + } + } +} /** * BlockBlobClient defines a set of operations applicable to block blobs. */ -var BlockBlobClient = /** @class */ (function (_super) { - tslib.__extends(BlockBlobClient, _super); - function BlockBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { - var _this = this; +class BlockBlobClient extends BlobClient { + constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); - var pipeline; - var url; + let pipeline; + let url; options = options || {}; - if (credentialOrPipelineOrContainerName instanceof Pipeline) { + if (isPipelineLike(credentialOrPipelineOrContainerName)) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; @@ -36781,12 +33534,12 @@ var BlockBlobClient = /** @class */ (function (_super) { blobNameOrOptions && typeof blobNameOrOptions === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) - var containerName = credentialOrPipelineOrContainerName; - var blobName = blobNameOrOptions; - var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + const containerName = credentialOrPipelineOrContainerName; + const blobName = blobNameOrOptions; + const extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + const 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); @@ -36806,10 +33559,9 @@ var BlockBlobClient = /** @class */ (function (_super) { else { throw new Error("Expecting non-empty strings for containerName and blobName parameters"); } - _this = _super.call(this, url, pipeline) || this; - _this.blockBlobContext = new BlockBlob(_this.storageClientContext); - _this._blobContext = new Blob$1(_this.storageClientContext); - return _this; + super(url, pipeline); + this.blockBlobContext = new BlockBlob(this.storageClientContext); + this._blobContext = new Blob$1(this.storageClientContext); } /** * Creates a new BlockBlobClient object identical to the source but with the @@ -36819,9 +33571,9 @@ var BlockBlobClient = /** @class */ (function (_super) { * @param snapshot - The snapshot timestamp. * @returns A new BlockBlobClient object identical to the source but with the specified snapshot timestamp. */ - BlockBlobClient.prototype.withSnapshot = function (snapshot) { + withSnapshot(snapshot) { return new BlockBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); - }; + } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -36852,47 +33604,35 @@ var BlockBlobClient = /** @class */ (function (_super) { * @param query - * @param options - */ - BlockBlobClient.prototype.query = function (query, options) { + async query(query, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, response, e_23; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - _b = createSpan("BlockBlobClient-query", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this._blobContext.query(tslib.__assign({ abortSignal: options.abortSignal, queryRequest: { - queryType: "SQL", - expression: query, - inputSerialization: toQuerySerialization(options.inputTextConfiguration), - outputSerialization: toQuerySerialization(options.outputTextConfiguration) - }, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: - response = _c.sent(); - return [2 /*return*/, new BlobQueryResponse(response, { - abortSignal: options.abortSignal, - onProgress: options.onProgress, - onError: options.onError - })]; - case 3: - e_23 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_23.message - }); - throw e_23; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + const { span, updatedOptions } = createSpan("BlockBlobClient-query", options); + try { + if (false) {} + const response = await this._blobContext.query(Object.assign({ abortSignal: options.abortSignal, queryRequest: { + queryType: "SQL", + expression: query, + inputSerialization: toQuerySerialization(options.inputTextConfiguration), + outputSerialization: toQuerySerialization(options.outputTextConfiguration) + }, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + return new BlobQueryResponse(response, { + abortSignal: options.abortSignal, + onProgress: options.onProgress, + onError: options.onError }); - }); - }; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message + }); + throw e; + } + finally { + span.end(); + } + } /** * Creates a new block blob, or updates the content of an existing block blob. * Updating an existing block blob overwrites any existing metadata on the blob. @@ -36920,39 +33660,27 @@ var BlockBlobClient = /** @class */ (function (_super) { * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); * ``` */ - BlockBlobClient.prototype.upload = function (body, contentLength, options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_24; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _b = createSpan("BlockBlobClient-upload", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blockBlobContext.upload(contentLength, body, tslib.__assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: { - onUploadProgress: options.onProgress - }, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_24 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_24.message - }); - throw e_24; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async upload(body, contentLength, options = {}) { + var _a, _b, _c; + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("BlockBlobClient-upload", options); + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.blockBlobContext.upload(contentLength, body, Object.assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: { + onUploadProgress: options.onProgress + }, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, legalHold: options.legalHold, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * 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 @@ -36971,43 +33699,31 @@ var BlockBlobClient = /** @class */ (function (_super) { * - https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= * @param options - Optional parameters. */ - BlockBlobClient.prototype.syncUploadFromURL = function (sourceURL, options) { + async syncUploadFromURL(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, updatedOptions, e_25; - return tslib.__generator(this, function (_g) { - switch (_g.label) { - case 0: - options.conditions = options.conditions || {}; - _f = createSpan("BlockBlobClient-syncUploadFromURL", options), span = _f.span, updatedOptions = _f.updatedOptions; - _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(tslib.__assign({}, options), { blobHttpHeaders: options.blobHTTPHeaders, 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) }), convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _g.sent()]; - case 3: - e_25 = _g.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_25.message - }); - throw e_25; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("BlockBlobClient-syncUploadFromURL", options); + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.blockBlobContext.putBlobFromUrl(0, sourceURL, Object.assign(Object.assign(Object.assign({}, options), { blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.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, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization), tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags) }), convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Uploads the specified block to the block blob's "staging area" to be later * committed by a call to commitBlockList. @@ -37019,37 +33735,25 @@ var BlockBlobClient = /** @class */ (function (_super) { * @param options - Options to the Block Blob Stage Block operation. * @returns Response data for the Block Blob Stage Block operation. */ - 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, updatedOptions, e_26; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlockBlobClient-stageBlock", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blockBlobContext.stageBlock(blockId, contentLength, body, tslib.__assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, requestOptions: { - onUploadProgress: options.onProgress - }, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_26 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_26.message - }); - throw e_26; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async stageBlock(blockId, body, contentLength, options = {}) { + const { span, updatedOptions } = createSpan("BlockBlobClient-stageBlock", options); + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.blockBlobContext.stageBlock(blockId, contentLength, body, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, requestOptions: { + onUploadProgress: options.onProgress + }, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * The Stage Block From URL operation creates a new block to be committed as part * of a blob where the contents are read from a URL. @@ -37071,36 +33775,23 @@ var BlockBlobClient = /** @class */ (function (_super) { * @param options - Options to the Block Blob Stage Block From URL operation. * @returns Response data for the Block Blob Stage Block From URL operation. */ - BlockBlobClient.prototype.stageBlockFromURL = function (blockId, sourceURL, offset, count, options) { - if (offset === void 0) { offset = 0; } - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_27; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlockBlobClient-stageBlockFromURL", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blockBlobContext.stageBlockFromURL(blockId, 0, sourceURL, tslib.__assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, sourceContentMD5: options.sourceContentMD5, sourceContentCrc64: options.sourceContentCrc64, sourceRange: offset === 0 && !count ? undefined : rangeToString({ offset: offset, count: count }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_27 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_27.message - }); - throw e_27; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async stageBlockFromURL(blockId, sourceURL, offset = 0, count, options = {}) { + const { span, updatedOptions } = createSpan("BlockBlobClient-stageBlockFromURL", options); + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.blockBlobContext.stageBlockFromURL(blockId, 0, sourceURL, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, sourceContentMD5: options.sourceContentMD5, sourceContentCrc64: options.sourceContentCrc64, sourceRange: offset === 0 && !count ? undefined : rangeToString({ offset, count }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Writes a blob by specifying the list of block IDs that make up the blob. * In order to be written as part of a blob, a block must have been successfully written @@ -37113,37 +33804,25 @@ var BlockBlobClient = /** @class */ (function (_super) { * @param options - Options to the Block Blob Commit Block List operation. * @returns Response data for the Block Blob Commit Block List operation. */ - BlockBlobClient.prototype.commitBlockList = function (blocks, options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_28; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _b = createSpan("BlockBlobClient-commitBlockList", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.blockBlobContext.commitBlockList({ latest: blocks }, tslib.__assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_28 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_28.message - }); - throw e_28; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async commitBlockList(blocks, options = {}) { + var _a, _b, _c; + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("BlockBlobClient-commitBlockList", options); + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.blockBlobContext.commitBlockList({ latest: blocks }, Object.assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, legalHold: options.legalHold, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Returns the list of blocks that have been uploaded as part of a block blob * using the specified block list filter. @@ -37154,43 +33833,30 @@ var BlockBlobClient = /** @class */ (function (_super) { * @param options - Options to the Block Blob Get Block List operation. * @returns Response data for the Block Blob Get Block List operation. */ - BlockBlobClient.prototype.getBlockList = function (listType, options) { + async getBlockList(listType, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, res, e_29; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlockBlobClient-getBlockList", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.blockBlobContext.getBlockList(listType, tslib.__assign({ 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 }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: - res = _c.sent(); - if (!res.committedBlocks) { - res.committedBlocks = []; - } - if (!res.uncommittedBlocks) { - res.uncommittedBlocks = []; - } - return [2 /*return*/, res]; - case 3: - e_29 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_29.message - }); - throw e_29; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlockBlobClient-getBlockList", options); + try { + const res = await this.blockBlobContext.getBlockList(listType, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + if (!res.committedBlocks) { + res.committedBlocks = []; + } + if (!res.uncommittedBlocks) { + res.uncommittedBlocks = []; + } + return res; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } // High level functions /** * Uploads a Buffer(Node.js)/Blob(browsers)/ArrayBuffer/ArrayBufferView object to a BlockBlob. @@ -37200,45 +33866,43 @@ 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. * + * A common {@link BlockBlobParallelUploadOptions.blobHTTPHeaders} option to set is + * `blobContentType`, enabling the browser to provide + * functionality based on file type. + * * @param data - Buffer(Node.js), Blob, ArrayBuffer or ArrayBufferView * @param options - */ - BlockBlobClient.prototype.uploadData = function (data, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, buffer_1, browserBlob_1; - return tslib.__generator(this, function (_b) { - _a = createSpan("BlockBlobClient-uploadData", options), span = _a.span, updatedOptions = _a.updatedOptions; - 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, updatedOptions)]; - } - else {} + async uploadData(data, options = {}) { + const { span, updatedOptions } = createSpan("BlockBlobClient-uploadData", options); + try { + if (true) { + let buffer; + if (data instanceof Buffer) { + buffer = data; } - catch (e) { - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e.message - }); - throw e; + else if (data instanceof ArrayBuffer) { + buffer = Buffer.from(data); } - finally { - span.end(); + else { + data = data; + buffer = Buffer.from(data.buffer, data.byteOffset, data.byteLength); } - return [2 /*return*/]; + return this.uploadSeekableInternal((offset, size) => buffer.slice(offset, offset + size), buffer.byteLength, updatedOptions); + } + else {} + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * ONLY AVAILABLE IN BROWSERS. * @@ -37248,41 +33912,33 @@ 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. * + * A common {@link BlockBlobParallelUploadOptions.blobHTTPHeaders} option to set is + * `blobContentType`, enabling the browser to provide + * functionality based on file type. + * * @deprecated Use {@link uploadData} instead. * * @param browserData - Blob, File, ArrayBuffer or ArrayBufferView * @param options - Options to upload browser data. * @returns Response data for the Blob Upload operation. */ - BlockBlobClient.prototype.uploadBrowserData = function (browserData, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, browserBlob_2, e_30; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlockBlobClient-uploadBrowserData", options), span = _a.span, updatedOptions = _a.updatedOptions; - _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, updatedOptions)]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_30 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_30.message - }); - throw e_30; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async uploadBrowserData(browserData, options = {}) { + const { span, updatedOptions } = createSpan("BlockBlobClient-uploadBrowserData", options); + try { + const browserBlob = new Blob([browserData]); + return await this.uploadSeekableInternal((offset, size) => browserBlob.slice(offset, offset + size), browserBlob.size, updatedOptions); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * * Uploads data to block blob. Requires a bodyFactory as the data source, @@ -37298,115 +33954,88 @@ var BlockBlobClient = /** @class */ (function (_super) { * @param options - Options to Upload to Block Blob operation. * @returns Response data for the Blob Upload operation. */ - BlockBlobClient.prototype.uploadSeekableInternal = function (bodyFactory, size, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, numBlocks_1, blockList_1, blockIDPrefix_1, transferProgress_2, batch, _loop_2, i, e_31; - 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_STAGE_BLOCK_BYTES * BLOCK_BLOB_MAX_BLOCKS) { - 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-uploadSeekableInternal", options), span = _a.span, updatedOptions = _a.updatedOptions; - _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, updatedOptions)]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - numBlocks_1 = Math.floor((size - 1) / options.blockSize) + 1; - if (numBlocks_1 > 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_1 = []; - blockIDPrefix_1 = coreHttp.generateUuid(); - transferProgress_2 = 0; - batch = new Batch(options.concurrency); - _loop_2 = 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_1, i); - start = options.blockSize * i; - 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, { - abortSignal: options.abortSignal, - conditions: options.conditions, - encryptionScope: options.encryptionScope, - tracingOptions: updatedOptions.tracingOptions - })]; - case 1: - _a.sent(); - // Update progress after block is successfully uploaded to server, in case of block trying - // TODO: Hook with convenience layer progress event in finer level - transferProgress_2 += contentLength; - if (options.onProgress) { - options.onProgress({ - loadedBytes: transferProgress_2 - }); - } - return [2 /*return*/]; - } - }); - }); }); - }; - for (i = 0; i < numBlocks_1; i++) { - _loop_2(i); - } - return [4 /*yield*/, batch.do()]; - case 4: - _b.sent(); - return [2 /*return*/, this.commitBlockList(blockList_1, updatedOptions)]; - case 5: - e_31 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_31.message - }); - throw e_31; - case 6: - span.end(); - return [7 /*endfinally*/]; - case 7: return [2 /*return*/]; + async uploadSeekableInternal(bodyFactory, size, options = {}) { + 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_STAGE_BLOCK_BYTES * BLOCK_BLOB_MAX_BLOCKS) { + 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 = {}; + } + const { span, updatedOptions } = createSpan("BlockBlobClient-uploadSeekableInternal", options); + try { + if (size <= options.maxSingleShotSize) { + return await this.upload(bodyFactory(0, size), size, updatedOptions); + } + const numBlocks = Math.floor((size - 1) / options.blockSize) + 1; + if (numBlocks > 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}`); + } + const blockList = []; + const blockIDPrefix = coreHttp.generateUuid(); + let transferProgress = 0; + const batch = new Batch(options.concurrency); + for (let i = 0; i < numBlocks; i++) { + batch.addOperation(async () => { + const blockID = generateBlockID(blockIDPrefix, i); + const start = options.blockSize * i; + const end = i === numBlocks - 1 ? size : start + options.blockSize; + const contentLength = end - start; + blockList.push(blockID); + await this.stageBlock(blockID, bodyFactory(start, contentLength), contentLength, { + abortSignal: options.abortSignal, + conditions: options.conditions, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + }); + // Update progress after block is successfully uploaded to server, in case of block trying + // TODO: Hook with convenience layer progress event in finer level + transferProgress += contentLength; + if (options.onProgress) { + options.onProgress({ + loadedBytes: transferProgress + }); + } + }); + } + await batch.do(); + return this.commitBlockList(blockList, updatedOptions); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -37420,45 +34049,29 @@ var BlockBlobClient = /** @class */ (function (_super) { * @param options - Options to Upload to Block Blob operation. * @returns Response data for the Blob Upload operation. */ - BlockBlobClient.prototype.uploadFile = function (filePath, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, size, e_32; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlockBlobClient-uploadFile", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 4, 5, 6]); - 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 - }); - }; - }, size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) }))]; - case 3: return [2 /*return*/, _b.sent()]; - case 4: - e_32 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_32.message - }); - throw e_32; - case 5: - span.end(); - return [7 /*endfinally*/]; - case 6: return [2 /*return*/]; - } + async uploadFile(filePath, options = {}) { + const { span, updatedOptions } = createSpan("BlockBlobClient-uploadFile", options); + try { + const size = (await fsStat(filePath)).size; + return await this.uploadSeekableInternal((offset, count) => { + return () => fsCreateReadStream(filePath, { + autoClose: true, + end: count ? offset + count - 1 : Infinity, + start: offset + }); + }, size, Object.assign(Object.assign({}, options), { tracingOptions: Object.assign(Object.assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) })); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * @@ -37475,94 +34088,68 @@ var BlockBlobClient = /** @class */ (function (_super) { * @param options - Options to Upload Stream to Block Blob operation. * @returns Response data for the Blob Upload operation. */ - BlockBlobClient.prototype.uploadStream = function (stream, bufferSize, maxConcurrency, options) { - if (bufferSize === void 0) { bufferSize = DEFAULT_BLOCK_BUFFER_SIZE_BYTES; } - if (maxConcurrency === void 0) { maxConcurrency = 5; } - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, blockNum_1, blockIDPrefix_2, transferProgress_3, blockList_2, scheduler, e_33; - var _this = this; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!options.blobHTTPHeaders) { - options.blobHTTPHeaders = {}; - } - if (!options.conditions) { - options.conditions = {}; - } - _a = createSpan("BlockBlobClient-uploadStream", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 4, 5, 6]); - blockNum_1 = 0; - blockIDPrefix_2 = coreHttp.generateUuid(); - transferProgress_3 = 0; - blockList_2 = []; - scheduler = new BufferScheduler(stream, bufferSize, maxConcurrency, function (body, length) { return tslib.__awaiter(_this, void 0, void 0, function () { - var blockID; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - blockID = generateBlockID(blockIDPrefix_2, blockNum_1); - blockList_2.push(blockID); - blockNum_1++; - return [4 /*yield*/, this.stageBlock(blockID, body, length, { - conditions: options.conditions, - encryptionScope: options.encryptionScope, - tracingOptions: updatedOptions.tracingOptions - })]; - case 1: - _a.sent(); - // Update progress after block is successfully uploaded to server, in case of block trying - transferProgress_3 += length; - if (options.onProgress) { - options.onProgress({ loadedBytes: transferProgress_3 }); - } - return [2 /*return*/]; - } - }); - }); }, - // concurrency should set a smaller value than maxConcurrency, which is helpful to - // reduce the possibility when a outgoing handler waits for stream data, in - // this situation, outgoing handlers are blocked. - // Outgoing queue shouldn't be empty. - Math.ceil((maxConcurrency / 4) * 3)); - return [4 /*yield*/, scheduler.do()]; - case 2: - _b.sent(); - return [4 /*yield*/, this.commitBlockList(blockList_2, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) }))]; - case 3: return [2 /*return*/, _b.sent()]; - case 4: - e_33 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_33.message - }); - throw e_33; - case 5: - span.end(); - return [7 /*endfinally*/]; - case 6: return [2 /*return*/]; + async uploadStream(stream, bufferSize = DEFAULT_BLOCK_BUFFER_SIZE_BYTES, maxConcurrency = 5, options = {}) { + if (!options.blobHTTPHeaders) { + options.blobHTTPHeaders = {}; + } + if (!options.conditions) { + options.conditions = {}; + } + const { span, updatedOptions } = createSpan("BlockBlobClient-uploadStream", options); + try { + let blockNum = 0; + const blockIDPrefix = coreHttp.generateUuid(); + let transferProgress = 0; + const blockList = []; + const scheduler = new BufferScheduler(stream, bufferSize, maxConcurrency, async (body, length) => { + const blockID = generateBlockID(blockIDPrefix, blockNum); + blockList.push(blockID); + blockNum++; + await this.stageBlock(blockID, body, length, { + conditions: options.conditions, + encryptionScope: options.encryptionScope, + tracingOptions: updatedOptions.tracingOptions + }); + // Update progress after block is successfully uploaded to server, in case of block trying + transferProgress += length; + if (options.onProgress) { + options.onProgress({ loadedBytes: transferProgress }); } + }, + // concurrency should set a smaller value than maxConcurrency, which is helpful to + // reduce the possibility when a outgoing handler waits for stream data, in + // this situation, outgoing handlers are blocked. + // Outgoing queue shouldn't be empty. + Math.ceil((maxConcurrency / 4) * 3)); + await scheduler.do(); + return await this.commitBlockList(blockList, Object.assign(Object.assign({}, options), { tracingOptions: Object.assign(Object.assign({}, options.tracingOptions), convertTracingToRequestOptionsBase(updatedOptions)) })); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; - return BlockBlobClient; -}(BlobClient)); + throw e; + } + finally { + span.end(); + } + } +} /** * PageBlobClient defines a set of operations applicable to page blobs. */ -var PageBlobClient = /** @class */ (function (_super) { - tslib.__extends(PageBlobClient, _super); - function PageBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { - var _this = this; +class PageBlobClient extends BlobClient { + constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { // In TypeScript we cannot simply pass all parameters to super() like below so have to duplicate the code instead. // super(s, credentialOrPipelineOrContainerNameOrOptions, blobNameOrOptions, options); - var pipeline; - var url; + let pipeline; + let url; options = options || {}; - if (credentialOrPipelineOrContainerName instanceof Pipeline) { + if (isPipelineLike(credentialOrPipelineOrContainerName)) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; @@ -37587,12 +34174,12 @@ var PageBlobClient = /** @class */ (function (_super) { blobNameOrOptions && typeof blobNameOrOptions === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) - var containerName = credentialOrPipelineOrContainerName; - var blobName = blobNameOrOptions; - var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + const containerName = credentialOrPipelineOrContainerName; + const blobName = blobNameOrOptions; + const extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + const 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); @@ -37612,9 +34199,8 @@ var PageBlobClient = /** @class */ (function (_super) { else { throw new Error("Expecting non-empty strings for containerName and blobName parameters"); } - _this = _super.call(this, url, pipeline) || this; - _this.pageBlobContext = new PageBlob(_this.storageClientContext); - return _this; + super(url, pipeline); + this.pageBlobContext = new PageBlob(this.storageClientContext); } /** * Creates a new PageBlobClient object identical to the source but with the @@ -37624,9 +34210,9 @@ var PageBlobClient = /** @class */ (function (_super) { * @param snapshot - The snapshot timestamp. * @returns A new PageBlobClient object identical to the source but with the specified snapshot timestamp. */ - PageBlobClient.prototype.withSnapshot = function (snapshot) { + withSnapshot(snapshot) { return new PageBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); - }; + } /** * Creates a page blob of the specified length. Call uploadPages to upload data * data to a page blob. @@ -37636,37 +34222,25 @@ var PageBlobClient = /** @class */ (function (_super) { * @param options - Options to the Page Blob Create operation. * @returns Response data for the Page Blob Create operation. */ - PageBlobClient.prototype.create = function (size, options) { - var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_34; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-create", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.pageBlobContext.create(0, size, tslib.__assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, blobSequenceNumber: options.blobSequenceNumber, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_34 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_34.message - }); - throw e_34; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async create(size, options = {}) { + var _a, _b, _c; + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("PageBlobClient-create", options); + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.pageBlobContext.create(0, size, Object.assign({ abortSignal: options.abortSignal, blobHttpHeaders: options.blobHTTPHeaders, blobSequenceNumber: options.blobSequenceNumber, leaseAccessConditions: options.conditions, metadata: options.metadata, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, immutabilityPolicyExpiry: (_b = options.immutabilityPolicy) === null || _b === void 0 ? void 0 : _b.expiriesOn, immutabilityPolicyMode: (_c = options.immutabilityPolicy) === null || _c === void 0 ? void 0 : _c.policyMode, legalHold: options.legalHold, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Creates a page blob of the specified length. Call uploadPages to upload data * data to a page blob. If the blob with the same name already exists, the content @@ -37676,46 +34250,33 @@ var PageBlobClient = /** @class */ (function (_super) { * @param size - size of the page blob. * @param options - */ - PageBlobClient.prototype.createIfNotExists = function (size, options) { + async createIfNotExists(size, options = {}) { var _a, _b; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _c, span, updatedOptions, conditions, res, e_35; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _c = createSpan("PageBlobClient-createIfNotExists", options), span = _c.span, updatedOptions = _c.updatedOptions; - _d.label = 1; - case 1: - _d.trys.push([1, 3, 4, 5]); - conditions = { ifNoneMatch: ETagAny }; - return [4 /*yield*/, this.create(size, tslib.__assign(tslib.__assign({}, options), { conditions: conditions, tracingOptions: updatedOptions.tracingOptions }))]; - case 2: - res = _d.sent(); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable - })]; - case 3: - e_35 = _d.sent(); - if (((_a = e_35.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: "Expected exception when creating a blob only if it does not already exist." - }); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_35.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_35.response })]; - } - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_35.message - }); - throw e_35; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("PageBlobClient-createIfNotExists", options); + try { + const conditions = { ifNoneMatch: ETagAny }; + const res = await this.create(size, Object.assign(Object.assign({}, options), { conditions, tracingOptions: updatedOptions.tracingOptions })); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable + }); + } + catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: "Expected exception when creating a blob only if it does not already exist." + }); + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Writes 1 or more pages to the page blob. The start and end offsets must be a multiple of 512. * @see https://docs.microsoft.com/rest/api/storageservices/put-page @@ -37726,39 +34287,27 @@ var PageBlobClient = /** @class */ (function (_super) { * @param options - Options to the Page Blob Upload Pages operation. * @returns Response data for the Page Blob Upload Pages operation. */ - PageBlobClient.prototype.uploadPages = function (body, offset, count, options) { + async uploadPages(body, offset, count, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_36; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-uploadPages", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.pageBlobContext.uploadPages(count, body, tslib.__assign({ 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 }), requestOptions: { - onUploadProgress: options.onProgress - }, range: rangeToString({ offset: offset, count: count }), sequenceNumberAccessConditions: options.conditions, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_36 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_36.message - }); - throw e_36; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("PageBlobClient-uploadPages", options); + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.pageBlobContext.uploadPages(count, body, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), requestOptions: { + onUploadProgress: options.onProgress + }, range: rangeToString({ offset, count }), sequenceNumberAccessConditions: options.conditions, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * The Upload Pages operation writes a range of pages to a page blob where the * contents are read from a URL. @@ -37770,43 +34319,31 @@ var PageBlobClient = /** @class */ (function (_super) { * @param count - Number of bytes to be uploaded from source page blob * @param options - */ - PageBlobClient.prototype.uploadPagesFromURL = function (sourceURL, sourceOffset, destOffset, count, options) { + async uploadPagesFromURL(sourceURL, sourceOffset, destOffset, count, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_37; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - options.sourceConditions = options.sourceConditions || {}; - _b = createSpan("PageBlobClient-uploadPagesFromURL", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); - return [4 /*yield*/, this.pageBlobContext.uploadPagesFromURL(sourceURL, rangeToString({ offset: sourceOffset, count: count }), 0, rangeToString({ offset: destOffset, count: count }), tslib.__assign({ abortSignal: options.abortSignal, sourceContentMD5: options.sourceContentMD5, sourceContentCrc64: options.sourceContentCrc64, leaseAccessConditions: options.conditions, sequenceNumberAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { - sourceIfMatch: options.sourceConditions.ifMatch, - sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, - sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, - sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince - }, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_37 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_37.message - }); - throw e_37; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + options.conditions = options.conditions || {}; + options.sourceConditions = options.sourceConditions || {}; + const { span, updatedOptions } = createSpan("PageBlobClient-uploadPagesFromURL", options); + try { + ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); + return await this.pageBlobContext.uploadPagesFromURL(sourceURL, rangeToString({ offset: sourceOffset, count }), 0, rangeToString({ offset: destOffset, count }), Object.assign({ abortSignal: options.abortSignal, sourceContentMD5: options.sourceContentMD5, sourceContentCrc64: options.sourceContentCrc64, leaseAccessConditions: options.conditions, sequenceNumberAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), sourceModifiedAccessConditions: { + sourceIfMatch: options.sourceConditions.ifMatch, + sourceIfModifiedSince: options.sourceConditions.ifModifiedSince, + sourceIfNoneMatch: options.sourceConditions.ifNoneMatch, + sourceIfUnmodifiedSince: options.sourceConditions.ifUnmodifiedSince + }, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, copySourceAuthorization: httpAuthorizationToString(options.sourceAuthorization) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Frees the specified pages from the page blob. * @see https://docs.microsoft.com/rest/api/storageservices/put-page @@ -37816,37 +34353,24 @@ var PageBlobClient = /** @class */ (function (_super) { * @param options - Options to the Page Blob Clear Pages operation. * @returns Response data for the Page Blob Clear Pages operation. */ - PageBlobClient.prototype.clearPages = function (offset, count, options) { + async clearPages(offset = 0, 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, updatedOptions, e_38; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-clearPages", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext.clearPages(0, tslib.__assign({ 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 }), range: rangeToString({ offset: offset, count: count }), sequenceNumberAccessConditions: options.conditions, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_38 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_38.message - }); - throw e_38; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("PageBlobClient-clearPages", options); + try { + return await this.pageBlobContext.clearPages(0, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), range: rangeToString({ offset, count }), sequenceNumberAccessConditions: options.conditions, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Returns the list of valid page ranges for a page blob or snapshot of a page blob. * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges @@ -37856,39 +34380,26 @@ var PageBlobClient = /** @class */ (function (_super) { * @param options - Options to the Page Blob Get Ranges operation. * @returns Response data for the Page Blob Get Ranges operation. */ - PageBlobClient.prototype.getPageRanges = function (offset, count, options) { + async getPageRanges(offset = 0, 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, updatedOptions, e_39; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-getPageRanges", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext - .getPageRanges(tslib.__assign({ 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 }), range: rangeToString({ offset: offset, count: count }) }, convertTracingToRequestOptionsBase(updatedOptions))) - .then(rangeResponseFromModel)]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_39 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_39.message - }); - throw e_39; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("PageBlobClient-getPageRanges", options); + try { + return await this.pageBlobContext + .getPageRanges(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), range: rangeToString({ offset, count }) }, convertTracingToRequestOptionsBase(updatedOptions))) + .then(rangeResponseFromModel); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Gets the collection of page ranges that differ between a specified snapshot and this page blob. * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges @@ -37899,38 +34410,26 @@ var PageBlobClient = /** @class */ (function (_super) { * @param options - Options to the Page Blob Get Page Ranges Diff operation. * @returns Response data for the Page Blob Get Page Range Diff operation. */ - PageBlobClient.prototype.getPageRangesDiff = function (offset, count, prevSnapshot, options) { + async getPageRangesDiff(offset, count, prevSnapshot, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_40; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-getPageRangesDiff", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext - .getPageRangesDiff(tslib.__assign({ 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 }), prevsnapshot: prevSnapshot, range: rangeToString({ offset: offset, count: count }) }, convertTracingToRequestOptionsBase(updatedOptions))) - .then(rangeResponseFromModel)]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_40 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_40.message - }); - throw e_40; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("PageBlobClient-getPageRangesDiff", options); + try { + return await this.pageBlobContext + .getPageRangesDiff(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), prevsnapshot: prevSnapshot, range: rangeToString({ offset, count }) }, convertTracingToRequestOptionsBase(updatedOptions))) + .then(rangeResponseFromModel); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Gets the collection of page ranges that differ between a specified snapshot and this page blob for managed disks. * @see https://docs.microsoft.com/rest/api/storageservices/get-page-ranges @@ -37941,38 +34440,26 @@ var PageBlobClient = /** @class */ (function (_super) { * @param options - Options to the Page Blob Get Page Ranges Diff operation. * @returns Response data for the Page Blob Get Page Range Diff operation. */ - PageBlobClient.prototype.getPageRangesDiffForManagedDisks = function (offset, count, prevSnapshotUrl, options) { + async getPageRangesDiffForManagedDisks(offset, count, prevSnapshotUrl, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_41; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-GetPageRangesDiffForManagedDisks", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext - .getPageRangesDiff(tslib.__assign({ 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 }), prevSnapshotUrl: prevSnapshotUrl, range: rangeToString({ offset: offset, count: count }) }, convertTracingToRequestOptionsBase(updatedOptions))) - .then(rangeResponseFromModel)]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_41 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_41.message - }); - throw e_41; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("PageBlobClient-GetPageRangesDiffForManagedDisks", options); + try { + return await this.pageBlobContext + .getPageRangesDiff(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), prevSnapshotUrl, range: rangeToString({ offset, count }) }, convertTracingToRequestOptionsBase(updatedOptions))) + .then(rangeResponseFromModel); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Resizes the page blob to the specified size (which must be a multiple of 512). * @see https://docs.microsoft.com/rest/api/storageservices/set-blob-properties @@ -37981,36 +34468,24 @@ var PageBlobClient = /** @class */ (function (_super) { * @param options - Options to the Page Blob Resize operation. * @returns Response data for the Page Blob Resize operation. */ - PageBlobClient.prototype.resize = function (size, options) { + async resize(size, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_42; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-resize", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext.resize(size, tslib.__assign({ 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 }), encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_42 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_42.message - }); - throw e_42; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("PageBlobClient-resize", options); + try { + return await this.pageBlobContext.resize(size, Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), encryptionScope: options.encryptionScope }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Sets a page blob's sequence number. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties @@ -38020,36 +34495,24 @@ var PageBlobClient = /** @class */ (function (_super) { * @param options - Options to the Page Blob Update Sequence Number operation. * @returns Response data for the Page Blob Update Sequence Number operation. */ - PageBlobClient.prototype.updateSequenceNumber = function (sequenceNumberAction, sequenceNumber, options) { + async updateSequenceNumber(sequenceNumberAction, sequenceNumber, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_43; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _b = createSpan("PageBlobClient-updateSequenceNumber", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext.updateSequenceNumber(sequenceNumberAction, tslib.__assign({ abortSignal: options.abortSignal, blobSequenceNumber: sequenceNumber, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_43 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_43.message - }); - throw e_43; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("PageBlobClient-updateSequenceNumber", options); + try { + return await this.pageBlobContext.updateSequenceNumber(sequenceNumberAction, Object.assign({ abortSignal: options.abortSignal, blobSequenceNumber: sequenceNumber, leaseAccessConditions: options.conditions, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Begins an operation to start an incremental copy from one page blob's snapshot to this page blob. * The snapshot is copied such that only the differential changes between the previously @@ -38063,69 +34526,46 @@ var PageBlobClient = /** @class */ (function (_super) { * @param options - Options to the Page Blob Copy Incremental operation. * @returns Response data for the Page Blob Copy Incremental operation. */ - PageBlobClient.prototype.startCopyIncremental = function (copySource, options) { + async startCopyIncremental(copySource, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, e_44; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("PageBlobClient-startCopyIncremental", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.pageBlobContext.copyIncremental(copySource, tslib.__assign({ abortSignal: options.abortSignal, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_44 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_44.message - }); - throw e_44; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("PageBlobClient-startCopyIncremental", options); + try { + return await this.pageBlobContext.copyIncremental(copySource, Object.assign({ abortSignal: options.abortSignal, modifiedAccessConditions: Object.assign(Object.assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }) }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; - return PageBlobClient; -}(BlobClient)); + throw e; + } + finally { + span.end(); + } + } +} // Copyright (c) Microsoft Corporation. -function getBodyAsText(batchResponse) { - return tslib.__awaiter(this, void 0, void 0, function () { - var buffer, responseLength; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - buffer = Buffer.alloc(BATCH_MAX_PAYLOAD_IN_BYTES); - return [4 /*yield*/, streamToBuffer2(batchResponse.readableStreamBody, buffer)]; - case 1: - responseLength = _a.sent(); - // Slice the buffer to trim the empty ending. - buffer = buffer.slice(0, responseLength); - return [2 /*return*/, buffer.toString()]; - } - }); - }); +async function getBodyAsText(batchResponse) { + let buffer = Buffer.alloc(BATCH_MAX_PAYLOAD_IN_BYTES); + const responseLength = await streamToBuffer2(batchResponse.readableStreamBody, buffer); + // Slice the buffer to trim the empty ending. + buffer = buffer.slice(0, responseLength); + return buffer.toString(); } function utf8ByteLength(str) { return Buffer.byteLength(str); } // Copyright (c) Microsoft Corporation. -var HTTP_HEADER_DELIMITER = ": "; -var SPACE_DELIMITER = " "; -var NOT_FOUND = -1; +const HTTP_HEADER_DELIMITER = ": "; +const SPACE_DELIMITER = " "; +const NOT_FOUND = -1; /** * Util class for parsing batch response. */ -var BatchResponseParser = /** @class */ (function () { - function BatchResponseParser(batchResponse, subRequests) { +class BatchResponseParser { + constructor(batchResponse, subRequests) { if (!batchResponse || !batchResponse.contentType) { // In special case(reported), server may return invalid content-type which could not be parsed. throw new RangeError("batchResponse is malformed or doesn't contain valid content-type."); @@ -38137,129 +34577,119 @@ var BatchResponseParser = /** @class */ (function () { this.batchResponse = batchResponse; this.subRequests = subRequests; this.responseBatchBoundary = this.batchResponse.contentType.split("=")[1]; - this.perResponsePrefix = "--" + this.responseBatchBoundary + HTTP_LINE_ENDING; - this.batchResponseEnding = "--" + this.responseBatchBoundary + "--"; + this.perResponsePrefix = `--${this.responseBatchBoundary}${HTTP_LINE_ENDING}`; + this.batchResponseEnding = `--${this.responseBatchBoundary}--`; } // For example of response, please refer to https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#response - BatchResponseParser.prototype.parseBatchResponse = function () { - return tslib.__awaiter(this, void 0, void 0, function () { - var responseBodyAsText, subResponses, subResponseCount, deserializedSubResponses, subResponsesSucceededCount, subResponsesFailedCount, index, subResponse, deserializedSubResponse, responseLines, subRespHeaderStartFound, subRespHeaderEndFound, subRespFailed, contentId, _i, responseLines_1, responseLine, tokens, tokens; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - // When logic reach here, suppose batch request has already succeeded with 202, so we can further parse - // sub request's response. - if (this.batchResponse._response.status != HTTPURLConnection.HTTP_ACCEPTED) { - throw new Error("Invalid state: batch request failed with status: '" + this.batchResponse._response.status + "'."); - } - return [4 /*yield*/, getBodyAsText(this.batchResponse)]; - case 1: - responseBodyAsText = _a.sent(); - subResponses = responseBodyAsText - .split(this.batchResponseEnding)[0] // string after ending is useless - .split(this.perResponsePrefix) - .slice(1); - subResponseCount = subResponses.length; - // Defensive coding in case of potential error parsing. - // Note: subResponseCount == 1 is special case where sub request is invalid. - // We try to prevent such cases through early validation, e.g. validate sub request count >= 1. - // While in unexpected sub request invalid case, we allow sub response to be parsed and return to user. - if (subResponseCount != this.subRequests.size && subResponseCount != 1) { - throw new Error("Invalid state: sub responses' count is not equal to sub requests' count."); - } - deserializedSubResponses = new Array(subResponseCount); - subResponsesSucceededCount = 0; - subResponsesFailedCount = 0; - // Parse sub subResponses. - for (index = 0; index < subResponseCount; index++) { - subResponse = subResponses[index]; - deserializedSubResponse = {}; - deserializedSubResponse.headers = new coreHttp.HttpHeaders(); - responseLines = subResponse.split("" + HTTP_LINE_ENDING); - subRespHeaderStartFound = false; - subRespHeaderEndFound = false; - subRespFailed = false; - contentId = NOT_FOUND; - for (_i = 0, responseLines_1 = responseLines; _i < responseLines_1.length; _i++) { - responseLine = responseLines_1[_i]; - if (!subRespHeaderStartFound) { - // Convention line to indicate content ID - if (responseLine.startsWith(HeaderConstants.CONTENT_ID)) { - contentId = parseInt(responseLine.split(HTTP_HEADER_DELIMITER)[1]); - } - // Http version line with status code indicates the start of sub request's response. - // Example: HTTP/1.1 202 Accepted - if (responseLine.startsWith(HTTP_VERSION_1_1)) { - subRespHeaderStartFound = true; - tokens = responseLine.split(SPACE_DELIMITER); - deserializedSubResponse.status = parseInt(tokens[1]); - deserializedSubResponse.statusMessage = tokens.slice(2).join(SPACE_DELIMITER); - } - continue; // Skip convention headers not specifically for sub request i.e. Content-Type: application/http and Content-ID: * - } - if (responseLine.trim() === "") { - // Sub response's header start line already found, and the first empty line indicates header end line found. - if (!subRespHeaderEndFound) { - subRespHeaderEndFound = true; - } - continue; // Skip empty line - } - // Note: when code reach here, it indicates subRespHeaderStartFound == true - if (!subRespHeaderEndFound) { - if (responseLine.indexOf(HTTP_HEADER_DELIMITER) === -1) { - // Defensive coding to prevent from missing valuable lines. - throw new Error("Invalid state: find non-empty line '" + responseLine + "' without HTTP header delimiter '" + HTTP_HEADER_DELIMITER + "'."); - } - tokens = responseLine.split(HTTP_HEADER_DELIMITER); - deserializedSubResponse.headers.set(tokens[0], tokens[1]); - if (tokens[0] === HeaderConstants.X_MS_ERROR_CODE) { - deserializedSubResponse.errorCode = tokens[1]; - subRespFailed = true; - } - } - else { - // Assemble body of sub response. - if (!deserializedSubResponse.bodyAsText) { - deserializedSubResponse.bodyAsText = ""; - } - 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) { - 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++; - } - else { - subResponsesSucceededCount++; - } - } - return [2 /*return*/, { - subResponses: deserializedSubResponses, - subResponsesSucceededCount: subResponsesSucceededCount, - subResponsesFailedCount: subResponsesFailedCount - }]; + async parseBatchResponse() { + // When logic reach here, suppose batch request has already succeeded with 202, so we can further parse + // sub request's response. + if (this.batchResponse._response.status !== HTTPURLConnection.HTTP_ACCEPTED) { + throw new Error(`Invalid state: batch request failed with status: '${this.batchResponse._response.status}'.`); + } + const responseBodyAsText = await getBodyAsText(this.batchResponse); + const subResponses = responseBodyAsText + .split(this.batchResponseEnding)[0] // string after ending is useless + .split(this.perResponsePrefix) + .slice(1); // string before first response boundary is useless + const subResponseCount = subResponses.length; + // Defensive coding in case of potential error parsing. + // Note: subResponseCount == 1 is special case where sub request is invalid. + // We try to prevent such cases through early validation, e.g. validate sub request count >= 1. + // While in unexpected sub request invalid case, we allow sub response to be parsed and return to user. + if (subResponseCount !== this.subRequests.size && subResponseCount !== 1) { + throw new Error("Invalid state: sub responses' count is not equal to sub requests' count."); + } + const deserializedSubResponses = new Array(subResponseCount); + let subResponsesSucceededCount = 0; + let subResponsesFailedCount = 0; + // Parse sub subResponses. + for (let index = 0; index < subResponseCount; index++) { + const subResponse = subResponses[index]; + const deserializedSubResponse = {}; + deserializedSubResponse.headers = new coreHttp.HttpHeaders(); + const responseLines = subResponse.split(`${HTTP_LINE_ENDING}`); + let subRespHeaderStartFound = false; + let subRespHeaderEndFound = false; + let subRespFailed = false; + let contentId = NOT_FOUND; + for (const responseLine of responseLines) { + if (!subRespHeaderStartFound) { + // Convention line to indicate content ID + if (responseLine.startsWith(HeaderConstants.CONTENT_ID)) { + contentId = parseInt(responseLine.split(HTTP_HEADER_DELIMITER)[1]); + } + // Http version line with status code indicates the start of sub request's response. + // Example: HTTP/1.1 202 Accepted + if (responseLine.startsWith(HTTP_VERSION_1_1)) { + subRespHeaderStartFound = true; + const tokens = responseLine.split(SPACE_DELIMITER); + deserializedSubResponse.status = parseInt(tokens[1]); + deserializedSubResponse.statusMessage = tokens.slice(2).join(SPACE_DELIMITER); + } + continue; // Skip convention headers not specifically for sub request i.e. Content-Type: application/http and Content-ID: * } - }); - }); - }; - return BatchResponseParser; -}()); + if (responseLine.trim() === "") { + // Sub response's header start line already found, and the first empty line indicates header end line found. + if (!subRespHeaderEndFound) { + subRespHeaderEndFound = true; + } + continue; // Skip empty line + } + // Note: when code reach here, it indicates subRespHeaderStartFound == true + if (!subRespHeaderEndFound) { + if (responseLine.indexOf(HTTP_HEADER_DELIMITER) === -1) { + // Defensive coding to prevent from missing valuable lines. + throw new Error(`Invalid state: find non-empty line '${responseLine}' without HTTP header delimiter '${HTTP_HEADER_DELIMITER}'.`); + } + // Parse headers of sub response. + const tokens = responseLine.split(HTTP_HEADER_DELIMITER); + deserializedSubResponse.headers.set(tokens[0], tokens[1]); + if (tokens[0] === HeaderConstants.X_MS_ERROR_CODE) { + deserializedSubResponse.errorCode = tokens[1]; + subRespFailed = true; + } + } + else { + // Assemble body of sub response. + if (!deserializedSubResponse.bodyAsText) { + deserializedSubResponse.bodyAsText = ""; + } + 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) { + 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++; + } + else { + subResponsesSucceededCount++; + } + } + return { + subResponses: deserializedSubResponses, + subResponsesSucceededCount: subResponsesSucceededCount, + subResponsesFailedCount: subResponsesFailedCount + }; + } +} // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. var MutexLockStatus; (function (MutexLockStatus) { MutexLockStatus[MutexLockStatus["LOCKED"] = 0] = "LOCKED"; @@ -38268,82 +34698,68 @@ var MutexLockStatus; /** * An async mutex lock. */ -var Mutex = /** @class */ (function () { - function Mutex() { - } +class Mutex { /** * Lock for a specific key. If the lock has been acquired by another customer, then * will wait until getting the lock. * * @param key - lock key */ - Mutex.lock = function (key) { - return tslib.__awaiter(this, void 0, void 0, function () { - var _this = this; - return tslib.__generator(this, function (_a) { - return [2 /*return*/, new Promise(function (resolve) { - if (_this.keys[key] === undefined || _this.keys[key] === MutexLockStatus.UNLOCKED) { - _this.keys[key] = MutexLockStatus.LOCKED; - resolve(); - } - else { - _this.onUnlockEvent(key, function () { - _this.keys[key] = MutexLockStatus.LOCKED; - resolve(); - }); - } - })]; - }); + static async lock(key) { + return new Promise((resolve) => { + if (this.keys[key] === undefined || this.keys[key] === MutexLockStatus.UNLOCKED) { + this.keys[key] = MutexLockStatus.LOCKED; + resolve(); + } + else { + this.onUnlockEvent(key, () => { + this.keys[key] = MutexLockStatus.LOCKED; + resolve(); + }); + } }); - }; + } /** * Unlock a key. * * @param key - */ - Mutex.unlock = function (key) { - return tslib.__awaiter(this, void 0, void 0, function () { - var _this = this; - return tslib.__generator(this, function (_a) { - return [2 /*return*/, new Promise(function (resolve) { - if (_this.keys[key] === MutexLockStatus.LOCKED) { - _this.emitUnlockEvent(key); - } - delete _this.keys[key]; - resolve(); - })]; - }); + static async unlock(key) { + return new Promise((resolve) => { + if (this.keys[key] === MutexLockStatus.LOCKED) { + this.emitUnlockEvent(key); + } + delete this.keys[key]; + resolve(); }); - }; - Mutex.onUnlockEvent = function (key, handler) { + } + static onUnlockEvent(key, handler) { if (this.listeners[key] === undefined) { this.listeners[key] = [handler]; } else { this.listeners[key].push(handler); } - }; - Mutex.emitUnlockEvent = function (key) { - var _this = this; + } + static emitUnlockEvent(key) { if (this.listeners[key] !== undefined && this.listeners[key].length > 0) { - var handler_1 = this.listeners[key].shift(); - setImmediate(function () { - handler_1.call(_this); + const handler = this.listeners[key].shift(); + setImmediate(() => { + handler.call(this); }); } - }; - Mutex.keys = {}; - Mutex.listeners = {}; - return Mutex; -}()); + } +} +Mutex.keys = {}; +Mutex.listeners = {}; // Copyright (c) Microsoft Corporation. /** * A BlobBatch represents an aggregated set of operations on blobs. * Currently, only `delete` and `setAccessTier` are supported. */ -var BlobBatch = /** @class */ (function () { - function BlobBatch() { +class BlobBatch { + constructor() { this.batch = "batch"; this.batchRequest = new InnerBatchRequest(); } @@ -38352,203 +34768,151 @@ var BlobBatch = /** @class */ (function () { * The value must be multipart/mixed with a batch boundary. * Example: multipart/mixed; boundary=batch_a81786c8-e301-4e42-a729-a32ca24ae252 */ - BlobBatch.prototype.getMultiPartContentType = function () { + getMultiPartContentType() { return this.batchRequest.getMultipartContentType(); - }; + } /** * Get assembled HTTP request body for sub requests. */ - BlobBatch.prototype.getHttpRequestBody = function () { + getHttpRequestBody() { return this.batchRequest.getHttpRequestBody(); - }; + } /** * Get sub requests that are added into the batch request. */ - BlobBatch.prototype.getSubRequests = function () { + getSubRequests() { return this.batchRequest.getSubRequests(); - }; - BlobBatch.prototype.addSubRequestInternal = function (subRequest, assembleSubRequestFunc) { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, Mutex.lock(this.batch)]; - case 1: - _a.sent(); - _a.label = 2; - case 2: - _a.trys.push([2, , 4, 6]); - this.batchRequest.preAddSubRequest(subRequest); - return [4 /*yield*/, assembleSubRequestFunc()]; - case 3: - _a.sent(); - this.batchRequest.postAddSubRequest(subRequest); - return [3 /*break*/, 6]; - case 4: return [4 /*yield*/, Mutex.unlock(this.batch)]; - case 5: - _a.sent(); - return [7 /*endfinally*/]; - case 6: return [2 /*return*/]; - } - }); - }); - }; - BlobBatch.prototype.setBatchType = function (batchType) { + } + async addSubRequestInternal(subRequest, assembleSubRequestFunc) { + await Mutex.lock(this.batch); + try { + this.batchRequest.preAddSubRequest(subRequest); + await assembleSubRequestFunc(); + this.batchRequest.postAddSubRequest(subRequest); + } + finally { + await Mutex.unlock(this.batch); + } + } + setBatchType(batchType) { if (!this.batchType) { this.batchType = batchType; } if (this.batchType !== batchType) { - throw new RangeError("BlobBatch only supports one operation type per batch and it already is being used for " + this.batchType + " operations."); + throw new RangeError(`BlobBatch only supports one operation type per batch and it already is being used for ${this.batchType} operations.`); } - }; - BlobBatch.prototype.deleteBlob = function (urlOrBlobClient, credentialOrOptions, options) { - return tslib.__awaiter(this, void 0, void 0, function () { - var url, credential, _a, span, updatedOptions, e_1; - var _this = this; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (typeof urlOrBlobClient === "string" && - ((coreHttp.isNode && credentialOrOptions instanceof StorageSharedKeyCredential) || - credentialOrOptions instanceof AnonymousCredential || - coreHttp.isTokenCredential(credentialOrOptions))) { - // First overload - url = urlOrBlobClient; - credential = credentialOrOptions; - } - else if (urlOrBlobClient instanceof BlobClient) { - // Second overload - url = urlOrBlobClient.url; - credential = urlOrBlobClient.credential; - options = credentialOrOptions; - } - else { - throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); - } - if (!options) { - options = {}; - } - _a = createSpan("BatchDeleteRequest-addSubRequest", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - this.setBatchType("delete"); - return [4 /*yield*/, this.addSubRequestInternal({ - url: url, - credential: credential - }, function () { return tslib.__awaiter(_this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, new BlobClient(url, this.batchRequest.createPipeline(credential)).delete(updatedOptions)]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); })]; - case 2: - _b.sent(); - return [3 /*break*/, 5]; - case 3: - e_1 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_1.message - }); - throw e_1; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + } + async deleteBlob(urlOrBlobClient, credentialOrOptions, options) { + let url; + let credential; + if (typeof urlOrBlobClient === "string" && + ((coreHttp.isNode && credentialOrOptions instanceof StorageSharedKeyCredential) || + credentialOrOptions instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrOptions))) { + // First overload + url = urlOrBlobClient; + credential = credentialOrOptions; + } + else if (urlOrBlobClient instanceof BlobClient) { + // Second overload + url = urlOrBlobClient.url; + credential = urlOrBlobClient.credential; + options = credentialOrOptions; + } + else { + throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + } + if (!options) { + options = {}; + } + const { span, updatedOptions } = createSpan("BatchDeleteRequest-addSubRequest", options); + try { + this.setBatchType("delete"); + await this.addSubRequestInternal({ + url: url, + credential: credential + }, async () => { + await new BlobClient(url, this.batchRequest.createPipeline(credential)).delete(updatedOptions); }); - }); - }; - BlobBatch.prototype.setBlobAccessTier = function (urlOrBlobClient, credentialOrTier, tierOrOptions, options) { - return tslib.__awaiter(this, void 0, void 0, function () { - var url, credential, tier, _a, span, updatedOptions, e_2; - var _this = this; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (typeof urlOrBlobClient === "string" && - ((coreHttp.isNode && credentialOrTier instanceof StorageSharedKeyCredential) || - credentialOrTier instanceof AnonymousCredential || - coreHttp.isTokenCredential(credentialOrTier))) { - // First overload - url = urlOrBlobClient; - credential = credentialOrTier; - tier = tierOrOptions; - } - else if (urlOrBlobClient instanceof BlobClient) { - // Second overload - url = urlOrBlobClient.url; - credential = urlOrBlobClient.credential; - tier = credentialOrTier; - options = tierOrOptions; - } - else { - throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); - } - if (!options) { - options = {}; - } - _a = createSpan("BatchSetTierRequest-addSubRequest", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - this.setBatchType("setAccessTier"); - return [4 /*yield*/, this.addSubRequestInternal({ - url: url, - credential: credential - }, function () { return tslib.__awaiter(_this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, new BlobClient(url, this.batchRequest.createPipeline(credential)).setAccessTier(tier, updatedOptions)]; - case 1: - _a.sent(); - return [2 /*return*/]; - } - }); - }); })]; - case 2: - _b.sent(); - return [3 /*break*/, 5]; - case 3: - e_2 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_2.message - }); - throw e_2; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; - return BlobBatch; -}()); + throw e; + } + finally { + span.end(); + } + } + async setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options) { + let url; + let credential; + let tier; + if (typeof urlOrBlobClient === "string" && + ((coreHttp.isNode && credentialOrTier instanceof StorageSharedKeyCredential) || + credentialOrTier instanceof AnonymousCredential || + coreHttp.isTokenCredential(credentialOrTier))) { + // First overload + url = urlOrBlobClient; + credential = credentialOrTier; + tier = tierOrOptions; + } + else if (urlOrBlobClient instanceof BlobClient) { + // Second overload + url = urlOrBlobClient.url; + credential = urlOrBlobClient.credential; + tier = credentialOrTier; + options = tierOrOptions; + } + else { + throw new RangeError("Invalid arguments. Either url and credential, or BlobClient need be provided."); + } + if (!options) { + options = {}; + } + const { span, updatedOptions } = createSpan("BatchSetTierRequest-addSubRequest", options); + try { + this.setBatchType("setAccessTier"); + await this.addSubRequestInternal({ + url: url, + credential: credential + }, async () => { + await new BlobClient(url, this.batchRequest.createPipeline(credential)).setAccessTier(tier, updatedOptions); + }); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message + }); + throw e; + } + finally { + span.end(); + } + } +} /** * Inner batch request class which is responsible for assembling and serializing sub requests. * See https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch#request-body for how requests are assembled. */ -var InnerBatchRequest = /** @class */ (function () { - function InnerBatchRequest() { +class InnerBatchRequest { + constructor() { this.operationCount = 0; this.body = ""; - var tempGuid = coreHttp.generateUuid(); + const tempGuid = coreHttp.generateUuid(); // batch_{batchid} - this.boundary = "batch_" + tempGuid; + this.boundary = `batch_${tempGuid}`; // --batch_{batchid} // Content-Type: application/http // Content-Transfer-Encoding: binary - this.subRequestPrefix = "--" + this.boundary + HTTP_LINE_ENDING + HeaderConstants.CONTENT_TYPE + ": application/http" + HTTP_LINE_ENDING + HeaderConstants.CONTENT_TRANSFER_ENCODING + ": binary"; + this.subRequestPrefix = `--${this.boundary}${HTTP_LINE_ENDING}${HeaderConstants.CONTENT_TYPE}: application/http${HTTP_LINE_ENDING}${HeaderConstants.CONTENT_TRANSFER_ENCODING}: binary`; // multipart/mixed; boundary=batch_{batchid} - this.multipartContentType = "multipart/mixed; boundary=" + this.boundary; + this.multipartContentType = `multipart/mixed; boundary=${this.boundary}`; // --batch_{batchid}-- - this.batchRequestEnding = "--" + this.boundary + "--"; + this.batchRequestEnding = `--${this.boundary}--`; this.subRequests = new Map(); } /** @@ -38558,10 +34922,10 @@ var InnerBatchRequest = /** @class */ (function () { * and intercept request from going to wire. * @param credential - Such as AnonymousCredential, StorageSharedKeyCredential or any credential from the `@azure/identity` package to authenticate requests to the service. You can also provide an object that implements the TokenCredential interface. If not specified, AnonymousCredential is used. */ - InnerBatchRequest.prototype.createPipeline = function (credential) { - var isAnonymousCreds = credential instanceof AnonymousCredential; - var policyFactoryLength = 3 + (isAnonymousCreds ? 0 : 1); // [deserializationPolicy, BatchHeaderFilterPolicyFactory, (Optional)Credential, BatchRequestAssemblePolicyFactory] - var factories = new Array(policyFactoryLength); + createPipeline(credential) { + const isAnonymousCreds = credential instanceof AnonymousCredential; + const policyFactoryLength = 3 + (isAnonymousCreds ? 0 : 1); // [deserializationPolicy, BatchHeaderFilterPolicyFactory, (Optional)Credential, BatchRequestAssemblePolicyFactory] + const factories = new Array(policyFactoryLength); factories[0] = coreHttp.deserializationPolicy(); // Default deserializationPolicy is provided by protocol layer factories[1] = new BatchHeaderFilterPolicyFactory(); // Use batch header filter policy to exclude unnecessary headers if (!isAnonymousCreds) { @@ -38571,117 +34935,94 @@ var InnerBatchRequest = /** @class */ (function () { } factories[policyFactoryLength - 1] = new BatchRequestAssemblePolicyFactory(this); // Use batch assemble policy to assemble request and intercept request from going to wire return new Pipeline(factories, {}); - }; - InnerBatchRequest.prototype.appendSubRequestToBody = function (request) { + } + appendSubRequestToBody(request) { // Start to assemble sub request this.body += [ this.subRequestPrefix, - HeaderConstants.CONTENT_ID + ": " + this.operationCount, + `${HeaderConstants.CONTENT_ID}: ${this.operationCount}`, "", - request.method.toString() + " " + getURLPathAndQuery(request.url) + " " + HTTP_VERSION_1_1 + HTTP_LINE_ENDING // sub request start line with method + `${request.method.toString()} ${getURLPathAndQuery(request.url)} ${HTTP_VERSION_1_1}${HTTP_LINE_ENDING}` // sub request start line with method ].join(HTTP_LINE_ENDING); - for (var _i = 0, _a = request.headers.headersArray(); _i < _a.length; _i++) { - var header = _a[_i]; - this.body += header.name + ": " + header.value + HTTP_LINE_ENDING; + for (const header of request.headers.headersArray()) { + this.body += `${header.name}: ${header.value}${HTTP_LINE_ENDING}`; } this.body += HTTP_LINE_ENDING; // sub request's headers need be ending with an empty line // No body to assemble for current batch request support // End to assemble sub request - }; - InnerBatchRequest.prototype.preAddSubRequest = function (subRequest) { + } + preAddSubRequest(subRequest) { if (this.operationCount >= BATCH_MAX_REQUEST) { - throw new RangeError("Cannot exceed " + BATCH_MAX_REQUEST + " sub requests in a single batch"); + throw new RangeError(`Cannot exceed ${BATCH_MAX_REQUEST} sub requests in a single batch`); } // Fast fail if url for sub request is invalid - var path = getURLPath(subRequest.url); - if (!path || path == "") { - throw new RangeError("Invalid url for sub request: '" + subRequest.url + "'"); + const path = getURLPath(subRequest.url); + if (!path || path === "") { + throw new RangeError(`Invalid url for sub request: '${subRequest.url}'`); } - }; - InnerBatchRequest.prototype.postAddSubRequest = function (subRequest) { + } + postAddSubRequest(subRequest) { this.subRequests.set(this.operationCount, subRequest); this.operationCount++; - }; + } // Return the http request body with assembling the ending line to the sub request body. - InnerBatchRequest.prototype.getHttpRequestBody = function () { - return "" + this.body + this.batchRequestEnding + HTTP_LINE_ENDING; - }; - InnerBatchRequest.prototype.getMultipartContentType = function () { + getHttpRequestBody() { + return `${this.body}${this.batchRequestEnding}${HTTP_LINE_ENDING}`; + } + getMultipartContentType() { return this.multipartContentType; - }; - InnerBatchRequest.prototype.getSubRequests = function () { + } + getSubRequests() { return this.subRequests; - }; - return InnerBatchRequest; -}()); -var BatchRequestAssemblePolicy = /** @class */ (function (_super) { - tslib.__extends(BatchRequestAssemblePolicy, _super); - function BatchRequestAssemblePolicy(batchRequest, nextPolicy, options) { - var _this = _super.call(this, nextPolicy, options) || this; - _this.dummyResponse = { + } +} +class BatchRequestAssemblePolicy extends coreHttp.BaseRequestPolicy { + constructor(batchRequest, nextPolicy, options) { + super(nextPolicy, options); + this.dummyResponse = { request: new coreHttp.WebResource(), status: 200, headers: new coreHttp.HttpHeaders() }; - _this.batchRequest = batchRequest; - return _this; - } - BatchRequestAssemblePolicy.prototype.sendRequest = function (request) { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, this.batchRequest.appendSubRequestToBody(request)]; - case 1: - _a.sent(); - return [2 /*return*/, this.dummyResponse]; // Intercept request from going to wire - } - }); - }); - }; - return BatchRequestAssemblePolicy; -}(coreHttp.BaseRequestPolicy)); -var BatchRequestAssemblePolicyFactory = /** @class */ (function () { - function BatchRequestAssemblePolicyFactory(batchRequest) { this.batchRequest = batchRequest; } - BatchRequestAssemblePolicyFactory.prototype.create = function (nextPolicy, options) { + async sendRequest(request) { + await this.batchRequest.appendSubRequestToBody(request); + return this.dummyResponse; // Intercept request from going to wire + } +} +class BatchRequestAssemblePolicyFactory { + constructor(batchRequest) { + this.batchRequest = batchRequest; + } + create(nextPolicy, options) { return new BatchRequestAssemblePolicy(this.batchRequest, nextPolicy, options); - }; - return BatchRequestAssemblePolicyFactory; -}()); -var BatchHeaderFilterPolicy = /** @class */ (function (_super) { - tslib.__extends(BatchHeaderFilterPolicy, _super); - function BatchHeaderFilterPolicy(nextPolicy, options) { - return _super.call(this, nextPolicy, options) || this; } - BatchHeaderFilterPolicy.prototype.sendRequest = function (request) { - return tslib.__awaiter(this, void 0, void 0, function () { - var xMsHeaderName, _i, _a, header; - return tslib.__generator(this, function (_b) { - xMsHeaderName = ""; - for (_i = 0, _a = request.headers.headersArray(); _i < _a.length; _i++) { - header = _a[_i]; - if (iEqual(header.name, HeaderConstants.X_MS_VERSION)) { - xMsHeaderName = header.name; - } - } - if (xMsHeaderName !== "") { - 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() { +} +class BatchHeaderFilterPolicy extends coreHttp.BaseRequestPolicy { + // The base class has a protected constructor. Adding a public one to enable constructing of this class. + /* eslint-disable-next-line @typescript-eslint/no-useless-constructor*/ + constructor(nextPolicy, options) { + super(nextPolicy, options); } - BatchHeaderFilterPolicyFactory.prototype.create = function (nextPolicy, options) { + async sendRequest(request) { + let xMsHeaderName = ""; + for (const header of request.headers.headersArray()) { + if (iEqual(header.name, HeaderConstants.X_MS_VERSION)) { + xMsHeaderName = header.name; + } + } + if (xMsHeaderName !== "") { + request.headers.remove(xMsHeaderName); // The subrequests should not have the x-ms-version header. + } + return this._nextPolicy.sendRequest(request); + } +} +class BatchHeaderFilterPolicyFactory { + create(nextPolicy, options) { return new BatchHeaderFilterPolicy(nextPolicy, options); - }; - return BatchHeaderFilterPolicyFactory; -}()); + } +} // Copyright (c) Microsoft Corporation. /** @@ -38689,10 +35030,13 @@ var BatchHeaderFilterPolicyFactory = /** @class */ (function () { * * @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) { +class BlobBatchClient { + constructor(url, credentialOrPipeline, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { + let pipeline; + if (isPipelineLike(credentialOrPipeline)) { pipeline = credentialOrPipeline; } else if (!credentialOrPipeline) { @@ -38702,8 +35046,8 @@ var BlobBatchClient = /** @class */ (function () { else { pipeline = newPipeline(credentialOrPipeline, options); } - var storageClientContext = new StorageClientContext(url, pipeline.toServiceClientOptions()); - var path = getURLPath(url); + const storageClientContext = new StorageClientContext(url, pipeline.toServiceClientOptions()); + const path = getURLPath(url); if (path && path !== "/") { // Container scoped. this.serviceOrContainerContext = new Container(storageClientContext); @@ -38716,67 +35060,39 @@ var BlobBatchClient = /** @class */ (function () { * Creates a {@link BlobBatch}. * A BlobBatch represents an aggregated set of operations on blobs. */ - BlobBatchClient.prototype.createBatch = function () { + createBatch() { 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)]; - } - }); - }); - }; + } + async deleteBlobs(urlsOrBlobClients, credentialOrOptions, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { + const batch = new BlobBatch(); + for (const urlOrBlobClient of urlsOrBlobClients) { + if (typeof urlOrBlobClient === "string") { + await batch.deleteBlob(urlOrBlobClient, credentialOrOptions, options); + } + else { + await batch.deleteBlob(urlOrBlobClient, credentialOrOptions); + } + } + return this.submitBatch(batch); + } + async setBlobsAccessTier(urlsOrBlobClients, credentialOrTier, tierOrOptions, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { + const batch = new BlobBatch(); + for (const urlOrBlobClient of urlsOrBlobClients) { + if (typeof urlOrBlobClient === "string") { + await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options); + } + else { + await batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions); + } + } + return this.submitBatch(batch); + } /** * Submit batch request which consists of multiple subrequests. * @@ -38812,69 +35128,56 @@ var BlobBatchClient = /** @class */ (function () { * @param batchRequest - A set of Delete or SetTier operations. * @param options - */ - BlobBatchClient.prototype.submitBatch = function (batchRequest, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, 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), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 4, 5, 6]); - batchRequestBody = batchRequest.getHttpRequestBody(); - return [4 /*yield*/, this.serviceOrContainerContext.submitBatch(utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), batchRequestBody, tslib.__assign(tslib.__assign({}, options), convertTracingToRequestOptionsBase(updatedOptions)))]; - 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: coreTracing.SpanStatusCode.ERROR, - message: e_1.message - }); - throw e_1; - case 5: - span.end(); - return [7 /*endfinally*/]; - case 6: return [2 /*return*/]; - } + async submitBatch(batchRequest, options = {}) { + if (!batchRequest || batchRequest.getSubRequests().size === 0) { + throw new RangeError("Batch request should contain one or more sub requests."); + } + const { span, updatedOptions } = createSpan("BlobBatchClient-submitBatch", options); + try { + const batchRequestBody = batchRequest.getHttpRequestBody(); + // ServiceSubmitBatchResponseModel and ContainerSubmitBatchResponse are compatible for now. + const rawBatchResponse = await this.serviceOrContainerContext.submitBatch(utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), batchRequestBody, Object.assign(Object.assign({}, options), convertTracingToRequestOptionsBase(updatedOptions))); + // Parse the sub responses result, if logic reaches here(i.e. the batch request succeeded with status code 202). + const batchResponseParser = new BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests()); + const responseSummary = await batchResponseParser.parseBatchResponse(); + const 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 res; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; - return BlobBatchClient; -}()); + throw e; + } + finally { + span.end(); + } + } +} /** * A ContainerClient represents a URL to the Azure Storage container allowing you to manipulate its blobs. */ -var ContainerClient = /** @class */ (function (_super) { - tslib.__extends(ContainerClient, _super); - function ContainerClient(urlOrConnectionString, credentialOrPipelineOrContainerName, options) { - var _this = this; - var pipeline; - var url; +class ContainerClient extends StorageClient { + constructor(urlOrConnectionString, credentialOrPipelineOrContainerName, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { + let pipeline; + let url; options = options || {}; - if (credentialOrPipelineOrContainerName instanceof Pipeline) { + if (isPipelineLike(credentialOrPipelineOrContainerName)) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; @@ -38896,11 +35199,11 @@ var ContainerClient = /** @class */ (function (_super) { else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) - var containerName = credentialOrPipelineOrContainerName; - var extractedCreds = extractConnectionStringParts(urlOrConnectionString); + const containerName = credentialOrPipelineOrContainerName; + const extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); url = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)); options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); pipeline = newPipeline(sharedKeyCredential, options); @@ -38920,21 +35223,16 @@ var ContainerClient = /** @class */ (function (_super) { else { throw new Error("Expecting non-empty strings for containerName parameter"); } - _this = _super.call(this, url, pipeline) || this; - _this._containerName = _this.getContainerNameFromUrl(); - _this.containerContext = new Container(_this.storageClientContext); - return _this; + super(url, pipeline); + this._containerName = this.getContainerNameFromUrl(); + this.containerContext = new Container(this.storageClientContext); + } + /** + * The name of the container. + */ + get containerName() { + return this._containerName; } - Object.defineProperty(ContainerClient.prototype, "containerName", { - /** - * The name of the container. - */ - get: function () { - return this._containerName; - }, - enumerable: false, - configurable: true - }); /** * Creates a new container under the specified account. If the container with * the same name already exists, the operation fails. @@ -38951,37 +35249,24 @@ var ContainerClient = /** @class */ (function (_super) { * console.log("Container was created successfully", createContainerResponse.requestId); * ``` */ - ContainerClient.prototype.create = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_1; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("ContainerClient-create", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.create(tslib.__assign(tslib.__assign({}, options), convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: - // Spread operator in destructuring assignments, - // this will filter out unwanted properties from the response object into result object - return [2 /*return*/, _b.sent()]; - case 3: - e_1 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_1.message - }); - throw e_1; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async create(options = {}) { + const { span, updatedOptions } = createSpan("ContainerClient-create", options); + try { + // Spread operator in destructuring assignments, + // this will filter out unwanted properties from the response object into result object + return await this.containerContext.create(Object.assign(Object.assign({}, options), convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Creates a new container under the specified account. If the container with * the same name already exists, it is not changed. @@ -38989,45 +35274,32 @@ var ContainerClient = /** @class */ (function (_super) { * * @param options - */ - ContainerClient.prototype.createIfNotExists = function (options) { + async createIfNotExists(options = {}) { var _a, _b; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _c, span, updatedOptions, res, e_2; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _c = createSpan("ContainerClient-createIfNotExists", options), span = _c.span, updatedOptions = _c.updatedOptions; - _d.label = 1; - case 1: - _d.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.create(updatedOptions)]; - case 2: - res = _d.sent(); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable - })]; - case 3: - e_2 = _d.sent(); - if (((_a = e_2.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerAlreadyExists") { - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: "Expected exception when creating a container only if it does not already exist." - }); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_2.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_2.response })]; - } - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_2.message - }); - throw e_2; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("ContainerClient-createIfNotExists", options); + try { + const res = await this.create(updatedOptions); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable + }); + } + catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerAlreadyExists") { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: "Expected exception when creating a container only if it does not already exist." + }); + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Returns true if the Azure container resource represented by this client exists; false otherwise. * @@ -39037,63 +35309,50 @@ var ContainerClient = /** @class */ (function (_super) { * * @param options - */ - ContainerClient.prototype.exists = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_3; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("ContainerClient-exists", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.getProperties({ - abortSignal: options.abortSignal, - tracingOptions: updatedOptions.tracingOptions - })]; - case 2: - _b.sent(); - return [2 /*return*/, true]; - case 3: - e_3 = _b.sent(); - if (e_3.statusCode === 404) { - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: "Expected exception when checking container existence" - }); - return [2 /*return*/, false]; - } - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_3.message - }); - throw e_3; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async exists(options = {}) { + const { span, updatedOptions } = createSpan("ContainerClient-exists", options); + try { + await this.getProperties({ + abortSignal: options.abortSignal, + tracingOptions: updatedOptions.tracingOptions }); - }); - }; + return true; + } + catch (e) { + if (e.statusCode === 404) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: "Expected exception when checking container existence" + }); + return false; + } + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message + }); + throw e; + } + finally { + span.end(); + } + } /** * Creates a {@link BlobClient} * * @param blobName - A blob name * @returns A new BlobClient object for the given blob name. */ - ContainerClient.prototype.getBlobClient = function (blobName) { + getBlobClient(blobName) { return new BlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); - }; + } /** * Creates an {@link AppendBlobClient} * * @param blobName - An append blob name */ - ContainerClient.prototype.getAppendBlobClient = function (blobName) { + getAppendBlobClient(blobName) { return new AppendBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); - }; + } /** * Creates a {@link BlockBlobClient} * @@ -39109,17 +35368,17 @@ var ContainerClient = /** @class */ (function (_super) { * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); * ``` */ - ContainerClient.prototype.getBlockBlobClient = function (blobName) { + getBlockBlobClient(blobName) { return new BlockBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); - }; + } /** * Creates a {@link PageBlobClient} * * @param blobName - A page blob name */ - ContainerClient.prototype.getPageBlobClient = function (blobName) { + getPageBlobClient(blobName) { return new PageBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); - }; + } /** * Returns all user-defined metadata and system properties for the specified * container. The data returned does not include the container's list of blobs. @@ -39132,37 +35391,25 @@ var ContainerClient = /** @class */ (function (_super) { * * @param options - Options to Container Get Properties operation. */ - ContainerClient.prototype.getProperties = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_4; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!options.conditions) { - options.conditions = {}; - } - _a = createSpan("ContainerClient-getProperties", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.getProperties(tslib.__assign(tslib.__assign({ abortSignal: options.abortSignal }, options.conditions), convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_4 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_4.message - }); - throw e_4; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async getProperties(options = {}) { + if (!options.conditions) { + options.conditions = {}; + } + const { span, updatedOptions } = createSpan("ContainerClient-getProperties", options); + try { + return await this.containerContext.getProperties(Object.assign(Object.assign({ abortSignal: options.abortSignal }, options.conditions), convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Marks the specified container for deletion. The container and any blobs * contained within it are later deleted during garbage collection. @@ -39170,37 +35417,25 @@ var ContainerClient = /** @class */ (function (_super) { * * @param options - Options to Container Delete operation. */ - ContainerClient.prototype.delete = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_5; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!options.conditions) { - options.conditions = {}; - } - _a = createSpan("ContainerClient-delete", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.delete(tslib.__assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_5 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_5.message - }); - throw e_5; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async delete(options = {}) { + if (!options.conditions) { + options.conditions = {}; + } + const { span, updatedOptions } = createSpan("ContainerClient-delete", options); + try { + return await this.containerContext.delete(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Marks the specified container for deletion if it exists. The container and any blobs * contained within it are later deleted during garbage collection. @@ -39208,45 +35443,32 @@ var ContainerClient = /** @class */ (function (_super) { * * @param options - Options to Container Delete operation. */ - ContainerClient.prototype.deleteIfExists = function (options) { + async deleteIfExists(options = {}) { var _a, _b; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _c, span, updatedOptions, res, e_6; - return tslib.__generator(this, function (_d) { - switch (_d.label) { - case 0: - _c = createSpan("ContainerClient-deleteIfExists", options), span = _c.span, updatedOptions = _c.updatedOptions; - _d.label = 1; - case 1: - _d.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.delete(updatedOptions)]; - case 2: - res = _d.sent(); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable - })]; - case 3: - e_6 = _d.sent(); - if (((_a = e_6.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerNotFound") { - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: "Expected exception when deleting a container only if it exists." - }); - return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_6.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_6.response })]; - } - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_6.message - }); - throw e_6; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("ContainerClient-deleteIfExists", options); + try { + const res = await this.delete(updatedOptions); + return Object.assign(Object.assign({ succeeded: true }, res), { _response: res._response // _response is made non-enumerable + }); + } + catch (e) { + if (((_a = e.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerNotFound") { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: "Expected exception when deleting a container only if it exists." + }); + return Object.assign(Object.assign({ succeeded: false }, (_b = e.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e.response }); + } + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Sets one or more user-defined name-value pairs for the specified container. * @@ -39259,40 +35481,28 @@ var ContainerClient = /** @class */ (function (_super) { * If no value provided the existing metadata will be removed. * @param options - Options to Container Set Metadata operation. */ - ContainerClient.prototype.setMetadata = function (metadata, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_7; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!options.conditions) { - options.conditions = {}; - } - if (options.conditions.ifUnmodifiedSince) { - throw new RangeError("the IfUnmodifiedSince must have their default values because they are ignored by the blob service"); - } - _a = createSpan("ContainerClient-setMetadata", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.setMetadata(tslib.__assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata: metadata, modifiedAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_7 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_7.message - }); - throw e_7; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async setMetadata(metadata, options = {}) { + if (!options.conditions) { + options.conditions = {}; + } + if (options.conditions.ifUnmodifiedSince) { + throw new RangeError("the IfUnmodifiedSince must have their default values because they are ignored by the blob service"); + } + const { span, updatedOptions } = createSpan("ContainerClient-setMetadata", options); + try { + return await this.containerContext.setMetadata(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata, modifiedAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Gets the permissions for the specified container. The permissions indicate * whether container data may be accessed publicly. @@ -39304,70 +35514,56 @@ var ContainerClient = /** @class */ (function (_super) { * * @param options - Options to Container Get Access Policy operation. */ - ContainerClient.prototype.getAccessPolicy = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, response, res, _i, response_1, identifier, accessPolicy, e_8; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!options.conditions) { - options.conditions = {}; - } - _a = createSpan("ContainerClient-getAccessPolicy", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.getAccessPolicy(tslib.__assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: - response = _b.sent(); - res = { - _response: response._response, - blobPublicAccess: response.blobPublicAccess, - date: response.date, - etag: response.etag, - errorCode: response.errorCode, - lastModified: response.lastModified, - requestId: response.requestId, - clientRequestId: response.clientRequestId, - signedIdentifiers: [], - version: response.version - }; - for (_i = 0, response_1 = response; _i < response_1.length; _i++) { - identifier = response_1[_i]; - accessPolicy = undefined; - if (identifier.accessPolicy) { - accessPolicy = { - permissions: identifier.accessPolicy.permissions - }; - if (identifier.accessPolicy.expiresOn) { - accessPolicy.expiresOn = new Date(identifier.accessPolicy.expiresOn); - } - if (identifier.accessPolicy.startsOn) { - accessPolicy.startsOn = new Date(identifier.accessPolicy.startsOn); - } - } - res.signedIdentifiers.push({ - accessPolicy: accessPolicy, - id: identifier.id - }); - } - return [2 /*return*/, res]; - case 3: - e_8 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_8.message - }); - throw e_8; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + async getAccessPolicy(options = {}) { + if (!options.conditions) { + options.conditions = {}; + } + const { span, updatedOptions } = createSpan("ContainerClient-getAccessPolicy", options); + try { + const response = await this.containerContext.getAccessPolicy(Object.assign({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions))); + const res = { + _response: response._response, + blobPublicAccess: response.blobPublicAccess, + date: response.date, + etag: response.etag, + errorCode: response.errorCode, + lastModified: response.lastModified, + requestId: response.requestId, + clientRequestId: response.clientRequestId, + signedIdentifiers: [], + version: response.version + }; + for (const identifier of response) { + let accessPolicy = undefined; + if (identifier.accessPolicy) { + accessPolicy = { + permissions: identifier.accessPolicy.permissions + }; + if (identifier.accessPolicy.expiresOn) { + accessPolicy.expiresOn = new Date(identifier.accessPolicy.expiresOn); + } + if (identifier.accessPolicy.startsOn) { + accessPolicy.startsOn = new Date(identifier.accessPolicy.startsOn); + } } + res.signedIdentifiers.push({ + accessPolicy, + id: identifier.id + }); + } + return res; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Sets the permissions for the specified container. The permissions indicate * whether blobs in a container may be accessed publicly. @@ -39385,60 +35581,47 @@ var ContainerClient = /** @class */ (function (_super) { * @param containerAcl - Array of elements each having a unique Id and details of the access policy. * @param options - Options to Container Set Access Policy operation. */ - ContainerClient.prototype.setAccessPolicy = function (access, containerAcl, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, acl, _i, _b, identifier, e_9; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - options.conditions = options.conditions || {}; - _a = createSpan("ContainerClient-setAccessPolicy", options), span = _a.span, updatedOptions = _a.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - acl = []; - for (_i = 0, _b = containerAcl || []; _i < _b.length; _i++) { - identifier = _b[_i]; - acl.push({ - accessPolicy: { - expiresOn: identifier.accessPolicy.expiresOn - ? truncatedISO8061Date(identifier.accessPolicy.expiresOn) - : "", - permissions: identifier.accessPolicy.permissions, - startsOn: identifier.accessPolicy.startsOn - ? truncatedISO8061Date(identifier.accessPolicy.startsOn) - : "" - }, - id: identifier.id - }); - } - return [4 /*yield*/, this.containerContext.setAccessPolicy(tslib.__assign({ abortSignal: options.abortSignal, access: access, containerAcl: acl, leaseAccessConditions: options.conditions, modifiedAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _c.sent()]; - case 3: - e_9 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_9.message - }); - throw e_9; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async setAccessPolicy(access, containerAcl, options = {}) { + options.conditions = options.conditions || {}; + const { span, updatedOptions } = createSpan("ContainerClient-setAccessPolicy", options); + try { + const acl = []; + for (const identifier of containerAcl || []) { + acl.push({ + accessPolicy: { + expiresOn: identifier.accessPolicy.expiresOn + ? truncatedISO8061Date(identifier.accessPolicy.expiresOn) + : "", + permissions: identifier.accessPolicy.permissions, + startsOn: identifier.accessPolicy.startsOn + ? truncatedISO8061Date(identifier.accessPolicy.startsOn) + : "" + }, + id: identifier.id + }); + } + return await this.containerContext.setAccessPolicy(Object.assign({ abortSignal: options.abortSignal, access, containerAcl: acl, leaseAccessConditions: options.conditions, modifiedAccessConditions: options.conditions }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Get a {@link BlobLeaseClient} that manages leases on the container. * * @param proposeLeaseId - Initial proposed lease Id. * @returns A new BlobLeaseClient object for managing leases on the container. */ - ContainerClient.prototype.getBlobLeaseClient = function (proposeLeaseId) { + getBlobLeaseClient(proposeLeaseId) { return new BlobLeaseClient(this, proposeLeaseId); - }; + } /** * Creates a new block blob, or updates the content of an existing block blob. * @@ -39461,40 +35644,27 @@ var ContainerClient = /** @class */ (function (_super) { * @param options - Options to configure the Block Blob Upload operation. * @returns Block Blob upload response data and the corresponding BlockBlobClient instance. */ - ContainerClient.prototype.uploadBlockBlob = function (blobName, body, contentLength, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, blockBlobClient, response, e_10; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("ContainerClient-uploadBlockBlob", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - blockBlobClient = this.getBlockBlobClient(blobName); - return [4 /*yield*/, blockBlobClient.upload(body, contentLength, updatedOptions)]; - case 2: - response = _b.sent(); - return [2 /*return*/, { - blockBlobClient: blockBlobClient, - response: response - }]; - case 3: - e_10 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_10.message - }); - throw e_10; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async uploadBlockBlob(blobName, body, contentLength, options = {}) { + const { span, updatedOptions } = createSpan("ContainerClient-uploadBlockBlob", options); + try { + const blockBlobClient = this.getBlockBlobClient(blobName); + const response = await blockBlobClient.upload(body, contentLength, updatedOptions); + return { + blockBlobClient, + response + }; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * 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 @@ -39506,38 +35676,26 @@ var ContainerClient = /** @class */ (function (_super) { * @param options - Options to Blob Delete operation. * @returns Block blob deletion response data. */ - ContainerClient.prototype.deleteBlob = function (blobName, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, blobClient, e_11; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("ContainerClient-deleteBlob", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - blobClient = this.getBlobClient(blobName); - if (options.versionId) { - blobClient = blobClient.withVersion(options.versionId); - } - return [4 /*yield*/, blobClient.delete(updatedOptions)]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_11 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_11.message - }); - throw e_11; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async deleteBlob(blobName, options = {}) { + const { span, updatedOptions } = createSpan("ContainerClient-deleteBlob", options); + try { + let blobClient = this.getBlobClient(blobName); + if (options.versionId) { + blobClient = blobClient.withVersion(options.versionId); + } + return await blobClient.delete(updatedOptions); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * listBlobFlatSegment returns a single segment of blobs starting from the * specified Marker. Use an empty Marker to start enumeration from the beginning. @@ -39548,40 +35706,27 @@ var ContainerClient = /** @class */ (function (_super) { * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. * @param options - Options to Container List Blob Flat Segment operation. */ - ContainerClient.prototype.listBlobFlatSegment = function (marker, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, response, wrappedResponse, e_12; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("ContainerClient-listBlobFlatSegment", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.listBlobFlatSegment(tslib.__assign(tslib.__assign({ marker: marker }, options), convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: - response = _b.sent(); - wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, segment: tslib.__assign(tslib.__assign({}, response.segment), { blobItems: response.segment.blobItems.map(function (blobItemInteral) { - var blobItem = tslib.__assign(tslib.__assign({}, blobItemInteral), { tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) }); - return blobItem; - }) }) }); - return [2 /*return*/, wrappedResponse]; - case 3: - e_12 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_12.message - }); - throw e_12; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async listBlobFlatSegment(marker, options = {}) { + const { span, updatedOptions } = createSpan("ContainerClient-listBlobFlatSegment", options); + try { + const response = await this.containerContext.listBlobFlatSegment(Object.assign(Object.assign({ marker }, options), convertTracingToRequestOptionsBase(updatedOptions))); + const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, segment: Object.assign(Object.assign({}, response.segment), { blobItems: response.segment.blobItems.map((blobItemInteral) => { + const blobItem = Object.assign(Object.assign({}, blobItemInteral), { tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) }); + return blobItem; + }) }) }); + return wrappedResponse; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * listBlobHierarchySegment returns a single segment of blobs starting from * the specified Marker. Use an empty Marker to start enumeration from the @@ -39593,40 +35738,27 @@ var ContainerClient = /** @class */ (function (_super) { * @param marker - A string value that identifies the portion of the list to be returned with the next list operation. * @param options - Options to Container List Blob Hierarchy Segment operation. */ - ContainerClient.prototype.listBlobHierarchySegment = function (delimiter, marker, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, response, wrappedResponse, e_13; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("ContainerClient-listBlobHierarchySegment", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.containerContext.listBlobHierarchySegment(delimiter, tslib.__assign(tslib.__assign({ marker: marker }, options), convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: - response = _b.sent(); - wrappedResponse = tslib.__assign(tslib.__assign({}, response), { _response: response._response, segment: tslib.__assign(tslib.__assign({}, response.segment), { blobItems: response.segment.blobItems.map(function (blobItemInteral) { - var blobItem = tslib.__assign(tslib.__assign({}, blobItemInteral), { tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) }); - return blobItem; - }) }) }); - return [2 /*return*/, wrappedResponse]; - case 3: - e_13 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_13.message - }); - throw e_13; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async listBlobHierarchySegment(delimiter, marker, options = {}) { + const { span, updatedOptions } = createSpan("ContainerClient-listBlobHierarchySegment", options); + try { + const response = await this.containerContext.listBlobHierarchySegment(delimiter, Object.assign(Object.assign({ marker }, options), convertTracingToRequestOptionsBase(updatedOptions))); + const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, segment: Object.assign(Object.assign({}, response.segment), { blobItems: response.segment.blobItems.map((blobItemInteral) => { + const blobItem = Object.assign(Object.assign({}, blobItemInteral), { tags: toTags(blobItemInteral.blobTags), objectReplicationSourceProperties: parseObjectReplicationRecord(blobItemInteral.objectReplicationMetadata) }); + return blobItem; + }) }) }); + return wrappedResponse; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Returns an AsyncIterableIterator for ContainerListBlobFlatSegmentResponse * @@ -39639,81 +35771,42 @@ var ContainerClient = /** @class */ (function (_super) { * items. The marker value is opaque to the client. * @param options - Options to list blobs operation. */ - ContainerClient.prototype.listSegments = function (marker, options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listSegments_1() { - var listBlobsFlatSegmentResponse; - 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.listBlobFlatSegment(marker, options))]; - case 2: - listBlobsFlatSegmentResponse = _a.sent(); - marker = listBlobsFlatSegmentResponse.continuationToken; - return [4 /*yield*/, tslib.__await(listBlobsFlatSegmentResponse)]; - 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*/]; - } - }); + listSegments(marker, options = {}) { + return tslib.__asyncGenerator(this, arguments, function* listSegments_1() { + let listBlobsFlatSegmentResponse; + if (!!marker || marker === undefined) { + do { + listBlobsFlatSegmentResponse = yield tslib.__await(this.listBlobFlatSegment(marker, options)); + marker = listBlobsFlatSegmentResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(listBlobsFlatSegmentResponse)); + } while (marker); + } }); - }; + } /** * Returns an AsyncIterableIterator of {@link BlobItem} objects * * @param options - Options to list blobs operation. */ - ContainerClient.prototype.listItems = function (options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listItems_1() { - var marker, _a, _b, listBlobsFlatSegmentResponse, e_14_1; - var e_14, _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]; - listBlobsFlatSegmentResponse = _b.value; - return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(listBlobsFlatSegmentResponse.segment.blobItems)))]; - 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_14_1 = _d.sent(); - e_14 = { error: e_14_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_14) throw e_14.error; - return [7 /*endfinally*/]; - case 12: return [7 /*endfinally*/]; - case 13: return [2 /*return*/]; + listItems(options = {}) { + return tslib.__asyncGenerator(this, arguments, function* listItems_1() { + var e_1, _a; + let marker; + try { + for (var _b = tslib.__asyncValues(this.listSegments(marker, options)), _c; _c = yield tslib.__await(_b.next()), !_c.done;) { + const listBlobsFlatSegmentResponse = _c.value; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(listBlobsFlatSegmentResponse.segment.blobItems))); } - }); + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) yield tslib.__await(_a.call(_b)); + } + finally { if (e_1) throw e_1.error; } + } }); - }; + } /** * Returns an async iterable iterator to list all the blobs * under the specified account. @@ -39784,11 +35877,8 @@ var ContainerClient = /** @class */ (function (_super) { * @param options - Options to list blobs. * @returns An asyncIterableIterator that supports paging. */ - ContainerClient.prototype.listBlobsFlat = function (options) { - var _a; - var _this = this; - if (options === void 0) { options = {}; } - var include = []; + listBlobsFlat(options = {}) { + const include = []; if (options.includeCopy) { include.push("copy"); } @@ -39810,35 +35900,42 @@ var ContainerClient = /** @class */ (function (_super) { if (options.includeTags) { include.push("tags"); } + if (options.includeDeletedWithVersions) { + include.push("deletedwithversions"); + } + if (options.includeImmutabilityPolicy) { + include.push("immutabilitypolicy"); + } + if (options.includeLegalHold) { + include.push("legalhold"); + } if (options.prefix === "") { options.prefix = undefined; } - var updatedOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); + const updatedOptions = Object.assign(Object.assign({}, options), (include.length > 0 ? { include: include } : {})); // AsyncIterableIterator to iterate over blobs - var iter = this.listItems(updatedOptions); - return _a = { - /** - * The next method, part of the iteration protocol - */ - next: function () { - return iter.next(); - } + const iter = this.listItems(updatedOptions); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ - _a[Symbol.asyncIterator] = function () { + [Symbol.asyncIterator]() { return this; }, /** * 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 }, updatedOptions)); - }, - _a; - }; + byPage: (settings = {}) => { + return this.listSegments(settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); + } + }; + } /** * Returns an AsyncIterableIterator for ContainerListBlobHierarchySegmentResponse * @@ -39852,106 +35949,51 @@ var ContainerClient = /** @class */ (function (_super) { * items. The marker value is opaque to the client. * @param options - Options to list blobs operation. */ - ContainerClient.prototype.listHierarchySegments = function (delimiter, marker, options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listHierarchySegments_1() { - var listBlobsHierarchySegmentResponse; - 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.listBlobHierarchySegment(delimiter, marker, options))]; - case 2: - listBlobsHierarchySegmentResponse = _a.sent(); - marker = listBlobsHierarchySegmentResponse.continuationToken; - return [4 /*yield*/, tslib.__await(listBlobsHierarchySegmentResponse)]; - 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*/]; - } - }); + listHierarchySegments(delimiter, marker, options = {}) { + return tslib.__asyncGenerator(this, arguments, function* listHierarchySegments_1() { + let listBlobsHierarchySegmentResponse; + if (!!marker || marker === undefined) { + do { + listBlobsHierarchySegmentResponse = yield tslib.__await(this.listBlobHierarchySegment(delimiter, marker, options)); + marker = listBlobsHierarchySegmentResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(listBlobsHierarchySegmentResponse)); + } while (marker); + } }); - }; + } /** * Returns an AsyncIterableIterator for {@link BlobPrefix} and {@link BlobItem} objects. * * @param delimiter - The character or string used to define the virtual hierarchy * @param options - Options to list blobs operation. */ - ContainerClient.prototype.listItemsByHierarchy = function (delimiter, options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listItemsByHierarchy_1() { - var marker, _a, _b, listBlobsHierarchySegmentResponse, segment, _i, _c, prefix, _d, _e, blob, e_15_1; - var e_15, _f; - return tslib.__generator(this, function (_g) { - switch (_g.label) { - case 0: - _g.trys.push([0, 14, 15, 20]); - _a = tslib.__asyncValues(this.listHierarchySegments(delimiter, marker, options)); - _g.label = 1; - case 1: return [4 /*yield*/, tslib.__await(_a.next())]; - case 2: - if (!(_b = _g.sent(), !_b.done)) return [3 /*break*/, 13]; - listBlobsHierarchySegmentResponse = _b.value; - segment = listBlobsHierarchySegmentResponse.segment; - if (!segment.blobPrefixes) return [3 /*break*/, 7]; - _i = 0, _c = segment.blobPrefixes; - _g.label = 3; - case 3: - if (!(_i < _c.length)) return [3 /*break*/, 7]; - prefix = _c[_i]; - return [4 /*yield*/, tslib.__await(tslib.__assign({ kind: "prefix" }, prefix))]; - case 4: return [4 /*yield*/, _g.sent()]; - case 5: - _g.sent(); - _g.label = 6; - case 6: - _i++; - return [3 /*break*/, 3]; - case 7: - _d = 0, _e = segment.blobItems; - _g.label = 8; - case 8: - if (!(_d < _e.length)) return [3 /*break*/, 12]; - blob = _e[_d]; - return [4 /*yield*/, tslib.__await(tslib.__assign({ kind: "blob" }, blob))]; - case 9: return [4 /*yield*/, _g.sent()]; - case 10: - _g.sent(); - _g.label = 11; - case 11: - _d++; - return [3 /*break*/, 8]; - case 12: return [3 /*break*/, 1]; - case 13: return [3 /*break*/, 20]; - case 14: - e_15_1 = _g.sent(); - e_15 = { error: e_15_1 }; - return [3 /*break*/, 20]; - case 15: - _g.trys.push([15, , 18, 19]); - if (!(_b && !_b.done && (_f = _a.return))) return [3 /*break*/, 17]; - return [4 /*yield*/, tslib.__await(_f.call(_a))]; - case 16: - _g.sent(); - _g.label = 17; - case 17: return [3 /*break*/, 19]; - case 18: - if (e_15) throw e_15.error; - return [7 /*endfinally*/]; - case 19: return [7 /*endfinally*/]; - case 20: return [2 /*return*/]; + listItemsByHierarchy(delimiter, options = {}) { + return tslib.__asyncGenerator(this, arguments, function* listItemsByHierarchy_1() { + var e_2, _a; + let marker; + try { + for (var _b = tslib.__asyncValues(this.listHierarchySegments(delimiter, marker, options)), _c; _c = yield tslib.__await(_b.next()), !_c.done;) { + const listBlobsHierarchySegmentResponse = _c.value; + const segment = listBlobsHierarchySegmentResponse.segment; + if (segment.blobPrefixes) { + for (const prefix of segment.blobPrefixes) { + yield yield tslib.__await(Object.assign({ kind: "prefix" }, prefix)); + } + } + for (const blob of segment.blobItems) { + yield yield tslib.__await(Object.assign({ kind: "blob" }, blob)); + } } - }); + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) yield tslib.__await(_a.call(_b)); + } + finally { if (e_2) throw e_2.error; } + } }); - }; + } /** * Returns an async iterable iterator to list all the blobs by hierarchy. * under the specified account. @@ -40028,14 +36070,11 @@ var ContainerClient = /** @class */ (function (_super) { * @param delimiter - The character or string used to define the virtual hierarchy * @param options - Options to list blobs operation. */ - ContainerClient.prototype.listBlobsByHierarchy = function (delimiter, options) { - var _a; - var _this = this; - if (options === void 0) { options = {}; } + listBlobsByHierarchy(delimiter, options = {}) { if (delimiter === "") { throw new RangeError("delimiter should contain one or more characters"); } - var include = []; + const include = []; if (options.includeCopy) { include.push("copy"); } @@ -40057,48 +36096,51 @@ var ContainerClient = /** @class */ (function (_super) { if (options.includeTags) { include.push("tags"); } + if (options.includeDeletedWithVersions) { + include.push("deletedwithversions"); + } + if (options.includeImmutabilityPolicy) { + include.push("immutabilitypolicy"); + } + if (options.includeLegalHold) { + include.push("legalhold"); + } if (options.prefix === "") { options.prefix = undefined; } - var updatedOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); + const updatedOptions = Object.assign(Object.assign({}, options), (include.length > 0 ? { include: include } : {})); // AsyncIterableIterator to iterate over blob prefixes and blobs - var iter = this.listItemsByHierarchy(delimiter, updatedOptions); - return _a = { - /** - * The next method, part of the iteration protocol - */ - next: function () { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - return [2 /*return*/, iter.next()]; - }); - }); - } + const iter = this.listItemsByHierarchy(delimiter, updatedOptions); + return { + /** + * The next method, part of the iteration protocol + */ + async next() { + return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ - _a[Symbol.asyncIterator] = function () { + [Symbol.asyncIterator]() { return this; }, /** * Return an AsyncIterableIterator that works a page at a time */ - _a.byPage = function (settings) { - if (settings === void 0) { settings = {}; } - return _this.listHierarchySegments(delimiter, settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); - }, - _a; - }; - ContainerClient.prototype.getContainerNameFromUrl = function () { - var containerName; + byPage: (settings = {}) => { + return this.listHierarchySegments(delimiter, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); + } + }; + } + getContainerNameFromUrl() { + let containerName; try { // URL may look like the following // "https://myaccount.blob.core.windows.net/mycontainer?sasString"; // "https://myaccount.blob.core.windows.net/mycontainer"; // IPv4/IPv6 address hosts, Endpoints - `http://127.0.0.1:10000/devstoreaccount1/containername` // http://localhost:10001/devstoreaccount1/containername - var parsedUrl = coreHttp.URLBuilder.parse(this.url); + const parsedUrl = coreHttp.URLBuilder.parse(this.url); if (parsedUrl.getHost().split(".")[1] === "blob") { // "https://myaccount.blob.core.windows.net/containername". // "https://customdomain.com/containername". @@ -40126,7 +36168,7 @@ var ContainerClient = /** @class */ (function (_super) { catch (error) { throw new Error("Unable to extract containerName with provided information."); } - }; + } /** * Only available for ContainerClient constructed with a shared key credential. * @@ -40138,16 +36180,15 @@ var ContainerClient = /** @class */ (function (_super) { * @param options - Optional parameters. * @returns The SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ - ContainerClient.prototype.generateSasUrl = function (options) { - var _this = this; - return new Promise(function (resolve) { - if (!(_this.credential instanceof StorageSharedKeyCredential)) { + generateSasUrl(options) { + return new Promise((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)); + const sas = generateBlobSASQueryParameters(Object.assign({ containerName: this._containerName }, options), this.credential).toString(); + resolve(appendToURLQuery(this.url, sas)); }); - }; + } /** * Creates a BlobBatchClient object to conduct batch operations. * @@ -40155,11 +36196,10 @@ var ContainerClient = /** @class */ (function (_super) { * * @returns A new BlobBatchClient object for this container. */ - ContainerClient.prototype.getBlobBatchClient = function () { + getBlobBatchClient() { return new BlobBatchClient(this.url, this.pipeline); - }; - return ContainerClient; -}(StorageClient)); + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -40172,8 +36212,8 @@ var ContainerClient = /** @class */ (function (_super) { * {@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. */ -var AccountSASPermissions = /** @class */ (function () { - function AccountSASPermissions() { +class AccountSASPermissions { + constructor() { /** * Permission to read resources and list queues and tables granted. */ @@ -40218,16 +36258,19 @@ var AccountSASPermissions = /** @class */ (function () { * Permission to filter blobs. */ this.filter = false; + /** + * Permission to set immutability policy. + */ + this.setImmutabilityPolicy = false; } /** * Parse initializes the AccountSASPermissions fields from a string. * * @param permissions - */ - 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]; + static parse(permissions) { + const accountSASPermissions = new AccountSASPermissions(); + for (const c of permissions) { switch (c) { case "r": accountSASPermissions.read = true; @@ -40262,20 +36305,23 @@ var AccountSASPermissions = /** @class */ (function () { case "f": accountSASPermissions.filter = true; break; + case "i": + accountSASPermissions.setImmutabilityPolicy = true; + break; default: - throw new RangeError("Invalid permission character: " + c); + 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. * * @param permissionLike - */ - AccountSASPermissions.from = function (permissionLike) { - var accountSASPermissions = new AccountSASPermissions(); + static from(permissionLike) { + const accountSASPermissions = new AccountSASPermissions(); if (permissionLike.read) { accountSASPermissions.read = true; } @@ -40309,8 +36355,11 @@ var AccountSASPermissions = /** @class */ (function () { if (permissionLike.process) { accountSASPermissions.process = true; } + if (permissionLike.setImmutabilityPolicy) { + accountSASPermissions.setImmutabilityPolicy = true; + } return accountSASPermissions; - }; + } /** * Produces the SAS permissions string for an Azure Storage account. * Call this method to set AccountSASSignatureValues Permissions field. @@ -40321,11 +36370,11 @@ var AccountSASPermissions = /** @class */ (function () { * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas * */ - AccountSASPermissions.prototype.toString = function () { + toString() { // 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 = []; + const permissions = []; if (this.read) { permissions.push("r"); } @@ -40359,10 +36408,12 @@ var AccountSASPermissions = /** @class */ (function () { if (this.process) { permissions.push("p"); } + if (this.setImmutabilityPolicy) { + permissions.push("i"); + } return permissions.join(""); - }; - return AccountSASPermissions; -}()); + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -40375,8 +36426,8 @@ var AccountSASPermissions = /** @class */ (function () { * {@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. */ -var AccountSASResourceTypes = /** @class */ (function () { - function AccountSASResourceTypes() { +class AccountSASResourceTypes { + constructor() { /** * Permission to access service level APIs granted. */ @@ -40396,10 +36447,9 @@ var AccountSASResourceTypes = /** @class */ (function () { * * @param resourceTypes - */ - 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]; + static parse(resourceTypes) { + const accountSASResourceTypes = new AccountSASResourceTypes(); + for (const c of resourceTypes) { switch (c) { case "s": accountSASResourceTypes.service = true; @@ -40411,19 +36461,19 @@ var AccountSASResourceTypes = /** @class */ (function () { accountSASResourceTypes.object = true; break; default: - throw new RangeError("Invalid resource type: " + c); + 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 * */ - AccountSASResourceTypes.prototype.toString = function () { - var resourceTypes = []; + toString() { + const resourceTypes = []; if (this.service) { resourceTypes.push("s"); } @@ -40434,9 +36484,8 @@ var AccountSASResourceTypes = /** @class */ (function () { resourceTypes.push("o"); } return resourceTypes.join(""); - }; - return AccountSASResourceTypes; -}()); + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -40449,8 +36498,8 @@ var AccountSASResourceTypes = /** @class */ (function () { * {@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. */ -var AccountSASServices = /** @class */ (function () { - function AccountSASServices() { +class AccountSASServices { + constructor() { /** * Permission to access blob resources granted. */ @@ -40474,10 +36523,9 @@ var AccountSASServices = /** @class */ (function () { * * @param services - */ - 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]; + static parse(services) { + const accountSASServices = new AccountSASServices(); + for (const c of services) { switch (c) { case "b": accountSASServices.blob = true; @@ -40492,17 +36540,17 @@ var AccountSASServices = /** @class */ (function () { accountSASServices.table = true; break; default: - throw new RangeError("Invalid service character: " + c); + throw new RangeError(`Invalid service character: ${c}`); } } return accountSASServices; - }; + } /** * Converts the given services to a string. * */ - AccountSASServices.prototype.toString = function () { - var services = []; + toString() { + const services = []; if (this.blob) { services.push("b"); } @@ -40516,9 +36564,8 @@ var AccountSASServices = /** @class */ (function () { services.push("f"); } return services.join(""); - }; - return AccountSASServices; -}()); + } +} // Copyright (c) Microsoft Corporation. /** @@ -40533,9 +36580,14 @@ var AccountSASServices = /** @class */ (function () { * @param sharedKeyCredential - */ function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { - var version = accountSASSignatureValues.version + const version = accountSASSignatureValues.version ? accountSASSignatureValues.version : SERVICE_VERSION; + if (accountSASSignatureValues.permissions && + accountSASSignatureValues.permissions.setImmutabilityPolicy && + version < "2020-08-04") { + throw RangeError("'version' must be >= '2020-08-04' when provided 'i' permission."); + } if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.deleteVersion && version < "2019-10-10") { @@ -40551,10 +36603,10 @@ function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyC 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 = [ + const parsedPermissions = AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()); + const parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); + const parsedResourceTypes = AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString(); + const stringToSign = [ sharedKeyCredential.accountName, parsedPermissions, parsedServices, @@ -40568,7 +36620,7 @@ function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyC version, "" // Account SAS requires an additional newline character ].join("\n"); - var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); + const signature = sharedKeyCredential.computeHMACSHA256(stringToSign); return new SASQueryParameters(version, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange); } @@ -40576,12 +36628,13 @@ function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyC * A BlobServiceClient represents a Client to the Azure Storage Blob service allowing you * to manipulate blob containers. */ -var BlobServiceClient = /** @class */ (function (_super) { - tslib.__extends(BlobServiceClient, _super); - function BlobServiceClient(url, credentialOrPipeline, options) { - var _this = this; - var pipeline; - if (credentialOrPipeline instanceof Pipeline) { +class BlobServiceClient extends StorageClient { + constructor(url, credentialOrPipeline, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { + let pipeline; + if (isPipelineLike(credentialOrPipeline)) { pipeline = credentialOrPipeline; } else if ((coreHttp.isNode && credentialOrPipeline instanceof StorageSharedKeyCredential) || @@ -40593,9 +36646,8 @@ var BlobServiceClient = /** @class */ (function (_super) { // The second parameter is undefined. Use anonymous credential pipeline = newPipeline(new AnonymousCredential(), options); } - _this = _super.call(this, url, pipeline) || this; - _this.serviceContext = new Service(_this.storageClientContext); - return _this; + super(url, pipeline); + this.serviceContext = new Service(this.storageClientContext); } /** * @@ -40609,25 +36661,28 @@ var BlobServiceClient = /** @class */ (function (_super) { * `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 options - Optional. Options to configure the HTTP pipeline. */ - BlobServiceClient.fromConnectionString = function (connectionString, options) { + static fromConnectionString(connectionString, + // Legacy, no fix for eslint error without breaking. Disable it for this interface. + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options*/ + options) { options = options || {}; - var extractedCreds = extractConnectionStringParts(connectionString); + const extractedCreds = extractConnectionStringParts(connectionString); if (extractedCreds.kind === "AccountConnString") { { - var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); + const sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); - var pipeline = newPipeline(sharedKeyCredential, options); + const pipeline = newPipeline(sharedKeyCredential, options); return new BlobServiceClient(extractedCreds.url, pipeline); } } else if (extractedCreds.kind === "SASConnString") { - var pipeline = newPipeline(new AnonymousCredential(), options); + const 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 * @@ -40640,9 +36695,9 @@ var BlobServiceClient = /** @class */ (function (_super) { * const containerClient = blobServiceClient.getContainerClient(""); * ``` */ - BlobServiceClient.prototype.getContainerClient = function (containerName) { + getContainerClient(containerName) { return new ContainerClient(appendToURLPath(this.url, encodeURIComponent(containerName)), this.pipeline); - }; + } /** * Create a Blob container. * @@ -40650,40 +36705,27 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param options - Options to configure Container Create operation. * @returns Container creation response and the corresponding container client. */ - BlobServiceClient.prototype.createContainer = function (containerName, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, containerClient, containerCreateResponse, e_1; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-createContainer", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - containerClient = this.getContainerClient(containerName); - return [4 /*yield*/, containerClient.create(updatedOptions)]; - case 2: - containerCreateResponse = _b.sent(); - return [2 /*return*/, { - containerClient: containerClient, - containerCreateResponse: containerCreateResponse - }]; - case 3: - e_1 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_1.message - }); - throw e_1; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async createContainer(containerName, options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-createContainer", options); + try { + const containerClient = this.getContainerClient(containerName); + const containerCreateResponse = await containerClient.create(updatedOptions); + return { + containerClient, + containerCreateResponse + }; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Deletes a Blob container. * @@ -40691,35 +36733,23 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param options - Options to configure Container Delete operation. * @returns Container deletion response. */ - BlobServiceClient.prototype.deleteContainer = function (containerName, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, containerClient, e_2; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-deleteContainer", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - containerClient = this.getContainerClient(containerName); - return [4 /*yield*/, containerClient.delete(updatedOptions)]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_2 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_2.message - }); - throw e_2; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async deleteContainer(containerName, options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-deleteContainer", options); + try { + const containerClient = this.getContainerClient(containerName); + return await containerClient.delete(updatedOptions); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * 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. @@ -40729,39 +36759,27 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param options - Options to configure Container Restore operation. * @returns Container deletion response. */ - BlobServiceClient.prototype.undeleteContainer = function (deletedContainerName, deletedContainerVersion, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, containerClient, containerContext, containerUndeleteResponse, e_3; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-undeleteContainer", options), span = _a.span, updatedOptions = _a.updatedOptions; - _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({ deletedContainerName: deletedContainerName, - deletedContainerVersion: deletedContainerVersion }, updatedOptions))]; - case 2: - containerUndeleteResponse = _b.sent(); - return [2 /*return*/, { containerClient: containerClient, containerUndeleteResponse: containerUndeleteResponse }]; - case 3: - e_3 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_3.message - }); - throw e_3; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async undeleteContainer(deletedContainerName, deletedContainerVersion, options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-undeleteContainer", options); + try { + const containerClient = this.getContainerClient(options.destinationContainerName || deletedContainerName); + // Hack to access a protected member. + const containerContext = new Container(containerClient["storageClientContext"]); + const containerUndeleteResponse = await containerContext.restore(Object.assign({ deletedContainerName, + deletedContainerVersion }, updatedOptions)); + return { containerClient, containerUndeleteResponse }; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Rename an existing Blob Container. * @@ -40769,40 +36787,29 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param destinationContainerName - The new name of the container. * @param options - Options to configure Container Rename operation. */ + /* eslint-disable-next-line @typescript-eslint/ban-ts-comment */ // @ts-ignore Need to hide this interface for now. Make it public and turn on the live tests for it when the service is ready. - BlobServiceClient.prototype.renameContainer = function (sourceContainerName, destinationContainerName, options) { + async renameContainer(sourceContainerName, destinationContainerName, options = {}) { var _a; - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _b, span, updatedOptions, containerClient, containerContext, containerRenameResponse, e_4; - return tslib.__generator(this, function (_c) { - switch (_c.label) { - case 0: - _b = createSpan("BlobServiceClient-renameContainer", options), span = _b.span, updatedOptions = _b.updatedOptions; - _c.label = 1; - case 1: - _c.trys.push([1, 3, 4, 5]); - containerClient = this.getContainerClient(destinationContainerName); - containerContext = new Container(containerClient["storageClientContext"]); - return [4 /*yield*/, containerContext.rename(sourceContainerName, tslib.__assign(tslib.__assign({}, updatedOptions), { sourceLeaseId: (_a = options.sourceCondition) === null || _a === void 0 ? void 0 : _a.leaseId }))]; - case 2: - containerRenameResponse = _c.sent(); - return [2 /*return*/, { containerClient: containerClient, containerRenameResponse: containerRenameResponse }]; - case 3: - e_4 = _c.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_4.message - }); - throw e_4; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + const { span, updatedOptions } = createSpan("BlobServiceClient-renameContainer", options); + try { + const containerClient = this.getContainerClient(destinationContainerName); + // Hack to access a protected member. + const containerContext = new Container(containerClient["storageClientContext"]); + const containerRenameResponse = await containerContext.rename(sourceContainerName, Object.assign(Object.assign({}, updatedOptions), { sourceLeaseId: (_a = options.sourceCondition) === null || _a === void 0 ? void 0 : _a.leaseId })); + return { containerClient, containerRenameResponse }; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Gets the properties of a storage account’s Blob service, including properties * for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. @@ -40811,34 +36818,22 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param options - Options to the Service Get Properties operation. * @returns Response data for the Service Get Properties operation. */ - BlobServiceClient.prototype.getProperties = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_5; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-getProperties", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getProperties(tslib.__assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_5 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_5.message - }); - throw e_5; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async getProperties(options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-getProperties", options); + try { + return await this.serviceContext.getProperties(Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * 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. @@ -40848,34 +36843,22 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param options - Options to the Service Set Properties operation. * @returns Response data for the Service Set Properties operation. */ - BlobServiceClient.prototype.setProperties = function (properties, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_6; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-setProperties", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.setProperties(properties, tslib.__assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_6 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_6.message - }); - throw e_6; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async setProperties(properties, options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-setProperties", options); + try { + return await this.serviceContext.setProperties(properties, Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Retrieves statistics related to replication for the Blob service. It is only * available on the secondary location endpoint when read-access geo-redundant @@ -40885,34 +36868,22 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param options - Options to the Service Get Statistics operation. * @returns Response data for the Service Get Statistics operation. */ - BlobServiceClient.prototype.getStatistics = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_7; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-getStatistics", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getStatistics(tslib.__assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_7 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_7.message - }); - throw e_7; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async getStatistics(options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-getStatistics", options); + try { + return await this.serviceContext.getStatistics(Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * The Get Account Information operation returns the sku name and account kind * for the specified account. @@ -40923,34 +36894,22 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param options - Options to the Service Get Account Info operation. * @returns Response data for the Service Get Account Info operation. */ - BlobServiceClient.prototype.getAccountInfo = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_8; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-getAccountInfo", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.getAccountInfo(tslib.__assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_8 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_8.message - }); - throw e_8; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async getAccountInfo(options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-getAccountInfo", options); + try { + return await this.serviceContext.getAccountInfo(Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Returns a list of the containers under the specified account. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/list-containers2 @@ -40965,34 +36924,22 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param options - Options to the Service List Container Segment operation. * @returns Response data for the Service List Container Segment operation. */ - BlobServiceClient.prototype.listContainersSegment = function (marker, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, e_9; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-listContainersSegment", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.listContainersSegment(tslib.__assign(tslib.__assign(tslib.__assign({ abortSignal: options.abortSignal, marker: marker }, options), { include: typeof options.include === "string" ? [options.include] : options.include }), convertTracingToRequestOptionsBase(updatedOptions)))]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - e_9 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_9.message - }); - throw e_9; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async listContainersSegment(marker, options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-listContainersSegment", options); + try { + return await this.serviceContext.listContainersSegment(Object.assign(Object.assign(Object.assign({ abortSignal: options.abortSignal, marker }, options), { include: typeof options.include === "string" ? [options.include] : options.include }), convertTracingToRequestOptionsBase(updatedOptions))); + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * 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 @@ -41011,44 +36958,31 @@ var BlobServiceClient = /** @class */ (function (_super) { * items. The marker value is opaque to the client. * @param options - Options to find blobs by tags. */ - BlobServiceClient.prototype.findBlobsByTagsSegment = function (tagFilterSqlExpression, marker, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, response, wrappedResponse, e_10; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-findBlobsByTagsSegment", options), span = _a.span, updatedOptions = _a.updatedOptions; - _b.label = 1; - case 1: - _b.trys.push([1, 3, 4, 5]); - return [4 /*yield*/, this.serviceContext.filterBlobs(tslib.__assign({ abortSignal: options.abortSignal, where: tagFilterSqlExpression, marker: marker, maxPageSize: options.maxPageSize }, convertTracingToRequestOptionsBase(updatedOptions)))]; - 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_10 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_10.message - }); - throw e_10; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async findBlobsByTagsSegment(tagFilterSqlExpression, marker, options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-findBlobsByTagsSegment", options); + try { + const response = await this.serviceContext.filterBlobs(Object.assign({ abortSignal: options.abortSignal, where: tagFilterSqlExpression, marker, maxPageSize: options.maxPageSize }, convertTracingToRequestOptionsBase(updatedOptions))); + const wrappedResponse = Object.assign(Object.assign({}, response), { _response: response._response, blobs: response.blobs.map((blob) => { + var _a; + let tagValue = ""; + if (((_a = blob.tags) === null || _a === void 0 ? void 0 : _a.blobTagSet.length) === 1) { + tagValue = blob.tags.blobTagSet[0].value; + } + return Object.assign(Object.assign({}, blob), { tags: toTags(blob.tags), tagValue }); + }) }); + return wrappedResponse; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Returns an AsyncIterableIterator for ServiceFindBlobsByTagsSegmentResponse. * @@ -41065,33 +36999,19 @@ var BlobServiceClient = /** @class */ (function (_super) { * items. The marker value is opaque to the client. * @param options - Options to find blobs by tags. */ - 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*/]; - } - }); + findBlobsByTagsSegments(tagFilterSqlExpression, marker, options = {}) { + return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsSegments_1() { + let response; + if (!!marker || marker === undefined) { + do { + response = yield tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker, options)); + response.blobs = response.blobs || []; + marker = response.continuationToken; + yield yield tslib.__await(response); + } while (marker); + } }); - }; + } /** * Returns an AsyncIterableIterator for blobs. * @@ -41101,49 +37021,25 @@ var BlobServiceClient = /** @class */ (function (_super) { * however, only a subset of the OData filter syntax is supported in the Blob service. * @param options - Options to findBlobsByTagsItems. */ - 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_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.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_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*/]; + findBlobsByTagsItems(tagFilterSqlExpression, options = {}) { + return tslib.__asyncGenerator(this, arguments, function* findBlobsByTagsItems_1() { + var e_1, _a; + let marker; + try { + for (var _b = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker, options)), _c; _c = yield tslib.__await(_b.next()), !_c.done;) { + const segment = _c.value; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs))); } - }); + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) yield tslib.__await(_a.call(_b)); + } + finally { if (e_1) throw e_1.error; } + } }); - }; + } /** * Returns an async iterable iterator to find all blobs with specified tag * under the specified account. @@ -41223,36 +37119,31 @@ var BlobServiceClient = /** @class */ (function (_super) { * however, only a subset of the OData filter syntax is supported in the Blob service. * @param options - Options to find blobs by tags. */ - BlobServiceClient.prototype.findBlobsByTags = function (tagFilterSqlExpression, options) { - var _a; - var _this = this; - if (options === void 0) { options = {}; } + findBlobsByTags(tagFilterSqlExpression, options = {}) { // AsyncIterableIterator to iterate over blobs - var listSegmentOptions = tslib.__assign({}, options); - var iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); - return _a = { - /** - * The next method, part of the iteration protocol - */ - next: function () { - return iter.next(); - } + const listSegmentOptions = Object.assign({}, options); + const iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ - _a[Symbol.asyncIterator] = function () { + [Symbol.asyncIterator]() { return this; }, /** * 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; - }; + byPage: (settings = {}) => { + return this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + } + }; + } /** * Returns an AsyncIterableIterator for ServiceListContainersSegmentResponses * @@ -41265,83 +37156,44 @@ var BlobServiceClient = /** @class */ (function (_super) { * items. The marker value is opaque to the client. * @param options - Options to list containers operation. */ - 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*/]; - } - }); + listSegments(marker, options = {}) { + return tslib.__asyncGenerator(this, arguments, function* listSegments_1() { + let listContainersSegmentResponse; + if (!!marker || marker === undefined) { + do { + listContainersSegmentResponse = yield tslib.__await(this.listContainersSegment(marker, options)); + listContainersSegmentResponse.containerItems = + listContainersSegmentResponse.containerItems || []; + marker = listContainersSegmentResponse.continuationToken; + yield yield tslib.__await(yield tslib.__await(listContainersSegmentResponse)); + } while (marker); + } }); - }; + } /** * Returns an AsyncIterableIterator for Container Items * * @param options - Options to list containers operation. */ - BlobServiceClient.prototype.listItems = function (options) { - if (options === void 0) { options = {}; } - return tslib.__asyncGenerator(this, arguments, function listItems_1() { - var marker, _a, _b, segment, e_12_1; - var e_12, _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_12_1 = _d.sent(); - e_12 = { error: e_12_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_12) throw e_12.error; - return [7 /*endfinally*/]; - case 12: return [7 /*endfinally*/]; - case 13: return [2 /*return*/]; + listItems(options = {}) { + return tslib.__asyncGenerator(this, arguments, function* listItems_1() { + var e_2, _a; + let marker; + try { + for (var _b = tslib.__asyncValues(this.listSegments(marker, options)), _c; _c = yield tslib.__await(_b.next()), !_c.done;) { + const segment = _c.value; + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(segment.containerItems))); } - }); + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) yield tslib.__await(_a.call(_b)); + } + finally { if (e_2) throw e_2.error; } + } }); - }; + } /** * Returns an async iterable iterator to list all the containers * under the specified account. @@ -41416,14 +37268,11 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param options - Options to list containers. * @returns An asyncIterableIterator that supports paging. */ - BlobServiceClient.prototype.listContainers = function (options) { - var _a; - var _this = this; - if (options === void 0) { options = {}; } + listContainers(options = {}) { if (options.prefix === "") { options.prefix = undefined; } - var include = []; + const include = []; if (options.includeDeleted) { include.push("deleted"); } @@ -41431,31 +37280,29 @@ var BlobServiceClient = /** @class */ (function (_super) { include.push("metadata"); } // AsyncIterableIterator to iterate over containers - var listSegmentOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); - var iter = this.listItems(listSegmentOptions); - return _a = { - /** - * The next method, part of the iteration protocol - */ - next: function () { - return iter.next(); - } + const listSegmentOptions = Object.assign(Object.assign({}, options), (include.length > 0 ? { include } : {})); + const iter = this.listItems(listSegmentOptions); + return { + /** + * The next method, part of the iteration protocol + */ + next() { + return iter.next(); }, /** * The connection to the async iterator, part of the iteration protocol */ - _a[Symbol.asyncIterator] = function () { + [Symbol.asyncIterator]() { return this; }, /** * 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; - }; + byPage: (settings = {}) => { + return this.listSegments(settings.continuationToken, Object.assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); + } + }; + } /** * ONLY AVAILABLE WHEN USING BEARER TOKEN AUTHENTICATION (TokenCredential). * @@ -41467,49 +37314,36 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param startsOn - The start time for the user delegation SAS. Must be within 7 days of the current time * @param expiresOn - The end time for the user delegation SAS. Must be within 7 days of the current time */ - BlobServiceClient.prototype.getUserDelegationKey = function (startsOn, expiresOn, options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, span, updatedOptions, response, userDelegationKey, res, e_13; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = createSpan("BlobServiceClient-getUserDelegationKey", options), span = _a.span, updatedOptions = _a.updatedOptions; - _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) - }, tslib.__assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions)))]; - 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_13 = _b.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: e_13.message - }); - throw e_13; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; - } + async getUserDelegationKey(startsOn, expiresOn, options = {}) { + const { span, updatedOptions } = createSpan("BlobServiceClient-getUserDelegationKey", options); + try { + const response = await this.serviceContext.getUserDelegationKey({ + startsOn: truncatedISO8061Date(startsOn, false), + expiresOn: truncatedISO8061Date(expiresOn, false) + }, Object.assign({ abortSignal: options.abortSignal }, convertTracingToRequestOptionsBase(updatedOptions))); + const 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 + }; + const res = Object.assign({ _response: response._response, requestId: response.requestId, clientRequestId: response.clientRequestId, version: response.version, date: response.date, errorCode: response.errorCode }, userDelegationKey); + return res; + } + catch (e) { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: e.message }); - }); - }; + throw e; + } + finally { + span.end(); + } + } /** * Creates a BlobBatchClient object to conduct batch operations. * @@ -41517,9 +37351,9 @@ var BlobServiceClient = /** @class */ (function (_super) { * * @returns A new BlobBatchClient object for this service. */ - BlobServiceClient.prototype.getBlobBatchClient = function () { + getBlobBatchClient() { return new BlobBatchClient(this.url, this.pipeline); - }; + } /** * Only available for BlobServiceClient constructed with a shared key credential. * @@ -41534,24 +37368,20 @@ var BlobServiceClient = /** @class */ (function (_super) { * @param options - Optional parameters. * @returns An account SAS URI consisting of the URI to the resource represented by this client, followed by the generated SAS token. */ - 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 = {}; } + generateAccountSasUrl(expiresOn, permissions = AccountSASPermissions.parse("r"), resourceTypes = "sco", options = {}) { if (!(this.credential instanceof StorageSharedKeyCredential)) { throw RangeError("Can only generate the account SAS when the client is initialized with a shared key credential"); } if (expiresOn === undefined) { - var now = new Date(); + const now = new Date(); expiresOn = new Date(now.getTime() + 3600 * 1000); } - var sas = generateAccountSASQueryParameters(tslib.__assign({ permissions: permissions, - expiresOn: expiresOn, - resourceTypes: resourceTypes, services: AccountSASServices.parse("b").toString() }, options), this.credential).toString(); + const sas = generateAccountSASQueryParameters(Object.assign({ permissions, + expiresOn, + resourceTypes, services: AccountSASServices.parse("b").toString() }, options), this.credential).toString(); return appendToURLQuery(this.url, sas); - }; - return BlobServiceClient; -}(StorageClient)); + } +} Object.defineProperty(exports, 'BaseRequestPolicy', { enumerable: true, @@ -41618,6 +37448,7 @@ exports.StorageSharedKeyCredential = StorageSharedKeyCredential; exports.StorageSharedKeyCredentialPolicy = StorageSharedKeyCredentialPolicy; exports.generateAccountSASQueryParameters = generateAccountSASQueryParameters; exports.generateBlobSASQueryParameters = generateBlobSASQueryParameters; +exports.isPipelineLike = isPipelineLike; exports.logger = logger; exports.newPipeline = newPipeline; //# sourceMappingURL=index.js.map @@ -41637,119 +37468,77 @@ exports.newPipeline = newPipeline; /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; - -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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Path = void 0; -const path = __importStar(__webpack_require__(622)); -const pathHelper = __importStar(__webpack_require__(972)); -const assert_1 = __importDefault(__webpack_require__(357)); -const IS_WINDOWS = process.platform === 'win32'; -/** - * Helper class for parsing paths into segments +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. */ -class Path { - /** - * Constructs a Path - * @param itemPath Path or array of segments - */ - constructor(itemPath) { - this.segments = []; - // String - if (typeof itemPath === 'string') { - assert_1.default(itemPath, `Parameter 'itemPath' must not be empty`); - // Normalize slashes and trim unnecessary trailing slash - itemPath = pathHelper.safeTrimTrailingSeparator(itemPath); - // Not rooted - if (!pathHelper.hasRoot(itemPath)) { - this.segments = itemPath.split(path.sep); - } - // Rooted - else { - // Add all segments, while not at the root - let remaining = itemPath; - let dir = pathHelper.dirname(remaining); - while (dir !== remaining) { - // Add the segment - const basename = path.basename(remaining); - this.segments.unshift(basename); - // Truncate the last segment - remaining = dir; - dir = pathHelper.dirname(remaining); - } - // Remainder is the root - this.segments.unshift(remaining); - } - } - // Array - else { - // Must not be empty - assert_1.default(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`); - // 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`); - 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`); - this.segments.push(segment); - } - } - } - } - /** - * Converts the path to it's string representation - */ - toString() { - // First segment - let result = this.segments[0]; - // All others - let skipSlash = result.endsWith(path.sep) || (IS_WINDOWS && /^[A-Z]:$/i.test(result)); - for (let i = 1; i < this.segments.length; i++) { - if (skipSlash) { - skipSlash = false; - } - else { - result += path.sep; - } - result += this.segments[i]; - } - return result; + +const pubsuffix = __webpack_require__(519); + +// Gives the permutation of all possible domainMatch()es of a given domain. The +// array is in shortest-to-longest order. Handy for indexing. +const SPECIAL_USE_DOMAINS = ["local"]; // RFC 6761 +function permuteDomain(domain, allowSpecialUseDomain) { + let pubSuf = null; + if (allowSpecialUseDomain) { + const domainParts = domain.split("."); + if (SPECIAL_USE_DOMAINS.includes(domainParts[domainParts.length - 1])) { + pubSuf = `${domainParts[domainParts.length - 2]}.${ + domainParts[domainParts.length - 1] + }`; + } else { + pubSuf = pubsuffix.getPublicSuffix(domain); } + } else { + pubSuf = pubsuffix.getPublicSuffix(domain); + } + + if (!pubSuf) { + return null; + } + if (pubSuf == domain) { + return [domain]; + } + + const prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com" + const parts = prefix.split(".").reverse(); + let cur = pubSuf; + const permutations = [cur]; + while (parts.length) { + cur = `${parts.shift()}.${cur}`; + permutations.push(cur); + } + return permutations; } -exports.Path = Path; -//# sourceMappingURL=internal-path.js.map + +exports.permuteDomain = permuteDomain; + /***/ }), /* 384 */ @@ -42277,6 +38066,7 @@ exports.partialMatch = partialMatch; */ Object.defineProperty(exports, "__esModule", { value: true }); exports.DiagAPI = void 0; +var ComponentLogger_1 = __webpack_require__(362); var logLevelLogger_1 = __webpack_require__(673); var types_1 = __webpack_require__(545); var global_utils_1 = __webpack_require__(525); @@ -42307,7 +38097,7 @@ var DiagAPI = /** @class */ (function () { var self = this; // DiagAPI specific functions self.setLogger = function (logger, logLevel) { - var _a; + var _a, _b; if (logLevel === void 0) { logLevel = types_1.DiagLogLevel.INFO; } if (logger === self) { // There isn't much we can do here. @@ -42315,12 +38105,23 @@ var DiagAPI = /** @class */ (function () { // Try to log to self. If a logger was previously registered it will receive the log. var err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message); - return; + return false; } - global_utils_1.registerGlobal('diag', logLevelLogger_1.createLogLevelDiagLogger(logLevel, logger), true); + var oldLogger = global_utils_1.getGlobal('diag'); + var newLogger = logLevelLogger_1.createLogLevelDiagLogger(logLevel, logger); + // There already is an logger registered. We'll let it know before overwriting it. + if (oldLogger) { + var stack = (_b = new Error().stack) !== null && _b !== void 0 ? _b : ''; + oldLogger.warn("Current logger will be overwritten from " + stack); + newLogger.warn("Current logger will overwrite one already registered from " + stack); + } + return global_utils_1.registerGlobal('diag', newLogger, self, true); }; self.disable = function () { - global_utils_1.unregisterGlobal(API_NAME); + global_utils_1.unregisterGlobal(API_NAME, self); + }; + self.createComponentLogger = function (options) { + return new ComponentLogger_1.DiagComponentLogger(options); }; self.verbose = _logProxy('verbose'); self.debug = _logProxy('debug'); @@ -42412,1684 +38213,7 @@ exports.getUserAgent = getUserAgent; /***/ }), -/* 393 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; -/*! - * Copyright (c) 2015, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of Salesforce.com nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -const punycode = __webpack_require__(815); -const urlParse = __webpack_require__(835).parse; -const util = __webpack_require__(669); -const pubsuffix = __webpack_require__(324); -const Store = __webpack_require__(338).Store; -const MemoryCookieStore = __webpack_require__(332).MemoryCookieStore; -const pathMatch = __webpack_require__(678).pathMatch; -const VERSION = __webpack_require__(460); -const { fromCallback } = __webpack_require__(147); - -// From RFC6265 S4.1.1 -// note that it excludes \x3B ";" -const COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/; - -const CONTROL_CHARS = /[\x00-\x1F]/; - -// From Chromium // '\r', '\n' and '\0' should be treated as a terminator in -// the "relaxed" mode, see: -// https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60 -const TERMINATORS = ["\n", "\r", "\0"]; - -// RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"' -// Note ';' is \x3B -const PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/; - -// date-time parsing constants (RFC6265 S5.1.1) - -const DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/; - -const MONTH_TO_NUM = { - jan: 0, - feb: 1, - mar: 2, - apr: 3, - may: 4, - jun: 5, - jul: 6, - aug: 7, - sep: 8, - oct: 9, - nov: 10, - dec: 11 -}; - -const MAX_TIME = 2147483647000; // 31-bit max -const MIN_TIME = 0; // 31-bit min -const SAME_SITE_CONTEXT_VAL_ERR = - 'Invalid sameSiteContext option for getCookies(); expected one of "strict", "lax", or "none"'; - -function checkSameSiteContext(value) { - const context = String(value).toLowerCase(); - if (context === "none" || context === "lax" || context === "strict") { - return context; - } else { - return null; - } -} - -const PrefixSecurityEnum = Object.freeze({ - SILENT: "silent", - STRICT: "strict", - DISABLED: "unsafe-disabled" -}); - -// Dumped from ip-regex@4.0.0, with the following changes: -// * all capturing groups converted to non-capturing -- "(?:)" -// * support for IPv6 Scoped Literal ("%eth1") removed -// * lowercase hexadecimal only -var IP_REGEX_LOWERCASE =/(?:^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$)|(?:^(?:(?:[a-f\d]{1,4}:){7}(?:[a-f\d]{1,4}|:)|(?:[a-f\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|:[a-f\d]{1,4}|:)|(?:[a-f\d]{1,4}:){5}(?::(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,2}|:)|(?:[a-f\d]{1,4}:){4}(?:(?::[a-f\d]{1,4}){0,1}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,3}|:)|(?:[a-f\d]{1,4}:){3}(?:(?::[a-f\d]{1,4}){0,2}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,4}|:)|(?:[a-f\d]{1,4}:){2}(?:(?::[a-f\d]{1,4}){0,3}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,5}|:)|(?:[a-f\d]{1,4}:){1}(?:(?::[a-f\d]{1,4}){0,4}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,6}|:)|(?::(?:(?::[a-f\d]{1,4}){0,5}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,7}|:)))$)/; - -/* - * Parses a Natural number (i.e., non-negative integer) with either the - * *DIGIT ( non-digit *OCTET ) - * or - * *DIGIT - * grammar (RFC6265 S5.1.1). - * - * The "trailingOK" boolean controls if the grammar accepts a - * "( non-digit *OCTET )" trailer. - */ -function parseDigits(token, minDigits, maxDigits, trailingOK) { - let count = 0; - while (count < token.length) { - const c = token.charCodeAt(count); - // "non-digit = %x00-2F / %x3A-FF" - if (c <= 0x2f || c >= 0x3a) { - break; - } - count++; - } - - // constrain to a minimum and maximum number of digits. - if (count < minDigits || count > maxDigits) { - return null; - } - - if (!trailingOK && count != token.length) { - return null; - } - - return parseInt(token.substr(0, count), 10); -} - -function parseTime(token) { - const parts = token.split(":"); - const result = [0, 0, 0]; - - /* RF6256 S5.1.1: - * time = hms-time ( non-digit *OCTET ) - * hms-time = time-field ":" time-field ":" time-field - * time-field = 1*2DIGIT - */ - - if (parts.length !== 3) { - return null; - } - - for (let i = 0; i < 3; i++) { - // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be - // followed by "( non-digit *OCTET )" so therefore the last time-field can - // have a trailer - const trailingOK = i == 2; - const num = parseDigits(parts[i], 1, 2, trailingOK); - if (num === null) { - return null; - } - result[i] = num; - } - - return result; -} - -function parseMonth(token) { - token = String(token) - .substr(0, 3) - .toLowerCase(); - const num = MONTH_TO_NUM[token]; - return num >= 0 ? num : null; -} - -/* - * RFC6265 S5.1.1 date parser (see RFC for full grammar) - */ -function parseDate(str) { - if (!str) { - return; - } - - /* RFC6265 S5.1.1: - * 2. Process each date-token sequentially in the order the date-tokens - * appear in the cookie-date - */ - const tokens = str.split(DATE_DELIM); - if (!tokens) { - return; - } - - let hour = null; - let minute = null; - let second = null; - let dayOfMonth = null; - let month = null; - let year = null; - - for (let i = 0; i < tokens.length; i++) { - const token = tokens[i].trim(); - if (!token.length) { - continue; - } - - let result; - - /* 2.1. If the found-time flag is not set and the token matches the time - * production, set the found-time flag and set the hour- value, - * minute-value, and second-value to the numbers denoted by the digits in - * the date-token, respectively. Skip the remaining sub-steps and continue - * to the next date-token. - */ - if (second === null) { - result = parseTime(token); - if (result) { - hour = result[0]; - minute = result[1]; - second = result[2]; - continue; - } - } - - /* 2.2. If the found-day-of-month flag is not set and the date-token matches - * the day-of-month production, set the found-day-of- month flag and set - * the day-of-month-value to the number denoted by the date-token. Skip - * the remaining sub-steps and continue to the next date-token. - */ - if (dayOfMonth === null) { - // "day-of-month = 1*2DIGIT ( non-digit *OCTET )" - result = parseDigits(token, 1, 2, true); - if (result !== null) { - dayOfMonth = result; - continue; - } - } - - /* 2.3. If the found-month flag is not set and the date-token matches the - * month production, set the found-month flag and set the month-value to - * the month denoted by the date-token. Skip the remaining sub-steps and - * continue to the next date-token. - */ - if (month === null) { - result = parseMonth(token); - if (result !== null) { - month = result; - continue; - } - } - - /* 2.4. If the found-year flag is not set and the date-token matches the - * year production, set the found-year flag and set the year-value to the - * number denoted by the date-token. Skip the remaining sub-steps and - * continue to the next date-token. - */ - if (year === null) { - // "year = 2*4DIGIT ( non-digit *OCTET )" - result = parseDigits(token, 2, 4, true); - if (result !== null) { - year = result; - /* From S5.1.1: - * 3. If the year-value is greater than or equal to 70 and less - * than or equal to 99, increment the year-value by 1900. - * 4. If the year-value is greater than or equal to 0 and less - * than or equal to 69, increment the year-value by 2000. - */ - if (year >= 70 && year <= 99) { - year += 1900; - } else if (year >= 0 && year <= 69) { - year += 2000; - } - } - } - } - - /* RFC 6265 S5.1.1 - * "5. Abort these steps and fail to parse the cookie-date if: - * * at least one of the found-day-of-month, found-month, found- - * year, or found-time flags is not set, - * * the day-of-month-value is less than 1 or greater than 31, - * * the year-value is less than 1601, - * * the hour-value is greater than 23, - * * the minute-value is greater than 59, or - * * the second-value is greater than 59. - * (Note that leap seconds cannot be represented in this syntax.)" - * - * So, in order as above: - */ - if ( - dayOfMonth === null || - month === null || - year === null || - second === null || - dayOfMonth < 1 || - dayOfMonth > 31 || - year < 1601 || - hour > 23 || - minute > 59 || - second > 59 - ) { - return; - } - - return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second)); -} - -function formatDate(date) { - return date.toUTCString(); -} - -// S5.1.2 Canonicalized Host Names -function canonicalDomain(str) { - if (str == null) { - return null; - } - str = str.trim().replace(/^\./, ""); // S4.1.2.3 & S5.2.3: ignore leading . - - // convert to IDN if any non-ASCII characters - if (punycode && /[^\u0001-\u007f]/.test(str)) { - str = punycode.toASCII(str); - } - - return str.toLowerCase(); -} - -// S5.1.3 Domain Matching -function domainMatch(str, domStr, canonicalize) { - if (str == null || domStr == null) { - return null; - } - if (canonicalize !== false) { - str = canonicalDomain(str); - domStr = canonicalDomain(domStr); - } - - /* - * S5.1.3: - * "A string domain-matches a given domain string if at least one of the - * following conditions hold:" - * - * " o The domain string and the string are identical. (Note that both the - * domain string and the string will have been canonicalized to lower case at - * this point)" - */ - if (str == domStr) { - return true; - } - - /* " o All of the following [three] conditions hold:" */ - - /* "* The domain string is a suffix of the string" */ - const idx = str.indexOf(domStr); - if (idx <= 0) { - return false; // it's a non-match (-1) or prefix (0) - } - - // next, check it's a proper suffix - // e.g., "a.b.c".indexOf("b.c") === 2 - // 5 === 3+2 - if (str.length !== domStr.length + idx) { - return false; // it's not a suffix - } - - /* " * The last character of the string that is not included in the - * domain string is a %x2E (".") character." */ - if (str.substr(idx-1,1) !== '.') { - return false; // doesn't align on "." - } - - /* " * The string is a host name (i.e., not an IP address)." */ - if (IP_REGEX_LOWERCASE.test(str)) { - return false; // it's an IP address - } - - return true; -} - -// RFC6265 S5.1.4 Paths and Path-Match - -/* - * "The user agent MUST use an algorithm equivalent to the following algorithm - * to compute the default-path of a cookie:" - * - * Assumption: the path (and not query part or absolute uri) is passed in. - */ -function defaultPath(path) { - // "2. If the uri-path is empty or if the first character of the uri-path is not - // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps. - if (!path || path.substr(0, 1) !== "/") { - return "/"; - } - - // "3. If the uri-path contains no more than one %x2F ("/") character, output - // %x2F ("/") and skip the remaining step." - if (path === "/") { - return path; - } - - const rightSlash = path.lastIndexOf("/"); - if (rightSlash === 0) { - return "/"; - } - - // "4. Output the characters of the uri-path from the first character up to, - // but not including, the right-most %x2F ("/")." - return path.slice(0, rightSlash); -} - -function trimTerminator(str) { - for (let t = 0; t < TERMINATORS.length; t++) { - const terminatorIdx = str.indexOf(TERMINATORS[t]); - if (terminatorIdx !== -1) { - str = str.substr(0, terminatorIdx); - } - } - - return str; -} - -function parseCookiePair(cookiePair, looseMode) { - cookiePair = trimTerminator(cookiePair); - - let firstEq = cookiePair.indexOf("="); - if (looseMode) { - if (firstEq === 0) { - // '=' is immediately at start - cookiePair = cookiePair.substr(1); - firstEq = cookiePair.indexOf("="); // might still need to split on '=' - } - } else { - // non-loose mode - if (firstEq <= 0) { - // no '=' or is at start - return; // needs to have non-empty "cookie-name" - } - } - - let cookieName, cookieValue; - if (firstEq <= 0) { - cookieName = ""; - cookieValue = cookiePair.trim(); - } else { - cookieName = cookiePair.substr(0, firstEq).trim(); - cookieValue = cookiePair.substr(firstEq + 1).trim(); - } - - if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) { - return; - } - - const c = new Cookie(); - c.key = cookieName; - c.value = cookieValue; - return c; -} - -function parse(str, options) { - if (!options || typeof options !== "object") { - options = {}; - } - str = str.trim(); - - // We use a regex to parse the "name-value-pair" part of S5.2 - const firstSemi = str.indexOf(";"); // S5.2 step 1 - const cookiePair = firstSemi === -1 ? str : str.substr(0, firstSemi); - const c = parseCookiePair(cookiePair, !!options.loose); - if (!c) { - return; - } - - if (firstSemi === -1) { - return c; - } - - // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string - // (including the %x3B (";") in question)." plus later on in the same section - // "discard the first ";" and trim". - const unparsed = str.slice(firstSemi + 1).trim(); - - // "If the unparsed-attributes string is empty, skip the rest of these - // steps." - if (unparsed.length === 0) { - return c; - } - - /* - * S5.2 says that when looping over the items "[p]rocess the attribute-name - * and attribute-value according to the requirements in the following - * subsections" for every item. Plus, for many of the individual attributes - * in S5.3 it says to use the "attribute-value of the last attribute in the - * cookie-attribute-list". Therefore, in this implementation, we overwrite - * the previous value. - */ - const cookie_avs = unparsed.split(";"); - while (cookie_avs.length) { - const av = cookie_avs.shift().trim(); - if (av.length === 0) { - // happens if ";;" appears - continue; - } - const av_sep = av.indexOf("="); - let av_key, av_value; - - if (av_sep === -1) { - av_key = av; - av_value = null; - } else { - av_key = av.substr(0, av_sep); - av_value = av.substr(av_sep + 1); - } - - av_key = av_key.trim().toLowerCase(); - - if (av_value) { - av_value = av_value.trim(); - } - - switch (av_key) { - case "expires": // S5.2.1 - if (av_value) { - const exp = parseDate(av_value); - // "If the attribute-value failed to parse as a cookie date, ignore the - // cookie-av." - if (exp) { - // over and underflow not realistically a concern: V8's getTime() seems to - // store something larger than a 32-bit time_t (even with 32-bit node) - c.expires = exp; - } - } - break; - - case "max-age": // S5.2.2 - if (av_value) { - // "If the first character of the attribute-value is not a DIGIT or a "-" - // character ...[or]... If the remainder of attribute-value contains a - // non-DIGIT character, ignore the cookie-av." - if (/^-?[0-9]+$/.test(av_value)) { - const delta = parseInt(av_value, 10); - // "If delta-seconds is less than or equal to zero (0), let expiry-time - // be the earliest representable date and time." - c.setMaxAge(delta); - } - } - break; - - case "domain": // S5.2.3 - // "If the attribute-value is empty, the behavior is undefined. However, - // the user agent SHOULD ignore the cookie-av entirely." - if (av_value) { - // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E - // (".") character." - const domain = av_value.trim().replace(/^\./, ""); - if (domain) { - // "Convert the cookie-domain to lower case." - c.domain = domain.toLowerCase(); - } - } - break; - - case "path": // S5.2.4 - /* - * "If the attribute-value is empty or if the first character of the - * attribute-value is not %x2F ("/"): - * Let cookie-path be the default-path. - * Otherwise: - * Let cookie-path be the attribute-value." - * - * We'll represent the default-path as null since it depends on the - * context of the parsing. - */ - c.path = av_value && av_value[0] === "/" ? av_value : null; - break; - - case "secure": // S5.2.5 - /* - * "If the attribute-name case-insensitively matches the string "Secure", - * the user agent MUST append an attribute to the cookie-attribute-list - * with an attribute-name of Secure and an empty attribute-value." - */ - c.secure = true; - break; - - case "httponly": // S5.2.6 -- effectively the same as 'secure' - c.httpOnly = true; - break; - - case "samesite": // RFC6265bis-02 S5.3.7 - const enforcement = av_value ? av_value.toLowerCase() : ""; - switch (enforcement) { - case "strict": - c.sameSite = "strict"; - break; - case "lax": - c.sameSite = "lax"; - break; - default: - // RFC6265bis-02 S5.3.7 step 1: - // "If cookie-av's attribute-value is not a case-insensitive match - // for "Strict" or "Lax", ignore the "cookie-av"." - // This effectively sets it to 'none' from the prototype. - break; - } - break; - - default: - c.extensions = c.extensions || []; - c.extensions.push(av); - break; - } - } - - return c; -} - -/** - * If the cookie-name begins with a case-sensitive match for the - * string "__Secure-", abort these steps and ignore the cookie - * entirely unless the cookie's secure-only-flag is true. - * @param cookie - * @returns boolean - */ -function isSecurePrefixConditionMet(cookie) { - return !cookie.key.startsWith("__Secure-") || cookie.secure; -} - -/** - * If the cookie-name begins with a case-sensitive match for the - * string "__Host-", abort these steps and ignore the cookie - * entirely unless the cookie meets all the following criteria: - * 1. The cookie's secure-only-flag is true. - * 2. The cookie's host-only-flag is true. - * 3. The cookie-attribute-list contains an attribute with an - * attribute-name of "Path", and the cookie's path is "/". - * @param cookie - * @returns boolean - */ -function isHostPrefixConditionMet(cookie) { - return ( - !cookie.key.startsWith("__Host-") || - (cookie.secure && - cookie.hostOnly && - cookie.path != null && - cookie.path === "/") - ); -} - -// avoid the V8 deoptimization monster! -function jsonParse(str) { - let obj; - try { - obj = JSON.parse(str); - } catch (e) { - return e; - } - return obj; -} - -function fromJSON(str) { - if (!str) { - return null; - } - - let obj; - if (typeof str === "string") { - obj = jsonParse(str); - if (obj instanceof Error) { - return null; - } - } else { - // assume it's an Object - obj = str; - } - - const c = new Cookie(); - for (let i = 0; i < Cookie.serializableProperties.length; i++) { - const prop = Cookie.serializableProperties[i]; - if (obj[prop] === undefined || obj[prop] === cookieDefaults[prop]) { - continue; // leave as prototype default - } - - if (prop === "expires" || prop === "creation" || prop === "lastAccessed") { - if (obj[prop] === null) { - c[prop] = null; - } else { - c[prop] = obj[prop] == "Infinity" ? "Infinity" : new Date(obj[prop]); - } - } else { - c[prop] = obj[prop]; - } - } - - return c; -} - -/* Section 5.4 part 2: - * "* Cookies with longer paths are listed before cookies with - * shorter paths. - * - * * Among cookies that have equal-length path fields, cookies with - * earlier creation-times are listed before cookies with later - * creation-times." - */ - -function cookieCompare(a, b) { - let cmp = 0; - - // descending for length: b CMP a - const aPathLen = a.path ? a.path.length : 0; - const bPathLen = b.path ? b.path.length : 0; - cmp = bPathLen - aPathLen; - if (cmp !== 0) { - return cmp; - } - - // ascending for time: a CMP b - const aTime = a.creation ? a.creation.getTime() : MAX_TIME; - const bTime = b.creation ? b.creation.getTime() : MAX_TIME; - cmp = aTime - bTime; - if (cmp !== 0) { - return cmp; - } - - // break ties for the same millisecond (precision of JavaScript's clock) - cmp = a.creationIndex - b.creationIndex; - - return cmp; -} - -// Gives the permutation of all possible pathMatch()es of a given path. The -// array is in longest-to-shortest order. Handy for indexing. -function permutePath(path) { - if (path === "/") { - return ["/"]; - } - const permutations = [path]; - while (path.length > 1) { - const lindex = path.lastIndexOf("/"); - if (lindex === 0) { - break; - } - path = path.substr(0, lindex); - permutations.push(path); - } - permutations.push("/"); - return permutations; -} - -function getCookieContext(url) { - if (url instanceof Object) { - return url; - } - // NOTE: decodeURI will throw on malformed URIs (see GH-32). - // Therefore, we will just skip decoding for such URIs. - try { - url = decodeURI(url); - } catch (err) { - // Silently swallow error - } - - return urlParse(url); -} - -const cookieDefaults = { - // the order in which the RFC has them: - key: "", - value: "", - expires: "Infinity", - maxAge: null, - domain: null, - path: null, - secure: false, - httpOnly: false, - extensions: null, - // set by the CookieJar: - hostOnly: null, - pathIsDefault: null, - creation: null, - lastAccessed: null, - sameSite: "none" -}; - -class Cookie { - constructor(options = {}) { - if (util.inspect.custom) { - this[util.inspect.custom] = this.inspect; - } - - Object.assign(this, cookieDefaults, options); - this.creation = this.creation || new Date(); - - // used to break creation ties in cookieCompare(): - Object.defineProperty(this, "creationIndex", { - configurable: false, - enumerable: false, // important for assert.deepEqual checks - writable: true, - value: ++Cookie.cookiesCreated - }); - } - - inspect() { - const now = Date.now(); - const hostOnly = this.hostOnly != null ? this.hostOnly : "?"; - const createAge = this.creation - ? `${now - this.creation.getTime()}ms` - : "?"; - const accessAge = this.lastAccessed - ? `${now - this.lastAccessed.getTime()}ms` - : "?"; - return `Cookie="${this.toString()}; hostOnly=${hostOnly}; aAge=${accessAge}; cAge=${createAge}"`; - } - - toJSON() { - const obj = {}; - - for (const prop of Cookie.serializableProperties) { - if (this[prop] === cookieDefaults[prop]) { - continue; // leave as prototype default - } - - if ( - prop === "expires" || - prop === "creation" || - prop === "lastAccessed" - ) { - if (this[prop] === null) { - obj[prop] = null; - } else { - obj[prop] = - this[prop] == "Infinity" // intentionally not === - ? "Infinity" - : this[prop].toISOString(); - } - } else if (prop === "maxAge") { - if (this[prop] !== null) { - // again, intentionally not === - obj[prop] = - this[prop] == Infinity || this[prop] == -Infinity - ? this[prop].toString() - : this[prop]; - } - } else { - if (this[prop] !== cookieDefaults[prop]) { - obj[prop] = this[prop]; - } - } - } - - return obj; - } - - clone() { - return fromJSON(this.toJSON()); - } - - validate() { - if (!COOKIE_OCTETS.test(this.value)) { - return false; - } - if ( - this.expires != Infinity && - !(this.expires instanceof Date) && - !parseDate(this.expires) - ) { - return false; - } - if (this.maxAge != null && this.maxAge <= 0) { - return false; // "Max-Age=" non-zero-digit *DIGIT - } - if (this.path != null && !PATH_VALUE.test(this.path)) { - return false; - } - - const cdomain = this.cdomain(); - if (cdomain) { - if (cdomain.match(/\.$/)) { - return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this - } - const suffix = pubsuffix.getPublicSuffix(cdomain); - if (suffix == null) { - // it's a public suffix - return false; - } - } - return true; - } - - setExpires(exp) { - if (exp instanceof Date) { - this.expires = exp; - } else { - this.expires = parseDate(exp) || "Infinity"; - } - } - - setMaxAge(age) { - if (age === Infinity || age === -Infinity) { - this.maxAge = age.toString(); // so JSON.stringify() works - } else { - this.maxAge = age; - } - } - - cookieString() { - let val = this.value; - if (val == null) { - val = ""; - } - if (this.key === "") { - return val; - } - return `${this.key}=${val}`; - } - - // gives Set-Cookie header format - toString() { - let str = this.cookieString(); - - if (this.expires != Infinity) { - if (this.expires instanceof Date) { - str += `; Expires=${formatDate(this.expires)}`; - } else { - str += `; Expires=${this.expires}`; - } - } - - if (this.maxAge != null && this.maxAge != Infinity) { - str += `; Max-Age=${this.maxAge}`; - } - - if (this.domain && !this.hostOnly) { - str += `; Domain=${this.domain}`; - } - if (this.path) { - str += `; Path=${this.path}`; - } - - if (this.secure) { - str += "; Secure"; - } - if (this.httpOnly) { - str += "; HttpOnly"; - } - if (this.sameSite && this.sameSite !== "none") { - const ssCanon = Cookie.sameSiteCanonical[this.sameSite.toLowerCase()]; - str += `; SameSite=${ssCanon ? ssCanon : this.sameSite}`; - } - if (this.extensions) { - this.extensions.forEach(ext => { - str += `; ${ext}`; - }); - } - - return str; - } - - // TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie() - // elsewhere) - // S5.3 says to give the "latest representable date" for which we use Infinity - // For "expired" we use 0 - TTL(now) { - /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires - * attribute, the Max-Age attribute has precedence and controls the - * expiration date of the cookie. - * (Concurs with S5.3 step 3) - */ - if (this.maxAge != null) { - return this.maxAge <= 0 ? 0 : this.maxAge * 1000; - } - - let expires = this.expires; - if (expires != Infinity) { - if (!(expires instanceof Date)) { - expires = parseDate(expires) || Infinity; - } - - if (expires == Infinity) { - return Infinity; - } - - return expires.getTime() - (now || Date.now()); - } - - return Infinity; - } - - // expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() - // elsewhere) - expiryTime(now) { - if (this.maxAge != null) { - const relativeTo = now || this.creation || new Date(); - const age = this.maxAge <= 0 ? -Infinity : this.maxAge * 1000; - return relativeTo.getTime() + age; - } - - if (this.expires == Infinity) { - return Infinity; - } - return this.expires.getTime(); - } - - // expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() - // elsewhere), except it returns a Date - expiryDate(now) { - const millisec = this.expiryTime(now); - if (millisec == Infinity) { - return new Date(MAX_TIME); - } else if (millisec == -Infinity) { - return new Date(MIN_TIME); - } else { - return new Date(millisec); - } - } - - // This replaces the "persistent-flag" parts of S5.3 step 3 - isPersistent() { - return this.maxAge != null || this.expires != Infinity; - } - - // Mostly S5.1.2 and S5.2.3: - canonicalizedDomain() { - if (this.domain == null) { - return null; - } - return canonicalDomain(this.domain); - } - - cdomain() { - return this.canonicalizedDomain(); - } -} - -Cookie.cookiesCreated = 0; -Cookie.parse = parse; -Cookie.fromJSON = fromJSON; -Cookie.serializableProperties = Object.keys(cookieDefaults); -Cookie.sameSiteLevel = { - strict: 3, - lax: 2, - none: 1 -}; - -Cookie.sameSiteCanonical = { - strict: "Strict", - lax: "Lax" -}; - -function getNormalizedPrefixSecurity(prefixSecurity) { - if (prefixSecurity != null) { - const normalizedPrefixSecurity = prefixSecurity.toLowerCase(); - /* The three supported options */ - switch (normalizedPrefixSecurity) { - case PrefixSecurityEnum.STRICT: - case PrefixSecurityEnum.SILENT: - case PrefixSecurityEnum.DISABLED: - return normalizedPrefixSecurity; - } - } - /* Default is SILENT */ - return PrefixSecurityEnum.SILENT; -} - -class CookieJar { - constructor(store, options = { rejectPublicSuffixes: true }) { - if (typeof options === "boolean") { - options = { rejectPublicSuffixes: options }; - } - this.rejectPublicSuffixes = options.rejectPublicSuffixes; - this.enableLooseMode = !!options.looseMode; - this.allowSpecialUseDomain = !!options.allowSpecialUseDomain; - this.store = store || new MemoryCookieStore(); - this.prefixSecurity = getNormalizedPrefixSecurity(options.prefixSecurity); - this._cloneSync = syncWrap("clone"); - this._importCookiesSync = syncWrap("_importCookies"); - this.getCookiesSync = syncWrap("getCookies"); - this.getCookieStringSync = syncWrap("getCookieString"); - this.getSetCookieStringsSync = syncWrap("getSetCookieStrings"); - this.removeAllCookiesSync = syncWrap("removeAllCookies"); - this.setCookieSync = syncWrap("setCookie"); - this.serializeSync = syncWrap("serialize"); - } - - setCookie(cookie, url, options, cb) { - let err; - const context = getCookieContext(url); - if (typeof options === "function") { - cb = options; - options = {}; - } - - const host = canonicalDomain(context.hostname); - const loose = options.loose || this.enableLooseMode; - - let sameSiteContext = null; - if (options.sameSiteContext) { - sameSiteContext = checkSameSiteContext(options.sameSiteContext); - if (!sameSiteContext) { - return cb(new Error(SAME_SITE_CONTEXT_VAL_ERR)); - } - } - - // S5.3 step 1 - if (typeof cookie === "string" || cookie instanceof String) { - cookie = Cookie.parse(cookie, { loose: loose }); - if (!cookie) { - err = new Error("Cookie failed to parse"); - return cb(options.ignoreError ? null : err); - } - } else if (!(cookie instanceof Cookie)) { - // If you're seeing this error, and are passing in a Cookie object, - // it *might* be a Cookie object from another loaded version of tough-cookie. - err = new Error( - "First argument to setCookie must be a Cookie object or string" - ); - return cb(options.ignoreError ? null : err); - } - - // S5.3 step 2 - const now = options.now || new Date(); // will assign later to save effort in the face of errors - - // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie() - - // S5.3 step 4: NOOP; domain is null by default - - // S5.3 step 5: public suffixes - if (this.rejectPublicSuffixes && cookie.domain) { - const suffix = pubsuffix.getPublicSuffix(cookie.cdomain()); - if (suffix == null) { - // e.g. "com" - err = new Error("Cookie has domain set to a public suffix"); - return cb(options.ignoreError ? null : err); - } - } - - // S5.3 step 6: - if (cookie.domain) { - if (!domainMatch(host, cookie.cdomain(), false)) { - err = new Error( - `Cookie not in this host's domain. Cookie:${cookie.cdomain()} Request:${host}` - ); - return cb(options.ignoreError ? null : err); - } - - if (cookie.hostOnly == null) { - // don't reset if already set - cookie.hostOnly = false; - } - } else { - cookie.hostOnly = true; - cookie.domain = host; - } - - //S5.2.4 If the attribute-value is empty or if the first character of the - //attribute-value is not %x2F ("/"): - //Let cookie-path be the default-path. - if (!cookie.path || cookie.path[0] !== "/") { - cookie.path = defaultPath(context.pathname); - cookie.pathIsDefault = true; - } - - // S5.3 step 8: NOOP; secure attribute - // S5.3 step 9: NOOP; httpOnly attribute - - // S5.3 step 10 - if (options.http === false && cookie.httpOnly) { - err = new Error("Cookie is HttpOnly and this isn't an HTTP API"); - return cb(options.ignoreError ? null : err); - } - - // 6252bis-02 S5.4 Step 13 & 14: - if (cookie.sameSite !== "none" && sameSiteContext) { - // "If the cookie's "same-site-flag" is not "None", and the cookie - // is being set from a context whose "site for cookies" is not an - // exact match for request-uri's host's registered domain, then - // abort these steps and ignore the newly created cookie entirely." - if (sameSiteContext === "none") { - err = new Error( - "Cookie is SameSite but this is a cross-origin request" - ); - return cb(options.ignoreError ? null : err); - } - } - - /* 6265bis-02 S5.4 Steps 15 & 16 */ - const ignoreErrorForPrefixSecurity = - this.prefixSecurity === PrefixSecurityEnum.SILENT; - const prefixSecurityDisabled = - this.prefixSecurity === PrefixSecurityEnum.DISABLED; - /* If prefix checking is not disabled ...*/ - if (!prefixSecurityDisabled) { - let errorFound = false; - let errorMsg; - /* Check secure prefix condition */ - if (!isSecurePrefixConditionMet(cookie)) { - errorFound = true; - errorMsg = "Cookie has __Secure prefix but Secure attribute is not set"; - } else if (!isHostPrefixConditionMet(cookie)) { - /* Check host prefix condition */ - errorFound = true; - errorMsg = - "Cookie has __Host prefix but either Secure or HostOnly attribute is not set or Path is not '/'"; - } - if (errorFound) { - return cb( - options.ignoreError || ignoreErrorForPrefixSecurity - ? null - : new Error(errorMsg) - ); - } - } - - const store = this.store; - - if (!store.updateCookie) { - store.updateCookie = function(oldCookie, newCookie, cb) { - this.putCookie(newCookie, cb); - }; - } - - function withCookie(err, oldCookie) { - if (err) { - return cb(err); - } - - const next = function(err) { - if (err) { - return cb(err); - } else { - cb(null, cookie); - } - }; - - if (oldCookie) { - // S5.3 step 11 - "If the cookie store contains a cookie with the same name, - // domain, and path as the newly created cookie:" - if (options.http === false && oldCookie.httpOnly) { - // step 11.2 - err = new Error("old Cookie is HttpOnly and this isn't an HTTP API"); - return cb(options.ignoreError ? null : err); - } - cookie.creation = oldCookie.creation; // step 11.3 - cookie.creationIndex = oldCookie.creationIndex; // preserve tie-breaker - cookie.lastAccessed = now; - // Step 11.4 (delete cookie) is implied by just setting the new one: - store.updateCookie(oldCookie, cookie, next); // step 12 - } else { - cookie.creation = cookie.lastAccessed = now; - store.putCookie(cookie, next); // step 12 - } - } - - store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie); - } - - // RFC6365 S5.4 - getCookies(url, options, cb) { - const context = getCookieContext(url); - if (typeof options === "function") { - cb = options; - options = {}; - } - - const host = canonicalDomain(context.hostname); - const path = context.pathname || "/"; - - let secure = options.secure; - if ( - secure == null && - context.protocol && - (context.protocol == "https:" || context.protocol == "wss:") - ) { - secure = true; - } - - let sameSiteLevel = 0; - if (options.sameSiteContext) { - const sameSiteContext = checkSameSiteContext(options.sameSiteContext); - sameSiteLevel = Cookie.sameSiteLevel[sameSiteContext]; - if (!sameSiteLevel) { - return cb(new Error(SAME_SITE_CONTEXT_VAL_ERR)); - } - } - - let http = options.http; - if (http == null) { - http = true; - } - - const now = options.now || Date.now(); - const expireCheck = options.expire !== false; - const allPaths = !!options.allPaths; - const store = this.store; - - function matchingCookie(c) { - // "Either: - // The cookie's host-only-flag is true and the canonicalized - // request-host is identical to the cookie's domain. - // Or: - // The cookie's host-only-flag is false and the canonicalized - // request-host domain-matches the cookie's domain." - if (c.hostOnly) { - if (c.domain != host) { - return false; - } - } else { - if (!domainMatch(host, c.domain, false)) { - return false; - } - } - - // "The request-uri's path path-matches the cookie's path." - if (!allPaths && !pathMatch(path, c.path)) { - return false; - } - - // "If the cookie's secure-only-flag is true, then the request-uri's - // scheme must denote a "secure" protocol" - if (c.secure && !secure) { - return false; - } - - // "If the cookie's http-only-flag is true, then exclude the cookie if the - // cookie-string is being generated for a "non-HTTP" API" - if (c.httpOnly && !http) { - return false; - } - - // RFC6265bis-02 S5.3.7 - if (sameSiteLevel) { - const cookieLevel = Cookie.sameSiteLevel[c.sameSite || "none"]; - if (cookieLevel > sameSiteLevel) { - // only allow cookies at or below the request level - return false; - } - } - - // deferred from S5.3 - // non-RFC: allow retention of expired cookies by choice - if (expireCheck && c.expiryTime() <= now) { - store.removeCookie(c.domain, c.path, c.key, () => {}); // result ignored - return false; - } - - return true; - } - - store.findCookies( - host, - allPaths ? null : path, - this.allowSpecialUseDomain, - (err, cookies) => { - if (err) { - return cb(err); - } - - cookies = cookies.filter(matchingCookie); - - // sorting of S5.4 part 2 - if (options.sort !== false) { - cookies = cookies.sort(cookieCompare); - } - - // S5.4 part 3 - const now = new Date(); - for (const cookie of cookies) { - cookie.lastAccessed = now; - } - // TODO persist lastAccessed - - cb(null, cookies); - } - ); - } - - getCookieString(...args) { - const cb = args.pop(); - const next = function(err, cookies) { - if (err) { - cb(err); - } else { - cb( - null, - cookies - .sort(cookieCompare) - .map(c => c.cookieString()) - .join("; ") - ); - } - }; - args.push(next); - this.getCookies.apply(this, args); - } - - getSetCookieStrings(...args) { - const cb = args.pop(); - const next = function(err, cookies) { - if (err) { - cb(err); - } else { - cb( - null, - cookies.map(c => { - return c.toString(); - }) - ); - } - }; - args.push(next); - this.getCookies.apply(this, args); - } - - serialize(cb) { - let type = this.store.constructor.name; - if (type === "Object") { - type = null; - } - - // update README.md "Serialization Format" if you change this, please! - const serialized = { - // The version of tough-cookie that serialized this jar. Generally a good - // practice since future versions can make data import decisions based on - // known past behavior. When/if this matters, use `semver`. - version: `tough-cookie@${VERSION}`, - - // add the store type, to make humans happy: - storeType: type, - - // CookieJar configuration: - rejectPublicSuffixes: !!this.rejectPublicSuffixes, - - // this gets filled from getAllCookies: - cookies: [] - }; - - if ( - !( - this.store.getAllCookies && - typeof this.store.getAllCookies === "function" - ) - ) { - return cb( - new Error( - "store does not support getAllCookies and cannot be serialized" - ) - ); - } - - this.store.getAllCookies((err, cookies) => { - if (err) { - return cb(err); - } - - serialized.cookies = cookies.map(cookie => { - // convert to serialized 'raw' cookies - cookie = cookie instanceof Cookie ? cookie.toJSON() : cookie; - - // Remove the index so new ones get assigned during deserialization - delete cookie.creationIndex; - - return cookie; - }); - - return cb(null, serialized); - }); - } - - toJSON() { - return this.serializeSync(); - } - - // use the class method CookieJar.deserialize instead of calling this directly - _importCookies(serialized, cb) { - let cookies = serialized.cookies; - if (!cookies || !Array.isArray(cookies)) { - return cb(new Error("serialized jar has no cookies array")); - } - cookies = cookies.slice(); // do not modify the original - - const putNext = err => { - if (err) { - return cb(err); - } - - if (!cookies.length) { - return cb(err, this); - } - - let cookie; - try { - cookie = fromJSON(cookies.shift()); - } catch (e) { - return cb(e); - } - - if (cookie === null) { - return putNext(null); // skip this cookie - } - - this.store.putCookie(cookie, putNext); - }; - - putNext(); - } - - clone(newStore, cb) { - if (arguments.length === 1) { - cb = newStore; - newStore = null; - } - - this.serialize((err, serialized) => { - if (err) { - return cb(err); - } - CookieJar.deserialize(serialized, newStore, cb); - }); - } - - cloneSync(newStore) { - if (arguments.length === 0) { - return this._cloneSync(); - } - if (!newStore.synchronous) { - throw new Error( - "CookieJar clone destination store is not synchronous; use async API instead." - ); - } - return this._cloneSync(newStore); - } - - removeAllCookies(cb) { - const store = this.store; - - // Check that the store implements its own removeAllCookies(). The default - // implementation in Store will immediately call the callback with a "not - // implemented" Error. - if ( - typeof store.removeAllCookies === "function" && - store.removeAllCookies !== Store.prototype.removeAllCookies - ) { - return store.removeAllCookies(cb); - } - - store.getAllCookies((err, cookies) => { - if (err) { - return cb(err); - } - - if (cookies.length === 0) { - return cb(null); - } - - let completedCount = 0; - const removeErrors = []; - - function removeCookieCb(removeErr) { - if (removeErr) { - removeErrors.push(removeErr); - } - - completedCount++; - - if (completedCount === cookies.length) { - return cb(removeErrors.length ? removeErrors[0] : null); - } - } - - cookies.forEach(cookie => { - store.removeCookie( - cookie.domain, - cookie.path, - cookie.key, - removeCookieCb - ); - }); - }); - } - - static deserialize(strOrObj, store, cb) { - if (arguments.length !== 3) { - // store is optional - cb = store; - store = null; - } - - let serialized; - if (typeof strOrObj === "string") { - serialized = jsonParse(strOrObj); - if (serialized instanceof Error) { - return cb(serialized); - } - } else { - serialized = strOrObj; - } - - const jar = new CookieJar(store, serialized.rejectPublicSuffixes); - jar._importCookies(serialized, err => { - if (err) { - return cb(err); - } - cb(null, jar); - }); - } - - static deserializeSync(strOrObj, store) { - const serialized = - typeof strOrObj === "string" ? JSON.parse(strOrObj) : strOrObj; - const jar = new CookieJar(store, serialized.rejectPublicSuffixes); - - // catch this mistake early: - if (!jar.store.synchronous) { - throw new Error( - "CookieJar store is not synchronous; use async API instead." - ); - } - - jar._importCookiesSync(serialized); - return jar; - } -} -CookieJar.fromJSON = CookieJar.deserializeSync; - -[ - "_importCookies", - "clone", - "getCookies", - "getCookieString", - "getSetCookieStrings", - "removeAllCookies", - "serialize", - "setCookie" -].forEach(name => { - CookieJar.prototype[name] = fromCallback(CookieJar.prototype[name]); -}); -CookieJar.deserialize = fromCallback(CookieJar.deserialize); - -// Use a closure to provide a true imperative API for synchronous stores. -function syncWrap(method) { - return function(...args) { - if (!this.store.synchronous) { - throw new Error( - "CookieJar store is not synchronous; use async API instead." - ); - } - - let syncErr, syncResult; - this[method](...args, (err, result) => { - syncErr = err; - syncResult = result; - }); - - if (syncErr) { - throw syncErr; - } - return syncResult; - }; -} - -exports.version = VERSION; -exports.CookieJar = CookieJar; -exports.Cookie = Cookie; -exports.Store = Store; -exports.MemoryCookieStore = MemoryCookieStore; -exports.parseDate = parseDate; -exports.formatDate = formatDate; -exports.parse = parse; -exports.fromJSON = fromJSON; -exports.domainMatch = domainMatch; -exports.defaultPath = defaultPath; -exports.pathMatch = pathMatch; -exports.getPublicSuffix = pubsuffix.getPublicSuffix; -exports.cookieCompare = cookieCompare; -exports.permuteDomain = __webpack_require__(898).permuteDomain; -exports.permutePath = permutePath; -exports.canonicalDomain = canonicalDomain; -exports.PrefixSecurityEnum = PrefixSecurityEnum; - - -/***/ }), +/* 393 */, /* 394 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { @@ -44114,6 +38238,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.ProxyTracerProvider = void 0; var ProxyTracer_1 = __webpack_require__(398); var NoopTracerProvider_1 = __webpack_require__(162); +var NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); /** * Tracer provider which provides {@link ProxyTracer}s. * @@ -44134,7 +38259,7 @@ var ProxyTracerProvider = /** @class */ (function () { }; ProxyTracerProvider.prototype.getDelegate = function () { var _a; - return (_a = this._delegate) !== null && _a !== void 0 ? _a : NoopTracerProvider_1.NOOP_TRACER_PROVIDER; + return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER; }; /** * Set the delegate tracer provider @@ -44178,6 +38303,7 @@ exports.ProxyTracerProvider = ProxyTracerProvider; Object.defineProperty(exports, "__esModule", { value: true }); exports.ProxyTracer = void 0; var NoopTracer_1 = __webpack_require__(151); +var NOOP_TRACER = new NoopTracer_1.NoopTracer(); /** * Proxy tracer provided by the proxy tracer provider */ @@ -44190,6 +38316,10 @@ var ProxyTracer = /** @class */ (function () { ProxyTracer.prototype.startSpan = function (name, options, context) { return this._getTracer().startSpan(name, options, context); }; + ProxyTracer.prototype.startActiveSpan = function (_name, _options, _context, _fn) { + var tracer = this._getTracer(); + return Reflect.apply(tracer.startActiveSpan, tracer, arguments); + }; /** * Try to get a tracer from the proxy tracer provider. * If the proxy tracer provider has no delegate, return a noop tracer. @@ -44200,7 +38330,7 @@ var ProxyTracer = /** @class */ (function () { } var tracer = this._provider.getDelegateTracer(this.name, this.version); if (!tracer) { - return NoopTracer_1.NOOP_TRACER; + return NOOP_TRACER; } this._delegate = tracer; return this._delegate; @@ -45395,12 +39525,10 @@ function parallel(list, iterator, callback) * See the License for the specific language governing permissions and * limitations under the License. */ -var __spreadArrays = (this && this.__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; +var __spreadArray = (this && this.__spreadArray) || function (to, from) { + for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) + to[j] = from[i]; + return to; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.NoopContextManager = void 0; @@ -45416,9 +39544,9 @@ var NoopContextManager = /** @class */ (function () { for (var _i = 3; _i < arguments.length; _i++) { args[_i - 3] = arguments[_i]; } - return fn.call.apply(fn, __spreadArrays([thisArg], args)); + return fn.call.apply(fn, __spreadArray([thisArg], args)); }; - NoopContextManager.prototype.bind = function (target, _context) { + NoopContextManager.prototype.bind = function (_context, target) { return target; }; NoopContextManager.prototype.enable = function () { @@ -45765,9 +39893,111 @@ exports.listTar = listTar; //# sourceMappingURL=tar.js.map /***/ }), -/* 435 */, +/* 435 */ +/***/ (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.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; +var trace_flags_1 = __webpack_require__(975); +exports.INVALID_SPANID = '0000000000000000'; +exports.INVALID_TRACEID = '00000000000000000000000000000000'; +exports.INVALID_SPAN_CONTEXT = { + traceId: exports.INVALID_TRACEID, + spanId: exports.INVALID_SPANID, + traceFlags: trace_flags_1.TraceFlags.NONE, +}; +//# sourceMappingURL=invalid-span-constants.js.map + +/***/ }), /* 436 */, -/* 437 */, +/* 437 */ +/***/ (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.NonRecordingSpan = void 0; +var invalid_span_constants_1 = __webpack_require__(435); +/** + * The NonRecordingSpan is the default {@link Span} that is used when no Span + * implementation is available. All operations are no-op including context + * propagation. + */ +var NonRecordingSpan = /** @class */ (function () { + function NonRecordingSpan(_spanContext) { + if (_spanContext === void 0) { _spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT; } + this._spanContext = _spanContext; + } + // Returns a SpanContext. + NonRecordingSpan.prototype.spanContext = function () { + return this._spanContext; + }; + // By default does nothing + NonRecordingSpan.prototype.setAttribute = function (_key, _value) { + return this; + }; + // By default does nothing + NonRecordingSpan.prototype.setAttributes = function (_attributes) { + return this; + }; + // By default does nothing + NonRecordingSpan.prototype.addEvent = function (_name, _attributes) { + return this; + }; + // By default does nothing + NonRecordingSpan.prototype.setStatus = function (_status) { + return this; + }; + // By default does nothing + NonRecordingSpan.prototype.updateName = function (_name) { + return this; + }; + // By default does nothing + NonRecordingSpan.prototype.end = function (_endTime) { }; + // isRecording always returns false for NonRecordingSpan. + NonRecordingSpan.prototype.isRecording = function () { + return false; + }; + // By default does nothing + NonRecordingSpan.prototype.recordException = function (_exception, _time) { }; + return NonRecordingSpan; +}()); +exports.NonRecordingSpan = NonRecordingSpan; +//# sourceMappingURL=NonRecordingSpan.js.map + +/***/ }), /* 438 */, /* 439 */, /* 440 */ @@ -45801,19 +40031,16 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); -exports.diag = exports.propagation = exports.trace = exports.context = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; -__exportStar(__webpack_require__(792), exports); +exports.diag = exports.propagation = exports.trace = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.baggageEntryMetadataFromString = void 0; +__exportStar(__webpack_require__(880), exports); +var utils_1 = __webpack_require__(112); +Object.defineProperty(exports, "baggageEntryMetadataFromString", { enumerable: true, get: function () { return utils_1.baggageEntryMetadataFromString; } }); __exportStar(__webpack_require__(452), exports); __exportStar(__webpack_require__(158), exports); __exportStar(__webpack_require__(893), exports); -__exportStar(__webpack_require__(918), exports); __exportStar(__webpack_require__(875), exports); __exportStar(__webpack_require__(906), exports); -__exportStar(__webpack_require__(727), exports); -__exportStar(__webpack_require__(851), exports); __exportStar(__webpack_require__(95), exports); -__exportStar(__webpack_require__(151), exports); -__exportStar(__webpack_require__(162), exports); __exportStar(__webpack_require__(398), exports); __exportStar(__webpack_require__(394), exports); __exportStar(__webpack_require__(781), exports); @@ -45823,20 +40050,19 @@ __exportStar(__webpack_require__(670), exports); __exportStar(__webpack_require__(181), exports); __exportStar(__webpack_require__(220), exports); __exportStar(__webpack_require__(932), exports); -__exportStar(__webpack_require__(839), exports); __exportStar(__webpack_require__(975), exports); __exportStar(__webpack_require__(70), exports); __exportStar(__webpack_require__(694), exports); __exportStar(__webpack_require__(695), exports); var spancontext_utils_1 = __webpack_require__(629); -Object.defineProperty(exports, "INVALID_SPANID", { enumerable: true, get: function () { return spancontext_utils_1.INVALID_SPANID; } }); -Object.defineProperty(exports, "INVALID_TRACEID", { enumerable: true, get: function () { return spancontext_utils_1.INVALID_TRACEID; } }); -Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", { enumerable: true, get: function () { return spancontext_utils_1.INVALID_SPAN_CONTEXT; } }); Object.defineProperty(exports, "isSpanContextValid", { enumerable: true, get: function () { return spancontext_utils_1.isSpanContextValid; } }); Object.defineProperty(exports, "isValidTraceId", { enumerable: true, get: function () { return spancontext_utils_1.isValidTraceId; } }); Object.defineProperty(exports, "isValidSpanId", { enumerable: true, get: function () { return spancontext_utils_1.isValidSpanId; } }); +var invalid_span_constants_1 = __webpack_require__(435); +Object.defineProperty(exports, "INVALID_SPANID", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPANID; } }); +Object.defineProperty(exports, "INVALID_TRACEID", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_TRACEID; } }); +Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPAN_CONTEXT; } }); __exportStar(__webpack_require__(132), exports); -__exportStar(__webpack_require__(425), exports); __exportStar(__webpack_require__(845), exports); var context_1 = __webpack_require__(492); /** Entrypoint for context API */ @@ -45844,7 +40070,7 @@ exports.context = context_1.ContextAPI.getInstance(); var trace_1 = __webpack_require__(911); /** Entrypoint for trace API */ exports.trace = trace_1.TraceAPI.getInstance(); -var propagation_1 = __webpack_require__(21); +var propagation_1 = __webpack_require__(22); /** Entrypoint for propagation API */ exports.propagation = propagation_1.PropagationAPI.getInstance(); var diag_1 = __webpack_require__(387); @@ -47891,8 +42117,7 @@ exports.FetchError = FetchError; /***/ }), -/* 459 */, -/* 460 */ +/* 459 */ /***/ (function(module) { // generated by genversion @@ -47900,34 +42125,8 @@ module.exports = '4.0.0' /***/ }), -/* 461 */ -/***/ (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 }); -exports._globalThis = void 0; -/** only globals that common to node and browsers are allowed */ -// eslint-disable-next-line node/no-unsupported-features/es-builtins -exports._globalThis = typeof globalThis === 'object' ? globalThis : global; -//# sourceMappingURL=globalThis.js.map - -/***/ }), +/* 460 */, +/* 461 */, /* 462 */ /***/ (function(module) { @@ -49125,7 +43324,65 @@ function authenticationBeforeRequest(state, options) { /* 480 */, /* 481 */, /* 482 */, -/* 483 */, +/* 483 */ +/***/ (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.deleteBaggage = exports.setBaggage = exports.getBaggage = void 0; +var context_1 = __webpack_require__(132); +/** + * Baggage key + */ +var BAGGAGE_KEY = context_1.createContextKey('OpenTelemetry Baggage Key'); +/** + * Retrieve the current baggage from the given context + * + * @param {Context} Context that manage all context values + * @returns {Baggage} Extracted baggage from the context + */ +function getBaggage(context) { + return context.getValue(BAGGAGE_KEY) || undefined; +} +exports.getBaggage = getBaggage; +/** + * Store a baggage in the given context + * + * @param {Context} Context that manage all context values + * @param {Baggage} baggage that will be set in the actual context + */ +function setBaggage(context, baggage) { + return context.setValue(BAGGAGE_KEY, baggage); +} +exports.setBaggage = setBaggage; +/** + * Delete the baggage stored in the given context + * + * @param {Context} Context that manage all context values + */ +function deleteBaggage(context) { + return context.deleteValue(BAGGAGE_KEY); +} +exports.deleteBaggage = deleteBaggage; +//# sourceMappingURL=context-helpers.js.map + +/***/ }), /* 484 */, /* 485 */, /* 486 */, @@ -49261,17 +43518,16 @@ module.exports = resolveCommand; * See the License for the specific language governing permissions and * limitations under the License. */ -var __spreadArrays = (this && this.__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; +var __spreadArray = (this && this.__spreadArray) || function (to, from) { + for (var i = 0, il = from.length, j = to.length; i < il; i++, j++) + to[j] = from[i]; + return to; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.ContextAPI = void 0; var NoopContextManager_1 = __webpack_require__(425); var global_utils_1 = __webpack_require__(525); +var diag_1 = __webpack_require__(387); var API_NAME = 'context'; var NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); /** @@ -49289,11 +43545,12 @@ var ContextAPI = /** @class */ (function () { return this._instance; }; /** - * Set the current context manager. Returns the initialized context manager + * Set the current context manager. + * + * @returns true if the context manager was successfully registered, else false */ ContextAPI.prototype.setGlobalContextManager = function (contextManager) { - global_utils_1.registerGlobal(API_NAME, contextManager); - return contextManager; + return global_utils_1.registerGlobal(API_NAME, contextManager, diag_1.DiagAPI.instance()); }; /** * Get the currently active context @@ -49315,17 +43572,16 @@ var ContextAPI = /** @class */ (function () { for (var _i = 3; _i < arguments.length; _i++) { args[_i - 3] = arguments[_i]; } - return (_a = this._getContextManager()).with.apply(_a, __spreadArrays([context, fn, thisArg], args)); + return (_a = this._getContextManager()).with.apply(_a, __spreadArray([context, fn, thisArg], args)); }; /** * Bind a context to a target function or event emitter * - * @param target function or event emitter to bind * @param context context to bind to the event emitter or function. Defaults to the currently active context + * @param target function or event emitter to bind */ - ContextAPI.prototype.bind = function (target, context) { - if (context === void 0) { context = this.active(); } - return this._getContextManager().bind(target, context); + ContextAPI.prototype.bind = function (context, target) { + return this._getContextManager().bind(context, target); }; ContextAPI.prototype._getContextManager = function () { return global_utils_1.getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER; @@ -49333,7 +43589,7 @@ var ContextAPI = /** @class */ (function () { /** Disable and remove the global context manager */ ContextAPI.prototype.disable = function () { this._getContextManager().disable(); - global_utils_1.unregisterGlobal(API_NAME); + global_utils_1.unregisterGlobal(API_NAME, diag_1.DiagAPI.instance()); }; return ContextAPI; }()); @@ -49573,7 +43829,51 @@ exports.default = _default; /***/ }), /* 517 */, /* 518 */, -/* 519 */, +/* 519 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2018, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +const psl = __webpack_require__(750); + +function getPublicSuffix(domain) { + return psl.get(domain); +} + +exports.getPublicSuffix = getPublicSuffix; + + +/***/ }), /* 520 */, /* 521 */, /* 522 */, @@ -49732,33 +44032,33 @@ module.exports.Collection = Hook.Collection */ Object.defineProperty(exports, "__esModule", { value: true }); exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0; -var __1 = __webpack_require__(440); var platform_1 = __webpack_require__(910); var version_1 = __webpack_require__(830); var semver_1 = __webpack_require__(987); var major = version_1.VERSION.split('.')[0]; -var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("io.opentelemetry.js.api." + major); +var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major); var _global = platform_1._globalThis; -function registerGlobal(type, instance, allowOverride) { +function registerGlobal(type, instance, diag, allowOverride) { var _a; if (allowOverride === void 0) { allowOverride = false; } - _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { + var api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { version: version_1.VERSION, - }; - var api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; + }); if (!allowOverride && api[type]) { // already registered an API of this type var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type); - __1.diag.error(err.stack || err.message); - return; + diag.error(err.stack || err.message); + return false; } if (api.version !== version_1.VERSION) { // All registered APIs must be of the same version exactly var err = new Error('@opentelemetry/api: All API registration versions must match'); - __1.diag.error(err.stack || err.message); - return; + diag.error(err.stack || err.message); + return false; } api[type] = instance; + diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + version_1.VERSION + "."); + return true; } exports.registerGlobal = registerGlobal; function getGlobal(type) { @@ -49770,7 +44070,8 @@ function getGlobal(type) { return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; } exports.getGlobal = getGlobal; -function unregisterGlobal(type) { +function unregisterGlobal(type, diag) { + diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + version_1.VERSION + "."); var api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; if (api) { delete api[type]; @@ -52232,76 +46533,7 @@ function octokitRestApiEndpoints(octokit) { /***/ }), /* 598 */, -/* 599 */ -/***/ (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 }); -exports.BaggageImpl = void 0; -var BaggageImpl = /** @class */ (function () { - function BaggageImpl(entries) { - this._entries = entries ? new Map(entries) : new Map(); - } - BaggageImpl.prototype.getEntry = function (key) { - var entry = this._entries.get(key); - if (!entry) { - return undefined; - } - return Object.assign({}, entry); - }; - BaggageImpl.prototype.getAllEntries = function () { - return Array.from(this._entries.entries()).map(function (_a) { - var k = _a[0], v = _a[1]; - return [k, v]; - }); - }; - BaggageImpl.prototype.setEntry = function (key, entry) { - var newBaggage = new BaggageImpl(this._entries); - newBaggage._entries.set(key, entry); - return newBaggage; - }; - BaggageImpl.prototype.removeEntry = function (key) { - var newBaggage = new BaggageImpl(this._entries); - newBaggage._entries.delete(key); - return newBaggage; - }; - BaggageImpl.prototype.removeEntries = function () { - var keys = []; - for (var _i = 0; _i < arguments.length; _i++) { - keys[_i] = arguments[_i]; - } - var newBaggage = new BaggageImpl(this._entries); - for (var _a = 0, keys_1 = keys; _a < keys_1.length; _a++) { - var key = keys_1[_a]; - newBaggage._entries.delete(key); - } - return newBaggage; - }; - BaggageImpl.prototype.clear = function () { - return new BaggageImpl(); - }; - return BaggageImpl; -}()); -exports.BaggageImpl = BaggageImpl; -//# sourceMappingURL=baggage.js.map - -/***/ }), +/* 599 */, /* 600 */, /* 601 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { @@ -52629,7 +46861,7 @@ Object.defineProperty(exports, "__esModule", { }); exports.default = void 0; -var _rng = _interopRequireDefault(__webpack_require__(944)); +var _rng = _interopRequireDefault(__webpack_require__(733)); var _stringify = _interopRequireDefault(__webpack_require__(164)); @@ -52900,7 +47132,7 @@ var __createBinding; ar[i] = from[i]; } } - return to.concat(ar || from); + return to.concat(ar || Array.prototype.slice.call(from)); }; __await = function (v) { @@ -53059,70 +47291,7 @@ exports.default = _default; /***/ }), /* 617 */, -/* 618 */ -/***/ (function(__unusedmodule, exports) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -function getProxyUrl(reqUrl) { - let usingSsl = reqUrl.protocol === 'https:'; - let proxyUrl; - if (checkBypass(reqUrl)) { - return proxyUrl; - } - let proxyVar; - if (usingSsl) { - proxyVar = process.env['https_proxy'] || process.env['HTTPS_PROXY']; - } - else { - proxyVar = process.env['http_proxy'] || process.env['HTTP_PROXY']; - } - if (proxyVar) { - proxyUrl = new URL(proxyVar); - } - return proxyUrl; -} -exports.getProxyUrl = getProxyUrl; -function checkBypass(reqUrl) { - if (!reqUrl.hostname) { - return false; - } - let noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; - if (!noProxy) { - return false; - } - // Determine the request port - let reqPort; - if (reqUrl.port) { - reqPort = Number(reqUrl.port); - } - else if (reqUrl.protocol === 'http:') { - reqPort = 80; - } - else if (reqUrl.protocol === 'https:') { - reqPort = 443; - } - // Format the request hostname and hostname with port - let upperReqHosts = [reqUrl.hostname.toUpperCase()]; - if (typeof reqPort === 'number') { - upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); - } - // Compare request host against noproxy - for (let upperNoProxyItem of noProxy - .split(',') - .map(x => x.trim().toUpperCase()) - .filter(x => x)) { - if (upperReqHosts.some(x => x === upperNoProxyItem)) { - return true; - } - } - return false; -} -exports.checkBypass = checkBypass; - - -/***/ }), +/* 618 */, /* 619 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { @@ -53263,7 +47432,89 @@ module.exports = isPlainObject; /***/ }), -/* 627 */, +/* 627 */ +/***/ (function(__unusedmodule, exports) { + +"use strict"; +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/*jshint unused:false */ + +class Store { + constructor() { + this.synchronous = false; + } + + findCookie(domain, path, key, cb) { + throw new Error("findCookie is not implemented"); + } + + findCookies(domain, path, allowSpecialUseDomain, cb) { + throw new Error("findCookies is not implemented"); + } + + putCookie(cookie, cb) { + throw new Error("putCookie is not implemented"); + } + + updateCookie(oldCookie, newCookie, cb) { + // recommended default implementation: + // return this.putCookie(newCookie, cb); + throw new Error("updateCookie is not implemented"); + } + + removeCookie(domain, path, key, cb) { + throw new Error("removeCookie is not implemented"); + } + + removeCookies(domain, path, cb) { + throw new Error("removeCookies is not implemented"); + } + + removeAllCookies(cb) { + throw new Error("removeAllCookies is not implemented"); + } + + getAllCookies(cb) { + throw new Error( + "getAllCookies is not implemented (therefore jar cannot be serialized)" + ); + } +} + +exports.Store = Store; + + +/***/ }), /* 628 */, /* 629 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { @@ -53271,23 +47522,32 @@ module.exports = isPlainObject; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.isSpanContextValid = exports.isValidSpanId = exports.isValidTraceId = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; -var trace_flags_1 = __webpack_require__(975); +exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = exports.isValidTraceId = 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 invalid_span_constants_1 = __webpack_require__(435); +var NonRecordingSpan_1 = __webpack_require__(437); var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; -exports.INVALID_SPANID = '0000000000000000'; -exports.INVALID_TRACEID = '00000000000000000000000000000000'; -exports.INVALID_SPAN_CONTEXT = { - traceId: exports.INVALID_TRACEID, - spanId: exports.INVALID_SPANID, - traceFlags: trace_flags_1.TraceFlags.NONE, -}; function isValidTraceId(traceId) { - return VALID_TRACEID_REGEX.test(traceId) && traceId !== exports.INVALID_TRACEID; + return VALID_TRACEID_REGEX.test(traceId) && traceId !== invalid_span_constants_1.INVALID_TRACEID; } exports.isValidTraceId = isValidTraceId; function isValidSpanId(spanId) { - return VALID_SPANID_REGEX.test(spanId) && spanId !== exports.INVALID_SPANID; + return VALID_SPANID_REGEX.test(spanId) && spanId !== invalid_span_constants_1.INVALID_SPANID; } exports.isValidSpanId = isValidSpanId; /** @@ -53298,6 +47558,16 @@ function isSpanContextValid(spanContext) { return (isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId)); } exports.isSpanContextValid = isSpanContextValid; +/** + * Wrap the given {@link SpanContext} in a new non-recording {@link Span} + * + * @param spanContext span context to be wrapped + * @returns a new non-recording {@link Span} with the provided context + */ +function wrapSpanContext(spanContext) { + return new NonRecordingSpan_1.NonRecordingSpan(spanContext); +} +exports.wrapSpanContext = wrapSpanContext; //# sourceMappingURL=spancontext-utils.js.map /***/ }), @@ -53410,7 +47680,7 @@ function restoreCache(paths, primaryKey, restoreKeys, options) { if (core.isDebug()) { yield tar_1.listTar(archivePath, compressionMethod); } - const archiveFileSize = utils.getArchiveFileSizeIsBytes(archivePath); + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); core.info(`Cache Size: ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B)`); yield tar_1.extractTar(archivePath, compressionMethod); core.info('Cache restored successfully'); @@ -53455,18 +47725,29 @@ function saveCache(paths, key, options) { const archiveFolder = yield utils.createTempDirectory(); 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); + try { + yield tar_1.createTar(archiveFolder, cachePaths, compressionMethod); + if (core.isDebug()) { + yield tar_1.listTar(archivePath, compressionMethod); + } + const fileSizeLimit = 10 * 1024 * 1024 * 1024; // 10GB per repo limit + const archiveFileSize = utils.getArchiveFileSizeInBytes(archivePath); + core.debug(`File Size: ${archiveFileSize}`); + if (archiveFileSize > fileSizeLimit) { + throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 10GB limit, not saving cache.`); + } + core.debug(`Saving Cache (ID: ${cacheId})`); + yield cacheHttpClient.saveCache(cacheId, archivePath, options); } - const fileSizeLimit = 5 * 1024 * 1024 * 1024; // 5GB per repo limit - const archiveFileSize = utils.getArchiveFileSizeIsBytes(archivePath); - core.debug(`File Size: ${archiveFileSize}`); - if (archiveFileSize > fileSizeLimit) { - throw new Error(`Cache size of ~${Math.round(archiveFileSize / (1024 * 1024))} MB (${archiveFileSize} B) is over the 5GB limit, not saving cache.`); + finally { + // Try to delete the archive to save space + try { + yield utils.unlinkFile(archivePath); + } + catch (error) { + core.debug(`Failed to delete archive: ${error}`); + } } - core.debug(`Saving Cache (ID: ${cacheId})`); - yield cacheHttpClient.saveCache(cacheId, archivePath, options); return cacheId; }); } @@ -53774,7 +48055,7 @@ var __createBinding; ar[i] = from[i]; } } - return to.concat(ar || from); + return to.concat(ar || Array.prototype.slice.call(from)); }; __await = function (v) { @@ -55446,30 +49727,7 @@ var __createBinding; /***/ }), -/* 646 */ -/***/ (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=Entry.js.map - -/***/ }), +/* 646 */, /* 647 */, /* 648 */, /* 649 */ @@ -55752,7 +50010,203 @@ if (process.platform === 'linux') { /***/ }), /* 655 */, -/* 656 */, +/* 656 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +const { fromCallback } = __webpack_require__(147); +const Store = __webpack_require__(627).Store; +const permuteDomain = __webpack_require__(383).permuteDomain; +const pathMatch = __webpack_require__(54).pathMatch; +const util = __webpack_require__(669); + +class MemoryCookieStore extends Store { + constructor() { + super(); + this.synchronous = true; + this.idx = {}; + if (util.inspect.custom) { + this[util.inspect.custom] = this.inspect; + } + } + + inspect() { + return `{ idx: ${util.inspect(this.idx, false, 2)} }`; + } + + findCookie(domain, path, key, cb) { + if (!this.idx[domain]) { + return cb(null, undefined); + } + if (!this.idx[domain][path]) { + return cb(null, undefined); + } + return cb(null, this.idx[domain][path][key] || null); + } + findCookies(domain, path, allowSpecialUseDomain, cb) { + const results = []; + if (typeof allowSpecialUseDomain === "function") { + cb = allowSpecialUseDomain; + allowSpecialUseDomain = false; + } + if (!domain) { + return cb(null, []); + } + + let pathMatcher; + if (!path) { + // null means "all paths" + pathMatcher = function matchAll(domainIndex) { + for (const curPath in domainIndex) { + const pathIndex = domainIndex[curPath]; + for (const key in pathIndex) { + results.push(pathIndex[key]); + } + } + }; + } else { + pathMatcher = function matchRFC(domainIndex) { + //NOTE: we should use path-match algorithm from S5.1.4 here + //(see : https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/canonical_cookie.cc#L299) + Object.keys(domainIndex).forEach(cookiePath => { + if (pathMatch(path, cookiePath)) { + const pathIndex = domainIndex[cookiePath]; + for (const key in pathIndex) { + results.push(pathIndex[key]); + } + } + }); + }; + } + + const domains = permuteDomain(domain, allowSpecialUseDomain) || [domain]; + const idx = this.idx; + domains.forEach(curDomain => { + const domainIndex = idx[curDomain]; + if (!domainIndex) { + return; + } + pathMatcher(domainIndex); + }); + + cb(null, results); + } + + putCookie(cookie, cb) { + if (!this.idx[cookie.domain]) { + this.idx[cookie.domain] = {}; + } + if (!this.idx[cookie.domain][cookie.path]) { + this.idx[cookie.domain][cookie.path] = {}; + } + this.idx[cookie.domain][cookie.path][cookie.key] = cookie; + cb(null); + } + updateCookie(oldCookie, newCookie, cb) { + // updateCookie() may avoid updating cookies that are identical. For example, + // lastAccessed may not be important to some stores and an equality + // comparison could exclude that field. + this.putCookie(newCookie, cb); + } + removeCookie(domain, path, key, cb) { + if ( + this.idx[domain] && + this.idx[domain][path] && + this.idx[domain][path][key] + ) { + delete this.idx[domain][path][key]; + } + cb(null); + } + removeCookies(domain, path, cb) { + if (this.idx[domain]) { + if (path) { + delete this.idx[domain][path]; + } else { + delete this.idx[domain]; + } + } + return cb(null); + } + removeAllCookies(cb) { + this.idx = {}; + return cb(null); + } + getAllCookies(cb) { + const cookies = []; + const idx = this.idx; + + const domains = Object.keys(idx); + domains.forEach(domain => { + const paths = Object.keys(idx[domain]); + paths.forEach(path => { + const keys = Object.keys(idx[domain][path]); + keys.forEach(key => { + if (key !== null) { + cookies.push(idx[domain][path][key]); + } + }); + }); + }); + + // Sort by creationIndex so deserializing retains the creation order. + // When implementing your own store, this SHOULD retain the order too + cookies.sort((a, b) => { + return (a.creationIndex || 0) - (b.creationIndex || 0); + }); + + cb(null, cookies); + } +} + +[ + "findCookie", + "findCookies", + "putCookie", + "updateCookie", + "removeCookie", + "removeCookies", + "removeAllCookies", + "getAllCookies" +].forEach(name => { + MemoryCookieStore[name] = fromCallback(MemoryCookieStore.prototype[name]); +}); + +exports.MemoryCookieStore = MemoryCookieStore; + + +/***/ }), /* 657 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -55945,7 +50399,76 @@ if (process.platform === 'linux') { /* 663 */, /* 664 */, /* 665 */, -/* 666 */, +/* 666 */ +/***/ (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 }); +exports.BaggageImpl = void 0; +var BaggageImpl = /** @class */ (function () { + function BaggageImpl(entries) { + this._entries = entries ? new Map(entries) : new Map(); + } + BaggageImpl.prototype.getEntry = function (key) { + var entry = this._entries.get(key); + if (!entry) { + return undefined; + } + return Object.assign({}, entry); + }; + BaggageImpl.prototype.getAllEntries = function () { + return Array.from(this._entries.entries()).map(function (_a) { + var k = _a[0], v = _a[1]; + return [k, v]; + }); + }; + BaggageImpl.prototype.setEntry = function (key, entry) { + var newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.set(key, entry); + return newBaggage; + }; + BaggageImpl.prototype.removeEntry = function (key) { + var newBaggage = new BaggageImpl(this._entries); + newBaggage._entries.delete(key); + return newBaggage; + }; + BaggageImpl.prototype.removeEntries = function () { + var keys = []; + for (var _i = 0; _i < arguments.length; _i++) { + keys[_i] = arguments[_i]; + } + var newBaggage = new BaggageImpl(this._entries); + for (var _a = 0, keys_1 = keys; _a < keys_1.length; _a++) { + var key = keys_1[_a]; + newBaggage._entries.delete(key); + } + return newBaggage; + }; + BaggageImpl.prototype.clear = function () { + return new BaggageImpl(); + }; + return BaggageImpl; +}()); +exports.BaggageImpl = BaggageImpl; +//# sourceMappingURL=baggage-impl.js.map + +/***/ }), /* 667 */, /* 668 */, /* 669 */ @@ -56006,7 +50529,318 @@ var SpanKind; //# sourceMappingURL=span_kind.js.map /***/ }), -/* 671 */, +/* 671 */ +/***/ (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, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + + __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, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), 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); +}); + + +/***/ }), /* 672 */ /***/ (function(__unusedmodule, exports, __webpack_require__) { @@ -56350,74 +51184,7 @@ exports.default = _default; /***/ }), /* 677 */, -/* 678 */ -/***/ (function(__unusedmodule, exports) { - -"use strict"; -/*! - * Copyright (c) 2015, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of Salesforce.com nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -/* - * "A request-path path-matches a given cookie-path if at least one of the - * following conditions holds:" - */ -function pathMatch(reqPath, cookiePath) { - // "o The cookie-path and the request-path are identical." - if (cookiePath === reqPath) { - return true; - } - - const idx = reqPath.indexOf(cookiePath); - if (idx === 0) { - // "o The cookie-path is a prefix of the request-path, and the last - // character of the cookie-path is %x2F ("/")." - if (cookiePath.substr(-1) === "/") { - return true; - } - - // " o The cookie-path is a prefix of the request-path, and the first - // character of the request-path that is not included in the cookie- path - // is a %x2F ("/") character." - if (reqPath.substr(cookiePath.length, 1) === "/") { - return true; - } - } - - return false; -} - -exports.pathMatch = pathMatch; - - -/***/ }), +/* 678 */, /* 679 */, /* 680 */, /* 681 */, @@ -56561,7 +51328,1684 @@ module.exports = (promise, onFinally) => { /* 698 */, /* 699 */, /* 700 */, -/* 701 */, +/* 701 */ +/***/ (function(__unusedmodule, exports, __webpack_require__) { + +"use strict"; +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +const punycode = __webpack_require__(815); +const urlParse = __webpack_require__(835).parse; +const util = __webpack_require__(669); +const pubsuffix = __webpack_require__(519); +const Store = __webpack_require__(627).Store; +const MemoryCookieStore = __webpack_require__(656).MemoryCookieStore; +const pathMatch = __webpack_require__(54).pathMatch; +const VERSION = __webpack_require__(459); +const { fromCallback } = __webpack_require__(147); + +// From RFC6265 S4.1.1 +// note that it excludes \x3B ";" +const COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/; + +const CONTROL_CHARS = /[\x00-\x1F]/; + +// From Chromium // '\r', '\n' and '\0' should be treated as a terminator in +// the "relaxed" mode, see: +// https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60 +const TERMINATORS = ["\n", "\r", "\0"]; + +// RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"' +// Note ';' is \x3B +const PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/; + +// date-time parsing constants (RFC6265 S5.1.1) + +const DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/; + +const MONTH_TO_NUM = { + jan: 0, + feb: 1, + mar: 2, + apr: 3, + may: 4, + jun: 5, + jul: 6, + aug: 7, + sep: 8, + oct: 9, + nov: 10, + dec: 11 +}; + +const MAX_TIME = 2147483647000; // 31-bit max +const MIN_TIME = 0; // 31-bit min +const SAME_SITE_CONTEXT_VAL_ERR = + 'Invalid sameSiteContext option for getCookies(); expected one of "strict", "lax", or "none"'; + +function checkSameSiteContext(value) { + const context = String(value).toLowerCase(); + if (context === "none" || context === "lax" || context === "strict") { + return context; + } else { + return null; + } +} + +const PrefixSecurityEnum = Object.freeze({ + SILENT: "silent", + STRICT: "strict", + DISABLED: "unsafe-disabled" +}); + +// Dumped from ip-regex@4.0.0, with the following changes: +// * all capturing groups converted to non-capturing -- "(?:)" +// * support for IPv6 Scoped Literal ("%eth1") removed +// * lowercase hexadecimal only +var IP_REGEX_LOWERCASE =/(?:^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$)|(?:^(?:(?:[a-f\d]{1,4}:){7}(?:[a-f\d]{1,4}|:)|(?:[a-f\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|:[a-f\d]{1,4}|:)|(?:[a-f\d]{1,4}:){5}(?::(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,2}|:)|(?:[a-f\d]{1,4}:){4}(?:(?::[a-f\d]{1,4}){0,1}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,3}|:)|(?:[a-f\d]{1,4}:){3}(?:(?::[a-f\d]{1,4}){0,2}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,4}|:)|(?:[a-f\d]{1,4}:){2}(?:(?::[a-f\d]{1,4}){0,3}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,5}|:)|(?:[a-f\d]{1,4}:){1}(?:(?::[a-f\d]{1,4}){0,4}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,6}|:)|(?::(?:(?::[a-f\d]{1,4}){0,5}:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}|(?::[a-f\d]{1,4}){1,7}|:)))$)/; + +/* + * Parses a Natural number (i.e., non-negative integer) with either the + * *DIGIT ( non-digit *OCTET ) + * or + * *DIGIT + * grammar (RFC6265 S5.1.1). + * + * The "trailingOK" boolean controls if the grammar accepts a + * "( non-digit *OCTET )" trailer. + */ +function parseDigits(token, minDigits, maxDigits, trailingOK) { + let count = 0; + while (count < token.length) { + const c = token.charCodeAt(count); + // "non-digit = %x00-2F / %x3A-FF" + if (c <= 0x2f || c >= 0x3a) { + break; + } + count++; + } + + // constrain to a minimum and maximum number of digits. + if (count < minDigits || count > maxDigits) { + return null; + } + + if (!trailingOK && count != token.length) { + return null; + } + + return parseInt(token.substr(0, count), 10); +} + +function parseTime(token) { + const parts = token.split(":"); + const result = [0, 0, 0]; + + /* RF6256 S5.1.1: + * time = hms-time ( non-digit *OCTET ) + * hms-time = time-field ":" time-field ":" time-field + * time-field = 1*2DIGIT + */ + + if (parts.length !== 3) { + return null; + } + + for (let i = 0; i < 3; i++) { + // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be + // followed by "( non-digit *OCTET )" so therefore the last time-field can + // have a trailer + const trailingOK = i == 2; + const num = parseDigits(parts[i], 1, 2, trailingOK); + if (num === null) { + return null; + } + result[i] = num; + } + + return result; +} + +function parseMonth(token) { + token = String(token) + .substr(0, 3) + .toLowerCase(); + const num = MONTH_TO_NUM[token]; + return num >= 0 ? num : null; +} + +/* + * RFC6265 S5.1.1 date parser (see RFC for full grammar) + */ +function parseDate(str) { + if (!str) { + return; + } + + /* RFC6265 S5.1.1: + * 2. Process each date-token sequentially in the order the date-tokens + * appear in the cookie-date + */ + const tokens = str.split(DATE_DELIM); + if (!tokens) { + return; + } + + let hour = null; + let minute = null; + let second = null; + let dayOfMonth = null; + let month = null; + let year = null; + + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i].trim(); + if (!token.length) { + continue; + } + + let result; + + /* 2.1. If the found-time flag is not set and the token matches the time + * production, set the found-time flag and set the hour- value, + * minute-value, and second-value to the numbers denoted by the digits in + * the date-token, respectively. Skip the remaining sub-steps and continue + * to the next date-token. + */ + if (second === null) { + result = parseTime(token); + if (result) { + hour = result[0]; + minute = result[1]; + second = result[2]; + continue; + } + } + + /* 2.2. If the found-day-of-month flag is not set and the date-token matches + * the day-of-month production, set the found-day-of- month flag and set + * the day-of-month-value to the number denoted by the date-token. Skip + * the remaining sub-steps and continue to the next date-token. + */ + if (dayOfMonth === null) { + // "day-of-month = 1*2DIGIT ( non-digit *OCTET )" + result = parseDigits(token, 1, 2, true); + if (result !== null) { + dayOfMonth = result; + continue; + } + } + + /* 2.3. If the found-month flag is not set and the date-token matches the + * month production, set the found-month flag and set the month-value to + * the month denoted by the date-token. Skip the remaining sub-steps and + * continue to the next date-token. + */ + if (month === null) { + result = parseMonth(token); + if (result !== null) { + month = result; + continue; + } + } + + /* 2.4. If the found-year flag is not set and the date-token matches the + * year production, set the found-year flag and set the year-value to the + * number denoted by the date-token. Skip the remaining sub-steps and + * continue to the next date-token. + */ + if (year === null) { + // "year = 2*4DIGIT ( non-digit *OCTET )" + result = parseDigits(token, 2, 4, true); + if (result !== null) { + year = result; + /* From S5.1.1: + * 3. If the year-value is greater than or equal to 70 and less + * than or equal to 99, increment the year-value by 1900. + * 4. If the year-value is greater than or equal to 0 and less + * than or equal to 69, increment the year-value by 2000. + */ + if (year >= 70 && year <= 99) { + year += 1900; + } else if (year >= 0 && year <= 69) { + year += 2000; + } + } + } + } + + /* RFC 6265 S5.1.1 + * "5. Abort these steps and fail to parse the cookie-date if: + * * at least one of the found-day-of-month, found-month, found- + * year, or found-time flags is not set, + * * the day-of-month-value is less than 1 or greater than 31, + * * the year-value is less than 1601, + * * the hour-value is greater than 23, + * * the minute-value is greater than 59, or + * * the second-value is greater than 59. + * (Note that leap seconds cannot be represented in this syntax.)" + * + * So, in order as above: + */ + if ( + dayOfMonth === null || + month === null || + year === null || + second === null || + dayOfMonth < 1 || + dayOfMonth > 31 || + year < 1601 || + hour > 23 || + minute > 59 || + second > 59 + ) { + return; + } + + return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second)); +} + +function formatDate(date) { + return date.toUTCString(); +} + +// S5.1.2 Canonicalized Host Names +function canonicalDomain(str) { + if (str == null) { + return null; + } + str = str.trim().replace(/^\./, ""); // S4.1.2.3 & S5.2.3: ignore leading . + + // convert to IDN if any non-ASCII characters + if (punycode && /[^\u0001-\u007f]/.test(str)) { + str = punycode.toASCII(str); + } + + return str.toLowerCase(); +} + +// S5.1.3 Domain Matching +function domainMatch(str, domStr, canonicalize) { + if (str == null || domStr == null) { + return null; + } + if (canonicalize !== false) { + str = canonicalDomain(str); + domStr = canonicalDomain(domStr); + } + + /* + * S5.1.3: + * "A string domain-matches a given domain string if at least one of the + * following conditions hold:" + * + * " o The domain string and the string are identical. (Note that both the + * domain string and the string will have been canonicalized to lower case at + * this point)" + */ + if (str == domStr) { + return true; + } + + /* " o All of the following [three] conditions hold:" */ + + /* "* The domain string is a suffix of the string" */ + const idx = str.indexOf(domStr); + if (idx <= 0) { + return false; // it's a non-match (-1) or prefix (0) + } + + // next, check it's a proper suffix + // e.g., "a.b.c".indexOf("b.c") === 2 + // 5 === 3+2 + if (str.length !== domStr.length + idx) { + return false; // it's not a suffix + } + + /* " * The last character of the string that is not included in the + * domain string is a %x2E (".") character." */ + if (str.substr(idx-1,1) !== '.') { + return false; // doesn't align on "." + } + + /* " * The string is a host name (i.e., not an IP address)." */ + if (IP_REGEX_LOWERCASE.test(str)) { + return false; // it's an IP address + } + + return true; +} + +// RFC6265 S5.1.4 Paths and Path-Match + +/* + * "The user agent MUST use an algorithm equivalent to the following algorithm + * to compute the default-path of a cookie:" + * + * Assumption: the path (and not query part or absolute uri) is passed in. + */ +function defaultPath(path) { + // "2. If the uri-path is empty or if the first character of the uri-path is not + // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps. + if (!path || path.substr(0, 1) !== "/") { + return "/"; + } + + // "3. If the uri-path contains no more than one %x2F ("/") character, output + // %x2F ("/") and skip the remaining step." + if (path === "/") { + return path; + } + + const rightSlash = path.lastIndexOf("/"); + if (rightSlash === 0) { + return "/"; + } + + // "4. Output the characters of the uri-path from the first character up to, + // but not including, the right-most %x2F ("/")." + return path.slice(0, rightSlash); +} + +function trimTerminator(str) { + for (let t = 0; t < TERMINATORS.length; t++) { + const terminatorIdx = str.indexOf(TERMINATORS[t]); + if (terminatorIdx !== -1) { + str = str.substr(0, terminatorIdx); + } + } + + return str; +} + +function parseCookiePair(cookiePair, looseMode) { + cookiePair = trimTerminator(cookiePair); + + let firstEq = cookiePair.indexOf("="); + if (looseMode) { + if (firstEq === 0) { + // '=' is immediately at start + cookiePair = cookiePair.substr(1); + firstEq = cookiePair.indexOf("="); // might still need to split on '=' + } + } else { + // non-loose mode + if (firstEq <= 0) { + // no '=' or is at start + return; // needs to have non-empty "cookie-name" + } + } + + let cookieName, cookieValue; + if (firstEq <= 0) { + cookieName = ""; + cookieValue = cookiePair.trim(); + } else { + cookieName = cookiePair.substr(0, firstEq).trim(); + cookieValue = cookiePair.substr(firstEq + 1).trim(); + } + + if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) { + return; + } + + const c = new Cookie(); + c.key = cookieName; + c.value = cookieValue; + return c; +} + +function parse(str, options) { + if (!options || typeof options !== "object") { + options = {}; + } + str = str.trim(); + + // We use a regex to parse the "name-value-pair" part of S5.2 + const firstSemi = str.indexOf(";"); // S5.2 step 1 + const cookiePair = firstSemi === -1 ? str : str.substr(0, firstSemi); + const c = parseCookiePair(cookiePair, !!options.loose); + if (!c) { + return; + } + + if (firstSemi === -1) { + return c; + } + + // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string + // (including the %x3B (";") in question)." plus later on in the same section + // "discard the first ";" and trim". + const unparsed = str.slice(firstSemi + 1).trim(); + + // "If the unparsed-attributes string is empty, skip the rest of these + // steps." + if (unparsed.length === 0) { + return c; + } + + /* + * S5.2 says that when looping over the items "[p]rocess the attribute-name + * and attribute-value according to the requirements in the following + * subsections" for every item. Plus, for many of the individual attributes + * in S5.3 it says to use the "attribute-value of the last attribute in the + * cookie-attribute-list". Therefore, in this implementation, we overwrite + * the previous value. + */ + const cookie_avs = unparsed.split(";"); + while (cookie_avs.length) { + const av = cookie_avs.shift().trim(); + if (av.length === 0) { + // happens if ";;" appears + continue; + } + const av_sep = av.indexOf("="); + let av_key, av_value; + + if (av_sep === -1) { + av_key = av; + av_value = null; + } else { + av_key = av.substr(0, av_sep); + av_value = av.substr(av_sep + 1); + } + + av_key = av_key.trim().toLowerCase(); + + if (av_value) { + av_value = av_value.trim(); + } + + switch (av_key) { + case "expires": // S5.2.1 + if (av_value) { + const exp = parseDate(av_value); + // "If the attribute-value failed to parse as a cookie date, ignore the + // cookie-av." + if (exp) { + // over and underflow not realistically a concern: V8's getTime() seems to + // store something larger than a 32-bit time_t (even with 32-bit node) + c.expires = exp; + } + } + break; + + case "max-age": // S5.2.2 + if (av_value) { + // "If the first character of the attribute-value is not a DIGIT or a "-" + // character ...[or]... If the remainder of attribute-value contains a + // non-DIGIT character, ignore the cookie-av." + if (/^-?[0-9]+$/.test(av_value)) { + const delta = parseInt(av_value, 10); + // "If delta-seconds is less than or equal to zero (0), let expiry-time + // be the earliest representable date and time." + c.setMaxAge(delta); + } + } + break; + + case "domain": // S5.2.3 + // "If the attribute-value is empty, the behavior is undefined. However, + // the user agent SHOULD ignore the cookie-av entirely." + if (av_value) { + // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E + // (".") character." + const domain = av_value.trim().replace(/^\./, ""); + if (domain) { + // "Convert the cookie-domain to lower case." + c.domain = domain.toLowerCase(); + } + } + break; + + case "path": // S5.2.4 + /* + * "If the attribute-value is empty or if the first character of the + * attribute-value is not %x2F ("/"): + * Let cookie-path be the default-path. + * Otherwise: + * Let cookie-path be the attribute-value." + * + * We'll represent the default-path as null since it depends on the + * context of the parsing. + */ + c.path = av_value && av_value[0] === "/" ? av_value : null; + break; + + case "secure": // S5.2.5 + /* + * "If the attribute-name case-insensitively matches the string "Secure", + * the user agent MUST append an attribute to the cookie-attribute-list + * with an attribute-name of Secure and an empty attribute-value." + */ + c.secure = true; + break; + + case "httponly": // S5.2.6 -- effectively the same as 'secure' + c.httpOnly = true; + break; + + case "samesite": // RFC6265bis-02 S5.3.7 + const enforcement = av_value ? av_value.toLowerCase() : ""; + switch (enforcement) { + case "strict": + c.sameSite = "strict"; + break; + case "lax": + c.sameSite = "lax"; + break; + default: + // RFC6265bis-02 S5.3.7 step 1: + // "If cookie-av's attribute-value is not a case-insensitive match + // for "Strict" or "Lax", ignore the "cookie-av"." + // This effectively sets it to 'none' from the prototype. + break; + } + break; + + default: + c.extensions = c.extensions || []; + c.extensions.push(av); + break; + } + } + + return c; +} + +/** + * If the cookie-name begins with a case-sensitive match for the + * string "__Secure-", abort these steps and ignore the cookie + * entirely unless the cookie's secure-only-flag is true. + * @param cookie + * @returns boolean + */ +function isSecurePrefixConditionMet(cookie) { + return !cookie.key.startsWith("__Secure-") || cookie.secure; +} + +/** + * If the cookie-name begins with a case-sensitive match for the + * string "__Host-", abort these steps and ignore the cookie + * entirely unless the cookie meets all the following criteria: + * 1. The cookie's secure-only-flag is true. + * 2. The cookie's host-only-flag is true. + * 3. The cookie-attribute-list contains an attribute with an + * attribute-name of "Path", and the cookie's path is "/". + * @param cookie + * @returns boolean + */ +function isHostPrefixConditionMet(cookie) { + return ( + !cookie.key.startsWith("__Host-") || + (cookie.secure && + cookie.hostOnly && + cookie.path != null && + cookie.path === "/") + ); +} + +// avoid the V8 deoptimization monster! +function jsonParse(str) { + let obj; + try { + obj = JSON.parse(str); + } catch (e) { + return e; + } + return obj; +} + +function fromJSON(str) { + if (!str) { + return null; + } + + let obj; + if (typeof str === "string") { + obj = jsonParse(str); + if (obj instanceof Error) { + return null; + } + } else { + // assume it's an Object + obj = str; + } + + const c = new Cookie(); + for (let i = 0; i < Cookie.serializableProperties.length; i++) { + const prop = Cookie.serializableProperties[i]; + if (obj[prop] === undefined || obj[prop] === cookieDefaults[prop]) { + continue; // leave as prototype default + } + + if (prop === "expires" || prop === "creation" || prop === "lastAccessed") { + if (obj[prop] === null) { + c[prop] = null; + } else { + c[prop] = obj[prop] == "Infinity" ? "Infinity" : new Date(obj[prop]); + } + } else { + c[prop] = obj[prop]; + } + } + + return c; +} + +/* Section 5.4 part 2: + * "* Cookies with longer paths are listed before cookies with + * shorter paths. + * + * * Among cookies that have equal-length path fields, cookies with + * earlier creation-times are listed before cookies with later + * creation-times." + */ + +function cookieCompare(a, b) { + let cmp = 0; + + // descending for length: b CMP a + const aPathLen = a.path ? a.path.length : 0; + const bPathLen = b.path ? b.path.length : 0; + cmp = bPathLen - aPathLen; + if (cmp !== 0) { + return cmp; + } + + // ascending for time: a CMP b + const aTime = a.creation ? a.creation.getTime() : MAX_TIME; + const bTime = b.creation ? b.creation.getTime() : MAX_TIME; + cmp = aTime - bTime; + if (cmp !== 0) { + return cmp; + } + + // break ties for the same millisecond (precision of JavaScript's clock) + cmp = a.creationIndex - b.creationIndex; + + return cmp; +} + +// Gives the permutation of all possible pathMatch()es of a given path. The +// array is in longest-to-shortest order. Handy for indexing. +function permutePath(path) { + if (path === "/") { + return ["/"]; + } + const permutations = [path]; + while (path.length > 1) { + const lindex = path.lastIndexOf("/"); + if (lindex === 0) { + break; + } + path = path.substr(0, lindex); + permutations.push(path); + } + permutations.push("/"); + return permutations; +} + +function getCookieContext(url) { + if (url instanceof Object) { + return url; + } + // NOTE: decodeURI will throw on malformed URIs (see GH-32). + // Therefore, we will just skip decoding for such URIs. + try { + url = decodeURI(url); + } catch (err) { + // Silently swallow error + } + + return urlParse(url); +} + +const cookieDefaults = { + // the order in which the RFC has them: + key: "", + value: "", + expires: "Infinity", + maxAge: null, + domain: null, + path: null, + secure: false, + httpOnly: false, + extensions: null, + // set by the CookieJar: + hostOnly: null, + pathIsDefault: null, + creation: null, + lastAccessed: null, + sameSite: "none" +}; + +class Cookie { + constructor(options = {}) { + if (util.inspect.custom) { + this[util.inspect.custom] = this.inspect; + } + + Object.assign(this, cookieDefaults, options); + this.creation = this.creation || new Date(); + + // used to break creation ties in cookieCompare(): + Object.defineProperty(this, "creationIndex", { + configurable: false, + enumerable: false, // important for assert.deepEqual checks + writable: true, + value: ++Cookie.cookiesCreated + }); + } + + inspect() { + const now = Date.now(); + const hostOnly = this.hostOnly != null ? this.hostOnly : "?"; + const createAge = this.creation + ? `${now - this.creation.getTime()}ms` + : "?"; + const accessAge = this.lastAccessed + ? `${now - this.lastAccessed.getTime()}ms` + : "?"; + return `Cookie="${this.toString()}; hostOnly=${hostOnly}; aAge=${accessAge}; cAge=${createAge}"`; + } + + toJSON() { + const obj = {}; + + for (const prop of Cookie.serializableProperties) { + if (this[prop] === cookieDefaults[prop]) { + continue; // leave as prototype default + } + + if ( + prop === "expires" || + prop === "creation" || + prop === "lastAccessed" + ) { + if (this[prop] === null) { + obj[prop] = null; + } else { + obj[prop] = + this[prop] == "Infinity" // intentionally not === + ? "Infinity" + : this[prop].toISOString(); + } + } else if (prop === "maxAge") { + if (this[prop] !== null) { + // again, intentionally not === + obj[prop] = + this[prop] == Infinity || this[prop] == -Infinity + ? this[prop].toString() + : this[prop]; + } + } else { + if (this[prop] !== cookieDefaults[prop]) { + obj[prop] = this[prop]; + } + } + } + + return obj; + } + + clone() { + return fromJSON(this.toJSON()); + } + + validate() { + if (!COOKIE_OCTETS.test(this.value)) { + return false; + } + if ( + this.expires != Infinity && + !(this.expires instanceof Date) && + !parseDate(this.expires) + ) { + return false; + } + if (this.maxAge != null && this.maxAge <= 0) { + return false; // "Max-Age=" non-zero-digit *DIGIT + } + if (this.path != null && !PATH_VALUE.test(this.path)) { + return false; + } + + const cdomain = this.cdomain(); + if (cdomain) { + if (cdomain.match(/\.$/)) { + return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this + } + const suffix = pubsuffix.getPublicSuffix(cdomain); + if (suffix == null) { + // it's a public suffix + return false; + } + } + return true; + } + + setExpires(exp) { + if (exp instanceof Date) { + this.expires = exp; + } else { + this.expires = parseDate(exp) || "Infinity"; + } + } + + setMaxAge(age) { + if (age === Infinity || age === -Infinity) { + this.maxAge = age.toString(); // so JSON.stringify() works + } else { + this.maxAge = age; + } + } + + cookieString() { + let val = this.value; + if (val == null) { + val = ""; + } + if (this.key === "") { + return val; + } + return `${this.key}=${val}`; + } + + // gives Set-Cookie header format + toString() { + let str = this.cookieString(); + + if (this.expires != Infinity) { + if (this.expires instanceof Date) { + str += `; Expires=${formatDate(this.expires)}`; + } else { + str += `; Expires=${this.expires}`; + } + } + + if (this.maxAge != null && this.maxAge != Infinity) { + str += `; Max-Age=${this.maxAge}`; + } + + if (this.domain && !this.hostOnly) { + str += `; Domain=${this.domain}`; + } + if (this.path) { + str += `; Path=${this.path}`; + } + + if (this.secure) { + str += "; Secure"; + } + if (this.httpOnly) { + str += "; HttpOnly"; + } + if (this.sameSite && this.sameSite !== "none") { + const ssCanon = Cookie.sameSiteCanonical[this.sameSite.toLowerCase()]; + str += `; SameSite=${ssCanon ? ssCanon : this.sameSite}`; + } + if (this.extensions) { + this.extensions.forEach(ext => { + str += `; ${ext}`; + }); + } + + return str; + } + + // TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie() + // elsewhere) + // S5.3 says to give the "latest representable date" for which we use Infinity + // For "expired" we use 0 + TTL(now) { + /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires + * attribute, the Max-Age attribute has precedence and controls the + * expiration date of the cookie. + * (Concurs with S5.3 step 3) + */ + if (this.maxAge != null) { + return this.maxAge <= 0 ? 0 : this.maxAge * 1000; + } + + let expires = this.expires; + if (expires != Infinity) { + if (!(expires instanceof Date)) { + expires = parseDate(expires) || Infinity; + } + + if (expires == Infinity) { + return Infinity; + } + + return expires.getTime() - (now || Date.now()); + } + + return Infinity; + } + + // expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() + // elsewhere) + expiryTime(now) { + if (this.maxAge != null) { + const relativeTo = now || this.creation || new Date(); + const age = this.maxAge <= 0 ? -Infinity : this.maxAge * 1000; + return relativeTo.getTime() + age; + } + + if (this.expires == Infinity) { + return Infinity; + } + return this.expires.getTime(); + } + + // expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() + // elsewhere), except it returns a Date + expiryDate(now) { + const millisec = this.expiryTime(now); + if (millisec == Infinity) { + return new Date(MAX_TIME); + } else if (millisec == -Infinity) { + return new Date(MIN_TIME); + } else { + return new Date(millisec); + } + } + + // This replaces the "persistent-flag" parts of S5.3 step 3 + isPersistent() { + return this.maxAge != null || this.expires != Infinity; + } + + // Mostly S5.1.2 and S5.2.3: + canonicalizedDomain() { + if (this.domain == null) { + return null; + } + return canonicalDomain(this.domain); + } + + cdomain() { + return this.canonicalizedDomain(); + } +} + +Cookie.cookiesCreated = 0; +Cookie.parse = parse; +Cookie.fromJSON = fromJSON; +Cookie.serializableProperties = Object.keys(cookieDefaults); +Cookie.sameSiteLevel = { + strict: 3, + lax: 2, + none: 1 +}; + +Cookie.sameSiteCanonical = { + strict: "Strict", + lax: "Lax" +}; + +function getNormalizedPrefixSecurity(prefixSecurity) { + if (prefixSecurity != null) { + const normalizedPrefixSecurity = prefixSecurity.toLowerCase(); + /* The three supported options */ + switch (normalizedPrefixSecurity) { + case PrefixSecurityEnum.STRICT: + case PrefixSecurityEnum.SILENT: + case PrefixSecurityEnum.DISABLED: + return normalizedPrefixSecurity; + } + } + /* Default is SILENT */ + return PrefixSecurityEnum.SILENT; +} + +class CookieJar { + constructor(store, options = { rejectPublicSuffixes: true }) { + if (typeof options === "boolean") { + options = { rejectPublicSuffixes: options }; + } + this.rejectPublicSuffixes = options.rejectPublicSuffixes; + this.enableLooseMode = !!options.looseMode; + this.allowSpecialUseDomain = !!options.allowSpecialUseDomain; + this.store = store || new MemoryCookieStore(); + this.prefixSecurity = getNormalizedPrefixSecurity(options.prefixSecurity); + this._cloneSync = syncWrap("clone"); + this._importCookiesSync = syncWrap("_importCookies"); + this.getCookiesSync = syncWrap("getCookies"); + this.getCookieStringSync = syncWrap("getCookieString"); + this.getSetCookieStringsSync = syncWrap("getSetCookieStrings"); + this.removeAllCookiesSync = syncWrap("removeAllCookies"); + this.setCookieSync = syncWrap("setCookie"); + this.serializeSync = syncWrap("serialize"); + } + + setCookie(cookie, url, options, cb) { + let err; + const context = getCookieContext(url); + if (typeof options === "function") { + cb = options; + options = {}; + } + + const host = canonicalDomain(context.hostname); + const loose = options.loose || this.enableLooseMode; + + let sameSiteContext = null; + if (options.sameSiteContext) { + sameSiteContext = checkSameSiteContext(options.sameSiteContext); + if (!sameSiteContext) { + return cb(new Error(SAME_SITE_CONTEXT_VAL_ERR)); + } + } + + // S5.3 step 1 + if (typeof cookie === "string" || cookie instanceof String) { + cookie = Cookie.parse(cookie, { loose: loose }); + if (!cookie) { + err = new Error("Cookie failed to parse"); + return cb(options.ignoreError ? null : err); + } + } else if (!(cookie instanceof Cookie)) { + // If you're seeing this error, and are passing in a Cookie object, + // it *might* be a Cookie object from another loaded version of tough-cookie. + err = new Error( + "First argument to setCookie must be a Cookie object or string" + ); + return cb(options.ignoreError ? null : err); + } + + // S5.3 step 2 + const now = options.now || new Date(); // will assign later to save effort in the face of errors + + // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie() + + // S5.3 step 4: NOOP; domain is null by default + + // S5.3 step 5: public suffixes + if (this.rejectPublicSuffixes && cookie.domain) { + const suffix = pubsuffix.getPublicSuffix(cookie.cdomain()); + if (suffix == null) { + // e.g. "com" + err = new Error("Cookie has domain set to a public suffix"); + return cb(options.ignoreError ? null : err); + } + } + + // S5.3 step 6: + if (cookie.domain) { + if (!domainMatch(host, cookie.cdomain(), false)) { + err = new Error( + `Cookie not in this host's domain. Cookie:${cookie.cdomain()} Request:${host}` + ); + return cb(options.ignoreError ? null : err); + } + + if (cookie.hostOnly == null) { + // don't reset if already set + cookie.hostOnly = false; + } + } else { + cookie.hostOnly = true; + cookie.domain = host; + } + + //S5.2.4 If the attribute-value is empty or if the first character of the + //attribute-value is not %x2F ("/"): + //Let cookie-path be the default-path. + if (!cookie.path || cookie.path[0] !== "/") { + cookie.path = defaultPath(context.pathname); + cookie.pathIsDefault = true; + } + + // S5.3 step 8: NOOP; secure attribute + // S5.3 step 9: NOOP; httpOnly attribute + + // S5.3 step 10 + if (options.http === false && cookie.httpOnly) { + err = new Error("Cookie is HttpOnly and this isn't an HTTP API"); + return cb(options.ignoreError ? null : err); + } + + // 6252bis-02 S5.4 Step 13 & 14: + if (cookie.sameSite !== "none" && sameSiteContext) { + // "If the cookie's "same-site-flag" is not "None", and the cookie + // is being set from a context whose "site for cookies" is not an + // exact match for request-uri's host's registered domain, then + // abort these steps and ignore the newly created cookie entirely." + if (sameSiteContext === "none") { + err = new Error( + "Cookie is SameSite but this is a cross-origin request" + ); + return cb(options.ignoreError ? null : err); + } + } + + /* 6265bis-02 S5.4 Steps 15 & 16 */ + const ignoreErrorForPrefixSecurity = + this.prefixSecurity === PrefixSecurityEnum.SILENT; + const prefixSecurityDisabled = + this.prefixSecurity === PrefixSecurityEnum.DISABLED; + /* If prefix checking is not disabled ...*/ + if (!prefixSecurityDisabled) { + let errorFound = false; + let errorMsg; + /* Check secure prefix condition */ + if (!isSecurePrefixConditionMet(cookie)) { + errorFound = true; + errorMsg = "Cookie has __Secure prefix but Secure attribute is not set"; + } else if (!isHostPrefixConditionMet(cookie)) { + /* Check host prefix condition */ + errorFound = true; + errorMsg = + "Cookie has __Host prefix but either Secure or HostOnly attribute is not set or Path is not '/'"; + } + if (errorFound) { + return cb( + options.ignoreError || ignoreErrorForPrefixSecurity + ? null + : new Error(errorMsg) + ); + } + } + + const store = this.store; + + if (!store.updateCookie) { + store.updateCookie = function(oldCookie, newCookie, cb) { + this.putCookie(newCookie, cb); + }; + } + + function withCookie(err, oldCookie) { + if (err) { + return cb(err); + } + + const next = function(err) { + if (err) { + return cb(err); + } else { + cb(null, cookie); + } + }; + + if (oldCookie) { + // S5.3 step 11 - "If the cookie store contains a cookie with the same name, + // domain, and path as the newly created cookie:" + if (options.http === false && oldCookie.httpOnly) { + // step 11.2 + err = new Error("old Cookie is HttpOnly and this isn't an HTTP API"); + return cb(options.ignoreError ? null : err); + } + cookie.creation = oldCookie.creation; // step 11.3 + cookie.creationIndex = oldCookie.creationIndex; // preserve tie-breaker + cookie.lastAccessed = now; + // Step 11.4 (delete cookie) is implied by just setting the new one: + store.updateCookie(oldCookie, cookie, next); // step 12 + } else { + cookie.creation = cookie.lastAccessed = now; + store.putCookie(cookie, next); // step 12 + } + } + + store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie); + } + + // RFC6365 S5.4 + getCookies(url, options, cb) { + const context = getCookieContext(url); + if (typeof options === "function") { + cb = options; + options = {}; + } + + const host = canonicalDomain(context.hostname); + const path = context.pathname || "/"; + + let secure = options.secure; + if ( + secure == null && + context.protocol && + (context.protocol == "https:" || context.protocol == "wss:") + ) { + secure = true; + } + + let sameSiteLevel = 0; + if (options.sameSiteContext) { + const sameSiteContext = checkSameSiteContext(options.sameSiteContext); + sameSiteLevel = Cookie.sameSiteLevel[sameSiteContext]; + if (!sameSiteLevel) { + return cb(new Error(SAME_SITE_CONTEXT_VAL_ERR)); + } + } + + let http = options.http; + if (http == null) { + http = true; + } + + const now = options.now || Date.now(); + const expireCheck = options.expire !== false; + const allPaths = !!options.allPaths; + const store = this.store; + + function matchingCookie(c) { + // "Either: + // The cookie's host-only-flag is true and the canonicalized + // request-host is identical to the cookie's domain. + // Or: + // The cookie's host-only-flag is false and the canonicalized + // request-host domain-matches the cookie's domain." + if (c.hostOnly) { + if (c.domain != host) { + return false; + } + } else { + if (!domainMatch(host, c.domain, false)) { + return false; + } + } + + // "The request-uri's path path-matches the cookie's path." + if (!allPaths && !pathMatch(path, c.path)) { + return false; + } + + // "If the cookie's secure-only-flag is true, then the request-uri's + // scheme must denote a "secure" protocol" + if (c.secure && !secure) { + return false; + } + + // "If the cookie's http-only-flag is true, then exclude the cookie if the + // cookie-string is being generated for a "non-HTTP" API" + if (c.httpOnly && !http) { + return false; + } + + // RFC6265bis-02 S5.3.7 + if (sameSiteLevel) { + const cookieLevel = Cookie.sameSiteLevel[c.sameSite || "none"]; + if (cookieLevel > sameSiteLevel) { + // only allow cookies at or below the request level + return false; + } + } + + // deferred from S5.3 + // non-RFC: allow retention of expired cookies by choice + if (expireCheck && c.expiryTime() <= now) { + store.removeCookie(c.domain, c.path, c.key, () => {}); // result ignored + return false; + } + + return true; + } + + store.findCookies( + host, + allPaths ? null : path, + this.allowSpecialUseDomain, + (err, cookies) => { + if (err) { + return cb(err); + } + + cookies = cookies.filter(matchingCookie); + + // sorting of S5.4 part 2 + if (options.sort !== false) { + cookies = cookies.sort(cookieCompare); + } + + // S5.4 part 3 + const now = new Date(); + for (const cookie of cookies) { + cookie.lastAccessed = now; + } + // TODO persist lastAccessed + + cb(null, cookies); + } + ); + } + + getCookieString(...args) { + const cb = args.pop(); + const next = function(err, cookies) { + if (err) { + cb(err); + } else { + cb( + null, + cookies + .sort(cookieCompare) + .map(c => c.cookieString()) + .join("; ") + ); + } + }; + args.push(next); + this.getCookies.apply(this, args); + } + + getSetCookieStrings(...args) { + const cb = args.pop(); + const next = function(err, cookies) { + if (err) { + cb(err); + } else { + cb( + null, + cookies.map(c => { + return c.toString(); + }) + ); + } + }; + args.push(next); + this.getCookies.apply(this, args); + } + + serialize(cb) { + let type = this.store.constructor.name; + if (type === "Object") { + type = null; + } + + // update README.md "Serialization Format" if you change this, please! + const serialized = { + // The version of tough-cookie that serialized this jar. Generally a good + // practice since future versions can make data import decisions based on + // known past behavior. When/if this matters, use `semver`. + version: `tough-cookie@${VERSION}`, + + // add the store type, to make humans happy: + storeType: type, + + // CookieJar configuration: + rejectPublicSuffixes: !!this.rejectPublicSuffixes, + + // this gets filled from getAllCookies: + cookies: [] + }; + + if ( + !( + this.store.getAllCookies && + typeof this.store.getAllCookies === "function" + ) + ) { + return cb( + new Error( + "store does not support getAllCookies and cannot be serialized" + ) + ); + } + + this.store.getAllCookies((err, cookies) => { + if (err) { + return cb(err); + } + + serialized.cookies = cookies.map(cookie => { + // convert to serialized 'raw' cookies + cookie = cookie instanceof Cookie ? cookie.toJSON() : cookie; + + // Remove the index so new ones get assigned during deserialization + delete cookie.creationIndex; + + return cookie; + }); + + return cb(null, serialized); + }); + } + + toJSON() { + return this.serializeSync(); + } + + // use the class method CookieJar.deserialize instead of calling this directly + _importCookies(serialized, cb) { + let cookies = serialized.cookies; + if (!cookies || !Array.isArray(cookies)) { + return cb(new Error("serialized jar has no cookies array")); + } + cookies = cookies.slice(); // do not modify the original + + const putNext = err => { + if (err) { + return cb(err); + } + + if (!cookies.length) { + return cb(err, this); + } + + let cookie; + try { + cookie = fromJSON(cookies.shift()); + } catch (e) { + return cb(e); + } + + if (cookie === null) { + return putNext(null); // skip this cookie + } + + this.store.putCookie(cookie, putNext); + }; + + putNext(); + } + + clone(newStore, cb) { + if (arguments.length === 1) { + cb = newStore; + newStore = null; + } + + this.serialize((err, serialized) => { + if (err) { + return cb(err); + } + CookieJar.deserialize(serialized, newStore, cb); + }); + } + + cloneSync(newStore) { + if (arguments.length === 0) { + return this._cloneSync(); + } + if (!newStore.synchronous) { + throw new Error( + "CookieJar clone destination store is not synchronous; use async API instead." + ); + } + return this._cloneSync(newStore); + } + + removeAllCookies(cb) { + const store = this.store; + + // Check that the store implements its own removeAllCookies(). The default + // implementation in Store will immediately call the callback with a "not + // implemented" Error. + if ( + typeof store.removeAllCookies === "function" && + store.removeAllCookies !== Store.prototype.removeAllCookies + ) { + return store.removeAllCookies(cb); + } + + store.getAllCookies((err, cookies) => { + if (err) { + return cb(err); + } + + if (cookies.length === 0) { + return cb(null); + } + + let completedCount = 0; + const removeErrors = []; + + function removeCookieCb(removeErr) { + if (removeErr) { + removeErrors.push(removeErr); + } + + completedCount++; + + if (completedCount === cookies.length) { + return cb(removeErrors.length ? removeErrors[0] : null); + } + } + + cookies.forEach(cookie => { + store.removeCookie( + cookie.domain, + cookie.path, + cookie.key, + removeCookieCb + ); + }); + }); + } + + static deserialize(strOrObj, store, cb) { + if (arguments.length !== 3) { + // store is optional + cb = store; + store = null; + } + + let serialized; + if (typeof strOrObj === "string") { + serialized = jsonParse(strOrObj); + if (serialized instanceof Error) { + return cb(serialized); + } + } else { + serialized = strOrObj; + } + + const jar = new CookieJar(store, serialized.rejectPublicSuffixes); + jar._importCookies(serialized, err => { + if (err) { + return cb(err); + } + cb(null, jar); + }); + } + + static deserializeSync(strOrObj, store) { + const serialized = + typeof strOrObj === "string" ? JSON.parse(strOrObj) : strOrObj; + const jar = new CookieJar(store, serialized.rejectPublicSuffixes); + + // catch this mistake early: + if (!jar.store.synchronous) { + throw new Error( + "CookieJar store is not synchronous; use async API instead." + ); + } + + jar._importCookiesSync(serialized); + return jar; + } +} +CookieJar.fromJSON = CookieJar.deserializeSync; + +[ + "_importCookies", + "clone", + "getCookies", + "getCookieString", + "getSetCookieStrings", + "removeAllCookies", + "serialize", + "setCookie" +].forEach(name => { + CookieJar.prototype[name] = fromCallback(CookieJar.prototype[name]); +}); +CookieJar.deserialize = fromCallback(CookieJar.deserialize); + +// Use a closure to provide a true imperative API for synchronous stores. +function syncWrap(method) { + return function(...args) { + if (!this.store.synchronous) { + throw new Error( + "CookieJar store is not synchronous; use async API instead." + ); + } + + let syncErr, syncResult; + this[method](...args, (err, result) => { + syncErr = err; + syncResult = result; + }); + + if (syncErr) { + throw syncErr; + } + return syncResult; + }; +} + +exports.version = VERSION; +exports.CookieJar = CookieJar; +exports.Cookie = Cookie; +exports.Store = Store; +exports.MemoryCookieStore = MemoryCookieStore; +exports.parseDate = parseDate; +exports.formatDate = formatDate; +exports.parse = parse; +exports.fromJSON = fromJSON; +exports.domainMatch = domainMatch; +exports.defaultPath = defaultPath; +exports.pathMatch = pathMatch; +exports.getPublicSuffix = pubsuffix.getPublicSuffix; +exports.cookieCompare = cookieCompare; +exports.permuteDomain = __webpack_require__(383).permuteDomain; +exports.permutePath = permutePath; +exports.canonicalDomain = canonicalDomain; +exports.PrefixSecurityEnum = PrefixSecurityEnum; + + +/***/ }), /* 702 */, /* 703 */, /* 704 */, @@ -56655,10 +53099,79 @@ module.exports = {"activity":{"checkStarringRepo":{"method":"GET","params":{"own "use strict"; + +Object.defineProperty(exports, '__esModule', { value: true }); + +__webpack_require__(338); +var tslib = __webpack_require__(671); + // Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -Object.defineProperty(exports, "__esModule", { value: true }); -__webpack_require__(71); +/** + * returns an async iterator that iterates over results. It also has a `byPage` + * method that returns pages of items at once. + * + * @param pagedResult - an object that specifies how to get pages. + * @returns a paged async iterator that iterates over results. + */ +function getPagedAsyncIterator(pagedResult) { + var _a; + const iter = getItemAsyncIterator(pagedResult); + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: (_a = pagedResult === null || pagedResult === void 0 ? void 0 : pagedResult.byPage) !== null && _a !== void 0 ? _a : ((settings) => { + return getPageAsyncIterator(pagedResult, settings === null || settings === void 0 ? void 0 : settings.maxPageSize); + }) + }; +} +function getItemAsyncIterator(pagedResult, maxPageSize) { + return tslib.__asyncGenerator(this, arguments, function* getItemAsyncIterator_1() { + var e_1, _a; + const pages = getPageAsyncIterator(pagedResult, maxPageSize); + const firstVal = yield tslib.__await(pages.next()); + // if the result does not have an array shape, i.e. TPage = TElement, then we return it as is + if (!Array.isArray(firstVal.value)) { + yield yield tslib.__await(firstVal.value); + // `pages` is of type `AsyncIterableIterator` but TPage = TElement in this case + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(pages))); + } + else { + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(firstVal.value))); + try { + for (var pages_1 = tslib.__asyncValues(pages), pages_1_1; pages_1_1 = yield tslib.__await(pages_1.next()), !pages_1_1.done;) { + const page = pages_1_1.value; + // pages is of type `AsyncIterableIterator` so `page` is of type `TPage`. In this branch, + // it must be the case that `TPage = TElement[]` + yield tslib.__await(yield* tslib.__asyncDelegator(tslib.__asyncValues(page))); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (pages_1_1 && !pages_1_1.done && (_a = pages_1.return)) yield tslib.__await(_a.call(pages_1)); + } + finally { if (e_1) throw e_1.error; } + } + } + }); +} +function getPageAsyncIterator(pagedResult, maxPageSize) { + return tslib.__asyncGenerator(this, arguments, function* getPageAsyncIterator_1() { + let response = yield tslib.__await(pagedResult.getPage(pagedResult.firstPageLink, maxPageSize)); + yield yield tslib.__await(response.page); + while (response.nextPageLink) { + response = yield tslib.__await(pagedResult.getPage(response.nextPageLink, maxPageSize)); + yield yield tslib.__await(response.page); + } + }); +} + +exports.getPagedAsyncIterator = getPagedAsyncIterator; +//# sourceMappingURL=index.js.map /***/ }), @@ -56670,7 +53183,86 @@ __webpack_require__(71); /* 717 */, /* 718 */, /* 719 */, -/* 720 */, +/* 720 */ +/***/ (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.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getSpan = void 0; +var context_1 = __webpack_require__(132); +var NonRecordingSpan_1 = __webpack_require__(437); +/** + * span key + */ +var SPAN_KEY = context_1.createContextKey('OpenTelemetry Context Key SPAN'); +/** + * Return the span if one exists + * + * @param context context to get span from + */ +function getSpan(context) { + return context.getValue(SPAN_KEY) || undefined; +} +exports.getSpan = getSpan; +/** + * Set the span on a context + * + * @param context context to use as parent + * @param span span to set active + */ +function setSpan(context, span) { + return context.setValue(SPAN_KEY, span); +} +exports.setSpan = setSpan; +/** + * Remove current span stored in the context + * + * @param context context to delete span from + */ +function deleteSpan(context) { + return context.deleteValue(SPAN_KEY); +} +exports.deleteSpan = deleteSpan; +/** + * Wrap span context in a NoopSpan and set as span in a new + * context + * + * @param context context to set active span on + * @param spanContext span context to be wrapped + */ +function setSpanContext(context, spanContext) { + return setSpan(context, new NonRecordingSpan_1.NonRecordingSpan(spanContext)); +} +exports.setSpanContext = setSpanContext; +/** + * Get the span context of the span if it exists. + * + * @param context context to get values from + */ +function getSpanContext(context) { + var _a; + return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext(); +} +exports.getSpanContext = getSpanContext; +//# sourceMappingURL=context-utils.js.map + +/***/ }), /* 721 */, /* 722 */ /***/ (function(module) { @@ -56725,343 +53317,9 @@ module.exports = bytesToUuid; /***/ }), -/* 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, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || from); - }; - - __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, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), 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) { - -"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=Event.js.map - -/***/ }), +/* 727 */, /* 728 */ /***/ (function(__unusedmodule, exports) { @@ -57183,68 +53441,33 @@ exports.hashFiles = hashFiles; /* 731 */, /* 732 */, /* 733 */ -/***/ (function(__unusedmodule, exports) { +/***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -class BasicCredentialHandler { - constructor(username, password) { - this.username = username; - this.password = password; - } - prepareRequest(options) { - options.headers['Authorization'] = - 'Basic ' + - Buffer.from(this.username + ':' + this.password).toString('base64'); - } - // This handler cannot handle 401 - canHandleAuthentication(response) { - return false; - } - handleAuthentication(httpClient, requestInfo, objs) { - return null; - } -} -exports.BasicCredentialHandler = BasicCredentialHandler; -class BearerCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - options.headers['Authorization'] = 'Bearer ' + this.token; - } - // This handler cannot handle 401 - canHandleAuthentication(response) { - return false; - } - handleAuthentication(httpClient, requestInfo, objs) { - return null; - } -} -exports.BearerCredentialHandler = BearerCredentialHandler; -class PersonalAccessTokenCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - options.headers['Authorization'] = - 'Basic ' + Buffer.from('PAT:' + this.token).toString('base64'); - } - // This handler cannot handle 401 - canHandleAuthentication(response) { - return false; - } - handleAuthentication(httpClient, requestInfo, objs) { - return null; - } -} -exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = rng; + +var _crypto = _interopRequireDefault(__webpack_require__(417)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate + +let poolPtr = rnds8Pool.length; + +function rng() { + if (poolPtr > rnds8Pool.length - 16) { + _crypto.default.randomFillSync(rnds8Pool); + + poolPtr = 0; + } + + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} /***/ }), /* 734 */, @@ -57588,315 +53811,31 @@ module.exports = require("fs"); /***/ }), /* 748 */ -/***/ (function(module) { +/***/ (function(__unusedmodule, exports) { -/*! ***************************************************************************** -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, pack) { - if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { - if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || from); - }; - - __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, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), 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); -}); +"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._globalThis = void 0; +/** only globals that common to node and browsers are allowed */ +// eslint-disable-next-line node/no-unsupported-features/es-builtins +exports._globalThis = typeof globalThis === 'object' ? globalThis : global; +//# sourceMappingURL=globalThis.js.map /***/ }), /* 749 */ @@ -58742,7 +54681,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); -__exportStar(__webpack_require__(461), exports); +__exportStar(__webpack_require__(748), exports); //# sourceMappingURL=index.js.map /***/ }), @@ -58763,77 +54702,7 @@ module.exports = function(dst, src) { /***/ }), -/* 767 */ -/***/ (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.NoopSpan = void 0; -var spancontext_utils_1 = __webpack_require__(629); -/** - * The NoopSpan is the default {@link Span} that is used when no Span - * implementation is available. All operations are no-op including context - * propagation. - */ -var NoopSpan = /** @class */ (function () { - function NoopSpan(_spanContext) { - if (_spanContext === void 0) { _spanContext = spancontext_utils_1.INVALID_SPAN_CONTEXT; } - this._spanContext = _spanContext; - } - // Returns a SpanContext. - NoopSpan.prototype.context = function () { - return this._spanContext; - }; - // By default does nothing - NoopSpan.prototype.setAttribute = function (_key, _value) { - return this; - }; - // By default does nothing - NoopSpan.prototype.setAttributes = function (_attributes) { - return this; - }; - // By default does nothing - NoopSpan.prototype.addEvent = function (_name, _attributes) { - return this; - }; - // By default does nothing - NoopSpan.prototype.setStatus = function (_status) { - return this; - }; - // By default does nothing - NoopSpan.prototype.updateName = function (_name) { - return this; - }; - // By default does nothing - NoopSpan.prototype.end = function (_endTime) { }; - // isRecording always returns false for noopSpan. - NoopSpan.prototype.isRecording = function () { - return false; - }; - // By default does nothing - NoopSpan.prototype.recordException = function (_exception, _time) { }; - return NoopSpan; -}()); -exports.NoopSpan = NoopSpan; -//# sourceMappingURL=NoopSpan.js.map - -/***/ }), +/* 767 */, /* 768 */ /***/ (function(module) { @@ -59116,6 +54985,7 @@ var http = __webpack_require__(605); var https = __webpack_require__(211); var parseUrl = __webpack_require__(835).parse; var fs = __webpack_require__(747); +var Stream = __webpack_require__(794).Stream; var mime = __webpack_require__(779); var asynckit = __webpack_require__(334); var populate = __webpack_require__(766); @@ -59211,8 +55081,8 @@ FormData.prototype._trackLength = function(header, value, options) { Buffer.byteLength(header) + FormData.LINE_BREAK.length; - // empty or either doesn't have path or not an http response - if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) )) { + // empty or either doesn't have path or not an http response or not a stream + if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) { return; } @@ -59567,13 +55437,15 @@ FormData.prototype.submit = function(params, cb) { // get content length and fire away this.getLength(function(err, length) { - if (err) { + if (err && err !== 'Unknown stream') { this._error(err); return; } // add content length - request.setHeader('Content-Length', length); + if (length) { + request.setHeader('Content-Length', length); + } this.pipe(request); if (cb) { @@ -59688,74 +55560,7 @@ FormData.prototype.toString = function () { /***/ }), -/* 792 */ -/***/ (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" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.baggageEntryMetadataFromString = exports.createBaggage = void 0; -var baggage_1 = __webpack_require__(599); -var symbol_1 = __webpack_require__(561); -__exportStar(__webpack_require__(938), exports); -__exportStar(__webpack_require__(646), exports); -/** - * Create a new Baggage with optional entries - * - * @param entries An array of baggage entries the new baggage should contain - */ -function createBaggage(entries) { - if (entries === void 0) { entries = {}; } - return new baggage_1.BaggageImpl(new Map(Object.entries(entries))); -} -exports.createBaggage = createBaggage; -/** - * Create a serializable BaggageEntryMetadata object from a string. - * - * @param str string metadata. Format is currently not defined by the spec and has no special meaning. - * - */ -function baggageEntryMetadataFromString(str) { - if (typeof str !== 'string') { - // @TODO log diagnostic - str = ''; - } - return { - __TYPE__: symbol_1.baggageEntryMetadataSymbol, - toString: function () { - return str; - }, - }; -} -exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; -//# sourceMappingURL=index.js.map - -/***/ }), +/* 792 */, /* 793 */, /* 794 */ /***/ (function(module) { @@ -60525,7 +56330,7 @@ module.exports = v4; Object.defineProperty(exports, "__esModule", { value: true }); exports.VERSION = void 0; // this is autogenerated file, see scripts/version-update.js -exports.VERSION = '1.0.0-rc.0'; +exports.VERSION = '1.0.3'; //# sourceMappingURL=version.js.map /***/ }), @@ -60542,30 +56347,7 @@ module.exports = require("url"); /* 836 */, /* 837 */, /* 838 */, -/* 839 */ -/***/ (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=TimedEvent.js.map - -/***/ }), +/* 839 */, /* 840 */, /* 841 */, /* 842 */, @@ -60617,30 +56399,7 @@ function paginationMethodsPlugin (octokit) { /***/ }), -/* 851 */ -/***/ (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=link_context.js.map - -/***/ }), +/* 851 */, /* 852 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -62154,7 +57913,7 @@ var __createBinding; ar[i] = from[i]; } } - return to.concat(ar || from); + return to.concat(ar || Array.prototype.slice.call(from)); }; __await = function (v) { @@ -62336,7 +58095,30 @@ exports.defaultTextMapSetter = { /* 877 */, /* 878 */, /* 879 */, -/* 880 */, +/* 880 */ +/***/ (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 + +/***/ }), /* 881 */ /***/ (function(module) { @@ -64005,48 +59787,36 @@ function escapeProperty(s) { /***/ (function(__unusedmodule, exports, __webpack_require__) { "use strict"; -/*! - * Copyright (c) Microsoft and contributors. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. - * - * Azure Core LRO SDK for JavaScript - 1.0.5 - */ Object.defineProperty(exports, '__esModule', { value: true }); -var tslib = __webpack_require__(725); +var logger$1 = __webpack_require__(928); // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** * When a poller is manually stopped through the `stopPolling` method, * the poller will be rejected with an instance of the PollerStoppedError. */ -var PollerStoppedError = /** @class */ (function (_super) { - tslib.__extends(PollerStoppedError, _super); - function PollerStoppedError(message) { - var _this = _super.call(this, message) || this; - _this.name = "PollerStoppedError"; - Object.setPrototypeOf(_this, PollerStoppedError.prototype); - return _this; +class PollerStoppedError extends Error { + constructor(message) { + super(message); + this.name = "PollerStoppedError"; + Object.setPrototypeOf(this, PollerStoppedError.prototype); } - return PollerStoppedError; -}(Error)); +} /** * When a poller is cancelled through the `cancelOperation` method, * the poller will be rejected with an instance of the PollerCancelledError. */ -var PollerCancelledError = /** @class */ (function (_super) { - tslib.__extends(PollerCancelledError, _super); - function PollerCancelledError(message) { - var _this = _super.call(this, message) || this; - _this.name = "PollerCancelledError"; - Object.setPrototypeOf(_this, PollerCancelledError.prototype); - return _this; +class PollerCancelledError extends Error { + constructor(message) { + super(message); + this.name = "PollerCancelledError"; + Object.setPrototypeOf(this, PollerCancelledError.prototype); } - return PollerCancelledError; -}(Error)); +} /** * A class that represents the definition of a program that polls through consecutive requests * until it reaches a state of completion. @@ -64109,7 +59879,7 @@ var PollerCancelledError = /** @class */ (function (_super) { * */ // eslint-disable-next-line no-use-before-define -var Poller = /** @class */ (function () { +class Poller { /** * A poller needs to be initialized by passing in at least the basic properties of the `PollOperation`. * @@ -64175,19 +59945,18 @@ var Poller = /** @class */ (function () { * * @param operation - Must contain the basic properties of `PollOperation`. */ - function Poller(operation) { - var _this = this; + constructor(operation) { this.stopped = true; this.pollProgressCallbacks = []; this.operation = operation; - this.promise = new Promise(function (resolve, reject) { - _this.resolve = resolve; - _this.reject = reject; + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; }); // This prevents the UnhandledPromiseRejectionWarning in node.js from being thrown. // The above warning would get thrown if `poller.poll` is called, it returns an error, // and pullUntilDone did not have a .catch or await try/catch on it's return value. - this.promise.catch(function () { + this.promise.catch(() => { /* intentionally blank */ }); } @@ -64196,29 +59965,15 @@ var Poller = /** @class */ (function () { * Starts a loop that will break only if the poller is done * or if the poller is stopped. */ - Poller.prototype.startPolling = function () { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - if (this.stopped) { - this.stopped = false; - } - _a.label = 1; - case 1: - if (!(!this.isStopped() && !this.isDone())) return [3 /*break*/, 4]; - return [4 /*yield*/, this.poll()]; - case 2: - _a.sent(); - return [4 /*yield*/, this.delay()]; - case 3: - _a.sent(); - return [3 /*break*/, 1]; - case 4: return [2 /*return*/]; - } - }); - }); - }; + async startPolling() { + if (this.stopped) { + this.stopped = false; + } + while (!this.isStopped() && !this.isDone()) { + await this.poll(); + await this.delay(); + } + } /** * @internal * pollOnce does one polling, by calling to the update method of the underlying @@ -64228,44 +59983,31 @@ var Poller = /** @class */ (function () { * * @param options - Optional properties passed to the operation's update method. */ - Poller.prototype.pollOnce = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, e_1; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _b.trys.push([0, 3, , 4]); - if (!!this.isDone()) return [3 /*break*/, 2]; - _a = this; - return [4 /*yield*/, this.operation.update({ - abortSignal: options.abortSignal, - fireProgress: this.fireProgress.bind(this) - })]; - case 1: - _a.operation = _b.sent(); - if (this.isDone() && this.resolve) { - // If the poller has finished polling, this means we now have a result. - // However, it can be the case that TResult is instantiated to void, so - // we are not expecting a result anyway. To assert that we might not - // have a result eventually after finishing polling, we cast the result - // to TResult. - this.resolve(this.operation.state.result); - } - _b.label = 2; - case 2: return [3 /*break*/, 4]; - case 3: - e_1 = _b.sent(); - this.operation.state.error = e_1; - if (this.reject) { - this.reject(e_1); - } - throw e_1; - case 4: return [2 /*return*/]; + async pollOnce(options = {}) { + try { + if (!this.isDone()) { + this.operation = await this.operation.update({ + abortSignal: options.abortSignal, + fireProgress: this.fireProgress.bind(this) + }); + if (this.isDone() && this.resolve) { + // If the poller has finished polling, this means we now have a result. + // However, it can be the case that TResult is instantiated to void, so + // we are not expecting a result anyway. To assert that we might not + // have a result eventually after finishing polling, we cast the result + // to TResult. + this.resolve(this.operation.state.result); } - }); - }); - }; + } + } + catch (e) { + this.operation.state.error = e; + if (this.reject) { + this.reject(e); + } + throw e; + } + } /** * @internal * fireProgress calls the functions passed in via onProgress the method of the poller. @@ -64275,36 +60017,22 @@ var Poller = /** @class */ (function () { * * @param state - The current operation state. */ - Poller.prototype.fireProgress = function (state) { - for (var _i = 0, _a = this.pollProgressCallbacks; _i < _a.length; _i++) { - var callback = _a[_i]; + fireProgress(state) { + for (const callback of this.pollProgressCallbacks) { callback(state); } - }; + } /** * @internal * Invokes the underlying operation's cancel method, and rejects the * pollUntilDone promise. */ - Poller.prototype.cancelOnce = function (options) { - if (options === void 0) { options = {}; } - return tslib.__awaiter(this, void 0, void 0, function () { - var _a; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - _a = this; - return [4 /*yield*/, this.operation.cancel(options)]; - case 1: - _a.operation = _b.sent(); - if (this.reject) { - this.reject(new PollerCancelledError("Poller cancelled")); - } - return [2 /*return*/]; - } - }); - }); - }; + async cancelOnce(options = {}) { + this.operation = await this.operation.cancel(options); + if (this.reject) { + this.reject(new PollerCancelledError("Poller cancelled")); + } + } /** * Returns a promise that will resolve once a single polling request finishes. * It does this by calling the update method of the Poller's operation. @@ -64313,68 +60041,61 @@ var Poller = /** @class */ (function () { * * @param options - Optional properties passed to the operation's update method. */ - Poller.prototype.poll = function (options) { - var _this = this; - if (options === void 0) { options = {}; } + poll(options = {}) { if (!this.pollOncePromise) { this.pollOncePromise = this.pollOnce(options); - var clearPollOncePromise = function () { - _this.pollOncePromise = undefined; + const clearPollOncePromise = () => { + this.pollOncePromise = undefined; }; this.pollOncePromise.then(clearPollOncePromise, clearPollOncePromise).catch(this.reject); } return this.pollOncePromise; - }; + } /** * Returns a promise that will resolve once the underlying operation is completed. */ - Poller.prototype.pollUntilDone = function () { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - if (this.stopped) { - this.startPolling().catch(this.reject); - } - return [2 /*return*/, this.promise]; - }); - }); - }; + async pollUntilDone() { + if (this.stopped) { + this.startPolling().catch(this.reject); + } + return this.promise; + } /** * Invokes the provided callback after each polling is completed, * sending the current state of the poller's operation. * * It returns a method that can be used to stop receiving updates on the given callback function. */ - Poller.prototype.onProgress = function (callback) { - var _this = this; + onProgress(callback) { this.pollProgressCallbacks.push(callback); - return function () { - _this.pollProgressCallbacks = _this.pollProgressCallbacks.filter(function (c) { return c !== callback; }); + return () => { + this.pollProgressCallbacks = this.pollProgressCallbacks.filter((c) => c !== callback); }; - }; + } /** * Returns true if the poller has finished polling. */ - Poller.prototype.isDone = function () { - var state = this.operation.state; + isDone() { + const state = this.operation.state; return Boolean(state.isCompleted || state.isCancelled || state.error); - }; + } /** * Stops the poller from continuing to poll. */ - Poller.prototype.stopPolling = function () { + stopPolling() { if (!this.stopped) { this.stopped = true; if (this.reject) { this.reject(new PollerStoppedError("This poller is already stopped")); } } - }; + } /** * Returns true if the poller is stopped. */ - Poller.prototype.isStopped = function () { + isStopped() { return this.stopped; - }; + } /** * Attempts to cancel the underlying operation. * @@ -64384,8 +60105,7 @@ var Poller = /** @class */ (function () { * * @param options - Optional properties passed to the operation's update method. */ - Poller.prototype.cancelOperation = function (options) { - if (options === void 0) { options = {}; } + cancelOperation(options = {}) { if (!this.stopped) { this.stopped = true; } @@ -64396,7 +60116,7 @@ var Poller = /** @class */ (function () { throw new Error("A cancel request is currently pending"); } return this.cancelPromise; - }; + } /** * Returns the state of the operation. * @@ -64445,29 +60165,379 @@ var Poller = /** @class */ (function () { * `../test/utils/testPoller.ts` * and look for the getOperationState implementation. */ - Poller.prototype.getOperationState = function () { + getOperationState() { return this.operation.state; - }; + } /** * Returns the result value of the operation, * regardless of the state of the poller. * It can return undefined or an incomplete form of the final TResult value * depending on the implementation. */ - Poller.prototype.getResult = function () { - var state = this.operation.state; + getResult() { + const state = this.operation.state; return state.result; - }; + } /** * Returns a serialized version of the poller's operation * by invoking the operation's toString method. */ - Poller.prototype.toString = function () { + toString() { return this.operation.toString(); - }; - return Poller; -}()); + } +} +// Copyright (c) Microsoft Corporation. +/** + * The `@azure/logger` configuration for this package. + * @internal + */ +const logger = logger$1.createClientLogger("core-lro"); + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Detects where the continuation token is and returns it. Notice that azure-asyncoperation + * must be checked first before the other location headers because there are scenarios + * where both azure-asyncoperation and location could be present in the same response but + * azure-asyncoperation should be the one to use for polling. + */ +function getPollingUrl(rawResponse, defaultPath) { + var _a, _b, _c; + return ((_c = (_b = (_a = getAzureAsyncOperation(rawResponse)) !== null && _a !== void 0 ? _a : getLocation(rawResponse)) !== null && _b !== void 0 ? _b : getOperationLocation(rawResponse)) !== null && _c !== void 0 ? _c : defaultPath); +} +function getLocation(rawResponse) { + return rawResponse.headers["location"]; +} +function getOperationLocation(rawResponse) { + return rawResponse.headers["operation-location"]; +} +function getAzureAsyncOperation(rawResponse) { + return rawResponse.headers["azure-asyncoperation"]; +} +function inferLroMode(requestPath, requestMethod, rawResponse) { + if (getAzureAsyncOperation(rawResponse) !== undefined) { + return { + mode: "AzureAsync", + resourceLocation: requestMethod === "PUT" + ? requestPath + : requestMethod === "POST" + ? getLocation(rawResponse) + : undefined + }; + } + else if (getLocation(rawResponse) !== undefined || + getOperationLocation(rawResponse) !== undefined) { + return { + mode: "Location" + }; + } + else if (["PUT", "PATCH"].includes(requestMethod)) { + return { + mode: "Body" + }; + } + return {}; +} +class SimpleRestError extends Error { + constructor(message, statusCode) { + super(message); + this.name = "RestError"; + this.statusCode = statusCode; + Object.setPrototypeOf(this, SimpleRestError.prototype); + } +} +function isUnexpectedInitialResponse(rawResponse) { + const code = rawResponse.statusCode; + if (![203, 204, 202, 201, 200, 500].includes(code)) { + throw new SimpleRestError(`Received unexpected HTTP status code ${code} in the initial response. This may indicate a server issue.`, code); + } + return false; +} +function isUnexpectedPollingResponse(rawResponse) { + const code = rawResponse.statusCode; + if (![202, 201, 200, 500].includes(code)) { + throw new SimpleRestError(`Received unexpected HTTP status code ${code} while polling. This may indicate a server issue.`, code); + } + return false; +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +const successStates = ["succeeded"]; +const failureStates = ["failed", "canceled", "cancelled"]; + +// Copyright (c) Microsoft Corporation. +function getResponseStatus(rawResponse) { + var _a; + const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; + return typeof status === "string" ? status.toLowerCase() : "succeeded"; +} +function isAzureAsyncPollingDone(rawResponse) { + const state = getResponseStatus(rawResponse); + if (isUnexpectedPollingResponse(rawResponse) || failureStates.includes(state)) { + throw new Error(`The long running operation has failed. The provisioning state: ${state}.`); + } + return successStates.includes(state); +} +/** + * Sends a request to the URI of the provisioned resource if needed. + */ +async function sendFinalRequest(lro, resourceLocation, lroResourceLocationConfig) { + switch (lroResourceLocationConfig) { + case "original-uri": + return lro.sendPollRequest(lro.requestPath); + case "azure-async-operation": + return undefined; + case "location": + default: + return lro.sendPollRequest(resourceLocation !== null && resourceLocation !== void 0 ? resourceLocation : lro.requestPath); + } +} +function processAzureAsyncOperationResult(lro, resourceLocation, lroResourceLocationConfig) { + return (response) => { + if (isAzureAsyncPollingDone(response.rawResponse)) { + if (resourceLocation === undefined) { + return Object.assign(Object.assign({}, response), { done: true }); + } + else { + return Object.assign(Object.assign({}, response), { done: false, next: async () => { + const finalResponse = await sendFinalRequest(lro, resourceLocation, lroResourceLocationConfig); + return Object.assign(Object.assign({}, (finalResponse !== null && finalResponse !== void 0 ? finalResponse : response)), { done: true }); + } }); + } + } + return Object.assign(Object.assign({}, response), { done: false }); + }; +} + +// Copyright (c) Microsoft Corporation. +function getProvisioningState(rawResponse) { + var _a, _b; + const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {}; + const state = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState; + return typeof state === "string" ? state.toLowerCase() : "succeeded"; +} +function isBodyPollingDone(rawResponse) { + const state = getProvisioningState(rawResponse); + if (isUnexpectedPollingResponse(rawResponse) || failureStates.includes(state)) { + throw new Error(`The long running operation has failed. The provisioning state: ${state}.`); + } + return successStates.includes(state); +} +/** + * Creates a polling strategy based on BodyPolling which uses the provisioning state + * from the result to determine the current operation state + */ +function processBodyPollingOperationResult(response) { + return Object.assign(Object.assign({}, response), { done: isBodyPollingDone(response.rawResponse) }); +} + +// Copyright (c) Microsoft Corporation. +function isLocationPollingDone(rawResponse) { + return !isUnexpectedPollingResponse(rawResponse) && rawResponse.statusCode !== 202; +} +function processLocationPollingOperationResult(response) { + return Object.assign(Object.assign({}, response), { done: isLocationPollingDone(response.rawResponse) }); +} + +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +function processPassthroughOperationResult(response) { + return Object.assign(Object.assign({}, response), { done: true }); +} + +// Copyright (c) Microsoft Corporation. +/** + * creates a stepping function that maps an LRO state to another. + */ +function createGetLroStatusFromResponse(lroPrimitives, config, lroResourceLocationConfig) { + switch (config.mode) { + case "AzureAsync": { + return processAzureAsyncOperationResult(lroPrimitives, config.resourceLocation, lroResourceLocationConfig); + } + case "Location": { + return processLocationPollingOperationResult; + } + case "Body": { + return processBodyPollingOperationResult; + } + default: { + return processPassthroughOperationResult; + } + } +} +/** + * Creates a polling operation. + */ +function createPoll(lroPrimitives) { + return async (path, pollerConfig, getLroStatusFromResponse) => { + const response = await lroPrimitives.sendPollRequest(path); + const retryAfter = response.rawResponse.headers["retry-after"]; + if (retryAfter !== undefined) { + const retryAfterInMs = parseInt(retryAfter); + pollerConfig.intervalInMs = isNaN(retryAfterInMs) + ? calculatePollingIntervalFromDate(new Date(retryAfter), pollerConfig.intervalInMs) + : retryAfterInMs; + } + return getLroStatusFromResponse(response); + }; +} +function calculatePollingIntervalFromDate(retryAfterDate, defaultIntervalInMs) { + const timeNow = Math.floor(new Date().getTime()); + const retryAfterTime = retryAfterDate.getTime(); + if (timeNow < retryAfterTime) { + return retryAfterTime - timeNow; + } + return defaultIntervalInMs; +} +/** + * Creates a callback to be used to initialize the polling operation state. + * @param state - of the polling operation + * @param operationSpec - of the LRO + * @param callback - callback to be called when the operation is done + * @returns callback that initializes the state of the polling operation + */ +function createInitializeState(state, requestPath, requestMethod) { + return (response) => { + if (isUnexpectedInitialResponse(response.rawResponse)) + ; + state.initialRawResponse = response.rawResponse; + state.isStarted = true; + state.pollingURL = getPollingUrl(state.initialRawResponse, requestPath); + state.config = inferLroMode(requestPath, requestMethod, state.initialRawResponse); + /** short circuit polling if body polling is done in the initial request */ + if (state.config.mode === undefined || + (state.config.mode === "Body" && isBodyPollingDone(state.initialRawResponse))) { + state.result = response.flatResponse; + state.isCompleted = true; + } + logger.verbose(`LRO: initial state: ${JSON.stringify(state)}`); + return Boolean(state.isCompleted); + }; +} + +// Copyright (c) Microsoft Corporation. +class GenericPollOperation { + constructor(state, lro, lroResourceLocationConfig, processResult, updateState, isDone) { + this.state = state; + this.lro = lro; + this.lroResourceLocationConfig = lroResourceLocationConfig; + this.processResult = processResult; + this.updateState = updateState; + this.isDone = isDone; + } + setPollerConfig(pollerConfig) { + this.pollerConfig = pollerConfig; + } + /** + * General update function for LROPoller, the general process is as follows + * 1. Check initial operation result to determine the strategy to use + * - Strategies: Location, Azure-AsyncOperation, Original Uri + * 2. Check if the operation result has a terminal state + * - Terminal state will be determined by each strategy + * 2.1 If it is terminal state Check if a final GET request is required, if so + * send final GET request and return result from operation. If no final GET + * is required, just return the result from operation. + * - Determining what to call for final request is responsibility of each strategy + * 2.2 If it is not terminal state, call the polling operation and go to step 1 + * - Determining what to call for polling is responsibility of each strategy + * - Strategies will always use the latest URI for polling if provided otherwise + * the last known one + */ + async update(options) { + var _a, _b, _c; + const state = this.state; + let lastResponse = undefined; + if (!state.isStarted) { + const initializeState = createInitializeState(state, this.lro.requestPath, this.lro.requestMethod); + lastResponse = await this.lro.sendInitialRequest(); + initializeState(lastResponse); + } + if (!state.isCompleted) { + if (!this.poll || !this.getLroStatusFromResponse) { + if (!state.config) { + throw new Error("Bad state: LRO mode is undefined. Please check if the serialized state is well-formed."); + } + const isDone = this.isDone; + this.getLroStatusFromResponse = isDone + ? (response) => (Object.assign(Object.assign({}, response), { done: isDone(response.flatResponse, this.state) })) + : createGetLroStatusFromResponse(this.lro, state.config, this.lroResourceLocationConfig); + this.poll = createPoll(this.lro); + } + if (!state.pollingURL) { + throw new Error("Bad state: polling URL is undefined. Please check if the serialized state is well-formed."); + } + const currentState = await this.poll(state.pollingURL, this.pollerConfig, this.getLroStatusFromResponse); + logger.verbose(`LRO: polling response: ${JSON.stringify(currentState.rawResponse)}`); + if (currentState.done) { + state.result = this.processResult + ? this.processResult(currentState.flatResponse, state) + : currentState.flatResponse; + state.isCompleted = true; + } + else { + this.poll = (_a = currentState.next) !== null && _a !== void 0 ? _a : this.poll; + state.pollingURL = getPollingUrl(currentState.rawResponse, state.pollingURL); + } + lastResponse = currentState; + } + logger.verbose(`LRO: current state: ${JSON.stringify(state)}`); + if (lastResponse) { + (_b = this.updateState) === null || _b === void 0 ? void 0 : _b.call(this, state, lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.rawResponse); + } + else { + logger.error(`LRO: no response was received`); + } + (_c = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _c === void 0 ? void 0 : _c.call(options, state); + return this; + } + async cancel() { + this.state.isCancelled = true; + return this; + } + /** + * Serializes the Poller operation. + */ + toString() { + return JSON.stringify({ + state: this.state + }); + } +} + +// Copyright (c) Microsoft Corporation. +function deserializeState(serializedState) { + try { + return JSON.parse(serializedState).state; + } + catch (e) { + throw new Error(`LroEngine: Unable to deserialize state: ${serializedState}`); + } +} +/** + * The LRO Engine, a class that performs polling. + */ +class LroEngine extends Poller { + constructor(lro, options) { + const { intervalInMs = 2000, resumeFrom } = options || {}; + const state = resumeFrom + ? deserializeState(resumeFrom) + : {}; + const operation = new GenericPollOperation(state, lro, options === null || options === void 0 ? void 0 : options.lroResourceLocationConfig, options === null || options === void 0 ? void 0 : options.processResult, options === null || options === void 0 ? void 0 : options.updateState, options === null || options === void 0 ? void 0 : options.isDone); + super(operation); + this.config = { intervalInMs: intervalInMs }; + operation.setPollerConfig(this.config); + } + /** + * The method used by the poller to wait before attempting to update its operation. + */ + delay() { + return new Promise((resolve) => setTimeout(() => resolve(), this.config.intervalInMs)); + } +} + +exports.LroEngine = LroEngine; exports.Poller = Poller; exports.PollerCancelledError = PollerCancelledError; exports.PollerStoppedError = PollerStoppedError; @@ -64673,83 +60743,7 @@ var isArray = Array.isArray || function (xs) { /***/ }), /* 897 */, -/* 898 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; -/*! - * Copyright (c) 2015, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of Salesforce.com nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -const pubsuffix = __webpack_require__(324); - -// Gives the permutation of all possible domainMatch()es of a given domain. The -// array is in shortest-to-longest order. Handy for indexing. -const SPECIAL_USE_DOMAINS = ["local"]; // RFC 6761 -function permuteDomain(domain, allowSpecialUseDomain) { - let pubSuf = null; - if (allowSpecialUseDomain) { - const domainParts = domain.split("."); - if (SPECIAL_USE_DOMAINS.includes(domainParts[domainParts.length - 1])) { - pubSuf = `${domainParts[domainParts.length - 2]}.${ - domainParts[domainParts.length - 1] - }`; - } else { - pubSuf = pubsuffix.getPublicSuffix(domain); - } - } else { - pubSuf = pubsuffix.getPublicSuffix(domain); - } - - if (!pubSuf) { - return null; - } - if (pubSuf == domain) { - return [domain]; - } - - const prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com" - const parts = prefix.split(".").reverse(); - let cur = pubSuf; - const permutations = [cur]; - while (parts.length) { - cur = `${parts.shift()}.${cur}`; - permutations.push(cur); - } - return permutations; -} - -exports.permuteDomain = permuteDomain; - - -/***/ }), +/* 898 */, /* 899 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -65213,9 +61207,11 @@ __exportStar(__webpack_require__(764), exports); */ Object.defineProperty(exports, "__esModule", { value: true }); exports.TraceAPI = void 0; +var global_utils_1 = __webpack_require__(525); var ProxyTracerProvider_1 = __webpack_require__(394); var spancontext_utils_1 = __webpack_require__(629); -var global_utils_1 = __webpack_require__(525); +var context_utils_1 = __webpack_require__(720); +var diag_1 = __webpack_require__(387); var API_NAME = 'trace'; /** * Singleton object which represents the entry point to the OpenTelemetry Tracing API @@ -65224,7 +61220,13 @@ var TraceAPI = /** @class */ (function () { /** Empty private constructor prevents end users from constructing a new instance of the API */ function TraceAPI() { this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); + this.wrapSpanContext = spancontext_utils_1.wrapSpanContext; this.isSpanContextValid = spancontext_utils_1.isSpanContextValid; + this.deleteSpan = context_utils_1.deleteSpan; + this.getSpan = context_utils_1.getSpan; + this.getSpanContext = context_utils_1.getSpanContext; + this.setSpan = context_utils_1.setSpan; + this.setSpanContext = context_utils_1.setSpanContext; } /** Get the singleton instance of the Trace API */ TraceAPI.getInstance = function () { @@ -65234,12 +61236,16 @@ var TraceAPI = /** @class */ (function () { return this._instance; }; /** - * Set the current global tracer. Returns the initialized global tracer provider + * Set the current global tracer. + * + * @returns true if the tracer provider was successfully registered, else false */ TraceAPI.prototype.setGlobalTracerProvider = function (provider) { - this._proxyTracerProvider.setDelegate(provider); - global_utils_1.registerGlobal(API_NAME, this._proxyTracerProvider); - return this._proxyTracerProvider; + var success = global_utils_1.registerGlobal(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance()); + if (success) { + this._proxyTracerProvider.setDelegate(provider); + } + return success; }; /** * Returns the global tracer provider. @@ -65255,7 +61261,7 @@ var TraceAPI = /** @class */ (function () { }; /** Remove the global tracer provider */ TraceAPI.prototype.disable = function () { - global_utils_1.unregisterGlobal(API_NAME); + global_utils_1.unregisterGlobal(API_NAME, diag_1.DiagAPI.instance()); this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); }; return TraceAPI; @@ -65291,7 +61297,7 @@ exports.TraceAPI = TraceAPI; * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); -exports.NOOP_TEXT_MAP_PROPAGATOR = exports.NoopTextMapPropagator = void 0; +exports.NoopTextMapPropagator = void 0; /** * No-op implementations of {@link TextMapPropagator}. */ @@ -65310,7 +61316,6 @@ var NoopTextMapPropagator = /** @class */ (function () { return NoopTextMapPropagator; }()); exports.NoopTextMapPropagator = NoopTextMapPropagator; -exports.NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator(); //# sourceMappingURL=NoopTextMapPropagator.js.map /***/ }), @@ -65750,143 +61755,92 @@ Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var tslib = __webpack_require__(748); var util = _interopDefault(__webpack_require__(669)); var os = __webpack_require__(87); // Copyright (c) Microsoft Corporation. -function log(message) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - process.stderr.write("" + util.format.apply(util, tslib.__spread([message], args)) + os.EOL); +function log(message, ...args) { + process.stderr.write(`${util.format(message, ...args)}${os.EOL}`); } // Copyright (c) Microsoft Corporation. -var debugEnvVariable = (typeof process !== "undefined" && process.env && process.env.DEBUG) || undefined; -var enabledString; -var enabledNamespaces = []; -var skippedNamespaces = []; -var debuggers = []; +const debugEnvVariable = (typeof process !== "undefined" && process.env && process.env.DEBUG) || undefined; +let enabledString; +let enabledNamespaces = []; +let skippedNamespaces = []; +const debuggers = []; if (debugEnvVariable) { enable(debugEnvVariable); } -var debugObj = Object.assign(function (namespace) { +const debugObj = Object.assign((namespace) => { return createDebugger(namespace); }, { - enable: enable, - enabled: enabled, - disable: disable, - log: log + enable, + enabled, + disable, + log }); function enable(namespaces) { - var e_1, _a, e_2, _b; enabledString = namespaces; enabledNamespaces = []; skippedNamespaces = []; - var wildcard = /\*/g; - var namespaceList = namespaces.split(",").map(function (ns) { return ns.trim().replace(wildcard, ".*?"); }); - try { - for (var namespaceList_1 = tslib.__values(namespaceList), namespaceList_1_1 = namespaceList_1.next(); !namespaceList_1_1.done; namespaceList_1_1 = namespaceList_1.next()) { - var ns = namespaceList_1_1.value; - if (ns.startsWith("-")) { - skippedNamespaces.push(new RegExp("^" + ns.substr(1) + "$")); - } - else { - enabledNamespaces.push(new RegExp("^" + ns + "$")); - } + const wildcard = /\*/g; + const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); + for (const ns of namespaceList) { + if (ns.startsWith("-")) { + skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); + } + else { + enabledNamespaces.push(new RegExp(`^${ns}$`)); } } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (namespaceList_1_1 && !namespaceList_1_1.done && (_a = namespaceList_1.return)) _a.call(namespaceList_1); - } - finally { if (e_1) throw e_1.error; } - } - try { - for (var debuggers_1 = tslib.__values(debuggers), debuggers_1_1 = debuggers_1.next(); !debuggers_1_1.done; debuggers_1_1 = debuggers_1.next()) { - var instance = debuggers_1_1.value; - instance.enabled = enabled(instance.namespace); - } - } - catch (e_2_1) { e_2 = { error: e_2_1 }; } - finally { - try { - if (debuggers_1_1 && !debuggers_1_1.done && (_b = debuggers_1.return)) _b.call(debuggers_1); - } - finally { if (e_2) throw e_2.error; } + for (const instance of debuggers) { + instance.enabled = enabled(instance.namespace); } } function enabled(namespace) { - var e_3, _a, e_4, _b; if (namespace.endsWith("*")) { return true; } - try { - for (var skippedNamespaces_1 = tslib.__values(skippedNamespaces), skippedNamespaces_1_1 = skippedNamespaces_1.next(); !skippedNamespaces_1_1.done; skippedNamespaces_1_1 = skippedNamespaces_1.next()) { - var skipped = skippedNamespaces_1_1.value; - if (skipped.test(namespace)) { - return false; - } + for (const skipped of skippedNamespaces) { + if (skipped.test(namespace)) { + return false; } } - catch (e_3_1) { e_3 = { error: e_3_1 }; } - finally { - try { - if (skippedNamespaces_1_1 && !skippedNamespaces_1_1.done && (_a = skippedNamespaces_1.return)) _a.call(skippedNamespaces_1); + for (const enabledNamespace of enabledNamespaces) { + if (enabledNamespace.test(namespace)) { + return true; } - finally { if (e_3) throw e_3.error; } - } - try { - for (var enabledNamespaces_1 = tslib.__values(enabledNamespaces), enabledNamespaces_1_1 = enabledNamespaces_1.next(); !enabledNamespaces_1_1.done; enabledNamespaces_1_1 = enabledNamespaces_1.next()) { - var enabledNamespace = enabledNamespaces_1_1.value; - if (enabledNamespace.test(namespace)) { - return true; - } - } - } - catch (e_4_1) { e_4 = { error: e_4_1 }; } - finally { - try { - if (enabledNamespaces_1_1 && !enabledNamespaces_1_1.done && (_b = enabledNamespaces_1.return)) _b.call(enabledNamespaces_1); - } - finally { if (e_4) throw e_4.error; } } return false; } function disable() { - var result = enabledString || ""; + const result = enabledString || ""; enable(""); return result; } function createDebugger(namespace) { - var newDebugger = Object.assign(debug, { + const newDebugger = Object.assign(debug, { enabled: enabled(namespace), - destroy: destroy, + destroy, log: debugObj.log, - namespace: namespace, - extend: extend + namespace, + extend }); - function debug() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } + function debug(...args) { if (!newDebugger.enabled) { return; } if (args.length > 0) { - args[0] = namespace + " " + args[0]; + args[0] = `${namespace} ${args[0]}`; } - newDebugger.log.apply(newDebugger, tslib.__spread(args)); + newDebugger.log(...args); } debuggers.push(newDebugger); return newDebugger; } function destroy() { - var index = debuggers.indexOf(this); + const index = debuggers.indexOf(this); if (index >= 0) { debuggers.splice(index, 1); return true; @@ -65894,36 +61848,32 @@ function destroy() { return false; } function extend(namespace) { - var newDebugger = createDebugger(this.namespace + ":" + namespace); + const newDebugger = createDebugger(`${this.namespace}:${namespace}`); newDebugger.log = this.log; return newDebugger; } // Copyright (c) Microsoft Corporation. -var registeredLoggers = new Set(); -var logLevelFromEnv = (typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL) || undefined; -var azureLogLevel; +const registeredLoggers = new Set(); +const logLevelFromEnv = (typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL) || undefined; +let azureLogLevel; /** * The AzureLogger provides a mechanism for overriding where logs are output to. * By default, logs are sent to stderr. * Override the `log` method to redirect logs to another location. */ -var AzureLogger = debugObj("azure"); -AzureLogger.log = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - debugObj.log.apply(debugObj, tslib.__spread(args)); +const AzureLogger = debugObj("azure"); +AzureLogger.log = (...args) => { + debugObj.log(...args); }; -var AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; +const AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"]; if (logLevelFromEnv) { // avoid calling setLogLevel because we don't want a mis-set environment variable to crash if (isAzureLogLevel(logLevelFromEnv)) { setLogLevel(logLevelFromEnv); } else { - console.error("AZURE_LOG_LEVEL set to unknown log level '" + logLevelFromEnv + "'; logging is not enabled. Acceptable values: " + AZURE_LOG_LEVELS.join(", ") + "."); + console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`); } } /** @@ -65936,27 +61886,16 @@ if (logLevelFromEnv) { * - error */ function setLogLevel(level) { - var e_1, _a; if (level && !isAzureLogLevel(level)) { - throw new Error("Unknown log level '" + level + "'. Acceptable values: " + AZURE_LOG_LEVELS.join(",")); + throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`); } azureLogLevel = level; - var enabledNamespaces = []; - try { - for (var registeredLoggers_1 = tslib.__values(registeredLoggers), registeredLoggers_1_1 = registeredLoggers_1.next(); !registeredLoggers_1_1.done; registeredLoggers_1_1 = registeredLoggers_1.next()) { - var logger = registeredLoggers_1_1.value; - if (shouldEnable(logger)) { - enabledNamespaces.push(logger.namespace); - } + const enabledNamespaces = []; + for (const logger of registeredLoggers) { + if (shouldEnable(logger)) { + enabledNamespaces.push(logger.namespace); } } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (registeredLoggers_1_1 && !registeredLoggers_1_1.done && (_a = registeredLoggers_1.return)) _a.call(registeredLoggers_1); - } - finally { if (e_1) throw e_1.error; } - } debugObj.enable(enabledNamespaces.join(",")); } /** @@ -65965,7 +61904,7 @@ function setLogLevel(level) { function getLogLevel() { return azureLogLevel; } -var levelMap = { +const levelMap = { verbose: 400, info: 300, warning: 200, @@ -65977,7 +61916,7 @@ var levelMap = { * @hidden */ function createClientLogger(namespace) { - var clientRootLogger = AzureLogger.extend(namespace); + const clientRootLogger = AzureLogger.extend(namespace); patchLogMethod(AzureLogger, clientRootLogger); return { error: createLogger(clientRootLogger, "error"), @@ -65987,21 +61926,17 @@ function createClientLogger(namespace) { }; } function patchLogMethod(parent, child) { - child.log = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - parent.log.apply(parent, tslib.__spread(args)); + child.log = (...args) => { + parent.log(...args); }; } function createLogger(parent, level) { - var logger = Object.assign(parent.extend(level), { - level: level + const logger = Object.assign(parent.extend(level), { + level }); patchLogMethod(parent, logger); if (shouldEnable(logger)) { - var enabledNamespaces = debugObj.disable(); + const enabledNamespaces = debugObj.disable(); debugObj.enable(enabledNamespaces + "," + logger.namespace); } registeredLoggers.add(logger); @@ -66107,30 +62042,7 @@ var SpanStatusCode; /* 935 */, /* 936 */, /* 937 */, -/* 938 */ -/***/ (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=Baggage.js.map - -/***/ }), +/* 938 */, /* 939 */ /***/ (function(module, __unusedexports, __webpack_require__) { @@ -66170,36 +62082,7 @@ function terminator(callback) /* 941 */, /* 942 */, /* 943 */, -/* 944 */ -/***/ (function(__unusedmodule, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = rng; - -var _crypto = _interopRequireDefault(__webpack_require__(417)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate - -let poolPtr = rnds8Pool.length; - -function rng() { - if (poolPtr > rnds8Pool.length - 16) { - _crypto.default.randomFillSync(rnds8Pool); - - poolPtr = 0; - } - - return rnds8Pool.slice(poolPtr, poolPtr += 16); -} - -/***/ }), +/* 944 */, /* 945 */, /* 946 */, /* 947 */, @@ -67591,7 +63474,7 @@ exports.getExecOutput = getExecOutput; Object.defineProperty(exports, "__esModule", { value: true }); exports.isCompatible = exports._makeCompatibilityCheck = void 0; var version_1 = __webpack_require__(830); -var re = /^(\d+)\.(\d+)\.(\d+)(?:-(.*))?$/; +var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; /** * Create a function to test an API version to see if it is compatible with the provided ownVersion. * @@ -67620,7 +63503,14 @@ function _makeCompatibilityCheck(ownVersion) { major: +myVersionMatch[1], minor: +myVersionMatch[2], patch: +myVersionMatch[3], + prerelease: myVersionMatch[4], }; + // if ownVersion has a prerelease tag, versions must match exactly + if (ownVersionParsed.prerelease != null) { + return function isExactmatch(globalVersion) { + return globalVersion === ownVersion; + }; + } function _reject(v) { rejectedVersions.add(v); return false; @@ -67646,7 +63536,12 @@ function _makeCompatibilityCheck(ownVersion) { major: +globalVersionMatch[1], minor: +globalVersionMatch[2], patch: +globalVersionMatch[3], + prerelease: globalVersionMatch[4], }; + // if globalVersion has a prerelease tag, versions must match exactly + if (globalVersionParsed.prerelease != null) { + return _reject(globalVersion); + } // major versions must match if (ownVersionParsed.major !== globalVersionParsed.major) { return _reject(globalVersion); @@ -67749,9 +63644,8 @@ Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var tslib = __webpack_require__(865); var uuid = __webpack_require__(585); -var tough = __webpack_require__(393); +var tough = __webpack_require__(701); var http = __webpack_require__(605); var https = __webpack_require__(211); var node_fetch = _interopDefault(__webpack_require__(454)); @@ -67762,11 +63656,12 @@ var url = __webpack_require__(835); var stream = __webpack_require__(794); var logger$1 = __webpack_require__(928); var tunnel = __webpack_require__(413); +var tslib = __webpack_require__(865); var coreAuth = __webpack_require__(229); var xml2js = __webpack_require__(992); var os = __webpack_require__(87); var coreTracing = __webpack_require__(263); -__webpack_require__(71); +__webpack_require__(338); // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -67778,7 +63673,7 @@ function getHeaderKey(headerName) { } function isHttpHeadersLike(object) { if (object && typeof object === "object") { - var castObject = object; + const castObject = object; if (typeof castObject.rawHeaders === "function" && typeof castObject.clone === "function" && typeof castObject.get === "function" && @@ -67797,11 +63692,11 @@ function isHttpHeadersLike(object) { /** * A collection of HTTP header key/value pairs. */ -var HttpHeaders = /** @class */ (function () { - function HttpHeaders(rawHeaders) { +class HttpHeaders { + constructor(rawHeaders) { this._headersMap = {}; if (rawHeaders) { - for (var headerName in rawHeaders) { + for (const headerName in rawHeaders) { this.set(headerName, rawHeaders[headerName]); } } @@ -67812,100 +63707,104 @@ var HttpHeaders = /** @class */ (function () { * @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) { + set(headerName, headerValue) { this._headersMap[getHeaderKey(headerName)] = { name: headerName, value: headerValue.toString() }; - }; + } /** * 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. */ - HttpHeaders.prototype.get = function (headerName) { - var header = this._headersMap[getHeaderKey(headerName)]; + get(headerName) { + const header = this._headersMap[getHeaderKey(headerName)]; return !header ? undefined : header.value; - }; + } /** * Get whether or not this header collection contains a header entry for the provided header name. */ - HttpHeaders.prototype.contains = function (headerName) { + contains(headerName) { return !!this._headersMap[getHeaderKey(headerName)]; - }; + } /** * 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. */ - HttpHeaders.prototype.remove = function (headerName) { - var result = this.contains(headerName); + remove(headerName) { + const result = this.contains(headerName); delete this._headersMap[getHeaderKey(headerName)]; return result; - }; + } /** * Get the headers that are contained this collection as an object. */ - HttpHeaders.prototype.rawHeaders = function () { - var result = {}; - for (var headerKey in this._headersMap) { - var header = this._headersMap[headerKey]; + rawHeaders() { + const result = {}; + for (const headerKey in this._headersMap) { + const header = this._headersMap[headerKey]; result[header.name.toLowerCase()] = header.value; } return result; - }; + } /** * Get the headers that are contained in this collection as an array. */ - HttpHeaders.prototype.headersArray = function () { - var headers = []; - for (var headerKey in this._headersMap) { + headersArray() { + const headers = []; + for (const headerKey in this._headersMap) { headers.push(this._headersMap[headerKey]); } return headers; - }; + } /** * Get the header names that are contained in this collection. */ - HttpHeaders.prototype.headerNames = function () { - var headerNames = []; - var headers = this.headersArray(); - for (var i = 0; i < headers.length; ++i) { + headerNames() { + const headerNames = []; + const headers = this.headersArray(); + for (let i = 0; i < headers.length; ++i) { headerNames.push(headers[i].name); } return headerNames; - }; + } /** * Get the header values that are contained in this collection. */ - HttpHeaders.prototype.headerValues = function () { - var headerValues = []; - var headers = this.headersArray(); - for (var i = 0; i < headers.length; ++i) { + headerValues() { + const headerValues = []; + const headers = this.headersArray(); + for (let i = 0; i < headers.length; ++i) { headerValues.push(headers[i].value); } return headerValues; - }; + } /** * Get the JSON object representation of this HTTP header collection. */ - HttpHeaders.prototype.toJson = function () { + toJson() { return this.rawHeaders(); - }; + } /** * Get the string representation of this HTTP header collection. */ - HttpHeaders.prototype.toString = function () { + toString() { return JSON.stringify(this.toJson()); - }; + } /** * Create a deep clone/copy of this HttpHeaders collection. */ - HttpHeaders.prototype.clone = function () { - return new HttpHeaders(this.rawHeaders()); - }; - return HttpHeaders; -}()); + clone() { + const resultPreservingCasing = {}; + for (const headerKey in this._headersMap) { + const header = this._headersMap[headerKey]; + resultPreservingCasing[header.name] = header.value; + } + return new HttpHeaders(resultPreservingCasing); + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -67923,7 +63822,7 @@ function encodeString(value) { function encodeByteArray(value) { // Buffer.from accepts | -- the TypeScript definition is off here // https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length - var bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer); + const bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer); return bufferValue.toString("base64"); } /** @@ -67936,11 +63835,11 @@ function decodeString(value) { // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -var Constants = { +const Constants = { /** * The core-http version */ - coreHttpVersion: "1.2.6", + coreHttpVersion: "2.2.2", /** * Specifies HTTP. */ @@ -67979,7 +63878,8 @@ var Constants = { PATCH: "PATCH" }, StatusCodes: { - TooManyRequests: 429 + TooManyRequests: 429, + ServiceUnavailable: 503 } }, /** @@ -68009,18 +63909,18 @@ var Constants = { /** * Default key used to access the XML attributes. */ -var XML_ATTRKEY = "$"; +const XML_ATTRKEY = "$"; /** * Default key used to access the XML value content. */ -var XML_CHARKEY = "_"; +const 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; +const 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; /** * A constant that indicates whether the environment is node.js or browser based. */ -var isNode = typeof process !== "undefined" && +const isNode = typeof process !== "undefined" && !!process.version && !!process.versions && !!process.versions.node; @@ -68046,7 +63946,7 @@ function encodeUri(uri) { * @returns The stripped version of Http Response. */ function stripResponse(response) { - var strippedResponse = {}; + const strippedResponse = {}; strippedResponse.body = response.bodyAsText; strippedResponse.headers = response.headers; strippedResponse.status = response.status; @@ -68060,7 +63960,7 @@ function stripResponse(response) { * @returns The stripped version of Http Request. */ function stripRequest(request) { - var strippedRequest = request.clone(); + const strippedRequest = request.clone(); if (strippedRequest.headers) { strippedRequest.headers.remove("authorization"); } @@ -68093,21 +63993,12 @@ function generateUuid() { * @returns A chain of resolved or rejected promises */ function executePromisesSequentially(promiseFactories, kickstart) { - var result = Promise.resolve(kickstart); - promiseFactories.forEach(function (promiseFactory) { + let result = Promise.resolve(kickstart); + promiseFactories.forEach((promiseFactory) => { result = result.then(promiseFactory); }); return result; } -/** - * 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 - */ -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 @@ -68120,13 +64011,13 @@ function promiseToCallback(promise) { throw new Error("The provided input is not a Promise."); } // eslint-disable-next-line @typescript-eslint/ban-types - return function (cb) { + return (cb) => { promise - .then(function (data) { + .then((data) => { // eslint-disable-next-line promise/no-callback-in-promise return cb(undefined, data); }) - .catch(function (err) { + .catch((err) => { // eslint-disable-next-line promise/no-callback-in-promise cb(err); }); @@ -68141,26 +64032,25 @@ function promiseToServiceCallback(promise) { if (typeof promise.then !== "function") { throw new Error("The provided input is not a Promise."); } - return function (cb) { + return (cb) => { promise - .then(function (data) { + .then((data) => { return process.nextTick(cb, undefined, data.parsedBody, data.request, data); }) - .catch(function (err) { + .catch((err) => { process.nextTick(cb, err); }); }; } function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) { - var _a, _b, _c; if (!Array.isArray(obj)) { obj = [obj]; } if (!xmlNamespaceKey || !xmlNamespace) { - return _a = {}, _a[elementName] = obj, _a; + return { [elementName]: obj }; } - var result = (_b = {}, _b[elementName] = obj, _b); - result[XML_ATTRKEY] = (_c = {}, _c[xmlNamespaceKey] = xmlNamespace, _c); + const result = { [elementName]: obj }; + result[XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace }; return result; } /** @@ -68169,14 +64059,14 @@ function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) { * @param 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) { + const castTargetCtorParam = targetCtorParam; + sourceCtors.forEach((sourceCtor) => { + Object.getOwnPropertyNames(sourceCtor.prototype).forEach((name) => { castTargetCtorParam.prototype[name] = sourceCtor.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)?)?$/; +const 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. @@ -68226,19 +64116,18 @@ function isObject(input) { } // Copyright (c) Microsoft Corporation. -var Serializer = /** @class */ (function () { - function Serializer(modelMappers, isXML) { - if (modelMappers === void 0) { modelMappers = {}; } +class Serializer { + constructor(modelMappers = {}, isXML) { this.modelMappers = modelMappers; this.isXML = isXML; } - Serializer.prototype.validateConstraints = function (mapper, value, objectName) { - var failValidation = function (constraintName, constraintValue) { - throw new Error("\"" + objectName + "\" with value \"" + value + "\" should satisfy the constraint \"" + constraintName + "\": " + constraintValue + "."); + validateConstraints(mapper, value, objectName) { + const failValidation = (constraintName, constraintValue) => { + 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; + const valueAsNumber = value; + const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems } = mapper.constraints; if (ExclusiveMaximum != undefined && valueAsNumber >= ExclusiveMaximum) { failValidation("ExclusiveMaximum", ExclusiveMaximum); } @@ -68251,7 +64140,7 @@ var Serializer = /** @class */ (function () { if (InclusiveMinimum != undefined && valueAsNumber < InclusiveMinimum) { failValidation("InclusiveMinimum", InclusiveMinimum); } - var valueAsArray = value; + const valueAsArray = value; if (MaxItems != undefined && valueAsArray.length > MaxItems) { failValidation("MaxItems", MaxItems); } @@ -68268,17 +64157,17 @@ var Serializer = /** @class */ (function () { failValidation("MultipleOf", MultipleOf); } if (Pattern) { - var pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern; + const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern; if (typeof value !== "string" || value.match(pattern) === null) { failValidation("Pattern", Pattern); } } if (UniqueItems && - valueAsArray.some(function (item, i, ar) { return ar.indexOf(item) !== i; })) { + valueAsArray.some((item, i, ar) => ar.indexOf(item) !== i)) { failValidation("UniqueItems", UniqueItems); } } - }; + } /** * Serialize the given object based on its metadata defined in the mapper * @@ -68288,16 +64177,15 @@ var Serializer = /** @class */ (function () { * @param options - additional options to deserialization * @returns A valid serialized Javascript object */ - Serializer.prototype.serialize = function (mapper, object, objectName, options) { + serialize(mapper, object, objectName, options = {}) { var _a, _b, _c; - if (options === void 0) { options = {}; } - var updatedOptions = { + const 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 }; - var payload = {}; - var mapperType = mapper.type.name; + let payload = {}; + const mapperType = mapper.type.name; if (!objectName) { objectName = mapper.serializedName; } @@ -68316,15 +64204,15 @@ var Serializer = /** @class */ (function () { // true || null | undefined/null // false || X | undefined // undefined || X | undefined/null - var required = mapper.required, nullable = mapper.nullable; + const { required, nullable } = mapper; if (required && nullable && object === undefined) { - throw new Error(objectName + " cannot be undefined."); + throw new Error(`${objectName} cannot be undefined.`); } if (required && !nullable && object == undefined) { - throw new Error(objectName + " cannot be null or undefined."); + throw new Error(`${objectName} cannot be null or undefined.`); } if (!required && nullable === false && object === null) { - throw new Error(objectName + " cannot be null."); + throw new Error(`${objectName} cannot be null.`); } if (object == undefined) { payload = object; @@ -68339,7 +64227,7 @@ var Serializer = /** @class */ (function () { payload = serializeBasicTypes(mapperType, objectName, object); } else if (mapperType.match(/^Enum$/i) !== null) { - var enumMapper = mapper; + const enumMapper = mapper; payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object); } else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) { @@ -68362,7 +64250,7 @@ var Serializer = /** @class */ (function () { } } return payload; - }; + } /** * Deserialize the given object based on its metadata defined in the mapper * @@ -68372,10 +64260,9 @@ var Serializer = /** @class */ (function () { * @param options - Controls behavior of XML parser and builder. * @returns A valid deserialized Javascript object */ - Serializer.prototype.deserialize = function (mapper, responseBody, objectName, options) { + deserialize(mapper, responseBody, objectName, options = {}) { var _a, _b, _c; - if (options === void 0) { options = {}; } - var updatedOptions = { + const 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 @@ -68393,8 +64280,8 @@ var Serializer = /** @class */ (function () { } return responseBody; } - var payload; - var mapperType = mapper.type.name; + let payload; + const mapperType = mapper.type.name; if (!objectName) { objectName = mapper.serializedName; } @@ -68403,8 +64290,8 @@ var Serializer = /** @class */ (function () { } else { if (this.isXML) { - var xmlCharKey = updatedOptions.xmlCharKey; - var castResponseBody = responseBody; + const xmlCharKey = updatedOptions.xmlCharKey; + const 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, @@ -68458,11 +64345,10 @@ var Serializer = /** @class */ (function () { payload = mapper.defaultValue; } return payload; - }; - return Serializer; -}()); + } +} function trimEnd(str, ch) { - var len = str.length; + let len = str.length; while (len - 1 >= 0 && str[len - 1] === ch) { --len; } @@ -68473,10 +64359,10 @@ function bufferToBase64Url(buffer) { return undefined; } if (!(buffer instanceof Uint8Array)) { - throw new Error("Please provide an input of type Uint8Array for converting to Base64Url."); + throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`); } // Uint8Array to Base64. - var str = encodeByteArray(buffer); + const str = encodeByteArray(buffer); // Base64 to Base64Url. return trimEnd(str, "=") .replace(/\+/g, "-") @@ -68495,12 +64381,11 @@ function base64UrlToByteArray(str) { return decodeString(str); } function splitSerializeName(prop) { - var classes = []; - var partialclass = ""; + const classes = []; + let partialclass = ""; if (prop) { - var subwords = prop.split("."); - for (var _i = 0, subwords_1 = subwords; _i < subwords_1.length; _i++) { - var item = subwords_1[_i]; + const subwords = prop.split("."); + for (const item of subwords) { if (item.charAt(item.length - 1) === "\\") { partialclass += item.substr(0, item.length - 1) + "."; } @@ -68532,32 +64417,32 @@ function serializeBasicTypes(typeName, objectName, value) { if (value !== null && value !== undefined) { if (typeName.match(/^Number$/i) !== null) { if (typeof value !== "number") { - throw new Error(objectName + " with value " + value + " must be of type number."); + throw new Error(`${objectName} with value ${value} must be of type number.`); } } else if (typeName.match(/^String$/i) !== null) { if (typeof value.valueOf() !== "string") { - throw new Error(objectName + " with value \"" + value + "\" must be of type string."); + throw new Error(`${objectName} with value "${value}" must be of type string.`); } } else if (typeName.match(/^Uuid$/i) !== null) { if (!(typeof value.valueOf() === "string" && isValidUuid(value))) { - throw new Error(objectName + " with value \"" + value + "\" must be of type string and a valid uuid."); + throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`); } } else if (typeName.match(/^Boolean$/i) !== null) { if (typeof value !== "boolean") { - throw new Error(objectName + " with value " + value + " must be of type boolean."); + throw new Error(`${objectName} with value ${value} must be of type boolean.`); } } else if (typeName.match(/^Stream$/i) !== null) { - var objectType = typeof value; + const objectType = typeof value; if (objectType !== "string" && objectType !== "function" && !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value) && !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob)) { - throw new Error(objectName + " must be a string, Blob, ArrayBuffer, ArrayBufferView, or a function returning NodeJS.ReadableStream."); + throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, or a function returning NodeJS.ReadableStream.`); } } } @@ -68565,34 +64450,34 @@ function serializeBasicTypes(typeName, objectName, value) { } function serializeEnumType(objectName, allowedValues, value) { if (!allowedValues) { - throw new Error("Please provide a set of allowedValues to validate " + objectName + " as an Enum Type."); + throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`); } - var isPresent = allowedValues.some(function (item) { + const isPresent = allowedValues.some((item) => { if (typeof item.valueOf() === "string") { return item.toLowerCase() === value.toLowerCase(); } return item === value; }); if (!isPresent) { - throw new Error(value + " is not a valid value for " + objectName + ". The valid values are: " + JSON.stringify(allowedValues) + "."); + throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`); } return value; } function serializeByteArrayType(objectName, value) { - var returnValue = ""; + let returnValue = ""; if (value != undefined) { if (!(value instanceof Uint8Array)) { - throw new Error(objectName + " must be of type Uint8Array."); + throw new Error(`${objectName} must be of type Uint8Array.`); } returnValue = encodeByteArray(value); } return returnValue; } function serializeBase64UrlType(objectName, value) { - var returnValue = ""; + let returnValue = ""; if (value != undefined) { if (!(value instanceof Uint8Array)) { - throw new Error(objectName + " must be of type Uint8Array."); + throw new Error(`${objectName} must be of type Uint8Array.`); } returnValue = bufferToBase64Url(value) || ""; } @@ -68603,7 +64488,7 @@ function serializeDateTypes(typeName, value, objectName) { if (typeName.match(/^Date$/i) !== null) { if (!(value instanceof Date || (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { - throw new Error(objectName + " must be an instanceof Date or a string in ISO8601 format."); + throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); } value = value instanceof Date @@ -68613,58 +64498,57 @@ function serializeDateTypes(typeName, value, objectName) { else if (typeName.match(/^DateTime$/i) !== null) { if (!(value instanceof Date || (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { - throw new Error(objectName + " must be an instanceof Date or a string in ISO8601 format."); + throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); } value = value instanceof Date ? value.toISOString() : new Date(value).toISOString(); } else if (typeName.match(/^DateTimeRfc1123$/i) !== null) { if (!(value instanceof Date || (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { - throw new Error(objectName + " must be an instanceof Date or a string in RFC-1123 format."); + throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`); } value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString(); } else if (typeName.match(/^UnixTime$/i) !== null) { if (!(value instanceof Date || (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { - throw new Error(objectName + " must be an instanceof Date or a string in RFC-1123/ISO8601 format " + - "for it to be serialized in UnixTime/Epoch format."); + throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format ` + + `for it to be serialized in UnixTime/Epoch format.`); } value = dateToUnixTime(value); } else if (typeName.match(/^TimeSpan$/i) !== null) { if (!isDuration(value)) { - throw new Error(objectName + " must be a string in ISO 8601 format. Instead was \"" + value + "\"."); + throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`); } } } return value; } function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) { - var _a, _b; if (!Array.isArray(object)) { - throw new Error(objectName + " must be of type Array."); + throw new Error(`${objectName} must be of type Array.`); } - var elementType = mapper.type.element; + const elementType = mapper.type.element; if (!elementType || typeof elementType !== "object") { - throw new Error("element\" metadata for an Array must be defined in the " + - ("mapper and it must of type \"object\" in " + objectName + ".")); + throw new Error(`element" metadata for an Array must be defined in the ` + + `mapper and it must of type "object" in ${objectName}.`); } - var tempArray = []; - for (var i = 0; i < object.length; i++) { - var serializedValue = serializer.serialize(elementType, object[i], objectName, options); + const tempArray = []; + for (let i = 0; i < object.length; i++) { + const serializedValue = serializer.serialize(elementType, object[i], objectName, options); if (isXml && elementType.xmlNamespace) { - var xmlnsKey = elementType.xmlNamespacePrefix - ? "xmlns:" + elementType.xmlNamespacePrefix + const 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] = Object.assign({}, serializedValue); + tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; } else { tempArray[i] = {}; tempArray[i][options.xmlCharKey] = serializedValue; - tempArray[i][XML_ATTRKEY] = (_b = {}, _b[xmlnsKey] = elementType.xmlNamespace, _b); + tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; } } else { @@ -68674,27 +64558,25 @@ function serializeSequenceType(serializer, mapper, object, objectName, isXml, op return tempArray; } function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) { - var _a; if (typeof object !== "object") { - throw new Error(objectName + " must be of type object."); + throw new Error(`${objectName} must be of type object.`); } - var valueType = mapper.type.value; + const valueType = mapper.type.value; if (!valueType || typeof valueType !== "object") { - throw new Error("\"value\" metadata for a Dictionary must be defined in the " + - ("mapper and it must of type \"object\" in " + objectName + ".")); + throw new Error(`"value" metadata for a Dictionary must be defined in the ` + + `mapper and it must of type "object" in ${objectName}.`); } - 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); + const tempDictionary = {}; + for (const key of Object.keys(object)) { + const serializedValue = serializer.serialize(valueType, object[key], objectName, options); // If the element needs an XML namespace we need to add it within the $ property tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options); } // 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); + const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns"; + const result = tempDictionary; + result[XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace }; return result; } return tempDictionary; @@ -68706,9 +64588,9 @@ function serializeDictionaryType(serializer, mapper, object, objectName, isXml, * @param objectName - Name of the object being serialized */ function resolveAdditionalProperties(serializer, mapper, objectName) { - var additionalProperties = mapper.type.additionalProperties; + const additionalProperties = mapper.type.additionalProperties; if (!additionalProperties && mapper.type.className) { - var modelMapper = resolveReferencedMapper(serializer, mapper, objectName); + const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); return modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.additionalProperties; } return additionalProperties; @@ -68720,9 +64602,9 @@ function resolveAdditionalProperties(serializer, mapper, objectName) { * @param objectName - Name of the object being serialized */ function resolveReferencedMapper(serializer, mapper, objectName) { - var className = mapper.type.className; + const className = mapper.type.className; if (!className) { - throw new Error("Class name for model \"" + objectName + "\" is not provided in the mapper \"" + JSON.stringify(mapper, undefined, 2) + "\"."); + throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, undefined, 2)}".`); } return serializer.modelMappers[className]; } @@ -68732,36 +64614,34 @@ function resolveReferencedMapper(serializer, mapper, objectName) { * @param mapper - The composite mapper to resolve */ function resolveModelProperties(serializer, mapper, objectName) { - var modelProps = mapper.type.modelProperties; + let modelProps = mapper.type.modelProperties; if (!modelProps) { - var modelMapper = resolveReferencedMapper(serializer, mapper, objectName); + const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); if (!modelMapper) { - throw new Error("mapper() cannot be null or undefined for model \"" + mapper.type.className + "\"."); + throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`); } modelProps = modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.modelProperties; if (!modelProps) { - throw new Error("modelProperties cannot be null or undefined in the " + - ("mapper \"" + JSON.stringify(modelMapper) + "\" of type \"" + mapper.type.className + "\" for object \"" + objectName + "\".")); + throw new Error(`modelProperties cannot be null or undefined in the ` + + `mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`); } } return modelProps; } function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) { - var _a, _b; if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { mapper = getPolymorphicMapper(serializer, mapper, object, "clientName"); } if (object != undefined) { - var payload = {}; - var modelProps = resolveModelProperties(serializer, mapper, objectName); - for (var _i = 0, _c = Object.keys(modelProps); _i < _c.length; _i++) { - var key = _c[_i]; - var propertyMapper = modelProps[key]; + const payload = {}; + const modelProps = resolveModelProperties(serializer, mapper, objectName); + for (const key of Object.keys(modelProps)) { + const propertyMapper = modelProps[key]; if (propertyMapper.readOnly) { continue; } - var propName = void 0; - var parentObject = payload; + let propName; + let parentObject = payload; if (serializer.isXML) { if (propertyMapper.xmlIsWrapped) { propName = propertyMapper.xmlName; @@ -68771,11 +64651,10 @@ function serializeCompositeType(serializer, mapper, object, objectName, isXml, o } } else { - var paths = splitSerializeName(propertyMapper.serializedName); + const paths = splitSerializeName(propertyMapper.serializedName); propName = paths.pop(); - for (var _d = 0, paths_1 = paths; _d < paths_1.length; _d++) { - var pathName = paths_1[_d]; - var childObject = parentObject[pathName]; + for (const pathName of paths) { + const childObject = parentObject[pathName]; if (childObject == undefined && (object[key] != undefined || propertyMapper.defaultValue !== undefined)) { parentObject[pathName] = {}; @@ -68785,24 +64664,24 @@ function serializeCompositeType(serializer, mapper, object, objectName, isXml, o } if (parentObject != undefined) { if (isXml && mapper.xmlNamespace) { - var xmlnsKey = mapper.xmlNamespacePrefix - ? "xmlns:" + mapper.xmlNamespacePrefix + const xmlnsKey = mapper.xmlNamespacePrefix + ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns"; - parentObject[XML_ATTRKEY] = tslib.__assign(tslib.__assign({}, parentObject[XML_ATTRKEY]), (_a = {}, _a[xmlnsKey] = mapper.xmlNamespace, _a)); + parentObject[XML_ATTRKEY] = Object.assign(Object.assign({}, parentObject[XML_ATTRKEY]), { [xmlnsKey]: mapper.xmlNamespace }); } - var propertyObjectName = propertyMapper.serializedName !== "" + const propertyObjectName = propertyMapper.serializedName !== "" ? objectName + "." + propertyMapper.serializedName : objectName; - var toSerialize = object[key]; - var polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); + let toSerialize = object[key]; + const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); if (polymorphicDiscriminator && polymorphicDiscriminator.clientName === key && toSerialize == undefined) { toSerialize = mapper.serializedName; } - var serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options); + const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options); if (serializedValue !== undefined && propName != undefined) { - var value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options); + const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options); if (isXml && propertyMapper.xmlIsAttribute) { // XML_ATTRKEY, i.e., $ is the key attributes are kept under in xml2js. // This keeps things simple while preventing name collision @@ -68811,7 +64690,7 @@ function serializeCompositeType(serializer, mapper, object, objectName, isXml, o parentObject[XML_ATTRKEY][propName] = serializedValue; } else if (isXml && propertyMapper.xmlIsWrapped) { - parentObject[propName] = (_b = {}, _b[propertyMapper.xmlElementName] = value, _b); + parentObject[propName] = { [propertyMapper.xmlElementName]: value }; } else { parentObject[propName] = value; @@ -68819,17 +64698,14 @@ function serializeCompositeType(serializer, mapper, object, objectName, isXml, o } } } - var additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName); + const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName); if (additionalPropertiesMapper) { - var propNames = Object.keys(modelProps); - var _loop_1 = function (clientPropName) { - var isAdditionalProperty = propNames.every(function (pn) { return pn !== clientPropName; }); + const propNames = Object.keys(modelProps); + for (const clientPropName in object) { + const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName); if (isAdditionalProperty) { payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options); } - }; - for (var clientPropName in object) { - _loop_1(clientPropName); } } return payload; @@ -68837,25 +64713,24 @@ function serializeCompositeType(serializer, mapper, object, objectName, isXml, o return object; } function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) { - var _a; if (!isXml || !propertyMapper.xmlNamespace) { return serializedValue; } - var xmlnsKey = propertyMapper.xmlNamespacePrefix - ? "xmlns:" + propertyMapper.xmlNamespacePrefix + const xmlnsKey = propertyMapper.xmlNamespacePrefix + ? `xmlns:${propertyMapper.xmlNamespacePrefix}` : "xmlns"; - var xmlNamespace = (_a = {}, _a[xmlnsKey] = propertyMapper.xmlNamespace, _a); + const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace }; 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; + const result = Object.assign({}, serializedValue); + result[XML_ATTRKEY] = xmlNamespace; + return result; } } - var result = {}; + const result = {}; result[options.xmlCharKey] = serializedValue; result[XML_ATTRKEY] = xmlNamespace; return result; @@ -68868,24 +64743,22 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName"); } - var modelProps = resolveModelProperties(serializer, mapper, objectName); - var instance = {}; - var handledPropertyNames = []; - for (var _i = 0, _b = Object.keys(modelProps); _i < _b.length; _i++) { - var key = _b[_i]; - var propertyMapper = modelProps[key]; - var paths = splitSerializeName(modelProps[key].serializedName); + const modelProps = resolveModelProperties(serializer, mapper, objectName); + let instance = {}; + const handledPropertyNames = []; + for (const key of Object.keys(modelProps)) { + const propertyMapper = modelProps[key]; + const paths = splitSerializeName(modelProps[key].serializedName); handledPropertyNames.push(paths[0]); - var serializedName = propertyMapper.serializedName, xmlName = propertyMapper.xmlName, xmlElementName = propertyMapper.xmlElementName; - var propertyObjectName = objectName; + const { serializedName, xmlName, xmlElementName } = propertyMapper; + let propertyObjectName = objectName; if (serializedName !== "" && serializedName !== undefined) { propertyObjectName = objectName + "." + serializedName; } - var headerCollectionPrefix = propertyMapper.headerCollectionPrefix; + const headerCollectionPrefix = propertyMapper.headerCollectionPrefix; if (headerCollectionPrefix) { - var dictionary = {}; - for (var _c = 0, _d = Object.keys(responseBody); _c < _d.length; _c++) { - var headerKey = _d[_c]; + const dictionary = {}; + for (const headerKey of Object.keys(responseBody)) { if (headerKey.startsWith(headerCollectionPrefix)) { dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options); } @@ -68898,7 +64771,7 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, instance[key] = serializer.deserialize(propertyMapper, responseBody[XML_ATTRKEY][xmlName], propertyObjectName, options); } else { - var propertyName = xmlElementName || xmlName || serializedName; + const propertyName = xmlElementName || xmlName || serializedName; if (propertyMapper.xmlIsWrapped) { /* a list of wrapped by For the xml example below @@ -68914,29 +64787,28 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, } xmlName is "Cors" and xmlElementName is"CorsRule". */ - var wrapped = responseBody[xmlName]; - var elementList = (_a = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _a !== void 0 ? _a : []; + const wrapped = responseBody[xmlName]; + const elementList = (_a = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _a !== void 0 ? _a : []; instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options); } else { - var property = responseBody[propertyName]; + const property = responseBody[propertyName]; instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options); } } } else { // deserialize the property if it is present in the provided responseBody instance - var propertyInstance = void 0; - var res = responseBody; + let propertyInstance; + let res = responseBody; // traversing the object step by step. - for (var _e = 0, paths_2 = paths; _e < paths_2.length; _e++) { - var item = paths_2[_e]; + for (const item of paths) { if (!res) break; res = res[item]; } propertyInstance = res; - var polymorphicDiscriminator = mapper.type.polymorphicDiscriminator; + const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator; // checking that the model property name (key)(ex: "fishtype") and the // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype") // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type") @@ -68951,15 +64823,14 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, propertyInstance == undefined) { propertyInstance = mapper.serializedName; } - var serializedValue = void 0; + let serializedValue; // paging if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") { propertyInstance = responseBody[key]; - var arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); + const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); // Copy over any properties that have already been added into the instance, where they do // not exist on the newly de-serialized array - for (var _f = 0, _g = Object.entries(instance); _f < _g.length; _f++) { - var _h = _g[_f], k = _h[0], v = _h[1]; + for (const [k, v] of Object.entries(instance)) { if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) { arrayInstance[k] = v; } @@ -68972,26 +64843,25 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, } } } - var additionalPropertiesMapper = mapper.type.additionalProperties; + const additionalPropertiesMapper = mapper.type.additionalProperties; if (additionalPropertiesMapper) { - var isAdditionalProperty = function (responsePropName) { - for (var clientPropName in modelProps) { - var paths = splitSerializeName(modelProps[clientPropName].serializedName); + const isAdditionalProperty = (responsePropName) => { + for (const clientPropName in modelProps) { + const paths = splitSerializeName(modelProps[clientPropName].serializedName); if (paths[0] === responsePropName) { return false; } } return true; }; - for (var responsePropName in responseBody) { + for (const responsePropName in responseBody) { if (isAdditionalProperty(responsePropName)) { instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options); } } } else if (responseBody) { - for (var _j = 0, _k = Object.keys(responseBody); _j < _k.length; _j++) { - var key = _k[_j]; + for (const key of Object.keys(responseBody)) { if (instance[key] === undefined && !handledPropertyNames.includes(key) && !isSpecialXmlProperty(key, options)) { @@ -69002,15 +64872,14 @@ function deserializeCompositeType(serializer, mapper, responseBody, objectName, return instance; } function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) { - var value = mapper.type.value; + const value = mapper.type.value; if (!value || typeof value !== "object") { - throw new Error("\"value\" metadata for a Dictionary must be defined in the " + - ("mapper and it must of type \"object\" in " + objectName)); + throw new Error(`"value" metadata for a Dictionary must be defined in the ` + + `mapper and it must of type "object" in ${objectName}`); } if (responseBody) { - var tempDictionary = {}; - for (var _i = 0, _a = Object.keys(responseBody); _i < _a.length; _i++) { - var key = _a[_i]; + const tempDictionary = {}; + for (const key of Object.keys(responseBody)) { tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options); } return tempDictionary; @@ -69018,36 +64887,36 @@ function deserializeDictionaryType(serializer, mapper, responseBody, objectName, return responseBody; } function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) { - var element = mapper.type.element; + const element = mapper.type.element; if (!element || typeof element !== "object") { - throw new Error("element\" metadata for an Array must be defined in the " + - ("mapper and it must of type \"object\" in " + objectName)); + throw new Error(`element" metadata for an Array must be defined in the ` + + `mapper and it must of type "object" in ${objectName}`); } if (responseBody) { if (!Array.isArray(responseBody)) { // xml2js will interpret a single element array as just the element, so force it to be an array responseBody = [responseBody]; } - var tempArray = []; - for (var i = 0; i < responseBody.length; i++) { - tempArray[i] = serializer.deserialize(element, responseBody[i], objectName + "[" + i + "]", options); + const tempArray = []; + for (let i = 0; i < responseBody.length; i++) { + tempArray[i] = serializer.deserialize(element, responseBody[i], `${objectName}[${i}]`, options); } return tempArray; } return responseBody; } function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) { - var polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); + const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); if (polymorphicDiscriminator) { - var discriminatorName = polymorphicDiscriminator[polymorphicPropertyName]; + const discriminatorName = polymorphicDiscriminator[polymorphicPropertyName]; if (discriminatorName != undefined) { - var discriminatorValue = object[discriminatorName]; + const discriminatorValue = object[discriminatorName]; if (discriminatorValue != undefined) { - var typeName = mapper.type.uberParent || mapper.type.className; - var indexDiscriminator = discriminatorValue === typeName + const typeName = mapper.type.uberParent || mapper.type.className; + const indexDiscriminator = discriminatorValue === typeName ? discriminatorValue : typeName + "." + discriminatorValue; - var polymorphicMapper = serializer.modelMappers.discriminators[indexDiscriminator]; + const polymorphicMapper = serializer.modelMappers.discriminators[indexDiscriminator]; if (polymorphicMapper) { mapper = polymorphicMapper; } @@ -69068,7 +64937,7 @@ function getPolymorphicDiscriminatorSafely(serializer, typeName) { } // TODO: why is this here? function serializeObject(toSerialize) { - var castToSerialize = toSerialize; + const castToSerialize = toSerialize; if (toSerialize == undefined) return undefined; if (toSerialize instanceof Uint8Array) { @@ -69079,15 +64948,15 @@ function serializeObject(toSerialize) { return toSerialize.toISOString(); } else if (Array.isArray(toSerialize)) { - var array = []; - for (var i = 0; i < toSerialize.length; i++) { + const array = []; + for (let i = 0; i < toSerialize.length; i++) { array.push(serializeObject(toSerialize[i])); } return array; } else if (typeof toSerialize === "object") { - var dictionary = {}; - for (var property in toSerialize) { + const dictionary = {}; + for (const property in toSerialize) { dictionary[property] = serializeObject(castToSerialize[property]); } return dictionary; @@ -69098,15 +64967,14 @@ function serializeObject(toSerialize) { * Utility function to create a K:V from a list of strings */ function strEnum(o) { - var result = {}; - for (var _i = 0, o_1 = o; _i < o_1.length; _i++) { - var key = o_1[_i]; + const result = {}; + for (const key of o) { result[key] = key; } return result; } // eslint-disable-next-line @typescript-eslint/no-redeclare -var MapperType = strEnum([ +const MapperType = strEnum([ "Base64Url", "Boolean", "ByteArray", @@ -69128,7 +64996,7 @@ var MapperType = strEnum([ // Copyright (c) Microsoft Corporation. function isWebResourceLike(object) { if (object && typeof object === "object") { - var castObject = object; + const castObject = object; if (typeof castObject.url === "string" && typeof castObject.method === "string" && typeof castObject.headers === "object" && @@ -69147,8 +65015,8 @@ 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. */ -var WebResource = /** @class */ (function () { - function WebResource(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, decompressResponse, streamResponseStatusCodes) { +class WebResource { + constructor(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, decompressResponse, streamResponseStatusCodes) { this.streamResponseBody = streamResponseBody; this.streamResponseStatusCodes = streamResponseStatusCodes; this.url = url || ""; @@ -69172,20 +65040,20 @@ var WebResource = /** @class */ (function () { * headers["accept-language"] are defined. It will throw an error if one of the above * mentioned properties are not defined. */ - WebResource.prototype.validateRequestProperties = function () { + validateRequestProperties() { if (!this.method) { throw new Error("WebResource.method is required."); } if (!this.url) { throw new Error("WebResource.url is required."); } - }; + } /** * 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. */ - WebResource.prototype.prepare = function (options) { + prepare(options) { if (!options) { throw new Error("options object is required"); } @@ -69214,7 +65082,7 @@ var WebResource = /** @class */ (function () { } // set the method if (options.method) { - var validMethods = ["GET", "PUT", "HEAD", "DELETE", "OPTIONS", "POST", "PATCH", "TRACE"]; + const validMethods = ["GET", "PUT", "HEAD", "DELETE", "OPTIONS", "POST", "PATCH", "TRACE"]; if (validMethods.indexOf(options.method.toUpperCase()) === -1) { throw new Error('The provided method "' + options.method + @@ -69225,70 +65093,70 @@ var WebResource = /** @class */ (function () { this.method = options.method.toUpperCase(); // construct the url if path template is provided if (options.pathTemplate) { - var pathTemplate_1 = options.pathTemplate, pathParameters_1 = options.pathParameters; - if (typeof pathTemplate_1 !== "string") { + const { pathTemplate, pathParameters } = options; + if (typeof pathTemplate !== "string") { throw new Error('options.pathTemplate must be of type "string".'); } if (!options.baseUrl) { options.baseUrl = "https://management.azure.com"; } - var baseUrl = options.baseUrl; - var url_1 = baseUrl + + const baseUrl = options.baseUrl; + let url = baseUrl + (baseUrl.endsWith("/") ? "" : "/") + - (pathTemplate_1.startsWith("/") ? pathTemplate_1.slice(1) : pathTemplate_1); - var segments = url_1.match(/({[\w-]*\s*[\w-]*})/gi); + (pathTemplate.startsWith("/") ? pathTemplate.slice(1) : pathTemplate); + const segments = url.match(/({[\w-]*\s*[\w-]*})/gi); if (segments && segments.length) { - if (!pathParameters_1) { - throw new Error("pathTemplate: " + pathTemplate_1 + " has been provided. Hence, options.pathParameters must also be provided."); + if (!pathParameters) { + throw new Error(`pathTemplate: ${pathTemplate} has been provided. Hence, options.pathParameters must also be provided.`); } segments.forEach(function (item) { - var pathParamName = item.slice(1, -1); - var pathParam = pathParameters_1[pathParamName]; + const pathParamName = item.slice(1, -1); + const pathParam = pathParameters[pathParamName]; if (pathParam === null || pathParam === undefined || !(typeof pathParam === "string" || typeof pathParam === "object")) { - var stringifiedPathParameters = JSON.stringify(pathParameters_1, undefined, 2); - throw new Error("pathTemplate: " + pathTemplate_1 + " contains the path parameter " + pathParamName + - (" however, it is not present in parameters: " + stringifiedPathParameters + ".") + - ("The value of the path parameter can either be a \"string\" of the form { " + pathParamName + ": \"some sample value\" } or ") + - ("it can be an \"object\" of the form { \"" + pathParamName + "\": { value: \"some sample value\", skipUrlEncoding: true } }.")); + const stringifiedPathParameters = JSON.stringify(pathParameters, undefined, 2); + throw new Error(`pathTemplate: ${pathTemplate} contains the path parameter ${pathParamName}` + + ` however, it is not present in parameters: ${stringifiedPathParameters}.` + + `The value of the path parameter can either be a "string" of the form { ${pathParamName}: "some sample value" } or ` + + `it can be an "object" of the form { "${pathParamName}": { value: "some sample value", skipUrlEncoding: true } }.`); } if (typeof pathParam.valueOf() === "string") { - url_1 = url_1.replace(item, encodeURIComponent(pathParam)); + url = url.replace(item, encodeURIComponent(pathParam)); } if (typeof pathParam.valueOf() === "object") { if (!pathParam.value) { - throw new Error("options.pathParameters[" + pathParamName + "] is of type \"object\" but it does not contain a \"value\" property."); + throw new Error(`options.pathParameters[${pathParamName}] is of type "object" but it does not contain a "value" property.`); } if (pathParam.skipUrlEncoding) { - url_1 = url_1.replace(item, pathParam.value); + url = url.replace(item, pathParam.value); } else { - url_1 = url_1.replace(item, encodeURIComponent(pathParam.value)); + url = url.replace(item, encodeURIComponent(pathParam.value)); } } }); } - this.url = url_1; + this.url = url; } // append query parameters to the url if they are provided. They can be provided with pathTemplate or url option. if (options.queryParameters) { - var queryParameters = options.queryParameters; + const queryParameters = options.queryParameters; if (typeof queryParameters !== "object") { - throw new Error("options.queryParameters must be of type object. It should be a JSON object " + - "of \"query-parameter-name\" as the key and the \"query-parameter-value\" as the value. " + - "The \"query-parameter-value\" may be fo type \"string\" or an \"object\" of the form { value: \"query-parameter-value\", skipUrlEncoding: true }."); + throw new Error(`options.queryParameters must be of type object. It should be a JSON object ` + + `of "query-parameter-name" as the key and the "query-parameter-value" as the value. ` + + `The "query-parameter-value" may be fo type "string" or an "object" of the form { value: "query-parameter-value", skipUrlEncoding: true }.`); } // append question mark if it is not present in the url if (this.url && this.url.indexOf("?") === -1) { this.url += "?"; } // construct queryString - var queryParams = []; + const queryParams = []; // We need to populate this.query as a dictionary if the request is being used for Sway's validateRequest(). this.query = {}; - for (var queryParamName in queryParameters) { - var queryParam = queryParameters[queryParamName]; + for (const queryParamName in queryParameters) { + const queryParam = queryParameters[queryParamName]; if (queryParam) { if (typeof queryParam === "string") { queryParams.push(queryParamName + "=" + encodeURIComponent(queryParam)); @@ -69296,7 +65164,7 @@ var WebResource = /** @class */ (function () { } else if (typeof queryParam === "object") { if (!queryParam.value) { - throw new Error("options.queryParameters[" + queryParamName + "] is of type \"object\" but it does not contain a \"value\" property."); + throw new Error(`options.queryParameters[${queryParamName}] is of type "object" but it does not contain a "value" property.`); } if (queryParam.skipUrlEncoding) { queryParams.push(queryParamName + "=" + queryParam.value); @@ -69314,9 +65182,8 @@ var WebResource = /** @class */ (function () { } // add headers to the request if they are provided if (options.headers) { - var headers = options.headers; - for (var _i = 0, _a = Object.keys(options.headers); _i < _a.length; _i++) { - var headerName = _a[_i]; + const headers = options.headers; + for (const headerName of Object.keys(options.headers)) { this.headers.set(headerName, headers[headerName]); } } @@ -69363,13 +65230,13 @@ var WebResource = /** @class */ (function () { this.onDownloadProgress = options.onDownloadProgress; this.onUploadProgress = options.onUploadProgress; return this; - }; + } /** * Clone this WebResource HTTP request object. * @returns 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); + clone() { + const 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); if (this.formData) { result.formData = this.formData; } @@ -69383,43 +65250,42 @@ var WebResource = /** @class */ (function () { result.operationResponseGetter = this.operationResponseGetter; } return result; - }; - return WebResource; -}()); + } +} // Copyright (c) Microsoft Corporation. -var custom = util.inspect.custom; +const custom = util.inspect.custom; // Copyright (c) Microsoft Corporation. /** * A class that handles the query portion of a URLBuilder. */ -var URLQuery = /** @class */ (function () { - function URLQuery() { +class URLQuery { + constructor() { this._rawQuery = {}; } /** * Get whether or not there any query parameters in this URLQuery. */ - URLQuery.prototype.any = function () { + any() { return Object.keys(this._rawQuery).length > 0; - }; + } /** * Get the keys of the query string. */ - URLQuery.prototype.keys = function () { + keys() { return Object.keys(this._rawQuery); - }; + } /** * Set a query parameter with the provided name and value. If the parameterValue is undefined or * empty, then this will attempt to remove an existing query parameter with the provided * parameterName. */ - URLQuery.prototype.set = function (parameterName, parameterValue) { - var caseParameterValue = parameterValue; + set(parameterName, parameterValue) { + const caseParameterValue = parameterValue; if (parameterName) { if (caseParameterValue !== undefined && caseParameterValue !== null) { - var newValue = Array.isArray(caseParameterValue) + const newValue = Array.isArray(caseParameterValue) ? caseParameterValue : caseParameterValue.toString(); this._rawQuery[parameterName] = newValue; @@ -69428,52 +65294,51 @@ var URLQuery = /** @class */ (function () { delete this._rawQuery[parameterName]; } } - }; + } /** * Get the value of the query parameter with the provided name. If no parameter exists with the * provided parameter name, then undefined will be returned. */ - URLQuery.prototype.get = function (parameterName) { + get(parameterName) { return parameterName ? this._rawQuery[parameterName] : undefined; - }; + } /** * Get the string representation of this query. The return value will not start with a "?". */ - URLQuery.prototype.toString = function () { - var result = ""; - for (var parameterName in this._rawQuery) { + toString() { + let result = ""; + for (const parameterName in this._rawQuery) { if (result) { result += "&"; } - var parameterValue = this._rawQuery[parameterName]; + const parameterValue = this._rawQuery[parameterName]; if (Array.isArray(parameterValue)) { - var parameterStrings = []; - for (var _i = 0, parameterValue_1 = parameterValue; _i < parameterValue_1.length; _i++) { - var parameterValueElement = parameterValue_1[_i]; - parameterStrings.push(parameterName + "=" + parameterValueElement); + const parameterStrings = []; + for (const parameterValueElement of parameterValue) { + parameterStrings.push(`${parameterName}=${parameterValueElement}`); } result += parameterStrings.join("&"); } else { - result += parameterName + "=" + parameterValue; + result += `${parameterName}=${parameterValue}`; } } return result; - }; + } /** * Parse a URLQuery from the provided text. */ - URLQuery.parse = function (text) { - var result = new URLQuery(); + static parse(text) { + const result = new URLQuery(); if (text) { if (text.startsWith("?")) { text = text.substring(1); } - var currentState = "ParameterName"; - var parameterName = ""; - var parameterValue = ""; - for (var i = 0; i < text.length; ++i) { - var currentCharacter = text[i]; + let currentState = "ParameterName"; + let parameterName = ""; + let parameterValue = ""; + for (let i = 0; i < text.length; ++i) { + const currentCharacter = text[i]; switch (currentState) { case "ParameterName": switch (currentCharacter) { @@ -69511,81 +65376,78 @@ var URLQuery = /** @class */ (function () { } } return result; - }; - return URLQuery; -}()); + } +} /** * A class that handles creating, modifying, and parsing URLs. */ -var URLBuilder = /** @class */ (function () { - function URLBuilder() { - } +class URLBuilder { /** * Set the scheme/protocol for this URL. If the provided scheme contains other parts of a URL * (such as a host, port, path, or query), those parts will be added to this URL as well. */ - URLBuilder.prototype.setScheme = function (scheme) { + setScheme(scheme) { if (!scheme) { this._scheme = undefined; } else { this.set(scheme, "SCHEME"); } - }; + } /** * Get the scheme that has been set in this URL. */ - URLBuilder.prototype.getScheme = function () { + getScheme() { return this._scheme; - }; + } /** * Set the host for this URL. If the provided host contains other parts of a URL (such as a * port, path, or query), those parts will be added to this URL as well. */ - URLBuilder.prototype.setHost = function (host) { + setHost(host) { if (!host) { this._host = undefined; } else { this.set(host, "SCHEME_OR_HOST"); } - }; + } /** * Get the host that has been set in this URL. */ - URLBuilder.prototype.getHost = function () { + getHost() { return this._host; - }; + } /** * Set the port for this URL. If the provided port contains other parts of a URL (such as a * path or query), those parts will be added to this URL as well. */ - URLBuilder.prototype.setPort = function (port) { + setPort(port) { if (port === undefined || port === null || port === "") { this._port = undefined; } else { this.set(port.toString(), "PORT"); } - }; + } /** * Get the port that has been set in this URL. */ - URLBuilder.prototype.getPort = function () { + getPort() { return this._port; - }; + } /** * Set the path for this URL. If the provided path contains a query, then it will be added to * this URL as well. */ - URLBuilder.prototype.setPath = function (path) { + setPath(path) { if (!path) { this._path = undefined; } else { - var schemeIndex = path.indexOf("://"); + const schemeIndex = path.indexOf("://"); if (schemeIndex !== -1) { - var schemeStart = path.lastIndexOf("/", schemeIndex); + const schemeStart = path.lastIndexOf("/", schemeIndex); // Make sure to only grab the URL part of the path before setting the state back to SCHEME // this will handle cases such as "/a/b/c/https://microsoft.com" => "https://microsoft.com" this.set(schemeStart === -1 ? path : path.substr(schemeStart + 1), "SCHEME"); @@ -69594,14 +65456,14 @@ var URLBuilder = /** @class */ (function () { this.set(path, "PATH"); } } - }; + } /** * Append the provided path to this URL's existing path. If the provided path contains a query, * then it will be added to this URL as well. */ - URLBuilder.prototype.appendPath = function (path) { + appendPath(path) { if (path) { - var currentPath = this.getPath(); + let currentPath = this.getPath(); if (currentPath) { if (!currentPath.endsWith("/")) { currentPath += "/"; @@ -69613,58 +65475,58 @@ var URLBuilder = /** @class */ (function () { } this.set(path, "PATH"); } - }; + } /** * Get the path that has been set in this URL. */ - URLBuilder.prototype.getPath = function () { + getPath() { return this._path; - }; + } /** * Set the query in this URL. */ - URLBuilder.prototype.setQuery = function (query) { + setQuery(query) { if (!query) { this._query = undefined; } else { this._query = URLQuery.parse(query); } - }; + } /** * Set a query parameter with the provided name and value in this URL's query. If the provided * query parameter value is undefined or empty, then the query parameter will be removed if it * existed. */ - URLBuilder.prototype.setQueryParameter = function (queryParameterName, queryParameterValue) { + setQueryParameter(queryParameterName, queryParameterValue) { if (queryParameterName) { if (!this._query) { this._query = new URLQuery(); } this._query.set(queryParameterName, queryParameterValue); } - }; + } /** * Get the value of the query parameter with the provided query parameter name. If no query * parameter exists with the provided name, then undefined will be returned. */ - URLBuilder.prototype.getQueryParameterValue = function (queryParameterName) { + getQueryParameterValue(queryParameterName) { return this._query ? this._query.get(queryParameterName) : undefined; - }; + } /** * Get the query in this URL. */ - URLBuilder.prototype.getQuery = function () { + getQuery() { return this._query ? this._query.toString() : undefined; - }; + } /** * Set the parts of this URL by parsing the provided text using the provided startState. */ - URLBuilder.prototype.set = function (text, startState) { - var tokenizer = new URLTokenizer(text, startState); + set(text, startState) { + const tokenizer = new URLTokenizer(text, startState); while (tokenizer.next()) { - var token = tokenizer.current(); - var tokenPath = void 0; + const token = tokenizer.current(); + let tokenPath; if (token) { switch (token.type) { case "SCHEME": @@ -69686,21 +65548,21 @@ var URLBuilder = /** @class */ (function () { this._query = URLQuery.parse(token.text); break; default: - throw new Error("Unrecognized URLTokenType: " + token.type); + throw new Error(`Unrecognized URLTokenType: ${token.type}`); } } } - }; - URLBuilder.prototype.toString = function () { - var result = ""; + } + toString() { + let result = ""; if (this._scheme) { - result += this._scheme + "://"; + result += `${this._scheme}://`; } if (this._host) { result += this._host; } if (this._port) { - result += ":" + this._port; + result += `:${this._port}`; } if (this._path) { if (!this._path.startsWith("/")) { @@ -69709,15 +65571,15 @@ var URLBuilder = /** @class */ (function () { result += this._path; } if (this._query && this._query.any()) { - result += "?" + this._query.toString(); + result += `?${this._query.toString()}`; } return result; - }; + } /** * If the provided searchValue is found in this URLBuilder, then replace it with the provided * replaceValue. */ - URLBuilder.prototype.replaceAll = function (searchValue, replaceValue) { + replaceAll(searchValue, replaceValue) { if (searchValue) { this.setScheme(replaceAll(this.getScheme(), searchValue, replaceValue)); this.setHost(replaceAll(this.getHost(), searchValue, replaceValue)); @@ -69725,42 +65587,40 @@ var URLBuilder = /** @class */ (function () { this.setPath(replaceAll(this.getPath(), searchValue, replaceValue)); this.setQuery(replaceAll(this.getQuery(), searchValue, replaceValue)); } - }; - URLBuilder.parse = function (text) { - var result = new URLBuilder(); + } + static parse(text) { + const result = new URLBuilder(); result.set(text, "SCHEME_OR_HOST"); return result; - }; - return URLBuilder; -}()); -var URLToken = /** @class */ (function () { - function URLToken(text, type) { + } +} +class URLToken { + constructor(text, type) { this.text = text; this.type = type; } - URLToken.scheme = function (text) { + static scheme(text) { return new URLToken(text, "SCHEME"); - }; - URLToken.host = function (text) { + } + static host(text) { return new URLToken(text, "HOST"); - }; - URLToken.port = function (text) { + } + static port(text) { return new URLToken(text, "PORT"); - }; - URLToken.path = function (text) { + } + static path(text) { return new URLToken(text, "PATH"); - }; - URLToken.query = function (text) { + } + static query(text) { return new URLToken(text, "QUERY"); - }; - return URLToken; -}()); + } +} /** * Get whether or not the provided character (single character string) is an alphanumeric (letter or * digit) character. */ function isAlphaNumericCharacter(character) { - var characterCode = character.charCodeAt(0); + const characterCode = character.charCodeAt(0); return ((48 /* '0' */ <= characterCode && characterCode <= 57) /* '9' */ || (65 /* 'A' */ <= characterCode && characterCode <= 90) /* 'Z' */ || (97 /* 'a' */ <= characterCode && characterCode <= 122) /* 'z' */); @@ -69768,8 +65628,8 @@ function isAlphaNumericCharacter(character) { /** * A class that tokenizes URL strings. */ -var URLTokenizer = /** @class */ (function () { - function URLTokenizer(_text, state) { +class URLTokenizer { + constructor(_text, state) { this._text = _text; this._textLength = _text ? _text.length : 0; this._currentState = state !== undefined && state !== null ? state : "SCHEME_OR_HOST"; @@ -69779,13 +65639,13 @@ var URLTokenizer = /** @class */ (function () { * Get the current URLToken this URLTokenizer is pointing at, or undefined if the URLTokenizer * hasn't started or has finished tokenizing. */ - URLTokenizer.prototype.current = function () { + current() { return this._currentToken; - }; + } /** * Advance to the next URLToken and return whether or not a URLToken was found. */ - URLTokenizer.prototype.next = function () { + next() { if (!hasCurrentCharacter(this)) { this._currentToken = undefined; } @@ -69810,18 +65670,17 @@ var URLTokenizer = /** @class */ (function () { nextQuery(this); break; default: - throw new Error("Unrecognized URLTokenizerState: " + this._currentState); + throw new Error(`Unrecognized URLTokenizerState: ${this._currentState}`); } } return !!this._currentToken; - }; - return URLTokenizer; -}()); + } +} /** * Read the remaining characters from this Tokenizer's character stream. */ function readRemaining(tokenizer) { - var result = ""; + let result = ""; if (tokenizer._currentIndex < tokenizer._textLength) { result = tokenizer._text.substring(tokenizer._currentIndex); tokenizer._currentIndex = tokenizer._textLength; @@ -69857,7 +65716,7 @@ function nextCharacter(tokenizer, step) { * Tokenizer's stream of characters. */ function peekCharacters(tokenizer, charactersToPeek) { - var endIndex = tokenizer._currentIndex + charactersToPeek; + let endIndex = tokenizer._currentIndex + charactersToPeek; if (tokenizer._textLength < endIndex) { endIndex = tokenizer._textLength; } @@ -69868,9 +65727,9 @@ function peekCharacters(tokenizer, charactersToPeek) { * is false when provided the current character. */ function readWhile(tokenizer, condition) { - var result = ""; + let result = ""; while (hasCurrentCharacter(tokenizer)) { - var currentCharacter = getCurrentCharacter(tokenizer); + const currentCharacter = getCurrentCharacter(tokenizer); if (!condition(currentCharacter)) { break; } @@ -69886,21 +65745,17 @@ function readWhile(tokenizer, condition) { * character stream is reached. */ function readWhileLetterOrDigit(tokenizer) { - return readWhile(tokenizer, function (character) { return isAlphaNumericCharacter(character); }); + return readWhile(tokenizer, (character) => isAlphaNumericCharacter(character)); } /** * Read characters from this Tokenizer until one of the provided terminating characters is read or * the end of the character stream is reached. */ -function readUntilCharacter(tokenizer) { - var terminatingCharacters = []; - for (var _i = 1; _i < arguments.length; _i++) { - terminatingCharacters[_i - 1] = arguments[_i]; - } - return readWhile(tokenizer, function (character) { return terminatingCharacters.indexOf(character) === -1; }); +function readUntilCharacter(tokenizer, ...terminatingCharacters) { + return readWhile(tokenizer, (character) => terminatingCharacters.indexOf(character) === -1); } function nextScheme(tokenizer) { - var scheme = readWhileLetterOrDigit(tokenizer); + const scheme = readWhileLetterOrDigit(tokenizer); tokenizer._currentToken = URLToken.scheme(scheme); if (!hasCurrentCharacter(tokenizer)) { tokenizer._currentState = "DONE"; @@ -69910,7 +65765,7 @@ function nextScheme(tokenizer) { } } function nextSchemeOrHost(tokenizer) { - var schemeOrHost = readUntilCharacter(tokenizer, ":", "/", "?"); + const schemeOrHost = readUntilCharacter(tokenizer, ":", "/", "?"); if (!hasCurrentCharacter(tokenizer)) { tokenizer._currentToken = URLToken.host(schemeOrHost); tokenizer._currentState = "DONE"; @@ -69939,7 +65794,7 @@ function nextHost(tokenizer) { if (peekCharacters(tokenizer, 3) === "://") { nextCharacter(tokenizer, 3); } - var host = readUntilCharacter(tokenizer, ":", "/", "?"); + const host = readUntilCharacter(tokenizer, ":", "/", "?"); tokenizer._currentToken = URLToken.host(host); if (!hasCurrentCharacter(tokenizer)) { tokenizer._currentState = "DONE"; @@ -69958,7 +65813,7 @@ function nextPort(tokenizer) { if (getCurrentCharacter(tokenizer) === ":") { nextCharacter(tokenizer); } - var port = readUntilCharacter(tokenizer, "/", "?"); + const port = readUntilCharacter(tokenizer, "/", "?"); tokenizer._currentToken = URLToken.port(port); if (!hasCurrentCharacter(tokenizer)) { tokenizer._currentState = "DONE"; @@ -69971,7 +65826,7 @@ function nextPort(tokenizer) { } } function nextPath(tokenizer) { - var path = readUntilCharacter(tokenizer, "?"); + const path = readUntilCharacter(tokenizer, "?"); tokenizer._currentToken = URLToken.path(path); if (!hasCurrentCharacter(tokenizer)) { tokenizer._currentState = "DONE"; @@ -69984,14 +65839,14 @@ function nextQuery(tokenizer) { if (getCurrentCharacter(tokenizer) === "?") { nextCharacter(tokenizer); } - var query = readRemaining(tokenizer); + const query = readRemaining(tokenizer); tokenizer._currentToken = URLToken.query(query); tokenizer._currentState = "DONE"; } // Copyright (c) Microsoft Corporation. -var RedactedString = "REDACTED"; -var defaultAllowedHeaderNames = [ +const RedactedString = "REDACTED"; +const defaultAllowedHeaderNames = [ "x-ms-client-request-id", "x-ms-return-client-request-id", "x-ms-useragent", @@ -70031,35 +65886,33 @@ var defaultAllowedHeaderNames = [ "Transfer-Encoding", "User-Agent" ]; -var defaultAllowedQueryParameters = ["api-version"]; -var Sanitizer = /** @class */ (function () { - function Sanitizer(_a) { - var _b = _a === void 0 ? {} : _a, _c = _b.allowedHeaderNames, allowedHeaderNames = _c === void 0 ? [] : _c, _d = _b.allowedQueryParameters, allowedQueryParameters = _d === void 0 ? [] : _d; +const defaultAllowedQueryParameters = ["api-version"]; +class Sanitizer { + constructor({ allowedHeaderNames = [], allowedQueryParameters = [] } = {}) { allowedHeaderNames = Array.isArray(allowedHeaderNames) ? defaultAllowedHeaderNames.concat(allowedHeaderNames) : defaultAllowedHeaderNames; allowedQueryParameters = Array.isArray(allowedQueryParameters) ? defaultAllowedQueryParameters.concat(allowedQueryParameters) : defaultAllowedQueryParameters; - this.allowedHeaderNames = new Set(allowedHeaderNames.map(function (n) { return n.toLowerCase(); })); - this.allowedQueryParameters = new Set(allowedQueryParameters.map(function (p) { return p.toLowerCase(); })); + this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); + this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); } - Sanitizer.prototype.sanitize = function (obj) { - var _this = this; - var seen = new Set(); - return JSON.stringify(obj, function (key, value) { + sanitize(obj) { + const seen = new Set(); + return JSON.stringify(obj, (key, value) => { // Ensure Errors include their interesting non-enumerable members if (value instanceof Error) { - return tslib.__assign(tslib.__assign({}, value), { name: value.name, message: value.message }); + return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); } if (key === "_headersMap") { - return _this.sanitizeHeaders(value); + return this.sanitizeHeaders(value); } else if (key === "url") { - return _this.sanitizeUrl(value); + return this.sanitizeUrl(value); } else if (key === "query") { - return _this.sanitizeQuery(value); + return this.sanitizeQuery(value); } else if (key === "body") { // Don't log the request body @@ -70082,20 +65935,19 @@ var Sanitizer = /** @class */ (function () { } return value; }, 2); - }; - Sanitizer.prototype.sanitizeHeaders = function (value) { - return this.sanitizeObject(value, this.allowedHeaderNames, function (v, k) { return v[k].value; }); - }; - Sanitizer.prototype.sanitizeQuery = function (value) { - return this.sanitizeObject(value, this.allowedQueryParameters, function (v, k) { return v[k]; }); - }; - Sanitizer.prototype.sanitizeObject = function (value, allowedKeys, accessor) { + } + sanitizeHeaders(value) { + return this.sanitizeObject(value, this.allowedHeaderNames, (v, k) => v[k].value); + } + sanitizeQuery(value) { + return this.sanitizeObject(value, this.allowedQueryParameters, (v, k) => v[k]); + } + sanitizeObject(value, allowedKeys, accessor) { if (typeof value !== "object" || value === null) { return value; } - var sanitized = {}; - for (var _i = 0, _a = Object.keys(value); _i < _a.length; _i++) { - var k = _a[_i]; + const sanitized = {}; + for (const k of Object.keys(value)) { if (allowedKeys.has(k.toLowerCase())) { sanitized[k] = accessor(value, k); } @@ -70104,267 +65956,233 @@ var Sanitizer = /** @class */ (function () { } } return sanitized; - }; - Sanitizer.prototype.sanitizeUrl = function (value) { + } + sanitizeUrl(value) { if (typeof value !== "string" || value === null) { return value; } - var urlBuilder = URLBuilder.parse(value); - var queryString = urlBuilder.getQuery(); + const urlBuilder = URLBuilder.parse(value); + const queryString = urlBuilder.getQuery(); if (!queryString) { return value; } - var query = URLQuery.parse(queryString); - for (var _i = 0, _a = query.keys(); _i < _a.length; _i++) { - var k = _a[_i]; + const query = URLQuery.parse(queryString); + for (const k of query.keys()) { if (!this.allowedQueryParameters.has(k.toLowerCase())) { query.set(k, RedactedString); } } urlBuilder.setQuery(query.toString()); return urlBuilder.toString(); - }; - return Sanitizer; -}()); + } +} // Copyright (c) Microsoft Corporation. -var errorSanitizer = new Sanitizer(); -var RestError = /** @class */ (function (_super) { - tslib.__extends(RestError, _super); - function RestError(message, code, statusCode, request, response) { - var _this = _super.call(this, message) || this; - _this.name = "RestError"; - _this.code = code; - _this.statusCode = statusCode; - _this.request = request; - _this.response = response; - Object.setPrototypeOf(_this, RestError.prototype); - return _this; +const errorSanitizer = new Sanitizer(); +class RestError extends Error { + constructor(message, code, statusCode, request, response) { + super(message); + this.name = "RestError"; + this.code = code; + this.statusCode = statusCode; + this.request = request; + this.response = response; + Object.setPrototypeOf(this, RestError.prototype); } /** * Logging method for util.inspect in Node */ - RestError.prototype[custom] = function () { - return "RestError: " + this.message + " \n " + errorSanitizer.sanitize(this); - }; - RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; - RestError.PARSE_ERROR = "PARSE_ERROR"; - 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); - function ReportTransform(progressCallback) { - var _this = _super.call(this) || this; - _this.progressCallback = progressCallback; - _this.loadedBytes = 0; - return _this; + [custom]() { + return `RestError: ${this.message} \n ${errorSanitizer.sanitize(this)}`; } - ReportTransform.prototype._transform = function (chunk, _encoding, callback) { +} +RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; +RestError.PARSE_ERROR = "PARSE_ERROR"; + +// Copyright (c) Microsoft Corporation. +const logger = logger$1.createClientLogger("core-http"); + +// Copyright (c) Microsoft Corporation. +class ReportTransform extends stream.Transform { + constructor(progressCallback) { + super(); + this.progressCallback = progressCallback; + this.loadedBytes = 0; + } + _transform(chunk, _encoding, callback) { this.push(chunk); this.loadedBytes += chunk.length; this.progressCallback({ loadedBytes: this.loadedBytes }); callback(undefined); - }; - return ReportTransform; -}(stream.Transform)); -var FetchHttpClient = /** @class */ (function () { - function FetchHttpClient() { } - FetchHttpClient.prototype.sendRequest = function (httpRequest) { +} +class FetchHttpClient { + async sendRequest(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) { - case 0: - if (!httpRequest && typeof httpRequest !== "object") { - throw new Error("'httpRequest' (WebResourceLike) cannot be null or undefined and must be of type object."); - } - abortController$1 = new abortController.AbortController(); - if (httpRequest.abortSignal) { - if (httpRequest.abortSignal.aborted) { - throw new abortController.AbortError("The operation was aborted."); - } - abortListener = function (event) { - if (event.type === "abort") { - abortController$1.abort(); - } - }; - httpRequest.abortSignal.addEventListener("abort", abortListener); - } - if (httpRequest.timeout) { - setTimeout(function () { - abortController$1.abort(); - }, httpRequest.timeout); - } - if (httpRequest.formData) { - formData = httpRequest.formData; - requestForm_1 = new FormData(); - appendFormValue = function (key, value) { - // value function probably returns a stream so we can provide a fresh stream on each retry - if (typeof value === "function") { - value = value(); - } - if (value && - Object.prototype.hasOwnProperty.call(value, "value") && - Object.prototype.hasOwnProperty.call(value, "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]; - formValue = formData[formKey]; - if (Array.isArray(formValue)) { - for (j = 0; j < formValue.length; j++) { - appendFormValue(formKey, formValue[j]); - } - } - else { - appendFormValue(formKey, formValue); - } - } - httpRequest.body = requestForm_1; - httpRequest.formData = undefined; - contentType = httpRequest.headers.get("Content-Type"); - if (contentType && contentType.indexOf("multipart/form-data") !== -1) { - if (typeof requestForm_1.getBoundary === "function") { - httpRequest.headers.set("Content-Type", "multipart/form-data; boundary=" + requestForm_1.getBoundary()); - } - else { - // browser will automatically apply a suitable content-type header - httpRequest.headers.remove("Content-Type"); - } - } - } - body = httpRequest.body - ? typeof httpRequest.body === "function" - ? httpRequest.body() - : httpRequest.body - : undefined; - if (httpRequest.onUploadProgress && httpRequest.body) { - onUploadProgress = httpRequest.onUploadProgress; - uploadReportStream = new ReportTransform(onUploadProgress); - if (isReadableStream(body)) { - body.pipe(uploadReportStream); - } - else { - uploadReportStream.end(body); - } - body = uploadReportStream; - } - 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; - case 2: - _e.trys.push([2, 8, 9, 10]); - return [4 /*yield*/, this.fetch(httpRequest.url, requestInit)]; - case 3: - response = _e.sent(); - headers = parseHeaders(response.headers); - streaming = ((_a = httpRequest.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(response.status)) || - httpRequest.streamResponseBody; - _d = { - headers: headers, - request: httpRequest, - status: response.status, - readableStreamBody: streaming - ? response.body - : undefined - }; - if (!!streaming) return [3 /*break*/, 5]; - return [4 /*yield*/, response.text()]; - case 4: - _c = _e.sent(); - return [3 /*break*/, 6]; - case 5: - _c = undefined; - _e.label = 6; - case 6: - operationResponse = (_d.bodyAsText = _c, - _d); - onDownloadProgress = httpRequest.onDownloadProgress; - if (onDownloadProgress) { - responseBody = response.body || undefined; - if (isReadableStream(responseBody)) { - downloadReportStream = new ReportTransform(onDownloadProgress); - responseBody.pipe(downloadReportStream); - operationResponse.readableStreamBody = downloadReportStream; - } - else { - length_1 = parseInt(headers.get("Content-Length")) || undefined; - if (length_1) { - // Calling callback for non-stream response for consistency with browser - onDownloadProgress({ loadedBytes: length_1 }); - } - } - } - return [4 /*yield*/, this.processRequest(operationResponse)]; - case 7: - _e.sent(); - return [2 /*return*/, operationResponse]; - case 8: - error_1 = _e.sent(); - fetchError = error_1; - if (fetchError.code === "ENOTFOUND") { - throw new RestError(fetchError.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest); - } - else if (fetchError.type === "aborted") { - throw new abortController.AbortError("The operation was aborted."); - } - throw fetchError; - 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); - }); - } - return [7 /*endfinally*/]; - case 10: return [2 /*return*/]; + if (!httpRequest && typeof httpRequest !== "object") { + throw new Error("'httpRequest' (WebResourceLike) cannot be null or undefined and must be of type object."); + } + const abortController$1 = new abortController.AbortController(); + let abortListener; + if (httpRequest.abortSignal) { + if (httpRequest.abortSignal.aborted) { + throw new abortController.AbortError("The operation was aborted."); + } + abortListener = (event) => { + if (event.type === "abort") { + abortController$1.abort(); } - }); - }); - }; - return FetchHttpClient; -}()); + }; + httpRequest.abortSignal.addEventListener("abort", abortListener); + } + if (httpRequest.timeout) { + setTimeout(() => { + abortController$1.abort(); + }, httpRequest.timeout); + } + if (httpRequest.formData) { + const formData = httpRequest.formData; + const requestForm = new FormData(); + const appendFormValue = (key, value) => { + // value function probably returns a stream so we can provide a fresh stream on each retry + if (typeof value === "function") { + value = value(); + } + if (value && + Object.prototype.hasOwnProperty.call(value, "value") && + Object.prototype.hasOwnProperty.call(value, "options")) { + requestForm.append(key, value.value, value.options); + } + else { + requestForm.append(key, value); + } + }; + for (const formKey of Object.keys(formData)) { + const formValue = formData[formKey]; + if (Array.isArray(formValue)) { + for (let j = 0; j < formValue.length; j++) { + appendFormValue(formKey, formValue[j]); + } + } + else { + appendFormValue(formKey, formValue); + } + } + httpRequest.body = requestForm; + httpRequest.formData = undefined; + const contentType = httpRequest.headers.get("Content-Type"); + if (contentType && contentType.indexOf("multipart/form-data") !== -1) { + if (typeof requestForm.getBoundary === "function") { + httpRequest.headers.set("Content-Type", `multipart/form-data; boundary=${requestForm.getBoundary()}`); + } + else { + // browser will automatically apply a suitable content-type header + httpRequest.headers.remove("Content-Type"); + } + } + } + let body = httpRequest.body + ? typeof httpRequest.body === "function" + ? httpRequest.body() + : httpRequest.body + : undefined; + if (httpRequest.onUploadProgress && httpRequest.body) { + const onUploadProgress = httpRequest.onUploadProgress; + const uploadReportStream = new ReportTransform(onUploadProgress); + if (isReadableStream(body)) { + body.pipe(uploadReportStream); + } + else { + uploadReportStream.end(body); + } + body = uploadReportStream; + } + const platformSpecificRequestInit = await this.prepareRequest(httpRequest); + const requestInit = Object.assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method, signal: abortController$1.signal, redirect: "manual" }, platformSpecificRequestInit); + let operationResponse; + try { + const response = await this.fetch(httpRequest.url, requestInit); + const headers = parseHeaders(response.headers); + const streaming = ((_a = httpRequest.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(response.status)) || + httpRequest.streamResponseBody; + operationResponse = { + headers: headers, + request: httpRequest, + status: response.status, + readableStreamBody: streaming + ? response.body + : undefined, + bodyAsText: !streaming ? await response.text() : undefined + }; + const onDownloadProgress = httpRequest.onDownloadProgress; + if (onDownloadProgress) { + const responseBody = response.body || undefined; + if (isReadableStream(responseBody)) { + const downloadReportStream = new ReportTransform(onDownloadProgress); + responseBody.pipe(downloadReportStream); + operationResponse.readableStreamBody = downloadReportStream; + } + else { + const length = parseInt(headers.get("Content-Length")) || undefined; + if (length) { + // Calling callback for non-stream response for consistency with browser + onDownloadProgress({ loadedBytes: length }); + } + } + } + await this.processRequest(operationResponse); + return operationResponse; + } + catch (error) { + const fetchError = error; + if (fetchError.code === "ENOTFOUND") { + throw new RestError(fetchError.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest); + } + else if (fetchError.type === "aborted") { + throw new abortController.AbortError("The operation was aborted."); + } + throw fetchError; + } + finally { + // clean up event listener + if (httpRequest.abortSignal && abortListener) { + let uploadStreamDone = Promise.resolve(); + if (isReadableStream(body)) { + uploadStreamDone = isStreamComplete(body); + } + let downloadStreamDone = Promise.resolve(); + if (isReadableStream(operationResponse === null || operationResponse === void 0 ? void 0 : operationResponse.readableStreamBody)) { + downloadStreamDone = isStreamComplete(operationResponse.readableStreamBody, abortController$1); + } + Promise.all([uploadStreamDone, downloadStreamDone]) + .then(() => { + var _a; + (_a = httpRequest.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener); + return; + }) + .catch((e) => { + logger.warning("Error when cleaning up abortListener on httpRequest", e); + }); + } + } + } +} 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 isStreamComplete(stream, aborter) { + return new Promise((resolve) => { + stream.once("close", () => { + aborter === null || aborter === void 0 ? void 0 : aborter.abort(); + resolve(); + }); + stream.once("end", resolve); + stream.once("error", resolve); }); } function parseHeaders(headers) { - var httpHeaders = new HttpHeaders(); - headers.forEach(function (value, key) { + const httpHeaders = new HttpHeaders(); + headers.forEach((value, key) => { httpHeaders.set(key, value); }); return httpHeaders; @@ -70372,14 +66190,14 @@ function parseHeaders(headers) { // Copyright (c) Microsoft Corporation. function createProxyAgent(requestUrl, proxySettings, headers) { - var host = URLBuilder.parse(proxySettings.host).getHost(); + const host = URLBuilder.parse(proxySettings.host).getHost(); if (!host) { throw new Error("Expecting a non-empty host in proxy settings."); } if (!isValidPort(proxySettings.port)) { throw new Error("Expecting a valid port number in the range of [0, 65535] in proxy settings."); } - var tunnelOptions = { + const tunnelOptions = { proxy: { host: host, port: proxySettings.port, @@ -70387,18 +66205,21 @@ function createProxyAgent(requestUrl, proxySettings, headers) { } }; if (proxySettings.username && proxySettings.password) { - tunnelOptions.proxy.proxyAuth = proxySettings.username + ":" + proxySettings.password; + tunnelOptions.proxy.proxyAuth = `${proxySettings.username}:${proxySettings.password}`; } - var isRequestHttps = isUrlHttps(requestUrl); - var isProxyHttps = isUrlHttps(proxySettings.host); - var proxyAgent = { + else if (proxySettings.username) { + tunnelOptions.proxy.proxyAuth = `${proxySettings.username}`; + } + const isRequestHttps = isUrlHttps(requestUrl); + const isProxyHttps = isUrlHttps(proxySettings.host); + const proxyAgent = { isHttps: isRequestHttps, agent: createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) }; return proxyAgent; } function isUrlHttps(url) { - var urlScheme = URLBuilder.parse(url).getScheme() || ""; + const urlScheme = URLBuilder.parse(url).getScheme() || ""; return urlScheme.toLowerCase() === "https"; } function createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) { @@ -70425,41 +66246,45 @@ function isValidPort(port) { function getCachedAgent(isHttps, agentCache) { return isHttps ? agentCache.httpsAgent : agentCache.httpAgent; } -var NodeFetchHttpClient = /** @class */ (function (_super) { - tslib.__extends(NodeFetchHttpClient, _super); - function NodeFetchHttpClient() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.proxyAgents = {}; - _this.keepAliveAgents = {}; - _this.cookieJar = new tough.CookieJar(undefined, { looseMode: true }); - return _this; +class NodeFetchHttpClient extends FetchHttpClient { + constructor() { + super(...arguments); + // a mapping of proxy settings string `${host}:${port}:${username}:${password}` to agent + this.proxyAgentMap = new Map(); + this.keepAliveAgents = {}; + this.cookieJar = new tough.CookieJar(undefined, { looseMode: true }); } - NodeFetchHttpClient.prototype.getOrCreateAgent = function (httpRequest) { - var isHttps = isUrlHttps(httpRequest.url); + getOrCreateAgent(httpRequest) { + var _a; + const isHttps = isUrlHttps(httpRequest.url); // At the moment, proxy settings and keepAlive are mutually // exclusive because the 'tunnel' library currently lacks the // ability to create a proxy with keepAlive turned on. if (httpRequest.proxySettings) { - var agent = getCachedAgent(isHttps, this.proxyAgents); + const { host, port, username, password } = httpRequest.proxySettings; + const key = `${host}:${port}:${username}:${password}`; + const proxyAgents = (_a = this.proxyAgentMap.get(key)) !== null && _a !== void 0 ? _a : {}; + let agent = getCachedAgent(isHttps, proxyAgents); if (agent) { return agent; } - var tunnel = createProxyAgent(httpRequest.url, httpRequest.proxySettings, httpRequest.headers); + const tunnel = createProxyAgent(httpRequest.url, httpRequest.proxySettings, httpRequest.headers); agent = tunnel.agent; if (tunnel.isHttps) { - this.proxyAgents.httpsAgent = tunnel.agent; + proxyAgents.httpsAgent = tunnel.agent; } else { - this.proxyAgents.httpAgent = tunnel.agent; + proxyAgents.httpAgent = tunnel.agent; } + this.proxyAgentMap.set(key, proxyAgents); return agent; } else if (httpRequest.keepAlive) { - var agent = getCachedAgent(isHttps, this.keepAliveAgents); + let agent = getCachedAgent(isHttps, this.keepAliveAgents); if (agent) { return agent; } - var agentOptions = { + const agentOptions = { keepAlive: httpRequest.keepAlive }; if (isHttps) { @@ -70473,77 +66298,49 @@ var NodeFetchHttpClient = /** @class */ (function (_super) { else { return isHttps ? https.globalAgent : http.globalAgent; } - }; + } // eslint-disable-next-line @azure/azure-sdk/ts-apisurface-standardized-verbs - NodeFetchHttpClient.prototype.fetch = function (input, init) { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - return [2 /*return*/, node_fetch(input, init)]; + async fetch(input, init) { + return node_fetch(input, init); + } + async prepareRequest(httpRequest) { + const requestInit = {}; + if (this.cookieJar && !httpRequest.headers.get("Cookie")) { + const cookieString = await new Promise((resolve, reject) => { + this.cookieJar.getCookieString(httpRequest.url, (err, cookie) => { + if (err) { + reject(err); + } + else { + resolve(cookie); + } + }); }); - }); - }; - NodeFetchHttpClient.prototype.prepareRequest = function (httpRequest) { - return tslib.__awaiter(this, void 0, void 0, function () { - var requestInit, cookieString; - var _this = this; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - requestInit = {}; - if (!(this.cookieJar && !httpRequest.headers.get("Cookie"))) return [3 /*break*/, 2]; - return [4 /*yield*/, new Promise(function (resolve, reject) { - _this.cookieJar.getCookieString(httpRequest.url, function (err, cookie) { - if (err) { - reject(err); - } - else { - resolve(cookie); - } - }); - })]; - case 1: - cookieString = _a.sent(); - httpRequest.headers.set("Cookie", cookieString); - _a.label = 2; - case 2: - // Set the http(s) agent - requestInit.agent = this.getOrCreateAgent(httpRequest); - requestInit.compress = httpRequest.decompressResponse; - return [2 /*return*/, requestInit]; - } - }); - }); - }; - NodeFetchHttpClient.prototype.processRequest = function (operationResponse) { - return tslib.__awaiter(this, void 0, void 0, function () { - var setCookieHeader_1; - var _this = this; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!this.cookieJar) return [3 /*break*/, 2]; - setCookieHeader_1 = operationResponse.headers.get("Set-Cookie"); - if (!(setCookieHeader_1 !== undefined)) return [3 /*break*/, 2]; - return [4 /*yield*/, new Promise(function (resolve, reject) { - _this.cookieJar.setCookie(setCookieHeader_1, operationResponse.request.url, { ignoreError: true }, function (err) { - if (err) { - reject(err); - } - else { - resolve(); - } - }); - })]; - case 1: - _a.sent(); - _a.label = 2; - case 2: return [2 /*return*/]; - } - }); - }); - }; - return NodeFetchHttpClient; -}(FetchHttpClient)); + httpRequest.headers.set("Cookie", cookieString); + } + // Set the http(s) agent + requestInit.agent = this.getOrCreateAgent(httpRequest); + requestInit.compress = httpRequest.decompressResponse; + return requestInit; + } + async processRequest(operationResponse) { + if (this.cookieJar) { + const setCookieHeader = operationResponse.headers.get("Set-Cookie"); + if (setCookieHeader !== undefined) { + await new Promise((resolve, reject) => { + this.cookieJar.setCookie(setCookieHeader, operationResponse.request.url, { ignoreError: true }, (err) => { + if (err) { + reject(err); + } + else { + resolve(); + } + }); + }); + } + } + } +} // Copyright (c) Microsoft Corporation. (function (HttpPipelineLogLevel) { @@ -70571,21 +66368,23 @@ var NodeFetchHttpClient = /** @class */ (function (_super) { * @param opts - OperationOptions object to convert to RequestOptionsBase */ function operationOptionsToRequestOptionsBase(opts) { - var requestOptions = opts.requestOptions, tracingOptions = opts.tracingOptions, additionalOptions = tslib.__rest(opts, ["requestOptions", "tracingOptions"]); - var result = additionalOptions; + var _a; + const { requestOptions, tracingOptions } = opts, additionalOptions = tslib.__rest(opts, ["requestOptions", "tracingOptions"]); + let result = additionalOptions; if (requestOptions) { - result = tslib.__assign(tslib.__assign({}, result), requestOptions); + result = Object.assign(Object.assign({}, result), requestOptions); } if (tracingOptions) { - result.spanOptions = tracingOptions.spanOptions; result.tracingContext = tracingOptions.tracingContext; + // By passing spanOptions if they exist at runtime, we're backwards compatible with @azure/core-tracing@preview.13 and earlier. + result.spanOptions = (_a = tracingOptions) === null || _a === void 0 ? void 0 : _a.spanOptions; } return result; } // Copyright (c) Microsoft Corporation. -var BaseRequestPolicy = /** @class */ (function () { - function BaseRequestPolicy(_nextPolicy, _options) { +class BaseRequestPolicy { + constructor(_nextPolicy, _options) { this._nextPolicy = _nextPolicy; this._options = _options; } @@ -70594,25 +66393,24 @@ var BaseRequestPolicy = /** @class */ (function () { * @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) { + shouldLog(logLevel) { return this._options.shouldLog(logLevel); - }; + } /** * 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. */ - BaseRequestPolicy.prototype.log = function (logLevel, message) { + log(logLevel, message) { this._options.log(logLevel, message); - }; - return BaseRequestPolicy; -}()); + } +} /** * Optional properties that can be used when creating a RequestPolicy. */ -var RequestPolicyOptions = /** @class */ (function () { - function RequestPolicyOptions(_logger) { +class RequestPolicyOptions { + constructor(_logger) { this._logger = _logger; } /** @@ -70620,104 +66418,89 @@ var RequestPolicyOptions = /** @class */ (function () { * @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) { + shouldLog(logLevel) { return (!!this._logger && logLevel !== exports.HttpPipelineLogLevel.OFF && logLevel <= this._logger.minimumLogLevel); - }; + } /** * 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. */ - RequestPolicyOptions.prototype.log = function (logLevel, message) { + log(logLevel, message) { if (this._logger && this.shouldLog(logLevel)) { this._logger.log(logLevel, message); } - }; - return RequestPolicyOptions; -}()); + } +} // Copyright (c) Microsoft Corporation. -function logPolicy(loggingOptions) { - if (loggingOptions === void 0) { loggingOptions = {}; } +function logPolicy(loggingOptions = {}) { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new LogPolicy(nextPolicy, options, loggingOptions); } }; } -var LogPolicy = /** @class */ (function (_super) { - tslib.__extends(LogPolicy, _super); - function LogPolicy(nextPolicy, options, _a) { - var _b = _a === void 0 ? {} : _a, _c = _b.logger, logger$1 = _c === void 0 ? logger.info : _c, _d = _b.allowedHeaderNames, allowedHeaderNames = _d === void 0 ? [] : _d, _e = _b.allowedQueryParameters, allowedQueryParameters = _e === void 0 ? [] : _e; - var _this = _super.call(this, nextPolicy, options) || this; - _this.logger = logger$1; - _this.sanitizer = new Sanitizer({ allowedHeaderNames: allowedHeaderNames, allowedQueryParameters: allowedQueryParameters }); - return _this; +class LogPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, { logger: logger$1 = logger.info, allowedHeaderNames = [], allowedQueryParameters = [] } = {}) { + super(nextPolicy, options); + this.logger = logger$1; + this.sanitizer = new Sanitizer({ allowedHeaderNames, allowedQueryParameters }); } - Object.defineProperty(LogPolicy.prototype, "allowedHeaderNames", { - /** - * Header names whose values will be logged when logging is enabled. Defaults to - * Date, traceparent, x-ms-client-request-id, and x-ms-request id. Any headers - * specified in this field will be added to that list. Any other values will - * be written to logs as "REDACTED". - * @deprecated Pass these into the constructor instead. - */ - get: function () { - return this.sanitizer.allowedHeaderNames; - }, - /** - * Header names whose values will be logged when logging is enabled. Defaults to - * Date, traceparent, x-ms-client-request-id, and x-ms-request id. Any headers - * specified in this field will be added to that list. Any other values will - * be written to logs as "REDACTED". - * @deprecated Pass these into the constructor instead. - */ - set: function (allowedHeaderNames) { - this.sanitizer.allowedHeaderNames = allowedHeaderNames; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(LogPolicy.prototype, "allowedQueryParameters", { - /** - * Query string names whose values will be logged when logging is enabled. By default no - * query string values are logged. - * @deprecated Pass these into the constructor instead. - */ - get: function () { - return this.sanitizer.allowedQueryParameters; - }, - /** - * Query string names whose values will be logged when logging is enabled. By default no - * query string values are logged. - * @deprecated Pass these into the constructor instead. - */ - set: function (allowedQueryParameters) { - this.sanitizer.allowedQueryParameters = allowedQueryParameters; - }, - enumerable: false, - configurable: true - }); - LogPolicy.prototype.sendRequest = function (request) { - var _this = this; + /** + * Header names whose values will be logged when logging is enabled. Defaults to + * Date, traceparent, x-ms-client-request-id, and x-ms-request id. Any headers + * specified in this field will be added to that list. Any other values will + * be written to logs as "REDACTED". + * @deprecated Pass these into the constructor instead. + */ + get allowedHeaderNames() { + return this.sanitizer.allowedHeaderNames; + } + /** + * Header names whose values will be logged when logging is enabled. Defaults to + * Date, traceparent, x-ms-client-request-id, and x-ms-request id. Any headers + * specified in this field will be added to that list. Any other values will + * be written to logs as "REDACTED". + * @deprecated Pass these into the constructor instead. + */ + set allowedHeaderNames(allowedHeaderNames) { + this.sanitizer.allowedHeaderNames = allowedHeaderNames; + } + /** + * Query string names whose values will be logged when logging is enabled. By default no + * query string values are logged. + * @deprecated Pass these into the constructor instead. + */ + get allowedQueryParameters() { + return this.sanitizer.allowedQueryParameters; + } + /** + * Query string names whose values will be logged when logging is enabled. By default no + * query string values are logged. + * @deprecated Pass these into the constructor instead. + */ + set allowedQueryParameters(allowedQueryParameters) { + this.sanitizer.allowedQueryParameters = allowedQueryParameters; + } + sendRequest(request) { if (!this.logger.enabled) return this._nextPolicy.sendRequest(request); this.logRequest(request); - return this._nextPolicy.sendRequest(request).then(function (response) { return _this.logResponse(response); }); - }; - LogPolicy.prototype.logRequest = function (request) { - this.logger("Request: " + this.sanitizer.sanitize(request)); - }; - LogPolicy.prototype.logResponse = function (response) { - this.logger("Response status code: " + response.status); - this.logger("Headers: " + this.sanitizer.sanitize(response.headers)); + return this._nextPolicy.sendRequest(request).then((response) => this.logResponse(response)); + } + logRequest(request) { + this.logger(`Request: ${this.sanitizer.sanitize(request)}`); + } + logResponse(response) { + this.logger(`Response status code: ${response.status}`); + this.logger(`Headers: ${this.sanitizer.sanitize(response.headers)}`); return response; - }; - return LogPolicy; -}(BaseRequestPolicy)); + } +} // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. @@ -70730,7 +66513,7 @@ function getPathStringFromParameter(parameter) { return getPathStringFromParameterPath(parameter.parameterPath, parameter.mapper); } function getPathStringFromParameterPath(parameterPath, mapper) { - var result; + let result; if (typeof parameterPath === "string") { result = parameterPath; } @@ -70749,9 +66532,9 @@ function getPathStringFromParameterPath(parameterPath, mapper) { * @internal */ function getStreamResponseStatusCodes(operationSpec) { - var result = new Set(); - for (var statusCode in operationSpec.responses) { - var operationResponse = operationSpec.responses[statusCode]; + const result = new Set(); + for (const statusCode in operationSpec.responses) { + const operationResponse = operationSpec.responses[statusCode]; if (operationResponse.bodyMapper && operationResponse.bodyMapper.type.name === MapperType.Stream) { result.add(Number(statusCode)); @@ -70765,7 +66548,7 @@ function getStreamResponseStatusCodes(operationSpec) { // by the xm2js library is mutable. See https://github.com/Leonidas-from-XIV/node-xml2js/issues/536 // By creating a new copy of the settings each time we instantiate the parser, // we are safeguarding against the possibility of the default settings being mutated elsewhere unintentionally. -var xml2jsDefaultOptionsV2 = { +const xml2jsDefaultOptionsV2 = { explicitCharkey: false, trim: false, normalize: false, @@ -70806,10 +66589,10 @@ var xml2jsDefaultOptionsV2 = { cdata: false }; // The xml2js settings for general XML parsing operations. -var xml2jsParserSettings = Object.assign({}, xml2jsDefaultOptionsV2); +const xml2jsParserSettings = Object.assign({}, xml2jsDefaultOptionsV2); xml2jsParserSettings.explicitArray = false; // The xml2js settings for general XML building operations. -var xml2jsBuilderSettings = Object.assign({}, xml2jsDefaultOptionsV2); +const xml2jsBuilderSettings = Object.assign({}, xml2jsDefaultOptionsV2); xml2jsBuilderSettings.explicitArray = false; xml2jsBuilderSettings.renderOpts = { pretty: false @@ -70819,12 +66602,11 @@ xml2jsBuilderSettings.renderOpts = { * @param obj - JSON object to be converted into XML string * @param opts - Options that govern the parsing of given JSON object */ -function stringifyXML(obj, opts) { +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; - var builder = new xml2js.Builder(xml2jsBuilderSettings); + const builder = new xml2js.Builder(xml2jsBuilderSettings); return builder.buildObject(obj); } /** @@ -70832,18 +66614,17 @@ function stringifyXML(obj, opts) { * @param str - String containing the XML content to be parsed into JSON * @param opts - Options that govern the parsing of given xml string */ -function parseXML(str, opts) { +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; - var xmlParser = new xml2js.Parser(xml2jsParserSettings); - return new Promise(function (resolve, reject) { + const xmlParser = new xml2js.Parser(xml2jsParserSettings); + return new Promise((resolve, reject) => { if (!str) { reject(new Error("Document is empty")); } else { - xmlParser.parseString(str, function (err, res) { + xmlParser.parseString(str, (err, res) => { if (err) { reject(err); } @@ -70862,14 +66643,14 @@ function parseXML(str, opts) { */ function deserializationPolicy(deserializationContentTypes, parsingOptions) { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new DeserializationPolicy(nextPolicy, options, deserializationContentTypes, parsingOptions); } }; } -var defaultJsonContentTypes = ["application/json", "text/json"]; -var defaultXmlContentTypes = ["application/xml", "application/atom+xml"]; -var DefaultDeserializationOptions = { +const defaultJsonContentTypes = ["application/json", "text/json"]; +const defaultXmlContentTypes = ["application/xml", "application/atom+xml"]; +const DefaultDeserializationOptions = { expectedContentTypes: { json: defaultJsonContentTypes, xml: defaultXmlContentTypes @@ -70879,39 +66660,28 @@ var DefaultDeserializationOptions = { * A RequestPolicy that will deserialize HTTP response bodies and headers as they pass through the * HTTP pipeline. */ -var DeserializationPolicy = /** @class */ (function (_super) { - tslib.__extends(DeserializationPolicy, _super); - function DeserializationPolicy(nextPolicy, requestPolicyOptions, deserializationContentTypes, parsingOptions) { - if (parsingOptions === void 0) { parsingOptions = {}; } +class DeserializationPolicy extends BaseRequestPolicy { + constructor(nextPolicy, requestPolicyOptions, deserializationContentTypes, parsingOptions = {}) { var _a; - var _this = _super.call(this, nextPolicy, requestPolicyOptions) || this; - _this.jsonContentTypes = + super(nextPolicy, requestPolicyOptions); + this.jsonContentTypes = (deserializationContentTypes && deserializationContentTypes.json) || defaultJsonContentTypes; - _this.xmlContentTypes = + this.xmlContentTypes = (deserializationContentTypes && deserializationContentTypes.xml) || defaultXmlContentTypes; - _this.xmlCharKey = (_a = parsingOptions.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; - return _this; + this.xmlCharKey = (_a = parsingOptions.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; } - 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 DeserializationPolicy; -}(BaseRequestPolicy)); + async sendRequest(request) { + return this._nextPolicy.sendRequest(request).then((response) => deserializeResponseBody(this.jsonContentTypes, this.xmlContentTypes, response, { + xmlCharKey: this.xmlCharKey + })); + } +} function getOperationResponse(parsedResponse) { - var result; - var request = parsedResponse.request; - var operationSpec = request.operationSpec; + let result; + const request = parsedResponse.request; + const operationSpec = request.operationSpec; if (operationSpec) { - var operationResponseGetter = request.operationResponseGetter; + const operationResponseGetter = request.operationResponseGetter; if (!operationResponseGetter) { result = operationSpec.responses[parsedResponse.status]; } @@ -70922,8 +66692,8 @@ function getOperationResponse(parsedResponse) { return result; } function shouldDeserializeResponse(parsedResponse) { - var shouldDeserialize = parsedResponse.request.shouldDeserialize; - var result; + const shouldDeserialize = parsedResponse.request.shouldDeserialize; + let result; if (shouldDeserialize === undefined) { result = true; } @@ -70935,24 +66705,23 @@ function shouldDeserializeResponse(parsedResponse) { } return result; } -function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options) { +function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options = {}) { var _a, _b, _c; - if (options === void 0) { options = {}; } - var updatedOptions = { + const 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) { + return parse(jsonContentTypes, xmlContentTypes, response, updatedOptions).then((parsedResponse) => { if (!shouldDeserializeResponse(parsedResponse)) { return parsedResponse; } - var operationSpec = parsedResponse.request.operationSpec; + const operationSpec = parsedResponse.request.operationSpec; if (!operationSpec || !operationSpec.responses) { return parsedResponse; } - var responseSpec = getOperationResponse(parsedResponse); - var _a = handleErrorResponse(parsedResponse, operationSpec, responseSpec), error = _a.error, shouldReturnResponse = _a.shouldReturnResponse; + const responseSpec = getOperationResponse(parsedResponse); + const { error, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec); if (error) { throw error; } @@ -70963,7 +66732,7 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, op // use it to deserialize the response. if (responseSpec) { if (responseSpec.bodyMapper) { - var valueToDeserialize = parsedResponse.parsedBody; + let valueToDeserialize = parsedResponse.parsedBody; if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperType.Sequence) { valueToDeserialize = typeof valueToDeserialize === "object" @@ -70974,7 +66743,7 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, op parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options); } catch (innerError) { - var restError = new RestError("Error " + innerError + " occurred in deserializing the responseBody - " + parsedResponse.bodyAsText, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); + const restError = new RestError(`Error ${innerError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); throw restError; } } @@ -70990,14 +66759,14 @@ function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, op }); } function isOperationSpecEmpty(operationSpec) { - var expectedStatusCodes = Object.keys(operationSpec.responses); + const 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) + const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300; + const isExpectedStatusCode = isOperationSpecEmpty(operationSpec) ? isSuccessByStatus : !!responseSpec; if (isExpectedStatusCode) { @@ -71010,35 +66779,35 @@ function handleErrorResponse(parsedResponse, operationSpec, responseSpec) { 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)) || + const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default; + const 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 + const initialErrorMessage = streaming + ? `Unexpected status code: ${parsedResponse.status}` : parsedResponse.bodyAsText; - var error = new RestError(initialErrorMessage, undefined, parsedResponse.status, parsedResponse.request, parsedResponse); + const 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; + const defaultBodyMapper = errorResponseSpec.bodyMapper; + const 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; + const parsedBody = parsedResponse.parsedBody; + let parsedError; if (defaultBodyMapper) { - var valueToDeserialize = parsedBody; + let 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; + const internalError = parsedBody.error || parsedError || parsedBody; error.code = internalError.code; if (internalError.message) { error.message = internalError.message; @@ -71053,36 +66822,36 @@ function handleErrorResponse(parsedResponse, operationSpec, responseSpec) { } } catch (defaultError) { - error.message = "Error \"" + defaultError.message + "\" occurred in deserializing the responseBody - \"" + parsedResponse.bodyAsText + "\" for the default response."; + error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`; } - return { error: error, shouldReturnResponse: false }; + return { error, shouldReturnResponse: false }; } function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts) { var _a; - 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); + const errorHandler = (err) => { + const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`; + const errCode = err.code || RestError.PARSE_ERROR; + const 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)) || + const streaming = ((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) || operationResponse.request.streamResponseBody; if (!streaming && operationResponse.bodyAsText) { - var text_1 = operationResponse.bodyAsText; - var contentType = operationResponse.headers.get("Content-Type") || ""; - var contentComponents = !contentType + const text = operationResponse.bodyAsText; + const contentType = operationResponse.headers.get("Content-Type") || ""; + const contentComponents = !contentType ? [] - : contentType.split(";").map(function (component) { return component.toLowerCase(); }); + : contentType.split(";").map((component) => component.toLowerCase()); if (contentComponents.length === 0 || - contentComponents.some(function (component) { return jsonContentTypes.indexOf(component) !== -1; })) { - return new Promise(function (resolve) { - operationResponse.parsedBody = JSON.parse(text_1); + contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) { + return new Promise((resolve) => { + operationResponse.parsedBody = JSON.parse(text); resolve(operationResponse); }).catch(errorHandler); } - else if (contentComponents.some(function (component) { return xmlContentTypes.indexOf(component) !== -1; })) { - return parseXML(text_1, opts) - .then(function (body) { + else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) { + return parseXML(text, opts) + .then((body) => { operationResponse.parsedBody = body; return operationResponse; }) @@ -71094,11 +66863,11 @@ function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts) { // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -var DEFAULT_CLIENT_RETRY_COUNT = 3; +const DEFAULT_CLIENT_RETRY_COUNT = 3; // intervals are in ms -var DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30; -var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90; -var DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3; +const DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30; +const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90; +const DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3; function isNumber(n) { return typeof n === "number"; } @@ -71125,8 +66894,7 @@ function shouldRetry(retryLimit, predicate, retryData, response, error) { * @param retryData - The retry data. * @param err - The operation"s error, if any. */ -function updateRetryData(retryOptions, retryData, err) { - if (retryData === void 0) { retryData = { retryCount: 0, retryInterval: 0 }; } +function updateRetryData(retryOptions, retryData = { retryCount: 0, retryInterval: 0 }, err) { if (err) { if (retryData.error) { err.innerError = retryData.error; @@ -71136,18 +66904,72 @@ function updateRetryData(retryOptions, retryData, err) { // Adjust retry count retryData.retryCount++; // Adjust retry interval - var incrementDelta = Math.pow(2, retryData.retryCount - 1) - 1; - var boundedRandDelta = retryOptions.retryInterval * 0.8 + + let incrementDelta = Math.pow(2, retryData.retryCount - 1) - 1; + const boundedRandDelta = retryOptions.retryInterval * 0.8 + Math.floor(Math.random() * (retryOptions.retryInterval * 0.4)); incrementDelta *= boundedRandDelta; retryData.retryInterval = Math.min(retryOptions.minRetryInterval + incrementDelta, retryOptions.maxRetryInterval); return retryData; } +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. +/** + * Helper TypeGuard that checks if the value is not null or undefined. + * @param thing - Anything + * @internal + */ +function isDefined(thing) { + return typeof thing !== "undefined" && thing !== null; +} + +// Copyright (c) Microsoft Corporation. +const StandardAbortMessage = "The operation was aborted."; +/** + * A wrapper for setTimeout that resolves a promise after delayInMs milliseconds. + * @param delayInMs - The number of milliseconds to be delayed. + * @param value - The value to be resolved with after a timeout of t milliseconds. + * @param options - The options for delay - currently abort options + * @param abortSignal - The abortSignal associated with containing operation. + * @param abortErrorMsg - The abort error message associated with containing operation. + * @returns - Resolved promise + */ +function delay(delayInMs, value, options) { + return new Promise((resolve, reject) => { + let timer = undefined; + let onAborted = undefined; + const rejectOnAbort = () => { + return reject(new abortController.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage)); + }; + const removeListeners = () => { + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) { + options.abortSignal.removeEventListener("abort", onAborted); + } + }; + onAborted = () => { + if (isDefined(timer)) { + clearTimeout(timer); + } + removeListeners(); + return rejectOnAbort(); + }; + if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) { + return rejectOnAbort(); + } + timer = setTimeout(() => { + removeListeners(); + resolve(value); + }, delayInMs); + if (options === null || options === void 0 ? void 0 : options.abortSignal) { + options.abortSignal.addEventListener("abort", onAborted); + } + }); +} + // Copyright (c) Microsoft Corporation. function exponentialRetryPolicy(retryCount, retryInterval, maxRetryInterval) { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, maxRetryInterval); } }; @@ -71155,7 +66977,7 @@ function exponentialRetryPolicy(retryCount, retryInterval, maxRetryInterval) { (function (RetryMode) { RetryMode[RetryMode["Exponential"] = 0] = "Exponential"; })(exports.RetryMode || (exports.RetryMode = {})); -var DefaultRetryOptions = { +const DefaultRetryOptions = { maxRetries: DEFAULT_CLIENT_RETRY_COUNT, retryDelayInMs: DEFAULT_CLIENT_RETRY_INTERVAL, maxRetryDelayInMs: DEFAULT_CLIENT_MAX_RETRY_INTERVAL @@ -71163,8 +66985,7 @@ var DefaultRetryOptions = { /** * Instantiates a new "ExponentialRetryPolicyFilter" instance. */ -var ExponentialRetryPolicy = /** @class */ (function (_super) { - tslib.__extends(ExponentialRetryPolicy, _super); +class ExponentialRetryPolicy extends BaseRequestPolicy { /** * @param nextPolicy - The next RequestPolicy in the pipeline chain. * @param options - The options for this RequestPolicy. @@ -71173,217 +66994,188 @@ var ExponentialRetryPolicy = /** @class */ (function (_super) { * @param minRetryInterval - The minimum retry interval, in milliseconds. * @param maxRetryInterval - The maximum retry interval, in milliseconds. */ - function ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, maxRetryInterval) { - var _this = _super.call(this, nextPolicy, options) || this; - _this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT; - _this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL; - _this.maxRetryInterval = isNumber(maxRetryInterval) + constructor(nextPolicy, options, retryCount, retryInterval, maxRetryInterval) { + super(nextPolicy, options); + this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT; + this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL; + this.maxRetryInterval = isNumber(maxRetryInterval) ? maxRetryInterval : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; - return _this; } - ExponentialRetryPolicy.prototype.sendRequest = function (request) { - var _this = this; + sendRequest(request) { return this._nextPolicy .sendRequest(request.clone()) - .then(function (response) { return retry(_this, request, response); }) - .catch(function (error) { return retry(_this, request, error.response, undefined, error); }); - }; - return ExponentialRetryPolicy; -}(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; - if (statusCode === undefined || - (statusCode < 500 && statusCode !== 408) || - statusCode === 501 || - statusCode === 505) { - return false; - } - return true; + .then((response) => retry(this, request, response)) + .catch((error) => retry(this, request, error.response, undefined, error)); + } +} +async function retry(policy, request, response, retryData, requestError) { + function shouldPolicyRetry(responseParam) { + const statusCode = responseParam === null || responseParam === void 0 ? void 0 : responseParam.status; + if (statusCode === 503 && (response === null || response === void 0 ? void 0 : response.headers.get(Constants.HeaderConstants.RETRY_AFTER))) { + return false; } - var isAborted, res, err_1, err; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - retryData = updateRetryData({ - retryInterval: policy.retryInterval, - minRetryInterval: 0, - maxRetryInterval: policy.maxRetryInterval - }, retryData, requestError); - isAborted = request.abortSignal && request.abortSignal.aborted; - if (!(!isAborted && shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, response))) return [3 /*break*/, 6]; - logger.info("Retrying request in " + retryData.retryInterval); - _a.label = 1; - case 1: - _a.trys.push([1, 4, , 5]); - return [4 /*yield*/, delay(retryData.retryInterval)]; - case 2: - _a.sent(); - return [4 /*yield*/, policy._nextPolicy.sendRequest(request.clone())]; - case 3: - res = _a.sent(); - return [2 /*return*/, retry(policy, request, res, retryData)]; - case 4: - err_1 = _a.sent(); - return [2 /*return*/, retry(policy, request, response, retryData, err_1)]; - case 5: return [3 /*break*/, 7]; - case 6: - if (isAborted || requestError || !response) { - err = retryData.error || - new RestError("Failed to send the request.", RestError.REQUEST_SEND_ERROR, response && response.status, response && response.request, response); - throw err; - } - else { - return [2 /*return*/, response]; - } - case 7: return [2 /*return*/]; - } - }); - }); + if (statusCode === undefined || + (statusCode < 500 && statusCode !== 408) || + statusCode === 501 || + statusCode === 505) { + return false; + } + return true; + } + retryData = updateRetryData({ + retryInterval: policy.retryInterval, + minRetryInterval: 0, + maxRetryInterval: policy.maxRetryInterval + }, retryData, requestError); + const isAborted = request.abortSignal && request.abortSignal.aborted; + if (!isAborted && shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, response)) { + logger.info(`Retrying request in ${retryData.retryInterval}`); + try { + await delay(retryData.retryInterval); + const res = await policy._nextPolicy.sendRequest(request.clone()); + return retry(policy, request, res, retryData); + } + catch (err) { + return retry(policy, request, response, retryData, err); + } + } + else if (isAborted || requestError || !response) { + // If the operation failed in the end, return all errors instead of just the last one + const err = retryData.error || + new RestError("Failed to send the request.", RestError.REQUEST_SEND_ERROR, response && response.status, response && response.request, response); + throw err; + } + else { + return response; + } } // Copyright (c) Microsoft Corporation. -function generateClientRequestIdPolicy(requestIdHeaderName) { - if (requestIdHeaderName === void 0) { requestIdHeaderName = "x-ms-client-request-id"; } +function generateClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new GenerateClientRequestIdPolicy(nextPolicy, options, requestIdHeaderName); } }; } -var GenerateClientRequestIdPolicy = /** @class */ (function (_super) { - tslib.__extends(GenerateClientRequestIdPolicy, _super); - function GenerateClientRequestIdPolicy(nextPolicy, options, _requestIdHeaderName) { - var _this = _super.call(this, nextPolicy, options) || this; - _this._requestIdHeaderName = _requestIdHeaderName; - return _this; +class GenerateClientRequestIdPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, _requestIdHeaderName) { + super(nextPolicy, options); + this._requestIdHeaderName = _requestIdHeaderName; } - GenerateClientRequestIdPolicy.prototype.sendRequest = function (request) { + sendRequest(request) { if (!request.headers.contains(this._requestIdHeaderName)) { request.headers.set(this._requestIdHeaderName, request.requestId); } return this._nextPolicy.sendRequest(request); - }; - return GenerateClientRequestIdPolicy; -}(BaseRequestPolicy)); + } +} // Copyright (c) Microsoft Corporation. function getDefaultUserAgentKey() { return Constants.HeaderConstants.USER_AGENT; } function getPlatformSpecificData() { - var runtimeInfo = { + const runtimeInfo = { key: "Node", value: process.version }; - var osInfo = { + const osInfo = { key: "OS", - value: "(" + os.arch() + "-" + os.type() + "-" + os.release() + ")" + value: `(${os.arch()}-${os.type()}-${os.release()})` }; return [runtimeInfo, osInfo]; } // Copyright (c) Microsoft Corporation. function getRuntimeInfo() { - var msRestRuntime = { + const msRestRuntime = { key: "core-http", value: Constants.coreHttpVersion }; return [msRestRuntime]; } -function getUserAgentString(telemetryInfo, keySeparator, valueSeparator) { - if (keySeparator === void 0) { keySeparator = " "; } - if (valueSeparator === void 0) { valueSeparator = "/"; } +function getUserAgentString(telemetryInfo, keySeparator = " ", valueSeparator = "/") { return telemetryInfo - .map(function (info) { - var value = info.value ? "" + valueSeparator + info.value : ""; - return "" + info.key + value; + .map((info) => { + const value = info.value ? `${valueSeparator}${info.value}` : ""; + return `${info.key}${value}`; }) .join(keySeparator); } -var getDefaultUserAgentHeaderName = getDefaultUserAgentKey; +const getDefaultUserAgentHeaderName = getDefaultUserAgentKey; function getDefaultUserAgentValue() { - var runtimeInfo = getRuntimeInfo(); - var platformSpecificData = getPlatformSpecificData(); - var userAgent = getUserAgentString(runtimeInfo.concat(platformSpecificData)); + const runtimeInfo = getRuntimeInfo(); + const platformSpecificData = getPlatformSpecificData(); + const userAgent = getUserAgentString(runtimeInfo.concat(platformSpecificData)); return userAgent; } function userAgentPolicy(userAgentData) { - var key = !userAgentData || userAgentData.key === undefined || userAgentData.key === null + const key = !userAgentData || userAgentData.key === undefined || userAgentData.key === null ? getDefaultUserAgentKey() : userAgentData.key; - var value = !userAgentData || userAgentData.value === undefined || userAgentData.value === null + const value = !userAgentData || userAgentData.value === undefined || userAgentData.value === null ? getDefaultUserAgentValue() : userAgentData.value; return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new UserAgentPolicy(nextPolicy, options, key, value); } }; } -var UserAgentPolicy = /** @class */ (function (_super) { - tslib.__extends(UserAgentPolicy, _super); - function UserAgentPolicy(_nextPolicy, _options, headerKey, headerValue) { - var _this = _super.call(this, _nextPolicy, _options) || this; - _this._nextPolicy = _nextPolicy; - _this._options = _options; - _this.headerKey = headerKey; - _this.headerValue = headerValue; - return _this; +class UserAgentPolicy extends BaseRequestPolicy { + constructor(_nextPolicy, _options, headerKey, headerValue) { + super(_nextPolicy, _options); + this._nextPolicy = _nextPolicy; + this._options = _options; + this.headerKey = headerKey; + this.headerValue = headerValue; } - UserAgentPolicy.prototype.sendRequest = function (request) { + sendRequest(request) { this.addUserAgentHeader(request); return this._nextPolicy.sendRequest(request); - }; - UserAgentPolicy.prototype.addUserAgentHeader = function (request) { + } + addUserAgentHeader(request) { if (!request.headers) { request.headers = new HttpHeaders(); } if (!request.headers.get(this.headerKey) && this.headerValue) { request.headers.set(this.headerKey, this.headerValue); } - }; - return UserAgentPolicy; -}(BaseRequestPolicy)); + } +} // Copyright (c) Microsoft Corporation. /** * Methods that are allowed to follow redirects 301 and 302 */ -var allowedRedirect = ["GET", "HEAD"]; -var DefaultRedirectOptions = { +const allowedRedirect = ["GET", "HEAD"]; +const DefaultRedirectOptions = { handleRedirects: true, maxRetries: 20 }; -function redirectPolicy(maximumRetries) { - if (maximumRetries === void 0) { maximumRetries = 20; } +function redirectPolicy(maximumRetries = 20) { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new RedirectPolicy(nextPolicy, options, maximumRetries); } }; } -var RedirectPolicy = /** @class */ (function (_super) { - tslib.__extends(RedirectPolicy, _super); - function RedirectPolicy(nextPolicy, options, maxRetries) { - if (maxRetries === void 0) { maxRetries = 20; } - var _this = _super.call(this, nextPolicy, options) || this; - _this.maxRetries = maxRetries; - return _this; +class RedirectPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, maxRetries = 20) { + super(nextPolicy, options); + this.maxRetries = maxRetries; } - RedirectPolicy.prototype.sendRequest = function (request) { - var _this = this; + sendRequest(request) { return this._nextPolicy .sendRequest(request) - .then(function (response) { return handleRedirect(_this, response, 0); }); - }; - return RedirectPolicy; -}(BaseRequestPolicy)); + .then((response) => handleRedirect(this, response, 0)); + } +} function handleRedirect(policy, response, currentRetries) { - var request = response.request, status = response.status; - var locationHeader = response.headers.get("location"); + const { request, status } = response; + const locationHeader = response.headers.get("location"); if (locationHeader && (status === 300 || (status === 301 && allowedRedirect.includes(request.method)) || @@ -71391,7 +67183,7 @@ function handleRedirect(policy, response, currentRetries) { (status === 303 && request.method === "POST") || status === 307) && (!policy.maxRetries || currentRetries < policy.maxRetries)) { - var builder = URLBuilder.parse(request.url); + const builder = URLBuilder.parse(request.url); builder.setPath(locationHeader); request.url = builder.toString(); // POST request with Status code 303 should be converted into a @@ -71402,47 +67194,41 @@ function handleRedirect(policy, response, currentRetries) { } return policy._nextPolicy .sendRequest(request) - .then(function (res) { return handleRedirect(policy, res, currentRetries + 1); }); + .then((res) => handleRedirect(policy, res, currentRetries + 1)); } return Promise.resolve(response); } // Copyright (c) Microsoft Corporation. -function rpRegistrationPolicy(retryTimeout) { - if (retryTimeout === void 0) { retryTimeout = 30; } +function rpRegistrationPolicy(retryTimeout = 30) { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new RPRegistrationPolicy(nextPolicy, options, retryTimeout); } }; } -var RPRegistrationPolicy = /** @class */ (function (_super) { - tslib.__extends(RPRegistrationPolicy, _super); - function RPRegistrationPolicy(nextPolicy, options, _retryTimeout) { - if (_retryTimeout === void 0) { _retryTimeout = 30; } - var _this = _super.call(this, nextPolicy, options) || this; - _this._retryTimeout = _retryTimeout; - return _this; +class RPRegistrationPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, _retryTimeout = 30) { + super(nextPolicy, options); + this._retryTimeout = _retryTimeout; } - RPRegistrationPolicy.prototype.sendRequest = function (request) { - var _this = this; + sendRequest(request) { return this._nextPolicy .sendRequest(request.clone()) - .then(function (response) { return registerIfNeeded(_this, request, response); }); - }; - return RPRegistrationPolicy; -}(BaseRequestPolicy)); + .then((response) => registerIfNeeded(this, request, response)); + } +} function registerIfNeeded(policy, request, response) { if (response.status === 409) { - var rpName = checkRPNotRegisteredError(response.bodyAsText); + const rpName = checkRPNotRegisteredError(response.bodyAsText); if (rpName) { - var urlPrefix = extractSubscriptionUrl(request.url); + const urlPrefix = extractSubscriptionUrl(request.url); return (registerRP(policy, urlPrefix, rpName, request) // Autoregistration of ${provider} failed for some reason. We will not return this error // instead will return the initial response with 409 status code back to the user. // do nothing here as we are returning the original response at the end of this method. - .catch(function () { return false; }) - .then(function (registrationStatus) { + .catch(() => false) + .then((registrationStatus) => { if (registrationStatus) { // Retry the original request. We have to change the x-ms-client-request-id // otherwise Azure endpoint will return the initial 409 (cached) response. @@ -71461,9 +67247,8 @@ function registerIfNeeded(policy, request, response) { * @param reuseUrlToo - Should the url from the original request be reused as well. Default false. * @returns A new request object with desired headers. */ -function getRequestEssentials(originalRequest, reuseUrlToo) { - if (reuseUrlToo === void 0) { reuseUrlToo = false; } - var reqOptions = originalRequest.clone(); +function getRequestEssentials(originalRequest, reuseUrlToo = false) { + const reqOptions = originalRequest.clone(); if (reuseUrlToo) { reqOptions.url = originalRequest.url; } @@ -71481,7 +67266,7 @@ function getRequestEssentials(originalRequest, reuseUrlToo) { * @returns The name of the RP if condition is satisfied else undefined. */ function checkRPNotRegisteredError(body) { - var result, responseBody; + let result, responseBody; if (body) { try { responseBody = JSON.parse(body); @@ -71494,7 +67279,7 @@ function checkRPNotRegisteredError(body) { responseBody.error.message && responseBody.error.code && responseBody.error.code === "MissingSubscriptionRegistration") { - var matchRes = responseBody.error.message.match(/.*'(.*)'/i); + const matchRes = responseBody.error.message.match(/.*'(.*)'/i); if (matchRes) { result = matchRes.pop(); } @@ -71509,13 +67294,13 @@ function checkRPNotRegisteredError(body) { * @returns The url prefix as explained above. */ function extractSubscriptionUrl(url) { - var result; - var matchRes = url.match(/.*\/subscriptions\/[a-f0-9-]+\//gi); + let result; + const matchRes = url.match(/.*\/subscriptions\/[a-f0-9-]+\//gi); if (matchRes && matchRes[0]) { result = matchRes[0]; } else { - throw new Error("Unable to extract subscriptionId from the given url - " + url + "."); + throw new Error(`Unable to extract subscriptionId from the given url - ${url}.`); } return result; } @@ -71526,20 +67311,18 @@ function extractSubscriptionUrl(url) { * @param provider - The provider name to be registered. * @param 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 */ -function registerRP(policy, urlPrefix, provider, originalRequest) { - var postUrl = urlPrefix + "providers/" + provider + "/register?api-version=2016-02-01"; - var getUrl = urlPrefix + "providers/" + provider + "?api-version=2016-02-01"; - var reqOptions = getRequestEssentials(originalRequest); +async function registerRP(policy, urlPrefix, provider, originalRequest) { + const postUrl = `${urlPrefix}providers/${provider}/register?api-version=2016-02-01`; + const getUrl = `${urlPrefix}providers/${provider}?api-version=2016-02-01`; + const reqOptions = getRequestEssentials(originalRequest); reqOptions.method = "POST"; reqOptions.url = postUrl; - return policy._nextPolicy.sendRequest(reqOptions).then(function (response) { - if (response.status !== 200) { - throw new Error("Autoregistration of " + provider + " failed. Please try registering manually."); - } - return getRegistrationStatus(policy, getUrl, originalRequest); - }); + const response = await policy._nextPolicy.sendRequest(reqOptions); + if (response.status !== 200) { + throw new Error(`Autoregistration of ${provider} failed. Please try registering manually.`); + } + return getRegistrationStatus(policy, getUrl, originalRequest); } /** * Polls the registration status of the provider that was registered. Polling happens at an interval of 30 seconds. @@ -71550,25 +67333,24 @@ function registerRP(policy, urlPrefix, provider, originalRequest) { * with a message that the provider is not registered. * @returns True if RP Registration is successful. */ -function getRegistrationStatus(policy, url, originalRequest) { - var reqOptions = getRequestEssentials(originalRequest); +async function getRegistrationStatus(policy, url, originalRequest) { + const reqOptions = getRequestEssentials(originalRequest); reqOptions.url = url; reqOptions.method = "GET"; - return policy._nextPolicy.sendRequest(reqOptions).then(function (res) { - var obj = res.parsedBody; - if (res.parsedBody && obj.registrationState && obj.registrationState === "Registered") { - return true; - } - else { - return delay(policy._retryTimeout * 1000) - .then(function () { return getRegistrationStatus(policy, url, originalRequest); }); - } - }); + const res = await policy._nextPolicy.sendRequest(reqOptions); + const obj = res.parsedBody; + if (res.parsedBody && obj.registrationState && obj.registrationState === "Registered") { + return true; + } + else { + await delay(policy._retryTimeout * 1000); + return getRegistrationStatus(policy, url, originalRequest); + } } // Copyright (c) Microsoft Corporation. // Default options for the cycler if none are provided -var DEFAULT_CYCLER_OPTIONS = { +const DEFAULT_CYCLER_OPTIONS = { forcedRefreshWindowInMs: 1000, retryIntervalInMs: 3000, refreshWindowInMs: 1000 * 60 * 2 // Start refreshing 2m before expiry @@ -71586,59 +67368,33 @@ var DEFAULT_CYCLER_OPTIONS = { * throwing an exception * @returns - a promise that, if it resolves, will resolve with an access token */ -function beginRefresh(getAccessToken, retryIntervalInMs, timeoutInMs) { - return tslib.__awaiter(this, void 0, void 0, function () { - // This wrapper handles exceptions gracefully as long as we haven't exceeded - // the timeout. - function tryGetAccessToken() { - return tslib.__awaiter(this, void 0, void 0, function () { - var _a, finalToken; - return tslib.__generator(this, function (_b) { - switch (_b.label) { - case 0: - if (!(Date.now() < timeoutInMs)) return [3 /*break*/, 5]; - _b.label = 1; - case 1: - _b.trys.push([1, 3, , 4]); - return [4 /*yield*/, getAccessToken()]; - case 2: return [2 /*return*/, _b.sent()]; - case 3: - _a = _b.sent(); - return [2 /*return*/, null]; - case 4: return [3 /*break*/, 7]; - case 5: return [4 /*yield*/, getAccessToken()]; - case 6: - finalToken = _b.sent(); - // Timeout is up, so throw if it's still null - if (finalToken === null) { - throw new Error("Failed to refresh access token."); - } - return [2 /*return*/, finalToken]; - case 7: return [2 /*return*/]; - } - }); - }); - } - var token; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, tryGetAccessToken()]; - case 1: - token = _a.sent(); - _a.label = 2; - case 2: - if (!(token === null)) return [3 /*break*/, 5]; - return [4 /*yield*/, delay(retryIntervalInMs)]; - case 3: - _a.sent(); - return [4 /*yield*/, tryGetAccessToken()]; - case 4: - token = _a.sent(); - return [3 /*break*/, 2]; - case 5: return [2 /*return*/, token]; +async function beginRefresh(getAccessToken, retryIntervalInMs, timeoutInMs) { + // This wrapper handles exceptions gracefully as long as we haven't exceeded + // the timeout. + async function tryGetAccessToken() { + if (Date.now() < timeoutInMs) { + try { + return await getAccessToken(); } - }); - }); + catch (_a) { + return null; + } + } + else { + const finalToken = await getAccessToken(); + // Timeout is up, so throw if it's still null + if (finalToken === null) { + throw new Error("Failed to refresh access token."); + } + return finalToken; + } + } + let token = await tryGetAccessToken(); + while (token === null) { + await delay(retryIntervalInMs); + token = await tryGetAccessToken(); + } + return token; } /** * Creates a token cycler from a credential, scopes, and optional settings. @@ -71656,15 +67412,14 @@ function beginRefresh(getAccessToken, retryIntervalInMs, timeoutInMs) { * @returns - a function that reliably produces a valid access token */ function createTokenCycler(credential, scopes, tokenCyclerOptions) { - var _this = this; - var refreshWorker = null; - var token = null; - var options = tslib.__assign(tslib.__assign({}, DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); + let refreshWorker = null; + let token = null; + const options = Object.assign(Object.assign({}, DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); /** * This little holder defines several predicates that we use to construct * the rules of refreshing the token. */ - var cycler = { + const cycler = { /** * Produces true if a refresh job is currently in progress. */ @@ -71696,20 +67451,18 @@ function createTokenCycler(credential, scopes, tokenCyclerOptions) { var _a; if (!cycler.isRefreshing) { // We bind `scopes` here to avoid passing it around a lot - var tryGetAccessToken = function () { - return credential.getToken(scopes, getTokenOptions); - }; + const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); // Take advantage of promise chaining to insert an assignment to `token` // before the refresh can be considered done. refreshWorker = beginRefresh(tryGetAccessToken, options.retryIntervalInMs, // If we don't have a token, then we should timeout immediately (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now()) - .then(function (_token) { + .then((_token) => { refreshWorker = null; token = _token; return token; }) - .catch(function (reason) { + .catch((reason) => { // We also should reset the refresher if we enter a failed state. All // existing awaiters will throw, but subsequent requests will start a // new retry chain. @@ -71720,25 +67473,23 @@ function createTokenCycler(credential, scopes, tokenCyclerOptions) { } return refreshWorker; } - return function (tokenOptions) { return tslib.__awaiter(_this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - // - // Simple rules: - // - If we MUST refresh, then return the refresh task, blocking - // the pipeline until a token is available. - // - If we SHOULD refresh, then run refresh but don't return it - // (we can still use the cached token). - // - Return the token, since it's fine if we didn't return in - // step 1. - // - if (cycler.mustRefresh) - return [2 /*return*/, refresh(tokenOptions)]; - if (cycler.shouldRefresh) { - refresh(tokenOptions); - } - return [2 /*return*/, token]; - }); - }); }; + return async (tokenOptions) => { + // + // Simple rules: + // - If we MUST refresh, then return the refresh task, blocking + // the pipeline until a token is available. + // - If we SHOULD refresh, then run refresh but don't return it + // (we can still use the cached token). + // - Return the token, since it's fine if we didn't return in + // step 1. + // + if (cycler.mustRefresh) + return refresh(tokenOptions); + if (cycler.shouldRefresh) { + refresh(tokenOptions); + } + return token; + }; } // #endregion /** @@ -71750,36 +67501,27 @@ function createTokenCycler(credential, scopes, tokenCyclerOptions) { */ function bearerTokenAuthenticationPolicy(credential, scopes) { // This simple function encapsulates the entire process of reliably retrieving the token - var getToken = createTokenCycler(credential, scopes /* , options */); - var BearerTokenAuthenticationPolicy = /** @class */ (function (_super) { - tslib.__extends(BearerTokenAuthenticationPolicy, _super); - function BearerTokenAuthenticationPolicy(nextPolicy, options) { - return _super.call(this, nextPolicy, options) || this; + const getToken = createTokenCycler(credential, scopes /* , options */); + class BearerTokenAuthenticationPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options) { + super(nextPolicy, options); } - BearerTokenAuthenticationPolicy.prototype.sendRequest = function (webResource) { - return tslib.__awaiter(this, void 0, void 0, function () { - var token; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: return [4 /*yield*/, getToken({ - abortSignal: webResource.abortSignal, - tracingOptions: { - spanOptions: webResource.spanOptions, - tracingContext: webResource.tracingContext - } - })]; - case 1: - token = (_a.sent()).token; - webResource.headers.set(Constants.HeaderConstants.AUTHORIZATION, "Bearer " + token); - return [2 /*return*/, this._nextPolicy.sendRequest(webResource)]; - } - }); + async sendRequest(webResource) { + if (!webResource.url.toLowerCase().startsWith("https://")) { + throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); + } + const { token } = await getToken({ + abortSignal: webResource.abortSignal, + tracingOptions: { + tracingContext: webResource.tracingContext + } }); - }; - return BearerTokenAuthenticationPolicy; - }(BaseRequestPolicy)); + webResource.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${token}`); + return this._nextPolicy.sendRequest(webResource); + } + } return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new BearerTokenAuthenticationPolicy(nextPolicy, options); } }; @@ -71788,7 +67530,7 @@ function bearerTokenAuthenticationPolicy(credential, scopes) { // Copyright (c) Microsoft Corporation. function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval); } }; @@ -71799,69 +67541,55 @@ function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, max * @param minRetryInterval - The minimum retry interval, in milliseconds. * @param maxRetryInterval - The maximum retry interval, in milliseconds. */ -var SystemErrorRetryPolicy = /** @class */ (function (_super) { - tslib.__extends(SystemErrorRetryPolicy, _super); - function SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) { - var _this = _super.call(this, nextPolicy, options) || this; - _this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT; - _this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL; - _this.minRetryInterval = isNumber(minRetryInterval) +class SystemErrorRetryPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) { + super(nextPolicy, options); + this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT; + this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL; + this.minRetryInterval = isNumber(minRetryInterval) ? minRetryInterval : DEFAULT_CLIENT_MIN_RETRY_INTERVAL; - _this.maxRetryInterval = isNumber(maxRetryInterval) + this.maxRetryInterval = isNumber(maxRetryInterval) ? maxRetryInterval : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; - return _this; } - SystemErrorRetryPolicy.prototype.sendRequest = function (request) { - var _this = this; + sendRequest(request) { return this._nextPolicy .sendRequest(request.clone()) - .catch(function (error) { return retry$1(_this, request, error.response, error); }); - }; - return SystemErrorRetryPolicy; -}(BaseRequestPolicy)); -function retry$1(policy, request, operationResponse, err, retryData) { - return tslib.__awaiter(this, void 0, void 0, function () { - function shouldPolicyRetry(_response, error) { - if (error && - error.code && - (error.code === "ETIMEDOUT" || - error.code === "ESOCKETTIMEDOUT" || - error.code === "ECONNREFUSED" || - error.code === "ECONNRESET" || - error.code === "ENOENT")) { - return true; - } - return false; + .catch((error) => retry$1(this, request, error.response, error)); + } +} +async function retry$1(policy, request, operationResponse, err, retryData) { + retryData = updateRetryData(policy, retryData, err); + function shouldPolicyRetry(_response, error) { + if (error && + error.code && + (error.code === "ETIMEDOUT" || + error.code === "ESOCKETTIMEDOUT" || + error.code === "ECONNREFUSED" || + error.code === "ECONNRESET" || + error.code === "ENOENT")) { + return true; } - var nestedErr_1; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - retryData = updateRetryData(policy, retryData, err); - if (!shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, operationResponse, err)) return [3 /*break*/, 5]; - _a.label = 1; - case 1: - _a.trys.push([1, 3, , 4]); - return [4 /*yield*/, delay(retryData.retryInterval)]; - case 2: - _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)]; - case 4: return [3 /*break*/, 6]; - case 5: - if (err) { - // If the operation failed in the end, return all errors instead of just the last one - return [2 /*return*/, Promise.reject(retryData.error)]; - } - return [2 /*return*/, operationResponse]; - case 6: return [2 /*return*/]; - } - }); - }); + return false; + } + if (shouldRetry(policy.retryCount, shouldPolicyRetry, retryData, operationResponse, err)) { + // If previous operation ended with an error and the policy allows a retry, do that + try { + await delay(retryData.retryInterval); + return policy._nextPolicy.sendRequest(request.clone()); + } + catch (nestedErr) { + return retry$1(policy, request, operationResponse, nestedErr, retryData); + } + } + else { + if (err) { + // If the operation failed in the end, return all errors instead of just the last one + return Promise.reject(retryData.error); + } + return operationResponse; + } } // Copyright (c) Microsoft Corporation. @@ -71875,34 +67603,37 @@ function retry$1(policy, request, operationResponse, err, retryData) { // Copyright (c) Microsoft Corporation. /** + * Stores the patterns specified in NO_PROXY environment variable. * @internal */ -var noProxyList = []; -var noProxyListLoaded = false; -var byPassedList = new Map(); +const globalNoProxyList = []; +let noProxyListLoaded = false; +/** A cache of whether a host should bypass the proxy. */ +const globalBypassedMap = new Map(); function loadEnvironmentProxyValue() { if (!process) { return undefined; } - var httpsProxy = getEnvironmentValue(Constants.HTTPS_PROXY); - var allProxy = getEnvironmentValue(Constants.ALL_PROXY); - var httpProxy = getEnvironmentValue(Constants.HTTP_PROXY); + const httpsProxy = getEnvironmentValue(Constants.HTTPS_PROXY); + const allProxy = getEnvironmentValue(Constants.ALL_PROXY); + const 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 -function isBypassed(uri) { +/** + * Check whether the host of a given `uri` matches any pattern in the no proxy list. + * If there's a match, any request sent to the same host shouldn'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 + */ +function isBypassed(uri, noProxyList, bypassedMap) { if (noProxyList.length === 0) { return false; } - var host = URLBuilder.parse(uri).getHost(); - if (byPassedList.has(host)) { - return byPassedList.get(host); + const host = URLBuilder.parse(uri).getHost(); + if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { + return bypassedMap.get(host); } - var isBypassedFlag = false; - for (var _i = 0, noProxyList_1 = noProxyList; _i < noProxyList_1.length; _i++) { - var pattern = noProxyList_1[_i]; + let isBypassedFlag = false; + for (const pattern of noProxyList) { 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 @@ -71921,20 +67652,20 @@ function isBypassed(uri) { } } } - byPassedList.set(host, isBypassedFlag); + bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); return isBypassedFlag; } /** * @internal */ function loadNoProxy() { - var noProxy = getEnvironmentValue(Constants.NO_PROXY); + const noProxy = getEnvironmentValue(Constants.NO_PROXY); noProxyListLoaded = true; if (noProxy) { return noProxy .split(",") - .map(function (item) { return item.trim(); }) - .filter(function (item) { return item.length; }); + .map((item) => item.trim()) + .filter((item) => item.length); } return []; } @@ -71945,174 +67676,184 @@ function getDefaultProxySettings(proxyUrl) { return undefined; } } - var _a = extractAuthFromUrl(proxyUrl), username = _a.username, password = _a.password, urlWithoutAuth = _a.urlWithoutAuth; - var parsedUrl = URLBuilder.parse(urlWithoutAuth); - var schema = parsedUrl.getScheme() ? parsedUrl.getScheme() + "://" : ""; + const { username, password, urlWithoutAuth } = extractAuthFromUrl(proxyUrl); + const parsedUrl = URLBuilder.parse(urlWithoutAuth); + const schema = parsedUrl.getScheme() ? parsedUrl.getScheme() + "://" : ""; return { host: schema + parsedUrl.getHost(), port: Number.parseInt(parsedUrl.getPort() || "80"), - username: username, - password: password + username, + password }; } -function proxyPolicy(proxySettings) { +/** + * A policy that allows one to apply proxy settings to all requests. + * If not passed static settings, they will be retrieved from the HTTPS_PROXY + * or HTTP_PROXY environment variables. + * @param proxySettings - ProxySettings to use on each request. + * @param options - additional settings, for example, custom NO_PROXY patterns + */ +function proxyPolicy(proxySettings, options) { if (!proxySettings) { proxySettings = getDefaultProxySettings(); } if (!noProxyListLoaded) { - noProxyList.push.apply(noProxyList, loadNoProxy()); + globalNoProxyList.push(...loadNoProxy()); } return { - create: function (nextPolicy, options) { - return new ProxyPolicy(nextPolicy, options, proxySettings); + create: (nextPolicy, requestPolicyOptions) => { + return new ProxyPolicy(nextPolicy, requestPolicyOptions, proxySettings, options === null || options === void 0 ? void 0 : options.customNoProxyList); } }; } function extractAuthFromUrl(url) { - var atIndex = url.indexOf("@"); + const atIndex = url.indexOf("@"); if (atIndex === -1) { return { urlWithoutAuth: url }; } - var schemeIndex = url.indexOf("://"); - var authStart = schemeIndex !== -1 ? schemeIndex + 3 : 0; - var auth = url.substring(authStart, atIndex); - var colonIndex = auth.indexOf(":"); - var hasPassword = colonIndex !== -1; - var username = hasPassword ? auth.substring(0, colonIndex) : auth; - var password = hasPassword ? auth.substring(colonIndex + 1) : undefined; - var urlWithoutAuth = url.substring(0, authStart) + url.substring(atIndex + 1); + const schemeIndex = url.indexOf("://"); + const authStart = schemeIndex !== -1 ? schemeIndex + 3 : 0; + const auth = url.substring(authStart, atIndex); + const colonIndex = auth.indexOf(":"); + const hasPassword = colonIndex !== -1; + const username = hasPassword ? auth.substring(0, colonIndex) : auth; + const password = hasPassword ? auth.substring(colonIndex + 1) : undefined; + const urlWithoutAuth = url.substring(0, authStart) + url.substring(atIndex + 1); return { - username: username, - password: password, - urlWithoutAuth: urlWithoutAuth + username, + password, + urlWithoutAuth }; } -var ProxyPolicy = /** @class */ (function (_super) { - tslib.__extends(ProxyPolicy, _super); - function ProxyPolicy(nextPolicy, options, proxySettings) { - var _this = _super.call(this, nextPolicy, options) || this; - _this.proxySettings = proxySettings; - return _this; +class ProxyPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, proxySettings, customNoProxyList) { + super(nextPolicy, options); + this.proxySettings = proxySettings; + this.customNoProxyList = customNoProxyList; } - ProxyPolicy.prototype.sendRequest = function (request) { - if (!request.proxySettings && !isBypassed(request.url)) { + sendRequest(request) { + var _a; + if (!request.proxySettings && + !isBypassed(request.url, (_a = this.customNoProxyList) !== null && _a !== void 0 ? _a : globalNoProxyList, this.customNoProxyList ? undefined : globalBypassedMap)) { request.proxySettings = this.proxySettings; } return this._nextPolicy.sendRequest(request); - }; - return ProxyPolicy; -}(BaseRequestPolicy)); + } +} // Copyright (c) Microsoft Corporation. -var StatusCodes = Constants.HttpConstants.StatusCodes; +// Licensed under the MIT license. +/** + * Maximum number of retries for the throttling retry policy + */ +const DEFAULT_CLIENT_MAX_RETRY_COUNT = 3; + +// Copyright (c) Microsoft Corporation. +const StatusCodes = Constants.HttpConstants.StatusCodes; function throttlingRetryPolicy() { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new ThrottlingRetryPolicy(nextPolicy, options); } }; } +const StandardAbortMessage$1 = "The operation was aborted."; /** * To learn more, please refer to * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits, * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors */ -var ThrottlingRetryPolicy = /** @class */ (function (_super) { - tslib.__extends(ThrottlingRetryPolicy, _super); - function ThrottlingRetryPolicy(nextPolicy, options, _handleResponse) { - var _this = _super.call(this, nextPolicy, options) || this; - _this._handleResponse = _handleResponse || _this._defaultResponseHandler; - return _this; +class ThrottlingRetryPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, _handleResponse) { + super(nextPolicy, options); + this.numberOfRetries = 0; + this._handleResponse = _handleResponse || this._defaultResponseHandler; } - ThrottlingRetryPolicy.prototype.sendRequest = function (httpRequest) { - return tslib.__awaiter(this, void 0, void 0, function () { - var _this = this; - return tslib.__generator(this, function (_a) { - return [2 /*return*/, this._nextPolicy.sendRequest(httpRequest.clone()).then(function (response) { - if (response.status !== StatusCodes.TooManyRequests) { - return response; - } - else { - return _this._handleResponse(httpRequest, response); - } - })]; - }); - }); - }; - ThrottlingRetryPolicy.prototype._defaultResponseHandler = function (httpRequest, httpResponse) { - return tslib.__awaiter(this, void 0, void 0, function () { - var retryAfterHeader, delayInMs; - var _this = this; - return tslib.__generator(this, function (_a) { - retryAfterHeader = httpResponse.headers.get(Constants.HeaderConstants.RETRY_AFTER); - if (retryAfterHeader) { - delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader); - if (delayInMs) { - return [2 /*return*/, delay(delayInMs).then(function (_) { return _this._nextPolicy.sendRequest(httpRequest); })]; - } + async sendRequest(httpRequest) { + const response = await this._nextPolicy.sendRequest(httpRequest.clone()); + if (response.status !== StatusCodes.TooManyRequests && + response.status !== StatusCodes.ServiceUnavailable) { + return response; + } + else { + return this._handleResponse(httpRequest, response); + } + } + async _defaultResponseHandler(httpRequest, httpResponse) { + var _a; + const retryAfterHeader = httpResponse.headers.get(Constants.HeaderConstants.RETRY_AFTER); + if (retryAfterHeader) { + const delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader); + if (delayInMs) { + this.numberOfRetries += 1; + await delay(delayInMs, undefined, { + abortSignal: httpRequest.abortSignal, + abortErrorMsg: StandardAbortMessage$1 + }); + if ((_a = httpRequest.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { + throw new abortController.AbortError(StandardAbortMessage$1); } - return [2 /*return*/, httpResponse]; - }); - }); - }; - ThrottlingRetryPolicy.parseRetryAfterHeader = function (headerValue) { - var retryAfterInSeconds = Number(headerValue); + if (this.numberOfRetries < DEFAULT_CLIENT_MAX_RETRY_COUNT) { + return this.sendRequest(httpRequest); + } + else { + return this._nextPolicy.sendRequest(httpRequest); + } + } + } + return httpResponse; + } + static parseRetryAfterHeader(headerValue) { + const retryAfterInSeconds = Number(headerValue); if (Number.isNaN(retryAfterInSeconds)) { return ThrottlingRetryPolicy.parseDateRetryAfterHeader(headerValue); } else { return retryAfterInSeconds * 1000; } - }; - ThrottlingRetryPolicy.parseDateRetryAfterHeader = function (headerValue) { + } + static parseDateRetryAfterHeader(headerValue) { try { - var now = Date.now(); - var date = Date.parse(headerValue); - var diff = date - now; + const now = Date.now(); + const date = Date.parse(headerValue); + const diff = date - now; return Number.isNaN(diff) ? undefined : diff; } catch (error) { return undefined; } - }; - return ThrottlingRetryPolicy; -}(BaseRequestPolicy)); + } +} // Copyright (c) Microsoft Corporation. function signingPolicy(authenticationProvider) { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new SigningPolicy(nextPolicy, options, authenticationProvider); } }; } -var SigningPolicy = /** @class */ (function (_super) { - tslib.__extends(SigningPolicy, _super); - function SigningPolicy(nextPolicy, options, authenticationProvider) { - var _this = _super.call(this, nextPolicy, options) || this; - _this.authenticationProvider = authenticationProvider; - return _this; +class SigningPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, authenticationProvider) { + super(nextPolicy, options); + this.authenticationProvider = authenticationProvider; } - SigningPolicy.prototype.signRequest = function (request) { + signRequest(request) { return this.authenticationProvider.signRequest(request); - }; - SigningPolicy.prototype.sendRequest = function (request) { - var _this = this; - return this.signRequest(request).then(function (nextRequest) { - return _this._nextPolicy.sendRequest(nextRequest); - }); - }; - return SigningPolicy; -}(BaseRequestPolicy)); + } + sendRequest(request) { + return this.signRequest(request).then((nextRequest) => this._nextPolicy.sendRequest(nextRequest)); + } +} // Copyright (c) Microsoft Corporation. -var DefaultKeepAliveOptions = { +const DefaultKeepAliveOptions = { enable: true }; function keepAlivePolicy(keepAliveOptions) { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new KeepAlivePolicy(nextPolicy, options, keepAliveOptions || DefaultKeepAliveOptions); } }; @@ -72120,8 +67861,7 @@ function keepAlivePolicy(keepAliveOptions) { /** * KeepAlivePolicy is a policy used to control keep alive settings for every request. */ -var KeepAlivePolicy = /** @class */ (function (_super) { - tslib.__extends(KeepAlivePolicy, _super); +class KeepAlivePolicy extends BaseRequestPolicy { /** * Creates an instance of KeepAlivePolicy. * @@ -72129,10 +67869,9 @@ var KeepAlivePolicy = /** @class */ (function (_super) { * @param options - * @param keepAliveOptions - */ - function KeepAlivePolicy(nextPolicy, options, keepAliveOptions) { - var _this = _super.call(this, nextPolicy, options) || this; - _this.keepAliveOptions = keepAliveOptions; - return _this; + constructor(nextPolicy, options, keepAliveOptions) { + super(nextPolicy, options); + this.keepAliveOptions = keepAliveOptions; } /** * Sends out request. @@ -72140,104 +67879,126 @@ var KeepAlivePolicy = /** @class */ (function (_super) { * @param request - * @returns */ - KeepAlivePolicy.prototype.sendRequest = function (request) { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - request.keepAlive = this.keepAliveOptions.enable; - return [2 /*return*/, this._nextPolicy.sendRequest(request)]; - }); - }); - }; - return KeepAlivePolicy; -}(BaseRequestPolicy)); + async sendRequest(request) { + request.keepAlive = this.keepAliveOptions.enable; + return this._nextPolicy.sendRequest(request); + } +} // Copyright (c) Microsoft Corporation. -var createSpan = coreTracing.createSpanFunction({ +const createSpan = coreTracing.createSpanFunction({ packagePrefix: "", namespace: "" }); -function tracingPolicy(tracingOptions) { - if (tracingOptions === void 0) { tracingOptions = {}; } +function tracingPolicy(tracingOptions = {}) { return { - create: function (nextPolicy, options) { + create(nextPolicy, options) { return new TracingPolicy(nextPolicy, options, tracingOptions); } }; } -var TracingPolicy = /** @class */ (function (_super) { - tslib.__extends(TracingPolicy, _super); - function TracingPolicy(nextPolicy, options, tracingOptions) { - var _this = _super.call(this, nextPolicy, options) || this; - _this.userAgent = tracingOptions.userAgent; - return _this; +class TracingPolicy extends BaseRequestPolicy { + constructor(nextPolicy, options, tracingOptions) { + super(nextPolicy, options); + this.userAgent = tracingOptions.userAgent; } - TracingPolicy.prototype.sendRequest = function (request) { - return tslib.__awaiter(this, void 0, void 0, function () { - var path, span, spanContext, traceParentHeader, traceState, response, serviceRequestId, err_1; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!request.tracingContext) { - return [2 /*return*/, this._nextPolicy.sendRequest(request)]; - } - path = URLBuilder.parse(request.url).getPath() || "/"; - span = createSpan(path, { - tracingOptions: { - spanOptions: tslib.__assign(tslib.__assign({}, request.spanOptions), { kind: coreTracing.SpanKind.CLIENT }), - tracingContext: request.tracingContext - } - }).span; - span.setAttributes({ - "http.method": request.method, - "http.url": request.url, - requestId: request.requestId - }); - if (this.userAgent) { - span.setAttribute("http.user_agent", this.userAgent); - } - _a.label = 1; - case 1: - _a.trys.push([1, 3, 4, 5]); - spanContext = span.context(); - traceParentHeader = coreTracing.getTraceParentHeader(spanContext); - if (traceParentHeader) { - request.headers.set("traceparent", traceParentHeader); - traceState = spanContext.traceState && spanContext.traceState.serialize(); - // if tracestate is set, traceparent MUST be set, so only set tracestate after traceparent - if (traceState) { - request.headers.set("tracestate", traceState); - } - } - return [4 /*yield*/, this._nextPolicy.sendRequest(request)]; - case 2: - response = _a.sent(); - span.setAttribute("http.status_code", response.status); - serviceRequestId = response.headers.get("x-ms-request-id"); - if (serviceRequestId) { - span.setAttribute("serviceRequestId", serviceRequestId); - } - span.setStatus({ - code: coreTracing.SpanStatusCode.OK - }); - return [2 /*return*/, response]; - case 3: - err_1 = _a.sent(); - span.setStatus({ - code: coreTracing.SpanStatusCode.ERROR, - message: err_1.message - }); - span.setAttribute("http.status_code", err_1.statusCode); - throw err_1; - case 4: - span.end(); - return [7 /*endfinally*/]; - case 5: return [2 /*return*/]; + async sendRequest(request) { + if (!request.tracingContext) { + return this._nextPolicy.sendRequest(request); + } + const span = this.tryCreateSpan(request); + if (!span) { + return this._nextPolicy.sendRequest(request); + } + try { + const response = await this._nextPolicy.sendRequest(request); + this.tryProcessResponse(span, response); + return response; + } + catch (err) { + this.tryProcessError(span, err); + throw err; + } + } + tryCreateSpan(request) { + var _a; + try { + const path = URLBuilder.parse(request.url).getPath() || "/"; + // Passing spanOptions as part of tracingOptions to maintain compatibility @azure/core-tracing@preview.13 and earlier. + // We can pass this as a separate parameter once we upgrade to the latest core-tracing. + const { span } = createSpan(path, { + tracingOptions: { + spanOptions: Object.assign(Object.assign({}, request.spanOptions), { kind: coreTracing.SpanKind.CLIENT }), + tracingContext: request.tracingContext } }); - }); - }; - return TracingPolicy; -}(BaseRequestPolicy)); + // If the span is not recording, don't do any more work. + if (!span.isRecording()) { + span.end(); + return undefined; + } + const namespaceFromContext = (_a = request.tracingContext) === null || _a === void 0 ? void 0 : _a.getValue(Symbol.for("az.namespace")); + if (typeof namespaceFromContext === "string") { + span.setAttribute("az.namespace", namespaceFromContext); + } + span.setAttributes({ + "http.method": request.method, + "http.url": request.url, + requestId: request.requestId + }); + if (this.userAgent) { + span.setAttribute("http.user_agent", this.userAgent); + } + // set headers + const spanContext = span.spanContext(); + const traceParentHeader = coreTracing.getTraceParentHeader(spanContext); + if (traceParentHeader && coreTracing.isSpanContextValid(spanContext)) { + request.headers.set("traceparent", traceParentHeader); + const traceState = spanContext.traceState && spanContext.traceState.serialize(); + // if tracestate is set, traceparent MUST be set, so only set tracestate after traceparent + if (traceState) { + request.headers.set("tracestate", traceState); + } + } + return span; + } + catch (error) { + logger.warning(`Skipping creating a tracing span due to an error: ${error.message}`); + return undefined; + } + } + tryProcessError(span, err) { + try { + span.setStatus({ + code: coreTracing.SpanStatusCode.ERROR, + message: err.message + }); + if (err.statusCode) { + span.setAttribute("http.status_code", err.statusCode); + } + span.end(); + } + catch (error) { + logger.warning(`Skipping tracing span processing due to an error: ${error.message}`); + } + } + tryProcessResponse(span, response) { + try { + span.setAttribute("http.status_code", response.status); + const serviceRequestId = response.headers.get("x-ms-request-id"); + if (serviceRequestId) { + span.setAttribute("serviceRequestId", serviceRequestId); + } + span.setStatus({ + code: coreTracing.SpanStatusCode.OK + }); + span.end(); + } + catch (error) { + logger.warning(`Skipping tracing span processing due to an error: ${error.message}`); + } + } +} // Copyright (c) Microsoft Corporation. /** @@ -72246,7 +68007,7 @@ var TracingPolicy = /** @class */ (function (_super) { */ function disableResponseDecompressionPolicy() { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new DisableResponseDecompressionPolicy(nextPolicy, options); } }; @@ -72255,8 +68016,7 @@ function disableResponseDecompressionPolicy() { * A policy to disable response decompression according to Accept-Encoding header * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding */ -var DisableResponseDecompressionPolicy = /** @class */ (function (_super) { - tslib.__extends(DisableResponseDecompressionPolicy, _super); +class DisableResponseDecompressionPolicy extends BaseRequestPolicy { /** * Creates an instance of DisableResponseDecompressionPolicy. * @@ -72265,8 +68025,8 @@ var DisableResponseDecompressionPolicy = /** @class */ (function (_super) { */ // The parent constructor is protected. /* eslint-disable-next-line @typescript-eslint/no-useless-constructor */ - function DisableResponseDecompressionPolicy(nextPolicy, options) { - return _super.call(this, nextPolicy, options) || this; + constructor(nextPolicy, options) { + super(nextPolicy, options); } /** * Sends out request. @@ -72274,21 +68034,16 @@ var DisableResponseDecompressionPolicy = /** @class */ (function (_super) { * @param request - * @returns */ - DisableResponseDecompressionPolicy.prototype.sendRequest = function (request) { - return tslib.__awaiter(this, void 0, void 0, function () { - return tslib.__generator(this, function (_a) { - request.decompressResponse = false; - return [2 /*return*/, this._nextPolicy.sendRequest(request)]; - }); - }); - }; - return DisableResponseDecompressionPolicy; -}(BaseRequestPolicy)); + async sendRequest(request) { + request.decompressResponse = false; + return this._nextPolicy.sendRequest(request); + } +} // Copyright (c) Microsoft Corporation. function ndJsonPolicy() { return { - create: function (nextPolicy, options) { + create: (nextPolicy, options) => { return new NdJsonPolicy(nextPolicy, options); } }; @@ -72296,37 +68051,30 @@ function ndJsonPolicy() { /** * NdJsonPolicy that formats a JSON array as newline-delimited JSON */ -var NdJsonPolicy = /** @class */ (function (_super) { - tslib.__extends(NdJsonPolicy, _super); +class NdJsonPolicy extends BaseRequestPolicy { /** * Creates an instance of KeepAlivePolicy. */ - function NdJsonPolicy(nextPolicy, options) { - return _super.call(this, nextPolicy, options) || this; + constructor(nextPolicy, options) { + super(nextPolicy, options); } /** * Sends a request. */ - NdJsonPolicy.prototype.sendRequest = function (request) { - return tslib.__awaiter(this, void 0, void 0, function () { - var body; - return tslib.__generator(this, function (_a) { - // There currently isn't a good way to bypass the serializer - if (typeof request.body === "string" && request.body.startsWith("[")) { - body = JSON.parse(request.body); - if (Array.isArray(body)) { - request.body = body.map(function (item) { return JSON.stringify(item) + "\n"; }).join(""); - } - } - return [2 /*return*/, this._nextPolicy.sendRequest(request)]; - }); - }); - }; - return NdJsonPolicy; -}(BaseRequestPolicy)); + async sendRequest(request) { + // There currently isn't a good way to bypass the serializer + if (typeof request.body === "string" && request.body.startsWith("[")) { + const body = JSON.parse(request.body); + if (Array.isArray(body)) { + request.body = body.map((item) => JSON.stringify(item) + "\n").join(""); + } + } + return this._nextPolicy.sendRequest(request); + } +} // Copyright (c) Microsoft Corporation. -var cachedHttpClient; +let cachedHttpClient; function getCachedDefaultHttpClient() { if (!cachedHttpClient) { cachedHttpClient = new NodeFetchHttpClient(); @@ -72338,29 +68086,28 @@ function getCachedDefaultHttpClient() { /** * ServiceClient sends service requests and receives responses. */ -var ServiceClient = /** @class */ (function () { +class ServiceClient { /** * 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. */ - function ServiceClient(credentials, + constructor(credentials, /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options */ options) { - var _this = this; if (!options) { options = {}; } this._withCredentials = options.withCredentials || false; this._httpClient = options.httpClient || getCachedDefaultHttpClient(); this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger); - var requestPolicyFactories; + let requestPolicyFactories; if (Array.isArray(options.requestPolicyFactories)) { logger.info("ServiceClient: using custom request policies"); requestPolicyFactories = options.requestPolicyFactories; } else { - var authPolicyFactory = undefined; + let authPolicyFactory = undefined; if (coreAuth.isTokenCredential(credentials)) { logger.info("ServiceClient: creating bearer token authentication policy from provided credentials"); // Create a wrapped RequestPolicyFactory here so that we can provide the @@ -72369,16 +68116,16 @@ var ServiceClient = /** @class */ (function () { // implementations do not set baseUri until after ServiceClient's constructor // is finished, leaving baseUri empty at the time when it is needed to // build the correct scope name. - var wrappedPolicyFactory = function () { - var bearerTokenPolicyFactory = undefined; + const wrappedPolicyFactory = () => { + let bearerTokenPolicyFactory = undefined; // eslint-disable-next-line @typescript-eslint/no-this-alias - var serviceClient = _this; - var serviceClientOptions = options; + const serviceClient = this; + const serviceClientOptions = options; return { - create: function (nextPolicy, createOptions) { - var credentialScopes = getCredentialScopes(serviceClientOptions, serviceClient.baseUri); + create(nextPolicy, createOptions) { + const 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"); + throw new Error(`When using credential, the ServiceClient must contain a baseUri or a credentialScopes in ServiceClientOptions. Unable to create a bearerTokenAuthenticationPolicy`); } if (bearerTokenPolicyFactory === undefined || bearerTokenPolicyFactory === null) { bearerTokenPolicyFactory = bearerTokenAuthenticationPolicy(credentials, credentialScopes); @@ -72401,7 +68148,7 @@ var ServiceClient = /** @class */ (function () { if (options.requestPolicyFactories) { // options.requestPolicyFactories can also be a function that manipulates // the default requestPolicyFactories array - var newRequestPolicyFactories = options.requestPolicyFactories(requestPolicyFactories); + const newRequestPolicyFactories = options.requestPolicyFactories(requestPolicyFactories); if (newRequestPolicyFactories) { requestPolicyFactories = newRequestPolicyFactories; } @@ -72412,11 +68159,11 @@ var ServiceClient = /** @class */ (function () { /** * Send the provided httpRequest. */ - ServiceClient.prototype.sendRequest = function (options) { + sendRequest(options) { if (options === null || options === undefined || typeof options !== "object") { throw new Error("options cannot be null or undefined and it must be of type object."); } - var httpRequest; + let httpRequest; try { if (isWebResourceLike(options)) { options.validateRequestProperties(); @@ -72430,242 +68177,221 @@ var ServiceClient = /** @class */ (function () { catch (error) { return Promise.reject(error); } - var httpPipeline = this._httpClient; + let httpPipeline = this._httpClient; if (this._requestPolicyFactories && this._requestPolicyFactories.length > 0) { - for (var i = this._requestPolicyFactories.length - 1; i >= 0; --i) { + for (let i = this._requestPolicyFactories.length - 1; i >= 0; --i) { httpPipeline = this._requestPolicyFactories[i].create(httpPipeline, this._requestPolicyOptions); } } return httpPipeline.sendRequest(httpRequest); - }; + } /** * 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. */ - ServiceClient.prototype.sendOperationRequest = function (operationArguments, operationSpec, callback) { + async sendOperationRequest(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) { - 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; - case 1: - _j.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."); - } - httpRequest.method = operationSpec.httpMethod; - httpRequest.operationSpec = operationSpec; - requestUrl = URLBuilder.parse(baseUri); - if (operationSpec.path) { - requestUrl.appendPath(operationSpec.path); - } - if (operationSpec.urlParameters && operationSpec.urlParameters.length > 0) { - for (_i = 0, _b = operationSpec.urlParameters; _i < _b.length; _i++) { - urlParameter = _b[_i]; - urlParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, urlParameter, operationSpec.serializer); - urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, getPathStringFromParameter(urlParameter), serializerOptions); - if (!urlParameter.skipEncoding) { - urlParameterValue = encodeURIComponent(urlParameterValue); + if (typeof operationArguments.options === "function") { + callback = operationArguments.options; + operationArguments.options = undefined; + } + const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; + const httpRequest = new WebResource(); + let result; + try { + const 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."); + } + httpRequest.method = operationSpec.httpMethod; + httpRequest.operationSpec = operationSpec; + const requestUrl = URLBuilder.parse(baseUri); + if (operationSpec.path) { + requestUrl.appendPath(operationSpec.path); + } + if (operationSpec.urlParameters && operationSpec.urlParameters.length > 0) { + for (const urlParameter of operationSpec.urlParameters) { + let urlParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, urlParameter, operationSpec.serializer); + urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, getPathStringFromParameter(urlParameter), serializerOptions); + if (!urlParameter.skipEncoding) { + urlParameterValue = encodeURIComponent(urlParameterValue); + } + requestUrl.replaceAll(`{${urlParameter.mapper.serializedName || getPathStringFromParameter(urlParameter)}}`, urlParameterValue); + } + } + if (operationSpec.queryParameters && operationSpec.queryParameters.length > 0) { + for (const queryParameter of operationSpec.queryParameters) { + let queryParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, queryParameter, operationSpec.serializer); + if (queryParameterValue !== undefined && queryParameterValue !== null) { + queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter), serializerOptions); + 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; } - requestUrl.replaceAll("{" + (urlParameter.mapper.serializedName || getPathStringFromParameter(urlParameter)) + "}", urlParameterValue); - } - } - if (operationSpec.queryParameters && operationSpec.queryParameters.length > 0) { - for (_c = 0, _d = operationSpec.queryParameters; _c < _d.length; _c++) { - queryParameter = _d[_c]; - queryParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, queryParameter, operationSpec.serializer); - if (queryParameterValue !== undefined && queryParameterValue !== null) { - queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter), serializerOptions); - 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; - } - else { - for (index in queryParameterValue) { - item = queryParameterValue[index]; - queryParameterValue[index] = - item === undefined || item === null ? "" : item.toString(); - } - } - } - else if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Ssv || - queryParameter.collectionFormat === exports.QueryCollectionFormat.Tsv) { - queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat); - } - } - if (!queryParameter.skipEncoding) { - if (Array.isArray(queryParameterValue)) { - for (index in queryParameterValue) { - if (queryParameterValue[index] !== undefined && - queryParameterValue[index] !== null) { - queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]); - } - } - } - else { - queryParameterValue = encodeURIComponent(queryParameterValue); - } - } - if (queryParameter.collectionFormat !== undefined && - queryParameter.collectionFormat !== null && - queryParameter.collectionFormat !== exports.QueryCollectionFormat.Multi && - queryParameter.collectionFormat !== exports.QueryCollectionFormat.Ssv && - queryParameter.collectionFormat !== exports.QueryCollectionFormat.Tsv) { - queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat); - } - requestUrl.setQueryParameter(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue); - } - } - } - httpRequest.url = requestUrl.toString(); - contentType = operationSpec.contentType || this.requestContentType; - if (contentType && operationSpec.requestBody) { - httpRequest.headers.set("Content-Type", contentType); - } - if (operationSpec.headerParameters) { - for (_e = 0, _f = operationSpec.headerParameters; _e < _f.length; _e++) { - headerParameter = _f[_e]; - headerValue = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer); - if (headerValue !== undefined && headerValue !== null) { - headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter), serializerOptions); - headerCollectionPrefix = headerParameter.mapper - .headerCollectionPrefix; - if (headerCollectionPrefix) { - for (_g = 0, _h = Object.keys(headerValue); _g < _h.length; _g++) { - key = _h[_g]; - httpRequest.headers.set(headerCollectionPrefix + key, headerValue[key]); - } - } - else { - httpRequest.headers.set(headerParameter.mapper.serializedName || - getPathStringFromParameter(headerParameter), headerValue); + else { + for (const index in queryParameterValue) { + const item = queryParameterValue[index]; + queryParameterValue[index] = + item === undefined || item === null ? "" : item.toString(); } } } + else if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Ssv || + queryParameter.collectionFormat === exports.QueryCollectionFormat.Tsv) { + queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat); + } } - options = operationArguments.options; - if (options) { - if (options.customHeaders) { - for (customHeaderName in options.customHeaders) { - httpRequest.headers.set(customHeaderName, options.customHeaders[customHeaderName]); + if (!queryParameter.skipEncoding) { + if (Array.isArray(queryParameterValue)) { + for (const index in queryParameterValue) { + if (queryParameterValue[index] !== undefined && + queryParameterValue[index] !== null) { + queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]); + } } } - if (options.abortSignal) { - httpRequest.abortSignal = options.abortSignal; - } - if (options.timeout) { - httpRequest.timeout = options.timeout; - } - if (options.onUploadProgress) { - httpRequest.onUploadProgress = options.onUploadProgress; - } - if (options.onDownloadProgress) { - httpRequest.onDownloadProgress = options.onDownloadProgress; - } - if (options.spanOptions) { - httpRequest.spanOptions = options.spanOptions; - } - if (options.tracingContext) { - httpRequest.tracingContext = options.tracingContext; - } - if (options.shouldDeserialize !== undefined && options.shouldDeserialize !== null) { - httpRequest.shouldDeserialize = options.shouldDeserialize; + else { + queryParameterValue = encodeURIComponent(queryParameterValue); } } - httpRequest.withCredentials = this._withCredentials; - serializeRequestBody(this, httpRequest, operationArguments, operationSpec); - if (httpRequest.streamResponseStatusCodes === undefined) { - httpRequest.streamResponseStatusCodes = getStreamResponseStatusCodes(operationSpec); + if (queryParameter.collectionFormat !== undefined && + queryParameter.collectionFormat !== null && + queryParameter.collectionFormat !== exports.QueryCollectionFormat.Multi && + queryParameter.collectionFormat !== exports.QueryCollectionFormat.Ssv && + queryParameter.collectionFormat !== exports.QueryCollectionFormat.Tsv) { + queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat); } - rawResponse = void 0; - sendRequestError = void 0; - _j.label = 2; - case 2: - _j.trys.push([2, 4, , 5]); - return [4 /*yield*/, this.sendRequest(httpRequest)]; - case 3: - rawResponse = _j.sent(); - return [3 /*break*/, 5]; - case 4: - error_1 = _j.sent(); - sendRequestError = error_1; - return [3 /*break*/, 5]; - case 5: - if (sendRequestError) { - if (sendRequestError.response) { - sendRequestError.details = flattenResponse(sendRequestError.response, operationSpec.responses[sendRequestError.statusCode] || - operationSpec.responses["default"]); + requestUrl.setQueryParameter(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue); + } + } + } + httpRequest.url = requestUrl.toString(); + const contentType = operationSpec.contentType || this.requestContentType; + if (contentType && operationSpec.requestBody) { + httpRequest.headers.set("Content-Type", contentType); + } + if (operationSpec.headerParameters) { + for (const headerParameter of operationSpec.headerParameters) { + let headerValue = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer); + if (headerValue !== undefined && headerValue !== null) { + headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter), serializerOptions); + const headerCollectionPrefix = headerParameter.mapper + .headerCollectionPrefix; + if (headerCollectionPrefix) { + for (const key of Object.keys(headerValue)) { + httpRequest.headers.set(headerCollectionPrefix + key, headerValue[key]); } - result = Promise.reject(sendRequestError); } else { - result = Promise.resolve(flattenResponse(rawResponse, operationSpec.responses[rawResponse.status])); + httpRequest.headers.set(headerParameter.mapper.serializedName || + getPathStringFromParameter(headerParameter), headerValue); } - return [3 /*break*/, 7]; - case 6: - error_2 = _j.sent(); - result = Promise.reject(error_2); - return [3 /*break*/, 7]; - case 7: - cb = callback; - if (cb) { - result - .then(function (res) { return cb(null, res._response.parsedBody, res._response.request, res._response); }) - .catch(function (err) { return cb(err); }); - } - return [2 /*return*/, result]; + } } - }); - }); - }; - return ServiceClient; -}()); + } + const options = operationArguments.options; + if (options) { + if (options.customHeaders) { + for (const customHeaderName in options.customHeaders) { + httpRequest.headers.set(customHeaderName, options.customHeaders[customHeaderName]); + } + } + if (options.abortSignal) { + httpRequest.abortSignal = options.abortSignal; + } + if (options.timeout) { + httpRequest.timeout = options.timeout; + } + if (options.onUploadProgress) { + httpRequest.onUploadProgress = options.onUploadProgress; + } + if (options.onDownloadProgress) { + httpRequest.onDownloadProgress = options.onDownloadProgress; + } + if (options.spanOptions) { + // By passing spanOptions if they exist at runtime, we're backwards compatible with @azure/core-tracing@preview.13 and earlier. + httpRequest.spanOptions = options.spanOptions; + } + if (options.tracingContext) { + httpRequest.tracingContext = options.tracingContext; + } + if (options.shouldDeserialize !== undefined && options.shouldDeserialize !== null) { + httpRequest.shouldDeserialize = options.shouldDeserialize; + } + } + httpRequest.withCredentials = this._withCredentials; + serializeRequestBody(this, httpRequest, operationArguments, operationSpec); + if (httpRequest.streamResponseStatusCodes === undefined) { + httpRequest.streamResponseStatusCodes = getStreamResponseStatusCodes(operationSpec); + } + let rawResponse; + let sendRequestError; + try { + rawResponse = await this.sendRequest(httpRequest); + } + catch (error) { + sendRequestError = error; + } + if (sendRequestError) { + if (sendRequestError.response) { + sendRequestError.details = flattenResponse(sendRequestError.response, operationSpec.responses[sendRequestError.statusCode] || + operationSpec.responses["default"]); + } + result = Promise.reject(sendRequestError); + } + else { + result = Promise.resolve(flattenResponse(rawResponse, operationSpec.responses[rawResponse.status])); + } + } + catch (error) { + result = Promise.reject(error); + } + const cb = callback; + if (cb) { + result + .then((res) => cb(null, res._response.parsedBody, res._response.request, res._response)) + .catch((err) => cb(err)); + } + return result; + } +} 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 = { + const serializerOptions = (_b = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions) !== null && _b !== void 0 ? _b : {}; + const 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; + const xmlCharKey = serializerOptions.xmlCharKey; if (operationSpec.requestBody && operationSpec.requestBody.mapper) { httpRequest.body = getOperationArgumentValueFromParameter(serviceClient, operationArguments, operationSpec.requestBody, operationSpec.serializer); - var bodyMapper = operationSpec.requestBody.mapper; - var required = bodyMapper.required, xmlName = bodyMapper.xmlName, xmlElementName = bodyMapper.xmlElementName, serializedName = bodyMapper.serializedName, xmlNamespace = bodyMapper.xmlNamespace, xmlNamespacePrefix = bodyMapper.xmlNamespacePrefix; - var typeName = bodyMapper.type.name; + const bodyMapper = operationSpec.requestBody.mapper; + const { required, xmlName, xmlElementName, serializedName, xmlNamespace, xmlNamespacePrefix } = bodyMapper; + const typeName = bodyMapper.type.name; try { if ((httpRequest.body !== undefined && httpRequest.body !== null) || required) { - var requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody); + const requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody); httpRequest.body = operationSpec.serializer.serialize(bodyMapper, httpRequest.body, requestBodyParameterPathString, updatedOptions); - var isStream = typeName === MapperType.Stream; + const isStream = typeName === MapperType.Stream; if (operationSpec.isXML) { - var xmlnsKey = xmlNamespacePrefix ? "xmlns:" + xmlNamespacePrefix : "xmlns"; - var value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, httpRequest.body, updatedOptions); + const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns"; + const value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, httpRequest.body, updatedOptions); if (typeName === MapperType.Sequence) { httpRequest.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName, - xmlCharKey: xmlCharKey + xmlCharKey }); } else if (!isStream) { httpRequest.body = stringifyXML(value, { rootName: xmlName || serializedName, - xmlCharKey: xmlCharKey + xmlCharKey }); } } @@ -72681,16 +68407,15 @@ function serializeRequestBody(serviceClient, httpRequest, operationArguments, op } } catch (error) { - throw new Error("Error \"" + error.message + "\" occurred in serializing the payload - " + JSON.stringify(serializedName, undefined, " ") + "."); + throw new Error(`Error "${error.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, undefined, " ")}.`); } } 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]; - var formDataParameterValue = getOperationArgumentValueFromParameter(serviceClient, operationArguments, formDataParameter, operationSpec.serializer); + for (const formDataParameter of operationSpec.formDataParameters) { + const formDataParameterValue = getOperationArgumentValueFromParameter(serviceClient, operationArguments, formDataParameter, operationSpec.serializer); if (formDataParameterValue !== undefined && formDataParameterValue !== null) { - var formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter); + const formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter); httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter), updatedOptions); } } @@ -72700,19 +68425,18 @@ 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) { - 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 = {}; + const result = {}; result[options.xmlCharKey] = serializedValue; - result[XML_ATTRKEY] = (_a = {}, _a[xmlnsKey] = xmlNamespace, _a); + result[XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace }; return result; } return serializedValue; } function getValueOrFunctionResult(value, defaultValueCreator) { - var result; + let result; if (typeof value === "string") { result = value; } @@ -72725,15 +68449,15 @@ function getValueOrFunctionResult(value, defaultValueCreator) { return result; } function createDefaultRequestPolicyFactories(authPolicyFactory, options) { - var factories = []; + const factories = []; if (options.generateClientRequestIdHeader) { factories.push(generateClientRequestIdPolicy(options.clientRequestIdHeaderName)); } if (authPolicyFactory) { factories.push(authPolicyFactory); } - var userAgentHeaderName = getValueOrFunctionResult(options.userAgentHeaderName, getDefaultUserAgentHeaderName); - var userAgentHeaderValue = getValueOrFunctionResult(options.userAgent, getDefaultUserAgentValue); + const userAgentHeaderName = getValueOrFunctionResult(options.userAgentHeaderName, getDefaultUserAgentHeaderName); + const userAgentHeaderValue = getValueOrFunctionResult(options.userAgent, getDefaultUserAgentValue); if (userAgentHeaderName && userAgentHeaderValue) { factories.push(userAgentPolicy({ key: userAgentHeaderName, value: userAgentHeaderValue })); } @@ -72745,37 +68469,37 @@ function createDefaultRequestPolicyFactories(authPolicyFactory, options) { factories.push(throttlingRetryPolicy()); } factories.push(deserializationPolicy(options.deserializationContentTypes)); - { + if (isNode) { factories.push(proxyPolicy(options.proxySettings)); } factories.push(logPolicy({ logger: logger.info })); return factories; } function createPipelineFromOptions(pipelineOptions, authPolicyFactory) { - var requestPolicyFactories = []; + const requestPolicyFactories = []; if (pipelineOptions.sendStreamingJson) { requestPolicyFactories.push(ndJsonPolicy()); } - var userAgentValue = undefined; + let userAgentValue = undefined; if (pipelineOptions.userAgentOptions && pipelineOptions.userAgentOptions.userAgentPrefix) { - var userAgentInfo = []; + const userAgentInfo = []; userAgentInfo.push(pipelineOptions.userAgentOptions.userAgentPrefix); // Add the default user agent value if it isn't already specified // by the userAgentPrefix option. - var defaultUserAgentInfo = getDefaultUserAgentValue(); + const defaultUserAgentInfo = getDefaultUserAgentValue(); if (userAgentInfo.indexOf(defaultUserAgentInfo) === -1) { userAgentInfo.push(defaultUserAgentInfo); } userAgentValue = userAgentInfo.join(" "); } - var keepAliveOptions = tslib.__assign(tslib.__assign({}, DefaultKeepAliveOptions), pipelineOptions.keepAliveOptions); - var retryOptions = tslib.__assign(tslib.__assign({}, DefaultRetryOptions), pipelineOptions.retryOptions); - var redirectOptions = tslib.__assign(tslib.__assign({}, DefaultRedirectOptions), pipelineOptions.redirectOptions); - { + const keepAliveOptions = Object.assign(Object.assign({}, DefaultKeepAliveOptions), pipelineOptions.keepAliveOptions); + const retryOptions = Object.assign(Object.assign({}, DefaultRetryOptions), pipelineOptions.retryOptions); + const redirectOptions = Object.assign(Object.assign({}, DefaultRedirectOptions), pipelineOptions.redirectOptions); + if (isNode) { requestPolicyFactories.push(proxyPolicy(pipelineOptions.proxyOptions)); } - var deserializationOptions = tslib.__assign(tslib.__assign({}, DefaultDeserializationOptions), pipelineOptions.deserializationOptions); - var loggingOptions = tslib.__assign({}, pipelineOptions.loggingOptions); + const deserializationOptions = Object.assign(Object.assign({}, DefaultDeserializationOptions), pipelineOptions.deserializationOptions); + const loggingOptions = Object.assign({}, pipelineOptions.loggingOptions); requestPolicyFactories.push(tracingPolicy({ userAgent: userAgentValue }), keepAlivePolicy(keepAliveOptions), userAgentPolicy({ value: userAgentValue }), generateClientRequestIdPolicy(), deserializationPolicy(deserializationOptions.expectedContentTypes), throttlingRetryPolicy(), systemErrorRetryPolicy(), exponentialRetryPolicy(retryOptions.maxRetries, retryOptions.retryDelayInMs, retryOptions.maxRetryDelayInMs)); if (redirectOptions.handleRedirects) { requestPolicyFactories.push(redirectPolicy(redirectOptions.maxRetries)); @@ -72789,7 +68513,7 @@ function createPipelineFromOptions(pipelineOptions, authPolicyFactory) { } return { httpClient: pipelineOptions.httpClient, - requestPolicyFactories: requestPolicyFactories + requestPolicyFactories }; } function getOperationArgumentValueFromParameter(serviceClient, operationArguments, parameter, serializer) { @@ -72797,22 +68521,22 @@ function getOperationArgumentValueFromParameter(serviceClient, operationArgument } function getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, serializer) { var _a; - var value; + let value; if (typeof parameterPath === "string") { parameterPath = [parameterPath]; } - var serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; + const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; if (Array.isArray(parameterPath)) { if (parameterPath.length > 0) { if (parameterMapper.isConstant) { value = parameterMapper.defaultValue; } else { - var propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath); + let propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath); if (!propertySearchResult.propertyFound) { propertySearchResult = getPropertyFromParameterPath(serviceClient, parameterPath); } - var useDefaultValue = false; + let useDefaultValue = false; if (!propertySearchResult.propertyFound) { useDefaultValue = parameterMapper.required || @@ -72821,7 +68545,7 @@ function getOperationArgumentValueFromParameterPath(serviceClient, operationArgu value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue; } // Serialize just for validation purposes. - var parameterPathString = getPathStringFromParameterPath(parameterPath, parameterMapper); + const parameterPathString = getPathStringFromParameterPath(parameterPath, parameterMapper); serializer.serialize(parameterMapper, value, parameterPathString, serializerOptions); } } @@ -72829,12 +68553,12 @@ function getOperationArgumentValueFromParameterPath(serviceClient, operationArgu if (parameterMapper.required) { value = {}; } - for (var propertyName in parameterPath) { - var propertyMapper = parameterMapper.type.modelProperties[propertyName]; - var propertyPath = parameterPath[propertyName]; - var propertyValue = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, propertyPath, propertyMapper, serializer); + for (const propertyName in parameterPath) { + const propertyMapper = parameterMapper.type.modelProperties[propertyName]; + const propertyPath = parameterPath[propertyName]; + const propertyValue = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, propertyPath, propertyMapper, serializer); // Serialize just for validation purposes. - var propertyPathString = getPathStringFromParameterPath(propertyPath, propertyMapper); + const propertyPathString = getPathStringFromParameterPath(propertyPath, propertyMapper); serializer.serialize(propertyMapper, propertyValue, propertyPathString, serializerOptions); if (propertyValue !== undefined && propertyValue !== null) { if (!value) { @@ -72847,10 +68571,10 @@ function getOperationArgumentValueFromParameterPath(serviceClient, operationArgu return value; } function getPropertyFromParameterPath(parent, parameterPath) { - var result = { propertyFound: false }; - var i = 0; + const result = { propertyFound: false }; + let i = 0; for (; i < parameterPath.length; ++i) { - var parameterPathPart = parameterPath[i]; + const parameterPathPart = parameterPath[i]; // Make sure to check inherited properties too, so don't use hasOwnProperty(). if (parent !== undefined && parent !== null && parameterPathPart in parent) { parent = parent[parameterPathPart]; @@ -72866,31 +68590,29 @@ function getPropertyFromParameterPath(parent, parameterPath) { return result; } function flattenResponse(_response, responseSpec) { - var parsedHeaders = _response.parsedHeaders; - var bodyMapper = responseSpec && responseSpec.bodyMapper; - var addOperationResponse = function (obj) { + const parsedHeaders = _response.parsedHeaders; + const bodyMapper = responseSpec && responseSpec.bodyMapper; + const addOperationResponse = (obj) => { return Object.defineProperty(obj, "_response", { value: _response }); }; if (bodyMapper) { - var typeName = bodyMapper.type.name; + const typeName = bodyMapper.type.name; if (typeName === "Stream") { - return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), { blobBody: _response.blobBody, readableStreamBody: _response.readableStreamBody })); + return addOperationResponse(Object.assign(Object.assign({}, parsedHeaders), { blobBody: _response.blobBody, readableStreamBody: _response.readableStreamBody })); } - var modelProperties_1 = (typeName === "Composite" && bodyMapper.type.modelProperties) || {}; - var isPageableResponse = Object.keys(modelProperties_1).some(function (k) { return modelProperties_1[k].serializedName === ""; }); + const modelProperties = (typeName === "Composite" && bodyMapper.type.modelProperties) || {}; + const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === ""); if (typeName === "Sequence" || isPageableResponse) { - var arrayResponse = tslib.__spreadArray([], (_response.parsedBody || [])); - for (var _i = 0, _a = Object.keys(modelProperties_1); _i < _a.length; _i++) { - var key = _a[_i]; - if (modelProperties_1[key].serializedName) { + const arrayResponse = [...(_response.parsedBody || [])]; + for (const key of Object.keys(modelProperties)) { + if (modelProperties[key].serializedName) { arrayResponse[key] = _response.parsedBody[key]; } } if (parsedHeaders) { - for (var _b = 0, _c = Object.keys(parsedHeaders); _b < _c.length; _b++) { - var key = _c[_b]; + for (const key of Object.keys(parsedHeaders)) { arrayResponse[key] = parsedHeaders[key]; } } @@ -72898,26 +68620,26 @@ function flattenResponse(_response, responseSpec) { return arrayResponse; } if (typeName === "Composite" || typeName === "Dictionary") { - return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), _response.parsedBody)); + return addOperationResponse(Object.assign(Object.assign({}, parsedHeaders), _response.parsedBody)); } } if (bodyMapper || _response.request.method === "HEAD" || isPrimitiveType(_response.parsedBody)) { // primitive body types and HEAD booleans - return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), { body: _response.parsedBody })); + return addOperationResponse(Object.assign(Object.assign({}, parsedHeaders), { body: _response.parsedBody })); } - return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), _response.parsedBody)); + return addOperationResponse(Object.assign(Object.assign({}, parsedHeaders), _response.parsedBody)); } function getCredentialScopes(options, baseUri) { if (options === null || options === void 0 ? void 0 : options.credentialScopes) { - var scopes = options.credentialScopes; + const scopes = options.credentialScopes; return Array.isArray(scopes) - ? scopes.map(function (scope) { return new url.URL(scope).toString(); }) + ? scopes.map((scope) => new url.URL(scope).toString()) : new url.URL(scopes).toString(); } if (baseUri) { - return baseUri + "/.default"; + return `${baseUri}/.default`; } return undefined; } @@ -72941,7 +68663,7 @@ function createSpanFunction(args) { /** * Defines the default token refresh buffer duration. */ -var TokenRefreshBufferMs = 2 * 60 * 1000; // 2 Minutes +const TokenRefreshBufferMs = 2 * 60 * 1000; // 2 Minutes /** * Provides an {@link AccessTokenCache} implementation which clears * the cached {@link AccessToken}'s after the expiresOnTimestamp has @@ -72949,38 +68671,36 @@ var TokenRefreshBufferMs = 2 * 60 * 1000; // 2 Minutes * * @deprecated No longer used in the bearer authorization policy. */ -var ExpiringAccessTokenCache = /** @class */ (function () { +class ExpiringAccessTokenCache { /** * Constructs an instance of {@link ExpiringAccessTokenCache} with * an optional expiration buffer time. */ - function ExpiringAccessTokenCache(tokenRefreshBufferMs) { - if (tokenRefreshBufferMs === void 0) { tokenRefreshBufferMs = TokenRefreshBufferMs; } + constructor(tokenRefreshBufferMs = TokenRefreshBufferMs) { this.cachedToken = undefined; this.tokenRefreshBufferMs = tokenRefreshBufferMs; } - ExpiringAccessTokenCache.prototype.setCachedToken = function (accessToken) { + setCachedToken(accessToken) { this.cachedToken = accessToken; - }; - ExpiringAccessTokenCache.prototype.getCachedToken = function () { + } + getCachedToken() { if (this.cachedToken && Date.now() + this.tokenRefreshBufferMs >= this.cachedToken.expiresOnTimestamp) { this.cachedToken = undefined; } return this.cachedToken; - }; - return ExpiringAccessTokenCache; -}()); + } +} // Copyright (c) Microsoft Corporation. +// Licensed under the MIT license. /** * Helps the core-http token authentication policies with requesting a new token if we're not currently waiting for a new token. * * @deprecated No longer used in the bearer authorization policy. */ -var AccessTokenRefresher = /** @class */ (function () { - function AccessTokenRefresher(credential, scopes, requiredMillisecondsBeforeNewRefresh) { - if (requiredMillisecondsBeforeNewRefresh === void 0) { requiredMillisecondsBeforeNewRefresh = 30000; } +class AccessTokenRefresher { + constructor(credential, scopes, requiredMillisecondsBeforeNewRefresh = 30000) { this.credential = credential; this.scopes = scopes; this.requiredMillisecondsBeforeNewRefresh = requiredMillisecondsBeforeNewRefresh; @@ -72990,49 +68710,38 @@ 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. */ - AccessTokenRefresher.prototype.isReady = function () { + isReady() { // We're only ready for a new refresh if the required milliseconds have passed. return (!this.lastCalled || Date.now() - this.lastCalled > this.requiredMillisecondsBeforeNewRefresh); - }; + } /** * Stores the time in which it is called, * then requests a new token, * then sets this.promise to undefined, * then returns the token. */ - AccessTokenRefresher.prototype.getToken = function (options) { - return tslib.__awaiter(this, void 0, void 0, function () { - var token; - return tslib.__generator(this, function (_a) { - switch (_a.label) { - case 0: - this.lastCalled = Date.now(); - return [4 /*yield*/, this.credential.getToken(this.scopes, options)]; - case 1: - token = _a.sent(); - this.promise = undefined; - return [2 /*return*/, token || undefined]; - } - }); - }); - }; + async getToken(options) { + this.lastCalled = Date.now(); + const token = await this.credential.getToken(this.scopes, options); + this.promise = undefined; + return token || undefined; + } /** * 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. */ - AccessTokenRefresher.prototype.refresh = function (options) { + refresh(options) { if (!this.promise) { this.promise = this.getToken(options); } return this.promise; - }; - return AccessTokenRefresher; -}()); + } +} // Copyright (c) Microsoft Corporation. -var HeaderConstants = Constants.HeaderConstants; -var DEFAULT_AUTHORIZATION_SCHEME = "Basic"; -var BasicAuthenticationCredentials = /** @class */ (function () { +const HeaderConstants = Constants.HeaderConstants; +const DEFAULT_AUTHORIZATION_SCHEME = "Basic"; +class BasicAuthenticationCredentials { /** * Creates a new BasicAuthenticationCredentials object. * @@ -73040,8 +68749,7 @@ var BasicAuthenticationCredentials = /** @class */ (function () { * @param password - Password. * @param authorizationScheme - The authorization scheme. */ - function BasicAuthenticationCredentials(userName, password, authorizationScheme) { - if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME; } + constructor(userName, password, authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME) { this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME; if (userName === null || userName === undefined || typeof userName.valueOf() !== "string") { throw new Error("userName cannot be null or undefined and must be of type string."); @@ -73059,28 +68767,27 @@ var BasicAuthenticationCredentials = /** @class */ (function () { * @param webResource - The WebResourceLike to be signed. * @returns The signed request object. */ - BasicAuthenticationCredentials.prototype.signRequest = function (webResource) { - var credentials = this.userName + ":" + this.password; - var encodedCredentials = this.authorizationScheme + " " + encodeString(credentials); + signRequest(webResource) { + const credentials = `${this.userName}:${this.password}`; + const encodedCredentials = `${this.authorizationScheme} ${encodeString(credentials)}`; if (!webResource.headers) webResource.headers = new HttpHeaders(); webResource.headers.set(HeaderConstants.AUTHORIZATION, encodedCredentials); return Promise.resolve(webResource); - }; - return BasicAuthenticationCredentials; -}()); + } +} // Copyright (c) Microsoft Corporation. /** * Authenticates to a service using an API key. */ -var ApiKeyCredentials = /** @class */ (function () { +class ApiKeyCredentials { /** * @param options - Specifies the options to be provided for auth. Either header or query needs to be provided. */ - function ApiKeyCredentials(options) { + constructor(options) { if (!options || (options && !options.inHeader && !options.inQuery)) { - throw new Error("options cannot be null or undefined. Either \"inHeader\" or \"inQuery\" property of the options object needs to be provided."); + throw new Error(`options cannot be null or undefined. Either "inHeader" or "inQuery" property of the options object needs to be provided.`); } this.inHeader = options.inHeader; this.inQuery = options.inQuery; @@ -73091,60 +68798,55 @@ var ApiKeyCredentials = /** @class */ (function () { * @param webResource - The WebResourceLike to be signed. * @returns The signed request object. */ - ApiKeyCredentials.prototype.signRequest = function (webResource) { + signRequest(webResource) { if (!webResource) { - return Promise.reject(new Error("webResource cannot be null or undefined and must be of type \"object\".")); + return Promise.reject(new Error(`webResource cannot be null or undefined and must be of type "object".`)); } if (this.inHeader) { if (!webResource.headers) { webResource.headers = new HttpHeaders(); } - for (var headerName in this.inHeader) { + for (const headerName in this.inHeader) { webResource.headers.set(headerName, this.inHeader[headerName]); } } if (this.inQuery) { if (!webResource.url) { - return Promise.reject(new Error("url cannot be null in the request object.")); + return Promise.reject(new Error(`url cannot be null in the request object.`)); } if (webResource.url.indexOf("?") < 0) { webResource.url += "?"; } - for (var key in this.inQuery) { + for (const key in this.inQuery) { if (!webResource.url.endsWith("?")) { webResource.url += "&"; } - webResource.url += key + "=" + this.inQuery[key]; + webResource.url += `${key}=${this.inQuery[key]}`; } } return Promise.resolve(webResource); - }; - return ApiKeyCredentials; -}()); + } +} // Copyright (c) Microsoft Corporation. -var TopicCredentials = /** @class */ (function (_super) { - tslib.__extends(TopicCredentials, _super); +class TopicCredentials extends ApiKeyCredentials { /** * Creates a new EventGrid TopicCredentials object. * * @param topicKey - The EventGrid topic key */ - function TopicCredentials(topicKey) { - var _this = this; + constructor(topicKey) { if (!topicKey || (topicKey && typeof topicKey !== "string")) { throw new Error("topicKey cannot be null or undefined and must be of type string."); } - var options = { + const options = { inHeader: { "aeg-sas-key": topicKey } }; - _this = _super.call(this, options) || this; - return _this; + super(options); } - return TopicCredentials; -}(ApiKeyCredentials)); +} Object.defineProperty(exports, 'isTokenCredential', { enumerable: true, diff --git a/package-lock.json b/package-lock.json index 19d7761c..72fcd8bd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5,9 +5,9 @@ "requires": true, "dependencies": { "@actions/cache": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/@actions/cache/-/cache-1.0.7.tgz", - "integrity": "sha512-MY69kxuubqUFq84pFlu8m6Poxl5sR/xyhpC4JEvno7Yg9ASYdGizEmKgt0m8ovewpYKf15UAOcSC0hzS+DuosA==", + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@actions/cache/-/cache-1.0.8.tgz", + "integrity": "sha512-GWNNB67w93HGJRQXlsV56YqrdAuDoP3esK/mo5mzU8WoDCVjtQgJGsTdkYUX7brswtT7xnI30bWNo1WLKQ8FZQ==", "requires": { "@actions/core": "^1.2.6", "@actions/exec": "^1.0.1", @@ -29,14 +29,6 @@ "minimatch": "^3.0.4" } }, - "@actions/http-client": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-1.0.11.tgz", - "integrity": "sha512-VRYHGQV1rqnROJqdMvGUbY/Kn8vriQe/F9HR2AlYHzmKuM/p3kjNuXhmdBfcVgsvRWTz5C5XW5xvndZrVBuAYg==", - "requires": { - "tunnel": "0.0.6" - } - }, "uuid": { "version": "3.4.0", "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", @@ -128,9 +120,9 @@ }, "dependencies": { "tslib": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz", - "integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==" + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz", + "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw==" } } }, @@ -140,34 +132,34 @@ "integrity": "sha512-kmv8CGrPfN9SwMwrkiBK9VTQYxdFQEGe0BmQk+M8io56P9KNzpAxcWE/1fxJj7uouwN4kXF0BHW8DNlgx+wtCg==" }, "@azure/core-auth": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/@azure/core-auth/-/core-auth-1.3.0.tgz", - "integrity": "sha512-kSDSZBL6c0CYdhb+7KuutnKGf2geeT+bCJAgccB0DD7wmNJSsQPcF7TcuoZX83B7VK4tLz/u+8sOO/CnCsYp8A==", + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@azure/core-auth/-/core-auth-1.3.2.tgz", + "integrity": "sha512-7CU6DmCHIZp5ZPiZ9r3J17lTKMmYsm/zGvNkjArQwPkrLlZ1TZ+EUYfGgh2X31OLMVAQCTJZW4cXHJi02EbJnA==", "requires": { "@azure/abort-controller": "^1.0.0", - "tslib": "^2.0.0" + "tslib": "^2.2.0" }, "dependencies": { "tslib": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz", - "integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==" + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz", + "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw==" } } }, "@azure/core-http": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@azure/core-http/-/core-http-1.2.6.tgz", - "integrity": "sha512-odtH7UMKtekc5YQ86xg9GlVHNXR6pq2JgJ5FBo7/jbOjNGdBqcrIVrZx2bevXVJz/uUTSx6vUf62gzTXTfqYSQ==", + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@azure/core-http/-/core-http-2.2.2.tgz", + "integrity": "sha512-V1DdoO9V/sFimKpdWoNBgsE+QUjQgpXYnxrTdUp5RyhsTJjvEVn/HKmTQXIHuLUUo6IyIWj+B+Dg4VaXse9dIA==", "requires": { "@azure/abort-controller": "^1.0.0", "@azure/core-asynciterator-polyfill": "^1.0.0", "@azure/core-auth": "^1.3.0", - "@azure/core-tracing": "1.0.0-preview.11", + "@azure/core-tracing": "1.0.0-preview.13", "@azure/logger": "^1.0.0", "@types/node-fetch": "^2.5.0", - "@types/tunnel": "^0.0.1", - "form-data": "^3.0.0", + "@types/tunnel": "^0.0.3", + "form-data": "^4.0.0", "node-fetch": "^2.6.0", "process": "^0.11.10", "tough-cookie": "^4.0.0", @@ -178,29 +170,19 @@ }, "dependencies": { "form-data": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz", - "integrity": "sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", "requires": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "mime-types": "^2.1.12" } }, - "tough-cookie": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.0.0.tgz", - "integrity": "sha512-tHdtEpQCMrc1YLrMaqXXcj6AxhYi/xgit6mZu1+EDWUn+qhUf8wMQoFIy9NXuq23zAwtcB0t/MjACGR18pcRbg==", - "requires": { - "psl": "^1.1.33", - "punycode": "^2.1.1", - "universalify": "^0.1.2" - } - }, "tslib": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz", - "integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==" + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz", + "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw==" }, "uuid": { "version": "8.3.2", @@ -210,68 +192,74 @@ } }, "@azure/core-lro": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/@azure/core-lro/-/core-lro-1.0.5.tgz", - "integrity": "sha512-0EFCFZxARrIoLWMIRt4vuqconRVIO2Iin7nFBfJiYCCbKp5eEmxutNk8uqudPmG0XFl5YqlVh68/al/vbE5OOg==", + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@azure/core-lro/-/core-lro-2.2.1.tgz", + "integrity": "sha512-HE6PBl+mlKa0eBsLwusHqAqjLc5n9ByxeDo3Hz4kF3B1hqHvRkBr4oMgoT6tX7Hc3q97KfDctDUon7EhvoeHPA==", "requires": { "@azure/abort-controller": "^1.0.0", - "@azure/core-http": "^1.2.0", - "@azure/core-tracing": "1.0.0-preview.11", - "events": "^3.0.0", - "tslib": "^2.0.0" + "@azure/core-tracing": "1.0.0-preview.13", + "@azure/logger": "^1.0.0", + "tslib": "^2.2.0" }, "dependencies": { "tslib": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz", - "integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==" + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz", + "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw==" } } }, "@azure/core-paging": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@azure/core-paging/-/core-paging-1.1.3.tgz", - "integrity": "sha512-his7Ah40ThEYORSpIAwuh6B8wkGwO/zG7gqVtmSE4WAJ46e36zUDXTKReUCLBDc6HmjjApQQxxcRFy5FruG79A==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@azure/core-paging/-/core-paging-1.2.0.tgz", + "integrity": "sha512-ZX1bCjm/MjKPCN6kQD/9GJErYSoKA8YWp6YWoo5EIzcTWlSBLXu3gNaBTUl8usGl+UShiKo7b4Gdy1NSTIlpZg==", "requires": { - "@azure/core-asynciterator-polyfill": "^1.0.0" - } - }, - "@azure/core-tracing": { - "version": "1.0.0-preview.11", - "resolved": "https://registry.npmjs.org/@azure/core-tracing/-/core-tracing-1.0.0-preview.11.tgz", - "integrity": "sha512-frF0pJc9HTmKncVokhBxCqipjbql02DThQ1ZJ9wLi7SDMLdPAFyDI5xZNzX5guLz+/DtPkY+SGK2li9FIXqshQ==", - "requires": { - "@opencensus/web-types": "0.0.7", - "@opentelemetry/api": "1.0.0-rc.0", - "tslib": "^2.0.0" + "@azure/core-asynciterator-polyfill": "^1.0.0", + "tslib": "^2.2.0" }, "dependencies": { "tslib": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz", - "integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==" + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz", + "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw==" + } + } + }, + "@azure/core-tracing": { + "version": "1.0.0-preview.13", + "resolved": "https://registry.npmjs.org/@azure/core-tracing/-/core-tracing-1.0.0-preview.13.tgz", + "integrity": "sha512-KxDlhXyMlh2Jhj2ykX6vNEU0Vou4nHr025KoSEiz7cS3BNiHNaZcdECk/DmLkEB0as5T7b/TpRcehJ5yV6NeXQ==", + "requires": { + "@opentelemetry/api": "^1.0.1", + "tslib": "^2.2.0" + }, + "dependencies": { + "tslib": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz", + "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw==" } } }, "@azure/logger": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@azure/logger/-/logger-1.0.2.tgz", - "integrity": "sha512-YZNjNV0vL3nN2nedmcjQBcpCTo3oqceXmgiQtEm6fLpucjRZyQKAQruhCmCpRlB1iykqKJJ/Y8CDmT5rIE6IJw==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@azure/logger/-/logger-1.0.3.tgz", + "integrity": "sha512-aK4s3Xxjrx3daZr3VylxejK3vG5ExXck5WOHDJ8in/k9AqlfIyFMMT1uG7u8mNjX+QRILTIn0/Xgschfh/dQ9g==", "requires": { - "tslib": "^2.0.0" + "tslib": "^2.2.0" }, "dependencies": { "tslib": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz", - "integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==" + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz", + "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw==" } } }, "@azure/ms-rest-js": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/@azure/ms-rest-js/-/ms-rest-js-2.5.2.tgz", - "integrity": "sha512-9nCuuoYwHZEZw1t0MVtENH+c1k2R4maYAlBBDSZhZu6bEucyfYUUigNXXKjt2cFBt4sO+sTzi0uI0f/fiPFr+Q==", + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@azure/ms-rest-js/-/ms-rest-js-2.6.0.tgz", + "integrity": "sha512-4C5FCtvEzWudblB+h92/TYYPiq7tuElX8icVYToxOdggnYqeec4Se14mjse5miInKtZahiFHdl8lZA/jziEc5g==", "requires": { "@azure/core-auth": "^1.1.4", "abort-controller": "^3.0.0", @@ -280,7 +268,7 @@ "tough-cookie": "^3.0.1", "tslib": "^1.10.0", "tunnel": "0.0.6", - "uuid": "^3.3.2", + "uuid": "^8.3.2", "xml2js": "^0.4.19" }, "dependencies": { @@ -303,28 +291,33 @@ "psl": "^1.1.28", "punycode": "^2.1.1" } + }, + "uuid": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", + "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==" } } }, "@azure/storage-blob": { - "version": "12.6.0", - "resolved": "https://registry.npmjs.org/@azure/storage-blob/-/storage-blob-12.6.0.tgz", - "integrity": "sha512-cAzsae+5ZdhugQfIT7o5SlVyF2Sc+HygZdPO41ZYdXklfGUyEt+5K4PyM5HQDc0MTVt6x7+waXcaAXT2eF9E6A==", + "version": "12.8.0", + "resolved": "https://registry.npmjs.org/@azure/storage-blob/-/storage-blob-12.8.0.tgz", + "integrity": "sha512-c8+Wz19xauW0bGkTCoqZH4dYfbtBniPiGiRQOn1ca6G5jsjr4azwaTk9gwjVY8r3vY2Taf95eivLzipfIfiS4A==", "requires": { "@azure/abort-controller": "^1.0.0", - "@azure/core-http": "^1.2.0", - "@azure/core-lro": "^1.0.2", + "@azure/core-http": "^2.0.0", + "@azure/core-lro": "^2.2.0", "@azure/core-paging": "^1.1.1", - "@azure/core-tracing": "1.0.0-preview.11", + "@azure/core-tracing": "1.0.0-preview.13", "@azure/logger": "^1.0.0", "events": "^3.0.0", - "tslib": "^2.0.0" + "tslib": "^2.2.0" }, "dependencies": { "tslib": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz", - "integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==" + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.1.tgz", + "integrity": "sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw==" } } }, @@ -1141,15 +1134,10 @@ "@types/node": ">= 8" } }, - "@opencensus/web-types": { - "version": "0.0.7", - "resolved": "https://registry.npmjs.org/@opencensus/web-types/-/web-types-0.0.7.tgz", - "integrity": "sha512-xB+w7ZDAu3YBzqH44rCmG9/RlrOmFuDPt/bpf17eJr8eZSrLt7nc7LnWdxM9Mmoj/YKMHpxRg28txu3TcpiL+g==" - }, "@opentelemetry/api": { - "version": "1.0.0-rc.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.0.0-rc.0.tgz", - "integrity": "sha512-iXKByCMfrlO5S6Oh97BuM56tM2cIBB0XsL/vWF/AtJrJEKx4MC/Xdu0xDsGXMGcNWpqF7ujMsjjnp0+UHBwnDQ==" + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.0.3.tgz", + "integrity": "sha512-puWxACExDe9nxbBB3lOymQFrLYml2dVOrd7USiVRnSbgXE+KwBu+HxFvxrzfqsiSda9IWsXJG1ef7C1O2/GmKQ==" }, "@sinonjs/commons": { "version": "1.8.3", @@ -1265,24 +1253,12 @@ "integrity": "sha512-LcsGbPomWsad6wmMNv7nBLw7YYYyfdYcz6xryKYQhx89c3XXan+8Q6AJ43G5XDIaklaVkK3mE4fCb0SBvMiPSQ==" }, "@types/node-fetch": { - "version": "2.5.10", - "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.5.10.tgz", - "integrity": "sha512-IpkX0AasN44hgEad0gEF/V6EgR5n69VEqPEgnmoM8GsIGro3PowbWs4tR6IhxUTyPLpOn+fiGG6nrQhcmoCuIQ==", + "version": "2.5.12", + "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.5.12.tgz", + "integrity": "sha512-MKgC4dlq4kKNa/mYrwpKfzQMB5X3ee5U6fSprkKpToBqBmX4nFZL9cW5jl6sWn+xpRJ7ypWh2yyqqr8UUCstSw==", "requires": { "@types/node": "*", "form-data": "^3.0.0" - }, - "dependencies": { - "form-data": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz", - "integrity": "sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg==", - "requires": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "mime-types": "^2.1.12" - } - } } }, "@types/prettier": { @@ -1304,9 +1280,9 @@ "dev": true }, "@types/tunnel": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/@types/tunnel/-/tunnel-0.0.1.tgz", - "integrity": "sha512-AOqu6bQu5MSWwYvehMXLukFHnupHrpZ8nvgae5Ggie9UwzDR1CCwoXgSSWNZJuyOlCdfdsWMA5F2LlmvyoTv8A==", + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/@types/tunnel/-/tunnel-0.0.3.tgz", + "integrity": "sha512-sOUTGn6h1SfQ+gbgqC364jLFBw2lnFqkgF3q0WovEHRLMrVD1sd5aufqi/aJObLekJO+Aq5z646U4Oxy6shXMA==", "requires": { "@types/node": "*" } @@ -1981,7 +1957,6 @@ "version": "3.0.1", "resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.1.tgz", "integrity": "sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg==", - "dev": true, "requires": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", @@ -3685,7 +3660,6 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.0.0.tgz", "integrity": "sha512-tHdtEpQCMrc1YLrMaqXXcj6AxhYi/xgit6mZu1+EDWUn+qhUf8wMQoFIy9NXuq23zAwtcB0t/MjACGR18pcRbg==", - "dev": true, "requires": { "psl": "^1.1.33", "punycode": "^2.1.1", diff --git a/package.json b/package.json index 1596c508..0663191f 100644 --- a/package.json +++ b/package.json @@ -23,7 +23,7 @@ "author": "GitHub", "license": "MIT", "dependencies": { - "@actions/cache": "^1.0.7", + "@actions/cache": "^1.0.8", "@actions/core": "^1.6.0", "@actions/exec": "^1.1.0", "@actions/github": "^1.1.0",