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

@microsoft/mgt-element

Package Overview
Dependencies
Maintainers
2
Versions
831
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@microsoft/mgt-element - npm Package Compare versions

Comparing version 3.1.3 to 4.0.0-next.mgt-chat.eeea1d6

dist/es6/components/baseTaskComponent.d.ts

3

dist/es6/components/baseComponent.d.ts

@@ -8,2 +8,3 @@ /**

import { LitElement, PropertyValueMap, PropertyValues } from 'lit';
import { ProviderState } from '../providers/IProvider';
/**

@@ -36,4 +37,6 @@ * Defines media query based on component width

* @extends {LitElement}
* @deprecated Use MgtBaseTaskComponent instead
*/
export declare abstract class MgtBaseComponent extends LitElement {
protected providerState: ProviderState;
/**

@@ -40,0 +43,0 @@ * Exposes the semver of the library the component is part of

@@ -59,2 +59,3 @@ /**

* @extends {LitElement}
* @deprecated Use MgtBaseTaskComponent instead
*/

@@ -122,2 +123,3 @@ export class MgtBaseComponent extends LitElement {

super();
this.providerState = ProviderState.Loading;
/**

@@ -145,2 +147,4 @@ * Gets or sets the direction of the component

this.handleProviderUpdates = () => {
var _a, _b;
this.providerState = (_b = (_a = Providers.globalProvider) === null || _a === void 0 ? void 0 : _a.state) !== null && _b !== void 0 ? _b : ProviderState.Loading;
void this.requestStateUpdate();

@@ -318,4 +322,8 @@ };

state(),
__metadata("design:type", Number)
], MgtBaseComponent.prototype, "providerState", void 0);
__decorate([
state(),
__metadata("design:type", String)
], MgtBaseComponent.prototype, "direction", void 0);
//# sourceMappingURL=baseComponent.js.map

2

dist/es6/components/customElementHelper.d.ts

@@ -13,3 +13,3 @@ /**

*
* @param {string} disambiguation
* @param {string} disambiguation the disambiguation value to be used, should be lowercase
* @return {CustomElementHelper} the current object

@@ -16,0 +16,0 @@ * @memberof CustomElementHelper

@@ -17,3 +17,3 @@ /**

*
* @param {string} disambiguation
* @param {string} disambiguation the disambiguation value to be used, should be lowercase
* @return {CustomElementHelper} the current object

@@ -23,4 +23,7 @@ * @memberof CustomElementHelper

withDisambiguation(disambiguation) {
if (disambiguation && !this._disambiguation)
this._disambiguation = disambiguation;
if (disambiguation && !this._disambiguation) {
this._disambiguation = disambiguation.toLowerCase();
if (disambiguation !== this._disambiguation)
console.warn(`🦒: Disambiguation value, ${disambiguation}, should be lowercase. Value has been converted to lowercase, ${this._disambiguation}.`);
}
return this;

@@ -27,0 +30,0 @@ }

@@ -10,2 +10,15 @@ /**

import { TemplateContext } from '../utils/TemplateContext';
/**
* Lookup for rendered component templates and contexts by slot name.
*/
export type RenderedTemplates = Record<string, {
/**
* Reference to the data context used to render the slot.
*/
context: Record<string, unknown>;
/**
* Reference to the rendered DOM element corresponding to the slot.
*/
slot: HTMLElement;
}>;
export interface TemplateRenderedData {

@@ -16,3 +29,3 @@ templateType: string;

}
type OrderedHtmlTemplate = HTMLTemplateElement & {
export type OrderedHtmlTemplate = HTMLTemplateElement & {
templateOrder: number;

@@ -27,2 +40,3 @@ };

* @extends {MgtBaseComponent}
* @deprecated Use MgtTemplatedTaskComponent instead
*

@@ -104,3 +118,2 @@ * @fires {CustomEvent<MgtElement.TemplateRenderedData>} templateRendered - fires when a template is rendered

}
export {};
//# sourceMappingURL=templatedComponent.d.ts.map

@@ -28,2 +28,3 @@ /**

* @extends {MgtBaseComponent}
* @deprecated Use MgtTemplatedTaskComponent instead
*

@@ -30,0 +31,0 @@ * @fires {CustomEvent<MgtElement.TemplateRenderedData>} templateRendered - fires when a template is rendered

@@ -55,3 +55,3 @@ /**

*/
forComponent(component: Element | string): Graph;
forComponent(component: Element | string, version?: string): Graph;
/**

@@ -89,3 +89,3 @@ * Returns a new graph request for a specific component

*/
export declare const createFromProvider: (provider: IProvider, version?: string, component?: Element) => Graph;
export declare const createFromProvider: (provider: IProvider, version?: string, component?: Element | string) => Graph;
//# sourceMappingURL=Graph.d.ts.map

@@ -11,3 +11,3 @@ /**

import { ComponentMiddlewareOptions } from './utils/ComponentMiddlewareOptions';
import { chainMiddleware } from './utils/GraphHelpers';
import { chainMiddleware } from './utils/chainMiddleware';
import { SdkVersionMiddleware } from './utils/SdkVersionMiddleware';

@@ -70,4 +70,4 @@ import { PACKAGE_VERSION } from './utils/version';

*/
forComponent(component) {
const graph = new Graph(this._client, this._version);
forComponent(component, version) {
const graph = new Graph(this._client, version || this._version);
graph.setComponent(component);

@@ -87,3 +87,3 @@ return graph;

request.middlewareOptions = (options) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call, @typescript-eslint/dot-notation
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/dot-notation
request['_middlewareOptions'] = request['_middlewareOptions'].concat(options);

@@ -90,0 +90,0 @@ return request;

@@ -45,3 +45,3 @@ /**

*/
forComponent(component: Element): IGraph;
forComponent(component: Element | string, version?: string): IGraph;
/**

@@ -48,0 +48,0 @@ * use this method to make calls directly to the Graph.

@@ -13,3 +13,5 @@ /**

export * from './components/baseProvider';
export * from './components/baseTaskComponent';
export * from './components/templatedComponent';
export * from './components/templatedTaskComponent';
export * from './components/customElementHelper';

@@ -23,3 +25,5 @@ export * from './providers/IProvider';

export * from './utils/equals';
export * from './utils/GraphHelpers';
export * from './utils/chainMiddleware';
export * from './utils/prepScopes';
export * from './utils/validateBaseURL';
export * from './utils/TeamsHelper';

@@ -32,2 +36,4 @@ export * from './utils/TemplateContext';

export * from './utils/CustomElement';
export * from './utils/Logging';
export * from './utils/registerComponent';
export { PACKAGE_VERSION } from './utils/version';

@@ -34,0 +40,0 @@ export * from './CollectionResponse';

@@ -13,3 +13,5 @@ /**

export * from './components/baseProvider';
export * from './components/baseTaskComponent';
export * from './components/templatedComponent';
export * from './components/templatedTaskComponent';
export * from './components/customElementHelper';

@@ -23,3 +25,5 @@ export * from './providers/IProvider';

export * from './utils/equals';
export * from './utils/GraphHelpers';
export * from './utils/chainMiddleware';
export * from './utils/prepScopes';
export * from './utils/validateBaseURL';
export * from './utils/TeamsHelper';

@@ -32,2 +36,4 @@ export * from './utils/TemplateContext';

export * from './utils/CustomElement';
export * from './utils/Logging';
export * from './utils/registerComponent';
export { PACKAGE_VERSION } from './utils/version';

@@ -34,0 +40,0 @@ export * from './CollectionResponse';

@@ -34,4 +34,4 @@ /**

*/
forComponent(component: MgtBaseComponent): MockGraph;
forComponent(component: MgtBaseComponent | string): MockGraph;
}
//# sourceMappingURL=MockGraph.d.ts.map

@@ -18,3 +18,3 @@ /**

import { Graph } from '../Graph';
import { chainMiddleware } from '../utils/GraphHelpers';
import { chainMiddleware } from '../utils/chainMiddleware';
import { MockMiddleware } from './MockMiddleware';

@@ -21,0 +21,0 @@ /**

@@ -90,5 +90,5 @@ /**

static setBaseFallbackUrl() {
this._baseUrl = 'https://proxy.apisandbox.msdn.microsoft.com/svc?url=';
this._baseUrl = 'https://graph.office.net/en-us/graph/api/proxy?url=';
}
}
//# sourceMappingURL=MockMiddleware.js.map

@@ -11,3 +11,3 @@ /**

/**
* Provider Type to be extended for implmenting new providers
* Provider Type to be extended for implementing new providers
*

@@ -47,3 +47,15 @@ * @export

private _baseURL;
private _approvedScopes;
get approvedScopes(): string[];
set approvedScopes(value: string[]);
hasAtLeastOneApprovedScope(requiredScopeSet: string[]): boolean;
hasAllOneApprovedScope(requiredScopeSet: string[]): boolean;
/**
* Examines the currently consented scopes for any match in the requiredScopeSet to determine what, if any, scopes need to be consented to
*
* @param {string[]} requiredScopeSet an array of scopes to be checked
* @returns {string[]} if any matches in requiredScopeSet exist then an empty array is returns, otherwise an array containing the first element in the requiredScopeSet is returned
*/
needsAdditionalScopes(requiredScopeSet: string[]): string[];
/**
* The base URL to be used in the graph client config.

@@ -213,2 +225,3 @@ */

export interface ActiveAccountChanged {
detail: IProviderAccount;
}

@@ -222,2 +235,3 @@ /**

export interface LoginChangedEvent {
detail: ProviderState;
}

@@ -224,0 +238,0 @@ /**

@@ -7,7 +7,7 @@ /**

*/
import { validateBaseURL } from '../utils/GraphHelpers';
import { validateBaseURL } from '../utils/validateBaseURL';
import { MICROSOFT_GRAPH_DEFAULT_ENDPOINT } from '../IGraph';
import { EventDispatcher } from '../utils/EventDispatcher';
/**
* Provider Type to be extended for implmenting new providers
* Provider Type to be extended for implementing new providers
*

@@ -30,3 +30,28 @@ * @export

}
get approvedScopes() {
return this._approvedScopes;
}
set approvedScopes(value) {
this._approvedScopes = value.map(v => v.toLowerCase());
}
hasAtLeastOneApprovedScope(requiredScopeSet) {
return requiredScopeSet.some(s => this.approvedScopes.includes(s.toLowerCase().trim()));
}
hasAllOneApprovedScope(requiredScopeSet) {
return requiredScopeSet.some(s => !this.approvedScopes.includes(s.toLowerCase().trim()));
}
/**
* Examines the currently consented scopes for any match in the requiredScopeSet to determine what, if any, scopes need to be consented to
*
* @param {string[]} requiredScopeSet an array of scopes to be checked
* @returns {string[]} if any matches in requiredScopeSet exist then an empty array is returns, otherwise an array containing the first element in the requiredScopeSet is returned
*/
needsAdditionalScopes(requiredScopeSet) {
const reqScopes = [];
if (requiredScopeSet.length && !this.hasAtLeastOneApprovedScope(requiredScopeSet)) {
reqScopes.push(requiredScopeSet[0].trim());
}
return reqScopes;
}
/**
* The base URL to be used in the graph client config.

@@ -114,2 +139,3 @@ */

this._baseURL = MICROSOFT_GRAPH_DEFAULT_ENDPOINT;
this._approvedScopes = [];
this._customHosts = undefined;

@@ -142,3 +168,3 @@ /**

this._state = state;
this._loginChangedDispatcher.fire({});
this._loginChangedDispatcher.fire({ detail: this._state });
}

@@ -172,3 +198,3 @@ }

setActiveAccount(user) {
this.fireActiveAccountChanged();
this.fireActiveAccountChanged({ detail: user });
}

@@ -198,4 +224,4 @@ /**

*/
fireActiveAccountChanged() {
this._activeAccountChangedDispatcher.fire({});
fireActiveAccountChanged(account) {
this._activeAccountChangedDispatcher.fire(account);
}

@@ -202,0 +228,0 @@ /**

@@ -36,3 +36,5 @@ /**

* @param {string} resource
* @param {string[]} [scopes]
* @param {string[]} [scopes] any additional scopes that should be requested
* Note: use `IProvider.needsAdditionalScopes(scopes)` to calculate which
* scopes, if any, need to be requested before calling `Batch.get()`
* @memberof Batch

@@ -39,0 +41,0 @@ */

@@ -18,4 +18,4 @@ /**

import { BatchRequestContent } from '@microsoft/microsoft-graph-client';
import { delay } from '../utils';
import { prepScopes } from './GraphHelpers';
import { delay } from './delay';
import { prepScopes } from './prepScopes';
import { BatchRequest } from './BatchRequest';

@@ -56,3 +56,5 @@ /**

* @param {string} resource
* @param {string[]} [scopes]
* @param {string[]} [scopes] any additional scopes that should be requested
* Note: use `IProvider.needsAdditionalScopes(scopes)` to calculate which
* scopes, if any, need to be requested before calling `Batch.get()`
* @memberof Batch

@@ -99,3 +101,3 @@ */

}
const middlewareOptions = this.scopes.length ? prepScopes(...this.scopes) : [];
const middlewareOptions = this.scopes.length ? prepScopes(this.scopes) : [];
const batchRequest = this.graph.api('$batch').middlewareOptions(middlewareOptions);

@@ -102,0 +104,0 @@ const batchRequestBody = yield batchRequestContent.getContent();

@@ -92,2 +92,9 @@ /**

fileLists: CacheOptions;
/**
* Cache options for conversation store
*
* @type {CacheOptions}
* @memberof CacheConfig
*/
conversation: CacheOptions;
}

@@ -164,2 +171,6 @@ /**

}
export interface Index {
name: string;
field: string;
}
/**

@@ -193,2 +204,8 @@ * Represents organization for a cache

stores: Record<string, string>;
/**
* Optional field to define indexed fields on a per store basis
* K is the name of the store for which the indexes should be applied
* T is the names of the fields on the stored data to be indexed
*/
indexes?: Record<string, Index[]>;
}

@@ -195,0 +212,0 @@ /**

@@ -19,2 +19,3 @@ /**

import { CacheStore } from './CacheStore';
import { error } from './Logging';
/**

@@ -72,3 +73,3 @@ * Localstorage key for storing names of cache databases

delReq.onerror = () => {
console.error(`🦒: ${delReq.error.name} occurred deleting cache: ${x}`, delReq.error.message);
error(`${delReq.error.name} occurred deleting cache: ${x}`, delReq.error.message);
reject();

@@ -164,4 +165,8 @@ };

isEnabled: true
},
conversation: {
invalidationPeriod: 5 * 24 * 60 * 60 * 1000,
isEnabled: true
}
};
//# sourceMappingURL=CacheService.js.map

@@ -7,2 +7,3 @@ /**

*/
import { IDBPObjectStore } from 'idb';
import { CacheItem, CacheSchema } from './CacheService';

@@ -26,4 +27,12 @@ /**

*/
getValue(key: string): Promise<T>;
getValue(key: string): Promise<T | null>;
/**
* removes a value from the cache for the given key
*
* @param {string} key
* @returns {Promise<void>}
* @memberof Cache
*/
delete(key: string): Promise<void>;
/**
* inserts value into cache for the given key

@@ -49,3 +58,9 @@ *

private getDb;
queryDb(indexName: string, query: IDBKeyRange | IDBValidKey): Promise<T[]>;
/**
* Helper function to get a wrapping transaction for an action function
* @param action a function that takes an object store uses it to make changes to the cache
*/
transaction(action: (store: IDBPObjectStore<unknown, [string], string, 'readwrite'>) => Promise<void>): Promise<void>;
}
//# sourceMappingURL=CacheStore.d.ts.map

