@microsoft/microsoft-graph-client
Advanced tools
Comparing version 1.6.0-Preview.2 to 1.6.0-Preview.3
@@ -7,2 +7,10 @@ /** | ||
*/ | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
/** | ||
@@ -37,37 +45,39 @@ * @class | ||
*/ | ||
async getAccessToken(authenticationProviderOptions) { | ||
const options = authenticationProviderOptions; | ||
let scopes; | ||
if (typeof options !== "undefined") { | ||
scopes = options.scopes; | ||
} | ||
if (typeof scopes === "undefined" || scopes.length === 0) { | ||
scopes = this.scopes; | ||
} | ||
if (scopes.length === 0) { | ||
const error = new Error(); | ||
error.name = "EmptyScopes"; | ||
error.message = "Scopes cannot be empty, Please provide a scope"; | ||
throw error; | ||
} | ||
try { | ||
const accessToken = await this.userAgentApplication.acquireTokenSilent(scopes); | ||
return accessToken; | ||
} | ||
catch (errorMsg) { | ||
getAccessToken(authenticationProviderOptions) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const options = authenticationProviderOptions; | ||
let scopes; | ||
if (typeof options !== "undefined") { | ||
scopes = options.scopes; | ||
} | ||
if (typeof scopes === "undefined" || scopes.length === 0) { | ||
scopes = this.scopes; | ||
} | ||
if (scopes.length === 0) { | ||
const error = new Error(); | ||
error.name = "EmptyScopes"; | ||
error.message = "Scopes cannot be empty, Please provide a scope"; | ||
throw error; | ||
} | ||
try { | ||
const idToken = await this.userAgentApplication.loginPopup(scopes); | ||
const accessToken = yield this.userAgentApplication.acquireTokenSilent(scopes); | ||
return accessToken; | ||
} | ||
catch (errorMsg) { | ||
try { | ||
const accessToken = await this.userAgentApplication.acquireTokenSilent(scopes); | ||
return accessToken; | ||
const idToken = yield this.userAgentApplication.loginPopup(scopes); | ||
try { | ||
const accessToken = yield this.userAgentApplication.acquireTokenSilent(scopes); | ||
return accessToken; | ||
} | ||
catch (error) { | ||
const accessToken = yield this.userAgentApplication.acquireTokenPopup(scopes); | ||
return accessToken; | ||
} | ||
} | ||
catch (error) { | ||
const accessToken = await this.userAgentApplication.acquireTokenPopup(scopes); | ||
return accessToken; | ||
catch (errorMsg) { | ||
throw new Error(errorMsg); | ||
} | ||
} | ||
catch (errorMsg) { | ||
throw new Error(errorMsg); | ||
} | ||
} | ||
}); | ||
} | ||
@@ -74,0 +84,0 @@ /** |
@@ -26,2 +26,2 @@ /** | ||
*/ | ||
export declare const PACKAGE_VERSION = "1.6.0-Preview.2"; | ||
export declare const PACKAGE_VERSION = "1.6.0-Preview.3"; |
@@ -26,3 +26,3 @@ /** | ||
*/ | ||
export const PACKAGE_VERSION = "1.6.0-Preview.2"; | ||
export const PACKAGE_VERSION = "1.6.0-Preview.3"; | ||
//# sourceMappingURL=Constants.js.map |
@@ -7,2 +7,10 @@ /** | ||
*/ | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
/** | ||
@@ -141,24 +149,26 @@ * @module BatchRequestContent | ||
*/ | ||
static async getRequestData(request) { | ||
const requestData = { | ||
url: "", | ||
}; | ||
const hasHttpRegex = new RegExp("^https?://"); | ||
// Stripping off hostname, port and url scheme | ||
requestData.url = hasHttpRegex.test(request.url) ? "/" + request.url.split(/.*?\/\/.*?\//)[1] : request.url; | ||
requestData.method = request.method; | ||
const headers = {}; | ||
request.headers.forEach((value, key) => { | ||
headers[key] = value; | ||
static getRequestData(request) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const requestData = { | ||
url: "", | ||
}; | ||
const hasHttpRegex = new RegExp("^https?://"); | ||
// Stripping off hostname, port and url scheme | ||
requestData.url = hasHttpRegex.test(request.url) ? "/" + request.url.split(/.*?\/\/.*?\//)[1] : request.url; | ||
requestData.method = request.method; | ||
const headers = {}; | ||
request.headers.forEach((value, key) => { | ||
headers[key] = value; | ||
}); | ||
if (Object.keys(headers).length) { | ||
requestData.headers = headers; | ||
} | ||
if (request.method === RequestMethod.PATCH || request.method === RequestMethod.POST || request.method === RequestMethod.PUT) { | ||
requestData.body = yield BatchRequestContent.getRequestBody(request); | ||
} | ||
/** | ||
* TODO: Check any other property needs to be used from the Request object and add them | ||
*/ | ||
return requestData; | ||
}); | ||
if (Object.keys(headers).length) { | ||
requestData.headers = headers; | ||
} | ||
if (request.method === RequestMethod.PATCH || request.method === RequestMethod.POST || request.method === RequestMethod.PUT) { | ||
requestData.body = await BatchRequestContent.getRequestBody(request); | ||
} | ||
/** | ||
* TODO: Check any other property needs to be used from the Request object and add them | ||
*/ | ||
return requestData; | ||
} | ||
@@ -173,41 +183,9 @@ /** | ||
*/ | ||
static async getRequestBody(request) { | ||
let bodyParsed = false; | ||
let body; | ||
try { | ||
const cloneReq = request.clone(); | ||
body = await cloneReq.json(); | ||
bodyParsed = true; | ||
} | ||
catch (e) { | ||
// tslint:disable-line: no-empty | ||
} | ||
if (!bodyParsed) { | ||
static getRequestBody(request) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
let bodyParsed = false; | ||
let body; | ||
try { | ||
if (typeof Blob !== "undefined") { | ||
const blob = await request.blob(); | ||
const reader = new FileReader(); | ||
body = await new Promise((resolve) => { | ||
reader.addEventListener("load", () => { | ||
const dataURL = reader.result; | ||
/** | ||
* Some valid dataURL schemes: | ||
* 1. data:text/vnd-example+xyz;foo=bar;base64,R0lGODdh | ||
* 2. data:text/plain;charset=UTF-8;page=21,the%20data:1234,5678 | ||
* 3. data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg== | ||
* 4. data:image/png,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg== | ||
* 5. data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg== | ||
* @see Syntax {@link https://en.wikipedia.org/wiki/Data_URI_scheme} for more | ||
*/ | ||
const regex = new RegExp("^s*data:(.+?/.+?(;.+?=.+?)*)?(;base64)?,(.*)s*$"); | ||
const segments = regex.exec(dataURL); | ||
resolve(segments[4]); | ||
}, false); | ||
reader.readAsDataURL(blob); | ||
}); | ||
} | ||
else if (typeof Buffer !== "undefined") { | ||
const buffer = await request.buffer(); | ||
body = buffer.toString("base64"); | ||
} | ||
const cloneReq = request.clone(); | ||
body = yield cloneReq.json(); | ||
bodyParsed = true; | ||
@@ -218,4 +196,38 @@ } | ||
} | ||
} | ||
return body; | ||
if (!bodyParsed) { | ||
try { | ||
if (typeof Blob !== "undefined") { | ||
const blob = yield request.blob(); | ||
const reader = new FileReader(); | ||
body = yield new Promise((resolve) => { | ||
reader.addEventListener("load", () => { | ||
const dataURL = reader.result; | ||
/** | ||
* Some valid dataURL schemes: | ||
* 1. data:text/vnd-example+xyz;foo=bar;base64,R0lGODdh | ||
* 2. data:text/plain;charset=UTF-8;page=21,the%20data:1234,5678 | ||
* 3. data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg== | ||
* 4. data:image/png,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg== | ||
* 5. data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg== | ||
* @see Syntax {@link https://en.wikipedia.org/wiki/Data_URI_scheme} for more | ||
*/ | ||
const regex = new RegExp("^s*data:(.+?/.+?(;.+?=.+?)*)?(;base64)?,(.*)s*$"); | ||
const segments = regex.exec(dataURL); | ||
resolve(segments[4]); | ||
}, false); | ||
reader.readAsDataURL(blob); | ||
}); | ||
} | ||
else if (typeof Buffer !== "undefined") { | ||
const buffer = yield request.buffer(); | ||
body = buffer.toString("base64"); | ||
} | ||
bodyParsed = true; | ||
} | ||
catch (e) { | ||
// tslint:disable-line: no-empty | ||
} | ||
} | ||
return body; | ||
}); | ||
} | ||
@@ -282,42 +294,44 @@ /** | ||
*/ | ||
async getContent() { | ||
const requests = []; | ||
const requestBody = { | ||
requests, | ||
}; | ||
const iterator = this.requests.entries(); | ||
let cur = iterator.next(); | ||
if (cur.done) { | ||
const error = new Error("No requests added yet, Please add at least one request."); | ||
error.name = "Empty Payload"; | ||
throw error; | ||
} | ||
if (!BatchRequestContent.validateDependencies(this.requests)) { | ||
const error = new Error(`Invalid dependency found, Dependency should be: | ||
getContent() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const requests = []; | ||
const requestBody = { | ||
requests, | ||
}; | ||
const iterator = this.requests.entries(); | ||
let cur = iterator.next(); | ||
if (cur.done) { | ||
const error = new Error("No requests added yet, Please add at least one request."); | ||
error.name = "Empty Payload"; | ||
throw error; | ||
} | ||
if (!BatchRequestContent.validateDependencies(this.requests)) { | ||
const error = new Error(`Invalid dependency found, Dependency should be: | ||
1. Parallel - no individual request states a dependency in the dependsOn property. | ||
2. Serial - all individual requests depend on the previous individual request. | ||
3. Same - all individual requests that state a dependency in the dependsOn property, state the same dependency.`); | ||
error.name = "Invalid Dependency"; | ||
throw error; | ||
} | ||
while (!cur.done) { | ||
const requestStep = cur.value[1]; | ||
const batchRequestData = (await BatchRequestContent.getRequestData(requestStep.request)); | ||
/** | ||
* @see {@link https://developer.microsoft.com/en-us/graph/docs/concepts/json_batching#request-format} | ||
*/ | ||
if (batchRequestData.body !== undefined && (batchRequestData.headers === undefined || batchRequestData.headers["content-type"] === undefined)) { | ||
const error = new Error(`Content-type header is not mentioned for request #${requestStep.id}, For request having body, Content-type header should be mentioned`); | ||
error.name = "Invalid Content-type header"; | ||
error.name = "Invalid Dependency"; | ||
throw error; | ||
} | ||
batchRequestData.id = requestStep.id; | ||
if (requestStep.dependsOn !== undefined && requestStep.dependsOn.length > 0) { | ||
batchRequestData.dependsOn = requestStep.dependsOn; | ||
while (!cur.done) { | ||
const requestStep = cur.value[1]; | ||
const batchRequestData = (yield BatchRequestContent.getRequestData(requestStep.request)); | ||
/** | ||
* @see {@link https://developer.microsoft.com/en-us/graph/docs/concepts/json_batching#request-format} | ||
*/ | ||
if (batchRequestData.body !== undefined && (batchRequestData.headers === undefined || batchRequestData.headers["content-type"] === undefined)) { | ||
const error = new Error(`Content-type header is not mentioned for request #${requestStep.id}, For request having body, Content-type header should be mentioned`); | ||
error.name = "Invalid Content-type header"; | ||
throw error; | ||
} | ||
batchRequestData.id = requestStep.id; | ||
if (requestStep.dependsOn !== undefined && requestStep.dependsOn.length > 0) { | ||
batchRequestData.dependsOn = requestStep.dependsOn; | ||
} | ||
requests.push(batchRequestData); | ||
cur = iterator.next(); | ||
} | ||
requests.push(batchRequestData); | ||
cur = iterator.next(); | ||
} | ||
requestBody.requests = requests; | ||
return requestBody; | ||
requestBody.requests = requests; | ||
return requestBody; | ||
}); | ||
} | ||
@@ -324,0 +338,0 @@ /** |
@@ -7,2 +7,10 @@ /** | ||
*/ | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
/** | ||
@@ -30,11 +38,13 @@ * @class | ||
*/ | ||
async getAccessToken() { | ||
return new Promise((resolve, reject) => { | ||
this.provider((error, accessToken) => { | ||
if (accessToken) { | ||
resolve(accessToken); | ||
} | ||
else { | ||
reject(error); | ||
} | ||
getAccessToken() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
return new Promise((resolve, reject) => { | ||
this.provider((error, accessToken) => { | ||
if (accessToken) { | ||
resolve(accessToken); | ||
} | ||
else { | ||
reject(error); | ||
} | ||
}); | ||
}); | ||
@@ -41,0 +51,0 @@ }); |
@@ -7,2 +7,10 @@ /** | ||
*/ | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
/** | ||
@@ -44,11 +52,13 @@ * @module GraphErrorHandler | ||
*/ | ||
static async constructErrorFromRawResponse(error, statusCode) { | ||
const gError = new GraphError(statusCode); | ||
try { | ||
gError.body = await error.text(); | ||
} | ||
catch (error) { | ||
// tslint:disable-line: no-empty | ||
} | ||
return gError; | ||
static constructErrorFromRawResponse(error, statusCode) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const gError = new GraphError(statusCode); | ||
try { | ||
gError.body = yield error.text(); | ||
} | ||
catch (error) { | ||
// tslint:disable-line: no-empty | ||
} | ||
return gError; | ||
}); | ||
} | ||
@@ -103,24 +113,26 @@ /** | ||
*/ | ||
static async getError(error = null, statusCode = -1, callback) { | ||
let gError; | ||
if (error && (error.constructor.name === "Response" || error.constructor.name === "Body")) { | ||
gError = await GraphErrorHandler.constructErrorFromRawResponse(error, statusCode); | ||
} | ||
else if (error && error.error) { | ||
gError = GraphErrorHandler.constructErrorFromResponse(error, statusCode); | ||
} | ||
else if (error && error.constructor.name === "Error") { | ||
gError = GraphErrorHandler.constructError(error, statusCode); | ||
} | ||
else { | ||
gError = new GraphError(statusCode); | ||
} | ||
if (typeof callback === "function") { | ||
callback(gError, null); | ||
} | ||
else { | ||
return gError; | ||
} | ||
static getError(error = null, statusCode = -1, callback) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
let gError; | ||
if (error && (error.constructor.name === "Response" || error.constructor.name === "Body")) { | ||
gError = yield GraphErrorHandler.constructErrorFromRawResponse(error, statusCode); | ||
} | ||
else if (error && error.error) { | ||
gError = GraphErrorHandler.constructErrorFromResponse(error, statusCode); | ||
} | ||
else if (error && error.constructor.name === "Error") { | ||
gError = GraphErrorHandler.constructError(error, statusCode); | ||
} | ||
else { | ||
gError = new GraphError(statusCode); | ||
} | ||
if (typeof callback === "function") { | ||
callback(gError, null); | ||
} | ||
else { | ||
return gError; | ||
} | ||
}); | ||
} | ||
} | ||
//# sourceMappingURL=GraphErrorHandler.js.map |
@@ -7,2 +7,10 @@ /** | ||
*/ | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
/** | ||
@@ -169,8 +177,8 @@ * @module GraphRequest | ||
}; | ||
const optionsHeaders = { ...options.headers }; | ||
const optionsHeaders = Object.assign({}, options.headers); | ||
if (this.config.fetchOptions !== undefined) { | ||
const fetchOptions = { ...this.config.fetchOptions }; | ||
const fetchOptions = Object.assign({}, this.config.fetchOptions); | ||
Object.assign(options, fetchOptions); | ||
if (typeof this.config.fetchOptions.headers !== undefined) { | ||
options.headers = { ...this.config.fetchOptions.headers }; | ||
options.headers = Object.assign({}, this.config.fetchOptions.headers); | ||
} | ||
@@ -195,24 +203,26 @@ } | ||
*/ | ||
async send(request, options, callback) { | ||
let rawResponse; | ||
const middlewareControl = new MiddlewareControl(this._middlewareOptions); | ||
this.updateRequestOptions(options); | ||
try { | ||
const context = await this.httpClient.sendRequest({ | ||
request, | ||
options, | ||
middlewareControl, | ||
}); | ||
rawResponse = context.response; | ||
const response = await GraphResponseHandler.getResponse(rawResponse, this._responseType, callback); | ||
return response; | ||
} | ||
catch (error) { | ||
let statusCode; | ||
if (typeof rawResponse !== "undefined") { | ||
statusCode = rawResponse.status; | ||
send(request, options, callback) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
let rawResponse; | ||
const middlewareControl = new MiddlewareControl(this._middlewareOptions); | ||
this.updateRequestOptions(options); | ||
try { | ||
const context = yield this.httpClient.sendRequest({ | ||
request, | ||
options, | ||
middlewareControl, | ||
}); | ||
rawResponse = context.response; | ||
const response = yield GraphResponseHandler.getResponse(rawResponse, this._responseType, callback); | ||
return response; | ||
} | ||
const gError = await GraphErrorHandler.getError(error, statusCode, callback); | ||
throw gError; | ||
} | ||
catch (error) { | ||
let statusCode; | ||
if (typeof rawResponse !== "undefined") { | ||
statusCode = rawResponse.status; | ||
} | ||
const gError = yield GraphErrorHandler.getError(error, statusCode, callback); | ||
throw gError; | ||
} | ||
}); | ||
} | ||
@@ -425,14 +435,16 @@ /** | ||
*/ | ||
async get(callback) { | ||
const url = this.buildFullUrl(); | ||
const options = { | ||
method: RequestMethod.GET, | ||
}; | ||
try { | ||
const response = await this.send(url, options, callback); | ||
return response; | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
get(callback) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const url = this.buildFullUrl(); | ||
const options = { | ||
method: RequestMethod.GET, | ||
}; | ||
try { | ||
const response = yield this.send(url, options, callback); | ||
return response; | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
}); | ||
} | ||
@@ -447,20 +459,22 @@ /** | ||
*/ | ||
async post(content, callback) { | ||
const url = this.buildFullUrl(); | ||
const options = { | ||
method: RequestMethod.POST, | ||
body: serializeContent(content), | ||
headers: content.constructor !== undefined && content.constructor.name === "FormData" | ||
? {} | ||
: { | ||
"Content-Type": "application/json", | ||
}, | ||
}; | ||
try { | ||
const response = await this.send(url, options, callback); | ||
return response; | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
post(content, callback) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const url = this.buildFullUrl(); | ||
const options = { | ||
method: RequestMethod.POST, | ||
body: serializeContent(content), | ||
headers: content.constructor !== undefined && content.constructor.name === "FormData" | ||
? {} | ||
: { | ||
"Content-Type": "application/json", | ||
}, | ||
}; | ||
try { | ||
const response = yield this.send(url, options, callback); | ||
return response; | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
}); | ||
} | ||
@@ -475,9 +489,11 @@ /** | ||
*/ | ||
async create(content, callback) { | ||
try { | ||
return await this.post(content, callback); | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
create(content, callback) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
return yield this.post(content, callback); | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
}); | ||
} | ||
@@ -492,18 +508,20 @@ /** | ||
*/ | ||
async put(content, callback) { | ||
const url = this.buildFullUrl(); | ||
const options = { | ||
method: RequestMethod.PUT, | ||
body: serializeContent(content), | ||
headers: { | ||
"Content-Type": "application/octet-stream", | ||
}, | ||
}; | ||
try { | ||
const response = await this.send(url, options, callback); | ||
return response; | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
put(content, callback) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const url = this.buildFullUrl(); | ||
const options = { | ||
method: RequestMethod.PUT, | ||
body: serializeContent(content), | ||
headers: { | ||
"Content-Type": "application/octet-stream", | ||
}, | ||
}; | ||
try { | ||
const response = yield this.send(url, options, callback); | ||
return response; | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
}); | ||
} | ||
@@ -518,18 +536,20 @@ /** | ||
*/ | ||
async patch(content, callback) { | ||
const url = this.buildFullUrl(); | ||
const options = { | ||
method: RequestMethod.PATCH, | ||
body: serializeContent(content), | ||
headers: { | ||
"Content-Type": "application/json", | ||
}, | ||
}; | ||
try { | ||
const response = await this.send(url, options, callback); | ||
return response; | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
patch(content, callback) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const url = this.buildFullUrl(); | ||
const options = { | ||
method: RequestMethod.PATCH, | ||
body: serializeContent(content), | ||
headers: { | ||
"Content-Type": "application/json", | ||
}, | ||
}; | ||
try { | ||
const response = yield this.send(url, options, callback); | ||
return response; | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
}); | ||
} | ||
@@ -544,9 +564,11 @@ /** | ||
*/ | ||
async update(content, callback) { | ||
try { | ||
return await this.patch(content, callback); | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
update(content, callback) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
return yield this.patch(content, callback); | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
}); | ||
} | ||
@@ -560,14 +582,16 @@ /** | ||
*/ | ||
async delete(callback) { | ||
const url = this.buildFullUrl(); | ||
const options = { | ||
method: RequestMethod.DELETE, | ||
}; | ||
try { | ||
const response = await this.send(url, options, callback); | ||
return response; | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
delete(callback) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const url = this.buildFullUrl(); | ||
const options = { | ||
method: RequestMethod.DELETE, | ||
}; | ||
try { | ||
const response = yield this.send(url, options, callback); | ||
return response; | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
}); | ||
} | ||
@@ -581,9 +605,11 @@ /** | ||
*/ | ||
async del(callback) { | ||
try { | ||
return await this.delete(callback); | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
del(callback) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
return yield this.delete(callback); | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
}); | ||
} | ||
@@ -597,15 +623,17 @@ /** | ||
*/ | ||
async getStream(callback) { | ||
const url = this.buildFullUrl(); | ||
const options = { | ||
method: RequestMethod.GET, | ||
}; | ||
this.responseType(ResponseType.STREAM); | ||
try { | ||
const stream = await this.send(url, options, callback); | ||
return stream; | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
getStream(callback) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const url = this.buildFullUrl(); | ||
const options = { | ||
method: RequestMethod.GET, | ||
}; | ||
this.responseType(ResponseType.STREAM); | ||
try { | ||
const stream = yield this.send(url, options, callback); | ||
return stream; | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
}); | ||
} | ||
@@ -620,20 +648,22 @@ /** | ||
*/ | ||
async putStream(stream, callback) { | ||
const url = this.buildFullUrl(); | ||
const options = { | ||
method: RequestMethod.PUT, | ||
headers: { | ||
"Content-Type": "application/octet-stream", | ||
}, | ||
body: stream, | ||
}; | ||
try { | ||
const response = await this.send(url, options, callback); | ||
return response; | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
putStream(stream, callback) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const url = this.buildFullUrl(); | ||
const options = { | ||
method: RequestMethod.PUT, | ||
headers: { | ||
"Content-Type": "application/octet-stream", | ||
}, | ||
body: stream, | ||
}; | ||
try { | ||
const response = yield this.send(url, options, callback); | ||
return response; | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
}); | ||
} | ||
} | ||
//# sourceMappingURL=GraphRequest.js.map |
@@ -7,2 +7,10 @@ /** | ||
*/ | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
import { ResponseType } from "./ResponseType"; | ||
@@ -92,70 +100,72 @@ /** | ||
*/ | ||
static async convertResponse(rawResponse, responseType) { | ||
const clonedRawResponse = rawResponse.clone(); | ||
if (clonedRawResponse.status === 204) { | ||
// NO CONTENT | ||
return Promise.resolve(); | ||
} | ||
let responseValue; | ||
try { | ||
switch (responseType) { | ||
case ResponseType.ARRAYBUFFER: | ||
responseValue = await clonedRawResponse.arrayBuffer(); | ||
break; | ||
case ResponseType.BLOB: | ||
responseValue = await clonedRawResponse.blob(); | ||
break; | ||
case ResponseType.DOCUMENT: | ||
responseValue = await GraphResponseHandler.parseDocumentResponse(clonedRawResponse, DocumentType.TEXT_XML); | ||
break; | ||
case ResponseType.JSON: | ||
responseValue = await clonedRawResponse.json(); | ||
break; | ||
case ResponseType.STREAM: | ||
responseValue = await Promise.resolve(clonedRawResponse.body); | ||
break; | ||
case ResponseType.TEXT: | ||
responseValue = await clonedRawResponse.text(); | ||
break; | ||
default: | ||
const contentType = clonedRawResponse.headers.get("Content-type"); | ||
if (contentType !== null) { | ||
const mimeType = contentType.split(";")[0]; | ||
if (new RegExp(ContentTypeRegexStr.DOCUMENT).test(mimeType)) { | ||
responseValue = await GraphResponseHandler.parseDocumentResponse(clonedRawResponse, mimeType); | ||
static convertResponse(rawResponse, responseType) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const clonedRawResponse = rawResponse.clone(); | ||
if (clonedRawResponse.status === 204) { | ||
// NO CONTENT | ||
return Promise.resolve(); | ||
} | ||
let responseValue; | ||
try { | ||
switch (responseType) { | ||
case ResponseType.ARRAYBUFFER: | ||
responseValue = yield clonedRawResponse.arrayBuffer(); | ||
break; | ||
case ResponseType.BLOB: | ||
responseValue = yield clonedRawResponse.blob(); | ||
break; | ||
case ResponseType.DOCUMENT: | ||
responseValue = yield GraphResponseHandler.parseDocumentResponse(clonedRawResponse, DocumentType.TEXT_XML); | ||
break; | ||
case ResponseType.JSON: | ||
responseValue = yield clonedRawResponse.json(); | ||
break; | ||
case ResponseType.STREAM: | ||
responseValue = yield Promise.resolve(clonedRawResponse.body); | ||
break; | ||
case ResponseType.TEXT: | ||
responseValue = yield clonedRawResponse.text(); | ||
break; | ||
default: | ||
const contentType = clonedRawResponse.headers.get("Content-type"); | ||
if (contentType !== null) { | ||
const mimeType = contentType.split(";")[0]; | ||
if (new RegExp(ContentTypeRegexStr.DOCUMENT).test(mimeType)) { | ||
responseValue = yield GraphResponseHandler.parseDocumentResponse(clonedRawResponse, mimeType); | ||
} | ||
else if (new RegExp(ContentTypeRegexStr.IMAGE).test(mimeType)) { | ||
responseValue = clonedRawResponse.blob(); | ||
} | ||
else if (mimeType === ContentType.TEXT_PLAIN) { | ||
responseValue = yield clonedRawResponse.text(); | ||
} | ||
else if (mimeType === ContentType.APPLICATION_JSON) { | ||
responseValue = yield clonedRawResponse.json(); | ||
} | ||
else { | ||
responseValue = Promise.resolve(clonedRawResponse.body); | ||
} | ||
} | ||
else if (new RegExp(ContentTypeRegexStr.IMAGE).test(mimeType)) { | ||
responseValue = clonedRawResponse.blob(); | ||
} | ||
else if (mimeType === ContentType.TEXT_PLAIN) { | ||
responseValue = await clonedRawResponse.text(); | ||
} | ||
else if (mimeType === ContentType.APPLICATION_JSON) { | ||
responseValue = await clonedRawResponse.json(); | ||
} | ||
else { | ||
/** | ||
* 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(clonedRawResponse.body); | ||
} | ||
} | ||
else { | ||
/** | ||
* 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(clonedRawResponse.body); | ||
} | ||
break; | ||
break; | ||
} | ||
} | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
return responseValue; | ||
catch (error) { | ||
throw error; | ||
} | ||
return responseValue; | ||
}); | ||
} | ||
@@ -172,29 +182,31 @@ /** | ||
*/ | ||
static async getResponse(rawResponse, responseType, callback) { | ||
try { | ||
if (responseType === ResponseType.RAW) { | ||
return Promise.resolve(rawResponse); | ||
} | ||
else { | ||
const response = await GraphResponseHandler.convertResponse(rawResponse, responseType); | ||
if (rawResponse.ok) { | ||
// Status Code 2XX | ||
if (typeof callback === "function") { | ||
callback(null, response, rawResponse); | ||
static getResponse(rawResponse, responseType, callback) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
if (responseType === ResponseType.RAW) { | ||
return Promise.resolve(rawResponse); | ||
} | ||
else { | ||
const response = yield GraphResponseHandler.convertResponse(rawResponse, responseType); | ||
if (rawResponse.ok) { | ||
// Status Code 2XX | ||
if (typeof callback === "function") { | ||
callback(null, response, rawResponse); | ||
} | ||
else { | ||
return response; | ||
} | ||
} | ||
else { | ||
return response; | ||
// NOT OK Response | ||
throw response; | ||
} | ||
} | ||
else { | ||
// NOT OK Response | ||
throw response; | ||
} | ||
} | ||
} | ||
catch (error) { | ||
throw rawResponse.ok ? error : rawResponse; | ||
} | ||
catch (error) { | ||
throw rawResponse.ok ? error : rawResponse; | ||
} | ||
}); | ||
} | ||
} | ||
//# sourceMappingURL=GraphResponseHandler.js.map |
@@ -7,2 +7,10 @@ /** | ||
*/ | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
/** | ||
@@ -29,18 +37,20 @@ * @class | ||
*/ | ||
async sendRequest(context) { | ||
try { | ||
if (!(context.request instanceof Request) && context.options === undefined) { | ||
const error = new Error(); | ||
error.name = "InvalidRequestOptions"; | ||
error.message = "Unable to execute the middleware, Please provide valid options for a request"; | ||
sendRequest(context) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
if (!(context.request instanceof Request) && context.options === undefined) { | ||
const error = new Error(); | ||
error.name = "InvalidRequestOptions"; | ||
error.message = "Unable to execute the middleware, Please provide valid options for a request"; | ||
throw error; | ||
} | ||
yield this.middleware.execute(context); | ||
return context; | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
await this.middleware.execute(context); | ||
return context; | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
}); | ||
} | ||
} | ||
//# sourceMappingURL=HTTPClient.js.map |
@@ -7,2 +7,10 @@ /** | ||
*/ | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
import { MiddlewareControl } from "./MiddlewareControl"; | ||
@@ -33,25 +41,27 @@ import { setRequestHeader } from "./MiddlewareUtil"; | ||
*/ | ||
async execute(context) { | ||
try { | ||
let options; | ||
if (context.middlewareControl instanceof MiddlewareControl) { | ||
options = context.middlewareControl.getMiddlewareOptions(AuthenticationHandlerOptions.name); | ||
execute(context) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
let options; | ||
if (context.middlewareControl instanceof MiddlewareControl) { | ||
options = context.middlewareControl.getMiddlewareOptions(AuthenticationHandlerOptions.name); | ||
} | ||
let authenticationProvider; | ||
let authenticationProviderOptions; | ||
if (typeof options !== "undefined") { | ||
authenticationProvider = options.authenticationProvider; | ||
authenticationProviderOptions = options.authenticationProviderOptions; | ||
} | ||
if (typeof authenticationProvider === "undefined") { | ||
authenticationProvider = this.authenticationProvider; | ||
} | ||
const token = yield authenticationProvider.getAccessToken(authenticationProviderOptions); | ||
const bearerKey = `Bearer ${token}`; | ||
setRequestHeader(context.request, context.options, AuthenticationHandler.AUTHORIZATION_HEADER, bearerKey); | ||
return yield this.nextMiddleware.execute(context); | ||
} | ||
let authenticationProvider; | ||
let authenticationProviderOptions; | ||
if (typeof options !== "undefined") { | ||
authenticationProvider = options.authenticationProvider; | ||
authenticationProviderOptions = options.authenticationProviderOptions; | ||
catch (error) { | ||
throw error; | ||
} | ||
if (typeof authenticationProvider === "undefined") { | ||
authenticationProvider = this.authenticationProvider; | ||
} | ||
const token = await authenticationProvider.getAccessToken(authenticationProviderOptions); | ||
const bearerKey = `Bearer ${token}`; | ||
setRequestHeader(context.request, context.options, AuthenticationHandler.AUTHORIZATION_HEADER, bearerKey); | ||
return await this.nextMiddleware.execute(context); | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
}); | ||
} | ||
@@ -58,0 +68,0 @@ /** |
@@ -7,2 +7,10 @@ /** | ||
*/ | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
/** | ||
@@ -21,12 +29,14 @@ * @class | ||
*/ | ||
async execute(context) { | ||
try { | ||
context.response = await fetch(context.request, context.options); | ||
return; | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
execute(context) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
context.response = yield fetch(context.request, context.options); | ||
return; | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
}); | ||
} | ||
} | ||
//# sourceMappingURL=HTTPMessageHandler.js.map |
@@ -7,2 +7,10 @@ /** | ||
*/ | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
/** | ||
@@ -79,7 +87,7 @@ * @constant | ||
*/ | ||
export const cloneRequestWithNewUrl = async (newUrl, request) => { | ||
const body = request.headers.get("Content-Type") ? await request.blob() : await Promise.resolve(undefined); | ||
export const cloneRequestWithNewUrl = (newUrl, request) => __awaiter(this, void 0, void 0, function* () { | ||
const body = request.headers.get("Content-Type") ? yield request.blob() : yield Promise.resolve(undefined); | ||
const { method, headers, referrer, referrerPolicy, mode, credentials, cache, redirect, integrity, keepalive, signal } = request; | ||
return new Request(newUrl, { method, headers, body, referrer, referrerPolicy, mode, credentials, cache, redirect, integrity, keepalive, signal }); | ||
}; | ||
}); | ||
//# sourceMappingURL=MiddlewareUtil.js.map |
@@ -7,2 +7,10 @@ /** | ||
*/ | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
import { RequestMethod } from "../RequestMethod"; | ||
@@ -94,4 +102,6 @@ import { MiddlewareControl } from "./MiddlewareControl"; | ||
*/ | ||
async updateRequestUrl(redirectUrl, context) { | ||
context.request = context.request instanceof Request ? await cloneRequestWithNewUrl(redirectUrl, context.request) : redirectUrl; | ||
updateRequestUrl(redirectUrl, context) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
context.request = context.request instanceof Request ? yield cloneRequestWithNewUrl(redirectUrl, context.request) : redirectUrl; | ||
}); | ||
} | ||
@@ -123,28 +133,30 @@ /** | ||
*/ | ||
async executeWithRedirect(context, redirectCount, options) { | ||
try { | ||
await this.nextMiddleware.execute(context); | ||
const response = context.response; | ||
if (redirectCount < options.maxRedirects && this.isRedirect(response) && this.hasLocationHeader(response) && options.shouldRedirect(response)) { | ||
++redirectCount; | ||
if (response.status === RedirectHandler.STATUS_CODE_SEE_OTHER) { | ||
context.options.method = RequestMethod.GET; | ||
delete context.options.body; | ||
executeWithRedirect(context, redirectCount, options) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
yield this.nextMiddleware.execute(context); | ||
const response = context.response; | ||
if (redirectCount < options.maxRedirects && this.isRedirect(response) && this.hasLocationHeader(response) && options.shouldRedirect(response)) { | ||
++redirectCount; | ||
if (response.status === RedirectHandler.STATUS_CODE_SEE_OTHER) { | ||
context.options.method = RequestMethod.GET; | ||
delete context.options.body; | ||
} | ||
else { | ||
const redirectUrl = this.getLocationHeader(response); | ||
if (!this.isRelativeURL(redirectUrl) && this.shouldDropAuthorizationHeader(response.url, redirectUrl)) { | ||
setRequestHeader(context.request, context.options, RedirectHandler.AUTHORIZATION_HEADER, undefined); | ||
} | ||
yield this.updateRequestUrl(redirectUrl, context); | ||
} | ||
yield this.executeWithRedirect(context, redirectCount, options); | ||
} | ||
else { | ||
const redirectUrl = this.getLocationHeader(response); | ||
if (!this.isRelativeURL(redirectUrl) && this.shouldDropAuthorizationHeader(response.url, redirectUrl)) { | ||
setRequestHeader(context.request, context.options, RedirectHandler.AUTHORIZATION_HEADER, undefined); | ||
} | ||
await this.updateRequestUrl(redirectUrl, context); | ||
return; | ||
} | ||
await this.executeWithRedirect(context, redirectCount, options); | ||
} | ||
else { | ||
return; | ||
catch (error) { | ||
throw error; | ||
} | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
}); | ||
} | ||
@@ -158,12 +170,14 @@ /** | ||
*/ | ||
async execute(context) { | ||
try { | ||
const redirectCount = 0; | ||
const options = this.getOptions(context); | ||
context.options.redirect = RedirectHandler.MANUAL_REDIRECT; | ||
return await this.executeWithRedirect(context, redirectCount, options); | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
execute(context) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
const redirectCount = 0; | ||
const options = this.getOptions(context); | ||
context.options.redirect = RedirectHandler.MANUAL_REDIRECT; | ||
return yield this.executeWithRedirect(context, redirectCount, options); | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
}); | ||
} | ||
@@ -170,0 +184,0 @@ /** |
@@ -7,2 +7,10 @@ /** | ||
*/ | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
import { RequestMethod } from "../RequestMethod"; | ||
@@ -91,3 +99,3 @@ import { MiddlewareControl } from "./MiddlewareControl"; | ||
getExponentialBackOffTime(attempts) { | ||
return Math.round((1 / 2) * (2 ** attempts - 1)); | ||
return Math.round((1 / 2) * (Math.pow(2, attempts) - 1)); | ||
} | ||
@@ -101,5 +109,7 @@ /** | ||
*/ | ||
async sleep(delaySeconds) { | ||
const delayMilliseconds = delaySeconds * 1000; | ||
return new Promise((resolve) => setTimeout(resolve, delayMilliseconds)); | ||
sleep(delaySeconds) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const delayMilliseconds = delaySeconds * 1000; | ||
return new Promise((resolve) => setTimeout(resolve, delayMilliseconds)); | ||
}); | ||
} | ||
@@ -125,19 +135,21 @@ getOptions(context) { | ||
*/ | ||
async executeWithRetry(context, retryAttempts, options) { | ||
try { | ||
await this.nextMiddleware.execute(context); | ||
if (retryAttempts < options.maxRetries && this.isRetry(context.response) && this.isBuffered(context.request, context.options) && options.shouldRetry(options.delay, retryAttempts, context.request, context.options, context.response)) { | ||
++retryAttempts; | ||
setRequestHeader(context.request, context.options, RetryHandler.RETRY_ATTEMPT_HEADER, retryAttempts.toString()); | ||
const delay = this.getDelay(context.response, retryAttempts, options.delay); | ||
await this.sleep(delay); | ||
return await this.executeWithRetry(context, retryAttempts, options); | ||
executeWithRetry(context, retryAttempts, options) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
yield this.nextMiddleware.execute(context); | ||
if (retryAttempts < options.maxRetries && this.isRetry(context.response) && this.isBuffered(context.request, context.options) && options.shouldRetry(options.delay, retryAttempts, context.request, context.options, context.response)) { | ||
++retryAttempts; | ||
setRequestHeader(context.request, context.options, RetryHandler.RETRY_ATTEMPT_HEADER, retryAttempts.toString()); | ||
const delay = this.getDelay(context.response, retryAttempts, options.delay); | ||
yield this.sleep(delay); | ||
return yield this.executeWithRetry(context, retryAttempts, options); | ||
} | ||
else { | ||
return; | ||
} | ||
} | ||
else { | ||
return; | ||
catch (error) { | ||
throw error; | ||
} | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
}); | ||
} | ||
@@ -151,11 +163,13 @@ /** | ||
*/ | ||
async execute(context) { | ||
try { | ||
const retryAttempts = 0; | ||
const options = this.getOptions(context); | ||
return await this.executeWithRetry(context, retryAttempts, options); | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
execute(context) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
const retryAttempts = 0; | ||
const options = this.getOptions(context); | ||
return yield this.executeWithRetry(context, retryAttempts, options); | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
}); | ||
} | ||
@@ -162,0 +176,0 @@ /** |
@@ -7,2 +7,10 @@ /** | ||
*/ | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
/** | ||
@@ -39,37 +47,39 @@ * @module MSALAuthenticationProvider | ||
*/ | ||
async getAccessToken(authenticationProviderOptions) { | ||
const options = authenticationProviderOptions; | ||
let scopes; | ||
if (typeof options !== "undefined") { | ||
scopes = options.scopes; | ||
} | ||
if (typeof scopes === "undefined" || scopes.length === 0) { | ||
scopes = this.scopes; | ||
} | ||
if (scopes.length === 0) { | ||
const error = new Error(); | ||
error.name = "EmptyScopes"; | ||
error.message = "Scopes cannot be empty, Please provide a scope"; | ||
throw error; | ||
} | ||
try { | ||
const accessToken = await this.userAgentApplication.acquireTokenSilent(scopes); | ||
return accessToken; | ||
} | ||
catch (errorMsg) { | ||
getAccessToken(authenticationProviderOptions) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const options = authenticationProviderOptions; | ||
let scopes; | ||
if (typeof options !== "undefined") { | ||
scopes = options.scopes; | ||
} | ||
if (typeof scopes === "undefined" || scopes.length === 0) { | ||
scopes = this.scopes; | ||
} | ||
if (scopes.length === 0) { | ||
const error = new Error(); | ||
error.name = "EmptyScopes"; | ||
error.message = "Scopes cannot be empty, Please provide a scope"; | ||
throw error; | ||
} | ||
try { | ||
const idToken = await this.userAgentApplication.loginPopup(scopes); | ||
const accessToken = yield this.userAgentApplication.acquireTokenSilent(scopes); | ||
return accessToken; | ||
} | ||
catch (errorMsg) { | ||
try { | ||
const accessToken = await this.userAgentApplication.acquireTokenSilent(scopes); | ||
return accessToken; | ||
const idToken = yield this.userAgentApplication.loginPopup(scopes); | ||
try { | ||
const accessToken = yield this.userAgentApplication.acquireTokenSilent(scopes); | ||
return accessToken; | ||
} | ||
catch (error) { | ||
const accessToken = yield this.userAgentApplication.acquireTokenPopup(scopes); | ||
return accessToken; | ||
} | ||
} | ||
catch (error) { | ||
const accessToken = await this.userAgentApplication.acquireTokenPopup(scopes); | ||
return accessToken; | ||
catch (errorMsg) { | ||
throw new Error(errorMsg); | ||
} | ||
} | ||
catch (errorMsg) { | ||
throw new Error(errorMsg); | ||
} | ||
} | ||
}); | ||
} | ||
@@ -76,0 +86,0 @@ /** |
@@ -7,2 +7,10 @@ /** | ||
*/ | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
import { Range } from "../Range"; | ||
@@ -100,25 +108,27 @@ /** | ||
*/ | ||
async upload() { | ||
try { | ||
while (true) { | ||
const nextRange = this.getNextRange(); | ||
if (nextRange.maxValue === -1) { | ||
const err = new Error("Task with which you are trying to upload is already completed, Please check for your uploaded file"); | ||
err.name = "Invalid Session"; | ||
throw err; | ||
upload() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
while (true) { | ||
const nextRange = this.getNextRange(); | ||
if (nextRange.maxValue === -1) { | ||
const err = new Error("Task with which you are trying to upload is already completed, Please check for your uploaded file"); | ||
err.name = "Invalid Session"; | ||
throw err; | ||
} | ||
const fileSlice = this.sliceFile(nextRange); | ||
const response = yield this.uploadSlice(fileSlice, nextRange, this.file.size); | ||
// Upon completion of upload process incase of onedrive, driveItem is returned, which contains id | ||
if (response.id !== undefined) { | ||
return response; | ||
} | ||
else { | ||
this.updateTaskStatus(response); | ||
} | ||
} | ||
const fileSlice = this.sliceFile(nextRange); | ||
const response = await this.uploadSlice(fileSlice, nextRange, this.file.size); | ||
// Upon completion of upload process incase of onedrive, driveItem is returned, which contains id | ||
if (response.id !== undefined) { | ||
return response; | ||
} | ||
else { | ||
this.updateTaskStatus(response); | ||
} | ||
} | ||
} | ||
catch (err) { | ||
throw err; | ||
} | ||
catch (err) { | ||
throw err; | ||
} | ||
}); | ||
} | ||
@@ -133,15 +143,17 @@ /** | ||
*/ | ||
async uploadSlice(fileSlice, range, totalSize) { | ||
try { | ||
return await this.client | ||
.api(this.uploadSession.url) | ||
.headers({ | ||
"Content-Length": `${range.maxValue - range.minValue + 1}`, | ||
"Content-Range": `bytes ${range.minValue}-${range.maxValue}/${totalSize}`, | ||
}) | ||
.put(fileSlice); | ||
} | ||
catch (err) { | ||
throw err; | ||
} | ||
uploadSlice(fileSlice, range, totalSize) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
return yield this.client | ||
.api(this.uploadSession.url) | ||
.headers({ | ||
"Content-Length": `${range.maxValue - range.minValue + 1}`, | ||
"Content-Range": `bytes ${range.minValue}-${range.maxValue}/${totalSize}`, | ||
}) | ||
.put(fileSlice); | ||
} | ||
catch (err) { | ||
throw err; | ||
} | ||
}); | ||
} | ||
@@ -154,9 +166,11 @@ /** | ||
*/ | ||
async cancel() { | ||
try { | ||
return await this.client.api(this.uploadSession.url).delete(); | ||
} | ||
catch (err) { | ||
throw err; | ||
} | ||
cancel() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
return yield this.client.api(this.uploadSession.url).delete(); | ||
} | ||
catch (err) { | ||
throw err; | ||
} | ||
}); | ||
} | ||
@@ -169,11 +183,13 @@ /** | ||
*/ | ||
async getStatus() { | ||
try { | ||
const response = await this.client.api(this.uploadSession.url).get(); | ||
this.updateTaskStatus(response); | ||
return response; | ||
} | ||
catch (err) { | ||
throw err; | ||
} | ||
getStatus() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
const response = yield this.client.api(this.uploadSession.url).get(); | ||
this.updateTaskStatus(response); | ||
return response; | ||
} | ||
catch (err) { | ||
throw err; | ||
} | ||
}); | ||
} | ||
@@ -186,12 +202,14 @@ /** | ||
*/ | ||
async resume() { | ||
try { | ||
await this.getStatus(); | ||
return await this.upload(); | ||
} | ||
catch (err) { | ||
throw err; | ||
} | ||
resume() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
yield this.getStatus(); | ||
return yield this.upload(); | ||
} | ||
catch (err) { | ||
throw err; | ||
} | ||
}); | ||
} | ||
} | ||
//# sourceMappingURL=LargeFileUploadTask.js.map |
@@ -7,2 +7,10 @@ /** | ||
*/ | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
import { LargeFileUploadTask } from "./LargeFileUploadTask"; | ||
@@ -38,37 +46,39 @@ import { getValidRangeSize } from "./OneDriveLargeFileUploadTaskUtil"; | ||
*/ | ||
static async create(client, file, options) { | ||
const name = options.fileName; | ||
let content; | ||
let size; | ||
switch (file.constructor.name) { | ||
case "Blob": | ||
content = new File([file], name); | ||
size = content.size; | ||
break; | ||
case "File": | ||
content = file; | ||
size = content.size; | ||
break; | ||
case "Buffer": | ||
const b = file; | ||
size = b.byteLength - b.byteOffset; | ||
content = b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength); | ||
break; | ||
} | ||
try { | ||
const requestUrl = OneDriveLargeFileUploadTask.constructCreateSessionUrl(options.fileName, options.path); | ||
const session = await OneDriveLargeFileUploadTask.createUploadSession(client, requestUrl, options.fileName); | ||
const rangeSize = getValidRangeSize(options.rangeSize); | ||
const fileObj = { | ||
name, | ||
content, | ||
size, | ||
}; | ||
return new OneDriveLargeFileUploadTask(client, fileObj, session, { | ||
rangeSize, | ||
}); | ||
} | ||
catch (err) { | ||
throw err; | ||
} | ||
static create(client, file, options) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const name = options.fileName; | ||
let content; | ||
let size; | ||
switch (file.constructor.name) { | ||
case "Blob": | ||
content = new File([file], name); | ||
size = content.size; | ||
break; | ||
case "File": | ||
content = file; | ||
size = content.size; | ||
break; | ||
case "Buffer": | ||
const b = file; | ||
size = b.byteLength - b.byteOffset; | ||
content = b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength); | ||
break; | ||
} | ||
try { | ||
const requestUrl = OneDriveLargeFileUploadTask.constructCreateSessionUrl(options.fileName, options.path); | ||
const session = yield OneDriveLargeFileUploadTask.createUploadSession(client, requestUrl, options.fileName); | ||
const rangeSize = getValidRangeSize(options.rangeSize); | ||
const fileObj = { | ||
name, | ||
content, | ||
size, | ||
}; | ||
return new OneDriveLargeFileUploadTask(client, fileObj, session, { | ||
rangeSize, | ||
}); | ||
} | ||
catch (err) { | ||
throw err; | ||
} | ||
}); | ||
} | ||
@@ -107,20 +117,22 @@ /** | ||
*/ | ||
static async createUploadSession(client, requestUrl, fileName) { | ||
const payload = { | ||
item: { | ||
"@microsoft.graph.conflictBehavior": "rename", | ||
name: fileName, | ||
}, | ||
}; | ||
try { | ||
const session = await client.api(requestUrl).post(payload); | ||
const largeFileUploadSession = { | ||
url: session.uploadUrl, | ||
expiry: new Date(session.expirationDateTime), | ||
static createUploadSession(client, requestUrl, fileName) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
const payload = { | ||
item: { | ||
"@microsoft.graph.conflictBehavior": "rename", | ||
name: fileName, | ||
}, | ||
}; | ||
return largeFileUploadSession; | ||
} | ||
catch (err) { | ||
throw err; | ||
} | ||
try { | ||
const session = yield client.api(requestUrl).post(payload); | ||
const largeFileUploadSession = { | ||
url: session.uploadUrl, | ||
expiry: new Date(session.expirationDateTime), | ||
}; | ||
return largeFileUploadSession; | ||
} | ||
catch (err) { | ||
throw err; | ||
} | ||
}); | ||
} | ||
@@ -133,14 +145,16 @@ /** | ||
*/ | ||
async commit(requestUrl) { | ||
try { | ||
const payload = { | ||
name: this.file.name, | ||
"@microsoft.graph.conflictBehavior": "rename", | ||
"@microsoft.graph.sourceUrl": this.uploadSession.url, | ||
}; | ||
return await this.client.api(requestUrl).put(payload); | ||
} | ||
catch (err) { | ||
throw err; | ||
} | ||
commit(requestUrl) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
const payload = { | ||
name: this.file.name, | ||
"@microsoft.graph.conflictBehavior": "rename", | ||
"@microsoft.graph.sourceUrl": this.uploadSession.url, | ||
}; | ||
return yield this.client.api(requestUrl).put(payload); | ||
} | ||
catch (err) { | ||
throw err; | ||
} | ||
}); | ||
} | ||
@@ -147,0 +161,0 @@ } |
@@ -7,2 +7,10 @@ /** | ||
*/ | ||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
}; | ||
/** | ||
@@ -52,12 +60,14 @@ * @class | ||
*/ | ||
async fetchAndUpdateNextPageData() { | ||
try { | ||
const response = await this.client.api(this.nextLink).get(); | ||
this.collection = response.value; | ||
this.nextLink = response["@odata.nextLink"]; | ||
this.deltaLink = response["@odata.deltaLink"]; | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
fetchAndUpdateNextPageData() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
const response = yield this.client.api(this.nextLink).get(); | ||
this.collection = response.value; | ||
this.nextLink = response["@odata.nextLink"]; | ||
this.deltaLink = response["@odata.deltaLink"]; | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
}); | ||
} | ||
@@ -79,21 +89,23 @@ /** | ||
*/ | ||
async iterate() { | ||
try { | ||
let advance = this.iterationHelper(); | ||
while (advance) { | ||
if (this.nextLink !== undefined) { | ||
await this.fetchAndUpdateNextPageData(); | ||
advance = this.iterationHelper(); | ||
iterate() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
let advance = this.iterationHelper(); | ||
while (advance) { | ||
if (this.nextLink !== undefined) { | ||
yield this.fetchAndUpdateNextPageData(); | ||
advance = this.iterationHelper(); | ||
} | ||
else { | ||
advance = false; | ||
} | ||
} | ||
else { | ||
advance = false; | ||
if (this.nextLink === undefined && this.collection.length === 0) { | ||
this.complete = true; | ||
} | ||
} | ||
if (this.nextLink === undefined && this.collection.length === 0) { | ||
this.complete = true; | ||
catch (error) { | ||
throw error; | ||
} | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
}); | ||
} | ||
@@ -107,9 +119,11 @@ /** | ||
*/ | ||
async resume() { | ||
try { | ||
return this.iterate(); | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
resume() { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
try { | ||
return this.iterate(); | ||
} | ||
catch (error) { | ||
throw error; | ||
} | ||
}); | ||
} | ||
@@ -116,0 +130,0 @@ /** |
@@ -1,1 +0,1 @@ | ||
var e;!function(e){e.GET="GET",e.PATCH="PATCH",e.POST="POST",e.PUT="PUT",e.DELETE="DELETE"}(e||(e={}));class t{constructor(e){if(this.requests=new Map,void 0!==e){const s=t.requestLimit;if(e.length>s){const e=new Error(`Maximum requests limit exceeded, Max allowed number of requests are ${s}`);throw e.name="Limit Exceeded Error",e}for(const t of e)this.addRequest(t)}}static validateDependencies(e){if(0===e.size){const e=new Error("Empty requests map, Please provide at least one request.");throw e.name="Empty Requests Error",e}return(e=>{const t=e.entries();let s=t.next();for(;!s.done;){const e=s.value[1];if(void 0!==e.dependsOn&&e.dependsOn.length>0)return!1;s=t.next()}return!0})(e)||(e=>{const t=e.entries();let s=t.next();const r=s.value[1];if(void 0!==r.dependsOn&&r.dependsOn.length>0)return!1;let n=s;for(s=t.next();!s.done;){const e=s.value[1];if(void 0===e.dependsOn||1!==e.dependsOn.length||e.dependsOn[0]!==n.value[1].id)return!1;n=s,s=t.next()}return!0})(e)||(e=>{const t=e.entries();let s=t.next();const r=s.value[1];let n;if(void 0===r.dependsOn||0===r.dependsOn.length)n=r.id;else{if(1!==r.dependsOn.length)return!1;{const t=r.dependsOn[0];if(t===r.id||!e.has(t))return!1;n=t}}for(s=t.next();!s.done;){const e=s.value[1];if((void 0===e.dependsOn||0===e.dependsOn.length)&&n!==e.id)return!1;if(void 0!==e.dependsOn&&0!==e.dependsOn.length){if(1===e.dependsOn.length&&(e.id===n||e.dependsOn[0]!==n))return!1;if(e.dependsOn.length>1)return!1}s=t.next()}return!0})(e)}static async getRequestData(s){const r={url:""},n=new RegExp("^https?://");r.url=n.test(s.url)?"/"+s.url.split(/.*?\/\/.*?\//)[1]:s.url,r.method=s.method;const i={};return s.headers.forEach((e,t)=>{i[t]=e}),Object.keys(i).length&&(r.headers=i),s.method!==e.PATCH&&s.method!==e.POST&&s.method!==e.PUT||(r.body=await t.getRequestBody(s)),r}static async getRequestBody(e){let t,s=!1;try{const r=e.clone();t=await r.json(),s=!0}catch(e){}if(!s)try{if("undefined"!=typeof Blob){const s=await e.blob(),r=new FileReader;t=await new Promise(e=>{r.addEventListener("load",()=>{const t=r.result,s=new RegExp("^s*data:(.+?/.+?(;.+?=.+?)*)?(;base64)?,(.*)s*$").exec(t);e(s[4])},!1),r.readAsDataURL(s)})}else if("undefined"!=typeof Buffer){t=(await e.buffer()).toString("base64")}s=!0}catch(e){}return t}addRequest(e){const s=t.requestLimit;if(""===e.id){const e=new Error("Id for a request is empty, Please provide an unique id");throw e.name="Empty Id For Request",e}if(this.requests.size===s){const e=new Error(`Maximum requests limit exceeded, Max allowed number of requests are ${s}`);throw e.name="Limit Exceeded Error",e}if(this.requests.has(e.id)){const t=new Error(`Adding request with duplicate id ${e.id}, Make the id of the requests unique`);throw t.name="Duplicate RequestId Error",t}return this.requests.set(e.id,e),e.id}removeRequest(e){const t=this.requests.delete(e),s=this.requests.entries();let r=s.next();for(;!r.done;){const t=r.value[1].dependsOn;if(void 0!==t){const s=t.indexOf(e);-1!==s&&t.splice(s,1),0===t.length&&delete r.value[1].dependsOn}r=s.next()}return t}async getContent(){const e=[],s={requests:e},r=this.requests.entries();let n=r.next();if(n.done){const e=new Error("No requests added yet, Please add at least one request.");throw e.name="Empty Payload",e}if(!t.validateDependencies(this.requests)){const e=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.");throw e.name="Invalid Dependency",e}for(;!n.done;){const s=n.value[1],i=await t.getRequestData(s.request);if(void 0!==i.body&&(void 0===i.headers||void 0===i.headers["content-type"])){const e=new Error(`Content-type header is not mentioned for request #${s.id}, For request having body, Content-type header should be mentioned`);throw e.name="Invalid Content-type header",e}i.id=s.id,void 0!==s.dependsOn&&s.dependsOn.length>0&&(i.dependsOn=s.dependsOn),e.push(i),n=r.next()}return s.requests=e,s}addDependency(e,t){if(!this.requests.has(e)){const t=new Error(`Dependent ${e} does not exists, Please check the id`);throw t.name="Invalid Dependent",t}if(void 0!==t&&!this.requests.has(t)){const e=new Error(`Dependency ${t} does not exists, Please check the id`);throw e.name="Invalid Dependency",e}if(void 0!==t){const s=this.requests.get(e);if(void 0===s.dependsOn&&(s.dependsOn=[]),-1!==s.dependsOn.indexOf(t)){const s=new Error(`Dependency ${t} is already added for the request ${e}`);throw s.name="Duplicate Dependency",s}s.dependsOn.push(t)}else{const s=this.requests.entries();let r,n=s.next();for(;!n.done&&n.value[1].id!==e;)r=n,n=s.next();if(void 0===r){const e=new Error(`Can't add dependency ${t}, There is only a dependent request in the batch`);throw e.name="Invalid Dependency Addition",e}{const t=r.value[0];if(void 0===n.value[1].dependsOn&&(n.value[1].dependsOn=[]),-1!==n.value[1].dependsOn.indexOf(t)){const s=new Error(`Dependency ${t} is already added for the request ${e}`);throw s.name="Duplicate Dependency",s}n.value[1].dependsOn.push(t)}}}removeDependency(e,t){const s=this.requests.get(e);if(void 0===s||void 0===s.dependsOn||0===s.dependsOn.length)return!1;if(void 0!==t){const e=s.dependsOn.indexOf(t);return-1!==e&&(s.dependsOn.splice(e,1),!0)}return delete s.dependsOn,!0}}t.requestLimit=20;class s{constructor(e){this.responses=new Map,this.update(e)}createResponseObject(e){const t=e.body,s={};return s.status=e.status,void 0!==e.statusText&&(s.statusText=e.statusText),s.headers=e.headers,new Response(t,s)}update(e){this.nextLink=e["@nextLink"];const t=e.responses;for(let e=0,s=t.length;e<s;e++)this.responses.set(t[e].id,this.createResponseObject(t[e]))}getResponseById(e){return this.responses.get(e)}getResponses(){return this.responses}*getResponsesIterator(){const e=this.responses.entries();let t=e.next();for(;!t.done;)yield t.value,t=e.next()}}class r{constructor(e){this.middlewareOptions=new Map;for(const t of e){const e=t.constructor.name;this.middlewareOptions.set(e,t)}}getMiddlewareOptions(e){return this.middlewareOptions.get(e)}}const n=(e,t,s)=>{let r=null;if(e instanceof Request)r=e.headers.get(s);else if(void 0!==t&&void 0!==t.headers)if(t.headers instanceof Headers)r=t.headers.get(s);else if(t.headers instanceof Array){const e=t.headers;for(let t=0,n=e.length;t<n;t++)if(e[t][0]===s){r=e[t][1];break}}else void 0!==t.headers[s]&&(r=t.headers[s]);return r},i=(e,t,s,r)=>{e instanceof Request?e.headers.set(s,r):void 0!==t&&(void 0===t.headers?t.headers={[s]:r}:t.headers instanceof Headers?t.headers.set(s,r):t.headers instanceof Array?t.headers.push([s,r]):Object.assign(t.headers,{[s]:r}))},o=async(e,t)=>{const s=t.headers.get("Content-Type")?await t.blob():await Promise.resolve(void 0),{method:r,headers:n,referrer:i,referrerPolicy:o,mode:a,credentials:c,cache:d,redirect:h,integrity:l,keepalive:u,signal:p}=t;return new Request(e,{method:r,headers:n,body:s,referrer:i,referrerPolicy:o,mode:a,credentials:c,cache:d,redirect:h,integrity:l,keepalive:u,signal:p})};class a{constructor(e,t){this.authenticationProvider=e,this.authenticationProviderOptions=t}}class c{constructor(e){this.authenticationProvider=e}async execute(e){try{let t,s,n;e.middlewareControl instanceof r&&(t=e.middlewareControl.getMiddlewareOptions(a.name)),void 0!==t&&(s=t.authenticationProvider,n=t.authenticationProviderOptions),void 0===s&&(s=this.authenticationProvider);const o=`Bearer ${await s.getAccessToken(n)}`;return i(e.request,e.options,c.AUTHORIZATION_HEADER,o),await this.nextMiddleware.execute(e)}catch(e){throw e}}setNext(e){this.nextMiddleware=e}}c.AUTHORIZATION_HEADER="Authorization";class d{async execute(e){try{return void(e.response=await fetch(e.request,e.options))}catch(e){throw e}}}class h{constructor(e=h.DEFAULT_DELAY,t=h.DEFAULT_MAX_RETRIES,s=h.DEFAULT_SHOULD_RETRY){if(e>h.MAX_DELAY&&t>h.MAX_MAX_RETRIES){const e=new Error(`Delay and MaxRetries should not be more than ${h.MAX_DELAY} and ${h.MAX_MAX_RETRIES}`);throw e.name="MaxLimitExceeded",e}if(e>h.MAX_DELAY){const e=new Error(`Delay should not be more than ${h.MAX_DELAY}`);throw e.name="MaxLimitExceeded",e}if(t>h.MAX_MAX_RETRIES){const e=new Error(`MaxRetries should not be more than ${h.MAX_MAX_RETRIES}`);throw e.name="MaxLimitExceeded",e}this.delay=Math.min(e,h.MAX_DELAY),this.maxRetries=Math.min(t,h.MAX_MAX_RETRIES),this.shouldRetry=s}getMaxDelay(){return h.MAX_DELAY}}h.DEFAULT_DELAY=3,h.DEFAULT_MAX_RETRIES=3,h.MAX_DELAY=180,h.MAX_MAX_RETRIES=10,h.DEFAULT_SHOULD_RETRY=(()=>!0);class l{constructor(e=new h){this.options=e}isRetry(e){return-1!==l.RETRY_STATUS_CODES.indexOf(e.status)}isBuffered(t,s){const r=t instanceof Request?t.method:s.method;if(r===e.PUT||r===e.PATCH||r===e.POST){if("application/octet-stream"===n(t,s,"Content-Type"))return!1}return!0}getDelay(e,t,s){const r=()=>Number(Math.random().toFixed(3)),n=void 0!==e.headers?e.headers.get(l.RETRY_AFTER_HEADER):null;let i;return i=null!==n?Number.isNaN(Number(n))?Math.round((new Date(n).getTime()-Date.now())/1e3):Number(n):t>=2?this.getExponentialBackOffTime(t)+s+r():s+r(),Math.min(i,this.options.getMaxDelay()+r())}getExponentialBackOffTime(e){return Math.round(.5*(2**e-1))}async sleep(e){const t=1e3*e;return new Promise(e=>setTimeout(e,t))}getOptions(e){let t;return e.middlewareControl instanceof r&&(t=e.middlewareControl.getMiddlewareOptions(this.options.constructor.name)),void 0===t&&(t=Object.assign(new h,this.options)),t}async executeWithRetry(e,t,s){try{if(await this.nextMiddleware.execute(e),t<s.maxRetries&&this.isRetry(e.response)&&this.isBuffered(e.request,e.options)&&s.shouldRetry(s.delay,t,e.request,e.options,e.response)){++t,i(e.request,e.options,l.RETRY_ATTEMPT_HEADER,t.toString());const r=this.getDelay(e.response,t,s.delay);return await this.sleep(r),await this.executeWithRetry(e,t,s)}return}catch(e){throw e}}async execute(e){try{const t=0,s=this.getOptions(e);return await this.executeWithRetry(e,t,s)}catch(e){throw e}}setNext(e){this.nextMiddleware=e}}l.RETRY_STATUS_CODES=[429,503,504],l.RETRY_ATTEMPT_HEADER="Retry-Attempt",l.RETRY_AFTER_HEADER="Retry-After",l.TRANSFER_ENCODING_HEADER="Transfer-Encoding",l.TRANSFER_ENCODING_CHUNKED="chunked";class u{constructor(e=-1,t=-1){this.minValue=e,this.maxValue=t}}class p{constructor(e,t,s,r){this.DEFAULT_FILE_SIZE=5242880,this.client=e,this.file=t,void 0===r.rangeSize&&(r.rangeSize=this.DEFAULT_FILE_SIZE),this.options=r,this.uploadSession=s,this.nextRange=new u(0,this.options.rangeSize-1)}parseRange(e){const t=e[0];if(void 0===t||""===t)return new u;const s=t.split("-"),r=parseInt(s[0],10);let n=parseInt(s[1],10);return Number.isNaN(n)&&(n=this.file.size-1),new u(r,n)}updateTaskStatus(e){this.uploadSession.expiry=new Date(e.expirationDateTime),this.nextRange=this.parseRange(e.nextExpectedRanges)}getNextRange(){if(-1===this.nextRange.minValue)return this.nextRange;const e=this.nextRange.minValue;let t=e+this.options.rangeSize-1;return t>=this.file.size&&(t=this.file.size-1),new u(e,t)}sliceFile(e){return this.file.content.slice(e.minValue,e.maxValue+1)}async upload(){try{for(;;){const e=this.getNextRange();if(-1===e.maxValue){const e=new Error("Task with which you are trying to upload is already completed, Please check for your uploaded file");throw e.name="Invalid Session",e}const t=this.sliceFile(e),s=await this.uploadSlice(t,e,this.file.size);if(void 0!==s.id)return s;this.updateTaskStatus(s)}}catch(e){throw e}}async uploadSlice(e,t,s){try{return await this.client.api(this.uploadSession.url).headers({"Content-Length":`${t.maxValue-t.minValue+1}`,"Content-Range":`bytes ${t.minValue}-${t.maxValue}/${s}`}).put(e)}catch(e){throw e}}async cancel(){try{return await this.client.api(this.uploadSession.url).delete()}catch(e){throw e}}async getStatus(){try{const e=await this.client.api(this.uploadSession.url).get();return this.updateTaskStatus(e),e}catch(e){throw e}}async resume(){try{return await this.getStatus(),await this.upload()}catch(e){throw e}}}const m=(e=5242880)=>{return e>62914560&&(e=62914560),(e=>(e>327680&&(e=320*Math.floor(e/327680)*1024),e))(e)};class y extends p{constructor(e,t,s,r){super(e,t,s,r)}static async create(e,t,s){const r=s.fileName;let n,i;switch(t.constructor.name){case"Blob":i=(n=new File([t],r)).size;break;case"File":i=(n=t).size;break;case"Buffer":const e=t;i=e.byteLength-e.byteOffset,n=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}try{const t=y.constructCreateSessionUrl(s.fileName,s.path),o=await y.createUploadSession(e,t,s.fileName),a=m(s.rangeSize);return new y(e,{name:r,content:n,size:i},o,{rangeSize:a})}catch(e){throw e}}static constructCreateSessionUrl(e,t=y.DEFAULT_UPLOAD_PATH){return e=e.trim(),""===(t=t.trim())&&(t="/"),"/"!==t[0]&&(t=`/${t}`),"/"!==t[t.length-1]&&(t=`${t}/`),encodeURI(`/me/drive/root:${t}${e}:/createUploadSession`)}static async createUploadSession(e,t,s){const r={item:{"@microsoft.graph.conflictBehavior":"rename",name:s}};try{const s=await e.api(t).post(r);return{url:s.uploadUrl,expiry:new Date(s.expirationDateTime)}}catch(e){throw e}}async commit(e){try{const t={name:this.file.name,"@microsoft.graph.conflictBehavior":"rename","@microsoft.graph.sourceUrl":this.uploadSession.url};return await this.client.api(e).put(t)}catch(e){throw e}}}y.DEFAULT_UPLOAD_PATH="/";class f{constructor(e,t,s){this.client=e,this.collection=t.value,this.nextLink=t["@odata.nextLink"],this.deltaLink=t["@odata.deltaLink"],this.callback=s,this.complete=!1}iterationHelper(){if(void 0===this.collection)return!1;let e=!0;for(;e&&0!==this.collection.length;){const t=this.collection.shift();e=this.callback(t)}return e}async fetchAndUpdateNextPageData(){try{const e=await this.client.api(this.nextLink).get();this.collection=e.value,this.nextLink=e["@odata.nextLink"],this.deltaLink=e["@odata.deltaLink"]}catch(e){throw e}}getDeltaLink(){return this.deltaLink}async iterate(){try{let e=this.iterationHelper();for(;e;)void 0!==this.nextLink?(await this.fetchAndUpdateNextPageData(),e=this.iterationHelper()):e=!1;void 0===this.nextLink&&0===this.collection.length&&(this.complete=!0)}catch(e){throw e}}async resume(){try{return this.iterate()}catch(e){throw e}}isComplete(){return this.complete}}const w="v1.0",E="https://graph.microsoft.com/",g="1.6.0-Preview.2";class R{constructor(e){this.provider=e}async getAccessToken(){return new Promise((e,t)=>{this.provider((s,r)=>{r?e(r):t(s)})})}}class A{constructor(e=-1){this.statusCode=e,this.code=null,this.message=null,this.requestId=null,this.date=new Date,this.body=null}}class T{static constructError(e,t){const s=new A(t);return void 0!==e.name&&(s.code=e.name),s.body=e.toString(),s.message=e.message,s.date=new Date,s}static async constructErrorFromRawResponse(e,t){const s=new A(t);try{s.body=await e.text()}catch(e){}return s}static constructErrorFromResponse(e,t){e=e.error;const s=new A(t);s.code=e.code,s.message=e.message,void 0!==e.innerError&&(s.requestId=e.innerError["request-id"],s.date=new Date(e.innerError.date));try{s.body=JSON.stringify(e)}catch(e){}return s}static async getError(e=null,t=-1,s){let r;if(r=!e||"Response"!==e.constructor.name&&"Body"!==e.constructor.name?e&&e.error?T.constructErrorFromResponse(e,t):e&&"Error"===e.constructor.name?T.constructError(e,t):new A(t):await T.constructErrorFromRawResponse(e,t),"function"!=typeof s)return r;s(r,null)}}const v=["$select","$expand","$orderby","$filter","$top","$skip","$skipToken","$count"],O=e=>{const t=e=>e.replace(/\/+$/,""),s=e=>e.replace(/^\/+/,"");return Array.prototype.slice.call(e).reduce((e,r)=>[t(e),s(r)].join("/"))},x=e=>{const t=e.constructor.name;if("Buffer"===t||"Blob"===t||"File"===t||"FormData"===t||"string"==typeof e)return e;if("ArrayBuffer"===t)e=Buffer.from(e);else if("Int8Array"===t||"Int16Array"===t||"Int32Array"===t||"Uint8Array"===t||"Uint16Array"===t||"Uint32Array"===t||"Uint8ClampedArray"===t||"Float32Array"===t||"Float64Array"===t||"DataView"===t)e=Buffer.from(e.buffer);else try{e=JSON.stringify(e)}catch(e){throw new Error("Unable to stringify the content")}return e};var D,P,b,_;!function(e){e.ARRAYBUFFER="arraybuffer",e.BLOB="blob",e.DOCUMENT="document",e.JSON="json",e.RAW="raw",e.STREAM="stream",e.TEXT="text"}(D||(D={})),function(e){e.TEXT_HTML="text/html",e.TEXT_XML="text/xml",e.APPLICATION_XML="application/xml",e.APPLICATION_XHTML="application/xhtml+xml"}(P||(P={})),function(e){e.TEXT_PLAIN="text/plain",e.APPLICATION_JSON="application/json"}(b||(b={})),function(e){e.DOCUMENT="^(text\\/(html|xml))|(application\\/(xml|xhtml\\+xml))$",e.IMAGE="^image\\/.+"}(_||(_={}));class S{static parseDocumentResponse(e,t){try{return"undefined"!=typeof DOMParser?new Promise((s,r)=>{e.text().then(e=>{try{const n=(new DOMParser).parseFromString(e,t);s(n)}catch(e){r(e)}})}):Promise.resolve(e.body)}catch(e){throw e}}static async convertResponse(e,t){const s=e.clone();if(204===s.status)return Promise.resolve();let r;try{switch(t){case D.ARRAYBUFFER:r=await s.arrayBuffer();break;case D.BLOB:r=await s.blob();break;case D.DOCUMENT:r=await S.parseDocumentResponse(s,P.TEXT_XML);break;case D.JSON:r=await s.json();break;case D.STREAM:r=await Promise.resolve(s.body);break;case D.TEXT:r=await s.text();break;default:const e=s.headers.get("Content-type");if(null!==e){const t=e.split(";")[0];r=new RegExp(_.DOCUMENT).test(t)?await S.parseDocumentResponse(s,t):new RegExp(_.IMAGE).test(t)?s.blob():t===b.TEXT_PLAIN?await s.text():t===b.APPLICATION_JSON?await s.json():Promise.resolve(s.body)}else r=Promise.resolve(s.body)}}catch(e){throw e}return r}static async getResponse(e,t,s){try{if(t===D.RAW)return Promise.resolve(e);{const r=await S.convertResponse(e,t);if(!e.ok)throw r;if("function"!=typeof s)return r;s(null,r,e)}}catch(t){throw e.ok?t:e}}}class L{constructor(e,t,s){this.parsePath=(e=>{if(-1!==e.indexOf("https://")){const t=(e=e.replace("https://","")).indexOf("/");-1!==t&&(this.urlComponents.host="https://"+e.substring(0,t),e=e.substring(t+1,e.length));const s=e.indexOf("/");-1!==s&&(this.urlComponents.version=e.substring(0,s),e=e.substring(s+1,e.length))}"/"===e.charAt(0)&&(e=e.substr(1));const t=e.indexOf("?");if(-1===t)this.urlComponents.path=e;else{this.urlComponents.path=e.substr(0,t);const s=e.substring(t+1,e.length).split("&");for(const e of s){const t=e.split("="),s=t[0],r=t[1];-1!==v.indexOf(s)?this.urlComponents.oDataQueryParams[s]=r:this.urlComponents.otherURLQueryParams[s]=r}}}),this.httpClient=e,this.config=t,this.urlComponents={host:this.config.baseUrl,version:this.config.defaultVersion,oDataQueryParams:{},otherURLQueryParams:{}},this._headers={},this._options={},this._middlewareOptions=[],this.parsePath(s)}addCsvQueryParameter(e,t,s){this.urlComponents.oDataQueryParams[e]=this.urlComponents.oDataQueryParams[e]?this.urlComponents.oDataQueryParams[e]+",":"";let r=[];s.length>1&&"string"==typeof t?r=Array.prototype.slice.call(s):"string"==typeof t?r.push(t):r=r.concat(t),this.urlComponents.oDataQueryParams[e]+=r.join(",")}buildFullUrl(){const e=O([this.urlComponents.host,this.urlComponents.version,this.urlComponents.path])+this.createQueryString();return this.config.debugLogging&&console.log(e),e}createQueryString(){const e=this.urlComponents,t=[];if(0!==Object.keys(e.oDataQueryParams).length)for(const s in e.oDataQueryParams)e.oDataQueryParams.hasOwnProperty(s)&&t.push(s+"="+e.oDataQueryParams[s]);if(0!==Object.keys(e.otherURLQueryParams).length)for(const s in e.otherURLQueryParams)e.otherURLQueryParams.hasOwnProperty(s)&&t.push(s+"="+e.otherURLQueryParams[s]);return t.length>0?"?"+t.join("&"):""}updateRequestOptions(e){const t={SdkVersion:`graph-js-${g}`},s={...e.headers};if(void 0!==this.config.fetchOptions){const t={...this.config.fetchOptions};Object.assign(e,t),void 0!==typeof this.config.fetchOptions.headers&&(e.headers={...this.config.fetchOptions.headers})}Object.assign(e,this._options),Object.assign(s,t),void 0!==e.headers&&Object.assign(s,e.headers),Object.assign(s,this._headers),e.headers=s}async send(e,t,s){let n;const i=new r(this._middlewareOptions);this.updateRequestOptions(t);try{return n=(await this.httpClient.sendRequest({request:e,options:t,middlewareControl:i})).response,await S.getResponse(n,this._responseType,s)}catch(e){let t;throw void 0!==n&&(t=n.status),await T.getError(e,t,s)}}header(e,t){return this._headers[e]=t,this}headers(e){for(const t in e)e.hasOwnProperty(t)&&(this._headers[t]=e[t]);return this}option(e,t){return this._options[e]=t,this}options(e){for(const t in e)e.hasOwnProperty(t)&&(this._options[t]=e[t]);return this}middlewareOptions(e){return this._middlewareOptions=e,this}version(e){return this.urlComponents.version=e,this}responseType(e){return this._responseType=e,this}select(e){return this.addCsvQueryParameter("$select",e,arguments),this}expand(e){return this.addCsvQueryParameter("$expand",e,arguments),this}orderby(e){return this.addCsvQueryParameter("$orderby",e,arguments),this}filter(e){return this.urlComponents.oDataQueryParams.$filter=e,this}search(e){return this.urlComponents.oDataQueryParams.$search=e,this}top(e){return this.urlComponents.oDataQueryParams.$top=e,this}skip(e){return this.urlComponents.oDataQueryParams.$skip=e,this}skipToken(e){return this.urlComponents.oDataQueryParams.$skipToken=e,this}count(e){return this.urlComponents.oDataQueryParams.$count=e.toString(),this}query(e){const t=this.urlComponents.otherURLQueryParams;if("string"==typeof e){const s=e.split("="),r=s[0],n=s[1];t[r]=n}else for(const s in e)e.hasOwnProperty(s)&&(t[s]=e[s]);return this}async get(t){const s=this.buildFullUrl(),r={method:e.GET};try{return await this.send(s,r,t)}catch(e){throw e}}async post(t,s){const r=this.buildFullUrl(),n={method:e.POST,body:x(t),headers:void 0!==t.constructor&&"FormData"===t.constructor.name?{}:{"Content-Type":"application/json"}};try{return await this.send(r,n,s)}catch(e){throw e}}async create(e,t){try{return await this.post(e,t)}catch(e){throw e}}async put(t,s){const r=this.buildFullUrl(),n={method:e.PUT,body:x(t),headers:{"Content-Type":"application/octet-stream"}};try{return await this.send(r,n,s)}catch(e){throw e}}async patch(t,s){const r=this.buildFullUrl(),n={method:e.PATCH,body:x(t),headers:{"Content-Type":"application/json"}};try{return await this.send(r,n,s)}catch(e){throw e}}async update(e,t){try{return await this.patch(e,t)}catch(e){throw e}}async delete(t){const s=this.buildFullUrl(),r={method:e.DELETE};try{return await this.send(s,r,t)}catch(e){throw e}}async del(e){try{return await this.delete(e)}catch(e){throw e}}async getStream(t){const s=this.buildFullUrl(),r={method:e.GET};this.responseType(D.STREAM);try{return await this.send(s,r,t)}catch(e){throw e}}async putStream(t,s){const r=this.buildFullUrl(),n={method:e.PUT,headers:{"Content-Type":"application/octet-stream"},body:t};try{return await this.send(r,n,s)}catch(e){throw e}}}class C{constructor(e){this.middleware=e}async sendRequest(e){try{if(!(e.request instanceof Request)&&void 0===e.options){const e=new Error;throw e.name="InvalidRequestOptions",e.message="Unable to execute the middleware, Please provide valid options for a request",e}return await this.middleware.execute(e),e}catch(e){throw e}}}class M{constructor(e=M.DEFAULT_MAX_REDIRECTS,t=M.DEFAULT_SHOULD_RETRY){if(e>M.MAX_MAX_REDIRECTS){const e=new Error(`MaxRedirects should not be more than ${M.MAX_MAX_REDIRECTS}`);throw e.name="MaxLimitExceeded",e}this.maxRedirects=e,this.shouldRedirect=t}}M.DEFAULT_MAX_REDIRECTS=5,M.MAX_MAX_REDIRECTS=20,M.DEFAULT_SHOULD_RETRY=(()=>!0);class U{constructor(e=new M){this.options=e}isRedirect(e){return-1!==U.REDIRECT_STATUS_CODES.indexOf(e.status)}hasLocationHeader(e){return e.headers.has(U.LOCATION_HEADER)}getLocationHeader(e){return e.headers.get(U.LOCATION_HEADER)}isRelativeURL(e){return-1===e.indexOf("://")}shouldDropAuthorizationHeader(e,t){const s=/^[A-Za-z].+?:\/\/.+?(?=\/|$)/,r=s.exec(e);let n,i;null!==r&&(n=r[0]);const o=s.exec(t);return null!==o&&(i=o[0]),void 0!==n&&void 0!==i&&n!==i}async updateRequestUrl(e,t){t.request=t.request instanceof Request?await o(e,t.request):e}getOptions(e){let t;return e.middlewareControl instanceof r&&(t=e.middlewareControl.getMiddlewareOptions(this.options.constructor.name)),void 0===t&&(t=Object.assign(new M,this.options)),t}async executeWithRedirect(t,s,r){try{await this.nextMiddleware.execute(t);const n=t.response;if(!(s<r.maxRedirects&&this.isRedirect(n)&&this.hasLocationHeader(n)&&r.shouldRedirect(n)))return;if(++s,n.status===U.STATUS_CODE_SEE_OTHER)t.options.method=e.GET,delete t.options.body;else{const e=this.getLocationHeader(n);!this.isRelativeURL(e)&&this.shouldDropAuthorizationHeader(n.url,e)&&i(t.request,t.options,U.AUTHORIZATION_HEADER,void 0),await this.updateRequestUrl(e,t)}await this.executeWithRedirect(t,s,r)}catch(e){throw e}}async execute(e){try{const t=0,s=this.getOptions(e);return e.options.redirect=U.MANUAL_REDIRECT,await this.executeWithRedirect(e,t,s)}catch(e){throw e}}setNext(e){this.nextMiddleware=e}}U.REDIRECT_STATUS_CODES=[301,302,303,307,308],U.STATUS_CODE_SEE_OTHER=303,U.LOCATION_HEADER="Location",U.AUTHORIZATION_HEADER="Authorization",U.MANUAL_REDIRECT="manual";const q=()=>new Function("try {return this === global;}catch(e){return false;}")();class I{static createWithAuthenticationProvider(e){const t=new c(e),s=new l(new h),r=new d;if(t.setNext(s),q()){const e=new U(new M);s.setNext(e),e.setNext(r)}else s.setNext(r);return I.createWithMiddleware(t)}static createWithMiddleware(e){return new C(e)}}const k=()=>{if("undefined"==typeof Promise&&"undefined"==typeof fetch){const e=new Error("Library cannot function without Promise and fetch. So, please provide polyfill for them.");throw e.name="PolyFillNotAvailable",e}if("undefined"==typeof Promise){const e=new Error("Library cannot function without Promise. So, please provide polyfill for it.");throw e.name="PolyFillNotAvailable",e}if("undefined"==typeof fetch){const e=new Error("Library cannot function without fetch. So, please provide polyfill for it.");throw e.name="PolyFillNotAvailable",e}return!0};class N{constructor(e){this.config={baseUrl:E,debugLogging:!1,defaultVersion:w};try{k()}catch(e){throw e}for(const t in e)e.hasOwnProperty(t)&&(this.config[t]=e[t]);let t;if(void 0!==e.authProvider&&void 0!==e.middleware){const e=new Error;throw e.name="AmbiguityInInitialization",e.message="Unable to Create Client, Please provide either authentication provider for default middleware chain or custom middleware chain not both",e}if(void 0!==e.authProvider)t=I.createWithAuthenticationProvider(e.authProvider);else{if(void 0===e.middleware){const e=new Error;throw e.name="InvalidMiddlewareChain",e.message="Unable to Create Client, Please provide either authentication provider for default middleware chain or custom middleware chain",e}t=new C(e.middleware)}this.httpClient=t}static init(e){const t={};for(const s in e)e.hasOwnProperty(s)&&(t[s]="authProvider"===s?new R(e[s]):e[s]);return N.initWithMiddleware(t)}static initWithMiddleware(e){try{return new N(e)}catch(e){throw e}}api(e){return new L(this.httpClient,this.config,e)}}class F{constructor(e,t,s){this.scopes=t,this.userAgentApplication="string"==typeof e?new Msal.UserAgentApplication(e,void 0,(e,t,s,r)=>{},s):e}async getAccessToken(e){let t;if(void 0!==e&&(t=e.scopes),void 0!==t&&0!==t.length||(t=this.scopes),0===t.length){const e=new Error;throw e.name="EmptyScopes",e.message="Scopes cannot be empty, Please provide a scope",e}try{return await this.userAgentApplication.acquireTokenSilent(t)}catch(e){try{await this.userAgentApplication.loginPopup(t);try{return await this.userAgentApplication.acquireTokenSilent(t)}catch(e){return await this.userAgentApplication.acquireTokenPopup(t)}}catch(e){throw new Error(e)}}}addScopes(e){if(0===e.length){const e=new Error;throw e.name="EmptyScopes",e.message="Scopes array cannot be empty",e}this.scopes=Array.from(new Set(this.scopes.concat(e)))}clearScopes(){this.scopes=[]}}class ${constructor(e){this.scopes=e}}export{c as AuthenticationHandler,a as AuthenticationHandlerOptions,t as BatchRequestContent,s as BatchResponseContent,N as Client,A as GraphError,L as GraphRequest,d as HTTPMessageHandler,F as MSALAuthenticationProvider,$ as MSALAuthenticationProviderOptions,y as OneDriveLargeFileUploadTask,f as PageIterator,D as ResponseType,l as RetryHandler,h as RetryHandlerOptions}; | ||
var e;!function(e){e.GET="GET",e.PATCH="PATCH",e.POST="POST",e.PUT="PUT",e.DELETE="DELETE"}(e||(e={}));var t=function(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(s,a)}c((r=r.apply(e,t||[])).next())})};class n{constructor(e){if(this.requests=new Map,void 0!==e){const t=n.requestLimit;if(e.length>t){const e=new Error(`Maximum requests limit exceeded, Max allowed number of requests are ${t}`);throw e.name="Limit Exceeded Error",e}for(const t of e)this.addRequest(t)}}static validateDependencies(e){if(0===e.size){const e=new Error("Empty requests map, Please provide at least one request.");throw e.name="Empty Requests Error",e}return(e=>{const t=e.entries();let n=t.next();for(;!n.done;){const e=n.value[1];if(void 0!==e.dependsOn&&e.dependsOn.length>0)return!1;n=t.next()}return!0})(e)||(e=>{const t=e.entries();let n=t.next();const r=n.value[1];if(void 0!==r.dependsOn&&r.dependsOn.length>0)return!1;let i=n;for(n=t.next();!n.done;){const e=n.value[1];if(void 0===e.dependsOn||1!==e.dependsOn.length||e.dependsOn[0]!==i.value[1].id)return!1;i=n,n=t.next()}return!0})(e)||(e=>{const t=e.entries();let n=t.next();const r=n.value[1];let i;if(void 0===r.dependsOn||0===r.dependsOn.length)i=r.id;else{if(1!==r.dependsOn.length)return!1;{const t=r.dependsOn[0];if(t===r.id||!e.has(t))return!1;i=t}}for(n=t.next();!n.done;){const e=n.value[1];if((void 0===e.dependsOn||0===e.dependsOn.length)&&i!==e.id)return!1;if(void 0!==e.dependsOn&&0!==e.dependsOn.length){if(1===e.dependsOn.length&&(e.id===i||e.dependsOn[0]!==i))return!1;if(e.dependsOn.length>1)return!1}n=t.next()}return!0})(e)}static getRequestData(r){return t(this,void 0,void 0,function*(){const t={url:""},i=new RegExp("^https?://");t.url=i.test(r.url)?"/"+r.url.split(/.*?\/\/.*?\//)[1]:r.url,t.method=r.method;const o={};return r.headers.forEach((e,t)=>{o[t]=e}),Object.keys(o).length&&(t.headers=o),r.method!==e.PATCH&&r.method!==e.POST&&r.method!==e.PUT||(t.body=yield n.getRequestBody(r)),t})}static getRequestBody(e){return t(this,void 0,void 0,function*(){let t,n=!1;try{const r=e.clone();t=yield r.json(),n=!0}catch(e){}if(!n)try{if("undefined"!=typeof Blob){const n=yield e.blob(),r=new FileReader;t=yield new Promise(e=>{r.addEventListener("load",()=>{const t=r.result,n=new RegExp("^s*data:(.+?/.+?(;.+?=.+?)*)?(;base64)?,(.*)s*$").exec(t);e(n[4])},!1),r.readAsDataURL(n)})}else if("undefined"!=typeof Buffer){t=(yield e.buffer()).toString("base64")}n=!0}catch(e){}return t})}addRequest(e){const t=n.requestLimit;if(""===e.id){const e=new Error("Id for a request is empty, Please provide an unique id");throw e.name="Empty Id For Request",e}if(this.requests.size===t){const e=new Error(`Maximum requests limit exceeded, Max allowed number of requests are ${t}`);throw e.name="Limit Exceeded Error",e}if(this.requests.has(e.id)){const t=new Error(`Adding request with duplicate id ${e.id}, Make the id of the requests unique`);throw t.name="Duplicate RequestId Error",t}return this.requests.set(e.id,e),e.id}removeRequest(e){const t=this.requests.delete(e),n=this.requests.entries();let r=n.next();for(;!r.done;){const t=r.value[1].dependsOn;if(void 0!==t){const n=t.indexOf(e);-1!==n&&t.splice(n,1),0===t.length&&delete r.value[1].dependsOn}r=n.next()}return t}getContent(){return t(this,void 0,void 0,function*(){const e=[],t={requests:e},r=this.requests.entries();let i=r.next();if(i.done){const e=new Error("No requests added yet, Please add at least one request.");throw e.name="Empty Payload",e}if(!n.validateDependencies(this.requests)){const e=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.");throw e.name="Invalid Dependency",e}for(;!i.done;){const t=i.value[1],o=yield n.getRequestData(t.request);if(void 0!==o.body&&(void 0===o.headers||void 0===o.headers["content-type"])){const e=new Error(`Content-type header is not mentioned for request #${t.id}, For request having body, Content-type header should be mentioned`);throw e.name="Invalid Content-type header",e}o.id=t.id,void 0!==t.dependsOn&&t.dependsOn.length>0&&(o.dependsOn=t.dependsOn),e.push(o),i=r.next()}return t.requests=e,t})}addDependency(e,t){if(!this.requests.has(e)){const t=new Error(`Dependent ${e} does not exists, Please check the id`);throw t.name="Invalid Dependent",t}if(void 0!==t&&!this.requests.has(t)){const e=new Error(`Dependency ${t} does not exists, Please check the id`);throw e.name="Invalid Dependency",e}if(void 0!==t){const n=this.requests.get(e);if(void 0===n.dependsOn&&(n.dependsOn=[]),-1!==n.dependsOn.indexOf(t)){const n=new Error(`Dependency ${t} is already added for the request ${e}`);throw n.name="Duplicate Dependency",n}n.dependsOn.push(t)}else{const n=this.requests.entries();let r,i=n.next();for(;!i.done&&i.value[1].id!==e;)r=i,i=n.next();if(void 0===r){const e=new Error(`Can't add dependency ${t}, There is only a dependent request in the batch`);throw e.name="Invalid Dependency Addition",e}{const t=r.value[0];if(void 0===i.value[1].dependsOn&&(i.value[1].dependsOn=[]),-1!==i.value[1].dependsOn.indexOf(t)){const n=new Error(`Dependency ${t} is already added for the request ${e}`);throw n.name="Duplicate Dependency",n}i.value[1].dependsOn.push(t)}}}removeDependency(e,t){const n=this.requests.get(e);if(void 0===n||void 0===n.dependsOn||0===n.dependsOn.length)return!1;if(void 0!==t){const e=n.dependsOn.indexOf(t);return-1!==e&&(n.dependsOn.splice(e,1),!0)}return delete n.dependsOn,!0}}n.requestLimit=20;class r{constructor(e){this.responses=new Map,this.update(e)}createResponseObject(e){const t=e.body,n={};return n.status=e.status,void 0!==e.statusText&&(n.statusText=e.statusText),n.headers=e.headers,new Response(t,n)}update(e){this.nextLink=e["@nextLink"];const t=e.responses;for(let e=0,n=t.length;e<n;e++)this.responses.set(t[e].id,this.createResponseObject(t[e]))}getResponseById(e){return this.responses.get(e)}getResponses(){return this.responses}*getResponsesIterator(){const e=this.responses.entries();let t=e.next();for(;!t.done;)yield t.value,t=e.next()}}class i{constructor(e){this.middlewareOptions=new Map;for(const t of e){const e=t.constructor.name;this.middlewareOptions.set(e,t)}}getMiddlewareOptions(e){return this.middlewareOptions.get(e)}}var o=function(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(s,a)}c((r=r.apply(e,t||[])).next())})};const s=(e,t,n)=>{let r=null;if(e instanceof Request)r=e.headers.get(n);else if(void 0!==t&&void 0!==t.headers)if(t.headers instanceof Headers)r=t.headers.get(n);else if(t.headers instanceof Array){const e=t.headers;for(let t=0,i=e.length;t<i;t++)if(e[t][0]===n){r=e[t][1];break}}else void 0!==t.headers[n]&&(r=t.headers[n]);return r},a=(e,t,n,r)=>{e instanceof Request?e.headers.set(n,r):void 0!==t&&(void 0===t.headers?t.headers={[n]:r}:t.headers instanceof Headers?t.headers.set(n,r):t.headers instanceof Array?t.headers.push([n,r]):Object.assign(t.headers,{[n]:r}))},c=(e,t)=>o(void 0,void 0,void 0,function*(){const n=t.headers.get("Content-Type")?yield t.blob():yield Promise.resolve(void 0),{method:r,headers:i,referrer:o,referrerPolicy:s,mode:a,credentials:c,cache:d,redirect:u,integrity:h,keepalive:l,signal:p}=t;return new Request(e,{method:r,headers:i,body:n,referrer:o,referrerPolicy:s,mode:a,credentials:c,cache:d,redirect:u,integrity:h,keepalive:l,signal:p})});class d{constructor(e,t){this.authenticationProvider=e,this.authenticationProviderOptions=t}}var u=function(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(s,a)}c((r=r.apply(e,t||[])).next())})};class h{constructor(e){this.authenticationProvider=e}execute(e){return u(this,void 0,void 0,function*(){try{let t,n,r;e.middlewareControl instanceof i&&(t=e.middlewareControl.getMiddlewareOptions(d.name)),void 0!==t&&(n=t.authenticationProvider,r=t.authenticationProviderOptions),void 0===n&&(n=this.authenticationProvider);const o=`Bearer ${yield n.getAccessToken(r)}`;return a(e.request,e.options,h.AUTHORIZATION_HEADER,o),yield this.nextMiddleware.execute(e)}catch(e){throw e}})}setNext(e){this.nextMiddleware=e}}h.AUTHORIZATION_HEADER="Authorization";var l=function(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(s,a)}c((r=r.apply(e,t||[])).next())})};class p{execute(e){return l(this,void 0,void 0,function*(){try{return void(e.response=yield fetch(e.request,e.options))}catch(e){throw e}})}}class f{constructor(e=f.DEFAULT_DELAY,t=f.DEFAULT_MAX_RETRIES,n=f.DEFAULT_SHOULD_RETRY){if(e>f.MAX_DELAY&&t>f.MAX_MAX_RETRIES){const e=new Error(`Delay and MaxRetries should not be more than ${f.MAX_DELAY} and ${f.MAX_MAX_RETRIES}`);throw e.name="MaxLimitExceeded",e}if(e>f.MAX_DELAY){const e=new Error(`Delay should not be more than ${f.MAX_DELAY}`);throw e.name="MaxLimitExceeded",e}if(t>f.MAX_MAX_RETRIES){const e=new Error(`MaxRetries should not be more than ${f.MAX_MAX_RETRIES}`);throw e.name="MaxLimitExceeded",e}this.delay=Math.min(e,f.MAX_DELAY),this.maxRetries=Math.min(t,f.MAX_MAX_RETRIES),this.shouldRetry=n}getMaxDelay(){return f.MAX_DELAY}}f.DEFAULT_DELAY=3,f.DEFAULT_MAX_RETRIES=3,f.MAX_DELAY=180,f.MAX_MAX_RETRIES=10,f.DEFAULT_SHOULD_RETRY=(()=>!0);var y=function(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(s,a)}c((r=r.apply(e,t||[])).next())})};class m{constructor(e=new f){this.options=e}isRetry(e){return-1!==m.RETRY_STATUS_CODES.indexOf(e.status)}isBuffered(t,n){const r=t instanceof Request?t.method:n.method;if(r===e.PUT||r===e.PATCH||r===e.POST){if("application/octet-stream"===s(t,n,"Content-Type"))return!1}return!0}getDelay(e,t,n){const r=()=>Number(Math.random().toFixed(3)),i=void 0!==e.headers?e.headers.get(m.RETRY_AFTER_HEADER):null;let o;return o=null!==i?Number.isNaN(Number(i))?Math.round((new Date(i).getTime()-Date.now())/1e3):Number(i):t>=2?this.getExponentialBackOffTime(t)+n+r():n+r(),Math.min(o,this.options.getMaxDelay()+r())}getExponentialBackOffTime(e){return Math.round(.5*(Math.pow(2,e)-1))}sleep(e){return y(this,void 0,void 0,function*(){const t=1e3*e;return new Promise(e=>setTimeout(e,t))})}getOptions(e){let t;return e.middlewareControl instanceof i&&(t=e.middlewareControl.getMiddlewareOptions(this.options.constructor.name)),void 0===t&&(t=Object.assign(new f,this.options)),t}executeWithRetry(e,t,n){return y(this,void 0,void 0,function*(){try{if(yield this.nextMiddleware.execute(e),t<n.maxRetries&&this.isRetry(e.response)&&this.isBuffered(e.request,e.options)&&n.shouldRetry(n.delay,t,e.request,e.options,e.response)){++t,a(e.request,e.options,m.RETRY_ATTEMPT_HEADER,t.toString());const r=this.getDelay(e.response,t,n.delay);return yield this.sleep(r),yield this.executeWithRetry(e,t,n)}return}catch(e){throw e}})}execute(e){return y(this,void 0,void 0,function*(){try{const t=0,n=this.getOptions(e);return yield this.executeWithRetry(e,t,n)}catch(e){throw e}})}setNext(e){this.nextMiddleware=e}}m.RETRY_STATUS_CODES=[429,503,504],m.RETRY_ATTEMPT_HEADER="Retry-Attempt",m.RETRY_AFTER_HEADER="Retry-After",m.TRANSFER_ENCODING_HEADER="Transfer-Encoding",m.TRANSFER_ENCODING_CHUNKED="chunked";class v{constructor(e=-1,t=-1){this.minValue=e,this.maxValue=t}}var w=function(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(s,a)}c((r=r.apply(e,t||[])).next())})};class E{constructor(e,t,n,r){this.DEFAULT_FILE_SIZE=5242880,this.client=e,this.file=t,void 0===r.rangeSize&&(r.rangeSize=this.DEFAULT_FILE_SIZE),this.options=r,this.uploadSession=n,this.nextRange=new v(0,this.options.rangeSize-1)}parseRange(e){const t=e[0];if(void 0===t||""===t)return new v;const n=t.split("-"),r=parseInt(n[0],10);let i=parseInt(n[1],10);return Number.isNaN(i)&&(i=this.file.size-1),new v(r,i)}updateTaskStatus(e){this.uploadSession.expiry=new Date(e.expirationDateTime),this.nextRange=this.parseRange(e.nextExpectedRanges)}getNextRange(){if(-1===this.nextRange.minValue)return this.nextRange;const e=this.nextRange.minValue;let t=e+this.options.rangeSize-1;return t>=this.file.size&&(t=this.file.size-1),new v(e,t)}sliceFile(e){return this.file.content.slice(e.minValue,e.maxValue+1)}upload(){return w(this,void 0,void 0,function*(){try{for(;;){const e=this.getNextRange();if(-1===e.maxValue){const e=new Error("Task with which you are trying to upload is already completed, Please check for your uploaded file");throw e.name="Invalid Session",e}const t=this.sliceFile(e),n=yield this.uploadSlice(t,e,this.file.size);if(void 0!==n.id)return n;this.updateTaskStatus(n)}}catch(e){throw e}})}uploadSlice(e,t,n){return w(this,void 0,void 0,function*(){try{return yield this.client.api(this.uploadSession.url).headers({"Content-Length":`${t.maxValue-t.minValue+1}`,"Content-Range":`bytes ${t.minValue}-${t.maxValue}/${n}`}).put(e)}catch(e){throw e}})}cancel(){return w(this,void 0,void 0,function*(){try{return yield this.client.api(this.uploadSession.url).delete()}catch(e){throw e}})}getStatus(){return w(this,void 0,void 0,function*(){try{const e=yield this.client.api(this.uploadSession.url).get();return this.updateTaskStatus(e),e}catch(e){throw e}})}resume(){return w(this,void 0,void 0,function*(){try{return yield this.getStatus(),yield this.upload()}catch(e){throw e}})}}const g=(e=5242880)=>{return e>62914560&&(e=62914560),(e=>(e>327680&&(e=320*Math.floor(e/327680)*1024),e))(e)};var R=function(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(s,a)}c((r=r.apply(e,t||[])).next())})};class x extends E{constructor(e,t,n,r){super(e,t,n,r)}static create(e,t,n){return R(this,void 0,void 0,function*(){const r=n.fileName;let i,o;switch(t.constructor.name){case"Blob":o=(i=new File([t],r)).size;break;case"File":o=(i=t).size;break;case"Buffer":const e=t;o=e.byteLength-e.byteOffset,i=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}try{const t=x.constructCreateSessionUrl(n.fileName,n.path),s=yield x.createUploadSession(e,t,n.fileName),a=g(n.rangeSize);return new x(e,{name:r,content:i,size:o},s,{rangeSize:a})}catch(e){throw e}})}static constructCreateSessionUrl(e,t=x.DEFAULT_UPLOAD_PATH){return e=e.trim(),""===(t=t.trim())&&(t="/"),"/"!==t[0]&&(t=`/${t}`),"/"!==t[t.length-1]&&(t=`${t}/`),encodeURI(`/me/drive/root:${t}${e}:/createUploadSession`)}static createUploadSession(e,t,n){return R(this,void 0,void 0,function*(){const r={item:{"@microsoft.graph.conflictBehavior":"rename",name:n}};try{const n=yield e.api(t).post(r);return{url:n.uploadUrl,expiry:new Date(n.expirationDateTime)}}catch(e){throw e}})}commit(e){return R(this,void 0,void 0,function*(){try{const t={name:this.file.name,"@microsoft.graph.conflictBehavior":"rename","@microsoft.graph.sourceUrl":this.uploadSession.url};return yield this.client.api(e).put(t)}catch(e){throw e}})}}x.DEFAULT_UPLOAD_PATH="/";var A=function(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(s,a)}c((r=r.apply(e,t||[])).next())})};class T{constructor(e,t,n){this.client=e,this.collection=t.value,this.nextLink=t["@odata.nextLink"],this.deltaLink=t["@odata.deltaLink"],this.callback=n,this.complete=!1}iterationHelper(){if(void 0===this.collection)return!1;let e=!0;for(;e&&0!==this.collection.length;){const t=this.collection.shift();e=this.callback(t)}return e}fetchAndUpdateNextPageData(){return A(this,void 0,void 0,function*(){try{const e=yield this.client.api(this.nextLink).get();this.collection=e.value,this.nextLink=e["@odata.nextLink"],this.deltaLink=e["@odata.deltaLink"]}catch(e){throw e}})}getDeltaLink(){return this.deltaLink}iterate(){return A(this,void 0,void 0,function*(){try{let e=this.iterationHelper();for(;e;)void 0!==this.nextLink?(yield this.fetchAndUpdateNextPageData(),e=this.iterationHelper()):e=!1;void 0===this.nextLink&&0===this.collection.length&&(this.complete=!0)}catch(e){throw e}})}resume(){return A(this,void 0,void 0,function*(){try{return this.iterate()}catch(e){throw e}})}isComplete(){return this.complete}}const O="v1.0",P="https://graph.microsoft.com/",D="1.6.0-Preview.3";var b=function(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(s,a)}c((r=r.apply(e,t||[])).next())})};class _{constructor(e){this.provider=e}getAccessToken(){return b(this,void 0,void 0,function*(){return new Promise((e,t)=>{this.provider((n,r)=>{r?e(r):t(n)})})})}}class S{constructor(e=-1){this.statusCode=e,this.code=null,this.message=null,this.requestId=null,this.date=new Date,this.body=null}}var L=function(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(s,a)}c((r=r.apply(e,t||[])).next())})};class C{static constructError(e,t){const n=new S(t);return void 0!==e.name&&(n.code=e.name),n.body=e.toString(),n.message=e.message,n.date=new Date,n}static constructErrorFromRawResponse(e,t){return L(this,void 0,void 0,function*(){const n=new S(t);try{n.body=yield e.text()}catch(e){}return n})}static constructErrorFromResponse(e,t){e=e.error;const n=new S(t);n.code=e.code,n.message=e.message,void 0!==e.innerError&&(n.requestId=e.innerError["request-id"],n.date=new Date(e.innerError.date));try{n.body=JSON.stringify(e)}catch(e){}return n}static getError(e=null,t=-1,n){return L(this,void 0,void 0,function*(){let r;if(r=!e||"Response"!==e.constructor.name&&"Body"!==e.constructor.name?e&&e.error?C.constructErrorFromResponse(e,t):e&&"Error"===e.constructor.name?C.constructError(e,t):new S(t):yield C.constructErrorFromRawResponse(e,t),"function"!=typeof n)return r;n(r,null)})}}const M=["$select","$expand","$orderby","$filter","$top","$skip","$skipToken","$count"],U=e=>{const t=e=>e.replace(/\/+$/,""),n=e=>e.replace(/^\/+/,"");return Array.prototype.slice.call(e).reduce((e,r)=>[t(e),n(r)].join("/"))},q=e=>{const t=e.constructor.name;if("Buffer"===t||"Blob"===t||"File"===t||"FormData"===t||"string"==typeof e)return e;if("ArrayBuffer"===t)e=Buffer.from(e);else if("Int8Array"===t||"Int16Array"===t||"Int32Array"===t||"Uint8Array"===t||"Uint16Array"===t||"Uint32Array"===t||"Uint8ClampedArray"===t||"Float32Array"===t||"Float64Array"===t||"DataView"===t)e=Buffer.from(e.buffer);else try{e=JSON.stringify(e)}catch(e){throw new Error("Unable to stringify the content")}return e};var I;!function(e){e.ARRAYBUFFER="arraybuffer",e.BLOB="blob",e.DOCUMENT="document",e.JSON="json",e.RAW="raw",e.STREAM="stream",e.TEXT="text"}(I||(I={}));var k,N,F,$=function(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(s,a)}c((r=r.apply(e,t||[])).next())})};!function(e){e.TEXT_HTML="text/html",e.TEXT_XML="text/xml",e.APPLICATION_XML="application/xml",e.APPLICATION_XHTML="application/xhtml+xml"}(k||(k={})),function(e){e.TEXT_PLAIN="text/plain",e.APPLICATION_JSON="application/json"}(N||(N={})),function(e){e.DOCUMENT="^(text\\/(html|xml))|(application\\/(xml|xhtml\\+xml))$",e.IMAGE="^image\\/.+"}(F||(F={}));class H{static parseDocumentResponse(e,t){try{return"undefined"!=typeof DOMParser?new Promise((n,r)=>{e.text().then(e=>{try{const i=(new DOMParser).parseFromString(e,t);n(i)}catch(e){r(e)}})}):Promise.resolve(e.body)}catch(e){throw e}}static convertResponse(e,t){return $(this,void 0,void 0,function*(){const n=e.clone();if(204===n.status)return Promise.resolve();let r;try{switch(t){case I.ARRAYBUFFER:r=yield n.arrayBuffer();break;case I.BLOB:r=yield n.blob();break;case I.DOCUMENT:r=yield H.parseDocumentResponse(n,k.TEXT_XML);break;case I.JSON:r=yield n.json();break;case I.STREAM:r=yield Promise.resolve(n.body);break;case I.TEXT:r=yield n.text();break;default:const e=n.headers.get("Content-type");if(null!==e){const t=e.split(";")[0];r=new RegExp(F.DOCUMENT).test(t)?yield H.parseDocumentResponse(n,t):new RegExp(F.IMAGE).test(t)?n.blob():t===N.TEXT_PLAIN?yield n.text():t===N.APPLICATION_JSON?yield n.json():Promise.resolve(n.body)}else r=Promise.resolve(n.body)}}catch(e){throw e}return r})}static getResponse(e,t,n){return $(this,void 0,void 0,function*(){try{if(t===I.RAW)return Promise.resolve(e);{const r=yield H.convertResponse(e,t);if(!e.ok)throw r;if("function"!=typeof n)return r;n(null,r,e)}}catch(t){throw e.ok?t:e}})}}var X=function(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(s,a)}c((r=r.apply(e,t||[])).next())})};class Q{constructor(e,t,n){this.parsePath=(e=>{if(-1!==e.indexOf("https://")){const t=(e=e.replace("https://","")).indexOf("/");-1!==t&&(this.urlComponents.host="https://"+e.substring(0,t),e=e.substring(t+1,e.length));const n=e.indexOf("/");-1!==n&&(this.urlComponents.version=e.substring(0,n),e=e.substring(n+1,e.length))}"/"===e.charAt(0)&&(e=e.substr(1));const t=e.indexOf("?");if(-1===t)this.urlComponents.path=e;else{this.urlComponents.path=e.substr(0,t);const n=e.substring(t+1,e.length).split("&");for(const e of n){const t=e.split("="),n=t[0],r=t[1];-1!==M.indexOf(n)?this.urlComponents.oDataQueryParams[n]=r:this.urlComponents.otherURLQueryParams[n]=r}}}),this.httpClient=e,this.config=t,this.urlComponents={host:this.config.baseUrl,version:this.config.defaultVersion,oDataQueryParams:{},otherURLQueryParams:{}},this._headers={},this._options={},this._middlewareOptions=[],this.parsePath(n)}addCsvQueryParameter(e,t,n){this.urlComponents.oDataQueryParams[e]=this.urlComponents.oDataQueryParams[e]?this.urlComponents.oDataQueryParams[e]+",":"";let r=[];n.length>1&&"string"==typeof t?r=Array.prototype.slice.call(n):"string"==typeof t?r.push(t):r=r.concat(t),this.urlComponents.oDataQueryParams[e]+=r.join(",")}buildFullUrl(){const e=U([this.urlComponents.host,this.urlComponents.version,this.urlComponents.path])+this.createQueryString();return this.config.debugLogging&&console.log(e),e}createQueryString(){const e=this.urlComponents,t=[];if(0!==Object.keys(e.oDataQueryParams).length)for(const n in e.oDataQueryParams)e.oDataQueryParams.hasOwnProperty(n)&&t.push(n+"="+e.oDataQueryParams[n]);if(0!==Object.keys(e.otherURLQueryParams).length)for(const n in e.otherURLQueryParams)e.otherURLQueryParams.hasOwnProperty(n)&&t.push(n+"="+e.otherURLQueryParams[n]);return t.length>0?"?"+t.join("&"):""}updateRequestOptions(e){const t={SdkVersion:`graph-js-${D}`},n=Object.assign({},e.headers);if(void 0!==this.config.fetchOptions){const t=Object.assign({},this.config.fetchOptions);Object.assign(e,t),void 0!==typeof this.config.fetchOptions.headers&&(e.headers=Object.assign({},this.config.fetchOptions.headers))}Object.assign(e,this._options),Object.assign(n,t),void 0!==e.headers&&Object.assign(n,e.headers),Object.assign(n,this._headers),e.headers=n}send(e,t,n){return X(this,void 0,void 0,function*(){let r;const o=new i(this._middlewareOptions);this.updateRequestOptions(t);try{return r=(yield this.httpClient.sendRequest({request:e,options:t,middlewareControl:o})).response,yield H.getResponse(r,this._responseType,n)}catch(e){let t;throw void 0!==r&&(t=r.status),yield C.getError(e,t,n)}})}header(e,t){return this._headers[e]=t,this}headers(e){for(const t in e)e.hasOwnProperty(t)&&(this._headers[t]=e[t]);return this}option(e,t){return this._options[e]=t,this}options(e){for(const t in e)e.hasOwnProperty(t)&&(this._options[t]=e[t]);return this}middlewareOptions(e){return this._middlewareOptions=e,this}version(e){return this.urlComponents.version=e,this}responseType(e){return this._responseType=e,this}select(e){return this.addCsvQueryParameter("$select",e,arguments),this}expand(e){return this.addCsvQueryParameter("$expand",e,arguments),this}orderby(e){return this.addCsvQueryParameter("$orderby",e,arguments),this}filter(e){return this.urlComponents.oDataQueryParams.$filter=e,this}search(e){return this.urlComponents.oDataQueryParams.$search=e,this}top(e){return this.urlComponents.oDataQueryParams.$top=e,this}skip(e){return this.urlComponents.oDataQueryParams.$skip=e,this}skipToken(e){return this.urlComponents.oDataQueryParams.$skipToken=e,this}count(e){return this.urlComponents.oDataQueryParams.$count=e.toString(),this}query(e){const t=this.urlComponents.otherURLQueryParams;if("string"==typeof e){const n=e.split("="),r=n[0],i=n[1];t[r]=i}else for(const n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);return this}get(t){return X(this,void 0,void 0,function*(){const n=this.buildFullUrl(),r={method:e.GET};try{return yield this.send(n,r,t)}catch(e){throw e}})}post(t,n){return X(this,void 0,void 0,function*(){const r=this.buildFullUrl(),i={method:e.POST,body:q(t),headers:void 0!==t.constructor&&"FormData"===t.constructor.name?{}:{"Content-Type":"application/json"}};try{return yield this.send(r,i,n)}catch(e){throw e}})}create(e,t){return X(this,void 0,void 0,function*(){try{return yield this.post(e,t)}catch(e){throw e}})}put(t,n){return X(this,void 0,void 0,function*(){const r=this.buildFullUrl(),i={method:e.PUT,body:q(t),headers:{"Content-Type":"application/octet-stream"}};try{return yield this.send(r,i,n)}catch(e){throw e}})}patch(t,n){return X(this,void 0,void 0,function*(){const r=this.buildFullUrl(),i={method:e.PATCH,body:q(t),headers:{"Content-Type":"application/json"}};try{return yield this.send(r,i,n)}catch(e){throw e}})}update(e,t){return X(this,void 0,void 0,function*(){try{return yield this.patch(e,t)}catch(e){throw e}})}delete(t){return X(this,void 0,void 0,function*(){const n=this.buildFullUrl(),r={method:e.DELETE};try{return yield this.send(n,r,t)}catch(e){throw e}})}del(e){return X(this,void 0,void 0,function*(){try{return yield this.delete(e)}catch(e){throw e}})}getStream(t){return X(this,void 0,void 0,function*(){const n=this.buildFullUrl(),r={method:e.GET};this.responseType(I.STREAM);try{return yield this.send(n,r,t)}catch(e){throw e}})}putStream(t,n){return X(this,void 0,void 0,function*(){const r=this.buildFullUrl(),i={method:e.PUT,headers:{"Content-Type":"application/octet-stream"},body:t};try{return yield this.send(r,i,n)}catch(e){throw e}})}}var j=function(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(s,a)}c((r=r.apply(e,t||[])).next())})};class B{constructor(e){this.middleware=e}sendRequest(e){return j(this,void 0,void 0,function*(){try{if(!(e.request instanceof Request)&&void 0===e.options){const e=new Error;throw e.name="InvalidRequestOptions",e.message="Unable to execute the middleware, Please provide valid options for a request",e}return yield this.middleware.execute(e),e}catch(e){throw e}})}}class z{constructor(e=z.DEFAULT_MAX_REDIRECTS,t=z.DEFAULT_SHOULD_RETRY){if(e>z.MAX_MAX_REDIRECTS){const e=new Error(`MaxRedirects should not be more than ${z.MAX_MAX_REDIRECTS}`);throw e.name="MaxLimitExceeded",e}this.maxRedirects=e,this.shouldRedirect=t}}z.DEFAULT_MAX_REDIRECTS=5,z.MAX_MAX_REDIRECTS=20,z.DEFAULT_SHOULD_RETRY=(()=>!0);var Y=function(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(s,a)}c((r=r.apply(e,t||[])).next())})};class V{constructor(e=new z){this.options=e}isRedirect(e){return-1!==V.REDIRECT_STATUS_CODES.indexOf(e.status)}hasLocationHeader(e){return e.headers.has(V.LOCATION_HEADER)}getLocationHeader(e){return e.headers.get(V.LOCATION_HEADER)}isRelativeURL(e){return-1===e.indexOf("://")}shouldDropAuthorizationHeader(e,t){const n=/^[A-Za-z].+?:\/\/.+?(?=\/|$)/,r=n.exec(e);let i,o;null!==r&&(i=r[0]);const s=n.exec(t);return null!==s&&(o=s[0]),void 0!==i&&void 0!==o&&i!==o}updateRequestUrl(e,t){return Y(this,void 0,void 0,function*(){t.request=t.request instanceof Request?yield c(e,t.request):e})}getOptions(e){let t;return e.middlewareControl instanceof i&&(t=e.middlewareControl.getMiddlewareOptions(this.options.constructor.name)),void 0===t&&(t=Object.assign(new z,this.options)),t}executeWithRedirect(t,n,r){return Y(this,void 0,void 0,function*(){try{yield this.nextMiddleware.execute(t);const i=t.response;if(!(n<r.maxRedirects&&this.isRedirect(i)&&this.hasLocationHeader(i)&&r.shouldRedirect(i)))return;if(++n,i.status===V.STATUS_CODE_SEE_OTHER)t.options.method=e.GET,delete t.options.body;else{const e=this.getLocationHeader(i);!this.isRelativeURL(e)&&this.shouldDropAuthorizationHeader(i.url,e)&&a(t.request,t.options,V.AUTHORIZATION_HEADER,void 0),yield this.updateRequestUrl(e,t)}yield this.executeWithRedirect(t,n,r)}catch(e){throw e}})}execute(e){return Y(this,void 0,void 0,function*(){try{const t=0,n=this.getOptions(e);return e.options.redirect=V.MANUAL_REDIRECT,yield this.executeWithRedirect(e,t,n)}catch(e){throw e}})}setNext(e){this.nextMiddleware=e}}V.REDIRECT_STATUS_CODES=[301,302,303,307,308],V.STATUS_CODE_SEE_OTHER=303,V.LOCATION_HEADER="Location",V.AUTHORIZATION_HEADER="Authorization",V.MANUAL_REDIRECT="manual";const W=()=>new Function("try {return this === global;}catch(e){return false;}")();class G{static createWithAuthenticationProvider(e){const t=new h(e),n=new m(new f),r=new p;if(t.setNext(n),W()){const e=new V(new z);n.setNext(e),e.setNext(r)}else n.setNext(r);return G.createWithMiddleware(t)}static createWithMiddleware(e){return new B(e)}}const Z=()=>{if("undefined"==typeof Promise&&"undefined"==typeof fetch){const e=new Error("Library cannot function without Promise and fetch. So, please provide polyfill for them.");throw e.name="PolyFillNotAvailable",e}if("undefined"==typeof Promise){const e=new Error("Library cannot function without Promise. So, please provide polyfill for it.");throw e.name="PolyFillNotAvailable",e}if("undefined"==typeof fetch){const e=new Error("Library cannot function without fetch. So, please provide polyfill for it.");throw e.name="PolyFillNotAvailable",e}return!0};class J{constructor(e){this.config={baseUrl:P,debugLogging:!1,defaultVersion:O};try{Z()}catch(e){throw e}for(const t in e)e.hasOwnProperty(t)&&(this.config[t]=e[t]);let t;if(void 0!==e.authProvider&&void 0!==e.middleware){const e=new Error;throw e.name="AmbiguityInInitialization",e.message="Unable to Create Client, Please provide either authentication provider for default middleware chain or custom middleware chain not both",e}if(void 0!==e.authProvider)t=G.createWithAuthenticationProvider(e.authProvider);else{if(void 0===e.middleware){const e=new Error;throw e.name="InvalidMiddlewareChain",e.message="Unable to Create Client, Please provide either authentication provider for default middleware chain or custom middleware chain",e}t=new B(e.middleware)}this.httpClient=t}static init(e){const t={};for(const n in e)e.hasOwnProperty(n)&&(t[n]="authProvider"===n?new _(e[n]):e[n]);return J.initWithMiddleware(t)}static initWithMiddleware(e){try{return new J(e)}catch(e){throw e}}api(e){return new Q(this.httpClient,this.config,e)}}var K=function(e,t,n,r){return new(n||(n=Promise))(function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){e.done?i(e.value):new n(function(t){t(e.value)}).then(s,a)}c((r=r.apply(e,t||[])).next())})};class ee{constructor(e,t,n){this.scopes=t,this.userAgentApplication="string"==typeof e?new Msal.UserAgentApplication(e,void 0,(e,t,n,r)=>{},n):e}getAccessToken(e){return K(this,void 0,void 0,function*(){let t;if(void 0!==e&&(t=e.scopes),void 0!==t&&0!==t.length||(t=this.scopes),0===t.length){const e=new Error;throw e.name="EmptyScopes",e.message="Scopes cannot be empty, Please provide a scope",e}try{return yield this.userAgentApplication.acquireTokenSilent(t)}catch(e){try{yield this.userAgentApplication.loginPopup(t);try{return yield this.userAgentApplication.acquireTokenSilent(t)}catch(e){return yield this.userAgentApplication.acquireTokenPopup(t)}}catch(e){throw new Error(e)}}})}addScopes(e){if(0===e.length){const e=new Error;throw e.name="EmptyScopes",e.message="Scopes array cannot be empty",e}this.scopes=Array.from(new Set(this.scopes.concat(e)))}clearScopes(){this.scopes=[]}}class te{constructor(e){this.scopes=e}}export{h as AuthenticationHandler,d as AuthenticationHandlerOptions,n as BatchRequestContent,r as BatchResponseContent,J as Client,S as GraphError,Q as GraphRequest,p as HTTPMessageHandler,ee as MSALAuthenticationProvider,te as MSALAuthenticationProviderOptions,x as OneDriveLargeFileUploadTask,T as PageIterator,I as ResponseType,m as RetryHandler,f as RetryHandlerOptions}; |
@@ -26,2 +26,2 @@ /** | ||
*/ | ||
export declare const PACKAGE_VERSION = "1.6.0-Preview.2"; | ||
export declare const PACKAGE_VERSION = "1.6.0-Preview.3"; |
@@ -28,3 +28,3 @@ "use strict"; | ||
*/ | ||
exports.PACKAGE_VERSION = "1.6.0-Preview.2"; | ||
exports.PACKAGE_VERSION = "1.6.0-Preview.3"; | ||
//# sourceMappingURL=Constants.js.map |
{ | ||
"name": "@microsoft/microsoft-graph-client", | ||
"//": "NOTE: The version here should match exactly the exported const PACKAGE_VERSION in Constants.ts. If you change it here, also change it there.", | ||
"version": "1.6.0-Preview.2", | ||
"version": "1.6.0-Preview.3", | ||
"description": "Microsoft Graph Client Library", | ||
@@ -6,0 +6,0 @@ "main": "lib/src/index.js", |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
981221
13043