Add PBandGraphOauth scaffold and auth UI

This commit is contained in:
2025-12-19 05:42:29 +00:00
commit b51963f5d7
6264 changed files with 606430 additions and 0 deletions
+51
View File
@@ -0,0 +1,51 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { GraphRequest } from "./GraphRequest";
import { ClientOptions } from "./IClientOptions";
import { Options } from "./IOptions";
export declare class Client {
/**
* @private
* A member which stores the Client instance options
*/
private config;
/**
* @private
* A member which holds the HTTPClient instance
*/
private httpClient;
/**
* @public
* @static
* To create a client instance with options and initializes the default middleware chain
* @param {Options} options - The options for client instance
* @returns The Client instance
*/
static init(options: Options): 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
* @constructor
* Creates an instance of Client
* @param {ClientOptions} clientOptions - The options to instantiate the client object
*/
private constructor();
/**
* @public
* Entry point to make requests
* @param {string} path - The path string value
* @returns The graph request instance
*/
api(path: string): GraphRequest;
}
+102
View File
@@ -0,0 +1,102 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
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 () {
/**
* @private
* @constructor
* Creates an instance of Client
* @param {ClientOptions} clientOptions - The options to instantiate the client object
*/
function Client(clientOptions) {
/**
* @private
* A member which stores the Client instance options
*/
this.config = {
baseUrl: Constants_1.GRAPH_BASE_URL,
debugLogging: false,
defaultVersion: Constants_1.GRAPH_API_VERSION,
};
(0, ValidatePolyFilling_1.validatePolyFilling)();
for (var key in clientOptions) {
if (Object.prototype.hasOwnProperty.call(clientOptions, key)) {
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";
throw error;
}
else if (clientOptions.authProvider !== undefined) {
httpClient = HTTPClientFactory_1.HTTPClientFactory.createWithAuthenticationProvider(clientOptions.authProvider);
}
else if (clientOptions.middleware !== undefined) {
httpClient = new (HTTPClient_1.HTTPClient.bind.apply(HTTPClient_1.HTTPClient, 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;
}
this.httpClient = httpClient;
}
/**
* @public
* @static
* To create a client instance with options and initializes the default middleware chain
* @param {Options} options - The options for client instance
* @returns The Client instance
*/
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);
};
/**
* @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
* @param {string} path - The path string value
* @returns The graph request instance
*/
Client.prototype.api = function (path) {
return new GraphRequest_1.GraphRequest(this.httpClient, this.config, path);
};
return Client;
}());
exports.Client = Client;
//# sourceMappingURL=Client.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"Client.js","sourceRoot":"","sources":["../../src/Client.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;AAEH;;GAEG;AAEH,yCAAgE;AAChE,+EAA8E;AAC9E,+CAA8C;AAC9C,2CAA0C;AAC1C,yDAAwD;AAGxD,6DAA4D;AAE5D;IA6CC;;;;;OAKG;IACH,gBAAoB,aAA4B;QAlDhD;;;WAGG;QACK,WAAM,GAAkB;YAC/B,OAAO,EAAE,0BAAc;YACvB,YAAY,EAAE,KAAK;YACnB,cAAc,EAAE,6BAAiB;SACjC,CAAC;QA2CD,IAAA,yCAAmB,GAAE,CAAC;QACtB,KAAK,IAAM,GAAG,IAAI,aAAa,EAAE;YAChC,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,aAAa,EAAE,GAAG,CAAC,EAAE;gBAC7D,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,aAAa,CAAC,GAAG,CAAC,CAAC;aACtC;SACD;QACD,IAAI,UAAsB,CAAC;QAC3B,IAAI,aAAa,CAAC,YAAY,KAAK,SAAS,IAAI,aAAa,CAAC,UAAU,KAAK,SAAS,EAAE;YACvF,IAAM,KAAK,GAAG,IAAI,KAAK,EAAE,CAAC;YAC1B,KAAK,CAAC,IAAI,GAAG,2BAA2B,CAAC;YACzC,KAAK,CAAC,OAAO,GAAG,yIAAyI,CAAC;YAC1J,MAAM,KAAK,CAAC;SACZ;aAAM,IAAI,aAAa,CAAC,YAAY,KAAK,SAAS,EAAE;YACpD,UAAU,GAAG,qCAAiB,CAAC,gCAAgC,CAAC,aAAa,CAAC,YAAY,CAAC,CAAC;SAC5F;aAAM,IAAI,aAAa,CAAC,UAAU,KAAK,SAAS,EAAE;YAClD,UAAU,QAAO,uBAAU,YAAV,uBAAU,kCAAI,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,UAAU,CAAC,YAAC,CAAC;SACpE;aAAM;YACN,IAAM,KAAK,GAAG,IAAI,KAAK,EAAE,CAAC;YAC1B,KAAK,CAAC,IAAI,GAAG,wBAAwB,CAAC;YACtC,KAAK,CAAC,OAAO,GAAG,gIAAgI,CAAC;YACjJ,MAAM,KAAK,CAAC;SACZ;QACD,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC9B,CAAC;IA1DD;;;;;;OAMG;IACW,WAAI,GAAlB,UAAmB,OAAgB;QAClC,IAAM,aAAa,GAAkB,EAAE,CAAC;QACxC,KAAK,IAAM,CAAC,IAAI,OAAO,EAAE;YACxB,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE;gBACrD,aAAa,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,cAAc,CAAC,CAAC,CAAC,IAAI,2DAA4B,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;aACpG;SACD;QACD,OAAO,MAAM,CAAC,kBAAkB,CAAC,aAAa,CAAC,CAAC;IACjD,CAAC;IAED;;;;;;OAMG;IACW,yBAAkB,GAAhC,UAAiC,aAA4B;QAC5D,OAAO,IAAI,MAAM,CAAC,aAAa,CAAC,CAAC;IAClC,CAAC;IAkCD;;;;;OAKG;IACI,oBAAG,GAAV,UAAW,IAAY;QACtB,OAAO,IAAI,2BAAY,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IAC7D,CAAC;IACF,aAAC;AAAD,CAAC,AAtFD,IAsFC;AAtFY,wBAAM"}
+24
View File
@@ -0,0 +1,24 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module Constants
*/
/**
* @constant
* A Default API endpoint version for a request
*/
export declare const GRAPH_API_VERSION = "v1.0";
/**
* @constant
* A Default base url for a request
*/
export declare const GRAPH_BASE_URL = "https://graph.microsoft.com/";
/**
* To hold list of the service root endpoints for Microsoft Graph and Graph Explorer for each national cloud.
* Set(iterable:Object) is not supported in Internet Explorer. The consumer is recommended to use a suitable polyfill.
*/
export declare const GRAPH_URLS: Set<string>;
+28
View File
@@ -0,0 +1,28 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.GRAPH_URLS = exports.GRAPH_BASE_URL = exports.GRAPH_API_VERSION = void 0;
/**
* @module Constants
*/
/**
* @constant
* A Default API endpoint version for a request
*/
exports.GRAPH_API_VERSION = "v1.0";
/**
* @constant
* A Default base url for a request
*/
exports.GRAPH_BASE_URL = "https://graph.microsoft.com/";
/**
* To hold list of the service root endpoints for Microsoft Graph and Graph Explorer for each national cloud.
* Set(iterable:Object) is not supported in Internet Explorer. The consumer is recommended to use a suitable polyfill.
*/
exports.GRAPH_URLS = new Set(["graph.microsoft.com", "graph.microsoft.us", "dod-graph.microsoft.us", "graph.microsoft.de", "microsoftgraph.chinacloudapi.cn", "canary.graph.microsoft.com"]);
//# sourceMappingURL=Constants.js.map
@@ -0,0 +1 @@
{"version":3,"file":"Constants.js","sourceRoot":"","sources":["../../src/Constants.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEH;;GAEG;AAEH;;;GAGG;AACU,QAAA,iBAAiB,GAAG,MAAM,CAAC;AAExC;;;GAGG;AACU,QAAA,cAAc,GAAG,8BAA8B,CAAC;AAE7D;;;GAGG;AACU,QAAA,UAAU,GAAG,IAAI,GAAG,CAAS,CAAC,qBAAqB,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,iCAAiC,EAAE,4BAA4B,CAAC,CAAC,CAAC"}
@@ -0,0 +1,35 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { AuthenticationProvider } from "./IAuthenticationProvider";
import { AuthProvider } from "./IAuthProvider";
/**
* @class
* Class representing CustomAuthenticationProvider
* @extends AuthenticationProvider
*/
export declare class CustomAuthenticationProvider implements AuthenticationProvider {
/**
* @private
* A member to hold authProvider callback
*/
private provider;
/**
* @public
* @constructor
* Creates an instance of CustomAuthenticationProvider
* @param {AuthProviderCallback} provider - An authProvider function
* @returns An instance of CustomAuthenticationProvider
*/
constructor(provider: AuthProvider);
/**
* @public
* @async
* To get the access token
* @returns The promise that resolves to an access token
*/
getAccessToken(): Promise<any>;
}
@@ -0,0 +1,73 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.CustomAuthenticationProvider = void 0;
var tslib_1 = require("tslib");
/**
* @module CustomAuthenticationProvider
*/
var GraphClientError_1 = require("./GraphClientError");
/**
* @class
* Class representing CustomAuthenticationProvider
* @extends AuthenticationProvider
*/
var CustomAuthenticationProvider = /** @class */ (function () {
/**
* @public
* @constructor
* Creates an instance of CustomAuthenticationProvider
* @param {AuthProviderCallback} provider - An authProvider function
* @returns An instance of CustomAuthenticationProvider
*/
function CustomAuthenticationProvider(provider) {
this.provider = provider;
}
/**
* @public
* @async
* To get the access token
* @returns The promise that resolves to an access token
*/
CustomAuthenticationProvider.prototype.getAccessToken = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var _this = this;
return tslib_1.__generator(this, function (_a) {
return [2 /*return*/, new Promise(function (resolve, reject) {
_this.provider(function (error, accessToken) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
var invalidTokenMessage, err;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!accessToken) return [3 /*break*/, 1];
resolve(accessToken);
return [3 /*break*/, 3];
case 1:
if (!error) {
invalidTokenMessage = "Access token is undefined or empty.\
Please provide a valid token.\
For more help - https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/CustomAuthenticationProvider.md";
error = new GraphClientError_1.GraphClientError(invalidTokenMessage);
}
return [4 /*yield*/, GraphClientError_1.GraphClientError.setGraphClientError(error)];
case 2:
err = _a.sent();
reject(err);
_a.label = 3;
case 3: return [2 /*return*/];
}
});
}); });
})];
});
});
};
return CustomAuthenticationProvider;
}());
exports.CustomAuthenticationProvider = CustomAuthenticationProvider;
//# sourceMappingURL=CustomAuthenticationProvider.js.map
@@ -0,0 +1 @@
{"version":3,"file":"CustomAuthenticationProvider.js","sourceRoot":"","sources":["../../src/CustomAuthenticationProvider.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;AAEH;;GAEG;AAEH,uDAAsD;AAItD;;;;GAIG;AACH;IAOC;;;;;;OAMG;IACH,sCAAmB,QAAsB;QACxC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC1B,CAAC;IAED;;;;;OAKG;IACU,qDAAc,GAA3B;;;;gBACC,sBAAO,IAAI,OAAO,CAAC,UAAC,OAAsC,EAAE,MAA4B;wBACvF,KAAI,CAAC,QAAQ,CAAC,UAAO,KAAU,EAAE,WAA0B;;;;;6CACtD,WAAW,EAAX,wBAAW;wCACd,OAAO,CAAC,WAAW,CAAC,CAAC;;;wCAErB,IAAI,CAAC,KAAK,EAAE;4CACL,mBAAmB,GAAG;;6HAE2F,CAAC;4CACxH,KAAK,GAAG,IAAI,mCAAgB,CAAC,mBAAmB,CAAC,CAAC;yCAClD;wCACW,qBAAM,mCAAgB,CAAC,mBAAmB,CAAC,KAAK,CAAC,EAAA;;wCAAvD,GAAG,GAAG,SAAiD;wCAC7D,MAAM,CAAC,GAAG,CAAC,CAAC;;;;;6BAEb,CAAC,CAAC;oBACJ,CAAC,CAAC,EAAC;;;KACH;IACF,mCAAC;AAAD,CAAC,AA1CD,IA0CC;AA1CY,oEAA4B"}
@@ -0,0 +1,44 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module GraphClientError
*/
/**
* @class
* Create GraphClientError object to handle client-side errors
* encountered within the JavaScript Client SDK.
* Whereas GraphError Class should be used to handle errors in the response from the Graph API.
*/
export declare class GraphClientError extends Error {
/**
* @public
* A custom error. This property should set be when the error is not of instanceOf Error/GraphClientError.
* Example =
* const client = MicrosoftGraph.Client.init({
* defaultVersion: "v1.0",
* authProvider: (done) => { done({TokenError:"AccessToken cannot be null"}, "<ACCESS_TOKEN>");
* });
*/
customError?: any;
/**
* @public
* @static
* @async
* To set the GraphClientError object
* @param {any} error - The error returned encountered by the Graph JavaScript Client SDK while processing request
* @returns GraphClientError object set to the error passed
*/
static setGraphClientError(error: any): GraphClientError;
/**
* @public
* @constructor
* Creates an instance of GraphClientError
* @param {string} message? - Error message
* @returns An instance of GraphClientError
*/
constructor(message?: string);
}
@@ -0,0 +1,56 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.GraphClientError = void 0;
var tslib_1 = require("tslib");
/**
* @module GraphClientError
*/
/**
* @class
* Create GraphClientError object to handle client-side errors
* encountered within the JavaScript Client SDK.
* Whereas GraphError Class should be used to handle errors in the response from the Graph API.
*/
var GraphClientError = /** @class */ (function (_super) {
tslib_1.__extends(GraphClientError, _super);
/**
* @public
* @constructor
* Creates an instance of GraphClientError
* @param {string} message? - Error message
* @returns An instance of GraphClientError
*/
function GraphClientError(message) {
var _this = _super.call(this, message) || this;
Object.setPrototypeOf(_this, GraphClientError.prototype);
return _this;
}
/**
* @public
* @static
* @async
* To set the GraphClientError object
* @param {any} error - The error returned encountered by the Graph JavaScript Client SDK while processing request
* @returns GraphClientError object set to the error passed
*/
GraphClientError.setGraphClientError = function (error) {
var graphClientError;
if (error instanceof Error) {
graphClientError = error;
}
else {
graphClientError = new GraphClientError();
graphClientError.customError = error;
}
return graphClientError;
};
return GraphClientError;
}(Error));
exports.GraphClientError = GraphClientError;
//# sourceMappingURL=GraphClientError.js.map
@@ -0,0 +1 @@
{"version":3,"file":"GraphClientError.js","sourceRoot":"","sources":["../../src/GraphClientError.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;AAEH;;GAEG;AAEH;;;;;GAKG;AAEH;IAAsC,4CAAK;IA+B1C;;;;;;OAMG;IACH,0BAAmB,OAAgB;QAAnC,YACC,kBAAM,OAAO,CAAC,SAEd;QADA,MAAM,CAAC,cAAc,CAAC,KAAI,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC;;IACzD,CAAC;IA7BD;;;;;;;OAOG;IACW,oCAAmB,GAAjC,UAAkC,KAAU;QAC3C,IAAI,gBAAkC,CAAC;QACvC,IAAI,KAAK,YAAY,KAAK,EAAE;YAC3B,gBAAgB,GAAG,KAAK,CAAC;SACzB;aAAM;YACN,gBAAgB,GAAG,IAAI,gBAAgB,EAAE,CAAC;YAC1C,gBAAgB,CAAC,WAAW,GAAG,KAAK,CAAC;SACrC;QACD,OAAO,gBAAgB,CAAC;IACzB,CAAC;IAaF,uBAAC;AAAD,CAAC,AA1CD,CAAsC,KAAK,GA0C1C;AA1CY,4CAAgB"}
+54
View File
@@ -0,0 +1,54 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module GraphError
*/
/**
* @class
* Class for GraphError
* @NOTE: This is NOT what is returned from the Graph
* GraphError is created from parsing JSON errors returned from the graph
* Some fields are renamed ie, "request-id" => requestId so you can use dot notation
*/
export declare class GraphError extends Error {
/**
* @public
* A member holding status code of the error
*/
statusCode: number;
/**
* @public
* A member holding code i.e name of the error
*/
code: string | null;
/**
* @public
* A member holding request-id i.e identifier of the request
*/
requestId: string | null;
/**
* @public
* A member holding processed date and time of the request
*/
date: Date;
headers?: Headers;
/**
* @public
* A member holding original error response by the graph service
*/
body: any;
/**
* @public
* @constructor
* Creates an instance of GraphError
* @param {number} [statusCode = -1] - The status code of the error
* @param {string} [message] - The message of the error
* @param {Error} [baseError] - The base error
* @returns An instance of GraphError
*/
constructor(statusCode?: number, message?: string, baseError?: Error);
}
+48
View File
@@ -0,0 +1,48 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.GraphError = void 0;
var tslib_1 = require("tslib");
/**
* @module GraphError
*/
/**
* @class
* Class for GraphError
* @NOTE: This is NOT what is returned from the Graph
* GraphError is created from parsing JSON errors returned from the graph
* Some fields are renamed ie, "request-id" => requestId so you can use dot notation
*/
var GraphError = /** @class */ (function (_super) {
tslib_1.__extends(GraphError, _super);
/**
* @public
* @constructor
* Creates an instance of GraphError
* @param {number} [statusCode = -1] - The status code of the error
* @param {string} [message] - The message of the error
* @param {Error} [baseError] - The base error
* @returns An instance of GraphError
*/
function GraphError(statusCode, message, baseError) {
if (statusCode === void 0) { statusCode = -1; }
var _this = _super.call(this, message || (baseError && baseError.message)) || this;
// 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;
}
return GraphError;
}(Error));
exports.GraphError = GraphError;
//# sourceMappingURL=GraphError.js.map
@@ -0,0 +1 @@
{"version":3,"file":"GraphError.js","sourceRoot":"","sources":["../../src/GraphError.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;AAEH;;GAEG;AAEH;;;;;;GAMG;AAEH;IAAgC,sCAAK;IAiCpC;;;;;;;;OAQG;IACH,oBAAmB,UAAe,EAAE,OAAgB,EAAE,SAAiB;QAApD,2BAAA,EAAA,cAAc,CAAC;QAAlC,YACC,kBAAM,OAAO,IAAI,CAAC,SAAS,IAAI,SAAS,CAAC,OAAO,CAAC,CAAC,SASlD;QARA,gIAAgI;QAChI,MAAM,CAAC,cAAc,CAAC,KAAI,EAAE,UAAU,CAAC,SAAS,CAAC,CAAC;QAClD,KAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,KAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,KAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,KAAI,CAAC,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC;QACvB,KAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,KAAI,CAAC,KAAK,GAAG,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,KAAI,CAAC,KAAK,CAAC;;IACvD,CAAC;IACF,iBAAC;AAAD,CAAC,AArDD,CAAgC,KAAK,GAqDpC;AArDY,gCAAU"}
@@ -0,0 +1,60 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module GraphErrorHandler
*/
import { GraphError } from "./GraphError";
import { GraphRequestCallback } from "./IGraphRequestCallback";
/**
* @class
* Class for GraphErrorHandler
*/
export declare class GraphErrorHandler {
/**
* @private
* @static
* Populates the GraphError instance with Error instance values
* @param {Error} error - The error returned by graph service or some native error
* @param {number} [statusCode] - The status code of the response
* @returns The GraphError instance
*/
private static constructError;
/**
* @private
* @static
* @async
* Populates the GraphError instance from the Error returned by graph service
* @param {GraphAPIErrorResponse} graphError - The error possibly returned by graph service or some native error
* @param {number} statusCode - The status code of the response
* @returns A promise that resolves to GraphError instance
*
* Example error for https://graph.microsoft.com/v1.0/me/events?$top=3&$search=foo
* {
* "error": {
* "code": "SearchEvents",
* "message": "The parameter $search is not currently supported on the Events resource.",
* "innerError": {
* "request-id": "b31c83fd-944c-4663-aa50-5d9ceb367e19",
* "date": "2016-11-17T18:37:45"
* }
* }
* }
*/
private static constructErrorFromResponse;
/**
* @public
* @static
* @async
* To get the GraphError object
* Reference - https://docs.microsoft.com/en-us/graph/errors
* @param {any} [error = null] - The error returned by graph service or some native error
* @param {number} [statusCode = -1] - The status code of the response
* @param {GraphRequestCallback} [callback] - The graph request callback function
* @returns A promise that resolves to GraphError instance
*/
static getError(error?: any, statusCode?: number, callback?: GraphRequestCallback, rawResponse?: Response): Promise<GraphError>;
}
@@ -0,0 +1,113 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.GraphErrorHandler = void 0;
var tslib_1 = require("tslib");
/**
* @module GraphErrorHandler
*/
var GraphError_1 = require("./GraphError");
/**
* @class
* Class for GraphErrorHandler
*/
var GraphErrorHandler = /** @class */ (function () {
function GraphErrorHandler() {
}
/**
* @private
* @static
* Populates the GraphError instance with Error instance values
* @param {Error} error - The error returned by graph service or some native error
* @param {number} [statusCode] - The status code of the response
* @returns The GraphError instance
*/
GraphErrorHandler.constructError = function (error, statusCode, rawResponse) {
var gError = new GraphError_1.GraphError(statusCode, "", error);
if (error.name !== undefined) {
gError.code = error.name;
}
gError.body = error.toString();
gError.date = new Date();
gError.headers = rawResponse === null || rawResponse === void 0 ? void 0 : rawResponse.headers;
return gError;
};
/**
* @private
* @static
* @async
* Populates the GraphError instance from the Error returned by graph service
* @param {GraphAPIErrorResponse} graphError - The error possibly returned by graph service or some native error
* @param {number} statusCode - The status code of the response
* @returns A promise that resolves to GraphError instance
*
* Example error for https://graph.microsoft.com/v1.0/me/events?$top=3&$search=foo
* {
* "error": {
* "code": "SearchEvents",
* "message": "The parameter $search is not currently supported on the Events resource.",
* "innerError": {
* "request-id": "b31c83fd-944c-4663-aa50-5d9ceb367e19",
* "date": "2016-11-17T18:37:45"
* }
* }
* }
*/
GraphErrorHandler.constructErrorFromResponse = function (graphError, statusCode, rawResponse) {
var error = graphError.error;
var gError = new GraphError_1.GraphError(statusCode, error.message);
gError.code = error.code;
if (error.innerError !== undefined) {
gError.requestId = error.innerError["request-id"];
gError.date = new Date(error.innerError.date);
}
gError.body = JSON.stringify(error);
gError.headers = rawResponse === null || rawResponse === void 0 ? void 0 : rawResponse.headers;
return gError;
};
/**
* @public
* @static
* @async
* To get the GraphError object
* Reference - https://docs.microsoft.com/en-us/graph/errors
* @param {any} [error = null] - The error returned by graph service or some native error
* @param {number} [statusCode = -1] - The status code of the response
* @param {GraphRequestCallback} [callback] - The graph request callback function
* @returns A promise that resolves to GraphError instance
*/
GraphErrorHandler.getError = function (error, statusCode, callback, rawResponse) {
if (error === void 0) { error = null; }
if (statusCode === void 0) { statusCode = -1; }
return tslib_1.__awaiter(this, void 0, void 0, function () {
var gError;
return tslib_1.__generator(this, function (_a) {
if (error && error.error) {
gError = GraphErrorHandler.constructErrorFromResponse(error, statusCode, rawResponse);
}
else if (error instanceof Error) {
gError = GraphErrorHandler.constructError(error, statusCode, rawResponse);
}
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*/];
});
});
};
return GraphErrorHandler;
}());
exports.GraphErrorHandler = GraphErrorHandler;
//# sourceMappingURL=GraphErrorHandler.js.map
@@ -0,0 +1 @@
{"version":3,"file":"GraphErrorHandler.js","sourceRoot":"","sources":["../../src/GraphErrorHandler.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;AAEH;;GAEG;AAEH,2CAA0C;AAiB1C;;;GAGG;AAEH;IAAA;IAmFA,CAAC;IAlFA;;;;;;;OAOG;IACY,gCAAc,GAA7B,UAA8B,KAAY,EAAE,UAAmB,EAAE,WAAsB;QACtF,IAAM,MAAM,GAAG,IAAI,uBAAU,CAAC,UAAU,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;QACrD,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,EAAE;YAC7B,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;SACzB;QACD,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC,QAAQ,EAAE,CAAC;QAC/B,MAAM,CAAC,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC;QACzB,MAAM,CAAC,OAAO,GAAG,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,OAAO,CAAC;QACtC,OAAO,MAAM,CAAC;IACf,CAAC;IAED;;;;;;;;;;;;;;;;;;;;OAoBG;IACY,4CAA0B,GAAzC,UAA0C,UAAiC,EAAE,UAAkB,EAAE,WAAsB;QACtH,IAAM,KAAK,GAAG,UAAU,CAAC,KAAK,CAAC;QAC/B,IAAM,MAAM,GAAG,IAAI,uBAAU,CAAC,UAAU,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;QACzD,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;QACzB,IAAI,KAAK,CAAC,UAAU,KAAK,SAAS,EAAE;YACnC,MAAM,CAAC,SAAS,GAAG,KAAK,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC;YAClD,MAAM,CAAC,IAAI,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;SAC9C;QAED,MAAM,CAAC,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;QACpC,MAAM,CAAC,OAAO,GAAG,WAAW,aAAX,WAAW,uBAAX,WAAW,CAAE,OAAO,CAAC;QAEtC,OAAO,MAAM,CAAC;IACf,CAAC;IAED;;;;;;;;;;OAUG;IACiB,0BAAQ,GAA5B,UAA6B,KAAiB,EAAE,UAAe,EAAE,QAA+B,EAAE,WAAsB;QAA3F,sBAAA,EAAA,YAAiB;QAAE,2BAAA,EAAA,cAAc,CAAC;;;;gBAE9D,IAAI,KAAK,IAAI,KAAK,CAAC,KAAK,EAAE;oBACzB,MAAM,GAAG,iBAAiB,CAAC,0BAA0B,CAAC,KAAK,EAAE,UAAU,EAAE,WAAW,CAAC,CAAC;iBACtF;qBAAM,IAAI,KAAK,YAAY,KAAK,EAAE;oBAClC,MAAM,GAAG,iBAAiB,CAAC,cAAc,CAAC,KAAK,EAAE,UAAU,EAAE,WAAW,CAAC,CAAC;iBAC1E;qBAAM;oBACN,MAAM,GAAG,IAAI,uBAAU,CAAC,UAAU,CAAC,CAAC;oBACpC,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC,CAAC,4FAA4F;iBACjH;gBACD,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;oBACnC,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;iBACvB;qBAAM;oBACN,sBAAO,MAAM,EAAC;iBACd;;;;KACD;IACF,wBAAC;AAAD,CAAC,AAnFD,IAmFC;AAnFY,8CAAiB"}
@@ -0,0 +1,380 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { HTTPClient } from "./HTTPClient";
import { ClientOptions } from "./IClientOptions";
import { GraphRequestCallback } from "./IGraphRequestCallback";
import { MiddlewareOptions } from "./middleware/options/IMiddlewareOptions";
import { ResponseType } from "./ResponseType";
/**
* @interface
* Signature to representing key value pairs
* @property {[key: string] : string | number} - The Key value pair
*/
interface KeyValuePairObjectStringNumber {
[key: string]: string | number;
}
/**
* @interface
* Signature to define URL components
* @template http://graph.microsoft.com/VERSION/PATH?QUERYSTRING&OTHER_QUERY_PARAMS
*
* @property {string} host - The host to which the request needs to be made
* @property {string} version - Version of the graph endpoint
* @property {string} [path] - The path of the resource request
* @property {KeyValuePairObjectStringNumber} oDataQueryParams - The oData Query Params
* @property {KeyValuePairObjectStringNumber} otherURLQueryParams - The other query params for a request
* @property {string[]} otherURLQueryOptions - The non key-value query parameters. Example- '/me?$whatif'
*/
export interface URLComponents {
host: string;
version: string;
path?: string;
oDataQueryParams: KeyValuePairObjectStringNumber;
otherURLQueryParams: KeyValuePairObjectStringNumber;
otherURLQueryOptions?: string[];
}
/**
* @class
* A Class representing GraphRequest
*/
export declare class GraphRequest {
/**
* @private
* A member variable to hold HTTPClient instance
*/
private httpClient;
/**
* @private
* A member variable to hold client options
*/
private config;
/**
* @private
* A member to hold URL Components data
*/
private urlComponents;
/**
* @private
* A member to hold custom header options for a request
*/
private _headers;
/**
* @private
* A member to hold custom options for a request
*/
private _options;
/**
* @private
* A member to hold the array of middleware options for a request
*/
private _middlewareOptions;
/**
* @private
* A member to hold custom response type for a request
*/
private _responseType;
/**
* @public
* @constructor
* Creates an instance of GraphRequest
* @param {HTTPClient} httpClient - The HTTPClient instance
* @param {ClientOptions} config - The options for making request
* @param {string} path - A path string
*/
constructor(httpClient: HTTPClient, config: ClientOptions, path: string);
/**
* @private
* Parses the path string and creates URLComponents out of it
* @param {string} path - The request path string
* @returns Nothing
*/
private parsePath;
/**
* @private
* Adds the query parameter as comma separated values
* @param {string} propertyName - The name of a property
* @param {string|string[]} propertyValue - The vale of a property
* @param {IArguments} additionalProperties - The additional properties
* @returns Nothing
*/
private addCsvQueryParameter;
/**
* @private
* Builds the full url from the URLComponents to make a request
* @returns The URL string that is qualified to make a request to graph endpoint
*/
private buildFullUrl;
/**
* @private
* Builds the query string from the URLComponents
* @returns The Constructed query string
*/
private createQueryString;
/**
* @private
* Parses the query parameters to set the urlComponents property of the GraphRequest object
* @param {string|KeyValuePairObjectStringNumber} queryDictionaryOrString - The query parameter
* @returns The same GraphRequest instance that is being called with
*/
private parseQueryParameter;
/**
* @private
* Parses the query parameter of string type to set the urlComponents property of the GraphRequest object
* @param {string} queryParameter - the query parameters
* returns nothing
*/
private parseQueryParamenterString;
/**
* @private
* Sets values into the urlComponents property of GraphRequest object.
* @param {string} paramKey - the query parameter key
* @param {string} paramValue - the query paramter value
* @returns nothing
*/
private setURLComponentsQueryParamater;
/**
* @private
* Check if the query parameter string has a valid key-value structure
* @param {string} queryString - the query parameter string. Example -> "name=value"
* #returns true if the query string has a valid key-value structure else false
*/
private isValidQueryKeyValuePair;
/**
* @private
* Updates the custom headers and options for a request
* @param {FetchOptions} options - The request options object
* @returns Nothing
*/
private updateRequestOptions;
/**
* @private
* @async
* Adds the custom headers and options to the request and makes the HTTPClient send request call
* @param {RequestInfo} request - The request url string or the Request object value
* @param {FetchOptions} options - The options to make a request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the response content
*/
private send;
/**
* @private
* Checks if the content-type is present in the _headers property. If not present, defaults the content-type to application/json
* @param none
* @returns nothing
*/
private setHeaderContentType;
/**
* @public
* Sets the custom header for a request
* @param {string} headerKey - A header key
* @param {string} headerValue - A header value
* @returns The same GraphRequest instance that is being called with
*/
header(headerKey: string, headerValue: string): GraphRequest;
/**
* @public
* Sets the custom headers for a request
* @param {KeyValuePairObjectStringNumber | HeadersInit} headers - The request headers
* @returns The same GraphRequest instance that is being called with
*/
headers(headers: KeyValuePairObjectStringNumber | HeadersInit): GraphRequest;
/**
* @public
* Sets the option for making a request
* @param {string} key - The key value
* @param {any} value - The value
* @returns The same GraphRequest instance that is being called with
*/
option(key: string, value: any): GraphRequest;
/**
* @public
* Sets the options for making a request
* @param {{ [key: string]: any }} options - The options key value pair
* @returns The same GraphRequest instance that is being called with
*/
options(options: {
[key: string]: any;
}): GraphRequest;
/**
* @public
* Sets the middleware options for a request
* @param {MiddlewareOptions[]} options - The array of middleware options
* @returns The same GraphRequest instance that is being called with
*/
middlewareOptions(options: MiddlewareOptions[]): GraphRequest;
/**
* @public
* Sets the api endpoint version for a request
* @param {string} version - The version value
* @returns The same GraphRequest instance that is being called with
*/
version(version: string): GraphRequest;
/**
* @public
* Sets the api endpoint version for a request
* @param {ResponseType} responseType - The response type value
* @returns The same GraphRequest instance that is being called with
*/
responseType(responseType: ResponseType): GraphRequest;
/**
* @public
* To add properties for select OData Query param
* @param {string|string[]} properties - The Properties value
* @returns The same GraphRequest instance that is being called with, after adding the properties for $select query
*/
select(properties: string | string[]): GraphRequest;
/**
* @public
* To add properties for expand OData Query param
* @param {string|string[]} properties - The Properties value
* @returns The same GraphRequest instance that is being called with, after adding the properties for $expand query
*/
expand(properties: string | string[]): GraphRequest;
/**
* @public
* To add properties for orderby OData Query param
* @param {string|string[]} properties - The Properties value
* @returns The same GraphRequest instance that is being called with, after adding the properties for $orderby query
*/
orderby(properties: string | string[]): GraphRequest;
/**
* @public
* To add query string for filter OData Query param. The request URL accepts only one $filter Odata Query option and its value is set to the most recently passed filter query string.
* @param {string} filterStr - The filter query string
* @returns The same GraphRequest instance that is being called with, after adding the $filter query
*/
filter(filterStr: string): GraphRequest;
/**
* @public
* To add criterion for search OData Query param. The request URL accepts only one $search Odata Query option and its value is set to the most recently passed search criterion string.
* @param {string} searchStr - The search criterion string
* @returns The same GraphRequest instance that is being called with, after adding the $search query criteria
*/
search(searchStr: string): GraphRequest;
/**
* @public
* To add number for top OData Query param. The request URL accepts only one $top Odata Query option and its value is set to the most recently passed number value.
* @param {number} n - The number value
* @returns The same GraphRequest instance that is being called with, after adding the number for $top query
*/
top(n: number): GraphRequest;
/**
* @public
* To add number for skip OData Query param. The request URL accepts only one $skip Odata Query option and its value is set to the most recently passed number value.
* @param {number} n - The number value
* @returns The same GraphRequest instance that is being called with, after adding the number for the $skip query
*/
skip(n: number): GraphRequest;
/**
* @public
* To add token string for skipToken OData Query param. The request URL accepts only one $skipToken Odata Query option and its value is set to the most recently passed token value.
* @param {string} token - The token value
* @returns The same GraphRequest instance that is being called with, after adding the token string for $skipToken query option
*/
skipToken(token: string): GraphRequest;
/**
* @public
* To add boolean for count OData Query param. The URL accepts only one $count Odata Query option and its value is set to the most recently passed boolean value.
* @param {boolean} isCount - The count boolean
* @returns The same GraphRequest instance that is being called with, after adding the boolean value for the $count query option
*/
count(isCount?: boolean): GraphRequest;
/**
* @public
* Appends query string to the urlComponent
* @param {string|KeyValuePairObjectStringNumber} queryDictionaryOrString - The query value
* @returns The same GraphRequest instance that is being called with, after appending the query string to the url component
*/
query(queryDictionaryOrString: string | KeyValuePairObjectStringNumber): GraphRequest;
/**
* @public
* @async
* Makes a http request with GET method
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the get response
*/
get(callback?: GraphRequestCallback): Promise<any>;
/**
* @public
* @async
* Makes a http request with POST method
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the post response
*/
post(content: any, callback?: GraphRequestCallback): Promise<any>;
/**
* @public
* @async
* Alias for Post request call
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the post response
*/
create(content: any, callback?: GraphRequestCallback): Promise<any>;
/**
* @public
* @async
* Makes http request with PUT method
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the put response
*/
put(content: any, callback?: GraphRequestCallback): Promise<any>;
/**
* @public
* @async
* Makes http request with PATCH method
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the patch response
*/
patch(content: any, callback?: GraphRequestCallback): Promise<any>;
/**
* @public
* @async
* Alias for PATCH request
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the patch response
*/
update(content: any, callback?: GraphRequestCallback): Promise<any>;
/**
* @public
* @async
* Makes http request with DELETE method
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the delete response
*/
delete(callback?: GraphRequestCallback): Promise<any>;
/**
* @public
* @async
* Alias for delete request call
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the delete response
*/
del(callback?: GraphRequestCallback): Promise<any>;
/**
* @public
* @async
* Makes a http request with GET method to read response as a stream.
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the getStream response
*/
getStream(callback?: GraphRequestCallback): Promise<any>;
/**
* @public
* @async
* Makes a http request with GET method to read response as a stream.
* @param {any} stream - The stream instance
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the putStream response
*/
putStream(stream: any, callback?: GraphRequestCallback): Promise<any>;
}
export {};
+777
View File
@@ -0,0 +1,777 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.GraphRequest = void 0;
var tslib_1 = require("tslib");
/**
* @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 () {
/**
* @public
* @constructor
* Creates an instance of GraphRequest
* @param {HTTPClient} httpClient - The HTTPClient instance
* @param {ClientOptions} config - The options for making request
* @param {string} path - A path string
*/
function GraphRequest(httpClient, config, path) {
var _this = this;
/**
* @private
* Parses the path string and creates URLComponents out of it
* @param {string} path - The request path string
* @returns Nothing
*/
this.parsePath = function (path) {
// Strips out the base of the url if they passed in
if (path.indexOf("https://") !== -1) {
path = path.replace("https://", "");
// Find where the host ends
var endOfHostStrPos = path.indexOf("/");
if (endOfHostStrPos !== -1) {
// Parse out the host
_this.urlComponents.host = "https://" + path.substring(0, endOfHostStrPos);
// Strip the host from path
path = path.substring(endOfHostStrPos + 1, path.length);
}
// Remove the following version
var endOfVersionStrPos = path.indexOf("/");
if (endOfVersionStrPos !== -1) {
// Parse out the version
_this.urlComponents.version = path.substring(0, endOfVersionStrPos);
// Strip version from path
path = path.substring(endOfVersionStrPos + 1, path.length);
}
}
// Strip out any leading "/"
if (path.charAt(0) === "/") {
path = path.substr(1);
}
var queryStrPos = path.indexOf("?");
if (queryStrPos === -1) {
// No query string
_this.urlComponents.path = path;
}
else {
_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);
}
}
};
this.httpClient = httpClient;
this.config = config;
this.urlComponents = {
host: this.config.baseUrl,
version: this.config.defaultVersion,
oDataQueryParams: {},
otherURLQueryParams: {},
otherURLQueryOptions: [],
};
this._headers = {};
this._options = {};
this._middlewareOptions = [];
this.parsePath(path);
}
/**
* @private
* Adds the query parameter as comma separated values
* @param {string} propertyName - The name of a property
* @param {string|string[]} propertyValue - The vale of a property
* @param {IArguments} additionalProperties - The additional properties
* @returns Nothing
*/
GraphRequest.prototype.addCsvQueryParameter = function (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 = [];
if (additionalProperties.length > 1 && typeof propertyValue === "string") {
allValues = Array.prototype.slice.call(additionalProperties);
}
else if (typeof propertyValue === "string") {
allValues.push(propertyValue);
}
else {
allValues = allValues.concat(propertyValue);
}
this.urlComponents.oDataQueryParams[propertyName] += allValues.join(",");
};
/**
* @private
* Builds the full url from the URLComponents to make a request
* @returns The URL string that is qualified to make a request to graph endpoint
*/
GraphRequest.prototype.buildFullUrl = function () {
var url = (0, GraphRequestUtil_1.urlJoin)([this.urlComponents.host, this.urlComponents.version, this.urlComponents.path]) + this.createQueryString();
if (this.config.debugLogging) {
console.log(url);
}
return url;
};
/**
* @private
* Builds the query string from the URLComponents
* @returns The Constructed query string
*/
GraphRequest.prototype.createQueryString = function () {
// Combining query params from oDataQueryParams and otherURLQueryParams
var urlComponents = this.urlComponents;
var query = [];
if (Object.keys(urlComponents.oDataQueryParams).length !== 0) {
for (var property in urlComponents.oDataQueryParams) {
if (Object.prototype.hasOwnProperty.call(urlComponents.oDataQueryParams, property)) {
query.push(property + "=" + urlComponents.oDataQueryParams[property]);
}
}
}
if (Object.keys(urlComponents.otherURLQueryParams).length !== 0) {
for (var property in urlComponents.otherURLQueryParams) {
if (Object.prototype.hasOwnProperty.call(urlComponents.otherURLQueryParams, property)) {
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];
query.push(str);
}
}
return query.length > 0 ? "?" + query.join("&") : "";
};
/**
* @private
* Parses the query parameters to set the urlComponents property of the GraphRequest object
* @param {string|KeyValuePairObjectStringNumber} queryDictionaryOrString - The query parameter
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.parseQueryParameter = function (queryDictionaryOrString) {
if (typeof queryDictionaryOrString === "string") {
if (queryDictionaryOrString.charAt(0) === "?") {
queryDictionaryOrString = queryDictionaryOrString.substring(1);
}
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];
this.parseQueryParamenterString(str);
}
}
else {
this.parseQueryParamenterString(queryDictionaryOrString);
}
}
else if (queryDictionaryOrString.constructor === Object) {
for (var key in queryDictionaryOrString) {
if (Object.prototype.hasOwnProperty.call(queryDictionaryOrString, key)) {
this.setURLComponentsQueryParamater(key, queryDictionaryOrString[key]);
}
}
}
return this;
};
/**
* @private
* Parses the query parameter of string type to set the urlComponents property of the GraphRequest object
* @param {string} queryParameter - the query parameters
* returns nothing
*/
GraphRequest.prototype.parseQueryParamenterString = function (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);
this.setURLComponentsQueryParamater(paramKey, paramValue);
}
else {
/* Push values which are not of key-value structure.
Example-> Handle an invalid input->.query(test), .query($select($select=name)) and let the Graph API respond with the error in the URL*/
this.urlComponents.otherURLQueryOptions.push(queryParameter);
}
};
/**
* @private
* Sets values into the urlComponents property of GraphRequest object.
* @param {string} paramKey - the query parameter key
* @param {string} paramValue - the query paramter value
* @returns nothing
*/
GraphRequest.prototype.setURLComponentsQueryParamater = function (paramKey, paramValue) {
if (GraphRequestUtil_1.oDataQueryNames.indexOf(paramKey) !== -1) {
var currentValue = this.urlComponents.oDataQueryParams[paramKey];
var isValueAppendable = currentValue && (paramKey === "$expand" || paramKey === "$select" || paramKey === "$orderby");
this.urlComponents.oDataQueryParams[paramKey] = isValueAppendable ? currentValue + "," + paramValue : paramValue;
}
else {
this.urlComponents.otherURLQueryParams[paramKey] = paramValue;
}
};
/**
* @private
* Check if the query parameter string has a valid key-value structure
* @param {string} queryString - the query parameter string. Example -> "name=value"
* #returns true if the query string has a valid key-value structure else false
*/
GraphRequest.prototype.isValidQueryKeyValuePair = function (queryString) {
var indexofFirstEquals = queryString.indexOf("=");
if (indexofFirstEquals === -1) {
return false;
}
var indexofOpeningParanthesis = queryString.indexOf("(");
if (indexofOpeningParanthesis !== -1 && queryString.indexOf("(") < indexofFirstEquals) {
// Example -> .query($select($expand=true));
return false;
}
return true;
};
/**
* @private
* Updates the custom headers and options for a request
* @param {FetchOptions} options - The request options object
* @returns Nothing
*/
GraphRequest.prototype.updateRequestOptions = function (options) {
var optionsHeaders = tslib_1.__assign({}, options.headers);
if (this.config.fetchOptions !== undefined) {
var fetchOptions = tslib_1.__assign({}, this.config.fetchOptions);
Object.assign(options, fetchOptions);
if (typeof this.config.fetchOptions.headers !== undefined) {
options.headers = tslib_1.__assign({}, this.config.fetchOptions.headers);
}
}
Object.assign(options, this._options);
if (options.headers !== undefined) {
Object.assign(optionsHeaders, options.headers);
}
Object.assign(optionsHeaders, this._headers);
options.headers = optionsHeaders;
};
/**
* @private
* @async
* Adds the custom headers and options to the request and makes the HTTPClient send request call
* @param {RequestInfo} request - The request url string or the Request object value
* @param {FetchOptions} options - The options to make a request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the response content
*/
GraphRequest.prototype.send = function (request, options, callback) {
var _a;
return tslib_1.__awaiter(this, void 0, void 0, function () {
var rawResponse, middlewareControl, customHosts, context_1, response, error_1, statusCode, gError;
return 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, rawResponse)];
case 5:
gError = _b.sent();
throw gError;
case 6: return [2 /*return*/];
}
});
});
};
/**
* @private
* Checks if the content-type is present in the _headers property. If not present, defaults the content-type to application/json
* @param none
* @returns nothing
*/
GraphRequest.prototype.setHeaderContentType = function () {
if (!this._headers) {
this.header("Content-Type", "application/json");
return;
}
var headerKeys = Object.keys(this._headers);
for (var _i = 0, headerKeys_1 = headerKeys; _i < headerKeys_1.length; _i++) {
var headerKey = headerKeys_1[_i];
if (headerKey.toLowerCase() === "content-type") {
return;
}
}
// Default the content-type to application/json in case the content-type is not present in the header
this.header("Content-Type", "application/json");
};
/**
* @public
* Sets the custom header for a request
* @param {string} headerKey - A header key
* @param {string} headerValue - A header value
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.header = function (headerKey, headerValue) {
this._headers[headerKey] = headerValue;
return this;
};
/**
* @public
* Sets the custom headers for a request
* @param {KeyValuePairObjectStringNumber | HeadersInit} headers - The request headers
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.headers = function (headers) {
for (var key in headers) {
if (Object.prototype.hasOwnProperty.call(headers, key)) {
this._headers[key] = headers[key];
}
}
return this;
};
/**
* @public
* Sets the option for making a request
* @param {string} key - The key value
* @param {any} value - The value
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.option = function (key, value) {
this._options[key] = value;
return this;
};
/**
* @public
* Sets the options for making a request
* @param {{ [key: string]: any }} options - The options key value pair
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.options = function (options) {
for (var key in options) {
if (Object.prototype.hasOwnProperty.call(options, key)) {
this._options[key] = options[key];
}
}
return this;
};
/**
* @public
* Sets the middleware options for a request
* @param {MiddlewareOptions[]} options - The array of middleware options
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.middlewareOptions = function (options) {
this._middlewareOptions = options;
return this;
};
/**
* @public
* Sets the api endpoint version for a request
* @param {string} version - The version value
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.version = function (version) {
this.urlComponents.version = version;
return this;
};
/**
* @public
* Sets the api endpoint version for a request
* @param {ResponseType} responseType - The response type value
* @returns The same GraphRequest instance that is being called with
*/
GraphRequest.prototype.responseType = function (responseType) {
this._responseType = responseType;
return this;
};
/**
* @public
* To add properties for select OData Query param
* @param {string|string[]} properties - The Properties value
* @returns The same GraphRequest instance that is being called with, after adding the properties for $select query
*/
/*
* Accepts .select("displayName,birthday")
* and .select(["displayName", "birthday"])
* and .select("displayName", "birthday")
*
*/
GraphRequest.prototype.select = function (properties) {
this.addCsvQueryParameter("$select", properties, arguments);
return this;
};
/**
* @public
* To add properties for expand OData Query param
* @param {string|string[]} properties - The Properties value
* @returns The same GraphRequest instance that is being called with, after adding the properties for $expand query
*/
GraphRequest.prototype.expand = function (properties) {
this.addCsvQueryParameter("$expand", properties, arguments);
return this;
};
/**
* @public
* To add properties for orderby OData Query param
* @param {string|string[]} properties - The Properties value
* @returns The same GraphRequest instance that is being called with, after adding the properties for $orderby query
*/
GraphRequest.prototype.orderby = function (properties) {
this.addCsvQueryParameter("$orderby", properties, arguments);
return this;
};
/**
* @public
* To add query string for filter OData Query param. The request URL accepts only one $filter Odata Query option and its value is set to the most recently passed filter query string.
* @param {string} filterStr - The filter query string
* @returns The same GraphRequest instance that is being called with, after adding the $filter query
*/
GraphRequest.prototype.filter = function (filterStr) {
this.urlComponents.oDataQueryParams.$filter = filterStr;
return this;
};
/**
* @public
* To add criterion for search OData Query param. The request URL accepts only one $search Odata Query option and its value is set to the most recently passed search criterion string.
* @param {string} searchStr - The search criterion string
* @returns The same GraphRequest instance that is being called with, after adding the $search query criteria
*/
GraphRequest.prototype.search = function (searchStr) {
this.urlComponents.oDataQueryParams.$search = searchStr;
return this;
};
/**
* @public
* To add number for top OData Query param. The request URL accepts only one $top Odata Query option and its value is set to the most recently passed number value.
* @param {number} n - The number value
* @returns The same GraphRequest instance that is being called with, after adding the number for $top query
*/
GraphRequest.prototype.top = function (n) {
this.urlComponents.oDataQueryParams.$top = n;
return this;
};
/**
* @public
* To add number for skip OData Query param. The request URL accepts only one $skip Odata Query option and its value is set to the most recently passed number value.
* @param {number} n - The number value
* @returns The same GraphRequest instance that is being called with, after adding the number for the $skip query
*/
GraphRequest.prototype.skip = function (n) {
this.urlComponents.oDataQueryParams.$skip = n;
return this;
};
/**
* @public
* To add token string for skipToken OData Query param. The request URL accepts only one $skipToken Odata Query option and its value is set to the most recently passed token value.
* @param {string} token - The token value
* @returns The same GraphRequest instance that is being called with, after adding the token string for $skipToken query option
*/
GraphRequest.prototype.skipToken = function (token) {
this.urlComponents.oDataQueryParams.$skipToken = token;
return this;
};
/**
* @public
* To add boolean for count OData Query param. The URL accepts only one $count Odata Query option and its value is set to the most recently passed boolean value.
* @param {boolean} isCount - The count boolean
* @returns The same GraphRequest instance that is being called with, after adding the boolean value for the $count query option
*/
GraphRequest.prototype.count = function (isCount) {
if (isCount === void 0) { isCount = true; }
this.urlComponents.oDataQueryParams.$count = isCount.toString();
return this;
};
/**
* @public
* Appends query string to the urlComponent
* @param {string|KeyValuePairObjectStringNumber} queryDictionaryOrString - The query value
* @returns The same GraphRequest instance that is being called with, after appending the query string to the url component
*/
/*
* Accepts .query("displayName=xyz")
* and .select({ name: "value" })
*/
GraphRequest.prototype.query = function (queryDictionaryOrString) {
return this.parseQueryParameter(queryDictionaryOrString);
};
/**
* @public
* @async
* Makes a http request with GET method
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the get response
*/
GraphRequest.prototype.get = function (callback) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var url, options, response;
return 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];
}
});
});
};
/**
* @public
* @async
* Makes a http request with POST method
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the post response
*/
GraphRequest.prototype.post = function (content, callback) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var url, options, className;
return 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()];
}
});
});
};
/**
* @public
* @async
* Alias for Post request call
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the post response
*/
GraphRequest.prototype.create = function (content, callback) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
return 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()];
}
});
});
};
/**
* @public
* @async
* Makes http request with PUT method
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the put response
*/
GraphRequest.prototype.put = function (content, callback) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var url, options;
return 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()];
}
});
});
};
/**
* @public
* @async
* Makes http request with PATCH method
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the patch response
*/
GraphRequest.prototype.patch = function (content, callback) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var url, options;
return 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()];
}
});
});
};
/**
* @public
* @async
* Alias for PATCH request
* @param {any} content - The content that needs to be sent with the request
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the patch response
*/
GraphRequest.prototype.update = function (content, callback) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
return 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()];
}
});
});
};
/**
* @public
* @async
* Makes http request with DELETE method
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the delete response
*/
GraphRequest.prototype.delete = function (callback) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var url, options;
return 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()];
}
});
});
};
/**
* @public
* @async
* Alias for delete request call
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the delete response
*/
GraphRequest.prototype.del = function (callback) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.delete(callback)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* @public
* @async
* Makes a http request with GET method to read response as a stream.
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the getStream response
*/
GraphRequest.prototype.getStream = function (callback) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var url, options;
return 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()];
}
});
});
};
/**
* @public
* @async
* Makes a http request with GET method to read response as a stream.
* @param {any} stream - The stream instance
* @param {GraphRequestCallback} [callback] - The callback function to be called in response with async call
* @returns A promise that resolves to the putStream response
*/
GraphRequest.prototype.putStream = function (stream, callback) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var url, options;
return 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()];
}
});
});
};
return GraphRequest;
}());
exports.GraphRequest = GraphRequest;
//# sourceMappingURL=GraphRequest.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,42 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* To hold list of OData query params
*/
export declare const oDataQueryNames: string[];
/**
* To construct the URL by appending the segments with "/"
* @param {string[]} urlSegments - The array of strings
* @returns The constructed URL string
*/
export declare const urlJoin: (urlSegments: string[]) => string;
/**
* Serializes the content
* @param {any} content - The content value that needs to be serialized
* @returns The serialized content
*
* Note:
* This conversion is required due to the following reasons:
* Body parameter of Request method of isomorphic-fetch only accepts Blob, ArrayBuffer, FormData, TypedArrays string.
* Node.js platform does not support Blob, FormData. Javascript File object inherits from Blob so it is also not supported in node. Therefore content of type Blob, File, FormData will only come from browsers.
* Parallel to ArrayBuffer in javascript, node provides Buffer interface. Node's Buffer is able to send the arbitrary binary data to the server successfully for both Browser and Node platform. Whereas sending binary data via ArrayBuffer or TypedArrays was only possible using Browser. To support both Node and Browser, `serializeContent` converts TypedArrays or ArrayBuffer to `Node Buffer`.
* If the data received is in JSON format, `serializeContent` converts the JSON to string.
*/
export declare const serializeContent: (content: any) => any;
/**
* Checks if the url is one of the service root endpoints for Microsoft Graph and Graph Explorer.
* @param {string} url - The url to be verified
* @returns {boolean} - Returns true if the url is a Graph URL
*/
export declare const isGraphURL: (url: string) => boolean;
/**
* Checks if the url is for one of the custom hosts provided during client initialization
* @param {string} url - The url to be verified
* @param {Set} customHosts - The url to be verified
* @returns {boolean} - Returns true if the url is a for a custom host
*/
export declare const isCustomHost: (url: string, customHosts: Set<string>) => boolean;
@@ -0,0 +1,124 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.isCustomHost = exports.isGraphURL = exports.serializeContent = exports.urlJoin = exports.oDataQueryNames = void 0;
/**
* @module GraphRequestUtil
*/
var Constants_1 = require("./Constants");
var GraphClientError_1 = require("./GraphClientError");
/**
* To hold list of OData query params
*/
exports.oDataQueryNames = ["$select", "$expand", "$orderby", "$filter", "$top", "$skip", "$skipToken", "$count"];
/**
* To construct the URL by appending the segments with "/"
* @param {string[]} urlSegments - The array of strings
* @returns The constructed URL string
*/
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);
return parts.reduce(joiner);
};
exports.urlJoin = urlJoin;
/**
* Serializes the content
* @param {any} content - The content value that needs to be serialized
* @returns The serialized content
*
* Note:
* This conversion is required due to the following reasons:
* Body parameter of Request method of isomorphic-fetch only accepts Blob, ArrayBuffer, FormData, TypedArrays string.
* Node.js platform does not support Blob, FormData. Javascript File object inherits from Blob so it is also not supported in node. Therefore content of type Blob, File, FormData will only come from browsers.
* Parallel to ArrayBuffer in javascript, node provides Buffer interface. Node's Buffer is able to send the arbitrary binary data to the server successfully for both Browser and Node platform. Whereas sending binary data via ArrayBuffer or TypedArrays was only possible using Browser. To support both Node and Browser, `serializeContent` converts TypedArrays or ArrayBuffer to `Node Buffer`.
* If the data received is in JSON format, `serializeContent` converts the JSON to string.
*/
var serializeContent = function (content) {
var className = content && content.constructor && content.constructor.name;
if (className === "Buffer" || className === "Blob" || className === "File" || className === "FormData" || typeof content === "string") {
return content;
}
if (className === "ArrayBuffer") {
content = Buffer.from(content);
}
else if (className === "Int8Array" || className === "Int16Array" || className === "Int32Array" || className === "Uint8Array" || className === "Uint16Array" || className === "Uint32Array" || className === "Uint8ClampedArray" || className === "Float32Array" || className === "Float64Array" || className === "DataView") {
content = Buffer.from(content.buffer);
}
else {
try {
content = JSON.stringify(content);
}
catch (error) {
throw new Error("Unable to stringify the content");
}
}
return content;
};
exports.serializeContent = serializeContent;
/**
* Checks if the url is one of the service root endpoints for Microsoft Graph and Graph Explorer.
* @param {string} url - The url to be verified
* @returns {boolean} - Returns true if the url is a Graph URL
*/
var isGraphURL = function (url) {
return isValidEndpoint(url);
};
exports.isGraphURL = isGraphURL;
/**
* Checks if the url is for one of the custom hosts provided during client initialization
* @param {string} url - The url to be verified
* @param {Set} customHosts - The url to be verified
* @returns {boolean} - Returns true if the url is a for a custom host
*/
var isCustomHost = function (url, customHosts) {
customHosts.forEach(function (host) { return isCustomHostValid(host); });
return isValidEndpoint(url, customHosts);
};
exports.isCustomHost = isCustomHost;
/**
* Checks if the url is for one of the provided hosts.
* @param {string} url - The url to be verified
* @param {Set<string>} allowedHosts - A set of hosts.
* @returns {boolean} - Returns true is for one of the provided endpoints.
*/
var isValidEndpoint = function (url, allowedHosts) {
if (allowedHosts === void 0) { allowedHosts = Constants_1.GRAPH_URLS; }
// Valid Graph URL pattern - https://graph.microsoft.com/{version}/{resource}?{query-parameters}
// Valid Graph URL example - https://graph.microsoft.com/v1.0/
url = url.toLowerCase();
if (url.indexOf("https://") !== -1) {
url = url.replace("https://", "");
// Find where the host ends
var startofPortNoPos = url.indexOf(":");
var endOfHostStrPos = url.indexOf("/");
var hostName = "";
if (endOfHostStrPos !== -1) {
if (startofPortNoPos !== -1 && startofPortNoPos < endOfHostStrPos) {
hostName = url.substring(0, startofPortNoPos);
return allowedHosts.has(hostName);
}
// Parse out the host
hostName = url.substring(0, endOfHostStrPos);
return allowedHosts.has(hostName);
}
}
return false;
};
/**
* Throws error if the string is not a valid host/hostname and contains other url parts.
* @param {string} host - The host to be verified
*/
var isCustomHostValid = function (host) {
if (host.indexOf("/") !== -1) {
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`");
}
};
//# sourceMappingURL=GraphRequestUtil.js.map
@@ -0,0 +1 @@
{"version":3,"file":"GraphRequestUtil.js","sourceRoot":"","sources":["../../src/GraphRequestUtil.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEH;;GAEG;AACH,yCAAyC;AACzC,uDAAsD;AACtD;;GAEG;AACU,QAAA,eAAe,GAAG,CAAC,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY,EAAE,QAAQ,CAAC,CAAC;AAEtH;;;;GAIG;AACI,IAAM,OAAO,GAAG,UAAC,WAAqB;IAC5C,IAAM,eAAe,GAAG,UAAC,CAAC,IAAK,OAAA,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,EAArB,CAAqB,CAAC;IACrD,IAAM,cAAc,GAAG,UAAC,CAAC,IAAK,OAAA,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,EAArB,CAAqB,CAAC;IACpD,IAAM,MAAM,GAAG,UAAC,GAAG,EAAE,GAAG,IAAK,OAAA,CAAC,eAAe,CAAC,GAAG,CAAC,EAAE,cAAc,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAArD,CAAqD,CAAC;IACnF,IAAM,KAAK,GAAG,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACtD,OAAO,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;AAC7B,CAAC,CAAC;AANW,QAAA,OAAO,WAMlB;AAEF;;;;;;;;;;;GAWG;AAEI,IAAM,gBAAgB,GAAG,UAAC,OAAY;IAC5C,IAAM,SAAS,GAAW,OAAO,IAAI,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC;IACrF,IAAI,SAAS,KAAK,QAAQ,IAAI,SAAS,KAAK,MAAM,IAAI,SAAS,KAAK,MAAM,IAAI,SAAS,KAAK,UAAU,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;QACtI,OAAO,OAAO,CAAC;KACf;IACD,IAAI,SAAS,KAAK,aAAa,EAAE;QAChC,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;KAC/B;SAAM,IAAI,SAAS,KAAK,WAAW,IAAI,SAAS,KAAK,YAAY,IAAI,SAAS,KAAK,YAAY,IAAI,SAAS,KAAK,YAAY,IAAI,SAAS,KAAK,aAAa,IAAI,SAAS,KAAK,aAAa,IAAI,SAAS,KAAK,mBAAmB,IAAI,SAAS,KAAK,cAAc,IAAI,SAAS,KAAK,cAAc,IAAI,SAAS,KAAK,UAAU,EAAE;QAC9T,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;KACtC;SAAM;QACN,IAAI;YACH,OAAO,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;SAClC;QAAC,OAAO,KAAK,EAAE;YACf,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;SACnD;KACD;IACD,OAAO,OAAO,CAAC;AAChB,CAAC,CAAC;AAjBW,QAAA,gBAAgB,oBAiB3B;AAEF;;;;GAIG;AACI,IAAM,UAAU,GAAG,UAAC,GAAW;IACrC,OAAO,eAAe,CAAC,GAAG,CAAC,CAAC;AAC7B,CAAC,CAAC;AAFW,QAAA,UAAU,cAErB;AAEF;;;;;GAKG;AACI,IAAM,YAAY,GAAG,UAAC,GAAW,EAAE,WAAwB;IACjE,WAAW,CAAC,OAAO,CAAC,UAAC,IAAI,IAAK,OAAA,iBAAiB,CAAC,IAAI,CAAC,EAAvB,CAAuB,CAAC,CAAC;IACvD,OAAO,eAAe,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC;AAC1C,CAAC,CAAC;AAHW,QAAA,YAAY,gBAGvB;AAEF;;;;;GAKG;AACH,IAAM,eAAe,GAAG,UAAC,GAAW,EAAE,YAAsC;IAAtC,6BAAA,EAAA,eAA4B,sBAAU;IAC3E,gGAAgG;IAChG,8DAA8D;IAC9D,GAAG,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC;IAExB,IAAI,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,EAAE;QACnC,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;QAElC,2BAA2B;QAC3B,IAAM,gBAAgB,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAC1C,IAAM,eAAe,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QACzC,IAAI,QAAQ,GAAG,EAAE,CAAC;QAClB,IAAI,eAAe,KAAK,CAAC,CAAC,EAAE;YAC3B,IAAI,gBAAgB,KAAK,CAAC,CAAC,IAAI,gBAAgB,GAAG,eAAe,EAAE;gBAClE,QAAQ,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,gBAAgB,CAAC,CAAC;gBAC9C,OAAO,YAAY,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;aAClC;YACD,qBAAqB;YACrB,QAAQ,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,eAAe,CAAC,CAAC;YAC7C,OAAO,YAAY,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;SAClC;KACD;IAED,OAAO,KAAK,CAAC;AACd,CAAC,CAAC;AAEF;;;GAGG;AACH,IAAM,iBAAiB,GAAG,UAAC,IAAY;IACtC,IAAI,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE;QAC7B,MAAM,IAAI,mCAAgB,CAAC,gIAAgI,CAAC,CAAC;KAC7J;AACF,CAAC,CAAC"}
@@ -0,0 +1,62 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module GraphResponseHandler
* References - https://fetch.spec.whatwg.org/#responses
*/
import { GraphRequestCallback } from "./IGraphRequestCallback";
import { ResponseType } from "./ResponseType";
/**
* @enum
* Enum for document types
* @property {string} TEXT_HTML - The text/html content type
* @property {string} TEXT_XML - The text/xml content type
* @property {string} APPLICATION_XML - The application/xml content type
* @property {string} APPLICATION_XHTML - The application/xhml+xml content type
*/
export declare enum DocumentType {
TEXT_HTML = "text/html",
TEXT_XML = "text/xml",
APPLICATION_XML = "application/xml",
APPLICATION_XHTML = "application/xhtml+xml"
}
/**
* @class
* Class for GraphResponseHandler
*/
export declare class GraphResponseHandler {
/**
* @private
* @static
* To parse Document response
* @param {Response} rawResponse - The response object
* @param {DocumentType} type - The type to which the document needs to be parsed
* @returns A promise that resolves to a document content
*/
private static parseDocumentResponse;
/**
* @private
* @static
* @async
* To convert the native Response to response content
* @param {Response} rawResponse - The response object
* @param {ResponseType} [responseType] - The response type value
* @returns A promise that resolves to the converted response content
*/
private static convertResponse;
/**
* @public
* @static
* @async
* To get the parsed response
* @param {Response} rawResponse - The response object
* @param {ResponseType} [responseType] - The response type value
* @param {GraphRequestCallback} [callback] - The graph request callback function
* @returns The parsed response
*/
static getResponse(rawResponse: Response, responseType?: ResponseType, callback?: GraphRequestCallback): Promise<any>;
}
@@ -0,0 +1,228 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.GraphResponseHandler = exports.DocumentType = void 0;
var tslib_1 = require("tslib");
var ResponseType_1 = require("./ResponseType");
/**
* @enum
* Enum for document types
* @property {string} TEXT_HTML - The text/html content type
* @property {string} TEXT_XML - The text/xml content type
* @property {string} APPLICATION_XML - The application/xml content type
* @property {string} APPLICATION_XHTML - The application/xhml+xml content type
*/
var DocumentType;
(function (DocumentType) {
DocumentType["TEXT_HTML"] = "text/html";
DocumentType["TEXT_XML"] = "text/xml";
DocumentType["APPLICATION_XML"] = "application/xml";
DocumentType["APPLICATION_XHTML"] = "application/xhtml+xml";
})(DocumentType || (exports.DocumentType = DocumentType = {}));
/**
* @enum
* Enum for Content types
* @property {string} TEXT_PLAIN - The text/plain content type
* @property {string} APPLICATION_JSON - The application/json content type
*/
var ContentType;
(function (ContentType) {
ContentType["TEXT_PLAIN"] = "text/plain";
ContentType["APPLICATION_JSON"] = "application/json";
})(ContentType || (ContentType = {}));
/**
* @enum
* Enum for Content type regex
* @property {string} DOCUMENT - The regex to match document content types
* @property {string} IMAGE - The regex to match image content types
*/
var ContentTypeRegexStr;
(function (ContentTypeRegexStr) {
ContentTypeRegexStr["DOCUMENT"] = "^(text\\/(html|xml))|(application\\/(xml|xhtml\\+xml))$";
ContentTypeRegexStr["IMAGE"] = "^image\\/.+";
})(ContentTypeRegexStr || (ContentTypeRegexStr = {}));
/**
* @class
* Class for GraphResponseHandler
*/
var GraphResponseHandler = /** @class */ (function () {
function GraphResponseHandler() {
}
/**
* @private
* @static
* To parse Document response
* @param {Response} rawResponse - The response object
* @param {DocumentType} type - The type to which the document needs to be parsed
* @returns A promise that resolves to a document content
*/
GraphResponseHandler.parseDocumentResponse = function (rawResponse, type) {
if (typeof DOMParser !== "undefined") {
return new Promise(function (resolve, reject) {
rawResponse.text().then(function (xmlString) {
try {
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlString, type);
resolve(xmlDoc);
}
catch (error) {
reject(error);
}
});
});
}
else {
return Promise.resolve(rawResponse.body);
}
};
/**
* @private
* @static
* @async
* To convert the native Response to response content
* @param {Response} rawResponse - The response object
* @param {ResponseType} [responseType] - The response type value
* @returns A promise that resolves to the converted response content
*/
GraphResponseHandler.convertResponse = function (rawResponse, responseType) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var responseValue, contentType, _a, mimeType;
return tslib_1.__generator(this, function (_b) {
switch (_b.label) {
case 0:
if (rawResponse.status === 204) {
// NO CONTENT
return [2 /*return*/, Promise.resolve()];
}
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];
}
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:
/**
* RFC specification {@link https://tools.ietf.org/html/rfc7231#section-3.1.1.5} says:
* A sender that generates a message containing a payload body SHOULD
* generate a Content-Type header field in that message unless the
* intended media type of the enclosed representation is unknown to the
* sender. If a Content-Type header field is not present, the recipient
* MAY either assume a media type of "application/octet-stream"
* ([RFC2046], Section 4.5.1) or examine the data to determine its type.
*
* So assuming it as a stream type so returning the body.
*/
responseValue = Promise.resolve(rawResponse.body);
_b.label = 23;
case 23: return [3 /*break*/, 24];
case 24: return [2 /*return*/, responseValue];
}
});
});
};
/**
* @public
* @static
* @async
* To get the parsed response
* @param {Response} rawResponse - The response object
* @param {ResponseType} [responseType] - The response type value
* @param {GraphRequestCallback} [callback] - The graph request callback function
* @returns The parsed response
*/
GraphResponseHandler.getResponse = function (rawResponse, responseType, callback) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var response;
return 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*/];
}
});
});
};
return GraphResponseHandler;
}());
exports.GraphResponseHandler = GraphResponseHandler;
//# sourceMappingURL=GraphResponseHandler.js.map
@@ -0,0 +1 @@
{"version":3,"file":"GraphResponseHandler.js","sourceRoot":"","sources":["../../src/GraphResponseHandler.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;AAQH,+CAA8C;AAE9C;;;;;;;GAOG;AACH,IAAY,YAKX;AALD,WAAY,YAAY;IACvB,uCAAuB,CAAA;IACvB,qCAAqB,CAAA;IACrB,mDAAmC,CAAA;IACnC,2DAA2C,CAAA;AAC5C,CAAC,EALW,YAAY,4BAAZ,YAAY,QAKvB;AAED;;;;;GAKG;AAEH,IAAK,WAGJ;AAHD,WAAK,WAAW;IACf,wCAAyB,CAAA;IACzB,oDAAqC,CAAA;AACtC,CAAC,EAHI,WAAW,KAAX,WAAW,QAGf;AAED;;;;;GAKG;AACH,IAAK,mBAGJ;AAHD,WAAK,mBAAmB;IACvB,2FAAoE,CAAA;IACpE,4CAAqB,CAAA;AACtB,CAAC,EAHI,mBAAmB,KAAnB,mBAAmB,QAGvB;AAED;;;GAGG;AAEH;IAAA;IA2HA,CAAC;IA1HA;;;;;;;OAOG;IACY,0CAAqB,GAApC,UAAqC,WAAqB,EAAE,IAAkB;QAC7E,IAAI,OAAO,SAAS,KAAK,WAAW,EAAE;YACrC,OAAO,IAAI,OAAO,CAAC,UAAC,OAAO,EAAE,MAAM;gBAClC,WAAW,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,UAAC,SAAS;oBACjC,IAAI;wBACH,IAAM,MAAM,GAAG,IAAI,SAAS,EAAE,CAAC;wBAC/B,IAAM,MAAM,GAAG,MAAM,CAAC,eAAe,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;wBACvD,OAAO,CAAC,MAAM,CAAC,CAAC;qBAChB;oBAAC,OAAO,KAAK,EAAE;wBACf,MAAM,CAAC,KAAK,CAAC,CAAC;qBACd;gBACF,CAAC,CAAC,CAAC;YACJ,CAAC,CAAC,CAAC;SACH;aAAM;YACN,OAAO,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;SACzC;IACF,CAAC;IAED;;;;;;;;OAQG;IACkB,oCAAe,GAApC,UAAqC,WAAqB,EAAE,YAA2B;;;;;;wBACtF,IAAI,WAAW,CAAC,MAAM,KAAK,GAAG,EAAE;4BAC/B,aAAa;4BACb,sBAAO,OAAO,CAAC,OAAO,EAAE,EAAC;yBACzB;wBAEK,WAAW,GAAG,WAAW,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;wBACpD,KAAA,YAAY,CAAA;;iCACd,2BAAY,CAAC,WAAW,CAAC,CAAzB,wBAAwB;iCAGxB,2BAAY,CAAC,IAAI,CAAC,CAAlB,wBAAiB;iCAGjB,2BAAY,CAAC,QAAQ,CAAC,CAAtB,wBAAqB;iCAGrB,2BAAY,CAAC,IAAI,CAAC,CAAlB,wBAAiB;iCAGjB,2BAAY,CAAC,MAAM,CAAC,CAApB,wBAAmB;iCAGnB,2BAAY,CAAC,IAAI,CAAC,CAAlB,yBAAiB;;;4BAdL,qBAAM,WAAW,CAAC,WAAW,EAAE,EAAA;;wBAA/C,aAAa,GAAG,SAA+B,CAAC;wBAChD,yBAAM;4BAEU,qBAAM,WAAW,CAAC,IAAI,EAAE,EAAA;;wBAAxC,aAAa,GAAG,SAAwB,CAAC;wBACzC,yBAAM;4BAEU,qBAAM,oBAAoB,CAAC,qBAAqB,CAAC,WAAW,EAAE,YAAY,CAAC,QAAQ,CAAC,EAAA;;wBAApG,aAAa,GAAG,SAAoF,CAAC;wBACrG,yBAAM;4BAEU,qBAAM,WAAW,CAAC,IAAI,EAAE,EAAA;;wBAAxC,aAAa,GAAG,SAAwB,CAAC;wBACzC,yBAAM;4BAEU,qBAAM,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,EAAA;;wBAAvD,aAAa,GAAG,SAAuC,CAAC;wBACxD,yBAAM;6BAEU,qBAAM,WAAW,CAAC,IAAI,EAAE,EAAA;;wBAAxC,aAAa,GAAG,SAAwB,CAAC;wBACzC,yBAAM;;6BAEF,CAAA,WAAW,KAAK,IAAI,CAAA,EAApB,yBAAoB;wBACjB,QAAQ,GAAG,WAAW,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;6BACvC,IAAI,MAAM,CAAC,mBAAmB,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAvD,yBAAuD;wBAC1C,qBAAM,oBAAoB,CAAC,qBAAqB,CAAC,WAAW,EAAE,QAAwB,CAAC,EAAA;;wBAAvG,aAAa,GAAG,SAAuF,CAAC;;;6BAC9F,IAAI,MAAM,CAAC,mBAAmB,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,EAApD,yBAAoD;wBAC9D,aAAa,GAAG,WAAW,CAAC,IAAI,EAAE,CAAC;;;6BACzB,CAAA,QAAQ,KAAK,WAAW,CAAC,UAAU,CAAA,EAAnC,yBAAmC;wBAC7B,qBAAM,WAAW,CAAC,IAAI,EAAE,EAAA;;wBAAxC,aAAa,GAAG,SAAwB,CAAC;;;6BAC/B,CAAA,QAAQ,KAAK,WAAW,CAAC,gBAAgB,CAAA,EAAzC,yBAAyC;wBACnC,qBAAM,WAAW,CAAC,IAAI,EAAE,EAAA;;wBAAxC,aAAa,GAAG,SAAwB,CAAC;;;wBAEzC,aAAa,GAAG,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;;;;wBAGnD;;;;;;;;;;2BAUG;wBACH,aAAa,GAAG,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;;6BAEnD,yBAAM;6BAER,sBAAO,aAAa,EAAC;;;;KACrB;IAED;;;;;;;;;OASG;IACiB,gCAAW,GAA/B,UAAgC,WAAqB,EAAE,YAA2B,EAAE,QAA+B;;;;;;6BAC9G,CAAA,YAAY,KAAK,2BAAY,CAAC,GAAG,CAAA,EAAjC,wBAAiC;wBACpC,sBAAO,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC,EAAC;4BAEnB,qBAAM,oBAAoB,CAAC,eAAe,CAAC,WAAW,EAAE,YAAY,CAAC,EAAA;;wBAAhF,QAAQ,GAAG,SAAqE;wBACtF,IAAI,WAAW,CAAC,EAAE,EAAE;4BACnB,kBAAkB;4BAClB,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;gCACnC,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;6BACzB;iCAAM;gCACN,sBAAO,QAAQ,EAAC;6BAChB;yBACD;6BAAM;4BACN,kBAAkB;4BAClB,MAAM,QAAQ,CAAC;yBACf;;;;;;KAEF;IACF,2BAAC;AAAD,CAAC,AA3HD,IA2HC;AA3HY,oDAAoB"}
+54
View File
@@ -0,0 +1,54 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module HTTPClient
*/
import { Context } from "./IContext";
import { Middleware } from "./middleware/IMiddleware";
/**
* @class
* Class representing HTTPClient
*/
export declare class HTTPClient {
/**
* @private
* A member holding first middleware of the middleware chain
*/
private middleware;
/**
* @public
* @constructor
* Creates an instance of a HTTPClient
* @param {...Middleware} middleware - The first middleware of the middleware chain or a sequence of all the Middleware handlers
*/
constructor(...middleware: Middleware[]);
/**
* @private
* Processes the middleware parameter passed to set this.middleware property
* The calling function should validate if middleware is not undefined or not empty.
* @param {...Middleware} middleware - The middleware passed
* @returns Nothing
*/
private setMiddleware;
/**
* @private
* Processes the middleware array to construct the chain
* and sets this.middleware property to the first middleware handler of the array
* The calling function should validate if middleware is not undefined or not empty
* @param {Middleware[]} middlewareArray - The array of middleware handlers
* @returns Nothing
*/
private parseMiddleWareArray;
/**
* @public
* @async
* To send the request through the middleware chain
* @param {Context} context - The context of a request
* @returns A promise that resolves to the Context
*/
sendRequest(context: Context): Promise<Context>;
}
+100
View File
@@ -0,0 +1,100 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.HTTPClient = void 0;
var tslib_1 = require("tslib");
/**
* @class
* Class representing HTTPClient
*/
var HTTPClient = /** @class */ (function () {
/**
* @public
* @constructor
* Creates an instance of a HTTPClient
* @param {...Middleware} middleware - The first middleware of the middleware chain or a sequence of all the Middleware handlers
*/
function HTTPClient() {
var middleware = [];
for (var _i = 0; _i < arguments.length; _i++) {
middleware[_i] = arguments[_i];
}
if (!middleware || !middleware.length) {
var error = new Error();
error.name = "InvalidMiddlewareChain";
error.message = "Please provide a default middleware chain or custom middleware chain";
throw error;
}
this.setMiddleware.apply(this, middleware);
}
/**
* @private
* Processes the middleware parameter passed to set this.middleware property
* The calling function should validate if middleware is not undefined or not empty.
* @param {...Middleware} middleware - The middleware passed
* @returns Nothing
*/
HTTPClient.prototype.setMiddleware = function () {
var middleware = [];
for (var _i = 0; _i < arguments.length; _i++) {
middleware[_i] = arguments[_i];
}
if (middleware.length > 1) {
this.parseMiddleWareArray(middleware);
}
else {
this.middleware = middleware[0];
}
};
/**
* @private
* Processes the middleware array to construct the chain
* and sets this.middleware property to the first middleware handler of the array
* The calling function should validate if middleware is not undefined or not empty
* @param {Middleware[]} middlewareArray - The array of middleware handlers
* @returns Nothing
*/
HTTPClient.prototype.parseMiddleWareArray = function (middlewareArray) {
middlewareArray.forEach(function (element, index) {
if (index < middlewareArray.length - 1) {
element.setNext(middlewareArray[index + 1]);
}
});
this.middleware = middlewareArray[0];
};
/**
* @public
* @async
* To send the request through the middleware chain
* @param {Context} context - The context of a request
* @returns A promise that resolves to the Context
*/
HTTPClient.prototype.sendRequest = function (context) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var error;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
if (typeof context.request === "string" && context.options === undefined) {
error = new Error();
error.name = "InvalidRequestOptions";
error.message = "Unable to execute the middleware, Please provide valid options for a request";
throw error;
}
return [4 /*yield*/, this.middleware.execute(context)];
case 1:
_a.sent();
return [2 /*return*/, context];
}
});
});
};
return HTTPClient;
}());
exports.HTTPClient = HTTPClient;
//# sourceMappingURL=HTTPClient.js.map
@@ -0,0 +1 @@
{"version":3,"file":"HTTPClient.js","sourceRoot":"","sources":["../../src/HTTPClient.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;AASH;;;GAGG;AACH;IAOC;;;;;OAKG;IACH;QAAmB,oBAA2B;aAA3B,UAA2B,EAA3B,qBAA2B,EAA3B,IAA2B;YAA3B,+BAA2B;;QAC7C,IAAI,CAAC,UAAU,IAAI,CAAC,UAAU,CAAC,MAAM,EAAE;YACtC,IAAM,KAAK,GAAG,IAAI,KAAK,EAAE,CAAC;YAC1B,KAAK,CAAC,IAAI,GAAG,wBAAwB,CAAC;YACtC,KAAK,CAAC,OAAO,GAAG,sEAAsE,CAAC;YACvF,MAAM,KAAK,CAAC;SACZ;QACD,IAAI,CAAC,aAAa,OAAlB,IAAI,EAAkB,UAAU,EAAE;IACnC,CAAC;IAED;;;;;;OAMG;IACK,kCAAa,GAArB;QAAsB,oBAA2B;aAA3B,UAA2B,EAA3B,qBAA2B,EAA3B,IAA2B;YAA3B,+BAA2B;;QAChD,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,EAAE;YAC1B,IAAI,CAAC,oBAAoB,CAAC,UAAU,CAAC,CAAC;SACtC;aAAM;YACN,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC;SAChC;IACF,CAAC;IAED;;;;;;;OAOG;IACK,yCAAoB,GAA5B,UAA6B,eAA6B;QACzD,eAAe,CAAC,OAAO,CAAC,UAAC,OAAO,EAAE,KAAK;YACtC,IAAI,KAAK,GAAG,eAAe,CAAC,MAAM,GAAG,CAAC,EAAE;gBACvC,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC;aAC5C;QACF,CAAC,CAAC,CAAC;QACH,IAAI,CAAC,UAAU,GAAG,eAAe,CAAC,CAAC,CAAC,CAAC;IACtC,CAAC;IAED;;;;;;OAMG;IACU,gCAAW,GAAxB,UAAyB,OAAgB;;;;;;wBACxC,IAAI,OAAO,OAAO,CAAC,OAAO,KAAK,QAAQ,IAAI,OAAO,CAAC,OAAO,KAAK,SAAS,EAAE;4BACnE,KAAK,GAAG,IAAI,KAAK,EAAE,CAAC;4BAC1B,KAAK,CAAC,IAAI,GAAG,uBAAuB,CAAC;4BACrC,KAAK,CAAC,OAAO,GAAG,8EAA8E,CAAC;4BAC/F,MAAM,KAAK,CAAC;yBACZ;wBACD,qBAAM,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,OAAO,CAAC,EAAA;;wBAAtC,SAAsC,CAAC;wBACvC,sBAAO,OAAO,EAAC;;;;KACf;IACF,iBAAC;AAAD,CAAC,AAxED,IAwEC;AAxEY,gCAAU"}
@@ -0,0 +1,40 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module HTTPClientFactory
*/
import { HTTPClient } from "./HTTPClient";
import { AuthenticationProvider } from "./IAuthenticationProvider";
import { Middleware } from "./middleware/IMiddleware";
/**
* @class
* Class representing HTTPClientFactory
*/
export declare class HTTPClientFactory {
/**
* @public
* @static
* Creates HTTPClient with default middleware chain
* @param {AuthenticationProvider} authProvider - The authentication provider instance
* @returns A HTTPClient instance
*
* NOTE: These are the things that we need to remember while doing modifications in the below default pipeline.
* * HTTPMessageHandler should be the last one in the middleware pipeline, because this makes the actual network call of the request
* * TelemetryHandler should be the one prior to the last middleware in the chain, because this is the one which actually collects and appends the usage flag and placing this handler * before making the actual network call ensures that the usage of all features are recorded in the flag.
* * The best place for AuthenticationHandler is in the starting of the pipeline, because every other handler might have to work for multiple times for a request but the auth token for
* them will remain same. For example, Retry and Redirect handlers might be working multiple times for a request based on the response but their auth token would remain same.
*/
static createWithAuthenticationProvider(authProvider: AuthenticationProvider): HTTPClient;
/**
* @public
* @static
* Creates a middleware chain with the given one
* @property {...Middleware} middleware - The first middleware of the middleware chain or a sequence of all the Middleware handlers
* @returns A HTTPClient instance
*/
static createWithMiddleware(...middleware: Middleware[]): HTTPClient;
}
@@ -0,0 +1,85 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.HTTPClientFactory = void 0;
var tslib_1 = require("tslib");
/**
* @module HTTPClientFactory
*/
var HTTPClient_1 = require("./HTTPClient");
var AuthenticationHandler_1 = require("./middleware/AuthenticationHandler");
var HTTPMessageHandler_1 = require("./middleware/HTTPMessageHandler");
var RedirectHandlerOptions_1 = require("./middleware/options/RedirectHandlerOptions");
var RetryHandlerOptions_1 = require("./middleware/options/RetryHandlerOptions");
var RedirectHandler_1 = require("./middleware/RedirectHandler");
var RetryHandler_1 = require("./middleware/RetryHandler");
var TelemetryHandler_1 = require("./middleware/TelemetryHandler");
/**
* @private
* To check whether the environment is node or not
* @returns A boolean representing the environment is node or not
*/
var isNodeEnvironment = function () {
return typeof process === "object" && typeof require === "function";
};
/**
* @class
* Class representing HTTPClientFactory
*/
var HTTPClientFactory = /** @class */ (function () {
function HTTPClientFactory() {
}
/**
* @public
* @static
* Creates HTTPClient with default middleware chain
* @param {AuthenticationProvider} authProvider - The authentication provider instance
* @returns A HTTPClient instance
*
* NOTE: These are the things that we need to remember while doing modifications in the below default pipeline.
* * HTTPMessageHandler should be the last one in the middleware pipeline, because this makes the actual network call of the request
* * TelemetryHandler should be the one prior to the last middleware in the chain, because this is the one which actually collects and appends the usage flag and placing this handler * before making the actual network call ensures that the usage of all features are recorded in the flag.
* * The best place for AuthenticationHandler is in the starting of the pipeline, because every other handler might have to work for multiple times for a request but the auth token for
* them will remain same. For example, Retry and Redirect handlers might be working multiple times for a request based on the response but their auth token would remain same.
*/
HTTPClientFactory.createWithAuthenticationProvider = function (authProvider) {
var authenticationHandler = new AuthenticationHandler_1.AuthenticationHandler(authProvider);
var retryHandler = new RetryHandler_1.RetryHandler(new RetryHandlerOptions_1.RetryHandlerOptions());
var telemetryHandler = new TelemetryHandler_1.TelemetryHandler();
var httpMessageHandler = new HTTPMessageHandler_1.HTTPMessageHandler();
authenticationHandler.setNext(retryHandler);
if (isNodeEnvironment()) {
var redirectHandler = new RedirectHandler_1.RedirectHandler(new RedirectHandlerOptions_1.RedirectHandlerOptions());
retryHandler.setNext(redirectHandler);
redirectHandler.setNext(telemetryHandler);
}
else {
retryHandler.setNext(telemetryHandler);
}
telemetryHandler.setNext(httpMessageHandler);
return HTTPClientFactory.createWithMiddleware(authenticationHandler);
};
/**
* @public
* @static
* Creates a middleware chain with the given one
* @property {...Middleware} middleware - The first middleware of the middleware chain or a sequence of all the Middleware handlers
* @returns A HTTPClient instance
*/
HTTPClientFactory.createWithMiddleware = function () {
var middleware = [];
for (var _i = 0; _i < arguments.length; _i++) {
middleware[_i] = arguments[_i];
}
// Middleware should not empty or undefined. This is check is present in the HTTPClient constructor.
return new (HTTPClient_1.HTTPClient.bind.apply(HTTPClient_1.HTTPClient, tslib_1.__spreadArray([void 0], middleware, false)))();
};
return HTTPClientFactory;
}());
exports.HTTPClientFactory = HTTPClientFactory;
//# sourceMappingURL=HTTPClientFactory.js.map
@@ -0,0 +1 @@
{"version":3,"file":"HTTPClientFactory.js","sourceRoot":"","sources":["../../src/HTTPClientFactory.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;AAEH;;GAEG;AAEH,2CAA0C;AAE1C,4EAA2E;AAC3E,sEAAqE;AAErE,sFAAqF;AACrF,gFAA+E;AAC/E,gEAA+D;AAC/D,0DAAyD;AACzD,kEAAiE;AAEjE;;;;GAIG;AACH,IAAM,iBAAiB,GAAG;IACzB,OAAO,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,OAAO,KAAK,UAAU,CAAC;AACrE,CAAC,CAAC;AAEF;;;GAGG;AACH;IAAA;IA2CA,CAAC;IA1CA;;;;;;;;;;;;OAYG;IACW,kDAAgC,GAA9C,UAA+C,YAAoC;QAClF,IAAM,qBAAqB,GAAG,IAAI,6CAAqB,CAAC,YAAY,CAAC,CAAC;QACtE,IAAM,YAAY,GAAG,IAAI,2BAAY,CAAC,IAAI,yCAAmB,EAAE,CAAC,CAAC;QACjE,IAAM,gBAAgB,GAAG,IAAI,mCAAgB,EAAE,CAAC;QAChD,IAAM,kBAAkB,GAAG,IAAI,uCAAkB,EAAE,CAAC;QAEpD,qBAAqB,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;QAC5C,IAAI,iBAAiB,EAAE,EAAE;YACxB,IAAM,eAAe,GAAG,IAAI,iCAAe,CAAC,IAAI,+CAAsB,EAAE,CAAC,CAAC;YAC1E,YAAY,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;YACtC,eAAe,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC;SAC1C;aAAM;YACN,YAAY,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC;SACvC;QACD,gBAAgB,CAAC,OAAO,CAAC,kBAAkB,CAAC,CAAC;QAC7C,OAAO,iBAAiB,CAAC,oBAAoB,CAAC,qBAAqB,CAAC,CAAC;IACtE,CAAC;IAED;;;;;;OAMG;IACW,sCAAoB,GAAlC;QAAmC,oBAA2B;aAA3B,UAA2B,EAA3B,qBAA2B,EAA3B,IAA2B;YAA3B,+BAA2B;;QAC7D,oGAAoG;QACpG,YAAW,uBAAU,YAAV,uBAAU,kCAAI,UAAU,aAAE;IACtC,CAAC;IACF,wBAAC;AAAD,CAAC,AA3CD,IA2CC;AA3CY,8CAAiB"}
@@ -0,0 +1,13 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { AuthProviderCallback } from "./IAuthProviderCallback";
/**
* @interface
* Signature that holds authProvider
* @callback - The anonymous callback function which takes a single param
*/
export type AuthProvider = (done: AuthProviderCallback) => void;
@@ -0,0 +1,9 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=IAuthProvider.js.map
@@ -0,0 +1 @@
{"version":3,"file":"IAuthProvider.js","sourceRoot":"","sources":["../../src/IAuthProvider.ts"],"names":[],"mappings":";AAAA;;;;;GAKG"}
@@ -0,0 +1,12 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @interface
* Signature that defines callback for an authentication provider
* @callback - The anonymous callback function which takes two params
*/
export type AuthProviderCallback = (error: any, accessToken: string | null) => void;
@@ -0,0 +1,9 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=IAuthProviderCallback.js.map
@@ -0,0 +1 @@
{"version":3,"file":"IAuthProviderCallback.js","sourceRoot":"","sources":["../../src/IAuthProviderCallback.ts"],"names":[],"mappings":";AAAA;;;;;GAKG"}
@@ -0,0 +1,20 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { AuthenticationProviderOptions } from "./IAuthenticationProviderOptions";
/**
* @interface
* A signature representing Authentication provider
* @property {Function} getAccessToken - The function to get the access token from the authentication provider
*/
export interface AuthenticationProvider {
/**
* To get access token from the authentication provider
* @param {AuthenticationProviderOptions} [authenticationProviderOptions] - The authentication provider options instance
* @returns A promise that resolves to an access token
*/
getAccessToken: (authenticationProviderOptions?: AuthenticationProviderOptions) => Promise<string>;
}
@@ -0,0 +1,9 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=IAuthenticationProvider.js.map
@@ -0,0 +1 @@
{"version":3,"file":"IAuthenticationProvider.js","sourceRoot":"","sources":["../../src/IAuthenticationProvider.ts"],"names":[],"mappings":";AAAA;;;;;GAKG"}
@@ -0,0 +1,14 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @interface
* A signature represents the Authentication provider options
* @property {string[]} [scopes] - The array of scopes
*/
export interface AuthenticationProviderOptions {
scopes?: string[];
}
@@ -0,0 +1,9 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=IAuthenticationProviderOptions.js.map
@@ -0,0 +1 @@
{"version":3,"file":"IAuthenticationProviderOptions.js","sourceRoot":"","sources":["../../src/IAuthenticationProviderOptions.ts"],"names":[],"mappings":";AAAA;;;;;GAKG"}
@@ -0,0 +1,32 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { AuthenticationProvider } from "./IAuthenticationProvider";
import { FetchOptions } from "./IFetchOptions";
import { Middleware } from "./middleware/IMiddleware";
/**
* @interface
* Options for initializing the Graph Client
* @property {Function} [authProvider] - The authentication provider instance
* @property {string} [baseUrl] - Base url that needs to be appended to every request
* @property {boolean} [debugLogging] - The boolean to enable/disable debug logging
* @property {string} [defaultVersion] - The default version that needs to be used while making graph api request
* @property {FetchOptions} [fetchOptions] - The options for fetch request
* @property {Middleware| Middleware[]} [middleware] - The first middleware of the middleware chain or an array of the Middleware handlers
* @property {Set<string>}[customHosts] - A set of custom host names. Should contain hostnames only.
*/
export interface ClientOptions {
authProvider?: AuthenticationProvider;
baseUrl?: string;
debugLogging?: boolean;
defaultVersion?: string;
fetchOptions?: FetchOptions;
middleware?: Middleware | Middleware[];
/**
* Example - If URL is "https://test_host/v1.0", then set property "customHosts" as "customHosts: Set<string>(["test_host"])"
*/
customHosts?: Set<string>;
}
@@ -0,0 +1,9 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=IClientOptions.js.map
@@ -0,0 +1 @@
{"version":3,"file":"IClientOptions.js","sourceRoot":"","sources":["../../src/IClientOptions.ts"],"names":[],"mappings":";AAAA;;;;;GAKG"}
+27
View File
@@ -0,0 +1,27 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { FetchOptions } from "./IFetchOptions";
import { MiddlewareControl } from "./middleware/MiddlewareControl";
/**
* @interface
* @property {RequestInfo} request - The request url string or the Request instance
* @property {FetchOptions} [options] - The options for the request
* @property {Response} [response] - The response content
* @property {MiddlewareControl} [middlewareControl] - The options for the middleware chain
* @property {Set<string>}[customHosts] - A set of custom host names. Should contain hostnames only.
*
*/
export interface Context {
request: RequestInfo;
options?: FetchOptions;
response?: Response;
middlewareControl?: MiddlewareControl;
/**
* Example - If URL is "https://test_host", then set property "customHosts" as "customHosts: Set<string>(["test_host"])"
*/
customHosts?: Set<string>;
}
+9
View File
@@ -0,0 +1,9 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=IContext.js.map
@@ -0,0 +1 @@
{"version":3,"file":"IContext.js","sourceRoot":"","sources":["../../src/IContext.ts"],"names":[],"mappings":";AAAA;;;;;GAKG"}
@@ -0,0 +1,32 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @interface {@link https://github.com/bitinn/node-fetch/#options}
* Signature to define the fetch request options for node environment
* @property {number} [follow] - node-fetch option: maximum redirect count. 0 to not follow redirect
* @property {number} [compress] - node-fetch option: support gzip/deflate content encoding. false to disable
* @property {number} [size] - node-fetch option: maximum response body size in bytes. 0 to disable
* @property {any} [agent] - node-fetch option: HTTP(S).Agent instance, allows custom proxy, certificate, lookup, family etc.
* @property {number} [highWaterMark] - node-fetch option: maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.
* @property {boolean} [insecureHTTPParser] - node-fetch option: use an insecure HTTP parser that accepts invalid HTTP headers when `true`.
*/
export interface NodeFetchInit {
follow?: number;
compress?: boolean;
size?: number;
agent?: any;
highWaterMark?: number;
insecureHTTPParser?: boolean;
}
/**
* @interface
* Signature to define the fetch api options which includes both fetch standard options and also the extended node fetch options
* @extends RequestInit @see {@link https://fetch.spec.whatwg.org/#requestinit}
* @extends NodeFetchInit
*/
export interface FetchOptions extends RequestInit, NodeFetchInit {
}
@@ -0,0 +1,9 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=IFetchOptions.js.map
@@ -0,0 +1 @@
{"version":3,"file":"IFetchOptions.js","sourceRoot":"","sources":["../../src/IFetchOptions.ts"],"names":[],"mappings":";AAAA;;;;;GAKG"}
@@ -0,0 +1,13 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { GraphError } from "./GraphError";
/**
* @interface
* Signature to define the GraphRequest callback
* @callback - The anonymous callback function
*/
export type GraphRequestCallback = (error: GraphError, response: any, rawResponse?: any) => void;
@@ -0,0 +1,9 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=IGraphRequestCallback.js.map
@@ -0,0 +1 @@
{"version":3,"file":"IGraphRequestCallback.js","sourceRoot":"","sources":["../../src/IGraphRequestCallback.ts"],"names":[],"mappings":";AAAA;;;;;GAKG"}
+29
View File
@@ -0,0 +1,29 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { AuthProvider } from "./IAuthProvider";
import { FetchOptions } from "./IFetchOptions";
/**
* @interface
* Options for initializing the Graph Client
* @property {AuthProvider} authProvider - The function to get the authentication token
* @property {string} [baseUrl] - Base url that needs to be appended to every request
* @property {boolean} [debugLogging] - The boolean to enable/disable debug logging
* @property {string} [defaultVersion] - The default version that needs to be used while making graph api request
* @property {FetchOptions} [fetchOptions] - The options for fetch request
* @property {Set<string>}[customHosts] - A set of custom host names. Should contain hostnames only.
*/
export interface Options {
authProvider: AuthProvider;
baseUrl?: string;
debugLogging?: boolean;
defaultVersion?: string;
fetchOptions?: FetchOptions;
/**
* Example - If URL is "https://test_host/v1.0", then set property "customHosts" as "customHosts: Set<string>(["test_host"])"
*/
customHosts?: Set<string>;
}
+9
View File
@@ -0,0 +1,9 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=IOptions.js.map
@@ -0,0 +1 @@
{"version":3,"file":"IOptions.js","sourceRoot":"","sources":["../../src/IOptions.ts"],"names":[],"mappings":";AAAA;;;;;GAKG"}
@@ -0,0 +1,22 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @enum
* Enum for RequestMethods
* @property {string} GET - The get request type
* @property {string} PATCH - The patch request type
* @property {string} POST - The post request type
* @property {string} PUT - The put request type
* @property {string} DELETE - The delete request type
*/
export declare enum RequestMethod {
GET = "GET",
PATCH = "PATCH",
POST = "POST",
PUT = "PUT",
DELETE = "DELETE"
}
@@ -0,0 +1,27 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.RequestMethod = void 0;
/**
* @enum
* Enum for RequestMethods
* @property {string} GET - The get request type
* @property {string} PATCH - The patch request type
* @property {string} POST - The post request type
* @property {string} PUT - The put request type
* @property {string} DELETE - The delete request type
*/
var RequestMethod;
(function (RequestMethod) {
RequestMethod["GET"] = "GET";
RequestMethod["PATCH"] = "PATCH";
RequestMethod["POST"] = "POST";
RequestMethod["PUT"] = "PUT";
RequestMethod["DELETE"] = "DELETE";
})(RequestMethod || (exports.RequestMethod = RequestMethod = {}));
//# sourceMappingURL=RequestMethod.js.map
@@ -0,0 +1 @@
{"version":3,"file":"RequestMethod.js","sourceRoot":"","sources":["../../src/RequestMethod.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEH;;;;;;;;GAQG;AACH,IAAY,aAMX;AAND,WAAY,aAAa;IACxB,4BAAW,CAAA;IACX,gCAAe,CAAA;IACf,8BAAa,CAAA;IACb,4BAAW,CAAA;IACX,kCAAiB,CAAA;AAClB,CAAC,EANW,aAAa,6BAAb,aAAa,QAMxB"}
@@ -0,0 +1,25 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @enum
* Enum for ResponseType values
* @property {string} ARRAYBUFFER - To download response content as an [ArrayBuffer]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer}
* @property {string} BLOB - To download content as a [binary/blob] {@link https://developer.mozilla.org/en-US/docs/Web/API/Blob}
* @property {string} DOCUMENT - This downloads content as a document or stream
* @property {string} JSON - To download response content as a json
* @property {string} STREAM - To download response as a [stream]{@link https://nodejs.org/api/stream.html}
* @property {string} TEXT - For downloading response as a text
*/
export declare enum ResponseType {
ARRAYBUFFER = "arraybuffer",
BLOB = "blob",
DOCUMENT = "document",
JSON = "json",
RAW = "raw",
STREAM = "stream",
TEXT = "text"
}
+30
View File
@@ -0,0 +1,30 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResponseType = void 0;
/**
* @enum
* Enum for ResponseType values
* @property {string} ARRAYBUFFER - To download response content as an [ArrayBuffer]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer}
* @property {string} BLOB - To download content as a [binary/blob] {@link https://developer.mozilla.org/en-US/docs/Web/API/Blob}
* @property {string} DOCUMENT - This downloads content as a document or stream
* @property {string} JSON - To download response content as a json
* @property {string} STREAM - To download response as a [stream]{@link https://nodejs.org/api/stream.html}
* @property {string} TEXT - For downloading response as a text
*/
var ResponseType;
(function (ResponseType) {
ResponseType["ARRAYBUFFER"] = "arraybuffer";
ResponseType["BLOB"] = "blob";
ResponseType["DOCUMENT"] = "document";
ResponseType["JSON"] = "json";
ResponseType["RAW"] = "raw";
ResponseType["STREAM"] = "stream";
ResponseType["TEXT"] = "text";
})(ResponseType || (exports.ResponseType = ResponseType = {}));
//# sourceMappingURL=ResponseType.js.map
@@ -0,0 +1 @@
{"version":3,"file":"ResponseType.js","sourceRoot":"","sources":["../../src/ResponseType.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEH;;;;;;;;;GASG;AAEH,IAAY,YAQX;AARD,WAAY,YAAY;IACvB,2CAA2B,CAAA;IAC3B,6BAAa,CAAA;IACb,qCAAqB,CAAA;IACrB,6BAAa,CAAA;IACb,2BAAW,CAAA;IACX,iCAAiB,CAAA;IACjB,6BAAa,CAAA;AACd,CAAC,EARW,YAAY,4BAAZ,YAAY,QAQvB"}
@@ -0,0 +1,13 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @constant
* @function
* Validates availability of Promise and fetch in global context
* @returns The true in case the Promise and fetch available, otherwise throws error
*/
export declare const validatePolyFilling: () => boolean;
@@ -0,0 +1,35 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.validatePolyFilling = void 0;
/**
* @constant
* @function
* Validates availability of Promise and fetch in global context
* @returns The true in case the Promise and fetch available, otherwise throws error
*/
var validatePolyFilling = function () {
if (typeof Promise === "undefined" && typeof fetch === "undefined") {
var error = new Error("Library cannot function without Promise and fetch. So, please provide polyfill for them.");
error.name = "PolyFillNotAvailable";
throw error;
}
else if (typeof Promise === "undefined") {
var error = new Error("Library cannot function without Promise. So, please provide polyfill for it.");
error.name = "PolyFillNotAvailable";
throw error;
}
else if (typeof fetch === "undefined") {
var error = new Error("Library cannot function without fetch. So, please provide polyfill for it.");
error.name = "PolyFillNotAvailable";
throw error;
}
return true;
};
exports.validatePolyFilling = validatePolyFilling;
//# sourceMappingURL=ValidatePolyFilling.js.map
@@ -0,0 +1 @@
{"version":3,"file":"ValidatePolyFilling.js","sourceRoot":"","sources":["../../src/ValidatePolyFilling.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEH;;;;;GAKG;AAEI,IAAM,mBAAmB,GAAG;IAClC,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE;QACnE,IAAM,KAAK,GAAG,IAAI,KAAK,CAAC,0FAA0F,CAAC,CAAC;QACpH,KAAK,CAAC,IAAI,GAAG,sBAAsB,CAAC;QACpC,MAAM,KAAK,CAAC;KACZ;SAAM,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;QAC1C,IAAM,KAAK,GAAG,IAAI,KAAK,CAAC,8EAA8E,CAAC,CAAC;QACxG,KAAK,CAAC,IAAI,GAAG,sBAAsB,CAAC;QACpC,MAAM,KAAK,CAAC;KACZ;SAAM,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE;QACxC,IAAM,KAAK,GAAG,IAAI,KAAK,CAAC,4EAA4E,CAAC,CAAC;QACtG,KAAK,CAAC,IAAI,GAAG,sBAAsB,CAAC;QACpC,MAAM,KAAK,CAAC;KACZ;IACD,OAAO,IAAI,CAAC;AACb,CAAC,CAAC;AAfW,QAAA,mBAAmB,uBAe9B"}
+10
View File
@@ -0,0 +1,10 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module Version
*/
export declare const PACKAGE_VERSION = "3.0.7";
+16
View File
@@ -0,0 +1,16 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.PACKAGE_VERSION = void 0;
// THIS FILE IS AUTO GENERATED
// ANY CHANGES WILL BE LOST DURING BUILD
/**
* @module Version
*/
exports.PACKAGE_VERSION = "3.0.7";
//# sourceMappingURL=Version.js.map
@@ -0,0 +1 @@
{"version":3,"file":"Version.js","sourceRoot":"","sources":["../../src/Version.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEH,8BAA8B;AAC9B,wCAAwC;AAExC;;GAEG;AAEU,QAAA,eAAe,GAAG,OAAO,CAAC"}
@@ -0,0 +1,16 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { GetTokenOptions } from "@azure/identity";
import { AuthenticationProviderOptions } from "../../IAuthenticationProviderOptions";
/**
* @interface
* A signature represents the Authentication provider options for Token Credentials
* @property {getTokenOptions} [GetTokenOptions] - Defines options for TokenCredential.getToken.
*/
export interface TokenCredentialAuthenticationProviderOptions extends AuthenticationProviderOptions {
getTokenOptions?: GetTokenOptions;
}
@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=ITokenCredentialAuthenticationProviderOptions.js.map
@@ -0,0 +1 @@
{"version":3,"file":"ITokenCredentialAuthenticationProviderOptions.js","sourceRoot":"","sources":["../../../../src/authentication/azureTokenCredentials/ITokenCredentialAuthenticationProviderOptions.ts"],"names":[],"mappings":""}
@@ -0,0 +1,48 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { TokenCredential } from "@azure/identity";
import { AuthenticationProvider } from "../../IAuthenticationProvider";
import { TokenCredentialAuthenticationProviderOptions } from "./ITokenCredentialAuthenticationProviderOptions";
/**
* @module TokenCredentialAuthenticationProvider
*/
/**
* @class
* Class representing TokenCredentialAuthenticationProvider
* This feature is introduced in Version 3.0.0
* @extends AuthenticationProvider
* Reference - https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/README.md
*/
export declare class TokenCredentialAuthenticationProvider implements AuthenticationProvider {
/**
* @private
* A member holding an instance of @azure/identity TokenCredential
*/
private tokenCredential;
/**
* @private
* A member holding an instance of TokenCredentialAuthenticationProviderOptions
*/
private authenticationProviderOptions;
/**
* @public
* @constructor
* Creates an instance of TokenCredentialAuthenticationProvider
* @param {TokenCredential} tokenCredential - An instance of @azure/identity TokenCredential
* @param {TokenCredentialAuthenticationProviderOptions} authenticationProviderOptions - An instance of TokenCredentialAuthenticationProviderOptions
* @returns An instance of TokenCredentialAuthenticationProvider
*/
constructor(tokenCredential: TokenCredential, authenticationProviderOptions: TokenCredentialAuthenticationProviderOptions);
/**
* @public
* @async
* To get the access token
* @param {TokenCredentialAuthenticationProviderOptions} authenticationProviderOptions - The authentication provider options object
* @returns The promise that resolves to an access token
*/
getAccessToken(): Promise<string>;
}
@@ -0,0 +1,77 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.TokenCredentialAuthenticationProvider = void 0;
var tslib_1 = require("tslib");
var GraphClientError_1 = require("../../GraphClientError");
/**
* @module TokenCredentialAuthenticationProvider
*/
/**
* @class
* Class representing TokenCredentialAuthenticationProvider
* This feature is introduced in Version 3.0.0
* @extends AuthenticationProvider
* Reference - https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/identity/identity/README.md
*/
var TokenCredentialAuthenticationProvider = /** @class */ (function () {
/**
* @public
* @constructor
* Creates an instance of TokenCredentialAuthenticationProvider
* @param {TokenCredential} tokenCredential - An instance of @azure/identity TokenCredential
* @param {TokenCredentialAuthenticationProviderOptions} authenticationProviderOptions - An instance of TokenCredentialAuthenticationProviderOptions
* @returns An instance of TokenCredentialAuthenticationProvider
*/
function TokenCredentialAuthenticationProvider(tokenCredential, authenticationProviderOptions) {
if (!tokenCredential) {
throw new GraphClientError_1.GraphClientError("Please pass a token credential object to the TokenCredentialAuthenticationProvider class constructor");
}
if (!authenticationProviderOptions) {
throw new GraphClientError_1.GraphClientError("Please pass the TokenCredentialAuthenticationProviderOptions with scopes to the TokenCredentialAuthenticationProvider class constructor");
}
this.authenticationProviderOptions = authenticationProviderOptions;
this.tokenCredential = tokenCredential;
}
/**
* @public
* @async
* To get the access token
* @param {TokenCredentialAuthenticationProviderOptions} authenticationProviderOptions - The authentication provider options object
* @returns The promise that resolves to an access token
*/
TokenCredentialAuthenticationProvider.prototype.getAccessToken = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var scopes, error, response;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
scopes = this.authenticationProviderOptions.scopes;
error = new GraphClientError_1.GraphClientError();
if (!scopes || scopes.length === 0) {
error.name = "Empty Scopes";
error.message = "Scopes cannot be empty, Please provide scopes";
throw error;
}
return [4 /*yield*/, this.tokenCredential.getToken(scopes, this.authenticationProviderOptions.getTokenOptions)];
case 1:
response = _a.sent();
if (response) {
return [2 /*return*/, response.token];
}
error.message = "Cannot retrieve accessToken from the Token Credential object";
error.name = "Access token is undefined";
throw error;
}
});
});
};
return TokenCredentialAuthenticationProvider;
}());
exports.TokenCredentialAuthenticationProvider = TokenCredentialAuthenticationProvider;
//# sourceMappingURL=TokenCredentialAuthenticationProvider.js.map
@@ -0,0 +1 @@
{"version":3,"file":"TokenCredentialAuthenticationProvider.js","sourceRoot":"","sources":["../../../../src/authentication/azureTokenCredentials/TokenCredentialAuthenticationProvider.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;AAIH,2DAA0D;AAI1D;;GAEG;AAEH;;;;;;GAMG;AACH;IAaC;;;;;;;OAOG;IACH,+CAAmB,eAAgC,EAAE,6BAA2E;QAC/H,IAAI,CAAC,eAAe,EAAE;YACrB,MAAM,IAAI,mCAAgB,CAAC,sGAAsG,CAAC,CAAC;SACnI;QACD,IAAI,CAAC,6BAA6B,EAAE;YACnC,MAAM,IAAI,mCAAgB,CAAC,yIAAyI,CAAC,CAAC;SACtK;QACD,IAAI,CAAC,6BAA6B,GAAG,6BAA6B,CAAC;QACnE,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;IACxC,CAAC;IAED;;;;;;OAMG;IACU,8DAAc,GAA3B;;;;;;wBACO,MAAM,GAAG,IAAI,CAAC,6BAA6B,CAAC,MAAM,CAAC;wBACnD,KAAK,GAAG,IAAI,mCAAgB,EAAE,CAAC;wBAErC,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE;4BACnC,KAAK,CAAC,IAAI,GAAG,cAAc,CAAC;4BAC5B,KAAK,CAAC,OAAO,GAAG,+CAA+C,CAAC;4BAChE,MAAM,KAAK,CAAC;yBACZ;wBACgB,qBAAM,IAAI,CAAC,eAAe,CAAC,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,6BAA6B,CAAC,eAAe,CAAC,EAAA;;wBAA1G,QAAQ,GAAG,SAA+F;wBAChH,IAAI,QAAQ,EAAE;4BACb,sBAAO,QAAQ,CAAC,KAAK,EAAC;yBACtB;wBACD,KAAK,CAAC,OAAO,GAAG,8DAA8D,CAAC;wBAC/E,KAAK,CAAC,IAAI,GAAG,2BAA2B,CAAC;wBACzC,MAAM,KAAK,CAAC;;;;KACZ;IACF,4CAAC;AAAD,CAAC,AAxDD,IAwDC;AAxDY,sFAAqC"}
@@ -0,0 +1,8 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export { TokenCredentialAuthenticationProviderOptions } from "./ITokenCredentialAuthenticationProviderOptions";
export { TokenCredentialAuthenticationProvider } from "./TokenCredentialAuthenticationProvider";
@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TokenCredentialAuthenticationProvider = void 0;
var TokenCredentialAuthenticationProvider_1 = require("./TokenCredentialAuthenticationProvider");
Object.defineProperty(exports, "TokenCredentialAuthenticationProvider", { enumerable: true, get: function () { return TokenCredentialAuthenticationProvider_1.TokenCredentialAuthenticationProvider; } });
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/authentication/azureTokenCredentials/index.ts"],"names":[],"mappings":";;;AAOA,iGAAgG;AAAvF,8JAAA,qCAAqC,OAAA"}
@@ -0,0 +1,38 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module AuthCodeMSALBrowserAuthenticationProvider
*/
import { PublicClientApplication } from "@azure/msal-browser";
import { AuthenticationProvider } from "../../IAuthenticationProvider";
import { AuthCodeMSALBrowserAuthenticationProviderOptions } from "../msalOptions/MSALAuthenticationProviderOptions";
/**
* an AuthenticationProvider implementation supporting msal-browser library.
* This feature is introduced in Version 3.0.0
* @class
* @extends AuthenticationProvider
*/
export declare class AuthCodeMSALBrowserAuthenticationProvider implements AuthenticationProvider {
private publicClientApplication;
private options;
/**
* @public
* @constructor
* Creates an instance of ImplicitMSALAuthenticationProvider
* @param {PublicClientApplication} msalApplication - An instance of MSAL PublicClientApplication
* @param {AuthCodeMSALBrowserAuthenticationProviderOptions} options - An instance of MSALAuthenticationProviderOptions
* @returns An instance of ImplicitMSALAuthenticationProvider
*/
constructor(publicClientApplication: PublicClientApplication, options: AuthCodeMSALBrowserAuthenticationProviderOptions);
/**
* @public
* @async
* To get the access token for the request
* @returns The promise that resolves to an access token
*/
getAccessToken(): Promise<string>;
}
@@ -0,0 +1,96 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthCodeMSALBrowserAuthenticationProvider = void 0;
var tslib_1 = require("tslib");
/**
* @module AuthCodeMSALBrowserAuthenticationProvider
*/
var msal_browser_1 = require("@azure/msal-browser");
var GraphClientError_1 = require("../../GraphClientError");
/**
* an AuthenticationProvider implementation supporting msal-browser library.
* This feature is introduced in Version 3.0.0
* @class
* @extends AuthenticationProvider
*/
var AuthCodeMSALBrowserAuthenticationProvider = /** @class */ (function () {
/**
* @public
* @constructor
* Creates an instance of ImplicitMSALAuthenticationProvider
* @param {PublicClientApplication} msalApplication - An instance of MSAL PublicClientApplication
* @param {AuthCodeMSALBrowserAuthenticationProviderOptions} options - An instance of MSALAuthenticationProviderOptions
* @returns An instance of ImplicitMSALAuthenticationProvider
*/
function AuthCodeMSALBrowserAuthenticationProvider(publicClientApplication, options) {
this.publicClientApplication = publicClientApplication;
this.options = options;
if (!options || !publicClientApplication) {
throw new GraphClientError_1.GraphClientError("Please pass valid PublicClientApplication instance and AuthCodeMSALBrowserAuthenticationProviderOptions instance to instantiate MSALBrowserAuthenticationProvider");
}
}
/**
* @public
* @async
* To get the access token for the request
* @returns The promise that resolves to an access token
*/
AuthCodeMSALBrowserAuthenticationProvider.prototype.getAccessToken = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var scopes, account, error, response, error_1, response;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
scopes = this.options && this.options.scopes;
account = this.options && this.options.account;
error = new GraphClientError_1.GraphClientError();
if (!scopes || scopes.length === 0) {
error.name = "Empty Scopes";
error.message = "Scopes cannot be empty, Please provide scopes";
throw error;
}
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 9]);
return [4 /*yield*/, this.publicClientApplication.acquireTokenSilent({
scopes: scopes,
account: account,
})];
case 2:
response = _a.sent();
if (!response || !response.accessToken) {
error.name = "Access token is undefined";
error.message = "Received empty access token from PublicClientApplication";
throw error;
}
return [2 /*return*/, response.accessToken];
case 3:
error_1 = _a.sent();
if (!(error_1 instanceof msal_browser_1.InteractionRequiredAuthError)) return [3 /*break*/, 7];
if (!(this.options.interactionType === msal_browser_1.InteractionType.Redirect)) return [3 /*break*/, 4];
this.publicClientApplication.acquireTokenRedirect({ scopes: scopes });
return [3 /*break*/, 6];
case 4:
if (!(this.options.interactionType === msal_browser_1.InteractionType.Popup)) return [3 /*break*/, 6];
return [4 /*yield*/, this.publicClientApplication.acquireTokenPopup({ scopes: scopes })];
case 5:
response = _a.sent();
return [2 /*return*/, response.accessToken];
case 6: return [3 /*break*/, 8];
case 7: throw error_1;
case 8: return [3 /*break*/, 9];
case 9: return [2 /*return*/];
}
});
});
};
return AuthCodeMSALBrowserAuthenticationProvider;
}());
exports.AuthCodeMSALBrowserAuthenticationProvider = AuthCodeMSALBrowserAuthenticationProvider;
//# sourceMappingURL=AuthCodeMSALBrowserAuthenticationProvider.js.map
@@ -0,0 +1 @@
{"version":3,"file":"AuthCodeMSALBrowserAuthenticationProvider.js","sourceRoot":"","sources":["../../../../src/authentication/msal-browser/AuthCodeMSALBrowserAuthenticationProvider.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;AAEH;;GAEG;AAEH,oDAAmI;AAEnI,2DAA0D;AAI1D;;;;;GAKG;AACH;IACC;;;;;;;OAOG;IACH,mDAA2B,uBAAgD,EAAU,OAAyD;QAAnH,4BAAuB,GAAvB,uBAAuB,CAAyB;QAAU,YAAO,GAAP,OAAO,CAAkD;QAC7I,IAAI,CAAC,OAAO,IAAI,CAAC,uBAAuB,EAAE;YACzC,MAAM,IAAI,mCAAgB,CAAC,mKAAmK,CAAC,CAAC;SAChM;IACF,CAAC;IAED;;;;;OAKG;IACU,kEAAc,GAA3B;;;;;;wBACO,MAAM,GAAG,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC;wBAC7C,OAAO,GAAG,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;wBAC/C,KAAK,GAAG,IAAI,mCAAgB,EAAE,CAAC;wBACrC,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE;4BACnC,KAAK,CAAC,IAAI,GAAG,cAAc,CAAC;4BAC5B,KAAK,CAAC,OAAO,GAAG,+CAA+C,CAAC;4BAChE,MAAM,KAAK,CAAC;yBACZ;;;;wBAEuC,qBAAM,IAAI,CAAC,uBAAuB,CAAC,kBAAkB,CAAC;gCAC5F,MAAM,QAAA;gCACN,OAAO,SAAA;6BACP,CAAC,EAAA;;wBAHI,QAAQ,GAAyB,SAGrC;wBACF,IAAI,CAAC,QAAQ,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE;4BACvC,KAAK,CAAC,IAAI,GAAG,2BAA2B,CAAC;4BACzC,KAAK,CAAC,OAAO,GAAG,0DAA0D,CAAC;4BAC3E,MAAM,KAAK,CAAC;yBACZ;wBACD,sBAAO,QAAQ,CAAC,WAAW,EAAC;;;6BAExB,CAAA,OAAK,YAAY,2CAA4B,CAAA,EAA7C,wBAA6C;6BAC5C,CAAA,IAAI,CAAC,OAAO,CAAC,eAAe,KAAK,8BAAe,CAAC,QAAQ,CAAA,EAAzD,wBAAyD;wBAC5D,IAAI,CAAC,uBAAuB,CAAC,oBAAoB,CAAC,EAAE,MAAM,QAAA,EAAE,CAAC,CAAC;;;6BACpD,CAAA,IAAI,CAAC,OAAO,CAAC,eAAe,KAAK,8BAAe,CAAC,KAAK,CAAA,EAAtD,wBAAsD;wBACzB,qBAAM,IAAI,CAAC,uBAAuB,CAAC,iBAAiB,CAAC,EAAE,MAAM,QAAA,EAAE,CAAC,EAAA;;wBAAjG,QAAQ,GAAyB,SAAgE;wBACvG,sBAAO,QAAQ,CAAC,WAAW,EAAC;;4BAG7B,MAAM,OAAK,CAAC;;;;;;KAGd;IACF,gDAAC;AAAD,CAAC,AAtDD,IAsDC;AAtDY,8FAAyC"}
@@ -0,0 +1,7 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
export { AuthCodeMSALBrowserAuthenticationProvider } from "./AuthCodeMSALBrowserAuthenticationProvider";
@@ -0,0 +1,12 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthCodeMSALBrowserAuthenticationProvider = void 0;
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
var AuthCodeMSALBrowserAuthenticationProvider_1 = require("./AuthCodeMSALBrowserAuthenticationProvider");
Object.defineProperty(exports, "AuthCodeMSALBrowserAuthenticationProvider", { enumerable: true, get: function () { return AuthCodeMSALBrowserAuthenticationProvider_1.AuthCodeMSALBrowserAuthenticationProvider; } });
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/authentication/msal-browser/index.ts"],"names":[],"mappings":";;;AAAA;;;;;GAKG;AACH,yGAAwG;AAA/F,sKAAA,yCAAyC,OAAA"}
@@ -0,0 +1,16 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module MSALAuthenticationProviderOptions
*/
import { AccountInfo, InteractionType } from "@azure/msal-browser";
import { AuthenticationProviderOptions } from "../../IAuthenticationProviderOptions";
export interface AuthCodeMSALBrowserAuthenticationProviderOptions extends AuthenticationProviderOptions {
scopes: string[];
account: AccountInfo;
interactionType: InteractionType;
}
@@ -0,0 +1,9 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=MSALAuthenticationProviderOptions.js.map
@@ -0,0 +1 @@
{"version":3,"file":"MSALAuthenticationProviderOptions.js","sourceRoot":"","sources":["../../../../src/authentication/msalOptions/MSALAuthenticationProviderOptions.ts"],"names":[],"mappings":";AAAA;;;;;GAKG"}
@@ -0,0 +1,48 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/// <reference path="../../../shims.d.ts" />
export { BatchRequestStep, BatchRequestData, BatchRequestContent, RequestData, BatchRequestBody } 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 { 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 { getValidRangeSize } from "../tasks/OneDriveLargeFileUploadTaskUtil";
export { StreamUpload } from "../tasks/FileUploadTask/FileObjectClasses/StreamUpload";
export { FileUpload } from "../tasks/FileUploadTask/FileObjectClasses/FileUpload";
export { UploadResult } from "../tasks/FileUploadTask/UploadResult";
export { UploadEventHandlers } from "../tasks/FileUploadTask/Interfaces/IUploadEventHandlers";
export { Range } from "../tasks/FileUploadTask/Range";
export { PageIteratorCallback, PageIterator, PageCollection, GraphRequestOptions } 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 { ClientOptions } from "../IClientOptions";
export { Context } from "../IContext";
export { NodeFetchInit, FetchOptions } from "../IFetchOptions";
export { GraphRequestCallback } from "../IGraphRequestCallback";
export { Options } from "../IOptions";
export { ResponseType } from "../ResponseType";
@@ -0,0 +1,71 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
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 BatchRequestContent_1 = require("../content/BatchRequestContent");
Object.defineProperty(exports, "BatchRequestContent", { enumerable: true, get: function () { return BatchRequestContent_1.BatchRequestContent; } });
var BatchResponseContent_1 = require("../content/BatchResponseContent");
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 ChaosHandlerOptions_1 = require("../middleware/options/ChaosHandlerOptions");
Object.defineProperty(exports, "ChaosHandlerOptions", { enumerable: true, get: function () { return ChaosHandlerOptions_1.ChaosHandlerOptions; } });
var ChaosStrategy_1 = require("../middleware/options/ChaosStrategy");
Object.defineProperty(exports, "ChaosStrategy", { enumerable: true, get: function () { return ChaosStrategy_1.ChaosStrategy; } });
var ChaosHandler_1 = require("../middleware/ChaosHandler");
Object.defineProperty(exports, "ChaosHandler", { enumerable: true, get: function () { return ChaosHandler_1.ChaosHandler; } });
var LargeFileUploadTask_1 = require("../tasks/LargeFileUploadTask");
Object.defineProperty(exports, "LargeFileUploadTask", { enumerable: true, get: function () { return LargeFileUploadTask_1.LargeFileUploadTask; } });
var OneDriveLargeFileUploadTask_1 = require("../tasks/OneDriveLargeFileUploadTask");
Object.defineProperty(exports, "OneDriveLargeFileUploadTask", { enumerable: true, get: function () { return OneDriveLargeFileUploadTask_1.OneDriveLargeFileUploadTask; } });
var OneDriveLargeFileUploadTaskUtil_1 = require("../tasks/OneDriveLargeFileUploadTaskUtil");
Object.defineProperty(exports, "getValidRangeSize", { enumerable: true, get: function () { return OneDriveLargeFileUploadTaskUtil_1.getValidRangeSize; } });
var StreamUpload_1 = require("../tasks/FileUploadTask/FileObjectClasses/StreamUpload");
Object.defineProperty(exports, "StreamUpload", { enumerable: true, get: function () { return StreamUpload_1.StreamUpload; } });
var FileUpload_1 = require("../tasks/FileUploadTask/FileObjectClasses/FileUpload");
Object.defineProperty(exports, "FileUpload", { enumerable: true, get: function () { return FileUpload_1.FileUpload; } });
var UploadResult_1 = require("../tasks/FileUploadTask/UploadResult");
Object.defineProperty(exports, "UploadResult", { enumerable: true, get: function () { return UploadResult_1.UploadResult; } });
var Range_1 = require("../tasks/FileUploadTask/Range");
Object.defineProperty(exports, "Range", { enumerable: true, get: function () { return Range_1.Range; } });
var PageIterator_1 = require("../tasks/PageIterator");
Object.defineProperty(exports, "PageIterator", { enumerable: true, get: function () { return PageIterator_1.PageIterator; } });
var Client_1 = require("../Client");
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");
Object.defineProperty(exports, "GraphError", { enumerable: true, get: function () { return GraphError_1.GraphError; } });
var GraphClientError_1 = require("../GraphClientError");
Object.defineProperty(exports, "GraphClientError", { enumerable: true, get: function () { return GraphClientError_1.GraphClientError; } });
var GraphRequest_1 = require("../GraphRequest");
Object.defineProperty(exports, "GraphRequest", { enumerable: true, get: function () { return GraphRequest_1.GraphRequest; } });
var ResponseType_1 = require("../ResponseType");
Object.defineProperty(exports, "ResponseType", { enumerable: true, get: function () { return ResponseType_1.ResponseType; } });
//# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/browser/index.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEH,qEAAqE;AACrE,0CAA0C;AAC1C,sEAAwI;AAA3F,0HAAA,mBAAmB,OAAA;AAChE,wEAA0F;AAA9D,4HAAA,oBAAoB,OAAA;AAEhD,6EAA4E;AAAnE,8HAAA,qBAAqB,OAAA;AAC9B,uEAAsE;AAA7D,wHAAA,kBAAkB,OAAA;AAE3B,2DAA0D;AAAjD,4GAAA,YAAY,OAAA;AACrB,iEAAgE;AAAvD,kHAAA,eAAe,OAAA;AACxB,mEAAkE;AAAzD,oHAAA,gBAAgB,OAAA;AACzB,qEAAoE;AAA3D,sHAAA,iBAAiB,OAAA;AAC1B,mGAAkG;AAAzF,4IAAA,4BAA4B,OAAA;AAErC,iFAA6F;AAAvE,0HAAA,mBAAmB,OAAA;AACzC,uFAAsG;AAA7E,gIAAA,sBAAsB,OAAA;AAC/C,yFAA0G;AAAjG,2HAAA,gBAAgB,OAAA;AAAE,kIAAA,uBAAuB,OAAA;AAClD,iFAAgF;AAAvE,0HAAA,mBAAmB,OAAA;AAC5B,qEAAoE;AAA3D,8GAAA,aAAa,OAAA;AACtB,2DAA0D;AAAjD,4GAAA,YAAY,OAAA;AAErB,oEAA8I;AAA9F,0HAAA,mBAAmB,OAAA;AACnE,oFAAmH;AAA1G,0IAAA,2BAA2B,OAAA;AACpC,4FAA6E;AAApE,oIAAA,iBAAiB,OAAA;AAC1B,uFAAsF;AAA7E,4GAAA,YAAY,OAAA;AACrB,mFAAkF;AAAzE,wGAAA,UAAU,OAAA;AACnB,qEAAoE;AAA3D,4GAAA,YAAY,OAAA;AAErB,uDAAsD;AAA7C,8FAAA,KAAK,OAAA;AACd,sDAAgH;AAAjF,4GAAA,YAAY,OAAA;AAE3C,oCAAmC;AAA1B,gGAAA,MAAM,OAAA;AACf,gFAA+E;AAAtE,4IAAA,4BAA4B,OAAA;AACrC,4CAA2C;AAAlC,wGAAA,UAAU,OAAA;AACnB,wDAAuD;AAA9C,oHAAA,gBAAgB,OAAA;AACzB,gDAA+C;AAAtC,4GAAA,YAAY,OAAA;AAUrB,gDAA+C;AAAtC,4GAAA,YAAY,OAAA"}
@@ -0,0 +1,144 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @interface
* Signature representing BatchRequestStep data
* @property {string} id - Unique identity for the request, Should not be an empty string
* @property {string[]} [dependsOn] - Array of dependencies
* @property {Request} request - The Request object
*/
export interface BatchRequestStep {
id: string;
dependsOn?: string[];
request: Request;
}
/**
* @interface
* Signature representing single request in a Batching
* @extends RequestInit
* @see {@link https://github.com/Microsoft/TypeScript/blob/master/lib/lib.dom.d.ts#L1337} and {@link https://fetch.spec.whatwg.org/#requestinit}
*
* @property {string} url - The url value of the request
*/
export interface RequestData extends RequestInit {
url: string;
}
/**
* @interface
* Signature representing batch request data
* @property {string} id - Unique identity for the request, Should not be an empty string
* @property {string[]} [dependsOn] - Array of dependencies
*/
export interface BatchRequestData extends RequestData {
id: string;
dependsOn?: string[];
}
/**
* @interface
* Signature representing batch request body
* @property {BatchRequestData[]} requests - Array of request data, a json representation of requests for batch
*/
export interface BatchRequestBody {
requests: BatchRequestData[];
}
/**
* @class
* Class for handling BatchRequestContent
*/
export declare class BatchRequestContent {
/**
* @private
* @static
* Limit for number of requests {@link - https://developer.microsoft.com/en-us/graph/docs/concepts/known_issues#json-batching}
*/
private static requestLimit;
/**
* @public
* To keep track of requests, key will be id of the request and value will be the request json
*/
requests: Map<string, BatchRequestStep>;
/**
* @private
* @static
* Validates the dependency chain of the requests
*
* Note:
* Individual requests can depend on other individual requests. Currently, requests can only depend on a single other request, and must follow one of these three patterns:
* 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.
* As JSON batching matures, these limitations will be removed.
* @see {@link https://developer.microsoft.com/en-us/graph/docs/concepts/known_issues#json-batching}
*
* @param {Map<string, BatchRequestStep>} requests - The map of requests.
* @returns The boolean indicating the validation status
*/
private static validateDependencies;
/**
* @private
* @static
* @async
* Converts Request Object instance to a JSON
* @param {IsomorphicRequest} request - The IsomorphicRequest Object instance
* @returns A promise that resolves to JSON representation of a request
*/
private static getRequestData;
/**
* @private
* @static
* @async
* Gets the body of a Request object instance
* @param {IsomorphicRequest} request - The IsomorphicRequest object instance
* @returns The Promise that resolves to a body value of a Request
*/
private static getRequestBody;
/**
* @public
* @constructor
* Constructs a BatchRequestContent instance
* @param {BatchRequestStep[]} [requests] - Array of requests value
* @returns An instance of a BatchRequestContent
*/
constructor(requests?: BatchRequestStep[]);
/**
* @public
* Adds a request to the batch request content
* @param {BatchRequestStep} request - The request value
* @returns The id of the added request
*/
addRequest(request: BatchRequestStep): string;
/**
* @public
* Removes request from the batch payload and its dependencies from all dependents
* @param {string} requestId - The id of a request that needs to be removed
* @returns The boolean indicating removed status
*/
removeRequest(requestId: string): boolean;
/**
* @public
* @async
* Serialize content from BatchRequestContent instance
* @returns The body content to make batch request
*/
getContent(): Promise<BatchRequestBody>;
/**
* @public
* Adds a dependency for a given dependent request
* @param {string} dependentId - The id of the dependent request
* @param {string} [dependencyId] - The id of the dependency request, if not specified the preceding request will be considered as a dependency
* @returns Nothing
*/
addDependency(dependentId: string, dependencyId?: string): void;
/**
* @public
* Removes a dependency for a given dependent request id
* @param {string} dependentId - The id of the dependent request
* @param {string} [dependencyId] - The id of the dependency request, if not specified will remove all the dependencies of that request
* @returns The boolean indicating removed status
*/
removeDependency(dependentId: string, dependencyId?: string): boolean;
}
@@ -0,0 +1,460 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.BatchRequestContent = void 0;
var tslib_1 = require("tslib");
/**
* @module BatchRequestContent
*/
var RequestMethod_1 = require("../RequestMethod");
/**
* @class
* Class for handling BatchRequestContent
*/
var BatchRequestContent = /** @class */ (function () {
/**
* @public
* @constructor
* Constructs a BatchRequestContent instance
* @param {BatchRequestStep[]} [requests] - Array of requests value
* @returns An instance of a BatchRequestContent
*/
function BatchRequestContent(requests) {
this.requests = new Map();
if (typeof requests !== "undefined") {
var limit = BatchRequestContent.requestLimit;
if (requests.length > limit) {
var error = new Error("Maximum requests limit exceeded, Max allowed number of requests are ".concat(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];
this.addRequest(req);
}
}
}
/**
* @private
* @static
* Validates the dependency chain of the requests
*
* Note:
* Individual requests can depend on other individual requests. Currently, requests can only depend on a single other request, and must follow one of these three patterns:
* 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.
* As JSON batching matures, these limitations will be removed.
* @see {@link https://developer.microsoft.com/en-us/graph/docs/concepts/known_issues#json-batching}
*
* @param {Map<string, BatchRequestStep>} requests - The map of requests.
* @returns The boolean indicating the validation status
*/
BatchRequestContent.validateDependencies = function (requests) {
var isParallel = function (reqs) {
var iterator = reqs.entries();
var cur = iterator.next();
while (!cur.done) {
var curReq = cur.value[1];
if (curReq.dependsOn !== undefined && curReq.dependsOn.length > 0) {
return false;
}
cur = iterator.next();
}
return true;
};
var isSerial = function (reqs) {
var iterator = reqs.entries();
var cur = iterator.next();
var firstRequest = cur.value[1];
if (firstRequest.dependsOn !== undefined && firstRequest.dependsOn.length > 0) {
return false;
}
var prev = cur;
cur = iterator.next();
while (!cur.done) {
var curReq = cur.value[1];
if (curReq.dependsOn === undefined || curReq.dependsOn.length !== 1 || curReq.dependsOn[0] !== prev.value[1].id) {
return false;
}
prev = cur;
cur = iterator.next();
}
return true;
};
var isSame = function (reqs) {
var iterator = reqs.entries();
var cur = iterator.next();
var firstRequest = cur.value[1];
var dependencyId;
if (firstRequest.dependsOn === undefined || firstRequest.dependsOn.length === 0) {
dependencyId = firstRequest.id;
}
else {
if (firstRequest.dependsOn.length === 1) {
var fDependencyId = firstRequest.dependsOn[0];
if (fDependencyId !== firstRequest.id && reqs.has(fDependencyId)) {
dependencyId = fDependencyId;
}
else {
return false;
}
}
else {
return false;
}
}
cur = iterator.next();
while (!cur.done) {
var curReq = cur.value[1];
if ((curReq.dependsOn === undefined || curReq.dependsOn.length === 0) && dependencyId !== curReq.id) {
return false;
}
if (curReq.dependsOn !== undefined && curReq.dependsOn.length !== 0) {
if (curReq.dependsOn.length === 1 && (curReq.id === dependencyId || curReq.dependsOn[0] !== dependencyId)) {
return false;
}
if (curReq.dependsOn.length > 1) {
return false;
}
}
cur = iterator.next();
}
return true;
};
if (requests.size === 0) {
var error = new Error("Empty requests map, Please provide at least one request.");
error.name = "Empty Requests Error";
throw error;
}
return isParallel(requests) || isSerial(requests) || isSame(requests);
};
/**
* @private
* @static
* @async
* Converts Request Object instance to a JSON
* @param {IsomorphicRequest} request - The IsomorphicRequest Object instance
* @returns A promise that resolves to JSON representation of a request
*/
BatchRequestContent.getRequestData = function (request) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var requestData, hasHttpRegex, headers, _a;
return 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];
}
});
});
};
/**
* @private
* @static
* @async
* Gets the body of a Request object instance
* @param {IsomorphicRequest} request - The IsomorphicRequest object instance
* @returns The Promise that resolves to a body value of a Request
*/
BatchRequestContent.getRequestBody = function (request) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var bodyParsed, body, cloneReq, e_1, blob_1, reader_1, buffer, e_2;
return 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();
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];
}
});
});
};
/**
* @public
* Adds a request to the batch request content
* @param {BatchRequestStep} request - The request value
* @returns The id of the added request
*/
BatchRequestContent.prototype.addRequest = function (request) {
var limit = BatchRequestContent.requestLimit;
if (request.id === "") {
var error = new Error("Id for a request is empty, Please provide an unique id");
error.name = "Empty Id For Request";
throw error;
}
if (this.requests.size === limit) {
var error = new Error("Maximum requests limit exceeded, Max allowed number of requests are ".concat(limit));
error.name = "Limit Exceeded Error";
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"));
error.name = "Duplicate RequestId Error";
throw error;
}
this.requests.set(request.id, request);
return request.id;
};
/**
* @public
* Removes request from the batch payload and its dependencies from all dependents
* @param {string} requestId - The id of a request that needs to be removed
* @returns The boolean indicating removed status
*/
BatchRequestContent.prototype.removeRequest = function (requestId) {
var deleteStatus = this.requests.delete(requestId);
var iterator = this.requests.entries();
var cur = iterator.next();
/**
* Removing dependencies where this request is present as a dependency
*/
while (!cur.done) {
var dependencies = cur.value[1].dependsOn;
if (typeof dependencies !== "undefined") {
var index = dependencies.indexOf(requestId);
if (index !== -1) {
dependencies.splice(index, 1);
}
if (dependencies.length === 0) {
delete cur.value[1].dependsOn;
}
}
cur = iterator.next();
}
return deleteStatus;
};
/**
* @public
* @async
* Serialize content from BatchRequestContent instance
* @returns The body content to make batch request
*/
BatchRequestContent.prototype.getContent = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var requests, requestBody, iterator, cur, error, error, requestStep, batchRequestData, error;
return 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];
}
});
});
};
/**
* @public
* Adds a dependency for a given dependent request
* @param {string} dependentId - The id of the dependent request
* @param {string} [dependencyId] - The id of the dependency request, if not specified the preceding request will be considered as a dependency
* @returns Nothing
*/
BatchRequestContent.prototype.addDependency = function (dependentId, dependencyId) {
if (!this.requests.has(dependentId)) {
var error = new Error("Dependent ".concat(dependentId, " does not exists, Please check the id"));
error.name = "Invalid Dependent";
throw error;
}
if (typeof dependencyId !== "undefined" && !this.requests.has(dependencyId)) {
var error = new Error("Dependency ".concat(dependencyId, " does not exists, Please check the id"));
error.name = "Invalid Dependency";
throw error;
}
if (typeof dependencyId !== "undefined") {
var dependent = this.requests.get(dependentId);
if (dependent.dependsOn === undefined) {
dependent.dependsOn = [];
}
if (dependent.dependsOn.indexOf(dependencyId) !== -1) {
var error = new Error("Dependency ".concat(dependencyId, " is already added for the request ").concat(dependentId));
error.name = "Duplicate Dependency";
throw error;
}
dependent.dependsOn.push(dependencyId);
}
else {
var iterator = this.requests.entries();
var prev = void 0;
var cur = iterator.next();
while (!cur.done && cur.value[1].id !== dependentId) {
prev = cur;
cur = iterator.next();
}
if (typeof prev !== "undefined") {
var dId = prev.value[0];
if (cur.value[1].dependsOn === undefined) {
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));
error.name = "Duplicate Dependency";
throw error;
}
cur.value[1].dependsOn.push(dId);
}
else {
var error = new Error("Can't add dependency ".concat(dependencyId, ", There is only a dependent request in the batch"));
error.name = "Invalid Dependency Addition";
throw error;
}
}
};
/**
* @public
* Removes a dependency for a given dependent request id
* @param {string} dependentId - The id of the dependent request
* @param {string} [dependencyId] - The id of the dependency request, if not specified will remove all the dependencies of that request
* @returns The boolean indicating removed status
*/
BatchRequestContent.prototype.removeDependency = function (dependentId, dependencyId) {
var request = this.requests.get(dependentId);
if (typeof request === "undefined" || request.dependsOn === undefined || request.dependsOn.length === 0) {
return false;
}
if (typeof dependencyId !== "undefined") {
var index = request.dependsOn.indexOf(dependencyId);
if (index === -1) {
return false;
}
request.dependsOn.splice(index, 1);
return true;
}
else {
delete request.dependsOn;
return true;
}
};
/**
* @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;
//# sourceMappingURL=BatchRequestContent.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,82 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/**
* @module BatchResponseContent
*/
/**
* @interface
* Signature represents key value pair object
*/
interface KeyValuePairObject {
[key: string]: any;
}
/**
* @interface
* Signature representing Batch response body
* @property {KeyValuePairObject[]} responses - An array of key value pair representing response object for every request
* @property {string} [@odata.nextLink] - The nextLink value to get next set of responses in case of asynchronous batch requests
*/
export interface BatchResponseBody {
responses: KeyValuePairObject[];
"@odata.nextLink"?: string;
}
/**
* @class
* Class that handles BatchResponseContent
*/
export declare class BatchResponseContent {
/**
* To hold the responses
*/
private responses;
/**
* Holds the next link url
*/
private nextLink;
/**
* @public
* @constructor
* Creates the BatchResponseContent instance
* @param {BatchResponseBody} response - The response body returned for batch request from server
* @returns An instance of a BatchResponseContent
*/
constructor(response: BatchResponseBody);
/**
* @private
* Creates native Response object from the json representation of it.
* @param {KeyValuePairObject} responseJSON - The response json value
* @returns The Response Object instance
*/
private createResponseObject;
/**
* @public
* Updates the Batch response content instance with given responses.
* @param {BatchResponseBody} response - The response json representing batch response message
* @returns Nothing
*/
update(response: BatchResponseBody): void;
/**
* @public
* To get the response of a request for a given request id
* @param {string} requestId - The request id value
* @returns The Response object instance for the particular request
*/
getResponseById(requestId: string): Response;
/**
* @public
* To get all the responses of the batch request
* @returns The Map of id and Response objects
*/
getResponses(): Map<string, Response>;
/**
* @public
* To get the iterator for the responses
* @returns The Iterable generator for the response objects
*/
getResponsesIterator(): IterableIterator<[string, Response]>;
}
export {};
@@ -0,0 +1,106 @@
"use strict";
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.BatchResponseContent = void 0;
var tslib_1 = require("tslib");
/**
* @class
* Class that handles BatchResponseContent
*/
var BatchResponseContent = /** @class */ (function () {
/**
* @public
* @constructor
* Creates the BatchResponseContent instance
* @param {BatchResponseBody} response - The response body returned for batch request from server
* @returns An instance of a BatchResponseContent
*/
function BatchResponseContent(response) {
this.responses = new Map();
this.update(response);
}
/**
* @private
* Creates native Response object from the json representation of it.
* @param {KeyValuePairObject} responseJSON - The response json value
* @returns The Response Object instance
*/
BatchResponseContent.prototype.createResponseObject = function (responseJSON) {
var body = responseJSON.body;
var options = {};
options.status = responseJSON.status;
if (responseJSON.statusText !== undefined) {
options.statusText = responseJSON.statusText;
}
options.headers = responseJSON.headers;
if (options.headers !== undefined && options.headers["Content-Type"] !== undefined) {
if (options.headers["Content-Type"].split(";")[0] === "application/json") {
var bodyString = JSON.stringify(body);
return new Response(bodyString, options);
}
}
return new Response(body, options);
};
/**
* @public
* Updates the Batch response content instance with given responses.
* @param {BatchResponseBody} response - The response json representing batch response message
* @returns Nothing
*/
BatchResponseContent.prototype.update = function (response) {
this.nextLink = response["@odata.nextLink"];
var responses = response.responses;
for (var i = 0, l = responses.length; i < l; i++) {
this.responses.set(responses[i].id, this.createResponseObject(responses[i]));
}
};
/**
* @public
* To get the response of a request for a given request id
* @param {string} requestId - The request id value
* @returns The Response object instance for the particular request
*/
BatchResponseContent.prototype.getResponseById = function (requestId) {
return this.responses.get(requestId);
};
/**
* @public
* To get all the responses of the batch request
* @returns The Map of id and Response objects
*/
BatchResponseContent.prototype.getResponses = function () {
return this.responses;
};
/**
* @public
* To get the iterator for the responses
* @returns The Iterable generator for the response objects
*/
BatchResponseContent.prototype.getResponsesIterator = function () {
var iterator, cur;
return 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;
}());
exports.BatchResponseContent = BatchResponseContent;
//# sourceMappingURL=BatchResponseContent.js.map
@@ -0,0 +1 @@
{"version":3,"file":"BatchResponseContent.js","sourceRoot":"","sources":["../../../src/content/BatchResponseContent.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;AAyBH;;;GAGG;AACH;IAWC;;;;;;OAMG;IACH,8BAAmB,QAA2B;QAC7C,IAAI,CAAC,SAAS,GAAG,IAAI,GAAG,EAAE,CAAC;QAC3B,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IACvB,CAAC;IAED;;;;;OAKG;IACK,mDAAoB,GAA5B,UAA6B,YAAgC;QAC5D,IAAM,IAAI,GAAG,YAAY,CAAC,IAAI,CAAC;QAC/B,IAAM,OAAO,GAAuB,EAAE,CAAC;QACvC,OAAO,CAAC,MAAM,GAAG,YAAY,CAAC,MAAM,CAAC;QACrC,IAAI,YAAY,CAAC,UAAU,KAAK,SAAS,EAAE;YAC1C,OAAO,CAAC,UAAU,GAAG,YAAY,CAAC,UAAU,CAAC;SAC7C;QACD,OAAO,CAAC,OAAO,GAAG,YAAY,CAAC,OAAO,CAAC;QACvC,IAAI,OAAO,CAAC,OAAO,KAAK,SAAS,IAAI,OAAO,CAAC,OAAO,CAAC,cAAc,CAAC,KAAK,SAAS,EAAE;YACnF,IAAI,OAAO,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,kBAAkB,EAAE;gBACzE,IAAM,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;gBACxC,OAAO,IAAI,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;aACzC;SACD;QACD,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IACpC,CAAC;IAED;;;;;OAKG;IACI,qCAAM,GAAb,UAAc,QAA2B;QACxC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC,iBAAiB,CAAC,CAAC;QAC5C,IAAM,SAAS,GAAG,QAAQ,CAAC,SAAS,CAAC;QACrC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;YACjD,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,IAAI,CAAC,oBAAoB,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;SAC7E;IACF,CAAC;IAED;;;;;OAKG;IACI,8CAAe,GAAtB,UAAuB,SAAiB;QACvC,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IACtC,CAAC;IAED;;;;OAIG;IACI,2CAAY,GAAnB;QACC,OAAO,IAAI,CAAC,SAAS,CAAC;IACvB,CAAC;IAED;;;;OAIG;IACK,mDAAoB,GAA5B;;;;;oBACO,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC;oBACtC,GAAG,GAAG,QAAQ,CAAC,IAAI,EAAE,CAAC;;;yBACnB,CAAC,GAAG,CAAC,IAAI;oBACf,qBAAM,GAAG,CAAC,KAAK,EAAA;;oBAAf,SAAe,CAAC;oBAChB,GAAG,GAAG,QAAQ,CAAC,IAAI,EAAE,CAAC;;;;;KAEvB;IACF,2BAAC;AAAD,CAAC,AA5FD,IA4FC;AA5FY,oDAAoB"}
+48
View File
@@ -0,0 +1,48 @@
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
/// <reference path="../../shims.d.ts" />
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 { ChaosHandlerOptions } from "./middleware/options/ChaosHandlerOptions";
export { ChaosStrategy } from "./middleware/options/ChaosStrategy";
export { ChaosHandler } from "./middleware/ChaosHandler";
export { FileObject, LargeFileUploadSession, LargeFileUploadTask, LargeFileUploadTaskOptions, SliceType } from "./tasks/LargeFileUploadTask";
export { OneDriveLargeFileUploadOptions, OneDriveLargeFileUploadTask } from "./tasks/OneDriveLargeFileUploadTask";
export { getValidRangeSize } from "./tasks/OneDriveLargeFileUploadTaskUtil";
export { StreamUpload } from "./tasks/FileUploadTask/FileObjectClasses/StreamUpload";
export { FileUpload } from "./tasks/FileUploadTask/FileObjectClasses/FileUpload";
export { UploadResult } from "./tasks/FileUploadTask/UploadResult";
export { UploadEventHandlers } from "./tasks/FileUploadTask/Interfaces/IUploadEventHandlers";
export { Range } from "./tasks/FileUploadTask/Range";
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, 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";

Some files were not shown because too many files have changed in this diff Show More