@microsoft/microsoft-graph-client
Advanced tools
Comparing version 3.0.2 to 4.0.0-Preview.1
@@ -0,1 +1,2 @@ | ||
/// <reference path="../../../../shims.d.ts" /> | ||
/** | ||
@@ -7,22 +8,13 @@ * ------------------------------------------------------------------------------------------- | ||
*/ | ||
/// <reference path="../../../../shims.d.ts" /> | ||
export { BatchRequestStep, BatchRequestData, BatchRequestContent, RequestData, BatchRequestBody } from "../content/BatchRequestContent"; | ||
export { BaseBearerTokenAuthenticationProvider, AccessTokenProvider, RequestOption } from "@microsoft/kiota-abstractions"; | ||
export { RetryHandler, RedirectHandler, TelemetryHandler, RetryHandlerOptions, HttpClient, TelemetryHandlerOptions, TelemetryHandlerOptionsKey, RetryHandlerOptionKey } from "@microsoft/kiota-http-fetchlibrary"; | ||
export { BatchRequestBody, RequestData, BatchRequestContent, BatchRequestData, BatchRequestStep } from "../content/BatchRequestContent"; | ||
export { BatchResponseBody, BatchResponseContent } from "../content/BatchResponseContent"; | ||
export { AuthenticationHandler } from "../middleware/AuthenticationHandler"; | ||
export { HTTPMessageHandler } from "../middleware/HTTPMessageHandler"; | ||
export { Middleware } from "../middleware/IMiddleware"; | ||
export { RetryHandler } from "../middleware/RetryHandler"; | ||
export { RedirectHandler } from "../middleware/RedirectHandler"; | ||
export { TelemetryHandler } from "../middleware/TelemetryHandler"; | ||
export { MiddlewareFactory } from "../middleware/MiddlewareFactory"; | ||
export { AuthenticationHandlerOptions } from "../middleware/options/AuthenticationHandlerOptions"; | ||
export { MiddlewareOptions } from "../middleware/options/IMiddlewareOptions"; | ||
export { ShouldRetry, RetryHandlerOptions } from "../middleware/options/RetryHandlerOptions"; | ||
export { ShouldRedirect, RedirectHandlerOptions } from "../middleware/options/RedirectHandlerOptions"; | ||
export { FeatureUsageFlag, TelemetryHandlerOptions } from "../middleware/options/TelemetryHandlerOptions"; | ||
export { FeatureUsageFlag } from "../middleware/Telemetry/TelemetryFeatureUsageFlag"; | ||
export { ChaosHandlerOptions } from "../middleware/options/ChaosHandlerOptions"; | ||
export { ChaosStrategy } from "../middleware/options/ChaosStrategy"; | ||
export { ChaosHandler } from "../middleware/ChaosHandler"; | ||
export { SliceType, LargeFileUploadTaskOptions, LargeFileUploadTask, LargeFileUploadSession, FileObject } from "../tasks/LargeFileUploadTask"; | ||
export { OneDriveLargeFileUploadTask, OneDriveLargeFileUploadOptions } from "../tasks/OneDriveLargeFileUploadTask"; | ||
export { FileObject, LargeFileUploadSession, LargeFileUploadTask, LargeFileUploadTaskOptions, SliceType } from "../tasks/LargeFileUploadTask"; | ||
export { OneDriveLargeFileUploadOptions, OneDriveLargeFileUploadTask } from "../tasks/OneDriveLargeFileUploadTask"; | ||
export { getValidRangeSize } from "../tasks/OneDriveLargeFileUploadTaskUtil"; | ||
@@ -34,17 +26,19 @@ export { StreamUpload } from "../tasks/FileUploadTask/FileObjectClasses/StreamUpload"; | ||
export { Range } from "../tasks/FileUploadTask/Range"; | ||
export { PageIteratorCallback, PageIterator, PageCollection, GraphRequestOptions } from "../tasks/PageIterator"; | ||
export { GraphRequestOptions, PageCollection, PageIterator, PageIteratorCallback } from "../tasks/PageIterator"; | ||
export { Client } from "../Client"; | ||
export { CustomAuthenticationProvider } from "../CustomAuthenticationProvider"; | ||
export { GraphError } from "../GraphError"; | ||
export { GraphClientError } from "../GraphClientError"; | ||
export { GraphRequest } from "../GraphRequest"; | ||
export { AuthProvider } from "../IAuthProvider"; | ||
export { AuthenticationProvider } from "../IAuthenticationProvider"; | ||
export { AuthenticationProviderOptions } from "../IAuthenticationProviderOptions"; | ||
export { AuthProviderCallback } from "../IAuthProviderCallback"; | ||
export { GraphRequest, URLComponents } from "../GraphRequest"; | ||
export { ClientOptions } from "../IClientOptions"; | ||
export { Context } from "../IContext"; | ||
export { NodeFetchInit, FetchOptions } from "../IFetchOptions"; | ||
export { FetchOptions, NodeFetchInit } from "../IFetchOptions"; | ||
export { GraphRequestCallback } from "../IGraphRequestCallback"; | ||
export { Options } from "../IOptions"; | ||
export { ResponseType } from "../ResponseType"; | ||
export { SimpleAuthenticationProvider } from "../authentication/SimpleAuthentication/SimpleAuthenticationProvider"; | ||
export { SimpleAccessTokenProvider } from "../authentication/SimpleAuthentication/SimpleAccessTokenProvider"; | ||
export { GraphBaseClient } from "../requestBuilderUtils/GraphBaseClient"; | ||
export { GraphSDKConfig } from "../requestBuilderUtils/GraphSDKConfig"; | ||
export { coreSdkVersionValue, getGraphTelemetryCallback, CORE_PRODUCT_NAME, graphTelemetryCallback } from "../middleware/Telemetry/TelemetryUtil"; | ||
export { GraphTelemetryConfig } from "../middleware/Telemetry/GraphTelemetryConfig"; | ||
export { getDefaultMiddlewareChain } from "./MiddlewareFactory"; | ||
export { GRAPH_API_VERSION, GRAPH_BASE_URL, GRAPH_URLS } from "../Constants"; | ||
export { isCustomHost, isGraphURL, updateAndReturnAllAllowedHosts } from "../GraphRequestUtil"; |
@@ -9,14 +9,7 @@ /** | ||
/// <reference path= "../../shims.d.ts" /> | ||
export { BaseBearerTokenAuthenticationProvider } from "@microsoft/kiota-abstractions"; | ||
export { RetryHandler, RedirectHandler, TelemetryHandler, RetryHandlerOptions, HttpClient, TelemetryHandlerOptionsKey, RetryHandlerOptionKey } from "@microsoft/kiota-http-fetchlibrary"; | ||
export { BatchRequestContent } from "../content/BatchRequestContent"; | ||
export { BatchResponseContent } from "../content/BatchResponseContent"; | ||
export { AuthenticationHandler } from "../middleware/AuthenticationHandler"; | ||
export { HTTPMessageHandler } from "../middleware/HTTPMessageHandler"; | ||
export { RetryHandler } from "../middleware/RetryHandler"; | ||
export { RedirectHandler } from "../middleware/RedirectHandler"; | ||
export { TelemetryHandler } from "../middleware/TelemetryHandler"; | ||
export { MiddlewareFactory } from "../middleware/MiddlewareFactory"; | ||
export { AuthenticationHandlerOptions } from "../middleware/options/AuthenticationHandlerOptions"; | ||
export { RetryHandlerOptions } from "../middleware/options/RetryHandlerOptions"; | ||
export { RedirectHandlerOptions } from "../middleware/options/RedirectHandlerOptions"; | ||
export { FeatureUsageFlag, TelemetryHandlerOptions } from "../middleware/options/TelemetryHandlerOptions"; | ||
export { FeatureUsageFlag } from "../middleware/Telemetry/TelemetryFeatureUsageFlag"; | ||
export { ChaosHandlerOptions } from "../middleware/options/ChaosHandlerOptions"; | ||
@@ -34,3 +27,2 @@ export { ChaosStrategy } from "../middleware/options/ChaosStrategy"; | ||
export { Client } from "../Client"; | ||
export { CustomAuthenticationProvider } from "../CustomAuthenticationProvider"; | ||
export { GraphError } from "../GraphError"; | ||
@@ -40,2 +32,8 @@ export { GraphClientError } from "../GraphClientError"; | ||
export { ResponseType } from "../ResponseType"; | ||
export { SimpleAuthenticationProvider } from "../authentication/SimpleAuthentication/SimpleAuthenticationProvider"; | ||
export { SimpleAccessTokenProvider } from "../authentication/SimpleAuthentication/SimpleAccessTokenProvider"; | ||
export { coreSdkVersionValue, getGraphTelemetryCallback, CORE_PRODUCT_NAME, graphTelemetryCallback } from "../middleware/Telemetry/TelemetryUtil"; | ||
export { getDefaultMiddlewareChain } from "./MiddlewareFactory"; | ||
export { GRAPH_API_VERSION, GRAPH_BASE_URL, GRAPH_URLS } from "../Constants"; | ||
export { isCustomHost, isGraphURL, updateAndReturnAllAllowedHosts } from "../GraphRequestUtil"; | ||
//# sourceMappingURL=index.js.map |
@@ -7,6 +7,11 @@ /** | ||
*/ | ||
/** | ||
* @module Client | ||
*/ | ||
import { BaseBearerTokenAuthenticationProvider } from "@microsoft/kiota-abstractions"; | ||
import { HttpClient } from "@microsoft/kiota-http-fetchlibrary"; | ||
import { GraphBaseClient } from "."; | ||
import { GraphRequest } from "./GraphRequest"; | ||
import { ClientOptions } from "./IClientOptions"; | ||
import { Options } from "./IOptions"; | ||
export declare class Client { | ||
export declare class Client implements GraphBaseClient { | ||
/** | ||
@@ -21,3 +26,4 @@ * @private | ||
*/ | ||
private httpClient; | ||
protected httpClient: HttpClient; | ||
protected authProvider: BaseBearerTokenAuthenticationProvider; | ||
/** | ||
@@ -30,12 +36,4 @@ * @public | ||
*/ | ||
static init(options: Options): Client; | ||
static init(options: ClientOptions): Client; | ||
/** | ||
* @public | ||
* @static | ||
* To create a client instance with the Client Options | ||
* @param {ClientOptions} clientOptions - The options object for initializing the client | ||
* @returns The Client instance | ||
*/ | ||
static initWithMiddleware(clientOptions: ClientOptions): Client; | ||
/** | ||
* @private | ||
@@ -42,0 +40,0 @@ * @constructor |
@@ -7,11 +7,8 @@ /** | ||
*/ | ||
/** | ||
* @module Client | ||
*/ | ||
import { HttpClient } from "@microsoft/kiota-http-fetchlibrary"; | ||
import { GraphClientError } from "."; | ||
import { GRAPH_API_VERSION, GRAPH_BASE_URL } from "./Constants"; | ||
import { CustomAuthenticationProvider } from "./CustomAuthenticationProvider"; | ||
import { GraphRequest } from "./GraphRequest"; | ||
import { HTTPClient } from "./HTTPClient"; | ||
import { HTTPClientFactory } from "./HTTPClientFactory"; | ||
import { validatePolyFilling } from "./ValidatePolyFilling"; | ||
import { updateAndReturnAllAllowedHosts } from "./GraphRequestUtil"; | ||
import { getDefaultMiddlewareChain } from "./MiddlewareFactory"; | ||
export class Client { | ||
@@ -34,3 +31,2 @@ /** | ||
}; | ||
validatePolyFilling(); | ||
for (const key in clientOptions) { | ||
@@ -42,19 +38,14 @@ if (Object.prototype.hasOwnProperty.call(clientOptions, key)) { | ||
let httpClient; | ||
if (clientOptions.authProvider !== undefined && clientOptions.middleware !== undefined) { | ||
const error = new Error(); | ||
error.name = "AmbiguityInInitialization"; | ||
error.message = "Unable to Create Client, Please provide either authentication provider for default middleware chain or custom middleware chain not both"; | ||
if (clientOptions.authProvider === undefined) { | ||
const error = new GraphClientError(); | ||
error.name = "Client Initialization Failed"; | ||
error.message = "Unable to Create Client, Please provide an authentication provider"; | ||
throw error; | ||
} | ||
else if (clientOptions.authProvider !== undefined) { | ||
httpClient = HTTPClientFactory.createWithAuthenticationProvider(clientOptions.authProvider); | ||
const allowedHosts = updateAndReturnAllAllowedHosts(clientOptions.authProvider, this.config.customHosts); | ||
if (!clientOptions.middleware) { | ||
httpClient = new HttpClient(undefined, ...[].concat(getDefaultMiddlewareChain(clientOptions, allowedHosts))); | ||
} | ||
else if (clientOptions.middleware !== undefined) { | ||
httpClient = new HTTPClient(...[].concat(clientOptions.middleware)); | ||
} | ||
else { | ||
const error = new Error(); | ||
error.name = "InvalidMiddlewareChain"; | ||
error.message = "Unable to Create Client, Please provide either authentication provider for default middleware chain or custom middleware chain"; | ||
throw error; | ||
httpClient = new HttpClient(clientOptions.customFetch, ...[].concat(clientOptions.middleware)); | ||
} | ||
@@ -71,22 +62,6 @@ this.httpClient = httpClient; | ||
static init(options) { | ||
const clientOptions = {}; | ||
for (const i in options) { | ||
if (Object.prototype.hasOwnProperty.call(options, i)) { | ||
clientOptions[i] = i === "authProvider" ? new CustomAuthenticationProvider(options[i]) : options[i]; | ||
} | ||
} | ||
return Client.initWithMiddleware(clientOptions); | ||
return new Client(options); | ||
} | ||
/** | ||
* @public | ||
* @static | ||
* To create a client instance with the Client Options | ||
* @param {ClientOptions} clientOptions - The options object for initializing the client | ||
* @returns The Client instance | ||
*/ | ||
static initWithMiddleware(clientOptions) { | ||
return new Client(clientOptions); | ||
} | ||
/** | ||
* @public | ||
* Entry point to make requests | ||
@@ -93,0 +68,0 @@ * @param {string} path - The path string value |
@@ -7,3 +7,6 @@ /** | ||
*/ | ||
import { HTTPClient } from "./HTTPClient"; | ||
/** | ||
* @module GraphRequest | ||
*/ | ||
import { HttpClient } from "@microsoft/kiota-http-fetchlibrary"; | ||
import { ClientOptions } from "./IClientOptions"; | ||
@@ -89,3 +92,3 @@ import { GraphRequestCallback } from "./IGraphRequestCallback"; | ||
*/ | ||
constructor(httpClient: HTTPClient, config: ClientOptions, path: string); | ||
constructor(httpClient: HttpClient, config: ClientOptions, path: string); | ||
/** | ||
@@ -92,0 +95,0 @@ * @private |
@@ -8,5 +8,2 @@ /** | ||
import { __awaiter } from "tslib"; | ||
/** | ||
* @module GraphRequest | ||
*/ | ||
import { GraphClientError } from "./GraphClientError"; | ||
@@ -16,3 +13,2 @@ import { GraphErrorHandler } from "./GraphErrorHandler"; | ||
import { GraphResponseHandler } from "./GraphResponseHandler"; | ||
import { MiddlewareControl } from "./middleware/MiddlewareControl"; | ||
import { RequestMethod } from "./RequestMethod"; | ||
@@ -276,16 +272,7 @@ import { ResponseType } from "./ResponseType"; | ||
send(request, options, callback) { | ||
var _a; | ||
return __awaiter(this, void 0, void 0, function* () { | ||
let rawResponse; | ||
const middlewareControl = new MiddlewareControl(this._middlewareOptions); | ||
this.updateRequestOptions(options); | ||
const customHosts = (_a = this.config) === null || _a === void 0 ? void 0 : _a.customHosts; | ||
try { | ||
const context = yield this.httpClient.sendRequest({ | ||
request, | ||
options, | ||
middlewareControl, | ||
customHosts, | ||
}); | ||
rawResponse = context.response; | ||
const rawResponse = yield this.httpClient.executeFetch(request, options); | ||
const response = yield GraphResponseHandler.getResponse(rawResponse, this._responseType, callback); | ||
@@ -292,0 +279,0 @@ return response; |
@@ -8,2 +8,6 @@ /** | ||
/** | ||
* @module GraphRequestUtil | ||
*/ | ||
import { BaseBearerTokenAuthenticationProvider } from "@microsoft/kiota-abstractions"; | ||
/** | ||
* To hold list of OData query params | ||
@@ -44,1 +48,7 @@ */ | ||
export declare const isCustomHost: (url: string, customHosts: Set<string>) => boolean; | ||
/** | ||
* | ||
* @param customHosts | ||
* @returns | ||
*/ | ||
export declare const updateAndReturnAllAllowedHosts: (authProvider: BaseBearerTokenAuthenticationProvider, customHosts: Set<string>) => Set<string>; |
@@ -7,5 +7,2 @@ /** | ||
*/ | ||
/** | ||
* @module GraphRequestUtil | ||
*/ | ||
import { GRAPH_URLS } from "./Constants"; | ||
@@ -117,2 +114,14 @@ import { GraphClientError } from "./GraphClientError"; | ||
}; | ||
/** | ||
* | ||
* @param customHosts | ||
* @returns | ||
*/ | ||
export const updateAndReturnAllAllowedHosts = (authProvider, customHosts) => { | ||
const hostsValidator = authProvider.accessTokenProvider.getAllowedHostsValidator(); | ||
const allowedHosts = customHosts ? new Set([...customHosts, ...hostsValidator.getAllowedHosts()]) : new Set(hostsValidator.getAllowedHosts()); | ||
const hostSetWithGraphandCustomHosts = customHosts ? new Set([...allowedHosts, ...GRAPH_URLS, ...customHosts]) : new Set([...allowedHosts, ...GRAPH_URLS]); | ||
hostsValidator.setAllowedHosts(hostSetWithGraphandCustomHosts); | ||
return hostSetWithGraphandCustomHosts; | ||
}; | ||
//# sourceMappingURL=GraphRequestUtil.js.map |
@@ -7,5 +7,5 @@ /** | ||
*/ | ||
import { AuthenticationProvider } from "./IAuthenticationProvider"; | ||
import { BaseBearerTokenAuthenticationProvider } from "@microsoft/kiota-abstractions"; | ||
import { Middleware } from "@microsoft/kiota-http-fetchlibrary"; | ||
import { FetchOptions } from "./IFetchOptions"; | ||
import { Middleware } from "./middleware/IMiddleware"; | ||
/** | ||
@@ -23,3 +23,3 @@ * @interface | ||
export interface ClientOptions { | ||
authProvider?: AuthenticationProvider; | ||
authProvider?: BaseBearerTokenAuthenticationProvider; | ||
baseUrl?: string; | ||
@@ -30,2 +30,3 @@ debugLogging?: boolean; | ||
middleware?: Middleware | Middleware[]; | ||
customFetch?: (input: string, init?: RequestInit) => Promise<Response>; | ||
/** | ||
@@ -32,0 +33,0 @@ * Example - If URL is "https://test_host/v1.0", then set property "customHosts" as "customHosts: Set<string>(["test_host"])" |
@@ -0,1 +1,2 @@ | ||
/// <reference path="../../../shims.d.ts" /> | ||
/** | ||
@@ -7,17 +8,8 @@ * ------------------------------------------------------------------------------------------- | ||
*/ | ||
/// <reference path="../../../shims.d.ts" /> | ||
export { BaseBearerTokenAuthenticationProvider, AccessTokenProvider, RequestOption } from "@microsoft/kiota-abstractions"; | ||
export { RetryHandler, RedirectHandler, TelemetryHandler, RedirectHandlerOptionKey, RetryHandlerOptions, HttpClient, RedirectHandlerOptions, TelemetryHandlerOptions, TelemetryHandlerOptionsKey, RetryHandlerOptionKey } from "@microsoft/kiota-http-fetchlibrary"; | ||
export { BatchRequestBody, RequestData, BatchRequestContent, BatchRequestData, BatchRequestStep } from "./content/BatchRequestContent"; | ||
export { BatchResponseBody, BatchResponseContent } from "./content/BatchResponseContent"; | ||
export { AuthenticationHandler } from "./middleware/AuthenticationHandler"; | ||
export { HTTPMessageHandler } from "./middleware/HTTPMessageHandler"; | ||
export { Middleware } from "./middleware/IMiddleware"; | ||
export { RetryHandler } from "./middleware/RetryHandler"; | ||
export { RedirectHandler } from "./middleware/RedirectHandler"; | ||
export { TelemetryHandler } from "./middleware/TelemetryHandler"; | ||
export { MiddlewareFactory } from "./middleware/MiddlewareFactory"; | ||
export { AuthenticationHandlerOptions } from "./middleware/options/AuthenticationHandlerOptions"; | ||
export { MiddlewareOptions } from "./middleware/options/IMiddlewareOptions"; | ||
export { RetryHandlerOptions, ShouldRetry } from "./middleware/options/RetryHandlerOptions"; | ||
export { RedirectHandlerOptions, ShouldRedirect } from "./middleware/options/RedirectHandlerOptions"; | ||
export { FeatureUsageFlag, TelemetryHandlerOptions } from "./middleware/options/TelemetryHandlerOptions"; | ||
export { FeatureUsageFlag } from "./middleware/Telemetry/TelemetryFeatureUsageFlag"; | ||
export { ChaosHandlerOptions } from "./middleware/options/ChaosHandlerOptions"; | ||
@@ -36,15 +28,17 @@ export { ChaosStrategy } from "./middleware/options/ChaosStrategy"; | ||
export { Client } from "./Client"; | ||
export { CustomAuthenticationProvider } from "./CustomAuthenticationProvider"; | ||
export { GraphError } from "./GraphError"; | ||
export { GraphClientError } from "./GraphClientError"; | ||
export { GraphRequest, URLComponents } from "./GraphRequest"; | ||
export { AuthProvider } from "./IAuthProvider"; | ||
export { AuthenticationProvider } from "./IAuthenticationProvider"; | ||
export { AuthenticationProviderOptions } from "./IAuthenticationProviderOptions"; | ||
export { AuthProviderCallback } from "./IAuthProviderCallback"; | ||
export { ClientOptions } from "./IClientOptions"; | ||
export { Context } from "./IContext"; | ||
export { FetchOptions, NodeFetchInit } from "./IFetchOptions"; | ||
export { GraphRequestCallback } from "./IGraphRequestCallback"; | ||
export { Options } from "./IOptions"; | ||
export { ResponseType } from "./ResponseType"; | ||
export { SimpleAuthenticationProvider } from "./authentication/SimpleAuthentication/SimpleAuthenticationProvider"; | ||
export { SimpleAccessTokenProvider } from "./authentication/SimpleAuthentication/SimpleAccessTokenProvider"; | ||
export { GraphBaseClient } from "./requestBuilderUtils/GraphBaseClient"; | ||
export { GraphSDKConfig } from "./requestBuilderUtils/GraphSDKConfig"; | ||
export { coreSdkVersionValue, getGraphTelemetryCallback, CORE_PRODUCT_NAME, graphTelemetryCallback } from "./middleware/Telemetry/TelemetryUtil"; | ||
export { GraphTelemetryConfig } from "./middleware/Telemetry/GraphTelemetryConfig"; | ||
export { getDefaultMiddlewareChain } from "./MiddlewareFactory"; | ||
export { GRAPH_API_VERSION, GRAPH_BASE_URL, GRAPH_URLS } from "./Constants"; | ||
export { isCustomHost, isGraphURL, updateAndReturnAllAllowedHosts } from "./GraphRequestUtil"; |
@@ -9,14 +9,7 @@ /** | ||
/// <reference path= "./../shims.d.ts" /> | ||
export { BaseBearerTokenAuthenticationProvider } from "@microsoft/kiota-abstractions"; | ||
export { RetryHandler, RedirectHandler, TelemetryHandler, RedirectHandlerOptionKey, RetryHandlerOptions, HttpClient, RedirectHandlerOptions, TelemetryHandlerOptionsKey, RetryHandlerOptionKey } from "@microsoft/kiota-http-fetchlibrary"; | ||
export { BatchRequestContent } from "./content/BatchRequestContent"; | ||
export { BatchResponseContent } from "./content/BatchResponseContent"; | ||
export { AuthenticationHandler } from "./middleware/AuthenticationHandler"; | ||
export { HTTPMessageHandler } from "./middleware/HTTPMessageHandler"; | ||
export { RetryHandler } from "./middleware/RetryHandler"; | ||
export { RedirectHandler } from "./middleware/RedirectHandler"; | ||
export { TelemetryHandler } from "./middleware/TelemetryHandler"; | ||
export { MiddlewareFactory } from "./middleware/MiddlewareFactory"; | ||
export { AuthenticationHandlerOptions } from "./middleware/options/AuthenticationHandlerOptions"; | ||
export { RetryHandlerOptions } from "./middleware/options/RetryHandlerOptions"; | ||
export { RedirectHandlerOptions } from "./middleware/options/RedirectHandlerOptions"; | ||
export { FeatureUsageFlag, TelemetryHandlerOptions } from "./middleware/options/TelemetryHandlerOptions"; | ||
export { FeatureUsageFlag } from "./middleware/Telemetry/TelemetryFeatureUsageFlag"; | ||
export { ChaosHandlerOptions } from "./middleware/options/ChaosHandlerOptions"; | ||
@@ -34,3 +27,2 @@ export { ChaosStrategy } from "./middleware/options/ChaosStrategy"; | ||
export { Client } from "./Client"; | ||
export { CustomAuthenticationProvider } from "./CustomAuthenticationProvider"; | ||
export { GraphError } from "./GraphError"; | ||
@@ -40,2 +32,8 @@ export { GraphClientError } from "./GraphClientError"; | ||
export { ResponseType } from "./ResponseType"; | ||
export { SimpleAuthenticationProvider } from "./authentication/SimpleAuthentication/SimpleAuthenticationProvider"; | ||
export { SimpleAccessTokenProvider } from "./authentication/SimpleAuthentication/SimpleAccessTokenProvider"; | ||
export { coreSdkVersionValue, getGraphTelemetryCallback, CORE_PRODUCT_NAME, graphTelemetryCallback } from "./middleware/Telemetry/TelemetryUtil"; | ||
export { getDefaultMiddlewareChain } from "./MiddlewareFactory"; | ||
export { GRAPH_API_VERSION, GRAPH_BASE_URL, GRAPH_URLS } from "./Constants"; | ||
export { isCustomHost, isGraphURL, updateAndReturnAllAllowedHosts } from "./GraphRequestUtil"; | ||
//# sourceMappingURL=index.js.map |
@@ -7,6 +7,8 @@ /** | ||
*/ | ||
import { AuthenticationProvider } from "../IAuthenticationProvider"; | ||
import { Context } from "../IContext"; | ||
import { Middleware } from "./IMiddleware"; | ||
/** | ||
* @module AuthenticationHandler | ||
*/ | ||
import { BaseBearerTokenAuthenticationProvider, RequestOption } from "@microsoft/kiota-abstractions"; | ||
import { Middleware } from "@microsoft/kiota-http-fetchlibrary"; | ||
/** | ||
* @class | ||
@@ -17,2 +19,3 @@ * @implements Middleware | ||
export declare class AuthenticationHandler implements Middleware { | ||
private authenticationProvider; | ||
/** | ||
@@ -25,10 +28,5 @@ * @private | ||
* @private | ||
* A member to hold an AuthenticationProvider instance | ||
*/ | ||
private authenticationProvider; | ||
/** | ||
* @private | ||
* A member to hold next middleware in the middleware chain | ||
*/ | ||
private nextMiddleware; | ||
next: Middleware; | ||
/** | ||
@@ -40,3 +38,3 @@ * @public | ||
*/ | ||
constructor(authenticationProvider: AuthenticationProvider); | ||
constructor(authenticationProvider: BaseBearerTokenAuthenticationProvider); | ||
/** | ||
@@ -49,10 +47,3 @@ * @public | ||
*/ | ||
execute(context: Context): Promise<void>; | ||
/** | ||
* @public | ||
* To set the next middleware in the chain | ||
* @param {Middleware} next - The middleware instance | ||
* @returns Nothing | ||
*/ | ||
setNext(next: Middleware): void; | ||
execute(url: string, requestInit: RequestInit, requestOptions?: Record<string, RequestOption>): Promise<Response>; | ||
} |
@@ -8,11 +8,4 @@ /** | ||
import { __awaiter } from "tslib"; | ||
import { appendRequestHeader } from "@microsoft/kiota-http-fetchlibrary"; | ||
/** | ||
* @module AuthenticationHandler | ||
*/ | ||
import { isCustomHost, isGraphURL } from "../GraphRequestUtil"; | ||
import { MiddlewareControl } from "./MiddlewareControl"; | ||
import { appendRequestHeader } from "./MiddlewareUtil"; | ||
import { AuthenticationHandlerOptions } from "./options/AuthenticationHandlerOptions"; | ||
import { FeatureUsageFlag, TelemetryHandlerOptions } from "./options/TelemetryHandlerOptions"; | ||
/** | ||
* @class | ||
@@ -39,41 +32,21 @@ * @implements Middleware | ||
*/ | ||
execute(context) { | ||
execute(url, requestInit, requestOptions) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const url = typeof context.request === "string" ? context.request : context.request.url; | ||
if (isGraphURL(url) || (context.customHosts && isCustomHost(url, context.customHosts))) { | ||
let options; | ||
if (context.middlewareControl instanceof MiddlewareControl) { | ||
options = context.middlewareControl.getMiddlewareOptions(AuthenticationHandlerOptions); | ||
if (this.authenticationProvider.accessTokenProvider.getAllowedHostsValidator().isUrlHostValid(url)) { | ||
if ((requestInit === null || requestInit === void 0 ? void 0 : requestInit.headers) && !requestInit.headers[AuthenticationHandler.AUTHORIZATION_HEADER]) { | ||
const token = yield this.authenticationProvider.accessTokenProvider.getAuthorizationToken(url); | ||
const bearerKey = `Bearer ${token}`; | ||
appendRequestHeader(requestInit, AuthenticationHandler.AUTHORIZATION_HEADER, bearerKey); | ||
} | ||
let authenticationProvider; | ||
let authenticationProviderOptions; | ||
if (options) { | ||
authenticationProvider = options.authenticationProvider; | ||
authenticationProviderOptions = options.authenticationProviderOptions; | ||
} | ||
if (!authenticationProvider) { | ||
authenticationProvider = this.authenticationProvider; | ||
} | ||
const token = yield authenticationProvider.getAccessToken(authenticationProviderOptions); | ||
const bearerKey = `Bearer ${token}`; | ||
appendRequestHeader(context.request, context.options, AuthenticationHandler.AUTHORIZATION_HEADER, bearerKey); | ||
TelemetryHandlerOptions.updateFeatureUsageFlag(context, FeatureUsageFlag.AUTHENTICATION_HANDLER_ENABLED); | ||
} | ||
else { | ||
if (context.options.headers) { | ||
delete context.options.headers[AuthenticationHandler.AUTHORIZATION_HEADER]; | ||
} | ||
/** | ||
* deleting auth headers because the tasks such as LargeFileUpload use client.api() to upload to redirected url | ||
* delete the auth header and allow the request to go through with the rest of the middleware chain | ||
**/ | ||
delete requestInit.headers[AuthenticationHandler.AUTHORIZATION_HEADER]; | ||
} | ||
return yield this.nextMiddleware.execute(context); | ||
return yield this.next.execute(url, requestInit, requestOptions); | ||
}); | ||
} | ||
/** | ||
* @public | ||
* To set the next middleware in the chain | ||
* @param {Middleware} next - The middleware instance | ||
* @returns Nothing | ||
*/ | ||
setNext(next) { | ||
this.nextMiddleware = next; | ||
} | ||
} | ||
@@ -80,0 +53,0 @@ /** |
@@ -10,5 +10,6 @@ /** | ||
*/ | ||
import { Context } from "../IContext"; | ||
import { Middleware } from "./IMiddleware"; | ||
import { RequestOption } from "@microsoft/kiota-abstractions"; | ||
import { Middleware } from "@microsoft/kiota-http-fetchlibrary"; | ||
import { ChaosHandlerOptions } from "./options/ChaosHandlerOptions"; | ||
export declare const ChaosHandlerOptionKey = "ChaosHandlerOptionKey"; | ||
/** | ||
@@ -21,20 +22,6 @@ * Class representing ChaosHandler | ||
export declare class ChaosHandler implements Middleware { | ||
private chaosHandlerOptions; | ||
private manualMap?; | ||
next: Middleware | undefined; | ||
/** | ||
* A member holding options to customize the handler behavior | ||
* | ||
* @private | ||
*/ | ||
private options; | ||
/** | ||
* container for the manual map that has been written by the client | ||
* | ||
* @private | ||
*/ | ||
private manualMap; | ||
/** | ||
* @private | ||
* A member to hold next middleware in the middleware chain | ||
*/ | ||
private nextMiddleware; | ||
/** | ||
* @public | ||
@@ -47,3 +34,4 @@ * @constructor | ||
*/ | ||
constructor(options?: ChaosHandlerOptions, manualMap?: Map<string, Map<string, number>>); | ||
constructor(chaosHandlerOptions?: ChaosHandlerOptions, manualMap?: Map<string, Map<string, number>>); | ||
execute(url: string, requestInit: RequestInit, requestOptions?: Record<string, RequestOption>): Promise<Response>; | ||
/** | ||
@@ -105,18 +93,3 @@ * Generates responseHeader | ||
/** | ||
* To get the options for execution of the middleware | ||
* @private | ||
* @param {Context} context - The context object | ||
* @returns options for middleware execution | ||
*/ | ||
private getOptions; | ||
/** | ||
* To execute the current middleware | ||
* @public | ||
* @async | ||
* @param {Context} context - The context object of the request | ||
* @returns A Promise that resolves to nothing | ||
*/ | ||
execute(context: Context): Promise<void>; | ||
/** | ||
* @public | ||
* To set the next middleware in the chain | ||
@@ -123,0 +96,0 @@ * @param {Middleware} next - The middleware instance |
@@ -8,3 +8,2 @@ /** | ||
import { __awaiter } from "tslib"; | ||
import { MiddlewareControl } from "./MiddlewareControl"; | ||
import { generateUUID } from "./MiddlewareUtil"; | ||
@@ -14,2 +13,3 @@ import { httpStatusCode, methodStatusCode } from "./options/ChaosHandlerData"; | ||
import { ChaosStrategy } from "./options/ChaosStrategy"; | ||
export const ChaosHandlerOptionKey = "ChaosHandlerOptionKey"; | ||
/** | ||
@@ -30,6 +30,12 @@ * Class representing ChaosHandler | ||
*/ | ||
constructor(options = new ChaosHandlerOptions(), manualMap) { | ||
this.options = options; | ||
constructor(chaosHandlerOptions = new ChaosHandlerOptions(), manualMap) { | ||
this.chaosHandlerOptions = chaosHandlerOptions; | ||
this.manualMap = manualMap; | ||
} | ||
execute(url, requestInit, requestOptions) { | ||
if (requestOptions && requestOptions[ChaosHandlerOptionKey]) { | ||
this.chaosHandlerOptions = requestOptions[ChaosHandlerOptionKey]; | ||
} | ||
return this.sendRequest(url, requestInit, requestOptions); | ||
} | ||
/** | ||
@@ -43,4 +49,4 @@ * Generates responseHeader | ||
*/ | ||
createResponseHeaders(chaosHandlerOptions, requestID, requestDate) { | ||
const responseHeader = chaosHandlerOptions.headers ? new Headers(chaosHandlerOptions.headers) : new Headers(); | ||
createResponseHeaders(requestID, requestDate) { | ||
const responseHeader = this.chaosHandlerOptions.headers ? new Headers(this.chaosHandlerOptions.headers) : new Headers(); | ||
responseHeader.append("Cache-Control", "no-store"); | ||
@@ -52,3 +58,3 @@ responseHeader.append("request-id", requestID); | ||
responseHeader.append("Strict-Transport-Security", ""); | ||
if (chaosHandlerOptions.statusCode === 429) { | ||
if (this.chaosHandlerOptions.statusCode === 429) { | ||
// throttling case has to have a timeout scenario | ||
@@ -67,10 +73,10 @@ responseHeader.append("retry-after", "3"); | ||
*/ | ||
createResponseBody(chaosHandlerOptions, requestID, requestDate) { | ||
if (chaosHandlerOptions.responseBody) { | ||
return chaosHandlerOptions.responseBody; | ||
createResponseBody(requestID, requestDate) { | ||
if (this.chaosHandlerOptions.responseBody) { | ||
return this.chaosHandlerOptions.responseBody; | ||
} | ||
let body; | ||
if (chaosHandlerOptions.statusCode >= 400) { | ||
const codeMessage = httpStatusCode[chaosHandlerOptions.statusCode]; | ||
const errMessage = chaosHandlerOptions.statusMessage; | ||
if (this.chaosHandlerOptions.statusCode >= 400) { | ||
const codeMessage = httpStatusCode[this.chaosHandlerOptions.statusCode]; | ||
const errMessage = this.chaosHandlerOptions.statusMessage; | ||
body = { | ||
@@ -98,10 +104,9 @@ error: { | ||
*/ | ||
createResponse(chaosHandlerOptions, context) { | ||
const requestURL = context.request; | ||
createResponse(requestURL) { | ||
const requestID = generateUUID(); | ||
const requestDate = new Date(); | ||
const responseHeader = this.createResponseHeaders(chaosHandlerOptions, requestID, requestDate.toString()); | ||
const responseBody = this.createResponseBody(chaosHandlerOptions, requestID, requestDate.toString()); | ||
const init = { url: requestURL, status: chaosHandlerOptions.statusCode, statusText: chaosHandlerOptions.statusMessage, headers: responseHeader }; | ||
context.response = new Response(typeof responseBody === "string" ? responseBody : JSON.stringify(responseBody), init); | ||
const responseHeader = this.createResponseHeaders(requestID, requestDate.toString()); | ||
const responseBody = this.createResponseBody(requestID, requestDate.toString()); | ||
const init = { url: requestURL, status: this.chaosHandlerOptions.statusCode, statusText: this.chaosHandlerOptions.statusMessage, headers: responseHeader }; | ||
return new Response(typeof responseBody === "string" ? responseBody : JSON.stringify(responseBody), init); | ||
} | ||
@@ -115,10 +120,10 @@ /** | ||
*/ | ||
sendRequest(chaosHandlerOptions, context) { | ||
sendRequest(url, requestInit, requestOptions) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
this.setStatusCode(chaosHandlerOptions, context.request, context.options.method); | ||
if ((chaosHandlerOptions.chaosStrategy === ChaosStrategy.MANUAL && !this.nextMiddleware) || Math.floor(Math.random() * 100) < chaosHandlerOptions.chaosPercentage) { | ||
this.createResponse(chaosHandlerOptions, context); | ||
this.setStatusCode(url, requestInit === null || requestInit === void 0 ? void 0 : requestInit.method); | ||
if ((this.chaosHandlerOptions.chaosStrategy === ChaosStrategy.MANUAL && !this.next) || Math.floor(Math.random() * 100) < this.chaosHandlerOptions.chaosPercentage) { | ||
return this.createResponse(url); | ||
} | ||
else if (this.nextMiddleware) { | ||
yield this.nextMiddleware.execute(context); | ||
else if (this.next) { | ||
yield this.next.execute(url, requestInit, requestOptions); | ||
} | ||
@@ -158,5 +163,5 @@ }); | ||
*/ | ||
setStatusCode(chaosHandlerOptions, requestURL, requestMethod) { | ||
if (chaosHandlerOptions.chaosStrategy === ChaosStrategy.MANUAL) { | ||
if (chaosHandlerOptions.statusCode === undefined) { | ||
setStatusCode(requestURL, requestMethod) { | ||
if (this.chaosHandlerOptions.chaosStrategy === ChaosStrategy.MANUAL) { | ||
if (this.chaosHandlerOptions.statusCode === undefined) { | ||
// manual mode with no status code, can be a global level or request level without statusCode | ||
@@ -167,3 +172,3 @@ const relativeURL = this.getRelativeURL(requestURL); | ||
if (this.manualMap.get(relativeURL).get(requestMethod) !== undefined) { | ||
chaosHandlerOptions.statusCode = this.manualMap.get(relativeURL).get(requestMethod); | ||
this.chaosHandlerOptions.statusCode = this.manualMap.get(relativeURL).get(requestMethod); | ||
} | ||
@@ -178,3 +183,3 @@ // else statusCode would be undefined | ||
if (this.manualMap.get(key).get(requestMethod) !== undefined) { | ||
chaosHandlerOptions.statusCode = this.manualMap.get(key).get(requestMethod); | ||
this.chaosHandlerOptions.statusCode = this.manualMap.get(key).get(requestMethod); | ||
} | ||
@@ -190,3 +195,3 @@ // else statusCode would be undefined | ||
// Handling the case of Random here | ||
chaosHandlerOptions.statusCode = this.getRandomStatusCode(requestMethod); | ||
this.chaosHandlerOptions.statusCode = this.getRandomStatusCode(requestMethod); | ||
// else statusCode would be undefined | ||
@@ -196,32 +201,3 @@ } | ||
/** | ||
* To get the options for execution of the middleware | ||
* @private | ||
* @param {Context} context - The context object | ||
* @returns options for middleware execution | ||
*/ | ||
getOptions(context) { | ||
let options; | ||
if (context.middlewareControl instanceof MiddlewareControl) { | ||
options = context.middlewareControl.getMiddlewareOptions(ChaosHandlerOptions); | ||
} | ||
if (typeof options === "undefined") { | ||
options = Object.assign(new ChaosHandlerOptions(), this.options); | ||
} | ||
return options; | ||
} | ||
/** | ||
* To execute the current middleware | ||
* @public | ||
* @async | ||
* @param {Context} context - The context object of the request | ||
* @returns A Promise that resolves to nothing | ||
*/ | ||
execute(context) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const chaosHandlerOptions = this.getOptions(context); | ||
return yield this.sendRequest(chaosHandlerOptions, context); | ||
}); | ||
} | ||
/** | ||
* @public | ||
* To set the next middleware in the chain | ||
@@ -232,5 +208,5 @@ * @param {Middleware} next - The middleware instance | ||
setNext(next) { | ||
this.nextMiddleware = next; | ||
this.next = next; | ||
} | ||
} | ||
//# sourceMappingURL=ChaosHandler.js.map |
@@ -10,4 +10,4 @@ /** | ||
*/ | ||
import { RequestOption } from "@microsoft/kiota-abstractions"; | ||
import { ChaosStrategy } from "./ChaosStrategy"; | ||
import { MiddlewareOptions } from "./IMiddlewareOptions"; | ||
/** | ||
@@ -19,3 +19,3 @@ * Class representing ChaosHandlerOptions | ||
*/ | ||
export declare class ChaosHandlerOptions implements MiddlewareOptions { | ||
export declare class ChaosHandlerOptions implements RequestOption { | ||
/** | ||
@@ -70,2 +70,3 @@ * Specifies the startegy used for the Testing Handler -> RANDOM/MANUAL | ||
constructor(chaosStrategy?: ChaosStrategy, statusMessage?: string, statusCode?: number, chaosPercentage?: number, responseBody?: any, headers?: Headers); | ||
getKey(): string; | ||
} |
@@ -7,5 +7,3 @@ /** | ||
*/ | ||
/** | ||
* @module ChaosHandlerOptions | ||
*/ | ||
import { ChaosHandlerOptionKey } from "../ChaosHandler"; | ||
import { ChaosStrategy } from "./ChaosStrategy"; | ||
@@ -41,3 +39,6 @@ /** | ||
} | ||
getKey() { | ||
return ChaosHandlerOptionKey; | ||
} | ||
} | ||
//# sourceMappingURL=ChaosHandlerOptions.js.map |
@@ -10,2 +10,2 @@ /** | ||
*/ | ||
export declare const PACKAGE_VERSION = "3.0.2"; | ||
export declare const PACKAGE_VERSION = "4.0.0-Preview.1"; |
@@ -12,3 +12,3 @@ /** | ||
*/ | ||
export const PACKAGE_VERSION = "3.0.2"; | ||
export const PACKAGE_VERSION = "4.0.0-Preview.1"; | ||
//# sourceMappingURL=Version.js.map |
@@ -0,1 +1,2 @@ | ||
/// <reference path="../../../shims.d.ts" /> | ||
/** | ||
@@ -7,22 +8,13 @@ * ------------------------------------------------------------------------------------------- | ||
*/ | ||
/// <reference path="../../../shims.d.ts" /> | ||
export { BatchRequestStep, BatchRequestData, BatchRequestContent, RequestData, BatchRequestBody } from "../content/BatchRequestContent"; | ||
export { BaseBearerTokenAuthenticationProvider, AccessTokenProvider, RequestOption } from "@microsoft/kiota-abstractions"; | ||
export { RetryHandler, RedirectHandler, TelemetryHandler, RetryHandlerOptions, HttpClient, TelemetryHandlerOptions, TelemetryHandlerOptionsKey, RetryHandlerOptionKey } from "@microsoft/kiota-http-fetchlibrary"; | ||
export { BatchRequestBody, RequestData, BatchRequestContent, BatchRequestData, BatchRequestStep } from "../content/BatchRequestContent"; | ||
export { BatchResponseBody, BatchResponseContent } from "../content/BatchResponseContent"; | ||
export { AuthenticationHandler } from "../middleware/AuthenticationHandler"; | ||
export { HTTPMessageHandler } from "../middleware/HTTPMessageHandler"; | ||
export { Middleware } from "../middleware/IMiddleware"; | ||
export { RetryHandler } from "../middleware/RetryHandler"; | ||
export { RedirectHandler } from "../middleware/RedirectHandler"; | ||
export { TelemetryHandler } from "../middleware/TelemetryHandler"; | ||
export { MiddlewareFactory } from "../middleware/MiddlewareFactory"; | ||
export { AuthenticationHandlerOptions } from "../middleware/options/AuthenticationHandlerOptions"; | ||
export { MiddlewareOptions } from "../middleware/options/IMiddlewareOptions"; | ||
export { ShouldRetry, RetryHandlerOptions } from "../middleware/options/RetryHandlerOptions"; | ||
export { ShouldRedirect, RedirectHandlerOptions } from "../middleware/options/RedirectHandlerOptions"; | ||
export { FeatureUsageFlag, TelemetryHandlerOptions } from "../middleware/options/TelemetryHandlerOptions"; | ||
export { FeatureUsageFlag } from "../middleware/Telemetry/TelemetryFeatureUsageFlag"; | ||
export { ChaosHandlerOptions } from "../middleware/options/ChaosHandlerOptions"; | ||
export { ChaosStrategy } from "../middleware/options/ChaosStrategy"; | ||
export { ChaosHandler } from "../middleware/ChaosHandler"; | ||
export { SliceType, LargeFileUploadTaskOptions, LargeFileUploadTask, LargeFileUploadSession, FileObject } from "../tasks/LargeFileUploadTask"; | ||
export { OneDriveLargeFileUploadTask, OneDriveLargeFileUploadOptions } from "../tasks/OneDriveLargeFileUploadTask"; | ||
export { FileObject, LargeFileUploadSession, LargeFileUploadTask, LargeFileUploadTaskOptions, SliceType } from "../tasks/LargeFileUploadTask"; | ||
export { OneDriveLargeFileUploadOptions, OneDriveLargeFileUploadTask } from "../tasks/OneDriveLargeFileUploadTask"; | ||
export { getValidRangeSize } from "../tasks/OneDriveLargeFileUploadTaskUtil"; | ||
@@ -34,17 +26,19 @@ export { StreamUpload } from "../tasks/FileUploadTask/FileObjectClasses/StreamUpload"; | ||
export { Range } from "../tasks/FileUploadTask/Range"; | ||
export { PageIteratorCallback, PageIterator, PageCollection, GraphRequestOptions } from "../tasks/PageIterator"; | ||
export { GraphRequestOptions, PageCollection, PageIterator, PageIteratorCallback } from "../tasks/PageIterator"; | ||
export { Client } from "../Client"; | ||
export { CustomAuthenticationProvider } from "../CustomAuthenticationProvider"; | ||
export { GraphError } from "../GraphError"; | ||
export { GraphClientError } from "../GraphClientError"; | ||
export { GraphRequest } from "../GraphRequest"; | ||
export { AuthProvider } from "../IAuthProvider"; | ||
export { AuthenticationProvider } from "../IAuthenticationProvider"; | ||
export { AuthenticationProviderOptions } from "../IAuthenticationProviderOptions"; | ||
export { AuthProviderCallback } from "../IAuthProviderCallback"; | ||
export { GraphRequest, URLComponents } from "../GraphRequest"; | ||
export { ClientOptions } from "../IClientOptions"; | ||
export { Context } from "../IContext"; | ||
export { NodeFetchInit, FetchOptions } from "../IFetchOptions"; | ||
export { FetchOptions, NodeFetchInit } from "../IFetchOptions"; | ||
export { GraphRequestCallback } from "../IGraphRequestCallback"; | ||
export { Options } from "../IOptions"; | ||
export { ResponseType } from "../ResponseType"; | ||
export { SimpleAuthenticationProvider } from "../authentication/SimpleAuthentication/SimpleAuthenticationProvider"; | ||
export { SimpleAccessTokenProvider } from "../authentication/SimpleAuthentication/SimpleAccessTokenProvider"; | ||
export { GraphBaseClient } from "../requestBuilderUtils/GraphBaseClient"; | ||
export { GraphSDKConfig } from "../requestBuilderUtils/GraphSDKConfig"; | ||
export { coreSdkVersionValue, getGraphTelemetryCallback, CORE_PRODUCT_NAME, graphTelemetryCallback } from "../middleware/Telemetry/TelemetryUtil"; | ||
export { GraphTelemetryConfig } from "../middleware/Telemetry/GraphTelemetryConfig"; | ||
export { getDefaultMiddlewareChain } from "./MiddlewareFactory"; | ||
export { GRAPH_API_VERSION, GRAPH_BASE_URL, GRAPH_URLS } from "../Constants"; | ||
export { isCustomHost, isGraphURL, updateAndReturnAllAllowedHosts } from "../GraphRequestUtil"; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.updateAndReturnAllAllowedHosts = exports.isGraphURL = exports.isCustomHost = exports.GRAPH_URLS = exports.GRAPH_BASE_URL = exports.GRAPH_API_VERSION = exports.getDefaultMiddlewareChain = exports.graphTelemetryCallback = exports.CORE_PRODUCT_NAME = exports.getGraphTelemetryCallback = exports.coreSdkVersionValue = exports.SimpleAccessTokenProvider = exports.SimpleAuthenticationProvider = exports.ResponseType = exports.GraphRequest = exports.GraphClientError = exports.GraphError = exports.Client = exports.PageIterator = exports.Range = exports.UploadResult = exports.FileUpload = exports.StreamUpload = exports.getValidRangeSize = exports.OneDriveLargeFileUploadTask = exports.LargeFileUploadTask = exports.ChaosHandler = exports.ChaosStrategy = exports.ChaosHandlerOptions = exports.FeatureUsageFlag = exports.BatchResponseContent = exports.BatchRequestContent = exports.RetryHandlerOptionKey = exports.TelemetryHandlerOptionsKey = exports.HttpClient = exports.RetryHandlerOptions = exports.TelemetryHandler = exports.RedirectHandler = exports.RetryHandler = exports.BaseBearerTokenAuthenticationProvider = void 0; | ||
/** | ||
@@ -8,6 +10,14 @@ * ------------------------------------------------------------------------------------------- | ||
*/ | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.ResponseType = exports.GraphRequest = exports.GraphClientError = exports.GraphError = exports.CustomAuthenticationProvider = exports.Client = exports.PageIterator = exports.Range = exports.UploadResult = exports.FileUpload = exports.StreamUpload = exports.getValidRangeSize = exports.OneDriveLargeFileUploadTask = exports.LargeFileUploadTask = exports.ChaosHandler = exports.ChaosStrategy = exports.ChaosHandlerOptions = exports.TelemetryHandlerOptions = exports.FeatureUsageFlag = exports.RedirectHandlerOptions = exports.RetryHandlerOptions = exports.AuthenticationHandlerOptions = exports.MiddlewareFactory = exports.TelemetryHandler = exports.RedirectHandler = exports.RetryHandler = exports.HTTPMessageHandler = exports.AuthenticationHandler = exports.BatchResponseContent = exports.BatchRequestContent = void 0; | ||
// eslint-disable-next-line @typescript-eslint/triple-slash-reference | ||
/// <reference path= "../../shims.d.ts" /> | ||
var kiota_abstractions_1 = require("@microsoft/kiota-abstractions"); | ||
Object.defineProperty(exports, "BaseBearerTokenAuthenticationProvider", { enumerable: true, get: function () { return kiota_abstractions_1.BaseBearerTokenAuthenticationProvider; } }); | ||
var kiota_http_fetchlibrary_1 = require("@microsoft/kiota-http-fetchlibrary"); | ||
Object.defineProperty(exports, "RetryHandler", { enumerable: true, get: function () { return kiota_http_fetchlibrary_1.RetryHandler; } }); | ||
Object.defineProperty(exports, "RedirectHandler", { enumerable: true, get: function () { return kiota_http_fetchlibrary_1.RedirectHandler; } }); | ||
Object.defineProperty(exports, "TelemetryHandler", { enumerable: true, get: function () { return kiota_http_fetchlibrary_1.TelemetryHandler; } }); | ||
Object.defineProperty(exports, "RetryHandlerOptions", { enumerable: true, get: function () { return kiota_http_fetchlibrary_1.RetryHandlerOptions; } }); | ||
Object.defineProperty(exports, "HttpClient", { enumerable: true, get: function () { return kiota_http_fetchlibrary_1.HttpClient; } }); | ||
Object.defineProperty(exports, "TelemetryHandlerOptionsKey", { enumerable: true, get: function () { return kiota_http_fetchlibrary_1.TelemetryHandlerOptionsKey; } }); | ||
Object.defineProperty(exports, "RetryHandlerOptionKey", { enumerable: true, get: function () { return kiota_http_fetchlibrary_1.RetryHandlerOptionKey; } }); | ||
var BatchRequestContent_1 = require("../content/BatchRequestContent"); | ||
@@ -17,23 +27,4 @@ Object.defineProperty(exports, "BatchRequestContent", { enumerable: true, get: function () { return BatchRequestContent_1.BatchRequestContent; } }); | ||
Object.defineProperty(exports, "BatchResponseContent", { enumerable: true, get: function () { return BatchResponseContent_1.BatchResponseContent; } }); | ||
var AuthenticationHandler_1 = require("../middleware/AuthenticationHandler"); | ||
Object.defineProperty(exports, "AuthenticationHandler", { enumerable: true, get: function () { return AuthenticationHandler_1.AuthenticationHandler; } }); | ||
var HTTPMessageHandler_1 = require("../middleware/HTTPMessageHandler"); | ||
Object.defineProperty(exports, "HTTPMessageHandler", { enumerable: true, get: function () { return HTTPMessageHandler_1.HTTPMessageHandler; } }); | ||
var RetryHandler_1 = require("../middleware/RetryHandler"); | ||
Object.defineProperty(exports, "RetryHandler", { enumerable: true, get: function () { return RetryHandler_1.RetryHandler; } }); | ||
var RedirectHandler_1 = require("../middleware/RedirectHandler"); | ||
Object.defineProperty(exports, "RedirectHandler", { enumerable: true, get: function () { return RedirectHandler_1.RedirectHandler; } }); | ||
var TelemetryHandler_1 = require("../middleware/TelemetryHandler"); | ||
Object.defineProperty(exports, "TelemetryHandler", { enumerable: true, get: function () { return TelemetryHandler_1.TelemetryHandler; } }); | ||
var MiddlewareFactory_1 = require("../middleware/MiddlewareFactory"); | ||
Object.defineProperty(exports, "MiddlewareFactory", { enumerable: true, get: function () { return MiddlewareFactory_1.MiddlewareFactory; } }); | ||
var AuthenticationHandlerOptions_1 = require("../middleware/options/AuthenticationHandlerOptions"); | ||
Object.defineProperty(exports, "AuthenticationHandlerOptions", { enumerable: true, get: function () { return AuthenticationHandlerOptions_1.AuthenticationHandlerOptions; } }); | ||
var RetryHandlerOptions_1 = require("../middleware/options/RetryHandlerOptions"); | ||
Object.defineProperty(exports, "RetryHandlerOptions", { enumerable: true, get: function () { return RetryHandlerOptions_1.RetryHandlerOptions; } }); | ||
var RedirectHandlerOptions_1 = require("../middleware/options/RedirectHandlerOptions"); | ||
Object.defineProperty(exports, "RedirectHandlerOptions", { enumerable: true, get: function () { return RedirectHandlerOptions_1.RedirectHandlerOptions; } }); | ||
var TelemetryHandlerOptions_1 = require("../middleware/options/TelemetryHandlerOptions"); | ||
Object.defineProperty(exports, "FeatureUsageFlag", { enumerable: true, get: function () { return TelemetryHandlerOptions_1.FeatureUsageFlag; } }); | ||
Object.defineProperty(exports, "TelemetryHandlerOptions", { enumerable: true, get: function () { return TelemetryHandlerOptions_1.TelemetryHandlerOptions; } }); | ||
var TelemetryFeatureUsageFlag_1 = require("../middleware/Telemetry/TelemetryFeatureUsageFlag"); | ||
Object.defineProperty(exports, "FeatureUsageFlag", { enumerable: true, get: function () { return TelemetryFeatureUsageFlag_1.FeatureUsageFlag; } }); | ||
var ChaosHandlerOptions_1 = require("../middleware/options/ChaosHandlerOptions"); | ||
@@ -63,4 +54,2 @@ Object.defineProperty(exports, "ChaosHandlerOptions", { enumerable: true, get: function () { return ChaosHandlerOptions_1.ChaosHandlerOptions; } }); | ||
Object.defineProperty(exports, "Client", { enumerable: true, get: function () { return Client_1.Client; } }); | ||
var CustomAuthenticationProvider_1 = require("../CustomAuthenticationProvider"); | ||
Object.defineProperty(exports, "CustomAuthenticationProvider", { enumerable: true, get: function () { return CustomAuthenticationProvider_1.CustomAuthenticationProvider; } }); | ||
var GraphError_1 = require("../GraphError"); | ||
@@ -74,2 +63,21 @@ Object.defineProperty(exports, "GraphError", { enumerable: true, get: function () { return GraphError_1.GraphError; } }); | ||
Object.defineProperty(exports, "ResponseType", { enumerable: true, get: function () { return ResponseType_1.ResponseType; } }); | ||
var SimpleAuthenticationProvider_1 = require("../authentication/SimpleAuthentication/SimpleAuthenticationProvider"); | ||
Object.defineProperty(exports, "SimpleAuthenticationProvider", { enumerable: true, get: function () { return SimpleAuthenticationProvider_1.SimpleAuthenticationProvider; } }); | ||
var SimpleAccessTokenProvider_1 = require("../authentication/SimpleAuthentication/SimpleAccessTokenProvider"); | ||
Object.defineProperty(exports, "SimpleAccessTokenProvider", { enumerable: true, get: function () { return SimpleAccessTokenProvider_1.SimpleAccessTokenProvider; } }); | ||
var TelemetryUtil_1 = require("../middleware/Telemetry/TelemetryUtil"); | ||
Object.defineProperty(exports, "coreSdkVersionValue", { enumerable: true, get: function () { return TelemetryUtil_1.coreSdkVersionValue; } }); | ||
Object.defineProperty(exports, "getGraphTelemetryCallback", { enumerable: true, get: function () { return TelemetryUtil_1.getGraphTelemetryCallback; } }); | ||
Object.defineProperty(exports, "CORE_PRODUCT_NAME", { enumerable: true, get: function () { return TelemetryUtil_1.CORE_PRODUCT_NAME; } }); | ||
Object.defineProperty(exports, "graphTelemetryCallback", { enumerable: true, get: function () { return TelemetryUtil_1.graphTelemetryCallback; } }); | ||
var MiddlewareFactory_1 = require("./MiddlewareFactory"); | ||
Object.defineProperty(exports, "getDefaultMiddlewareChain", { enumerable: true, get: function () { return MiddlewareFactory_1.getDefaultMiddlewareChain; } }); | ||
var Constants_1 = require("../Constants"); | ||
Object.defineProperty(exports, "GRAPH_API_VERSION", { enumerable: true, get: function () { return Constants_1.GRAPH_API_VERSION; } }); | ||
Object.defineProperty(exports, "GRAPH_BASE_URL", { enumerable: true, get: function () { return Constants_1.GRAPH_BASE_URL; } }); | ||
Object.defineProperty(exports, "GRAPH_URLS", { enumerable: true, get: function () { return Constants_1.GRAPH_URLS; } }); | ||
var GraphRequestUtil_1 = require("../GraphRequestUtil"); | ||
Object.defineProperty(exports, "isCustomHost", { enumerable: true, get: function () { return GraphRequestUtil_1.isCustomHost; } }); | ||
Object.defineProperty(exports, "isGraphURL", { enumerable: true, get: function () { return GraphRequestUtil_1.isGraphURL; } }); | ||
Object.defineProperty(exports, "updateAndReturnAllAllowedHosts", { enumerable: true, get: function () { return GraphRequestUtil_1.updateAndReturnAllAllowedHosts; } }); | ||
//# sourceMappingURL=index.js.map |
@@ -7,6 +7,11 @@ /** | ||
*/ | ||
/** | ||
* @module Client | ||
*/ | ||
import { BaseBearerTokenAuthenticationProvider } from "@microsoft/kiota-abstractions"; | ||
import { HttpClient } from "@microsoft/kiota-http-fetchlibrary"; | ||
import { GraphBaseClient } from "."; | ||
import { GraphRequest } from "./GraphRequest"; | ||
import { ClientOptions } from "./IClientOptions"; | ||
import { Options } from "./IOptions"; | ||
export declare class Client { | ||
export declare class Client implements GraphBaseClient { | ||
/** | ||
@@ -21,3 +26,4 @@ * @private | ||
*/ | ||
private httpClient; | ||
protected httpClient: HttpClient; | ||
protected authProvider: BaseBearerTokenAuthenticationProvider; | ||
/** | ||
@@ -30,12 +36,4 @@ * @public | ||
*/ | ||
static init(options: Options): Client; | ||
static init(options: ClientOptions): Client; | ||
/** | ||
* @public | ||
* @static | ||
* To create a client instance with the Client Options | ||
* @param {ClientOptions} clientOptions - The options object for initializing the client | ||
* @returns The Client instance | ||
*/ | ||
static initWithMiddleware(clientOptions: ClientOptions): Client; | ||
/** | ||
* @private | ||
@@ -42,0 +40,0 @@ * @constructor |
@@ -10,13 +10,9 @@ "use strict"; | ||
exports.Client = void 0; | ||
var tslib_1 = require("tslib"); | ||
/** | ||
* @module Client | ||
*/ | ||
var Constants_1 = require("./Constants"); | ||
var CustomAuthenticationProvider_1 = require("./CustomAuthenticationProvider"); | ||
var GraphRequest_1 = require("./GraphRequest"); | ||
var HTTPClient_1 = require("./HTTPClient"); | ||
var HTTPClientFactory_1 = require("./HTTPClientFactory"); | ||
var ValidatePolyFilling_1 = require("./ValidatePolyFilling"); | ||
var Client = /** @class */ (function () { | ||
const kiota_http_fetchlibrary_1 = require("@microsoft/kiota-http-fetchlibrary"); | ||
const _1 = require("."); | ||
const Constants_1 = require("./Constants"); | ||
const GraphRequest_1 = require("./GraphRequest"); | ||
const GraphRequestUtil_1 = require("./GraphRequestUtil"); | ||
const MiddlewareFactory_1 = require("./MiddlewareFactory"); | ||
class Client { | ||
/** | ||
@@ -28,3 +24,3 @@ * @private | ||
*/ | ||
function Client(clientOptions) { | ||
constructor(clientOptions) { | ||
/** | ||
@@ -39,4 +35,3 @@ * @private | ||
}; | ||
(0, ValidatePolyFilling_1.validatePolyFilling)(); | ||
for (var key in clientOptions) { | ||
for (const key in clientOptions) { | ||
if (Object.prototype.hasOwnProperty.call(clientOptions, key)) { | ||
@@ -46,20 +41,15 @@ this.config[key] = clientOptions[key]; | ||
} | ||
var httpClient; | ||
if (clientOptions.authProvider !== undefined && clientOptions.middleware !== undefined) { | ||
var error = new Error(); | ||
error.name = "AmbiguityInInitialization"; | ||
error.message = "Unable to Create Client, Please provide either authentication provider for default middleware chain or custom middleware chain not both"; | ||
let httpClient; | ||
if (clientOptions.authProvider === undefined) { | ||
const error = new _1.GraphClientError(); | ||
error.name = "Client Initialization Failed"; | ||
error.message = "Unable to Create Client, Please provide an authentication provider"; | ||
throw error; | ||
} | ||
else if (clientOptions.authProvider !== undefined) { | ||
httpClient = HTTPClientFactory_1.HTTPClientFactory.createWithAuthenticationProvider(clientOptions.authProvider); | ||
const allowedHosts = (0, GraphRequestUtil_1.updateAndReturnAllAllowedHosts)(clientOptions.authProvider, this.config.customHosts); | ||
if (!clientOptions.middleware) { | ||
httpClient = new kiota_http_fetchlibrary_1.HttpClient(undefined, ...[].concat((0, MiddlewareFactory_1.getDefaultMiddlewareChain)(clientOptions, allowedHosts))); | ||
} | ||
else if (clientOptions.middleware !== undefined) { | ||
httpClient = new (HTTPClient_1.HTTPClient.bind.apply(HTTPClient_1.HTTPClient, (0, tslib_1.__spreadArray)([void 0], [].concat(clientOptions.middleware), false)))(); | ||
} | ||
else { | ||
var error = new Error(); | ||
error.name = "InvalidMiddlewareChain"; | ||
error.message = "Unable to Create Client, Please provide either authentication provider for default middleware chain or custom middleware chain"; | ||
throw error; | ||
httpClient = new kiota_http_fetchlibrary_1.HttpClient(clientOptions.customFetch, ...[].concat(clientOptions.middleware)); | ||
} | ||
@@ -75,23 +65,7 @@ this.httpClient = httpClient; | ||
*/ | ||
Client.init = function (options) { | ||
var clientOptions = {}; | ||
for (var i in options) { | ||
if (Object.prototype.hasOwnProperty.call(options, i)) { | ||
clientOptions[i] = i === "authProvider" ? new CustomAuthenticationProvider_1.CustomAuthenticationProvider(options[i]) : options[i]; | ||
} | ||
} | ||
return Client.initWithMiddleware(clientOptions); | ||
}; | ||
static init(options) { | ||
return new Client(options); | ||
} | ||
/** | ||
* @public | ||
* @static | ||
* To create a client instance with the Client Options | ||
* @param {ClientOptions} clientOptions - The options object for initializing the client | ||
* @returns The Client instance | ||
*/ | ||
Client.initWithMiddleware = function (clientOptions) { | ||
return new Client(clientOptions); | ||
}; | ||
/** | ||
* @public | ||
* Entry point to make requests | ||
@@ -101,8 +75,7 @@ * @param {string} path - The path string value | ||
*/ | ||
Client.prototype.api = function (path) { | ||
api(path) { | ||
return new GraphRequest_1.GraphRequest(this.httpClient, this.config, path); | ||
}; | ||
return Client; | ||
}()); | ||
} | ||
} | ||
exports.Client = Client; | ||
//# sourceMappingURL=Client.js.map |
@@ -10,7 +10,7 @@ "use strict"; | ||
exports.BatchRequestContent = void 0; | ||
var tslib_1 = require("tslib"); | ||
const tslib_1 = require("tslib"); | ||
/** | ||
* @module BatchRequestContent | ||
*/ | ||
var RequestMethod_1 = require("../RequestMethod"); | ||
const RequestMethod_1 = require("../RequestMethod"); | ||
/** | ||
@@ -20,3 +20,3 @@ * @class | ||
*/ | ||
var BatchRequestContent = /** @class */ (function () { | ||
class BatchRequestContent { | ||
/** | ||
@@ -29,13 +29,12 @@ * @public | ||
*/ | ||
function BatchRequestContent(requests) { | ||
constructor(requests) { | ||
this.requests = new Map(); | ||
if (typeof requests !== "undefined") { | ||
var limit = BatchRequestContent.requestLimit; | ||
const limit = BatchRequestContent.requestLimit; | ||
if (requests.length > limit) { | ||
var error = new Error("Maximum requests limit exceeded, Max allowed number of requests are ".concat(limit)); | ||
const error = new Error(`Maximum requests limit exceeded, Max allowed number of requests are ${limit}`); | ||
error.name = "Limit Exceeded Error"; | ||
throw error; | ||
} | ||
for (var _i = 0, requests_1 = requests; _i < requests_1.length; _i++) { | ||
var req = requests_1[_i]; | ||
for (const req of requests) { | ||
this.addRequest(req); | ||
@@ -61,8 +60,8 @@ } | ||
*/ | ||
BatchRequestContent.validateDependencies = function (requests) { | ||
var isParallel = function (reqs) { | ||
var iterator = reqs.entries(); | ||
var cur = iterator.next(); | ||
static validateDependencies(requests) { | ||
const isParallel = (reqs) => { | ||
const iterator = reqs.entries(); | ||
let cur = iterator.next(); | ||
while (!cur.done) { | ||
var curReq = cur.value[1]; | ||
const curReq = cur.value[1]; | ||
if (curReq.dependsOn !== undefined && curReq.dependsOn.length > 0) { | ||
@@ -75,13 +74,13 @@ return false; | ||
}; | ||
var isSerial = function (reqs) { | ||
var iterator = reqs.entries(); | ||
var cur = iterator.next(); | ||
var firstRequest = cur.value[1]; | ||
const isSerial = (reqs) => { | ||
const iterator = reqs.entries(); | ||
let cur = iterator.next(); | ||
const firstRequest = cur.value[1]; | ||
if (firstRequest.dependsOn !== undefined && firstRequest.dependsOn.length > 0) { | ||
return false; | ||
} | ||
var prev = cur; | ||
let prev = cur; | ||
cur = iterator.next(); | ||
while (!cur.done) { | ||
var curReq = cur.value[1]; | ||
const curReq = cur.value[1]; | ||
if (curReq.dependsOn === undefined || curReq.dependsOn.length !== 1 || curReq.dependsOn[0] !== prev.value[1].id) { | ||
@@ -95,7 +94,7 @@ return false; | ||
}; | ||
var isSame = function (reqs) { | ||
var iterator = reqs.entries(); | ||
var cur = iterator.next(); | ||
var firstRequest = cur.value[1]; | ||
var dependencyId; | ||
const isSame = (reqs) => { | ||
const iterator = reqs.entries(); | ||
let cur = iterator.next(); | ||
const firstRequest = cur.value[1]; | ||
let dependencyId; | ||
if (firstRequest.dependsOn === undefined || firstRequest.dependsOn.length === 0) { | ||
@@ -106,3 +105,3 @@ dependencyId = firstRequest.id; | ||
if (firstRequest.dependsOn.length === 1) { | ||
var fDependencyId = firstRequest.dependsOn[0]; | ||
const fDependencyId = firstRequest.dependsOn[0]; | ||
if (fDependencyId !== firstRequest.id && reqs.has(fDependencyId)) { | ||
@@ -121,3 +120,3 @@ dependencyId = fDependencyId; | ||
while (!cur.done) { | ||
var curReq = cur.value[1]; | ||
const curReq = cur.value[1]; | ||
if ((curReq.dependsOn === undefined || curReq.dependsOn.length === 0) && dependencyId !== curReq.id) { | ||
@@ -139,3 +138,3 @@ return false; | ||
if (requests.size === 0) { | ||
var error = new Error("Empty requests map, Please provide at least one request."); | ||
const error = new Error("Empty requests map, Please provide at least one request."); | ||
error.name = "Empty Requests Error"; | ||
@@ -145,3 +144,3 @@ throw error; | ||
return isParallel(requests) || isSerial(requests) || isSame(requests); | ||
}; | ||
} | ||
/** | ||
@@ -155,37 +154,27 @@ * @private | ||
*/ | ||
BatchRequestContent.getRequestData = function (request) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var requestData, hasHttpRegex, headers, _a; | ||
return (0, tslib_1.__generator)(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
requestData = { | ||
url: "", | ||
}; | ||
hasHttpRegex = new RegExp("^https?://"); | ||
// Stripping off hostname, port and url scheme | ||
requestData.url = hasHttpRegex.test(request.url) ? "/" + request.url.split(/.*?\/\/.*?\//)[1] : request.url; | ||
requestData.method = request.method; | ||
headers = {}; | ||
request.headers.forEach(function (value, key) { | ||
headers[key] = value; | ||
}); | ||
if (Object.keys(headers).length) { | ||
requestData.headers = headers; | ||
} | ||
if (!(request.method === RequestMethod_1.RequestMethod.PATCH || request.method === RequestMethod_1.RequestMethod.POST || request.method === RequestMethod_1.RequestMethod.PUT)) return [3 /*break*/, 2]; | ||
_a = requestData; | ||
return [4 /*yield*/, BatchRequestContent.getRequestBody(request)]; | ||
case 1: | ||
_a.body = _b.sent(); | ||
_b.label = 2; | ||
case 2: | ||
/** | ||
* TODO: Check any other property needs to be used from the Request object and add them | ||
*/ | ||
return [2 /*return*/, requestData]; | ||
} | ||
static getRequestData(request) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
const requestData = { | ||
url: "", | ||
}; | ||
const hasHttpRegex = new RegExp("^https?://"); | ||
// Stripping off hostname, port and url scheme | ||
requestData.url = hasHttpRegex.test(request.url) ? "/" + request.url.split(/.*?\/\/.*?\//)[1] : request.url; | ||
requestData.method = request.method; | ||
const headers = {}; | ||
request.headers.forEach((value, key) => { | ||
headers[key] = value; | ||
}); | ||
if (Object.keys(headers).length) { | ||
requestData.headers = headers; | ||
} | ||
if (request.method === RequestMethod_1.RequestMethod.PATCH || request.method === RequestMethod_1.RequestMethod.POST || request.method === RequestMethod_1.RequestMethod.PUT) { | ||
requestData.body = yield BatchRequestContent.getRequestBody(request); | ||
} | ||
/** | ||
* TODO: Check any other property needs to be used from the Request object and add them | ||
*/ | ||
return requestData; | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -199,70 +188,51 @@ * @private | ||
*/ | ||
BatchRequestContent.getRequestBody = function (request) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var bodyParsed, body, cloneReq, e_1, blob_1, reader_1, buffer, e_2; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
bodyParsed = false; | ||
_a.label = 1; | ||
case 1: | ||
_a.trys.push([1, 3, , 4]); | ||
cloneReq = request.clone(); | ||
return [4 /*yield*/, cloneReq.json()]; | ||
case 2: | ||
body = _a.sent(); | ||
bodyParsed = true; | ||
return [3 /*break*/, 4]; | ||
case 3: | ||
e_1 = _a.sent(); | ||
return [3 /*break*/, 4]; | ||
case 4: | ||
if (!!bodyParsed) return [3 /*break*/, 12]; | ||
_a.label = 5; | ||
case 5: | ||
_a.trys.push([5, 11, , 12]); | ||
if (!(typeof Blob !== "undefined")) return [3 /*break*/, 8]; | ||
return [4 /*yield*/, request.blob()]; | ||
case 6: | ||
blob_1 = _a.sent(); | ||
reader_1 = new FileReader(); | ||
return [4 /*yield*/, new Promise(function (resolve) { | ||
reader_1.addEventListener("load", function () { | ||
var dataURL = reader_1.result; | ||
/** | ||
* Some valid dataURL schemes: | ||
* 1. data:text/vnd-example+xyz;foo=bar;base64,R0lGODdh | ||
* 2. data:text/plain;charset=UTF-8;page=21,the%20data:1234,5678 | ||
* 3. data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg== | ||
* 4. data:image/png,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg== | ||
* 5. data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg== | ||
* @see Syntax {@link https://en.wikipedia.org/wiki/Data_URI_scheme} for more | ||
*/ | ||
var regex = new RegExp("^s*data:(.+?/.+?(;.+?=.+?)*)?(;base64)?,(.*)s*$"); | ||
var segments = regex.exec(dataURL); | ||
resolve(segments[4]); | ||
}, false); | ||
reader_1.readAsDataURL(blob_1); | ||
})]; | ||
case 7: | ||
body = _a.sent(); | ||
return [3 /*break*/, 10]; | ||
case 8: | ||
if (!(typeof Buffer !== "undefined")) return [3 /*break*/, 10]; | ||
return [4 /*yield*/, request.buffer()]; | ||
case 9: | ||
buffer = _a.sent(); | ||
static getRequestBody(request) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let bodyParsed = false; | ||
let body; | ||
try { | ||
const cloneReq = request.clone(); | ||
body = yield cloneReq.json(); | ||
bodyParsed = true; | ||
} | ||
catch (e) { | ||
//TODO- Handle empty catches | ||
} | ||
if (!bodyParsed) { | ||
try { | ||
if (typeof Blob !== "undefined") { | ||
const blob = yield request.blob(); | ||
const reader = new FileReader(); | ||
body = yield new Promise((resolve) => { | ||
reader.addEventListener("load", () => { | ||
const dataURL = reader.result; | ||
/** | ||
* Some valid dataURL schemes: | ||
* 1. data:text/vnd-example+xyz;foo=bar;base64,R0lGODdh | ||
* 2. data:text/plain;charset=UTF-8;page=21,the%20data:1234,5678 | ||
* 3. data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg== | ||
* 4. data:image/png,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg== | ||
* 5. data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg== | ||
* @see Syntax {@link https://en.wikipedia.org/wiki/Data_URI_scheme} for more | ||
*/ | ||
const regex = new RegExp("^s*data:(.+?/.+?(;.+?=.+?)*)?(;base64)?,(.*)s*$"); | ||
const segments = regex.exec(dataURL); | ||
resolve(segments[4]); | ||
}, false); | ||
reader.readAsDataURL(blob); | ||
}); | ||
} | ||
else if (typeof Buffer !== "undefined") { | ||
const buffer = yield request.buffer(); | ||
body = buffer.toString("base64"); | ||
_a.label = 10; | ||
case 10: | ||
bodyParsed = true; | ||
return [3 /*break*/, 12]; | ||
case 11: | ||
e_2 = _a.sent(); | ||
return [3 /*break*/, 12]; | ||
case 12: return [2 /*return*/, body]; | ||
} | ||
bodyParsed = true; | ||
} | ||
}); | ||
catch (e) { | ||
// TODO-Handle empty catches | ||
} | ||
} | ||
return body; | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -274,6 +244,6 @@ * @public | ||
*/ | ||
BatchRequestContent.prototype.addRequest = function (request) { | ||
var limit = BatchRequestContent.requestLimit; | ||
addRequest(request) { | ||
const limit = BatchRequestContent.requestLimit; | ||
if (request.id === "") { | ||
var error = new Error("Id for a request is empty, Please provide an unique id"); | ||
const error = new Error(`Id for a request is empty, Please provide an unique id`); | ||
error.name = "Empty Id For Request"; | ||
@@ -283,3 +253,3 @@ throw error; | ||
if (this.requests.size === limit) { | ||
var error = new Error("Maximum requests limit exceeded, Max allowed number of requests are ".concat(limit)); | ||
const error = new Error(`Maximum requests limit exceeded, Max allowed number of requests are ${limit}`); | ||
error.name = "Limit Exceeded Error"; | ||
@@ -289,3 +259,3 @@ throw error; | ||
if (this.requests.has(request.id)) { | ||
var error = new Error("Adding request with duplicate id ".concat(request.id, ", Make the id of the requests unique")); | ||
const error = new Error(`Adding request with duplicate id ${request.id}, Make the id of the requests unique`); | ||
error.name = "Duplicate RequestId Error"; | ||
@@ -296,3 +266,3 @@ throw error; | ||
return request.id; | ||
}; | ||
} | ||
/** | ||
@@ -304,6 +274,6 @@ * @public | ||
*/ | ||
BatchRequestContent.prototype.removeRequest = function (requestId) { | ||
var deleteStatus = this.requests.delete(requestId); | ||
var iterator = this.requests.entries(); | ||
var cur = iterator.next(); | ||
removeRequest(requestId) { | ||
const deleteStatus = this.requests.delete(requestId); | ||
const iterator = this.requests.entries(); | ||
let cur = iterator.next(); | ||
/** | ||
@@ -313,5 +283,5 @@ * Removing dependencies where this request is present as a dependency | ||
while (!cur.done) { | ||
var dependencies = cur.value[1].dependsOn; | ||
const dependencies = cur.value[1].dependsOn; | ||
if (typeof dependencies !== "undefined") { | ||
var index = dependencies.indexOf(requestId); | ||
const index = dependencies.indexOf(requestId); | ||
if (index !== -1) { | ||
@@ -327,3 +297,3 @@ dependencies.splice(index, 1); | ||
return deleteStatus; | ||
}; | ||
} | ||
/** | ||
@@ -335,55 +305,47 @@ * @public | ||
*/ | ||
BatchRequestContent.prototype.getContent = function () { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var requests, requestBody, iterator, cur, error, error, requestStep, batchRequestData, error; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
requests = []; | ||
requestBody = { | ||
requests: requests, | ||
}; | ||
iterator = this.requests.entries(); | ||
cur = iterator.next(); | ||
if (cur.done) { | ||
error = new Error("No requests added yet, Please add at least one request."); | ||
error.name = "Empty Payload"; | ||
throw error; | ||
} | ||
if (!BatchRequestContent.validateDependencies(this.requests)) { | ||
error = new Error("Invalid dependency found, Dependency should be:\n1. Parallel - no individual request states a dependency in the dependsOn property.\n2. Serial - all individual requests depend on the previous individual request.\n3. Same - all individual requests that state a dependency in the dependsOn property, state the same dependency."); | ||
error.name = "Invalid Dependency"; | ||
throw error; | ||
} | ||
_a.label = 1; | ||
case 1: | ||
if (!!cur.done) return [3 /*break*/, 3]; | ||
requestStep = cur.value[1]; | ||
return [4 /*yield*/, BatchRequestContent.getRequestData(requestStep.request)]; | ||
case 2: | ||
batchRequestData = (_a.sent()); | ||
/** | ||
* @see{@https://tools.ietf.org/html/rfc7578#section-4.4} | ||
* TODO- Setting/Defaulting of content-type header to the correct value | ||
* @see {@link https://developer.microsoft.com/en-us/graph/docs/concepts/json_batching#request-format} | ||
*/ | ||
if (batchRequestData.body !== undefined && (batchRequestData.headers === undefined || batchRequestData.headers["content-type"] === undefined)) { | ||
error = new Error("Content-type header is not mentioned for request #".concat(requestStep.id, ", For request having body, Content-type header should be mentioned")); | ||
error.name = "Invalid Content-type header"; | ||
throw error; | ||
} | ||
batchRequestData.id = requestStep.id; | ||
if (requestStep.dependsOn !== undefined && requestStep.dependsOn.length > 0) { | ||
batchRequestData.dependsOn = requestStep.dependsOn; | ||
} | ||
requests.push(batchRequestData); | ||
cur = iterator.next(); | ||
return [3 /*break*/, 1]; | ||
case 3: | ||
requestBody.requests = requests; | ||
return [2 /*return*/, requestBody]; | ||
getContent() { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
const requests = []; | ||
const requestBody = { | ||
requests, | ||
}; | ||
const iterator = this.requests.entries(); | ||
let cur = iterator.next(); | ||
if (cur.done) { | ||
const error = new Error("No requests added yet, Please add at least one request."); | ||
error.name = "Empty Payload"; | ||
throw error; | ||
} | ||
if (!BatchRequestContent.validateDependencies(this.requests)) { | ||
const error = new Error(`Invalid dependency found, Dependency should be: | ||
1. Parallel - no individual request states a dependency in the dependsOn property. | ||
2. Serial - all individual requests depend on the previous individual request. | ||
3. Same - all individual requests that state a dependency in the dependsOn property, state the same dependency.`); | ||
error.name = "Invalid Dependency"; | ||
throw error; | ||
} | ||
while (!cur.done) { | ||
const requestStep = cur.value[1]; | ||
const batchRequestData = (yield BatchRequestContent.getRequestData(requestStep.request)); | ||
/** | ||
* @see{@https://tools.ietf.org/html/rfc7578#section-4.4} | ||
* TODO- Setting/Defaulting of content-type header to the correct value | ||
* @see {@link https://developer.microsoft.com/en-us/graph/docs/concepts/json_batching#request-format} | ||
*/ | ||
if (batchRequestData.body !== undefined && (batchRequestData.headers === undefined || batchRequestData.headers["content-type"] === undefined)) { | ||
const error = new Error(`Content-type header is not mentioned for request #${requestStep.id}, For request having body, Content-type header should be mentioned`); | ||
error.name = "Invalid Content-type header"; | ||
throw error; | ||
} | ||
}); | ||
batchRequestData.id = requestStep.id; | ||
if (requestStep.dependsOn !== undefined && requestStep.dependsOn.length > 0) { | ||
batchRequestData.dependsOn = requestStep.dependsOn; | ||
} | ||
requests.push(batchRequestData); | ||
cur = iterator.next(); | ||
} | ||
requestBody.requests = requests; | ||
return requestBody; | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -396,5 +358,5 @@ * @public | ||
*/ | ||
BatchRequestContent.prototype.addDependency = function (dependentId, dependencyId) { | ||
addDependency(dependentId, dependencyId) { | ||
if (!this.requests.has(dependentId)) { | ||
var error = new Error("Dependent ".concat(dependentId, " does not exists, Please check the id")); | ||
const error = new Error(`Dependent ${dependentId} does not exists, Please check the id`); | ||
error.name = "Invalid Dependent"; | ||
@@ -404,3 +366,3 @@ throw error; | ||
if (typeof dependencyId !== "undefined" && !this.requests.has(dependencyId)) { | ||
var error = new Error("Dependency ".concat(dependencyId, " does not exists, Please check the id")); | ||
const error = new Error(`Dependency ${dependencyId} does not exists, Please check the id`); | ||
error.name = "Invalid Dependency"; | ||
@@ -410,3 +372,3 @@ throw error; | ||
if (typeof dependencyId !== "undefined") { | ||
var dependent = this.requests.get(dependentId); | ||
const dependent = this.requests.get(dependentId); | ||
if (dependent.dependsOn === undefined) { | ||
@@ -416,3 +378,3 @@ dependent.dependsOn = []; | ||
if (dependent.dependsOn.indexOf(dependencyId) !== -1) { | ||
var error = new Error("Dependency ".concat(dependencyId, " is already added for the request ").concat(dependentId)); | ||
const error = new Error(`Dependency ${dependencyId} is already added for the request ${dependentId}`); | ||
error.name = "Duplicate Dependency"; | ||
@@ -424,5 +386,5 @@ throw error; | ||
else { | ||
var iterator = this.requests.entries(); | ||
var prev = void 0; | ||
var cur = iterator.next(); | ||
const iterator = this.requests.entries(); | ||
let prev; | ||
let cur = iterator.next(); | ||
while (!cur.done && cur.value[1].id !== dependentId) { | ||
@@ -433,3 +395,3 @@ prev = cur; | ||
if (typeof prev !== "undefined") { | ||
var dId = prev.value[0]; | ||
const dId = prev.value[0]; | ||
if (cur.value[1].dependsOn === undefined) { | ||
@@ -439,3 +401,3 @@ cur.value[1].dependsOn = []; | ||
if (cur.value[1].dependsOn.indexOf(dId) !== -1) { | ||
var error = new Error("Dependency ".concat(dId, " is already added for the request ").concat(dependentId)); | ||
const error = new Error(`Dependency ${dId} is already added for the request ${dependentId}`); | ||
error.name = "Duplicate Dependency"; | ||
@@ -447,3 +409,3 @@ throw error; | ||
else { | ||
var error = new Error("Can't add dependency ".concat(dependencyId, ", There is only a dependent request in the batch")); | ||
const error = new Error(`Can't add dependency ${dependencyId}, There is only a dependent request in the batch`); | ||
error.name = "Invalid Dependency Addition"; | ||
@@ -453,3 +415,3 @@ throw error; | ||
} | ||
}; | ||
} | ||
/** | ||
@@ -462,4 +424,4 @@ * @public | ||
*/ | ||
BatchRequestContent.prototype.removeDependency = function (dependentId, dependencyId) { | ||
var request = this.requests.get(dependentId); | ||
removeDependency(dependentId, dependencyId) { | ||
const request = this.requests.get(dependentId); | ||
if (typeof request === "undefined" || request.dependsOn === undefined || request.dependsOn.length === 0) { | ||
@@ -469,3 +431,3 @@ return false; | ||
if (typeof dependencyId !== "undefined") { | ||
var index = request.dependsOn.indexOf(dependencyId); | ||
const index = request.dependsOn.indexOf(dependencyId); | ||
if (index === -1) { | ||
@@ -481,12 +443,11 @@ return false; | ||
} | ||
}; | ||
/** | ||
* @private | ||
* @static | ||
* Limit for number of requests {@link - https://developer.microsoft.com/en-us/graph/docs/concepts/known_issues#json-batching} | ||
*/ | ||
BatchRequestContent.requestLimit = 20; | ||
return BatchRequestContent; | ||
}()); | ||
} | ||
} | ||
exports.BatchRequestContent = BatchRequestContent; | ||
/** | ||
* @private | ||
* @static | ||
* Limit for number of requests {@link - https://developer.microsoft.com/en-us/graph/docs/concepts/known_issues#json-batching} | ||
*/ | ||
BatchRequestContent.requestLimit = 20; | ||
//# sourceMappingURL=BatchRequestContent.js.map |
@@ -10,3 +10,2 @@ "use strict"; | ||
exports.BatchResponseContent = void 0; | ||
var tslib_1 = require("tslib"); | ||
/** | ||
@@ -16,3 +15,3 @@ * @class | ||
*/ | ||
var BatchResponseContent = /** @class */ (function () { | ||
class BatchResponseContent { | ||
/** | ||
@@ -25,3 +24,3 @@ * @public | ||
*/ | ||
function BatchResponseContent(response) { | ||
constructor(response) { | ||
this.responses = new Map(); | ||
@@ -36,5 +35,5 @@ this.update(response); | ||
*/ | ||
BatchResponseContent.prototype.createResponseObject = function (responseJSON) { | ||
var body = responseJSON.body; | ||
var options = {}; | ||
createResponseObject(responseJSON) { | ||
const body = responseJSON.body; | ||
const options = {}; | ||
options.status = responseJSON.status; | ||
@@ -47,3 +46,3 @@ if (responseJSON.statusText !== undefined) { | ||
if (options.headers["Content-Type"].split(";")[0] === "application/json") { | ||
var bodyString = JSON.stringify(body); | ||
const bodyString = JSON.stringify(body); | ||
return new Response(bodyString, options); | ||
@@ -53,3 +52,3 @@ } | ||
return new Response(body, options); | ||
}; | ||
} | ||
/** | ||
@@ -61,9 +60,9 @@ * @public | ||
*/ | ||
BatchResponseContent.prototype.update = function (response) { | ||
update(response) { | ||
this.nextLink = response["@odata.nextLink"]; | ||
var responses = response.responses; | ||
for (var i = 0, l = responses.length; i < l; i++) { | ||
const responses = response.responses; | ||
for (let i = 0, l = responses.length; i < l; i++) { | ||
this.responses.set(responses[i].id, this.createResponseObject(responses[i])); | ||
} | ||
}; | ||
} | ||
/** | ||
@@ -75,5 +74,5 @@ * @public | ||
*/ | ||
BatchResponseContent.prototype.getResponseById = function (requestId) { | ||
getResponseById(requestId) { | ||
return this.responses.get(requestId); | ||
}; | ||
} | ||
/** | ||
@@ -84,5 +83,5 @@ * @public | ||
*/ | ||
BatchResponseContent.prototype.getResponses = function () { | ||
getResponses() { | ||
return this.responses; | ||
}; | ||
} | ||
/** | ||
@@ -93,24 +92,12 @@ * @public | ||
*/ | ||
BatchResponseContent.prototype.getResponsesIterator = function () { | ||
var iterator, cur; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
iterator = this.responses.entries(); | ||
cur = iterator.next(); | ||
_a.label = 1; | ||
case 1: | ||
if (!!cur.done) return [3 /*break*/, 3]; | ||
return [4 /*yield*/, cur.value]; | ||
case 2: | ||
_a.sent(); | ||
cur = iterator.next(); | ||
return [3 /*break*/, 1]; | ||
case 3: return [2 /*return*/]; | ||
} | ||
}); | ||
}; | ||
return BatchResponseContent; | ||
}()); | ||
*getResponsesIterator() { | ||
const iterator = this.responses.entries(); | ||
let cur = iterator.next(); | ||
while (!cur.done) { | ||
yield cur.value; | ||
cur = iterator.next(); | ||
} | ||
} | ||
} | ||
exports.BatchResponseContent = BatchResponseContent; | ||
//# sourceMappingURL=BatchResponseContent.js.map |
@@ -10,3 +10,2 @@ "use strict"; | ||
exports.GraphClientError = void 0; | ||
var tslib_1 = require("tslib"); | ||
/** | ||
@@ -21,4 +20,3 @@ * @module GraphClientError | ||
*/ | ||
var GraphClientError = /** @class */ (function (_super) { | ||
(0, tslib_1.__extends)(GraphClientError, _super); | ||
class GraphClientError extends Error { | ||
/** | ||
@@ -31,6 +29,5 @@ * @public | ||
*/ | ||
function GraphClientError(message) { | ||
var _this = _super.call(this, message) || this; | ||
Object.setPrototypeOf(_this, GraphClientError.prototype); | ||
return _this; | ||
constructor(message) { | ||
super(message); | ||
Object.setPrototypeOf(this, GraphClientError.prototype); | ||
} | ||
@@ -45,4 +42,4 @@ /** | ||
*/ | ||
GraphClientError.setGraphClientError = function (error) { | ||
var graphClientError; | ||
static setGraphClientError(error) { | ||
let graphClientError; | ||
if (error instanceof Error) { | ||
@@ -56,6 +53,5 @@ graphClientError = error; | ||
return graphClientError; | ||
}; | ||
return GraphClientError; | ||
}(Error)); | ||
} | ||
} | ||
exports.GraphClientError = GraphClientError; | ||
//# sourceMappingURL=GraphClientError.js.map |
@@ -10,3 +10,2 @@ "use strict"; | ||
exports.GraphError = void 0; | ||
var tslib_1 = require("tslib"); | ||
/** | ||
@@ -22,4 +21,3 @@ * @module GraphError | ||
*/ | ||
var GraphError = /** @class */ (function (_super) { | ||
(0, tslib_1.__extends)(GraphError, _super); | ||
class GraphError extends Error { | ||
/** | ||
@@ -34,18 +32,15 @@ * @public | ||
*/ | ||
function GraphError(statusCode, message, baseError) { | ||
if (statusCode === void 0) { statusCode = -1; } | ||
var _this = _super.call(this, message || (baseError && baseError.message)) || this; | ||
constructor(statusCode = -1, message, baseError) { | ||
super(message || (baseError && baseError.message)); | ||
// https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work | ||
Object.setPrototypeOf(_this, GraphError.prototype); | ||
_this.statusCode = statusCode; | ||
_this.code = null; | ||
_this.requestId = null; | ||
_this.date = new Date(); | ||
_this.body = null; | ||
_this.stack = baseError ? baseError.stack : _this.stack; | ||
return _this; | ||
Object.setPrototypeOf(this, GraphError.prototype); | ||
this.statusCode = statusCode; | ||
this.code = null; | ||
this.requestId = null; | ||
this.date = new Date(); | ||
this.body = null; | ||
this.stack = baseError ? baseError.stack : this.stack; | ||
} | ||
return GraphError; | ||
}(Error)); | ||
} | ||
exports.GraphError = GraphError; | ||
//# sourceMappingURL=GraphError.js.map |
@@ -10,7 +10,7 @@ "use strict"; | ||
exports.GraphErrorHandler = void 0; | ||
var tslib_1 = require("tslib"); | ||
const tslib_1 = require("tslib"); | ||
/** | ||
* @module GraphErrorHandler | ||
*/ | ||
var GraphError_1 = require("./GraphError"); | ||
const GraphError_1 = require("./GraphError"); | ||
/** | ||
@@ -20,5 +20,3 @@ * @class | ||
*/ | ||
var GraphErrorHandler = /** @class */ (function () { | ||
function GraphErrorHandler() { | ||
} | ||
class GraphErrorHandler { | ||
/** | ||
@@ -32,4 +30,4 @@ * @private | ||
*/ | ||
GraphErrorHandler.constructError = function (error, statusCode) { | ||
var gError = new GraphError_1.GraphError(statusCode, "", error); | ||
static constructError(error, statusCode) { | ||
const gError = new GraphError_1.GraphError(statusCode, "", error); | ||
if (error.name !== undefined) { | ||
@@ -41,3 +39,3 @@ gError.code = error.name; | ||
return gError; | ||
}; | ||
} | ||
/** | ||
@@ -64,5 +62,5 @@ * @private | ||
*/ | ||
GraphErrorHandler.constructErrorFromResponse = function (graphError, statusCode) { | ||
var error = graphError.error; | ||
var gError = new GraphError_1.GraphError(statusCode, error.message); | ||
static constructErrorFromResponse(graphError, statusCode) { | ||
const error = graphError.error; | ||
const gError = new GraphError_1.GraphError(statusCode, error.message); | ||
gError.code = error.code; | ||
@@ -75,3 +73,3 @@ if (error.innerError !== undefined) { | ||
return gError; | ||
}; | ||
} | ||
/** | ||
@@ -88,31 +86,25 @@ * @public | ||
*/ | ||
GraphErrorHandler.getError = function (error, statusCode, callback) { | ||
if (error === void 0) { error = null; } | ||
if (statusCode === void 0) { statusCode = -1; } | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var gError; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
if (error && error.error) { | ||
gError = GraphErrorHandler.constructErrorFromResponse(error, statusCode); | ||
} | ||
else if (error instanceof Error) { | ||
gError = GraphErrorHandler.constructError(error, statusCode); | ||
} | ||
else { | ||
gError = new GraphError_1.GraphError(statusCode); | ||
gError.body = error; // if a custom error is passed which is not instance of Error object or a graph API response | ||
} | ||
if (typeof callback === "function") { | ||
callback(gError, null); | ||
} | ||
else { | ||
return [2 /*return*/, gError]; | ||
} | ||
return [2 /*return*/]; | ||
}); | ||
static getError(error = null, statusCode = -1, callback) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let gError; | ||
if (error && error.error) { | ||
gError = GraphErrorHandler.constructErrorFromResponse(error, statusCode); | ||
} | ||
else if (error instanceof Error) { | ||
gError = GraphErrorHandler.constructError(error, statusCode); | ||
} | ||
else { | ||
gError = new GraphError_1.GraphError(statusCode); | ||
gError.body = error; // if a custom error is passed which is not instance of Error object or a graph API response | ||
} | ||
if (typeof callback === "function") { | ||
callback(gError, null); | ||
} | ||
else { | ||
return gError; | ||
} | ||
}); | ||
}; | ||
return GraphErrorHandler; | ||
}()); | ||
} | ||
} | ||
exports.GraphErrorHandler = GraphErrorHandler; | ||
//# sourceMappingURL=GraphErrorHandler.js.map |
@@ -7,3 +7,6 @@ /** | ||
*/ | ||
import { HTTPClient } from "./HTTPClient"; | ||
/** | ||
* @module GraphRequest | ||
*/ | ||
import { HttpClient } from "@microsoft/kiota-http-fetchlibrary"; | ||
import { ClientOptions } from "./IClientOptions"; | ||
@@ -89,3 +92,3 @@ import { GraphRequestCallback } from "./IGraphRequestCallback"; | ||
*/ | ||
constructor(httpClient: HTTPClient, config: ClientOptions, path: string); | ||
constructor(httpClient: HttpClient, config: ClientOptions, path: string); | ||
/** | ||
@@ -92,0 +95,0 @@ * @private |
@@ -10,18 +10,14 @@ "use strict"; | ||
exports.GraphRequest = void 0; | ||
var tslib_1 = require("tslib"); | ||
const tslib_1 = require("tslib"); | ||
const GraphClientError_1 = require("./GraphClientError"); | ||
const GraphErrorHandler_1 = require("./GraphErrorHandler"); | ||
const GraphRequestUtil_1 = require("./GraphRequestUtil"); | ||
const GraphResponseHandler_1 = require("./GraphResponseHandler"); | ||
const RequestMethod_1 = require("./RequestMethod"); | ||
const ResponseType_1 = require("./ResponseType"); | ||
/** | ||
* @module GraphRequest | ||
*/ | ||
var GraphClientError_1 = require("./GraphClientError"); | ||
var GraphErrorHandler_1 = require("./GraphErrorHandler"); | ||
var GraphRequestUtil_1 = require("./GraphRequestUtil"); | ||
var GraphResponseHandler_1 = require("./GraphResponseHandler"); | ||
var MiddlewareControl_1 = require("./middleware/MiddlewareControl"); | ||
var RequestMethod_1 = require("./RequestMethod"); | ||
var ResponseType_1 = require("./ResponseType"); | ||
/** | ||
* @class | ||
* A Class representing GraphRequest | ||
*/ | ||
var GraphRequest = /** @class */ (function () { | ||
class GraphRequest { | ||
/** | ||
@@ -35,4 +31,3 @@ * @public | ||
*/ | ||
function GraphRequest(httpClient, config, path) { | ||
var _this = this; | ||
constructor(httpClient, config, path) { | ||
/** | ||
@@ -44,3 +39,3 @@ * @private | ||
*/ | ||
this.parsePath = function (path) { | ||
this.parsePath = (path) => { | ||
// Strips out the base of the url if they passed in | ||
@@ -50,6 +45,6 @@ if (path.indexOf("https://") !== -1) { | ||
// Find where the host ends | ||
var endOfHostStrPos = path.indexOf("/"); | ||
const endOfHostStrPos = path.indexOf("/"); | ||
if (endOfHostStrPos !== -1) { | ||
// Parse out the host | ||
_this.urlComponents.host = "https://" + path.substring(0, endOfHostStrPos); | ||
this.urlComponents.host = "https://" + path.substring(0, endOfHostStrPos); | ||
// Strip the host from path | ||
@@ -59,6 +54,6 @@ path = path.substring(endOfHostStrPos + 1, path.length); | ||
// Remove the following version | ||
var endOfVersionStrPos = path.indexOf("/"); | ||
const endOfVersionStrPos = path.indexOf("/"); | ||
if (endOfVersionStrPos !== -1) { | ||
// Parse out the version | ||
_this.urlComponents.version = path.substring(0, endOfVersionStrPos); | ||
this.urlComponents.version = path.substring(0, endOfVersionStrPos); | ||
// Strip version from path | ||
@@ -72,14 +67,13 @@ path = path.substring(endOfVersionStrPos + 1, path.length); | ||
} | ||
var queryStrPos = path.indexOf("?"); | ||
const queryStrPos = path.indexOf("?"); | ||
if (queryStrPos === -1) { | ||
// No query string | ||
_this.urlComponents.path = path; | ||
this.urlComponents.path = path; | ||
} | ||
else { | ||
_this.urlComponents.path = path.substr(0, queryStrPos); | ||
this.urlComponents.path = path.substr(0, queryStrPos); | ||
// Capture query string into oDataQueryParams and otherURLQueryParams | ||
var queryParams = path.substring(queryStrPos + 1, path.length).split("&"); | ||
for (var _i = 0, queryParams_1 = queryParams; _i < queryParams_1.length; _i++) { | ||
var queryParam = queryParams_1[_i]; | ||
_this.parseQueryParameter(queryParam); | ||
const queryParams = path.substring(queryStrPos + 1, path.length).split("&"); | ||
for (const queryParam of queryParams) { | ||
this.parseQueryParameter(queryParam); | ||
} | ||
@@ -110,6 +104,6 @@ } | ||
*/ | ||
GraphRequest.prototype.addCsvQueryParameter = function (propertyName, propertyValue, additionalProperties) { | ||
addCsvQueryParameter(propertyName, propertyValue, additionalProperties) { | ||
// If there are already $propertyName value there, append a "," | ||
this.urlComponents.oDataQueryParams[propertyName] = this.urlComponents.oDataQueryParams[propertyName] ? this.urlComponents.oDataQueryParams[propertyName] + "," : ""; | ||
var allValues = []; | ||
let allValues = []; | ||
if (additionalProperties.length > 1 && typeof propertyValue === "string") { | ||
@@ -125,3 +119,3 @@ allValues = Array.prototype.slice.call(additionalProperties); | ||
this.urlComponents.oDataQueryParams[propertyName] += allValues.join(","); | ||
}; | ||
} | ||
/** | ||
@@ -132,4 +126,4 @@ * @private | ||
*/ | ||
GraphRequest.prototype.buildFullUrl = function () { | ||
var url = (0, GraphRequestUtil_1.urlJoin)([this.urlComponents.host, this.urlComponents.version, this.urlComponents.path]) + this.createQueryString(); | ||
buildFullUrl() { | ||
const url = (0, GraphRequestUtil_1.urlJoin)([this.urlComponents.host, this.urlComponents.version, this.urlComponents.path]) + this.createQueryString(); | ||
if (this.config.debugLogging) { | ||
@@ -139,3 +133,3 @@ console.log(url); | ||
return url; | ||
}; | ||
} | ||
/** | ||
@@ -146,8 +140,8 @@ * @private | ||
*/ | ||
GraphRequest.prototype.createQueryString = function () { | ||
createQueryString() { | ||
// Combining query params from oDataQueryParams and otherURLQueryParams | ||
var urlComponents = this.urlComponents; | ||
var query = []; | ||
const urlComponents = this.urlComponents; | ||
const query = []; | ||
if (Object.keys(urlComponents.oDataQueryParams).length !== 0) { | ||
for (var property in urlComponents.oDataQueryParams) { | ||
for (const property in urlComponents.oDataQueryParams) { | ||
if (Object.prototype.hasOwnProperty.call(urlComponents.oDataQueryParams, property)) { | ||
@@ -159,3 +153,3 @@ query.push(property + "=" + urlComponents.oDataQueryParams[property]); | ||
if (Object.keys(urlComponents.otherURLQueryParams).length !== 0) { | ||
for (var property in urlComponents.otherURLQueryParams) { | ||
for (const property in urlComponents.otherURLQueryParams) { | ||
if (Object.prototype.hasOwnProperty.call(urlComponents.otherURLQueryParams, property)) { | ||
@@ -167,4 +161,3 @@ query.push(property + "=" + urlComponents.otherURLQueryParams[property]); | ||
if (urlComponents.otherURLQueryOptions.length !== 0) { | ||
for (var _i = 0, _a = urlComponents.otherURLQueryOptions; _i < _a.length; _i++) { | ||
var str = _a[_i]; | ||
for (const str of urlComponents.otherURLQueryOptions) { | ||
query.push(str); | ||
@@ -174,3 +167,3 @@ } | ||
return query.length > 0 ? "?" + query.join("&") : ""; | ||
}; | ||
} | ||
/** | ||
@@ -182,3 +175,3 @@ * @private | ||
*/ | ||
GraphRequest.prototype.parseQueryParameter = function (queryDictionaryOrString) { | ||
parseQueryParameter(queryDictionaryOrString) { | ||
if (typeof queryDictionaryOrString === "string") { | ||
@@ -189,5 +182,4 @@ if (queryDictionaryOrString.charAt(0) === "?") { | ||
if (queryDictionaryOrString.indexOf("&") !== -1) { | ||
var queryParams = queryDictionaryOrString.split("&"); | ||
for (var _i = 0, queryParams_2 = queryParams; _i < queryParams_2.length; _i++) { | ||
var str = queryParams_2[_i]; | ||
const queryParams = queryDictionaryOrString.split("&"); | ||
for (const str of queryParams) { | ||
this.parseQueryParamenterString(str); | ||
@@ -201,3 +193,3 @@ } | ||
else if (queryDictionaryOrString.constructor === Object) { | ||
for (var key in queryDictionaryOrString) { | ||
for (const key in queryDictionaryOrString) { | ||
if (Object.prototype.hasOwnProperty.call(queryDictionaryOrString, key)) { | ||
@@ -209,3 +201,3 @@ this.setURLComponentsQueryParamater(key, queryDictionaryOrString[key]); | ||
return this; | ||
}; | ||
} | ||
/** | ||
@@ -217,9 +209,9 @@ * @private | ||
*/ | ||
GraphRequest.prototype.parseQueryParamenterString = function (queryParameter) { | ||
parseQueryParamenterString(queryParameter) { | ||
/* The query key-value pair must be split on the first equals sign to avoid errors in parsing nested query parameters. | ||
Example-> "/me?$expand=home($select=city)" */ | ||
if (this.isValidQueryKeyValuePair(queryParameter)) { | ||
var indexOfFirstEquals = queryParameter.indexOf("="); | ||
var paramKey = queryParameter.substring(0, indexOfFirstEquals); | ||
var paramValue = queryParameter.substring(indexOfFirstEquals + 1); | ||
const indexOfFirstEquals = queryParameter.indexOf("="); | ||
const paramKey = queryParameter.substring(0, indexOfFirstEquals); | ||
const paramValue = queryParameter.substring(indexOfFirstEquals + 1); | ||
this.setURLComponentsQueryParamater(paramKey, paramValue); | ||
@@ -232,3 +224,3 @@ } | ||
} | ||
}; | ||
} | ||
/** | ||
@@ -241,6 +233,6 @@ * @private | ||
*/ | ||
GraphRequest.prototype.setURLComponentsQueryParamater = function (paramKey, paramValue) { | ||
setURLComponentsQueryParamater(paramKey, paramValue) { | ||
if (GraphRequestUtil_1.oDataQueryNames.indexOf(paramKey) !== -1) { | ||
var currentValue = this.urlComponents.oDataQueryParams[paramKey]; | ||
var isValueAppendable = currentValue && (paramKey === "$expand" || paramKey === "$select" || paramKey === "$orderby"); | ||
const currentValue = this.urlComponents.oDataQueryParams[paramKey]; | ||
const isValueAppendable = currentValue && (paramKey === "$expand" || paramKey === "$select" || paramKey === "$orderby"); | ||
this.urlComponents.oDataQueryParams[paramKey] = isValueAppendable ? currentValue + "," + paramValue : paramValue; | ||
@@ -251,3 +243,3 @@ } | ||
} | ||
}; | ||
} | ||
/** | ||
@@ -259,8 +251,8 @@ * @private | ||
*/ | ||
GraphRequest.prototype.isValidQueryKeyValuePair = function (queryString) { | ||
var indexofFirstEquals = queryString.indexOf("="); | ||
isValidQueryKeyValuePair(queryString) { | ||
const indexofFirstEquals = queryString.indexOf("="); | ||
if (indexofFirstEquals === -1) { | ||
return false; | ||
} | ||
var indexofOpeningParanthesis = queryString.indexOf("("); | ||
const indexofOpeningParanthesis = queryString.indexOf("("); | ||
if (indexofOpeningParanthesis !== -1 && queryString.indexOf("(") < indexofFirstEquals) { | ||
@@ -271,3 +263,3 @@ // Example -> .query($select($expand=true)); | ||
return true; | ||
}; | ||
} | ||
/** | ||
@@ -279,9 +271,9 @@ * @private | ||
*/ | ||
GraphRequest.prototype.updateRequestOptions = function (options) { | ||
var optionsHeaders = (0, tslib_1.__assign)({}, options.headers); | ||
updateRequestOptions(options) { | ||
const optionsHeaders = Object.assign({}, options.headers); | ||
if (this.config.fetchOptions !== undefined) { | ||
var fetchOptions = (0, tslib_1.__assign)({}, this.config.fetchOptions); | ||
const fetchOptions = Object.assign({}, this.config.fetchOptions); | ||
Object.assign(options, fetchOptions); | ||
if (typeof this.config.fetchOptions.headers !== undefined) { | ||
options.headers = (0, tslib_1.__assign)({}, this.config.fetchOptions.headers); | ||
options.headers = Object.assign({}, this.config.fetchOptions.headers); | ||
} | ||
@@ -295,3 +287,3 @@ } | ||
options.headers = optionsHeaders; | ||
}; | ||
} | ||
/** | ||
@@ -306,46 +298,24 @@ * @private | ||
*/ | ||
GraphRequest.prototype.send = function (request, options, callback) { | ||
var _a; | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var rawResponse, middlewareControl, customHosts, context_1, response, error_1, statusCode, gError; | ||
return (0, tslib_1.__generator)(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
middlewareControl = new MiddlewareControl_1.MiddlewareControl(this._middlewareOptions); | ||
this.updateRequestOptions(options); | ||
customHosts = (_a = this.config) === null || _a === void 0 ? void 0 : _a.customHosts; | ||
_b.label = 1; | ||
case 1: | ||
_b.trys.push([1, 4, , 6]); | ||
return [4 /*yield*/, this.httpClient.sendRequest({ | ||
request: request, | ||
options: options, | ||
middlewareControl: middlewareControl, | ||
customHosts: customHosts, | ||
})]; | ||
case 2: | ||
context_1 = _b.sent(); | ||
rawResponse = context_1.response; | ||
return [4 /*yield*/, GraphResponseHandler_1.GraphResponseHandler.getResponse(rawResponse, this._responseType, callback)]; | ||
case 3: | ||
response = _b.sent(); | ||
return [2 /*return*/, response]; | ||
case 4: | ||
error_1 = _b.sent(); | ||
if (error_1 instanceof GraphClientError_1.GraphClientError) { | ||
throw error_1; | ||
} | ||
statusCode = void 0; | ||
if (rawResponse) { | ||
statusCode = rawResponse.status; | ||
} | ||
return [4 /*yield*/, GraphErrorHandler_1.GraphErrorHandler.getError(error_1, statusCode, callback)]; | ||
case 5: | ||
gError = _b.sent(); | ||
throw gError; | ||
case 6: return [2 /*return*/]; | ||
send(request, options, callback) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let rawResponse; | ||
this.updateRequestOptions(options); | ||
try { | ||
const rawResponse = yield this.httpClient.executeFetch(request, options); | ||
const response = yield GraphResponseHandler_1.GraphResponseHandler.getResponse(rawResponse, this._responseType, callback); | ||
return response; | ||
} | ||
catch (error) { | ||
if (error instanceof GraphClientError_1.GraphClientError) { | ||
throw error; | ||
} | ||
}); | ||
let statusCode; | ||
if (rawResponse) { | ||
statusCode = rawResponse.status; | ||
} | ||
const gError = yield GraphErrorHandler_1.GraphErrorHandler.getError(error, statusCode, callback); | ||
throw gError; | ||
} | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -357,3 +327,3 @@ * @private | ||
*/ | ||
GraphRequest.prototype.setHeaderContentType = function () { | ||
setHeaderContentType() { | ||
if (!this._headers) { | ||
@@ -363,5 +333,4 @@ this.header("Content-Type", "application/json"); | ||
} | ||
var headerKeys = Object.keys(this._headers); | ||
for (var _i = 0, headerKeys_1 = headerKeys; _i < headerKeys_1.length; _i++) { | ||
var headerKey = headerKeys_1[_i]; | ||
const headerKeys = Object.keys(this._headers); | ||
for (const headerKey of headerKeys) { | ||
if (headerKey.toLowerCase() === "content-type") { | ||
@@ -373,3 +342,3 @@ return; | ||
this.header("Content-Type", "application/json"); | ||
}; | ||
} | ||
/** | ||
@@ -382,6 +351,6 @@ * @public | ||
*/ | ||
GraphRequest.prototype.header = function (headerKey, headerValue) { | ||
header(headerKey, headerValue) { | ||
this._headers[headerKey] = headerValue; | ||
return this; | ||
}; | ||
} | ||
/** | ||
@@ -393,4 +362,4 @@ * @public | ||
*/ | ||
GraphRequest.prototype.headers = function (headers) { | ||
for (var key in headers) { | ||
headers(headers) { | ||
for (const key in headers) { | ||
if (Object.prototype.hasOwnProperty.call(headers, key)) { | ||
@@ -401,3 +370,3 @@ this._headers[key] = headers[key]; | ||
return this; | ||
}; | ||
} | ||
/** | ||
@@ -410,6 +379,6 @@ * @public | ||
*/ | ||
GraphRequest.prototype.option = function (key, value) { | ||
option(key, value) { | ||
this._options[key] = value; | ||
return this; | ||
}; | ||
} | ||
/** | ||
@@ -421,4 +390,4 @@ * @public | ||
*/ | ||
GraphRequest.prototype.options = function (options) { | ||
for (var key in options) { | ||
options(options) { | ||
for (const key in options) { | ||
if (Object.prototype.hasOwnProperty.call(options, key)) { | ||
@@ -429,3 +398,3 @@ this._options[key] = options[key]; | ||
return this; | ||
}; | ||
} | ||
/** | ||
@@ -437,6 +406,6 @@ * @public | ||
*/ | ||
GraphRequest.prototype.middlewareOptions = function (options) { | ||
middlewareOptions(options) { | ||
this._middlewareOptions = options; | ||
return this; | ||
}; | ||
} | ||
/** | ||
@@ -448,6 +417,6 @@ * @public | ||
*/ | ||
GraphRequest.prototype.version = function (version) { | ||
version(version) { | ||
this.urlComponents.version = version; | ||
return this; | ||
}; | ||
} | ||
/** | ||
@@ -459,6 +428,6 @@ * @public | ||
*/ | ||
GraphRequest.prototype.responseType = function (responseType) { | ||
responseType(responseType) { | ||
this._responseType = responseType; | ||
return this; | ||
}; | ||
} | ||
/** | ||
@@ -476,6 +445,6 @@ * @public | ||
*/ | ||
GraphRequest.prototype.select = function (properties) { | ||
select(properties) { | ||
this.addCsvQueryParameter("$select", properties, arguments); | ||
return this; | ||
}; | ||
} | ||
/** | ||
@@ -487,6 +456,6 @@ * @public | ||
*/ | ||
GraphRequest.prototype.expand = function (properties) { | ||
expand(properties) { | ||
this.addCsvQueryParameter("$expand", properties, arguments); | ||
return this; | ||
}; | ||
} | ||
/** | ||
@@ -498,6 +467,6 @@ * @public | ||
*/ | ||
GraphRequest.prototype.orderby = function (properties) { | ||
orderby(properties) { | ||
this.addCsvQueryParameter("$orderby", properties, arguments); | ||
return this; | ||
}; | ||
} | ||
/** | ||
@@ -509,6 +478,6 @@ * @public | ||
*/ | ||
GraphRequest.prototype.filter = function (filterStr) { | ||
filter(filterStr) { | ||
this.urlComponents.oDataQueryParams.$filter = filterStr; | ||
return this; | ||
}; | ||
} | ||
/** | ||
@@ -520,6 +489,6 @@ * @public | ||
*/ | ||
GraphRequest.prototype.search = function (searchStr) { | ||
search(searchStr) { | ||
this.urlComponents.oDataQueryParams.$search = searchStr; | ||
return this; | ||
}; | ||
} | ||
/** | ||
@@ -531,6 +500,6 @@ * @public | ||
*/ | ||
GraphRequest.prototype.top = function (n) { | ||
top(n) { | ||
this.urlComponents.oDataQueryParams.$top = n; | ||
return this; | ||
}; | ||
} | ||
/** | ||
@@ -542,6 +511,6 @@ * @public | ||
*/ | ||
GraphRequest.prototype.skip = function (n) { | ||
skip(n) { | ||
this.urlComponents.oDataQueryParams.$skip = n; | ||
return this; | ||
}; | ||
} | ||
/** | ||
@@ -553,6 +522,6 @@ * @public | ||
*/ | ||
GraphRequest.prototype.skipToken = function (token) { | ||
skipToken(token) { | ||
this.urlComponents.oDataQueryParams.$skipToken = token; | ||
return this; | ||
}; | ||
} | ||
/** | ||
@@ -564,7 +533,6 @@ * @public | ||
*/ | ||
GraphRequest.prototype.count = function (isCount) { | ||
if (isCount === void 0) { isCount = true; } | ||
count(isCount = true) { | ||
this.urlComponents.oDataQueryParams.$count = isCount.toString(); | ||
return this; | ||
}; | ||
} | ||
/** | ||
@@ -580,5 +548,5 @@ * @public | ||
*/ | ||
GraphRequest.prototype.query = function (queryDictionaryOrString) { | ||
query(queryDictionaryOrString) { | ||
return this.parseQueryParameter(queryDictionaryOrString); | ||
}; | ||
} | ||
/** | ||
@@ -591,20 +559,12 @@ * @public | ||
*/ | ||
GraphRequest.prototype.get = function (callback) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var url, options, response; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
url = this.buildFullUrl(); | ||
options = { | ||
method: RequestMethod_1.RequestMethod.GET, | ||
}; | ||
return [4 /*yield*/, this.send(url, options, callback)]; | ||
case 1: | ||
response = _a.sent(); | ||
return [2 /*return*/, response]; | ||
} | ||
}); | ||
get(callback) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
const url = this.buildFullUrl(); | ||
const options = { | ||
method: RequestMethod_1.RequestMethod.GET, | ||
}; | ||
const response = yield this.send(url, options, callback); | ||
return response; | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -618,28 +578,21 @@ * @public | ||
*/ | ||
GraphRequest.prototype.post = function (content, callback) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var url, options, className; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
url = this.buildFullUrl(); | ||
options = { | ||
method: RequestMethod_1.RequestMethod.POST, | ||
body: (0, GraphRequestUtil_1.serializeContent)(content), | ||
}; | ||
className = content && content.constructor && content.constructor.name; | ||
if (className === "FormData") { | ||
// Content-Type headers should not be specified in case the of FormData type content | ||
options.headers = {}; | ||
} | ||
else { | ||
this.setHeaderContentType(); | ||
options.headers = this._headers; | ||
} | ||
return [4 /*yield*/, this.send(url, options, callback)]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
post(content, callback) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
const url = this.buildFullUrl(); | ||
const options = { | ||
method: RequestMethod_1.RequestMethod.POST, | ||
body: (0, GraphRequestUtil_1.serializeContent)(content), | ||
}; | ||
const className = content && content.constructor && content.constructor.name; | ||
if (className === "FormData") { | ||
// Content-Type headers should not be specified in case the of FormData type content | ||
options.headers = {}; | ||
} | ||
else { | ||
this.setHeaderContentType(); | ||
options.headers = this._headers; | ||
} | ||
return yield this.send(url, options, callback); | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -653,12 +606,7 @@ * @public | ||
*/ | ||
GraphRequest.prototype.create = function (content, callback) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.post(content, callback)]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
create(content, callback) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return yield this.post(content, callback); | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -672,20 +620,13 @@ * @public | ||
*/ | ||
GraphRequest.prototype.put = function (content, callback) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var url, options; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
url = this.buildFullUrl(); | ||
this.setHeaderContentType(); | ||
options = { | ||
method: RequestMethod_1.RequestMethod.PUT, | ||
body: (0, GraphRequestUtil_1.serializeContent)(content), | ||
}; | ||
return [4 /*yield*/, this.send(url, options, callback)]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
put(content, callback) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
const url = this.buildFullUrl(); | ||
this.setHeaderContentType(); | ||
const options = { | ||
method: RequestMethod_1.RequestMethod.PUT, | ||
body: (0, GraphRequestUtil_1.serializeContent)(content), | ||
}; | ||
return yield this.send(url, options, callback); | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -699,20 +640,13 @@ * @public | ||
*/ | ||
GraphRequest.prototype.patch = function (content, callback) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var url, options; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
url = this.buildFullUrl(); | ||
this.setHeaderContentType(); | ||
options = { | ||
method: RequestMethod_1.RequestMethod.PATCH, | ||
body: (0, GraphRequestUtil_1.serializeContent)(content), | ||
}; | ||
return [4 /*yield*/, this.send(url, options, callback)]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
patch(content, callback) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
const url = this.buildFullUrl(); | ||
this.setHeaderContentType(); | ||
const options = { | ||
method: RequestMethod_1.RequestMethod.PATCH, | ||
body: (0, GraphRequestUtil_1.serializeContent)(content), | ||
}; | ||
return yield this.send(url, options, callback); | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -726,12 +660,7 @@ * @public | ||
*/ | ||
GraphRequest.prototype.update = function (content, callback) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.patch(content, callback)]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
update(content, callback) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return yield this.patch(content, callback); | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -744,18 +673,11 @@ * @public | ||
*/ | ||
GraphRequest.prototype.delete = function (callback) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var url, options; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
url = this.buildFullUrl(); | ||
options = { | ||
method: RequestMethod_1.RequestMethod.DELETE, | ||
}; | ||
return [4 /*yield*/, this.send(url, options, callback)]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
delete(callback) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
const url = this.buildFullUrl(); | ||
const options = { | ||
method: RequestMethod_1.RequestMethod.DELETE, | ||
}; | ||
return yield this.send(url, options, callback); | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -768,12 +690,7 @@ * @public | ||
*/ | ||
GraphRequest.prototype.del = function (callback) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.delete(callback)]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
del(callback) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return yield this.delete(callback); | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -786,19 +703,12 @@ * @public | ||
*/ | ||
GraphRequest.prototype.getStream = function (callback) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var url, options; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
url = this.buildFullUrl(); | ||
options = { | ||
method: RequestMethod_1.RequestMethod.GET, | ||
}; | ||
this.responseType(ResponseType_1.ResponseType.STREAM); | ||
return [4 /*yield*/, this.send(url, options, callback)]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
getStream(callback) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
const url = this.buildFullUrl(); | ||
const options = { | ||
method: RequestMethod_1.RequestMethod.GET, | ||
}; | ||
this.responseType(ResponseType_1.ResponseType.STREAM); | ||
return yield this.send(url, options, callback); | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -812,25 +722,17 @@ * @public | ||
*/ | ||
GraphRequest.prototype.putStream = function (stream, callback) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var url, options; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
url = this.buildFullUrl(); | ||
options = { | ||
method: RequestMethod_1.RequestMethod.PUT, | ||
headers: { | ||
"Content-Type": "application/octet-stream", | ||
}, | ||
body: stream, | ||
}; | ||
return [4 /*yield*/, this.send(url, options, callback)]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
putStream(stream, callback) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
const url = this.buildFullUrl(); | ||
const options = { | ||
method: RequestMethod_1.RequestMethod.PUT, | ||
headers: { | ||
"Content-Type": "application/octet-stream", | ||
}, | ||
body: stream, | ||
}; | ||
return yield this.send(url, options, callback); | ||
}); | ||
}; | ||
return GraphRequest; | ||
}()); | ||
} | ||
} | ||
exports.GraphRequest = GraphRequest; | ||
//# sourceMappingURL=GraphRequest.js.map |
@@ -8,2 +8,6 @@ /** | ||
/** | ||
* @module GraphRequestUtil | ||
*/ | ||
import { BaseBearerTokenAuthenticationProvider } from "@microsoft/kiota-abstractions"; | ||
/** | ||
* To hold list of OData query params | ||
@@ -44,1 +48,7 @@ */ | ||
export declare const isCustomHost: (url: string, customHosts: Set<string>) => boolean; | ||
/** | ||
* | ||
* @param customHosts | ||
* @returns | ||
*/ | ||
export declare const updateAndReturnAllAllowedHosts: (authProvider: BaseBearerTokenAuthenticationProvider, customHosts: Set<string>) => Set<string>; |
@@ -9,9 +9,6 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.isCustomHost = exports.isGraphURL = exports.serializeContent = exports.urlJoin = exports.oDataQueryNames = void 0; | ||
exports.updateAndReturnAllAllowedHosts = exports.isCustomHost = exports.isGraphURL = exports.serializeContent = exports.urlJoin = exports.oDataQueryNames = void 0; | ||
const Constants_1 = require("./Constants"); | ||
const GraphClientError_1 = require("./GraphClientError"); | ||
/** | ||
* @module GraphRequestUtil | ||
*/ | ||
var Constants_1 = require("./Constants"); | ||
var GraphClientError_1 = require("./GraphClientError"); | ||
/** | ||
* To hold list of OData query params | ||
@@ -25,7 +22,7 @@ */ | ||
*/ | ||
var urlJoin = function (urlSegments) { | ||
var removePostSlash = function (s) { return s.replace(/\/+$/, ""); }; | ||
var removePreSlash = function (s) { return s.replace(/^\/+/, ""); }; | ||
var joiner = function (pre, cur) { return [removePostSlash(pre), removePreSlash(cur)].join("/"); }; | ||
var parts = Array.prototype.slice.call(urlSegments); | ||
const urlJoin = (urlSegments) => { | ||
const removePostSlash = (s) => s.replace(/\/+$/, ""); | ||
const removePreSlash = (s) => s.replace(/^\/+/, ""); | ||
const joiner = (pre, cur) => [removePostSlash(pre), removePreSlash(cur)].join("/"); | ||
const parts = Array.prototype.slice.call(urlSegments); | ||
return parts.reduce(joiner); | ||
@@ -46,4 +43,4 @@ }; | ||
*/ | ||
var serializeContent = function (content) { | ||
var className = content && content.constructor && content.constructor.name; | ||
const serializeContent = (content) => { | ||
const className = content && content.constructor && content.constructor.name; | ||
if (className === "Buffer" || className === "Blob" || className === "File" || className === "FormData" || typeof content === "string") { | ||
@@ -74,3 +71,3 @@ return content; | ||
*/ | ||
var isGraphURL = function (url) { | ||
const isGraphURL = (url) => { | ||
return isValidEndpoint(url); | ||
@@ -85,4 +82,4 @@ }; | ||
*/ | ||
var isCustomHost = function (url, customHosts) { | ||
customHosts.forEach(function (host) { return isCustomHostValid(host); }); | ||
const isCustomHost = (url, customHosts) => { | ||
customHosts.forEach((host) => isCustomHostValid(host)); | ||
return isValidEndpoint(url, customHosts); | ||
@@ -97,4 +94,3 @@ }; | ||
*/ | ||
var isValidEndpoint = function (url, allowedHosts) { | ||
if (allowedHosts === void 0) { allowedHosts = Constants_1.GRAPH_URLS; } | ||
const isValidEndpoint = (url, allowedHosts = Constants_1.GRAPH_URLS) => { | ||
// Valid Graph URL pattern - https://graph.microsoft.com/{version}/{resource}?{query-parameters} | ||
@@ -106,5 +102,5 @@ // Valid Graph URL example - https://graph.microsoft.com/v1.0/ | ||
// Find where the host ends | ||
var startofPortNoPos = url.indexOf(":"); | ||
var endOfHostStrPos = url.indexOf("/"); | ||
var hostName = ""; | ||
const startofPortNoPos = url.indexOf(":"); | ||
const endOfHostStrPos = url.indexOf("/"); | ||
let hostName = ""; | ||
if (endOfHostStrPos !== -1) { | ||
@@ -126,3 +122,3 @@ if (startofPortNoPos !== -1 && startofPortNoPos < endOfHostStrPos) { | ||
*/ | ||
var isCustomHostValid = function (host) { | ||
const isCustomHostValid = (host) => { | ||
if (host.indexOf("/") !== -1) { | ||
@@ -132,2 +128,15 @@ throw new GraphClientError_1.GraphClientError("Please add only hosts or hostnames to the CustomHosts config. If the url is `http://example.com:3000/`, host is `example:3000`"); | ||
}; | ||
/** | ||
* | ||
* @param customHosts | ||
* @returns | ||
*/ | ||
const updateAndReturnAllAllowedHosts = (authProvider, customHosts) => { | ||
const hostsValidator = authProvider.accessTokenProvider.getAllowedHostsValidator(); | ||
const allowedHosts = customHosts ? new Set([...customHosts, ...hostsValidator.getAllowedHosts()]) : new Set(hostsValidator.getAllowedHosts()); | ||
const hostSetWithGraphandCustomHosts = customHosts ? new Set([...allowedHosts, ...Constants_1.GRAPH_URLS, ...customHosts]) : new Set([...allowedHosts, ...Constants_1.GRAPH_URLS]); | ||
hostsValidator.setAllowedHosts(hostSetWithGraphandCustomHosts); | ||
return hostSetWithGraphandCustomHosts; | ||
}; | ||
exports.updateAndReturnAllAllowedHosts = updateAndReturnAllAllowedHosts; | ||
//# sourceMappingURL=GraphRequestUtil.js.map |
@@ -10,4 +10,4 @@ "use strict"; | ||
exports.GraphResponseHandler = exports.DocumentType = void 0; | ||
var tslib_1 = require("tslib"); | ||
var ResponseType_1 = require("./ResponseType"); | ||
const tslib_1 = require("tslib"); | ||
const ResponseType_1 = require("./ResponseType"); | ||
/** | ||
@@ -54,5 +54,3 @@ * @enum | ||
*/ | ||
var GraphResponseHandler = /** @class */ (function () { | ||
function GraphResponseHandler() { | ||
} | ||
class GraphResponseHandler { | ||
/** | ||
@@ -66,9 +64,9 @@ * @private | ||
*/ | ||
GraphResponseHandler.parseDocumentResponse = function (rawResponse, type) { | ||
static parseDocumentResponse(rawResponse, type) { | ||
if (typeof DOMParser !== "undefined") { | ||
return new Promise(function (resolve, reject) { | ||
rawResponse.text().then(function (xmlString) { | ||
return new Promise((resolve, reject) => { | ||
rawResponse.text().then((xmlString) => { | ||
try { | ||
var parser = new DOMParser(); | ||
var xmlDoc = parser.parseFromString(xmlString, type); | ||
const parser = new DOMParser(); | ||
const xmlDoc = parser.parseFromString(xmlString, type); | ||
resolve(xmlDoc); | ||
@@ -85,3 +83,3 @@ } | ||
} | ||
}; | ||
} | ||
/** | ||
@@ -96,76 +94,49 @@ * @private | ||
*/ | ||
GraphResponseHandler.convertResponse = function (rawResponse, responseType) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var responseValue, contentType, _a, mimeType; | ||
return (0, tslib_1.__generator)(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
if (rawResponse.status === 204) { | ||
// NO CONTENT | ||
return [2 /*return*/, Promise.resolve()]; | ||
static convertResponse(rawResponse, responseType) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (rawResponse.status === 204) { | ||
// NO CONTENT | ||
return Promise.resolve(); | ||
} | ||
let responseValue; | ||
const contentType = rawResponse.headers.get("Content-type"); | ||
switch (responseType) { | ||
case ResponseType_1.ResponseType.ARRAYBUFFER: | ||
responseValue = yield rawResponse.arrayBuffer(); | ||
break; | ||
case ResponseType_1.ResponseType.BLOB: | ||
responseValue = yield rawResponse.blob(); | ||
break; | ||
case ResponseType_1.ResponseType.DOCUMENT: | ||
responseValue = yield GraphResponseHandler.parseDocumentResponse(rawResponse, DocumentType.TEXT_XML); | ||
break; | ||
case ResponseType_1.ResponseType.JSON: | ||
responseValue = yield rawResponse.json(); | ||
break; | ||
case ResponseType_1.ResponseType.STREAM: | ||
responseValue = yield Promise.resolve(rawResponse.body); | ||
break; | ||
case ResponseType_1.ResponseType.TEXT: | ||
responseValue = yield rawResponse.text(); | ||
break; | ||
default: | ||
if (contentType !== null) { | ||
const mimeType = contentType.split(";")[0]; | ||
if (new RegExp(ContentTypeRegexStr.DOCUMENT).test(mimeType)) { | ||
responseValue = yield GraphResponseHandler.parseDocumentResponse(rawResponse, mimeType); | ||
} | ||
contentType = rawResponse.headers.get("Content-type"); | ||
_a = responseType; | ||
switch (_a) { | ||
case ResponseType_1.ResponseType.ARRAYBUFFER: return [3 /*break*/, 1]; | ||
case ResponseType_1.ResponseType.BLOB: return [3 /*break*/, 3]; | ||
case ResponseType_1.ResponseType.DOCUMENT: return [3 /*break*/, 5]; | ||
case ResponseType_1.ResponseType.JSON: return [3 /*break*/, 7]; | ||
case ResponseType_1.ResponseType.STREAM: return [3 /*break*/, 9]; | ||
case ResponseType_1.ResponseType.TEXT: return [3 /*break*/, 11]; | ||
else if (new RegExp(ContentTypeRegexStr.IMAGE).test(mimeType)) { | ||
responseValue = rawResponse.blob(); | ||
} | ||
return [3 /*break*/, 13]; | ||
case 1: return [4 /*yield*/, rawResponse.arrayBuffer()]; | ||
case 2: | ||
responseValue = _b.sent(); | ||
return [3 /*break*/, 24]; | ||
case 3: return [4 /*yield*/, rawResponse.blob()]; | ||
case 4: | ||
responseValue = _b.sent(); | ||
return [3 /*break*/, 24]; | ||
case 5: return [4 /*yield*/, GraphResponseHandler.parseDocumentResponse(rawResponse, DocumentType.TEXT_XML)]; | ||
case 6: | ||
responseValue = _b.sent(); | ||
return [3 /*break*/, 24]; | ||
case 7: return [4 /*yield*/, rawResponse.json()]; | ||
case 8: | ||
responseValue = _b.sent(); | ||
return [3 /*break*/, 24]; | ||
case 9: return [4 /*yield*/, Promise.resolve(rawResponse.body)]; | ||
case 10: | ||
responseValue = _b.sent(); | ||
return [3 /*break*/, 24]; | ||
case 11: return [4 /*yield*/, rawResponse.text()]; | ||
case 12: | ||
responseValue = _b.sent(); | ||
return [3 /*break*/, 24]; | ||
case 13: | ||
if (!(contentType !== null)) return [3 /*break*/, 22]; | ||
mimeType = contentType.split(";")[0]; | ||
if (!new RegExp(ContentTypeRegexStr.DOCUMENT).test(mimeType)) return [3 /*break*/, 15]; | ||
return [4 /*yield*/, GraphResponseHandler.parseDocumentResponse(rawResponse, mimeType)]; | ||
case 14: | ||
responseValue = _b.sent(); | ||
return [3 /*break*/, 21]; | ||
case 15: | ||
if (!new RegExp(ContentTypeRegexStr.IMAGE).test(mimeType)) return [3 /*break*/, 16]; | ||
responseValue = rawResponse.blob(); | ||
return [3 /*break*/, 21]; | ||
case 16: | ||
if (!(mimeType === ContentType.TEXT_PLAIN)) return [3 /*break*/, 18]; | ||
return [4 /*yield*/, rawResponse.text()]; | ||
case 17: | ||
responseValue = _b.sent(); | ||
return [3 /*break*/, 21]; | ||
case 18: | ||
if (!(mimeType === ContentType.APPLICATION_JSON)) return [3 /*break*/, 20]; | ||
return [4 /*yield*/, rawResponse.json()]; | ||
case 19: | ||
responseValue = _b.sent(); | ||
return [3 /*break*/, 21]; | ||
case 20: | ||
responseValue = Promise.resolve(rawResponse.body); | ||
_b.label = 21; | ||
case 21: return [3 /*break*/, 23]; | ||
case 22: | ||
else if (mimeType === ContentType.TEXT_PLAIN) { | ||
responseValue = yield rawResponse.text(); | ||
} | ||
else if (mimeType === ContentType.APPLICATION_JSON) { | ||
responseValue = yield rawResponse.json(); | ||
} | ||
else { | ||
responseValue = Promise.resolve(rawResponse.body); | ||
} | ||
} | ||
else { | ||
/** | ||
@@ -183,9 +154,8 @@ * RFC specification {@link https://tools.ietf.org/html/rfc7231#section-3.1.1.5} says: | ||
responseValue = Promise.resolve(rawResponse.body); | ||
_b.label = 23; | ||
case 23: return [3 /*break*/, 24]; | ||
case 24: return [2 /*return*/, responseValue]; | ||
} | ||
}); | ||
} | ||
break; | ||
} | ||
return responseValue; | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -201,35 +171,27 @@ * @public | ||
*/ | ||
GraphResponseHandler.getResponse = function (rawResponse, responseType, callback) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var response; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!(responseType === ResponseType_1.ResponseType.RAW)) return [3 /*break*/, 1]; | ||
return [2 /*return*/, Promise.resolve(rawResponse)]; | ||
case 1: return [4 /*yield*/, GraphResponseHandler.convertResponse(rawResponse, responseType)]; | ||
case 2: | ||
response = _a.sent(); | ||
if (rawResponse.ok) { | ||
// Status Code 2XX | ||
if (typeof callback === "function") { | ||
callback(null, response); | ||
} | ||
else { | ||
return [2 /*return*/, response]; | ||
} | ||
} | ||
else { | ||
// NOT OK Response | ||
throw response; | ||
} | ||
_a.label = 3; | ||
case 3: return [2 /*return*/]; | ||
static getResponse(rawResponse, responseType, callback) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (responseType === ResponseType_1.ResponseType.RAW) { | ||
return Promise.resolve(rawResponse); | ||
} | ||
else { | ||
const response = yield GraphResponseHandler.convertResponse(rawResponse, responseType); | ||
if (rawResponse.ok) { | ||
// Status Code 2XX | ||
if (typeof callback === "function") { | ||
callback(null, response); | ||
} | ||
else { | ||
return response; | ||
} | ||
} | ||
}); | ||
else { | ||
// NOT OK Response | ||
throw response; | ||
} | ||
} | ||
}); | ||
}; | ||
return GraphResponseHandler; | ||
}()); | ||
} | ||
} | ||
exports.GraphResponseHandler = GraphResponseHandler; | ||
//# sourceMappingURL=GraphResponseHandler.js.map |
@@ -7,5 +7,5 @@ /** | ||
*/ | ||
import { AuthenticationProvider } from "./IAuthenticationProvider"; | ||
import { BaseBearerTokenAuthenticationProvider } from "@microsoft/kiota-abstractions"; | ||
import { Middleware } from "@microsoft/kiota-http-fetchlibrary"; | ||
import { FetchOptions } from "./IFetchOptions"; | ||
import { Middleware } from "./middleware/IMiddleware"; | ||
/** | ||
@@ -23,3 +23,3 @@ * @interface | ||
export interface ClientOptions { | ||
authProvider?: AuthenticationProvider; | ||
authProvider?: BaseBearerTokenAuthenticationProvider; | ||
baseUrl?: string; | ||
@@ -30,2 +30,3 @@ debugLogging?: boolean; | ||
middleware?: Middleware | Middleware[]; | ||
customFetch?: (input: string, init?: RequestInit) => Promise<Response>; | ||
/** | ||
@@ -32,0 +33,0 @@ * Example - If URL is "https://test_host/v1.0", then set property "customHosts" as "customHosts: Set<string>(["test_host"])" |
@@ -0,1 +1,2 @@ | ||
/// <reference path="../../shims.d.ts" /> | ||
/** | ||
@@ -7,17 +8,8 @@ * ------------------------------------------------------------------------------------------- | ||
*/ | ||
/// <reference path="../../shims.d.ts" /> | ||
export { BaseBearerTokenAuthenticationProvider, AccessTokenProvider, RequestOption } from "@microsoft/kiota-abstractions"; | ||
export { RetryHandler, RedirectHandler, TelemetryHandler, RedirectHandlerOptionKey, RetryHandlerOptions, HttpClient, RedirectHandlerOptions, TelemetryHandlerOptions, TelemetryHandlerOptionsKey, RetryHandlerOptionKey } from "@microsoft/kiota-http-fetchlibrary"; | ||
export { BatchRequestBody, RequestData, BatchRequestContent, BatchRequestData, BatchRequestStep } from "./content/BatchRequestContent"; | ||
export { BatchResponseBody, BatchResponseContent } from "./content/BatchResponseContent"; | ||
export { AuthenticationHandler } from "./middleware/AuthenticationHandler"; | ||
export { HTTPMessageHandler } from "./middleware/HTTPMessageHandler"; | ||
export { Middleware } from "./middleware/IMiddleware"; | ||
export { RetryHandler } from "./middleware/RetryHandler"; | ||
export { RedirectHandler } from "./middleware/RedirectHandler"; | ||
export { TelemetryHandler } from "./middleware/TelemetryHandler"; | ||
export { MiddlewareFactory } from "./middleware/MiddlewareFactory"; | ||
export { AuthenticationHandlerOptions } from "./middleware/options/AuthenticationHandlerOptions"; | ||
export { MiddlewareOptions } from "./middleware/options/IMiddlewareOptions"; | ||
export { RetryHandlerOptions, ShouldRetry } from "./middleware/options/RetryHandlerOptions"; | ||
export { RedirectHandlerOptions, ShouldRedirect } from "./middleware/options/RedirectHandlerOptions"; | ||
export { FeatureUsageFlag, TelemetryHandlerOptions } from "./middleware/options/TelemetryHandlerOptions"; | ||
export { FeatureUsageFlag } from "./middleware/Telemetry/TelemetryFeatureUsageFlag"; | ||
export { ChaosHandlerOptions } from "./middleware/options/ChaosHandlerOptions"; | ||
@@ -36,15 +28,17 @@ export { ChaosStrategy } from "./middleware/options/ChaosStrategy"; | ||
export { Client } from "./Client"; | ||
export { CustomAuthenticationProvider } from "./CustomAuthenticationProvider"; | ||
export { GraphError } from "./GraphError"; | ||
export { GraphClientError } from "./GraphClientError"; | ||
export { GraphRequest, URLComponents } from "./GraphRequest"; | ||
export { AuthProvider } from "./IAuthProvider"; | ||
export { AuthenticationProvider } from "./IAuthenticationProvider"; | ||
export { AuthenticationProviderOptions } from "./IAuthenticationProviderOptions"; | ||
export { AuthProviderCallback } from "./IAuthProviderCallback"; | ||
export { ClientOptions } from "./IClientOptions"; | ||
export { Context } from "./IContext"; | ||
export { FetchOptions, NodeFetchInit } from "./IFetchOptions"; | ||
export { GraphRequestCallback } from "./IGraphRequestCallback"; | ||
export { Options } from "./IOptions"; | ||
export { ResponseType } from "./ResponseType"; | ||
export { SimpleAuthenticationProvider } from "./authentication/SimpleAuthentication/SimpleAuthenticationProvider"; | ||
export { SimpleAccessTokenProvider } from "./authentication/SimpleAuthentication/SimpleAccessTokenProvider"; | ||
export { GraphBaseClient } from "./requestBuilderUtils/GraphBaseClient"; | ||
export { GraphSDKConfig } from "./requestBuilderUtils/GraphSDKConfig"; | ||
export { coreSdkVersionValue, getGraphTelemetryCallback, CORE_PRODUCT_NAME, graphTelemetryCallback } from "./middleware/Telemetry/TelemetryUtil"; | ||
export { GraphTelemetryConfig } from "./middleware/Telemetry/GraphTelemetryConfig"; | ||
export { getDefaultMiddlewareChain } from "./MiddlewareFactory"; | ||
export { GRAPH_API_VERSION, GRAPH_BASE_URL, GRAPH_URLS } from "./Constants"; | ||
export { isCustomHost, isGraphURL, updateAndReturnAllAllowedHosts } from "./GraphRequestUtil"; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.updateAndReturnAllAllowedHosts = exports.isGraphURL = exports.isCustomHost = exports.GRAPH_URLS = exports.GRAPH_BASE_URL = exports.GRAPH_API_VERSION = exports.getDefaultMiddlewareChain = exports.graphTelemetryCallback = exports.CORE_PRODUCT_NAME = exports.getGraphTelemetryCallback = exports.coreSdkVersionValue = exports.SimpleAccessTokenProvider = exports.SimpleAuthenticationProvider = exports.ResponseType = exports.GraphRequest = exports.GraphClientError = exports.GraphError = exports.Client = exports.PageIterator = exports.Range = exports.UploadResult = exports.FileUpload = exports.StreamUpload = exports.getValidRangeSize = exports.OneDriveLargeFileUploadTask = exports.LargeFileUploadTask = exports.ChaosHandler = exports.ChaosStrategy = exports.ChaosHandlerOptions = exports.FeatureUsageFlag = exports.BatchResponseContent = exports.BatchRequestContent = exports.RetryHandlerOptionKey = exports.TelemetryHandlerOptionsKey = exports.RedirectHandlerOptions = exports.HttpClient = exports.RetryHandlerOptions = exports.RedirectHandlerOptionKey = exports.TelemetryHandler = exports.RedirectHandler = exports.RetryHandler = exports.BaseBearerTokenAuthenticationProvider = void 0; | ||
/** | ||
@@ -8,6 +10,16 @@ * ------------------------------------------------------------------------------------------- | ||
*/ | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.ResponseType = exports.GraphRequest = exports.GraphClientError = exports.GraphError = exports.CustomAuthenticationProvider = exports.Client = exports.PageIterator = exports.Range = exports.UploadResult = exports.FileUpload = exports.StreamUpload = exports.getValidRangeSize = exports.OneDriveLargeFileUploadTask = exports.LargeFileUploadTask = exports.ChaosHandler = exports.ChaosStrategy = exports.ChaosHandlerOptions = exports.TelemetryHandlerOptions = exports.FeatureUsageFlag = exports.RedirectHandlerOptions = exports.RetryHandlerOptions = exports.AuthenticationHandlerOptions = exports.MiddlewareFactory = exports.TelemetryHandler = exports.RedirectHandler = exports.RetryHandler = exports.HTTPMessageHandler = exports.AuthenticationHandler = exports.BatchResponseContent = exports.BatchRequestContent = void 0; | ||
// eslint-disable-next-line @typescript-eslint/triple-slash-reference | ||
/// <reference path= "./../shims.d.ts" /> | ||
var kiota_abstractions_1 = require("@microsoft/kiota-abstractions"); | ||
Object.defineProperty(exports, "BaseBearerTokenAuthenticationProvider", { enumerable: true, get: function () { return kiota_abstractions_1.BaseBearerTokenAuthenticationProvider; } }); | ||
var kiota_http_fetchlibrary_1 = require("@microsoft/kiota-http-fetchlibrary"); | ||
Object.defineProperty(exports, "RetryHandler", { enumerable: true, get: function () { return kiota_http_fetchlibrary_1.RetryHandler; } }); | ||
Object.defineProperty(exports, "RedirectHandler", { enumerable: true, get: function () { return kiota_http_fetchlibrary_1.RedirectHandler; } }); | ||
Object.defineProperty(exports, "TelemetryHandler", { enumerable: true, get: function () { return kiota_http_fetchlibrary_1.TelemetryHandler; } }); | ||
Object.defineProperty(exports, "RedirectHandlerOptionKey", { enumerable: true, get: function () { return kiota_http_fetchlibrary_1.RedirectHandlerOptionKey; } }); | ||
Object.defineProperty(exports, "RetryHandlerOptions", { enumerable: true, get: function () { return kiota_http_fetchlibrary_1.RetryHandlerOptions; } }); | ||
Object.defineProperty(exports, "HttpClient", { enumerable: true, get: function () { return kiota_http_fetchlibrary_1.HttpClient; } }); | ||
Object.defineProperty(exports, "RedirectHandlerOptions", { enumerable: true, get: function () { return kiota_http_fetchlibrary_1.RedirectHandlerOptions; } }); | ||
Object.defineProperty(exports, "TelemetryHandlerOptionsKey", { enumerable: true, get: function () { return kiota_http_fetchlibrary_1.TelemetryHandlerOptionsKey; } }); | ||
Object.defineProperty(exports, "RetryHandlerOptionKey", { enumerable: true, get: function () { return kiota_http_fetchlibrary_1.RetryHandlerOptionKey; } }); | ||
var BatchRequestContent_1 = require("./content/BatchRequestContent"); | ||
@@ -17,23 +29,4 @@ Object.defineProperty(exports, "BatchRequestContent", { enumerable: true, get: function () { return BatchRequestContent_1.BatchRequestContent; } }); | ||
Object.defineProperty(exports, "BatchResponseContent", { enumerable: true, get: function () { return BatchResponseContent_1.BatchResponseContent; } }); | ||
var AuthenticationHandler_1 = require("./middleware/AuthenticationHandler"); | ||
Object.defineProperty(exports, "AuthenticationHandler", { enumerable: true, get: function () { return AuthenticationHandler_1.AuthenticationHandler; } }); | ||
var HTTPMessageHandler_1 = require("./middleware/HTTPMessageHandler"); | ||
Object.defineProperty(exports, "HTTPMessageHandler", { enumerable: true, get: function () { return HTTPMessageHandler_1.HTTPMessageHandler; } }); | ||
var RetryHandler_1 = require("./middleware/RetryHandler"); | ||
Object.defineProperty(exports, "RetryHandler", { enumerable: true, get: function () { return RetryHandler_1.RetryHandler; } }); | ||
var RedirectHandler_1 = require("./middleware/RedirectHandler"); | ||
Object.defineProperty(exports, "RedirectHandler", { enumerable: true, get: function () { return RedirectHandler_1.RedirectHandler; } }); | ||
var TelemetryHandler_1 = require("./middleware/TelemetryHandler"); | ||
Object.defineProperty(exports, "TelemetryHandler", { enumerable: true, get: function () { return TelemetryHandler_1.TelemetryHandler; } }); | ||
var MiddlewareFactory_1 = require("./middleware/MiddlewareFactory"); | ||
Object.defineProperty(exports, "MiddlewareFactory", { enumerable: true, get: function () { return MiddlewareFactory_1.MiddlewareFactory; } }); | ||
var AuthenticationHandlerOptions_1 = require("./middleware/options/AuthenticationHandlerOptions"); | ||
Object.defineProperty(exports, "AuthenticationHandlerOptions", { enumerable: true, get: function () { return AuthenticationHandlerOptions_1.AuthenticationHandlerOptions; } }); | ||
var RetryHandlerOptions_1 = require("./middleware/options/RetryHandlerOptions"); | ||
Object.defineProperty(exports, "RetryHandlerOptions", { enumerable: true, get: function () { return RetryHandlerOptions_1.RetryHandlerOptions; } }); | ||
var RedirectHandlerOptions_1 = require("./middleware/options/RedirectHandlerOptions"); | ||
Object.defineProperty(exports, "RedirectHandlerOptions", { enumerable: true, get: function () { return RedirectHandlerOptions_1.RedirectHandlerOptions; } }); | ||
var TelemetryHandlerOptions_1 = require("./middleware/options/TelemetryHandlerOptions"); | ||
Object.defineProperty(exports, "FeatureUsageFlag", { enumerable: true, get: function () { return TelemetryHandlerOptions_1.FeatureUsageFlag; } }); | ||
Object.defineProperty(exports, "TelemetryHandlerOptions", { enumerable: true, get: function () { return TelemetryHandlerOptions_1.TelemetryHandlerOptions; } }); | ||
var TelemetryFeatureUsageFlag_1 = require("./middleware/Telemetry/TelemetryFeatureUsageFlag"); | ||
Object.defineProperty(exports, "FeatureUsageFlag", { enumerable: true, get: function () { return TelemetryFeatureUsageFlag_1.FeatureUsageFlag; } }); | ||
var ChaosHandlerOptions_1 = require("./middleware/options/ChaosHandlerOptions"); | ||
@@ -63,4 +56,2 @@ Object.defineProperty(exports, "ChaosHandlerOptions", { enumerable: true, get: function () { return ChaosHandlerOptions_1.ChaosHandlerOptions; } }); | ||
Object.defineProperty(exports, "Client", { enumerable: true, get: function () { return Client_1.Client; } }); | ||
var CustomAuthenticationProvider_1 = require("./CustomAuthenticationProvider"); | ||
Object.defineProperty(exports, "CustomAuthenticationProvider", { enumerable: true, get: function () { return CustomAuthenticationProvider_1.CustomAuthenticationProvider; } }); | ||
var GraphError_1 = require("./GraphError"); | ||
@@ -74,2 +65,21 @@ Object.defineProperty(exports, "GraphError", { enumerable: true, get: function () { return GraphError_1.GraphError; } }); | ||
Object.defineProperty(exports, "ResponseType", { enumerable: true, get: function () { return ResponseType_1.ResponseType; } }); | ||
var SimpleAuthenticationProvider_1 = require("./authentication/SimpleAuthentication/SimpleAuthenticationProvider"); | ||
Object.defineProperty(exports, "SimpleAuthenticationProvider", { enumerable: true, get: function () { return SimpleAuthenticationProvider_1.SimpleAuthenticationProvider; } }); | ||
var SimpleAccessTokenProvider_1 = require("./authentication/SimpleAuthentication/SimpleAccessTokenProvider"); | ||
Object.defineProperty(exports, "SimpleAccessTokenProvider", { enumerable: true, get: function () { return SimpleAccessTokenProvider_1.SimpleAccessTokenProvider; } }); | ||
var TelemetryUtil_1 = require("./middleware/Telemetry/TelemetryUtil"); | ||
Object.defineProperty(exports, "coreSdkVersionValue", { enumerable: true, get: function () { return TelemetryUtil_1.coreSdkVersionValue; } }); | ||
Object.defineProperty(exports, "getGraphTelemetryCallback", { enumerable: true, get: function () { return TelemetryUtil_1.getGraphTelemetryCallback; } }); | ||
Object.defineProperty(exports, "CORE_PRODUCT_NAME", { enumerable: true, get: function () { return TelemetryUtil_1.CORE_PRODUCT_NAME; } }); | ||
Object.defineProperty(exports, "graphTelemetryCallback", { enumerable: true, get: function () { return TelemetryUtil_1.graphTelemetryCallback; } }); | ||
var MiddlewareFactory_1 = require("./MiddlewareFactory"); | ||
Object.defineProperty(exports, "getDefaultMiddlewareChain", { enumerable: true, get: function () { return MiddlewareFactory_1.getDefaultMiddlewareChain; } }); | ||
var Constants_1 = require("./Constants"); | ||
Object.defineProperty(exports, "GRAPH_API_VERSION", { enumerable: true, get: function () { return Constants_1.GRAPH_API_VERSION; } }); | ||
Object.defineProperty(exports, "GRAPH_BASE_URL", { enumerable: true, get: function () { return Constants_1.GRAPH_BASE_URL; } }); | ||
Object.defineProperty(exports, "GRAPH_URLS", { enumerable: true, get: function () { return Constants_1.GRAPH_URLS; } }); | ||
var GraphRequestUtil_1 = require("./GraphRequestUtil"); | ||
Object.defineProperty(exports, "isCustomHost", { enumerable: true, get: function () { return GraphRequestUtil_1.isCustomHost; } }); | ||
Object.defineProperty(exports, "isGraphURL", { enumerable: true, get: function () { return GraphRequestUtil_1.isGraphURL; } }); | ||
Object.defineProperty(exports, "updateAndReturnAllAllowedHosts", { enumerable: true, get: function () { return GraphRequestUtil_1.updateAndReturnAllAllowedHosts; } }); | ||
//# sourceMappingURL=index.js.map |
@@ -7,6 +7,8 @@ /** | ||
*/ | ||
import { AuthenticationProvider } from "../IAuthenticationProvider"; | ||
import { Context } from "../IContext"; | ||
import { Middleware } from "./IMiddleware"; | ||
/** | ||
* @module AuthenticationHandler | ||
*/ | ||
import { BaseBearerTokenAuthenticationProvider, RequestOption } from "@microsoft/kiota-abstractions"; | ||
import { Middleware } from "@microsoft/kiota-http-fetchlibrary"; | ||
/** | ||
* @class | ||
@@ -17,2 +19,3 @@ * @implements Middleware | ||
export declare class AuthenticationHandler implements Middleware { | ||
private authenticationProvider; | ||
/** | ||
@@ -25,10 +28,5 @@ * @private | ||
* @private | ||
* A member to hold an AuthenticationProvider instance | ||
*/ | ||
private authenticationProvider; | ||
/** | ||
* @private | ||
* A member to hold next middleware in the middleware chain | ||
*/ | ||
private nextMiddleware; | ||
next: Middleware; | ||
/** | ||
@@ -40,3 +38,3 @@ * @public | ||
*/ | ||
constructor(authenticationProvider: AuthenticationProvider); | ||
constructor(authenticationProvider: BaseBearerTokenAuthenticationProvider); | ||
/** | ||
@@ -49,10 +47,3 @@ * @public | ||
*/ | ||
execute(context: Context): Promise<void>; | ||
/** | ||
* @public | ||
* To set the next middleware in the chain | ||
* @param {Middleware} next - The middleware instance | ||
* @returns Nothing | ||
*/ | ||
setNext(next: Middleware): void; | ||
execute(url: string, requestInit: RequestInit, requestOptions?: Record<string, RequestOption>): Promise<Response>; | ||
} |
@@ -10,12 +10,5 @@ "use strict"; | ||
exports.AuthenticationHandler = void 0; | ||
var tslib_1 = require("tslib"); | ||
const tslib_1 = require("tslib"); | ||
const kiota_http_fetchlibrary_1 = require("@microsoft/kiota-http-fetchlibrary"); | ||
/** | ||
* @module AuthenticationHandler | ||
*/ | ||
var GraphRequestUtil_1 = require("../GraphRequestUtil"); | ||
var MiddlewareControl_1 = require("./MiddlewareControl"); | ||
var MiddlewareUtil_1 = require("./MiddlewareUtil"); | ||
var AuthenticationHandlerOptions_1 = require("./options/AuthenticationHandlerOptions"); | ||
var TelemetryHandlerOptions_1 = require("./options/TelemetryHandlerOptions"); | ||
/** | ||
* @class | ||
@@ -25,3 +18,3 @@ * @implements Middleware | ||
*/ | ||
var AuthenticationHandler = /** @class */ (function () { | ||
class AuthenticationHandler { | ||
/** | ||
@@ -33,3 +26,3 @@ * @public | ||
*/ | ||
function AuthenticationHandler(authenticationProvider) { | ||
constructor(authenticationProvider) { | ||
this.authenticationProvider = authenticationProvider; | ||
@@ -44,58 +37,28 @@ } | ||
*/ | ||
AuthenticationHandler.prototype.execute = function (context) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var url, options, authenticationProvider, authenticationProviderOptions, token, bearerKey; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
url = typeof context.request === "string" ? context.request : context.request.url; | ||
if (!((0, GraphRequestUtil_1.isGraphURL)(url) || (context.customHosts && (0, GraphRequestUtil_1.isCustomHost)(url, context.customHosts)))) return [3 /*break*/, 2]; | ||
options = void 0; | ||
if (context.middlewareControl instanceof MiddlewareControl_1.MiddlewareControl) { | ||
options = context.middlewareControl.getMiddlewareOptions(AuthenticationHandlerOptions_1.AuthenticationHandlerOptions); | ||
} | ||
authenticationProvider = void 0; | ||
authenticationProviderOptions = void 0; | ||
if (options) { | ||
authenticationProvider = options.authenticationProvider; | ||
authenticationProviderOptions = options.authenticationProviderOptions; | ||
} | ||
if (!authenticationProvider) { | ||
authenticationProvider = this.authenticationProvider; | ||
} | ||
return [4 /*yield*/, authenticationProvider.getAccessToken(authenticationProviderOptions)]; | ||
case 1: | ||
token = _a.sent(); | ||
bearerKey = "Bearer ".concat(token); | ||
(0, MiddlewareUtil_1.appendRequestHeader)(context.request, context.options, AuthenticationHandler.AUTHORIZATION_HEADER, bearerKey); | ||
TelemetryHandlerOptions_1.TelemetryHandlerOptions.updateFeatureUsageFlag(context, TelemetryHandlerOptions_1.FeatureUsageFlag.AUTHENTICATION_HANDLER_ENABLED); | ||
return [3 /*break*/, 3]; | ||
case 2: | ||
if (context.options.headers) { | ||
delete context.options.headers[AuthenticationHandler.AUTHORIZATION_HEADER]; | ||
} | ||
_a.label = 3; | ||
case 3: return [4 /*yield*/, this.nextMiddleware.execute(context)]; | ||
case 4: return [2 /*return*/, _a.sent()]; | ||
execute(url, requestInit, requestOptions) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (this.authenticationProvider.accessTokenProvider.getAllowedHostsValidator().isUrlHostValid(url)) { | ||
if ((requestInit === null || requestInit === void 0 ? void 0 : requestInit.headers) && !requestInit.headers[AuthenticationHandler.AUTHORIZATION_HEADER]) { | ||
const token = yield this.authenticationProvider.accessTokenProvider.getAuthorizationToken(url); | ||
const bearerKey = `Bearer ${token}`; | ||
(0, kiota_http_fetchlibrary_1.appendRequestHeader)(requestInit, AuthenticationHandler.AUTHORIZATION_HEADER, bearerKey); | ||
} | ||
}); | ||
} | ||
else { | ||
/** | ||
* deleting auth headers because the tasks such as LargeFileUpload use client.api() to upload to redirected url | ||
* delete the auth header and allow the request to go through with the rest of the middleware chain | ||
**/ | ||
delete requestInit.headers[AuthenticationHandler.AUTHORIZATION_HEADER]; | ||
} | ||
return yield this.next.execute(url, requestInit, requestOptions); | ||
}); | ||
}; | ||
/** | ||
* @public | ||
* To set the next middleware in the chain | ||
* @param {Middleware} next - The middleware instance | ||
* @returns Nothing | ||
*/ | ||
AuthenticationHandler.prototype.setNext = function (next) { | ||
this.nextMiddleware = next; | ||
}; | ||
/** | ||
* @private | ||
* A member representing the authorization header name | ||
*/ | ||
AuthenticationHandler.AUTHORIZATION_HEADER = "Authorization"; | ||
return AuthenticationHandler; | ||
}()); | ||
} | ||
} | ||
exports.AuthenticationHandler = AuthenticationHandler; | ||
/** | ||
* @private | ||
* A member representing the authorization header name | ||
*/ | ||
AuthenticationHandler.AUTHORIZATION_HEADER = "Authorization"; | ||
//# sourceMappingURL=AuthenticationHandler.js.map |
@@ -10,5 +10,6 @@ /** | ||
*/ | ||
import { Context } from "../IContext"; | ||
import { Middleware } from "./IMiddleware"; | ||
import { RequestOption } from "@microsoft/kiota-abstractions"; | ||
import { Middleware } from "@microsoft/kiota-http-fetchlibrary"; | ||
import { ChaosHandlerOptions } from "./options/ChaosHandlerOptions"; | ||
export declare const ChaosHandlerOptionKey = "ChaosHandlerOptionKey"; | ||
/** | ||
@@ -21,20 +22,6 @@ * Class representing ChaosHandler | ||
export declare class ChaosHandler implements Middleware { | ||
private chaosHandlerOptions; | ||
private manualMap?; | ||
next: Middleware | undefined; | ||
/** | ||
* A member holding options to customize the handler behavior | ||
* | ||
* @private | ||
*/ | ||
private options; | ||
/** | ||
* container for the manual map that has been written by the client | ||
* | ||
* @private | ||
*/ | ||
private manualMap; | ||
/** | ||
* @private | ||
* A member to hold next middleware in the middleware chain | ||
*/ | ||
private nextMiddleware; | ||
/** | ||
* @public | ||
@@ -47,3 +34,4 @@ * @constructor | ||
*/ | ||
constructor(options?: ChaosHandlerOptions, manualMap?: Map<string, Map<string, number>>); | ||
constructor(chaosHandlerOptions?: ChaosHandlerOptions, manualMap?: Map<string, Map<string, number>>); | ||
execute(url: string, requestInit: RequestInit, requestOptions?: Record<string, RequestOption>): Promise<Response>; | ||
/** | ||
@@ -105,18 +93,3 @@ * Generates responseHeader | ||
/** | ||
* To get the options for execution of the middleware | ||
* @private | ||
* @param {Context} context - The context object | ||
* @returns options for middleware execution | ||
*/ | ||
private getOptions; | ||
/** | ||
* To execute the current middleware | ||
* @public | ||
* @async | ||
* @param {Context} context - The context object of the request | ||
* @returns A Promise that resolves to nothing | ||
*/ | ||
execute(context: Context): Promise<void>; | ||
/** | ||
* @public | ||
* To set the next middleware in the chain | ||
@@ -123,0 +96,0 @@ * @param {Middleware} next - The middleware instance |
@@ -9,9 +9,9 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.ChaosHandler = void 0; | ||
var tslib_1 = require("tslib"); | ||
var MiddlewareControl_1 = require("./MiddlewareControl"); | ||
var MiddlewareUtil_1 = require("./MiddlewareUtil"); | ||
var ChaosHandlerData_1 = require("./options/ChaosHandlerData"); | ||
var ChaosHandlerOptions_1 = require("./options/ChaosHandlerOptions"); | ||
var ChaosStrategy_1 = require("./options/ChaosStrategy"); | ||
exports.ChaosHandler = exports.ChaosHandlerOptionKey = void 0; | ||
const tslib_1 = require("tslib"); | ||
const MiddlewareUtil_1 = require("./MiddlewareUtil"); | ||
const ChaosHandlerData_1 = require("./options/ChaosHandlerData"); | ||
const ChaosHandlerOptions_1 = require("./options/ChaosHandlerOptions"); | ||
const ChaosStrategy_1 = require("./options/ChaosStrategy"); | ||
exports.ChaosHandlerOptionKey = "ChaosHandlerOptionKey"; | ||
/** | ||
@@ -23,3 +23,3 @@ * Class representing ChaosHandler | ||
*/ | ||
var ChaosHandler = /** @class */ (function () { | ||
class ChaosHandler { | ||
/** | ||
@@ -33,7 +33,12 @@ * @public | ||
*/ | ||
function ChaosHandler(options, manualMap) { | ||
if (options === void 0) { options = new ChaosHandlerOptions_1.ChaosHandlerOptions(); } | ||
this.options = options; | ||
constructor(chaosHandlerOptions = new ChaosHandlerOptions_1.ChaosHandlerOptions(), manualMap) { | ||
this.chaosHandlerOptions = chaosHandlerOptions; | ||
this.manualMap = manualMap; | ||
} | ||
execute(url, requestInit, requestOptions) { | ||
if (requestOptions && requestOptions[exports.ChaosHandlerOptionKey]) { | ||
this.chaosHandlerOptions = requestOptions[exports.ChaosHandlerOptionKey]; | ||
} | ||
return this.sendRequest(url, requestInit, requestOptions); | ||
} | ||
/** | ||
@@ -47,4 +52,4 @@ * Generates responseHeader | ||
*/ | ||
ChaosHandler.prototype.createResponseHeaders = function (chaosHandlerOptions, requestID, requestDate) { | ||
var responseHeader = chaosHandlerOptions.headers ? new Headers(chaosHandlerOptions.headers) : new Headers(); | ||
createResponseHeaders(requestID, requestDate) { | ||
const responseHeader = this.chaosHandlerOptions.headers ? new Headers(this.chaosHandlerOptions.headers) : new Headers(); | ||
responseHeader.append("Cache-Control", "no-store"); | ||
@@ -56,3 +61,3 @@ responseHeader.append("request-id", requestID); | ||
responseHeader.append("Strict-Transport-Security", ""); | ||
if (chaosHandlerOptions.statusCode === 429) { | ||
if (this.chaosHandlerOptions.statusCode === 429) { | ||
// throttling case has to have a timeout scenario | ||
@@ -62,3 +67,3 @@ responseHeader.append("retry-after", "3"); | ||
return responseHeader; | ||
}; | ||
} | ||
/** | ||
@@ -72,10 +77,10 @@ * Generates responseBody | ||
*/ | ||
ChaosHandler.prototype.createResponseBody = function (chaosHandlerOptions, requestID, requestDate) { | ||
if (chaosHandlerOptions.responseBody) { | ||
return chaosHandlerOptions.responseBody; | ||
createResponseBody(requestID, requestDate) { | ||
if (this.chaosHandlerOptions.responseBody) { | ||
return this.chaosHandlerOptions.responseBody; | ||
} | ||
var body; | ||
if (chaosHandlerOptions.statusCode >= 400) { | ||
var codeMessage = ChaosHandlerData_1.httpStatusCode[chaosHandlerOptions.statusCode]; | ||
var errMessage = chaosHandlerOptions.statusMessage; | ||
let body; | ||
if (this.chaosHandlerOptions.statusCode >= 400) { | ||
const codeMessage = ChaosHandlerData_1.httpStatusCode[this.chaosHandlerOptions.statusCode]; | ||
const errMessage = this.chaosHandlerOptions.statusMessage; | ||
body = { | ||
@@ -96,3 +101,3 @@ error: { | ||
return body; | ||
}; | ||
} | ||
/** | ||
@@ -104,11 +109,10 @@ * creates a response | ||
*/ | ||
ChaosHandler.prototype.createResponse = function (chaosHandlerOptions, context) { | ||
var requestURL = context.request; | ||
var requestID = (0, MiddlewareUtil_1.generateUUID)(); | ||
var requestDate = new Date(); | ||
var responseHeader = this.createResponseHeaders(chaosHandlerOptions, requestID, requestDate.toString()); | ||
var responseBody = this.createResponseBody(chaosHandlerOptions, requestID, requestDate.toString()); | ||
var init = { url: requestURL, status: chaosHandlerOptions.statusCode, statusText: chaosHandlerOptions.statusMessage, headers: responseHeader }; | ||
context.response = new Response(typeof responseBody === "string" ? responseBody : JSON.stringify(responseBody), init); | ||
}; | ||
createResponse(requestURL) { | ||
const requestID = (0, MiddlewareUtil_1.generateUUID)(); | ||
const requestDate = new Date(); | ||
const responseHeader = this.createResponseHeaders(requestID, requestDate.toString()); | ||
const responseBody = this.createResponseBody(requestID, requestDate.toString()); | ||
const init = { url: requestURL, status: this.chaosHandlerOptions.statusCode, statusText: this.chaosHandlerOptions.statusMessage, headers: responseHeader }; | ||
return new Response(typeof responseBody === "string" ? responseBody : JSON.stringify(responseBody), init); | ||
} | ||
/** | ||
@@ -121,22 +125,13 @@ * Decides whether to send the request to the graph or not | ||
*/ | ||
ChaosHandler.prototype.sendRequest = function (chaosHandlerOptions, context) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
this.setStatusCode(chaosHandlerOptions, context.request, context.options.method); | ||
if (!((chaosHandlerOptions.chaosStrategy === ChaosStrategy_1.ChaosStrategy.MANUAL && !this.nextMiddleware) || Math.floor(Math.random() * 100) < chaosHandlerOptions.chaosPercentage)) return [3 /*break*/, 1]; | ||
this.createResponse(chaosHandlerOptions, context); | ||
return [3 /*break*/, 3]; | ||
case 1: | ||
if (!this.nextMiddleware) return [3 /*break*/, 3]; | ||
return [4 /*yield*/, this.nextMiddleware.execute(context)]; | ||
case 2: | ||
_a.sent(); | ||
_a.label = 3; | ||
case 3: return [2 /*return*/]; | ||
} | ||
}); | ||
sendRequest(url, requestInit, requestOptions) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
this.setStatusCode(url, requestInit === null || requestInit === void 0 ? void 0 : requestInit.method); | ||
if ((this.chaosHandlerOptions.chaosStrategy === ChaosStrategy_1.ChaosStrategy.MANUAL && !this.next) || Math.floor(Math.random() * 100) < this.chaosHandlerOptions.chaosPercentage) { | ||
return this.createResponse(url); | ||
} | ||
else if (this.next) { | ||
yield this.next.execute(url, requestInit, requestOptions); | ||
} | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -148,6 +143,6 @@ * Fetches a random status code for the RANDOM mode from the predefined array | ||
*/ | ||
ChaosHandler.prototype.getRandomStatusCode = function (requestMethod) { | ||
var statusCodeArray = ChaosHandlerData_1.methodStatusCode[requestMethod]; | ||
getRandomStatusCode(requestMethod) { | ||
const statusCodeArray = ChaosHandlerData_1.methodStatusCode[requestMethod]; | ||
return statusCodeArray[Math.floor(Math.random() * statusCodeArray.length)]; | ||
}; | ||
} | ||
/** | ||
@@ -159,5 +154,5 @@ * To fetch the relative URL out of the complete URL using a predefined regex pattern | ||
*/ | ||
ChaosHandler.prototype.getRelativeURL = function (urlMethod) { | ||
var pattern = /https?:\/\/graph\.microsoft\.com\/[^/]+(.+?)(\?|$)/; | ||
var relativeURL; | ||
getRelativeURL(urlMethod) { | ||
const pattern = /https?:\/\/graph\.microsoft\.com\/[^/]+(.+?)(\?|$)/; | ||
let relativeURL; | ||
if (pattern.exec(urlMethod) !== null) { | ||
@@ -167,3 +162,3 @@ relativeURL = pattern.exec(urlMethod)[1]; | ||
return relativeURL; | ||
}; | ||
} | ||
/** | ||
@@ -176,12 +171,11 @@ * To fetch the status code from the map(if needed), then returns response by calling createResponse | ||
*/ | ||
ChaosHandler.prototype.setStatusCode = function (chaosHandlerOptions, requestURL, requestMethod) { | ||
var _this = this; | ||
if (chaosHandlerOptions.chaosStrategy === ChaosStrategy_1.ChaosStrategy.MANUAL) { | ||
if (chaosHandlerOptions.statusCode === undefined) { | ||
setStatusCode(requestURL, requestMethod) { | ||
if (this.chaosHandlerOptions.chaosStrategy === ChaosStrategy_1.ChaosStrategy.MANUAL) { | ||
if (this.chaosHandlerOptions.statusCode === undefined) { | ||
// manual mode with no status code, can be a global level or request level without statusCode | ||
var relativeURL_1 = this.getRelativeURL(requestURL); | ||
if (this.manualMap.get(relativeURL_1) !== undefined) { | ||
const relativeURL = this.getRelativeURL(requestURL); | ||
if (this.manualMap.get(relativeURL) !== undefined) { | ||
// checking Manual Map for exact match | ||
if (this.manualMap.get(relativeURL_1).get(requestMethod) !== undefined) { | ||
chaosHandlerOptions.statusCode = this.manualMap.get(relativeURL_1).get(requestMethod); | ||
if (this.manualMap.get(relativeURL).get(requestMethod) !== undefined) { | ||
this.chaosHandlerOptions.statusCode = this.manualMap.get(relativeURL).get(requestMethod); | ||
} | ||
@@ -192,7 +186,7 @@ // else statusCode would be undefined | ||
// checking for regex match if exact match doesn't work | ||
this.manualMap.forEach(function (value, key) { | ||
var regexURL = new RegExp(key + "$"); | ||
if (regexURL.test(relativeURL_1)) { | ||
if (_this.manualMap.get(key).get(requestMethod) !== undefined) { | ||
chaosHandlerOptions.statusCode = _this.manualMap.get(key).get(requestMethod); | ||
this.manualMap.forEach((value, key) => { | ||
const regexURL = new RegExp(key + "$"); | ||
if (regexURL.test(relativeURL)) { | ||
if (this.manualMap.get(key).get(requestMethod) !== undefined) { | ||
this.chaosHandlerOptions.statusCode = this.manualMap.get(key).get(requestMethod); | ||
} | ||
@@ -208,44 +202,8 @@ // else statusCode would be undefined | ||
// Handling the case of Random here | ||
chaosHandlerOptions.statusCode = this.getRandomStatusCode(requestMethod); | ||
this.chaosHandlerOptions.statusCode = this.getRandomStatusCode(requestMethod); | ||
// else statusCode would be undefined | ||
} | ||
}; | ||
} | ||
/** | ||
* To get the options for execution of the middleware | ||
* @private | ||
* @param {Context} context - The context object | ||
* @returns options for middleware execution | ||
*/ | ||
ChaosHandler.prototype.getOptions = function (context) { | ||
var options; | ||
if (context.middlewareControl instanceof MiddlewareControl_1.MiddlewareControl) { | ||
options = context.middlewareControl.getMiddlewareOptions(ChaosHandlerOptions_1.ChaosHandlerOptions); | ||
} | ||
if (typeof options === "undefined") { | ||
options = Object.assign(new ChaosHandlerOptions_1.ChaosHandlerOptions(), this.options); | ||
} | ||
return options; | ||
}; | ||
/** | ||
* To execute the current middleware | ||
* @public | ||
* @async | ||
* @param {Context} context - The context object of the request | ||
* @returns A Promise that resolves to nothing | ||
*/ | ||
ChaosHandler.prototype.execute = function (context) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var chaosHandlerOptions; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
chaosHandlerOptions = this.getOptions(context); | ||
return [4 /*yield*/, this.sendRequest(chaosHandlerOptions, context)]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
}); | ||
}; | ||
/** | ||
* @public | ||
* To set the next middleware in the chain | ||
@@ -255,8 +213,7 @@ * @param {Middleware} next - The middleware instance | ||
*/ | ||
ChaosHandler.prototype.setNext = function (next) { | ||
this.nextMiddleware = next; | ||
}; | ||
return ChaosHandler; | ||
}()); | ||
setNext(next) { | ||
this.next = next; | ||
} | ||
} | ||
exports.ChaosHandler = ChaosHandler; | ||
//# sourceMappingURL=ChaosHandler.js.map |
@@ -10,3 +10,3 @@ "use strict"; | ||
exports.cloneRequestWithNewUrl = exports.appendRequestHeader = exports.setRequestHeader = exports.getRequestHeader = exports.generateUUID = void 0; | ||
var tslib_1 = require("tslib"); | ||
const tslib_1 = require("tslib"); | ||
/** | ||
@@ -17,5 +17,5 @@ * @constant | ||
*/ | ||
var generateUUID = function () { | ||
var uuid = ""; | ||
for (var j = 0; j < 32; j++) { | ||
const generateUUID = () => { | ||
let uuid = ""; | ||
for (let j = 0; j < 32; j++) { | ||
if (j === 8 || j === 12 || j === 16 || j === 20) { | ||
@@ -37,4 +37,4 @@ uuid += "-"; | ||
*/ | ||
var getRequestHeader = function (request, options, key) { | ||
var value = null; | ||
const getRequestHeader = (request, options, key) => { | ||
let value = null; | ||
if (typeof Request !== "undefined" && request instanceof Request) { | ||
@@ -48,4 +48,4 @@ value = request.headers.get(key); | ||
else if (options.headers instanceof Array) { | ||
var headers = options.headers; | ||
for (var i = 0, l = headers.length; i < l; i++) { | ||
const headers = options.headers; | ||
for (let i = 0, l = headers.length; i < l; i++) { | ||
if (headers[i][0] === key) { | ||
@@ -73,4 +73,3 @@ value = headers[i][1]; | ||
*/ | ||
var setRequestHeader = function (request, options, key, value) { | ||
var _a, _b; | ||
const setRequestHeader = (request, options, key, value) => { | ||
if (typeof Request !== "undefined" && request instanceof Request) { | ||
@@ -81,5 +80,5 @@ request.headers.set(key, value); | ||
if (options.headers === undefined) { | ||
options.headers = new Headers((_a = {}, | ||
_a[key] = value, | ||
_a)); | ||
options.headers = new Headers({ | ||
[key]: value, | ||
}); | ||
} | ||
@@ -91,6 +90,6 @@ else { | ||
else if (options.headers instanceof Array) { | ||
var i = 0; | ||
var l = options.headers.length; | ||
let i = 0; | ||
const l = options.headers.length; | ||
for (; i < l; i++) { | ||
var header = options.headers[i]; | ||
const header = options.headers[i]; | ||
if (header[0] === key) { | ||
@@ -106,3 +105,3 @@ header[1] = value; | ||
else { | ||
Object.assign(options.headers, (_b = {}, _b[key] = value, _b)); | ||
Object.assign(options.headers, { [key]: value }); | ||
} | ||
@@ -122,4 +121,3 @@ } | ||
*/ | ||
var appendRequestHeader = function (request, options, key, value) { | ||
var _a, _b; | ||
const appendRequestHeader = (request, options, key, value) => { | ||
if (typeof Request !== "undefined" && request instanceof Request) { | ||
@@ -130,5 +128,5 @@ request.headers.append(key, value); | ||
if (options.headers === undefined) { | ||
options.headers = new Headers((_a = {}, | ||
_a[key] = value, | ||
_a)); | ||
options.headers = new Headers({ | ||
[key]: value, | ||
}); | ||
} | ||
@@ -143,3 +141,3 @@ else { | ||
else if (options.headers === undefined) { | ||
options.headers = (_b = {}, _b[key] = value, _b); | ||
options.headers = { [key]: value }; | ||
} | ||
@@ -150,3 +148,3 @@ else if (options.headers[key] === undefined) { | ||
else { | ||
options.headers[key] += ", ".concat(value); | ||
options.headers[key] += `, ${value}`; | ||
} | ||
@@ -164,24 +162,8 @@ } | ||
*/ | ||
var cloneRequestWithNewUrl = function (newUrl, request) { return (0, tslib_1.__awaiter)(void 0, void 0, void 0, function () { | ||
var body, _a, method, headers, referrer, referrerPolicy, mode, credentials, cache, redirect, integrity, keepalive, signal; | ||
return (0, tslib_1.__generator)(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
if (!request.headers.get("Content-Type")) return [3 /*break*/, 2]; | ||
return [4 /*yield*/, request.blob()]; | ||
case 1: | ||
_a = _b.sent(); | ||
return [3 /*break*/, 4]; | ||
case 2: return [4 /*yield*/, Promise.resolve(undefined)]; | ||
case 3: | ||
_a = _b.sent(); | ||
_b.label = 4; | ||
case 4: | ||
body = _a; | ||
method = request.method, headers = request.headers, referrer = request.referrer, referrerPolicy = request.referrerPolicy, mode = request.mode, credentials = request.credentials, cache = request.cache, redirect = request.redirect, integrity = request.integrity, keepalive = request.keepalive, signal = request.signal; | ||
return [2 /*return*/, new Request(newUrl, { method: method, headers: headers, body: body, referrer: referrer, referrerPolicy: referrerPolicy, mode: mode, credentials: credentials, cache: cache, redirect: redirect, integrity: integrity, keepalive: keepalive, signal: signal })]; | ||
} | ||
}); | ||
}); }; | ||
const cloneRequestWithNewUrl = (newUrl, request) => tslib_1.__awaiter(void 0, void 0, void 0, function* () { | ||
const body = request.headers.get("Content-Type") ? yield request.blob() : yield Promise.resolve(undefined); | ||
const { method, headers, referrer, referrerPolicy, mode, credentials, cache, redirect, integrity, keepalive, signal } = request; | ||
return new Request(newUrl, { method, headers, body, referrer, referrerPolicy, mode, credentials, cache, redirect, integrity, keepalive, signal }); | ||
}); | ||
exports.cloneRequestWithNewUrl = cloneRequestWithNewUrl; | ||
//# sourceMappingURL=MiddlewareUtil.js.map |
@@ -10,4 +10,4 @@ /** | ||
*/ | ||
import { RequestOption } from "@microsoft/kiota-abstractions"; | ||
import { ChaosStrategy } from "./ChaosStrategy"; | ||
import { MiddlewareOptions } from "./IMiddlewareOptions"; | ||
/** | ||
@@ -19,3 +19,3 @@ * Class representing ChaosHandlerOptions | ||
*/ | ||
export declare class ChaosHandlerOptions implements MiddlewareOptions { | ||
export declare class ChaosHandlerOptions implements RequestOption { | ||
/** | ||
@@ -70,2 +70,3 @@ * Specifies the startegy used for the Testing Handler -> RANDOM/MANUAL | ||
constructor(chaosStrategy?: ChaosStrategy, statusMessage?: string, statusCode?: number, chaosPercentage?: number, responseBody?: any, headers?: Headers); | ||
getKey(): string; | ||
} |
@@ -10,7 +10,5 @@ "use strict"; | ||
exports.ChaosHandlerOptions = void 0; | ||
const ChaosHandler_1 = require("../ChaosHandler"); | ||
const ChaosStrategy_1 = require("./ChaosStrategy"); | ||
/** | ||
* @module ChaosHandlerOptions | ||
*/ | ||
var ChaosStrategy_1 = require("./ChaosStrategy"); | ||
/** | ||
* Class representing ChaosHandlerOptions | ||
@@ -21,3 +19,3 @@ * @class | ||
*/ | ||
var ChaosHandlerOptions = /** @class */ (function () { | ||
class ChaosHandlerOptions { | ||
/** | ||
@@ -34,5 +32,3 @@ * @public | ||
*/ | ||
function ChaosHandlerOptions(chaosStrategy, statusMessage, statusCode, chaosPercentage, responseBody, headers) { | ||
if (chaosStrategy === void 0) { chaosStrategy = ChaosStrategy_1.ChaosStrategy.RANDOM; } | ||
if (statusMessage === void 0) { statusMessage = "Some error Happened"; } | ||
constructor(chaosStrategy = ChaosStrategy_1.ChaosStrategy.RANDOM, statusMessage = "Some error Happened", statusCode, chaosPercentage, responseBody, headers) { | ||
this.chaosStrategy = chaosStrategy; | ||
@@ -48,5 +44,7 @@ this.statusCode = statusCode; | ||
} | ||
return ChaosHandlerOptions; | ||
}()); | ||
getKey() { | ||
return ChaosHandler_1.ChaosHandlerOptionKey; | ||
} | ||
} | ||
exports.ChaosHandlerOptions = ChaosHandlerOptions; | ||
//# sourceMappingURL=ChaosHandlerOptions.js.map |
@@ -10,3 +10,3 @@ "use strict"; | ||
exports.FileUpload = void 0; | ||
var GraphClientError_1 = require("../../../GraphClientError"); | ||
const GraphClientError_1 = require("../../../GraphClientError"); | ||
/** | ||
@@ -17,3 +17,3 @@ * @class | ||
*/ | ||
var FileUpload = /** @class */ (function () { | ||
class FileUpload { | ||
/** | ||
@@ -27,3 +27,3 @@ * @public | ||
*/ | ||
function FileUpload(content, name, size) { | ||
constructor(content, name, size) { | ||
this.content = content; | ||
@@ -42,8 +42,7 @@ this.name = name; | ||
*/ | ||
FileUpload.prototype.sliceFile = function (range) { | ||
sliceFile(range) { | ||
return this.content.slice(range.minValue, range.maxValue + 1); | ||
}; | ||
return FileUpload; | ||
}()); | ||
} | ||
} | ||
exports.FileUpload = FileUpload; | ||
//# sourceMappingURL=FileUpload.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.StreamUpload = void 0; | ||
var tslib_1 = require("tslib"); | ||
var GraphClientError_1 = require("../../../GraphClientError"); | ||
const tslib_1 = require("tslib"); | ||
const GraphClientError_1 = require("../../../GraphClientError"); | ||
/** | ||
@@ -10,4 +10,4 @@ * @class | ||
*/ | ||
var StreamUpload = /** @class */ (function () { | ||
function StreamUpload(content, name, size) { | ||
class StreamUpload { | ||
constructor(content, name, size) { | ||
this.content = content; | ||
@@ -26,67 +26,62 @@ this.name = name; | ||
*/ | ||
StreamUpload.prototype.sliceFile = function (range) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var rangeSize, bufs, previousRangeMin, previousRangeMax, _a, _b, slicedChunk; | ||
return (0, tslib_1.__generator)(this, function (_c) { | ||
switch (_c.label) { | ||
case 0: | ||
rangeSize = range.maxValue - range.minValue + 1; | ||
bufs = []; | ||
/** | ||
* The sliceFile reads the first `rangeSize` number of bytes from the stream. | ||
* The previousSlice property is used to seek the range of bytes in the previous slice. | ||
* Suppose, the sliceFile reads bytes from `10 - 20` from the stream but the upload of this slice fails. | ||
* When the user resumes, the stream will have bytes from position 21. | ||
* The previousSlice.Range is used to compare if the requested range is cached in the previousSlice property or present in the Readable Stream. | ||
*/ | ||
if (this.previousSlice) { | ||
if (range.minValue < this.previousSlice.range.minValue) { | ||
throw new GraphClientError_1.GraphClientError("An error occurred while uploading the stream. Please restart the stream upload from the first byte of the file."); | ||
} | ||
if (range.minValue < this.previousSlice.range.maxValue) { | ||
previousRangeMin = this.previousSlice.range.minValue; | ||
previousRangeMax = this.previousSlice.range.maxValue; | ||
// Check if the requested range is same as previously sliced range | ||
if (range.minValue === previousRangeMin && range.maxValue === previousRangeMax) { | ||
return [2 /*return*/, this.previousSlice.fileSlice]; | ||
} | ||
/** | ||
* The following check considers a possibility | ||
* of an upload failing after some of the bytes of the previous slice | ||
* were successfully uploaded. | ||
* Example - Previous slice range - `10 - 20`. Current requested range is `15 - 20`. | ||
*/ | ||
if (range.maxValue === previousRangeMax) { | ||
return [2 /*return*/, this.previousSlice.fileSlice.slice(range.minValue, range.maxValue + 1)]; | ||
} | ||
/** | ||
* If an upload fails after some of the bytes of the previous slice | ||
* were successfully uploaded and the new Range.Maximum is greater than the previous Range.Maximum | ||
* Example - Previous slice range - `10 - 20`. Current requested range is `15 - 25`, | ||
* then read the bytes from position 15 to 20 from previousSlice.fileSlice and read bytes from position 21 to 25 from the Readable Stream | ||
*/ | ||
bufs.push(this.previousSlice.fileSlice.slice(range.minValue, previousRangeMax + 1)); | ||
rangeSize = range.maxValue - previousRangeMax; | ||
} | ||
} | ||
if (!(this.content && this.content.readable)) return [3 /*break*/, 4]; | ||
if (!(this.content.readableLength >= rangeSize)) return [3 /*break*/, 1]; | ||
bufs.push(this.content.read(rangeSize)); | ||
return [3 /*break*/, 3]; | ||
case 1: | ||
_b = (_a = bufs).push; | ||
return [4 /*yield*/, this.readNBytesFromStream(rangeSize)]; | ||
case 2: | ||
_b.apply(_a, [_c.sent()]); | ||
_c.label = 3; | ||
case 3: return [3 /*break*/, 5]; | ||
case 4: throw new GraphClientError_1.GraphClientError("Stream is not readable."); | ||
case 5: | ||
slicedChunk = Buffer.concat(bufs); | ||
this.previousSlice = { fileSlice: slicedChunk, range: range }; | ||
return [2 /*return*/, slicedChunk]; | ||
sliceFile(range) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let rangeSize = range.maxValue - range.minValue + 1; | ||
/* readable.readable Is true if it is safe to call readable.read(), | ||
* which means the stream has not been destroyed or emitted 'error' or 'end' | ||
*/ | ||
const bufs = []; | ||
/** | ||
* The sliceFile reads the first `rangeSize` number of bytes from the stream. | ||
* The previousSlice property is used to seek the range of bytes in the previous slice. | ||
* Suppose, the sliceFile reads bytes from `10 - 20` from the stream but the upload of this slice fails. | ||
* When the user resumes, the stream will have bytes from position 21. | ||
* The previousSlice.Range is used to compare if the requested range is cached in the previousSlice property or present in the Readable Stream. | ||
*/ | ||
if (this.previousSlice) { | ||
if (range.minValue < this.previousSlice.range.minValue) { | ||
throw new GraphClientError_1.GraphClientError("An error occurred while uploading the stream. Please restart the stream upload from the first byte of the file."); | ||
} | ||
}); | ||
if (range.minValue < this.previousSlice.range.maxValue) { | ||
const previousRangeMin = this.previousSlice.range.minValue; | ||
const previousRangeMax = this.previousSlice.range.maxValue; | ||
// Check if the requested range is same as previously sliced range | ||
if (range.minValue === previousRangeMin && range.maxValue === previousRangeMax) { | ||
return this.previousSlice.fileSlice; | ||
} | ||
/** | ||
* The following check considers a possibility | ||
* of an upload failing after some of the bytes of the previous slice | ||
* were successfully uploaded. | ||
* Example - Previous slice range - `10 - 20`. Current requested range is `15 - 20`. | ||
*/ | ||
if (range.maxValue === previousRangeMax) { | ||
return this.previousSlice.fileSlice.slice(range.minValue, range.maxValue + 1); | ||
} | ||
/** | ||
* If an upload fails after some of the bytes of the previous slice | ||
* were successfully uploaded and the new Range.Maximum is greater than the previous Range.Maximum | ||
* Example - Previous slice range - `10 - 20`. Current requested range is `15 - 25`, | ||
* then read the bytes from position 15 to 20 from previousSlice.fileSlice and read bytes from position 21 to 25 from the Readable Stream | ||
*/ | ||
bufs.push(this.previousSlice.fileSlice.slice(range.minValue, previousRangeMax + 1)); | ||
rangeSize = range.maxValue - previousRangeMax; | ||
} | ||
} | ||
if (this.content && this.content.readable) { | ||
if (this.content.readableLength >= rangeSize) { | ||
bufs.push(this.content.read(rangeSize)); | ||
} | ||
else { | ||
bufs.push(yield this.readNBytesFromStream(rangeSize)); | ||
} | ||
} | ||
else { | ||
throw new GraphClientError_1.GraphClientError("Stream is not readable."); | ||
} | ||
const slicedChunk = Buffer.concat(bufs); | ||
this.previousSlice = { fileSlice: slicedChunk, range }; | ||
return slicedChunk; | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -98,9 +93,8 @@ * @private | ||
*/ | ||
StreamUpload.prototype.readNBytesFromStream = function (size) { | ||
var _this = this; | ||
return new Promise(function (resolve, reject) { | ||
var chunks = []; | ||
var remainder = size; | ||
var length = 0; | ||
_this.content.on("end", function () { | ||
readNBytesFromStream(size) { | ||
return new Promise((resolve, reject) => { | ||
const chunks = []; | ||
let remainder = size; | ||
let length = 0; | ||
this.content.on("end", () => { | ||
if (remainder > 0) { | ||
@@ -110,3 +104,3 @@ return reject(new GraphClientError_1.GraphClientError("Stream ended before reading required range size")); | ||
}); | ||
_this.content.on("readable", function () { | ||
this.content.on("readable", () => { | ||
/** | ||
@@ -116,4 +110,4 @@ * (chunk = this.content.read(size)) can return null if size of stream is less than 'size' parameter. | ||
*/ | ||
var chunk; | ||
while (length < size && (chunk = _this.content.read(remainder)) !== null) { | ||
let chunk; | ||
while (length < size && (chunk = this.content.read(remainder)) !== null) { | ||
length += chunk.length; | ||
@@ -128,3 +122,3 @@ chunks.push(chunk); | ||
} | ||
if (!_this.content || !_this.content.readable) { | ||
if (!this.content || !this.content.readable) { | ||
return reject(new GraphClientError_1.GraphClientError("Error encountered while reading the stream during the upload")); | ||
@@ -134,6 +128,5 @@ } | ||
}); | ||
}; | ||
return StreamUpload; | ||
}()); | ||
} | ||
} | ||
exports.StreamUpload = StreamUpload; | ||
//# sourceMappingURL=StreamUpload.js.map |
@@ -17,3 +17,3 @@ "use strict"; | ||
*/ | ||
var Range = /** @class */ (function () { | ||
class Range { | ||
/** | ||
@@ -27,11 +27,8 @@ * @public | ||
*/ | ||
function Range(minVal, maxVal) { | ||
if (minVal === void 0) { minVal = -1; } | ||
if (maxVal === void 0) { maxVal = -1; } | ||
constructor(minVal = -1, maxVal = -1) { | ||
this.minValue = minVal; | ||
this.maxValue = maxVal; | ||
} | ||
return Range; | ||
}()); | ||
} | ||
exports.Range = Range; | ||
//# sourceMappingURL=Range.js.map |
@@ -13,3 +13,3 @@ "use strict"; | ||
*/ | ||
var UploadResult = /** @class */ (function () { | ||
class UploadResult { | ||
/** | ||
@@ -20,3 +20,3 @@ * @public | ||
*/ | ||
function UploadResult(responseBody, location) { | ||
constructor(responseBody, location) { | ||
// Response body or the location parameter can be undefined. | ||
@@ -26,51 +26,42 @@ this._location = location; | ||
} | ||
Object.defineProperty(UploadResult.prototype, "location", { | ||
/** | ||
* @public | ||
* Get of the location value. | ||
* Location value is looked up in the response header | ||
*/ | ||
get: function () { | ||
return this._location; | ||
}, | ||
/** | ||
* @public | ||
* Set the location value | ||
* Location value is looked up in the response header | ||
*/ | ||
set: function (location) { | ||
this._location = location; | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
Object.defineProperty(UploadResult.prototype, "responseBody", { | ||
/** | ||
* @public | ||
* Get The response body from the completed upload response | ||
*/ | ||
get: function () { | ||
return this._responseBody; | ||
}, | ||
/** | ||
* @public | ||
* Set the response body from the completed upload response | ||
*/ | ||
set: function (responseBody) { | ||
this._responseBody = responseBody; | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
/** | ||
* @public | ||
* Get of the location value. | ||
* Location value is looked up in the response header | ||
*/ | ||
get location() { | ||
return this._location; | ||
} | ||
/** | ||
* @public | ||
* Set the location value | ||
* Location value is looked up in the response header | ||
*/ | ||
set location(location) { | ||
this._location = location; | ||
} | ||
/** | ||
* @public | ||
* Get The response body from the completed upload response | ||
*/ | ||
get responseBody() { | ||
return this._responseBody; | ||
} | ||
/** | ||
* @public | ||
* Set the response body from the completed upload response | ||
*/ | ||
set responseBody(responseBody) { | ||
this._responseBody = responseBody; | ||
} | ||
/** | ||
* @public | ||
* @param {responseBody} responseBody - The response body from the completed upload response | ||
* @param {responseHeaders} responseHeaders - The headers from the completed upload response | ||
*/ | ||
UploadResult.CreateUploadResult = function (responseBody, responseHeaders) { | ||
static CreateUploadResult(responseBody, responseHeaders) { | ||
return new UploadResult(responseBody, responseHeaders.get("location")); | ||
}; | ||
return UploadResult; | ||
}()); | ||
} | ||
} | ||
exports.UploadResult = UploadResult; | ||
//# sourceMappingURL=UploadResult.js.map |
@@ -10,11 +10,11 @@ "use strict"; | ||
exports.LargeFileUploadTask = void 0; | ||
var tslib_1 = require("tslib"); | ||
const tslib_1 = require("tslib"); | ||
/** | ||
* @module LargeFileUploadTask | ||
*/ | ||
var GraphClientError_1 = require("../GraphClientError"); | ||
var GraphResponseHandler_1 = require("../GraphResponseHandler"); | ||
var ResponseType_1 = require("../ResponseType"); | ||
var Range_1 = require("./FileUploadTask/Range"); | ||
var UploadResult_1 = require("./FileUploadTask/UploadResult"); | ||
const GraphClientError_1 = require("../GraphClientError"); | ||
const GraphResponseHandler_1 = require("../GraphResponseHandler"); | ||
const ResponseType_1 = require("../ResponseType"); | ||
const Range_1 = require("./FileUploadTask/Range"); | ||
const UploadResult_1 = require("./FileUploadTask/UploadResult"); | ||
/** | ||
@@ -24,3 +24,3 @@ * @class | ||
*/ | ||
var LargeFileUploadTask = /** @class */ (function () { | ||
class LargeFileUploadTask { | ||
/** | ||
@@ -36,4 +36,3 @@ * @public | ||
*/ | ||
function LargeFileUploadTask(client, file, uploadSession, options) { | ||
if (options === void 0) { options = {}; } | ||
constructor(client, file, uploadSession, options = {}) { | ||
/** | ||
@@ -70,24 +69,16 @@ * @private | ||
*/ | ||
LargeFileUploadTask.createUploadSession = function (client, requestUrl, payload, headers) { | ||
if (headers === void 0) { headers = {}; } | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var session, largeFileUploadSession; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, client | ||
.api(requestUrl) | ||
.headers(headers) | ||
.post(payload)]; | ||
case 1: | ||
session = _a.sent(); | ||
largeFileUploadSession = { | ||
url: session.uploadUrl, | ||
expiry: new Date(session.expirationDateTime), | ||
isCancelled: false, | ||
}; | ||
return [2 /*return*/, largeFileUploadSession]; | ||
} | ||
}); | ||
static createUploadSession(client, requestUrl, payload, headers = {}) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
const session = yield client | ||
.api(requestUrl) | ||
.headers(headers) | ||
.post(payload); | ||
const largeFileUploadSession = { | ||
url: session.uploadUrl, | ||
expiry: new Date(session.expirationDateTime), | ||
isCancelled: false, | ||
}; | ||
return largeFileUploadSession; | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -99,10 +90,10 @@ * @private | ||
*/ | ||
LargeFileUploadTask.prototype.parseRange = function (ranges) { | ||
var rangeStr = ranges[0]; | ||
parseRange(ranges) { | ||
const rangeStr = ranges[0]; | ||
if (typeof rangeStr === "undefined" || rangeStr === "") { | ||
return new Range_1.Range(); | ||
} | ||
var firstRange = rangeStr.split("-"); | ||
var minVal = parseInt(firstRange[0], 10); | ||
var maxVal = parseInt(firstRange[1], 10); | ||
const firstRange = rangeStr.split("-"); | ||
const minVal = parseInt(firstRange[0], 10); | ||
let maxVal = parseInt(firstRange[1], 10); | ||
if (Number.isNaN(maxVal)) { | ||
@@ -112,3 +103,3 @@ maxVal = this.file.size - 1; | ||
return new Range_1.Range(minVal, maxVal); | ||
}; | ||
} | ||
/** | ||
@@ -120,6 +111,6 @@ * @private | ||
*/ | ||
LargeFileUploadTask.prototype.updateTaskStatus = function (response) { | ||
updateTaskStatus(response) { | ||
this.uploadSession.expiry = new Date(response.expirationDateTime); | ||
this.nextRange = this.parseRange(response.nextExpectedRanges); | ||
}; | ||
} | ||
/** | ||
@@ -130,8 +121,8 @@ * @public | ||
*/ | ||
LargeFileUploadTask.prototype.getNextRange = function () { | ||
getNextRange() { | ||
if (this.nextRange.minValue === -1) { | ||
return this.nextRange; | ||
} | ||
var minVal = this.nextRange.minValue; | ||
var maxValue = minVal + this.options.rangeSize - 1; | ||
const minVal = this.nextRange.minValue; | ||
let maxValue = minVal + this.options.rangeSize - 1; | ||
if (maxValue >= this.file.size) { | ||
@@ -141,3 +132,3 @@ maxValue = this.file.size - 1; | ||
return new Range_1.Range(minVal, maxValue); | ||
}; | ||
} | ||
/** | ||
@@ -150,3 +141,3 @@ * @deprecated This function has been moved into FileObject interface. | ||
*/ | ||
LargeFileUploadTask.prototype.sliceFile = function (range) { | ||
sliceFile(range) { | ||
console.warn("The LargeFileUploadTask.sliceFile() function has been deprecated and moved into the FileObject interface."); | ||
@@ -157,3 +148,3 @@ if (this.file.content instanceof ArrayBuffer || this.file.content instanceof Blob || this.file.content instanceof Uint8Array) { | ||
throw new GraphClientError_1.GraphClientError("The LargeFileUploadTask.sliceFile() function expects only Blob, ArrayBuffer or Uint8Array file content. Please note that the sliceFile() function is deprecated."); | ||
}; | ||
} | ||
/** | ||
@@ -165,52 +156,40 @@ * @public | ||
*/ | ||
LargeFileUploadTask.prototype.upload = function () { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var uploadEventHandlers, nextRange, err, fileSlice, rawResponse, responseBody, uploadResult, res; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
uploadEventHandlers = this.options && this.options.uploadEventHandlers; | ||
_a.label = 1; | ||
case 1: | ||
if (!!this.uploadSession.isCancelled) return [3 /*break*/, 5]; | ||
nextRange = this.getNextRange(); | ||
if (nextRange.maxValue === -1) { | ||
err = new Error("Task with which you are trying to upload is already completed, Please check for your uploaded file"); | ||
err.name = "Invalid Session"; | ||
throw err; | ||
} | ||
return [4 /*yield*/, this.file.sliceFile(nextRange)]; | ||
case 2: | ||
fileSlice = _a.sent(); | ||
return [4 /*yield*/, this.uploadSliceGetRawResponse(fileSlice, nextRange, this.file.size)]; | ||
case 3: | ||
rawResponse = _a.sent(); | ||
if (!rawResponse) { | ||
throw new GraphClientError_1.GraphClientError("Something went wrong! Large file upload slice response is null."); | ||
} | ||
return [4 /*yield*/, GraphResponseHandler_1.GraphResponseHandler.getResponse(rawResponse)]; | ||
case 4: | ||
responseBody = _a.sent(); | ||
/** | ||
* (rawResponse.status === 201) -> This condition is applicable for OneDrive, PrintDocument and Outlook APIs. | ||
* (rawResponse.status === 200 && responseBody.id) -> This additional condition is applicable only for OneDrive API. | ||
*/ | ||
if (rawResponse.status === 201 || (rawResponse.status === 200 && responseBody.id)) { | ||
uploadResult = UploadResult_1.UploadResult.CreateUploadResult(responseBody, rawResponse.headers); | ||
return [2 /*return*/, uploadResult]; | ||
} | ||
res = { | ||
expirationDateTime: responseBody.expirationDateTime || responseBody.ExpirationDateTime, | ||
nextExpectedRanges: responseBody.NextExpectedRanges || responseBody.nextExpectedRanges, | ||
}; | ||
this.updateTaskStatus(res); | ||
if (uploadEventHandlers && uploadEventHandlers.progress) { | ||
uploadEventHandlers.progress(nextRange, uploadEventHandlers.extraCallbackParam); | ||
} | ||
return [3 /*break*/, 1]; | ||
case 5: return [2 /*return*/]; | ||
upload() { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
const uploadEventHandlers = this.options && this.options.uploadEventHandlers; | ||
while (!this.uploadSession.isCancelled) { | ||
const nextRange = this.getNextRange(); | ||
if (nextRange.maxValue === -1) { | ||
const err = new Error("Task with which you are trying to upload is already completed, Please check for your uploaded file"); | ||
err.name = "Invalid Session"; | ||
throw err; | ||
} | ||
}); | ||
const fileSlice = yield this.file.sliceFile(nextRange); | ||
const rawResponse = yield this.uploadSliceGetRawResponse(fileSlice, nextRange, this.file.size); | ||
if (!rawResponse) { | ||
throw new GraphClientError_1.GraphClientError("Something went wrong! Large file upload slice response is null."); | ||
} | ||
const responseBody = yield GraphResponseHandler_1.GraphResponseHandler.getResponse(rawResponse); | ||
/** | ||
* (rawResponse.status === 201) -> This condition is applicable for OneDrive, PrintDocument and Outlook APIs. | ||
* (rawResponse.status === 200 && responseBody.id) -> This additional condition is applicable only for OneDrive API. | ||
*/ | ||
if (rawResponse.status === 201 || (rawResponse.status === 200 && responseBody.id)) { | ||
const uploadResult = UploadResult_1.UploadResult.CreateUploadResult(responseBody, rawResponse.headers); | ||
return uploadResult; | ||
} | ||
/* Handling the API issue where the case of Outlook upload response property -'nextExpectedRanges' is not uniform. | ||
* https://github.com/microsoftgraph/msgraph-sdk-serviceissues/issues/39 | ||
*/ | ||
const res = { | ||
expirationDateTime: responseBody.expirationDateTime || responseBody.ExpirationDateTime, | ||
nextExpectedRanges: responseBody.NextExpectedRanges || responseBody.nextExpectedRanges, | ||
}; | ||
this.updateTaskStatus(res); | ||
if (uploadEventHandlers && uploadEventHandlers.progress) { | ||
uploadEventHandlers.progress(nextRange, uploadEventHandlers.extraCallbackParam); | ||
} | ||
} | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -225,19 +204,14 @@ * @public | ||
*/ | ||
LargeFileUploadTask.prototype.uploadSlice = function (fileSlice, range, totalSize) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.client | ||
.api(this.uploadSession.url) | ||
.headers({ | ||
"Content-Length": "".concat(range.maxValue - range.minValue + 1), | ||
"Content-Range": "bytes ".concat(range.minValue, "-").concat(range.maxValue, "/").concat(totalSize), | ||
"Content-Type": "application/octet-stream", | ||
}) | ||
.put(fileSlice)]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
uploadSlice(fileSlice, range, totalSize) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return yield this.client | ||
.api(this.uploadSession.url) | ||
.headers({ | ||
"Content-Length": `${range.maxValue - range.minValue + 1}`, | ||
"Content-Range": `bytes ${range.minValue}-${range.maxValue}/${totalSize}`, | ||
"Content-Type": "application/octet-stream", | ||
}) | ||
.put(fileSlice); | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -252,20 +226,15 @@ * @public | ||
*/ | ||
LargeFileUploadTask.prototype.uploadSliceGetRawResponse = function (fileSlice, range, totalSize) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.client | ||
.api(this.uploadSession.url) | ||
.headers({ | ||
"Content-Length": "".concat(range.maxValue - range.minValue + 1), | ||
"Content-Range": "bytes ".concat(range.minValue, "-").concat(range.maxValue, "/").concat(totalSize), | ||
"Content-Type": "application/octet-stream", | ||
}) | ||
.responseType(ResponseType_1.ResponseType.RAW) | ||
.put(fileSlice)]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
uploadSliceGetRawResponse(fileSlice, range, totalSize) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return yield this.client | ||
.api(this.uploadSession.url) | ||
.headers({ | ||
"Content-Length": `${range.maxValue - range.minValue + 1}`, | ||
"Content-Range": `bytes ${range.minValue}-${range.maxValue}/${totalSize}`, | ||
"Content-Type": "application/octet-stream", | ||
}) | ||
.responseType(ResponseType_1.ResponseType.RAW) | ||
.put(fileSlice); | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -277,21 +246,14 @@ * @public | ||
*/ | ||
LargeFileUploadTask.prototype.cancel = function () { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var cancelResponse; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.client | ||
.api(this.uploadSession.url) | ||
.responseType(ResponseType_1.ResponseType.RAW) | ||
.delete()]; | ||
case 1: | ||
cancelResponse = _a.sent(); | ||
if (cancelResponse.status === 204) { | ||
this.uploadSession.isCancelled = true; | ||
} | ||
return [2 /*return*/, cancelResponse]; | ||
} | ||
}); | ||
cancel() { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
const cancelResponse = yield this.client | ||
.api(this.uploadSession.url) | ||
.responseType(ResponseType_1.ResponseType.RAW) | ||
.delete(); | ||
if (cancelResponse.status === 204) { | ||
this.uploadSession.isCancelled = true; | ||
} | ||
return cancelResponse; | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -303,16 +265,9 @@ * @public | ||
*/ | ||
LargeFileUploadTask.prototype.getStatus = function () { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var response; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.client.api(this.uploadSession.url).get()]; | ||
case 1: | ||
response = _a.sent(); | ||
this.updateTaskStatus(response); | ||
return [2 /*return*/, response]; | ||
} | ||
}); | ||
getStatus() { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
const response = yield this.client.api(this.uploadSession.url).get(); | ||
this.updateTaskStatus(response); | ||
return response; | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -324,15 +279,8 @@ * @public | ||
*/ | ||
LargeFileUploadTask.prototype.resume = function () { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, this.getStatus()]; | ||
case 1: | ||
_a.sent(); | ||
return [4 /*yield*/, this.upload()]; | ||
case 2: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
resume() { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
yield this.getStatus(); | ||
return yield this.upload(); | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -344,8 +292,7 @@ * @public | ||
*/ | ||
LargeFileUploadTask.prototype.getUploadSession = function () { | ||
getUploadSession() { | ||
return this.uploadSession; | ||
}; | ||
return LargeFileUploadTask; | ||
}()); | ||
} | ||
} | ||
exports.LargeFileUploadTask = LargeFileUploadTask; | ||
//# sourceMappingURL=LargeFileUploadTask.js.map |
@@ -10,10 +10,10 @@ "use strict"; | ||
exports.OneDriveLargeFileUploadTask = void 0; | ||
var tslib_1 = require("tslib"); | ||
const tslib_1 = require("tslib"); | ||
/** | ||
* @module OneDriveLargeFileUploadTask | ||
*/ | ||
var GraphClientError_1 = require("../GraphClientError"); | ||
var FileUpload_1 = require("./FileUploadTask/FileObjectClasses/FileUpload"); | ||
var LargeFileUploadTask_1 = require("./LargeFileUploadTask"); | ||
var OneDriveLargeFileUploadTaskUtil_1 = require("./OneDriveLargeFileUploadTaskUtil"); | ||
const GraphClientError_1 = require("../GraphClientError"); | ||
const FileUpload_1 = require("./FileUploadTask/FileObjectClasses/FileUpload"); | ||
const LargeFileUploadTask_1 = require("./LargeFileUploadTask"); | ||
const OneDriveLargeFileUploadTaskUtil_1 = require("./OneDriveLargeFileUploadTaskUtil"); | ||
/** | ||
@@ -23,4 +23,3 @@ * @class | ||
*/ | ||
var OneDriveLargeFileUploadTask = /** @class */ (function (_super) { | ||
(0, tslib_1.__extends)(OneDriveLargeFileUploadTask, _super); | ||
class OneDriveLargeFileUploadTask extends LargeFileUploadTask_1.LargeFileUploadTask { | ||
/** | ||
@@ -36,4 +35,4 @@ * @public | ||
*/ | ||
function OneDriveLargeFileUploadTask(client, file, uploadSession, options) { | ||
return _super.call(this, client, file, uploadSession, options) || this; | ||
constructor(client, file, uploadSession, options) { | ||
super(client, file, uploadSession, options); | ||
} | ||
@@ -48,4 +47,3 @@ /** | ||
*/ | ||
OneDriveLargeFileUploadTask.constructCreateSessionUrl = function (fileName, path) { | ||
if (path === void 0) { path = OneDriveLargeFileUploadTask.DEFAULT_UPLOAD_PATH; } | ||
static constructCreateSessionUrl(fileName, path = OneDriveLargeFileUploadTask.DEFAULT_UPLOAD_PATH) { | ||
fileName = fileName.trim(); | ||
@@ -57,14 +55,14 @@ path = path.trim(); | ||
if (path[0] !== "/") { | ||
path = "/".concat(path); | ||
path = `/${path}`; | ||
} | ||
if (path[path.length - 1] !== "/") { | ||
path = "".concat(path, "/"); | ||
path = `${path}/`; | ||
} | ||
// we choose to encode each component of the file path separately because when encoding full URI | ||
// with encodeURI, special characters like # or % in the file name doesn't get encoded as desired | ||
return "/me/drive/root:".concat(path | ||
return `/me/drive/root:${path | ||
.split("/") | ||
.map(function (p) { return encodeURIComponent(p); }) | ||
.join("/")).concat(encodeURIComponent(fileName), ":/createUploadSession"); | ||
}; | ||
.map((p) => encodeURIComponent(p)) | ||
.join("/")}${encodeURIComponent(fileName)}:/createUploadSession`; | ||
} | ||
/** | ||
@@ -78,5 +76,5 @@ * @private | ||
*/ | ||
OneDriveLargeFileUploadTask.getFileInfo = function (file, fileName) { | ||
var content; | ||
var size; | ||
static getFileInfo(file, fileName) { | ||
let content; | ||
let size; | ||
if (typeof Blob !== "undefined" && file instanceof Blob) { | ||
@@ -91,3 +89,3 @@ content = new File([file], fileName); | ||
else if (typeof Uint8Array !== "undefined" && file instanceof Uint8Array) { | ||
var b = file; | ||
const b = file; | ||
size = b.byteLength; | ||
@@ -97,6 +95,6 @@ content = b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength); | ||
return { | ||
content: content, | ||
size: size, | ||
content, | ||
size, | ||
}; | ||
}; | ||
} | ||
/** | ||
@@ -112,16 +110,13 @@ * @public | ||
*/ | ||
OneDriveLargeFileUploadTask.create = function (client, file, options) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var fileName, fileInfo, fileObj; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
if (!client || !file || !options) { | ||
throw new GraphClientError_1.GraphClientError("Please provide the Graph client instance, file object and OneDriveLargeFileUploadOptions value"); | ||
} | ||
fileName = options.fileName; | ||
fileInfo = OneDriveLargeFileUploadTask.getFileInfo(file, fileName); | ||
fileObj = new FileUpload_1.FileUpload(fileInfo.content, fileName, fileInfo.size); | ||
return [2 /*return*/, this.createTaskWithFileObject(client, fileObj, options)]; | ||
}); | ||
static create(client, file, options) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (!client || !file || !options) { | ||
throw new GraphClientError_1.GraphClientError("Please provide the Graph client instance, file object and OneDriveLargeFileUploadOptions value"); | ||
} | ||
const fileName = options.fileName; | ||
const fileInfo = OneDriveLargeFileUploadTask.getFileInfo(file, fileName); | ||
const fileObj = new FileUpload_1.FileUpload(fileInfo.content, fileName, fileInfo.size); | ||
return this.createTaskWithFileObject(client, fileObj, options); | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -137,29 +132,21 @@ * @public | ||
*/ | ||
OneDriveLargeFileUploadTask.createTaskWithFileObject = function (client, fileObject, options) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var requestUrl, uploadSessionPayload, session, rangeSize; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!client || !fileObject || !options) { | ||
throw new GraphClientError_1.GraphClientError("Please provide the Graph client instance, FileObject interface implementation and OneDriveLargeFileUploadOptions value"); | ||
} | ||
requestUrl = OneDriveLargeFileUploadTask.constructCreateSessionUrl(options.fileName, options.path); | ||
uploadSessionPayload = { | ||
fileName: options.fileName, | ||
fileDescription: options.fileDescription, | ||
conflictBehavior: options.conflictBehavior, | ||
}; | ||
return [4 /*yield*/, OneDriveLargeFileUploadTask.createUploadSession(client, requestUrl, uploadSessionPayload)]; | ||
case 1: | ||
session = _a.sent(); | ||
rangeSize = (0, OneDriveLargeFileUploadTaskUtil_1.getValidRangeSize)(options.rangeSize); | ||
return [2 /*return*/, new OneDriveLargeFileUploadTask(client, fileObject, session, { | ||
rangeSize: rangeSize, | ||
uploadEventHandlers: options.uploadEventHandlers, | ||
})]; | ||
} | ||
static createTaskWithFileObject(client, fileObject, options) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (!client || !fileObject || !options) { | ||
throw new GraphClientError_1.GraphClientError("Please provide the Graph client instance, FileObject interface implementation and OneDriveLargeFileUploadOptions value"); | ||
} | ||
const requestUrl = OneDriveLargeFileUploadTask.constructCreateSessionUrl(options.fileName, options.path); | ||
const uploadSessionPayload = { | ||
fileName: options.fileName, | ||
fileDescription: options.fileDescription, | ||
conflictBehavior: options.conflictBehavior, | ||
}; | ||
const session = yield OneDriveLargeFileUploadTask.createUploadSession(client, requestUrl, uploadSessionPayload); | ||
const rangeSize = (0, OneDriveLargeFileUploadTaskUtil_1.getValidRangeSize)(options.rangeSize); | ||
return new OneDriveLargeFileUploadTask(client, fileObject, session, { | ||
rangeSize, | ||
uploadEventHandlers: options.uploadEventHandlers, | ||
}); | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -175,17 +162,17 @@ * @public | ||
*/ | ||
OneDriveLargeFileUploadTask.createUploadSession = function (client, requestUrl, payloadOptions) { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var payload; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
payload = { | ||
item: { | ||
"@microsoft.graph.conflictBehavior": (payloadOptions === null || payloadOptions === void 0 ? void 0 : payloadOptions.conflictBehavior) || "rename", | ||
name: payloadOptions === null || payloadOptions === void 0 ? void 0 : payloadOptions.fileName, | ||
description: payloadOptions === null || payloadOptions === void 0 ? void 0 : payloadOptions.fileDescription, | ||
}, | ||
}; | ||
return [2 /*return*/, _super.createUploadSession.call(this, client, requestUrl, payload)]; | ||
}); | ||
static createUploadSession(client, requestUrl, payloadOptions) { | ||
const _super = Object.create(null, { | ||
createUploadSession: { get: () => super.createUploadSession } | ||
}); | ||
}; | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
const payload = { | ||
item: { | ||
"@microsoft.graph.conflictBehavior": (payloadOptions === null || payloadOptions === void 0 ? void 0 : payloadOptions.conflictBehavior) || "rename", | ||
name: payloadOptions === null || payloadOptions === void 0 ? void 0 : payloadOptions.fileName, | ||
description: payloadOptions === null || payloadOptions === void 0 ? void 0 : payloadOptions.fileDescription, | ||
}, | ||
}; | ||
return _super.createUploadSession.call(this, client, requestUrl, payload); | ||
}); | ||
} | ||
/** | ||
@@ -198,29 +185,20 @@ * @public | ||
*/ | ||
OneDriveLargeFileUploadTask.prototype.commit = function (requestUrl, conflictBehavior) { | ||
if (conflictBehavior === void 0) { conflictBehavior = "rename"; } | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var payload; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
payload = { | ||
name: this.file.name, | ||
"@microsoft.graph.conflictBehavior": conflictBehavior, | ||
"@microsoft.graph.sourceUrl": this.uploadSession.url, | ||
}; | ||
return [4 /*yield*/, this.client.api(requestUrl).put(payload)]; | ||
case 1: return [2 /*return*/, _a.sent()]; | ||
} | ||
}); | ||
commit(requestUrl, conflictBehavior = "rename") { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
const payload = { | ||
name: this.file.name, | ||
"@microsoft.graph.conflictBehavior": conflictBehavior, | ||
"@microsoft.graph.sourceUrl": this.uploadSession.url, | ||
}; | ||
return yield this.client.api(requestUrl).put(payload); | ||
}); | ||
}; | ||
/** | ||
* @private | ||
* @static | ||
* Default path for the file being uploaded | ||
*/ | ||
OneDriveLargeFileUploadTask.DEFAULT_UPLOAD_PATH = "/"; | ||
return OneDriveLargeFileUploadTask; | ||
}(LargeFileUploadTask_1.LargeFileUploadTask)); | ||
} | ||
} | ||
exports.OneDriveLargeFileUploadTask = OneDriveLargeFileUploadTask; | ||
/** | ||
* @private | ||
* @static | ||
* Default path for the file being uploaded | ||
*/ | ||
OneDriveLargeFileUploadTask.DEFAULT_UPLOAD_PATH = "/"; | ||
//# sourceMappingURL=OneDriveLargeFileUploadTask.js.map |
@@ -18,3 +18,3 @@ "use strict"; | ||
*/ | ||
var DEFAULT_FILE_SIZE = 5 * 1024 * 1024; | ||
const DEFAULT_FILE_SIZE = 5 * 1024 * 1024; | ||
/** | ||
@@ -26,3 +26,3 @@ * @constant | ||
*/ | ||
var roundTo320KB = function (value) { | ||
const roundTo320KB = (value) => { | ||
if (value > 320 * 1024) { | ||
@@ -41,5 +41,4 @@ value = Math.floor(value / (320 * 1024)) * 320 * 1024; | ||
*/ | ||
var getValidRangeSize = function (rangeSize) { | ||
if (rangeSize === void 0) { rangeSize = DEFAULT_FILE_SIZE; } | ||
var sixtyMB = 60 * 1024 * 1024; | ||
const getValidRangeSize = (rangeSize = DEFAULT_FILE_SIZE) => { | ||
const sixtyMB = 60 * 1024 * 1024; | ||
if (rangeSize > sixtyMB) { | ||
@@ -46,0 +45,0 @@ rangeSize = sixtyMB; |
@@ -10,3 +10,3 @@ "use strict"; | ||
exports.PageIterator = void 0; | ||
var tslib_1 = require("tslib"); | ||
const tslib_1 = require("tslib"); | ||
/** | ||
@@ -16,3 +16,3 @@ * @class | ||
*/ | ||
var PageIterator = /** @class */ (function () { | ||
class PageIterator { | ||
/** | ||
@@ -28,3 +28,3 @@ * @public | ||
*/ | ||
function PageIterator(client, pageCollection, callback, requestOptions) { | ||
constructor(client, pageCollection, callback, requestOptions) { | ||
this.client = client; | ||
@@ -43,13 +43,13 @@ this.collection = pageCollection.value; | ||
*/ | ||
PageIterator.prototype.iterationHelper = function () { | ||
iterationHelper() { | ||
if (this.collection === undefined) { | ||
return false; | ||
} | ||
var advance = true; | ||
let advance = true; | ||
while (advance && this.collection.length !== 0) { | ||
var item = this.collection.shift(); | ||
const item = this.collection.shift(); | ||
advance = this.callback(item); | ||
} | ||
return advance; | ||
}; | ||
} | ||
/** | ||
@@ -61,31 +61,22 @@ * @private | ||
*/ | ||
PageIterator.prototype.fetchAndUpdateNextPageData = function () { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var graphRequest, response; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
graphRequest = this.client.api(this.nextLink); | ||
if (this.requestOptions) { | ||
if (this.requestOptions.headers) { | ||
graphRequest = graphRequest.headers(this.requestOptions.headers); | ||
} | ||
if (this.requestOptions.middlewareOptions) { | ||
graphRequest = graphRequest.middlewareOptions(this.requestOptions.middlewareOptions); | ||
} | ||
if (this.requestOptions.options) { | ||
graphRequest = graphRequest.options(this.requestOptions.options); | ||
} | ||
} | ||
return [4 /*yield*/, graphRequest.get()]; | ||
case 1: | ||
response = _a.sent(); | ||
this.collection = response.value; | ||
this.nextLink = response["@odata.nextLink"]; | ||
this.deltaLink = response["@odata.deltaLink"]; | ||
return [2 /*return*/]; | ||
fetchAndUpdateNextPageData() { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let graphRequest = this.client.api(this.nextLink); | ||
if (this.requestOptions) { | ||
if (this.requestOptions.headers) { | ||
graphRequest = graphRequest.headers(this.requestOptions.headers); | ||
} | ||
}); | ||
if (this.requestOptions.middlewareOptions) { | ||
graphRequest = graphRequest.middlewareOptions(this.requestOptions.middlewareOptions); | ||
} | ||
if (this.requestOptions.options) { | ||
graphRequest = graphRequest.options(this.requestOptions.options); | ||
} | ||
} | ||
const response = yield graphRequest.get(); | ||
this.collection = response.value; | ||
this.nextLink = response["@odata.nextLink"]; | ||
this.deltaLink = response["@odata.deltaLink"]; | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -96,5 +87,5 @@ * @public | ||
*/ | ||
PageIterator.prototype.getDeltaLink = function () { | ||
getDeltaLink() { | ||
return this.deltaLink; | ||
}; | ||
} | ||
/** | ||
@@ -107,31 +98,19 @@ * @public | ||
*/ | ||
PageIterator.prototype.iterate = function () { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
var advance; | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
advance = this.iterationHelper(); | ||
_a.label = 1; | ||
case 1: | ||
if (!advance) return [3 /*break*/, 5]; | ||
if (!(this.nextLink !== undefined)) return [3 /*break*/, 3]; | ||
return [4 /*yield*/, this.fetchAndUpdateNextPageData()]; | ||
case 2: | ||
_a.sent(); | ||
advance = this.iterationHelper(); | ||
return [3 /*break*/, 4]; | ||
case 3: | ||
advance = false; | ||
_a.label = 4; | ||
case 4: return [3 /*break*/, 1]; | ||
case 5: | ||
if (this.nextLink === undefined && this.collection.length === 0) { | ||
this.complete = true; | ||
} | ||
return [2 /*return*/]; | ||
iterate() { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
let advance = this.iterationHelper(); | ||
while (advance) { | ||
if (this.nextLink !== undefined) { | ||
yield this.fetchAndUpdateNextPageData(); | ||
advance = this.iterationHelper(); | ||
} | ||
}); | ||
else { | ||
advance = false; | ||
} | ||
} | ||
if (this.nextLink === undefined && this.collection.length === 0) { | ||
this.complete = true; | ||
} | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -144,9 +123,7 @@ * @public | ||
*/ | ||
PageIterator.prototype.resume = function () { | ||
return (0, tslib_1.__awaiter)(this, void 0, void 0, function () { | ||
return (0, tslib_1.__generator)(this, function (_a) { | ||
return [2 /*return*/, this.iterate()]; | ||
}); | ||
resume() { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return this.iterate(); | ||
}); | ||
}; | ||
} | ||
/** | ||
@@ -157,8 +134,7 @@ * @public | ||
*/ | ||
PageIterator.prototype.isComplete = function () { | ||
isComplete() { | ||
return this.complete; | ||
}; | ||
return PageIterator; | ||
}()); | ||
} | ||
} | ||
exports.PageIterator = PageIterator; | ||
//# sourceMappingURL=PageIterator.js.map |
@@ -16,5 +16,5 @@ "use strict"; | ||
*/ | ||
var validatePolyFilling = function () { | ||
const validatePolyFilling = () => { | ||
if (typeof Promise === "undefined" && typeof fetch === "undefined") { | ||
var error = new Error("Library cannot function without Promise and fetch. So, please provide polyfill for them."); | ||
const error = new Error("Library cannot function without Promise and fetch. So, please provide polyfill for them."); | ||
error.name = "PolyFillNotAvailable"; | ||
@@ -24,3 +24,3 @@ throw error; | ||
else if (typeof Promise === "undefined") { | ||
var error = new Error("Library cannot function without Promise. So, please provide polyfill for it."); | ||
const error = new Error("Library cannot function without Promise. So, please provide polyfill for it."); | ||
error.name = "PolyFillNotAvailable"; | ||
@@ -30,3 +30,3 @@ throw error; | ||
else if (typeof fetch === "undefined") { | ||
var error = new Error("Library cannot function without fetch. So, please provide polyfill for it."); | ||
const error = new Error("Library cannot function without fetch. So, please provide polyfill for it."); | ||
error.name = "PolyFillNotAvailable"; | ||
@@ -33,0 +33,0 @@ throw error; |
@@ -10,2 +10,2 @@ /** | ||
*/ | ||
export declare const PACKAGE_VERSION = "3.0.2"; | ||
export declare const PACKAGE_VERSION = "4.0.0-Preview.1"; |
@@ -15,3 +15,3 @@ "use strict"; | ||
*/ | ||
exports.PACKAGE_VERSION = "3.0.2"; | ||
exports.PACKAGE_VERSION = "4.0.0-Preview.1"; | ||
//# sourceMappingURL=Version.js.map |
{ | ||
"name": "@microsoft/microsoft-graph-client", | ||
"version": "3.0.2", | ||
"version": "4.0.0-Preview.1", | ||
"description": "Microsoft Graph Client Library", | ||
@@ -32,7 +32,5 @@ "keywords": [ | ||
"scripts": { | ||
"build": "npm run pre-build && npm run build:sub_cjs && npm run build:sub_es && rollup -c", | ||
"build": "npm run pre-build && npm run build:cjs && npm run build:es && rollup -c", | ||
"build:cjs": "tsc --p tsconfig-cjs.json", | ||
"build:es": "tsc --p tsconfig-es.json", | ||
"build:sub_cjs": "tsc -b tsconfig-sub-cjs.json", | ||
"build:sub_es": "tsc -b tsconfig-sub-es.json", | ||
"format": "npm run format:css && npm run format:html && npm run format:js && npm run format:json && npm run format:md && npm run format:rc && npm run format:ts", | ||
@@ -49,10 +47,10 @@ "format:css": "prettier --write \"**/*.css\"", | ||
"lint:fix": "eslint . --ext .ts --fix", | ||
"prepack": "npm install && npm run build && npm run test", | ||
"prepack": "npm install && npm run build", | ||
"pre-build": "npm run setVersion", | ||
"setVersion": "gulp setVersion", | ||
"test": "npm run test:cjs && npm run test:esm", | ||
"test:cjs": "npm run build:sub_cjs && mocha 'lib/test/common/**/*.js' --require isomorphic-fetch && mocha 'lib/test/node/**/*.js' --require isomorphic-fetch", | ||
"test:cjs": "npm run build:cjs && mocha 'lib/test/common/**/*.js' --require isomorphic-fetch && mocha 'lib/test/node/**/*.js' --require isomorphic-fetch", | ||
"test:coverage": "TS_NODE_PROJECT='./tsconfig-cjs.json' nyc mocha --require isomorphic-fetch -r ts-node/register test/common/**/*.ts && mocha --require isomorphic-fetch -r ts-node/register test/common/**/*.ts", | ||
"test:development": "tsc --p test/tsconfig-test-development.json && mocha 'lib/test/development/**/*.js' --require isomorphic-fetch", | ||
"test:esm": "npm run build:sub_es && mocha 'lib/es/test/common/**/*.js' --require esm --require isomorphic-fetch && mocha 'lib/es/test/node/**/*.js' --require esm --require isomorphic-fetch" | ||
"test:esm": "npm run build:es && mocha 'lib/es/test/common/**/*.js' --require esm --require isomorphic-fetch && mocha 'lib/es/test/node/**/*.js' --require esm --require isomorphic-fetch" | ||
}, | ||
@@ -72,3 +70,4 @@ "nyc": { | ||
"dependencies": { | ||
"@babel/runtime": "^7.12.5", | ||
"@microsoft/kiota-abstractions": "^1.0.0-preview.1", | ||
"@microsoft/kiota-http-fetchlibrary": "^1.0.0-preview.1", | ||
"tslib": "^2.2.0" | ||
@@ -82,2 +81,3 @@ }, | ||
"@babel/preset-env": "^7.12.11", | ||
"@babel/runtime": "^7.12.5", | ||
"@istanbuljs/nyc-config-typescript": "^1.0.1", | ||
@@ -92,6 +92,6 @@ "@microsoft/microsoft-graph-types": "^2.11.0", | ||
"@types/sinon": "^10.0.8", | ||
"@typescript-eslint/eslint-plugin": "^4.0.0", | ||
"@typescript-eslint/parser": "^3.8.0", | ||
"@typescript-eslint/eslint-plugin": "^5.12.1", | ||
"@typescript-eslint/parser": "^5.12.1", | ||
"chai": "^4.2.0", | ||
"eslint": "^7.19.0", | ||
"eslint": "^8.9.0", | ||
"eslint-config-prettier": "^8.3.0", | ||
@@ -98,0 +98,0 @@ "eslint-plugin-prettier": "^4.0.0", |
@@ -7,20 +7,12 @@ /** | ||
*/ | ||
// eslint-disable-next-line @typescript-eslint/triple-slash-reference | ||
/// <reference path= "../../shims.d.ts" /> | ||
export { BatchRequestStep, BatchRequestData, BatchRequestContent, RequestData, BatchRequestBody } from "../content/BatchRequestContent"; | ||
export { BaseBearerTokenAuthenticationProvider, AccessTokenProvider, RequestOption } from "@microsoft/kiota-abstractions"; | ||
export { RetryHandler, RedirectHandler, TelemetryHandler, RetryHandlerOptions, HttpClient, TelemetryHandlerOptions, TelemetryHandlerOptionsKey, RetryHandlerOptionKey } from "@microsoft/kiota-http-fetchlibrary"; | ||
export { BatchRequestBody, RequestData, BatchRequestContent, BatchRequestData, BatchRequestStep } from "../content/BatchRequestContent"; | ||
export { BatchResponseBody, BatchResponseContent } from "../content/BatchResponseContent"; | ||
export { AuthenticationHandler } from "../middleware/AuthenticationHandler"; | ||
export { HTTPMessageHandler } from "../middleware/HTTPMessageHandler"; | ||
export { Middleware } from "../middleware/IMiddleware"; | ||
export { RetryHandler } from "../middleware/RetryHandler"; | ||
export { RedirectHandler } from "../middleware/RedirectHandler"; | ||
export { TelemetryHandler } from "../middleware/TelemetryHandler"; | ||
export { MiddlewareFactory } from "../middleware/MiddlewareFactory"; | ||
export { AuthenticationHandlerOptions } from "../middleware/options/AuthenticationHandlerOptions"; | ||
export { MiddlewareOptions } from "../middleware/options/IMiddlewareOptions"; | ||
export { ShouldRetry, RetryHandlerOptions } from "../middleware/options/RetryHandlerOptions"; | ||
export { ShouldRedirect, RedirectHandlerOptions } from "../middleware/options/RedirectHandlerOptions"; | ||
export { FeatureUsageFlag, TelemetryHandlerOptions } from "../middleware/options/TelemetryHandlerOptions"; | ||
export { FeatureUsageFlag } from "../middleware/Telemetry/TelemetryFeatureUsageFlag"; | ||
export { ChaosHandlerOptions } from "../middleware/options/ChaosHandlerOptions"; | ||
@@ -30,4 +22,4 @@ export { ChaosStrategy } from "../middleware/options/ChaosStrategy"; | ||
export { SliceType, LargeFileUploadTaskOptions, LargeFileUploadTask, LargeFileUploadSession, FileObject } from "../tasks/LargeFileUploadTask"; | ||
export { OneDriveLargeFileUploadTask, OneDriveLargeFileUploadOptions } from "../tasks/OneDriveLargeFileUploadTask"; | ||
export { FileObject, LargeFileUploadSession, LargeFileUploadTask, LargeFileUploadTaskOptions, SliceType } from "../tasks/LargeFileUploadTask"; | ||
export { OneDriveLargeFileUploadOptions, OneDriveLargeFileUploadTask } from "../tasks/OneDriveLargeFileUploadTask"; | ||
export { getValidRangeSize } from "../tasks/OneDriveLargeFileUploadTaskUtil"; | ||
@@ -39,18 +31,25 @@ export { StreamUpload } from "../tasks/FileUploadTask/FileObjectClasses/StreamUpload"; | ||
export { Range } from "../tasks/FileUploadTask/Range"; | ||
export { PageIteratorCallback, PageIterator, PageCollection, GraphRequestOptions } from "../tasks/PageIterator"; | ||
export { GraphRequestOptions, PageCollection, PageIterator, PageIteratorCallback } from "../tasks/PageIterator"; | ||
export { Client } from "../Client"; | ||
export { CustomAuthenticationProvider } from "../CustomAuthenticationProvider"; | ||
export { GraphError } from "../GraphError"; | ||
export { GraphClientError } from "../GraphClientError"; | ||
export { GraphRequest } from "../GraphRequest"; | ||
export { AuthProvider } from "../IAuthProvider"; | ||
export { AuthenticationProvider } from "../IAuthenticationProvider"; | ||
export { AuthenticationProviderOptions } from "../IAuthenticationProviderOptions"; | ||
export { AuthProviderCallback } from "../IAuthProviderCallback"; | ||
export { GraphRequest, URLComponents } from "../GraphRequest"; | ||
export { ClientOptions } from "../IClientOptions"; | ||
export { Context } from "../IContext"; | ||
export { NodeFetchInit, FetchOptions } from "../IFetchOptions"; | ||
export { FetchOptions, NodeFetchInit } from "../IFetchOptions"; | ||
export { GraphRequestCallback } from "../IGraphRequestCallback"; | ||
export { Options } from "../IOptions"; | ||
export { ResponseType } from "../ResponseType"; | ||
export { SimpleAuthenticationProvider } from "../authentication/SimpleAuthentication/SimpleAuthenticationProvider"; | ||
export { SimpleAccessTokenProvider } from "../authentication/SimpleAuthentication/SimpleAccessTokenProvider"; | ||
export { GraphBaseClient } from "../requestBuilderUtils/GraphBaseClient"; | ||
export { GraphSDKConfig } from "../requestBuilderUtils/GraphSDKConfig"; | ||
export { coreSdkVersionValue, getGraphTelemetryCallback, CORE_PRODUCT_NAME, graphTelemetryCallback } from "../middleware/Telemetry/TelemetryUtil"; | ||
export { GraphTelemetryConfig } from "../middleware/Telemetry/GraphTelemetryConfig"; | ||
export { getDefaultMiddlewareChain } from "./MiddlewareFactory"; | ||
export { GRAPH_API_VERSION, GRAPH_BASE_URL, GRAPH_URLS } from "../Constants"; | ||
export { isCustomHost, isGraphURL, updateAndReturnAllAllowedHosts } from "../GraphRequestUtil"; |
@@ -11,13 +11,13 @@ /** | ||
*/ | ||
import { BaseBearerTokenAuthenticationProvider } from "@microsoft/kiota-abstractions"; | ||
import { HttpClient } from "@microsoft/kiota-http-fetchlibrary"; | ||
import { GraphBaseClient, GraphClientError } from "."; | ||
import { GRAPH_API_VERSION, GRAPH_BASE_URL } from "./Constants"; | ||
import { CustomAuthenticationProvider } from "./CustomAuthenticationProvider"; | ||
import { GraphRequest } from "./GraphRequest"; | ||
import { HTTPClient } from "./HTTPClient"; | ||
import { HTTPClientFactory } from "./HTTPClientFactory"; | ||
import { updateAndReturnAllAllowedHosts } from "./GraphRequestUtil"; | ||
import { ClientOptions } from "./IClientOptions"; | ||
import { Options } from "./IOptions"; | ||
import { validatePolyFilling } from "./ValidatePolyFilling"; | ||
import { getDefaultMiddlewareChain } from "./MiddlewareFactory"; | ||
export class Client { | ||
export class Client implements GraphBaseClient { | ||
/** | ||
@@ -37,4 +37,6 @@ * @private | ||
*/ | ||
private httpClient: HTTPClient; | ||
protected httpClient: HttpClient; | ||
protected authProvider: BaseBearerTokenAuthenticationProvider; | ||
/** | ||
@@ -47,24 +49,7 @@ * @public | ||
*/ | ||
public static init(options: Options): Client { | ||
const clientOptions: ClientOptions = {}; | ||
for (const i in options) { | ||
if (Object.prototype.hasOwnProperty.call(options, i)) { | ||
clientOptions[i] = i === "authProvider" ? new CustomAuthenticationProvider(options[i]) : options[i]; | ||
} | ||
} | ||
return Client.initWithMiddleware(clientOptions); | ||
public static init(options: ClientOptions): Client { | ||
return new Client(options); | ||
} | ||
/** | ||
* @public | ||
* @static | ||
* To create a client instance with the Client Options | ||
* @param {ClientOptions} clientOptions - The options object for initializing the client | ||
* @returns The Client instance | ||
*/ | ||
public static initWithMiddleware(clientOptions: ClientOptions): Client { | ||
return new Client(clientOptions); | ||
} | ||
/** | ||
* @private | ||
@@ -76,3 +61,2 @@ * @constructor | ||
private constructor(clientOptions: ClientOptions) { | ||
validatePolyFilling(); | ||
for (const key in clientOptions) { | ||
@@ -83,17 +67,15 @@ if (Object.prototype.hasOwnProperty.call(clientOptions, key)) { | ||
} | ||
let httpClient: HTTPClient; | ||
if (clientOptions.authProvider !== undefined && clientOptions.middleware !== undefined) { | ||
const error = new Error(); | ||
error.name = "AmbiguityInInitialization"; | ||
error.message = "Unable to Create Client, Please provide either authentication provider for default middleware chain or custom middleware chain not both"; | ||
let httpClient: HttpClient; | ||
if (clientOptions.authProvider === undefined) { | ||
const error = new GraphClientError(); | ||
error.name = "Client Initialization Failed"; | ||
error.message = "Unable to Create Client, Please provide an authentication provider"; | ||
throw error; | ||
} else if (clientOptions.authProvider !== undefined) { | ||
httpClient = HTTPClientFactory.createWithAuthenticationProvider(clientOptions.authProvider); | ||
} else if (clientOptions.middleware !== undefined) { | ||
httpClient = new HTTPClient(...[].concat(clientOptions.middleware)); | ||
} | ||
const allowedHosts = updateAndReturnAllAllowedHosts(clientOptions.authProvider, this.config.customHosts); | ||
if (!clientOptions.middleware) { | ||
httpClient = new HttpClient(undefined, ...[].concat(getDefaultMiddlewareChain(clientOptions, allowedHosts))); | ||
} else { | ||
const error = new Error(); | ||
error.name = "InvalidMiddlewareChain"; | ||
error.message = "Unable to Create Client, Please provide either authentication provider for default middleware chain or custom middleware chain"; | ||
throw error; | ||
httpClient = new HttpClient(clientOptions.customFetch, ...[].concat(clientOptions.middleware)); | ||
} | ||
@@ -100,0 +82,0 @@ this.httpClient = httpClient; |
@@ -11,2 +11,4 @@ /** | ||
*/ | ||
import { HttpClient } from "@microsoft/kiota-http-fetchlibrary"; | ||
import { GraphClientError } from "./GraphClientError"; | ||
@@ -17,8 +19,5 @@ import { GraphError } from "./GraphError"; | ||
import { GraphResponseHandler } from "./GraphResponseHandler"; | ||
import { HTTPClient } from "./HTTPClient"; | ||
import { ClientOptions } from "./IClientOptions"; | ||
import { Context } from "./IContext"; | ||
import { FetchOptions } from "./IFetchOptions"; | ||
import { GraphRequestCallback } from "./IGraphRequestCallback"; | ||
import { MiddlewareControl } from "./middleware/MiddlewareControl"; | ||
import { MiddlewareOptions } from "./middleware/options/IMiddlewareOptions"; | ||
@@ -66,4 +65,5 @@ import { RequestMethod } from "./RequestMethod"; | ||
*/ | ||
private httpClient: HTTPClient; | ||
private httpClient: HttpClient; | ||
/** | ||
@@ -97,3 +97,3 @@ * @private | ||
*/ | ||
private _middlewareOptions: MiddlewareOptions[]; | ||
private _middlewareOptions: MiddlewareOptions[]; | ||
@@ -114,3 +114,3 @@ /** | ||
*/ | ||
public constructor(httpClient: HTTPClient, config: ClientOptions, path: string) { | ||
public constructor(httpClient: HttpClient, config: ClientOptions, path: string) { | ||
this.httpClient = httpClient; | ||
@@ -373,14 +373,7 @@ this.config = config; | ||
let rawResponse: Response; | ||
const middlewareControl = new MiddlewareControl(this._middlewareOptions); | ||
this.updateRequestOptions(options); | ||
const customHosts = this.config?.customHosts; | ||
try { | ||
const context: Context = await this.httpClient.sendRequest({ | ||
request, | ||
options, | ||
middlewareControl, | ||
customHosts, | ||
}); | ||
const rawResponse = await this.httpClient.executeFetch(request as string, options); | ||
rawResponse = context.response; | ||
const response: any = await GraphResponseHandler.getResponse(rawResponse, this._responseType, callback); | ||
@@ -476,3 +469,2 @@ return response; | ||
} | ||
/** | ||
@@ -479,0 +471,0 @@ * @public |
@@ -11,2 +11,4 @@ /** | ||
*/ | ||
import { BaseBearerTokenAuthenticationProvider } from "@microsoft/kiota-abstractions"; | ||
import { GRAPH_URLS } from "./Constants"; | ||
@@ -125,1 +127,14 @@ import { GraphClientError } from "./GraphClientError"; | ||
}; | ||
/** | ||
* | ||
* @param customHosts | ||
* @returns | ||
*/ | ||
export const updateAndReturnAllAllowedHosts = (authProvider: BaseBearerTokenAuthenticationProvider, customHosts: Set<string>): Set<string> => { | ||
const hostsValidator = authProvider.accessTokenProvider.getAllowedHostsValidator(); | ||
const allowedHosts = customHosts ? new Set([...customHosts, ...hostsValidator.getAllowedHosts()]) : new Set(hostsValidator.getAllowedHosts()); | ||
const hostSetWithGraphandCustomHosts = customHosts ? new Set([...allowedHosts, ...GRAPH_URLS, ...customHosts]) : new Set([...allowedHosts, ...GRAPH_URLS]); | ||
hostsValidator.setAllowedHosts(hostSetWithGraphandCustomHosts); | ||
return hostSetWithGraphandCustomHosts; | ||
}; |
@@ -8,5 +8,6 @@ /** | ||
import { AuthenticationProvider } from "./IAuthenticationProvider"; | ||
import { BaseBearerTokenAuthenticationProvider } from "@microsoft/kiota-abstractions"; | ||
import { Middleware } from "@microsoft/kiota-http-fetchlibrary"; | ||
import { FetchOptions } from "./IFetchOptions"; | ||
import { Middleware } from "./middleware/IMiddleware"; | ||
@@ -26,3 +27,3 @@ /** | ||
export interface ClientOptions { | ||
authProvider?: AuthenticationProvider; | ||
authProvider?: BaseBearerTokenAuthenticationProvider; | ||
baseUrl?: string; | ||
@@ -33,2 +34,3 @@ debugLogging?: boolean; | ||
middleware?: Middleware | Middleware[]; | ||
customFetch?: (input: string, init?: RequestInit) => Promise<Response>; | ||
/** | ||
@@ -35,0 +37,0 @@ * Example - If URL is "https://test_host/v1.0", then set property "customHosts" as "customHosts: Set<string>(["test_host"])" |
@@ -7,5 +7,6 @@ /** | ||
*/ | ||
// eslint-disable-next-line @typescript-eslint/triple-slash-reference | ||
/// <reference path= "./../shims.d.ts" /> | ||
export { BaseBearerTokenAuthenticationProvider, AccessTokenProvider, RequestOption } from "@microsoft/kiota-abstractions"; | ||
export { RetryHandler, RedirectHandler, TelemetryHandler, RedirectHandlerOptionKey, RetryHandlerOptions, HttpClient, RedirectHandlerOptions, TelemetryHandlerOptions, TelemetryHandlerOptionsKey, RetryHandlerOptionKey } from "@microsoft/kiota-http-fetchlibrary"; | ||
@@ -15,14 +16,4 @@ export { BatchRequestBody, RequestData, BatchRequestContent, BatchRequestData, BatchRequestStep } from "./content/BatchRequestContent"; | ||
export { AuthenticationHandler } from "./middleware/AuthenticationHandler"; | ||
export { HTTPMessageHandler } from "./middleware/HTTPMessageHandler"; | ||
export { Middleware } from "./middleware/IMiddleware"; | ||
export { RetryHandler } from "./middleware/RetryHandler"; | ||
export { RedirectHandler } from "./middleware/RedirectHandler"; | ||
export { TelemetryHandler } from "./middleware/TelemetryHandler"; | ||
export { MiddlewareFactory } from "./middleware/MiddlewareFactory"; | ||
export { AuthenticationHandlerOptions } from "./middleware/options/AuthenticationHandlerOptions"; | ||
export { MiddlewareOptions } from "./middleware/options/IMiddlewareOptions"; | ||
export { RetryHandlerOptions, ShouldRetry } from "./middleware/options/RetryHandlerOptions"; | ||
export { RedirectHandlerOptions, ShouldRedirect } from "./middleware/options/RedirectHandlerOptions"; | ||
export { FeatureUsageFlag, TelemetryHandlerOptions } from "./middleware/options/TelemetryHandlerOptions"; | ||
export { FeatureUsageFlag } from "./middleware/Telemetry/TelemetryFeatureUsageFlag"; | ||
export { ChaosHandlerOptions } from "./middleware/options/ChaosHandlerOptions"; | ||
@@ -43,15 +34,22 @@ export { ChaosStrategy } from "./middleware/options/ChaosStrategy"; | ||
export { Client } from "./Client"; | ||
export { CustomAuthenticationProvider } from "./CustomAuthenticationProvider"; | ||
export { GraphError } from "./GraphError"; | ||
export { GraphClientError } from "./GraphClientError"; | ||
export { GraphRequest, URLComponents } from "./GraphRequest"; | ||
export { AuthProvider } from "./IAuthProvider"; | ||
export { AuthenticationProvider } from "./IAuthenticationProvider"; | ||
export { AuthenticationProviderOptions } from "./IAuthenticationProviderOptions"; | ||
export { AuthProviderCallback } from "./IAuthProviderCallback"; | ||
export { ClientOptions } from "./IClientOptions"; | ||
export { Context } from "./IContext"; | ||
export { FetchOptions, NodeFetchInit } from "./IFetchOptions"; | ||
export { GraphRequestCallback } from "./IGraphRequestCallback"; | ||
export { Options } from "./IOptions"; | ||
export { ResponseType } from "./ResponseType"; | ||
export { SimpleAuthenticationProvider } from "./authentication/SimpleAuthentication/SimpleAuthenticationProvider"; | ||
export { SimpleAccessTokenProvider } from "./authentication/SimpleAuthentication/SimpleAccessTokenProvider"; | ||
export { GraphBaseClient } from "./requestBuilderUtils/GraphBaseClient"; | ||
export { GraphSDKConfig } from "./requestBuilderUtils/GraphSDKConfig"; | ||
export { coreSdkVersionValue, getGraphTelemetryCallback, CORE_PRODUCT_NAME, graphTelemetryCallback } from "./middleware/Telemetry/TelemetryUtil"; | ||
export { GraphTelemetryConfig } from "./middleware/Telemetry/GraphTelemetryConfig"; | ||
export { getDefaultMiddlewareChain } from "./MiddlewareFactory"; | ||
export { GRAPH_API_VERSION, GRAPH_BASE_URL, GRAPH_URLS } from "./Constants"; | ||
export { isCustomHost, isGraphURL, updateAndReturnAllAllowedHosts } from "./GraphRequestUtil"; |
@@ -12,11 +12,4 @@ /** | ||
import { isCustomHost, isGraphURL } from "../GraphRequestUtil"; | ||
import { AuthenticationProvider } from "../IAuthenticationProvider"; | ||
import { AuthenticationProviderOptions } from "../IAuthenticationProviderOptions"; | ||
import { Context } from "../IContext"; | ||
import { Middleware } from "./IMiddleware"; | ||
import { MiddlewareControl } from "./MiddlewareControl"; | ||
import { appendRequestHeader } from "./MiddlewareUtil"; | ||
import { AuthenticationHandlerOptions } from "./options/AuthenticationHandlerOptions"; | ||
import { FeatureUsageFlag, TelemetryHandlerOptions } from "./options/TelemetryHandlerOptions"; | ||
import { BaseBearerTokenAuthenticationProvider, RequestOption } from "@microsoft/kiota-abstractions"; | ||
import { appendRequestHeader, FetchRequestInit, Middleware } from "@microsoft/kiota-http-fetchlibrary"; | ||
@@ -37,11 +30,5 @@ /** | ||
* @private | ||
* A member to hold an AuthenticationProvider instance | ||
*/ | ||
private authenticationProvider: AuthenticationProvider; | ||
/** | ||
* @private | ||
* A member to hold next middleware in the middleware chain | ||
*/ | ||
private nextMiddleware: Middleware; | ||
next: Middleware; | ||
@@ -54,5 +41,3 @@ /** | ||
*/ | ||
public constructor(authenticationProvider: AuthenticationProvider) { | ||
this.authenticationProvider = authenticationProvider; | ||
} | ||
public constructor(private authenticationProvider: BaseBearerTokenAuthenticationProvider) {} | ||
@@ -66,39 +51,18 @@ /** | ||
*/ | ||
public async execute(context: Context): Promise<void> { | ||
const url = typeof context.request === "string" ? context.request : context.request.url; | ||
if (isGraphURL(url) || (context.customHosts && isCustomHost(url, context.customHosts))) { | ||
let options: AuthenticationHandlerOptions; | ||
if (context.middlewareControl instanceof MiddlewareControl) { | ||
options = context.middlewareControl.getMiddlewareOptions(AuthenticationHandlerOptions) as AuthenticationHandlerOptions; | ||
public async execute(url: string, requestInit: RequestInit, requestOptions?: Record<string, RequestOption>): Promise<Response> { | ||
if (this.authenticationProvider.accessTokenProvider.getAllowedHostsValidator().isUrlHostValid(url)) { | ||
if (requestInit?.headers && !requestInit.headers[AuthenticationHandler.AUTHORIZATION_HEADER]) { | ||
const token: string = await this.authenticationProvider.accessTokenProvider.getAuthorizationToken(url); | ||
const bearerKey = `Bearer ${token}`; | ||
appendRequestHeader(requestInit as FetchRequestInit, AuthenticationHandler.AUTHORIZATION_HEADER, bearerKey); | ||
} | ||
let authenticationProvider: AuthenticationProvider; | ||
let authenticationProviderOptions: AuthenticationProviderOptions; | ||
if (options) { | ||
authenticationProvider = options.authenticationProvider; | ||
authenticationProviderOptions = options.authenticationProviderOptions; | ||
} | ||
if (!authenticationProvider) { | ||
authenticationProvider = this.authenticationProvider; | ||
} | ||
const token: string = await authenticationProvider.getAccessToken(authenticationProviderOptions); | ||
const bearerKey = `Bearer ${token}`; | ||
appendRequestHeader(context.request, context.options, AuthenticationHandler.AUTHORIZATION_HEADER, bearerKey); | ||
TelemetryHandlerOptions.updateFeatureUsageFlag(context, FeatureUsageFlag.AUTHENTICATION_HANDLER_ENABLED); | ||
} else { | ||
if (context.options.headers) { | ||
delete context.options.headers[AuthenticationHandler.AUTHORIZATION_HEADER]; | ||
} | ||
/** | ||
* deleting auth headers because the tasks such as LargeFileUpload use client.api() to upload to redirected url | ||
* delete the auth header and allow the request to go through with the rest of the middleware chain | ||
**/ | ||
delete requestInit.headers[AuthenticationHandler.AUTHORIZATION_HEADER]; | ||
} | ||
return await this.nextMiddleware.execute(context); | ||
return await this.next.execute(url, requestInit, requestOptions); | ||
} | ||
/** | ||
* @public | ||
* To set the next middleware in the chain | ||
* @param {Middleware} next - The middleware instance | ||
* @returns Nothing | ||
*/ | ||
public setNext(next: Middleware): void { | ||
this.nextMiddleware = next; | ||
} | ||
} |
@@ -12,6 +12,6 @@ /** | ||
import { Context } from "../IContext"; | ||
import { RequestOption } from "@microsoft/kiota-abstractions"; | ||
import { Middleware } from "@microsoft/kiota-http-fetchlibrary"; | ||
import { RequestMethod } from "../RequestMethod"; | ||
import { Middleware } from "./IMiddleware"; | ||
import { MiddlewareControl } from "./MiddlewareControl"; | ||
import { generateUUID } from "./MiddlewareUtil"; | ||
@@ -22,2 +22,3 @@ import { httpStatusCode, methodStatusCode } from "./options/ChaosHandlerData"; | ||
export const ChaosHandlerOptionKey = "ChaosHandlerOptionKey"; | ||
/** | ||
@@ -30,23 +31,5 @@ * Class representing ChaosHandler | ||
export class ChaosHandler implements Middleware { | ||
/** | ||
* A member holding options to customize the handler behavior | ||
* | ||
* @private | ||
*/ | ||
private options: ChaosHandlerOptions; | ||
next: Middleware | undefined; | ||
/** | ||
* container for the manual map that has been written by the client | ||
* | ||
* @private | ||
*/ | ||
private manualMap: Map<string, Map<string, number>>; | ||
/** | ||
* @private | ||
* A member to hold next middleware in the middleware chain | ||
*/ | ||
private nextMiddleware: Middleware; | ||
/** | ||
* @public | ||
@@ -59,5 +42,9 @@ * @constructor | ||
*/ | ||
public constructor(options: ChaosHandlerOptions = new ChaosHandlerOptions(), manualMap?: Map<string, Map<string, number>>) { | ||
this.options = options; | ||
this.manualMap = manualMap; | ||
public constructor(private chaosHandlerOptions: ChaosHandlerOptions = new ChaosHandlerOptions(), private manualMap?: Map<string, Map<string, number>>) {} | ||
execute(url: string, requestInit: RequestInit, requestOptions?: Record<string, RequestOption>): Promise<Response> { | ||
if (requestOptions && requestOptions[ChaosHandlerOptionKey]) { | ||
this.chaosHandlerOptions = requestOptions[ChaosHandlerOptionKey] as ChaosHandlerOptions; | ||
} | ||
return this.sendRequest(url, requestInit, requestOptions); | ||
} | ||
@@ -73,4 +60,4 @@ | ||
*/ | ||
private createResponseHeaders(chaosHandlerOptions: ChaosHandlerOptions, requestID: string, requestDate: string) { | ||
const responseHeader: Headers = chaosHandlerOptions.headers ? new Headers(chaosHandlerOptions.headers) : new Headers(); | ||
private createResponseHeaders(requestID: string, requestDate: string) { | ||
const responseHeader: Headers = this.chaosHandlerOptions.headers ? new Headers(this.chaosHandlerOptions.headers) : new Headers(); | ||
responseHeader.append("Cache-Control", "no-store"); | ||
@@ -83,3 +70,3 @@ responseHeader.append("request-id", requestID); | ||
if (chaosHandlerOptions.statusCode === 429) { | ||
if (this.chaosHandlerOptions.statusCode === 429) { | ||
// throttling case has to have a timeout scenario | ||
@@ -100,10 +87,10 @@ responseHeader.append("retry-after", "3"); | ||
*/ | ||
private createResponseBody(chaosHandlerOptions: ChaosHandlerOptions, requestID: string, requestDate: string) { | ||
if (chaosHandlerOptions.responseBody) { | ||
return chaosHandlerOptions.responseBody; | ||
private createResponseBody(requestID: string, requestDate: string) { | ||
if (this.chaosHandlerOptions.responseBody) { | ||
return this.chaosHandlerOptions.responseBody; | ||
} | ||
let body: any; | ||
if (chaosHandlerOptions.statusCode >= 400) { | ||
const codeMessage: string = httpStatusCode[chaosHandlerOptions.statusCode]; | ||
const errMessage: string = chaosHandlerOptions.statusMessage; | ||
if (this.chaosHandlerOptions.statusCode >= 400) { | ||
const codeMessage: string = httpStatusCode[this.chaosHandlerOptions.statusCode]; | ||
const errMessage: string = this.chaosHandlerOptions.statusMessage; | ||
@@ -132,10 +119,9 @@ body = { | ||
*/ | ||
private createResponse(chaosHandlerOptions: ChaosHandlerOptions, context: Context) { | ||
const requestURL = context.request as string; | ||
private createResponse(requestURL: string): Response { | ||
const requestID = generateUUID(); | ||
const requestDate = new Date(); | ||
const responseHeader = this.createResponseHeaders(chaosHandlerOptions, requestID, requestDate.toString()); | ||
const responseBody = this.createResponseBody(chaosHandlerOptions, requestID, requestDate.toString()); | ||
const init: any = { url: requestURL, status: chaosHandlerOptions.statusCode, statusText: chaosHandlerOptions.statusMessage, headers: responseHeader }; | ||
context.response = new Response(typeof responseBody === "string" ? responseBody : JSON.stringify(responseBody), init); | ||
const responseHeader = this.createResponseHeaders(requestID, requestDate.toString()); | ||
const responseBody = this.createResponseBody(requestID, requestDate.toString()); | ||
const init: any = { url: requestURL, status: this.chaosHandlerOptions.statusCode, statusText: this.chaosHandlerOptions.statusMessage, headers: responseHeader }; | ||
return new Response(typeof responseBody === "string" ? responseBody : JSON.stringify(responseBody), init); | ||
} | ||
@@ -150,8 +136,8 @@ | ||
*/ | ||
private async sendRequest(chaosHandlerOptions: ChaosHandlerOptions, context: Context): Promise<void> { | ||
this.setStatusCode(chaosHandlerOptions, context.request as string, context.options.method as RequestMethod); | ||
if ((chaosHandlerOptions.chaosStrategy === ChaosStrategy.MANUAL && !this.nextMiddleware) || Math.floor(Math.random() * 100) < chaosHandlerOptions.chaosPercentage) { | ||
this.createResponse(chaosHandlerOptions, context); | ||
} else if (this.nextMiddleware) { | ||
await this.nextMiddleware.execute(context); | ||
private async sendRequest(url: string, requestInit?: RequestInit, requestOptions?: Record<string, RequestOption>): Promise<Response> { | ||
this.setStatusCode(url, requestInit?.method as RequestMethod); | ||
if ((this.chaosHandlerOptions.chaosStrategy === ChaosStrategy.MANUAL && !this.next) || Math.floor(Math.random() * 100) < this.chaosHandlerOptions.chaosPercentage) { | ||
return this.createResponse(url); | ||
} else if (this.next) { | ||
await this.next.execute(url, requestInit, requestOptions); | ||
} | ||
@@ -193,5 +179,5 @@ } | ||
*/ | ||
private setStatusCode(chaosHandlerOptions: ChaosHandlerOptions, requestURL: string, requestMethod: RequestMethod) { | ||
if (chaosHandlerOptions.chaosStrategy === ChaosStrategy.MANUAL) { | ||
if (chaosHandlerOptions.statusCode === undefined) { | ||
private setStatusCode(requestURL: string, requestMethod: RequestMethod) { | ||
if (this.chaosHandlerOptions.chaosStrategy === ChaosStrategy.MANUAL) { | ||
if (this.chaosHandlerOptions.statusCode === undefined) { | ||
// manual mode with no status code, can be a global level or request level without statusCode | ||
@@ -202,3 +188,3 @@ const relativeURL: string = this.getRelativeURL(requestURL); | ||
if (this.manualMap.get(relativeURL).get(requestMethod) !== undefined) { | ||
chaosHandlerOptions.statusCode = this.manualMap.get(relativeURL).get(requestMethod); | ||
this.chaosHandlerOptions.statusCode = this.manualMap.get(relativeURL).get(requestMethod); | ||
} | ||
@@ -212,3 +198,3 @@ // else statusCode would be undefined | ||
if (this.manualMap.get(key).get(requestMethod) !== undefined) { | ||
chaosHandlerOptions.statusCode = this.manualMap.get(key).get(requestMethod); | ||
this.chaosHandlerOptions.statusCode = this.manualMap.get(key).get(requestMethod); | ||
} | ||
@@ -224,3 +210,3 @@ // else statusCode would be undefined | ||
// Handling the case of Random here | ||
chaosHandlerOptions.statusCode = this.getRandomStatusCode(requestMethod); | ||
this.chaosHandlerOptions.statusCode = this.getRandomStatusCode(requestMethod); | ||
// else statusCode would be undefined | ||
@@ -231,33 +217,3 @@ } | ||
/** | ||
* To get the options for execution of the middleware | ||
* @private | ||
* @param {Context} context - The context object | ||
* @returns options for middleware execution | ||
*/ | ||
private getOptions(context: Context): ChaosHandlerOptions { | ||
let options: ChaosHandlerOptions; | ||
if (context.middlewareControl instanceof MiddlewareControl) { | ||
options = context.middlewareControl.getMiddlewareOptions(ChaosHandlerOptions) as ChaosHandlerOptions; | ||
} | ||
if (typeof options === "undefined") { | ||
options = Object.assign(new ChaosHandlerOptions(), this.options); | ||
} | ||
return options; | ||
} | ||
/** | ||
* To execute the current middleware | ||
* @public | ||
* @async | ||
* @param {Context} context - The context object of the request | ||
* @returns A Promise that resolves to nothing | ||
*/ | ||
public async execute(context: Context): Promise<void> { | ||
const chaosHandlerOptions: ChaosHandlerOptions = this.getOptions(context); | ||
return await this.sendRequest(chaosHandlerOptions, context); | ||
} | ||
/** | ||
* @public | ||
* To set the next middleware in the chain | ||
@@ -268,4 +224,4 @@ * @param {Middleware} next - The middleware instance | ||
public setNext(next: Middleware): void { | ||
this.nextMiddleware = next; | ||
this.next = next; | ||
} | ||
} |
@@ -12,4 +12,6 @@ /** | ||
import { RequestOption } from "@microsoft/kiota-abstractions"; | ||
import { ChaosHandlerOptionKey } from "../ChaosHandler"; | ||
import { ChaosStrategy } from "./ChaosStrategy"; | ||
import { MiddlewareOptions } from "./IMiddlewareOptions"; | ||
@@ -22,3 +24,3 @@ /** | ||
*/ | ||
export class ChaosHandlerOptions implements MiddlewareOptions { | ||
export class ChaosHandlerOptions implements RequestOption { | ||
/** | ||
@@ -89,2 +91,5 @@ * Specifies the startegy used for the Testing Handler -> RANDOM/MANUAL | ||
} | ||
public getKey(): string { | ||
return ChaosHandlerOptionKey; | ||
} | ||
} |
@@ -15,2 +15,2 @@ /** | ||
export const PACKAGE_VERSION = "3.0.2"; | ||
export const PACKAGE_VERSION = "4.0.0-Preview.1"; |
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
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 not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
4
980059
3
45
313
16641
2
+ Added@microsoft/kiota-abstractions@1.0.0-preview.78(transitive)
+ Added@microsoft/kiota-http-fetchlibrary@1.0.0-preview.78(transitive)
+ Added@opentelemetry/api@1.9.0(transitive)
+ Added@std-uritemplate/std-uritemplate@2.0.1(transitive)
+ Addedtinyduration@3.3.1(transitive)
+ Addeduuid@11.0.3(transitive)
- Removed@babel/runtime@^7.12.5
- Removed@babel/runtime@7.26.0(transitive)
- Removedregenerator-runtime@0.14.1(transitive)