Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@azure-rest/core-client

Package Overview
Dependencies
Maintainers
1
Versions
246
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

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

Comparing version 1.0.0-alpha.20211103.1 to 1.0.0-alpha.20211104.5

8

CHANGELOG.md
# Release History
## 1.0.0-beta.8 (Unreleased)
### Features Added
## 1.0.0-beta.8 (2021-11-04)
- Add options skipUrlEncoding to support skip path parameter encoding.
### Other Changes
- Add options skipUrlEncoding to support skip path parameter encoding. [#18381](https://github.com/Azure/azure-sdk-for-js/pull/18381)
- Adding more robust handling of request and response body. [#18478](https://github.com/Azure/azure-sdk-for-js/pull/18478)
## 1.0.0-beta.7 (2021-09-02)

@@ -9,0 +11,0 @@

@@ -7,8 +7,6 @@ // Copyright (c) Microsoft Corporation.

*/
export { createDefaultPipeline } from "./clientHelpers";
export { isCertificateCredential } from "./certificateCredential";
export { createRestError } from "./restError";
export * from "./getClient";
export * from "./common";
export * from "./getClient";
export * from "./pathClientTypes";
//# sourceMappingURL=index.js.map
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import { createHttpHeaders, createPipelineRequest, } from "@azure/core-rest-pipeline";
import { createHttpHeaders, createPipelineRequest, RestError, } from "@azure/core-rest-pipeline";
import { getCachedDefaultHttpsClient } from "./clientHelpers";

@@ -14,28 +14,11 @@ /**

export async function sendRequest(method, url, pipeline, options = {}) {
var _a, _b;
const httpClient = getCachedDefaultHttpsClient();
const body = options.body !== undefined ? JSON.stringify(options.body) : undefined;
const headers = createHttpHeaders(Object.assign(Object.assign({ accept: (_a = options.accept) !== null && _a !== void 0 ? _a : "application/json" }, (body !== undefined && {
"content-type": (_b = options.contentType) !== null && _b !== void 0 ? _b : getContentType(options.body),
})), (options.headers ? options.headers : {})));
const request = createPipelineRequest({
url,
method,
body,
headers,
allowInsecureConnection: options.allowInsecureConnection,
});
const result = await pipeline.sendRequest(httpClient, request);
const rawHeaders = result.headers.toJSON();
let parsedBody = undefined;
try {
parsedBody = result.bodyAsText ? JSON.parse(result.bodyAsText) : undefined;
}
catch (_c) {
parsedBody = undefined;
}
const request = buildPipelineRequest(method, url, options);
const response = await pipeline.sendRequest(httpClient, request);
const rawHeaders = response.headers.toJSON();
const parsedBody = getResponseBody(response);
return {
request,
headers: rawHeaders,
status: `${result.status}`,
status: `${response.status}`,
body: parsedBody,

@@ -57,2 +40,76 @@ };

}
function buildPipelineRequest(method, url, options = {}) {
var _a, _b;
const { body, formData } = getRequestBody(options.body, options.contentType);
const hasContent = body !== undefined || formData !== undefined;
const headers = createHttpHeaders(Object.assign(Object.assign(Object.assign({}, (options.headers ? options.headers : {})), { accept: (_a = options.accept) !== null && _a !== void 0 ? _a : "application/json" }), (hasContent && {
"content-type": (_b = options.contentType) !== null && _b !== void 0 ? _b : getContentType(options.body),
})));
return createPipelineRequest({
url,
method,
body,
formData,
headers,
allowInsecureConnection: options.allowInsecureConnection,
});
}
/**
* Prepares the body before sending the request
*/
function getRequestBody(body, contentType = "application/json") {
if (body === undefined) {
return { body: undefined };
}
const firstType = contentType.split(";")[0];
switch (firstType) {
case "multipart/form-data":
return isFormData(body) ? { formData: body } : { body: JSON.stringify(body) };
case "text/plain":
return { body: String(body) };
default:
return { body: JSON.stringify(body) };
}
}
function isFormData(body) {
return body instanceof Object && Object.keys(body).length > 0;
}
/**
* Prepares the response body
*/
function getResponseBody(response) {
var _a, _b;
// Set the default response type
const contentType = (_a = response.headers.get("content-type")) !== null && _a !== void 0 ? _a : "";
const firstType = contentType.split(";")[0];
const bodyToParse = (_b = response.bodyAsText) !== null && _b !== void 0 ? _b : "";
if (firstType === "text/plain") {
return String(bodyToParse);
}
// Default to "application/json" and fallback to string;
try {
return bodyToParse ? JSON.parse(bodyToParse) : undefined;
}
catch (error) {
// If we were supposed to get a JSON object and failed to
// parse, throw a parse error
if (firstType === "application/json") {
throw createParseError(response, error);
}
// We are not sure how to handle the response so we return it as
// plain text.
return String(bodyToParse);
}
}
function createParseError(response, err) {
var _a;
const msg = `Error "${err}" occurred while parsing the response body - ${response.bodyAsText}.`;
const errCode = (_a = err.code) !== null && _a !== void 0 ? _a : RestError.PARSE_ERROR;
return new RestError(msg, {
code: errCode,
statusCode: response.status,
request: response.request,
response: response,
});
}
//# sourceMappingURL=sendRequest.js.map

@@ -6,4 +6,4 @@ 'use strict';

var coreRestPipeline = require('@azure/core-rest-pipeline');
var coreAuth = require('@azure/core-auth');
var coreUtil = require('@azure/core-util');
var coreAuth = require('@azure/core-auth');
var url = require('url');

@@ -14,66 +14,2 @@

/**
* The programmatic identifier of the bearerTokenAuthenticationPolicy.
*/
const keyCredentialAuthenticationPolicyName = "keyCredentialAuthenticationPolicy";
function keyCredentialAuthenticationPolicy(credential, apiKeyHeaderName) {
return {
name: keyCredentialAuthenticationPolicyName,
async sendRequest(request, next) {
request.headers.set(apiKeyHeaderName, credential.key);
return next(request);
},
};
}
// Copyright (c) Microsoft Corporation.
let cachedHttpClient;
/**
* Creates a default rest pipeline to re-use accross Rest Level Clients
*/
function createDefaultPipeline(baseUrl, credential, options = {}) {
var _a, _b, _c, _d;
const pipeline = coreRestPipeline.createEmptyPipeline();
if (coreUtil.isNode) {
pipeline.addPolicy(coreRestPipeline.proxyPolicy(options.proxyOptions));
pipeline.addPolicy(coreRestPipeline.decompressResponsePolicy());
}
pipeline.addPolicy(coreRestPipeline.formDataPolicy());
pipeline.addPolicy(coreRestPipeline.userAgentPolicy(options.userAgentOptions));
pipeline.addPolicy(coreRestPipeline.setClientRequestIdPolicy());
pipeline.addPolicy(coreRestPipeline.throttlingRetryPolicy(), { phase: "Retry" });
pipeline.addPolicy(coreRestPipeline.systemErrorRetryPolicy(options.retryOptions), { phase: "Retry" });
pipeline.addPolicy(coreRestPipeline.exponentialRetryPolicy(options.retryOptions), { phase: "Retry" });
pipeline.addPolicy(coreRestPipeline.redirectPolicy(options.redirectOptions), { afterPhase: "Retry" });
pipeline.addPolicy(coreRestPipeline.logPolicy(), { afterPhase: "Retry" });
if (credential) {
if (coreAuth.isTokenCredential(credential)) {
const tokenPolicy = coreRestPipeline.bearerTokenAuthenticationPolicy({
credential,
scopes: (_b = (_a = options.credentials) === null || _a === void 0 ? void 0 : _a.scopes) !== null && _b !== void 0 ? _b : `${baseUrl}/.default`,
});
pipeline.addPolicy(tokenPolicy);
}
else if (isKeyCredential(credential)) {
if (!((_c = options.credentials) === null || _c === void 0 ? void 0 : _c.apiKeyHeaderName)) {
throw new Error(`Missing API Key Header Name`);
}
const keyPolicy = keyCredentialAuthenticationPolicy(credential, (_d = options.credentials) === null || _d === void 0 ? void 0 : _d.apiKeyHeaderName);
pipeline.addPolicy(keyPolicy);
}
}
return pipeline;
}
function isKeyCredential(credential) {
return credential.key !== undefined;
}
function getCachedDefaultHttpsClient() {
if (!cachedHttpClient) {
cachedHttpClient = coreRestPipeline.createDefaultHttpClient();
}
return cachedHttpClient;
}
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
* Helper TypeGuard that checks if something is defined or not.

@@ -150,3 +86,67 @@ * @param thing - Anything

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
* The programmatic identifier of the bearerTokenAuthenticationPolicy.
*/
const keyCredentialAuthenticationPolicyName = "keyCredentialAuthenticationPolicy";
function keyCredentialAuthenticationPolicy(credential, apiKeyHeaderName) {
return {
name: keyCredentialAuthenticationPolicyName,
async sendRequest(request, next) {
request.headers.set(apiKeyHeaderName, credential.key);
return next(request);
},
};
}
// Copyright (c) Microsoft Corporation.
let cachedHttpClient;
/**
* Creates a default rest pipeline to re-use accross Rest Level Clients
*/
function createDefaultPipeline(baseUrl, credential, options = {}) {
var _a, _b, _c, _d;
const pipeline = coreRestPipeline.createEmptyPipeline();
if (coreUtil.isNode) {
pipeline.addPolicy(coreRestPipeline.proxyPolicy(options.proxyOptions));
pipeline.addPolicy(coreRestPipeline.decompressResponsePolicy());
}
pipeline.addPolicy(coreRestPipeline.formDataPolicy());
pipeline.addPolicy(coreRestPipeline.userAgentPolicy(options.userAgentOptions));
pipeline.addPolicy(coreRestPipeline.setClientRequestIdPolicy());
pipeline.addPolicy(coreRestPipeline.throttlingRetryPolicy(), { phase: "Retry" });
pipeline.addPolicy(coreRestPipeline.systemErrorRetryPolicy(options.retryOptions), { phase: "Retry" });
pipeline.addPolicy(coreRestPipeline.exponentialRetryPolicy(options.retryOptions), { phase: "Retry" });
pipeline.addPolicy(coreRestPipeline.redirectPolicy(options.redirectOptions), { afterPhase: "Retry" });
pipeline.addPolicy(coreRestPipeline.logPolicy(), { afterPhase: "Retry" });
if (credential) {
if (coreAuth.isTokenCredential(credential)) {
const tokenPolicy = coreRestPipeline.bearerTokenAuthenticationPolicy({
credential,
scopes: (_b = (_a = options.credentials) === null || _a === void 0 ? void 0 : _a.scopes) !== null && _b !== void 0 ? _b : `${baseUrl}/.default`,
});
pipeline.addPolicy(tokenPolicy);
}
else if (isKeyCredential(credential)) {
if (!((_c = options.credentials) === null || _c === void 0 ? void 0 : _c.apiKeyHeaderName)) {
throw new Error(`Missing API Key Header Name`);
}
const keyPolicy = keyCredentialAuthenticationPolicy(credential, (_d = options.credentials) === null || _d === void 0 ? void 0 : _d.apiKeyHeaderName);
pipeline.addPolicy(keyPolicy);
}
}
return pipeline;
}
function isKeyCredential(credential) {
return credential.key !== undefined;
}
function getCachedDefaultHttpsClient() {
if (!cachedHttpClient) {
cachedHttpClient = coreRestPipeline.createDefaultHttpClient();
}
return cachedHttpClient;
}
// Copyright (c) Microsoft Corporation.
/**
* Helper function to send request used by the client

@@ -160,28 +160,11 @@ * @param method - method to use to send the request

async function sendRequest(method, url, pipeline, options = {}) {
var _a, _b;
const httpClient = getCachedDefaultHttpsClient();
const body = options.body !== undefined ? JSON.stringify(options.body) : undefined;
const headers = coreRestPipeline.createHttpHeaders(Object.assign(Object.assign({ accept: (_a = options.accept) !== null && _a !== void 0 ? _a : "application/json" }, (body !== undefined && {
"content-type": (_b = options.contentType) !== null && _b !== void 0 ? _b : getContentType(options.body),
})), (options.headers ? options.headers : {})));
const request = coreRestPipeline.createPipelineRequest({
url,
method,
body,
headers,
allowInsecureConnection: options.allowInsecureConnection,
});
const result = await pipeline.sendRequest(httpClient, request);
const rawHeaders = result.headers.toJSON();
let parsedBody = undefined;
try {
parsedBody = result.bodyAsText ? JSON.parse(result.bodyAsText) : undefined;
}
catch (_c) {
parsedBody = undefined;
}
const request = buildPipelineRequest(method, url, options);
const response = await pipeline.sendRequest(httpClient, request);
const rawHeaders = response.headers.toJSON();
const parsedBody = getResponseBody(response);
return {
request,
headers: rawHeaders,
status: `${result.status}`,
status: `${response.status}`,
body: parsedBody,

@@ -203,2 +186,76 @@ };

}
function buildPipelineRequest(method, url, options = {}) {
var _a, _b;
const { body, formData } = getRequestBody(options.body, options.contentType);
const hasContent = body !== undefined || formData !== undefined;
const headers = coreRestPipeline.createHttpHeaders(Object.assign(Object.assign(Object.assign({}, (options.headers ? options.headers : {})), { accept: (_a = options.accept) !== null && _a !== void 0 ? _a : "application/json" }), (hasContent && {
"content-type": (_b = options.contentType) !== null && _b !== void 0 ? _b : getContentType(options.body),
})));
return coreRestPipeline.createPipelineRequest({
url,
method,
body,
formData,
headers,
allowInsecureConnection: options.allowInsecureConnection,
});
}
/**
* Prepares the body before sending the request
*/
function getRequestBody(body, contentType = "application/json") {
if (body === undefined) {
return { body: undefined };
}
const firstType = contentType.split(";")[0];
switch (firstType) {
case "multipart/form-data":
return isFormData(body) ? { formData: body } : { body: JSON.stringify(body) };
case "text/plain":
return { body: String(body) };
default:
return { body: JSON.stringify(body) };
}
}
function isFormData(body) {
return body instanceof Object && Object.keys(body).length > 0;
}
/**
* Prepares the response body
*/
function getResponseBody(response) {
var _a, _b;
// Set the default response type
const contentType = (_a = response.headers.get("content-type")) !== null && _a !== void 0 ? _a : "";
const firstType = contentType.split(";")[0];
const bodyToParse = (_b = response.bodyAsText) !== null && _b !== void 0 ? _b : "";
if (firstType === "text/plain") {
return String(bodyToParse);
}
// Default to "application/json" and fallback to string;
try {
return bodyToParse ? JSON.parse(bodyToParse) : undefined;
}
catch (error) {
// If we were supposed to get a JSON object and failed to
// parse, throw a parse error
if (firstType === "application/json") {
throw createParseError(response, error);
}
// We are not sure how to handle the response so we return it as
// plain text.
return String(bodyToParse);
}
}
function createParseError(response, err) {
var _a;
const msg = `Error "${err}" occurred while parsing the response body - ${response.bodyAsText}.`;
const errCode = (_a = err.code) !== null && _a !== void 0 ? _a : coreRestPipeline.RestError.PARSE_ERROR;
return new coreRestPipeline.RestError(msg, {
code: errCode,
statusCode: response.status,
request: response.request,
response: response,
});
}

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

exports.createDefaultPipeline = createDefaultPipeline;
exports.createRestError = createRestError;

@@ -318,0 +374,0 @@ exports.getClient = getClient;

{
"name": "@azure-rest/core-client",
"version": "1.0.0-alpha.20211103.1",
"version": "1.0.0-alpha.20211104.5",
"description": "Core library for interfacing with AutoRest rest level generated code",

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

@@ -39,3 +39,9 @@ /**

* This method will be used to send request that would check the path to provide
* strong types
* strong types. When used by the codegen this type gets overriden wit the generated
* types. For example:
* ```typescript
* export type MyClient = Client & {
* path: Routes;
* }
* ```
*/

@@ -46,12 +52,3 @@ path: Function;

*/
pathUnchecked: (path: string, ...args: Array<any>) => {
get: (options?: RequestParameters) => Promise<PathUncheckedResponse>;
post: (options?: RequestParameters) => Promise<PathUncheckedResponse>;
put: (options?: RequestParameters) => Promise<PathUncheckedResponse>;
patch: (options?: RequestParameters) => Promise<PathUncheckedResponse>;
delete: (options?: RequestParameters) => Promise<PathUncheckedResponse>;
head: (options?: RequestParameters) => Promise<PathUncheckedResponse>;
options: (options?: RequestParameters) => Promise<PathUncheckedResponse>;
trace: (options?: RequestParameters) => Promise<PathUncheckedResponse>;
};
pathUnchecked: PathUnchecked;
}

@@ -91,7 +88,2 @@

/**
* Creates a default rest pipeline to re-use accross Rest Level Clients
*/
export declare function createDefaultPipeline(baseUrl: string, credential?: TokenCredential | KeyCredential, options?: ClientOptions): Pipeline;
/**
* Creates a rest error from a PathUnchecked response

@@ -146,2 +138,17 @@ */

/**
* Helper type used to detect parameters in a path template
* text surrounded by \{\} will be considered a path parameter
*/
export declare type PathParameters<TRoute extends string> = TRoute extends `${infer _Head}/{${infer _Param}}${infer Tail}` ? [
pathParameter: string,
...pathParameters: PathParameters<Tail>
] : [
];
/**
* Defines the signature for pathUnchecked.
*/
export declare type PathUnchecked = <TPath extends string>(path: TPath, ...args: PathParameters<TPath>) => ResourceMethods;
/**
* Type to use with pathUnchecked, overrides the body type to any to allow flexibility

@@ -164,3 +171,4 @@ */

* Sets the accept header to send to the service
* defaults to 'application/json'
* defaults to 'application/json'. If also a header "accept" is set
* this property will take precedence.
*/

@@ -177,3 +185,4 @@ accept?: string;

/**
* Set an explicit content-type to send with the request
* Set an explicit content-type to send with the request. If also a header "content-type" is set
* this property will take precedence.
*/

@@ -188,11 +197,39 @@ contentType?: string;

/**
* Helper type used to detect parameters in a path template
* keys surounded by \{\} will be considered a path parameter
* Defines the methods that can be called on a resource
*/
export declare type RouteParams<TRoute extends string> = TRoute extends `${infer _Head}/{${infer _Param}}${infer Tail}` ? [
pathParam: string,
...pathParams: RouteParams<Tail>
] : [
];
export declare interface ResourceMethods {
/**
* Definition of the GET HTTP method for a resource
*/
get: (options?: RequestParameters) => Promise<PathUncheckedResponse>;
/**
* Definition of the POST HTTP method for a resource
*/
post: (options?: RequestParameters) => Promise<PathUncheckedResponse>;
/**
* Definition of the PUT HTTP method for a resource
*/
put: (options?: RequestParameters) => Promise<PathUncheckedResponse>;
/**
* Definition of the PATCH HTTP method for a resource
*/
patch: (options?: RequestParameters) => Promise<PathUncheckedResponse>;
/**
* Definition of the DELETE HTTP method for a resource
*/
delete: (options?: RequestParameters) => Promise<PathUncheckedResponse>;
/**
* Definition of the HEAD HTTP method for a resource
*/
head: (options?: RequestParameters) => Promise<PathUncheckedResponse>;
/**
* Definition of the OPTIONS HTTP method for a resource
*/
options: (options?: RequestParameters) => Promise<PathUncheckedResponse>;
/**
* Definition of the TRACE HTTP method for a resource
*/
trace: (options?: RequestParameters) => Promise<PathUncheckedResponse>;
}
export { }

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

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