Socket
Socket
Sign inDemoInstall

@azure/core-rest-pipeline

Package Overview
Dependencies
Maintainers
3
Versions
290
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@azure/core-rest-pipeline - npm Package Compare versions

Comparing version 1.1.0-alpha.20210521.1 to 1.1.0-alpha.20210610.1

6

CHANGELOG.md
# Release History
## 1.1.0-beta.3 (Unreleased)
## 1.1.0-beta.4 (Unreleased)
## 1.1.0-beta.3 (2021-06-03)
- Merged `bearerTokenChallengeAuthenticationPolicy` into `bearerTokenAuthenticationPolicy`. This will keep the functionality of `bearerTokenAuthenticationPolicy`, but also adds the `challengeCallbacks` feature.
## 1.1.0-beta.2 (2021-05-20)

@@ -7,0 +11,0 @@

2

dist-esm/src/constants.js
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
export const SDK_VERSION = "1.1.0-beta.3";
export const SDK_VERSION = "1.1.0-beta.4";
//# sourceMappingURL=constants.js.map

@@ -20,4 +20,3 @@ // Copyright (c) Microsoft Corporation.

export { bearerTokenAuthenticationPolicy, bearerTokenAuthenticationPolicyName } from "./policies/bearerTokenAuthenticationPolicy";
export { bearerTokenChallengeAuthenticationPolicy, bearerTokenChallengeAuthenticationPolicyName } from "./policies/bearerTokenChallengeAuthenticationPolicy";
export { ndJsonPolicy, ndJsonPolicyName } from "./policies/ndJsonPolicy";
//# sourceMappingURL=index.js.map
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { __awaiter } from "tslib";
import * as http from "http";

@@ -54,114 +53,112 @@ import * as https from "https";

