@azure/core-amqp 4.4.0-alpha.20240701.3 → 4.4.0-alpha.20240704.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/index.d.ts +0 -1
- package/dist/browser/index.d.ts.map +1 -1
- package/dist/browser/messageProperties.d.ts +0 -1
- package/dist/browser/messageProperties.d.ts.map +1 -1
- package/dist/commonjs/auth/tokenProvider.js +2 -2
- package/dist/commonjs/auth/tokenProvider.js.map +1 -1
- package/dist/commonjs/connectionConfig/connectionConfig.js +2 -2
- package/dist/commonjs/connectionConfig/connectionConfig.js.map +1 -1
- package/dist/commonjs/errors.js +4 -4
- package/dist/commonjs/errors.js.map +1 -1
- package/dist/commonjs/index.d.ts +0 -1
- package/dist/commonjs/index.d.ts.map +1 -1
- package/dist/commonjs/log.js +2 -2
- package/dist/commonjs/log.js.map +1 -1
- package/dist/commonjs/messageProperties.d.ts +0 -1
- package/dist/commonjs/messageProperties.d.ts.map +1 -1
- package/dist/commonjs/requestResponseLink.js +2 -2
- package/dist/commonjs/requestResponseLink.js.map +1 -1
- package/dist/commonjs/retry.js +2 -2
- package/dist/commonjs/retry.js.map +1 -1
- package/dist/commonjs/util/checkNetworkConnection.js +1 -2
- package/dist/commonjs/util/checkNetworkConnection.js.map +1 -1
- package/dist/commonjs/util/hmacSha256.js +1 -2
- package/dist/commonjs/util/hmacSha256.js.map +1 -1
- package/dist/commonjs/util/runtimeInfo.js +2 -3
- package/dist/commonjs/util/runtimeInfo.js.map +1 -1
- package/dist/commonjs/util/typeGuards.js +1 -2
- package/dist/commonjs/util/typeGuards.js.map +1 -1
- package/dist/commonjs/util/utils.js +9 -9
- package/dist/commonjs/util/utils.js.map +1 -1
- package/dist/core-amqp.d.ts +0 -2
- package/dist/esm/index.d.ts +0 -1
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/messageProperties.d.ts +0 -1
- package/dist/esm/messageProperties.d.ts.map +1 -1
- package/dist/react-native/index.d.ts +0 -1
- package/dist/react-native/index.d.ts.map +1 -1
- package/dist/react-native/messageProperties.d.ts +0 -1
- package/dist/react-native/messageProperties.d.ts.map +1 -1
- package/package.json +5 -4
package/dist/browser/index.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AACnF,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC7F,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACnG,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAClD,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AACtE,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,EACL,qBAAqB,EACrB,oBAAoB,EACpB,qCAAqC,GACtC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,wBAAwB,EACxB,wBAAwB,EACxB,SAAS,EACT,eAAe,EACf,aAAa,EACb,0BAA0B,EAC1B,kBAAkB,GACnB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,KAAK,EACL,qBAAqB,EACrB,sBAAsB,EACtB,YAAY,EACZ,gBAAgB,GACjB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,cAAc,gBAAgB,CAAC;AAC/B,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messageProperties.d.ts","sourceRoot":"","sources":["../../src/messageProperties.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"messageProperties.d.ts","sourceRoot":"","sources":["../../src/messageProperties.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,iBAAiB,IAAI,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAG1E;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IACrC;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;OAEG;IACH,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IACzC;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB;;OAEG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;OAEG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CAKlB;AAED;;GAEG;AAEH,eAAO,MAAM,qBAAqB;IAChC;;;;OAIG;mCAC4B,qBAAqB,GAAG,qBAAqB;IA8C5E;;;;OAIG;qCAC8B,qBAAqB,GAAG,qBAAqB;CA6C/E,CAAC"}
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
// Copyright (c) Microsoft Corporation.
|
|
3
3
|
// Licensed under the MIT license.
|
|
4
4
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
-
exports.SasTokenProviderImpl =
|
|
5
|
+
exports.SasTokenProviderImpl = void 0;
|
|
6
|
+
exports.createSasTokenProvider = createSasTokenProvider;
|
|
6
7
|
const core_auth_1 = require("@azure/core-auth");
|
|
7
8
|
const hmacSha256_js_1 = require("../util/hmacSha256.js");
|
|
8
9
|
/**
|
|
@@ -21,7 +22,6 @@ function createSasTokenProvider(data) {
|
|
|
21
22
|
return new SasTokenProviderImpl({ signature: data.sharedAccessSignature });
|
|
22
23
|
}
|
|
23
24
|
}
|
|
24
|
-
exports.createSasTokenProvider = createSasTokenProvider;
|
|
25
25
|
/**
|
|
26
26
|
* A TokenProvider that generates a Sas token:
|
|
27
27
|
* `SharedAccessSignature sr=<resource>&sig=<signature>&se=<expiry>&skn=<keyname>`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tokenProvider.js","sourceRoot":"","sources":["../../../src/auth/tokenProvider.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;
|
|
1
|
+
{"version":3,"file":"tokenProvider.js","sourceRoot":"","sources":["../../../src/auth/tokenProvider.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAmClC,wDAcC;AA/CD,gDAM0B;AAC1B,yDAAmD;AAqBnD;;;;GAIG;AACH,SAAgB,sBAAsB,CACpC,IAIiB;IAEjB,IAAI,IAAA,gCAAoB,EAAC,IAAI,CAAC,IAAI,IAAA,2BAAe,EAAC,IAAI,CAAC,EAAE,CAAC;QACxD,OAAO,IAAI,oBAAoB,CAAC,IAAI,CAAC,CAAC;IACxC,CAAC;SAAM,IAAI,qBAAqB,IAAI,IAAI,IAAI,iBAAiB,IAAI,IAAI,EAAE,CAAC;QACtE,OAAO,IAAI,oBAAoB,CAAC,EAAE,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IAChD,OAAO;QACL,KAAK,EAAE,4BAA4B,QAAQ,QAAQ,GAAG,OAAO,MAAM,QAAQ,OAAO,EAAE;QACpF,kBAAkB,EAAE,MAAM;KAC3B,CAAC;AACJ,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport {\n AccessToken,\n NamedKeyCredential,\n SASCredential,\n isNamedKeyCredential,\n isSASCredential,\n} from \"@azure/core-auth\";\nimport { signString } from \"../util/hmacSha256.js\";\n\n/**\n * A SasTokenProvider provides an alternative to TokenCredential for providing an `AccessToken`.\n * @hidden\n */\nexport interface SasTokenProvider {\n /**\n * Property used to distinguish SasTokenProvider from TokenCredential.\n */\n isSasTokenProvider: true;\n /**\n * Gets the token provided by this provider.\n *\n * This method is called automatically by Azure SDK client libraries.\n *\n * @param audience - The audience for which the token is desired.\n */\n getToken(audience: string): Promise<AccessToken>;\n}\n\n/**\n * Creates a token provider from the provided shared access data.\n * @param data - The sharedAccessKeyName/sharedAccessKey pair or the sharedAccessSignature.\n * @hidden\n */\nexport function createSasTokenProvider(\n data:\n | { sharedAccessKeyName: string; sharedAccessKey: string }\n | { sharedAccessSignature: string }\n | NamedKeyCredential\n | SASCredential,\n): SasTokenProvider {\n if (isNamedKeyCredential(data) || isSASCredential(data)) {\n return new SasTokenProviderImpl(data);\n } else if (\"sharedAccessKeyName\" in data && \"sharedAccessKey\" in data) {\n return new SasTokenProviderImpl({ name: data.sharedAccessKeyName, key: data.sharedAccessKey });\n } else {\n return new SasTokenProviderImpl({ signature: data.sharedAccessSignature });\n }\n}\n\n/**\n * A TokenProvider that generates a Sas token:\n * `SharedAccessSignature sr=<resource>&sig=<signature>&se=<expiry>&skn=<keyname>`\n *\n * @internal\n */\nexport class SasTokenProviderImpl implements SasTokenProvider {\n /**\n * Property used to distinguish TokenProvider from TokenCredential.\n */\n get isSasTokenProvider(): true {\n return true;\n }\n\n /**\n * The SASCredential containing the key name and secret key value.\n */\n private _credential: SASCredential | NamedKeyCredential;\n\n /**\n * Initializes a new instance of SasTokenProvider\n * @param credential - The source `NamedKeyCredential` or `SASCredential`.\n */\n constructor(credential: SASCredential | NamedKeyCredential) {\n this._credential = credential;\n }\n\n /**\n * Gets the sas token for the specified audience\n * @param audience - The audience for which the token is desired.\n */\n async getToken(audience: string): Promise<AccessToken> {\n if (isNamedKeyCredential(this._credential)) {\n return createToken(\n this._credential.name,\n this._credential.key,\n Math.floor(Date.now() / 1000) + 3600,\n audience,\n );\n } else {\n return {\n token: this._credential.signature,\n expiresOnTimestamp: 0,\n };\n }\n }\n}\n\n/**\n * Creates the sas token based on the provided information.\n * @param keyName - The shared access key name.\n * @param key - The shared access key.\n * @param expiry - The time period in unix time after which the token will expire.\n * @param audience - The audience for which the token is desired.\n * @internal\n */\nasync function createToken(\n keyName: string,\n key: string,\n expiry: number,\n audience: string,\n): Promise<AccessToken> {\n audience = encodeURIComponent(audience);\n keyName = encodeURIComponent(keyName);\n const stringToSign = audience + \"\\n\" + expiry;\n\n const sig = await signString(key, stringToSign);\n return {\n token: `SharedAccessSignature sr=${audience}&sig=${sig}&se=${expiry}&skn=${keyName}`,\n expiresOnTimestamp: expiry,\n };\n}\n"]}
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
// Copyright (c) Microsoft Corporation.
|
|
3
3
|
// Licensed under the MIT license.
|
|
4
4
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
-
exports.
|
|
5
|
+
exports.ConnectionConfig = void 0;
|
|
6
|
+
exports.isSharedAccessSignature = isSharedAccessSignature;
|
|
6
7
|
const core_util_1 = require("@azure/core-util");
|
|
7
8
|
const utils_js_1 = require("../util/utils.js");
|
|
8
9
|
function getHost(endpoint) {
|
|
@@ -88,5 +89,4 @@ exports.ConnectionConfig = {
|
|
|
88
89
|
function isSharedAccessSignature(connectionString) {
|
|
89
90
|
return connectionString.match(/;{0,1}SharedAccessSignature=SharedAccessSignature /) != null;
|
|
90
91
|
}
|
|
91
|
-
exports.isSharedAccessSignature = isSharedAccessSignature;
|
|
92
92
|
//# sourceMappingURL=connectionConfig.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connectionConfig.js","sourceRoot":"","sources":["../../../src/connectionConfig/connectionConfig.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;
|
|
1
|
+
{"version":3,"file":"connectionConfig.js","sourceRoot":"","sources":["../../../src/connectionConfig/connectionConfig.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAuLlC,0DAEC;AAtLD,gDAA6C;AAC7C,+CAAyD;AAkFzD,SAAS,OAAO,CAAC,QAAgB;IAC/B,MAAM,OAAO,GAAG,gBAAgB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAChD,MAAM,KAAK,GAAG,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAG,CAAC,CAAC,CAAC;IAC3B,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC;AACnC,CAAC;AAED;;GAEG;AACH,4GAA4G;AAC/F,QAAA,gBAAgB,GAAG;IAC9B;;;;;;;;OAQG;IACH,MAAM,CAAC,gBAAwB,EAAE,IAAa;QAC5C,gBAAgB,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAC;QAE5C,MAAM,QAAQ,GAAG,IAAA,gCAAqB,EAMnC,gBAAgB,CAAC,CAAC;QACrB,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,CAAC;YACvB,MAAM,IAAI,SAAS,CAAC,wCAAwC,CAAC,CAAC;QAChE,CAAC;QAED,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC;YAAE,QAAQ,CAAC,QAAQ,IAAI,GAAG,CAAC;QAE/D,MAAM,MAAM,GAAqB;YAC/B,gBAAgB,EAAE,gBAAgB;YAClC,QAAQ,EAAE,QAAQ,CAAC,QAAQ;YAC3B,IAAI,EAAE,OAA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uBAAuB,CAAC,MAAM,CAAC,gBAAgB,CAAC,EAAE,CAAC;YACtD,IAAI,CAAC,MAAM,CAAC,mBAAmB,EAAE,CAAC;gBAChC,MAAM,IAAI,SAAS,CAAC,gDAAgD,CAAC,CAAC;YACxE,CAAC;YACD,MAAM,CAAC,mBAAmB,GAAG,MAAM,CAAC,MAAM,CAAC,mBAAmB,CAAC,CAAC;YAEhE,IAAI,CAAC,MAAM,CAAC,eAAe,EAAE,CAAC;gBAC5B,MAAM,IAAI,SAAS,CAAC,4CAA4C,CAAC,CAAC;YACpE,CAAC;YACD,MAAM,CAAC,eAAe,GAAG,MAAM,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC;QAC1D,CAAC;IACH,CAAC;CACF,CAAC;AAEF;;GAEG;AACH,SAAgB,uBAAuB,CAAC,gBAAwB;IAC9D,OAAO,gBAAgB,CAAC,KAAK,CAAC,oDAAoD,CAAC,IAAI,IAAI,CAAC;AAC9F,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { WebSocketImpl } from \"rhea-promise\";\nimport { isDefined } from \"@azure/core-util\";\nimport { parseConnectionString } from \"../util/utils.js\";\n\n/**\n * Describes the options that can be provided while creating a connection config.\n */\nexport interface ConnectionConfigOptions {\n /**\n * Indicates whether the entity path is required in the\n * connection config.\n */\n isEntityPathRequired?: boolean;\n}\n\n/**\n * Describes the connection config object that is created after parsing an EventHub or ServiceBus\n * connection string.\n */\nexport interface ConnectionConfig {\n /**\n * The service bus endpoint\n * \"sb://<yournamespace>.servicebus.windows.net/\".\n */\n endpoint: string;\n /**\n * The DNS hostname or IP address of the service.\n * Typically of the form \"<yournamespace>.servicebus.windows.net\" unless connecting\n * to the service through an intermediary.\n */\n host: string;\n /**\n * The fully qualified name of the host to connect to.\n * This field can be used by AMQP proxies to determine the correct back-end service to\n * connect the client to.\n * Typically of the form \"<yournamespace>.servicebus.windows.net\".\n */\n amqpHostname?: string;\n /**\n * The port number.\n */\n port?: number;\n /**\n * The connection string.\n */\n connectionString: string;\n /**\n * The name/path of the entity (hub/queue/topic name) to which the\n * connection needs to happen.\n */\n entityPath?: string;\n /**\n * The name of the access key.\n */\n sharedAccessKeyName: string;\n /**\n * The secret value of the access key.\n */\n sharedAccessKey: string;\n\n /**\n * The WebSocket constructor used to create an AMQP connection\n * over a WebSocket. In browsers, the built-in WebSocket will be used by default. In Node, a\n * TCP socket will be used if a WebSocket constructor is not provided.\n */\n webSocket?: WebSocketImpl;\n\n /**\n * The path for the endpoint that accepts an AMQP\n * connection over WebSockets.\n */\n webSocketEndpointPath?: string;\n\n /**\n * Options to be passed to the WebSocket constructor\n */\n webSocketConstructorOptions?: any;\n /**\n * This should be true only if the connection string contains the slug \";UseDevelopmentEmulator=true\"\n * and the endpoint is a loopback address.\n */\n useDevelopmentEmulator?: boolean;\n}\n\nfunction getHost(endpoint: string): string {\n const matches = /.*:\\/\\/([^/]*)/.exec(endpoint);\n const match = matches?.[1];\n return !match ? endpoint : match;\n}\n\n/**\n * Describes the ConnectionConfig module\n */\n// eslint-disable-next-line @typescript-eslint/no-redeclare -- renaming constant would be a breaking change.\nexport const ConnectionConfig = {\n /**\n * Creates the connection config.\n * @param connectionString - The connection string for a given service like\n * EventHub/ServiceBus.\n * @param path - The name/path of the entity (hub name) to which the\n * connection needs to happen. This will override the EntityPath in the connectionString\n * if present.\n * @returns ConnectionConfig\n */\n create(connectionString: string, path?: string): ConnectionConfig {\n connectionString = String(connectionString);\n\n const parsedCS = parseConnectionString<{\n Endpoint: string;\n SharedAccessKeyName: string;\n SharedAccessKey: string;\n EntityPath?: string;\n UseDevelopmentEmulator?: string;\n }>(connectionString);\n if (!parsedCS.Endpoint) {\n throw new TypeError(\"Missing Endpoint in Connection String.\");\n }\n\n if (!parsedCS.Endpoint.endsWith(\"/\")) parsedCS.Endpoint += \"/\";\n\n const result: ConnectionConfig = {\n connectionString: connectionString,\n endpoint: parsedCS.Endpoint,\n host: getHost(parsedCS.Endpoint),\n sharedAccessKeyName: parsedCS.SharedAccessKeyName,\n sharedAccessKey: parsedCS.SharedAccessKey,\n useDevelopmentEmulator: parsedCS.UseDevelopmentEmulator === \"true\",\n };\n\n if (path || parsedCS.EntityPath) {\n result.entityPath = path || parsedCS.EntityPath;\n }\n return result;\n },\n\n /**\n * Validates the properties of connection config.\n * @param config - The connection config to be validated.\n * @returns void\n */\n validate(config: ConnectionConfig, options?: ConnectionConfigOptions): void {\n if (!options) options = {};\n\n if (!config) {\n throw new TypeError(\"Missing configuration\");\n }\n\n if (!config.endpoint) {\n throw new TypeError(\"Missing 'endpoint' in configuration\");\n }\n config.endpoint = String(config.endpoint);\n\n if (!config.host) {\n throw new TypeError(\"Missing 'host' in configuration\");\n }\n config.host = String(config.host);\n\n if (options.isEntityPathRequired && !config.entityPath) {\n throw new TypeError(\"Missing 'entityPath' in configuration\");\n }\n if (isDefined(config.entityPath)) {\n config.entityPath = String(config.entityPath);\n }\n\n if (!isSharedAccessSignature(config.connectionString)) {\n if (!config.sharedAccessKeyName) {\n throw new TypeError(\"Missing 'sharedAccessKeyName' in configuration\");\n }\n config.sharedAccessKeyName = String(config.sharedAccessKeyName);\n\n if (!config.sharedAccessKey) {\n throw new TypeError(\"Missing 'sharedAccessKey' in configuration\");\n }\n config.sharedAccessKey = String(config.sharedAccessKey);\n }\n },\n};\n\n/**\n * @internal\n */\nexport function isSharedAccessSignature(connectionString: string): boolean {\n return connectionString.match(/;{0,1}SharedAccessSignature=SharedAccessSignature /) != null;\n}\n"]}
|
package/dist/commonjs/errors.js
CHANGED
|
@@ -3,7 +3,10 @@
|
|
|
3
3
|
// Licensed under the MIT license.
|
|
4
4
|
/* eslint-disable eqeqeq */
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.
|
|
6
|
+
exports.SystemErrorConditionMapper = exports.retryableErrors = exports.MessagingError = exports.ErrorNameConditionMapper = exports.ConditionErrorNameMapper = exports.ConditionStatusMapper = void 0;
|
|
7
|
+
exports.isMessagingError = isMessagingError;
|
|
8
|
+
exports.isSystemError = isSystemError;
|
|
9
|
+
exports.translate = translate;
|
|
7
10
|
const rhea_promise_1 = require("rhea-promise");
|
|
8
11
|
const core_util_1 = require("@azure/core-util");
|
|
9
12
|
const utils_js_1 = require("./util/utils.js");
|
|
@@ -466,7 +469,6 @@ const systemErrorFieldsToCopy = [
|
|
|
466
469
|
function isMessagingError(error) {
|
|
467
470
|
return error.name === "MessagingError";
|
|
468
471
|
}
|
|
469
|
-
exports.isMessagingError = isMessagingError;
|
|
470
472
|
/**
|
|
471
473
|
* Describes the base class for Messaging Error.
|
|
472
474
|
*/
|
|
@@ -560,7 +562,6 @@ function isSystemError(err) {
|
|
|
560
562
|
}
|
|
561
563
|
return true;
|
|
562
564
|
}
|
|
563
|
-
exports.isSystemError = isSystemError;
|
|
564
565
|
/**
|
|
565
566
|
* @internal
|
|
566
567
|
* Since browser doesn't differentiate between the various kinds of service communication errors,
|
|
@@ -681,7 +682,6 @@ function translate(err) {
|
|
|
681
682
|
}
|
|
682
683
|
return (0, core_util_1.isError)(errObj) ? errObj : new Error(String(errObj));
|
|
683
684
|
}
|
|
684
|
-
exports.translate = translate;
|
|
685
685
|
/**
|
|
686
686
|
* @internal
|
|
687
687
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;AAClC,2BAA2B;;;AAE3B,+CAAiG;AACjG,gDAA0F;AAC1F,8CAAqD;AAErD;;;GAGG;AACH,IAAY,qBAqBX;AArBD,WAAY,qBAAqB;IAC/B,qGAA+D,CAAA;IAC/D,uFAAkD,CAAA;IAClD,mGAA8D,CAAA;IAC9D,iIAAuE,CAAA;IACvE,yHAA+D,CAAA;IAC/D,yHAA+D,CAAA;IAC/D,uIAAqF,CAAA;IACrF,yHAAoE,CAAA;IACpE,6GAAuE,CAAA;IACvE,mHAAkE,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AAC;QAC1F,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC;QACxB,OAAO,KAAK,CAAC;IACf,CAAC;IAED,iFAAiF;IACjF,wCAAwC;IACxC,IAAI,IAAA,mBAAO,EAAC,MAAM,CAAC,IAAI,iBAAiB,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC;QACrE,MAAM,KAAK,GAAG,IAAI,cAAc,CAAC,MAAM,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QACzD,KAAK,CAAC,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC;QACzB,IAAI,KAAK,CAAC,IAAI,IAAI,uBAAe,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC;YAC7D,YAAY;YACZ,KAAK,CAAC,SAAS,GAAG,KAAK,CAAC;QAC1B,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,IAAA,mBAAO,EAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;AAC9D,CAAC;AArFD,8BAqFC;AAED;;GAEG;AACH,SAAS,WAAW,CAAC,KAAU;IAC7B,OAAO,IAAA,0BAAe,EAAC,KAAK,CAAC,CAAC;AAChC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n/* eslint-disable eqeqeq */\n\nimport { AmqpError, AmqpResponseStatusCode, isAmqpError as rheaIsAmqpError } from \"rhea-promise\";\nimport { isDefined, isError, isNodeLike, isObjectWithProperties } from \"@azure/core-util\";\nimport { isNumber, isString } from \"./util/utils.js\";\n\n/**\n * Maps the conditions to the numeric AMQP Response status codes.\n * @internal\n */\nexport enum ConditionStatusMapper {\n \"com.microsoft:timeout\" = AmqpResponseStatusCode.RequestTimeout,\n \"amqp:not-found\" = AmqpResponseStatusCode.NotFound,\n \"amqp:not-implemented\" = AmqpResponseStatusCode.NotImplemented,\n \"com.microsoft:entity-already-exists\" = AmqpResponseStatusCode.Conflict,\n \"com.microsoft:message-lock-lost\" = AmqpResponseStatusCode.Gone,\n \"com.microsoft:session-lock-lost\" = AmqpResponseStatusCode.Gone,\n \"com.microsoft:no-matching-subscription\" = AmqpResponseStatusCode.InternalServerError,\n \"amqp:link:message-size-exceeded\" = AmqpResponseStatusCode.Forbidden,\n \"com.microsoft:server-busy\" = AmqpResponseStatusCode.ServiceUnavailable,\n \"com.microsoft:argument-error\" = AmqpResponseStatusCode.BadRequest,\n \"com.microsoft:argument-out-of-range\" = AmqpResponseStatusCode.BadRequest,\n \"com.microsoft:store-lock-lost\" = AmqpResponseStatusCode.Gone,\n \"com.microsoft:session-cannot-be-locked\" = AmqpResponseStatusCode.Gone,\n \"com.microsoft:partition-not-owned\" = AmqpResponseStatusCode.Gone,\n \"com.microsoft:entity-disabled\" = AmqpResponseStatusCode.BadRequest,\n \"com.microsoft:publisher-revoked\" = AmqpResponseStatusCode.Unauthorized,\n \"amqp:link:stolen\" = AmqpResponseStatusCode.Gone,\n \"amqp:not-allowed\" = AmqpResponseStatusCode.BadRequest,\n \"amqp:unauthorized-access\" = AmqpResponseStatusCode.Unauthorized,\n \"amqp:resource-limit-exceeded\" = AmqpResponseStatusCode.Forbidden,\n}\n\n/**\n * Maps the amqp error conditions to the Error names.\n */\nexport enum ConditionErrorNameMapper {\n /**\n * Error is thrown when the address is already in use.\n */\n \"com.microsoft:address-already-in-use\" = \"AddressAlreadyInUseError\",\n /**\n * Error is thrown when the store lock is lost.\n */\n \"com.microsoft:store-lock-lost\" = \"StoreLockLostError\",\n /**\n * Error is thrown when a matching subscription is not found.\n */\n \"com.microsoft:no-matching-subscription\" = \"NoMatchingSubscriptionError\",\n /**\n * Error is thrown when an attempt is made to access a partition that is not owned by the\n * requesting entity.\n */\n \"com.microsoft:partition-not-owned\" = \"PartitionNotOwnedError\",\n /**\n * Error is thrown when access to publisher has been revoked.\n */\n \"com.microsoft:publisher-revoked\" = \"PublisherRevokedError\",\n /**\n * Error is thrown when an attempt is made to create an entity that already exists.\n */\n \"com.microsoft:entity-already-exists\" = \"MessagingEntityAlreadyExistsError\",\n /**\n * Error is thrown when trying to access/connect to a disabled messaging entity.\n */\n \"com.microsoft:entity-disabled\" = \"MessagingEntityDisabledError\",\n /**\n * Error is thrown when the lock on the message is lost.\n */\n \"com.microsoft:message-lock-lost\" = \"MessageLockLostError\",\n /**\n * Error is thrown when the lock on the Azure ServiceBus session is lost.\n */\n \"com.microsoft:session-lock-lost\" = \"SessionLockLostError\",\n /**\n * Error is thrown when the Azure ServiceBus session cannot be locked.\n */\n \"com.microsoft:session-cannot-be-locked\" = \"SessionCannotBeLockedError\",\n /**\n * Error is thrown when an internal server error occurred. You may have found a bug?\n */\n \"amqp:internal-error\" = \"InternalServerError\", // Retryable\n /**\n * Error for signaling general communication errors related to messaging operations.\n */\n \"amqp:not-found\" = \"ServiceCommunicationError\",\n /**\n * Error is thrown when the message is not found.\n */\n \"com.microsoft:message-not-found\" = \"MessageNotFoundError\",\n /**\n * Error is thrown when relay is not found.\n */\n \"com.microsoft:relay-not-found\" = \"RelayNotFoundError\",\n /**\n * Error is thrown when a feature is not implemented yet but the placeholder is present.\n */\n \"amqp:not-implemented\" = \"NotImplementedError\",\n /**\n * Error is thrown when an operation is attempted but is not allowed.\n */\n \"amqp:not-allowed\" = \"InvalidOperationError\",\n /**\n * Error is thrown the the Azure EventHub/ServiceBus quota has been exceeded.\n * Quotas are reset periodically, this operation will have to wait until then.\n * The messaging entity has reached its maximum allowable size.\n * This can happen if the maximum number of receivers (which is 5) has already\n * been opened on a per-consumer group level.\n */\n \"amqp:resource-limit-exceeded\" = \"QuotaExceededError\",\n /**\n * Error is thrown when the connection parameters are wrong and the server refused the connection.\n */\n \"amqp:unauthorized-access\" = \"UnauthorizedError\",\n /**\n * Error is thrown when the connection parameters are wrong and the server refused the connection.\n */\n // eslint-disable-next-line @typescript-eslint/no-duplicate-enum-values\n \"com.microsoft:auth-failed\" = \"UnauthorizedError\",\n /**\n * Error is thrown when the service is unavailable. The operation should be retried.\n */\n \"com.microsoft:timeout\" = \"ServiceUnavailableError\", // Retryable\n /**\n * Error is thrown when no new messages are received for the specified time.\n */\n \"com.microsoft:message-wait-timeout\" = \"MessageWaitTimeout\",\n /**\n * Error is thrown when an argument has a value that is out of the admissible range.\n */\n \"com.microsoft:argument-out-of-range\" = \"ArgumentOutOfRangeError\",\n /**\n * Error is thrown when a condition that should have been met in order to execute an operation was not.\n */\n \"amqp:precondition-failed\" = \"PreconditionFailedError\",\n /**\n * Error is thrown when a condition that should have been met in order to execute an operation was not.\n */\n // eslint-disable-next-line @typescript-eslint/no-duplicate-enum-values\n \"com.microsoft:precondition-failed\" = \"PreconditionFailedError\",\n /**\n * Error is thrown when data could not be decoded.\n */\n \"amqp:decode-error\" = \"DecodeError\",\n /**\n * Error is thrown when an invalid field was passed in a frame body, and the operation could not proceed.\n */\n \"amqp:invalid-field\" = \"InvalidFieldError\",\n /**\n * Error is thrown when the client attempted to work with a server entity to which it\n * has no access because another client is working with it.\n */\n \"amqp:resource-locked\" = \"ResourceLockedError\",\n /**\n * Error is thrown when a server entity the client is working with has been deleted.\n */\n \"amqp:resource-deleted\" = \"ResourceDeletedError\",\n /**\n * Error is thrown when the peer sent a frame that is not permitted in the current state.\n */\n \"amqp:illegal-state\" = \"IllegalStateError\",\n /**\n * Error is thrown when the peer cannot send a frame because the smallest encoding of\n * the performative with the currently valid values would be too large to fit within\n * a frame of the agreed maximum frame size.\n */\n \"amqp:frame-size-too-small\" = \"FrameSizeTooSmallError\",\n /**\n * Error is thrown when an operator intervened to detach for some reason.\n */\n \"amqp:link:detach-forced\" = \"DetachForcedError\", // Retryable\n /**\n * Error is thrown when the peer sent more message transfers than currently allowed on the link.\n */\n \"amqp:link:transfer-limit-exceeded\" = \"TransferLimitExceededError\", // Retryable\n /**\n * Error is thrown when the message sent is too large: the maximum size is 256Kb.\n */\n \"amqp:link:message-size-exceeded\" = \"MessageTooLargeError\",\n /**\n * Error is thrown when the address provided cannot be resolved to a terminus at the current container.\n */\n \"amqp:link:redirect\" = \"LinkRedirectError\",\n /**\n * Error is thrown when two or more instances connect to the same partition\n * with different epoch values.\n */\n \"amqp:link:stolen\" = \"ReceiverDisconnectedError\",\n /**\n * Error is thrown when the peer violated incoming window for the session.\n */\n \"amqp:session:window-violation\" = \"SessionWindowViolationError\",\n /**\n * Error is thrown when input was received for a link that was detached with an error.\n */\n \"amqp:session:errant-link\" = \"ErrantLinkError\",\n /**\n * Error is thrown when an attach was received using a handle that is already in use for an attached link.\n */\n \"amqp:session:handle-in-use\" = \"HandleInUseError\",\n /**\n * Error is thrown when a frame (other than attach) was received referencing a handle which is not\n * currently in use of an attached link.\n */\n \"amqp:session:unattached-handle\" = \"UnattachedHandleError\",\n /**\n * Error is thrown when an operator intervened to close the connection for some reason.\n */\n \"amqp:connection:forced\" = \"ConnectionForcedError\", // Retryable\n /**\n * Error is thrown when a valid frame header cannot be formed from the incoming byte stream.\n */\n \"amqp:connection:framing-error\" = \"FramingError\",\n /**\n * Error is thrown when the container is no longer available on the current connection.\n */\n \"amqp:connection:redirect\" = \"ConnectionRedirectError\",\n /**\n * Error is thrown when the server is busy. Callers should wait a while and retry the operation.\n */\n \"com.microsoft:server-busy\" = \"ServerBusyError\", // Retryable\n /**\n * Error is thrown when an incorrect argument was received.\n */\n \"com.microsoft:argument-error\" = \"ArgumentError\",\n /**\n * Error is thrown when server cancels the operation due to an internal issue.\n */\n \"com.microsoft:operation-cancelled\" = \"OperationCancelledError\", // Retryable\n /**\n * Error is thrown when the client sender does not have enough link credits to send the message.\n */\n \"client.sender:not-enough-link-credit\" = \"SenderBusyError\", // Retryable\n /**\n * Error is thrown when the client sender's link isn't ready\n */\n \"client.sender:link-not-ready\" = \"SenderNotReadyError\", // Retryable\n\n /**\n * Error is thrown when a low level system error is thrown by node.js.\n * {@link https://nodejs.org/dist/latest-v8.x/docs/api/all.html#errors_class_system_error}\n */\n \"system:error\" = \"SystemError\",\n}\n\n/**\n * Maps the Error names to the amqp error conditions.\n */\nexport enum ErrorNameConditionMapper {\n /**\n * Error is thrown when the address is already in use.\n */\n AddressAlreadyInUseError = \"com.microsoft:address-already-in-use\",\n /**\n * Error is thrown when the store lock is lost.\n */\n StoreLockLostError = \"com.microsoft:store-lock-lost\",\n /**\n * Error is thrown when a matching subscription is not found.\n */\n NoMatchingSubscriptionError = \"com.microsoft:no-matching-subscription\",\n /**\n * Error is thrown when an attempt is made to access a partition that is not owned by the\n * requesting entity.\n */\n PartitionNotOwnedError = \"com.microsoft:partition-not-owned\",\n /**\n * Error is thrown when access to publisher has been revoked.\n */\n PublisherRevokedError = \"com.microsoft:publisher-revoked\",\n /**\n * Error is thrown when an attempt is made to create an entity that already exists.\n */\n MessagingEntityAlreadyExistsError = \"com.microsoft:entity-already-exists\",\n /**\n * Error is thrown when trying to access/connect to a disabled messaging entity.\n */\n MessagingEntityDisabledError = \"com.microsoft:entity-disabled\",\n /**\n * Error is thrown when the lock on the message is lost.\n */\n MessageLockLostError = \"com.microsoft:message-lock-lost\",\n /**\n * Error is thrown when the lock on the Azure ServiceBus session is lost.\n */\n SessionLockLostError = \"com.microsoft:session-lock-lost\",\n /**\n * Error is thrown when the Azure ServiceBus session cannot be locked.\n */\n SessionCannotBeLockedError = \"com.microsoft:session-cannot-be-locked\",\n /**\n * Error is thrown when an internal server error occurred. You may have found a bug?\n */\n InternalServerError = \"amqp:internal-error\", // Retryable\n /**\n * Error for signaling general communication errors related to messaging operations.\n */\n ServiceCommunicationError = \"amqp:not-found\",\n /**\n * Error is thrown when message is not found.\n */\n MessageNotFoundError = \"com.microsoft:message-not-found\",\n /**\n * Error is thrown when relay is not found.\n */\n RelayNotFoundError = \"com.microsoft:relay-not-found\",\n /**\n * Error is thrown when a feature is not implemented yet but the placeholder is present.\n */\n NotImplementedError = \"amqp:not-implemented\",\n /**\n * Error is thrown when an operation is attempted but is not allowed.\n */\n InvalidOperationError = \"amqp:not-allowed\",\n /**\n * Error is thrown the the Azure EventHub/ServiceBus quota has been exceeded.\n * Quotas are reset periodically, this operation will have to wait until then.\n * The messaging entity has reached its maximum allowable size.\n * This can happen if the maximum number of receivers (which is 5) has already\n * been opened on a per-consumer group level.\n */\n QuotaExceededError = \"amqp:resource-limit-exceeded\",\n /**\n * Error is thrown when the connection parameters are wrong and the server refused the connection.\n */\n UnauthorizedError = \"amqp:unauthorized-access\",\n /**\n * Error is thrown when the service is unavailable. The operation should be retried.\n */\n ServiceUnavailableError = \"com.microsoft:timeout\", // Retryable\n /**\n * Error is thrown when no new messages are received for the specified time.\n */\n MessageWaitTimeout = \"com.microsoft:message-wait-timeout\",\n /**\n * Error is thrown when an argument has a value that is out of the admissible range.\n */\n ArgumentOutOfRangeError = \"com.microsoft:argument-out-of-range\",\n /**\n * Error is thrown when a condition that should have been met in order to execute an operation was not.\n */\n PreconditionFailedError = \"amqp:precondition-failed\",\n /**\n * Error is thrown when data could not be decoded.\n */\n DecodeError = \"amqp:decode-error\",\n /**\n * Error is thrown when an invalid field was passed in a frame body, and the operation could not proceed.\n */\n InvalidFieldError = \"amqp:invalid-field\",\n /**\n * Error is thrown when the client attempted to work with a server entity to which it\n * has no access because another client is working with it.\n */\n ResourceLockedError = \"amqp:resource-locked\",\n /**\n * Error is thrown when a server entity the client is working with has been deleted.\n */\n ResourceDeletedError = \"amqp:resource-deleted\",\n /**\n * Error is thrown when the peer sent a frame that is not permitted in the current state.\n */\n IllegalStateError = \"amqp:illegal-state\",\n /**\n * Error is thrown when the peer cannot send a frame because the smallest encoding of\n * the performative with the currently valid values would be too large to fit within\n * a frame of the agreed maximum frame size.\n */\n FrameSizeTooSmallError = \"amqp:frame-size-too-small\",\n /**\n * Error is thrown when an operator intervened to detach for some reason.\n */\n DetachForcedError = \"amqp:link:detach-forced\", // Retryable\n /**\n * Error is thrown when the peer sent more message transfers than currently allowed on the link.\n */\n TransferLimitExceededError = \"amqp:link:transfer-limit-exceeded\", // Retryable\n /**\n * Error is thrown when the message sent is too large: the maximum size is 256Kb.\n */\n MessageTooLargeError = \"amqp:link:message-size-exceeded\",\n /**\n * Error is thrown when the address provided cannot be resolved to a terminus at the current container.\n */\n LinkRedirectError = \"amqp:link:redirect\",\n /**\n * Error is thrown when two or more instances connect to the same partition\n * with different epoch values.\n */\n ReceiverDisconnectedError = \"amqp:link:stolen\",\n /**\n * Error is thrown when the peer violated incoming window for the session.\n */\n SessionWindowViolationError = \"amqp:session:window-violation\",\n /**\n * Error is thrown when input was received for a link that was detached with an error.\n */\n ErrantLinkError = \"amqp:session:errant-link\",\n /**\n * Error is thrown when an attach was received using a handle that is already in use for an attached link.\n */\n HandleInUseError = \"amqp:session:handle-in-use\",\n /**\n * Error is thrown when a frame (other than attach) was received referencing a handle which is not\n * currently in use of an attached link.\n */\n UnattachedHandleError = \"amqp:session:unattached-handle\",\n /**\n * Error is thrown when an operator intervened to close the connection for some reason.\n */\n ConnectionForcedError = \"amqp:connection:forced\", // Retryable\n /**\n * Error is thrown when a valid frame header cannot be formed from the incoming byte stream.\n */\n FramingError = \"amqp:connection:framing-error\",\n /**\n * Error is thrown when the container is no longer available on the current connection.\n */\n ConnectionRedirectError = \"amqp:connection:redirect\",\n /**\n * Error is thrown when the server is busy. Callers should wait a while and retry the operation.\n */\n ServerBusyError = \"com.microsoft:server-busy\", // Retryable\n /**\n * Error is thrown when an incorrect argument was received.\n */\n ArgumentError = \"com.microsoft:argument-error\",\n /**\n * Error is thrown when server cancels the operation due to an internal issue.\n */\n OperationCancelledError = \"com.microsoft:operation-cancelled\", // Retryable\n /**\n * Error is thrown when the client sender does not have enough link credits to send the message.\n */\n SenderBusyError = \"client.sender:not-enough-link-credit\", // Retryable\n /**\n * Error is thrown when the client sender's link isn't ready\n */\n SenderNotReadyError = \"client.sender:link-not-ready\", // Retryable\n /**\n * Error is thrown when a low level system error is thrown by node.js.\n * {@link https://nodejs.org/api/errors.html#errors_class_systemerror}\n */\n SystemError = \"system:error\",\n}\n\n/**\n * Describes the fields on a Node.js SystemError.\n * Omits fields that are not related to network calls (e.g. file system calls).\n * See https://nodejs.org/dist/latest-v12.x/docs/api/errors.html#errors_class_systemerror\n */\nexport interface NetworkSystemError {\n address?: string;\n code: string;\n errno: string | number;\n info?: any;\n message: string;\n name: string;\n port?: number;\n stack: string;\n syscall: string;\n}\n\n/**\n * @internal\n */\nconst systemErrorFieldsToCopy: (keyof Omit<NetworkSystemError, \"name\" | \"message\">)[] = [\n \"address\",\n \"code\",\n \"errno\",\n \"info\",\n \"port\",\n \"stack\",\n \"syscall\",\n];\n\n/**\n * Determines if an error is a MessagingError.\n *\n * @param error - An error that can either be an Error or a MessagingError.\n */\nexport function isMessagingError(error: Error | MessagingError): error is MessagingError {\n return error.name === \"MessagingError\";\n}\n\n/**\n * Describes the base class for Messaging Error.\n */\nexport class MessagingError extends Error {\n /**\n * Address to which the network connection failed.\n * Only present if the `MessagingError` was instantiated with a Node.js `SystemError`.\n */\n address?: string;\n /**\n * A string label that identifies the error.\n */\n code?: string;\n /**\n * System-provided error number.\n * Only present if the `MessagingError` was instantiated with a Node.js `SystemError`.\n */\n errno?: number | string;\n /**\n * The error name. Default value: \"MessagingError\".\n */\n name: string = \"MessagingError\";\n /**\n * The unavailable network connection port.\n * Only present if the `MessagingError` was instantiated with a Node.js `SystemError`.\n */\n port?: number;\n /**\n * Name of the system call that triggered the error.\n * Only present if the `MessagingError` was instantiated with a Node.js `SystemError`.\n */\n syscall?: string;\n /**\n *\n * Describes whether the error is retryable. Default: true.\n */\n retryable: boolean = true;\n /**\n * Extra details about the error.\n */\n info?: any;\n /**\n * @param message - The error message that provides more information about the error.\n * @param originalError - An error whose properties will be copied to the MessagingError if the\n * property matches one found on the Node.js `SystemError`.\n */\n constructor(message: string, originalError?: Error) {\n super(message);\n\n if (!originalError) {\n return;\n }\n\n // copy properties from system error\n for (const propName of systemErrorFieldsToCopy) {\n if ((originalError as NetworkSystemError)[propName] != undefined) {\n this[propName] = (originalError as NetworkSystemError)[propName];\n }\n }\n }\n}\n\n/**\n * Provides a list of retryable AMQP errors.\n * \"InternalServerError\", \"ServerBusyError\", \"ServiceUnavailableError\", \"OperationCancelledError\",\n * \"SenderBusyError\", \"SenderNotReadyError\", \"MessagingError\", \"DetachForcedError\", \"ConnectionForcedError\",\n * \"TransferLimitExceededError\"\n */\nexport const retryableErrors: string[] = [\n \"InternalServerError\",\n \"ServerBusyError\",\n \"ServiceUnavailableError\",\n \"OperationCancelledError\",\n\n // The service may throw UnauthorizedError if credentials have been rotated.\n // Attempt to retry in case the user has also rotated their credentials.\n \"UnauthorizedError\",\n\n // OperationTimeoutError occurs when the service fails to respond within a given timeframe.\n // Since reasons for such failures can be transient, this is treated as a retryable error.\n \"OperationTimeoutError\",\n\n \"SenderBusyError\",\n \"SenderNotReadyError\",\n \"MessagingError\",\n \"DetachForcedError\",\n \"ConnectionForcedError\",\n \"TransferLimitExceededError\",\n\n // InsufficientCreditError occurs when the number of credits available on Rhea link is insufficient.\n // Since reasons for such shortage can be transient such as for pending delivery of messages, this is treated as a retryable error.\n \"InsufficientCreditError\",\n];\n\n/**\n * Maps some SystemErrors to amqp error conditions\n */\nexport enum SystemErrorConditionMapper {\n /* eslint-disable @typescript-eslint/no-duplicate-enum-values */\n ENOTFOUND = \"amqp:not-found\",\n EBUSY = \"com.microsoft:server-busy\",\n ECONNREFUSED = \"amqp:connection:forced\",\n ETIMEDOUT = \"com.microsoft:timeout\",\n ECONNRESET = \"com.microsoft:timeout\",\n ENETDOWN = \"com.microsoft:timeout\",\n EHOSTDOWN = \"com.microsoft:timeout\",\n ENETRESET = \"com.microsoft:timeout\",\n ENETUNREACH = \"com.microsoft:timeout\",\n ENONET = \"com.microsoft:timeout\",\n /* eslint-enable @typescript-eslint/no-duplicate-enum-values */\n}\n\n/**\n * Checks whether the provided error is a node.js SystemError.\n * @param err - An object that may contain error information.\n */\nexport function isSystemError(err: unknown): err is NetworkSystemError {\n if (!isObjectWithProperties(err, [\"code\", \"syscall\", \"errno\"])) {\n return false;\n }\n\n if (!isString(err.code) || !isString(err.syscall)) {\n return false;\n }\n\n if (!isString(err.errno) && !isNumber(err.errno)) {\n return false;\n }\n\n return true;\n}\n\n/**\n * @internal\n * Since browser doesn't differentiate between the various kinds of service communication errors,\n * this utility is used to look at the error target to identify such category of errors.\n * For more information refer to - https://html.spec.whatwg.org/multipage/comms.html#feedback-from-the-protocol\n * @param err - object that may contain error information\n */\nfunction isBrowserWebsocketError(err: any): boolean {\n let result: boolean = false;\n if (\n !isNodeLike &&\n self &&\n err.type === \"error\" &&\n err.target instanceof (self as any).WebSocket\n ) {\n result = true;\n }\n return result;\n}\n\n/**\n * @internal\n * Checks whether a object is an ErrorEvent or not. https://html.spec.whatwg.org/multipage/webappapis.html#errorevent\n * @param err - object that may contain error information\n */\nfunction isErrorEvent(err: any): err is { message: string; error: any } {\n return typeof err.error === \"object\" && typeof err.message === \"string\";\n}\n\n/**\n * @internal\n */\nconst rheaPromiseErrors = [\n // OperationTimeoutError occurs when the service fails to respond within a given timeframe.\n \"OperationTimeoutError\",\n\n // InsufficientCreditError occurs when the number of credits available on Rhea link is insufficient.\n \"InsufficientCreditError\",\n\n // Defines the error that occurs when the Sender fails to send a message.\n \"SendOperationFailedError\",\n];\n\n/**\n * Translates the AMQP error received at the protocol layer or a SystemError into a MessagingError.\n * All other errors are returned unaltered.\n *\n * @param err - The amqp error that was received.\n * @returns MessagingError object.\n */\nexport function translate(err: unknown): MessagingError | Error {\n if (!isDefined(err)) {\n return new Error(`Unknown error encountered.`);\n } else if (typeof err !== \"object\") {\n // The error is a scalar type, make it the message of an actual error.\n return new Error(String(err));\n }\n\n const errObj = isErrorEvent(err) ? err.error : err;\n\n // Built-in errors like TypeError and RangeError should not be retryable as these indicate issues\n // with user input and not an issue with the Messaging process.\n if (errObj instanceof TypeError || errObj instanceof RangeError) {\n return errObj;\n }\n\n if (isAmqpError(errObj)) {\n // translate\n const condition = errObj.condition;\n const description = errObj.description!;\n const error = new MessagingError(description);\n if ((errObj as any).stack) error.stack = (errObj as any).stack;\n error.info = errObj.info;\n if (condition) {\n error.code = ConditionErrorNameMapper[condition as keyof typeof ConditionErrorNameMapper];\n }\n if (\n description &&\n (description.includes(\"status-code: 404\") ||\n description.match(/The messaging entity .* could not be found.*/i) !== null)\n ) {\n error.code = \"MessagingEntityNotFoundError\";\n }\n if (error.code && retryableErrors.indexOf(error.code) === -1) {\n // not found\n error.retryable = false;\n }\n return error;\n }\n\n if (errObj instanceof Error && errObj.name === \"MessagingError\") {\n // already translated\n return errObj;\n }\n\n if (isSystemError(errObj)) {\n // translate\n const condition = errObj.code;\n const description = errObj.message;\n const error = new MessagingError(description, errObj);\n let errorType = \"SystemError\";\n if (condition) {\n const amqpErrorCondition =\n SystemErrorConditionMapper[condition as keyof typeof SystemErrorConditionMapper];\n errorType =\n ConditionErrorNameMapper[amqpErrorCondition as keyof typeof ConditionErrorNameMapper];\n }\n if (retryableErrors.indexOf(errorType) === -1) {\n // not found\n error.retryable = false;\n }\n return error;\n }\n\n if (isBrowserWebsocketError(errObj)) {\n // Translate browser communication errors during opening handshake to generic ServiceCommunicationError\n const error = new MessagingError(\"Websocket connection failed.\");\n error.code = ConditionErrorNameMapper[ErrorNameConditionMapper.ServiceCommunicationError];\n error.retryable = false;\n return error;\n }\n\n // Some errors come from rhea-promise and need to be converted to MessagingError.\n // A subset of these are also retryable.\n if (isError(errObj) && rheaPromiseErrors.indexOf(errObj.name) !== -1) {\n const error = new MessagingError(errObj.message, errObj);\n error.code = errObj.name;\n if (error.code && retryableErrors.indexOf(error.code) === -1) {\n // not found\n error.retryable = false;\n }\n return error;\n }\n\n return isError(errObj) ? errObj : new Error(String(errObj));\n}\n\n/**\n * @internal\n */\nfunction isAmqpError(error: any): error is AmqpError {\n return rheaIsAmqpError(error);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts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AAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n/* eslint-disable eqeqeq */\n\nimport { AmqpError, AmqpResponseStatusCode, isAmqpError as rheaIsAmqpError } from \"rhea-promise\";\nimport { isDefined, isError, isNodeLike, isObjectWithProperties } from \"@azure/core-util\";\nimport { isNumber, isString } from \"./util/utils.js\";\n\n/**\n * Maps the conditions to the numeric AMQP Response status codes.\n * @internal\n */\nexport enum ConditionStatusMapper {\n \"com.microsoft:timeout\" = AmqpResponseStatusCode.RequestTimeout,\n \"amqp:not-found\" = AmqpResponseStatusCode.NotFound,\n \"amqp:not-implemented\" = AmqpResponseStatusCode.NotImplemented,\n \"com.microsoft:entity-already-exists\" = AmqpResponseStatusCode.Conflict,\n \"com.microsoft:message-lock-lost\" = AmqpResponseStatusCode.Gone,\n \"com.microsoft:session-lock-lost\" = AmqpResponseStatusCode.Gone,\n \"com.microsoft:no-matching-subscription\" = AmqpResponseStatusCode.InternalServerError,\n \"amqp:link:message-size-exceeded\" = AmqpResponseStatusCode.Forbidden,\n \"com.microsoft:server-busy\" = AmqpResponseStatusCode.ServiceUnavailable,\n \"com.microsoft:argument-error\" = AmqpResponseStatusCode.BadRequest,\n \"com.microsoft:argument-out-of-range\" = AmqpResponseStatusCode.BadRequest,\n \"com.microsoft:store-lock-lost\" = AmqpResponseStatusCode.Gone,\n \"com.microsoft:session-cannot-be-locked\" = AmqpResponseStatusCode.Gone,\n \"com.microsoft:partition-not-owned\" = AmqpResponseStatusCode.Gone,\n \"com.microsoft:entity-disabled\" = AmqpResponseStatusCode.BadRequest,\n \"com.microsoft:publisher-revoked\" = AmqpResponseStatusCode.Unauthorized,\n \"amqp:link:stolen\" = AmqpResponseStatusCode.Gone,\n \"amqp:not-allowed\" = AmqpResponseStatusCode.BadRequest,\n \"amqp:unauthorized-access\" = AmqpResponseStatusCode.Unauthorized,\n \"amqp:resource-limit-exceeded\" = AmqpResponseStatusCode.Forbidden,\n}\n\n/**\n * Maps the amqp error conditions to the Error names.\n */\nexport enum ConditionErrorNameMapper {\n /**\n * Error is thrown when the address is already in use.\n */\n \"com.microsoft:address-already-in-use\" = \"AddressAlreadyInUseError\",\n /**\n * Error is thrown when the store lock is lost.\n */\n \"com.microsoft:store-lock-lost\" = \"StoreLockLostError\",\n /**\n * Error is thrown when a matching subscription is not found.\n */\n \"com.microsoft:no-matching-subscription\" = \"NoMatchingSubscriptionError\",\n /**\n * Error is thrown when an attempt is made to access a partition that is not owned by the\n * requesting entity.\n */\n \"com.microsoft:partition-not-owned\" = \"PartitionNotOwnedError\",\n /**\n * Error is thrown when access to publisher has been revoked.\n */\n \"com.microsoft:publisher-revoked\" = \"PublisherRevokedError\",\n /**\n * Error is thrown when an attempt is made to create an entity that already exists.\n */\n \"com.microsoft:entity-already-exists\" = \"MessagingEntityAlreadyExistsError\",\n /**\n * Error is thrown when trying to access/connect to a disabled messaging entity.\n */\n \"com.microsoft:entity-disabled\" = \"MessagingEntityDisabledError\",\n /**\n * Error is thrown when the lock on the message is lost.\n */\n \"com.microsoft:message-lock-lost\" = \"MessageLockLostError\",\n /**\n * Error is thrown when the lock on the Azure ServiceBus session is lost.\n */\n \"com.microsoft:session-lock-lost\" = \"SessionLockLostError\",\n /**\n * Error is thrown when the Azure ServiceBus session cannot be locked.\n */\n \"com.microsoft:session-cannot-be-locked\" = \"SessionCannotBeLockedError\",\n /**\n * Error is thrown when an internal server error occurred. You may have found a bug?\n */\n \"amqp:internal-error\" = \"InternalServerError\", // Retryable\n /**\n * Error for signaling general communication errors related to messaging operations.\n */\n \"amqp:not-found\" = \"ServiceCommunicationError\",\n /**\n * Error is thrown when the message is not found.\n */\n \"com.microsoft:message-not-found\" = \"MessageNotFoundError\",\n /**\n * Error is thrown when relay is not found.\n */\n \"com.microsoft:relay-not-found\" = \"RelayNotFoundError\",\n /**\n * Error is thrown when a feature is not implemented yet but the placeholder is present.\n */\n \"amqp:not-implemented\" = \"NotImplementedError\",\n /**\n * Error is thrown when an operation is attempted but is not allowed.\n */\n \"amqp:not-allowed\" = \"InvalidOperationError\",\n /**\n * Error is thrown the the Azure EventHub/ServiceBus quota has been exceeded.\n * Quotas are reset periodically, this operation will have to wait until then.\n * The messaging entity has reached its maximum allowable size.\n * This can happen if the maximum number of receivers (which is 5) has already\n * been opened on a per-consumer group level.\n */\n \"amqp:resource-limit-exceeded\" = \"QuotaExceededError\",\n /**\n * Error is thrown when the connection parameters are wrong and the server refused the connection.\n */\n \"amqp:unauthorized-access\" = \"UnauthorizedError\",\n /**\n * Error is thrown when the connection parameters are wrong and the server refused the connection.\n */\n // eslint-disable-next-line @typescript-eslint/no-duplicate-enum-values\n \"com.microsoft:auth-failed\" = \"UnauthorizedError\",\n /**\n * Error is thrown when the service is unavailable. The operation should be retried.\n */\n \"com.microsoft:timeout\" = \"ServiceUnavailableError\", // Retryable\n /**\n * Error is thrown when no new messages are received for the specified time.\n */\n \"com.microsoft:message-wait-timeout\" = \"MessageWaitTimeout\",\n /**\n * Error is thrown when an argument has a value that is out of the admissible range.\n */\n \"com.microsoft:argument-out-of-range\" = \"ArgumentOutOfRangeError\",\n /**\n * Error is thrown when a condition that should have been met in order to execute an operation was not.\n */\n \"amqp:precondition-failed\" = \"PreconditionFailedError\",\n /**\n * Error is thrown when a condition that should have been met in order to execute an operation was not.\n */\n // eslint-disable-next-line @typescript-eslint/no-duplicate-enum-values\n \"com.microsoft:precondition-failed\" = \"PreconditionFailedError\",\n /**\n * Error is thrown when data could not be decoded.\n */\n \"amqp:decode-error\" = \"DecodeError\",\n /**\n * Error is thrown when an invalid field was passed in a frame body, and the operation could not proceed.\n */\n \"amqp:invalid-field\" = \"InvalidFieldError\",\n /**\n * Error is thrown when the client attempted to work with a server entity to which it\n * has no access because another client is working with it.\n */\n \"amqp:resource-locked\" = \"ResourceLockedError\",\n /**\n * Error is thrown when a server entity the client is working with has been deleted.\n */\n \"amqp:resource-deleted\" = \"ResourceDeletedError\",\n /**\n * Error is thrown when the peer sent a frame that is not permitted in the current state.\n */\n \"amqp:illegal-state\" = \"IllegalStateError\",\n /**\n * Error is thrown when the peer cannot send a frame because the smallest encoding of\n * the performative with the currently valid values would be too large to fit within\n * a frame of the agreed maximum frame size.\n */\n \"amqp:frame-size-too-small\" = \"FrameSizeTooSmallError\",\n /**\n * Error is thrown when an operator intervened to detach for some reason.\n */\n \"amqp:link:detach-forced\" = \"DetachForcedError\", // Retryable\n /**\n * Error is thrown when the peer sent more message transfers than currently allowed on the link.\n */\n \"amqp:link:transfer-limit-exceeded\" = \"TransferLimitExceededError\", // Retryable\n /**\n * Error is thrown when the message sent is too large: the maximum size is 256Kb.\n */\n \"amqp:link:message-size-exceeded\" = \"MessageTooLargeError\",\n /**\n * Error is thrown when the address provided cannot be resolved to a terminus at the current container.\n */\n \"amqp:link:redirect\" = \"LinkRedirectError\",\n /**\n * Error is thrown when two or more instances connect to the same partition\n * with different epoch values.\n */\n \"amqp:link:stolen\" = \"ReceiverDisconnectedError\",\n /**\n * Error is thrown when the peer violated incoming window for the session.\n */\n \"amqp:session:window-violation\" = \"SessionWindowViolationError\",\n /**\n * Error is thrown when input was received for a link that was detached with an error.\n */\n \"amqp:session:errant-link\" = \"ErrantLinkError\",\n /**\n * Error is thrown when an attach was received using a handle that is already in use for an attached link.\n */\n \"amqp:session:handle-in-use\" = \"HandleInUseError\",\n /**\n * Error is thrown when a frame (other than attach) was received referencing a handle which is not\n * currently in use of an attached link.\n */\n \"amqp:session:unattached-handle\" = \"UnattachedHandleError\",\n /**\n * Error is thrown when an operator intervened to close the connection for some reason.\n */\n \"amqp:connection:forced\" = \"ConnectionForcedError\", // Retryable\n /**\n * Error is thrown when a valid frame header cannot be formed from the incoming byte stream.\n */\n \"amqp:connection:framing-error\" = \"FramingError\",\n /**\n * Error is thrown when the container is no longer available on the current connection.\n */\n \"amqp:connection:redirect\" = \"ConnectionRedirectError\",\n /**\n * Error is thrown when the server is busy. Callers should wait a while and retry the operation.\n */\n \"com.microsoft:server-busy\" = \"ServerBusyError\", // Retryable\n /**\n * Error is thrown when an incorrect argument was received.\n */\n \"com.microsoft:argument-error\" = \"ArgumentError\",\n /**\n * Error is thrown when server cancels the operation due to an internal issue.\n */\n \"com.microsoft:operation-cancelled\" = \"OperationCancelledError\", // Retryable\n /**\n * Error is thrown when the client sender does not have enough link credits to send the message.\n */\n \"client.sender:not-enough-link-credit\" = \"SenderBusyError\", // Retryable\n /**\n * Error is thrown when the client sender's link isn't ready\n */\n \"client.sender:link-not-ready\" = \"SenderNotReadyError\", // Retryable\n\n /**\n * Error is thrown when a low level system error is thrown by node.js.\n * {@link https://nodejs.org/dist/latest-v8.x/docs/api/all.html#errors_class_system_error}\n */\n \"system:error\" = \"SystemError\",\n}\n\n/**\n * Maps the Error names to the amqp error conditions.\n */\nexport enum ErrorNameConditionMapper {\n /**\n * Error is thrown when the address is already in use.\n */\n AddressAlreadyInUseError = \"com.microsoft:address-already-in-use\",\n /**\n * Error is thrown when the store lock is lost.\n */\n StoreLockLostError = \"com.microsoft:store-lock-lost\",\n /**\n * Error is thrown when a matching subscription is not found.\n */\n NoMatchingSubscriptionError = \"com.microsoft:no-matching-subscription\",\n /**\n * Error is thrown when an attempt is made to access a partition that is not owned by the\n * requesting entity.\n */\n PartitionNotOwnedError = \"com.microsoft:partition-not-owned\",\n /**\n * Error is thrown when access to publisher has been revoked.\n */\n PublisherRevokedError = \"com.microsoft:publisher-revoked\",\n /**\n * Error is thrown when an attempt is made to create an entity that already exists.\n */\n MessagingEntityAlreadyExistsError = \"com.microsoft:entity-already-exists\",\n /**\n * Error is thrown when trying to access/connect to a disabled messaging entity.\n */\n MessagingEntityDisabledError = \"com.microsoft:entity-disabled\",\n /**\n * Error is thrown when the lock on the message is lost.\n */\n MessageLockLostError = \"com.microsoft:message-lock-lost\",\n /**\n * Error is thrown when the lock on the Azure ServiceBus session is lost.\n */\n SessionLockLostError = \"com.microsoft:session-lock-lost\",\n /**\n * Error is thrown when the Azure ServiceBus session cannot be locked.\n */\n SessionCannotBeLockedError = \"com.microsoft:session-cannot-be-locked\",\n /**\n * Error is thrown when an internal server error occurred. You may have found a bug?\n */\n InternalServerError = \"amqp:internal-error\", // Retryable\n /**\n * Error for signaling general communication errors related to messaging operations.\n */\n ServiceCommunicationError = \"amqp:not-found\",\n /**\n * Error is thrown when message is not found.\n */\n MessageNotFoundError = \"com.microsoft:message-not-found\",\n /**\n * Error is thrown when relay is not found.\n */\n RelayNotFoundError = \"com.microsoft:relay-not-found\",\n /**\n * Error is thrown when a feature is not implemented yet but the placeholder is present.\n */\n NotImplementedError = \"amqp:not-implemented\",\n /**\n * Error is thrown when an operation is attempted but is not allowed.\n */\n InvalidOperationError = \"amqp:not-allowed\",\n /**\n * Error is thrown the the Azure EventHub/ServiceBus quota has been exceeded.\n * Quotas are reset periodically, this operation will have to wait until then.\n * The messaging entity has reached its maximum allowable size.\n * This can happen if the maximum number of receivers (which is 5) has already\n * been opened on a per-consumer group level.\n */\n QuotaExceededError = \"amqp:resource-limit-exceeded\",\n /**\n * Error is thrown when the connection parameters are wrong and the server refused the connection.\n */\n UnauthorizedError = \"amqp:unauthorized-access\",\n /**\n * Error is thrown when the service is unavailable. The operation should be retried.\n */\n ServiceUnavailableError = \"com.microsoft:timeout\", // Retryable\n /**\n * Error is thrown when no new messages are received for the specified time.\n */\n MessageWaitTimeout = \"com.microsoft:message-wait-timeout\",\n /**\n * Error is thrown when an argument has a value that is out of the admissible range.\n */\n ArgumentOutOfRangeError = \"com.microsoft:argument-out-of-range\",\n /**\n * Error is thrown when a condition that should have been met in order to execute an operation was not.\n */\n PreconditionFailedError = \"amqp:precondition-failed\",\n /**\n * Error is thrown when data could not be decoded.\n */\n DecodeError = \"amqp:decode-error\",\n /**\n * Error is thrown when an invalid field was passed in a frame body, and the operation could not proceed.\n */\n InvalidFieldError = \"amqp:invalid-field\",\n /**\n * Error is thrown when the client attempted to work with a server entity to which it\n * has no access because another client is working with it.\n */\n ResourceLockedError = \"amqp:resource-locked\",\n /**\n * Error is thrown when a server entity the client is working with has been deleted.\n */\n ResourceDeletedError = \"amqp:resource-deleted\",\n /**\n * Error is thrown when the peer sent a frame that is not permitted in the current state.\n */\n IllegalStateError = \"amqp:illegal-state\",\n /**\n * Error is thrown when the peer cannot send a frame because the smallest encoding of\n * the performative with the currently valid values would be too large to fit within\n * a frame of the agreed maximum frame size.\n */\n FrameSizeTooSmallError = \"amqp:frame-size-too-small\",\n /**\n * Error is thrown when an operator intervened to detach for some reason.\n */\n DetachForcedError = \"amqp:link:detach-forced\", // Retryable\n /**\n * Error is thrown when the peer sent more message transfers than currently allowed on the link.\n */\n TransferLimitExceededError = \"amqp:link:transfer-limit-exceeded\", // Retryable\n /**\n * Error is thrown when the message sent is too large: the maximum size is 256Kb.\n */\n MessageTooLargeError = \"amqp:link:message-size-exceeded\",\n /**\n * Error is thrown when the address provided cannot be resolved to a terminus at the current container.\n */\n LinkRedirectError = \"amqp:link:redirect\",\n /**\n * Error is thrown when two or more instances connect to the same partition\n * with different epoch values.\n */\n ReceiverDisconnectedError = \"amqp:link:stolen\",\n /**\n * Error is thrown when the peer violated incoming window for the session.\n */\n SessionWindowViolationError = \"amqp:session:window-violation\",\n /**\n * Error is thrown when input was received for a link that was detached with an error.\n */\n ErrantLinkError = \"amqp:session:errant-link\",\n /**\n * Error is thrown when an attach was received using a handle that is already in use for an attached link.\n */\n HandleInUseError = \"amqp:session:handle-in-use\",\n /**\n * Error is thrown when a frame (other than attach) was received referencing a handle which is not\n * currently in use of an attached link.\n */\n UnattachedHandleError = \"amqp:session:unattached-handle\",\n /**\n * Error is thrown when an operator intervened to close the connection for some reason.\n */\n ConnectionForcedError = \"amqp:connection:forced\", // Retryable\n /**\n * Error is thrown when a valid frame header cannot be formed from the incoming byte stream.\n */\n FramingError = \"amqp:connection:framing-error\",\n /**\n * Error is thrown when the container is no longer available on the current connection.\n */\n ConnectionRedirectError = \"amqp:connection:redirect\",\n /**\n * Error is thrown when the server is busy. Callers should wait a while and retry the operation.\n */\n ServerBusyError = \"com.microsoft:server-busy\", // Retryable\n /**\n * Error is thrown when an incorrect argument was received.\n */\n ArgumentError = \"com.microsoft:argument-error\",\n /**\n * Error is thrown when server cancels the operation due to an internal issue.\n */\n OperationCancelledError = \"com.microsoft:operation-cancelled\", // Retryable\n /**\n * Error is thrown when the client sender does not have enough link credits to send the message.\n */\n SenderBusyError = \"client.sender:not-enough-link-credit\", // Retryable\n /**\n * Error is thrown when the client sender's link isn't ready\n */\n SenderNotReadyError = \"client.sender:link-not-ready\", // Retryable\n /**\n * Error is thrown when a low level system error is thrown by node.js.\n * {@link https://nodejs.org/api/errors.html#errors_class_systemerror}\n */\n SystemError = \"system:error\",\n}\n\n/**\n * Describes the fields on a Node.js SystemError.\n * Omits fields that are not related to network calls (e.g. file system calls).\n * See https://nodejs.org/dist/latest-v12.x/docs/api/errors.html#errors_class_systemerror\n */\nexport interface NetworkSystemError {\n address?: string;\n code: string;\n errno: string | number;\n info?: any;\n message: string;\n name: string;\n port?: number;\n stack: string;\n syscall: string;\n}\n\n/**\n * @internal\n */\nconst systemErrorFieldsToCopy: (keyof Omit<NetworkSystemError, \"name\" | \"message\">)[] = [\n \"address\",\n \"code\",\n \"errno\",\n \"info\",\n \"port\",\n \"stack\",\n \"syscall\",\n];\n\n/**\n * Determines if an error is a MessagingError.\n *\n * @param error - An error that can either be an Error or a MessagingError.\n */\nexport function isMessagingError(error: Error | MessagingError): error is MessagingError {\n return error.name === \"MessagingError\";\n}\n\n/**\n * Describes the base class for Messaging Error.\n */\nexport class MessagingError extends Error {\n /**\n * Address to which the network connection failed.\n * Only present if the `MessagingError` was instantiated with a Node.js `SystemError`.\n */\n address?: string;\n /**\n * A string label that identifies the error.\n */\n code?: string;\n /**\n * System-provided error number.\n * Only present if the `MessagingError` was instantiated with a Node.js `SystemError`.\n */\n errno?: number | string;\n /**\n * The error name. Default value: \"MessagingError\".\n */\n name: string = \"MessagingError\";\n /**\n * The unavailable network connection port.\n * Only present if the `MessagingError` was instantiated with a Node.js `SystemError`.\n */\n port?: number;\n /**\n * Name of the system call that triggered the error.\n * Only present if the `MessagingError` was instantiated with a Node.js `SystemError`.\n */\n syscall?: string;\n /**\n *\n * Describes whether the error is retryable. Default: true.\n */\n retryable: boolean = true;\n /**\n * Extra details about the error.\n */\n info?: any;\n /**\n * @param message - The error message that provides more information about the error.\n * @param originalError - An error whose properties will be copied to the MessagingError if the\n * property matches one found on the Node.js `SystemError`.\n */\n constructor(message: string, originalError?: Error) {\n super(message);\n\n if (!originalError) {\n return;\n }\n\n // copy properties from system error\n for (const propName of systemErrorFieldsToCopy) {\n if ((originalError as NetworkSystemError)[propName] != undefined) {\n this[propName] = (originalError as NetworkSystemError)[propName];\n }\n }\n }\n}\n\n/**\n * Provides a list of retryable AMQP errors.\n * \"InternalServerError\", \"ServerBusyError\", \"ServiceUnavailableError\", \"OperationCancelledError\",\n * \"SenderBusyError\", \"SenderNotReadyError\", \"MessagingError\", \"DetachForcedError\", \"ConnectionForcedError\",\n * \"TransferLimitExceededError\"\n */\nexport const retryableErrors: string[] = [\n \"InternalServerError\",\n \"ServerBusyError\",\n \"ServiceUnavailableError\",\n \"OperationCancelledError\",\n\n // The service may throw UnauthorizedError if credentials have been rotated.\n // Attempt to retry in case the user has also rotated their credentials.\n \"UnauthorizedError\",\n\n // OperationTimeoutError occurs when the service fails to respond within a given timeframe.\n // Since reasons for such failures can be transient, this is treated as a retryable error.\n \"OperationTimeoutError\",\n\n \"SenderBusyError\",\n \"SenderNotReadyError\",\n \"MessagingError\",\n \"DetachForcedError\",\n \"ConnectionForcedError\",\n \"TransferLimitExceededError\",\n\n // InsufficientCreditError occurs when the number of credits available on Rhea link is insufficient.\n // Since reasons for such shortage can be transient such as for pending delivery of messages, this is treated as a retryable error.\n \"InsufficientCreditError\",\n];\n\n/**\n * Maps some SystemErrors to amqp error conditions\n */\nexport enum SystemErrorConditionMapper {\n /* eslint-disable @typescript-eslint/no-duplicate-enum-values */\n ENOTFOUND = \"amqp:not-found\",\n EBUSY = \"com.microsoft:server-busy\",\n ECONNREFUSED = \"amqp:connection:forced\",\n ETIMEDOUT = \"com.microsoft:timeout\",\n ECONNRESET = \"com.microsoft:timeout\",\n ENETDOWN = \"com.microsoft:timeout\",\n EHOSTDOWN = \"com.microsoft:timeout\",\n ENETRESET = \"com.microsoft:timeout\",\n ENETUNREACH = \"com.microsoft:timeout\",\n ENONET = \"com.microsoft:timeout\",\n /* eslint-enable @typescript-eslint/no-duplicate-enum-values */\n}\n\n/**\n * Checks whether the provided error is a node.js SystemError.\n * @param err - An object that may contain error information.\n */\nexport function isSystemError(err: unknown): err is NetworkSystemError {\n if (!isObjectWithProperties(err, [\"code\", \"syscall\", \"errno\"])) {\n return false;\n }\n\n if (!isString(err.code) || !isString(err.syscall)) {\n return false;\n }\n\n if (!isString(err.errno) && !isNumber(err.errno)) {\n return false;\n }\n\n return true;\n}\n\n/**\n * @internal\n * Since browser doesn't differentiate between the various kinds of service communication errors,\n * this utility is used to look at the error target to identify such category of errors.\n * For more information refer to - https://html.spec.whatwg.org/multipage/comms.html#feedback-from-the-protocol\n * @param err - object that may contain error information\n */\nfunction isBrowserWebsocketError(err: any): boolean {\n let result: boolean = false;\n if (\n !isNodeLike &&\n self &&\n err.type === \"error\" &&\n err.target instanceof (self as any).WebSocket\n ) {\n result = true;\n }\n return result;\n}\n\n/**\n * @internal\n * Checks whether a object is an ErrorEvent or not. https://html.spec.whatwg.org/multipage/webappapis.html#errorevent\n * @param err - object that may contain error information\n */\nfunction isErrorEvent(err: any): err is { message: string; error: any } {\n return typeof err.error === \"object\" && typeof err.message === \"string\";\n}\n\n/**\n * @internal\n */\nconst rheaPromiseErrors = [\n // OperationTimeoutError occurs when the service fails to respond within a given timeframe.\n \"OperationTimeoutError\",\n\n // InsufficientCreditError occurs when the number of credits available on Rhea link is insufficient.\n \"InsufficientCreditError\",\n\n // Defines the error that occurs when the Sender fails to send a message.\n \"SendOperationFailedError\",\n];\n\n/**\n * Translates the AMQP error received at the protocol layer or a SystemError into a MessagingError.\n * All other errors are returned unaltered.\n *\n * @param err - The amqp error that was received.\n * @returns MessagingError object.\n */\nexport function translate(err: unknown): MessagingError | Error {\n if (!isDefined(err)) {\n return new Error(`Unknown error encountered.`);\n } else if (typeof err !== \"object\") {\n // The error is a scalar type, make it the message of an actual error.\n return new Error(String(err));\n }\n\n const errObj = isErrorEvent(err) ? err.error : err;\n\n // Built-in errors like TypeError and RangeError should not be retryable as these indicate issues\n // with user input and not an issue with the Messaging process.\n if (errObj instanceof TypeError || errObj instanceof RangeError) {\n return errObj;\n }\n\n if (isAmqpError(errObj)) {\n // translate\n const condition = errObj.condition;\n const description = errObj.description!;\n const error = new MessagingError(description);\n if ((errObj as any).stack) error.stack = (errObj as any).stack;\n error.info = errObj.info;\n if (condition) {\n error.code = ConditionErrorNameMapper[condition as keyof typeof ConditionErrorNameMapper];\n }\n if (\n description &&\n (description.includes(\"status-code: 404\") ||\n description.match(/The messaging entity .* could not be found.*/i) !== null)\n ) {\n error.code = \"MessagingEntityNotFoundError\";\n }\n if (error.code && retryableErrors.indexOf(error.code) === -1) {\n // not found\n error.retryable = false;\n }\n return error;\n }\n\n if (errObj instanceof Error && errObj.name === \"MessagingError\") {\n // already translated\n return errObj;\n }\n\n if (isSystemError(errObj)) {\n // translate\n const condition = errObj.code;\n const description = errObj.message;\n const error = new MessagingError(description, errObj);\n let errorType = \"SystemError\";\n if (condition) {\n const amqpErrorCondition =\n SystemErrorConditionMapper[condition as keyof typeof SystemErrorConditionMapper];\n errorType =\n ConditionErrorNameMapper[amqpErrorCondition as keyof typeof ConditionErrorNameMapper];\n }\n if (retryableErrors.indexOf(errorType) === -1) {\n // not found\n error.retryable = false;\n }\n return error;\n }\n\n if (isBrowserWebsocketError(errObj)) {\n // Translate browser communication errors during opening handshake to generic ServiceCommunicationError\n const error = new MessagingError(\"Websocket connection failed.\");\n error.code = ConditionErrorNameMapper[ErrorNameConditionMapper.ServiceCommunicationError];\n error.retryable = false;\n return error;\n }\n\n // Some errors come from rhea-promise and need to be converted to MessagingError.\n // A subset of these are also retryable.\n if (isError(errObj) && rheaPromiseErrors.indexOf(errObj.name) !== -1) {\n const error = new MessagingError(errObj.message, errObj);\n error.code = errObj.name;\n if (error.code && retryableErrors.indexOf(error.code) === -1) {\n // not found\n error.retryable = false;\n }\n return error;\n }\n\n return isError(errObj) ? errObj : new Error(String(errObj));\n}\n\n/**\n * @internal\n */\nfunction isAmqpError(error: any): error is AmqpError {\n return rheaIsAmqpError(error);\n}\n"]}
|
package/dist/commonjs/index.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AACnF,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC7F,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACnG,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAClD,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AACtE,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,EACL,qBAAqB,EACrB,oBAAoB,EACpB,qCAAqC,GACtC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,wBAAwB,EACxB,wBAAwB,EACxB,SAAS,EACT,eAAe,EACf,aAAa,EACb,0BAA0B,EAC1B,kBAAkB,GACnB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,KAAK,EACL,qBAAqB,EACrB,sBAAsB,EACtB,YAAY,EACZ,gBAAgB,GACjB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,cAAc,gBAAgB,CAAC;AAC/B,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC"}
|
package/dist/commonjs/log.js
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
// Copyright (c) Microsoft Corporation.
|
|
3
3
|
// Licensed under the MIT license.
|
|
4
4
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
-
exports.
|
|
5
|
+
exports.logger = void 0;
|
|
6
|
+
exports.logErrorStackTrace = logErrorStackTrace;
|
|
6
7
|
const logger_1 = require("@azure/logger");
|
|
7
8
|
const core_util_1 = require("@azure/core-util");
|
|
8
9
|
/**
|
|
@@ -20,5 +21,4 @@ function logErrorStackTrace(error) {
|
|
|
20
21
|
exports.logger.verbose(error.stack);
|
|
21
22
|
}
|
|
22
23
|
}
|
|
23
|
-
exports.logErrorStackTrace = logErrorStackTrace;
|
|
24
24
|
//# sourceMappingURL=log.js.map
|
package/dist/commonjs/log.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"log.js","sourceRoot":"","sources":["../../src/log.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;
|
|
1
|
+
{"version":3,"file":"log.js","sourceRoot":"","sources":["../../src/log.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAgBlC,gDAIC;AAlBD,0CAAmD;AACnD,gDAA0D;AAE1D;;;GAGG;AACU,QAAA,MAAM,GAAG,IAAA,2BAAkB,EAAC,WAAW,CAAC,CAAC;AAEtD;;;;GAIG;AACH,SAAgB,kBAAkB,CAAC,KAAc;IAC/C,IAAI,IAAA,kCAAsB,EAAC,KAAK,EAAE,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC;QAC7C,cAAM,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;AACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { createClientLogger } from \"@azure/logger\";\nimport { isObjectWithProperties } from \"@azure/core-util\";\n\n/**\n * The \\@azure/logger configuration for this package.\n * This will output logs using the `azure:event-hubs` namespace prefix.\n */\nexport const logger = createClientLogger(\"core-amqp\");\n\n/**\n * Logs the error's stack trace to \"verbose\" if a stack trace is available.\n * @param error - Error containing a stack trace.\n * @internal\n */\nexport function logErrorStackTrace(error: unknown): void {\n if (isObjectWithProperties(error, [\"stack\"])) {\n logger.verbose(error.stack);\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messageProperties.d.ts","sourceRoot":"","sources":["../../src/messageProperties.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"messageProperties.d.ts","sourceRoot":"","sources":["../../src/messageProperties.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,iBAAiB,IAAI,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAG1E;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IACrC;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;OAEG;IACH,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IACzC;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB;;OAEG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;OAEG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CAKlB;AAED;;GAEG;AAEH,eAAO,MAAM,qBAAqB;IAChC;;;;OAIG;mCAC4B,qBAAqB,GAAG,qBAAqB;IA8C5E;;;;OAIG;qCAC8B,qBAAqB,GAAG,qBAAqB;CA6C/E,CAAC"}
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
// Copyright (c) Microsoft Corporation.
|
|
3
3
|
// Licensed under the MIT license.
|
|
4
4
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
-
exports.
|
|
5
|
+
exports.getCodeDescriptionAndError = exports.RequestResponseLink = void 0;
|
|
6
|
+
exports.onMessageReceived = onMessageReceived;
|
|
6
7
|
const abort_controller_1 = require("@azure/abort-controller");
|
|
7
8
|
const errors_js_1 = require("./errors.js");
|
|
8
9
|
const rhea_promise_1 = require("rhea-promise");
|
|
@@ -232,7 +233,6 @@ function onMessageReceived(context, connectionId, responsesMap) {
|
|
|
232
233
|
(0, log_js_1.logErrorStackTrace)(error);
|
|
233
234
|
return promise.reject(error);
|
|
234
235
|
}
|
|
235
|
-
exports.onMessageReceived = onMessageReceived;
|
|
236
236
|
function onSenderError(context, connectionId, responsesMap) {
|
|
237
237
|
if (context.sender) {
|
|
238
238
|
for (const [key, promise] of responsesMap.entries()) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"requestResponseLink.js","sourceRoot":"","sources":["../../src/requestResponseLink.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAElC,8DAAsE;AACtE,2CAA+D;AAC/D,+CAasB;AACtB,sDAAsE;AACtE,qCA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EAAE,CAAC;YACvC,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACvC,CAAC;QACD,YAAY,CAAC,KAAK,EAAE,CAAC;IACvB,CAAC;AACH,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { AbortError, AbortSignalLike } from \"@azure/abort-controller\";\nimport { ConditionStatusMapper, translate } from \"./errors.js\";\nimport {\n Connection,\n EventContext,\n Receiver,\n ReceiverEvents,\n ReceiverOptions,\n ReqResLink,\n Message as RheaMessage,\n Sender,\n SenderEvents,\n SenderOptions,\n Session,\n generate_uuid,\n} from \"rhea-promise\";\nimport { Constants, StandardAbortMessage } from \"./util/constants.js\";\nimport { logErrorStackTrace, logger } from \"./log.js\";\nimport { isDefined } from \"@azure/core-util\";\n\n/**\n * Describes the options that can be specified while sending a request.\n */\nexport interface SendRequestOptions {\n /**\n * Cancels the operation.\n */\n abortSignal?: AbortSignalLike;\n /**\n * Max time to wait for the operation to complete.\n * Default: `60000 milliseconds`.\n */\n timeoutInMs?: number;\n /**\n * Name of the request being performed.\n */\n requestName?: string;\n}\n\n/**\n * @internal\n */\nexport interface DeferredPromiseWithCallback {\n resolve: (value?: any) => void;\n reject: (reason?: any) => void;\n /**\n * To be called before resolving or rejecting the deferred promise\n */\n cleanupBeforeResolveOrReject: () => void;\n}\n\n/**\n * Describes an amqp request(sender)-response(receiver) link that is created over an amqp session.\n */\nexport class RequestResponseLink implements ReqResLink {\n /**\n * @param session - The amqp session.\n * @param sender - The amqp sender link.\n * @param receiver - The amqp receiver link.\n */\n constructor(\n public session: Session,\n public sender: Sender,\n public receiver: Receiver,\n ) {\n this.session = session;\n this.sender = sender;\n this.receiver = receiver;\n this.receiver.on(ReceiverEvents.message, (context) => {\n onMessageReceived(context, this.connection.id, this._responsesMap);\n });\n this.sender.on(SenderEvents.senderError, (context) => {\n onSenderError(context, this.connection.id, this._responsesMap);\n });\n }\n\n /**\n * Maintains a map of responses that\n * are being actively returned. It acts as a store for correlating the responses received for\n * the send requests.\n */\n private _responsesMap: Map<string, DeferredPromiseWithCallback> = new Map<\n string,\n DeferredPromiseWithCallback\n >();\n\n /**\n * Provides the underlying amqp connection object.\n * @returns Connection.\n */\n get connection(): Connection {\n return this.session.connection;\n }\n\n /**\n * Indicates whether the session and the sender and receiver links are all open or closed.\n * @returns boolean - `true` - `open`, `false` - `closed`.\n */\n isOpen(): boolean {\n return this.session.isOpen() && this.sender.isOpen() && this.receiver.isOpen();\n }\n\n /**\n * Sends the given request message and returns the received response. If the operation is not\n * completed in the provided timeout in milliseconds `default: 60000`, then `OperationTimeoutError` is thrown.\n *\n * @param request - The AMQP (request) message.\n * @param options - Options that can be provided while sending a request.\n * @returns Promise<Message> The AMQP (response) message.\n */\n sendRequest(request: RheaMessage, options: SendRequestOptions = {}): Promise<RheaMessage> {\n const timeoutInMs = options.timeoutInMs || Constants.defaultOperationTimeoutInMs;\n\n const aborter: AbortSignalLike | undefined = options.abortSignal;\n\n // If message_id is not already set on the request, set it to a unique value\n // This helps in determining the right response for current request among multiple incoming messages\n if (!request.message_id) {\n request.message_id = generate_uuid();\n }\n\n return new Promise<RheaMessage>((resolve: any, reject: any) => {\n let timer: ReturnType<typeof setTimeout> | undefined = undefined;\n\n const rejectOnAbort = (): void => {\n this._responsesMap.delete(request.message_id as string);\n const address = this.receiver.address || \"address\";\n const requestName = options.requestName;\n const desc: string =\n `[${this.connection.id}] The request \"${requestName}\" ` +\n `to \"${address}\" has been cancelled by the user.`;\n // Cancellation is a user-intended action, so log to info instead of warning.\n logger.info(desc);\n const error = new AbortError(StandardAbortMessage);\n\n reject(error);\n };\n\n const onAbort = (): void => {\n // safe to clear the timeout if it hasn't already occurred.\n if (isDefined(timer)) {\n clearTimeout(timer);\n }\n aborter!.removeEventListener(\"abort\", onAbort);\n\n rejectOnAbort();\n };\n\n if (aborter) {\n // the aborter may have been triggered between request attempts\n // so check if it was triggered and reject if needed.\n if (aborter.aborted) {\n return rejectOnAbort();\n }\n aborter.addEventListener(\"abort\", onAbort);\n }\n\n timer = setTimeout(() => {\n this._responsesMap.delete(request.message_id as string);\n if (aborter) {\n aborter.removeEventListener(\"abort\", onAbort);\n }\n const address = this.receiver?.address || \"address\";\n const desc: string =\n `The request with message_id \"${request.message_id}\" to \"${address}\" ` +\n `endpoint timed out. Please try again later.`;\n const e: Error = {\n name: \"OperationTimeoutError\",\n message: desc,\n };\n return reject(translate(e));\n }, timeoutInMs);\n\n this._responsesMap.set(request.message_id as string, {\n resolve: resolve,\n reject: reject,\n cleanupBeforeResolveOrReject: () => {\n if (aborter) aborter.removeEventListener(\"abort\", onAbort);\n if (isDefined(timer)) {\n clearTimeout(timer);\n }\n },\n });\n\n logger.verbose(\n \"[%s] %s request sent: %O\",\n this.connection.id,\n request.to || \"$management\",\n request,\n );\n this.sender.send(request);\n });\n }\n\n /**\n * Closes the sender, receiver link and the underlying session.\n * @returns Promise<void>\n */\n async close(): Promise<void> {\n await this.sender.close({ closeSession: false });\n await this.receiver.close({ closeSession: false });\n await this.session.close();\n }\n\n /**\n * Removes the sender, receiver link and it's underlying session.\n * @returns void\n */\n remove(): void {\n this.sender.remove();\n this.receiver.remove();\n this.session.remove();\n }\n\n /**\n * Creates an amqp request/response link.\n *\n * @param connection - The amqp connection.\n * @param senderOptions - Options that must be provided to create the sender link.\n * @param receiverOptions - Options that must be provided to create the receiver link.\n * @param createOptions - Optional parameters that can be used to affect this method's behavior.\n * For example, `abortSignal` can be passed to allow cancelling an in-progress `create` invocation.\n * @returns Promise<RequestResponseLink>\n */\n static async create(\n connection: Connection,\n senderOptions: SenderOptions,\n receiverOptions: ReceiverOptions,\n createOptions: { abortSignal?: AbortSignalLike } = {},\n ): Promise<RequestResponseLink> {\n const { abortSignal } = createOptions;\n const session = await connection.createSession({ abortSignal });\n const sender = await session.createSender({ ...senderOptions, abortSignal });\n const receiver = await session.createReceiver({ ...receiverOptions, abortSignal });\n logger.verbose(\n \"[%s] Successfully created the sender and receiver links on the same session.\",\n connection.id,\n );\n return new RequestResponseLink(session, sender, receiver);\n }\n}\n/**\n * @internal\n *\n * Type used in getCodeDescriptionAndError to get the normalized info from the responses emitted by EventHubs and ServiceBus.\n */\ntype NormalizedInfo = {\n statusCode: number;\n statusDescription: string;\n errorCondition: string;\n};\n\n/**\n * @internal\n *\n * Handle different variations of property names in responses emitted by EventHubs and ServiceBus.\n */\nexport const getCodeDescriptionAndError = (\n props: { [key: string]: string | number | undefined } = {},\n): NormalizedInfo => {\n return {\n statusCode: (props[Constants.statusCode] || props.statusCode) as number,\n statusDescription: (props[Constants.statusDescription] || props.statusDescription) as string,\n errorCondition: (props[Constants.errorCondition] || props.errorCondition) as string,\n };\n};\n\n/**\n * This is used as the onMessage handler for the \"message\" event on the receiver.\n *\n * (This is inspired from the message settlement sequence in service-bus SDK which\n * relies on a single listener for settled event for all the messages.)\n * The sequence is as follows:\n * 1. User calls `await RequestResponseLink.sendRequest()`\n * 2. This creates a `Promise` that gets stored in the _responsesMap\n * 3. When the service acknowledges the response, this method gets called for that request.\n * 4. We resolve() the promise from the _responsesMap with the message.\n * 5. User's code after the sendRequest continues.\n *\n * @internal\n */\nexport function onMessageReceived(\n context: Pick<EventContext, \"message\">,\n connectionId: string,\n responsesMap: Map<string, DeferredPromiseWithCallback>,\n): void {\n const message = context.message;\n if (!message) {\n logger.verbose(\n `[${connectionId}] \"message\" property on the EventContext is \"undefined\" which is unexpected, ` +\n `returning from the \"onMessageReceived\" handler without resolving or rejecting the promise ` +\n `upon encountering the message event.`,\n );\n return;\n }\n\n const responseCorrelationId = message.correlation_id;\n if (!responsesMap.has(responseCorrelationId as string)) {\n logger.verbose(\n `[${connectionId}] correlationId \"${responseCorrelationId}\" property on the response does not match with ` +\n `any of the \"request-id\"s in the map, returning from the \"onMessageReceived\" handler without resolving ` +\n `or rejecting the promise upon encountering the message event.`,\n );\n return;\n }\n\n const promise = responsesMap.get(responseCorrelationId as string) as DeferredPromiseWithCallback;\n promise.cleanupBeforeResolveOrReject();\n\n const deleteResult = responsesMap.delete(responseCorrelationId as string);\n logger.verbose(\n `[${connectionId}] Successfully deleted the response with id ${responseCorrelationId} from the map. ` +\n `Delete result - ${deleteResult}`,\n );\n\n const info = getCodeDescriptionAndError(message.application_properties);\n let error;\n if (!info.statusCode) {\n error = new Error(\n `[${connectionId}] No statusCode in the \"application_properties\" in the returned response with correlation-id: ${responseCorrelationId}`,\n );\n }\n if (info.statusCode > 199 && info.statusCode < 300) {\n logger.verbose(\n `[${connectionId}] Resolving the response with correlation-id: ${responseCorrelationId}`,\n );\n return promise.resolve(message);\n }\n if (!error) {\n const condition =\n info.errorCondition || ConditionStatusMapper[info.statusCode] || \"amqp:internal-error\";\n error = translate({\n condition: condition,\n description: info.statusDescription,\n });\n logger.warning(`${error?.name}: ${error?.message}`);\n }\n logErrorStackTrace(error);\n return promise.reject(error);\n}\n\nfunction onSenderError(\n context: Pick<EventContext, \"sender\">,\n connectionId: string,\n responsesMap: Map<string, DeferredPromiseWithCallback>,\n): void {\n if (context.sender) {\n for (const [key, promise] of responsesMap.entries()) {\n logger.verbose(\n `[${connectionId}] Sender closed due to error when sending request with message_id \"${key}\"`,\n );\n promise.cleanupBeforeResolveOrReject();\n promise.reject(context.sender.error);\n }\n responsesMap.clear();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"requestResponseLink.js","sourceRoot":"","sources":["../../src/requestResponseLink.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AA2RlC,8CA0DC;AAnVD,8DAAsE;AACtE,2CAA+D;AAC/D,+CAasB;AACtB,sDAAsE;AACtE,qCAAsD;AACtD,gDAA6C;AAiC7C;;GAEG;AACH,MAAa,mBAAmB;IAC9B;;;;OAIG;IACH,YACS,OAAgB,EAChB,MAAc,EACd,QAAkB;QAFlB,YAAO,GAAP,OAAO,CAAS;QAChB,WAAM,GAAN,MAAM,CAAQ;QACd,aAAQ,GAAR,QAAQ,CAAU;Q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alLike } from \"@azure/abort-controller\";\nimport { ConditionStatusMapper, translate } from \"./errors.js\";\nimport {\n Connection,\n EventContext,\n Receiver,\n ReceiverEvents,\n ReceiverOptions,\n ReqResLink,\n Message as RheaMessage,\n Sender,\n SenderEvents,\n SenderOptions,\n Session,\n generate_uuid,\n} from \"rhea-promise\";\nimport { Constants, StandardAbortMessage } from \"./util/constants.js\";\nimport { logErrorStackTrace, logger } from \"./log.js\";\nimport { isDefined } from \"@azure/core-util\";\n\n/**\n * Describes the options that can be specified while sending a request.\n */\nexport interface SendRequestOptions {\n /**\n * Cancels the operation.\n */\n abortSignal?: AbortSignalLike;\n /**\n * Max time to wait for the operation to complete.\n * Default: `60000 milliseconds`.\n */\n timeoutInMs?: number;\n /**\n * Name of the request being performed.\n */\n requestName?: string;\n}\n\n/**\n * @internal\n */\nexport interface DeferredPromiseWithCallback {\n resolve: (value?: any) => void;\n reject: (reason?: any) => void;\n /**\n * To be called before resolving or rejecting the deferred promise\n */\n cleanupBeforeResolveOrReject: () => void;\n}\n\n/**\n * Describes an amqp request(sender)-response(receiver) link that is created over an amqp session.\n */\nexport class RequestResponseLink implements ReqResLink {\n /**\n * @param session - The amqp session.\n * @param sender - The amqp sender link.\n * @param receiver - The amqp receiver link.\n */\n constructor(\n public session: Session,\n public sender: Sender,\n public receiver: Receiver,\n ) {\n this.session = session;\n this.sender = sender;\n this.receiver = receiver;\n this.receiver.on(ReceiverEvents.message, (context) => {\n onMessageReceived(context, this.connection.id, this._responsesMap);\n });\n this.sender.on(SenderEvents.senderError, (context) => {\n onSenderError(context, this.connection.id, this._responsesMap);\n });\n }\n\n /**\n * Maintains a map of responses that\n * are being actively returned. It acts as a store for correlating the responses received for\n * the send requests.\n */\n private _responsesMap: Map<string, DeferredPromiseWithCallback> = new Map<\n string,\n DeferredPromiseWithCallback\n >();\n\n /**\n * Provides the underlying amqp connection object.\n * @returns Connection.\n */\n get connection(): Connection {\n return this.session.connection;\n }\n\n /**\n * Indicates whether the session and the sender and receiver links are all open or closed.\n * @returns boolean - `true` - `open`, `false` - `closed`.\n */\n isOpen(): boolean {\n return this.session.isOpen() && this.sender.isOpen() && this.receiver.isOpen();\n }\n\n /**\n * Sends the given request message and returns the received response. If the operation is not\n * completed in the provided timeout in milliseconds `default: 60000`, then `OperationTimeoutError` is thrown.\n *\n * @param request - The AMQP (request) message.\n * @param options - Options that can be provided while sending a request.\n * @returns Promise<Message> The AMQP (response) message.\n */\n sendRequest(request: RheaMessage, options: SendRequestOptions = {}): Promise<RheaMessage> {\n const timeoutInMs = options.timeoutInMs || Constants.defaultOperationTimeoutInMs;\n\n const aborter: AbortSignalLike | undefined = options.abortSignal;\n\n // If message_id is not already set on the request, set it to a unique value\n // This helps in determining the right response for current request among multiple incoming messages\n if (!request.message_id) {\n request.message_id = generate_uuid();\n }\n\n return new Promise<RheaMessage>((resolve: any, reject: any) => {\n let timer: ReturnType<typeof setTimeout> | undefined = undefined;\n\n const rejectOnAbort = (): void => {\n this._responsesMap.delete(request.message_id as string);\n const address = this.receiver.address || \"address\";\n const requestName = options.requestName;\n const desc: string =\n `[${this.connection.id}] The request \"${requestName}\" ` +\n `to \"${address}\" has been cancelled by the user.`;\n // Cancellation is a user-intended action, so log to info instead of warning.\n logger.info(desc);\n const error = new AbortError(StandardAbortMessage);\n\n reject(error);\n };\n\n const onAbort = (): void => {\n // safe to clear the timeout if it hasn't already occurred.\n if (isDefined(timer)) {\n clearTimeout(timer);\n }\n aborter!.removeEventListener(\"abort\", onAbort);\n\n rejectOnAbort();\n };\n\n if (aborter) {\n // the aborter may have been triggered between request attempts\n // so check if it was triggered and reject if needed.\n if (aborter.aborted) {\n return rejectOnAbort();\n }\n aborter.addEventListener(\"abort\", onAbort);\n }\n\n timer = setTimeout(() => {\n this._responsesMap.delete(request.message_id as string);\n if (aborter) {\n aborter.removeEventListener(\"abort\", onAbort);\n }\n const address = this.receiver?.address || \"address\";\n const desc: string =\n `The request with message_id \"${request.message_id}\" to \"${address}\" ` +\n `endpoint timed out. Please try again later.`;\n const e: Error = {\n name: \"OperationTimeoutError\",\n message: desc,\n };\n return reject(translate(e));\n }, timeoutInMs);\n\n this._responsesMap.set(request.message_id as string, {\n resolve: resolve,\n reject: reject,\n cleanupBeforeResolveOrReject: () => {\n if (aborter) aborter.removeEventListener(\"abort\", onAbort);\n if (isDefined(timer)) {\n clearTimeout(timer);\n }\n },\n });\n\n logger.verbose(\n \"[%s] %s request sent: %O\",\n this.connection.id,\n request.to || \"$management\",\n request,\n );\n this.sender.send(request);\n });\n }\n\n /**\n * Closes the sender, receiver link and the underlying session.\n * @returns Promise<void>\n */\n async close(): Promise<void> {\n await this.sender.close({ closeSession: false });\n await this.receiver.close({ closeSession: false });\n await this.session.close();\n }\n\n /**\n * Removes the sender, receiver link and it's underlying session.\n * @returns void\n */\n remove(): void {\n this.sender.remove();\n this.receiver.remove();\n this.session.remove();\n }\n\n /**\n * Creates an amqp request/response link.\n *\n * @param connection - The amqp connection.\n * @param senderOptions - Options that must be provided to create the sender link.\n * @param receiverOptions - Options that must be provided to create the receiver link.\n * @param createOptions - Optional parameters that can be used to affect this method's behavior.\n * For example, `abortSignal` can be passed to allow cancelling an in-progress `create` invocation.\n * @returns Promise<RequestResponseLink>\n */\n static async create(\n connection: Connection,\n senderOptions: SenderOptions,\n receiverOptions: ReceiverOptions,\n createOptions: { abortSignal?: AbortSignalLike } = {},\n ): Promise<RequestResponseLink> {\n const { abortSignal } = createOptions;\n const session = await connection.createSession({ abortSignal });\n const sender = await session.createSender({ ...senderOptions, abortSignal });\n const receiver = await session.createReceiver({ ...receiverOptions, abortSignal });\n logger.verbose(\n \"[%s] Successfully created the sender and receiver links on the same session.\",\n connection.id,\n );\n return new RequestResponseLink(session, sender, receiver);\n }\n}\n/**\n * @internal\n *\n * Type used in getCodeDescriptionAndError to get the normalized info from the responses emitted by EventHubs and ServiceBus.\n */\ntype NormalizedInfo = {\n statusCode: number;\n statusDescription: string;\n errorCondition: string;\n};\n\n/**\n * @internal\n *\n * Handle different variations of property names in responses emitted by EventHubs and ServiceBus.\n */\nexport const getCodeDescriptionAndError = (\n props: { [key: string]: string | number | undefined } = {},\n): NormalizedInfo => {\n return {\n statusCode: (props[Constants.statusCode] || props.statusCode) as number,\n statusDescription: (props[Constants.statusDescription] || props.statusDescription) as string,\n errorCondition: (props[Constants.errorCondition] || props.errorCondition) as string,\n };\n};\n\n/**\n * This is used as the onMessage handler for the \"message\" event on the receiver.\n *\n * (This is inspired from the message settlement sequence in service-bus SDK which\n * relies on a single listener for settled event for all the messages.)\n * The sequence is as follows:\n * 1. User calls `await RequestResponseLink.sendRequest()`\n * 2. This creates a `Promise` that gets stored in the _responsesMap\n * 3. When the service acknowledges the response, this method gets called for that request.\n * 4. We resolve() the promise from the _responsesMap with the message.\n * 5. User's code after the sendRequest continues.\n *\n * @internal\n */\nexport function onMessageReceived(\n context: Pick<EventContext, \"message\">,\n connectionId: string,\n responsesMap: Map<string, DeferredPromiseWithCallback>,\n): void {\n const message = context.message;\n if (!message) {\n logger.verbose(\n `[${connectionId}] \"message\" property on the EventContext is \"undefined\" which is unexpected, ` +\n `returning from the \"onMessageReceived\" handler without resolving or rejecting the promise ` +\n `upon encountering the message event.`,\n );\n return;\n }\n\n const responseCorrelationId = message.correlation_id;\n if (!responsesMap.has(responseCorrelationId as string)) {\n logger.verbose(\n `[${connectionId}] correlationId \"${responseCorrelationId}\" property on the response does not match with ` +\n `any of the \"request-id\"s in the map, returning from the \"onMessageReceived\" handler without resolving ` +\n `or rejecting the promise upon encountering the message event.`,\n );\n return;\n }\n\n const promise = responsesMap.get(responseCorrelationId as string) as DeferredPromiseWithCallback;\n promise.cleanupBeforeResolveOrReject();\n\n const deleteResult = responsesMap.delete(responseCorrelationId as string);\n logger.verbose(\n `[${connectionId}] Successfully deleted the response with id ${responseCorrelationId} from the map. ` +\n `Delete result - ${deleteResult}`,\n );\n\n const info = getCodeDescriptionAndError(message.application_properties);\n let error;\n if (!info.statusCode) {\n error = new Error(\n `[${connectionId}] No statusCode in the \"application_properties\" in the returned response with correlation-id: ${responseCorrelationId}`,\n );\n }\n if (info.statusCode > 199 && info.statusCode < 300) {\n logger.verbose(\n `[${connectionId}] Resolving the response with correlation-id: ${responseCorrelationId}`,\n );\n return promise.resolve(message);\n }\n if (!error) {\n const condition =\n info.errorCondition || ConditionStatusMapper[info.statusCode] || \"amqp:internal-error\";\n error = translate({\n condition: condition,\n description: info.statusDescription,\n });\n logger.warning(`${error?.name}: ${error?.message}`);\n }\n logErrorStackTrace(error);\n return promise.reject(error);\n}\n\nfunction onSenderError(\n context: Pick<EventContext, \"sender\">,\n connectionId: string,\n responsesMap: Map<string, DeferredPromiseWithCallback>,\n): void {\n if (context.sender) {\n for (const [key, promise] of responsesMap.entries()) {\n logger.verbose(\n `[${connectionId}] Sender closed due to error when sending request with message_id \"${key}\"`,\n );\n promise.cleanupBeforeResolveOrReject();\n promise.reject(context.sender.error);\n }\n responsesMap.clear();\n }\n}\n"]}
|
package/dist/commonjs/retry.js
CHANGED
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
// Licensed under the MIT license.
|
|
4
4
|
/* eslint-disable eqeqeq */
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.
|
|
6
|
+
exports.RetryOperationType = exports.RetryMode = void 0;
|
|
7
|
+
exports.retry = retry;
|
|
7
8
|
const errors_js_1 = require("./errors.js");
|
|
8
9
|
const constants_js_1 = require("./util/constants.js");
|
|
9
10
|
const checkNetworkConnection_js_1 = require("./util/checkNetworkConnection.js");
|
|
@@ -160,7 +161,6 @@ async function retry(config) {
|
|
|
160
161
|
throw compileErrors(errors);
|
|
161
162
|
}
|
|
162
163
|
}
|
|
163
|
-
exports.retry = retry;
|
|
164
164
|
function compileErrors(errors) {
|
|
165
165
|
if (!errors.length) {
|
|
166
166
|
throw new RangeError("Error array is empty");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/retry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C;SAAM,CAAC;QACN,MAAM,aAAa,CAAC,MAAM,CAAC,CAAC;IAC9B,CAAC;AACH,CAAC;AA5GD,sBA4GC;AAED,SAAS,aAAa,CAAC,MAAkC;IACvD,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;QACnB,MAAM,IAAI,UAAU,CAAC,sBAAsB,CAAC,CAAC;IAC/C,CAAC;IACD,IAAI,CAAC,GAAG,CAAC,CAAC;IACV,MAAM,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,SAAS,CAAC,EAAE,KAAK,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACzE,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC5C,SAAS,CAAC,OAAO,GAAG,GAAG,CAAC;IACxB,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n/* eslint-disable eqeqeq */\n\nimport { MessagingError, translate } from \"./errors.js\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { Constants } from \"./util/constants.js\";\nimport { checkNetworkConnection } from \"./util/checkNetworkConnection.js\";\nimport { delay } from \"@azure/core-util\";\nimport { logger } from \"./log.js\";\n\n/**\n * Determines whether the object is a Delivery object.\n * @internal\n */\nfunction isDelivery(obj: any): boolean {\n let result: boolean = false;\n if (\n obj &&\n typeof obj.id === \"number\" &&\n typeof obj.settled === \"boolean\" &&\n typeof obj.remote_settled === \"boolean\" &&\n typeof obj.format === \"number\"\n ) {\n result = true;\n }\n return result;\n}\n\n/**\n * Describes the Retry Mode type\n */\nexport enum RetryMode {\n Exponential,\n Fixed,\n}\n\n/**\n * Describes the retry operation type.\n */\nexport enum RetryOperationType {\n cbsAuth = \"cbsAuth\",\n connection = \"connection\",\n management = \"management\",\n receiverLink = \"receiverLink\",\n senderLink = \"senderLink\",\n sendMessage = \"sendMessage\",\n receiveMessage = \"receiveMessage\",\n session = \"session\",\n messageSettlement = \"settlement\",\n}\n\n/**\n * Retry policy options that determine the mode, number of retries, retry interval etc.\n */\nexport interface RetryOptions {\n /**\n * Number of times the operation needs to be retried in case\n * of retryable error. Default: 3.\n */\n maxRetries?: number;\n /**\n * Amount of time to wait in milliseconds before making the\n * next attempt. Default: `30000 milliseconds`.\n * When `mode` option is set to `Exponential`,\n * this is used to compute the exponentially increasing delays between retries.\n */\n retryDelayInMs?: number;\n /**\n * Number of milliseconds to wait before declaring that current attempt has timed out which will trigger a retry\n * A minimum value of `60000` milliseconds will be used if a value not greater than this is provided.\n */\n timeoutInMs?: number;\n /**\n * Denotes which retry mode to apply. If undefined, defaults to `Fixed`\n */\n mode?: RetryMode;\n /**\n * Denotes the maximum delay between retries\n * that the retry attempts will be capped at. Applicable only when performing exponential retry.\n */\n maxRetryDelayInMs?: number;\n}\n\n/**\n * Describes the parameters that need to be configured for the retry operation.\n */\nexport interface RetryConfig<T> {\n /**\n * The operation that needs to be retried.\n */\n operation: () => Promise<T>;\n /**\n * The connection identifier. Used in logging information.\n * Extremely useful when multiple connections are logged in the same file.\n */\n connectionId: string;\n /**\n * The name/type of operation to be performed.\n * Extremely useful in providing better debug logs.\n */\n operationType: RetryOperationType;\n /**\n * The host \"<yournamespace>.servicebus.windows.net\".\n * Used to check network connectivity.\n */\n connectionHost?: string;\n /**\n * The retry related options associated with given operation execution.\n */\n retryOptions?: RetryOptions;\n /**\n * The `AbortSignal` associated with the operation being retried on.\n * If this signal is fired during the wait time between retries, then the `retry()` method will ensure that the wait is abandoned and the retry process gets cancelled. If this signal is fired when the operation is in progress, then the operation is expected to react to it.\n */\n abortSignal?: AbortSignalLike;\n}\n\n/**\n * Validates the retry config.\n * @internal\n */\nfunction validateRetryConfig<T>(config: RetryConfig<T>): void {\n if (!config.operation) {\n throw new TypeError(\"Missing 'operation' in retry configuration\");\n }\n\n if (!config.connectionId) {\n throw new TypeError(\"Missing 'connectionId' in retry configuration\");\n }\n\n if (!config.operationType) {\n throw new TypeError(\"Missing 'operationType' in retry configuration\");\n }\n}\n\n/**\n * Calculates delay between retries, in milliseconds.\n * @internal\n */\nfunction calculateDelay(\n attemptCount: number,\n retryDelayInMs: number,\n maxRetryDelayInMs: number,\n mode: RetryMode,\n): number {\n if (mode === RetryMode.Exponential) {\n const boundedRandDelta =\n retryDelayInMs * 0.8 +\n Math.floor(Math.random() * (retryDelayInMs * 1.2 - retryDelayInMs * 0.8));\n\n const incrementDelta = boundedRandDelta * (Math.pow(2, attemptCount) - 1);\n return Math.min(incrementDelta, maxRetryDelayInMs);\n }\n\n return retryDelayInMs;\n}\n\n/**\n * Every operation is attempted at least once. Additional attempts are made if the previous attempt failed\n * with a retryable error. The number of additional attempts is governed by the `maxRetries` property provided\n * on the `RetryConfig` argument.\n *\n * If `mode` option is set to `Fixed`, then the retries are made on the\n * given operation for a specified number of times, with a fixed delay in between each retry each time.\n *\n * If `mode` option is set to `Exponential`, then the delay between retries is adjusted to increase\n * exponentially with each attempt using back-off factor of power 2.\n *\n * @param config - Parameters to configure retry operation\n *\n * @returns Promise<T>.\n */\nexport async function retry<T>(config: RetryConfig<T>): Promise<T> {\n validateRetryConfig(config);\n const updatedConfig = { ...config };\n if (!updatedConfig.retryOptions) {\n updatedConfig.retryOptions = {};\n }\n if (\n updatedConfig.retryOptions.maxRetries == undefined ||\n updatedConfig.retryOptions.maxRetries < 0\n ) {\n updatedConfig.retryOptions.maxRetries = Constants.defaultMaxRetries;\n }\n if (\n updatedConfig.retryOptions.retryDelayInMs == undefined ||\n updatedConfig.retryOptions.retryDelayInMs < 0\n ) {\n updatedConfig.retryOptions.retryDelayInMs = Constants.defaultDelayBetweenOperationRetriesInMs;\n }\n if (\n updatedConfig.retryOptions.maxRetryDelayInMs == undefined ||\n updatedConfig.retryOptions.maxRetryDelayInMs < 0\n ) {\n updatedConfig.retryOptions.maxRetryDelayInMs = Constants.defaultMaxDelayForExponentialRetryInMs;\n }\n if (updatedConfig.retryOptions.mode == undefined) {\n updatedConfig.retryOptions.mode = RetryMode.Fixed;\n }\n const errors: (MessagingError | Error)[] = [];\n let result: any;\n let success = false;\n const totalNumberOfAttempts = updatedConfig.retryOptions.maxRetries + 1;\n for (let i = 1; i <= totalNumberOfAttempts; i++) {\n logger.verbose(\n \"[%s] Attempt number for '%s': %d.\",\n updatedConfig.connectionId,\n updatedConfig.operationType,\n i,\n );\n try {\n result = await updatedConfig.operation();\n success = true;\n logger.verbose(\n \"[%s] Success for '%s', after attempt number: %d.\",\n updatedConfig.connectionId,\n updatedConfig.operationType,\n i,\n );\n if (result && !isDelivery(result)) {\n logger.verbose(\n \"[%s] Success result for '%s': %O\",\n updatedConfig.connectionId,\n updatedConfig.operationType,\n result,\n );\n }\n break;\n } catch (_err) {\n const err = translate(_err);\n\n if (\n !(err as any).retryable &&\n err.name === \"ServiceCommunicationError\" &&\n updatedConfig.connectionHost\n ) {\n const isConnected = await checkNetworkConnection(updatedConfig.connectionHost);\n if (!isConnected) {\n err.name = \"ConnectionLostError\";\n (err as any).retryable = true;\n }\n }\n logger.verbose(\n \"[%s] Error occurred for '%s' in attempt number %d: %O\",\n updatedConfig.connectionId,\n updatedConfig.operationType,\n i,\n err,\n );\n\n errors.push(err);\n if ((errors[errors?.length - 1] as MessagingError).retryable && totalNumberOfAttempts > i) {\n const targetDelayInMs = calculateDelay(\n i,\n updatedConfig.retryOptions.retryDelayInMs,\n updatedConfig.retryOptions.maxRetryDelayInMs,\n updatedConfig.retryOptions.mode,\n );\n logger.verbose(\n \"[%s] Sleeping for %d milliseconds for '%s'.\",\n updatedConfig.connectionId,\n targetDelayInMs,\n updatedConfig.operationType,\n );\n await delay(targetDelayInMs, {\n abortSignal: updatedConfig.abortSignal,\n abortErrorMsg: `The retry operation has been cancelled by the user.`,\n });\n\n continue;\n } else {\n break;\n }\n }\n }\n if (success) {\n return result;\n } else {\n throw compileErrors(errors);\n }\n}\n\nfunction compileErrors(errors: (MessagingError | Error)[]): MessagingError | Error {\n if (!errors.length) {\n throw new RangeError(\"Error array is empty\");\n }\n let i = 0;\n const str = errors.map((error) => `Error ${i++}: ${error}`).join(\"\\n\\n\");\n const lastError = errors[errors.length - 1];\n lastError.message = str;\n return lastError;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/retry.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;AAClC,2BAA2B;;;AA2K3B,sBA4GC;AArRD,2CAAwD;AAExD,sDAAgD;AAChD,gFAA0E;AAC1E,gDAAyC;AACzC,qCAAkC;AAElC;;;GAGG;AACH,SAAS,UAAU,CAAC,GAAQ;IAC1B,IAAI,MAAM,GAAY,KAAK,CAAC;IAC5B,IACE,GAAG;QACH,OAAO,GAAG,CAAC,EAAE,KAAK,QAAQ;QAC1B,OAAO,GAAG,CAAC,OAAO,KAAK,SAAS;QAChC,OAAO,GAAG,CAAC,cAAc,KAAK,SAAS;QACvC,OAAO,GAAG,CAAC,MAAM,KAAK,QAAQ,EAC9B,CAAC;QACD,MAAM,GAAG,IAAI,CAAC;IAChB,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;GAEG;AACH,IAAY,SAGX;AAHD,WAAY,SAAS;IACnB,uDAAW,CAAA;IACX,2CAAK,CAAA;AACP,CAAC,EAHW,SAAS,yBAAT,SAAS,QAGpB;AAED;;GAEG;AACH,IAAY,kBAUX;AAVD,WAAY,kBAAkB;IAC5B,yCAAmB,CAAA;IACnB,+CAAyB,CAAA;IACzB,+CAAyB,CAAA;IACzB,mDAA6B,CAAA;IAC7B,+CAAyB,CAAA;IACzB,iDAA2B,CAAA;IAC3B,uDAAiC,CAAA;IACjC,yCAAmB,CAAA;IACnB,sDAAgC,CAAA;AAClC,CAAC,EAVW,kBAAkB,kCAAlB,kBAAkB,QAU7B;AAoED;;;GAGG;AACH,SAAS,mBAAmB,CAAI,MAAsB;IACpD,IAAI,CAAC,MAAM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AAC,eAAe,EAAE;oBAC3B,WAAW,EAAE,aAAa,CAAC,WAAW;oBACtC,aAAa,EAAE,qDAAqD;iBACrE,CAAC,CAAC;gBAEH,SAAS;YACX,CAAC;iBAAM,CAAC;gBACN,MAAM;YACR,CAAC;QACH,CAAC;IACH,CAAC;IACD,IAAI,OAAO,EAAE,CAAC;QACZ,OAAO,MAAM,CAAC;IAChB,CAAC;SAAM,CAAC;QACN,MAAM,aAAa,CAAC,MAAM,CAAC,CAAC;IAC9B,CAAC;AACH,CAAC;AAED,SAAS,aAAa,CAAC,MAAkC;IACvD,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;QACnB,MAAM,IAAI,UAAU,CAAC,sBAAsB,CAAC,CAAC;IAC/C,CAAC;IACD,IAAI,CAAC,GAAG,CAAC,CAAC;IACV,MAAM,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,SAAS,CAAC,EAAE,KAAK,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IACzE,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAC5C,SAAS,CAAC,OAAO,GAAG,GAAG,CAAC;IACxB,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n/* eslint-disable eqeqeq */\n\nimport { MessagingError, translate } from \"./errors.js\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { Constants } from \"./util/constants.js\";\nimport { checkNetworkConnection } from \"./util/checkNetworkConnection.js\";\nimport { delay } from \"@azure/core-util\";\nimport { logger } from \"./log.js\";\n\n/**\n * Determines whether the object is a Delivery object.\n * @internal\n */\nfunction isDelivery(obj: any): boolean {\n let result: boolean = false;\n if (\n obj &&\n typeof obj.id === \"number\" &&\n typeof obj.settled === \"boolean\" &&\n typeof obj.remote_settled === \"boolean\" &&\n typeof obj.format === \"number\"\n ) {\n result = true;\n }\n return result;\n}\n\n/**\n * Describes the Retry Mode type\n */\nexport enum RetryMode {\n Exponential,\n Fixed,\n}\n\n/**\n * Describes the retry operation type.\n */\nexport enum RetryOperationType {\n cbsAuth = \"cbsAuth\",\n connection = \"connection\",\n management = \"management\",\n receiverLink = \"receiverLink\",\n senderLink = \"senderLink\",\n sendMessage = \"sendMessage\",\n receiveMessage = \"receiveMessage\",\n session = \"session\",\n messageSettlement = \"settlement\",\n}\n\n/**\n * Retry policy options that determine the mode, number of retries, retry interval etc.\n */\nexport interface RetryOptions {\n /**\n * Number of times the operation needs to be retried in case\n * of retryable error. Default: 3.\n */\n maxRetries?: number;\n /**\n * Amount of time to wait in milliseconds before making the\n * next attempt. Default: `30000 milliseconds`.\n * When `mode` option is set to `Exponential`,\n * this is used to compute the exponentially increasing delays between retries.\n */\n retryDelayInMs?: number;\n /**\n * Number of milliseconds to wait before declaring that current attempt has timed out which will trigger a retry\n * A minimum value of `60000` milliseconds will be used if a value not greater than this is provided.\n */\n timeoutInMs?: number;\n /**\n * Denotes which retry mode to apply. If undefined, defaults to `Fixed`\n */\n mode?: RetryMode;\n /**\n * Denotes the maximum delay between retries\n * that the retry attempts will be capped at. Applicable only when performing exponential retry.\n */\n maxRetryDelayInMs?: number;\n}\n\n/**\n * Describes the parameters that need to be configured for the retry operation.\n */\nexport interface RetryConfig<T> {\n /**\n * The operation that needs to be retried.\n */\n operation: () => Promise<T>;\n /**\n * The connection identifier. Used in logging information.\n * Extremely useful when multiple connections are logged in the same file.\n */\n connectionId: string;\n /**\n * The name/type of operation to be performed.\n * Extremely useful in providing better debug logs.\n */\n operationType: RetryOperationType;\n /**\n * The host \"<yournamespace>.servicebus.windows.net\".\n * Used to check network connectivity.\n */\n connectionHost?: string;\n /**\n * The retry related options associated with given operation execution.\n */\n retryOptions?: RetryOptions;\n /**\n * The `AbortSignal` associated with the operation being retried on.\n * If this signal is fired during the wait time between retries, then the `retry()` method will ensure that the wait is abandoned and the retry process gets cancelled. If this signal is fired when the operation is in progress, then the operation is expected to react to it.\n */\n abortSignal?: AbortSignalLike;\n}\n\n/**\n * Validates the retry config.\n * @internal\n */\nfunction validateRetryConfig<T>(config: RetryConfig<T>): void {\n if (!config.operation) {\n throw new TypeError(\"Missing 'operation' in retry configuration\");\n }\n\n if (!config.connectionId) {\n throw new TypeError(\"Missing 'connectionId' in retry configuration\");\n }\n\n if (!config.operationType) {\n throw new TypeError(\"Missing 'operationType' in retry configuration\");\n }\n}\n\n/**\n * Calculates delay between retries, in milliseconds.\n * @internal\n */\nfunction calculateDelay(\n attemptCount: number,\n retryDelayInMs: number,\n maxRetryDelayInMs: number,\n mode: RetryMode,\n): number {\n if (mode === RetryMode.Exponential) {\n const boundedRandDelta =\n retryDelayInMs * 0.8 +\n Math.floor(Math.random() * (retryDelayInMs * 1.2 - retryDelayInMs * 0.8));\n\n const incrementDelta = boundedRandDelta * (Math.pow(2, attemptCount) - 1);\n return Math.min(incrementDelta, maxRetryDelayInMs);\n }\n\n return retryDelayInMs;\n}\n\n/**\n * Every operation is attempted at least once. Additional attempts are made if the previous attempt failed\n * with a retryable error. The number of additional attempts is governed by the `maxRetries` property provided\n * on the `RetryConfig` argument.\n *\n * If `mode` option is set to `Fixed`, then the retries are made on the\n * given operation for a specified number of times, with a fixed delay in between each retry each time.\n *\n * If `mode` option is set to `Exponential`, then the delay between retries is adjusted to increase\n * exponentially with each attempt using back-off factor of power 2.\n *\n * @param config - Parameters to configure retry operation\n *\n * @returns Promise<T>.\n */\nexport async function retry<T>(config: RetryConfig<T>): Promise<T> {\n validateRetryConfig(config);\n const updatedConfig = { ...config };\n if (!updatedConfig.retryOptions) {\n updatedConfig.retryOptions = {};\n }\n if (\n updatedConfig.retryOptions.maxRetries == undefined ||\n updatedConfig.retryOptions.maxRetries < 0\n ) {\n updatedConfig.retryOptions.maxRetries = Constants.defaultMaxRetries;\n }\n if (\n updatedConfig.retryOptions.retryDelayInMs == undefined ||\n updatedConfig.retryOptions.retryDelayInMs < 0\n ) {\n updatedConfig.retryOptions.retryDelayInMs = Constants.defaultDelayBetweenOperationRetriesInMs;\n }\n if (\n updatedConfig.retryOptions.maxRetryDelayInMs == undefined ||\n updatedConfig.retryOptions.maxRetryDelayInMs < 0\n ) {\n updatedConfig.retryOptions.maxRetryDelayInMs = Constants.defaultMaxDelayForExponentialRetryInMs;\n }\n if (updatedConfig.retryOptions.mode == undefined) {\n updatedConfig.retryOptions.mode = RetryMode.Fixed;\n }\n const errors: (MessagingError | Error)[] = [];\n let result: any;\n let success = false;\n const totalNumberOfAttempts = updatedConfig.retryOptions.maxRetries + 1;\n for (let i = 1; i <= totalNumberOfAttempts; i++) {\n logger.verbose(\n \"[%s] Attempt number for '%s': %d.\",\n updatedConfig.connectionId,\n updatedConfig.operationType,\n i,\n );\n try {\n result = await updatedConfig.operation();\n success = true;\n logger.verbose(\n \"[%s] Success for '%s', after attempt number: %d.\",\n updatedConfig.connectionId,\n updatedConfig.operationType,\n i,\n );\n if (result && !isDelivery(result)) {\n logger.verbose(\n \"[%s] Success result for '%s': %O\",\n updatedConfig.connectionId,\n updatedConfig.operationType,\n result,\n );\n }\n break;\n } catch (_err) {\n const err = translate(_err);\n\n if (\n !(err as any).retryable &&\n err.name === \"ServiceCommunicationError\" &&\n updatedConfig.connectionHost\n ) {\n const isConnected = await checkNetworkConnection(updatedConfig.connectionHost);\n if (!isConnected) {\n err.name = \"ConnectionLostError\";\n (err as any).retryable = true;\n }\n }\n logger.verbose(\n \"[%s] Error occurred for '%s' in attempt number %d: %O\",\n updatedConfig.connectionId,\n updatedConfig.operationType,\n i,\n err,\n );\n\n errors.push(err);\n if ((errors[errors?.length - 1] as MessagingError).retryable && totalNumberOfAttempts > i) {\n const targetDelayInMs = calculateDelay(\n i,\n updatedConfig.retryOptions.retryDelayInMs,\n updatedConfig.retryOptions.maxRetryDelayInMs,\n updatedConfig.retryOptions.mode,\n );\n logger.verbose(\n \"[%s] Sleeping for %d milliseconds for '%s'.\",\n updatedConfig.connectionId,\n targetDelayInMs,\n updatedConfig.operationType,\n );\n await delay(targetDelayInMs, {\n abortSignal: updatedConfig.abortSignal,\n abortErrorMsg: `The retry operation has been cancelled by the user.`,\n });\n\n continue;\n } else {\n break;\n }\n }\n }\n if (success) {\n return result;\n } else {\n throw compileErrors(errors);\n }\n}\n\nfunction compileErrors(errors: (MessagingError | Error)[]): MessagingError | Error {\n if (!errors.length) {\n throw new RangeError(\"Error array is empty\");\n }\n let i = 0;\n const str = errors.map((error) => `Error ${i++}: ${error}`).join(\"\\n\\n\");\n const lastError = errors[errors.length - 1];\n lastError.message = str;\n return lastError;\n}\n"]}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// Copyright (c) Microsoft Corporation.
|
|
3
3
|
// Licensed under the MIT license.
|
|
4
4
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
-
exports.checkNetworkConnection =
|
|
5
|
+
exports.checkNetworkConnection = checkNetworkConnection;
|
|
6
6
|
const node_dns_1 = require("node:dns");
|
|
7
7
|
const log_js_1 = require("../log.js");
|
|
8
8
|
/**
|
|
@@ -28,5 +28,4 @@ function checkNetworkConnection(host) {
|
|
|
28
28
|
});
|
|
29
29
|
});
|
|
30
30
|
}
|
|
31
|
-
exports.checkNetworkConnection = checkNetworkConnection;
|
|
32
31
|
//# sourceMappingURL=checkNetworkConnection.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkNetworkConnection.js","sourceRoot":"","sources":["../../../src/util/checkNetworkConnection.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC
|
|
1
|
+
{"version":3,"file":"checkNetworkConnection.js","sourceRoot":"","sources":["../../../src/util/checkNetworkConnection.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;AASlC,wDAsBC;AA7BD,uCAAuE;AACvE,sCAAmC;AAEnC;;;GAGG;AACH,SAAgB,sBAAsB,CAAC,IAAY;IACjD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC7B,eAAM,CAAC,OAAO,CAAC,6DAA6D,CAAC,CAAC;QAC9E,IAAA,kBAAU,EAAC,IAAI,EAAE,UAAU,GAAQ;YACjC,IAAI,GAAG,EAAE,CAAC;gBACR,eAAM,CAAC,OAAO,CACZ,qEAAqE,EACrE,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,IAAI,EACpB,GAAG,CACJ,CAAC;gBACF,2GAA2G;gBAC3G,8GAA8G;gBAC9G,IAAI,GAAG,CAAC,IAAI,KAAK,sBAAW,IAAI,GAAG,CAAC,IAAI,KAAK,kBAAO,EAAE,CAAC;oBACrD,OAAO,OAAO,CAAC,KAAK,CAAC,CAAC;gBACxB,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,eAAM,CAAC,OAAO,CAAC,yEAAyE,CAAC,CAAC;YAC5F,CAAC;YAED,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC;QACvB,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { CONNREFUSED, TIMEOUT, resolve as dnsResolve } from \"node:dns\";\nimport { logger } from \"../log.js\";\n\n/**\n * Checks whether a network connection is detected.\n * @internal\n */\nexport function checkNetworkConnection(host: string): Promise<boolean> {\n return new Promise((resolve) => {\n logger.verbose(\"Calling dns.resolve to determine network connection status.\");\n dnsResolve(host, function (err: any): void {\n if (err) {\n logger.verbose(\n \"Error thrown from dns.resolve in network connection check: '%s', %O\",\n err.code || err.name,\n err,\n );\n // List of possible DNS error codes: https://nodejs.org/dist/latest-v12.x/docs/api/dns.html#dns_error_codes\n // We only resolve with `false` when dnsResolve fails with an error we expect to see when the network is down.\n if (err.code === CONNREFUSED || err.code === TIMEOUT) {\n return resolve(false);\n }\n } else {\n logger.verbose(\"Successfully resolved host via dns.resolve in network connection check.\");\n }\n\n return resolve(true);\n });\n });\n}\n"]}
|
|
@@ -2,11 +2,10 @@
|
|
|
2
2
|
// Copyright (c) Microsoft Corporation.
|
|
3
3
|
// Licensed under the MIT license.
|
|
4
4
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
-
exports.signString =
|
|
5
|
+
exports.signString = signString;
|
|
6
6
|
const node_crypto_1 = require("node:crypto");
|
|
7
7
|
async function signString(key, toSign) {
|
|
8
8
|
const hmac = (0, node_crypto_1.createHmac)("sha256", key).update(toSign).digest("base64");
|
|
9
9
|
return encodeURIComponent(hmac);
|
|
10
10
|
}
|
|
11
|
-
exports.signString = signString;
|
|
12
11
|
//# sourceMappingURL=hmacSha256.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hmacSha256.js","sourceRoot":"","sources":["../../../src/util/hmacSha256.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC
|
|
1
|
+
{"version":3,"file":"hmacSha256.js","sourceRoot":"","sources":["../../../src/util/hmacSha256.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;AAIlC,gCAGC;AALD,6CAAyC;AAElC,KAAK,UAAU,UAAU,CAAC,GAAW,EAAE,MAAc;IAC1D,MAAM,IAAI,GAAG,IAAA,wBAAU,EAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IACvE,OAAO,kBAAkB,CAAC,IAAI,CAAC,CAAC;AAClC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { createHmac } from \"node:crypto\";\n\nexport async function signString(key: string, toSign: string): Promise<string> {\n const hmac = createHmac(\"sha256\", key).update(toSign).digest(\"base64\");\n return encodeURIComponent(hmac);\n}\n"]}
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
// Copyright (c) Microsoft Corporation.
|
|
3
3
|
// Licensed under the MIT license.
|
|
4
4
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
-
exports.
|
|
5
|
+
exports.getPlatformInfo = getPlatformInfo;
|
|
6
|
+
exports.getFrameworkInfo = getFrameworkInfo;
|
|
6
7
|
const tslib_1 = require("tslib");
|
|
7
8
|
const os = tslib_1.__importStar(require("node:os"));
|
|
8
9
|
/**
|
|
@@ -12,7 +13,6 @@ const os = tslib_1.__importStar(require("node:os"));
|
|
|
12
13
|
function getPlatformInfo() {
|
|
13
14
|
return `(${os.arch()}-${os.type()}-${os.release()})`;
|
|
14
15
|
}
|
|
15
|
-
exports.getPlatformInfo = getPlatformInfo;
|
|
16
16
|
/**
|
|
17
17
|
* Returns information about Node.js this function is being run on.
|
|
18
18
|
* @internal
|
|
@@ -20,5 +20,4 @@ exports.getPlatformInfo = getPlatformInfo;
|
|
|
20
20
|
function getFrameworkInfo() {
|
|
21
21
|
return `Node/${process.version}`;
|
|
22
22
|
}
|
|
23
|
-
exports.getFrameworkInfo = getFrameworkInfo;
|
|
24
23
|
//# sourceMappingURL=runtimeInfo.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtimeInfo.js","sourceRoot":"","sources":["../../../src/util/runtimeInfo.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC
|
|
1
|
+
{"version":3,"file":"runtimeInfo.js","sourceRoot":"","sources":["../../../src/util/runtimeInfo.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;AAQlC,0CAEC;AAMD,4CAEC;;AAhBD,oDAA8B;AAE9B;;;GAGG;AACH,SAAgB,eAAe;IAC7B,OAAO,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,OAAO,EAAE,GAAG,CAAC;AACvD,CAAC;AAED;;;GAGG;AACH,SAAgB,gBAAgB;IAC9B,OAAO,QAAQ,OAAO,CAAC,OAAO,EAAE,CAAC;AACnC,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport * as os from \"node:os\";\n\n/**\n * Returns information about the platform this function is being run on.\n * @internal\n */\nexport function getPlatformInfo(): string {\n return `(${os.arch()}-${os.type()}-${os.release()})`;\n}\n\n/**\n * Returns information about Node.js this function is being run on.\n * @internal\n */\nexport function getFrameworkInfo(): string {\n return `Node/${process.version}`;\n}\n"]}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// Copyright (c) Microsoft Corporation.
|
|
3
3
|
// Licensed under the MIT license.
|
|
4
4
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
-
exports.isSasTokenProvider =
|
|
5
|
+
exports.isSasTokenProvider = isSasTokenProvider;
|
|
6
6
|
const core_util_1 = require("@azure/core-util");
|
|
7
7
|
/**
|
|
8
8
|
* Typeguard that checks if the input is a SasTokenProvider.
|
|
@@ -12,5 +12,4 @@ const core_util_1 = require("@azure/core-util");
|
|
|
12
12
|
function isSasTokenProvider(thing) {
|
|
13
13
|
return (0, core_util_1.isObjectWithProperties)(thing, ["isSasTokenProvider"]) && thing.isSasTokenProvider === true;
|
|
14
14
|
}
|
|
15
|
-
exports.isSasTokenProvider = isSasTokenProvider;
|
|
16
15
|
//# sourceMappingURL=typeGuards.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"typeGuards.js","sourceRoot":"","sources":["../../../src/util/typeGuards.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC
|
|
1
|
+
{"version":3,"file":"typeGuards.js","sourceRoot":"","sources":["../../../src/util/typeGuards.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;AAUlC,gDAEC;AATD,gDAA0D;AAE1D;;;;GAIG;AACH,SAAgB,kBAAkB,CAAC,KAAc;IAC/C,OAAO,IAAA,kCAAsB,EAAC,KAAK,EAAE,CAAC,oBAAoB,CAAC,CAAC,IAAI,KAAK,CAAC,kBAAkB,KAAK,IAAI,CAAC;AACpG,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { SasTokenProvider } from \"../auth/tokenProvider.js\";\nimport { isObjectWithProperties } from \"@azure/core-util\";\n\n/**\n * Typeguard that checks if the input is a SasTokenProvider.\n * @param thing - Any object.\n * @hidden\n */\nexport function isSasTokenProvider(thing: unknown): thing is SasTokenProvider {\n return isObjectWithProperties(thing, [\"isSasTokenProvider\"]) && thing.isSasTokenProvider === true;\n}\n"]}
|
|
@@ -2,7 +2,15 @@
|
|
|
2
2
|
// Copyright (c) Microsoft Corporation.
|
|
3
3
|
// Licensed under the MIT license.
|
|
4
4
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
-
exports.
|
|
5
|
+
exports.Timeout = exports.defaultCancellableLock = void 0;
|
|
6
|
+
exports.parseConnectionString = parseConnectionString;
|
|
7
|
+
exports.delay = delay;
|
|
8
|
+
exports.isLoopbackAddress = isLoopbackAddress;
|
|
9
|
+
exports.randomNumberFromInterval = randomNumberFromInterval;
|
|
10
|
+
exports.executePromisesSequentially = executePromisesSequentially;
|
|
11
|
+
exports.isIotHubConnectionString = isIotHubConnectionString;
|
|
12
|
+
exports.isString = isString;
|
|
13
|
+
exports.isNumber = isNumber;
|
|
6
14
|
const lock_js_1 = require("./lock.js");
|
|
7
15
|
const core_util_1 = require("@azure/core-util");
|
|
8
16
|
/**
|
|
@@ -41,7 +49,6 @@ function parseConnectionString(connectionString) {
|
|
|
41
49
|
}
|
|
42
50
|
return output;
|
|
43
51
|
}
|
|
44
|
-
exports.parseConnectionString = parseConnectionString;
|
|
45
52
|
/**
|
|
46
53
|
* The cancellable async lock instance.
|
|
47
54
|
*/
|
|
@@ -106,7 +113,6 @@ async function delay(delayInMs, abortSignal, abortErrorMsg, value) {
|
|
|
106
113
|
return value;
|
|
107
114
|
}
|
|
108
115
|
}
|
|
109
|
-
exports.delay = delay;
|
|
110
116
|
/**
|
|
111
117
|
* Checks if an address is localhost.
|
|
112
118
|
* @param address - The address to check.
|
|
@@ -115,7 +121,6 @@ exports.delay = delay;
|
|
|
115
121
|
function isLoopbackAddress(address) {
|
|
116
122
|
return /^(.*:\/\/)?(127\.[\d.]+|[0:]+1|localhost)/.test(address.toLowerCase());
|
|
117
123
|
}
|
|
118
|
-
exports.isLoopbackAddress = isLoopbackAddress;
|
|
119
124
|
/**
|
|
120
125
|
* @internal
|
|
121
126
|
*
|
|
@@ -126,7 +131,6 @@ exports.isLoopbackAddress = isLoopbackAddress;
|
|
|
126
131
|
function randomNumberFromInterval(min, max) {
|
|
127
132
|
return Math.floor(Math.random() * (max - min + 1) + min);
|
|
128
133
|
}
|
|
129
|
-
exports.randomNumberFromInterval = randomNumberFromInterval;
|
|
130
134
|
/**
|
|
131
135
|
* @internal
|
|
132
136
|
*
|
|
@@ -147,7 +151,6 @@ function executePromisesSequentially(promiseFactories, kickstart) {
|
|
|
147
151
|
});
|
|
148
152
|
return result;
|
|
149
153
|
}
|
|
150
|
-
exports.executePromisesSequentially = executePromisesSequentially;
|
|
151
154
|
/**
|
|
152
155
|
* @internal
|
|
153
156
|
*
|
|
@@ -164,19 +167,16 @@ function isIotHubConnectionString(connectionString) {
|
|
|
164
167
|
}
|
|
165
168
|
return result;
|
|
166
169
|
}
|
|
167
|
-
exports.isIotHubConnectionString = isIotHubConnectionString;
|
|
168
170
|
/**
|
|
169
171
|
* @internal
|
|
170
172
|
*/
|
|
171
173
|
function isString(s) {
|
|
172
174
|
return typeof s === "string";
|
|
173
175
|
}
|
|
174
|
-
exports.isString = isString;
|
|
175
176
|
/**
|
|
176
177
|
* @internal
|
|
177
178
|
*/
|
|
178
179
|
function isNumber(n) {
|
|
179
180
|
return typeof n === "number";
|
|
180
181
|
}
|
|
181
|
-
exports.isNumber = isNumber;
|
|
182
182
|
//# sourceMappingURL=utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/util/utils.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;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,SAAgB,wBAAwB,CAAC,gBAAwB;IAC/D,gBAAgB,GAAG,MAAM,CAAC,gBAAgB,CAAC,CAAC;IAE5C,IAAI,MAAM,GAAY,KAAK,CAAC;IAC5B,MAAM,KAAK,GAAQ,qBAAqB,CAAM,gBAAgB,CAAC,CAAC;IAChE,IAAI,KAAK,IAAI,KAAK,CAAC,QAAQ,IAAI,KAAK,CAAC,eAAe,IAAI,KAAK,CAAC,mBAAmB,EAAE,CAAC;QAClF,MAAM,GAAG,IAAI,CAAC;IAChB,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AATD,4DASC;AAED;;GAEG;AACH,SAAgB,QAAQ,CAAC,CAAU;IACjC,OAAO,OAAO,CAAC,KAAK,QAAQ,CAAC;AAC/B,CAAC;AAFD,4BAEC;AAED;;GAEG;AACH,SAAgB,QAAQ,CAAC,CAAU;IACjC,OAAO,OAAO,CAAC,KAAK,QAAQ,CAAC;AAC/B,CAAC;AAFD,4BAEC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { CancellableAsyncLock, CancellableAsyncLockImpl } from \"./lock.js\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { WebSocketImpl } from \"rhea-promise\";\nimport { delay as wrapperDelay } from \"@azure/core-util\";\n\n/**\n * @internal\n *\n * Describes the options that can be provided to create an async lock.\n */\nexport interface AsyncLockOptions {\n /**\n * The max timeout. Default is: 0 (never timeout).\n */\n timeout?: number;\n /**\n * Maximum pending tasks. Default is: 1000.\n */\n maxPending?: number;\n /**\n * Whether lock can reenter in the same domain.\n * Default is: false.\n */\n domainReentrant?: boolean;\n /**\n * Your implementation of the promise. Default is: global promise.\n */\n Promise?: any;\n}\n\n/**\n * Options to configure the channelling of the AMQP connection over Web Sockets.\n */\nexport interface WebSocketOptions {\n /**\n * The WebSocket constructor used to create an AMQP connection over a WebSocket.\n * This option should be provided in the below scenarios:\n * - The TCP port 5671 which is that is used by the AMQP connection to Event Hubs is blocked in your environment.\n * - Your application needs to be run behind a proxy server.\n * - Your application needs to run in the browser and you want to provide your own choice of Websocket implementation\n * instead of the built-in WebSocket in the browser.\n */\n webSocket?: WebSocketImpl;\n /**\n * Options to be passed to the WebSocket constructor when the underlying `rhea` library instantiates\n * the WebSocket.\n */\n webSocketConstructorOptions?: any;\n}\n\n/**\n * Defines an object with possible properties defined in T.\n */\nexport type ParsedOutput<T> = { [P in keyof T]: T[P] };\n\n/**\n * Parses the connection string and returns an object of type T.\n *\n * Connection strings have the following syntax:\n *\n * ConnectionString ::= `Part { \";\" Part } [ \";\" ] [ WhiteSpace ]`\n * Part ::= [ PartLiteral [ \"=\" PartLiteral ] ]\n * PartLiteral ::= [ WhiteSpace ] Literal [ WhiteSpace ]\n * Literal ::= ? any sequence of characters except ; or = or WhiteSpace ?\n * WhiteSpace ::= ? all whitespace characters including `\\r` and `\\n` ?\n *\n * @param connectionString - The connection string to be parsed.\n * @returns ParsedOutput<T>.\n */\nexport function parseConnectionString<T>(connectionString: string): ParsedOutput<T> {\n const output: { [k: string]: string } = {};\n const parts = connectionString.trim().split(\";\");\n\n for (let part of parts) {\n part = part.trim();\n\n if (part === \"\") {\n // parts can be empty\n continue;\n }\n\n const splitIndex = part.indexOf(\"=\");\n if (splitIndex === -1) {\n throw new Error(\n \"Connection string malformed: each part of the connection string must have an `=` assignment.\",\n );\n }\n\n const key = part.substring(0, splitIndex).trim();\n if (key === \"\") {\n throw new Error(\"Connection string malformed: missing key for assignment\");\n }\n\n const value = part.substring(splitIndex + 1).trim();\n\n output[key] = value;\n }\n\n return output as any;\n}\n\n/**\n * The cancellable async lock instance.\n */\nexport const defaultCancellableLock: CancellableAsyncLock = new CancellableAsyncLockImpl();\n\n/**\n * @internal\n *\n * Describes a Timeout class that can wait for the specified amount of time and then resolve/reject\n * the promise with the given value.\n */\nexport class Timeout {\n private _timer?: ReturnType<typeof setTimeout>;\n\n set<T>(t: number, value?: T): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n this.clear();\n const callback: (args: any) => void = value ? () => reject(new Error(`${value}`)) : resolve;\n this._timer = setTimeout(callback, t);\n });\n }\n\n clear(): void {\n if (this._timer) {\n clearTimeout(this._timer);\n }\n }\n\n wrap<T>(promise: Promise<T>, t: number, value?: T): Promise<T> {\n const wrappedPromise = this._promiseFinally(promise, () => this.clear());\n const timer = this.set(t, value);\n return Promise.race([wrappedPromise, timer]);\n }\n\n private _promiseFinally<T>(promise: Promise<T>, fn: (...args: any[]) => void): Promise<T> {\n const success = (result: T): T => {\n fn();\n return result;\n };\n const error = (e: Error): Promise<never> => {\n fn();\n return Promise.reject(e);\n };\n return Promise.resolve(promise).then(success, error);\n }\n\n static set<T>(t: number, value?: T): Promise<T> {\n return new Timeout().set(t, value);\n }\n\n static wrap<T>(promise: Promise<T>, t: number, value?: T): Promise<T> {\n return new Timeout().wrap(promise, t, value);\n }\n}\n\n/**\n * A wrapper for setTimeout that resolves a promise after t milliseconds.\n * @param delayInMs - The number of milliseconds to be delayed.\n * @param abortSignal - The abortSignal associated with containing operation.\n * @param abortErrorMsg - The abort error message associated with containing operation.\n * @param value - The value to be resolved with after a timeout of t milliseconds.\n * @returns - Resolved promise\n */\nexport async function delay<T>(\n delayInMs: number,\n abortSignal?: AbortSignalLike,\n abortErrorMsg?: string,\n value?: T,\n): Promise<T | void> {\n await wrapperDelay(delayInMs, {\n abortSignal: abortSignal,\n abortErrorMsg: abortErrorMsg,\n });\n if (value !== undefined) {\n return value;\n }\n}\n\n/**\n * Checks if an address is localhost.\n * @param address - The address to check.\n * @returns true if the address is localhost, false otherwise.\n */\nexport function isLoopbackAddress(address: string): boolean {\n return /^(.*:\\/\\/)?(127\\.[\\d.]+|[0:]+1|localhost)/.test(address.toLowerCase());\n}\n\n/**\n * @internal\n *\n * Generates a random number between the given interval\n * @param min - Min number of the range (inclusive).\n * @param max - Max number of the range (inclusive).\n */\nexport function randomNumberFromInterval(min: number, max: number): number {\n return Math.floor(Math.random() * (max - min + 1) + min);\n}\n\n/**\n * @internal\n *\n * Type declaration for a Function type where T is the input to the function and V is the output\n * of the function.\n */\nexport type Func<T, V> = (a: T) => V;\n\n/**\n * @internal\n *\n * Executes an array of promises sequentially. Inspiration of this method is here:\n * https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html. An awesome blog on promises!\n *\n * @param promiseFactories - An array of promise factories(A function that return a promise)\n *\n * @param kickstart - Input to the first promise that is used to kickstart the promise chain.\n * If not provided then the promise chain starts with undefined.\n *\n * @returns A chain of resolved or rejected promises\n */\nexport function executePromisesSequentially(\n promiseFactories: Array<any>,\n kickstart?: unknown,\n): Promise<any> {\n let result = Promise.resolve(kickstart);\n promiseFactories.forEach((promiseFactory) => {\n result = result.then(promiseFactory);\n });\n return result;\n}\n\n/**\n * @internal\n *\n * Determines whether the given connection string is an iothub connection string.\n * @param connectionString - The connection string.\n * @returns boolean.\n */\nexport function isIotHubConnectionString(connectionString: string): boolean {\n connectionString = String(connectionString);\n\n let result: boolean = false;\n const model: any = parseConnectionString<any>(connectionString);\n if (model && model.HostName && model.SharedAccessKey && model.SharedAccessKeyName) {\n result = true;\n }\n return result;\n}\n\n/**\n * @internal\n */\nexport function isString(s: unknown): s is string {\n return typeof s === \"string\";\n}\n\n/**\n * @internal\n */\nexport function isNumber(n: unknown): n is number {\n return typeof n === \"number\";\n}\n"]}
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/util/utils.ts"],"names":[],"mappings":";AAAA,uCAAuC;AACvC,kCAAkC;;;AAuElC,sDA8BC;AAiED,sBAaC;AAOD,8CAEC;AASD,4DAEC;AAuBD,kEASC;AASD,4DASC;AAKD,4BAEC;AAKD,4BAEC;AArQD,uCAA2E;AAG3E,gDAAyD;AAoDzD;;;;;;;;;;;;;GAaG;AACH,SAAgB,qBAAqB,CAAI,gBAAwB;IAC/D,MAAM,MAAM,GAA4B,EAAE,CAAC;IAC3C,MAAM,KAAK,GAAG,gBAAgB,CAAC,IAAI,EAAE,CAAC,KAA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AK,CAAC,mBAAmB,EAAE,CAAC;QAClF,MAAM,GAAG,IAAI,CAAC;IAChB,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;GAEG;AACH,SAAgB,QAAQ,CAAC,CAAU;IACjC,OAAO,OAAO,CAAC,KAAK,QAAQ,CAAC;AAC/B,CAAC;AAED;;GAEG;AACH,SAAgB,QAAQ,CAAC,CAAU;IACjC,OAAO,OAAO,CAAC,KAAK,QAAQ,CAAC;AAC/B,CAAC","sourcesContent":["// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\nimport { CancellableAsyncLock, CancellableAsyncLockImpl } from \"./lock.js\";\nimport { AbortSignalLike } from \"@azure/abort-controller\";\nimport { WebSocketImpl } from \"rhea-promise\";\nimport { delay as wrapperDelay } from \"@azure/core-util\";\n\n/**\n * @internal\n *\n * Describes the options that can be provided to create an async lock.\n */\nexport interface AsyncLockOptions {\n /**\n * The max timeout. Default is: 0 (never timeout).\n */\n timeout?: number;\n /**\n * Maximum pending tasks. Default is: 1000.\n */\n maxPending?: number;\n /**\n * Whether lock can reenter in the same domain.\n * Default is: false.\n */\n domainReentrant?: boolean;\n /**\n * Your implementation of the promise. Default is: global promise.\n */\n Promise?: any;\n}\n\n/**\n * Options to configure the channelling of the AMQP connection over Web Sockets.\n */\nexport interface WebSocketOptions {\n /**\n * The WebSocket constructor used to create an AMQP connection over a WebSocket.\n * This option should be provided in the below scenarios:\n * - The TCP port 5671 which is that is used by the AMQP connection to Event Hubs is blocked in your environment.\n * - Your application needs to be run behind a proxy server.\n * - Your application needs to run in the browser and you want to provide your own choice of Websocket implementation\n * instead of the built-in WebSocket in the browser.\n */\n webSocket?: WebSocketImpl;\n /**\n * Options to be passed to the WebSocket constructor when the underlying `rhea` library instantiates\n * the WebSocket.\n */\n webSocketConstructorOptions?: any;\n}\n\n/**\n * Defines an object with possible properties defined in T.\n */\nexport type ParsedOutput<T> = { [P in keyof T]: T[P] };\n\n/**\n * Parses the connection string and returns an object of type T.\n *\n * Connection strings have the following syntax:\n *\n * ConnectionString ::= `Part { \";\" Part } [ \";\" ] [ WhiteSpace ]`\n * Part ::= [ PartLiteral [ \"=\" PartLiteral ] ]\n * PartLiteral ::= [ WhiteSpace ] Literal [ WhiteSpace ]\n * Literal ::= ? any sequence of characters except ; or = or WhiteSpace ?\n * WhiteSpace ::= ? all whitespace characters including `\\r` and `\\n` ?\n *\n * @param connectionString - The connection string to be parsed.\n * @returns ParsedOutput<T>.\n */\nexport function parseConnectionString<T>(connectionString: string): ParsedOutput<T> {\n const output: { [k: string]: string } = {};\n const parts = connectionString.trim().split(\";\");\n\n for (let part of parts) {\n part = part.trim();\n\n if (part === \"\") {\n // parts can be empty\n continue;\n }\n\n const splitIndex = part.indexOf(\"=\");\n if (splitIndex === -1) {\n throw new Error(\n \"Connection string malformed: each part of the connection string must have an `=` assignment.\",\n );\n }\n\n const key = part.substring(0, splitIndex).trim();\n if (key === \"\") {\n throw new Error(\"Connection string malformed: missing key for assignment\");\n }\n\n const value = part.substring(splitIndex + 1).trim();\n\n output[key] = value;\n }\n\n return output as any;\n}\n\n/**\n * The cancellable async lock instance.\n */\nexport const defaultCancellableLock: CancellableAsyncLock = new CancellableAsyncLockImpl();\n\n/**\n * @internal\n *\n * Describes a Timeout class that can wait for the specified amount of time and then resolve/reject\n * the promise with the given value.\n */\nexport class Timeout {\n private _timer?: ReturnType<typeof setTimeout>;\n\n set<T>(t: number, value?: T): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n this.clear();\n const callback: (args: any) => void = value ? () => reject(new Error(`${value}`)) : resolve;\n this._timer = setTimeout(callback, t);\n });\n }\n\n clear(): void {\n if (this._timer) {\n clearTimeout(this._timer);\n }\n }\n\n wrap<T>(promise: Promise<T>, t: number, value?: T): Promise<T> {\n const wrappedPromise = this._promiseFinally(promise, () => this.clear());\n const timer = this.set(t, value);\n return Promise.race([wrappedPromise, timer]);\n }\n\n private _promiseFinally<T>(promise: Promise<T>, fn: (...args: any[]) => void): Promise<T> {\n const success = (result: T): T => {\n fn();\n return result;\n };\n const error = (e: Error): Promise<never> => {\n fn();\n return Promise.reject(e);\n };\n return Promise.resolve(promise).then(success, error);\n }\n\n static set<T>(t: number, value?: T): Promise<T> {\n return new Timeout().set(t, value);\n }\n\n static wrap<T>(promise: Promise<T>, t: number, value?: T): Promise<T> {\n return new Timeout().wrap(promise, t, value);\n }\n}\n\n/**\n * A wrapper for setTimeout that resolves a promise after t milliseconds.\n * @param delayInMs - The number of milliseconds to be delayed.\n * @param abortSignal - The abortSignal associated with containing operation.\n * @param abortErrorMsg - The abort error message associated with containing operation.\n * @param value - The value to be resolved with after a timeout of t milliseconds.\n * @returns - Resolved promise\n */\nexport async function delay<T>(\n delayInMs: number,\n abortSignal?: AbortSignalLike,\n abortErrorMsg?: string,\n value?: T,\n): Promise<T | void> {\n await wrapperDelay(delayInMs, {\n abortSignal: abortSignal,\n abortErrorMsg: abortErrorMsg,\n });\n if (value !== undefined) {\n return value;\n }\n}\n\n/**\n * Checks if an address is localhost.\n * @param address - The address to check.\n * @returns true if the address is localhost, false otherwise.\n */\nexport function isLoopbackAddress(address: string): boolean {\n return /^(.*:\\/\\/)?(127\\.[\\d.]+|[0:]+1|localhost)/.test(address.toLowerCase());\n}\n\n/**\n * @internal\n *\n * Generates a random number between the given interval\n * @param min - Min number of the range (inclusive).\n * @param max - Max number of the range (inclusive).\n */\nexport function randomNumberFromInterval(min: number, max: number): number {\n return Math.floor(Math.random() * (max - min + 1) + min);\n}\n\n/**\n * @internal\n *\n * Type declaration for a Function type where T is the input to the function and V is the output\n * of the function.\n */\nexport type Func<T, V> = (a: T) => V;\n\n/**\n * @internal\n *\n * Executes an array of promises sequentially. Inspiration of this method is here:\n * https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html. An awesome blog on promises!\n *\n * @param promiseFactories - An array of promise factories(A function that return a promise)\n *\n * @param kickstart - Input to the first promise that is used to kickstart the promise chain.\n * If not provided then the promise chain starts with undefined.\n *\n * @returns A chain of resolved or rejected promises\n */\nexport function executePromisesSequentially(\n promiseFactories: Array<any>,\n kickstart?: unknown,\n): Promise<any> {\n let result = Promise.resolve(kickstart);\n promiseFactories.forEach((promiseFactory) => {\n result = result.then(promiseFactory);\n });\n return result;\n}\n\n/**\n * @internal\n *\n * Determines whether the given connection string is an iothub connection string.\n * @param connectionString - The connection string.\n * @returns boolean.\n */\nexport function isIotHubConnectionString(connectionString: string): boolean {\n connectionString = String(connectionString);\n\n let result: boolean = false;\n const model: any = parseConnectionString<any>(connectionString);\n if (model && model.HostName && model.SharedAccessKey && model.SharedAccessKeyName) {\n result = true;\n }\n return result;\n}\n\n/**\n * @internal\n */\nexport function isString(s: unknown): s is string {\n return typeof s === \"string\";\n}\n\n/**\n * @internal\n */\nexport function isNumber(n: unknown): n is number {\n return typeof n === \"number\";\n}\n"]}
|
package/dist/core-amqp.d.ts
CHANGED
package/dist/esm/index.d.ts
CHANGED
package/dist/esm/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AACnF,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC7F,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACnG,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAClD,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AACtE,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,EACL,qBAAqB,EACrB,oBAAoB,EACpB,qCAAqC,GACtC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,wBAAwB,EACxB,wBAAwB,EACxB,SAAS,EACT,eAAe,EACf,aAAa,EACb,0BAA0B,EAC1B,kBAAkB,GACnB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,KAAK,EACL,qBAAqB,EACrB,sBAAsB,EACtB,YAAY,EACZ,gBAAgB,GACjB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,cAAc,gBAAgB,CAAC;AAC/B,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messageProperties.d.ts","sourceRoot":"","sources":["../../src/messageProperties.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"messageProperties.d.ts","sourceRoot":"","sources":["../../src/messageProperties.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,iBAAiB,IAAI,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAG1E;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IACrC;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;OAEG;IACH,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IACzC;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB;;OAEG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;OAEG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CAKlB;AAED;;GAEG;AAEH,eAAO,MAAM,qBAAqB;IAChC;;;;OAIG;mCAC4B,qBAAqB,GAAG,qBAAqB;IA8C5E;;;;OAIG;qCAC8B,qBAAqB,GAAG,qBAAqB;CA6C/E,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AACnF,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC7F,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AACnG,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAClD,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AACtE,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,EACL,qBAAqB,EACrB,oBAAoB,EACpB,qCAAqC,GACtC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,wBAAwB,EACxB,wBAAwB,EACxB,SAAS,EACT,eAAe,EACf,aAAa,EACb,0BAA0B,EAC1B,kBAAkB,GACnB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,KAAK,EACL,qBAAqB,EACrB,sBAAsB,EACtB,YAAY,EACZ,gBAAgB,GACjB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,cAAc,gBAAgB,CAAC;AAC/B,OAAO,EAAE,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messageProperties.d.ts","sourceRoot":"","sources":["../../src/messageProperties.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"messageProperties.d.ts","sourceRoot":"","sources":["../../src/messageProperties.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,iBAAiB,IAAI,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAG1E;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IACrC;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;OAEG;IACH,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IACzC;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB;;OAEG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;OAEG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;OAEG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CAKlB;AAED;;GAEG;AAEH,eAAO,MAAM,qBAAqB;IAChC;;;;OAIG;mCAC4B,qBAAqB,GAAG,qBAAqB;IA8C5E;;;;OAIG;qCAC8B,qBAAqB,GAAG,qBAAqB;CA6C/E,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@azure/core-amqp",
|
|
3
3
|
"sdk-type": "client",
|
|
4
|
-
"version": "4.4.0-alpha.
|
|
4
|
+
"version": "4.4.0-alpha.20240704.2",
|
|
5
5
|
"description": "Common library for amqp based azure sdks like @azure/event-hubs.",
|
|
6
6
|
"author": "Microsoft Corporation",
|
|
7
7
|
"license": "MIT",
|
|
@@ -101,8 +101,8 @@
|
|
|
101
101
|
"eslint": "^8.57.0",
|
|
102
102
|
"playwright": "^1.43.1",
|
|
103
103
|
"rimraf": "^5.0.7",
|
|
104
|
-
"tshy": "^1.
|
|
105
|
-
"typescript": "~5.
|
|
104
|
+
"tshy": "^1.17.0",
|
|
105
|
+
"typescript": "~5.5.3",
|
|
106
106
|
"vite": "^5.2.11",
|
|
107
107
|
"vite-plugin-node-polyfills": "^0.22.0",
|
|
108
108
|
"vitest": "^1.6.0",
|
|
@@ -125,5 +125,6 @@
|
|
|
125
125
|
"react-native"
|
|
126
126
|
],
|
|
127
127
|
"selfLink": false
|
|
128
|
-
}
|
|
128
|
+
},
|
|
129
|
+
"module": "./dist/esm/index.js"
|
|
129
130
|
}
|