@@ -55,2 +55,23 @@ /**

/**
* removes a value from the cache for the given key
*
* @param {string} key
* @returns {Promise<void>}
* @memberof Cache
*/
delete(key) {
return __awaiter(this, void 0, void 0, function* () {
if (!window.indexedDB) {
return;
}
try {
const db = yield this.getDb();
return db.delete(this.store, key);
}
catch (e) {
return;
}
});
}
/**
* inserts value into cache for the given key

@@ -112,3 +133,4 @@ *

// eslint-disable-next-line @typescript-eslint/no-unused-vars
upgrade: (db, _oldVersion, _newVersion, _transaction) => {
upgrade: (db, _oldVersion, _newVersion, transaction) => {
var _a, _b;
const dbArray = JSON.parse(localStorage.getItem(dbListKey)) || [];

@@ -120,5 +142,18 @@ if (!dbArray.includes(dbName)) {

for (const storeName in this.schema.stores) {
if (Object.prototype.hasOwnProperty.call(this.schema.stores, storeName) &&
!db.objectStoreNames.contains(storeName)) {
db.createObjectStore(storeName);
if (Object.prototype.hasOwnProperty.call(this.schema.stores, storeName)) {
const indexes = (_b = (_a = this.schema.indexes) === null || _a === void 0 ? void 0 : _a[storeName]) !== null && _b !== void 0 ? _b : [];
if (!db.objectStoreNames.contains(storeName)) {
const objectStore = db.createObjectStore(storeName);
indexes.forEach(i => {
objectStore.createIndex(i.name, i.field);
});
}
else {
const store = transaction.objectStore(storeName);
indexes.forEach(i => {
if (store && !store.indexNames.contains(i.name)) {
store.createIndex(i.name, i.field);
}
});
}
}

@@ -131,3 +166,22 @@ }

}
queryDb(indexName, query) {
return __awaiter(this, void 0, void 0, function* () {
const db = yield this.getDb();
return (yield db.getAllFromIndex(this.store, indexName, query));
});
}
/**
* Helper function to get a wrapping transaction for an action function
* @param action a function that takes an object store uses it to make changes to the cache
*/
transaction(action) {
return __awaiter(this, void 0, void 0, function* () {
const db = yield this.getDb();
const tx = db.transaction(this.store, 'readwrite');
const store = tx.objectStore(this.store);
yield action(store);
yield tx.done;
});
}
}
//# sourceMappingURL=CacheStore.js.map

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