*/
sendRequest(request) {
return __awaiter(this, void 0, void 0, function* () {
const abortController = new AbortController();
let abortListener;
if (request.abortSignal) {
if (request.abortSignal.aborted) {
throw new AbortError("The operation was aborted.");
}
abortListener = (event) => {
if (event.type === "abort") {
abortController.abort();
}
};
request.abortSignal.addEventListener("abort", abortListener);
async sendRequest(request) {
const abortController = new AbortController();
let abortListener;
if (request.abortSignal) {
if (request.abortSignal.aborted) {
throw new AbortError("The operation was aborted.");
}
if (request.timeout > 0) {
setTimeout(() => {
abortListener = (event) => {
if (event.type === "abort") {
abortController.abort();
}, request.timeout);
}
const acceptEncoding = request.headers.get("Accept-Encoding");
const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate"));
let body = request.body;
if (body && !request.headers.has("Content-Length")) {
const bodyLength = getBodyLength(body);
if (bodyLength !== null) {
request.headers.set("Content-Length", bodyLength);
}
};
request.abortSignal.addEventListener("abort", abortListener);
}
if (request.timeout > 0) {
setTimeout(() => {
abortController.abort();
}, request.timeout);
}
const acceptEncoding = request.headers.get("Accept-Encoding");
const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate"));
let body = request.body;
if (body && !request.headers.has("Content-Length")) {
const bodyLength = getBodyLength(body);
if (bodyLength !== null) {
request.headers.set("Content-Length", bodyLength);
}
let responseStream;
try {
const result = yield new Promise((resolve, reject) => {
if (body && request.onUploadProgress) {
const onUploadProgress = request.onUploadProgress;
const uploadReportStream = new ReportTransform(onUploadProgress);
uploadReportStream.on("error", reject);
if (isReadableStream(body)) {
body.pipe(uploadReportStream);
}
else {
uploadReportStream.end(body);
}
body = uploadReportStream;
}
let responseStream;
try {
const result = await new Promise((resolve, reject) => {
if (body && request.onUploadProgress) {
const onUploadProgress = request.onUploadProgress;
const uploadReportStream = new ReportTransform(onUploadProgress);
uploadReportStream.on("error", reject);
if (isReadableStream(body)) {
body.pipe(uploadReportStream);
}
const req = this.makeRequest(request, (res) => __awaiter(this, void 0, void 0, function* () {
var _a, _b;
const headers = getResponseHeaders(res);
const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0;
const response = {
status,
headers,
request
};
responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res;
const onDownloadProgress = request.onDownloadProgress;
if (onDownloadProgress) {
const downloadReportStream = new ReportTransform(onDownloadProgress);
downloadReportStream.on("error", reject);
responseStream.pipe(downloadReportStream);
responseStream = downloadReportStream;
}
if ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(response.status)) {
response.readableStreamBody = responseStream;
}
else {
response.bodyAsText = yield streamToText(responseStream);
}
resolve(response);
}));
req.on("error", (err) => {
reject(new RestError(err.message, { code: RestError.REQUEST_SEND_ERROR, request }));
});
abortController.signal.addEventListener("abort", () => {
req.abort();
reject(new AbortError("The operation was aborted."));
});
if (body && isReadableStream(body)) {
body.pipe(req);
else {
uploadReportStream.end(body);
}
else if (body) {
req.end(body);
body = uploadReportStream;
}
const req = this.makeRequest(request, async (res) => {
var _a, _b;
const headers = getResponseHeaders(res);
const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0;
const response = {
status,
headers,
request
};
responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res;
const onDownloadProgress = request.onDownloadProgress;
if (onDownloadProgress) {
const downloadReportStream = new ReportTransform(onDownloadProgress);
downloadReportStream.on("error", reject);
responseStream.pipe(downloadReportStream);
responseStream = downloadReportStream;
}
if ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(response.status)) {
response.readableStreamBody = responseStream;
}
else {
// streams don't like "undefined" being passed as data
req.end();
response.bodyAsText = await streamToText(responseStream);
}
resolve(response);
});
return result;
}
finally {
// clean up event listener
if (request.abortSignal && abortListener) {
let uploadStreamDone = Promise.resolve();
if (isReadableStream(body)) {
uploadStreamDone = isStreamComplete(body);
}
let downloadStreamDone = Promise.resolve();
if (isReadableStream(responseStream)) {
downloadStreamDone = isStreamComplete(responseStream);
}
Promise.all([uploadStreamDone, downloadStreamDone])
.then(() => {
var _a;
(_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener);
return;
})
.catch((e) => {
logger.warning("Error when cleaning up abortListener on httpRequest", e);
});
req.on("error", (err) => {
reject(new RestError(err.message, { code: RestError.REQUEST_SEND_ERROR, request }));
});
abortController.signal.addEventListener("abort", () => {
req.abort();
reject(new AbortError("The operation was aborted."));
});
if (body && isReadableStream(body)) {
body.pipe(req);
}
else if (body) {
req.end(body);
}
else {
// streams don't like "undefined" being passed as data
req.end();
}
});
return result;
}
finally {
// clean up event listener
if (request.abortSignal && abortListener) {
let uploadStreamDone = Promise.resolve();
if (isReadableStream(body)) {
uploadStreamDone = isStreamComplete(body);
}
let downloadStreamDone = Promise.resolve();
if (isReadableStream(responseStream)) {
downloadStreamDone = isStreamComplete(responseStream);
}
Promise.all([uploadStreamDone, downloadStreamDone])
.then(() => {
var _a;
(_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener);
return;
})
.catch((e) => {
logger.warning("Error when cleaning up abortListener on httpRequest", e);
});
}
});
}
}

@@ -168,0 +165,0 @@ makeRequest(request, callback) {

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { __awaiter } from "tslib";
import { createTokenCycler } from "../util/tokenCycler";

@@ -10,2 +9,27 @@ /**

/**
* Default authorize request handler
*/
async function defaultAuthorizeRequest(options) {
const { scopes, getAccessToken, request } = options;
const getTokenOptions = {
abortSignal: request.abortSignal,
tracingOptions: request.tracingOptions
};
const accessToken = await getAccessToken(scopes, getTokenOptions);
if (accessToken) {
options.request.headers.set("Authorization", `Bearer ${accessToken.token}`);
}
}
/**
* We will retrieve the challenge only if the response status code was 401,
* and if the response contained the header "WWW-Authenticate" with a non-empty value.
*/
function getChallenge(response) {
const challenge = response.headers.get("WWW-Authenticate");
if (response.status === 401 && challenge) {
return challenge;
}
return;
}
/**
* A policy that can request a token from a TokenCredential implementation and

@@ -15,3 +39,5 @@ * then apply it to the Authorization header of a request as a Bearer token.

export function bearerTokenAuthenticationPolicy(options) {
const { credential, scopes } = options;
var _a;
const { credential, scopes, challengeCallbacks } = options;
const callbacks = Object.assign({ authorizeRequest: (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) !== null && _a !== void 0 ? _a : defaultAuthorizeRequest, authorizeRequestOnChallenge: challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge }, challengeCallbacks);
// This function encapsulates the entire process of reliably retrieving the token

@@ -21,14 +47,55 @@ // The options are left out of the public API until there's demand to configure this.

// in order to pass through the `options` object.
const cycler = createTokenCycler(credential /* , options */);
const getAccessToken = credential
? createTokenCycler(credential /* , options */)
: () => Promise.resolve(null);
return {
name: bearerTokenAuthenticationPolicyName,
sendRequest(request, next) {
return __awaiter(this, void 0, void 0, function* () {
const { token } = yield cycler.getToken(scopes, {
abortSignal: request.abortSignal,
tracingOptions: request.tracingOptions
/**
* If there's no challenge parameter:
* - It will try to retrieve the token using the cache, or the credential's getToken.
* - Then it will try the next policy with or without the retrieved token.
*
* It uses the challenge parameters to:
* - Skip a first attempt to get the token from the credential if there's no cached token,
* since it expects the token to be retrievable only after the challenge.
* - Prepare the outgoing request if the `prepareRequest` method has been provided.
* - Send an initial request to receive the challenge if it fails.
* - Process a challenge if the response contains it.
* - Retrieve a token with the challenge information, then re-send the request.
*/
async sendRequest(request, next) {
await callbacks.authorizeRequest({
scopes: Array.isArray(scopes) ? scopes : [scopes],
request,
getAccessToken
});
let response;
let error;
try {
response = await next(request);
}
catch (err) {
error = err;
response = err.response;
}
if (callbacks.authorizeRequestOnChallenge &&
(response === null || response === void 0 ? void 0 : response.status) === 401 &&
getChallenge(response)) {
// processes challenge
const shouldSendRequest = await callbacks.authorizeRequestOnChallenge({
scopes: Array.isArray(scopes) ? scopes : [scopes],
request,
response,
getAccessToken
});
request.headers.set("Authorization", `Bearer ${token}`);
return next(request);
});
if (shouldSendRequest) {
return next(request);
}
}
if (error) {
throw error;
}
else {
return response;
}
}

@@ -35,0 +102,0 @@ };

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { __awaiter } from "tslib";
/**

@@ -15,7 +14,5 @@ * The programmatic identifier of the decompressResponsePolicy.

name: decompressResponsePolicyName,
sendRequest(request, next) {
return __awaiter(this, void 0, void 0, function* () {
request.headers.set("Accept-Encoding", "gzip,deflate");
return next(request);
});
async sendRequest(request, next) {
request.headers.set("Accept-Encoding", "gzip,deflate");
return next(request);
}

@@ -22,0 +19,0 @@ };

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { __awaiter } from "tslib";
import { logger } from "../log";

@@ -66,51 +65,47 @@ import { delay, getRandomIntegerInclusive } from "../util/helpers";

}
function retry(next, retryData, request, response, requestError) {
async function retry(next, retryData, request, response, requestError) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
retryData = updateRetryData(retryData, requestError);
const isAborted = (_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted;
if (!isAborted && shouldRetry(response === null || response === void 0 ? void 0 : response.status, retryData)) {
logger.info(`Retrying request in ${retryData.retryInterval}`);
try {
yield delay(retryData.retryInterval);
const res = yield next(request);
return retry(next, retryData, request, res);
}
catch (e) {
return retry(next, retryData, request, response, e);
}
retryData = updateRetryData(retryData, requestError);
const isAborted = (_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted;
if (!isAborted && shouldRetry(response === null || response === void 0 ? void 0 : response.status, retryData)) {
logger.info(`Retrying request in ${retryData.retryInterval}`);
try {
await delay(retryData.retryInterval);
const res = await next(request);
return retry(next, retryData, request, res);
}
else if (isAborted || requestError || !response) {
// If the operation failed in the end, return all errors instead of just the last one
const err = retryData.error ||
new RestError("Failed to send the request.", {
code: RestError.REQUEST_SEND_ERROR,
statusCode: response === null || response === void 0 ? void 0 : response.status,
request: response === null || response === void 0 ? void 0 : response.request,
response
});
throw err;
catch (e) {
return retry(next, retryData, request, response, e);
}
else {
return response;
}
});
}
else if (isAborted || requestError || !response) {
// If the operation failed in the end, return all errors instead of just the last one
const err = retryData.error ||
new RestError("Failed to send the request.", {
code: RestError.REQUEST_SEND_ERROR,
statusCode: response === null || response === void 0 ? void 0 : response.status,
request: response === null || response === void 0 ? void 0 : response.request,
response
});
throw err;
}
else {
return response;
}
}
return {
name: exponentialRetryPolicyName,
sendRequest(request, next) {
return __awaiter(this, void 0, void 0, function* () {
const retryData = {
retryCount: 0,
retryInterval: 0
};
try {
const response = yield next(request);
return retry(next, retryData, request, response);
}
catch (e) {
const error = e;
return retry(next, retryData, request, error.response, error);
}
});
async sendRequest(request, next) {
const retryData = {
retryCount: 0,
retryInterval: 0
};
try {
const response = await next(request);
return retry(next, retryData, request, response);
}
catch (e) {
const error = e;
return retry(next, retryData, request, error.response, error);
}
}

@@ -117,0 +112,0 @@ };

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { __awaiter } from "tslib";
/**

@@ -14,28 +13,26 @@ * The programmatic identifier of the formDataPolicy.

name: formDataPolicyName,
sendRequest(request, next) {
return __awaiter(this, void 0, void 0, function* () {
if (request.formData) {
const formData = request.formData;
const requestForm = new FormData();
for (const formKey of Object.keys(formData)) {
const formValue = formData[formKey];
if (Array.isArray(formValue)) {
for (const subValue of formValue) {
requestForm.append(formKey, subValue);
}
async sendRequest(request, next) {
if (request.formData) {
const formData = request.formData;
const requestForm = new FormData();
for (const formKey of Object.keys(formData)) {
const formValue = formData[formKey];
if (Array.isArray(formValue)) {
for (const subValue of formValue) {
requestForm.append(formKey, subValue);
}
else {
requestForm.append(formKey, formValue);
}
}
request.body = requestForm;
request.formData = undefined;
const contentType = request.headers.get("Content-Type");
if (contentType && contentType.indexOf("multipart/form-data") !== -1) {
// browser will automatically apply a suitable content-type header
request.headers.delete("Content-Type");
else {
requestForm.append(formKey, formValue);
}
}
return next(request);
});
request.body = requestForm;
request.formData = undefined;
const contentType = request.headers.get("Content-Type");
if (contentType && contentType.indexOf("multipart/form-data") !== -1) {
// browser will automatically apply a suitable content-type header
request.headers.delete("Content-Type");
}
}
return next(request);
}

@@ -42,0 +39,0 @@ };

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { __awaiter } from "tslib";
import FormData from "form-data";

@@ -15,50 +14,46 @@ /**

name: formDataPolicyName,
sendRequest(request, next) {
return __awaiter(this, void 0, void 0, function* () {
if (request.formData) {
prepareFormData(request.formData, request);
}
return next(request);
});
async sendRequest(request, next) {
if (request.formData) {
prepareFormData(request.formData, request);
}
return next(request);
}
};
}
function prepareFormData(formData, request) {
return __awaiter(this, void 0, void 0, function* () {
const requestForm = new FormData();
for (const formKey of Object.keys(formData)) {
const formValue = formData[formKey];
if (Array.isArray(formValue)) {
for (const subValue of formValue) {
requestForm.append(formKey, subValue);
}
async function prepareFormData(formData, request) {
const requestForm = new FormData();
for (const formKey of Object.keys(formData)) {
const formValue = formData[formKey];
if (Array.isArray(formValue)) {
for (const subValue of formValue) {
requestForm.append(formKey, subValue);
}
else {
requestForm.append(formKey, formValue);
}
}
request.body = requestForm;
request.formData = undefined;
const contentType = request.headers.get("Content-Type");
if (contentType && contentType.indexOf("multipart/form-data") !== -1) {
request.headers.set("Content-Type", `multipart/form-data; boundary=${requestForm.getBoundary()}`);
else {
requestForm.append(formKey, formValue);
}
try {
const contentLength = yield new Promise((resolve, reject) => {
requestForm.getLength((err, length) => {
if (err) {
reject(err);
}
else {
resolve(length);
}
});
}
request.body = requestForm;
request.formData = undefined;
const contentType = request.headers.get("Content-Type");
if (contentType && contentType.indexOf("multipart/form-data") !== -1) {
request.headers.set("Content-Type", `multipart/form-data; boundary=${requestForm.getBoundary()}`);
}
try {
const contentLength = await new Promise((resolve, reject) => {
requestForm.getLength((err, length) => {
if (err) {
reject(err);
}
else {
resolve(length);
}
});
request.headers.set("Content-Length", contentLength);
}
catch (e) {
// ignore setting the length if this fails
}
});
});
request.headers.set("Content-Length", contentLength);
}
catch (e) {
// ignore setting the length if this fails
}
}
//# sourceMappingURL=formDataPolicy.js.map
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { __awaiter } from "tslib";
import { logger as coreLogger } from "../log";

@@ -23,13 +22,11 @@ import { Sanitizer } from "../util/sanitizer";

name: logPolicyName,
sendRequest(request, next) {
return __awaiter(this, void 0, void 0, function* () {
if (!logger.enabled) {
return next(request);
}
logger(`Request: ${sanitizer.sanitize(request)}`);
const response = yield next(request);
logger(`Response status code: ${response.status}`);
logger(`Headers: ${sanitizer.sanitize(response.headers)}`);
return response;
});
async sendRequest(request, next) {
if (!logger.enabled) {
return next(request);
}
logger(`Request: ${sanitizer.sanitize(request)}`);
const response = await next(request);
logger(`Response status code: ${response.status}`);
logger(`Headers: ${sanitizer.sanitize(response.headers)}`);
return response;
}

@@ -36,0 +33,0 @@ };

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { __awaiter } from "tslib";
/**

@@ -14,13 +13,11 @@ * The programmatic identifier of the ndJsonPolicy.

name: ndJsonPolicyName,
sendRequest(request, next) {
return __awaiter(this, void 0, void 0, function* () {
// There currently isn't a good way to bypass the serializer
if (typeof request.body === "string" && request.body.startsWith("[")) {
const body = JSON.parse(request.body);
if (Array.isArray(body)) {
request.body = body.map((item) => JSON.stringify(item) + "\n").join("");
}
async sendRequest(request, next) {
// There currently isn't a good way to bypass the serializer
if (typeof request.body === "string" && request.body.startsWith("[")) {
const body = JSON.parse(request.body);
if (Array.isArray(body)) {
request.body = body.map((item) => JSON.stringify(item) + "\n").join("");
}
return next(request);
});
}
return next(request);
}

@@ -27,0 +24,0 @@ };

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { __awaiter } from "tslib";
import { HttpsProxyAgent } from "https-proxy-agent";

@@ -156,12 +155,10 @@ import { HttpProxyAgent } from "http-proxy-agent";

name: proxyPolicyName,
sendRequest(request, next) {
return __awaiter(this, void 0, void 0, function* () {
if (!request.proxySettings && !isBypassed(request.url)) {
request.proxySettings = proxySettings;
}
if (request.proxySettings) {
setProxyAgentOnRequest(request);
}
return next(request);
});
async sendRequest(request, next) {
if (!request.proxySettings && !isBypassed(request.url)) {
request.proxySettings = proxySettings;
}
if (request.proxySettings) {
setProxyAgentOnRequest(request);
}
return next(request);
}

@@ -168,0 +165,0 @@ };

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { __awaiter } from "tslib";
import { URL } from "../util/url";

@@ -22,36 +21,32 @@ /**

name: redirectPolicyName,
sendRequest(request, next) {
return __awaiter(this, void 0, void 0, function* () {
const response = yield next(request);
return handleRedirect(next, response, maxRetries);
});
async sendRequest(request, next) {
const response = await next(request);
return handleRedirect(next, response, maxRetries);
}
};
}
function handleRedirect(next, response, maxRetries, currentRetries = 0) {
return __awaiter(this, void 0, void 0, function* () {
const { request, status, headers } = response;
const locationHeader = headers.get("location");
if (locationHeader &&
(status === 300 ||
(status === 301 && allowedRedirect.includes(request.method)) ||
(status === 302 && allowedRedirect.includes(request.method)) ||
(status === 303 && request.method === "POST") ||
status === 307) &&
currentRetries < maxRetries) {
const url = new URL(locationHeader, request.url);
request.url = url.toString();
// POST request with Status code 303 should be converted into a
// redirected GET request if the redirect url is present in the location header
if (status === 303) {
request.method = "GET";
request.headers.delete("Content-Length");
delete request.body;
}
const res = yield next(request);
return handleRedirect(next, res, maxRetries, currentRetries + 1);
async function handleRedirect(next, response, maxRetries, currentRetries = 0) {
const { request, status, headers } = response;
const locationHeader = headers.get("location");
if (locationHeader &&
(status === 300 ||
(status === 301 && allowedRedirect.includes(request.method)) ||
(status === 302 && allowedRedirect.includes(request.method)) ||
(status === 303 && request.method === "POST") ||
status === 307) &&
currentRetries < maxRetries) {
const url = new URL(locationHeader, request.url);
request.url = url.toString();
// POST request with Status code 303 should be converted into a
// redirected GET request if the redirect url is present in the location header
if (status === 303) {
request.method = "GET";
request.headers.delete("Content-Length");
delete request.body;
}
return response;
});
const res = await next(request);
return handleRedirect(next, res, maxRetries, currentRetries + 1);
}
return response;
}
//# sourceMappingURL=redirectPolicy.js.map
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { __awaiter } from "tslib";
/**

@@ -17,9 +16,7 @@ * The programmatic identifier of the setClientRequestIdPolicy.

name: setClientRequestIdPolicyName,
sendRequest(request, next) {
return __awaiter(this, void 0, void 0, function* () {
if (!request.headers.has(requestIdHeaderName)) {
request.headers.set(requestIdHeaderName, request.requestId);
}
return next(request);
});
async sendRequest(request, next) {
if (!request.headers.has(requestIdHeaderName)) {
request.headers.set(requestIdHeaderName, request.requestId);
}
return next(request);
}

@@ -26,0 +23,0 @@ };

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { __awaiter } from "tslib";
import { logger } from "../log";

@@ -52,49 +51,45 @@ import { RestError } from "../restError";

}
function retry(next, retryData, request, response, requestError) {
return __awaiter(this, void 0, void 0, function* () {
retryData = updateRetryData(retryData, requestError);
if (shouldRetry(retryData, requestError)) {
try {
logger.info(`Retrying request in ${retryData.retryInterval}`);
yield delay(retryData.retryInterval);
const res = yield next(request);
return retry(next, retryData, request, res);
}
catch (e) {
return retry(next, retryData, request, response, e);
}
async function retry(next, retryData, request, response, requestError) {
retryData = updateRetryData(retryData, requestError);
if (shouldRetry(retryData, requestError)) {
try {
logger.info(`Retrying request in ${retryData.retryInterval}`);
await delay(retryData.retryInterval);
const res = await next(request);
return retry(next, retryData, request, res);
}
else if (requestError || !response) {
// If the operation failed in the end, return all errors instead of just the last one
const err = retryData.error ||
new RestError("Failed to send the request.", {
code: RestError.REQUEST_SEND_ERROR,
statusCode: response === null || response === void 0 ? void 0 : response.status,
request: response === null || response === void 0 ? void 0 : response.request,
response
});
throw err;
catch (e) {
return retry(next, retryData, request, response, e);
}
else {
return response;
}
});
}
else if (requestError || !response) {
// If the operation failed in the end, return all errors instead of just the last one
const err = retryData.error ||
new RestError("Failed to send the request.", {
code: RestError.REQUEST_SEND_ERROR,
statusCode: response === null || response === void 0 ? void 0 : response.status,
request: response === null || response === void 0 ? void 0 : response.request,
response
});
throw err;
}
else {
return response;
}
}
return {
name: systemErrorRetryPolicyName,
sendRequest(request, next) {
return __awaiter(this, void 0, void 0, function* () {
const retryData = {
retryCount: 0,
retryInterval: 0
};
try {
const response = yield next(request);
return retry(next, retryData, request, response);
}
catch (e) {
const error = e;
return retry(next, retryData, request, error.response, error);
}
});
async sendRequest(request, next) {
const retryData = {
retryCount: 0,
retryInterval: 0
};
try {
const response = await next(request);
return retry(next, retryData, request, response);
}
catch (e) {
const error = e;
return retry(next, retryData, request, error.response, error);
}
}

@@ -101,0 +96,0 @@ };

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { __awaiter } from "tslib";
import { delay } from "../util/helpers";

@@ -20,18 +19,16 @@ /**

name: throttlingRetryPolicyName,
sendRequest(request, next) {
return __awaiter(this, void 0, void 0, function* () {
const response = yield next(request);
if (response.status !== 429) {
return response;
async sendRequest(request, next) {
const response = await next(request);
if (response.status !== 429) {
return response;
}
const retryAfterHeader = response.headers.get("Retry-After");
if (retryAfterHeader) {
const delayInMs = parseRetryAfterHeader(retryAfterHeader);
if (delayInMs) {
await delay(delayInMs);
return next(request);
}
const retryAfterHeader = response.headers.get("Retry-After");
if (retryAfterHeader) {
const delayInMs = parseRetryAfterHeader(retryAfterHeader);
if (delayInMs) {
yield delay(delayInMs);
return next(request);
}
}
return response;
});
}
return response;
}

@@ -38,0 +35,0 @@ };

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { __awaiter } from "tslib";
import { getTraceParentHeader, createSpanFunction, SpanStatusCode } from "@azure/core-tracing";

@@ -26,56 +25,54 @@ import { SpanKind } from "@azure/core-tracing";

name: tracingPolicyName,
sendRequest(request, next) {
async sendRequest(request, next) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
if (!((_a = request.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext)) {
return next(request);
}
// create a new span
const tracingOptions = Object.assign(Object.assign({}, request.tracingOptions), { spanOptions: Object.assign(Object.assign({}, request.tracingOptions.spanOptions), { kind: SpanKind.CLIENT }) });
const url = new URL(request.url);
const path = url.pathname || "/";
const { span } = createSpan(path, { tracingOptions });
span.setAttributes({
"http.method": request.method,
"http.url": request.url,
requestId: request.requestId
});
if (userAgent) {
span.setAttribute("http.user_agent", userAgent);
}
try {
// set headers
const spanContext = span.context();
const traceParentHeader = getTraceParentHeader(spanContext);
if (traceParentHeader) {
request.headers.set("traceparent", traceParentHeader);
const traceState = spanContext.traceState && spanContext.traceState.serialize();
// if tracestate is set, traceparent MUST be set, so only set tracestate after traceparent
if (traceState) {
request.headers.set("tracestate", traceState);
}
if (!((_a = request.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext)) {
return next(request);
}
// create a new span
const tracingOptions = Object.assign(Object.assign({}, request.tracingOptions), { spanOptions: Object.assign(Object.assign({}, request.tracingOptions.spanOptions), { kind: SpanKind.CLIENT }) });
const url = new URL(request.url);
const path = url.pathname || "/";
const { span } = createSpan(path, { tracingOptions });
span.setAttributes({
"http.method": request.method,
"http.url": request.url,
requestId: request.requestId
});
if (userAgent) {
span.setAttribute("http.user_agent", userAgent);
}
try {
// set headers
const spanContext = span.context();
const traceParentHeader = getTraceParentHeader(spanContext);
if (traceParentHeader) {
request.headers.set("traceparent", traceParentHeader);
const traceState = spanContext.traceState && spanContext.traceState.serialize();
// if tracestate is set, traceparent MUST be set, so only set tracestate after traceparent
if (traceState) {
request.headers.set("tracestate", traceState);
}
const response = yield next(request);
span.setAttribute("http.status_code", response.status);
const serviceRequestId = response.headers.get("x-ms-request-id");
if (serviceRequestId) {
span.setAttribute("serviceRequestId", serviceRequestId);
}
span.setStatus({
code: SpanStatusCode.OK
});
return response;
}
catch (err) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: err.message
});
span.setAttribute("http.status_code", err.statusCode);
throw err;
const response = await next(request);
span.setAttribute("http.status_code", response.status);
const serviceRequestId = response.headers.get("x-ms-request-id");
if (serviceRequestId) {
span.setAttribute("serviceRequestId", serviceRequestId);
}
finally {
span.end();
}
});
span.setStatus({
code: SpanStatusCode.OK
});
return response;
}
catch (err) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: err.message
});
span.setAttribute("http.status_code", err.statusCode);
throw err;
}
finally {
span.end();
}
}

@@ -82,0 +79,0 @@ };

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { __awaiter } from "tslib";
import { getUserAgentValue, getUserAgentHeaderName } from "../util/userAgent";

@@ -19,9 +18,7 @@ const UserAgentHeaderName = getUserAgentHeaderName();

name: userAgentPolicyName,
sendRequest(request, next) {
return __awaiter(this, void 0, void 0, function* () {
if (!request.headers.has(UserAgentHeaderName)) {
request.headers.set(UserAgentHeaderName, userAgentValue);
}
return next(request);
});
async sendRequest(request, next) {
if (!request.headers.has(UserAgentHeaderName)) {
request.headers.set(UserAgentHeaderName, userAgentValue);
}
return next(request);
}

@@ -28,0 +25,0 @@ };

@@ -6,2 +6,3 @@ // Copyright (c) Microsoft Corporation.

* A constant that indicates whether the environment the code is running is Node.JS.
* @internal
*/

@@ -11,2 +12,3 @@ export const isNode = typeof process !== "undefined" && Boolean(process.version) && Boolean((_a = process.versions) === null || _a === void 0 ? void 0 : _a.node);

* A wrapper for setTimeout that resolves a promise after t milliseconds.
* @internal
* @param t - The number of milliseconds to be delayed.

@@ -38,2 +40,13 @@ * @param value - The value to be resolved with after a timeout of t milliseconds.

}
/**
* @internal
* @returns true when input is an object type that is not null, Array, RegExp, or Date.
*/
export function isObject(input) {
return (typeof input === "object" &&
input !== null &&
!Array.isArray(input) &&
!(input instanceof RegExp) &&
!(input instanceof Date));
}
//# sourceMappingURL=helpers.js.map
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { isObject } from "./helpers";
import { URL } from "./url";

@@ -57,33 +58,39 @@ const RedactedString = "REDACTED";

sanitize(obj) {
return JSON.stringify(obj, this.replacer.bind(this), 2);
const seen = new Set();
return JSON.stringify(obj, (key, value) => {
// Ensure Errors include their interesting non-enumerable members
if (value instanceof Error) {
return Object.assign(Object.assign({}, value), { name: value.name, message: value.message });
}
if (key === "headers") {
return this.sanitizeHeaders(value);
}
else if (key === "url") {
return this.sanitizeUrl(value);
}
else if (key === "query") {
return this.sanitizeQuery(value);
}
else if (key === "body") {
// Don't log the request body
return undefined;
}
else if (key === "response") {
// Don't log response again
return undefined;
}
else if (key === "operationSpec") {
// When using sendOperationRequest, the request carries a massive
// field with the autorest spec. No need to log it.
return undefined;
}
else if (Array.isArray(value) || isObject(value)) {
if (seen.has(value)) {
return "[Circular]";
}
seen.add(value);
}
return value;
}, 2);
}
replacer(key, value) {
// Ensure Errors include their interesting non-enumerable members
if (value instanceof Error) {
return Object.assign(Object.assign({}, value), { name: value.name, message: value.message });
}
if (key === "headers") {
return this.sanitizeHeaders(value);
}
else if (key === "url") {
return this.sanitizeUrl(value);
}
else if (key === "query") {
return this.sanitizeQuery(value);
}
else if (key === "body") {
// Don't log the request body
return undefined;
}
else if (key === "response") {
// Don't log response again
return undefined;
}
else if (key === "operationSpec") {
// When using sendOperationRequest, the request carries a massive
// field with the autorest spec. No need to log it.
return undefined;
}
return value;
}
sanitizeHeaders(obj) {

@@ -90,0 +97,0 @@ const sanitized = {};

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { __awaiter } from "tslib";
import { delay } from "./helpers";

@@ -21,33 +20,29 @@ // Default options for the cycler if none are provided

*/
function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) {
return __awaiter(this, void 0, void 0, function* () {
// This wrapper handles exceptions gracefully as long as we haven't exceeded
// the timeout.
function tryGetAccessToken() {
return __awaiter(this, void 0, void 0, function* () {
if (Date.now() < refreshTimeout) {
try {
return yield getAccessToken();
}
catch (_a) {
return null;
}
}
else {
const finalToken = yield getAccessToken();
// Timeout is up, so throw if it's still null
if (finalToken === null) {
throw new Error("Failed to refresh access token.");
}
return finalToken;
}
});
async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) {
// This wrapper handles exceptions gracefully as long as we haven't exceeded
// the timeout.
async function tryGetAccessToken() {
if (Date.now() < refreshTimeout) {
try {
return await getAccessToken();
}
catch (_a) {
return null;
}
}
let token = yield tryGetAccessToken();
while (token === null) {
yield delay(retryIntervalInMs);
token = yield tryGetAccessToken();
else {
const finalToken = await getAccessToken();
// Timeout is up, so throw if it's still null
if (finalToken === null) {
throw new Error("Failed to refresh access token.");
}
return finalToken;
}
return token;
});
}
let token = await tryGetAccessToken();
while (token === null) {
await delay(retryIntervalInMs);
token = await tryGetAccessToken();
}
return token;
}

@@ -130,25 +125,20 @@ /**

}
return {
get cachedToken() {
return token;
},
getToken: (scopes, tokenOptions) => __awaiter(this, void 0, void 0, function* () {
//
// Simple rules:
// - If we MUST refresh, then return the refresh task, blocking
// the pipeline until a token is available.
// - If we SHOULD refresh, then run refresh but don't return it
// (we can still use the cached token).
// - Return the token, since it's fine if we didn't return in
// step 1.
//
if (cycler.mustRefresh)
return refresh(scopes, tokenOptions);
if (cycler.shouldRefresh) {
refresh(scopes, tokenOptions);
}
return token;
})
return async (scopes, tokenOptions) => {
//
// Simple rules:
// - If we MUST refresh, then return the refresh task, blocking
// the pipeline until a token is available.
// - If we SHOULD refresh, then run refresh but don't return it
// (we can still use the cached token).
// - Return the token, since it's fine if we didn't return in
// step 1.
//
if (cycler.mustRefresh)
return refresh(scopes, tokenOptions);
if (cycler.shouldRefresh) {
refresh(scopes, tokenOptions);
}
return token;
};
}
//# sourceMappingURL=tokenCycler.js.map
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { __awaiter } from "tslib";
/// <reference lib="dom" />

@@ -20,60 +19,58 @@ import { AbortError } from "@azure/abort-controller";

*/
sendRequest(request) {
async sendRequest(request) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const url = new URL(request.url);
const isInsecure = url.protocol !== "https:";
if (isInsecure && !request.allowInsecureConnection) {
throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`);
const url = new URL(request.url);
const isInsecure = url.protocol !== "https:";
if (isInsecure && !request.allowInsecureConnection) {
throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`);
}
const xhr = new XMLHttpRequest();
if (request.proxySettings) {
throw new Error("HTTP proxy is not supported in browser environment");
}
const abortSignal = request.abortSignal;
if (abortSignal) {
if (abortSignal.aborted) {
throw new AbortError("The operation was aborted.");
}
const xhr = new XMLHttpRequest();
if (request.proxySettings) {
throw new Error("HTTP proxy is not supported in browser environment");
}
const abortSignal = request.abortSignal;
if (abortSignal) {
if (abortSignal.aborted) {
throw new AbortError("The operation was aborted.");
const listener = () => {
xhr.abort();
};
abortSignal.addEventListener("abort", listener);
xhr.addEventListener("readystatechange", () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
abortSignal.removeEventListener("abort", listener);
}
const listener = () => {
xhr.abort();
};
abortSignal.addEventListener("abort", listener);
xhr.addEventListener("readystatechange", () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
abortSignal.removeEventListener("abort", listener);
}
});
}
addProgressListener(xhr.upload, request.onUploadProgress);
addProgressListener(xhr, request.onDownloadProgress);
xhr.open(request.method, request.url);
xhr.timeout = request.timeout;
xhr.withCredentials = request.withCredentials;
for (const [name, value] of request.headers) {
xhr.setRequestHeader(name, value);
}
xhr.responseType = ((_a = request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.size) ? "blob" : "text";
if (isReadableStream(request.body)) {
throw new Error("Node streams are not supported in browser environment.");
}
xhr.send(request.body === undefined ? null : request.body);
if (xhr.responseType === "blob") {
return new Promise((resolve, reject) => {
handleBlobResponse(xhr, request, resolve, reject);
rejectOnTerminalEvent(request, xhr, reject);
});
}
else {
return new Promise(function (resolve, reject) {
xhr.addEventListener("load", () => resolve({
request,
status: xhr.status,
headers: parseHeaders(xhr),
bodyAsText: xhr.responseText
}));
rejectOnTerminalEvent(request, xhr, reject);
});
}
});
});
}
addProgressListener(xhr.upload, request.onUploadProgress);
addProgressListener(xhr, request.onDownloadProgress);
xhr.open(request.method, request.url);
xhr.timeout = request.timeout;
xhr.withCredentials = request.withCredentials;
for (const [name, value] of request.headers) {
xhr.setRequestHeader(name, value);
}
xhr.responseType = ((_a = request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.size) ? "blob" : "text";
if (isReadableStream(request.body)) {
throw new Error("Node streams are not supported in browser environment.");
}
xhr.send(request.body === undefined ? null : request.body);
if (xhr.responseType === "blob") {
return new Promise((resolve, reject) => {
handleBlobResponse(xhr, request, resolve, reject);
rejectOnTerminalEvent(request, xhr, reject);
});
}
else {
return new Promise(function (resolve, reject) {
xhr.addEventListener("load", () => resolve({
request,
status: xhr.status,
headers: parseHeaders(xhr),
bodyAsText: xhr.responseText
}));
rejectOnTerminalEvent(request, xhr, reject);
});
}
}

@@ -80,0 +77,0 @@ }

{
"name": "@azure/core-rest-pipeline",
"version": "1.1.0-alpha.20210521.1",
"version": "1.1.0-alpha.20210610.1",
"description": "Isomorphic client library for making HTTP requests in node.js and browser.",

@@ -5,0 +5,0 @@ "sdk-type": "client",

@@ -111,3 +111,3 @@ /// <reference types="node" />

*/
credential: TokenCredential;
credential?: TokenCredential;
/**

@@ -117,25 +117,3 @@ * The scopes for which the bearer token applies.

scopes: string | string[];
}
/**
* A policy that can request a token from a TokenCredential implementation and
* then apply it to the Authorization header of a request as a Bearer token.
*/
export declare function bearerTokenChallengeAuthenticationPolicy(options: BearerTokenChallengeAuthenticationPolicyOptions): PipelinePolicy;
/**
* The programmatic identifier of the bearerTokenChallengeAuthenticationPolicy.
*/
export declare const bearerTokenChallengeAuthenticationPolicyName = "bearerTokenChallengeAuthenticationPolicy";
/**
* Options to configure the bearerTokenChallengeAuthenticationPolicy
*/
export declare interface BearerTokenChallengeAuthenticationPolicyOptions {
/**
* The TokenCredential implementation that can supply the bearer token.
*/
credential?: TokenCredential;
/**
* The scopes for which the bearer token applies.
*/
scopes: string[];
/**
* Allows for the processing of [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation) challenges.

@@ -142,0 +120,0 @@ * If provided, it must contain at least the `authorizeRequestOnChallenge` method.

@@ -118,3 +118,3 @@ /// <reference types="node" />

*/
credential: TokenCredential;
credential?: TokenCredential;
/**

@@ -124,28 +124,3 @@ * The scopes for which the bearer token applies.

scopes: string | string[];
}
/**
* A policy that can request a token from a TokenCredential implementation and
* then apply it to the Authorization header of a request as a Bearer token.
*/
export declare function bearerTokenChallengeAuthenticationPolicy(options: BearerTokenChallengeAuthenticationPolicyOptions): PipelinePolicy;
/**
* The programmatic identifier of the bearerTokenChallengeAuthenticationPolicy.
*/
export declare const bearerTokenChallengeAuthenticationPolicyName = "bearerTokenChallengeAuthenticationPolicy";
/**
* Options to configure the bearerTokenChallengeAuthenticationPolicy
*/
export declare interface BearerTokenChallengeAuthenticationPolicyOptions {
/**
* The TokenCredential implementation that can supply the bearer token.
*/
credential?: TokenCredential;
/**
* The scopes for which the bearer token applies.
*/
scopes: string[];
/**
* Allows for the processing of [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation) challenges.

@@ -152,0 +127,0 @@ * If provided, it must contain at least the `authorizeRequestOnChallenge` method.

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc