'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var coreHttp = require('@azure/core-http'); var tslib = require('tslib'); var api = require('@opentelemetry/api'); var logger$1 = require('@azure/logger'); var abortController = require('@azure/abort-controller'); var os = require('os'); var stream = require('stream'); require('@azure/core-paging'); var crypto = require('crypto'); var coreLro = require('@azure/core-lro'); var events = require('events'); var coreTracing = require('@azure/core-tracing'); var fs = require('fs'); var util = require('util'); /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ var KeyInfo = { serializedName: "KeyInfo", type: { name: "Composite", className: "KeyInfo", modelProperties: { startsOn: { xmlName: "Start", required: true, serializedName: "Start", type: { name: "String" } }, expiresOn: { xmlName: "Expiry", required: true, serializedName: "Expiry", type: { name: "String" } } } } }; var UserDelegationKey = { serializedName: "UserDelegationKey", type: { name: "Composite", className: "UserDelegationKey", modelProperties: { signedObjectId: { xmlName: "SignedOid", required: true, serializedName: "SignedOid", type: { name: "String" } }, signedTenantId: { xmlName: "SignedTid", required: true, serializedName: "SignedTid", type: { name: "String" } }, signedStartsOn: { xmlName: "SignedStart", required: true, serializedName: "SignedStart", type: { name: "String" } }, signedExpiresOn: { xmlName: "SignedExpiry", required: true, serializedName: "SignedExpiry", type: { name: "String" } }, signedService: { xmlName: "SignedService", required: true, serializedName: "SignedService", type: { name: "String" } }, signedVersion: { xmlName: "SignedVersion", required: true, serializedName: "SignedVersion", type: { name: "String" } }, value: { xmlName: "Value", required: true, serializedName: "Value", type: { name: "String" } } } } }; var StorageError = { serializedName: "StorageError", type: { name: "Composite", className: "StorageError", modelProperties: { message: { xmlName: "Message", serializedName: "Message", type: { name: "String" } }, code: { xmlName: "Code", serializedName: "Code", type: { name: "String" } } } } }; var DataLakeStorageErrorError = { serializedName: "DataLakeStorageError_error", type: { name: "Composite", className: "DataLakeStorageErrorError", modelProperties: { code: { xmlName: "Code", serializedName: "Code", type: { name: "String" } }, message: { xmlName: "Message", serializedName: "Message", type: { name: "String" } } } } }; var DataLakeStorageError = { serializedName: "DataLakeStorageError", type: { name: "Composite", className: "DataLakeStorageError", modelProperties: { dataLakeStorageErrorDetails: { xmlName: "error", serializedName: "error", type: { name: "Composite", className: "DataLakeStorageErrorError" } } } } }; var AccessPolicy = { serializedName: "AccessPolicy", type: { name: "Composite", className: "AccessPolicy", modelProperties: { startsOn: { xmlName: "Start", serializedName: "Start", type: { name: "String" } }, expiresOn: { xmlName: "Expiry", serializedName: "Expiry", type: { name: "String" } }, permissions: { xmlName: "Permission", serializedName: "Permission", type: { name: "String" } } } } }; var BlobPropertiesInternal = { xmlName: "Properties", serializedName: "BlobPropertiesInternal", type: { name: "Composite", className: "BlobPropertiesInternal", modelProperties: { createdOn: { xmlName: "Creation-Time", serializedName: "Creation-Time", type: { name: "DateTimeRfc1123" } }, lastModified: { xmlName: "Last-Modified", required: true, serializedName: "Last-Modified", type: { name: "DateTimeRfc1123" } }, etag: { xmlName: "Etag", required: true, serializedName: "Etag", type: { name: "String" } }, contentLength: { xmlName: "Content-Length", serializedName: "Content-Length", type: { name: "Number" } }, contentType: { xmlName: "Content-Type", serializedName: "Content-Type", type: { name: "String" } }, contentEncoding: { xmlName: "Content-Encoding", serializedName: "Content-Encoding", type: { name: "String" } }, contentLanguage: { xmlName: "Content-Language", serializedName: "Content-Language", type: { name: "String" } }, contentMD5: { xmlName: "Content-MD5", serializedName: "Content-MD5", type: { name: "ByteArray" } }, contentDisposition: { xmlName: "Content-Disposition", serializedName: "Content-Disposition", type: { name: "String" } }, cacheControl: { xmlName: "Cache-Control", serializedName: "Cache-Control", type: { name: "String" } }, blobSequenceNumber: { xmlName: "x-ms-blob-sequence-number", serializedName: "x-ms-blob-sequence-number", type: { name: "Number" } }, blobType: { xmlName: "BlobType", serializedName: "BlobType", type: { name: "Enum", allowedValues: [ "BlockBlob", "PageBlob", "AppendBlob" ] } }, leaseStatus: { xmlName: "LeaseStatus", serializedName: "LeaseStatus", type: { name: "Enum", allowedValues: [ "locked", "unlocked" ] } }, leaseState: { xmlName: "LeaseState", serializedName: "LeaseState", type: { name: "Enum", allowedValues: [ "available", "leased", "expired", "breaking", "broken" ] } }, leaseDuration: { xmlName: "LeaseDuration", serializedName: "LeaseDuration", type: { name: "Enum", allowedValues: [ "infinite", "fixed" ] } }, copyId: { xmlName: "CopyId", serializedName: "CopyId", type: { name: "String" } }, copyStatus: { xmlName: "CopyStatus", serializedName: "CopyStatus", type: { name: "Enum", allowedValues: [ "pending", "success", "aborted", "failed" ] } }, copySource: { xmlName: "CopySource", serializedName: "CopySource", type: { name: "String" } }, copyProgress: { xmlName: "CopyProgress", serializedName: "CopyProgress", type: { name: "String" } }, copyCompletedOn: { xmlName: "CopyCompletionTime", serializedName: "CopyCompletionTime", type: { name: "DateTimeRfc1123" } }, copyStatusDescription: { xmlName: "CopyStatusDescription", serializedName: "CopyStatusDescription", type: { name: "String" } }, serverEncrypted: { xmlName: "ServerEncrypted", serializedName: "ServerEncrypted", type: { name: "Boolean" } }, incrementalCopy: { xmlName: "IncrementalCopy", serializedName: "IncrementalCopy", type: { name: "Boolean" } }, destinationSnapshot: { xmlName: "DestinationSnapshot", serializedName: "DestinationSnapshot", type: { name: "String" } }, deletedOn: { xmlName: "DeletedTime", serializedName: "DeletedTime", type: { name: "DateTimeRfc1123" } }, remainingRetentionDays: { xmlName: "RemainingRetentionDays", serializedName: "RemainingRetentionDays", type: { name: "Number" } }, accessTier: { xmlName: "AccessTier", serializedName: "AccessTier", type: { name: "String" } }, accessTierInferred: { xmlName: "AccessTierInferred", serializedName: "AccessTierInferred", type: { name: "Boolean" } }, archiveStatus: { xmlName: "ArchiveStatus", serializedName: "ArchiveStatus", type: { name: "String" } }, customerProvidedKeySha256: { xmlName: "CustomerProvidedKeySha256", serializedName: "CustomerProvidedKeySha256", type: { name: "String" } }, encryptionScope: { xmlName: "EncryptionScope", serializedName: "EncryptionScope", type: { name: "String" } }, accessTierChangedOn: { xmlName: "AccessTierChangeTime", serializedName: "AccessTierChangeTime", type: { name: "DateTimeRfc1123" } }, tagCount: { xmlName: "TagCount", serializedName: "TagCount", type: { name: "Number" } }, expiresOn: { xmlName: "Expiry-Time", serializedName: "Expiry-Time", type: { name: "DateTimeRfc1123" } }, isSealed: { xmlName: "Sealed", serializedName: "Sealed", type: { name: "Boolean" } }, rehydratePriority: { xmlName: "RehydratePriority", serializedName: "RehydratePriority", type: { name: "String" } }, lastAccessedOn: { xmlName: "LastAccessTime", serializedName: "LastAccessTime", type: { name: "DateTimeRfc1123" } } } } }; var BlobTag = { xmlName: "Tag", serializedName: "BlobTag", type: { name: "Composite", className: "BlobTag", modelProperties: { key: { xmlName: "Key", required: true, serializedName: "Key", type: { name: "String" } }, value: { xmlName: "Value", required: true, serializedName: "Value", type: { name: "String" } } } } }; var BlobTags = { xmlName: "Tags", serializedName: "BlobTags", type: { name: "Composite", className: "BlobTags", modelProperties: { blobTagSet: { xmlIsWrapped: true, xmlName: "TagSet", xmlElementName: "Tag", required: true, serializedName: "BlobTagSet", type: { name: "Sequence", element: { type: { name: "Composite", className: "BlobTag" } } } } } } }; var BlobItemInternal = { xmlName: "Blob", serializedName: "BlobItemInternal", type: { name: "Composite", className: "BlobItemInternal", modelProperties: { name: { xmlName: "Name", required: true, serializedName: "Name", type: { name: "String" } }, deleted: { xmlName: "Deleted", required: true, serializedName: "Deleted", type: { name: "Boolean" } }, snapshot: { xmlName: "Snapshot", required: true, serializedName: "Snapshot", type: { name: "String" } }, versionId: { xmlName: "VersionId", serializedName: "VersionId", type: { name: "String" } }, isCurrentVersion: { xmlName: "IsCurrentVersion", serializedName: "IsCurrentVersion", type: { name: "Boolean" } }, properties: { xmlName: "Properties", required: true, serializedName: "Properties", type: { name: "Composite", className: "BlobPropertiesInternal" } }, metadata: { xmlName: "Metadata", serializedName: "Metadata", type: { name: "Dictionary", value: { type: { name: "String" } } } }, blobTags: { xmlName: "Tags", serializedName: "BlobTags", type: { name: "Composite", className: "BlobTags" } }, objectReplicationMetadata: { xmlName: "OrMetadata", serializedName: "ObjectReplicationMetadata", type: { name: "Dictionary", value: { type: { name: "String" } } } } } } }; var BlobFlatListSegment = { xmlName: "Blobs", serializedName: "BlobFlatListSegment", type: { name: "Composite", className: "BlobFlatListSegment", modelProperties: { blobItems: { xmlName: "BlobItems", xmlElementName: "Blob", required: true, serializedName: "BlobItems", type: { name: "Sequence", element: { type: { name: "Composite", className: "BlobItemInternal" } } } } } } }; var ListBlobsFlatSegmentResponse = { xmlName: "EnumerationResults", serializedName: "ListBlobsFlatSegmentResponse", type: { name: "Composite", className: "ListBlobsFlatSegmentResponse", modelProperties: { serviceEndpoint: { xmlIsAttribute: true, xmlName: "ServiceEndpoint", required: true, serializedName: "ServiceEndpoint", type: { name: "String" } }, containerName: { xmlIsAttribute: true, xmlName: "ContainerName", required: true, serializedName: "ContainerName", type: { name: "String" } }, prefix: { xmlName: "Prefix", serializedName: "Prefix", type: { name: "String" } }, marker: { xmlName: "Marker", serializedName: "Marker", type: { name: "String" } }, maxPageSize: { xmlName: "MaxResults", serializedName: "MaxResults", type: { name: "Number" } }, segment: { xmlName: "Blobs", required: true, serializedName: "Segment", type: { name: "Composite", className: "BlobFlatListSegment" } }, continuationToken: { xmlName: "NextMarker", serializedName: "NextMarker", type: { name: "String" } } } } }; var BlobPrefix = { serializedName: "BlobPrefix", type: { name: "Composite", className: "BlobPrefix", modelProperties: { name: { xmlName: "Name", required: true, serializedName: "Name", type: { name: "String" } } } } }; var BlobHierarchyListSegment = { xmlName: "Blobs", serializedName: "BlobHierarchyListSegment", type: { name: "Composite", className: "BlobHierarchyListSegment", modelProperties: { blobPrefixes: { xmlName: "BlobPrefixes", xmlElementName: "BlobPrefix", serializedName: "BlobPrefixes", type: { name: "Sequence", element: { type: { name: "Composite", className: "BlobPrefix" } } } }, blobItems: { xmlName: "BlobItems", xmlElementName: "Blob", required: true, serializedName: "BlobItems", type: { name: "Sequence", element: { type: { name: "Composite", className: "BlobItemInternal" } } } } } } }; var ListBlobsHierarchySegmentResponse = { xmlName: "EnumerationResults", serializedName: "ListBlobsHierarchySegmentResponse", type: { name: "Composite", className: "ListBlobsHierarchySegmentResponse", modelProperties: { serviceEndpoint: { xmlIsAttribute: true, xmlName: "ServiceEndpoint", required: true, serializedName: "ServiceEndpoint", type: { name: "String" } }, containerName: { xmlIsAttribute: true, xmlName: "ContainerName", required: true, serializedName: "ContainerName", type: { name: "String" } }, prefix: { xmlName: "Prefix", serializedName: "Prefix", type: { name: "String" } }, marker: { xmlName: "Marker", serializedName: "Marker", type: { name: "String" } }, maxPageSize: { xmlName: "MaxResults", serializedName: "MaxResults", type: { name: "Number" } }, delimiter: { xmlName: "Delimiter", serializedName: "Delimiter", type: { name: "String" } }, segment: { xmlName: "Blobs", required: true, serializedName: "Segment", type: { name: "Composite", className: "BlobHierarchyListSegment" } }, continuationToken: { xmlName: "NextMarker", serializedName: "NextMarker", type: { name: "String" } } } } }; var Block = { serializedName: "Block", type: { name: "Composite", className: "Block", modelProperties: { name: { xmlName: "Name", required: true, serializedName: "Name", type: { name: "String" } }, size: { xmlName: "Size", required: true, serializedName: "Size", type: { name: "Number" } } } } }; var BlockList = { serializedName: "BlockList", type: { name: "Composite", className: "BlockList", modelProperties: { committedBlocks: { xmlIsWrapped: true, xmlName: "CommittedBlocks", xmlElementName: "Block", serializedName: "CommittedBlocks", type: { name: "Sequence", element: { type: { name: "Composite", className: "Block" } } } }, uncommittedBlocks: { xmlIsWrapped: true, xmlName: "UncommittedBlocks", xmlElementName: "Block", serializedName: "UncommittedBlocks", type: { name: "Sequence", element: { type: { name: "Composite", className: "Block" } } } } } } }; var BlockLookupList = { xmlName: "BlockList", serializedName: "BlockLookupList", type: { name: "Composite", className: "BlockLookupList", modelProperties: { committed: { xmlName: "Committed", xmlElementName: "Committed", serializedName: "Committed", type: { name: "Sequence", element: { type: { name: "String" } } } }, uncommitted: { xmlName: "Uncommitted", xmlElementName: "Uncommitted", serializedName: "Uncommitted", type: { name: "Sequence", element: { type: { name: "String" } } } }, latest: { xmlName: "Latest", xmlElementName: "Latest", serializedName: "Latest", type: { name: "Sequence", element: { type: { name: "String" } } } } } } }; var ContainerProperties = { serializedName: "ContainerProperties", type: { name: "Composite", className: "ContainerProperties", modelProperties: { lastModified: { xmlName: "Last-Modified", required: true, serializedName: "Last-Modified", type: { name: "DateTimeRfc1123" } }, etag: { xmlName: "Etag", required: true, serializedName: "Etag", type: { name: "String" } }, leaseStatus: { xmlName: "LeaseStatus", serializedName: "LeaseStatus", type: { name: "Enum", allowedValues: [ "locked", "unlocked" ] } }, leaseState: { xmlName: "LeaseState", serializedName: "LeaseState", type: { name: "Enum", allowedValues: [ "available", "leased", "expired", "breaking", "broken" ] } }, leaseDuration: { xmlName: "LeaseDuration", serializedName: "LeaseDuration", type: { name: "Enum", allowedValues: [ "infinite", "fixed" ] } }, publicAccess: { xmlName: "PublicAccess", serializedName: "PublicAccess", type: { name: "String" } }, hasImmutabilityPolicy: { xmlName: "HasImmutabilityPolicy", serializedName: "HasImmutabilityPolicy", type: { name: "Boolean" } }, hasLegalHold: { xmlName: "HasLegalHold", serializedName: "HasLegalHold", type: { name: "Boolean" } }, defaultEncryptionScope: { xmlName: "DefaultEncryptionScope", serializedName: "DefaultEncryptionScope", type: { name: "String" } }, preventEncryptionScopeOverride: { xmlName: "DenyEncryptionScopeOverride", serializedName: "DenyEncryptionScopeOverride", type: { name: "Boolean" } }, deletedOn: { xmlName: "DeletedTime", serializedName: "DeletedTime", type: { name: "DateTimeRfc1123" } }, remainingRetentionDays: { xmlName: "RemainingRetentionDays", serializedName: "RemainingRetentionDays", type: { name: "Number" } } } } }; var ContainerItem = { xmlName: "Container", serializedName: "ContainerItem", type: { name: "Composite", className: "ContainerItem", modelProperties: { name: { xmlName: "Name", required: true, serializedName: "Name", type: { name: "String" } }, deleted: { xmlName: "Deleted", serializedName: "Deleted", type: { name: "Boolean" } }, version: { xmlName: "Version", serializedName: "Version", type: { name: "String" } }, properties: { xmlName: "Properties", required: true, serializedName: "Properties", type: { name: "Composite", className: "ContainerProperties" } }, metadata: { xmlName: "Metadata", serializedName: "Metadata", type: { name: "Dictionary", value: { type: { name: "String" } } } } } } }; var DelimitedTextConfiguration = { serializedName: "DelimitedTextConfiguration", type: { name: "Composite", className: "DelimitedTextConfiguration", modelProperties: { columnSeparator: { xmlName: "ColumnSeparator", required: true, serializedName: "ColumnSeparator", type: { name: "String" } }, fieldQuote: { xmlName: "FieldQuote", required: true, serializedName: "FieldQuote", type: { name: "String" } }, recordSeparator: { xmlName: "RecordSeparator", required: true, serializedName: "RecordSeparator", type: { name: "String" } }, escapeChar: { xmlName: "EscapeChar", required: true, serializedName: "EscapeChar", type: { name: "String" } }, headersPresent: { xmlName: "HasHeaders", required: true, serializedName: "HeadersPresent", type: { name: "Boolean" } } } } }; var JsonTextConfiguration = { serializedName: "JsonTextConfiguration", type: { name: "Composite", className: "JsonTextConfiguration", modelProperties: { recordSeparator: { xmlName: "RecordSeparator", required: true, serializedName: "RecordSeparator", type: { name: "String" } } } } }; var ArrowField = { xmlName: "Field", serializedName: "ArrowField", type: { name: "Composite", className: "ArrowField", modelProperties: { type: { xmlName: "Type", required: true, serializedName: "Type", type: { name: "String" } }, name: { xmlName: "Name", serializedName: "Name", type: { name: "String" } }, precision: { xmlName: "Precision", serializedName: "Precision", type: { name: "Number" } }, scale: { xmlName: "Scale", serializedName: "Scale", type: { name: "Number" } } } } }; var ArrowConfiguration = { serializedName: "ArrowConfiguration", type: { name: "Composite", className: "ArrowConfiguration", modelProperties: { schema: { xmlIsWrapped: true, xmlName: "Schema", xmlElementName: "Field", required: true, serializedName: "Schema", type: { name: "Sequence", element: { type: { name: "Composite", className: "ArrowField" } } } } } } }; var ListContainersSegmentResponse = { xmlName: "EnumerationResults", serializedName: "ListContainersSegmentResponse", type: { name: "Composite", className: "ListContainersSegmentResponse", modelProperties: { serviceEndpoint: { xmlIsAttribute: true, xmlName: "ServiceEndpoint", required: true, serializedName: "ServiceEndpoint", type: { name: "String" } }, prefix: { xmlName: "Prefix", serializedName: "Prefix", type: { name: "String" } }, marker: { xmlName: "Marker", serializedName: "Marker", type: { name: "String" } }, maxPageSize: { xmlName: "MaxResults", serializedName: "MaxResults", type: { name: "Number" } }, containerItems: { xmlIsWrapped: true, xmlName: "Containers", xmlElementName: "Container", required: true, serializedName: "ContainerItems", type: { name: "Sequence", element: { type: { name: "Composite", className: "ContainerItem" } } } }, continuationToken: { xmlName: "NextMarker", serializedName: "NextMarker", type: { name: "String" } } } } }; var CorsRule = { serializedName: "CorsRule", type: { name: "Composite", className: "CorsRule", modelProperties: { allowedOrigins: { xmlName: "AllowedOrigins", required: true, serializedName: "AllowedOrigins", type: { name: "String" } }, allowedMethods: { xmlName: "AllowedMethods", required: true, serializedName: "AllowedMethods", type: { name: "String" } }, allowedHeaders: { xmlName: "AllowedHeaders", required: true, serializedName: "AllowedHeaders", type: { name: "String" } }, exposedHeaders: { xmlName: "ExposedHeaders", required: true, serializedName: "ExposedHeaders", type: { name: "String" } }, maxAgeInSeconds: { xmlName: "MaxAgeInSeconds", required: true, serializedName: "MaxAgeInSeconds", constraints: { InclusiveMinimum: 0 }, type: { name: "Number" } } } } }; var FilterBlobItem = { xmlName: "Blob", serializedName: "FilterBlobItem", type: { name: "Composite", className: "FilterBlobItem", modelProperties: { name: { xmlName: "Name", required: true, serializedName: "Name", type: { name: "String" } }, containerName: { xmlName: "ContainerName", required: true, serializedName: "ContainerName", type: { name: "String" } }, tagValue: { xmlName: "TagValue", required: true, serializedName: "TagValue", type: { name: "String" } } } } }; var FilterBlobSegment = { xmlName: "EnumerationResults", serializedName: "FilterBlobSegment", type: { name: "Composite", className: "FilterBlobSegment", modelProperties: { serviceEndpoint: { xmlIsAttribute: true, xmlName: "ServiceEndpoint", required: true, serializedName: "ServiceEndpoint", type: { name: "String" } }, where: { xmlName: "Where", required: true, serializedName: "Where", type: { name: "String" } }, blobs: { xmlIsWrapped: true, xmlName: "Blobs", xmlElementName: "Blob", required: true, serializedName: "Blobs", type: { name: "Sequence", element: { type: { name: "Composite", className: "FilterBlobItem" } } } }, continuationToken: { xmlName: "NextMarker", serializedName: "NextMarker", type: { name: "String" } } } } }; var GeoReplication = { serializedName: "GeoReplication", type: { name: "Composite", className: "GeoReplication", modelProperties: { status: { xmlName: "Status", required: true, serializedName: "Status", type: { name: "String" } }, lastSyncOn: { xmlName: "LastSyncTime", required: true, serializedName: "LastSyncTime", type: { name: "DateTimeRfc1123" } } } } }; var RetentionPolicy = { serializedName: "RetentionPolicy", type: { name: "Composite", className: "RetentionPolicy", modelProperties: { enabled: { xmlName: "Enabled", required: true, serializedName: "Enabled", type: { name: "Boolean" } }, days: { xmlName: "Days", serializedName: "Days", constraints: { InclusiveMinimum: 1 }, type: { name: "Number" } } } } }; var Logging = { serializedName: "Logging", type: { name: "Composite", className: "Logging", modelProperties: { version: { xmlName: "Version", required: true, serializedName: "Version", type: { name: "String" } }, deleteProperty: { xmlName: "Delete", required: true, serializedName: "Delete", type: { name: "Boolean" } }, read: { xmlName: "Read", required: true, serializedName: "Read", type: { name: "Boolean" } }, write: { xmlName: "Write", required: true, serializedName: "Write", type: { name: "Boolean" } }, retentionPolicy: { xmlName: "RetentionPolicy", required: true, serializedName: "RetentionPolicy", type: { name: "Composite", className: "RetentionPolicy" } } } } }; var Metrics = { serializedName: "Metrics", type: { name: "Composite", className: "Metrics", modelProperties: { version: { xmlName: "Version", serializedName: "Version", type: { name: "String" } }, enabled: { xmlName: "Enabled", required: true, serializedName: "Enabled", type: { name: "Boolean" } }, includeAPIs: { xmlName: "IncludeAPIs", serializedName: "IncludeAPIs", type: { name: "Boolean" } }, retentionPolicy: { xmlName: "RetentionPolicy", serializedName: "RetentionPolicy", type: { name: "Composite", className: "RetentionPolicy" } } } } }; var PageRange = { serializedName: "PageRange", type: { name: "Composite", className: "PageRange", modelProperties: { start: { xmlName: "Start", required: true, serializedName: "Start", type: { name: "Number" } }, end: { xmlName: "End", required: true, serializedName: "End", type: { name: "Number" } } } } }; var ClearRange = { serializedName: "ClearRange", type: { name: "Composite", className: "ClearRange", modelProperties: { start: { xmlName: "Start", required: true, serializedName: "Start", type: { name: "Number" } }, end: { xmlName: "End", required: true, serializedName: "End", type: { name: "Number" } } } } }; var PageList = { serializedName: "PageList", type: { name: "Composite", className: "PageList", modelProperties: { pageRange: { xmlName: "PageRange", xmlElementName: "PageRange", serializedName: "PageRange", type: { name: "Sequence", element: { type: { name: "Composite", className: "PageRange" } } } }, clearRange: { xmlName: "ClearRange", xmlElementName: "ClearRange", serializedName: "ClearRange", type: { name: "Sequence", element: { type: { name: "Composite", className: "ClearRange" } } } } } } }; var QueryFormat = { serializedName: "QueryFormat", type: { name: "Composite", className: "QueryFormat", modelProperties: { type: { xmlName: "Type", serializedName: "Type", type: { name: "Enum", allowedValues: [ "delimited", "json", "arrow" ] } }, delimitedTextConfiguration: { xmlName: "DelimitedTextConfiguration", serializedName: "DelimitedTextConfiguration", type: { name: "Composite", className: "DelimitedTextConfiguration" } }, jsonTextConfiguration: { xmlName: "JsonTextConfiguration", serializedName: "JsonTextConfiguration", type: { name: "Composite", className: "JsonTextConfiguration" } }, arrowConfiguration: { xmlName: "ArrowConfiguration", serializedName: "ArrowConfiguration", type: { name: "Composite", className: "ArrowConfiguration" } } } } }; var QuerySerialization = { serializedName: "QuerySerialization", type: { name: "Composite", className: "QuerySerialization", modelProperties: { format: { xmlName: "Format", required: true, serializedName: "Format", type: { name: "Composite", className: "QueryFormat" } } } } }; var QueryRequest = { serializedName: "QueryRequest", type: { name: "Composite", className: "QueryRequest", modelProperties: { queryType: { xmlName: "QueryType", required: true, isConstant: true, serializedName: "QueryType", defaultValue: 'SQL', type: { name: "String" } }, expression: { xmlName: "Expression", required: true, serializedName: "Expression", type: { name: "String" } }, inputSerialization: { xmlName: "InputSerialization", serializedName: "InputSerialization", type: { name: "Composite", className: "QuerySerialization" } }, outputSerialization: { xmlName: "OutputSerialization", serializedName: "OutputSerialization", type: { name: "Composite", className: "QuerySerialization" } } } } }; var SignedIdentifier = { serializedName: "SignedIdentifier", type: { name: "Composite", className: "SignedIdentifier", modelProperties: { id: { xmlName: "Id", required: true, serializedName: "Id", type: { name: "String" } }, accessPolicy: { xmlName: "AccessPolicy", required: true, serializedName: "AccessPolicy", type: { name: "Composite", className: "AccessPolicy" } } } } }; var StaticWebsite = { serializedName: "StaticWebsite", type: { name: "Composite", className: "StaticWebsite", modelProperties: { enabled: { xmlName: "Enabled", required: true, serializedName: "Enabled", type: { name: "Boolean" } }, indexDocument: { xmlName: "IndexDocument", serializedName: "IndexDocument", type: { name: "String" } }, errorDocument404Path: { xmlName: "ErrorDocument404Path", serializedName: "ErrorDocument404Path", type: { name: "String" } }, defaultIndexDocumentPath: { xmlName: "DefaultIndexDocumentPath", serializedName: "DefaultIndexDocumentPath", type: { name: "String" } } } } }; var BlobServiceProperties = { xmlName: "StorageServiceProperties", serializedName: "BlobServiceProperties", type: { name: "Composite", className: "BlobServiceProperties", modelProperties: { blobAnalyticsLogging: { xmlName: "Logging", serializedName: "Logging", type: { name: "Composite", className: "Logging" } }, hourMetrics: { xmlName: "HourMetrics", serializedName: "HourMetrics", type: { name: "Composite", className: "Metrics" } }, minuteMetrics: { xmlName: "MinuteMetrics", serializedName: "MinuteMetrics", type: { name: "Composite", className: "Metrics" } }, cors: { xmlIsWrapped: true, xmlName: "Cors", xmlElementName: "CorsRule", serializedName: "Cors", type: { name: "Sequence", element: { type: { name: "Composite", className: "CorsRule" } } } }, defaultServiceVersion: { xmlName: "DefaultServiceVersion", serializedName: "DefaultServiceVersion", type: { name: "String" } }, deleteRetentionPolicy: { xmlName: "DeleteRetentionPolicy", serializedName: "DeleteRetentionPolicy", type: { name: "Composite", className: "RetentionPolicy" } }, staticWebsite: { xmlName: "StaticWebsite", serializedName: "StaticWebsite", type: { name: "Composite", className: "StaticWebsite" } } } } }; var BlobServiceStatistics = { xmlName: "StorageServiceStats", serializedName: "BlobServiceStatistics", type: { name: "Composite", className: "BlobServiceStatistics", modelProperties: { geoReplication: { xmlName: "GeoReplication", serializedName: "GeoReplication", type: { name: "Composite", className: "GeoReplication" } } } } }; var ServiceSetPropertiesHeaders = { serializedName: "service-setproperties-headers", type: { name: "Composite", className: "ServiceSetPropertiesHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ServiceGetPropertiesHeaders = { serializedName: "service-getproperties-headers", type: { name: "Composite", className: "ServiceGetPropertiesHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ServiceGetStatisticsHeaders = { serializedName: "service-getstatistics-headers", type: { name: "Composite", className: "ServiceGetStatisticsHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ServiceListContainersSegmentHeaders = { serializedName: "service-listcontainerssegment-headers", type: { name: "Composite", className: "ServiceListContainersSegmentHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ServiceGetUserDelegationKeyHeaders = { serializedName: "service-getuserdelegationkey-headers", type: { name: "Composite", className: "ServiceGetUserDelegationKeyHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ServiceGetAccountInfoHeaders = { serializedName: "service-getaccountinfo-headers", type: { name: "Composite", className: "ServiceGetAccountInfoHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, skuName: { serializedName: "x-ms-sku-name", type: { name: "Enum", allowedValues: [ "Standard_LRS", "Standard_GRS", "Standard_RAGRS", "Standard_ZRS", "Premium_LRS" ] } }, accountKind: { serializedName: "x-ms-account-kind", type: { name: "Enum", allowedValues: [ "Storage", "BlobStorage", "StorageV2", "FileStorage", "BlockBlobStorage" ] } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ServiceSubmitBatchHeaders = { serializedName: "service-submitbatch-headers", type: { name: "Composite", className: "ServiceSubmitBatchHeaders", modelProperties: { contentType: { serializedName: "content-type", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ServiceFilterBlobsHeaders = { serializedName: "service-filterblobs-headers", type: { name: "Composite", className: "ServiceFilterBlobsHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ContainerCreateHeaders = { serializedName: "container-create-headers", type: { name: "Composite", className: "ContainerCreateHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ContainerGetPropertiesHeaders = { serializedName: "container-getproperties-headers", type: { name: "Composite", className: "ContainerGetPropertiesHeaders", modelProperties: { metadata: { serializedName: "x-ms-meta", type: { name: "Dictionary", value: { type: { name: "String" } } }, headerCollectionPrefix: "x-ms-meta-" }, etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, leaseDuration: { serializedName: "x-ms-lease-duration", type: { name: "Enum", allowedValues: [ "infinite", "fixed" ] } }, leaseState: { serializedName: "x-ms-lease-state", type: { name: "Enum", allowedValues: [ "available", "leased", "expired", "breaking", "broken" ] } }, leaseStatus: { serializedName: "x-ms-lease-status", type: { name: "Enum", allowedValues: [ "locked", "unlocked" ] } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, blobPublicAccess: { serializedName: "x-ms-blob-public-access", type: { name: "String" } }, hasImmutabilityPolicy: { serializedName: "x-ms-has-immutability-policy", type: { name: "Boolean" } }, hasLegalHold: { serializedName: "x-ms-has-legal-hold", type: { name: "Boolean" } }, defaultEncryptionScope: { serializedName: "x-ms-default-encryption-scope", type: { name: "String" } }, denyEncryptionScopeOverride: { serializedName: "x-ms-deny-encryption-scope-override", type: { name: "Boolean" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ContainerDeleteHeaders = { serializedName: "container-delete-headers", type: { name: "Composite", className: "ContainerDeleteHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ContainerSetMetadataHeaders = { serializedName: "container-setmetadata-headers", type: { name: "Composite", className: "ContainerSetMetadataHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ContainerGetAccessPolicyHeaders = { serializedName: "container-getaccesspolicy-headers", type: { name: "Composite", className: "ContainerGetAccessPolicyHeaders", modelProperties: { blobPublicAccess: { serializedName: "x-ms-blob-public-access", type: { name: "String" } }, etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ContainerSetAccessPolicyHeaders = { serializedName: "container-setaccesspolicy-headers", type: { name: "Composite", className: "ContainerSetAccessPolicyHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ContainerRestoreHeaders = { serializedName: "container-restore-headers", type: { name: "Composite", className: "ContainerRestoreHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ContainerAcquireLeaseHeaders = { serializedName: "container-acquirelease-headers", type: { name: "Composite", className: "ContainerAcquireLeaseHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, leaseId: { serializedName: "x-ms-lease-id", type: { name: "String" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ContainerReleaseLeaseHeaders = { serializedName: "container-releaselease-headers", type: { name: "Composite", className: "ContainerReleaseLeaseHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ContainerRenewLeaseHeaders = { serializedName: "container-renewlease-headers", type: { name: "Composite", className: "ContainerRenewLeaseHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, leaseId: { serializedName: "x-ms-lease-id", type: { name: "String" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ContainerBreakLeaseHeaders = { serializedName: "container-breaklease-headers", type: { name: "Composite", className: "ContainerBreakLeaseHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, leaseTime: { serializedName: "x-ms-lease-time", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ContainerChangeLeaseHeaders = { serializedName: "container-changelease-headers", type: { name: "Composite", className: "ContainerChangeLeaseHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, leaseId: { serializedName: "x-ms-lease-id", type: { name: "String" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ContainerListBlobFlatSegmentHeaders = { serializedName: "container-listblobflatsegment-headers", type: { name: "Composite", className: "ContainerListBlobFlatSegmentHeaders", modelProperties: { contentType: { serializedName: "content-type", type: { name: "String" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ContainerListBlobHierarchySegmentHeaders = { serializedName: "container-listblobhierarchysegment-headers", type: { name: "Composite", className: "ContainerListBlobHierarchySegmentHeaders", modelProperties: { contentType: { serializedName: "content-type", type: { name: "String" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var ContainerGetAccountInfoHeaders = { serializedName: "container-getaccountinfo-headers", type: { name: "Composite", className: "ContainerGetAccountInfoHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, skuName: { serializedName: "x-ms-sku-name", type: { name: "Enum", allowedValues: [ "Standard_LRS", "Standard_GRS", "Standard_RAGRS", "Standard_ZRS", "Premium_LRS" ] } }, accountKind: { serializedName: "x-ms-account-kind", type: { name: "Enum", allowedValues: [ "Storage", "BlobStorage", "StorageV2", "FileStorage", "BlockBlobStorage" ] } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobDownloadHeaders = { serializedName: "blob-download-headers", type: { name: "Composite", className: "BlobDownloadHeaders", modelProperties: { lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, metadata: { serializedName: "x-ms-meta", type: { name: "Dictionary", value: { type: { name: "String" } } }, headerCollectionPrefix: "x-ms-meta-" }, objectReplicationPolicyId: { serializedName: "x-ms-or-policy-id", type: { name: "String" } }, objectReplicationRules: { serializedName: "x-ms-or", type: { name: "Dictionary", value: { type: { name: "String" } } }, headerCollectionPrefix: "x-ms-or-" }, contentLength: { serializedName: "content-length", type: { name: "Number" } }, contentType: { serializedName: "content-type", type: { name: "String" } }, contentRange: { serializedName: "content-range", type: { name: "String" } }, etag: { serializedName: "etag", type: { name: "String" } }, contentMD5: { serializedName: "content-md5", type: { name: "ByteArray" } }, contentEncoding: { serializedName: "content-encoding", type: { name: "String" } }, cacheControl: { serializedName: "cache-control", type: { name: "String" } }, contentDisposition: { serializedName: "content-disposition", type: { name: "String" } }, contentLanguage: { serializedName: "content-language", type: { name: "String" } }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", type: { name: "Number" } }, blobType: { serializedName: "x-ms-blob-type", type: { name: "Enum", allowedValues: [ "BlockBlob", "PageBlob", "AppendBlob" ] } }, copyCompletedOn: { serializedName: "x-ms-copy-completion-time", type: { name: "DateTimeRfc1123" } }, copyStatusDescription: { serializedName: "x-ms-copy-status-description", type: { name: "String" } }, copyId: { serializedName: "x-ms-copy-id", type: { name: "String" } }, copyProgress: { serializedName: "x-ms-copy-progress", type: { name: "String" } }, copySource: { serializedName: "x-ms-copy-source", type: { name: "String" } }, copyStatus: { serializedName: "x-ms-copy-status", type: { name: "Enum", allowedValues: [ "pending", "success", "aborted", "failed" ] } }, leaseDuration: { serializedName: "x-ms-lease-duration", type: { name: "Enum", allowedValues: [ "infinite", "fixed" ] } }, leaseState: { serializedName: "x-ms-lease-state", type: { name: "Enum", allowedValues: [ "available", "leased", "expired", "breaking", "broken" ] } }, leaseStatus: { serializedName: "x-ms-lease-status", type: { name: "Enum", allowedValues: [ "locked", "unlocked" ] } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, versionId: { serializedName: "x-ms-version-id", type: { name: "String" } }, acceptRanges: { serializedName: "accept-ranges", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, blobCommittedBlockCount: { serializedName: "x-ms-blob-committed-block-count", type: { name: "Number" } }, isServerEncrypted: { serializedName: "x-ms-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", type: { name: "String" } }, blobContentMD5: { serializedName: "x-ms-blob-content-md5", type: { name: "ByteArray" } }, tagCount: { serializedName: "x-ms-tag-count", type: { name: "Number" } }, isSealed: { serializedName: "x-ms-blob-sealed", type: { name: "Boolean" } }, lastAccessed: { serializedName: "x-ms-last-access-time", type: { name: "DateTimeRfc1123" } }, contentCrc64: { serializedName: "x-ms-content-crc64", type: { name: "ByteArray" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobGetPropertiesHeaders = { serializedName: "blob-getproperties-headers", type: { name: "Composite", className: "BlobGetPropertiesHeaders", modelProperties: { lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, createdOn: { serializedName: "x-ms-creation-time", type: { name: "DateTimeRfc1123" } }, metadata: { serializedName: "x-ms-meta", type: { name: "Dictionary", value: { type: { name: "String" } } }, headerCollectionPrefix: "x-ms-meta-" }, objectReplicationPolicyId: { serializedName: "x-ms-or-policy-id", type: { name: "String" } }, objectReplicationRules: { serializedName: "x-ms-or", type: { name: "Dictionary", value: { type: { name: "String" } } }, headerCollectionPrefix: "x-ms-or-" }, blobType: { serializedName: "x-ms-blob-type", type: { name: "Enum", allowedValues: [ "BlockBlob", "PageBlob", "AppendBlob" ] } }, copyCompletedOn: { serializedName: "x-ms-copy-completion-time", type: { name: "DateTimeRfc1123" } }, copyStatusDescription: { serializedName: "x-ms-copy-status-description", type: { name: "String" } }, copyId: { serializedName: "x-ms-copy-id", type: { name: "String" } }, copyProgress: { serializedName: "x-ms-copy-progress", type: { name: "String" } }, copySource: { serializedName: "x-ms-copy-source", type: { name: "String" } }, copyStatus: { serializedName: "x-ms-copy-status", type: { name: "Enum", allowedValues: [ "pending", "success", "aborted", "failed" ] } }, isIncrementalCopy: { serializedName: "x-ms-incremental-copy", type: { name: "Boolean" } }, destinationSnapshot: { serializedName: "x-ms-copy-destination-snapshot", type: { name: "String" } }, leaseDuration: { serializedName: "x-ms-lease-duration", type: { name: "Enum", allowedValues: [ "infinite", "fixed" ] } }, leaseState: { serializedName: "x-ms-lease-state", type: { name: "Enum", allowedValues: [ "available", "leased", "expired", "breaking", "broken" ] } }, leaseStatus: { serializedName: "x-ms-lease-status", type: { name: "Enum", allowedValues: [ "locked", "unlocked" ] } }, contentLength: { serializedName: "content-length", type: { name: "Number" } }, contentType: { serializedName: "content-type", type: { name: "String" } }, etag: { serializedName: "etag", type: { name: "String" } }, contentMD5: { serializedName: "content-md5", type: { name: "ByteArray" } }, contentEncoding: { serializedName: "content-encoding", type: { name: "String" } }, contentDisposition: { serializedName: "content-disposition", type: { name: "String" } }, contentLanguage: { serializedName: "content-language", type: { name: "String" } }, cacheControl: { serializedName: "cache-control", type: { name: "String" } }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, acceptRanges: { serializedName: "accept-ranges", type: { name: "String" } }, blobCommittedBlockCount: { serializedName: "x-ms-blob-committed-block-count", type: { name: "Number" } }, isServerEncrypted: { serializedName: "x-ms-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", type: { name: "String" } }, accessTier: { serializedName: "x-ms-access-tier", type: { name: "String" } }, accessTierInferred: { serializedName: "x-ms-access-tier-inferred", type: { name: "Boolean" } }, archiveStatus: { serializedName: "x-ms-archive-status", type: { name: "String" } }, accessTierChangedOn: { serializedName: "x-ms-access-tier-change-time", type: { name: "DateTimeRfc1123" } }, versionId: { serializedName: "x-ms-version-id", type: { name: "String" } }, isCurrentVersion: { serializedName: "x-ms-is-current-version", type: { name: "Boolean" } }, tagCount: { serializedName: "x-ms-tag-count", type: { name: "Number" } }, expiresOn: { serializedName: "x-ms-expiry-time", type: { name: "DateTimeRfc1123" } }, isSealed: { serializedName: "x-ms-blob-sealed", type: { name: "Boolean" } }, rehydratePriority: { serializedName: "x-ms-rehydrate-priority", type: { name: "String" } }, lastAccessed: { serializedName: "x-ms-last-access-time", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobDeleteHeaders = { serializedName: "blob-delete-headers", type: { name: "Composite", className: "BlobDeleteHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobSetAccessControlHeaders = { serializedName: "blob-setaccesscontrol-headers", type: { name: "Composite", className: "BlobSetAccessControlHeaders", modelProperties: { date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } } } } }; var BlobGetAccessControlHeaders = { serializedName: "blob-getaccesscontrol-headers", type: { name: "Composite", className: "BlobGetAccessControlHeaders", modelProperties: { date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, xMsOwner: { serializedName: "x-ms-owner", type: { name: "String" } }, xMsGroup: { serializedName: "x-ms-group", type: { name: "String" } }, xMsPermissions: { serializedName: "x-ms-permissions", type: { name: "String" } }, xMsAcl: { serializedName: "x-ms-acl", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } } } } }; var BlobRenameHeaders = { serializedName: "blob-rename-headers", type: { name: "Composite", className: "BlobRenameHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, contentLength: { serializedName: "content-length", type: { name: "Number" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } } } } }; var PageBlobCreateHeaders = { serializedName: "pageblob-create-headers", type: { name: "Composite", className: "PageBlobCreateHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, contentMD5: { serializedName: "content-md5", type: { name: "ByteArray" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, versionId: { serializedName: "x-ms-version-id", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var AppendBlobCreateHeaders = { serializedName: "appendblob-create-headers", type: { name: "Composite", className: "AppendBlobCreateHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, contentMD5: { serializedName: "content-md5", type: { name: "ByteArray" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, versionId: { serializedName: "x-ms-version-id", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlockBlobUploadHeaders = { serializedName: "blockblob-upload-headers", type: { name: "Composite", className: "BlockBlobUploadHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, contentMD5: { serializedName: "content-md5", type: { name: "ByteArray" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, versionId: { serializedName: "x-ms-version-id", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobUndeleteHeaders = { serializedName: "blob-undelete-headers", type: { name: "Composite", className: "BlobUndeleteHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobSetExpiryHeaders = { serializedName: "blob-setexpiry-headers", type: { name: "Composite", className: "BlobSetExpiryHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobSetHTTPHeadersHeaders = { serializedName: "blob-sethttpheaders-headers", type: { name: "Composite", className: "BlobSetHTTPHeadersHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobSetMetadataHeaders = { serializedName: "blob-setmetadata-headers", type: { name: "Composite", className: "BlobSetMetadataHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, versionId: { serializedName: "x-ms-version-id", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobAcquireLeaseHeaders = { serializedName: "blob-acquirelease-headers", type: { name: "Composite", className: "BlobAcquireLeaseHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, leaseId: { serializedName: "x-ms-lease-id", type: { name: "String" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobReleaseLeaseHeaders = { serializedName: "blob-releaselease-headers", type: { name: "Composite", className: "BlobReleaseLeaseHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobRenewLeaseHeaders = { serializedName: "blob-renewlease-headers", type: { name: "Composite", className: "BlobRenewLeaseHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, leaseId: { serializedName: "x-ms-lease-id", type: { name: "String" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobChangeLeaseHeaders = { serializedName: "blob-changelease-headers", type: { name: "Composite", className: "BlobChangeLeaseHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, leaseId: { serializedName: "x-ms-lease-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobBreakLeaseHeaders = { serializedName: "blob-breaklease-headers", type: { name: "Composite", className: "BlobBreakLeaseHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, leaseTime: { serializedName: "x-ms-lease-time", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobCreateSnapshotHeaders = { serializedName: "blob-createsnapshot-headers", type: { name: "Composite", className: "BlobCreateSnapshotHeaders", modelProperties: { snapshot: { serializedName: "x-ms-snapshot", type: { name: "String" } }, etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, versionId: { serializedName: "x-ms-version-id", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobStartCopyFromURLHeaders = { serializedName: "blob-startcopyfromurl-headers", type: { name: "Composite", className: "BlobStartCopyFromURLHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, versionId: { serializedName: "x-ms-version-id", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, copyId: { serializedName: "x-ms-copy-id", type: { name: "String" } }, copyStatus: { serializedName: "x-ms-copy-status", type: { name: "Enum", allowedValues: [ "pending", "success", "aborted", "failed" ] } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobCopyFromURLHeaders = { serializedName: "blob-copyfromurl-headers", type: { name: "Composite", className: "BlobCopyFromURLHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, versionId: { serializedName: "x-ms-version-id", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, copyId: { serializedName: "x-ms-copy-id", type: { name: "String" } }, copyStatus: { serializedName: "x-ms-copy-status", type: { name: "Enum", allowedValues: [ "success" ] } }, contentMD5: { serializedName: "content-md5", type: { name: "ByteArray" } }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", type: { name: "ByteArray" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobAbortCopyFromURLHeaders = { serializedName: "blob-abortcopyfromurl-headers", type: { name: "Composite", className: "BlobAbortCopyFromURLHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobSetTierHeaders = { serializedName: "blob-settier-headers", type: { name: "Composite", className: "BlobSetTierHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobGetAccountInfoHeaders = { serializedName: "blob-getaccountinfo-headers", type: { name: "Composite", className: "BlobGetAccountInfoHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, skuName: { serializedName: "x-ms-sku-name", type: { name: "Enum", allowedValues: [ "Standard_LRS", "Standard_GRS", "Standard_RAGRS", "Standard_ZRS", "Premium_LRS" ] } }, accountKind: { serializedName: "x-ms-account-kind", type: { name: "Enum", allowedValues: [ "Storage", "BlobStorage", "StorageV2", "FileStorage", "BlockBlobStorage" ] } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlockBlobStageBlockHeaders = { serializedName: "blockblob-stageblock-headers", type: { name: "Composite", className: "BlockBlobStageBlockHeaders", modelProperties: { contentMD5: { serializedName: "content-md5", type: { name: "ByteArray" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", type: { name: "ByteArray" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlockBlobStageBlockFromURLHeaders = { serializedName: "blockblob-stageblockfromurl-headers", type: { name: "Composite", className: "BlockBlobStageBlockFromURLHeaders", modelProperties: { contentMD5: { serializedName: "content-md5", type: { name: "ByteArray" } }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", type: { name: "ByteArray" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlockBlobCommitBlockListHeaders = { serializedName: "blockblob-commitblocklist-headers", type: { name: "Composite", className: "BlockBlobCommitBlockListHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, contentMD5: { serializedName: "content-md5", type: { name: "ByteArray" } }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", type: { name: "ByteArray" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, versionId: { serializedName: "x-ms-version-id", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlockBlobGetBlockListHeaders = { serializedName: "blockblob-getblocklist-headers", type: { name: "Composite", className: "BlockBlobGetBlockListHeaders", modelProperties: { lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, etag: { serializedName: "etag", type: { name: "String" } }, contentType: { serializedName: "content-type", type: { name: "String" } }, blobContentLength: { serializedName: "x-ms-blob-content-length", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var PageBlobUploadPagesHeaders = { serializedName: "pageblob-uploadpages-headers", type: { name: "Composite", className: "PageBlobUploadPagesHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, contentMD5: { serializedName: "content-md5", type: { name: "ByteArray" } }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", type: { name: "ByteArray" } }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var PageBlobClearPagesHeaders = { serializedName: "pageblob-clearpages-headers", type: { name: "Composite", className: "PageBlobClearPagesHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, contentMD5: { serializedName: "content-md5", type: { name: "ByteArray" } }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", type: { name: "ByteArray" } }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var PageBlobUploadPagesFromURLHeaders = { serializedName: "pageblob-uploadpagesfromurl-headers", type: { name: "Composite", className: "PageBlobUploadPagesFromURLHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, contentMD5: { serializedName: "content-md5", type: { name: "ByteArray" } }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", type: { name: "ByteArray" } }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", type: { name: "Number" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var PageBlobGetPageRangesHeaders = { serializedName: "pageblob-getpageranges-headers", type: { name: "Composite", className: "PageBlobGetPageRangesHeaders", modelProperties: { lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, etag: { serializedName: "etag", type: { name: "String" } }, blobContentLength: { serializedName: "x-ms-blob-content-length", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var PageBlobGetPageRangesDiffHeaders = { serializedName: "pageblob-getpagerangesdiff-headers", type: { name: "Composite", className: "PageBlobGetPageRangesDiffHeaders", modelProperties: { lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, etag: { serializedName: "etag", type: { name: "String" } }, blobContentLength: { serializedName: "x-ms-blob-content-length", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var PageBlobResizeHeaders = { serializedName: "pageblob-resize-headers", type: { name: "Composite", className: "PageBlobResizeHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var PageBlobUpdateSequenceNumberHeaders = { serializedName: "pageblob-updatesequencenumber-headers", type: { name: "Composite", className: "PageBlobUpdateSequenceNumberHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", type: { name: "Number" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var PageBlobCopyIncrementalHeaders = { serializedName: "pageblob-copyincremental-headers", type: { name: "Composite", className: "PageBlobCopyIncrementalHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, copyId: { serializedName: "x-ms-copy-id", type: { name: "String" } }, copyStatus: { serializedName: "x-ms-copy-status", type: { name: "Enum", allowedValues: [ "pending", "success", "aborted", "failed" ] } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var AppendBlobAppendBlockHeaders = { serializedName: "appendblob-appendblock-headers", type: { name: "Composite", className: "AppendBlobAppendBlockHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, contentMD5: { serializedName: "content-md5", type: { name: "ByteArray" } }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", type: { name: "ByteArray" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, blobAppendOffset: { serializedName: "x-ms-blob-append-offset", type: { name: "String" } }, blobCommittedBlockCount: { serializedName: "x-ms-blob-committed-block-count", type: { name: "Number" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", type: { name: "String" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var AppendBlobAppendBlockFromUrlHeaders = { serializedName: "appendblob-appendblockfromurl-headers", type: { name: "Composite", className: "AppendBlobAppendBlockFromUrlHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, contentMD5: { serializedName: "content-md5", type: { name: "ByteArray" } }, xMsContentCrc64: { serializedName: "x-ms-content-crc64", type: { name: "ByteArray" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, blobAppendOffset: { serializedName: "x-ms-blob-append-offset", type: { name: "String" } }, blobCommittedBlockCount: { serializedName: "x-ms-blob-committed-block-count", type: { name: "Number" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", type: { name: "String" } }, isServerEncrypted: { serializedName: "x-ms-request-server-encrypted", type: { name: "Boolean" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var AppendBlobSealHeaders = { serializedName: "appendblob-seal-headers", type: { name: "Composite", className: "AppendBlobSealHeaders", modelProperties: { etag: { serializedName: "etag", type: { name: "String" } }, lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, isSealed: { serializedName: "x-ms-blob-sealed", type: { name: "Boolean" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobQueryHeaders = { serializedName: "blob-query-headers", type: { name: "Composite", className: "BlobQueryHeaders", modelProperties: { lastModified: { serializedName: "last-modified", type: { name: "DateTimeRfc1123" } }, metadata: { serializedName: "x-ms-meta", type: { name: "Dictionary", value: { type: { name: "String" } } }, headerCollectionPrefix: "x-ms-meta-" }, contentLength: { serializedName: "content-length", type: { name: "Number" } }, contentType: { serializedName: "content-type", type: { name: "String" } }, contentRange: { serializedName: "content-range", type: { name: "String" } }, etag: { serializedName: "etag", type: { name: "String" } }, contentMD5: { serializedName: "content-md5", type: { name: "ByteArray" } }, contentEncoding: { serializedName: "content-encoding", type: { name: "String" } }, cacheControl: { serializedName: "cache-control", type: { name: "String" } }, contentDisposition: { serializedName: "content-disposition", type: { name: "String" } }, contentLanguage: { serializedName: "content-language", type: { name: "String" } }, blobSequenceNumber: { serializedName: "x-ms-blob-sequence-number", type: { name: "Number" } }, blobType: { serializedName: "x-ms-blob-type", type: { name: "Enum", allowedValues: [ "BlockBlob", "PageBlob", "AppendBlob" ] } }, copyCompletionTime: { serializedName: "x-ms-copy-completion-time", type: { name: "DateTimeRfc1123" } }, copyStatusDescription: { serializedName: "x-ms-copy-status-description", type: { name: "String" } }, copyId: { serializedName: "x-ms-copy-id", type: { name: "String" } }, copyProgress: { serializedName: "x-ms-copy-progress", type: { name: "String" } }, copySource: { serializedName: "x-ms-copy-source", type: { name: "String" } }, copyStatus: { serializedName: "x-ms-copy-status", type: { name: "Enum", allowedValues: [ "pending", "success", "aborted", "failed" ] } }, leaseDuration: { serializedName: "x-ms-lease-duration", type: { name: "Enum", allowedValues: [ "infinite", "fixed" ] } }, leaseState: { serializedName: "x-ms-lease-state", type: { name: "Enum", allowedValues: [ "available", "leased", "expired", "breaking", "broken" ] } }, leaseStatus: { serializedName: "x-ms-lease-status", type: { name: "Enum", allowedValues: [ "locked", "unlocked" ] } }, clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, acceptRanges: { serializedName: "accept-ranges", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, blobCommittedBlockCount: { serializedName: "x-ms-blob-committed-block-count", type: { name: "Number" } }, isServerEncrypted: { serializedName: "x-ms-server-encrypted", type: { name: "Boolean" } }, encryptionKeySha256: { serializedName: "x-ms-encryption-key-sha256", type: { name: "String" } }, encryptionScope: { serializedName: "x-ms-encryption-scope", type: { name: "String" } }, blobContentMD5: { serializedName: "x-ms-blob-content-md5", type: { name: "ByteArray" } }, contentCrc64: { serializedName: "x-ms-content-crc64", type: { name: "ByteArray" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobGetTagsHeaders = { serializedName: "blob-gettags-headers", type: { name: "Composite", className: "BlobGetTagsHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; var BlobSetTagsHeaders = { serializedName: "blob-settags-headers", type: { name: "Composite", className: "BlobSetTagsHeaders", modelProperties: { clientRequestId: { serializedName: "x-ms-client-request-id", type: { name: "String" } }, requestId: { serializedName: "x-ms-request-id", type: { name: "String" } }, version: { serializedName: "x-ms-version", type: { name: "String" } }, date: { serializedName: "date", type: { name: "DateTimeRfc1123" } }, errorCode: { serializedName: "x-ms-error-code", type: { name: "String" } } } } }; /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ var Mappers = /*#__PURE__*/Object.freeze({ __proto__: null, BlobServiceProperties: BlobServiceProperties, BlobServiceStatistics: BlobServiceStatistics, ContainerItem: ContainerItem, ContainerProperties: ContainerProperties, CorsRule: CorsRule, FilterBlobItem: FilterBlobItem, FilterBlobSegment: FilterBlobSegment, GeoReplication: GeoReplication, KeyInfo: KeyInfo, ListContainersSegmentResponse: ListContainersSegmentResponse, Logging: Logging, Metrics: Metrics, RetentionPolicy: RetentionPolicy, ServiceFilterBlobsHeaders: ServiceFilterBlobsHeaders, ServiceGetAccountInfoHeaders: ServiceGetAccountInfoHeaders, ServiceGetPropertiesHeaders: ServiceGetPropertiesHeaders, ServiceGetStatisticsHeaders: ServiceGetStatisticsHeaders, ServiceGetUserDelegationKeyHeaders: ServiceGetUserDelegationKeyHeaders, ServiceListContainersSegmentHeaders: ServiceListContainersSegmentHeaders, ServiceSetPropertiesHeaders: ServiceSetPropertiesHeaders, ServiceSubmitBatchHeaders: ServiceSubmitBatchHeaders, StaticWebsite: StaticWebsite, StorageError: StorageError, UserDelegationKey: UserDelegationKey }); /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ var access = { parameterPath: [ "options", "access" ], mapper: { serializedName: "x-ms-blob-public-access", type: { name: "String" } } }; var action0 = { parameterPath: "action", mapper: { required: true, isConstant: true, serializedName: "x-ms-lease-action", defaultValue: 'acquire', type: { name: "String" } } }; var action1 = { parameterPath: "action", mapper: { required: true, isConstant: true, serializedName: "x-ms-lease-action", defaultValue: 'release', type: { name: "String" } } }; var action2 = { parameterPath: "action", mapper: { required: true, isConstant: true, serializedName: "x-ms-lease-action", defaultValue: 'renew', type: { name: "String" } } }; var action3 = { parameterPath: "action", mapper: { required: true, isConstant: true, serializedName: "x-ms-lease-action", defaultValue: 'break', type: { name: "String" } } }; var action4 = { parameterPath: "action", mapper: { required: true, isConstant: true, serializedName: "x-ms-lease-action", defaultValue: 'change', type: { name: "String" } } }; var action5 = { parameterPath: "action", mapper: { required: true, isConstant: true, serializedName: "action", defaultValue: 'setAccessControl', type: { name: "String" } } }; var action6 = { parameterPath: "action", mapper: { required: true, isConstant: true, serializedName: "action", defaultValue: 'getAccessControl', type: { name: "String" } } }; var appendPosition = { parameterPath: [ "options", "appendPositionAccessConditions", "appendPosition" ], mapper: { serializedName: "x-ms-blob-condition-appendpos", type: { name: "Number" } } }; var blobCacheControl = { parameterPath: [ "options", "blobHTTPHeaders", "blobCacheControl" ], mapper: { serializedName: "x-ms-blob-cache-control", type: { name: "String" } } }; var blobContentDisposition = { parameterPath: [ "options", "blobHTTPHeaders", "blobContentDisposition" ], mapper: { serializedName: "x-ms-blob-content-disposition", type: { name: "String" } } }; var blobContentEncoding = { parameterPath: [ "options", "blobHTTPHeaders", "blobContentEncoding" ], mapper: { serializedName: "x-ms-blob-content-encoding", type: { name: "String" } } }; var blobContentLanguage = { parameterPath: [ "options", "blobHTTPHeaders", "blobContentLanguage" ], mapper: { serializedName: "x-ms-blob-content-language", type: { name: "String" } } }; var blobContentLength = { parameterPath: "blobContentLength", mapper: { required: true, serializedName: "x-ms-blob-content-length", type: { name: "Number" } } }; var blobContentMD5 = { parameterPath: [ "options", "blobHTTPHeaders", "blobContentMD5" ], mapper: { serializedName: "x-ms-blob-content-md5", type: { name: "ByteArray" } } }; var blobContentType = { parameterPath: [ "options", "blobHTTPHeaders", "blobContentType" ], mapper: { serializedName: "x-ms-blob-content-type", type: { name: "String" } } }; var blobSequenceNumber = { parameterPath: [ "options", "blobSequenceNumber" ], mapper: { serializedName: "x-ms-blob-sequence-number", defaultValue: 0, type: { name: "Number" } } }; var blobTagsString = { parameterPath: [ "options", "blobTagsString" ], mapper: { serializedName: "x-ms-tags", type: { name: "String" } } }; var blobType0 = { parameterPath: "blobType", mapper: { required: true, isConstant: true, serializedName: "x-ms-blob-type", defaultValue: 'PageBlob', type: { name: "String" } } }; var blobType1 = { parameterPath: "blobType", mapper: { required: true, isConstant: true, serializedName: "x-ms-blob-type", defaultValue: 'AppendBlob', type: { name: "String" } } }; var blobType2 = { parameterPath: "blobType", mapper: { required: true, isConstant: true, serializedName: "x-ms-blob-type", defaultValue: 'BlockBlob', type: { name: "String" } } }; var blockId = { parameterPath: "blockId", mapper: { required: true, serializedName: "blockid", type: { name: "String" } } }; var breakPeriod = { parameterPath: [ "options", "breakPeriod" ], mapper: { serializedName: "x-ms-lease-break-period", type: { name: "Number" } } }; var cacheControl = { parameterPath: [ "options", "directoryHttpHeaders", "cacheControl" ], mapper: { serializedName: "x-ms-cache-control", type: { name: "String" } } }; var comp0 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'properties', type: { name: "String" } } }; var comp1 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'stats', type: { name: "String" } } }; var comp10 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'expiry', type: { name: "String" } } }; var comp11 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'snapshot', type: { name: "String" } } }; var comp12 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'copy', type: { name: "String" } } }; var comp13 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'tier', type: { name: "String" } } }; var comp14 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'query', type: { name: "String" } } }; var comp15 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'tags', type: { name: "String" } } }; var comp16 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'page', type: { name: "String" } } }; var comp17 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'pagelist', type: { name: "String" } } }; var comp18 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'incrementalcopy', type: { name: "String" } } }; var comp19 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'appendblock', type: { name: "String" } } }; var comp2 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'list', type: { name: "String" } } }; var comp20 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'seal', type: { name: "String" } } }; var comp21 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'block', type: { name: "String" } } }; var comp22 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'blocklist', type: { name: "String" } } }; var comp3 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'userdelegationkey', type: { name: "String" } } }; var comp4 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'batch', type: { name: "String" } } }; var comp5 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'blobs', type: { name: "String" } } }; var comp6 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'metadata', type: { name: "String" } } }; var comp7 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'acl', type: { name: "String" } } }; var comp8 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'undelete', type: { name: "String" } } }; var comp9 = { parameterPath: "comp", mapper: { required: true, isConstant: true, serializedName: "comp", defaultValue: 'lease', type: { name: "String" } } }; var contentDisposition = { parameterPath: [ "options", "directoryHttpHeaders", "contentDisposition" ], mapper: { serializedName: "x-ms-content-disposition", type: { name: "String" } } }; var contentEncoding = { parameterPath: [ "options", "directoryHttpHeaders", "contentEncoding" ], mapper: { serializedName: "x-ms-content-encoding", type: { name: "String" } } }; var contentLanguage = { parameterPath: [ "options", "directoryHttpHeaders", "contentLanguage" ], mapper: { serializedName: "x-ms-content-language", type: { name: "String" } } }; var contentLength = { parameterPath: "contentLength", mapper: { required: true, serializedName: "Content-Length", type: { name: "Number" } } }; var contentType = { parameterPath: [ "options", "directoryHttpHeaders", "contentType" ], mapper: { serializedName: "x-ms-content-type", type: { name: "String" } } }; var copyActionAbortConstant = { parameterPath: "copyActionAbortConstant", mapper: { required: true, isConstant: true, serializedName: "x-ms-copy-action", defaultValue: 'abort', type: { name: "String" } } }; var copyId = { parameterPath: "copyId", mapper: { required: true, serializedName: "copyid", type: { name: "String" } } }; var copySource = { parameterPath: "copySource", mapper: { required: true, serializedName: "x-ms-copy-source", type: { name: "String" } } }; var defaultEncryptionScope = { parameterPath: [ "options", "containerEncryptionScope", "defaultEncryptionScope" ], mapper: { serializedName: "x-ms-default-encryption-scope", type: { name: "String" } } }; var deletedContainerName = { parameterPath: [ "options", "deletedContainerName" ], mapper: { serializedName: "x-ms-deleted-container-name", type: { name: "String" } } }; var deletedContainerVersion = { parameterPath: [ "options", "deletedContainerVersion" ], mapper: { serializedName: "x-ms-deleted-container-version", type: { name: "String" } } }; var deleteSnapshots = { parameterPath: [ "options", "deleteSnapshots" ], mapper: { serializedName: "x-ms-delete-snapshots", type: { name: "Enum", allowedValues: [ "include", "only" ] } } }; var delimiter = { parameterPath: "delimiter", mapper: { required: true, serializedName: "delimiter", type: { name: "String" } } }; var directoryProperties = { parameterPath: [ "options", "directoryProperties" ], mapper: { serializedName: "x-ms-properties", type: { name: "String" } } }; var duration = { parameterPath: [ "options", "duration" ], mapper: { serializedName: "x-ms-lease-duration", type: { name: "Number" } } }; var encryptionAlgorithm = { parameterPath: [ "options", "cpkInfo", "encryptionAlgorithm" ], mapper: { serializedName: "x-ms-encryption-algorithm", type: { name: "Enum", allowedValues: [ "AES256" ] } } }; var encryptionKey = { parameterPath: [ "options", "cpkInfo", "encryptionKey" ], mapper: { serializedName: "x-ms-encryption-key", type: { name: "String" } } }; var encryptionKeySha256 = { parameterPath: [ "options", "cpkInfo", "encryptionKeySha256" ], mapper: { serializedName: "x-ms-encryption-key-sha256", type: { name: "String" } } }; var encryptionScope = { parameterPath: [ "options", "encryptionScope" ], mapper: { serializedName: "x-ms-encryption-scope", type: { name: "String" } } }; var expiresOn = { parameterPath: [ "options", "expiresOn" ], mapper: { serializedName: "x-ms-expiry-time", type: { name: "String" } } }; var expiryOptions = { parameterPath: "expiryOptions", mapper: { required: true, serializedName: "x-ms-expiry-option", type: { name: "String" } } }; var group = { parameterPath: [ "options", "group" ], mapper: { serializedName: "x-ms-group", type: { name: "String" } } }; var ifMatch = { parameterPath: [ "options", "modifiedAccessConditions", "ifMatch" ], mapper: { serializedName: "If-Match", type: { name: "String" } } }; var ifModifiedSince = { parameterPath: [ "options", "modifiedAccessConditions", "ifModifiedSince" ], mapper: { serializedName: "If-Modified-Since", type: { name: "DateTimeRfc1123" } } }; var ifNoneMatch = { parameterPath: [ "options", "modifiedAccessConditions", "ifNoneMatch" ], mapper: { serializedName: "If-None-Match", type: { name: "String" } } }; var ifSequenceNumberEqualTo = { parameterPath: [ "options", "sequenceNumberAccessConditions", "ifSequenceNumberEqualTo" ], mapper: { serializedName: "x-ms-if-sequence-number-eq", type: { name: "Number" } } }; var ifSequenceNumberLessThan = { parameterPath: [ "options", "sequenceNumberAccessConditions", "ifSequenceNumberLessThan" ], mapper: { serializedName: "x-ms-if-sequence-number-lt", type: { name: "Number" } } }; var ifSequenceNumberLessThanOrEqualTo = { parameterPath: [ "options", "sequenceNumberAccessConditions", "ifSequenceNumberLessThanOrEqualTo" ], mapper: { serializedName: "x-ms-if-sequence-number-le", type: { name: "Number" } } }; var ifTags = { parameterPath: [ "options", "modifiedAccessConditions", "ifTags" ], mapper: { serializedName: "x-ms-if-tags", type: { name: "String" } } }; var ifUnmodifiedSince = { parameterPath: [ "options", "modifiedAccessConditions", "ifUnmodifiedSince" ], mapper: { serializedName: "If-Unmodified-Since", type: { name: "DateTimeRfc1123" } } }; var include0 = { parameterPath: [ "options", "include" ], mapper: { serializedName: "include", type: { name: "Sequence", element: { type: { name: "Enum", allowedValues: [ "metadata", "deleted" ] } } } }, collectionFormat: coreHttp.QueryCollectionFormat.Csv }; var include1 = { parameterPath: [ "options", "include" ], mapper: { serializedName: "include", type: { name: "Sequence", element: { type: { name: "Enum", allowedValues: [ "copy", "deleted", "metadata", "snapshots", "uncommittedblobs", "versions", "tags" ] } } } }, collectionFormat: coreHttp.QueryCollectionFormat.Csv }; var leaseId0 = { parameterPath: [ "options", "leaseAccessConditions", "leaseId" ], mapper: { serializedName: "x-ms-lease-id", type: { name: "String" } } }; var leaseId1 = { parameterPath: "leaseId", mapper: { required: true, serializedName: "x-ms-lease-id", type: { name: "String" } } }; var listType = { parameterPath: "listType", mapper: { required: true, serializedName: "blocklisttype", defaultValue: 'committed', type: { name: "Enum", allowedValues: [ "committed", "uncommitted", "all" ] } } }; var marker0 = { parameterPath: [ "options", "marker" ], mapper: { serializedName: "marker", type: { name: "String" } } }; var maxPageSize = { parameterPath: [ "options", "maxPageSize" ], mapper: { serializedName: "maxresults", constraints: { InclusiveMinimum: 1 }, type: { name: "Number" } } }; var maxSize = { parameterPath: [ "options", "appendPositionAccessConditions", "maxSize" ], mapper: { serializedName: "x-ms-blob-condition-maxsize", type: { name: "Number" } } }; var metadata = { parameterPath: [ "options", "metadata" ], mapper: { serializedName: "x-ms-meta", type: { name: "Dictionary", value: { type: { name: "String" } } }, headerCollectionPrefix: "x-ms-meta-" } }; var multipartContentType = { parameterPath: "multipartContentType", mapper: { required: true, serializedName: "Content-Type", type: { name: "String" } } }; var owner = { parameterPath: [ "options", "owner" ], mapper: { serializedName: "x-ms-owner", type: { name: "String" } } }; var pageWrite0 = { parameterPath: "pageWrite", mapper: { required: true, isConstant: true, serializedName: "x-ms-page-write", defaultValue: 'update', type: { name: "String" } } }; var pageWrite1 = { parameterPath: "pageWrite", mapper: { required: true, isConstant: true, serializedName: "x-ms-page-write", defaultValue: 'clear', type: { name: "String" } } }; var pathRenameMode = { parameterPath: [ "options", "pathRenameMode" ], mapper: { serializedName: "mode", type: { name: "Enum", allowedValues: [ "legacy", "posix" ] } } }; var posixAcl = { parameterPath: [ "options", "posixAcl" ], mapper: { serializedName: "x-ms-acl", type: { name: "String" } } }; var posixPermissions = { parameterPath: [ "options", "posixPermissions" ], mapper: { serializedName: "x-ms-permissions", type: { name: "String" } } }; var posixUmask = { parameterPath: [ "options", "posixUmask" ], mapper: { serializedName: "x-ms-umask", type: { name: "String" } } }; var prefix = { parameterPath: [ "options", "prefix" ], mapper: { serializedName: "prefix", type: { name: "String" } } }; var preventEncryptionScopeOverride = { parameterPath: [ "options", "containerEncryptionScope", "preventEncryptionScopeOverride" ], mapper: { serializedName: "x-ms-deny-encryption-scope-override", type: { name: "Boolean" } } }; var prevsnapshot = { parameterPath: [ "options", "prevsnapshot" ], mapper: { serializedName: "prevsnapshot", type: { name: "String" } } }; var prevSnapshotUrl = { parameterPath: [ "options", "prevSnapshotUrl" ], mapper: { serializedName: "x-ms-previous-snapshot-url", type: { name: "String" } } }; var proposedLeaseId0 = { parameterPath: [ "options", "proposedLeaseId" ], mapper: { serializedName: "x-ms-proposed-lease-id", type: { name: "String" } } }; var proposedLeaseId1 = { parameterPath: "proposedLeaseId", mapper: { required: true, serializedName: "x-ms-proposed-lease-id", type: { name: "String" } } }; var range0 = { parameterPath: [ "options", "range" ], mapper: { serializedName: "x-ms-range", type: { name: "String" } } }; var range1 = { parameterPath: "range", mapper: { required: true, serializedName: "x-ms-range", type: { name: "String" } } }; var rangeGetContentCRC64 = { parameterPath: [ "options", "rangeGetContentCRC64" ], mapper: { serializedName: "x-ms-range-get-content-crc64", type: { name: "Boolean" } } }; var rangeGetContentMD5 = { parameterPath: [ "options", "rangeGetContentMD5" ], mapper: { serializedName: "x-ms-range-get-content-md5", type: { name: "Boolean" } } }; var rehydratePriority = { parameterPath: [ "options", "rehydratePriority" ], mapper: { serializedName: "x-ms-rehydrate-priority", type: { name: "String" } } }; var renameSource = { parameterPath: "renameSource", mapper: { required: true, serializedName: "x-ms-rename-source", type: { name: "String" } } }; var requestId = { parameterPath: [ "options", "requestId" ], mapper: { serializedName: "x-ms-client-request-id", type: { name: "String" } } }; var restype0 = { parameterPath: "restype", mapper: { required: true, isConstant: true, serializedName: "restype", defaultValue: 'service', type: { name: "String" } } }; var restype1 = { parameterPath: "restype", mapper: { required: true, isConstant: true, serializedName: "restype", defaultValue: 'account', type: { name: "String" } } }; var restype2 = { parameterPath: "restype", mapper: { required: true, isConstant: true, serializedName: "restype", defaultValue: 'container', type: { name: "String" } } }; var sealBlob = { parameterPath: [ "options", "sealBlob" ], mapper: { serializedName: "x-ms-seal-blob", type: { name: "Boolean" } } }; var sequenceNumberAction = { parameterPath: "sequenceNumberAction", mapper: { required: true, serializedName: "x-ms-sequence-number-action", type: { name: "Enum", allowedValues: [ "max", "update", "increment" ] } } }; var snapshot = { parameterPath: [ "options", "snapshot" ], mapper: { serializedName: "snapshot", type: { name: "String" } } }; var sourceContentCrc64 = { parameterPath: [ "options", "sourceContentCrc64" ], mapper: { serializedName: "x-ms-source-content-crc64", type: { name: "ByteArray" } } }; var sourceContentMD5 = { parameterPath: [ "options", "sourceContentMD5" ], mapper: { serializedName: "x-ms-source-content-md5", type: { name: "ByteArray" } } }; var sourceIfMatch = { parameterPath: [ "options", "sourceModifiedAccessConditions", "sourceIfMatch" ], mapper: { serializedName: "x-ms-source-if-match", type: { name: "String" } } }; var sourceIfModifiedSince = { parameterPath: [ "options", "sourceModifiedAccessConditions", "sourceIfModifiedSince" ], mapper: { serializedName: "x-ms-source-if-modified-since", type: { name: "DateTimeRfc1123" } } }; var sourceIfNoneMatch = { parameterPath: [ "options", "sourceModifiedAccessConditions", "sourceIfNoneMatch" ], mapper: { serializedName: "x-ms-source-if-none-match", type: { name: "String" } } }; var sourceIfTags = { parameterPath: [ "options", "sourceModifiedAccessConditions", "sourceIfTags" ], mapper: { serializedName: "x-ms-source-if-tags", type: { name: "String" } } }; var sourceIfUnmodifiedSince = { parameterPath: [ "options", "sourceModifiedAccessConditions", "sourceIfUnmodifiedSince" ], mapper: { serializedName: "x-ms-source-if-unmodified-since", type: { name: "DateTimeRfc1123" } } }; var sourceLeaseId = { parameterPath: [ "options", "sourceLeaseId" ], mapper: { serializedName: "x-ms-source-lease-id", type: { name: "String" } } }; var sourceRange0 = { parameterPath: "sourceRange", mapper: { required: true, serializedName: "x-ms-source-range", type: { name: "String" } } }; var sourceRange1 = { parameterPath: [ "options", "sourceRange" ], mapper: { serializedName: "x-ms-source-range", type: { name: "String" } } }; var sourceUrl = { parameterPath: "sourceUrl", mapper: { required: true, serializedName: "x-ms-copy-source", type: { name: "String" } } }; var tier0 = { parameterPath: [ "options", "tier" ], mapper: { serializedName: "x-ms-access-tier", type: { name: "String" } } }; var tier1 = { parameterPath: "tier", mapper: { required: true, serializedName: "x-ms-access-tier", type: { name: "String" } } }; var timeoutInSeconds = { parameterPath: [ "options", "timeoutInSeconds" ], mapper: { serializedName: "timeout", constraints: { InclusiveMinimum: 0 }, type: { name: "Number" } } }; var transactionalContentCrc64 = { parameterPath: [ "options", "transactionalContentCrc64" ], mapper: { serializedName: "x-ms-content-crc64", type: { name: "ByteArray" } } }; var transactionalContentMD5 = { parameterPath: [ "options", "transactionalContentMD5" ], mapper: { serializedName: "Content-MD5", type: { name: "ByteArray" } } }; var upn = { parameterPath: [ "options", "upn" ], mapper: { serializedName: "upn", type: { name: "Boolean" } } }; var url = { parameterPath: "url", mapper: { required: true, serializedName: "url", defaultValue: '', type: { name: "String" } }, skipEncoding: true }; var version = { parameterPath: "version", mapper: { required: true, isConstant: true, serializedName: "x-ms-version", defaultValue: '2020-02-10', type: { name: "String" } } }; var versionId = { parameterPath: [ "options", "versionId" ], mapper: { serializedName: "versionid", type: { name: "String" } } }; var where = { parameterPath: [ "options", "where" ], mapper: { serializedName: "where", type: { name: "String" } } }; var xMsRequiresSync = { parameterPath: "xMsRequiresSync", mapper: { required: true, isConstant: true, serializedName: "x-ms-requires-sync", defaultValue: 'true', type: { name: "String" } } }; /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ /** Class representing a Service. */ var Service = /** @class */ (function () { /** * Create a Service. * @param {StorageClientContext} client Reference to the service client. */ function Service(client) { this.client = client; } Service.prototype.setProperties = function (blobServiceProperties, options, callback) { return this.client.sendOperationRequest({ blobServiceProperties: blobServiceProperties, options: options }, setPropertiesOperationSpec, callback); }; Service.prototype.getProperties = function (options, callback) { return this.client.sendOperationRequest({ options: options }, getPropertiesOperationSpec, callback); }; Service.prototype.getStatistics = function (options, callback) { return this.client.sendOperationRequest({ options: options }, getStatisticsOperationSpec, callback); }; Service.prototype.listContainersSegment = function (options, callback) { return this.client.sendOperationRequest({ options: options }, listContainersSegmentOperationSpec, callback); }; Service.prototype.getUserDelegationKey = function (keyInfo, options, callback) { return this.client.sendOperationRequest({ keyInfo: keyInfo, options: options }, getUserDelegationKeyOperationSpec, callback); }; Service.prototype.getAccountInfo = function (options, callback) { return this.client.sendOperationRequest({ options: options }, getAccountInfoOperationSpec, callback); }; Service.prototype.submitBatch = function (body, contentLength, multipartContentType, options, callback) { return this.client.sendOperationRequest({ body: body, contentLength: contentLength, multipartContentType: multipartContentType, options: options }, submitBatchOperationSpec, callback); }; Service.prototype.filterBlobs = function (options, callback) { return this.client.sendOperationRequest({ options: options }, filterBlobsOperationSpec, callback); }; return Service; }()); // Operation Specifications var serializer = new coreHttp.Serializer(Mappers, true); var setPropertiesOperationSpec = { httpMethod: "PUT", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, restype0, comp0 ], headerParameters: [ version, requestId ], requestBody: { parameterPath: "blobServiceProperties", mapper: tslib.__assign(tslib.__assign({}, BlobServiceProperties), { required: true }) }, contentType: "application/xml; charset=utf-8", responses: { 202: { headersMapper: ServiceSetPropertiesHeaders }, default: { bodyMapper: StorageError, headersMapper: ServiceSetPropertiesHeaders } }, isXML: true, serializer: serializer }; var getPropertiesOperationSpec = { httpMethod: "GET", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, restype0, comp0 ], headerParameters: [ version, requestId ], responses: { 200: { bodyMapper: BlobServiceProperties, headersMapper: ServiceGetPropertiesHeaders }, default: { bodyMapper: StorageError, headersMapper: ServiceGetPropertiesHeaders } }, isXML: true, serializer: serializer }; var getStatisticsOperationSpec = { httpMethod: "GET", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, restype0, comp1 ], headerParameters: [ version, requestId ], responses: { 200: { bodyMapper: BlobServiceStatistics, headersMapper: ServiceGetStatisticsHeaders }, default: { bodyMapper: StorageError, headersMapper: ServiceGetStatisticsHeaders } }, isXML: true, serializer: serializer }; var listContainersSegmentOperationSpec = { httpMethod: "GET", urlParameters: [ url ], queryParameters: [ prefix, marker0, maxPageSize, include0, timeoutInSeconds, comp2 ], headerParameters: [ version, requestId ], responses: { 200: { bodyMapper: ListContainersSegmentResponse, headersMapper: ServiceListContainersSegmentHeaders }, default: { bodyMapper: StorageError, headersMapper: ServiceListContainersSegmentHeaders } }, isXML: true, serializer: serializer }; var getUserDelegationKeyOperationSpec = { httpMethod: "POST", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, restype0, comp3 ], headerParameters: [ version, requestId ], requestBody: { parameterPath: "keyInfo", mapper: tslib.__assign(tslib.__assign({}, KeyInfo), { required: true }) }, contentType: "application/xml; charset=utf-8", responses: { 200: { bodyMapper: UserDelegationKey, headersMapper: ServiceGetUserDelegationKeyHeaders }, default: { bodyMapper: StorageError, headersMapper: ServiceGetUserDelegationKeyHeaders } }, isXML: true, serializer: serializer }; var getAccountInfoOperationSpec = { httpMethod: "GET", urlParameters: [ url ], queryParameters: [ restype1, comp0 ], headerParameters: [ version ], responses: { 200: { headersMapper: ServiceGetAccountInfoHeaders }, default: { bodyMapper: StorageError, headersMapper: ServiceGetAccountInfoHeaders } }, isXML: true, serializer: serializer }; var submitBatchOperationSpec = { httpMethod: "POST", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp4 ], headerParameters: [ contentLength, multipartContentType, version, requestId ], requestBody: { parameterPath: "body", mapper: { required: true, serializedName: "body", type: { name: "Stream" } } }, contentType: "application/xml; charset=utf-8", responses: { 202: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Stream" } }, headersMapper: ServiceSubmitBatchHeaders }, default: { bodyMapper: StorageError, headersMapper: ServiceSubmitBatchHeaders } }, isXML: true, serializer: serializer }; var filterBlobsOperationSpec = { httpMethod: "GET", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, where, marker0, maxPageSize, comp5 ], headerParameters: [ version, requestId ], responses: { 200: { bodyMapper: FilterBlobSegment, headersMapper: ServiceFilterBlobsHeaders }, default: { bodyMapper: StorageError, headersMapper: ServiceFilterBlobsHeaders } }, isXML: true, serializer: serializer }; /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ var Mappers$1 = /*#__PURE__*/Object.freeze({ __proto__: null, AccessPolicy: AccessPolicy, BlobFlatListSegment: BlobFlatListSegment, BlobHierarchyListSegment: BlobHierarchyListSegment, BlobItemInternal: BlobItemInternal, BlobPrefix: BlobPrefix, BlobPropertiesInternal: BlobPropertiesInternal, BlobTag: BlobTag, BlobTags: BlobTags, ContainerAcquireLeaseHeaders: ContainerAcquireLeaseHeaders, ContainerBreakLeaseHeaders: ContainerBreakLeaseHeaders, ContainerChangeLeaseHeaders: ContainerChangeLeaseHeaders, ContainerCreateHeaders: ContainerCreateHeaders, ContainerDeleteHeaders: ContainerDeleteHeaders, ContainerGetAccessPolicyHeaders: ContainerGetAccessPolicyHeaders, ContainerGetAccountInfoHeaders: ContainerGetAccountInfoHeaders, ContainerGetPropertiesHeaders: ContainerGetPropertiesHeaders, ContainerListBlobFlatSegmentHeaders: ContainerListBlobFlatSegmentHeaders, ContainerListBlobHierarchySegmentHeaders: ContainerListBlobHierarchySegmentHeaders, ContainerReleaseLeaseHeaders: ContainerReleaseLeaseHeaders, ContainerRenewLeaseHeaders: ContainerRenewLeaseHeaders, ContainerRestoreHeaders: ContainerRestoreHeaders, ContainerSetAccessPolicyHeaders: ContainerSetAccessPolicyHeaders, ContainerSetMetadataHeaders: ContainerSetMetadataHeaders, ListBlobsFlatSegmentResponse: ListBlobsFlatSegmentResponse, ListBlobsHierarchySegmentResponse: ListBlobsHierarchySegmentResponse, SignedIdentifier: SignedIdentifier, StorageError: StorageError }); /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ /** Class representing a Container. */ var Container = /** @class */ (function () { /** * Create a Container. * @param {StorageClientContext} client Reference to the service client. */ function Container(client) { this.client = client; } Container.prototype.create = function (options, callback) { return this.client.sendOperationRequest({ options: options }, createOperationSpec, callback); }; Container.prototype.getProperties = function (options, callback) { return this.client.sendOperationRequest({ options: options }, getPropertiesOperationSpec$1, callback); }; Container.prototype.deleteMethod = function (options, callback) { return this.client.sendOperationRequest({ options: options }, deleteMethodOperationSpec, callback); }; Container.prototype.setMetadata = function (options, callback) { return this.client.sendOperationRequest({ options: options }, setMetadataOperationSpec, callback); }; Container.prototype.getAccessPolicy = function (options, callback) { return this.client.sendOperationRequest({ options: options }, getAccessPolicyOperationSpec, callback); }; Container.prototype.setAccessPolicy = function (options, callback) { return this.client.sendOperationRequest({ options: options }, setAccessPolicyOperationSpec, callback); }; Container.prototype.restore = function (options, callback) { return this.client.sendOperationRequest({ options: options }, restoreOperationSpec, callback); }; Container.prototype.acquireLease = function (options, callback) { return this.client.sendOperationRequest({ options: options }, acquireLeaseOperationSpec, callback); }; Container.prototype.releaseLease = function (leaseId, options, callback) { return this.client.sendOperationRequest({ leaseId: leaseId, options: options }, releaseLeaseOperationSpec, callback); }; Container.prototype.renewLease = function (leaseId, options, callback) { return this.client.sendOperationRequest({ leaseId: leaseId, options: options }, renewLeaseOperationSpec, callback); }; Container.prototype.breakLease = function (options, callback) { return this.client.sendOperationRequest({ options: options }, breakLeaseOperationSpec, callback); }; Container.prototype.changeLease = function (leaseId, proposedLeaseId, options, callback) { return this.client.sendOperationRequest({ leaseId: leaseId, proposedLeaseId: proposedLeaseId, options: options }, changeLeaseOperationSpec, callback); }; Container.prototype.listBlobFlatSegment = function (options, callback) { return this.client.sendOperationRequest({ options: options }, listBlobFlatSegmentOperationSpec, callback); }; Container.prototype.listBlobHierarchySegment = function (delimiter, options, callback) { return this.client.sendOperationRequest({ delimiter: delimiter, options: options }, listBlobHierarchySegmentOperationSpec, callback); }; Container.prototype.getAccountInfo = function (options, callback) { return this.client.sendOperationRequest({ options: options }, getAccountInfoOperationSpec$1, callback); }; return Container; }()); // Operation Specifications var serializer$1 = new coreHttp.Serializer(Mappers$1, true); var createOperationSpec = { httpMethod: "PUT", path: "{containerName}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, restype2 ], headerParameters: [ metadata, access, version, requestId, defaultEncryptionScope, preventEncryptionScopeOverride ], responses: { 201: { headersMapper: ContainerCreateHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerCreateHeaders } }, isXML: true, serializer: serializer$1 }; var getPropertiesOperationSpec$1 = { httpMethod: "GET", path: "{containerName}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, restype2 ], headerParameters: [ version, requestId, leaseId0 ], responses: { 200: { headersMapper: ContainerGetPropertiesHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerGetPropertiesHeaders } }, isXML: true, serializer: serializer$1 }; var deleteMethodOperationSpec = { httpMethod: "DELETE", path: "{containerName}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, restype2 ], headerParameters: [ version, requestId, leaseId0, ifModifiedSince, ifUnmodifiedSince ], responses: { 202: { headersMapper: ContainerDeleteHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerDeleteHeaders } }, isXML: true, serializer: serializer$1 }; var setMetadataOperationSpec = { httpMethod: "PUT", path: "{containerName}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, restype2, comp6 ], headerParameters: [ metadata, version, requestId, leaseId0, ifModifiedSince ], responses: { 200: { headersMapper: ContainerSetMetadataHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerSetMetadataHeaders } }, isXML: true, serializer: serializer$1 }; var getAccessPolicyOperationSpec = { httpMethod: "GET", path: "{containerName}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, restype2, comp7 ], headerParameters: [ version, requestId, leaseId0 ], responses: { 200: { bodyMapper: { xmlElementName: "SignedIdentifier", serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "SignedIdentifier" } } } }, headersMapper: ContainerGetAccessPolicyHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerGetAccessPolicyHeaders } }, isXML: true, serializer: serializer$1 }; var setAccessPolicyOperationSpec = { httpMethod: "PUT", path: "{containerName}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, restype2, comp7 ], headerParameters: [ access, version, requestId, leaseId0, ifModifiedSince, ifUnmodifiedSince ], requestBody: { parameterPath: [ "options", "containerAcl" ], mapper: { xmlName: "SignedIdentifiers", xmlElementName: "SignedIdentifier", serializedName: "containerAcl", type: { name: "Sequence", element: { type: { name: "Composite", className: "SignedIdentifier" } } } } }, contentType: "application/xml; charset=utf-8", responses: { 200: { headersMapper: ContainerSetAccessPolicyHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerSetAccessPolicyHeaders } }, isXML: true, serializer: serializer$1 }; var restoreOperationSpec = { httpMethod: "PUT", path: "{containerName}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, restype2, comp8 ], headerParameters: [ version, requestId, deletedContainerName, deletedContainerVersion ], responses: { 201: { headersMapper: ContainerRestoreHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerRestoreHeaders } }, isXML: true, serializer: serializer$1 }; var acquireLeaseOperationSpec = { httpMethod: "PUT", path: "{containerName}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp9, restype2 ], headerParameters: [ duration, proposedLeaseId0, version, requestId, action0, ifModifiedSince, ifUnmodifiedSince ], responses: { 201: { headersMapper: ContainerAcquireLeaseHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerAcquireLeaseHeaders } }, isXML: true, serializer: serializer$1 }; var releaseLeaseOperationSpec = { httpMethod: "PUT", path: "{containerName}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp9, restype2 ], headerParameters: [ leaseId1, version, requestId, action1, ifModifiedSince, ifUnmodifiedSince ], responses: { 200: { headersMapper: ContainerReleaseLeaseHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerReleaseLeaseHeaders } }, isXML: true, serializer: serializer$1 }; var renewLeaseOperationSpec = { httpMethod: "PUT", path: "{containerName}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp9, restype2 ], headerParameters: [ leaseId1, version, requestId, action2, ifModifiedSince, ifUnmodifiedSince ], responses: { 200: { headersMapper: ContainerRenewLeaseHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerRenewLeaseHeaders } }, isXML: true, serializer: serializer$1 }; var breakLeaseOperationSpec = { httpMethod: "PUT", path: "{containerName}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp9, restype2 ], headerParameters: [ breakPeriod, version, requestId, action3, ifModifiedSince, ifUnmodifiedSince ], responses: { 202: { headersMapper: ContainerBreakLeaseHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerBreakLeaseHeaders } }, isXML: true, serializer: serializer$1 }; var changeLeaseOperationSpec = { httpMethod: "PUT", path: "{containerName}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp9, restype2 ], headerParameters: [ leaseId1, proposedLeaseId1, version, requestId, action4, ifModifiedSince, ifUnmodifiedSince ], responses: { 200: { headersMapper: ContainerChangeLeaseHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerChangeLeaseHeaders } }, isXML: true, serializer: serializer$1 }; var listBlobFlatSegmentOperationSpec = { httpMethod: "GET", path: "{containerName}", urlParameters: [ url ], queryParameters: [ prefix, marker0, maxPageSize, include1, timeoutInSeconds, restype2, comp2 ], headerParameters: [ version, requestId ], responses: { 200: { bodyMapper: ListBlobsFlatSegmentResponse, headersMapper: ContainerListBlobFlatSegmentHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerListBlobFlatSegmentHeaders } }, isXML: true, serializer: serializer$1 }; var listBlobHierarchySegmentOperationSpec = { httpMethod: "GET", path: "{containerName}", urlParameters: [ url ], queryParameters: [ prefix, delimiter, marker0, maxPageSize, include1, timeoutInSeconds, restype2, comp2 ], headerParameters: [ version, requestId ], responses: { 200: { bodyMapper: ListBlobsHierarchySegmentResponse, headersMapper: ContainerListBlobHierarchySegmentHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerListBlobHierarchySegmentHeaders } }, isXML: true, serializer: serializer$1 }; var getAccountInfoOperationSpec$1 = { httpMethod: "GET", path: "{containerName}", urlParameters: [ url ], queryParameters: [ restype1, comp0 ], headerParameters: [ version ], responses: { 200: { headersMapper: ContainerGetAccountInfoHeaders }, default: { bodyMapper: StorageError, headersMapper: ContainerGetAccountInfoHeaders } }, isXML: true, serializer: serializer$1 }; /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ var Mappers$2 = /*#__PURE__*/Object.freeze({ __proto__: null, ArrowConfiguration: ArrowConfiguration, ArrowField: ArrowField, BlobAbortCopyFromURLHeaders: BlobAbortCopyFromURLHeaders, BlobAcquireLeaseHeaders: BlobAcquireLeaseHeaders, BlobBreakLeaseHeaders: BlobBreakLeaseHeaders, BlobChangeLeaseHeaders: BlobChangeLeaseHeaders, BlobCopyFromURLHeaders: BlobCopyFromURLHeaders, BlobCreateSnapshotHeaders: BlobCreateSnapshotHeaders, BlobDeleteHeaders: BlobDeleteHeaders, BlobDownloadHeaders: BlobDownloadHeaders, BlobGetAccessControlHeaders: BlobGetAccessControlHeaders, BlobGetAccountInfoHeaders: BlobGetAccountInfoHeaders, BlobGetPropertiesHeaders: BlobGetPropertiesHeaders, BlobGetTagsHeaders: BlobGetTagsHeaders, BlobQueryHeaders: BlobQueryHeaders, BlobReleaseLeaseHeaders: BlobReleaseLeaseHeaders, BlobRenameHeaders: BlobRenameHeaders, BlobRenewLeaseHeaders: BlobRenewLeaseHeaders, BlobSetAccessControlHeaders: BlobSetAccessControlHeaders, BlobSetExpiryHeaders: BlobSetExpiryHeaders, BlobSetHTTPHeadersHeaders: BlobSetHTTPHeadersHeaders, BlobSetMetadataHeaders: BlobSetMetadataHeaders, BlobSetTagsHeaders: BlobSetTagsHeaders, BlobSetTierHeaders: BlobSetTierHeaders, BlobStartCopyFromURLHeaders: BlobStartCopyFromURLHeaders, BlobTag: BlobTag, BlobTags: BlobTags, BlobUndeleteHeaders: BlobUndeleteHeaders, DataLakeStorageError: DataLakeStorageError, DataLakeStorageErrorError: DataLakeStorageErrorError, DelimitedTextConfiguration: DelimitedTextConfiguration, JsonTextConfiguration: JsonTextConfiguration, QueryFormat: QueryFormat, QueryRequest: QueryRequest, QuerySerialization: QuerySerialization, StorageError: StorageError }); /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ /** Class representing a Blob. */ var Blob$1 = /** @class */ (function () { /** * Create a Blob. * @param {StorageClientContext} client Reference to the service client. */ function Blob(client) { this.client = client; } Blob.prototype.download = function (options, callback) { return this.client.sendOperationRequest({ options: options }, downloadOperationSpec, callback); }; Blob.prototype.getProperties = function (options, callback) { return this.client.sendOperationRequest({ options: options }, getPropertiesOperationSpec$2, callback); }; Blob.prototype.deleteMethod = function (options, callback) { return this.client.sendOperationRequest({ options: options }, deleteMethodOperationSpec$1, callback); }; Blob.prototype.setAccessControl = function (options, callback) { return this.client.sendOperationRequest({ options: options }, setAccessControlOperationSpec, callback); }; Blob.prototype.getAccessControl = function (options, callback) { return this.client.sendOperationRequest({ options: options }, getAccessControlOperationSpec, callback); }; Blob.prototype.rename = function (renameSource, options, callback) { return this.client.sendOperationRequest({ renameSource: renameSource, options: options }, renameOperationSpec, callback); }; Blob.prototype.undelete = function (options, callback) { return this.client.sendOperationRequest({ options: options }, undeleteOperationSpec, callback); }; Blob.prototype.setExpiry = function (expiryOptions, options, callback) { return this.client.sendOperationRequest({ expiryOptions: expiryOptions, options: options }, setExpiryOperationSpec, callback); }; Blob.prototype.setHTTPHeaders = function (options, callback) { return this.client.sendOperationRequest({ options: options }, setHTTPHeadersOperationSpec, callback); }; Blob.prototype.setMetadata = function (options, callback) { return this.client.sendOperationRequest({ options: options }, setMetadataOperationSpec$1, callback); }; Blob.prototype.acquireLease = function (options, callback) { return this.client.sendOperationRequest({ options: options }, acquireLeaseOperationSpec$1, callback); }; Blob.prototype.releaseLease = function (leaseId, options, callback) { return this.client.sendOperationRequest({ leaseId: leaseId, options: options }, releaseLeaseOperationSpec$1, callback); }; Blob.prototype.renewLease = function (leaseId, options, callback) { return this.client.sendOperationRequest({ leaseId: leaseId, options: options }, renewLeaseOperationSpec$1, callback); }; Blob.prototype.changeLease = function (leaseId, proposedLeaseId, options, callback) { return this.client.sendOperationRequest({ leaseId: leaseId, proposedLeaseId: proposedLeaseId, options: options }, changeLeaseOperationSpec$1, callback); }; Blob.prototype.breakLease = function (options, callback) { return this.client.sendOperationRequest({ options: options }, breakLeaseOperationSpec$1, callback); }; Blob.prototype.createSnapshot = function (options, callback) { return this.client.sendOperationRequest({ options: options }, createSnapshotOperationSpec, callback); }; Blob.prototype.startCopyFromURL = function (copySource, options, callback) { return this.client.sendOperationRequest({ copySource: copySource, options: options }, startCopyFromURLOperationSpec, callback); }; Blob.prototype.copyFromURL = function (copySource, options, callback) { return this.client.sendOperationRequest({ copySource: copySource, options: options }, copyFromURLOperationSpec, callback); }; Blob.prototype.abortCopyFromURL = function (copyId, options, callback) { return this.client.sendOperationRequest({ copyId: copyId, options: options }, abortCopyFromURLOperationSpec, callback); }; Blob.prototype.setTier = function (tier, options, callback) { return this.client.sendOperationRequest({ tier: tier, options: options }, setTierOperationSpec, callback); }; Blob.prototype.getAccountInfo = function (options, callback) { return this.client.sendOperationRequest({ options: options }, getAccountInfoOperationSpec$2, callback); }; Blob.prototype.query = function (options, callback) { return this.client.sendOperationRequest({ options: options }, queryOperationSpec, callback); }; Blob.prototype.getTags = function (options, callback) { return this.client.sendOperationRequest({ options: options }, getTagsOperationSpec, callback); }; Blob.prototype.setTags = function (options, callback) { return this.client.sendOperationRequest({ options: options }, setTagsOperationSpec, callback); }; return Blob; }()); // Operation Specifications var serializer$2 = new coreHttp.Serializer(Mappers$2, true); var downloadOperationSpec = { httpMethod: "GET", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ snapshot, versionId, timeoutInSeconds ], headerParameters: [ range0, rangeGetContentMD5, rangeGetContentCRC64, version, requestId, leaseId0, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Stream" } }, headersMapper: BlobDownloadHeaders }, 206: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Stream" } }, headersMapper: BlobDownloadHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobDownloadHeaders } }, isXML: true, serializer: serializer$2 }; var getPropertiesOperationSpec$2 = { httpMethod: "HEAD", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ snapshot, versionId, timeoutInSeconds ], headerParameters: [ version, requestId, leaseId0, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], responses: { 200: { headersMapper: BlobGetPropertiesHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobGetPropertiesHeaders } }, isXML: true, serializer: serializer$2 }; var deleteMethodOperationSpec$1 = { httpMethod: "DELETE", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ snapshot, versionId, timeoutInSeconds ], headerParameters: [ deleteSnapshots, version, requestId, leaseId0, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], responses: { 202: { headersMapper: BlobDeleteHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobDeleteHeaders } }, isXML: true, serializer: serializer$2 }; var setAccessControlOperationSpec = { httpMethod: "PATCH", path: "{filesystem}/{path}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, action5 ], headerParameters: [ owner, group, posixPermissions, posixAcl, requestId, version, leaseId0, ifMatch, ifNoneMatch, ifModifiedSince, ifUnmodifiedSince ], responses: { 200: { headersMapper: BlobSetAccessControlHeaders }, default: { bodyMapper: DataLakeStorageError, headersMapper: BlobSetAccessControlHeaders } }, isXML: true, serializer: serializer$2 }; var getAccessControlOperationSpec = { httpMethod: "HEAD", path: "{filesystem}/{path}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, upn, action6 ], headerParameters: [ requestId, version, leaseId0, ifMatch, ifNoneMatch, ifModifiedSince, ifUnmodifiedSince ], responses: { 200: { headersMapper: BlobGetAccessControlHeaders }, default: { bodyMapper: DataLakeStorageError, headersMapper: BlobGetAccessControlHeaders } }, isXML: true, serializer: serializer$2 }; var renameOperationSpec = { httpMethod: "PUT", path: "{filesystem}/{path}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, pathRenameMode ], headerParameters: [ renameSource, directoryProperties, posixPermissions, posixUmask, sourceLeaseId, version, requestId, cacheControl, contentType, contentEncoding, contentLanguage, contentDisposition, leaseId0, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch ], responses: { 201: { headersMapper: BlobRenameHeaders }, default: { bodyMapper: DataLakeStorageError, headersMapper: BlobRenameHeaders } }, isXML: true, serializer: serializer$2 }; var undeleteOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp8 ], headerParameters: [ version, requestId ], responses: { 200: { headersMapper: BlobUndeleteHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobUndeleteHeaders } }, isXML: true, serializer: serializer$2 }; var setExpiryOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp10 ], headerParameters: [ version, requestId, expiryOptions, expiresOn ], responses: { 200: { headersMapper: BlobSetExpiryHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobSetExpiryHeaders } }, isXML: true, serializer: serializer$2 }; var setHTTPHeadersOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp0 ], headerParameters: [ version, requestId, blobCacheControl, blobContentType, blobContentMD5, blobContentEncoding, blobContentLanguage, blobContentDisposition, leaseId0, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], responses: { 200: { headersMapper: BlobSetHTTPHeadersHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobSetHTTPHeadersHeaders } }, isXML: true, serializer: serializer$2 }; var setMetadataOperationSpec$1 = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp6 ], headerParameters: [ metadata, encryptionScope, version, requestId, leaseId0, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], responses: { 200: { headersMapper: BlobSetMetadataHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobSetMetadataHeaders } }, isXML: true, serializer: serializer$2 }; var acquireLeaseOperationSpec$1 = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp9 ], headerParameters: [ duration, proposedLeaseId0, version, requestId, action0, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], responses: { 201: { headersMapper: BlobAcquireLeaseHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobAcquireLeaseHeaders } }, isXML: true, serializer: serializer$2 }; var releaseLeaseOperationSpec$1 = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp9 ], headerParameters: [ leaseId1, version, requestId, action1, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], responses: { 200: { headersMapper: BlobReleaseLeaseHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobReleaseLeaseHeaders } }, isXML: true, serializer: serializer$2 }; var renewLeaseOperationSpec$1 = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp9 ], headerParameters: [ leaseId1, version, requestId, action2, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], responses: { 200: { headersMapper: BlobRenewLeaseHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobRenewLeaseHeaders } }, isXML: true, serializer: serializer$2 }; var changeLeaseOperationSpec$1 = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp9 ], headerParameters: [ leaseId1, proposedLeaseId1, version, requestId, action4, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], responses: { 200: { headersMapper: BlobChangeLeaseHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobChangeLeaseHeaders } }, isXML: true, serializer: serializer$2 }; var breakLeaseOperationSpec$1 = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp9 ], headerParameters: [ breakPeriod, version, requestId, action3, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], responses: { 202: { headersMapper: BlobBreakLeaseHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobBreakLeaseHeaders } }, isXML: true, serializer: serializer$2 }; var createSnapshotOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp11 ], headerParameters: [ metadata, encryptionScope, version, requestId, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags, leaseId0 ], responses: { 201: { headersMapper: BlobCreateSnapshotHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobCreateSnapshotHeaders } }, isXML: true, serializer: serializer$2 }; var startCopyFromURLOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds ], headerParameters: [ metadata, tier0, rehydratePriority, copySource, version, requestId, blobTagsString, sealBlob, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, sourceIfTags, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags, leaseId0 ], responses: { 202: { headersMapper: BlobStartCopyFromURLHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobStartCopyFromURLHeaders } }, isXML: true, serializer: serializer$2 }; var copyFromURLOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds ], headerParameters: [ metadata, tier0, copySource, version, requestId, sourceContentMD5, blobTagsString, xMsRequiresSync, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags, leaseId0 ], responses: { 202: { headersMapper: BlobCopyFromURLHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobCopyFromURLHeaders } }, isXML: true, serializer: serializer$2 }; var abortCopyFromURLOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ copyId, timeoutInSeconds, comp12 ], headerParameters: [ version, requestId, copyActionAbortConstant, leaseId0 ], responses: { 204: { headersMapper: BlobAbortCopyFromURLHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobAbortCopyFromURLHeaders } }, isXML: true, serializer: serializer$2 }; var setTierOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ snapshot, versionId, timeoutInSeconds, comp13 ], headerParameters: [ tier1, rehydratePriority, version, requestId, leaseId0, ifTags ], responses: { 200: { headersMapper: BlobSetTierHeaders }, 202: { headersMapper: BlobSetTierHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobSetTierHeaders } }, isXML: true, serializer: serializer$2 }; var getAccountInfoOperationSpec$2 = { httpMethod: "GET", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ restype1, comp0 ], headerParameters: [ version ], responses: { 200: { headersMapper: BlobGetAccountInfoHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobGetAccountInfoHeaders } }, isXML: true, serializer: serializer$2 }; var queryOperationSpec = { httpMethod: "POST", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ snapshot, timeoutInSeconds, comp14 ], headerParameters: [ version, requestId, leaseId0, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], requestBody: { parameterPath: [ "options", "queryRequest" ], mapper: QueryRequest }, contentType: "application/xml; charset=utf-8", responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Stream" } }, headersMapper: BlobQueryHeaders }, 206: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Stream" } }, headersMapper: BlobQueryHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobQueryHeaders } }, isXML: true, serializer: serializer$2 }; var getTagsOperationSpec = { httpMethod: "GET", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, snapshot, versionId, comp15 ], headerParameters: [ version, requestId, ifTags ], responses: { 200: { bodyMapper: BlobTags, headersMapper: BlobGetTagsHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobGetTagsHeaders } }, isXML: true, serializer: serializer$2 }; var setTagsOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, versionId, comp15 ], headerParameters: [ version, transactionalContentMD5, transactionalContentCrc64, requestId, ifTags ], requestBody: { parameterPath: [ "options", "tags" ], mapper: BlobTags }, contentType: "application/xml; charset=utf-8", responses: { 204: { headersMapper: BlobSetTagsHeaders }, default: { bodyMapper: StorageError, headersMapper: BlobSetTagsHeaders } }, isXML: true, serializer: serializer$2 }; /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ var Mappers$3 = /*#__PURE__*/Object.freeze({ __proto__: null, ClearRange: ClearRange, PageBlobClearPagesHeaders: PageBlobClearPagesHeaders, PageBlobCopyIncrementalHeaders: PageBlobCopyIncrementalHeaders, PageBlobCreateHeaders: PageBlobCreateHeaders, PageBlobGetPageRangesDiffHeaders: PageBlobGetPageRangesDiffHeaders, PageBlobGetPageRangesHeaders: PageBlobGetPageRangesHeaders, PageBlobResizeHeaders: PageBlobResizeHeaders, PageBlobUpdateSequenceNumberHeaders: PageBlobUpdateSequenceNumberHeaders, PageBlobUploadPagesFromURLHeaders: PageBlobUploadPagesFromURLHeaders, PageBlobUploadPagesHeaders: PageBlobUploadPagesHeaders, PageList: PageList, PageRange: PageRange, StorageError: StorageError }); /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ /** Class representing a PageBlob. */ var PageBlob = /** @class */ (function () { /** * Create a PageBlob. * @param {StorageClientContext} client Reference to the service client. */ function PageBlob(client) { this.client = client; } PageBlob.prototype.create = function (contentLength, blobContentLength, options, callback) { return this.client.sendOperationRequest({ contentLength: contentLength, blobContentLength: blobContentLength, options: options }, createOperationSpec$1, callback); }; PageBlob.prototype.uploadPages = function (body, contentLength, options, callback) { return this.client.sendOperationRequest({ body: body, contentLength: contentLength, options: options }, uploadPagesOperationSpec, callback); }; PageBlob.prototype.clearPages = function (contentLength, options, callback) { return this.client.sendOperationRequest({ contentLength: contentLength, options: options }, clearPagesOperationSpec, callback); }; PageBlob.prototype.uploadPagesFromURL = function (sourceUrl, sourceRange, contentLength, range, options, callback) { return this.client.sendOperationRequest({ sourceUrl: sourceUrl, sourceRange: sourceRange, contentLength: contentLength, range: range, options: options }, uploadPagesFromURLOperationSpec, callback); }; PageBlob.prototype.getPageRanges = function (options, callback) { return this.client.sendOperationRequest({ options: options }, getPageRangesOperationSpec, callback); }; PageBlob.prototype.getPageRangesDiff = function (options, callback) { return this.client.sendOperationRequest({ options: options }, getPageRangesDiffOperationSpec, callback); }; PageBlob.prototype.resize = function (blobContentLength, options, callback) { return this.client.sendOperationRequest({ blobContentLength: blobContentLength, options: options }, resizeOperationSpec, callback); }; PageBlob.prototype.updateSequenceNumber = function (sequenceNumberAction, options, callback) { return this.client.sendOperationRequest({ sequenceNumberAction: sequenceNumberAction, options: options }, updateSequenceNumberOperationSpec, callback); }; PageBlob.prototype.copyIncremental = function (copySource, options, callback) { return this.client.sendOperationRequest({ copySource: copySource, options: options }, copyIncrementalOperationSpec, callback); }; return PageBlob; }()); // Operation Specifications var serializer$3 = new coreHttp.Serializer(Mappers$3, true); var createOperationSpec$1 = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds ], headerParameters: [ contentLength, tier0, metadata, encryptionScope, blobContentLength, blobSequenceNumber, version, requestId, blobTagsString, blobType0, blobContentType, blobContentEncoding, blobContentLanguage, blobContentMD5, blobCacheControl, blobContentDisposition, leaseId0, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], responses: { 201: { headersMapper: PageBlobCreateHeaders }, default: { bodyMapper: StorageError, headersMapper: PageBlobCreateHeaders } }, isXML: true, serializer: serializer$3 }; var uploadPagesOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp16 ], headerParameters: [ contentLength, transactionalContentMD5, transactionalContentCrc64, range0, encryptionScope, version, requestId, pageWrite0, leaseId0, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifSequenceNumberLessThanOrEqualTo, ifSequenceNumberLessThan, ifSequenceNumberEqualTo, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], requestBody: { parameterPath: "body", mapper: { required: true, serializedName: "body", type: { name: "Stream" } } }, contentType: "application/octet-stream", responses: { 201: { headersMapper: PageBlobUploadPagesHeaders }, default: { bodyMapper: StorageError, headersMapper: PageBlobUploadPagesHeaders } }, isXML: true, serializer: serializer$3 }; var clearPagesOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp16 ], headerParameters: [ contentLength, range0, encryptionScope, version, requestId, pageWrite1, leaseId0, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifSequenceNumberLessThanOrEqualTo, ifSequenceNumberLessThan, ifSequenceNumberEqualTo, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], responses: { 201: { headersMapper: PageBlobClearPagesHeaders }, default: { bodyMapper: StorageError, headersMapper: PageBlobClearPagesHeaders } }, isXML: true, serializer: serializer$3 }; var uploadPagesFromURLOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp16 ], headerParameters: [ sourceUrl, sourceRange0, sourceContentMD5, sourceContentCrc64, contentLength, range1, encryptionScope, version, requestId, pageWrite0, encryptionKey, encryptionKeySha256, encryptionAlgorithm, leaseId0, ifSequenceNumberLessThanOrEqualTo, ifSequenceNumberLessThan, ifSequenceNumberEqualTo, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch ], responses: { 201: { headersMapper: PageBlobUploadPagesFromURLHeaders }, default: { bodyMapper: StorageError, headersMapper: PageBlobUploadPagesFromURLHeaders } }, isXML: true, serializer: serializer$3 }; var getPageRangesOperationSpec = { httpMethod: "GET", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ snapshot, timeoutInSeconds, comp17 ], headerParameters: [ range0, version, requestId, leaseId0, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], responses: { 200: { bodyMapper: PageList, headersMapper: PageBlobGetPageRangesHeaders }, default: { bodyMapper: StorageError, headersMapper: PageBlobGetPageRangesHeaders } }, isXML: true, serializer: serializer$3 }; var getPageRangesDiffOperationSpec = { httpMethod: "GET", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ snapshot, timeoutInSeconds, prevsnapshot, comp17 ], headerParameters: [ prevSnapshotUrl, range0, version, requestId, leaseId0, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], responses: { 200: { bodyMapper: PageList, headersMapper: PageBlobGetPageRangesDiffHeaders }, default: { bodyMapper: StorageError, headersMapper: PageBlobGetPageRangesDiffHeaders } }, isXML: true, serializer: serializer$3 }; var resizeOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp0 ], headerParameters: [ encryptionScope, blobContentLength, version, requestId, leaseId0, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], responses: { 200: { headersMapper: PageBlobResizeHeaders }, default: { bodyMapper: StorageError, headersMapper: PageBlobResizeHeaders } }, isXML: true, serializer: serializer$3 }; var updateSequenceNumberOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp0 ], headerParameters: [ sequenceNumberAction, blobSequenceNumber, version, requestId, leaseId0, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], responses: { 200: { headersMapper: PageBlobUpdateSequenceNumberHeaders }, default: { bodyMapper: StorageError, headersMapper: PageBlobUpdateSequenceNumberHeaders } }, isXML: true, serializer: serializer$3 }; var copyIncrementalOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp18 ], headerParameters: [ copySource, version, requestId, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], responses: { 202: { headersMapper: PageBlobCopyIncrementalHeaders }, default: { bodyMapper: StorageError, headersMapper: PageBlobCopyIncrementalHeaders } }, isXML: true, serializer: serializer$3 }; /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ var Mappers$4 = /*#__PURE__*/Object.freeze({ __proto__: null, AppendBlobAppendBlockFromUrlHeaders: AppendBlobAppendBlockFromUrlHeaders, AppendBlobAppendBlockHeaders: AppendBlobAppendBlockHeaders, AppendBlobCreateHeaders: AppendBlobCreateHeaders, AppendBlobSealHeaders: AppendBlobSealHeaders, StorageError: StorageError }); /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ /** Class representing a AppendBlob. */ var AppendBlob = /** @class */ (function () { /** * Create a AppendBlob. * @param {StorageClientContext} client Reference to the service client. */ function AppendBlob(client) { this.client = client; } AppendBlob.prototype.create = function (contentLength, options, callback) { return this.client.sendOperationRequest({ contentLength: contentLength, options: options }, createOperationSpec$2, callback); }; AppendBlob.prototype.appendBlock = function (body, contentLength, options, callback) { return this.client.sendOperationRequest({ body: body, contentLength: contentLength, options: options }, appendBlockOperationSpec, callback); }; AppendBlob.prototype.appendBlockFromUrl = function (sourceUrl, contentLength, options, callback) { return this.client.sendOperationRequest({ sourceUrl: sourceUrl, contentLength: contentLength, options: options }, appendBlockFromUrlOperationSpec, callback); }; AppendBlob.prototype.seal = function (options, callback) { return this.client.sendOperationRequest({ options: options }, sealOperationSpec, callback); }; return AppendBlob; }()); // Operation Specifications var serializer$4 = new coreHttp.Serializer(Mappers$4, true); var createOperationSpec$2 = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds ], headerParameters: [ contentLength, metadata, encryptionScope, version, requestId, blobTagsString, blobType1, blobContentType, blobContentEncoding, blobContentLanguage, blobContentMD5, blobCacheControl, blobContentDisposition, leaseId0, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], responses: { 201: { headersMapper: AppendBlobCreateHeaders }, default: { bodyMapper: StorageError, headersMapper: AppendBlobCreateHeaders } }, isXML: true, serializer: serializer$4 }; var appendBlockOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp19 ], headerParameters: [ contentLength, transactionalContentMD5, transactionalContentCrc64, encryptionScope, version, requestId, leaseId0, maxSize, appendPosition, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], requestBody: { parameterPath: "body", mapper: { required: true, serializedName: "body", type: { name: "Stream" } } }, contentType: "application/octet-stream", responses: { 201: { headersMapper: AppendBlobAppendBlockHeaders }, default: { bodyMapper: StorageError, headersMapper: AppendBlobAppendBlockHeaders } }, isXML: true, serializer: serializer$4 }; var appendBlockFromUrlOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp19 ], headerParameters: [ sourceUrl, sourceRange1, sourceContentMD5, sourceContentCrc64, contentLength, transactionalContentMD5, encryptionScope, version, requestId, encryptionKey, encryptionKeySha256, encryptionAlgorithm, leaseId0, maxSize, appendPosition, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch ], responses: { 201: { headersMapper: AppendBlobAppendBlockFromUrlHeaders }, default: { bodyMapper: StorageError, headersMapper: AppendBlobAppendBlockFromUrlHeaders } }, isXML: true, serializer: serializer$4 }; var sealOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp20 ], headerParameters: [ version, requestId, leaseId0, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, appendPosition ], responses: { 200: { headersMapper: AppendBlobSealHeaders }, default: { bodyMapper: StorageError, headersMapper: AppendBlobSealHeaders } }, isXML: true, serializer: serializer$4 }; /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ var Mappers$5 = /*#__PURE__*/Object.freeze({ __proto__: null, Block: Block, BlockBlobCommitBlockListHeaders: BlockBlobCommitBlockListHeaders, BlockBlobGetBlockListHeaders: BlockBlobGetBlockListHeaders, BlockBlobStageBlockFromURLHeaders: BlockBlobStageBlockFromURLHeaders, BlockBlobStageBlockHeaders: BlockBlobStageBlockHeaders, BlockBlobUploadHeaders: BlockBlobUploadHeaders, BlockList: BlockList, BlockLookupList: BlockLookupList, StorageError: StorageError }); /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ /** Class representing a BlockBlob. */ var BlockBlob = /** @class */ (function () { /** * Create a BlockBlob. * @param {StorageClientContext} client Reference to the service client. */ function BlockBlob(client) { this.client = client; } BlockBlob.prototype.upload = function (body, contentLength, options, callback) { return this.client.sendOperationRequest({ body: body, contentLength: contentLength, options: options }, uploadOperationSpec, callback); }; BlockBlob.prototype.stageBlock = function (blockId, contentLength, body, options, callback) { return this.client.sendOperationRequest({ blockId: blockId, contentLength: contentLength, body: body, options: options }, stageBlockOperationSpec, callback); }; BlockBlob.prototype.stageBlockFromURL = function (blockId, contentLength, sourceUrl, options, callback) { return this.client.sendOperationRequest({ blockId: blockId, contentLength: contentLength, sourceUrl: sourceUrl, options: options }, stageBlockFromURLOperationSpec, callback); }; BlockBlob.prototype.commitBlockList = function (blocks, options, callback) { return this.client.sendOperationRequest({ blocks: blocks, options: options }, commitBlockListOperationSpec, callback); }; BlockBlob.prototype.getBlockList = function (listType, options, callback) { return this.client.sendOperationRequest({ listType: listType, options: options }, getBlockListOperationSpec, callback); }; return BlockBlob; }()); // Operation Specifications var serializer$5 = new coreHttp.Serializer(Mappers$5, true); var uploadOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds ], headerParameters: [ transactionalContentMD5, contentLength, metadata, encryptionScope, tier0, version, requestId, blobTagsString, blobType2, blobContentType, blobContentEncoding, blobContentLanguage, blobContentMD5, blobCacheControl, blobContentDisposition, leaseId0, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], requestBody: { parameterPath: "body", mapper: { required: true, serializedName: "body", type: { name: "Stream" } } }, contentType: "application/octet-stream", responses: { 201: { headersMapper: BlockBlobUploadHeaders }, default: { bodyMapper: StorageError, headersMapper: BlockBlobUploadHeaders } }, isXML: true, serializer: serializer$5 }; var stageBlockOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ blockId, timeoutInSeconds, comp21 ], headerParameters: [ contentLength, transactionalContentMD5, transactionalContentCrc64, encryptionScope, version, requestId, leaseId0, encryptionKey, encryptionKeySha256, encryptionAlgorithm ], requestBody: { parameterPath: "body", mapper: { required: true, serializedName: "body", type: { name: "Stream" } } }, contentType: "application/octet-stream", responses: { 201: { headersMapper: BlockBlobStageBlockHeaders }, default: { bodyMapper: StorageError, headersMapper: BlockBlobStageBlockHeaders } }, isXML: true, serializer: serializer$5 }; var stageBlockFromURLOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ blockId, timeoutInSeconds, comp21 ], headerParameters: [ contentLength, sourceUrl, sourceRange1, sourceContentMD5, sourceContentCrc64, encryptionScope, version, requestId, encryptionKey, encryptionKeySha256, encryptionAlgorithm, leaseId0, sourceIfModifiedSince, sourceIfUnmodifiedSince, sourceIfMatch, sourceIfNoneMatch ], responses: { 201: { headersMapper: BlockBlobStageBlockFromURLHeaders }, default: { bodyMapper: StorageError, headersMapper: BlockBlobStageBlockFromURLHeaders } }, isXML: true, serializer: serializer$5 }; var commitBlockListOperationSpec = { httpMethod: "PUT", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ timeoutInSeconds, comp22 ], headerParameters: [ transactionalContentMD5, transactionalContentCrc64, metadata, encryptionScope, tier0, version, requestId, blobTagsString, blobCacheControl, blobContentType, blobContentEncoding, blobContentLanguage, blobContentMD5, blobContentDisposition, leaseId0, encryptionKey, encryptionKeySha256, encryptionAlgorithm, ifModifiedSince, ifUnmodifiedSince, ifMatch, ifNoneMatch, ifTags ], requestBody: { parameterPath: "blocks", mapper: tslib.__assign(tslib.__assign({}, BlockLookupList), { required: true }) }, contentType: "application/xml; charset=utf-8", responses: { 201: { headersMapper: BlockBlobCommitBlockListHeaders }, default: { bodyMapper: StorageError, headersMapper: BlockBlobCommitBlockListHeaders } }, isXML: true, serializer: serializer$5 }; var getBlockListOperationSpec = { httpMethod: "GET", path: "{containerName}/{blob}", urlParameters: [ url ], queryParameters: [ snapshot, listType, timeoutInSeconds, comp22 ], headerParameters: [ version, requestId, leaseId0, ifTags ], responses: { 200: { bodyMapper: BlockList, headersMapper: BlockBlobGetBlockListHeaders }, default: { bodyMapper: StorageError, headersMapper: BlockBlobGetBlockListHeaders } }, isXML: true, serializer: serializer$5 }; // Copyright (c) Microsoft Corporation. /** * The @azure/logger configuration for this package. */ var logger = logger$1.createClientLogger("storage-blob"); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. var SDK_VERSION = "12.3.0"; var SERVICE_VERSION = "2020-02-10"; 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; /** * The OAuth scope to use with Azure Storage. */ var StorageOAuthScopes = "https://storage.azure.com/.default"; var URLConstants = { Parameters: { FORCE_BROWSER_NO_CACHE: "_", SIGNATURE: "sig", SNAPSHOT: "snapshot", VERSIONID: "versionid", TIMEOUT: "timeout" } }; var HTTPURLConnection = { HTTP_ACCEPTED: 202, HTTP_CONFLICT: 409, HTTP_NOT_FOUND: 404, HTTP_PRECON_FAILED: 412, HTTP_RANGE_NOT_SATISFIABLE: 416 }; var HeaderConstants = { AUTHORIZATION: "Authorization", AUTHORIZATION_SCHEME: "Bearer", CONTENT_ENCODING: "Content-Encoding", CONTENT_ID: "Content-ID", CONTENT_LANGUAGE: "Content-Language", CONTENT_LENGTH: "Content-Length", CONTENT_MD5: "Content-Md5", CONTENT_TRANSFER_ENCODING: "Content-Transfer-Encoding", CONTENT_TYPE: "Content-Type", COOKIE: "Cookie", DATE: "date", IF_MATCH: "if-match", IF_MODIFIED_SINCE: "if-modified-since", IF_NONE_MATCH: "if-none-match", IF_UNMODIFIED_SINCE: "if-unmodified-since", PREFIX_FOR_STORAGE: "x-ms-", RANGE: "Range", USER_AGENT: "User-Agent", X_MS_CLIENT_REQUEST_ID: "x-ms-client-request-id", X_MS_COPY_SOURCE: "x-ms-copy-source", X_MS_DATE: "x-ms-date", 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 = [ "Access-Control-Allow-Origin", "Cache-Control", "Content-Length", "Content-Type", "Date", "Request-Id", "traceparent", "Transfer-Encoding", "User-Agent", "x-ms-client-request-id", "x-ms-date", "x-ms-error-code", "x-ms-request-id", "x-ms-return-client-request-id", "x-ms-version", "Accept-Ranges", "Content-Disposition", "Content-Encoding", "Content-Language", "Content-MD5", "Content-Range", "ETag", "Last-Modified", "Server", "Vary", "x-ms-content-crc64", "x-ms-copy-action", "x-ms-copy-completion-time", "x-ms-copy-id", "x-ms-copy-progress", "x-ms-copy-status", "x-ms-has-immutability-policy", "x-ms-has-legal-hold", "x-ms-lease-state", "x-ms-lease-status", "x-ms-range", "x-ms-request-server-encrypted", "x-ms-server-encrypted", "x-ms-snapshot", "x-ms-source-range", "If-Match", "If-Modified-Since", "If-None-Match", "If-Unmodified-Since", "x-ms-access-tier", "x-ms-access-tier-change-time", "x-ms-access-tier-inferred", "x-ms-account-kind", "x-ms-archive-status", "x-ms-blob-append-offset", "x-ms-blob-cache-control", "x-ms-blob-committed-block-count", "x-ms-blob-condition-appendpos", "x-ms-blob-condition-maxsize", "x-ms-blob-content-disposition", "x-ms-blob-content-encoding", "x-ms-blob-content-language", "x-ms-blob-content-length", "x-ms-blob-content-md5", "x-ms-blob-content-type", "x-ms-blob-public-access", "x-ms-blob-sequence-number", "x-ms-blob-type", "x-ms-copy-destination-snapshot", "x-ms-creation-time", "x-ms-default-encryption-scope", "x-ms-delete-snapshots", "x-ms-delete-type-permanent", "x-ms-deny-encryption-scope-override", "x-ms-encryption-algorithm", "x-ms-if-sequence-number-eq", "x-ms-if-sequence-number-le", "x-ms-if-sequence-number-lt", "x-ms-incremental-copy", "x-ms-lease-action", "x-ms-lease-break-period", "x-ms-lease-duration", "x-ms-lease-id", "x-ms-lease-time", "x-ms-page-write", "x-ms-proposed-lease-id", "x-ms-range-get-content-md5", "x-ms-rehydrate-priority", "x-ms-sequence-number-action", "x-ms-sku-name", "x-ms-source-content-md5", "x-ms-source-if-match", "x-ms-source-if-modified-since", "x-ms-source-if-none-match", "x-ms-source-if-unmodified-since", "x-ms-tag-count", "x-ms-encryption-key-sha256", "x-ms-if-tags", "x-ms-source-if-tags" ]; var StorageBlobLoggingAllowedQueryParameters = [ "comp", "maxresults", "rscc", "rscd", "rsce", "rscl", "rsct", "se", "si", "sip", "sp", "spr", "sr", "srt", "ss", "st", "sv", "include", "marker", "prefix", "copyid", "restype", "blockid", "blocklisttype", "delimiter", "prevsnapshot", "ske", "skoid", "sks", "skt", "sktid", "skv", "snapshot" ]; // Copyright (c) Microsoft Corporation. All rights reserved. /** * Reserved URL characters must be properly escaped for Storage services like Blob or File. * * ## URL encode and escape strategy for JS SDKs * * When customers pass a URL string into XxxClient classes constructor, the URL string may already be URL encoded or not. * But before sending to Azure Storage server, the URL must be encoded. However, it's hard for a SDK to guess whether the URL * string has been encoded or not. We have 2 potential strategies, and chose strategy two for the XxxClient constructors. * * ### Strategy One: Assume the customer URL string is not encoded, and always encode URL string in SDK. * * This is what legacy V2 SDK does, simple and works for most of the cases. * - When customer URL string is "http://account.blob.core.windows.net/con/b:", * SDK will encode it to "http://account.blob.core.windows.net/con/b%3A" and send to server. A blob named "b:" will be created. * - When customer URL string is "http://account.blob.core.windows.net/con/b%3A", * SDK will encode it to "http://account.blob.core.windows.net/con/b%253A" and send to server. A blob named "b%3A" will be created. * * But this strategy will make it not possible to create a blob with "?" in it's name. Because when customer URL string is * "http://account.blob.core.windows.net/con/blob?name", the "?name" will be treated as URL paramter instead of blob name. * If customer URL string is "http://account.blob.core.windows.net/con/blob%3Fname", a blob named "blob%3Fname" will be created. * V2 SDK doesn't have this issue because it doesn't allow customer pass in a full URL, it accepts a separate blob name and encodeURIComponent for it. * We cannot accept a SDK cannot create a blob name with "?". So we implement strategy two: * * ### Strategy Two: SDK doesn't assume the URL has been encoded or not. It will just escape the special characters. * * This is what V10 Blob Go SDK does. It accepts a URL type in Go, and call url.EscapedPath() to escape the special chars unescaped. * - When customer URL string is "http://account.blob.core.windows.net/con/b:", * SDK will escape ":" like "http://account.blob.core.windows.net/con/b%3A" and send to server. A blob named "b:" will be created. * - When customer URL string is "http://account.blob.core.windows.net/con/b%3A", * There is no special characters, so send "http://account.blob.core.windows.net/con/b%3A" to server. A blob named "b:" will be created. * - When customer URL string is "http://account.blob.core.windows.net/con/b%253A", * There is no special characters, so send "http://account.blob.core.windows.net/con/b%253A" to server. A blob named "b%3A" will be created. * * This strategy gives us flexibility to create with any special characters. But "%" will be treated as a special characters, if the URL string * is not encoded, there shouldn't a "%" in the URL string, otherwise the URL is not a valid URL. * If customer needs to create a blob with "%" in it's blob name, use "%25" instead of "%". Just like above 3rd sample. * And following URL strings are invalid: * - "http://account.blob.core.windows.net/con/b%" * - "http://account.blob.core.windows.net/con/b%2" * - "http://account.blob.core.windows.net/con/b%G" * * Another special character is "?", use "%2F" to represent a blob name with "?" in a URL string. * * ### Strategy for containerName, blobName or other specific XXXName parameters in methods such as `containerClient.getBlobClient(blobName)` * * We will apply strategy one, and call encodeURIComponent for these parameters like blobName. Because what customers passes in is a plain name instead of a URL. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata * @see https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-shares--directories--files--and-metadata * * @export * @param {string} url * @returns {string} */ function escapeURLPath(url) { var urlParsed = coreHttp.URLBuilder.parse(url); var path = urlParsed.getPath(); path = path || "/"; path = escape(path); urlParsed.setPath(path); return urlParsed.toString(); } 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 = ""; 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]; if (element.trim().startsWith("DevelopmentStorageProxyUri=")) { proxyUri = element.trim().match("DevelopmentStorageProxyUri=(.*)")[1]; } } } 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]; if (element.trim().startsWith(argument)) { return element.trim().match(argument + "=(.*)")[1]; } } return ""; } /** * Extracts the parts of an Azure Storage account connection string. * * @export * @param {string} connectionString Connection string. * @returns {ConnectionString} String key value pairs of the storage account's url and credentials. */ function extractConnectionStringParts(connectionString) { var 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"); // 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 = ""; // Get account name and key accountName = getValueInConnString(connectionString, "AccountName"); accountKey = Buffer.from(getValueInConnString(connectionString, "AccountKey"), "base64"); if (!blobEndpoint) { // 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(); if (protocol !== "https" && protocol !== "http") { throw new Error("Invalid DefaultEndpointsProtocol in the provided Connection String. Expecting 'https' or 'http'"); } endpointSuffix = getValueInConnString(connectionString, "EndpointSuffix"); if (!endpointSuffix) { throw new Error("Invalid EndpointSuffix in the provided Connection String"); } blobEndpoint = defaultEndpointsProtocol + "://" + accountName + ".blob." + endpointSuffix; } if (!accountName) { throw new Error("Invalid AccountName in the provided Connection String"); } else if (accountKey.length === 0) { throw new Error("Invalid AccountKey in the provided Connection String"); } return { kind: "AccountConnString", url: blobEndpoint, accountName: accountName, accountKey: accountKey, proxyUri: proxyUri }; } else { // SAS connection string var accountSas = getValueInConnString(connectionString, "SharedAccessSignature"); var 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 }; } } /** * Internal escape method implemented Strategy Two mentioned in escapeURL() description. * * @param {string} text * @returns {string} */ function escape(text) { return encodeURIComponent(text) .replace(/%2F/g, "/") // Don't escape for "/" .replace(/'/g, "%27") // Escape for "'" .replace(/\+/g, "%20") .replace(/%25/g, "%"); // Revert encoded "%" } /** * Append a string to URL path. Will remove duplicated "/" in front of the string * when URL path ends with a "/". * * @export * @param {string} url Source URL string * @param {string} name String to be appended to URL * @returns {string} 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; urlParsed.setPath(path); return urlParsed.toString(); } /** * Set URL parameter name and value. If name exists in URL parameters, old value * will be replaced by name key. If not provide value, the parameter will be deleted. * * @export * @param {string} url Source URL string * @param {string} name Parameter name * @param {string} [value] Parameter value * @returns {string} An updated URL string */ function setURLParameter(url, name, value) { var urlParsed = coreHttp.URLBuilder.parse(url); urlParsed.setQueryParameter(name, value); return urlParsed.toString(); } /** * Set URL host. * * @export * @param {string} url Source URL string * @param {string} host New host string * @returns An updated URL string */ function setURLHost(url, host) { var urlParsed = coreHttp.URLBuilder.parse(url); urlParsed.setHost(host); return urlParsed.toString(); } /** * Get URL path from an URL string. * * @export * @param {string} url Source URL string * @returns {(string | undefined)} */ function getURLPath(url) { var urlParsed = coreHttp.URLBuilder.parse(url); return urlParsed.getPath(); } /** * Get URL scheme from an URL string. * * @export * @param {string} url Source URL string * @returns {(string | undefined)} */ function getURLScheme(url) { var urlParsed = coreHttp.URLBuilder.parse(url); return urlParsed.getScheme(); } /** * Get URL path and query from an URL string. * * @export * @param {string} url Source URL string * @returns {(string | undefined)} */ function getURLPathAndQuery(url) { var urlParsed = coreHttp.URLBuilder.parse(url); var pathString = urlParsed.getPath(); if (!pathString) { throw new RangeError("Invalid url without valid path."); } var queryString = urlParsed.getQuery() || ""; queryString = queryString.trim(); if (queryString != "") { queryString = queryString.startsWith("?") ? queryString : "?" + queryString; // Ensure query string start with '?' } return "" + pathString + queryString; } /** * Get URL query key value pairs from an URL string. * * @export * @param {string} url * @returns {{[key: string]: string}} */ function getURLQueries(url) { var 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("="); 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]; queries[key] = value; } return queries; } /** * Rounds a date off to seconds. * * @export * @param {Date} date * @param {boolean} [withMilliseconds=true] If true, YYYY-MM-DDThh:mm:ss.fffffffZ will be returned; * If false, YYYY-MM-DDThh:mm:ssZ will be returned. * @returns {string} Date string in ISO8061 format, with or without 7 milliseconds component */ function truncatedISO8061Date(date, withMilliseconds) { if (withMilliseconds === void 0) { withMilliseconds = true; } // Date.toISOString() will return like "2018-10-29T06:34:36.139Z" var dateString = date.toISOString(); return withMilliseconds ? dateString.substring(0, dateString.length - 1) + "0000" + "Z" : dateString.substring(0, dateString.length - 5) + "Z"; } /** * Base64 encode. * * @export * @param {string} content * @returns {string} */ function base64encode(content) { return !coreHttp.isNode ? btoa(content) : Buffer.from(content).toString("base64"); } /** * Generate a 64 bytes base64 block ID string. * * @export * @param {number} blockIndex * @returns {string} */ function generateBlockID(blockIDPrefix, blockIndex) { // To generate a 64 bytes base64 string, source string should be 48 var maxSourceStringLength = 48; // A blob can have a maximum of 100,000 uncommitted blocks at any given time var maxBlockIndexLength = 6; var maxAllowedBlockIDPrefixLength = maxSourceStringLength - maxBlockIndexLength; if (blockIDPrefix.length > maxAllowedBlockIDPrefixLength) { blockIDPrefix = blockIDPrefix.slice(0, maxAllowedBlockIDPrefixLength); } var res = blockIDPrefix + padStart(blockIndex.toString(), maxSourceStringLength - blockIDPrefix.length, "0"); return base64encode(res); } /** * Delay specified time interval. * * @export * @param {number} timeInMs * @param {AbortSignalLike} [aborter] * @param {Error} [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); } })]; }); }); } /** * String.prototype.padStart() * * @export * @param {string} currentString * @param {number} targetLength * @param {string} [padString=" "] * @returns {string} */ function padStart(currentString, targetLength, padString) { if (padString === void 0) { padString = " "; } // TS doesn't know this code needs to run downlevel sometimes. // @ts-expect-error if (String.prototype.padStart) { return currentString.padStart(targetLength, padString); } padString = padString || " "; if (currentString.length > targetLength) { return currentString; } else { targetLength = targetLength - currentString.length; if (targetLength > padString.length) { padString += padString.repeat(targetLength / padString.length); } return padString.slice(0, targetLength) + currentString; } } /** * If two strings are equal when compared case insensitive. * * @export * @param {string} str1 * @param {string} str2 * @returns {boolean} */ function iEqual(str1, str2) { return str1.toLocaleLowerCase() === str2.toLocaleLowerCase(); } /** * Extracts account name from the url * @param {string} url url to extract the account name from * @returns {string} with the account name */ function getAccountNameFromUrl(url) { var parsedUrl = coreHttp.URLBuilder.parse(url); var accountName; try { if (parsedUrl.getHost().split(".")[1] === "blob") { // `${defaultEndpointsProtocol}://${accountName}.blob.${endpointSuffix}`; accountName = parsedUrl.getHost().split(".")[0]; } else if (isIpEndpointStyle(parsedUrl)) { // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/ // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/ // .getPath() -> /devstoreaccount1/ accountName = parsedUrl.getPath().split("/")[1]; } else { // Custom domain case: "https://customdomain.com/containername/blob". accountName = ""; } return accountName; } catch (error) { throw new Error("Unable to extract accountName with provided information."); } } function isIpEndpointStyle(parsedUrl) { if (parsedUrl.getHost() == undefined) { return false; } var 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. // For valid host please refer to https://man7.org/linux/man-pages/man7/hostname.7.html. return /^.*:.*:.*$|^localhost(:[0-9]+)?$|^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])){3}(:[0-9]+)?$/.test(host); } /** * Convert Tags to encoded string. * * @export * @param {Tags} tags * @returns {string | undefined} */ 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)); } } return tagPairs.join("&"); } /** * Convert Tags type to BlobTags. * * @export * @param {Tags} [tags] * @returns {(BlobTags | undefined)} */ function toBlobTags(tags) { if (tags === undefined) { return undefined; } var res = { blobTagSet: [] }; for (var key in tags) { if (tags.hasOwnProperty(key)) { var value = tags[key]; res.blobTagSet.push({ key: key, value: value }); } } return res; } /** * Covert BlobTags to Tags type. * * @export * @param {BlobTags} [tags] * @returns {(Tags | undefined)} */ 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]; res[blobTag.key] = blobTag.value; } return res; } /** * Convert BlobQueryTextConfiguration to QuerySerialization type. * * @export * @param {(BlobQueryJsonTextConfiguration | BlobQueryCsvTextConfiguration | BlobQueryArrowConfiguration)} [textConfiguration] * @returns {(QuerySerialization | undefined)} */ function toQuerySerialization(textConfiguration) { if (textConfiguration === undefined) { return undefined; } switch (textConfiguration.kind) { case "csv": return { format: { type: "delimited", delimitedTextConfiguration: { columnSeparator: textConfiguration.columnSeparator || ",", fieldQuote: textConfiguration.fieldQuote || "", recordSeparator: textConfiguration.recordSeparator, escapeChar: textConfiguration.escapeCharacter || "", headersPresent: textConfiguration.hasHeaders || false } } }; case "json": return { format: { type: "json", jsonTextConfiguration: { recordSeparator: textConfiguration.recordSeparator } } }; case "arrow": return { format: { type: "arrow", arrowConfiguration: { schema: textConfiguration.schema } } }; default: throw Error("Invalid BlobQueryTextConfiguration."); } } function parseObjectReplicationRecord(objectReplicationRecord) { if (!objectReplicationRecord) { return undefined; } if ("policy-id" in objectReplicationRecord) { // If the dictionary contains a key with policy id, we are not required to do any parsing since // 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-"; if (ids[0].startsWith(policyPrefix)) { ids[0] = ids[0].substring(policyPrefix.length); } var rule = { ruleId: ids[1], replicationStatus: objectReplicationRecord[key] }; var policyIndex = orProperties.findIndex(function (policy) { return policy.policyId === ids[0]; }); if (policyIndex > -1) { orProperties[policyIndex].rules.push(rule); } else { orProperties.push({ policyId: ids[0], rules: [rule] }); } }; for (var key in objectReplicationRecord) { _loop_1(key); } return orProperties; } // Copyright (c) Microsoft Corporation. All rights reserved. /** * StorageBrowserPolicy will handle differences between Node.js and browser runtime, including: * * 1. Browsers cache GET/HEAD requests by adding conditional headers such as 'IF_MODIFIED_SINCE'. * StorageBrowserPolicy is a policy used to add a timestamp query to GET/HEAD request URL * thus avoid the browser cache. * * 2. Remove cookie header for security * * 3. Remove content-length header to avoid browsers warning * * @class StorageBrowserPolicy * @extends {BaseRequestPolicy} */ var StorageBrowserPolicy = /** @class */ (function (_super) { tslib.__extends(StorageBrowserPolicy, _super); /** * Creates an instance of StorageBrowserPolicy. * @param {RequestPolicy} nextPolicy * @param {RequestPolicyOptions} options * @memberof StorageBrowserPolicy */ function StorageBrowserPolicy(nextPolicy, options) { return _super.call(this, nextPolicy, options) || this; } /** * Sends out request. * * @param {WebResource} request * @returns {Promise} * @memberof StorageBrowserPolicy */ 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)); // Copyright (c) Microsoft Corporation. All rights reserved. /** * StorageBrowserPolicyFactory is a factory class helping generating StorageBrowserPolicy objects. * * @export * @class StorageBrowserPolicyFactory * @implements {RequestPolicyFactory} */ var StorageBrowserPolicyFactory = /** @class */ (function () { function StorageBrowserPolicyFactory() { } /** * Creates a StorageBrowserPolicyFactory object. * * @param {RequestPolicy} nextPolicy * @param {RequestPolicyOptions} options * @returns {StorageBrowserPolicy} * @memberof StorageBrowserPolicyFactory */ StorageBrowserPolicyFactory.prototype.create = function (nextPolicy, options) { return new StorageBrowserPolicy(nextPolicy, options); }; return StorageBrowserPolicyFactory; }()); // Copyright (c) Microsoft Corporation. All rights reserved. (function (StorageRetryPolicyType) { /** * Exponential retry. Retry time delay grows exponentially. */ StorageRetryPolicyType[StorageRetryPolicyType["EXPONENTIAL"] = 0] = "EXPONENTIAL"; /** * Linear retry. Retry time delay grows linearly. */ StorageRetryPolicyType[StorageRetryPolicyType["FIXED"] = 1] = "FIXED"; })(exports.StorageRetryPolicyType || (exports.StorageRetryPolicyType = {})); // Default values of StorageRetryOptions var DEFAULT_RETRY_OPTIONS = { maxRetryDelayInMs: 120 * 1000, maxTries: 4, retryDelayInMs: 4 * 1000, retryPolicyType: exports.StorageRetryPolicyType.EXPONENTIAL, secondaryHost: "", tryTimeoutInMs: undefined // Use server side default timeout strategy }; var RETRY_ABORT_ERROR = new abortController.AbortError("The operation was aborted."); /** * Retry policy with exponential retry and linear retry implemented. * * @class RetryPolicy * @extends {BaseRequestPolicy} */ var StorageRetryPolicy = /** @class */ (function (_super) { tslib.__extends(StorageRetryPolicy, _super); /** * Creates an instance of RetryPolicy. * * @param {RequestPolicy} nextPolicy * @param {RequestPolicyOptions} options * @param {StorageRetryOptions} [retryOptions=DEFAULT_RETRY_OPTIONS] * @memberof StorageRetryPolicy */ function StorageRetryPolicy(nextPolicy, options, retryOptions) { if (retryOptions === void 0) { retryOptions = DEFAULT_RETRY_OPTIONS; } var _this = _super.call(this, nextPolicy, options) || this; // Initialize retry options _this.retryOptions = { retryPolicyType: retryOptions.retryPolicyType ? retryOptions.retryPolicyType : DEFAULT_RETRY_OPTIONS.retryPolicyType, maxTries: retryOptions.maxTries && retryOptions.maxTries >= 1 ? Math.floor(retryOptions.maxTries) : DEFAULT_RETRY_OPTIONS.maxTries, tryTimeoutInMs: retryOptions.tryTimeoutInMs && retryOptions.tryTimeoutInMs >= 0 ? retryOptions.tryTimeoutInMs : DEFAULT_RETRY_OPTIONS.tryTimeoutInMs, retryDelayInMs: retryOptions.retryDelayInMs && retryOptions.retryDelayInMs >= 0 ? Math.min(retryOptions.retryDelayInMs, retryOptions.maxRetryDelayInMs ? retryOptions.maxRetryDelayInMs : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs) : DEFAULT_RETRY_OPTIONS.retryDelayInMs, maxRetryDelayInMs: retryOptions.maxRetryDelayInMs && retryOptions.maxRetryDelayInMs >= 0 ? retryOptions.maxRetryDelayInMs : DEFAULT_RETRY_OPTIONS.maxRetryDelayInMs, secondaryHost: retryOptions.secondaryHost ? retryOptions.secondaryHost : DEFAULT_RETRY_OPTIONS.secondaryHost }; return _this; } /** * Sends request. * * @param {WebResource} request * @returns {Promise} * @memberof StorageRetryPolicy */ 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)]; }); }); }; /** * Decide and perform next retry. Won't mutate request parameter. * * @protected * @param {WebResource} request * @param {boolean} secondaryHas404 If attempt was against the secondary & it returned a StatusNotFound (404), then * 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. * @param {number} attempt How many retries has been attempted to performed, starting from 1, which includes * the attempt will be performed by this method call. * @returns {Promise} * @memberof StorageRetryPolicy */ 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()]; } }); }); }; /** * Decide whether to retry according to last HTTP response and retry counters. * * @protected * @param {boolean} isPrimaryRetry * @param {number} attempt * @param {HttpOperationResponse} [response] * @param {RestError} [err] * @returns {boolean} * @memberof StorageRetryPolicy */ StorageRetryPolicy.prototype.shouldRetry = function (isPrimaryRetry, attempt, response, err) { if (attempt >= this.retryOptions.maxTries) { 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 = [ "ETIMEDOUT", "ESOCKETTIMEDOUT", "ECONNREFUSED", "ECONNRESET", "ENOENT", "ENOTFOUND", "TIMEOUT", "EPIPE", "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]; if (err.name.toUpperCase().includes(retriableError) || err.message.toUpperCase().includes(retriableError) || (err.code && err.code .toString() .toUpperCase() .includes(retriableError))) { logger.info("RetryPolicy: Network error " + retriableError + " found, will retry."); return true; } } } // If attempt was against the secondary & it returned a StatusNotFound (404), then // 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; if (!isPrimaryRetry && statusCode === 404) { 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 + "."); return true; } } return false; }; /** * Delay a calculated time between retries. * * @private * @param {boolean} isPrimaryRetry * @param {number} attempt * @param {AbortSignalLike} [abortSignal] * @memberof StorageRetryPolicy */ 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)); // Copyright (c) Microsoft Corporation. All rights reserved. /** * StorageRetryPolicyFactory is a factory class helping generating {@link StorageRetryPolicy} objects. * * @export * @class StorageRetryPolicyFactory * @implements {RequestPolicyFactory} */ var StorageRetryPolicyFactory = /** @class */ (function () { /** * Creates an instance of StorageRetryPolicyFactory. * @param {StorageRetryOptions} [retryOptions] * @memberof StorageRetryPolicyFactory */ function StorageRetryPolicyFactory(retryOptions) { this.retryOptions = retryOptions; } /** * Creates a StorageRetryPolicy object. * * @param {RequestPolicy} nextPolicy * @param {RequestPolicyOptions} options * @returns {StorageRetryPolicy} * @memberof StorageRetryPolicyFactory */ StorageRetryPolicyFactory.prototype.create = function (nextPolicy, options) { return new StorageRetryPolicy(nextPolicy, options, this.retryOptions); }; return StorageRetryPolicyFactory; }()); // Copyright (c) Microsoft Corporation. All rights reserved. /** * Credential policy used to sign HTTP(S) requests before sending. This is an * abstract class. * * @export * @abstract * @class CredentialPolicy * @extends {BaseRequestPolicy} */ var CredentialPolicy = /** @class */ (function (_super) { tslib.__extends(CredentialPolicy, _super); function CredentialPolicy() { return _super !== null && _super.apply(this, arguments) || this; } /** * Sends out request. * * @param {WebResource} request * @returns {Promise} * @memberof CredentialPolicy */ CredentialPolicy.prototype.sendRequest = function (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}. * * @protected * @abstract * @param {WebResource} request * @returns {WebResource} * @memberof CredentialPolicy */ CredentialPolicy.prototype.signRequest = function (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. All rights reserved. /** * AnonymousCredentialPolicy is used with HTTP(S) requests that read public resources * or for use with Shared Access Signatures (SAS). * * @export * @class AnonymousCredentialPolicy * @extends {CredentialPolicy} */ var AnonymousCredentialPolicy = /** @class */ (function (_super) { tslib.__extends(AnonymousCredentialPolicy, _super); /** * Creates an instance of AnonymousCredentialPolicy. * @param {RequestPolicy} nextPolicy * @param {RequestPolicyOptions} options * @memberof AnonymousCredentialPolicy */ function AnonymousCredentialPolicy(nextPolicy, options) { return _super.call(this, nextPolicy, options) || this; } return AnonymousCredentialPolicy; }(CredentialPolicy)); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /** * Credential is an abstract class for Azure Storage HTTP requests signing. This * class will host an credentialPolicyCreator factory which generates CredentialPolicy. * * @export * @abstract * @class Credential */ var Credential = /** @class */ (function () { function Credential() { } /** * Creates a RequestPolicy object. * * @param {RequestPolicy} _nextPolicy * @param {RequestPolicyOptions} _options * @returns {RequestPolicy} * @memberof Credential */ Credential.prototype.create = function ( // tslint:disable-next-line:variable-name _nextPolicy, // tslint:disable-next-line:variable-name _options) { throw new Error("Method should be implemented in children classes."); }; return Credential; }()); // Copyright (c) Microsoft Corporation. All rights reserved. /** * AnonymousCredential provides a credentialPolicyCreator member used to create * AnonymousCredentialPolicy objects. AnonymousCredentialPolicy is used with * HTTP(S) requests that read public resources or for use with Shared Access * Signatures (SAS). * * @export * @class AnonymousCredential * @extends {Credential} */ var AnonymousCredential = /** @class */ (function (_super) { tslib.__extends(AnonymousCredential, _super); function AnonymousCredential() { return _super !== null && _super.apply(this, arguments) || this; } /** * Creates an {@link AnonymousCredentialPolicy} object. * * @param {RequestPolicy} nextPolicy * @param {RequestPolicyOptions} options * @returns {AnonymousCredentialPolicy} * @memberof AnonymousCredential */ AnonymousCredential.prototype.create = function (nextPolicy, options) { return new AnonymousCredentialPolicy(nextPolicy, options); }; return AnonymousCredential; }(Credential)); // Copyright (c) Microsoft Corporation. All rights reserved. /** * TelemetryPolicy is a policy used to tag user-agent header for every requests. * * @class TelemetryPolicy * @extends {BaseRequestPolicy} */ var TelemetryPolicy = /** @class */ (function (_super) { tslib.__extends(TelemetryPolicy, _super); /** * Creates an instance of TelemetryPolicy. * @param {RequestPolicy} nextPolicy * @param {RequestPolicyOptions} options * @param {string} telemetry * @memberof TelemetryPolicy */ function TelemetryPolicy(nextPolicy, options, telemetry) { var _this = _super.call(this, nextPolicy, options) || this; _this.telemetry = telemetry; return _this; } /** * Sends out request. * * @param {WebResource} request * @returns {Promise} * @memberof TelemetryPolicy */ 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)); // Copyright (c) Microsoft Corporation. All rights reserved. /** * TelemetryPolicyFactory is a factory class helping generating {@link TelemetryPolicy} objects. * * @export * @class TelemetryPolicyFactory * @implements {RequestPolicyFactory} */ var TelemetryPolicyFactory = /** @class */ (function () { /** * Creates an instance of TelemetryPolicyFactory. * @param {UserAgentOptions} [telemetry] * @memberof TelemetryPolicyFactory */ function TelemetryPolicyFactory(telemetry) { var userAgentInfo = []; { if (telemetry) { // FIXME: replace() only replaces the first space. And we have no idea why we need to replace spaces in the first place. // But fixing this would be a breaking change. Logged an issue here: https://github.com/Azure/azure-sdk-for-js/issues/10793 var telemetryString = (telemetry.userAgentPrefix || "").replace(" ", ""); if (telemetryString.length > 0 && userAgentInfo.indexOf(telemetryString) === -1) { userAgentInfo.push(telemetryString); } } // e.g. azsdk-js-storageblob/10.0.0 var 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() + ")"; if (userAgentInfo.indexOf(runtimeInfo) === -1) { userAgentInfo.push(runtimeInfo); } } this.telemetryString = userAgentInfo.join(" "); } /** * Creates a TelemetryPolicy object. * * @param {RequestPolicy} nextPolicy * @param {RequestPolicyOptions} options * @returns {TelemetryPolicy} * @memberof TelemetryPolicyFactory */ TelemetryPolicyFactory.prototype.create = function (nextPolicy, options) { return new TelemetryPolicy(nextPolicy, options, this.telemetryString); }; return TelemetryPolicyFactory; }()); // Copyright (c) Microsoft Corporation. var _defaultHttpClient = new coreHttp.DefaultHttpClient(); function getCachedDefaultHttpClient() { return _defaultHttpClient; } // Copyright (c) Microsoft Corporation. All rights reserved. /** * A Pipeline class containing HTTP request policies. * You can create a default Pipeline by calling {@link newPipeline}. * Or you can create a Pipeline with your own policies by the constructor of Pipeline. * * Refer to {@link newPipeline} and provided policies before implementing your * customized Pipeline. * * @export * @class Pipeline */ var Pipeline = /** @class */ (function () { /** * Creates an instance of Pipeline. Customize HTTPClient by implementing IHttpClient interface. * * @param {RequestPolicyFactory[]} factories * @param {PipelineOptions} [options={}] * @memberof Pipeline */ function Pipeline(factories, options) { if (options === void 0) { 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() }); } /** * Transfer Pipeline object to ServiceClientOptions object which is required by * ServiceClient constructor. * * @returns {ServiceClientOptions} The ServiceClientOptions object from this Pipeline. * @memberof Pipeline */ Pipeline.prototype.toServiceClientOptions = function () { return { httpClient: this.options.httpClient, requestPolicyFactories: this.factories }; }; return Pipeline; }()); /** * Creates a new Pipeline object with Credential provided. * * @export * @param {StorageSharedKeyCredential | AnonymousCredential | TokenCredential} 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. * @param {StoragePipelineOptions} [pipelineOptions] Optional. Options. * @returns {Pipeline} A new Pipeline object. */ function newPipeline(credential, pipelineOptions) { if (pipelineOptions === void 0) { 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 = [ coreHttp.tracingPolicy({ userAgent: telemetryPolicy.telemetryString }), coreHttp.keepAlivePolicy(pipelineOptions.keepAliveOptions), telemetryPolicy, coreHttp.generateClientRequestIdPolicy(), new StorageBrowserPolicyFactory(), coreHttp.deserializationPolicy(), new StorageRetryPolicyFactory(pipelineOptions.retryOptions), coreHttp.logPolicy({ logger: logger.info, allowedHeaderNames: StorageBlobLoggingAllowedHeaderNames, allowedQueryParameters: StorageBlobLoggingAllowedQueryParameters }) ]; { // policies only available in Node.js runtime, not in browsers factories.push(coreHttp.proxyPolicy(pipelineOptions.proxyOptions)); factories.push(coreHttp.disableResponseDecompressionPolicy()); } factories.push(coreHttp.isTokenCredential(credential) ? coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes) : credential); return new Pipeline(factories, pipelineOptions); } // Copyright (c) Microsoft Corporation. All rights reserved. var ABORT_ERROR = new abortController.AbortError("The operation was aborted."); /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * A Node.js ReadableStream will internally retry when internal ReadableStream unexpected ends. * * @class RetriableReadableStream * @extends {Readable} */ var RetriableReadableStream = /** @class */ (function (_super) { tslib.__extends(RetriableReadableStream, _super); /** * Creates an instance of RetriableReadableStream. * * @param {NodeJS.ReadableStream} source The current ReadableStream returned from getter * @param {ReadableStreamGetter} getter A method calling downloading request returning * a new ReadableStream from specified offset * @param {number} offset Offset position in original data source to read * @param {number} count How much data in original data source to read * @param {RetriableReadableStreamOptions} [options={}] * @memberof RetriableReadableStream */ function RetriableReadableStream(source, getter, offset, count, options) { if (options === void 0) { options = {}; } var _this = _super.call(this) || this; _this.retries = 0; _this.abortHandler = function () { _this.source.pause(); _this.emit("error", ABORT_ERROR); }; _this.aborter = options.abortSignal || abortController.AbortSignal.none; _this.getter = getter; _this.source = source; _this.start = offset; _this.offset = offset; _this.end = offset + count - 1; _this.maxRetryRequests = options.maxRetryRequests && options.maxRetryRequests >= 0 ? options.maxRetryRequests : 0; _this.onProgress = options.onProgress; _this.options = options; _this.aborter.addEventListener("abort", _this.abortHandler); _this.setSourceDataHandler(); _this.setSourceEndHandler(); _this.setSourceErrorHandler(); return _this; } RetriableReadableStream.prototype._read = function () { if (!this.aborter.aborted) { this.source.resume(); } }; RetriableReadableStream.prototype.setSourceDataHandler = function () { var _this = this; this.source.on("data", function (data) { if (_this.options.doInjectErrorOnce) { _this.options.doInjectErrorOnce = undefined; _this.source.pause(); _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 }); } if (!_this.push(data)) { _this.source.pause(); } }); }; RetriableReadableStream.prototype.setSourceEndHandler = function () { var _this = this; this.source.on("end", function () { // console.log( // `Source stream emits end, offset: ${ // this.offset // }, dest end : ${this.end}` // ); if (_this.offset - 1 === _this.end) { _this.aborter.removeEventListener("abort", _this.abortHandler); _this.push(null); } 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.setSourceDataHandler(); _this.setSourceEndHandler(); _this.setSourceErrorHandler(); }) .catch(function (error) { _this.emit("error", error); }); } else { _this.emit("error", new Error( // tslint:disable-next-line:max-line-length "Data corruption failure: received less data than required and reached maxRetires limitation. Received data offset: " + (_this .offset - 1) + ", data needed offset: " + _this.end + ", retries: " + _this.retries + ", max retries: " + _this.maxRetryRequests)); } } else { _this.emit("error", new Error("Data corruption failure: Received more data than original request, data needed offset is " + _this.end + ", received offset: " + (_this.offset - 1))); } }); }; RetriableReadableStream.prototype.setSourceErrorHandler = function () { var _this = this; this.source.on("error", function (error) { _this.emit("error", error); }); }; return RetriableReadableStream; }(stream.Readable)); // Copyright (c) Microsoft Corporation. All rights reserved. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * BlobDownloadResponse implements BlobDownloadResponseParsed interface, and in Node.js runtime it will * automatically retry when internal read stream unexpected ends. (This kind of unexpected ends cannot * trigger retries defined in pipeline retry policy.) * * The {@link readableStreamBody} stream will retry underlayer, you can just use it as a normal Node.js * Readable stream. * * @export * @class BlobDownloadResponse * @implements {BlobDownloadResponseParsed} */ var BlobDownloadResponse = /** @class */ (function () { /** * Creates an instance of BlobDownloadResponse. * * @param {BlobDownloadResponseParsed} originalResponse * @param {ReadableStreamGetter} getter * @param {number} offset * @param {number} count * @param {RetriableReadableStreamOptions} [options={}] * @memberof BlobDownloadResponse */ function BlobDownloadResponse(originalResponse, getter, offset, count, options) { if (options === void 0) { 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 * @type {(string | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(string | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(string | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(string | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(string | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(number | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(BlobType | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(number | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(Uint8Array | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(string | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(string | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(Date | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(string | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(string | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(string | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(CopyStatusType | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(string | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(LeaseDurationType | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(LeaseStateType | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(LeaseStatusType | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(Date | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(number | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(string | undefined)} * @memberof BlobDownloadResponse */ get: function () { return this.originalResponse.etag; }, enumerable: false, configurable: true }); Object.defineProperty(BlobDownloadResponse.prototype, "tagCount", { /** * The number of tags associated with the blob * * @readonly * @type {(number | undefined)} * @memberof BlobDownloadResponse */ get: function () { return this.originalResponse.tagCount; }, enumerable: false, configurable: true }); Object.defineProperty(BlobDownloadResponse.prototype, "errorCode", { /** * The error code. * * @readonly * @type {(string | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(boolean | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(Uint8Array | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(Date | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(Date | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(Metadata | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(string | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(string | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(string | undefined)} * @memberof BlobDownloadResponse */ get: function () { return this.originalResponse.version; }, enumerable: false, configurable: true }); Object.defineProperty(BlobDownloadResponse.prototype, "versionId", { /** * Indicates the versionId of the downloaded blob version. * * @readonly * @type {(string | undefined)} * @memberof BlobDownloadResponse */ get: function () { return this.originalResponse.versionId; }, 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 * @type {(string | undefined)} * @memberof BlobDownloadResponse */ 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) * * @type {(Uint8Array | undefined)} * @memberof BlobDownloadResponse */ get: function () { return this.originalResponse.contentCrc64; }, enumerable: false, configurable: true }); Object.defineProperty(BlobDownloadResponse.prototype, "objectReplicationDestinationPolicyId", { /** * Object Replication Policy Id of the destination blob. * * @readonly * @type {(string| undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(ObjectReplicationPolicy[] | undefined)} * @memberof BlobDownloadResponse */ get: function () { return this.originalResponse.objectReplicationSourceProperties; }, enumerable: false, configurable: true }); Object.defineProperty(BlobDownloadResponse.prototype, "isSealed", { /** * If this blob has been sealed. * * @readonly * @type {(boolean | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(Promise | undefined)} * @memberof BlobDownloadResponse */ 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 * @type {(NodeJS.ReadableStream | undefined)} * @memberof BlobDownloadResponse */ get: function () { return coreHttp.isNode ? this.blobDownloadStream : undefined; }, enumerable: false, configurable: true }); Object.defineProperty(BlobDownloadResponse.prototype, "_response", { /** * The HTTP response. * * @type {HttpResponse} * @memberof BlobDownloadResponse */ get: function () { return this.originalResponse._response; }, enumerable: false, configurable: true }); return BlobDownloadResponse; }()); // 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"; // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. function arraysEqual(a, b) { if (a === b) return true; if (a == null || b == null) return false; if (a.length != b.length) return false; for (var i = 0; i < a.length; ++i) { if (a[i] !== b[i]) return false; } return true; } // Copyright (c) Microsoft Corporation. var AvroParser = /** @class */ (function () { function AvroParser() { } /** * Reads a fixed number of bytes from the stream. * * @static * @param {AvroReadable} [stream] * @param {number} [length] * @param {AvroParserReadOptions} [options={}] * @returns {Promise} * @memberof AvroParser */ 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]; } }); }); }; /** * Reads a single byte from the stream. * * @static * @param {AvroReadable} [stream] * @param {AvroParserReadOptions} [options={}] * @returns {Promise} * @memberof AvroParser */ 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]]; } }); }); }; // 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" && typeof require !== "undefined") { global.TextDecoder = require("util").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; }()); var AvroComplex; (function (AvroComplex) { AvroComplex["RECORD"] = "record"; AvroComplex["ENUM"] = "enum"; AvroComplex["ARRAY"] = "array"; AvroComplex["MAP"] = "map"; AvroComplex["UNION"] = "union"; AvroComplex["FIXED"] = "fixed"; })(AvroComplex || (AvroComplex = {})); var AvroType = /** @class */ (function () { function AvroType() { } /** * Determines the AvroType from the Avro Schema. */ AvroType.fromSchema = function (schema) { if (typeof schema == "string") { return AvroType.fromStringSchema(schema); } else if (Array.isArray(schema)) { return AvroType.fromArraySchema(schema); } else { return AvroType.fromObjectSchema(schema); } }; AvroType.fromStringSchema = function (schema) { switch (schema) { case AvroPrimitive.NULL: case AvroPrimitive.BOOLEAN: case AvroPrimitive.INT: case AvroPrimitive.LONG: case AvroPrimitive.FLOAT: case AvroPrimitive.DOUBLE: case AvroPrimitive.BYTES: case AvroPrimitive.STRING: return new AvroPrimitiveType(schema); default: throw new Error("Unexpected Avro type " + schema); } }; AvroType.fromArraySchema = function (schema) { return new AvroUnionType(schema.map(AvroType.fromSchema)); }; AvroType.fromObjectSchema = function (schema) { var type = schema.type; // Primitives can be defined as strings or objects try { return AvroType.fromStringSchema(type); } catch (err) { } switch (type) { case AvroComplex.RECORD: if (schema.aliases) { 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); } var fields = {}; if (!schema.fields) { 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]; 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); } if (!schema.symbols) { 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); } 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); } }; return AvroType; }()); var AvroPrimitive; (function (AvroPrimitive) { AvroPrimitive["NULL"] = "null"; AvroPrimitive["BOOLEAN"] = "boolean"; AvroPrimitive["INT"] = "int"; AvroPrimitive["LONG"] = "long"; AvroPrimitive["FLOAT"] = "float"; AvroPrimitive["DOUBLE"] = "double"; 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; } 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; } 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; } 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; } 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; } 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)); // Copyright (c) Microsoft Corporation. var AvroReader = /** @class */ (function () { function AvroReader(dataStream, headerStream, currentBlockOffset, indexWithinCurrentBlock) { this._dataStream = dataStream; this._headerStream = headerStream || dataStream; this._initialized = false; this._blockOffset = currentBlockOffset || 0; 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*/]; } }); }); }; AvroReader.prototype.hasNext = function () { 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(); // We hit the end of the stream. this._itemsRemainingInBlock = 0; return [3 /*break*/, 8]; case 8: if (!(this._itemsRemainingInBlock > 0)) return [3 /*break*/, 10]; // 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*/]; } }); }); }; return AvroReader; }()); // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. var AvroReadable = /** @class */ (function () { function AvroReadable() { } return AvroReadable; }()); // Copyright (c) Microsoft Corporation. var ABORT_ERROR$1 = new abortController.AbortError("Reading from the avro stream was aborted."); var AvroReadableFromStream = /** @class */ (function (_super) { tslib.__extends(AvroReadableFromStream, _super); function AvroReadableFromStream(readable) { var _this = _super.call(this) || this; _this._readable = readable; _this._position = 0; return _this; } AvroReadableFromStream.prototype.toUint8Array = function (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) { 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$1; } 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$1); }; _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. All rights reserved. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * A Node.js BlobQuickQueryStream will internally parse avro data stream for blob query. * * @class BlobQuickQueryStream * @extends {Readable} */ var BlobQuickQueryStream = /** @class */ (function (_super) { tslib.__extends(BlobQuickQueryStream, _super); /** * Creates an instance of BlobQuickQueryStream. * * @param {NodeJS.ReadableStream} source The current ReadableStream returned from getter * @param {BlobQuickQueryStreamOptions} [options={}] * @memberof BlobQuickQueryStream */ function BlobQuickQueryStream(source, options) { if (options === void 0) { options = {}; } var _this = _super.call(this) || this; _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; } BlobQuickQueryStream.prototype._read = function () { var _this = this; this.readInternal().catch(function (err) { _this.emit("error", err); }); }; BlobQuickQueryStream.prototype.readInternal = function () { var e_1, _a; return tslib.__awaiter(this, void 0, void 0, function () { var _b, _c, obj, schema, exit, data, bytesScanned, totalBytes, fatal, name_1, description, position, e_1_1; return tslib.__generator(this, function (_d) { switch (_d.label) { case 0: _d.trys.push([0, 5, 6, 11]); _b = tslib.__asyncValues(this.avroIter); _d.label = 1; case 1: return [4 /*yield*/, _b.next()]; case 2: if (!(_c = _d.sent(), !_c.done)) return [3 /*break*/, 4]; obj = _c.value; schema = obj.$schema; if (typeof schema !== "string") { throw Error("Missing schema in avro record."); } exit = false; switch (schema) { case "com.microsoft.azure.storage.queryBlobContents.resultData": data = obj.data; if (data instanceof Uint8Array === false) { throw Error("Invalid data in avro result record."); } if (!this.push(Buffer.from(data))) { exit = 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."); } if (exit) { return [3 /*break*/, 4]; } _d.label = 3; case 3: return [3 /*break*/, 1]; case 4: return [3 /*break*/, 11]; case 5: e_1_1 = _d.sent(); e_1 = { error: e_1_1 }; return [3 /*break*/, 11]; case 6: _d.trys.push([6, , 9, 10]); if (!(_c && !_c.done && (_a = _b.return))) return [3 /*break*/, 8]; return [4 /*yield*/, _a.call(_b)]; case 7: _d.sent(); _d.label = 8; case 8: return [3 /*break*/, 10]; case 9: if (e_1) throw e_1.error; return [7 /*endfinally*/]; case 10: return [7 /*endfinally*/]; case 11: return [2 /*return*/]; } }); }); }; return BlobQuickQueryStream; }(stream.Readable)); // Copyright (c) Microsoft Corporation. All rights reserved. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * BlobQueryResponse implements BlobDownloadResponseModel interface, and in Node.js runtime it will * parse avor data returned by blob query. * * @export * @class BlobQueryResponse * @implements {BlobDownloadResponseModel} */ var BlobQueryResponse = /** @class */ (function () { /** * Creates an instance of BlobQueryResponse. * * @param {BlobQueryResponseModel} originalResponse * @param {BlobQuickQueryStreamOptions} [options={}] * @memberof BlobQueryResponse */ function BlobQueryResponse(originalResponse, options) { if (options === void 0) { 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 * @type {(string | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(string | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(string | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(string | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(string | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(number | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(BlobType | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(number | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(Uint8Array | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(string | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(string | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(Date | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(string | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(string | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(string | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(CopyStatusType | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(string | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(LeaseDurationType | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(LeaseStateType | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(LeaseStatusType | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(Date | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(number | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(string | undefined)} * @memberof BlobQueryResponse */ get: function () { return this.originalResponse.etag; }, enumerable: false, configurable: true }); Object.defineProperty(BlobQueryResponse.prototype, "errorCode", { /** * The error code. * * @readonly * @type {(string | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(boolean | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(Uint8Array | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(Date | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(Metadata | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(string | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(string | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(string | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(string | undefined)} * @memberof BlobQueryResponse */ 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) * * @type {(Uint8Array | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(Promise | undefined)} * @memberof BlobQueryResponse */ 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 * @type {(NodeJS.ReadableStream | undefined)} * @memberof BlobQueryResponse */ get: function () { return coreHttp.isNode ? this.blobDownloadStream : undefined; }, enumerable: false, configurable: true }); Object.defineProperty(BlobQueryResponse.prototype, "_response", { /** * The HTTP response. * * @type {HttpResponse} * @memberof BlobQueryResponse */ get: function () { return this.originalResponse._response; }, enumerable: false, configurable: true }); return BlobQueryResponse; }()); // Copyright (c) Microsoft Corporation. All rights reserved. /** * StorageSharedKeyCredentialPolicy is a policy used to sign HTTP request with a shared key. * * @export * @class StorageSharedKeyCredentialPolicy * @extends {CredentialPolicy} */ var StorageSharedKeyCredentialPolicy = /** @class */ (function (_super) { tslib.__extends(StorageSharedKeyCredentialPolicy, _super); /** * Creates an instance of StorageSharedKeyCredentialPolicy. * @param {RequestPolicy} nextPolicy * @param {RequestPolicyOptions} options * @param {StorageSharedKeyCredential} factory * @memberof StorageSharedKeyCredentialPolicy */ function StorageSharedKeyCredentialPolicy(nextPolicy, options, factory) { var _this = _super.call(this, nextPolicy, options) || this; _this.factory = factory; return _this; } /** * Signs request. * * @protected * @param {WebResource} request * @returns {WebResource} * @memberof StorageSharedKeyCredentialPolicy */ StorageSharedKeyCredentialPolicy.prototype.signRequest = function (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 = [ request.method.toUpperCase(), this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LANGUAGE), this.getHeaderValueToSign(request, HeaderConstants.CONTENT_ENCODING), this.getHeaderValueToSign(request, HeaderConstants.CONTENT_LENGTH), this.getHeaderValueToSign(request, HeaderConstants.CONTENT_MD5), this.getHeaderValueToSign(request, HeaderConstants.CONTENT_TYPE), this.getHeaderValueToSign(request, HeaderConstants.DATE), this.getHeaderValueToSign(request, HeaderConstants.IF_MODIFIED_SINCE), this.getHeaderValueToSign(request, HeaderConstants.IF_MATCH), this.getHeaderValueToSign(request, HeaderConstants.IF_NONE_MATCH), this.getHeaderValueToSign(request, HeaderConstants.IF_UNMODIFIED_SINCE), this.getHeaderValueToSign(request, HeaderConstants.RANGE) ].join("\n") + "\n" + this.getCanonicalizedHeadersString(request) + this.getCanonicalizedResourceString(request); var 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 * * @private * @param {WebResource} request * @param {string} headerName * @returns {string} * @memberof StorageSharedKeyCredentialPolicy */ StorageSharedKeyCredentialPolicy.prototype.getHeaderValueToSign = function (request, headerName) { var value = request.headers.get(headerName); if (!value) { return ""; } // When using version 2015-02-21 or later, if Content-Length is zero, then // set the Content-Length part of the StringToSign to an empty string. // https://docs.microsoft.com/en-us/rest/api/storageservices/authenticate-with-shared-key if (headerName === HeaderConstants.CONTENT_LENGTH && value === "0") { 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. * 2. Convert each HTTP header name to lowercase. * 3. Sort the headers lexicographically by header name, in ascending order. * Each header may appear only once in the string. * 4. Replace any linear whitespace in the header value with a single space. * 5. Trim any whitespace around the colon in the header. * 6. Finally, append a new-line character to each canonicalized header in the resulting list. * Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string. * * @private * @param {WebResource} request * @returns {string} * @memberof StorageSharedKeyCredentialPolicy */ StorageSharedKeyCredentialPolicy.prototype.getCanonicalizedHeadersString = function (request) { var headersArray = request.headers.headersArray().filter(function (value) { return value.name.toLowerCase().startsWith(HeaderConstants.PREFIX_FOR_STORAGE); }); headersArray.sort(function (a, b) { return a.name.toLowerCase().localeCompare(b.name.toLowerCase()); }); // Remove duplicate headers headersArray = headersArray.filter(function (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 .toLowerCase() .trimRight() + ":" + header.value.trimLeft() + "\n"; }); return canonicalizedHeadersStringToSign; }; /** * Retrieves the webResource canonicalized resource string. * * @private * @param {WebResource} request * @returns {string} * @memberof StorageSharedKeyCredentialPolicy */ StorageSharedKeyCredentialPolicy.prototype.getCanonicalizedResourceString = function (request) { var path = getURLPath(request.url) || "/"; var canonicalizedResourceString = ""; canonicalizedResourceString += "/" + this.factory.accountName + path; var queries = getURLQueries(request.url); var lowercaseQueries = {}; if (queries) { var queryKeys = []; for (var key in queries) { if (queries.hasOwnProperty(key)) { var 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]); } } return canonicalizedResourceString; }; return StorageSharedKeyCredentialPolicy; }(CredentialPolicy)); // Copyright (c) Microsoft Corporation. All rights reserved. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * StorageSharedKeyCredential for account key authorization of Azure Storage service. * * @export * @class StorageSharedKeyCredential * @extends {Credential} */ var StorageSharedKeyCredential = /** @class */ (function (_super) { tslib.__extends(StorageSharedKeyCredential, _super); /** * Creates an instance of StorageSharedKeyCredential. * @param {string} accountName * @param {string} accountKey * @memberof StorageSharedKeyCredential */ function StorageSharedKeyCredential(accountName, accountKey) { var _this = _super.call(this) || this; _this.accountName = accountName; _this.accountKey = Buffer.from(accountKey, "base64"); return _this; } /** * Creates a StorageSharedKeyCredentialPolicy object. * * @param {RequestPolicy} nextPolicy * @param {RequestPolicyOptions} options * @returns {StorageSharedKeyCredentialPolicy} * @memberof StorageSharedKeyCredential */ StorageSharedKeyCredential.prototype.create = function (nextPolicy, options) { return new StorageSharedKeyCredentialPolicy(nextPolicy, options, this); }; /** * Generates a hash signature for an HTTP request or for a SAS. * * @param {string} stringToSign * @returns {string} * @memberof StorageSharedKeyCredential */ StorageSharedKeyCredential.prototype.computeHMACSHA256 = function (stringToSign) { return crypto.createHmac("sha256", this.accountKey) .update(stringToSign, "utf8") .digest("base64"); }; return StorageSharedKeyCredential; }(Credential)); /* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * 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.3.0"; var StorageClientContext = /** @class */ (function (_super) { tslib.__extends(StorageClientContext, _super); /** * 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 * operation. * @param [options] The parameter options */ function StorageClientContext(url, options) { var _this = this; if (url == undefined) { throw new Error("'url' cannot be null."); } if (!options) { options = {}; } if (!options.userAgent) { var defaultUserAgent = coreHttp.getDefaultUserAgentValue(); options.userAgent = packageName + "/" + packageVersion + " " + defaultUserAgent; } _this = _super.call(this, undefined, options) || this; _this.version = "2020-02-10"; _this.baseUri = "{url}"; _this.requestContentType = "application/json; charset=utf-8"; _this.url = url; return _this; } return StorageClientContext; }(coreHttp.ServiceClient)); // Copyright (c) Microsoft Corporation. All rights reserved. (function (BlockBlobTier) { /** * Optimized for storing data that is accessed frequently. */ BlockBlobTier["Hot"] = "Hot"; /** * Optimized for storing data that is infrequently accessed and stored for at least 30 days. */ BlockBlobTier["Cool"] = "Cool"; /** * Optimized for storing data that is rarely accessed and stored for at least 180 days * with flexible latency requirements (on the order of hours). */ BlockBlobTier["Archive"] = "Archive"; })(exports.BlockBlobTier || (exports.BlockBlobTier = {})); (function (PremiumPageBlobTier) { /** * P4 Tier. */ PremiumPageBlobTier["P4"] = "P4"; /** * P6 Tier. */ PremiumPageBlobTier["P6"] = "P6"; /** * P10 Tier. */ PremiumPageBlobTier["P10"] = "P10"; /** * P15 Tier. */ PremiumPageBlobTier["P15"] = "P15"; /** * P20 Tier. */ PremiumPageBlobTier["P20"] = "P20"; /** * P30 Tier. */ PremiumPageBlobTier["P30"] = "P30"; /** * P40 Tier. */ PremiumPageBlobTier["P40"] = "P40"; /** * P50 Tier. */ PremiumPageBlobTier["P50"] = "P50"; /** * P60 Tier. */ PremiumPageBlobTier["P60"] = "P60"; /** * P70 Tier. */ PremiumPageBlobTier["P70"] = "P70"; /** * P80 Tier. */ PremiumPageBlobTier["P80"] = "P80"; })(exports.PremiumPageBlobTier || (exports.PremiumPageBlobTier = {})); function toAccessTier(tier) { 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). } function ensureCpkIfSpecified(cpk, isHttps) { if (cpk && !isHttps) { throw new RangeError("Customer-provided encryption key must be used over HTTPS."); } if (cpk && !cpk.encryptionAlgorithm) { cpk.encryptionAlgorithm = EncryptionAlgorithmAES25; } } /** * Function that converts PageRange and ClearRange to a common Range object. * PageRange and ClearRange have start and end while Range offset and count * this function normalizes to Range. * @param response Model PageBlob Range response */ function rangeResponseFromModel(response) { var pageRange = (response._response.parsedBody.pageRange || []).map(function (x) { return ({ offset: x.start, count: x.end - x.start }); }); var clearRange = (response._response.parsedBody.clearRange || []).map(function (x) { return ({ 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 } }) }); } // Copyright (c) Microsoft Corporation. All rights reserved. /** * This is the poller returned by {@link BlobClient.beginCopyFromURL}. * This can not be instantiated directly outside of this package. * * @ignore */ 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; 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; if (typeof onProgress === "function") { _this.onProgress(onProgress); } _this.intervalInMs = intervalInMs; return _this; } BlobBeginCopyFromUrlPoller.prototype.delay = function () { 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. * @ignore */ 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)]; } }); }); }; /** * 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. * @ignore */ 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)]; } }); }); }; /** * 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. * @ignore */ var toString = function toString() { return JSON.stringify({ state: this.state }, function (key, value) { // remove blobClient from serialized state since a client can't be hydrated from this info. if (key === "blobClient") { return undefined; } return value; }); }; /** * Creates a poll operation given the provided state. * @ignore */ function makeBlobBeginCopyFromURLPollOperation(state) { return { state: tslib.__assign({}, state), cancel: cancel, toString: toString, update: update }; } // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /** * Generate a range string. For example: * * "bytes=255-" or "bytes=0-511" * * @export * @param {Range} iRange * @returns {string} */ function rangeToString(iRange) { if (iRange.offset < 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."); } return iRange.count ? "bytes=" + iRange.offset + "-" + (iRange.offset + iRange.count - 1) : "bytes=" + iRange.offset + "-"; } // Copyright (c) Microsoft Corporation. All rights reserved. /** * A StorageClient represents a based URL class for {@link BlobServiceClient}, {@link ContainerClient} * and etc. * * @export * @class StorageClient */ var StorageClient = /** @class */ (function () { /** * Creates an instance of StorageClient. * @param {string} url url to resource * @param {Pipeline} pipeline request policy pipeline. * @memberof StorageClient */ function StorageClient(url, pipeline) { // URL should be encoded and only once, protocol layer shouldn't encode URL again this.url = escapeURLPath(url); this.accountName = getAccountNameFromUrl(url); this.pipeline = pipeline; 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]; if ((coreHttp.isNode && factory instanceof StorageSharedKeyCredential) || factory instanceof AnonymousCredential || coreHttp.isTokenCredential(factory)) { this.credential = factory; } } // Override protocol layer's default content-type var storageClientContext = this.storageClientContext; storageClientContext.requestContentType = undefined; } return StorageClient; }()); // Copyright (c) Microsoft Corporation. All rights reserved. /** * States for Batch. * * @enum {number} */ var BatchStates; (function (BatchStates) { BatchStates[BatchStates["Good"] = 0] = "Good"; BatchStates[BatchStates["Error"] = 1] = "Error"; })(BatchStates || (BatchStates = {})); /** * Batch provides basic parallel execution with concurrency limits. * 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. * * @export * @class Batch */ var Batch = /** @class */ (function () { /** * Creates an instance of Batch. * @param {number} [concurrency=5] * @memberof Batch */ function Batch(concurrency) { if (concurrency === void 0) { concurrency = 5; } /** * Number of active operations under execution. * * @private * @type {number} * @memberof Batch */ this.actives = 0; /** * Number of completed operations under execution. * * @private * @type {number} * @memberof Batch */ this.completed = 0; /** * Offset of next operation to be executed. * * @private * @type {number} * @memberof Batch */ this.offset = 0; /** * Operation array to be executed. * * @private * @type {Operation[]} * @memberof Batch */ this.operations = []; /** * States of Batch. When an error happens, state will turn into error. * Batch will stop execute left operations. * * @private * @type {BatchStates} * @memberof Batch */ this.state = BatchStates.Good; if (concurrency < 1) { throw new RangeError("concurrency must be larger than 0"); } this.concurrency = concurrency; this.emitter = new events.EventEmitter(); } /** * Add a operation into queue. * * @param {Operation} operation * @memberof Batch */ 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*/]; } }); }); }); }; /** * Start execute operations in the queue. * * @returns {Promise} * @memberof Batch */ 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); }); })]; }); }); }; /** * Get next operation to be executed. Return null when reaching ends. * * @private * @returns {(Operation | null)} * @memberof Batch */ Batch.prototype.nextOperation = function () { 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. * * @private * @returns {void} * @memberof Batch */ Batch.prototype.parallelExecute = function () { if (this.state === BatchStates.Error) { return; } if (this.completed >= this.operations.length) { this.emitter.emit("finish"); return; } while (this.actives < this.concurrency) { var operation = this.nextOperation(); if (operation) { operation(); } else { return; } } }; return Batch; }()); // Copyright (c) Microsoft Corporation. All rights reserved. /** * This class generates a readable stream from the data in an array of buffers. * * @export * @class BuffersStream */ var BuffersStream = /** @class */ (function (_super) { tslib.__extends(BuffersStream, _super); /** * Creates an instance of BuffersStream that will emit the data * contained in the array of buffers. * * @param {Buffer[]} buffers Array of buffers containing the data * @param {number} byteLength The total length of data contained in the buffers * @memberof BuffersStream */ 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; // 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]; buffersLength += buf.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 {number} size Optional. The size of data to be read * @memberof BuffersStream */ BuffersStream.prototype._read = function (size) { if (this.pushedBytesLength >= this.byteLength) { this.push(null); } if (!size) { size = this.readableHighWaterMark; } var outBuffers = []; var 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); if (remaining > size - i) { // chunkSize = size - i var end = this.byteOffsetInCurrentBuffer + size - i; outBuffers.push(this.buffers[this.bufferIndex].slice(this.byteOffsetInCurrentBuffer, end)); this.pushedBytesLength += size - i; this.byteOffsetInCurrentBuffer = end; i = size; break; } else { // chunkSize = remaining var 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 this.byteOffsetInCurrentBuffer = 0; this.bufferIndex++; } else { this.byteOffsetInCurrentBuffer = end; } this.pushedBytesLength += remaining; i += remaining; } } if (outBuffers.length > 1) { this.push(Buffer.concat(outBuffers)); } else if (outBuffers.length === 1) { this.push(outBuffers[0]); } }; return BuffersStream; }(stream.Readable)); // Copyright (c) Microsoft Corporation. All rights reserved. /** * maxBufferLength is max size of each buffer in the pooled buffers. */ // Can't use import as Typescript doesn't recognize "buffer". var maxBufferLength = require("buffer").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. * It will allocate an internal "buffer" of the capacity and fill the data in the input buffers * into the internal "buffer" serially with respect to the total length. * Then by calling PooledBuffer.getReadableStream(), you can get a readable stream * assembled from all the data in the internal "buffer". * * @export * @class BufferScheduler */ var PooledBuffer = /** @class */ (function () { function PooledBuffer(capacity, buffers, totalLength) { /** * Internal buffers used to keep the data. * Each buffer has a length of the maxBufferLength except last one. * * @private * @type {Buffer[]} * @memberof PooledBuffer */ this.buffers = []; 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; if (len === 0) { len = maxBufferLength; } this.buffers.push(Buffer.allocUnsafe(len)); } if (buffers) { 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 }); /** * 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. * Data copied will be shift out of the input buffers. * * @param {Buffer[]} buffers Input buffers containing the data to be filled in the pooled buffer * @param {number} totalLength Total length of the data to be filled in. * * @returns {void} * @memberof PooledBuffer */ PooledBuffer.prototype.fill = function (buffers, totalLength) { this._size = Math.min(this.capacity, totalLength); var 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); totalCopiedNum += copiedNum; sourceOffset += copiedNum; targetOffset += copiedNum; if (sourceOffset === source.length) { i++; sourceOffset = 0; } if (targetOffset === target.length) { j++; targetOffset = 0; } } // clear copied from source buffers buffers.splice(0, i); if (buffers.length > 0) { buffers[0] = buffers[0].slice(sourceOffset); } }; /** * Get the readable stream assembled from all the data in the internal buffers. * * @returns {Readable} * @memberof PooledBuffer */ PooledBuffer.prototype.getReadableStream = function () { return new BuffersStream(this.buffers, this.size); }; return PooledBuffer; }()); // Copyright (c) Microsoft Corporation. All rights reserved. /** * This class accepts a Node.js Readable stream as input, and keeps reading data * from the stream into the internal buffer structure, until it reaches maxBuffers. * Every available buffer will try to trigger outgoingHandler. * * The internal buffer structure includes an incoming buffer array, and a outgoing * buffer array. The incoming buffer array includes the "empty" buffers can be filled * with new incoming data. The outgoing array includes the filled buffers to be * handled by outgoingHandler. Every above buffer size is defined by parameter bufferSize. * * NUM_OF_ALL_BUFFERS = BUFFERS_IN_INCOMING + BUFFERS_IN_OUTGOING + BUFFERS_UNDER_HANDLING * * NUM_OF_ALL_BUFFERS <= maxBuffers * * PERFORMANCE IMPROVEMENT TIPS: * 1. Input stream highWaterMark is better to set a same value with bufferSize * parameter, which will avoid Buffer.concat() operations. * 2. concurrency should set a smaller value than maxBuffers, which is helpful to * reduce the possibility when a outgoing handler waits for the stream data. * in this situation, outgoing handlers are blocked. * Outgoing queue shouldn't be empty. * @export * @class BufferScheduler */ var BufferScheduler = /** @class */ (function () { /** * Creates an instance of BufferScheduler. * * @param {Readable} readable A Node.js Readable stream * @param {number} bufferSize Buffer size of every maintained buffer * @param {number} maxBuffers How many buffers can be allocated * @param {OutgoingHandler} outgoingHandler An async function scheduled to be * triggered when a buffer fully filled * with stream data * @param {number} concurrency Concurrency of executing outgoingHandlers (>0) * @param {string} [encoding] [Optional] Encoding of Readable stream when it's a string stream * @memberof BufferScheduler */ function BufferScheduler(readable, bufferSize, maxBuffers, outgoingHandler, concurrency, encoding) { /** * An internal event emitter. * * @private * @type {EventEmitter} * @memberof BufferScheduler */ this.emitter = new events.EventEmitter(); /** * An internal offset marker to track data offset in bytes of next outgoingHandler. * * @private * @type {number} * @memberof BufferScheduler */ this.offset = 0; /** * An internal marker to track whether stream is end. * * @private * @type {boolean} * @memberof BufferScheduler */ this.isStreamEnd = false; /** * An internal marker to track whether stream or outgoingHandler returns error. * * @private * @type {boolean} * @memberof BufferScheduler */ this.isError = false; /** * How many handlers are executing. * * @private * @type {number} * @memberof BufferScheduler */ this.executingOutgoingHandlers = 0; /** * How many buffers have been allocated. * * @private * @type {number} * @memberof BufferScheduler */ this.numBuffers = 0; /** * Because this class doesn't know how much data every time stream pops, which * is defined by highWaterMarker of the stream. So BufferScheduler will cache * data received from the stream, when data in unresolvedDataArray exceeds the * blockSize defined, it will try to concat a blockSize of buffer, fill into available * buffers from incoming and push to outgoing array. * * @private * @type {Buffer[]} * @memberof BufferScheduler */ this.unresolvedDataArray = []; /** * How much data consisted in unresolvedDataArray. * * @private * @type {number} * @memberof BufferScheduler */ this.unresolvedLength = 0; /** * The array includes all the available buffers can be used to fill data from stream. * * @private * @type {PooledBuffer[]} * @memberof BufferScheduler */ this.incoming = []; /** * The array (queue) includes all the buffers filled from stream data. * * @private * @type {PooledBuffer[]} * @memberof BufferScheduler */ this.outgoing = []; if (bufferSize <= 0) { 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); } if (concurrency <= 0) { throw new RangeError("concurrency must be larger than 0, current is " + concurrency); } this.bufferSize = bufferSize; this.maxBuffers = maxBuffers; this.readable = readable; this.outgoingHandler = outgoingHandler; this.concurrency = concurrency; this.encoding = encoding; } /** * Start the scheduler, will return error when stream of any of the outgoingHandlers * returns error. * * @returns {Promise} * @memberof BufferScheduler */ 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(); } } }); })]; }); }); }; /** * Insert a new data into unresolved array. * * @private * @param {Buffer} data * @memberof BufferScheduler */ BufferScheduler.prototype.appendUnresolvedData = function (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. * * @private * @returns {PooledBuffer} * @memberof BufferScheduler */ BufferScheduler.prototype.shiftBufferFromUnresolvedDataArray = function (buffer) { if (!buffer) { buffer = new PooledBuffer(this.bufferSize, this.unresolvedDataArray, this.unresolvedLength); } else { buffer.fill(this.unresolvedDataArray, this.unresolvedLength); } 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, * then push it into outgoing to be handled by outgoing handler. * * Return false when available buffers in incoming are not enough, else true. * * @private * @returns {boolean} Return false when buffers in incoming are not enough, else true. * @memberof BufferScheduler */ BufferScheduler.prototype.resolveData = function () { while (this.unresolvedLength >= this.bufferSize) { var buffer = void 0; if (this.incoming.length > 0) { buffer = this.incoming.shift(); this.shiftBufferFromUnresolvedDataArray(buffer); } else { if (this.numBuffers < this.maxBuffers) { buffer = this.shiftBufferFromUnresolvedDataArray(); this.numBuffers++; } else { // No available buffer, wait for buffer returned return false; } } this.outgoing.push(buffer); this.triggerOutgoingHandlers(); } return true; }; /** * Try to trigger a outgoing handler for every buffer in outgoing. Stop when * concurrency reaches. * * @private * @memberof BufferScheduler */ 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*/]; }); }); }; /** * Trigger a outgoing handler for a buffer shifted from outgoing. * * @private * @param {Buffer} buffer * @returns {Promise} * @memberof BufferScheduler */ 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*/]; } }); }); }; /** * Return buffer used by outgoing handler into incoming. * * @private * @param {Buffer} buffer * @memberof BufferScheduler */ BufferScheduler.prototype.reuseBuffer = function (buffer) { this.incoming.push(buffer); if (!this.isError && this.resolveData() && !this.isStreamEnd) { this.readable.resume(); } }; return BufferScheduler; }()); // Copyright (c) Microsoft Corporation. /** * Creates a span using the global tracer. * @param name The name of the operation being performed. * @param tracingOptions The options for the underlying http request. */ function createSpan(operationName, tracingOptions) { if (tracingOptions === void 0) { tracingOptions = {}; } var tracer = coreTracing.getTracer(); var spanOptions = tslib.__assign(tslib.__assign({}, tracingOptions.spanOptions), { kind: api.SpanKind.INTERNAL }); var span = tracer.startSpan("Azure.Storage.Blob." + operationName, spanOptions); span.setAttribute("az.namespace", "Microsoft.Storage"); var newOptions = tracingOptions.spanOptions || {}; if (span.isRecording()) { newOptions = tslib.__assign(tslib.__assign({}, tracingOptions.spanOptions), { parent: span.context(), attributes: tslib.__assign(tslib.__assign({}, spanOptions.attributes), { "az.namespace": "Microsoft.Storage" }) }); } return { span: span, spanOptions: newOptions }; } // Copyright (c) Microsoft Corporation. All rights reserved. /** * Reads a readable stream into buffer. Fill the buffer from offset to end. * * @export * @param {NodeJS.ReadableStream} stream A Node.js Readable stream * @param {Buffer} buffer Buffer to be filled, length must >= offset * @param {number} offset From which position in the buffer to be filled, inclusive * @param {number} end To which position in the buffer to be filled, exclusive * @param {string} [encoding] Encoding of the Readable stream * @returns {Promise} */ 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); })]; }); }); } /** * Reads a readable stream into buffer entirely. * * @export * @param {NodeJS.ReadableStream} stream A Node.js Readable stream * @param {Buffer} buffer Buffer to be filled, length must >= offset * @param {string} [encoding] Encoding of the Readable stream * @returns {Promise} 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); })]; }); }); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * Writes the content of a readstream to a local file. Returns a Promise which is completed after the file handle is closed. * * @export * @param {NodeJS.ReadableStream} rs The read stream. * @param {string} file Destination file path. * @returns {Promise} */ 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); })]; }); }); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * Promisified version of fs.stat(). */ var fsStat = util.promisify(fs.stat); var 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. * * @export * @class BlobClient */ var BlobClient = /** @class */ (function (_super) { tslib.__extends(BlobClient, _super); function BlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { var _a; var _this = this; options = options || {}; var pipeline; var url; if (credentialOrPipelineOrContainerName instanceof Pipeline) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; } else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) url = urlOrConnectionString; options = blobNameOrOptions; pipeline = newPipeline(credentialOrPipelineOrContainerName, options); } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) // The second parameter is undefined. Use anonymous credential. url = urlOrConnectionString; pipeline = newPipeline(new AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string" && blobNameOrOptions && typeof blobNameOrOptions === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) var containerName = credentialOrPipelineOrContainerName; var blobName = blobNameOrOptions; var extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { { var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); pipeline = newPipeline(sharedKeyCredential, options); } } else if (extractedCreds.kind === "SASConnString") { url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + "?" + extractedCreds.accountSas; pipeline = newPipeline(new AnonymousCredential(), options); } else { throw new Error("Connection string must be either an Account connection string or a SAS connection string"); } } else { throw new Error("Expecting non-empty strings for containerName and blobName parameters"); } _this = _super.call(this, url, pipeline) || this; (_a = _this.getBlobAndContainerNamesFromUrl(), _this._name = _a.blobName, _this._containerName = _a.containerName); _this.blobContext = new Blob$1(_this.storageClientContext); return _this; } Object.defineProperty(BlobClient.prototype, "name", { /** * The name of the blob. */ get: function () { return this._name; }, enumerable: false, configurable: true }); Object.defineProperty(BlobClient.prototype, "containerName", { /** * The name of the storage container the blob is associated with. */ get: function () { return this._containerName; }, enumerable: false, configurable: true }); /** * Creates a new BlobClient object identical to the source but with the specified snapshot timestamp. * Provide "" will remove the snapshot and return a Client to the base blob. * * @param {string} snapshot The snapshot timestamp. * @returns {BlobClient} A new BlobClient object identical to the source but with the specified snapshot timestamp * @memberof BlobClient */ BlobClient.prototype.withSnapshot = function (snapshot) { return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); }; /** * Creates a new BlobClient object pointing to a version of this blob. * Provide "" will remove the versionId and return a Client to the base blob. * * @param {string} versionId The versionId. * @returns {BlobClient} A new BlobClient object pointing to the version of this blob. * @memberof BlobClient */ BlobClient.prototype.withVersion = function (versionId) { return new BlobClient(setURLParameter(this.url, URLConstants.Parameters.VERSIONID, versionId.length === 0 ? undefined : versionId), this.pipeline); }; /** * Creates a AppendBlobClient object. * * @returns {AppendBlobClient} * @memberof BlobClient */ BlobClient.prototype.getAppendBlobClient = function () { return new AppendBlobClient(this.url, this.pipeline); }; /** * Creates a BlockBlobClient object. * * @returns {BlockBlobClient} * @memberof BlobClient */ BlobClient.prototype.getBlockBlobClient = function () { return new BlockBlobClient(this.url, this.pipeline); }; /** * Creates a PageBlobClient object. * * @returns {PageBlobClient} * @memberof BlobClient */ BlobClient.prototype.getPageBlobClient = function () { return new PageBlobClient(this.url, this.pipeline); }; /** * Reads or downloads a blob from the system, including its metadata and properties. * You can also call Get Blob to read a snapshot. * * * In Node.js, data returns in a Readable stream readableStreamBody * * In browsers, data returns in a promise blobBody * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob * * @param {number} [offset] From which position of the blob to download, >= 0 * @param {number} [count] How much data to be downloaded, > 0. Will download to the end when undefined * @param {BlobDownloadOptions} [options] Optional options to Blob Download operation. * @returns {Promise} * @memberof BlobClient * * Example usage (Node.js): * * ```js * // Download and convert a blob to a string * const downloadBlockBlobResponse = await blobClient.download(); * const downloaded = await streamToBuffer(downloadBlockBlobResponse.readableStreamBody); * console.log("Downloaded blob content:", downloaded.toString()); * * async function streamToBuffer(readableStream) { * return new Promise((resolve, reject) => { * const chunks = []; * readableStream.on("data", (data) => { * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); * }); * readableStream.on("end", () => { * resolve(Buffer.concat(chunks)); * }); * readableStream.on("error", reject); * }); * } * ``` * * Example usage (browser): * * ```js * // Download and convert a blob to a string * const downloadBlockBlobResponse = await blobClient.download(); * const downloaded = await blobToString(await downloadBlockBlobResponse.blobBody); * console.log( * "Downloaded blob content", * downloaded * ); * * async function blobToString(blob: Blob): Promise { * const fileReader = new FileReader(); * return new Promise((resolve, reject) => { * fileReader.onloadend = (ev: any) => { * resolve(ev.target!.result); * }; * fileReader.onerror = reject; * fileReader.readAsText(blob); * }); * } * ``` */ BlobClient.prototype.download = function (offset, count, options) { var _a; if (offset === void 0) { offset = 0; } if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, res_1, wrappedRes, e_1; var _this = this; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: options.conditions = options.conditions || {}; options.conditions = options.conditions || {}; ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); _b = createSpan("BlobClient-download", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.blobContext.download({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), onDownloadProgress: coreHttp.isNode ? undefined : options.onProgress, range: offset === 0 && !count ? undefined : rangeToString({ offset: offset, count: count }), rangeGetContentMD5: options.rangeGetContentMD5, rangeGetContentCRC64: options.rangeGetContentCrc64, snapshot: options.snapshot, cpkInfo: options.customerProvidedKey, spanOptions: spanOptions })]; case 2: res_1 = _c.sent(); wrappedRes = tslib.__assign(tslib.__assign({}, res_1), { _response: res_1._response, objectReplicationDestinationPolicyId: res_1.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res_1.objectReplicationRules) }); // We support retrying when download stream unexpected ends in Node.js runtime // Following code shouldn't be bundled into browser build, however some // bundlers may try to bundle following code and "FileReadResponse.ts". // In this case, "FileDownloadResponse.browser.ts" will be used as a shim of "FileDownloadResponse.ts" // The config is in package.json "browser" field if (options.maxRetryRequests === undefined || options.maxRetryRequests < 0) { // TODO: Default value or make it a required parameter? options.maxRetryRequests = DEFAULT_MAX_DOWNLOAD_RETRY_REQUESTS; } if (res_1.contentLength === undefined) { throw new RangeError("File download response doesn't contain valid content length header"); } if (!res_1.etag) { throw new RangeError("File download response doesn't contain valid etag header"); } return [2 /*return*/, new BlobDownloadResponse(wrappedRes, function (start) { return tslib.__awaiter(_this, void 0, void 0, function () { var updatedOptions; var _a; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: updatedOptions = { leaseAccessConditions: options.conditions, modifiedAccessConditions: { ifMatch: options.conditions.ifMatch || res_1.etag, ifModifiedSince: options.conditions.ifModifiedSince, ifNoneMatch: options.conditions.ifNoneMatch, ifUnmodifiedSince: options.conditions.ifUnmodifiedSince, ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }, range: rangeToString({ count: offset + res_1.contentLength - start, offset: start }), rangeGetContentMD5: options.rangeGetContentMD5, rangeGetContentCRC64: options.rangeGetContentCrc64, snapshot: options.snapshot, cpkInfo: options.customerProvidedKey }; return [4 /*yield*/, this.blobContext.download(tslib.__assign({ abortSignal: options.abortSignal }, updatedOptions))]; case 1: // Debug purpose only // console.log( // `Read from internal stream, range: ${ // updatedOptions.range // }, options: ${JSON.stringify(updatedOptions)}` // ); return [2 /*return*/, (_b.sent()).readableStreamBody]; } }); }); }, offset, res_1.contentLength, { abortSignal: options.abortSignal, maxRetryRequests: options.maxRetryRequests, onProgress: options.onProgress })]; case 3: e_1 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_1.message }); throw e_1; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Returns true if the Azure blob resource represented by this client exists; false otherwise. * * NOTE: use this function with care since an existing blob might be deleted by other clients or * applications. Vice versa new blobs might be added by other clients or applications after this * function completes. * * @param {BlobExistsOptions} [options] options to Exists operation. * @returns {Promise} * @memberof BlobClient */ BlobClient.prototype.exists = function (options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, e_2; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("BlobClient-exists", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return [4 /*yield*/, this.getProperties({ abortSignal: options.abortSignal, customerProvidedKey: options.customerProvidedKey, conditions: options.conditions, tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) })]; case 2: _b.sent(); return [2 /*return*/, true]; case 3: e_2 = _b.sent(); if (e_2.statusCode === 404) { span.setStatus({ code: api.CanonicalCode.NOT_FOUND, message: "Expected exception when checking blob existence" }); return [2 /*return*/, false]; } span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_2.message }); throw e_2; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Returns all user-defined metadata, standard HTTP properties, and system properties * for the blob. It does not return the content of the blob. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-properties * * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if * they originally contained uppercase characters. This differs from the metadata keys returned by * the methods of {@link ContainerClient} that list blobs using the `includeMetadata` option, which * will retain their original casing. * * @param {BlobGetPropertiesOptions} [options] Optional options to Get Properties operation. * @returns {Promise} * @memberof BlobClient */ BlobClient.prototype.getProperties = function (options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, res, e_3; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: _b = createSpan("BlobClient-getProperties", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); options.conditions = options.conditions || {}; ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return [4 /*yield*/, this.blobContext.getProperties({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), cpkInfo: options.customerProvidedKey, spanOptions: spanOptions })]; case 2: res = _c.sent(); return [2 /*return*/, tslib.__assign(tslib.__assign({}, res), { _response: res._response, objectReplicationDestinationPolicyId: res.objectReplicationPolicyId, objectReplicationSourceProperties: parseObjectReplicationRecord(res.objectReplicationRules) })]; case 3: e_3 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_3.message }); throw e_3; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Marks the specified blob or snapshot for deletion. The blob is later deleted * during garbage collection. Note that in order to delete a blob, you must delete * all of its snapshots. You can delete both at the same time with the Delete * Blob operation. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob * * @param {BlobDeleteOptions} [options] Optional options to Blob Delete operation. * @returns {Promise} * @memberof BlobClient */ BlobClient.prototype.delete = function (options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, e_4; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: _b = createSpan("BlobClient-delete", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; options.conditions = options.conditions || {}; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.blobContext.deleteMethod({ 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 }), spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_4 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_4.message }); throw e_4; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * 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 * all of its snapshots. You can delete both at the same time with the Delete * Blob operation. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob * * @param {BlobDeleteOptions} [options] Optional options to Blob Delete operation. * @returns {Promise} * @memberof BlobClient */ BlobClient.prototype.deleteIfExists = function (options) { var _a, _b; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _c, span, spanOptions, res, e_5; return tslib.__generator(this, function (_d) { switch (_d.label) { case 0: _c = createSpan("BlobClient-deleteIfExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; _d.label = 1; case 1: _d.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; 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: api.CanonicalCode.NOT_FOUND, 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: api.CanonicalCode.UNKNOWN, message: e_5.message }); throw e_5; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * 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 * or later. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/undelete-blob * * @param {BlobUndeleteOptions} [options] Optional options to Blob Undelete operation. * @returns {Promise} * @memberof BlobClient */ BlobClient.prototype.undelete = function (options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, e_6; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("BlobClient-undelete", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.blobContext.undelete({ abortSignal: options.abortSignal, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _b.sent()]; case 3: e_6 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_6.message }); throw e_6; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Sets system properties on the blob. * * If no value provided, or no value provided for the specified blob HTTP headers, * these blob HTTP headers without a value will be cleared. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties * * @param {BlobHTTPHeaders} [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. * @param {BlobSetHTTPHeadersOptions} [options] Optional options to Blob Set HTTP Headers operation. * @returns {Promise} * @memberof BlobClient */ BlobClient.prototype.setHTTPHeaders = function (blobHTTPHeaders, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, e_7; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: _b = createSpan("BlobClient-setHTTPHeaders", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; 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({ 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 }), cpkInfo: options.customerProvidedKey, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_7 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_7.message }); throw e_7; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Sets user-defined metadata for the specified blob as one or more name-value pairs. * * If no option provided, or no metadata defined in the parameter, the blob * metadata will be removed. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-metadata * * @param {Metadata} [metadata] Replace existing metadata with this value. * If no value provided the existing metadata will be removed. * @param {BlobSetMetadataOptions} [options] Optional options to Set Metadata operation. * @returns {Promise} * @memberof BlobClient */ BlobClient.prototype.setMetadata = function (metadata, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, e_8; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: _b = createSpan("BlobClient-setMetadata", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; 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({ 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, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_8 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_8.message }); throw e_8; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * 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. * Valid tag key and value characters include lower and upper case letters, digits (0-9), * space (' '), plus ('+'), minus ('-'), period ('.'), foward slash ('/'), colon (':'), equals ('='), and underscore ('_'). * * @param {Tags} tags * @param {BlobSetTagsOptions} [options={}] * @returns {Promise} * @memberof BlobClient */ BlobClient.prototype.setTags = function (tags, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, e_9; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: _b = createSpan("BlobClient-setTags", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.blobContext.setTags({ abortSignal: options.abortSignal, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), spanOptions: spanOptions, tags: toBlobTags(tags) })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_9 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_9.message }); throw e_9; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Gets the tags associated with the underlying blob. * * @param {BlobGetTagsOptions} [options={}] * @returns {Promise} * @memberof BlobClient */ BlobClient.prototype.getTags = function (options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, response, wrappedResponse, e_10; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: _b = createSpan("BlobClient-getTags", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.blobContext.getTags({ abortSignal: options.abortSignal, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), spanOptions: spanOptions })]; 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: api.CanonicalCode.UNKNOWN, message: e_10.message }); throw e_10; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Get a {@link BlobLeaseClient} that manages leases on the blob. * * @param {string} [proposeLeaseId] Initial proposed lease Id. * @returns {BlobLeaseClient} A new BlobLeaseClient object for managing leases on the blob. * @memberof BlobClient */ BlobClient.prototype.getBlobLeaseClient = function (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 {BlobCreateSnapshotOptions} [options] Optional options to the Blob Create Snapshot operation. * @returns {Promise} * @memberof BlobClient */ BlobClient.prototype.createSnapshot = function (options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, e_11; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: _b = createSpan("BlobClient-createSnapshot", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; 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({ 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, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_11 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_11.message }); throw e_11; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Asynchronously copies a blob to a destination within the storage account. * This method returns a long running operation poller that allows you to wait * indefinitely until the copy is completed. * You can also cancel a copy before it is completed by calling `cancelOperation` on the poller. * Note that the onProgress callback will not be invoked if the operation completes in the first * request, and attempting to cancel a completed copy will result in an error being thrown. * * In version 2012-02-12 and later, the source for a Copy Blob operation can be * a committed blob in any Azure storage account. * Beginning with version 2015-02-21, the source for a Copy Blob operation can be * an Azure file in any Azure storage account. * Only storage accounts created on or after June 7th, 2012 allow the Copy Blob * operation to copy from another storage account. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob * * Example using automatic polling: * * ```js * const copyPoller = await blobClient.beginCopyFromURL('url'); * const result = await copyPoller.pollUntilDone(); * ``` * * Example using manual polling: * * ```js * const copyPoller = await blobClient.beginCopyFromURL('url'); * while (!poller.isDone()) { * await poller.poll(); * } * const result = copyPoller.getResult(); * ``` * * Example using progress updates: * * ```js * const copyPoller = await blobClient.beginCopyFromURL('url', { * onProgress(state) { * console.log(`Progress: ${state.copyProgress}`); * } * }); * const result = await copyPoller.pollUntilDone(); * ``` * * Example using a changing polling interval (default 15 seconds): * * ```js * const copyPoller = await blobClient.beginCopyFromURL('url', { * intervalInMs: 1000 // poll blob every 1 second for copy progress * }); * const result = await copyPoller.pollUntilDone(); * ``` * * Example using copy cancellation: * * ```js * const copyPoller = await blobClient.beginCopyFromURL('url'); * // cancel operation after starting it. * try { * await copyPoller.cancelOperation(); * // calls to get the result now throw PollerCancelledError * await copyPoller.getResult(); * } catch (err) { * if (err.name === 'PollerCancelledError') { * console.log('The copy was cancelled.'); * } * } * ``` * * @param {string} copySource url to the source Azure Blob/File. * @param {BlobBeginCopyFromURLOptions} [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]; } }); }); }; /** * Aborts a pending asynchronous Copy Blob operation, and leaves a destination blob with zero * length and full metadata. Version 2012-02-12 and newer. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/abort-copy-blob * * @param {string} copyId Id of the Copy From URL operation. * @param {BlobAbortCopyFromURLOptions} [options] Optional options to the Blob Abort Copy From URL operation. * @returns {Promise} * @memberof BlobClient */ BlobClient.prototype.abortCopyFromURL = function (copyId, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, e_12; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("BlobClient-abortCopyFromURL", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.blobContext.abortCopyFromURL(copyId, { abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _b.sent()]; case 3: e_12 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_12.message }); throw e_12; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * 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. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob-from-url * * @param {string} copySource The source URL to copy from, Shared Access Signature(SAS) maybe needed for authentication * @param {BlobSyncCopyFromURLOptions} [options={}] * @returns {Promise} * @memberof BlobClient */ 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, spanOptions, e_13; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: _b = createSpan("BlobClient-syncCopyFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; 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, { 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), spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_13 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_13.message }); throw e_13; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * 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 premium page blob's tier determines the allowed size, IOPS, * and bandwidth of the blob. A block blob's tier determines Hot/Cool/Archive * storage type. This operation does not update the blob's ETag. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-tier * * @param {BlockBlobTier | PremiumPageBlobTier | string} tier The tier to be set on the blob. Valid values are Hot, Cool, or Archive. * @param {BlobSetTierOptions} [options] Optional options to the Blob Set Tier operation. * @returns {Promise} * @memberof BlobClient */ BlobClient.prototype.setAccessTier = function (tier, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, e_14; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: _b = createSpan("BlobClient-setAccessTier", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.blobContext.setTier(toAccessTier(tier), { 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, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_14 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_14.message }); throw e_14; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; 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, spanOptions, 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.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _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 > 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), { spanOptions: spanOptions }) }))]; 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), { spanOptions: spanOptions }) })]; 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: api.CanonicalCode.UNKNOWN, message: e_15.message }); throw e_15; case 6: span.end(); return [7 /*endfinally*/]; case 7: return [2 /*return*/]; } }); }); }; /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * Downloads an Azure Blob to a local file. * Fails if the the given file path already exits. * Offset and count are optional, pass 0 and undefined respectively to download the entire blob. * * @param {string} filePath * @param {number} [offset] From which position of the block blob to download. * @param {number} [count] How much data to be downloaded. Will download to the end when passing undefined. * @param {BlobDownloadOptions} [options] Options to Blob download options. * @returns {Promise} The response data for blob download operation, * but with readableStreamBody set to undefined since its * content is already read and written into a local file * at the specified path. * @memberof BlobClient */ 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, spanOptions, response, e_16; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("BlobClient-downloadToFile", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _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), { spanOptions: spanOptions }) }))]; 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: api.CanonicalCode.UNKNOWN, message: e_16.message }); throw e_16; case 6: span.end(); return [7 /*endfinally*/]; case 7: return [2 /*return*/]; } }); }); }; BlobClient.prototype.getBlobAndContainerNamesFromUrl = function () { var containerName; var blobName; try { // URL may look like the following // "https://myaccount.blob.core.windows.net/mycontainer/blob?sasString"; // "https://myaccount.blob.core.windows.net/mycontainer/blob"; // "https://myaccount.blob.core.windows.net/mycontainer/blob/a.txt?sasString"; // "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); if (parsedUrl.getHost().split(".")[1] === "blob") { // "https://myaccount.blob.core.windows.net/containername/blob". // .getPath() -> /containername/blob var pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); containerName = pathComponents[1]; blobName = pathComponents[3]; } else if (isIpEndpointStyle(parsedUrl)) { // 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("/([^/]*)/([^/]*)(/(.*))?"); containerName = pathComponents[2]; blobName = pathComponents[4]; } else { // "https://customdomain.com/containername/blob". // .getPath() -> /containername/blob var pathComponents = parsedUrl.getPath().match("/([^/]*)(/(.*))?"); containerName = pathComponents[1]; blobName = pathComponents[3]; } // decode the encoded blobName, containerName - to get all the special characters that might be present in them containerName = decodeURIComponent(containerName); blobName = decodeURIComponent(blobName); // Azure Storage Server will replace "\" with "/" in the blob names // doing the same in the SDK side so that the user doesn't have to replace "\" instances in the blobName blobName = blobName.replace(/\\/g, "/"); if (!blobName) { throw new Error("Provided blobName is invalid."); } else if (!containerName) { throw new Error("Provided containerName is invalid."); } return { blobName: blobName, containerName: 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 * a committed blob in any Azure storage account. * Beginning with version 2015-02-21, the source for a Copy Blob operation can be * an Azure file in any Azure storage account. * Only storage accounts created on or after June 7th, 2012 allow the Copy Blob * operation to copy from another storage account. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob * * @param {string} copySource url to the source Azure Blob/File. * @param {BlobStartCopyFromURLOptions} [options] Optional options to the Blob Start Copy From URL operation. * @returns {Promise} * @memberof BlobClient */ 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, spanOptions, e_17; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: _b = createSpan("BlobClient-startCopyFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; 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, { 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, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_17 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_17.message }); throw e_17; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; return BlobClient; }(StorageClient)); /** * AppendBlobClient defines a set of operations applicable to append blobs. * * @export * @class AppendBlobClient * @extends {BlobClient} */ var AppendBlobClient = /** @class */ (function (_super) { tslib.__extends(AppendBlobClient, _super); function AppendBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { var _this = this; // 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; options = options || {}; if (credentialOrPipelineOrContainerName instanceof Pipeline) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; } else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) url = urlOrConnectionString; url = urlOrConnectionString; options = blobNameOrOptions; pipeline = newPipeline(credentialOrPipelineOrContainerName, options); } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) url = urlOrConnectionString; // The second parameter is undefined. Use anonymous credential. pipeline = newPipeline(new AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string" && blobNameOrOptions && typeof blobNameOrOptions === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) var containerName = credentialOrPipelineOrContainerName; var blobName = blobNameOrOptions; var extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { { var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); pipeline = newPipeline(sharedKeyCredential, options); } } else if (extractedCreds.kind === "SASConnString") { url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + "?" + extractedCreds.accountSas; pipeline = newPipeline(new AnonymousCredential(), options); } else { throw new Error("Connection string must be either an Account connection string or a SAS connection string"); } } else { throw new Error("Expecting non-empty strings for containerName and blobName parameters"); } _this = _super.call(this, url, pipeline) || this; _this.appendBlobContext = new AppendBlob(_this.storageClientContext); return _this; } /** * Creates a new AppendBlobClient object identical to the source but with the * specified snapshot timestamp. * Provide "" will remove the snapshot and return a Client to the base blob. * * @param {string} snapshot The snapshot timestamp. * @returns {AppendBlobClient} A new AppendBlobClient object identical to the source but with the specified snapshot timestamp. * @memberof AppendBlobClient */ AppendBlobClient.prototype.withSnapshot = function (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 * * @param {AppendBlobCreateOptions} [options] Options to the Append Block Create operation. * @returns {Promise} * @memberof AppendBlobClient * * Example usage: * * ```js * const appendBlobClient = containerClient.getAppendBlobClient(""); * 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, spanOptions, e_18; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: _b = createSpan("AppendBlobClient-create", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; 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, { 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), spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_18 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_18.message }); throw e_18; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * 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. * @see https://docs.microsoft.com/rest/api/storageservices/put-blob * * @param {AppendBlobCreateIfNotExistsOptions} [options] * @returns {Promise} * @memberof AppendBlobClient */ AppendBlobClient.prototype.createIfNotExists = function (options) { var _a, _b; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _c, span, spanOptions, conditions, res, e_19; return tslib.__generator(this, function (_d) { switch (_d.label) { case 0: _c = createSpan("AppendBlobClient-createIfNotExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; conditions = { ifNoneMatch: ETagAny }; _d.label = 1; case 1: _d.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.create(tslib.__assign(tslib.__assign({}, options), { conditions: conditions, tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; 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: api.CanonicalCode.ALREADY_EXISTS, 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: api.CanonicalCode.UNKNOWN, message: e_19.message }); throw e_19; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Seals the append blob, making it read only. * * @param {AppendBlobSealOptions} [options={}] * @returns {Promise} * @memberof AppendBlobClient */ AppendBlobClient.prototype.seal = function (options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, e_20; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: _b = createSpan("AppendBlobClient-seal", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; options.conditions = options.conditions || {}; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.appendBlobContext.seal({ 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 }), spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_20 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_20.message }); throw e_20; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Commits a new block of data to the end of the existing append blob. * @see https://docs.microsoft.com/rest/api/storageservices/append-block * * @param {HttpRequestBody} body Data to be appended. * @param {number} contentLength Length of the body in bytes. * @param {AppendBlobAppendBlockOptions} [options] Options to the Append Block operation. * @returns {Promise} * @memberof AppendBlobClient * * Example usage: * * ```js * const content = "Hello World!"; * * // Create a new append blob and append data to the blob. * const newAppendBlobClient = containerClient.getAppendBlobClient(""); * await newAppendBlobClient.create(); * await newAppendBlobClient.appendBlock(content, content.length); * * // Append data to an existing append blob. * const existingAppendBlobClient = containerClient.getAppendBlobClient(""); * await existingAppendBlobClient.appendBlock(content, content.length); * ``` */ AppendBlobClient.prototype.appendBlock = function (body, contentLength, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, e_21; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: _b = createSpan("AppendBlobClient-appendBlock", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; 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(body, contentLength, { 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 }), onUploadProgress: options.onProgress, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_21 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_21.message }); throw e_21; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * 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. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/append-block-from-url * * @param {string} sourceURL * The url to the blob that will be the source of the copy. A source blob in the same storage account can * be authenticated via Shared Key. However, if the source is a blob in another account, the source blob * must either be public or must be authenticated via a shared access signature. If the source blob is * public, no authentication is required to perform the operation. * @param {number} sourceOffset Offset in source to be appended * @param {number} count Number of bytes to be appended as a block * @param {AppendBlobAppendBlockFromURLOptions} [options={}] * @returns {Promise} * @memberof AppendBlobClient */ AppendBlobClient.prototype.appendBlockFromURL = function (sourceURL, sourceOffset, count, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, e_22; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: _b = createSpan("AppendBlobClient-appendBlockFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; 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, { 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, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_22 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_22.message }); throw e_22; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; return AppendBlobClient; }(BlobClient)); /** * BlockBlobClient defines a set of operations applicable to block blobs. * * @export * @class BlockBlobClient * @extends {BlobClient} */ var BlockBlobClient = /** @class */ (function (_super) { tslib.__extends(BlockBlobClient, _super); function BlockBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { var _this = this; // 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; options = options || {}; if (credentialOrPipelineOrContainerName instanceof Pipeline) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; } else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) url = urlOrConnectionString; options = blobNameOrOptions; pipeline = newPipeline(credentialOrPipelineOrContainerName, options); } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) // The second parameter is undefined. Use anonymous credential. url = urlOrConnectionString; pipeline = newPipeline(new AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string" && blobNameOrOptions && typeof blobNameOrOptions === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) var containerName = credentialOrPipelineOrContainerName; var blobName = blobNameOrOptions; var extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { { var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); pipeline = newPipeline(sharedKeyCredential, options); } } else if (extractedCreds.kind === "SASConnString") { url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + "?" + extractedCreds.accountSas; pipeline = newPipeline(new AnonymousCredential(), options); } else { throw new Error("Connection string must be either an Account connection string or a SAS connection string"); } } else { throw new Error("Expecting non-empty strings for containerName and blobName parameters"); } _this = _super.call(this, url, pipeline) || this; _this.blockBlobContext = new BlockBlob(_this.storageClientContext); _this._blobContext = new Blob$1(_this.storageClientContext); return _this; } /** * Creates a new BlockBlobClient object identical to the source but with the * specified snapshot timestamp. * Provide "" will remove the snapshot and return a URL to the base blob. * * @param {string} snapshot The snapshot timestamp. * @returns {BlockBlobClient} A new BlockBlobClient object identical to the source but with the specified snapshot timestamp. * @memberof BlockBlobClient */ BlockBlobClient.prototype.withSnapshot = function (snapshot) { return new BlockBlobClient(setURLParameter(this.url, URLConstants.Parameters.SNAPSHOT, snapshot.length === 0 ? undefined : snapshot), this.pipeline); }; /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * Quick query for a JSON or CSV formatted blob. * * Example usage (Node.js): * * ```js * // Query and convert a blob to a string * const queryBlockBlobResponse = await blockBlobClient.query("select * from BlobStorage"); * const downloaded = (await streamToBuffer(queryBlockBlobResponse.readableStreamBody)).toString(); * console.log("Query blob content:", downloaded); * * async function streamToBuffer(readableStream) { * return new Promise((resolve, reject) => { * const chunks = []; * readableStream.on("data", (data) => { * chunks.push(data instanceof Buffer ? data : Buffer.from(data)); * }); * readableStream.on("end", () => { * resolve(Buffer.concat(chunks)); * }); * readableStream.on("error", reject); * }); * } * ``` * * @param {string} query * @param {BlockBlobQueryOptions} [options={}] * @returns {Promise} * @memberof BlockBlobClient */ BlockBlobClient.prototype.query = function (query, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, response, e_23; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); _b = createSpan("BlockBlobClient-query", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this._blobContext.query({ abortSignal: options.abortSignal, queryRequest: { 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 }), spanOptions: spanOptions })]; 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: api.CanonicalCode.UNKNOWN, message: e_23.message }); throw e_23; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * 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. * Partial updates are not supported; the content of the existing blob is * overwritten with the new content. To perform a partial update of a block blob's, * use {@link stageBlock} and {@link commitBlockList}. * * This is a non-parallel uploading method, please use {@link uploadFile}, * {@link uploadStream} or {@link uploadBrowserData} for better performance * with concurrency uploading. * * @see https://docs.microsoft.com/rest/api/storageservices/put-blob * * @param {HttpRequestBody} body Blob, string, ArrayBuffer, ArrayBufferView or a function * which returns a new Readable stream whose offset is from data source beginning. * @param {number} contentLength Length of body in bytes. Use Buffer.byteLength() to calculate body length for a * string including non non-Base64/Hex-encoded characters. * @param {BlockBlobUploadOptions} [options] Options to the Block Blob Upload operation. * @returns {Promise} Response data for the Block Blob Upload operation. * @memberof BlockBlobClient * * Example usage: * * ```js * const content = "Hello world!"; * 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, spanOptions, e_24; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: options.conditions = options.conditions || {}; _b = createSpan("BlockBlobClient-upload", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return [4 /*yield*/, this.blockBlobContext.upload(body, contentLength, { 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 }), onUploadProgress: options.onProgress, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, tier: toAccessTier(options.tier), blobTagsString: toBlobTagsString(options.tags), spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_24 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_24.message }); throw e_24; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Uploads the specified block to the block blob's "staging area" to be later * committed by a call to commitBlockList. * @see https://docs.microsoft.com/rest/api/storageservices/put-block * * @param {string} blockId A 64-byte value that is base64-encoded * @param {HttpRequestBody} body Data to upload to the staging area. * @param {number} contentLength Number of bytes to upload. * @param {BlockBlobStageBlockOptions} [options] Options to the Block Blob Stage Block operation. * @returns {Promise} Response data for the Block Blob Stage Block operation. * @memberof BlockBlobClient */ BlockBlobClient.prototype.stageBlock = function (blockId, body, contentLength, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, e_25; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("BlockBlobClient-stageBlock", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return [4 /*yield*/, this.blockBlobContext.stageBlock(blockId, contentLength, body, { abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, onUploadProgress: options.onProgress, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _b.sent()]; case 3: e_25 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_25.message }); throw e_25; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * 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. * This API is available starting in version 2018-03-28. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-block-from-url * * @param {string} blockId A 64-byte value that is base64-encoded * @param {string} sourceURL Specifies the URL of the blob. The value * may be a URL of up to 2 KB in length that specifies a blob. * The value should be URL-encoded as it would appear * in a request URI. The source blob must either be public * or must be authenticated via a shared access signature. * If the source blob is public, no authentication is required * to perform the operation. Here are some examples of source object URLs: * - https://myaccount.blob.core.windows.net/mycontainer/myblob * - https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= * @param {number} [offset] From which position of the blob to download, >= 0 * @param {number} [count] How much data to be downloaded, > 0. Will download to the end when undefined * @param {BlockBlobStageBlockFromURLOptions} [options={}] Options to the Block Blob Stage Block From URL operation. * @returns {Promise} Response data for the Block Blob Stage Block From URL operation. * @memberof BlockBlobClient */ 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, spanOptions, e_26; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("BlockBlobClient-stageBlockFromURL", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return [4 /*yield*/, this.blockBlobContext.stageBlockFromURL(blockId, 0, sourceURL, { 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, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _b.sent()]; case 3: e_26 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_26.message }); throw e_26; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * 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 server in a prior {@link stageBlock} operation. You can call {@link commitBlockList} to * update a blob by uploading only those blocks that have changed, then committing the new and existing * blocks together. Any blocks not specified in the block list and permanently deleted. * @see https://docs.microsoft.com/rest/api/storageservices/put-block-list * * @param {string[]} blocks Array of 64-byte value that is base64-encoded * @param {BlockBlobCommitBlockListOptions} [options] Options to the Block Blob Commit Block List operation. * @returns {Promise} Response data for the Block Blob Commit Block List operation. * @memberof BlockBlobClient */ 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, spanOptions, e_27; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: options.conditions = options.conditions || {}; _b = createSpan("BlockBlobClient-commitBlockList", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _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 }, { 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), spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_27 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_27.message }); throw e_27; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Returns the list of blocks that have been uploaded as part of a block blob * using the specified block list filter. * @see https://docs.microsoft.com/rest/api/storageservices/get-block-list * * @param {BlockListType} listType Specifies whether to return the list of committed blocks, * the list of uncommitted blocks, or both lists together. * @param {BlockBlobGetBlockListOptions} [options] Options to the Block Blob Get Block List operation. * @returns {Promise} Response data for the Block Blob Get Block List operation. * @memberof BlockBlobClient */ BlockBlobClient.prototype.getBlockList = function (listType, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, res, e_28; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: _b = createSpan("BlockBlobClient-getBlockList", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.blockBlobContext.getBlockList(listType, { abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), spanOptions: spanOptions })]; case 2: res = _c.sent(); if (!res.committedBlocks) { res.committedBlocks = []; } if (!res.uncommittedBlocks) { res.uncommittedBlocks = []; } return [2 /*return*/, res]; case 3: e_28 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_28.message }); throw e_28; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; // High level functions /** * Uploads a Buffer(Node.js)/Blob(browsers)/ArrayBuffer/ArrayBufferView object to a BlockBlob. * * When data length is no more than the specifiled {@link BlockBlobParallelUploadOptions.maxSingleShotSize} (default is * {@link BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}), this method will use 1 {@link upload} call to finish the upload. * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList} * to commit the block list. * * @export * @param {Buffer | Blob | ArrayBuffer | ArrayBufferView} data Buffer(Node.js), Blob, ArrayBuffer or ArrayBufferView * @param {BlockBlobParallelUploadOptions} [options] * @returns {Promise} * @memberof BlockBlobClient */ BlockBlobClient.prototype.uploadData = function (data, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, buffer_1, browserBlob_1; return tslib.__generator(this, function (_b) { _a = createSpan("BlockBlobClient-uploadData", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; try { if (true) { if (data instanceof Buffer) { buffer_1 = data; } else if (data instanceof ArrayBuffer) { buffer_1 = Buffer.from(data); } else { data = data; buffer_1 = Buffer.from(data.buffer, data.byteOffset, data.byteLength); } return [2 /*return*/, this.uploadSeekableInternal(function (offset, size) { return buffer_1.slice(offset, offset + size); }, buffer_1.byteLength, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; } else { browserBlob_1 = new Blob([data]); return [2 /*return*/, this.uploadSeekableInternal(function (offset, size) { return browserBlob_1.slice(offset, offset + size); }, browserBlob_1.size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; } } catch (e) { span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e.message }); throw e; } finally { span.end(); } return [2 /*return*/]; }); }); }; /** * ONLY AVAILABLE IN BROWSERS. * * Uploads a browser Blob/File/ArrayBuffer/ArrayBufferView object to block blob. * * When buffer length <= 256MB, this method will use 1 upload call to finish the upload. * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call * {@link commitBlockList} to commit the block list. * * @deprecated Use {@link uploadData} instead. * * @export * @param {Blob | ArrayBuffer | ArrayBufferView} browserData Blob, File, ArrayBuffer or ArrayBufferView * @param {BlockBlobParallelUploadOptions} [options] Options to upload browser data. * @returns {Promise} Response data for the Blob Upload operation. * @memberof BlockBlobClient */ BlockBlobClient.prototype.uploadBrowserData = function (browserData, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, browserBlob_2, e_29; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("BlockBlobClient-uploadBrowserData", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); browserBlob_2 = new Blob([browserData]); return [4 /*yield*/, this.uploadSeekableInternal(function (offset, size) { return browserBlob_2.slice(offset, offset + size); }, browserBlob_2.size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: return [2 /*return*/, _b.sent()]; case 3: e_29 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_29.message }); throw e_29; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * * Uploads data to block blob. Requires a bodyFactory as the data source, * which need to return a {@link HttpRequestBody} object with the offset and size provided. * * When data length is no more than the specifiled {@link BlockBlobParallelUploadOptions.maxSingleShotSize} (default is * {@link BLOCK_BLOB_MAX_UPLOAD_BLOB_BYTES}), this method will use 1 {@link upload} call to finish the upload. * Otherwise, this method will call {@link stageBlock} to upload blocks, and finally call {@link commitBlockList} * to commit the block list. * * @param {(offset: number, size: number) => HttpRequestBody} bodyFactory * @param {number} size size of the data to upload. * @param {BlockBlobParallelUploadOptions} [options] Options to Upload to Block Blob operation. * @returns {Promise} Response data for the Blob Upload operation. * @memberof BlockBlobClient */ BlockBlobClient.prototype.uploadSeekableInternal = function (bodyFactory, size, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, numBlocks_1, blockList_1, blockIDPrefix_1, transferProgress_2, batch, _loop_2, i, e_30; 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.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 5, 6, 7]); if (!(size <= options.maxSingleShotSize)) return [3 /*break*/, 3]; return [4 /*yield*/, this.upload(bodyFactory(0, size), size, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; 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: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) })]; case 1: _a.sent(); // Update progress after block is successfully uploaded to server, in case of block trying // 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, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 5: e_30 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_30.message }); throw e_30; case 6: span.end(); return [7 /*endfinally*/]; case 7: return [2 /*return*/]; } }); }); }; /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * Uploads a local file in blocks to a block blob. * * When file size <= 256MB, this method will use 1 upload call to finish the upload. * Otherwise, this method will call stageBlock to upload blocks, and finally call commitBlockList * to commit the block list. * * @param {string} filePath Full path of local file * @param {BlockBlobParallelUploadOptions} [options] Options to Upload to Block Blob operation. * @returns {(Promise)} Response data for the Blob Upload operation. * @memberof BlockBlobClient */ BlockBlobClient.prototype.uploadFile = function (filePath, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, size, e_31; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("BlockBlobClient-uploadFile", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _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), { spanOptions: spanOptions }) }))]; case 3: return [2 /*return*/, _b.sent()]; case 4: e_31 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_31.message }); throw e_31; case 5: span.end(); return [7 /*endfinally*/]; case 6: return [2 /*return*/]; } }); }); }; /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * Uploads a Node.js Readable stream into block blob. * * PERFORMANCE IMPROVEMENT TIPS: * * Input stream highWaterMark is better to set a same value with bufferSize * parameter, which will avoid Buffer.concat() operations. * * @param {Readable} stream Node.js Readable stream * @param {number} bufferSize Size of every buffer allocated, also the block size in the uploaded block blob. Default value is 8MB * @param {number} maxConcurrency Max concurrency indicates the max number of buffers that can be allocated, * positive correlation with max uploading concurrency. Default value is 5 * @param {BlockBlobUploadStreamOptions} [options] Options to Upload Stream to Block Blob operation. * @returns {Promise} Response data for the Blob Upload operation. * @memberof BlockBlobClient */ 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, spanOptions, blockNum_1, blockIDPrefix_2, transferProgress_3, blockList_2, scheduler, e_32; 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.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _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: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) })]; case 1: _a.sent(); // Update progress after block is successfully uploaded to server, in case of block trying transferProgress_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), { spanOptions: spanOptions }) }))]; case 3: return [2 /*return*/, _b.sent()]; case 4: e_32 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_32.message }); throw e_32; case 5: span.end(); return [7 /*endfinally*/]; case 6: return [2 /*return*/]; } }); }); }; return BlockBlobClient; }(BlobClient)); /** * PageBlobClient defines a set of operations applicable to page blobs. * * @export * @class PageBlobClient * @extends {BlobClient} */ var PageBlobClient = /** @class */ (function (_super) { tslib.__extends(PageBlobClient, _super); function PageBlobClient(urlOrConnectionString, credentialOrPipelineOrContainerName, blobNameOrOptions, options) { var _this = this; // 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; options = options || {}; if (credentialOrPipelineOrContainerName instanceof Pipeline) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; } else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) url = urlOrConnectionString; options = blobNameOrOptions; pipeline = newPipeline(credentialOrPipelineOrContainerName, options); } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) // The second parameter is undefined. Use anonymous credential. url = urlOrConnectionString; pipeline = newPipeline(new AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string" && blobNameOrOptions && typeof blobNameOrOptions === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) var containerName = credentialOrPipelineOrContainerName; var blobName = blobNameOrOptions; var extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { { var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)); options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); pipeline = newPipeline(sharedKeyCredential, options); } } else if (extractedCreds.kind === "SASConnString") { url = appendToURLPath(appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)), encodeURIComponent(blobName)) + "?" + extractedCreds.accountSas; pipeline = newPipeline(new AnonymousCredential(), options); } else { throw new Error("Connection string must be either an Account connection string or a SAS connection string"); } } else { throw new Error("Expecting non-empty strings for containerName and blobName parameters"); } _this = _super.call(this, url, pipeline) || this; _this.pageBlobContext = new PageBlob(_this.storageClientContext); return _this; } /** * Creates a new PageBlobClient object identical to the source but with the * specified snapshot timestamp. * Provide "" will remove the snapshot and return a Client to the base blob. * * @param {string} snapshot The snapshot timestamp. * @returns {PageBlobClient} A new PageBlobClient object identical to the source but with the specified snapshot timestamp. * @memberof PageBlobClient */ PageBlobClient.prototype.withSnapshot = function (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. * @see https://docs.microsoft.com/rest/api/storageservices/put-blob * * @param {number} size size of the page blob. * @param {PageBlobCreateOptions} [options] Options to the Page Blob Create operation. * @returns {Promise} Response data for the Page Blob Create operation. * @memberof PageBlobClient */ 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, spanOptions, e_33; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: options.conditions = options.conditions || {}; _b = createSpan("PageBlobClient-create", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _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, { 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), spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_33 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_33.message }); throw e_33; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * 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 * of the existing blob will remain unchanged. * @see https://docs.microsoft.com/rest/api/storageservices/put-blob * * @param {number} size size of the page blob. * @param {PageBlobCreateIfNotExistsOptions} [options] * @returns {Promise} * @memberof PageBlobClient */ PageBlobClient.prototype.createIfNotExists = function (size, options) { var _a, _b; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _c, span, spanOptions, conditions, res, e_34; return tslib.__generator(this, function (_d) { switch (_d.label) { case 0: _c = createSpan("PageBlobClient-createIfNotExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; _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: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; 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_34 = _d.sent(); if (((_a = e_34.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "BlobAlreadyExists") { span.setStatus({ code: api.CanonicalCode.ALREADY_EXISTS, 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_34.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_34.response })]; } span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_34.message }); throw e_34; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * 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 * * @param {HttpRequestBody} body Data to upload * @param {number} offset Offset of destination page blob * @param {number} count Content length of the body, also number of bytes to be uploaded * @param {PageBlobUploadPagesOptions} [options] Options to the Page Blob Upload Pages operation. * @returns {Promise} Response data for the Page Blob Upload Pages operation. * @memberof PageBlobClient */ PageBlobClient.prototype.uploadPages = function (body, offset, count, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, e_35; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: options.conditions = options.conditions || {}; _b = createSpan("PageBlobClient-uploadPages", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); ensureCpkIfSpecified(options.customerProvidedKey, this.isHttps); return [4 /*yield*/, this.pageBlobContext.uploadPages(body, count, { 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 }), onUploadProgress: options.onProgress, range: rangeToString({ offset: offset, count: count }), sequenceNumberAccessConditions: options.conditions, transactionalContentMD5: options.transactionalContentMD5, transactionalContentCrc64: options.transactionalContentCrc64, cpkInfo: options.customerProvidedKey, encryptionScope: options.encryptionScope, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_35 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_35.message }); throw e_35; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * The Upload Pages operation writes a range of pages to a page blob where the * contents are read from a URL. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/put-page-from-url * * @param {string} sourceURL Specify a URL to the copy source, Shared Access Signature(SAS) maybe needed for authentication * @param {number} sourceOffset The source offset to copy from. Pass 0 to copy from the beginning of source page blob * @param {number} destOffset Offset of destination page blob * @param {number} count Number of bytes to be uploaded from source page blob * @param {PageBlobUploadPagesFromURLOptions} [options={}] * @returns {Promise} * @memberof PageBlobClient */ PageBlobClient.prototype.uploadPagesFromURL = function (sourceURL, sourceOffset, destOffset, count, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, e_36; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: options.conditions = options.conditions || {}; options.sourceConditions = options.sourceConditions || {}; _b = createSpan("PageBlobClient-uploadPagesFromURL", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _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 }), { 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, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_36 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_36.message }); throw e_36; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Frees the specified pages from the page blob. * @see https://docs.microsoft.com/rest/api/storageservices/put-page * * @param {number} [offset] Starting byte position of the pages to clear. * @param {number} [count] Number of bytes to clear. * @param {PageBlobClearPagesOptions} [options] Options to the Page Blob Clear Pages operation. * @returns {Promise} Response data for the Page Blob Clear Pages operation. * @memberof PageBlobClient */ PageBlobClient.prototype.clearPages = function (offset, count, options) { var _a; if (offset === void 0) { offset = 0; } if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, e_37; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: options.conditions = options.conditions || {}; _b = createSpan("PageBlobClient-clearPages", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.pageBlobContext.clearPages(0, { 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, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_37 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_37.message }); throw e_37; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * 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 * * @param {number} [offset] Starting byte position of the page ranges. * @param {number} [count] Number of bytes to get. * @param {PageBlobGetPageRangesOptions} [options] Options to the Page Blob Get Ranges operation. * @returns {Promise} Response data for the Page Blob Get Ranges operation. * @memberof PageBlobClient */ PageBlobClient.prototype.getPageRanges = function (offset, count, options) { var _a; if (offset === void 0) { offset = 0; } if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, e_38; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: options.conditions = options.conditions || {}; _b = createSpan("PageBlobClient-getPageRanges", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.pageBlobContext .getPageRanges({ 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 }), spanOptions: spanOptions }) .then(rangeResponseFromModel)]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_38 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_38.message }); throw e_38; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * 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 * * @param {number} offset Starting byte position of the page blob * @param {number} count Number of bytes to get ranges diff. * @param {string} prevSnapshot Timestamp of snapshot to retrieve the difference. * @param {PageBlobGetPageRangesDiffOptions} [options] Options to the Page Blob Get Page Ranges Diff operation. * @returns {Promise} Response data for the Page Blob Get Page Range Diff operation. * @memberof PageBlobClient */ PageBlobClient.prototype.getPageRangesDiff = function (offset, count, prevSnapshot, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, e_39; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: options.conditions = options.conditions || {}; _b = createSpan("PageBlobClient-getPageRangesDiff", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.pageBlobContext .getPageRangesDiff({ 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 }), spanOptions: spanOptions }) .then(rangeResponseFromModel)]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_39 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_39.message }); throw e_39; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * 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 * * @param {number} offset Starting byte position of the page blob * @param {number} count Number of bytes to get ranges diff. * @param {string} prevSnapshotUrl URL of snapshot to retrieve the difference. * @param {PageBlobGetPageRangesDiffOptions} [options] Options to the Page Blob Get Page Ranges Diff operation. * @returns {Promise} Response data for the Page Blob Get Page Range Diff operation. * @memberof PageBlobClient */ PageBlobClient.prototype.getPageRangesDiffForManagedDisks = function (offset, count, prevSnapshotUrl, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, e_40; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: options.conditions = options.conditions || {}; _b = createSpan("PageBlobClient-GetPageRangesDiffForManagedDisks", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.pageBlobContext .getPageRangesDiff({ 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 }), spanOptions: spanOptions }) .then(rangeResponseFromModel)]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_40 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_40.message }); throw e_40; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * 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 * * @param {number} size Target size * @param {PageBlobResizeOptions} [options] Options to the Page Blob Resize operation. * @returns {Promise} Response data for the Page Blob Resize operation. * @memberof PageBlobClient */ PageBlobClient.prototype.resize = function (size, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, e_41; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: options.conditions = options.conditions || {}; _b = createSpan("PageBlobClient-resize", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.pageBlobContext.resize(size, { 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, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_41 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_41.message }); throw e_41; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Sets a page blob's sequence number. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-properties * * @param {SequenceNumberActionType} sequenceNumberAction Indicates how the service should modify the blob's sequence number. * @param {number} [sequenceNumber] Required if sequenceNumberAction is max or update * @param {PageBlobUpdateSequenceNumberOptions} [options] Options to the Page Blob Update Sequence Number operation. * @returns {Promise} Response data for the Page Blob Update Sequence Number operation. * @memberof PageBlobClient */ PageBlobClient.prototype.updateSequenceNumber = function (sequenceNumberAction, sequenceNumber, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, e_42; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: options.conditions = options.conditions || {}; _b = createSpan("PageBlobClient-updateSequenceNumber", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.pageBlobContext.updateSequenceNumber(sequenceNumberAction, { 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 }), spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_42 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_42.message }); throw e_42; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * 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 * copied snapshot are transferred to the destination. * The copied snapshots are complete copies of the original snapshot and can be read or copied from as usual. * @see https://docs.microsoft.com/rest/api/storageservices/incremental-copy-blob * @see https://docs.microsoft.com/en-us/azure/virtual-machines/windows/incremental-snapshots * * @param {string} copySource Specifies the name of the source page blob snapshot. For example, * https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot= * @param {PageBlobStartCopyIncrementalOptions} [options] Options to the Page Blob Copy Incremental operation. * @returns {Promise} Response data for the Page Blob Copy Incremental operation. * @memberof PageBlobClient */ PageBlobClient.prototype.startCopyIncremental = function (copySource, options) { var _a; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _b, span, spanOptions, e_43; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: _b = createSpan("PageBlobClient-startCopyIncremental", options.tracingOptions), span = _b.span, spanOptions = _b.spanOptions; _c.label = 1; case 1: _c.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.pageBlobContext.copyIncremental(copySource, { abortSignal: options.abortSignal, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_a = options.conditions) === null || _a === void 0 ? void 0 : _a.tagConditions }), spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_43 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_43.message }); throw e_43; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; return PageBlobClient; }(BlobClient)); /** * A client that manages leases for a {@link ContainerClient} or a {@link BlobClient}. * * @export * @class BlobLeaseClient */ var BlobLeaseClient = /** @class */ (function () { /** * Creates an instance of BlobLeaseClient. * @param {(ContainerClient | BlobClient)} client The client to make the lease operation requests. * @param {string} leaseId Initial proposed lease id. * @memberof BlobLeaseClient */ function BlobLeaseClient(client, leaseId) { var clientContext = new StorageClientContext(client.url, client.pipeline.toServiceClientOptions()); this._url = client.url; if (client instanceof ContainerClient) { this._isContainer = true; this._containerOrBlobOperation = new Container(clientContext); } else { this._isContainer = false; this._containerOrBlobOperation = new Blob$1(clientContext); } if (!leaseId) { leaseId = coreHttp.generateUuid(); } this._leaseId = leaseId; } Object.defineProperty(BlobLeaseClient.prototype, "leaseId", { /** * Gets the lease Id. * * @readonly * @memberof BlobLeaseClient * @type {string} */ get: function () { return this._leaseId; }, enumerable: false, configurable: true }); Object.defineProperty(BlobLeaseClient.prototype, "url", { /** * Gets the url. * * @readonly * @memberof BlobLeaseClient * @type {string} */ get: function () { return this._url; }, enumerable: false, configurable: true }); /** * Establishes and manages a lock on a container for delete operations, or on a blob * for write and delete operations. * The lock duration can be 15 to 60 seconds, or can be infinite. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container * and * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * * @param {number} duration Must be between 15 to 60 seconds, or infinite (-1) * @param {LeaseOperationOptions} [options={}] option to configure lease management operations. * @returns {Promise} Response data for acquire lease operation. * @memberof BlobLeaseClient */ BlobLeaseClient.prototype.acquireLease = function (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, spanOptions, e_44; return tslib.__generator(this, function (_h) { switch (_h.label) { case 0: _g = createSpan("BlobLeaseClient-acquireLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; 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({ 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, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _h.sent()]; case 3: e_44 = _h.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_44.message }); throw e_44; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * To change the ID of the lease. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container * and * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * * @param {string} proposedLeaseId the proposed new lease Id. * @param {LeaseOperationOptions} [options={}] option to configure lease management operations. * @returns {Promise} Response data for change lease operation. * @memberof BlobLeaseClient */ BlobLeaseClient.prototype.changeLease = function (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, spanOptions, response, e_45; return tslib.__generator(this, function (_h) { switch (_h.label) { case 0: _g = createSpan("BlobLeaseClient-changeLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; 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, { abortSignal: options.abortSignal, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), spanOptions: spanOptions })]; case 2: response = _h.sent(); this._leaseId = proposedLeaseId; return [2 /*return*/, response]; case 3: e_45 = _h.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_45.message }); throw e_45; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * 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. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container * and * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * * @param {LeaseOperationOptions} [options={}] option to configure lease management operations. * @returns {Promise} Response data for release lease operation. * @memberof BlobLeaseClient */ BlobLeaseClient.prototype.releaseLease = function (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, spanOptions, e_46; return tslib.__generator(this, function (_h) { switch (_h.label) { case 0: _g = createSpan("BlobLeaseClient-releaseLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; 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, { abortSignal: options.abortSignal, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), spanOptions: spanOptions })]; case 2: return [2 /*return*/, _h.sent()]; case 3: e_46 = _h.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_46.message }); throw e_46; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * To renew the lease. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container * and * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * * @param {LeaseOperationOptions} [options={}] Optional option to configure lease management operations. * @returns {Promise} Response data for renew lease operation. * @memberof BlobLeaseClient */ BlobLeaseClient.prototype.renewLease = function (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, spanOptions, e_47; return tslib.__generator(this, function (_h) { switch (_h.label) { case 0: _g = createSpan("BlobLeaseClient-renewLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; 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, { abortSignal: options.abortSignal, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), spanOptions: spanOptions })]; case 2: return [2 /*return*/, _h.sent()]; case 3: e_47 = _h.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_47.message }); throw e_47; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * To end the lease but ensure that another client cannot acquire a new lease * until the current lease period has expired. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-container * and * @see https://docs.microsoft.com/en-us/rest/api/storageservices/lease-blob * * @static * @param {number} breakPeriod Break period * @param {LeaseOperationOptions} [options={}] Optional options to configure lease management operations. * @returns {Promise} Response data for break lease operation. * @memberof BlobLeaseClient */ BlobLeaseClient.prototype.breakLease = function (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, spanOptions, operationOptions, e_48; return tslib.__generator(this, function (_h) { switch (_h.label) { case 0: _g = createSpan("BlobLeaseClient-breakLease", options.tracingOptions), span = _g.span, spanOptions = _g.spanOptions; 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 = { abortSignal: options.abortSignal, breakPeriod: breakPeriod, modifiedAccessConditions: tslib.__assign(tslib.__assign({}, options.conditions), { ifTags: (_f = options.conditions) === null || _f === void 0 ? void 0 : _f.tagConditions }), spanOptions: spanOptions }; return [4 /*yield*/, this._containerOrBlobOperation.breakLease(operationOptions)]; case 2: return [2 /*return*/, _h.sent()]; case 3: e_48 = _h.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_48.message }); throw e_48; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; return BlobLeaseClient; }()); /** * A ContainerClient represents a URL to the Azure Storage container allowing you to manipulate its blobs. * * @export * @class ContainerClient */ var ContainerClient = /** @class */ (function (_super) { tslib.__extends(ContainerClient, _super); function ContainerClient(urlOrConnectionString, credentialOrPipelineOrContainerName, options) { var _this = this; var pipeline; var url; options = options || {}; if (credentialOrPipelineOrContainerName instanceof Pipeline) { // (url: string, pipeline: Pipeline) url = urlOrConnectionString; pipeline = credentialOrPipelineOrContainerName; } else if ((coreHttp.isNode && credentialOrPipelineOrContainerName instanceof StorageSharedKeyCredential) || credentialOrPipelineOrContainerName instanceof AnonymousCredential || coreHttp.isTokenCredential(credentialOrPipelineOrContainerName)) { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) url = urlOrConnectionString; pipeline = newPipeline(credentialOrPipelineOrContainerName, options); } else if (!credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName !== "string") { // (url: string, credential?: StorageSharedKeyCredential | AnonymousCredential | TokenCredential, options?: StoragePipelineOptions) // The second parameter is undefined. Use anonymous credential. url = urlOrConnectionString; pipeline = newPipeline(new AnonymousCredential(), options); } else if (credentialOrPipelineOrContainerName && typeof credentialOrPipelineOrContainerName === "string") { // (connectionString: string, containerName: string, blobName: string, options?: StoragePipelineOptions) var containerName = credentialOrPipelineOrContainerName; var extractedCreds = extractConnectionStringParts(urlOrConnectionString); if (extractedCreds.kind === "AccountConnString") { { var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); url = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)); options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); pipeline = newPipeline(sharedKeyCredential, options); } } else if (extractedCreds.kind === "SASConnString") { url = appendToURLPath(extractedCreds.url, encodeURIComponent(containerName)) + "?" + extractedCreds.accountSas; pipeline = newPipeline(new AnonymousCredential(), options); } else { throw new Error("Connection string must be either an Account connection string or a SAS connection string"); } } else { throw new Error("Expecting non-empty strings for containerName parameter"); } _this = _super.call(this, url, pipeline) || this; _this._containerName = _this.getContainerNameFromUrl(); _this.containerContext = new Container(_this.storageClientContext); return _this; } 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. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container * * @param {ContainerCreateOptions} [options] Options to Container Create operation. * @returns {Promise} * @memberof ContainerClient * * Example usage: * * ```js * const containerClient = blobServiceClient.getContainerClient(""); * const createContainerResponse = await containerClient.create(); * 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, spanOptions, e_49; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("ContainerClient-create", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.containerContext.create(tslib.__assign(tslib.__assign({}, options), { spanOptions: spanOptions }))]; 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_49 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_49.message }); throw e_49; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Creates a new container under the specified account. If the container with * the same name already exists, it is not changed. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-container * * @param {ContainerCreateOptions} [options] * @returns {Promise} * @memberof ContainerClient */ ContainerClient.prototype.createIfNotExists = function (options) { var _a, _b; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _c, span, spanOptions, res, e_50; return tslib.__generator(this, function (_d) { switch (_d.label) { case 0: _c = createSpan("ContainerClient-createIfNotExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; _d.label = 1; case 1: _d.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.create(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; 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_50 = _d.sent(); if (((_a = e_50.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerAlreadyExists") { span.setStatus({ code: api.CanonicalCode.ALREADY_EXISTS, 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_50.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_50.response })]; } span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_50.message }); throw e_50; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Returns true if the Azure container resource represented by this client exists; false otherwise. * * NOTE: use this function with care since an existing container might be deleted by other clients or * applications. Vice versa new containers with the same name might be added by other clients or * applications after this function completes. * * @param {ContainerExistsOptions} [options={}] * @returns {Promise} * @memberof ContainerClient */ ContainerClient.prototype.exists = function (options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, e_51; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("ContainerClient-exists", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.getProperties({ abortSignal: options.abortSignal, tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) })]; case 2: _b.sent(); return [2 /*return*/, true]; case 3: e_51 = _b.sent(); if (e_51.statusCode === 404) { span.setStatus({ code: api.CanonicalCode.NOT_FOUND, message: "Expected exception when checking container existence" }); return [2 /*return*/, false]; } span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_51.message }); throw e_51; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Creates a {@link BlobClient} * * @param {string} blobName A blob name * @returns {BlobClient} A new BlobClient object for the given blob name. * @memberof ContainerClient */ ContainerClient.prototype.getBlobClient = function (blobName) { return new BlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); }; /** * Creates an {@link AppendBlobClient} * * @param {string} blobName An append blob name * @returns {AppendBlobClient} * @memberof ContainerClient */ ContainerClient.prototype.getAppendBlobClient = function (blobName) { return new AppendBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); }; /** * Creates a {@link BlockBlobClient} * * @param {string} blobName A block blob name * @returns {BlockBlobClient} * @memberof ContainerClient * * Example usage: * * ```js * const content = "Hello world!"; * * const blockBlobClient = containerClient.getBlockBlobClient(""); * const uploadBlobResponse = await blockBlobClient.upload(content, content.length); * ``` */ ContainerClient.prototype.getBlockBlobClient = function (blobName) { return new BlockBlobClient(appendToURLPath(this.url, encodeURIComponent(blobName)), this.pipeline); }; /** * Creates a {@link PageBlobClient} * * @param {string} blobName A page blob name * @returns {PageBlobClient} * @memberof ContainerClient */ ContainerClient.prototype.getPageBlobClient = function (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. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-properties * * WARNING: The `metadata` object returned in the response will have its keys in lowercase, even if * they originally contained uppercase characters. This differs from the metadata keys returned by * the `listContainers` method of {@link BlobServiceClient} using the `includeMetadata` option, which * will retain their original casing. * * @param {ContainerGetPropertiesOptions} [options] Options to Container Get Properties operation. * @returns {Promise} * @memberof ContainerClient */ ContainerClient.prototype.getProperties = function (options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, e_52; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: if (!options.conditions) { options.conditions = {}; } _a = createSpan("ContainerClient-getProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.containerContext.getProperties(tslib.__assign(tslib.__assign({ abortSignal: options.abortSignal }, options.conditions), { spanOptions: spanOptions }))]; case 2: return [2 /*return*/, _b.sent()]; case 3: e_52 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_52.message }); throw e_52; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Marks the specified container for deletion. The container and any blobs * contained within it are later deleted during garbage collection. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container * * @param {ContainerDeleteMethodOptions} [options] Options to Container Delete operation. * @returns {Promise} * @memberof ContainerClient */ ContainerClient.prototype.delete = function (options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, e_53; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: if (!options.conditions) { options.conditions = {}; } _a = createSpan("ContainerClient-delete", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.containerContext.deleteMethod({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, modifiedAccessConditions: options.conditions, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _b.sent()]; case 3: e_53 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_53.message }); throw e_53; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Marks the specified container for deletion if it exists. The container and any blobs * contained within it are later deleted during garbage collection. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-container * * @param {ContainerDeleteMethodOptions} [options] Options to Container Delete operation. * @returns {Promise} * @memberof ContainerClient */ ContainerClient.prototype.deleteIfExists = function (options) { var _a, _b; if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _c, span, spanOptions, res, e_54; return tslib.__generator(this, function (_d) { switch (_d.label) { case 0: _c = createSpan("ContainerClient-deleteIfExists", options.tracingOptions), span = _c.span, spanOptions = _c.spanOptions; _d.label = 1; case 1: _d.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; 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_54 = _d.sent(); if (((_a = e_54.details) === null || _a === void 0 ? void 0 : _a.errorCode) === "ContainerNotFound") { span.setStatus({ code: api.CanonicalCode.NOT_FOUND, message: "Expected exception when deleting a container only if it exists." }); return [2 /*return*/, tslib.__assign(tslib.__assign({ succeeded: false }, (_b = e_54.response) === null || _b === void 0 ? void 0 : _b.parsedHeaders), { _response: e_54.response })]; } span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_54.message }); throw e_54; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Sets one or more user-defined name-value pairs for the specified container. * * If no option provided, or no metadata defined in the parameter, the container * metadata will be removed. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-metadata * * @param {Metadata} [metadata] Replace existing metadata with this value. * If no value provided the existing metadata will be removed. * @param {ContainerSetMetadataOptions} [options] Options to Container Set Metadata operation. * @returns {Promise} * @memberof ContainerClient */ ContainerClient.prototype.setMetadata = function (metadata, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, e_55; 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.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.containerContext.setMetadata({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, metadata: metadata, modifiedAccessConditions: options.conditions, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _b.sent()]; case 3: e_55 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_55.message }); throw e_55; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Gets the permissions for the specified container. The permissions indicate * whether container data may be accessed publicly. * * WARNING: JavaScript Date will potentially lose precision when parsing startsOn and expiresOn strings. * For example, new Date("2018-12-31T03:44:23.8827891Z").toISOString() will get "2018-12-31T03:44:23.882Z". * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-container-acl * * @param {ContainerGetAccessPolicyOptions} [options] Options to Container Get Access Policy operation. * @returns {Promise} * @memberof ContainerClient */ ContainerClient.prototype.getAccessPolicy = function (options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, response, res, _i, response_1, identifier, accessPolicy, e_56; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: if (!options.conditions) { options.conditions = {}; } _a = createSpan("ContainerClient-getAccessPolicy", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.containerContext.getAccessPolicy({ abortSignal: options.abortSignal, leaseAccessConditions: options.conditions, spanOptions: spanOptions })]; 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_56 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_56.message }); throw e_56; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Sets the permissions for the specified container. The permissions indicate * whether blobs in a container may be accessed publicly. * * When you set permissions for a container, the existing permissions are replaced. * If no access or containerAcl provided, the existing container ACL will be * removed. * * When you establish a stored access policy on a container, it may take up to 30 seconds to take effect. * During this interval, a shared access signature that is associated with the stored access policy will * fail with status code 403 (Forbidden), until the access policy becomes active. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-container-acl * * @param {PublicAccessType} [access] The level of public access to data in the container. * @param {SignedIdentifier[]} [containerAcl] Array of elements each having a unique Id and details of the access policy. * @param {ContainerSetAccessPolicyOptions} [options] Options to Container Set Access Policy operation. * @returns {Promise} * @memberof ContainerClient */ ContainerClient.prototype.setAccessPolicy = function (access, containerAcl, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, acl, _i, _b, identifier, e_57; return tslib.__generator(this, function (_c) { switch (_c.label) { case 0: options.conditions = options.conditions || {}; _a = createSpan("ContainerClient-setAccessPolicy", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _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({ abortSignal: options.abortSignal, access: access, containerAcl: acl, leaseAccessConditions: options.conditions, modifiedAccessConditions: options.conditions, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _c.sent()]; case 3: e_57 = _c.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_57.message }); throw e_57; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Get a {@link BlobLeaseClient} that manages leases on the container. * * @param {string} [proposeLeaseId] Initial proposed lease Id. * @returns {BlobLeaseClient} A new BlobLeaseClient object for managing leases on the container. * @memberof ContainerClient */ ContainerClient.prototype.getBlobLeaseClient = function (proposeLeaseId) { return new BlobLeaseClient(this, proposeLeaseId); }; /** * 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. * Partial updates are not supported; the content of the existing blob is * overwritten with the new content. To perform a partial update of a block blob's, * use {@link BlockBlobClient.stageBlock} and {@link BlockBlobClient.commitBlockList}. * * This is a non-parallel uploading method, please use {@link BlockBlobClient.uploadFile}, * {@link BlockBlobClient.uploadStream} or {@link BlockBlobClient.uploadBrowserData} for better * performance with concurrency uploading. * * @see https://docs.microsoft.com/rest/api/storageservices/put-blob * * @param {string} blobName Name of the block blob to create or update. * @param {HttpRequestBody} body Blob, string, ArrayBuffer, ArrayBufferView or a function * which returns a new Readable stream whose offset is from data source beginning. * @param {number} contentLength Length of body in bytes. Use Buffer.byteLength() to calculate body length for a * string including non non-Base64/Hex-encoded characters. * @param {BlockBlobUploadOptions} [options] Options to configure the Block Blob Upload operation. * @returns {Promise<{ blockBlobClient: BlockBlobClient; response: BlockBlobUploadResponse }>} Block Blob upload response data and the corresponding BlockBlobClient instance. * @memberof ContainerClient */ 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, spanOptions, blockBlobClient, response, e_58; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("ContainerClient-uploadBlockBlob", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); blockBlobClient = this.getBlockBlobClient(blobName); return [4 /*yield*/, blockBlobClient.upload(body, contentLength, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: response = _b.sent(); return [2 /*return*/, { blockBlobClient: blockBlobClient, response: response }]; case 3: e_58 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_58.message }); throw e_58; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Marks the specified blob or snapshot for deletion. The blob is later deleted * during garbage collection. Note that in order to delete a blob, you must delete * all of its snapshots. You can delete both at the same time with the Delete * Blob operation. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/delete-blob * * @param {string} blobName * @param {ContainerDeleteBlobOptions} [options] Options to Blob Delete operation. * @returns {Promise} Block blob deletion response data. * @memberof ContainerClient */ ContainerClient.prototype.deleteBlob = function (blobName, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, blobClient, e_59; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("ContainerClient-deleteBlob", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _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(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: return [2 /*return*/, _b.sent()]; case 3: e_59 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_59.message }); throw e_59; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * listBlobFlatSegment returns a single segment of blobs starting from the * specified Marker. Use an empty Marker to start enumeration from the beginning. * After getting a segment, process it, and then call listBlobsFlatSegment again * (passing the the previously-returned Marker) to get the next segment. * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs * * @param {string} [marker] A string value that identifies the portion of the list to be returned with the next list operation. * @param {ContainerListBlobsSegmentOptions} [options] Options to Container List Blob Flat Segment operation. * @returns {Promise} * @memberof ContainerClient */ ContainerClient.prototype.listBlobFlatSegment = function (marker, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, response, wrappedResponse, e_60; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("ContainerClient-listBlobFlatSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _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), { spanOptions: spanOptions }))]; 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_60 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_60.message }); throw e_60; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * listBlobHierarchySegment returns a single segment of blobs starting from * the specified Marker. Use an empty Marker to start enumeration from the * beginning. After getting a segment, process it, and then call listBlobsHierarchicalSegment * again (passing the the previously-returned Marker) to get the next segment. * @see https://docs.microsoft.com/rest/api/storageservices/list-blobs * * @param {string} delimiter The character or string used to define the virtual hierarchy * @param {string} [marker] A string value that identifies the portion of the list to be returned with the next list operation. * @param {ContainerListBlobsSegmentOptions} [options] Options to Container List Blob Hierarchy Segment operation. * @returns {Promise} * @memberof ContainerClient */ ContainerClient.prototype.listBlobHierarchySegment = function (delimiter, marker, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, response, wrappedResponse, e_61; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("ContainerClient-listBlobHierarchySegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _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), { spanOptions: spanOptions }))]; 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_61 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_61.message }); throw e_61; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Returns an AsyncIterableIterator for ContainerListBlobFlatSegmentResponse * * @private * @param {string} [marker] A string value that identifies the portion of * the list of blobs to be returned with the next listing operation. The * operation returns the ContinuationToken value within the response body if the * listing operation did not return all blobs remaining to be listed * with the current page. The ContinuationToken value can be used as the value for * the marker parameter in a subsequent call to request the next page of list * items. The marker value is opaque to the client. * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. * @returns {AsyncIterableIterator} * @memberof ContainerClient */ 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*/]; } }); }); }; /** * Returns an AsyncIterableIterator of {@link BlobItem} objects * * @private * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. * @returns {AsyncIterableIterator} * @memberof ContainerClient */ ContainerClient.prototype.listItems = function (options) { if (options === void 0) { options = {}; } return tslib.__asyncGenerator(this, arguments, function listItems_1() { var marker, _a, _b, listBlobsFlatSegmentResponse, e_62_1; var e_62, _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_62_1 = _d.sent(); e_62 = { error: e_62_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_62) throw e_62.error; return [7 /*endfinally*/]; case 12: return [7 /*endfinally*/]; case 13: return [2 /*return*/]; } }); }); }; /** * Returns an async iterable iterator to list all the blobs * under the specified account. * * .byPage() returns an async iterable iterator to list the blobs in pages. * * Example using `for await` syntax: * * ```js * // Get the containerClient before you run these snippets, * // Can be obtained from `blobServiceClient.getContainerClient("");` * let i = 1; * for await (const blob of containerClient.listBlobsFlat()) { * console.log(`Blob ${i++}: ${blob.name}`); * } * ``` * * Example using `iter.next()`: * * ```js * let i = 1; * let iter = containerClient.listBlobsFlat(); * let blobItem = await iter.next(); * while (!blobItem.done) { * console.log(`Blob ${i++}: ${blobItem.value.name}`); * blobItem = await iter.next(); * } * ``` * * Example using `byPage()`: * * ```js * // passing optional maxPageSize in the page settings * let i = 1; * for await (const response of containerClient.listBlobsFlat().byPage({ maxPageSize: 20 })) { * for (const blob of response.segment.blobItems) { * console.log(`Blob ${i++}: ${blob.name}`); * } * } * ``` * * Example using paging with a marker: * * ```js * let i = 1; * let iterator = containerClient.listBlobsFlat().byPage({ maxPageSize: 2 }); * let response = (await iterator.next()).value; * * // Prints 2 blob names * for (const blob of response.segment.blobItems) { * console.log(`Blob ${i++}: ${blob.name}`); * } * * // Gets next marker * let marker = response.continuationToken; * * // Passing next marker as continuationToken * * iterator = containerClient.listBlobsFlat().byPage({ continuationToken: marker, maxPageSize: 10 }); * response = (await iterator.next()).value; * * // Prints 10 blob names * for (const blob of response.segment.blobItems) { * console.log(`Blob ${i++}: ${blob.name}`); * } * ``` * * @param {ContainerListBlobsOptions} [options={}] Options to list blobs. * @returns {PagedAsyncIterableIterator} An asyncIterableIterator that supports paging. * @memberof ContainerClient */ ContainerClient.prototype.listBlobsFlat = function (options) { var _a; var _this = this; if (options === void 0) { options = {}; } var include = []; if (options.includeCopy) { include.push("copy"); } if (options.includeDeleted) { include.push("deleted"); } if (options.includeMetadata) { include.push("metadata"); } if (options.includeSnapshots) { include.push("snapshots"); } if (options.includeVersions) { include.push("versions"); } if (options.includeUncommitedBlobs) { include.push("uncommittedblobs"); } if (options.includeTags) { include.push("tags"); } if (options.prefix === "") { options.prefix = undefined; } var updatedOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); // AsyncIterableIterator to iterate over blobs var iter = this.listItems(updatedOptions); return _a = { /** * @member {Promise} [next] The next method, part of the iteration protocol */ next: function () { return iter.next(); } }, /** * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol */ _a[Symbol.asyncIterator] = function () { return this; }, /** * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time */ _a.byPage = function (settings) { if (settings === void 0) { settings = {}; } return _this.listSegments(settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); }, _a; }; /** * Returns an AsyncIterableIterator for ContainerListBlobHierarchySegmentResponse * * @private * @param {string} delimiter The character or string used to define the virtual hierarchy * @param {string} [marker] A string value that identifies the portion of * the list of blobs to be returned with the next listing operation. The * operation returns the ContinuationToken value within the response body if the * listing operation did not return all blobs remaining to be listed * with the current page. The ContinuationToken value can be used as the value for * the marker parameter in a subsequent call to request the next page of list * items. The marker value is opaque to the client. * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. * @returns {AsyncIterableIterator} * @memberof ContainerClient */ 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*/]; } }); }); }; /** * Returns an AsyncIterableIterator for {@link BlobPrefix} and {@link BlobItem} objects. * * @private * @param {string} delimiter The character or string used to define the virtual hierarchy * @param {ContainerListBlobsSegmentOptions} [options] Options to list blobs operation. * @returns {AsyncIterableIterator<{ kind: "prefix" } & BlobPrefix | { kind: "blob" } & BlobItem>} * @memberof ContainerClient */ 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_63_1; var e_63, _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_63_1 = _g.sent(); e_63 = { error: e_63_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_63) throw e_63.error; return [7 /*endfinally*/]; case 19: return [7 /*endfinally*/]; case 20: return [2 /*return*/]; } }); }); }; /** * Returns an async iterable iterator to list all the blobs by hierarchy. * under the specified account. * * .byPage() returns an async iterable iterator to list the blobs by hierarchy in pages. * * Example using `for await` syntax: * * ```js * for await (const item of containerClient.listBlobsByHierarchy("/")) { * if (item.kind === "prefix") { * console.log(`\tBlobPrefix: ${item.name}`); * } else { * console.log(`\tBlobItem: name - ${item.name}, last modified - ${item.properties.lastModified}`); * } * } * ``` * * Example using `iter.next()`: * * ```js * let iter = containerClient.listBlobsByHierarchy("/", { prefix: "prefix1/" }); * let entity = await iter.next(); * while (!entity.done) { * let item = entity.value; * if (item.kind === "prefix") { * console.log(`\tBlobPrefix: ${item.name}`); * } else { * console.log(`\tBlobItem: name - ${item.name}, last modified - ${item.properties.lastModified}`); * } * entity = await iter.next(); * } * ```js * * Example using `byPage()`: * * ```js * console.log("Listing blobs by hierarchy by page"); * for await (const response of containerClient.listBlobsByHierarchy("/").byPage()) { * const segment = response.segment; * if (segment.blobPrefixes) { * for (const prefix of segment.blobPrefixes) { * console.log(`\tBlobPrefix: ${prefix.name}`); * } * } * for (const blob of response.segment.blobItems) { * console.log(`\tBlobItem: name - ${blob.name}, last modified - ${blob.properties.lastModified}`); * } * } * ``` * * Example using paging with a max page size: * * ```js * console.log("Listing blobs by hierarchy by page, specifying a prefix and a max page size"); * * let i = 1; * for await (const response of containerClient.listBlobsByHierarchy("/", { prefix: "prefix2/sub1/"}).byPage({ maxPageSize: 2 })) { * console.log(`Page ${i++}`); * const segment = response.segment; * * if (segment.blobPrefixes) { * for (const prefix of segment.blobPrefixes) { * console.log(`\tBlobPrefix: ${prefix.name}`); * } * } * * for (const blob of response.segment.blobItems) { * console.log(`\tBlobItem: name - ${blob.name}, last modified - ${blob.properties.lastModified}`); * } * } * ``` * * @param {string} delimiter The character or string used to define the virtual hierarchy * @param {ContainerListBlobsOptions} [options={}] Options to list blobs operation. * @returns {(PagedAsyncIterableIterator< * { kind: "prefix" } & BlobPrefix | { kind: "blob" } & BlobItem, * ContainerListBlobHierarchySegmentResponse * >)} * @memberof ContainerClient */ ContainerClient.prototype.listBlobsByHierarchy = function (delimiter, options) { var _a; var _this = this; if (options === void 0) { options = {}; } if (delimiter === "") { throw new RangeError("delimiter should contain one or more characters"); } var include = []; if (options.includeCopy) { include.push("copy"); } if (options.includeDeleted) { include.push("deleted"); } if (options.includeMetadata) { include.push("metadata"); } if (options.includeSnapshots) { include.push("snapshots"); } if (options.includeVersions) { include.push("versions"); } if (options.includeUncommitedBlobs) { include.push("uncommittedblobs"); } if (options.includeTags) { include.push("tags"); } if (options.prefix === "") { options.prefix = undefined; } var updatedOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); // AsyncIterableIterator to iterate over blob prefixes and blobs var iter = this.listItemsByHierarchy(delimiter, updatedOptions); return _a = { /** * @member {Promise} [next] 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()]; }); }); } }, /** * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol */ _a[Symbol.asyncIterator] = function () { return this; }, /** * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time */ _a.byPage = function (settings) { if (settings === void 0) { settings = {}; } return _this.listHierarchySegments(delimiter, settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, updatedOptions)); }, _a; }; ContainerClient.prototype.getContainerNameFromUrl = function () { var 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); if (parsedUrl.getHost().split(".")[1] === "blob") { // "https://myaccount.blob.core.windows.net/containername". // "https://customdomain.com/containername". // .getPath() -> /containername containerName = parsedUrl.getPath().split("/")[1]; } else if (isIpEndpointStyle(parsedUrl)) { // IPv4/IPv6 address hosts... Example - http://192.0.0.10:10001/devstoreaccount1/containername // Single word domain without a [dot] in the endpoint... Example - http://localhost:10001/devstoreaccount1/containername // .getPath() -> /devstoreaccount1/containername containerName = parsedUrl.getPath().split("/")[2]; } else { // "https://customdomain.com/containername". // .getPath() -> /containername containerName = parsedUrl.getPath().split("/")[1]; } // decode the encoded containerName - to get all the special characters that might be present in it containerName = decodeURIComponent(containerName); if (!containerName) { throw new Error("Provided containerName is invalid."); } return containerName; } catch (error) { throw new Error("Unable to extract containerName with provided information."); } }; return ContainerClient; }(StorageClient)); 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()]; } }); }); } function utf8ByteLength(str) { return Buffer.byteLength(str); } var HTTP_HEADER_DELIMITER = ": "; var SPACE_DELIMITER = " "; var NOT_FOUND = -1; /** * Util class for parsing batch response. */ var BatchResponseParser = /** @class */ (function () { function BatchResponseParser(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."); } if (!subRequests || subRequests.size === 0) { // This should be prevent during coding. throw new RangeError("Invalid state: subRequests is not provided or size is 0."); } this.batchResponse = batchResponse; this.subRequests = subRequests; this.responseBatchBoundary = this.batchResponse.contentType.split("=")[1]; 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]; deserializedSubResponses[index] = {}; deserializedSubResponse = deserializedSubResponses[index]; 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 if (contentId != NOT_FOUND) { deserializedSubResponse._request = this.subRequests.get(contentId); } if (subRespFailed) { subResponsesFailedCount++; } else { subResponsesSucceededCount++; } } return [2 /*return*/, { subResponses: deserializedSubResponses, subResponsesSucceededCount: subResponsesSucceededCount, subResponsesFailedCount: subResponsesFailedCount }]; } }); }); }; return BatchResponseParser; }()); var MutexLockStatus; (function (MutexLockStatus) { MutexLockStatus[MutexLockStatus["LOCKED"] = 0] = "LOCKED"; MutexLockStatus[MutexLockStatus["UNLOCKED"] = 1] = "UNLOCKED"; })(MutexLockStatus || (MutexLockStatus = {})); /** * An async mutex lock. * * @export * @class Mutex */ var Mutex = /** @class */ (function () { function Mutex() { } /** * Lock for a specific key. If the lock has been acquired by another customer, then * will wait until getting the lock. * * @static * @param {string} key lock key * @returns {Promise} * @memberof Mutex */ 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(); }); } })]; }); }); }; /** * Unlock a key. * * @static * @param {string} key * @returns {Promise} * @memberof Mutex */ 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(); })]; }); }); }; Mutex.onUnlockEvent = function (key, handler) { if (this.listeners[key] === undefined) { this.listeners[key] = [handler]; } else { this.listeners[key].push(handler); } }; Mutex.emitUnlockEvent = function (key) { var _this = this; if (this.listeners[key] !== undefined && this.listeners[key].length > 0) { var handler_1 = this.listeners[key].shift(); setImmediate(function () { handler_1.call(_this); }); } }; Mutex.keys = {}; Mutex.listeners = {}; return Mutex; }()); /** * A BlobBatch represents an aggregated set of operations on blobs. * Currently, only `delete` and `setAccessTier` are supported. * * @export * @class BlobBatch */ var BlobBatch = /** @class */ (function () { function BlobBatch() { this.batch = "batch"; this.batchRequest = new InnerBatchRequest(); } /** * Get the value of Content-Type for a batch request. * The value must be multipart/mixed with a batch boundary. * Example: multipart/mixed; boundary=batch_a81786c8-e301-4e42-a729-a32ca24ae252 */ BlobBatch.prototype.getMultiPartContentType = function () { return this.batchRequest.getMultipartContentType(); }; /** * Get assembled HTTP request body for sub requests. */ BlobBatch.prototype.getHttpRequestBody = function () { return this.batchRequest.getHttpRequestBody(); }; /** * Get sub requests that are added into the batch request. */ BlobBatch.prototype.getSubRequests = function () { 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) { 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."); } }; BlobBatch.prototype.deleteBlob = function (urlOrBlobClient, credentialOrOptions, options) { return tslib.__awaiter(this, void 0, void 0, function () { var url, credential, _a, span, spanOptions, 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.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _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(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 1: _a.sent(); return [2 /*return*/]; } }); }); })]; case 2: _b.sent(); return [3 /*break*/, 5]; case 3: e_1 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_1.message }); throw e_1; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; BlobBatch.prototype.setBlobAccessTier = function (urlOrBlobClient, credentialOrTier, tierOrOptions, options) { return tslib.__awaiter(this, void 0, void 0, function () { var url, credential, tier, _a, span, spanOptions, 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.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _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, tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 1: _a.sent(); return [2 /*return*/]; } }); }); })]; case 2: _b.sent(); return [3 /*break*/, 5]; case 3: e_2 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_2.message }); throw e_2; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; return BlobBatch; }()); /** * 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() { this.operationCount = 0; this.body = ""; var tempGuid = coreHttp.generateUuid(); // batch_{batchid} 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"; // multipart/mixed; boundary=batch_{batchid} this.multipartContentType = "multipart/mixed; boundary=" + this.boundary; // --batch_{batchid}-- this.batchRequestEnding = "--" + this.boundary + "--"; this.subRequests = new Map(); } /** * Create pipeline to assemble sub requests. The idea here is to use existing * credential and serialization/deserialization components, with additional policies to * filter unnecessary headers, assemble sub requests into request's body * and intercept request from going to wire. * @param {StorageSharedKeyCredential | AnonymousCredential | TokenCredential} 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); 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) { factories[2] = coreHttp.isTokenCredential(credential) ? coreHttp.bearerTokenAuthenticationPolicy(credential, StorageOAuthScopes) : credential; } factories[policyFactoryLength - 1] = new BatchRequestAssemblePolicyFactory(this); // Use batch assemble policy to assemble request and intercept request from going to wire return new Pipeline(factories, {}); }; InnerBatchRequest.prototype.appendSubRequestToBody = function (request) { // Start to assemble sub request this.body += [ this.subRequestPrefix, HeaderConstants.CONTENT_ID + ": " + this.operationCount, "", 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; } 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) { if (this.operationCount >= BATCH_MAX_REQUEST) { 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 + "'"); } }; InnerBatchRequest.prototype.postAddSubRequest = function (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 () { return this.multipartContentType; }; InnerBatchRequest.prototype.getSubRequests = function () { 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 = { 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) { 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() { } BatchHeaderFilterPolicyFactory.prototype.create = function (nextPolicy, options) { return new BatchHeaderFilterPolicy(nextPolicy, options); }; return BatchHeaderFilterPolicyFactory; }()); // Copyright (c) Microsoft Corporation. All rights reserved. /** * A BlobBatchClient allows you to make batched requests to the Azure Storage Blob service. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch */ var BlobBatchClient = /** @class */ (function () { function BlobBatchClient(url, credentialOrPipeline, options) { var pipeline; if (credentialOrPipeline instanceof Pipeline) { pipeline = credentialOrPipeline; } else if (!credentialOrPipeline) { // no credential provided pipeline = newPipeline(new AnonymousCredential(), options); } else { pipeline = newPipeline(credentialOrPipeline, options); } var storageClientContext = new StorageClientContext(url, pipeline.toServiceClientOptions()); this._serviceContext = new Service(storageClientContext); } /** * Creates a {@link BlobBatch}. * A BlobBatch represents an aggregated set of operations on blobs. */ BlobBatchClient.prototype.createBatch = function () { return new BlobBatch(); }; BlobBatchClient.prototype.deleteBlobs = function (urlsOrBlobClients, credentialOrOptions, options) { return tslib.__awaiter(this, void 0, void 0, function () { var batch, _i, urlsOrBlobClients_1, urlOrBlobClient; return tslib.__generator(this, function (_a) { switch (_a.label) { case 0: batch = new BlobBatch(); _i = 0, urlsOrBlobClients_1 = urlsOrBlobClients; _a.label = 1; case 1: if (!(_i < urlsOrBlobClients_1.length)) return [3 /*break*/, 6]; urlOrBlobClient = urlsOrBlobClients_1[_i]; if (!(typeof urlOrBlobClient === "string")) return [3 /*break*/, 3]; return [4 /*yield*/, batch.deleteBlob(urlOrBlobClient, credentialOrOptions, options)]; case 2: _a.sent(); return [3 /*break*/, 5]; case 3: return [4 /*yield*/, batch.deleteBlob(urlOrBlobClient, credentialOrOptions)]; case 4: _a.sent(); _a.label = 5; case 5: _i++; return [3 /*break*/, 1]; case 6: return [2 /*return*/, this.submitBatch(batch)]; } }); }); }; BlobBatchClient.prototype.setBlobsAccessTier = function (urlsOrBlobClients, credentialOrTier, tierOrOptions, options) { return tslib.__awaiter(this, void 0, void 0, function () { var batch, _i, urlsOrBlobClients_2, urlOrBlobClient; return tslib.__generator(this, function (_a) { switch (_a.label) { case 0: batch = new BlobBatch(); _i = 0, urlsOrBlobClients_2 = urlsOrBlobClients; _a.label = 1; case 1: if (!(_i < urlsOrBlobClients_2.length)) return [3 /*break*/, 6]; urlOrBlobClient = urlsOrBlobClients_2[_i]; if (!(typeof urlOrBlobClient === "string")) return [3 /*break*/, 3]; return [4 /*yield*/, batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions, options)]; case 2: _a.sent(); return [3 /*break*/, 5]; case 3: return [4 /*yield*/, batch.setBlobAccessTier(urlOrBlobClient, credentialOrTier, tierOrOptions)]; case 4: _a.sent(); _a.label = 5; case 5: _i++; return [3 /*break*/, 1]; case 6: return [2 /*return*/, this.submitBatch(batch)]; } }); }); }; /** * Submit batch request which consists of multiple subrequests. * * Get `blobBatchClient` and other details before running the snippets. * `blobServiceClient.getBlobBatchClient()` gives the `blobBatchClient` * * Example usage: * * ```js * let batchRequest = new BlobBatch(); * await batchRequest.deleteBlob(urlInString0, credential0); * await batchRequest.deleteBlob(urlInString1, credential1, { * deleteSnapshots: "include" * }); * const batchResp = await blobBatchClient.submitBatch(batchRequest); * console.log(batchResp.subResponsesSucceededCount); * ``` * * Example using a lease: * * ```js * let batchRequest = new BlobBatch(); * await batchRequest.setBlobAccessTier(blockBlobClient0, "Cool"); * await batchRequest.setBlobAccessTier(blockBlobClient1, "Cool", { * conditions: { leaseId: leaseId } * }); * const batchResp = await blobBatchClient.submitBatch(batchRequest); * console.log(batchResp.subResponsesSucceededCount); * ``` * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch * * @param {BlobBatch} batchRequest A set of Delete or SetTier operations. * @param {BlobBatchSubmitBatchOptionalParams} [options] * @returns {Promise} * @memberof BlobBatchClient */ BlobBatchClient.prototype.submitBatch = function (batchRequest, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, batchRequestBody, rawBatchResponse, batchResponseParser, responseSummary, res, e_1; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: if (!batchRequest || batchRequest.getSubRequests().size == 0) { throw new RangeError("Batch request should contain one or more sub requests."); } _a = createSpan("BlobBatchClient-submitBatch", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 4, 5, 6]); batchRequestBody = batchRequest.getHttpRequestBody(); return [4 /*yield*/, this._serviceContext.submitBatch(batchRequestBody, utf8ByteLength(batchRequestBody), batchRequest.getMultiPartContentType(), tslib.__assign(tslib.__assign({}, options), { spanOptions: spanOptions }))]; case 2: rawBatchResponse = _b.sent(); batchResponseParser = new BatchResponseParser(rawBatchResponse, batchRequest.getSubRequests()); return [4 /*yield*/, batchResponseParser.parseBatchResponse()]; case 3: responseSummary = _b.sent(); res = { _response: rawBatchResponse._response, contentType: rawBatchResponse.contentType, errorCode: rawBatchResponse.errorCode, requestId: rawBatchResponse.requestId, clientRequestId: rawBatchResponse.clientRequestId, version: rawBatchResponse.version, subResponses: responseSummary.subResponses, subResponsesSucceededCount: responseSummary.subResponsesSucceededCount, subResponsesFailedCount: responseSummary.subResponsesFailedCount }; return [2 /*return*/, res]; case 4: e_1 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_1.message }); throw e_1; case 5: span.end(); return [7 /*endfinally*/]; case 6: return [2 /*return*/]; } }); }); }; return BlobBatchClient; }()); /** * A BlobServiceClient represents a Client to the Azure Storage Blob service allowing you * to manipulate blob containers. * * @export * @class BlobServiceClient */ var BlobServiceClient = /** @class */ (function (_super) { tslib.__extends(BlobServiceClient, _super); function BlobServiceClient(url, credentialOrPipeline, options) { var _this = this; var pipeline; if (credentialOrPipeline instanceof Pipeline) { pipeline = credentialOrPipeline; } else if ((coreHttp.isNode && credentialOrPipeline instanceof StorageSharedKeyCredential) || credentialOrPipeline instanceof AnonymousCredential || coreHttp.isTokenCredential(credentialOrPipeline)) { pipeline = newPipeline(credentialOrPipeline, options); } else { // 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; } /** * * Creates an instance of BlobServiceClient from connection string. * * @param {string} connectionString Account connection string or a SAS connection string of an Azure storage account. * [ Note - Account connection string can only be used in NODE.JS runtime. ] * Account connection string example - * `DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=accountKey;EndpointSuffix=core.windows.net` * SAS connection string example - * `BlobEndpoint=https://myaccount.blob.core.windows.net/;QueueEndpoint=https://myaccount.queue.core.windows.net/;FileEndpoint=https://myaccount.file.core.windows.net/;TableEndpoint=https://myaccount.table.core.windows.net/;SharedAccessSignature=sasString` * @param {StoragePipelineOptions} [options] Optional. Options to configure the HTTP pipeline. * @memberof BlobServiceClient */ BlobServiceClient.fromConnectionString = function (connectionString, options) { options = options || {}; var extractedCreds = extractConnectionStringParts(connectionString); if (extractedCreds.kind === "AccountConnString") { { var sharedKeyCredential = new StorageSharedKeyCredential(extractedCreds.accountName, extractedCreds.accountKey); options.proxyOptions = coreHttp.getDefaultProxySettings(extractedCreds.proxyUri); var pipeline = newPipeline(sharedKeyCredential, options); return new BlobServiceClient(extractedCreds.url, pipeline); } } else if (extractedCreds.kind === "SASConnString") { var pipeline = newPipeline(new AnonymousCredential(), options); return new BlobServiceClient(extractedCreds.url + "?" + extractedCreds.accountSas, pipeline); } else { throw new Error("Connection string must be either an Account connection string or a SAS connection string"); } }; /** * Creates a {@link ContainerClient} object * * @param {string} containerName A container name * @returns {ContainerClient} A new ContainerClient object for the given container name. * @memberof BlobServiceClient * * Example usage: * * ```js * const containerClient = blobServiceClient.getContainerClient(""); * ``` */ BlobServiceClient.prototype.getContainerClient = function (containerName) { return new ContainerClient(appendToURLPath(this.url, encodeURIComponent(containerName)), this.pipeline); }; /** * Create a Blob container. * * @param {string} containerName Name of the container to create. * @param {ContainerCreateOptions} [options] Options to configure Container Create operation. * @returns {Promise<{ containerClient: ContainerClient; containerCreateResponse: ContainerCreateResponse }>} Container creation response and the corresponding container client. * @memberof BlobServiceClient */ BlobServiceClient.prototype.createContainer = function (containerName, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, containerClient, containerCreateResponse, e_1; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("BlobServiceClient-createContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); containerClient = this.getContainerClient(containerName); return [4 /*yield*/, containerClient.create(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: containerCreateResponse = _b.sent(); return [2 /*return*/, { containerClient: containerClient, containerCreateResponse: containerCreateResponse }]; case 3: e_1 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_1.message }); throw e_1; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Deletes a Blob container. * * @param {string} containerName Name of the container to delete. * @param {ContainerDeleteMethodOptions} [options] Options to configure Container Delete operation. * @returns {Promise} Container deletion response. * @memberof BlobServiceClient */ BlobServiceClient.prototype.deleteContainer = function (containerName, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, containerClient, e_2; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("BlobServiceClient-deleteContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); containerClient = this.getContainerClient(containerName); return [4 /*yield*/, containerClient.delete(tslib.__assign(tslib.__assign({}, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: return [2 /*return*/, _b.sent()]; case 3: e_2 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_2.message }); throw e_2; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * 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. * * @param {string} deletedContainerName Name of the previously deleted container. * @param {string} deletedContainerVersion Version of the previously deleted container, used to uniquely identify the deleted container. * @returns {Promise} Container deletion response. * @memberof BlobServiceClient */ BlobServiceClient.prototype.undeleteContainer = function (deletedContainerName, deletedContainerVersion, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, containerClient, containerContext, containerUndeleteResponse, e_3; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("BlobServiceClient-undeleteContainer", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); containerClient = this.getContainerClient(options.destinationContainerName || deletedContainerName); containerContext = new Container(containerClient["storageClientContext"]); return [4 /*yield*/, containerContext.restore(tslib.__assign(tslib.__assign({ deletedContainerName: deletedContainerName, deletedContainerVersion: deletedContainerVersion }, options), { tracingOptions: tslib.__assign(tslib.__assign({}, options.tracingOptions), { spanOptions: spanOptions }) }))]; case 2: containerUndeleteResponse = _b.sent(); return [2 /*return*/, { containerClient: containerClient, containerUndeleteResponse: containerUndeleteResponse }]; case 3: e_3 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_3.message }); throw e_3; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Gets the properties of a storage account’s Blob service, including properties * for Storage Analytics and CORS (Cross-Origin Resource Sharing) rules. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties * * @param {ServiceGetPropertiesOptions} [options] Options to the Service Get Properties operation. * @returns {Promise} Response data for the Service Get Properties operation. * @memberof BlobServiceClient */ BlobServiceClient.prototype.getProperties = function (options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, e_4; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("BlobServiceClient-getProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.serviceContext.getProperties({ abortSignal: options.abortSignal, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _b.sent()]; case 3: e_4 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_4.message }); throw e_4; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Sets properties for a storage account’s Blob service endpoint, including properties * for Storage Analytics, CORS (Cross-Origin Resource Sharing) rules and soft delete settings. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/set-blob-service-properties} * * @param {BlobServiceProperties} properties * @param {ServiceSetPropertiesOptions} [options] Options to the Service Set Properties operation. * @returns {Promise} Response data for the Service Set Properties operation. * @memberof BlobServiceClient */ BlobServiceClient.prototype.setProperties = function (properties, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, e_5; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("BlobServiceClient-setProperties", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.serviceContext.setProperties(properties, { abortSignal: options.abortSignal, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _b.sent()]; case 3: e_5 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_5.message }); throw e_5; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Retrieves statistics related to replication for the Blob service. It is only * available on the secondary location endpoint when read-access geo-redundant * replication is enabled for the storage account. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-stats} * * @param {ServiceGetStatisticsOptions} [options] Options to the Service Get Statistics operation. * @returns {Promise} Response data for the Service Get Statistics operation. * @memberof BlobServiceClient */ BlobServiceClient.prototype.getStatistics = function (options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, e_6; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("BlobServiceClient-getStatistics", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.serviceContext.getStatistics({ abortSignal: options.abortSignal, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _b.sent()]; case 3: e_6 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_6.message }); throw e_6; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * The Get Account Information operation returns the sku name and account kind * for the specified account. * The Get Account Information operation is available on service versions beginning * with version 2018-03-28. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-account-information * * @param {ServiceGetAccountInfoOptions} [options] Options to the Service Get Account Info operation. * @returns {Promise} Response data for the Service Get Account Info operation. * @memberof BlobServiceClient */ BlobServiceClient.prototype.getAccountInfo = function (options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, e_7; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("BlobServiceClient-getAccountInfo", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.serviceContext.getAccountInfo({ abortSignal: options.abortSignal, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _b.sent()]; case 3: e_7 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_7.message }); throw e_7; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Returns a list of the containers under the specified account. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/list-containers2 * * @param {string} [marker] A string value that identifies the portion of * the list of containers to be returned with the next listing operation. The * operation returns the continuationToken value within the response body if the * listing operation did not return all containers remaining to be listed * with the current page. The continuationToken value can be used as the value for * the marker parameter in a subsequent call to request the next page of list * items. The marker value is opaque to the client. * @param {ServiceListContainersSegmentOptions} [options] Options to the Service List Container Segment operation. * @returns {Promise} Response data for the Service List Container Segment operation. * @memberof BlobServiceClient */ BlobServiceClient.prototype.listContainersSegment = function (marker, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, e_8; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("BlobServiceClient-listContainersSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.serviceContext.listContainersSegment(tslib.__assign(tslib.__assign({ abortSignal: options.abortSignal, marker: marker }, options), { include: typeof options.include === "string" ? [options.include] : options.include, spanOptions: spanOptions }))]; case 2: return [2 /*return*/, _b.sent()]; case 3: e_8 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_8.message }); throw e_8; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * 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. * * @private * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. * The given expression must evaluate to true for a blob to be returned in the results. * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; * however, only a subset of the OData filter syntax is supported in the Blob service. * @param {string} [marker] A string value that identifies the portion of * the list of blobs to be returned with the next listing operation. The * operation returns the continuationToken value within the response body if the * listing operation did not return all blobs remaining to be listed * with the current page. The continuationToken value can be used as the value for * the marker parameter in a subsequent call to request the next page of list * items. The marker value is opaque to the client. * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to find blobs by tags. * @returns {Promise} * @memberof BlobServiceClient */ BlobServiceClient.prototype.findBlobsByTagsSegment = function (tagFilterSqlExpression, marker, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, e_9; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("BlobServiceClient-findBlobsByTagsSegment", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.serviceContext.filterBlobs({ abortSignal: options.abortSignal, where: tagFilterSqlExpression, marker: marker, maxPageSize: options.maxPageSize, spanOptions: spanOptions })]; case 2: return [2 /*return*/, _b.sent()]; case 3: e_9 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_9.message }); throw e_9; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Returns an AsyncIterableIterator for ServiceFindBlobsByTagsSegmentResponse. * * @private * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. * The given expression must evaluate to true for a blob to be returned in the results. * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; * however, only a subset of the OData filter syntax is supported in the Blob service. * @param {string} [marker] A string value that identifies the portion of * the list of blobs to be returned with the next listing operation. The * operation returns the continuationToken value within the response body if the * listing operation did not return all blobs remaining to be listed * with the current page. The continuationToken value can be used as the value for * the marker parameter in a subsequent call to request the next page of list * items. The marker value is opaque to the client. * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to find blobs by tags. * @returns {AsyncIterableIterator} * @memberof BlobServiceClient */ BlobServiceClient.prototype.findBlobsByTagsSegments = function (tagFilterSqlExpression, marker, options) { if (options === void 0) { options = {}; } return tslib.__asyncGenerator(this, arguments, function findBlobsByTagsSegments_1() { var response; return tslib.__generator(this, function (_a) { switch (_a.label) { case 0: if (!(!!marker || marker === undefined)) return [3 /*break*/, 6]; _a.label = 1; case 1: return [4 /*yield*/, tslib.__await(this.findBlobsByTagsSegment(tagFilterSqlExpression, marker, options))]; case 2: response = _a.sent(); response.blobs = response.blobs || []; marker = response.continuationToken; return [4 /*yield*/, tslib.__await(response)]; case 3: return [4 /*yield*/, _a.sent()]; case 4: _a.sent(); _a.label = 5; case 5: if (marker) return [3 /*break*/, 1]; _a.label = 6; case 6: return [2 /*return*/]; } }); }); }; /** * Returns an AsyncIterableIterator for blobs. * * @private * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. * The given expression must evaluate to true for a blob to be returned in the results. * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; * however, only a subset of the OData filter syntax is supported in the Blob service. * @param {ServiceFindBlobsByTagsSegmentOptions} [options={}] Options to findBlobsByTagsItems. * @returns {AsyncIterableIterator} * @memberof BlobServiceClient */ BlobServiceClient.prototype.findBlobsByTagsItems = function (tagFilterSqlExpression, options) { if (options === void 0) { options = {}; } return tslib.__asyncGenerator(this, arguments, function findBlobsByTagsItems_1() { var marker, _a, _b, segment, e_10_1; var e_10, _c; return tslib.__generator(this, function (_d) { switch (_d.label) { case 0: _d.trys.push([0, 7, 8, 13]); _a = tslib.__asyncValues(this.findBlobsByTagsSegments(tagFilterSqlExpression, marker, options)); _d.label = 1; case 1: return [4 /*yield*/, tslib.__await(_a.next())]; case 2: if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; segment = _b.value; return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(segment.blobs)))]; case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; case 4: _d.sent(); _d.label = 5; case 5: return [3 /*break*/, 1]; case 6: return [3 /*break*/, 13]; case 7: e_10_1 = _d.sent(); e_10 = { error: e_10_1 }; return [3 /*break*/, 13]; case 8: _d.trys.push([8, , 11, 12]); if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; return [4 /*yield*/, tslib.__await(_c.call(_a))]; case 9: _d.sent(); _d.label = 10; case 10: return [3 /*break*/, 12]; case 11: if (e_10) throw e_10.error; return [7 /*endfinally*/]; case 12: return [7 /*endfinally*/]; case 13: return [2 /*return*/]; } }); }); }; /** * Returns an async iterable iterator to find all blobs with specified tag * under the specified account. * * .byPage() returns an async iterable iterator to list the blobs in pages. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob-service-properties * * Example using `for await` syntax: * * ```js * let i = 1; * for await (const blob of blobServiceClient.findBlobsByTags("tagkey='tagvalue'")) { * console.log(`Blob ${i++}: ${container.name}`); * } * ``` * * Example using `iter.next()`: * * ```js * let i = 1; * const iter = blobServiceClient.findBlobsByTags("tagkey='tagvalue'"); * let blobItem = await iter.next(); * while (!blobItem.done) { * console.log(`Blob ${i++}: ${blobItem.value.name}`); * blobItem = await iter.next(); * } * ``` * * Example using `byPage()`: * * ```js * // passing optional maxPageSize in the page settings * let i = 1; * for await (const response of blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 20 })) { * if (response.blobs) { * for (const blob of response.blobs) { * console.log(`Blob ${i++}: ${blob.name}`); * } * } * } * ``` * * Example using paging with a marker: * * ```js * let i = 1; * let iterator = blobServiceClient.findBlobsByTags("tagkey='tagvalue'").byPage({ maxPageSize: 2 }); * let response = (await iterator.next()).value; * * // Prints 2 blob names * if (response.blobs) { * for (const blob of response.blobs) { * console.log(`Blob ${i++}: ${blob.name}`); * } * } * * // Gets next marker * let marker = response.continuationToken; * // Passing next marker as continuationToken * iterator = blobServiceClient * .findBlobsByTags("tagkey='tagvalue'") * .byPage({ continuationToken: marker, maxPageSize: 10 }); * response = (await iterator.next()).value; * * // Prints blob names * if (response.blobs) { * for (const blob of response.blobs) { * console.log(`Blob ${i++}: ${blob.name}`); * } * } * ``` * * @param {string} tagFilterSqlExpression The where parameter enables the caller to query blobs whose tags match a given expression. * The given expression must evaluate to true for a blob to be returned in the results. * The[OData - ABNF] filter syntax rule defines the formal grammar for the value of the where query parameter; * however, only a subset of the OData filter syntax is supported in the Blob service. * @param {ServiceFindBlobByTagsOptions} [options={}] Options to find blobs by tags. * @returns {PagedAsyncIterableIterator} * @memberof BlobServiceClient */ BlobServiceClient.prototype.findBlobsByTags = function (tagFilterSqlExpression, options) { var _a; var _this = this; if (options === void 0) { options = {}; } // AsyncIterableIterator to iterate over blobs var listSegmentOptions = tslib.__assign({}, options); var iter = this.findBlobsByTagsItems(tagFilterSqlExpression, listSegmentOptions); return _a = { /** * @member {Promise} [next] The next method, part of the iteration protocol */ next: function () { return iter.next(); } }, /** * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol */ _a[Symbol.asyncIterator] = function () { return this; }, /** * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time */ _a.byPage = function (settings) { if (settings === void 0) { settings = {}; } return _this.findBlobsByTagsSegments(tagFilterSqlExpression, settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); }, _a; }; /** * Returns an AsyncIterableIterator for ServiceListContainersSegmentResponses * * @private * @param {string} [marker] A string value that identifies the portion of * the list of containers to be returned with the next listing operation. The * operation returns the continuationToken value within the response body if the * listing operation did not return all containers remaining to be listed * with the current page. The continuationToken value can be used as the value for * the marker parameter in a subsequent call to request the next page of list * items. The marker value is opaque to the client. * @param {ServiceListContainersSegmentOptions} [options] Options to list containers operation. * @returns {AsyncIterableIterator} * @memberof BlobServiceClient */ BlobServiceClient.prototype.listSegments = function (marker, options) { if (options === void 0) { options = {}; } return tslib.__asyncGenerator(this, arguments, function listSegments_1() { var listContainersSegmentResponse; return tslib.__generator(this, function (_a) { switch (_a.label) { case 0: if (!(!!marker || marker === undefined)) return [3 /*break*/, 7]; _a.label = 1; case 1: return [4 /*yield*/, tslib.__await(this.listContainersSegment(marker, options))]; case 2: listContainersSegmentResponse = _a.sent(); listContainersSegmentResponse.containerItems = listContainersSegmentResponse.containerItems || []; marker = listContainersSegmentResponse.continuationToken; return [4 /*yield*/, tslib.__await(listContainersSegmentResponse)]; case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_a.sent()])]; case 4: return [4 /*yield*/, _a.sent()]; case 5: _a.sent(); _a.label = 6; case 6: if (marker) return [3 /*break*/, 1]; _a.label = 7; case 7: return [2 /*return*/]; } }); }); }; /** * Returns an AsyncIterableIterator for Container Items * * @private * @param {ServiceListContainersSegmentOptions} [options] Options to list containers operation. * @returns {AsyncIterableIterator} * @memberof BlobServiceClient */ BlobServiceClient.prototype.listItems = function (options) { if (options === void 0) { options = {}; } return tslib.__asyncGenerator(this, arguments, function listItems_1() { var marker, _a, _b, segment, e_11_1; var e_11, _c; return tslib.__generator(this, function (_d) { switch (_d.label) { case 0: _d.trys.push([0, 7, 8, 13]); _a = tslib.__asyncValues(this.listSegments(marker, options)); _d.label = 1; case 1: return [4 /*yield*/, tslib.__await(_a.next())]; case 2: if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 6]; segment = _b.value; return [5 /*yield**/, tslib.__values(tslib.__asyncDelegator(tslib.__asyncValues(segment.containerItems)))]; case 3: return [4 /*yield*/, tslib.__await.apply(void 0, [_d.sent()])]; case 4: _d.sent(); _d.label = 5; case 5: return [3 /*break*/, 1]; case 6: return [3 /*break*/, 13]; case 7: e_11_1 = _d.sent(); e_11 = { error: e_11_1 }; return [3 /*break*/, 13]; case 8: _d.trys.push([8, , 11, 12]); if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 10]; return [4 /*yield*/, tslib.__await(_c.call(_a))]; case 9: _d.sent(); _d.label = 10; case 10: return [3 /*break*/, 12]; case 11: if (e_11) throw e_11.error; return [7 /*endfinally*/]; case 12: return [7 /*endfinally*/]; case 13: return [2 /*return*/]; } }); }); }; /** * Returns an async iterable iterator to list all the containers * under the specified account. * * .byPage() returns an async iterable iterator to list the containers in pages. * * Example using `for await` syntax: * * ```js * let i = 1; * for await (const container of blobServiceClient.listContainers()) { * console.log(`Container ${i++}: ${container.name}`); * } * ``` * * Example using `iter.next()`: * * ```js * let i = 1; * const iter = blobServiceClient.listContainers(); * let containerItem = await iter.next(); * while (!containerItem.done) { * console.log(`Container ${i++}: ${containerItem.value.name}`); * containerItem = await iter.next(); * } * ``` * * Example using `byPage()`: * * ```js * // passing optional maxPageSize in the page settings * let i = 1; * for await (const response of blobServiceClient.listContainers().byPage({ maxPageSize: 20 })) { * if (response.containerItems) { * for (const container of response.containerItems) { * console.log(`Container ${i++}: ${container.name}`); * } * } * } * ``` * * Example using paging with a marker: * * ```js * let i = 1; * let iterator = blobServiceClient.listContainers().byPage({ maxPageSize: 2 }); * let response = (await iterator.next()).value; * * // Prints 2 container names * if (response.containerItems) { * for (const container of response.containerItems) { * console.log(`Container ${i++}: ${container.name}`); * } * } * * // Gets next marker * let marker = response.continuationToken; * // Passing next marker as continuationToken * iterator = blobServiceClient * .listContainers() * .byPage({ continuationToken: marker, maxPageSize: 10 }); * response = (await iterator.next()).value; * * // Prints 10 container names * if (response.containerItems) { * for (const container of response.containerItems) { * console.log(`Container ${i++}: ${container.name}`); * } * } * ``` * * @param {ServiceListContainersOptions} [options={}] Options to list containers. * @returns {PagedAsyncIterableIterator} An asyncIterableIterator that supports paging. * @memberof BlobServiceClient */ BlobServiceClient.prototype.listContainers = function (options) { var _a; var _this = this; if (options === void 0) { options = {}; } if (options.prefix === "") { options.prefix = undefined; } var include = []; if (options.includeDeleted) { include.push("deleted"); } if (options.includeMetadata) { include.push("metadata"); } // AsyncIterableIterator to iterate over containers var listSegmentOptions = tslib.__assign(tslib.__assign({}, options), (include.length > 0 ? { include: include } : {})); var iter = this.listItems(listSegmentOptions); return _a = { /** * @member {Promise} [next] The next method, part of the iteration protocol */ next: function () { return iter.next(); } }, /** * @member {Symbol} [asyncIterator] The connection to the async iterator, part of the iteration protocol */ _a[Symbol.asyncIterator] = function () { return this; }, /** * @member {Function} [byPage] Return an AsyncIterableIterator that works a page at a time */ _a.byPage = function (settings) { if (settings === void 0) { settings = {}; } return _this.listSegments(settings.continuationToken, tslib.__assign({ maxPageSize: settings.maxPageSize }, listSegmentOptions)); }, _a; }; /** * ONLY AVAILABLE WHEN USING BEARER TOKEN AUTHENTICATION (TokenCredential). * * Retrieves a user delegation key for the Blob service. This is only a valid operation when using * bearer token authentication. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/get-user-delegation-key * * @param {Date} startsOn The start time for the user delegation SAS. Must be within 7 days of the current time * @param {Date} expiresOn The end time for the user delegation SAS. Must be within 7 days of the current time * @returns {Promise} * @memberof BlobServiceClient */ BlobServiceClient.prototype.getUserDelegationKey = function (startsOn, expiresOn, options) { if (options === void 0) { options = {}; } return tslib.__awaiter(this, void 0, void 0, function () { var _a, span, spanOptions, response, userDelegationKey, res, e_12; return tslib.__generator(this, function (_b) { switch (_b.label) { case 0: _a = createSpan("BlobServiceClient-getUserDelegationKey", options.tracingOptions), span = _a.span, spanOptions = _a.spanOptions; _b.label = 1; case 1: _b.trys.push([1, 3, 4, 5]); return [4 /*yield*/, this.serviceContext.getUserDelegationKey({ startsOn: truncatedISO8061Date(startsOn, false), expiresOn: truncatedISO8061Date(expiresOn, false) }, { abortSignal: options.abortSignal, spanOptions: spanOptions })]; case 2: response = _b.sent(); userDelegationKey = { signedObjectId: response.signedObjectId, signedTenantId: response.signedTenantId, signedStartsOn: new Date(response.signedStartsOn), signedExpiresOn: new Date(response.signedExpiresOn), signedService: response.signedService, signedVersion: response.signedVersion, value: response.value }; res = tslib.__assign({ _response: response._response, requestId: response.requestId, clientRequestId: response.clientRequestId, version: response.version, date: response.date, errorCode: response.errorCode }, userDelegationKey); return [2 /*return*/, res]; case 3: e_12 = _b.sent(); span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e_12.message }); throw e_12; case 4: span.end(); return [7 /*endfinally*/]; case 5: return [2 /*return*/]; } }); }); }; /** * Creates a BlobBatchClient object to conduct batch operations. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/blob-batch * * @returns {BlobBatchClient} A new BlobBatchClient object for this service. * @memberof BlobServiceClient */ BlobServiceClient.prototype.getBlobBatchClient = function () { return new BlobBatchClient(this.url, this.pipeline); }; return BlobServiceClient; }(StorageClient)); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * This is a helper class to construct a string representing the permissions granted by an AccountSAS. Setting a value * to true means that any SAS which uses these permissions will grant permissions for that operation. Once all the * values are set, this should be serialized with toString and set as the permissions field on an * {@link AccountSASSignatureValues} object. It is possible to construct the permissions string without this class, but * the order of the permissions is particular and this class guarantees correctness. * * @export * @class AccountSASPermissions */ var AccountSASPermissions = /** @class */ (function () { function AccountSASPermissions() { /** * Permission to read resources and list queues and tables granted. * * @type {boolean} * @memberof AccountSASPermissions */ this.read = false; /** * Permission to write resources granted. * * @type {boolean} * @memberof AccountSASPermissions */ this.write = false; /** * Permission to create blobs and files granted. * * @type {boolean} * @memberof AccountSASPermissions */ this.delete = false; /** * Permission to delete versions granted. * * @type {boolean} * @memberof AccountSASPermissions */ this.deleteVersion = false; /** * Permission to list blob containers, blobs, shares, directories, and files granted. * * @type {boolean} * @memberof AccountSASPermissions */ this.list = false; /** * Permission to add messages, table entities, and append to blobs granted. * * @type {boolean} * @memberof AccountSASPermissions */ this.add = false; /** * Permission to create blobs and files granted. * * @type {boolean} * @memberof AccountSASPermissions */ this.create = false; /** * Permissions to update messages and table entities granted. * * @type {boolean} * @memberof AccountSASPermissions */ this.update = false; /** * Permission to get and delete messages granted. * * @type {boolean} * @memberof AccountSASPermissions */ this.process = false; /** * Specfies Tag access granted. * * @type {boolean} * @memberof AccountSASPermissions */ this.tag = false; /** * Permission to filter blobs. * * @type {boolean} * @memberof AccountSASPermissions */ this.filter = false; } /** * Parse initializes the AccountSASPermissions fields from a string. * * @static * @param {string} permissions * @returns {AccountSASPermissions} * @memberof AccountSASPermissions */ AccountSASPermissions.parse = function (permissions) { var accountSASPermissions = new AccountSASPermissions(); for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { var c = permissions_1[_i]; switch (c) { case "r": accountSASPermissions.read = true; break; case "w": accountSASPermissions.write = true; break; case "d": accountSASPermissions.delete = true; break; case "x": accountSASPermissions.deleteVersion = true; break; case "l": accountSASPermissions.list = true; break; case "a": accountSASPermissions.add = true; break; case "c": accountSASPermissions.create = true; break; case "u": accountSASPermissions.update = true; break; case "p": accountSASPermissions.process = true; break; case "t": accountSASPermissions.tag = true; break; case "f": accountSASPermissions.filter = true; break; default: throw new RangeError("Invalid permission character: " + c); } } return accountSASPermissions; }; /** * Produces the SAS permissions string for an Azure Storage account. * Call this method to set AccountSASSignatureValues Permissions field. * * Using this method will guarantee the resource types are in * an order accepted by the service. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas * * @returns {string} * @memberof AccountSASPermissions */ AccountSASPermissions.prototype.toString = function () { // The order of the characters should be as specified here to ensure correctness: // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas // Use a string array instead of string concatenating += operator for performance var permissions = []; if (this.read) { permissions.push("r"); } if (this.write) { permissions.push("w"); } if (this.delete) { permissions.push("d"); } if (this.deleteVersion) { permissions.push("x"); } if (this.filter) { permissions.push("f"); } if (this.tag) { permissions.push("t"); } if (this.list) { permissions.push("l"); } if (this.add) { permissions.push("a"); } if (this.create) { permissions.push("c"); } if (this.update) { permissions.push("u"); } if (this.process) { permissions.push("p"); } return permissions.join(""); }; return AccountSASPermissions; }()); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * This is a helper class to construct a string representing the resources accessible by an AccountSAS. Setting a value * to true means that any SAS which uses these permissions will grant access to that resource type. Once all the * values are set, this should be serialized with toString and set as the resources field on an * {@link AccountSASSignatureValues} object. It is possible to construct the resources string without this class, but * the order of the resources is particular and this class guarantees correctness. * * @export * @class AccountSASResourceTypes */ var AccountSASResourceTypes = /** @class */ (function () { function AccountSASResourceTypes() { /** * Permission to access service level APIs granted. * * @type {boolean} * @memberof AccountSASResourceTypes */ this.service = false; /** * Permission to access container level APIs (Blob Containers, Tables, Queues, File Shares) granted. * * @type {boolean} * @memberof AccountSASResourceTypes */ this.container = false; /** * Permission to access object level APIs (Blobs, Table Entities, Queue Messages, Files) granted. * * @type {boolean} * @memberof AccountSASResourceTypes */ this.object = false; } /** * Creates an {@link AccountSASResourceTypes} from the specified resource types string. This method will throw an * Error if it encounters a character that does not correspond to a valid resource type. * * @static * @param {string} resourceTypes * @returns {AccountSASResourceTypes} * @memberof AccountSASResourceTypes */ AccountSASResourceTypes.parse = function (resourceTypes) { var accountSASResourceTypes = new AccountSASResourceTypes(); for (var _i = 0, resourceTypes_1 = resourceTypes; _i < resourceTypes_1.length; _i++) { var c = resourceTypes_1[_i]; switch (c) { case "s": accountSASResourceTypes.service = true; break; case "c": accountSASResourceTypes.container = true; break; case "o": accountSASResourceTypes.object = true; break; default: throw new RangeError("Invalid resource type: " + c); } } return accountSASResourceTypes; }; /** * Converts the given resource types to a string. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas * * @returns {string} * @memberof AccountSASResourceTypes */ AccountSASResourceTypes.prototype.toString = function () { var resourceTypes = []; if (this.service) { resourceTypes.push("s"); } if (this.container) { resourceTypes.push("c"); } if (this.object) { resourceTypes.push("o"); } return resourceTypes.join(""); }; return AccountSASResourceTypes; }()); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * This is a helper class to construct a string representing the services accessible by an AccountSAS. Setting a value * to true means that any SAS which uses these permissions will grant access to that service. Once all the * values are set, this should be serialized with toString and set as the services field on an * {@link AccountSASSignatureValues} object. It is possible to construct the services string without this class, but * the order of the services is particular and this class guarantees correctness. * * @export * @class AccountSASServices */ var AccountSASServices = /** @class */ (function () { function AccountSASServices() { /** * Permission to access blob resources granted. * * @type {boolean} * @memberof AccountSASServices */ this.blob = false; /** * Permission to access file resources granted. * * @type {boolean} * @memberof AccountSASServices */ this.file = false; /** * Permission to access queue resources granted. * * @type {boolean} * @memberof AccountSASServices */ this.queue = false; /** * Permission to access table resources granted. * * @type {boolean} * @memberof AccountSASServices */ this.table = false; } /** * Creates an {@link AccountSASServices} from the specified services string. This method will throw an * Error if it encounters a character that does not correspond to a valid service. * * @static * @param {string} services * @returns {AccountSASServices} * @memberof AccountSASServices */ AccountSASServices.parse = function (services) { var accountSASServices = new AccountSASServices(); for (var _i = 0, services_1 = services; _i < services_1.length; _i++) { var c = services_1[_i]; switch (c) { case "b": accountSASServices.blob = true; break; case "f": accountSASServices.file = true; break; case "q": accountSASServices.queue = true; break; case "t": accountSASServices.table = true; break; default: throw new RangeError("Invalid service character: " + c); } } return accountSASServices; }; /** * Converts the given services to a string. * * @returns {string} * @memberof AccountSASServices */ AccountSASServices.prototype.toString = function () { var services = []; if (this.blob) { services.push("b"); } if (this.table) { services.push("t"); } if (this.queue) { services.push("q"); } if (this.file) { services.push("f"); } return services.join(""); }; return AccountSASServices; }()); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /** * Generate SasIPRange format string. For example: * * "8.8.8.8" or "1.1.1.1-255.255.255.255" * * @export * @param {SasIPRange} ipRange * @returns {string} */ function ipRangeToString(ipRange) { return ipRange.end ? ipRange.start + "-" + ipRange.end : ipRange.start; } // Copyright (c) Microsoft Corporation. All rights reserved. (function (SASProtocol) { /** * Protocol that allows HTTPS only */ SASProtocol["Https"] = "https"; /** * Protocol that allows both HTTPS and HTTP */ SASProtocol["HttpsAndHttp"] = "https,http"; })(exports.SASProtocol || (exports.SASProtocol = {})); /** * Represents the components that make up an Azure Storage SAS' query parameters. This type is not constructed directly * by the user; it is only generated by the {@link AccountSASSignatureValues} and {@link BlobSASSignatureValues} * types. Once generated, it can be encoded into a {@code String} and appended to a URL directly (though caution should * be taken here in case there are existing query parameters, which might affect the appropriate means of appending * these query parameters). * * NOTE: Instances of this class are immutable. * * @export * @class SASQueryParameters */ var SASQueryParameters = /** @class */ (function () { function SASQueryParameters(version, signature, permissionsOrOptions, services, resourceTypes, protocol, startsOn, expiresOn, ipRange, identifier, resource, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType, userDelegationKey, preauthorizedAgentObjectId, correlationId) { this.version = version; this.signature = signature; if (permissionsOrOptions !== undefined && typeof permissionsOrOptions !== "string") { // SASQueryParametersOptions this.permissions = permissionsOrOptions.permissions; this.services = permissionsOrOptions.services; this.resourceTypes = permissionsOrOptions.resourceTypes; this.protocol = permissionsOrOptions.protocol; this.startsOn = permissionsOrOptions.startsOn; this.expiresOn = permissionsOrOptions.expiresOn; this.ipRangeInner = permissionsOrOptions.ipRange; this.identifier = permissionsOrOptions.identifier; this.resource = permissionsOrOptions.resource; this.cacheControl = permissionsOrOptions.cacheControl; this.contentDisposition = permissionsOrOptions.contentDisposition; this.contentEncoding = permissionsOrOptions.contentEncoding; this.contentLanguage = permissionsOrOptions.contentLanguage; this.contentType = permissionsOrOptions.contentType; if (permissionsOrOptions.userDelegationKey) { this.signedOid = permissionsOrOptions.userDelegationKey.signedObjectId; this.signedTenantId = permissionsOrOptions.userDelegationKey.signedTenantId; this.signedStartsOn = permissionsOrOptions.userDelegationKey.signedStartsOn; this.signedExpiresOn = permissionsOrOptions.userDelegationKey.signedExpiresOn; this.signedService = permissionsOrOptions.userDelegationKey.signedService; this.signedVersion = permissionsOrOptions.userDelegationKey.signedVersion; this.preauthorizedAgentObjectId = permissionsOrOptions.preauthorizedAgentObjectId; this.correlationId = permissionsOrOptions.correlationId; } } else { this.services = services; this.resourceTypes = resourceTypes; this.expiresOn = expiresOn; this.permissions = permissionsOrOptions; this.protocol = protocol; this.startsOn = startsOn; this.ipRangeInner = ipRange; this.identifier = identifier; this.resource = resource; this.cacheControl = cacheControl; this.contentDisposition = contentDisposition; this.contentEncoding = contentEncoding; this.contentLanguage = contentLanguage; this.contentType = contentType; if (userDelegationKey) { this.signedOid = userDelegationKey.signedObjectId; this.signedTenantId = userDelegationKey.signedTenantId; this.signedStartsOn = userDelegationKey.signedStartsOn; this.signedExpiresOn = userDelegationKey.signedExpiresOn; this.signedService = userDelegationKey.signedService; this.signedVersion = userDelegationKey.signedVersion; this.preauthorizedAgentObjectId = preauthorizedAgentObjectId; this.correlationId = correlationId; } } } Object.defineProperty(SASQueryParameters.prototype, "ipRange", { /** * Optional. IP range allowed for this SAS. * * @readonly * @type {(SasIPRange | undefined)} * @memberof SASQueryParameters */ get: function () { if (this.ipRangeInner) { return { end: this.ipRangeInner.end, start: this.ipRangeInner.start }; } return undefined; }, enumerable: false, configurable: true }); /** * Encodes all SAS query parameters into a string that can be appended to a URL. * * @returns {string} * @memberof SASQueryParameters */ SASQueryParameters.prototype.toString = function () { var params = [ "sv", "ss", "srt", "spr", "st", "se", "sip", "si", "skoid", "sktid", "skt", "ske", "sks", "skv", "sr", "sp", "sig", "rscc", "rscd", "rsce", "rscl", "rsct", "saoid", "scid" ]; var queries = []; for (var _i = 0, params_1 = params; _i < params_1.length; _i++) { var param = params_1[_i]; switch (param) { case "sv": this.tryAppendQueryParameter(queries, param, this.version); break; case "ss": this.tryAppendQueryParameter(queries, param, this.services); break; case "srt": this.tryAppendQueryParameter(queries, param, this.resourceTypes); break; case "spr": this.tryAppendQueryParameter(queries, param, this.protocol); break; case "st": this.tryAppendQueryParameter(queries, param, this.startsOn ? truncatedISO8061Date(this.startsOn, false) : undefined); break; case "se": this.tryAppendQueryParameter(queries, param, this.expiresOn ? truncatedISO8061Date(this.expiresOn, false) : undefined); break; case "sip": this.tryAppendQueryParameter(queries, param, this.ipRange ? ipRangeToString(this.ipRange) : undefined); break; case "si": this.tryAppendQueryParameter(queries, param, this.identifier); break; case "skoid": // Signed object ID this.tryAppendQueryParameter(queries, param, this.signedOid); break; case "sktid": // Signed tenant ID this.tryAppendQueryParameter(queries, param, this.signedTenantId); break; case "skt": // Signed key start time this.tryAppendQueryParameter(queries, param, this.signedStartsOn ? truncatedISO8061Date(this.signedStartsOn, false) : undefined); break; case "ske": // Signed key expiry time this.tryAppendQueryParameter(queries, param, this.signedExpiresOn ? truncatedISO8061Date(this.signedExpiresOn, false) : undefined); break; case "sks": // Signed key service this.tryAppendQueryParameter(queries, param, this.signedService); break; case "skv": // Signed key version this.tryAppendQueryParameter(queries, param, this.signedVersion); break; case "sr": this.tryAppendQueryParameter(queries, param, this.resource); break; case "sp": this.tryAppendQueryParameter(queries, param, this.permissions); break; case "sig": this.tryAppendQueryParameter(queries, param, this.signature); break; case "rscc": this.tryAppendQueryParameter(queries, param, this.cacheControl); break; case "rscd": this.tryAppendQueryParameter(queries, param, this.contentDisposition); break; case "rsce": this.tryAppendQueryParameter(queries, param, this.contentEncoding); break; case "rscl": this.tryAppendQueryParameter(queries, param, this.contentLanguage); break; case "rsct": this.tryAppendQueryParameter(queries, param, this.contentType); break; case "saoid": this.tryAppendQueryParameter(queries, param, this.preauthorizedAgentObjectId); break; case "scid": this.tryAppendQueryParameter(queries, param, this.correlationId); break; } } return queries.join("&"); }; /** * A private helper method used to filter and append query key/value pairs into an array. * * @private * @param {string[]} queries * @param {string} key * @param {string} [value] * @returns {void} * @memberof SASQueryParameters */ SASQueryParameters.prototype.tryAppendQueryParameter = function (queries, key, value) { if (!value) { return; } key = encodeURIComponent(key); value = encodeURIComponent(value); if (key.length > 0 && value.length > 0) { queries.push(key + "=" + value); } }; return SASQueryParameters; }()); // Copyright (c) Microsoft Corporation. All rights reserved. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * Generates a {@link SASQueryParameters} object which contains all SAS query parameters needed to make an actual * REST request. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas * * @param {AccountSASSignatureValues} accountSASSignatureValues * @param {StorageSharedKeyCredential} sharedKeyCredential * @returns {SASQueryParameters} * @memberof AccountSASSignatureValues */ function generateAccountSASQueryParameters(accountSASSignatureValues, sharedKeyCredential) { var version = accountSASSignatureValues.version ? accountSASSignatureValues.version : SERVICE_VERSION; if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.deleteVersion && version < "2019-10-10") { throw RangeError("'version' must be >= '2019-10-10' when provided 'x' permission."); } if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.tag && version < "2019-12-12") { throw RangeError("'version' must be >= '2019-12-12' when provided 't' permission."); } if (accountSASSignatureValues.permissions && accountSASSignatureValues.permissions.filter && version < "2019-12-12") { throw RangeError("'version' must be >= '2019-12-12' when provided 'f' permission."); } var parsedPermissions = AccountSASPermissions.parse(accountSASSignatureValues.permissions.toString()); var parsedServices = AccountSASServices.parse(accountSASSignatureValues.services).toString(); var parsedResourceTypes = AccountSASResourceTypes.parse(accountSASSignatureValues.resourceTypes).toString(); var stringToSign = [ sharedKeyCredential.accountName, parsedPermissions, parsedServices, parsedResourceTypes, accountSASSignatureValues.startsOn ? truncatedISO8061Date(accountSASSignatureValues.startsOn, false) : "", truncatedISO8061Date(accountSASSignatureValues.expiresOn, false), accountSASSignatureValues.ipRange ? ipRangeToString(accountSASSignatureValues.ipRange) : "", accountSASSignatureValues.protocol ? accountSASSignatureValues.protocol : "", version, "" // Account SAS requires an additional newline character ].join("\n"); var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); return new SASQueryParameters(version, signature, parsedPermissions.toString(), parsedServices, parsedResourceTypes, accountSASSignatureValues.protocol, accountSASSignatureValues.startsOn, accountSASSignatureValues.expiresOn, accountSASSignatureValues.ipRange); } // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a blob. Setting * a value to true means that any SAS which uses these permissions will grant permissions for that operation. Once all * the values are set, this should be serialized with toString and set as the permissions field on a * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but * the order of the permissions is particular and this class guarantees correctness. * * @export * @class BlobSASPermissions */ var BlobSASPermissions = /** @class */ (function () { function BlobSASPermissions() { /** * Specifies Read access granted. * * @type {boolean} * @memberof BlobSASPermissions */ this.read = false; /** * Specifies Add access granted. * * @type {boolean} * @memberof BlobSASPermissions */ this.add = false; /** * Specifies Create access granted. * * @type {boolean} * @memberof BlobSASPermissions */ this.create = false; /** * Specifies Write access granted. * * @type {boolean} * @memberof BlobSASPermissions */ this.write = false; /** * Specifies Delete access granted. * * @type {boolean} * @memberof BlobSASPermissions */ this.delete = false; /** * Specifies Delete version access granted. * * @type {boolean} * @memberof BlobSASPermissions */ this.deleteVersion = false; /** * Specfies Tag access granted. * * @type {boolean} * @memberof BlobSASPermissions */ this.tag = false; /** * Specifies Move access granted. * * @type {boolean} * @memberof BlobSASPermissions */ this.move = false; /** * Specifies Execute access granted. * * @type {boolean} * @memberof BlobSASPermissions */ this.execute = false; } /** * Creates a {@link BlobSASPermissions} from the specified permissions string. This method will throw an * Error if it encounters a character that does not correspond to a valid permission. * * @static * @param {string} permissions * @returns {BlobSASPermissions} * @memberof BlobSASPermissions */ BlobSASPermissions.parse = function (permissions) { var blobSASPermissions = new BlobSASPermissions(); for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { var char = permissions_1[_i]; switch (char) { case "r": blobSASPermissions.read = true; break; case "a": blobSASPermissions.add = true; break; case "c": blobSASPermissions.create = true; break; case "w": blobSASPermissions.write = true; break; case "d": blobSASPermissions.delete = true; break; case "x": blobSASPermissions.deleteVersion = true; break; case "t": blobSASPermissions.tag = true; break; case "m": blobSASPermissions.move = true; break; case "e": blobSASPermissions.execute = true; break; default: throw new RangeError("Invalid permission: " + char); } } return blobSASPermissions; }; /** * Converts the given permissions to a string. Using this method will guarantee the permissions are in an * order accepted by the service. * * @returns {string} A string which represents the BlobSASPermissions * @memberof BlobSASPermissions */ BlobSASPermissions.prototype.toString = function () { var permissions = []; if (this.read) { permissions.push("r"); } if (this.add) { permissions.push("a"); } if (this.create) { permissions.push("c"); } if (this.write) { permissions.push("w"); } if (this.delete) { permissions.push("d"); } if (this.deleteVersion) { permissions.push("x"); } if (this.tag) { permissions.push("t"); } if (this.move) { permissions.push("m"); } if (this.execute) { permissions.push("e"); } return permissions.join(""); }; return BlobSASPermissions; }()); // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /** * This is a helper class to construct a string representing the permissions granted by a ServiceSAS to a container. * Setting a value to true means that any SAS which uses these permissions will grant permissions for that operation. * Once all the values are set, this should be serialized with toString and set as the permissions field on a * {@link BlobSASSignatureValues} object. It is possible to construct the permissions string without this class, but * the order of the permissions is particular and this class guarantees correctness. * * @export * @class ContainerSASPermissions */ var ContainerSASPermissions = /** @class */ (function () { function ContainerSASPermissions() { /** * Specifies Read access granted. * * @type {boolean} * @memberof ContainerSASPermissions */ this.read = false; /** * Specifies Add access granted. * * @type {boolean} * @memberof ContainerSASPermissions */ this.add = false; /** * Specifies Create access granted. * * @type {boolean} * @memberof ContainerSASPermissions */ this.create = false; /** * Specifies Write access granted. * * @type {boolean} * @memberof ContainerSASPermissions */ this.write = false; /** * Specifies Delete access granted. * * @type {boolean} * @memberof ContainerSASPermissions */ this.delete = false; /** * Specifies Delete version access granted. * * @type {boolean} * @memberof ContainerSASPermissions */ this.deleteVersion = false; /** * Specifies List access granted. * * @type {boolean} * @memberof ContainerSASPermissions */ this.list = false; /** * Specfies Tag access granted. * * @type {boolean} * @memberof ContainerSASPermissions */ this.tag = false; /** * Specifies Move access granted. * * @type {boolean} * @memberof ContainerSASPermissions */ this.move = false; /** * Specifies Execute access granted. * * @type {boolean} * @memberof ContainerSASPermissions */ this.execute = false; } /** * Creates an {@link ContainerSASPermissions} from the specified permissions string. This method will throw an * Error if it encounters a character that does not correspond to a valid permission. * * @static * @param {string} permissions * @returns {ContainerSASPermissions} * @memberof ContainerSASPermissions */ ContainerSASPermissions.parse = function (permissions) { var containerSASPermissions = new ContainerSASPermissions(); for (var _i = 0, permissions_1 = permissions; _i < permissions_1.length; _i++) { var char = permissions_1[_i]; switch (char) { case "r": containerSASPermissions.read = true; break; case "a": containerSASPermissions.add = true; break; case "c": containerSASPermissions.create = true; break; case "w": containerSASPermissions.write = true; break; case "d": containerSASPermissions.delete = true; break; case "l": containerSASPermissions.list = true; break; case "t": containerSASPermissions.tag = true; break; case "x": containerSASPermissions.deleteVersion = true; break; case "m": containerSASPermissions.move = true; break; case "e": containerSASPermissions.execute = true; break; default: throw new RangeError("Invalid permission " + char); } } return containerSASPermissions; }; /** * Converts the given permissions to a string. Using this method will guarantee the permissions are in an * order accepted by the service. * * The order of the characters should be as specified here to ensure correctness. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas * * @returns {string} * @memberof ContainerSASPermissions */ ContainerSASPermissions.prototype.toString = function () { var permissions = []; if (this.read) { permissions.push("r"); } if (this.add) { permissions.push("a"); } if (this.create) { permissions.push("c"); } if (this.write) { permissions.push("w"); } if (this.delete) { permissions.push("d"); } if (this.deleteVersion) { permissions.push("x"); } if (this.list) { permissions.push("l"); } if (this.tag) { permissions.push("t"); } if (this.move) { permissions.push("m"); } if (this.execute) { permissions.push("e"); } return permissions.join(""); }; return ContainerSASPermissions; }()); /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * UserDelegationKeyCredential is only used for generation of user delegation SAS. * @see https://docs.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas * * @export * @class UserDelegationKeyCredential */ var UserDelegationKeyCredential = /** @class */ (function () { /** * Creates an instance of UserDelegationKeyCredential. * @param {string} accountName * @param {UserDelegationKey} userDelegationKey * @memberof UserDelegationKeyCredential */ function UserDelegationKeyCredential(accountName, userDelegationKey) { this.accountName = accountName; this.userDelegationKey = userDelegationKey; this.key = Buffer.from(userDelegationKey.value, "base64"); } /** * Generates a hash signature for an HTTP request or for a SAS. * * @param {string} stringToSign * @returns {string} * @memberof UserDelegationKeyCredential */ UserDelegationKeyCredential.prototype.computeHMACSHA256 = function (stringToSign) { // console.log(`stringToSign: ${JSON.stringify(stringToSign)}`); return crypto.createHmac("sha256", this.key) .update(stringToSign, "utf8") .digest("base64"); }; return UserDelegationKeyCredential; }()); // Copyright (c) Microsoft Corporation. All rights reserved. function generateBlobSASQueryParameters(blobSASSignatureValues, sharedKeyCredentialOrUserDelegationKey, accountName) { var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; var sharedKeyCredential = sharedKeyCredentialOrUserDelegationKey instanceof StorageSharedKeyCredential ? sharedKeyCredentialOrUserDelegationKey : undefined; var userDelegationKeyCredential; if (sharedKeyCredential === undefined && accountName !== undefined) { userDelegationKeyCredential = new UserDelegationKeyCredential(accountName, sharedKeyCredentialOrUserDelegationKey); } if (sharedKeyCredential === undefined && userDelegationKeyCredential === undefined) { throw TypeError("Invalid sharedKeyCredential, userDelegationKey or accountName."); } // Version 2019-12-12 adds support for the blob tags permission. // Version 2018-11-09 adds support for the signed resource and signed blob snapshot time fields. // https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-a-service-sas#constructing-the-signature-string if (version >= "2018-11-09") { if (sharedKeyCredential !== undefined) { return generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential); } else { // Version 2020-02-10 delegation SAS signature construction includes preauthorizedAgentObjectId, agentObjectId, correlationId. if (version >= "2020-02-10") { return generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userDelegationKeyCredential); } else { return generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential); } } } if (version >= "2015-04-05") { if (sharedKeyCredential !== undefined) { return generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential); } else { throw new RangeError("'version' must be >= '2018-11-09' when generating user delegation SAS using user delegation key."); } } throw new RangeError("'version' must be >= '2015-04-05'."); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * IMPLEMENTATION FOR API VERSION FROM 2015-04-05 AND BEFORE 2018-11-09. * * Creates an instance of SASQueryParameters. * * Only accepts required settings needed to create a SAS. For optional settings please * set corresponding properties directly, such as permissions, startsOn and identifier. * * WARNING: When identifier is not provided, permissions and expiresOn are required. * You MUST assign value to identifier or expiresOn & permissions manually if you initial with * this constructor. * * @param {BlobSASSignatureValues} blobSASSignatureValues * @param {StorageSharedKeyCredential} sharedKeyCredential * @returns {SASQueryParameters} */ function generateBlobSASQueryParameters20150405(blobSASSignatureValues, sharedKeyCredential) { blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); if (!blobSASSignatureValues.identifier && !blobSASSignatureValues.permissions && !blobSASSignatureValues.expiresOn) { throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); } var resource = "c"; if (blobSASSignatureValues.blobName) { resource = "b"; } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. var verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); } else { verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); } } // Signature is generated on the un-url-encoded values. var stringToSign = [ verifiedPermissions ? verifiedPermissions : "", blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) : "", blobSASSignatureValues.expiresOn ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) : "", getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), blobSASSignatureValues.identifier, blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", blobSASSignatureValues.version, blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" ].join("\n"); var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. * * Creates an instance of SASQueryParameters. * * Only accepts required settings needed to create a SAS. For optional settings please * set corresponding properties directly, such as permissions, startsOn and identifier. * * WARNING: When identifier is not provided, permissions and expiresOn are required. * You MUST assign value to identifier or expiresOn & permissions manually if you initial with * this constructor. * * @param {BlobSASSignatureValues} blobSASSignatureValues * @param {StorageSharedKeyCredential} sharedKeyCredential * @returns {SASQueryParameters} */ function generateBlobSASQueryParameters20181109(blobSASSignatureValues, sharedKeyCredential) { blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); if (!blobSASSignatureValues.identifier && !blobSASSignatureValues.permissions && !blobSASSignatureValues.expiresOn) { throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when 'identifier' is not provided."); } var resource = "c"; var timestamp = blobSASSignatureValues.snapshotTime; if (blobSASSignatureValues.blobName) { resource = "b"; if (blobSASSignatureValues.snapshotTime) { resource = "bs"; } else if (blobSASSignatureValues.versionId) { resource = "bv"; timestamp = blobSASSignatureValues.versionId; } } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. var verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); } else { verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); } } // Signature is generated on the un-url-encoded values. var stringToSign = [ verifiedPermissions ? verifiedPermissions : "", blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) : "", blobSASSignatureValues.expiresOn ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) : "", getCanonicalName(sharedKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), blobSASSignatureValues.identifier, blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", blobSASSignatureValues.version, resource, timestamp, blobSASSignatureValues.cacheControl ? blobSASSignatureValues.cacheControl : "", blobSASSignatureValues.contentDisposition ? blobSASSignatureValues.contentDisposition : "", blobSASSignatureValues.contentEncoding ? blobSASSignatureValues.contentEncoding : "", blobSASSignatureValues.contentLanguage ? blobSASSignatureValues.contentLanguage : "", blobSASSignatureValues.contentType ? blobSASSignatureValues.contentType : "" ].join("\n"); var signature = sharedKeyCredential.computeHMACSHA256(stringToSign); return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * IMPLEMENTATION FOR API VERSION FROM 2018-11-09. * * Creates an instance of SASQueryParameters. * * Only accepts required settings needed to create a SAS. For optional settings please * set corresponding properties directly, such as permissions, startsOn. * * WARNING: identifier will be ignored, permissions and expiresOn are required. * * @param {BlobSASSignatureValues} blobSASSignatureValues * @param {UserDelegationKeyCredential} userDelegationKeyCredential * @returns {SASQueryParameters} */ function generateBlobSASQueryParametersUDK20181109(blobSASSignatureValues, userDelegationKeyCredential) { blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); // Stored access policies are not supported for a user delegation SAS. if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); } var resource = "c"; var timestamp = blobSASSignatureValues.snapshotTime; if (blobSASSignatureValues.blobName) { resource = "b"; if (blobSASSignatureValues.snapshotTime) { resource = "bs"; } else if (blobSASSignatureValues.versionId) { resource = "bv"; timestamp = blobSASSignatureValues.versionId; } } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. var verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); } else { verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); } } // Signature is generated on the un-url-encoded values. var stringToSign = [ verifiedPermissions ? verifiedPermissions : "", blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) : "", blobSASSignatureValues.expiresOn ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) : "", getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), userDelegationKeyCredential.userDelegationKey.signedObjectId, userDelegationKeyCredential.userDelegationKey.signedTenantId, userDelegationKeyCredential.userDelegationKey.signedStartsOn ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) : "", userDelegationKeyCredential.userDelegationKey.signedExpiresOn ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) : "", userDelegationKeyCredential.userDelegationKey.signedService, userDelegationKeyCredential.userDelegationKey.signedVersion, blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", blobSASSignatureValues.version, resource, timestamp, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType ].join("\n"); var signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey); } /** * ONLY AVAILABLE IN NODE.JS RUNTIME. * IMPLEMENTATION FOR API VERSION FROM 2020-02-10. * * Creates an instance of SASQueryParameters. * * Only accepts required settings needed to create a SAS. For optional settings please * set corresponding properties directly, such as permissions, startsOn. * * WARNING: identifier will be ignored, permissions and expiresOn are required. * * @param {BlobSASSignatureValues} blobSASSignatureValues * @param {UserDelegationKeyCredential} userDelegationKeyCredential * @returns {SASQueryParameters} */ function generateBlobSASQueryParametersUDK20200210(blobSASSignatureValues, userDelegationKeyCredential) { blobSASSignatureValues = SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues); // Stored access policies are not supported for a user delegation SAS. if (!blobSASSignatureValues.permissions || !blobSASSignatureValues.expiresOn) { throw new RangeError("Must provide 'permissions' and 'expiresOn' for Blob SAS generation when generating user delegation SAS."); } var resource = "c"; var timestamp = blobSASSignatureValues.snapshotTime; if (blobSASSignatureValues.blobName) { resource = "b"; if (blobSASSignatureValues.snapshotTime) { resource = "bs"; } else if (blobSASSignatureValues.versionId) { resource = "bv"; timestamp = blobSASSignatureValues.versionId; } } // Calling parse and toString guarantees the proper ordering and throws on invalid characters. var verifiedPermissions; if (blobSASSignatureValues.permissions) { if (blobSASSignatureValues.blobName) { verifiedPermissions = BlobSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); } else { verifiedPermissions = ContainerSASPermissions.parse(blobSASSignatureValues.permissions.toString()).toString(); } } // Signature is generated on the un-url-encoded values. var stringToSign = [ verifiedPermissions ? verifiedPermissions : "", blobSASSignatureValues.startsOn ? truncatedISO8061Date(blobSASSignatureValues.startsOn, false) : "", blobSASSignatureValues.expiresOn ? truncatedISO8061Date(blobSASSignatureValues.expiresOn, false) : "", getCanonicalName(userDelegationKeyCredential.accountName, blobSASSignatureValues.containerName, blobSASSignatureValues.blobName), userDelegationKeyCredential.userDelegationKey.signedObjectId, userDelegationKeyCredential.userDelegationKey.signedTenantId, userDelegationKeyCredential.userDelegationKey.signedStartsOn ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedStartsOn, false) : "", userDelegationKeyCredential.userDelegationKey.signedExpiresOn ? truncatedISO8061Date(userDelegationKeyCredential.userDelegationKey.signedExpiresOn, false) : "", userDelegationKeyCredential.userDelegationKey.signedService, userDelegationKeyCredential.userDelegationKey.signedVersion, blobSASSignatureValues.preauthorizedAgentObjectId, undefined, blobSASSignatureValues.correlationId, blobSASSignatureValues.ipRange ? ipRangeToString(blobSASSignatureValues.ipRange) : "", blobSASSignatureValues.protocol ? blobSASSignatureValues.protocol : "", blobSASSignatureValues.version, resource, timestamp, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType ].join("\n"); var signature = userDelegationKeyCredential.computeHMACSHA256(stringToSign); return new SASQueryParameters(blobSASSignatureValues.version, signature, verifiedPermissions, undefined, undefined, blobSASSignatureValues.protocol, blobSASSignatureValues.startsOn, blobSASSignatureValues.expiresOn, blobSASSignatureValues.ipRange, blobSASSignatureValues.identifier, resource, blobSASSignatureValues.cacheControl, blobSASSignatureValues.contentDisposition, blobSASSignatureValues.contentEncoding, blobSASSignatureValues.contentLanguage, blobSASSignatureValues.contentType, userDelegationKeyCredential.userDelegationKey, blobSASSignatureValues.preauthorizedAgentObjectId, blobSASSignatureValues.correlationId); } function getCanonicalName(accountName, containerName, blobName) { // Container: "/blob/account/containerName" // Blob: "/blob/account/containerName/blobName" var elements = ["/blob/" + accountName + "/" + containerName]; if (blobName) { elements.push("/" + blobName); } return elements.join(""); } function SASSignatureValuesSanityCheckAndAutofill(blobSASSignatureValues) { var version = blobSASSignatureValues.version ? blobSASSignatureValues.version : SERVICE_VERSION; if (blobSASSignatureValues.snapshotTime && version < "2018-11-09") { throw RangeError("'version' must be >= '2018-11-09' when providing 'snapshotTime'."); } if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.snapshotTime) { throw RangeError("Must provide 'blobName' when providing 'snapshotTime'."); } if (blobSASSignatureValues.versionId && version < "2019-10-10") { throw RangeError("'version' must be >= '2019-10-10' when providing 'versionId'."); } if (blobSASSignatureValues.blobName === undefined && blobSASSignatureValues.versionId) { throw RangeError("Must provide 'blobName' when providing 'versionId'."); } if (blobSASSignatureValues.permissions && blobSASSignatureValues.permissions.deleteVersion && version < "2019-10-10") { throw RangeError("'version' must be >= '2019-10-10' when providing 'x' permission."); } if (blobSASSignatureValues.permissions && blobSASSignatureValues.permissions.tag && version < "2019-12-12") { throw RangeError("'version' must be >= '2019-12-12' when providing 't' permission."); } if (version < "2020-02-10" && blobSASSignatureValues.permissions && (blobSASSignatureValues.permissions.move || blobSASSignatureValues.permissions.execute)) { throw RangeError("'version' must be >= '2020-02-10' when providing the 'm' or 'e' permission."); } if (version < "2020-02-10" && (blobSASSignatureValues.preauthorizedAgentObjectId || blobSASSignatureValues.correlationId)) { throw RangeError("'version' must be >= '2020-02-10' when providing 'preauthorizedAgentObjectId' or 'correlationId'."); } blobSASSignatureValues.version = version; return blobSASSignatureValues; } Object.defineProperty(exports, 'BaseRequestPolicy', { enumerable: true, get: function () { return coreHttp.BaseRequestPolicy; } }); Object.defineProperty(exports, 'HttpHeaders', { enumerable: true, get: function () { return coreHttp.HttpHeaders; } }); Object.defineProperty(exports, 'RequestPolicyOptions', { enumerable: true, get: function () { return coreHttp.RequestPolicyOptions; } }); Object.defineProperty(exports, 'RestError', { enumerable: true, get: function () { return coreHttp.RestError; } }); Object.defineProperty(exports, 'WebResource', { enumerable: true, get: function () { return coreHttp.WebResource; } }); Object.defineProperty(exports, 'deserializationPolicy', { enumerable: true, get: function () { return coreHttp.deserializationPolicy; } }); exports.AccountSASPermissions = AccountSASPermissions; exports.AccountSASResourceTypes = AccountSASResourceTypes; exports.AccountSASServices = AccountSASServices; exports.AnonymousCredential = AnonymousCredential; exports.AnonymousCredentialPolicy = AnonymousCredentialPolicy; exports.AppendBlobClient = AppendBlobClient; exports.BlobBatch = BlobBatch; exports.BlobBatchClient = BlobBatchClient; exports.BlobClient = BlobClient; exports.BlobLeaseClient = BlobLeaseClient; exports.BlobSASPermissions = BlobSASPermissions; exports.BlobServiceClient = BlobServiceClient; exports.BlockBlobClient = BlockBlobClient; exports.ContainerClient = ContainerClient; exports.ContainerSASPermissions = ContainerSASPermissions; exports.Credential = Credential; exports.CredentialPolicy = CredentialPolicy; exports.PageBlobClient = PageBlobClient; exports.Pipeline = Pipeline; exports.SASQueryParameters = SASQueryParameters; exports.StorageBrowserPolicy = StorageBrowserPolicy; exports.StorageBrowserPolicyFactory = StorageBrowserPolicyFactory; exports.StorageOAuthScopes = StorageOAuthScopes; exports.StorageRetryPolicy = StorageRetryPolicy; exports.StorageRetryPolicyFactory = StorageRetryPolicyFactory; exports.StorageSharedKeyCredential = StorageSharedKeyCredential; exports.StorageSharedKeyCredentialPolicy = StorageSharedKeyCredentialPolicy; exports.generateAccountSASQueryParameters = generateAccountSASQueryParameters; exports.generateBlobSASQueryParameters = generateBlobSASQueryParameters; exports.logger = logger; exports.newPipeline = newPipeline; //# sourceMappingURL=index.js.map