import { customElementHelper } from '../components/customElementHelper';
import { error } from './Logging';
/**

@@ -27,4 +28,3 @@ * This is a wrapper decorator for `customElement` from `lit`

return (classOrDescriptor) => {
// eslint-disable-next-line no-console
console.error(`🦒: Tag name ${mgtTagName} is already defined using class ${mgtElement.name} version ${version(mgtElement)}\n`, `Currently registering class ${classOrDescriptor.name} with version ${version(classOrDescriptor)}\n`, 'Please use the disambiguation feature to define a unique tag name for this component see: https://github.com/microsoftgraph/microsoft-graph-toolkit/tree/main/packages/mgt-components#disambiguation');
error(`Tag name ${mgtTagName} is already defined using class ${mgtElement.name} version ${version(mgtElement)}\n`, `Currently registering class ${classOrDescriptor.name} with version ${version(classOrDescriptor)}\n`, 'Please use the disambiguation feature to define a unique tag name for this component see: https://github.com/microsoftgraph/microsoft-graph-toolkit/tree/main/packages/mgt-components#disambiguation');
return classOrDescriptor;

@@ -31,0 +31,0 @@ };

@@ -7,3 +7,10 @@ /**

*/
import { it } from '@jest/globals';
/* eslint-disable @typescript-eslint/no-unused-expressions */
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { expect } from '@open-wc/testing';
import { equals } from './equals';

@@ -17,34 +24,40 @@ describe('objectEquals', () => {

const simpleDate = new Date(0);
it.each([
[{}, {}],
[
{ a: 1, b: true, c: 'foo' },
{ c: 'foo', b: true, a: 1 }
],
[{ a: [1, 2, 3] }, { a: [1, 2, 3] }],
[{ a: { b: { c: 1 } } }, { a: { b: { c: 1 } } }],
[{ a: [1, [2, [3]]] }, { a: [1, [2, [3]]] }],
[circularObject, circularObject],
[circularObject, { a: circularObject }],
[circularArray, circularArray],
[
{ a: circularObject, b: circularArray },
{ a: circularObject, b: circularArray }
],
[{ a: simpleDate }, { a: simpleDate }]
])('should return true between %p and %p', (o1, o2) => {
expect(equals(o1, o2)).toBe(true);
it('should return true', () => {
const testValues = [
[{}, {}],
[
{ a: 1, b: true, c: 'foo' },
{ c: 'foo', b: true, a: 1 }
],
[{ a: [1, 2, 3] }, { a: [1, 2, 3] }],
[{ a: { b: { c: 1 } } }, { a: { b: { c: 1 } } }],
[{ a: [1, [2, [3]]] }, { a: [1, [2, [3]]] }],
[circularObject, circularObject],
[circularObject, { a: circularObject }],
[circularArray, circularArray],
[
{ a: circularObject, b: circularArray },
{ a: circularObject, b: circularArray }
],
[{ a: simpleDate }, { a: simpleDate }]
];
for (const [o1, o2] of testValues) {
expect(equals(o1, o2)).to.be.true;
}
});
it.each([
[{ a: {} }, { a: [] }],
[{ a: [1, 2, 3] }, { a: [3, 2, 1] }],
[{ a: [1, [2, [3]]] }, { a: [1, [2, [4]]] }],
[{ a: { b: [{ c: 1 }, { d: [2, 3] }] } }, { a: { b: [{ c: 1 }, { d: [3, 2] }] } }],
[{ a: new Date() }, { a: new Date() }],
[circularObject, circularArray],
[circularObject, { b: circularObject }]
])('should return false between %p and %p', (o1, o2) => {
expect(equals(o1, o2)).toBe(false);
it('should return false ', () => {
const testValues = [
[{ a: {} }, { a: [] }],
[{ a: [1, 2, 3] }, { a: [3, 2, 1] }],
[{ a: [1, [2, [3]]] }, { a: [1, [2, [4]]] }],
[{ a: { b: [{ c: 1 }, { d: [2, 3] }] } }, { a: { b: [{ c: 1 }, { d: [3, 2] }] } }],
[{ a: new Date() }, { a: new Date() }],
[circularObject, circularArray],
[circularObject, { b: circularObject }]
];
for (const [o1, o2] of testValues) {
expect(equals(o1, o2)).to.be.false;
}
});
});
//# sourceMappingURL=equals.tests.js.map

@@ -7,19 +7,22 @@ /**

*/
import { it } from '@jest/globals';
import { assert } from 'console';
import { EventDispatcher } from './EventDispatcher';
import { assert, restore, fake } from 'sinon';
describe('EventDispatcher tests', () => {
afterEach(() => {
// Restore the default sandbox here
restore();
});
it('should add and remove event handlers', () => {
const dispatcher = new EventDispatcher();
const handler1 = jest.fn();
const handler2 = jest.fn();
const handler1 = fake();
const handler2 = fake();
dispatcher.add(handler1);
dispatcher.add(handler2);
dispatcher.fire('event');
expect(handler1).toHaveBeenCalledTimes(1);
expect(handler2).toHaveBeenCalledTimes(1);
assert.calledOnce(handler1);
assert.calledOnce(handler2);
dispatcher.remove(handler1);
dispatcher.fire('event');
expect(handler1).toHaveBeenCalledTimes(1);
expect(handler2).toHaveBeenCalledTimes(2);
assert.calledOnce(handler1);
assert.callCount(handler2, 2);
});

@@ -29,11 +32,11 @@ it('should not throw when remove is called with an unregistered handler', () => {

const dispatcher = new EventDispatcher();
const handler1 = jest.fn();
const handler1 = fake();
dispatcher.remove(handler1);
}
catch (e) {
assert(false, 'should not throw');
assert.fail('should not throw');
}
assert(true, 'did not throw');
assert.pass('did not throw');
});
});
//# sourceMappingURL=EventDispatcher.tests.js.map

@@ -7,31 +7,51 @@ /**

*/
import { it } from '@jest/globals';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
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) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
/* eslint-disable @typescript-eslint/no-unused-expressions */
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { expect } from '@open-wc/testing';
import { fake } from 'sinon';
import { AuthenticationHandlerOptions } from '@microsoft/microsoft-graph-client';
import { MockProvider } from '../mock/MockProvider';
import { Providers } from '../providers/Providers';
import { chainMiddleware, prepScopes, validateBaseURL } from './GraphHelpers';
import { chainMiddleware } from './chainMiddleware';
import { prepScopes } from './prepScopes';
import { validateBaseURL } from './validateBaseURL';
describe('GraphHelpers - prepScopes', () => {
it('should return an empty array when incremental consent is disabled', () => {
it('should return an empty array when incremental consent is disabled', () => __awaiter(void 0, void 0, void 0, function* () {
const scopes = ['scope1', 'scope2'];
Providers.globalProvider = new MockProvider(true);
Providers.globalProvider.isIncrementalConsentDisabled = true;
expect(prepScopes(...scopes)).toEqual([]);
});
it('should return an array of AuthenticationHandlerOptions when incremental consent is enabled', () => {
// eql for loose equality
yield expect(prepScopes(scopes)).to.eql([]);
}));
it('should return an array of AuthenticationHandlerOptions when incremental consent is enabled with only the first scope in the list', () => __awaiter(void 0, void 0, void 0, function* () {
const scopes = ['scope1', 'scope2'];
Providers.globalProvider = new MockProvider(true);
Providers.globalProvider.isIncrementalConsentDisabled = false;
expect(prepScopes(...scopes)).toEqual([new AuthenticationHandlerOptions(undefined, { scopes })]);
});
yield expect(prepScopes(scopes)).to.eql([new AuthenticationHandlerOptions(undefined, { scopes: ['scope1'] })]);
}));
});
describe('GraphHelpers - chainMiddleware', () => {
it('should return the first middleware when only one is passed', () => {
const middleware = [{ execute: jest.fn(), setNext: jest.fn() }];
it('should return the first middleware when only one is passed', () => __awaiter(void 0, void 0, void 0, function* () {
const middleware = [{ execute: fake(), setNext: fake() }];
const result = chainMiddleware(...middleware);
expect(result).toEqual(middleware[0]);
});
yield expect(result).to.equal(middleware[0]);
}));
it('should return undefined when the middleware array is empty', () => {
const middleware = [];
const result = chainMiddleware(...middleware);
expect(result).toBeUndefined();
expect(result).to.be.undefined;
});

@@ -42,3 +62,3 @@ it('should now throw when the middleware array is undefined', () => {

const result = chainMiddleware(undefined);
expect(result).toBeUndefined();
expect(result).to.be.undefined;
}

@@ -48,22 +68,31 @@ catch (e) {

}
expect(error).toBeUndefined();
expect(error).to.be.undefined;
});
});
describe('GraphHelpers - validateBaseUrl', () => {
it.each([
'https://graph.microsoft.com',
'https://graph.microsoft.us',
'https://dod-graph.microsoft.us',
'https://graph.microsoft.de',
'https://microsoftgraph.chinacloudapi.cn'
])('should return %p as a valid base url', (graphUrl) => {
expect(validateBaseURL(graphUrl)).toBe(graphUrl);
it('should return as a valid Url', () => __awaiter(void 0, void 0, void 0, function* () {
const validUrls = [
'https://graph.microsoft.com',
'https://graph.microsoft.us',
'https://dod-graph.microsoft.us',
'https://graph.microsoft.de',
'https://microsoftgraph.chinacloudapi.cn'
];
for (const url of validUrls) {
yield expect(validateBaseURL(url)).to.equal(url);
}
}));
it('should return undefeined for invalid Url', () => {
const validUrls = ['https://graph.microsoft.net', 'https://random.us', 'https://nope.cn'];
for (const url of validUrls) {
expect(validateBaseURL(url)).to.be.undefined;
}
});
it.each(['https://graph.microsoft.net', 'https://random.us', 'https://nope.cn'])('should return undefined for %p as an invalid base url', (graphUrl) => {
expect(validateBaseURL(graphUrl)).toBeUndefined();
it('should return undefined for when supplied a %p which is not a well formed url', () => {
const testValues = ['not a url', 'graph.microsoft.com'];
for (const test of testValues) {
expect(validateBaseURL(test)).to.be.undefined;
}
});
it.each(['not a url', 'graph.microsoft.com'])('should return undefined for when supplied a %p which is not a well formed url', (input) => {
expect(validateBaseURL(input)).toBeUndefined();
});
});
//# sourceMappingURL=GraphHelpers.tests.js.map

@@ -12,3 +12,3 @@ /**

_components: LocalizationRecord;
} & Record<string, string>;
} & Record<string, string | LocalizationRecord>;
/**

@@ -15,0 +15,0 @@ * Helper class for Localization

@@ -18,3 +18,3 @@ /**

import { ComponentMiddlewareOptions } from './ComponentMiddlewareOptions';
import { validateBaseURL } from './GraphHelpers';
import { validateBaseURL } from './validateBaseURL';
/**

@@ -21,0 +21,0 @@ * Implements Middleware for the Graph sdk to inject

@@ -7,3 +7,3 @@ /**

*/
export declare const PACKAGE_VERSION = "3.1.3";
export declare const PACKAGE_VERSION = "4.0.0-next.mgt-chat.eeea1d6";
//# sourceMappingURL=version.d.ts.map

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

// ANY CHANGES WILL BE LOST DURING BUILD
export const PACKAGE_VERSION = '3.1.3';
export const PACKAGE_VERSION = '4.0.0-next.mgt-chat.eeea1d6';
//# sourceMappingURL=version.js.map
{
"name": "@microsoft/mgt-element",
"version": "3.1.3",
"version": "4.0.0-next.mgt-chat.eeea1d6",
"description": "Microsoft Graph Toolkit base classes",

@@ -33,6 +33,8 @@ "homepage": "https://github.com/microsoftgraph/microsoft-graph-toolkit",

},
"sideEffects": false,
"dependencies": {
"@lit/task": "^1.0.0",
"@microsoft/microsoft-graph-client": "3.0.2",
"idb": "6.0.0",
"lit": "^2.3.1"
"lit": "^3.0.0"
},

@@ -39,0 +41,0 @@ "publishConfig": {

@@ -27,3 +27,4 @@ # Microsoft Graph Toolkit Base package

import {Providers} from '@microsoft/mgt-element';
import {Msal2Provider} from '@microsoft/mgt-msal2-provider';
// importing via the export path will exclude the custom element for <mgt-msal2-proivder> from the final bundle
import {Msal2Provider} from '@microsoft/mgt-msal2-provider/dist/es6/exports';

@@ -30,0 +31,0 @@ // initialize the auth provider globally

@@ -45,4 +45,7 @@ /**

* @extends {LitElement}
* @deprecated Use MgtBaseTaskComponent instead
*/
export abstract class MgtBaseComponent extends LitElement {
@state()
protected providerState: ProviderState = ProviderState.Loading;
/**

@@ -313,2 +316,3 @@ * Exposes the semver of the library the component is part of

private readonly handleProviderUpdates = () => {
this.providerState = Providers.globalProvider?.state ?? ProviderState.Loading;
void this.requestStateUpdate();

@@ -315,0 +319,0 @@ };

@@ -17,3 +17,3 @@ /**

*
* @param {string} disambiguation
* @param {string} disambiguation the disambiguation value to be used, should be lowercase
* @return {CustomElementHelper} the current object

@@ -23,3 +23,9 @@ * @memberof CustomElementHelper

public withDisambiguation(disambiguation: string) {
if (disambiguation && !this._disambiguation) this._disambiguation = disambiguation;
if (disambiguation && !this._disambiguation) {
this._disambiguation = disambiguation.toLowerCase();
if (disambiguation !== this._disambiguation)
console.warn(
`🦒: Disambiguation value, ${disambiguation}, should be lowercase. Value has been converted to lowercase, ${this._disambiguation}.`
);
}
return this;

@@ -26,0 +32,0 @@ }

@@ -19,3 +19,3 @@ /**

*/
type RenderedTemplates = Record<
export type RenderedTemplates = Record<
string,

@@ -40,3 +40,3 @@ {

type OrderedHtmlTemplate = HTMLTemplateElement & { templateOrder: number };
export type OrderedHtmlTemplate = HTMLTemplateElement & { templateOrder: number };

@@ -50,2 +50,3 @@ /**

* @extends {MgtBaseComponent}
* @deprecated Use MgtTemplatedTaskComponent instead
*

@@ -52,0 +53,0 @@ * @fires {CustomEvent<MgtElement.TemplateRenderedData>} templateRendered - fires when a template is rendered

@@ -24,3 +24,3 @@ /**

import { ComponentMiddlewareOptions } from './utils/ComponentMiddlewareOptions';
import { chainMiddleware } from './utils/GraphHelpers';
import { chainMiddleware } from './utils/chainMiddleware';
import { SdkVersionMiddleware } from './utils/SdkVersionMiddleware';

@@ -93,4 +93,4 @@ import { PACKAGE_VERSION } from './utils/version';

*/
public forComponent(component: Element | string): Graph {
const graph = new Graph(this._client, this._version);
public forComponent(component: Element | string, version?: string): Graph {
const graph = new Graph(this._client, version || this._version);
graph.setComponent(component);

@@ -112,4 +112,4 @@ return graph;

request.middlewareOptions = (options: MiddlewareOptions[]): GraphRequest => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call, @typescript-eslint/dot-notation
request['_middlewareOptions'] = request['_middlewareOptions'].concat(options);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/dot-notation
request['_middlewareOptions'] = (request['_middlewareOptions'] as MiddlewareOptions[]).concat(options);
return request;

@@ -153,3 +153,3 @@ };

*/
export const createFromProvider = (provider: IProvider, version?: string, component?: Element): Graph => {
export const createFromProvider = (provider: IProvider, version?: string, component?: Element | string): Graph => {
const middleware: Middleware[] = [

@@ -156,0 +156,0 @@ new AuthenticationHandler(provider),

@@ -50,3 +50,3 @@ /**

*/
forComponent(component: Element): IGraph;
forComponent(component: Element | string, version?: string): IGraph;

@@ -53,0 +53,0 @@ /**

@@ -15,3 +15,5 @@ /**

export * from './components/baseProvider';
export * from './components/baseTaskComponent';
export * from './components/templatedComponent';
export * from './components/templatedTaskComponent';
export * from './components/customElementHelper';

@@ -27,3 +29,5 @@

export * from './utils/equals';
export * from './utils/GraphHelpers';
export * from './utils/chainMiddleware';
export * from './utils/prepScopes';
export * from './utils/validateBaseURL';
export * from './utils/TeamsHelper';

@@ -36,2 +40,5 @@ export * from './utils/TemplateContext';

export * from './utils/CustomElement';
export * from './utils/Logging';
export * from './utils/registerComponent';
export { PACKAGE_VERSION } from './utils/version';

@@ -38,0 +45,0 @@

@@ -19,3 +19,3 @@ /**

import { Graph } from '../Graph';
import { chainMiddleware } from '../utils/GraphHelpers';
import { chainMiddleware } from '../utils/chainMiddleware';

@@ -66,3 +66,3 @@ import { MockProvider } from './MockProvider';

// eslint-disable-next-line @typescript-eslint/no-unused-vars
public forComponent(component: MgtBaseComponent): MockGraph {
public forComponent(component: MgtBaseComponent | string): MockGraph {
// The purpose of the forComponent pattern is to update the headers of any outgoing Graph requests.

@@ -69,0 +69,0 @@ // The MockGraph isn't making real Graph requests, so we can simply no-op and return the same instance.

@@ -88,4 +88,4 @@ /**

private static setBaseFallbackUrl() {
this._baseUrl = 'https://proxy.apisandbox.msdn.microsoft.com/svc?url=';
this._baseUrl = 'https://graph.office.net/en-us/graph/api/proxy?url=';
}
}

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

import { AuthenticationProvider, AuthenticationProviderOptions } from '@microsoft/microsoft-graph-client';
import { validateBaseURL } from '../utils/GraphHelpers';
import { validateBaseURL } from '../utils/validateBaseURL';
import { GraphEndpoint, IGraph, MICROSOFT_GRAPH_DEFAULT_ENDPOINT } from '../IGraph';

@@ -15,3 +15,3 @@ import { EventDispatcher, EventHandler } from '../utils/EventDispatcher';

/**
* Provider Type to be extended for implmenting new providers
* Provider Type to be extended for implementing new providers
*

@@ -51,2 +51,3 @@ * @export

}
private _state: ProviderState;

@@ -57,3 +58,34 @@ private readonly _loginChangedDispatcher = new EventDispatcher<LoginChangedEvent>();

private _approvedScopes: string[] = [];
public get approvedScopes(): string[] {
return this._approvedScopes;
}
public set approvedScopes(value: string[]) {
this._approvedScopes = value.map(v => v.toLowerCase());
}
public hasAtLeastOneApprovedScope(requiredScopeSet: string[]): boolean {
return requiredScopeSet.some(s => this.approvedScopes.includes(s.toLowerCase().trim()));
}
public hasAllOneApprovedScope(requiredScopeSet: string[]): boolean {
return requiredScopeSet.some(s => !this.approvedScopes.includes(s.toLowerCase().trim()));
}
/**
* Examines the currently consented scopes for any match in the requiredScopeSet to determine what, if any, scopes need to be consented to
*
* @param {string[]} requiredScopeSet an array of scopes to be checked
* @returns {string[]} if any matches in requiredScopeSet exist then an empty array is returns, otherwise an array containing the first element in the requiredScopeSet is returned
*/
public needsAdditionalScopes(requiredScopeSet: string[]): string[] {
const reqScopes: string[] = [];
if (requiredScopeSet.length && !this.hasAtLeastOneApprovedScope(requiredScopeSet)) {
reqScopes.push(requiredScopeSet[0].trim());
}
return reqScopes;
}
/**
* The base URL to be used in the graph client config.

@@ -168,3 +200,3 @@ */

this._state = state;
this._loginChangedDispatcher.fire({});
this._loginChangedDispatcher.fire({ detail: this._state });
}

@@ -232,3 +264,3 @@ }

public setActiveAccount?(user: IProviderAccount) {
this.fireActiveAccountChanged();
this.fireActiveAccountChanged({ detail: user });
}

@@ -261,4 +293,4 @@

*/
private fireActiveAccountChanged() {
this._activeAccountChangedDispatcher.fire({});
private fireActiveAccountChanged(account: { detail: IProviderAccount }) {
this._activeAccountChangedDispatcher.fire(account);
}

@@ -295,3 +327,5 @@

// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface ActiveAccountChanged {}
export interface ActiveAccountChanged {
detail: IProviderAccount;
}
/**

@@ -304,3 +338,5 @@ * loginChangedEvent

// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface LoginChangedEvent {}
export interface LoginChangedEvent {
detail: ProviderState;
}

@@ -307,0 +343,0 @@ /**

@@ -10,4 +10,4 @@ /**

import { BatchRequestContent, MiddlewareOptions } from '@microsoft/microsoft-graph-client';
import { delay } from '../utils';
import { prepScopes } from './GraphHelpers';
import { delay } from './delay';
import { prepScopes } from './prepScopes';
import { IGraph } from '../IGraph';

@@ -62,3 +62,5 @@ import { BatchRequest } from './BatchRequest';

* @param {string} resource
* @param {string[]} [scopes]
* @param {string[]} [scopes] any additional scopes that should be requested
* Note: use `IProvider.needsAdditionalScopes(scopes)` to calculate which
* scopes, if any, need to be requested before calling `Batch.get()`
* @memberof Batch

@@ -111,3 +113,3 @@ */

const middlewareOptions: MiddlewareOptions[] = this.scopes.length ? prepScopes(...this.scopes) : [];
const middlewareOptions: MiddlewareOptions[] = this.scopes.length ? prepScopes(this.scopes) : [];
const batchRequest = this.graph.api('$batch').middlewareOptions(middlewareOptions);

@@ -114,0 +116,0 @@

@@ -11,2 +11,3 @@ /**

import { CacheStore } from './CacheStore';
import { error } from './Logging';

@@ -19,2 +20,3 @@ /**

*/
export const dbListKey = 'mgt-db-list';

@@ -102,2 +104,9 @@

fileLists: CacheOptions;
/**
* Cache options for conversation store
*
* @type {CacheOptions}
* @memberof CacheConfig
*/
conversation: CacheOptions;
}

@@ -177,3 +186,3 @@

delReq.onerror = () => {
console.error(`🦒: ${delReq.error.name} occurred deleting cache: ${x}`, delReq.error.message);
error(`${delReq.error.name} occurred deleting cache: ${x}`, delReq.error.message);
reject();

@@ -233,2 +242,6 @@ };

isEnabled: true
},
conversation: {
invalidationPeriod: 5 * 24 * 60 * 60 * 1000,
isEnabled: true
}

@@ -277,2 +290,7 @@ };

export interface Index {
name: string;
field: string;
}
/**

@@ -306,2 +324,8 @@ * Represents organization for a cache

stores: Record<string, string>;
/**
* Optional field to define indexed fields on a per store basis
* K is the name of the store for which the indexes should be applied
* T is the names of the fields on the stored data to be indexed
*/
indexes?: Record<string, Index[]>;
}

@@ -308,0 +332,0 @@

@@ -8,5 +8,5 @@ /**

import { openDB } from 'idb';
import { IDBPObjectStore, openDB } from 'idb';
import { Providers } from '../providers/Providers';
import { CacheItem, CacheSchema, dbListKey } from './CacheService';
import { CacheItem, CacheSchema, Index, dbListKey } from './CacheService';

@@ -40,3 +40,3 @@ /**

*/
public async getValue(key: string): Promise<T> {
public async getValue(key: string): Promise<T | null> {
if (!window.indexedDB) {

@@ -54,2 +54,21 @@ return null;

/**
* removes a value from the cache for the given key
*
* @param {string} key
* @returns {Promise<void>}
* @memberof Cache
*/
public async delete(key: string): Promise<void> {
if (!window.indexedDB) {
return;
}
try {
const db = await this.getDb();
return db.delete(this.store, key);
} catch (e) {
return;
}
}
/**
* inserts value into cache for the given key

@@ -105,3 +124,3 @@ *

// eslint-disable-next-line @typescript-eslint/no-unused-vars
upgrade: (db, _oldVersion, _newVersion, _transaction) => {
upgrade: (db, _oldVersion, _newVersion, transaction) => {
const dbArray: string[] = (JSON.parse(localStorage.getItem(dbListKey)) as string[]) || [];

@@ -113,7 +132,17 @@ if (!dbArray.includes(dbName)) {

for (const storeName in this.schema.stores) {
if (
Object.prototype.hasOwnProperty.call(this.schema.stores, storeName) &&
!db.objectStoreNames.contains(storeName)
) {
db.createObjectStore(storeName);
if (Object.prototype.hasOwnProperty.call(this.schema.stores, storeName)) {
const indexes: Index[] = this.schema.indexes?.[storeName] ?? [];
if (!db.objectStoreNames.contains(storeName)) {
const objectStore = db.createObjectStore(storeName);
indexes.forEach(i => {
objectStore.createIndex(i.name, i.field);
});
} else {
const store = transaction.objectStore(storeName);
indexes.forEach(i => {
if (store && !store.indexNames.contains(i.name)) {
store.createIndex(i.name, i.field);
}
});
}
}

@@ -125,2 +154,19 @@ }

}
public async queryDb(indexName: string, query: IDBKeyRange | IDBValidKey): Promise<T[]> {
const db = await this.getDb();
return (await db.getAllFromIndex(this.store, indexName, query)) as T[];
}
/**
* Helper function to get a wrapping transaction for an action function
* @param action a function that takes an object store uses it to make changes to the cache
*/
public async transaction(action: (store: IDBPObjectStore<unknown, [string], string, 'readwrite'>) => Promise<void>) {
const db = await this.getDb();
const tx = db.transaction(this.store, 'readwrite');
const store = tx.objectStore(this.store);
await action(store);
await tx.done;
}
}

@@ -10,2 +10,3 @@ /**

import { customElementHelper } from '../components/customElementHelper';
import { error } from './Logging';

@@ -29,5 +30,4 @@ /**

return (classOrDescriptor: CustomElementConstructor) => {
// eslint-disable-next-line no-console
console.error(
`🦒: Tag name ${mgtTagName} is already defined using class ${mgtElement.name} version ${version(mgtElement)}\n`,
error(
`Tag name ${mgtTagName} is already defined using class ${mgtElement.name} version ${version(mgtElement)}\n`,
`Currently registering class ${classOrDescriptor.name} with version ${version(classOrDescriptor)}\n`,

@@ -34,0 +34,0 @@ 'Please use the disambiguation feature to define a unique tag name for this component see: https://github.com/microsoftgraph/microsoft-graph-toolkit/tree/main/packages/mgt-components#disambiguation'

@@ -8,3 +8,10 @@ /**

import { it } from '@jest/globals';
/* eslint-disable @typescript-eslint/no-unused-expressions */
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { expect } from '@open-wc/testing';
import { equals } from './equals';

@@ -22,34 +29,40 @@

it.each([
[{}, {}],
[
{ a: 1, b: true, c: 'foo' },
{ c: 'foo', b: true, a: 1 }
],
[{ a: [1, 2, 3] }, { a: [1, 2, 3] }],
[{ a: { b: { c: 1 } } }, { a: { b: { c: 1 } } }],
[{ a: [1, [2, [3]]] }, { a: [1, [2, [3]]] }],
[circularObject, circularObject],
[circularObject, { a: circularObject }],
[circularArray, circularArray],
[
{ a: circularObject, b: circularArray },
{ a: circularObject, b: circularArray }
],
[{ a: simpleDate }, { a: simpleDate }]
])('should return true between %p and %p', (o1: unknown, o2: unknown) => {
expect(equals(o1, o2)).toBe(true);
it('should return true', () => {
const testValues = [
[{}, {}],
[
{ a: 1, b: true, c: 'foo' },
{ c: 'foo', b: true, a: 1 }
],
[{ a: [1, 2, 3] }, { a: [1, 2, 3] }],
[{ a: { b: { c: 1 } } }, { a: { b: { c: 1 } } }],
[{ a: [1, [2, [3]]] }, { a: [1, [2, [3]]] }],
[circularObject, circularObject],
[circularObject, { a: circularObject }],
[circularArray, circularArray],
[
{ a: circularObject, b: circularArray },
{ a: circularObject, b: circularArray }
],
[{ a: simpleDate }, { a: simpleDate }]
];
for (const [o1, o2] of testValues) {
expect(equals(o1, o2)).to.be.true;
}
});
it.each([
[{ a: {} }, { a: [] }],
[{ a: [1, 2, 3] }, { a: [3, 2, 1] }],
[{ a: [1, [2, [3]]] }, { a: [1, [2, [4]]] }],
[{ a: { b: [{ c: 1 }, { d: [2, 3] }] } }, { a: { b: [{ c: 1 }, { d: [3, 2] }] } }],
[{ a: new Date() }, { a: new Date() }],
[circularObject, circularArray],
[circularObject, { b: circularObject }]
])('should return false between %p and %p', (o1: unknown, o2: unknown) => {
expect(equals(o1, o2)).toBe(false);
it('should return false ', () => {
const testValues = [
[{ a: {} }, { a: [] }],
[{ a: [1, 2, 3] }, { a: [3, 2, 1] }],
[{ a: [1, [2, [3]]] }, { a: [1, [2, [4]]] }],
[{ a: { b: [{ c: 1 }, { d: [2, 3] }] } }, { a: { b: [{ c: 1 }, { d: [3, 2] }] } }],
[{ a: new Date() }, { a: new Date() }],
[circularObject, circularArray],
[circularObject, { b: circularObject }]
];
for (const [o1, o2] of testValues) {
expect(equals(o1, o2)).to.be.false;
}
});
});

@@ -8,31 +8,36 @@ /**

import { it } from '@jest/globals';
import { assert } from 'console';
import { EventDispatcher } from './EventDispatcher';
import { assert, restore, fake } from 'sinon';
describe('EventDispatcher tests', () => {
afterEach(() => {
// Restore the default sandbox here
restore();
});
it('should add and remove event handlers', () => {
const dispatcher = new EventDispatcher();
const handler1 = jest.fn();
const handler2 = jest.fn();
const handler1 = fake();
const handler2 = fake();
dispatcher.add(handler1);
dispatcher.add(handler2);
dispatcher.fire('event');
expect(handler1).toHaveBeenCalledTimes(1);
expect(handler2).toHaveBeenCalledTimes(1);
assert.calledOnce(handler1);
assert.calledOnce(handler2);
dispatcher.remove(handler1);
dispatcher.fire('event');
expect(handler1).toHaveBeenCalledTimes(1);
expect(handler2).toHaveBeenCalledTimes(2);
assert.calledOnce(handler1);
assert.callCount(handler2, 2);
});
it('should not throw when remove is called with an unregistered handler', () => {
try {
const dispatcher = new EventDispatcher();
const handler1 = jest.fn();
const handler1 = fake();
dispatcher.remove(handler1);
} catch (e) {
assert(false, 'should not throw');
assert.fail('should not throw');
}
assert(true, 'did not throw');
assert.pass('did not throw');
});
});

@@ -8,20 +8,32 @@ /**

import { it } from '@jest/globals';
/* eslint-disable @typescript-eslint/no-unused-expressions */
/**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { expect } from '@open-wc/testing';
import { fake } from 'sinon';
import { AuthenticationHandlerOptions, Middleware } from '@microsoft/microsoft-graph-client';
import { MockProvider } from '../mock/MockProvider';
import { Providers } from '../providers/Providers';
import { chainMiddleware, prepScopes, validateBaseURL } from './GraphHelpers';
import { chainMiddleware } from './chainMiddleware';
import { prepScopes } from './prepScopes';
import { validateBaseURL } from './validateBaseURL';
describe('GraphHelpers - prepScopes', () => {
it('should return an empty array when incremental consent is disabled', () => {
it('should return an empty array when incremental consent is disabled', async () => {
const scopes = ['scope1', 'scope2'];
Providers.globalProvider = new MockProvider(true);
Providers.globalProvider.isIncrementalConsentDisabled = true;
expect(prepScopes(...scopes)).toEqual([]);
// eql for loose equality
await expect(prepScopes(scopes)).to.eql([]);
});
it('should return an array of AuthenticationHandlerOptions when incremental consent is enabled', () => {
it('should return an array of AuthenticationHandlerOptions when incremental consent is enabled with only the first scope in the list', async () => {
const scopes = ['scope1', 'scope2'];
Providers.globalProvider = new MockProvider(true);
Providers.globalProvider.isIncrementalConsentDisabled = false;
expect(prepScopes(...scopes)).toEqual([new AuthenticationHandlerOptions(undefined, { scopes })]);
await expect(prepScopes(scopes)).to.eql([new AuthenticationHandlerOptions(undefined, { scopes: ['scope1'] })]);
});

@@ -31,6 +43,6 @@ });

describe('GraphHelpers - chainMiddleware', () => {
it('should return the first middleware when only one is passed', () => {
const middleware: Middleware[] = [{ execute: jest.fn(), setNext: jest.fn() }];
it('should return the first middleware when only one is passed', async () => {
const middleware: Middleware[] = [{ execute: fake(), setNext: fake() }];
const result = chainMiddleware(...middleware);
expect(result).toEqual(middleware[0]);
await expect(result).to.equal(middleware[0]);
});

@@ -41,3 +53,3 @@

const result = chainMiddleware(...middleware);
expect(result).toBeUndefined();
expect(result).to.be.undefined;
});

@@ -48,7 +60,7 @@ it('should now throw when the middleware array is undefined', () => {

const result = chainMiddleware(undefined);
expect(result).toBeUndefined();
expect(result).to.be.undefined;
} catch (e) {
error = 'thrown and caught';
}
expect(error).toBeUndefined();
expect(error).to.be.undefined;
});

@@ -58,23 +70,27 @@ });

describe('GraphHelpers - validateBaseUrl', () => {
it.each([
'https://graph.microsoft.com',
'https://graph.microsoft.us',
'https://dod-graph.microsoft.us',
'https://graph.microsoft.de',
'https://microsoftgraph.chinacloudapi.cn'
])('should return %p as a valid base url', (graphUrl: string) => {
expect(validateBaseURL(graphUrl)).toBe(graphUrl);
it('should return as a valid Url', async () => {
const validUrls = [
'https://graph.microsoft.com',
'https://graph.microsoft.us',
'https://dod-graph.microsoft.us',
'https://graph.microsoft.de',
'https://microsoftgraph.chinacloudapi.cn'
];
for (const url of validUrls) {
await expect(validateBaseURL(url)).to.equal(url);
}
});
it.each(['https://graph.microsoft.net', 'https://random.us', 'https://nope.cn'])(
'should return undefined for %p as an invalid base url',
(graphUrl: string) => {
expect(validateBaseURL(graphUrl)).toBeUndefined();
it('should return undefeined for invalid Url', () => {
const validUrls = ['https://graph.microsoft.net', 'https://random.us', 'https://nope.cn'];
for (const url of validUrls) {
expect(validateBaseURL(url)).to.be.undefined;
}
);
it.each(['not a url', 'graph.microsoft.com'])(
'should return undefined for when supplied a %p which is not a well formed url',
(input: string) => {
expect(validateBaseURL(input)).toBeUndefined();
});
it('should return undefined for when supplied a %p which is not a well formed url', () => {
const testValues = ['not a url', 'graph.microsoft.com'];
for (const test of testValues) {
expect(validateBaseURL(test)).to.be.undefined;
}
);
});
});

@@ -15,3 +15,3 @@ /**

_components: LocalizationRecord;
} & Record<string, string>;
} & Record<string, string | LocalizationRecord>;

@@ -18,0 +18,0 @@ /**

@@ -14,3 +14,3 @@ /**

import { ComponentMiddlewareOptions } from './ComponentMiddlewareOptions';
import { validateBaseURL } from './GraphHelpers';
import { validateBaseURL } from './validateBaseURL';

@@ -17,0 +17,0 @@ /**

@@ -11,2 +11,2 @@ /**

export const PACKAGE_VERSION = '3.1.3';
export const PACKAGE_VERSION = '4.0.0-next.mgt-chat.eeea1d6';

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc