From 6e388cea3ab66228079d77ac0d67d5e2ee3097c7 Mon Sep 17 00:00:00 2001 From: Joel Mut <62260472+sw-joelmut@users.noreply.github.com> Date: Mon, 6 Jan 2025 11:59:48 -0300 Subject: [PATCH 01/22] fix: [#4684] ESLint issues in botbuilder-dialogs-adaptive-testing (#4821) * Fix ESLint issues with --fix flag * Fix ESLint issues --- .../eslint.config.cjs | 10 ------- .../package.json | 3 +- .../src/actions/assertCondition.ts | 1 - .../src/adaptiveTestBotComponent.ts | 2 +- .../src/httpRequestMocks/httpResponseMock.ts | 29 +++++++++++++++---- .../src/mocks/mockHttpRequestMiddleware.ts | 2 +- .../src/mocks/mockLuisExtensions.ts | 2 +- .../src/mocks/mockLuisLoader.ts | 7 +++-- .../src/mocks/mockLuisRecognizer.ts | 4 +-- .../src/testAction.ts | 2 +- .../src/testActions/assertNoActivity.ts | 2 +- .../src/testActions/assertReply.ts | 4 +-- .../src/testActions/assertReplyActivity.ts | 4 +-- .../src/testActions/assertReplyOneOf.ts | 2 +- .../testActions/assertTelemetryContains.ts | 2 +- .../src/testActions/customEvent.ts | 2 +- .../src/testActions/memoryAssertions.ts | 2 +- .../src/testActions/setProperties.ts | 2 +- .../src/testActions/userActivity.ts | 2 +- .../src/testActions/userConversationUpdate.ts | 2 +- .../src/testActions/userDelay.ts | 2 +- .../src/testActions/userSays.ts | 2 +- .../src/testActions/userTyping.ts | 2 +- .../src/testScript.ts | 2 +- .../tests/action.test.js | 9 +++--- .../tests/actionScope.test.js | 1 + .../tests/adaptiveDialog.test.js | 3 +- .../tests/conditionals.test.js | 3 +- .../tests/crossTrainedRecognizerSet.test.js | 3 +- .../tests/functions.test.js | 1 + .../tests/injectLG.test.js | 1 + .../tests/lgGenerators.test.js | 1 + .../tests/misc.test.js | 1 + .../tests/multiLanguageGeneratorTests.test.js | 1 + .../tests/multiLanguageRecognizer.test.js | 3 +- .../tests/qnaMakerRecognizer.test.js | 5 ++-- .../tests/recognizerSet.test.js | 5 ++-- .../tests/recognizerTelemetryUtils.js | 2 +- .../tests/regexRecognizer.test.js | 1 + .../tests/selector.test.js | 3 +- .../tests/settingsState.test.js | 1 + .../tests/testScript.test.js | 5 ++-- .../tests/valueRecognizer.test.js | 1 + 43 files changed, 86 insertions(+), 58 deletions(-) delete mode 100644 libraries/botbuilder-dialogs-adaptive-testing/eslint.config.cjs diff --git a/libraries/botbuilder-dialogs-adaptive-testing/eslint.config.cjs b/libraries/botbuilder-dialogs-adaptive-testing/eslint.config.cjs deleted file mode 100644 index 63647b52cc..0000000000 --- a/libraries/botbuilder-dialogs-adaptive-testing/eslint.config.cjs +++ /dev/null @@ -1,10 +0,0 @@ -const onlyWarn = require("eslint-plugin-only-warn"); -const sharedConfig = require("../../eslint.config.cjs") - -module.exports = [ - ...sharedConfig, - { - plugins: { - "only-warn": onlyWarn, - }, - }]; diff --git a/libraries/botbuilder-dialogs-adaptive-testing/package.json b/libraries/botbuilder-dialogs-adaptive-testing/package.json index c152be89b8..5895e15204 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/package.json +++ b/libraries/botbuilder-dialogs-adaptive-testing/package.json @@ -7,7 +7,7 @@ "build": "tsc -b", "clean": "rimraf _ts3.4 lib tsconfig.tsbuildinfo", "depcheck": "depcheck --config ../../.depcheckrc", - "lint": "eslint .", + "lint": "eslint . --config ../../eslint.config.cjs", "postbuild": "downlevel-dts lib _ts3.4/lib --checksum", "test": "npm-run-all build test:mocha", "test:mocha": "mocha tests/*.test.js", @@ -32,7 +32,6 @@ "botbuilder-dialogs-adaptive-runtime-core": "4.1.6", "botbuilder-dialogs-declarative": "4.1.6", "botbuilder-stdlib": "4.1.6", - "eslint-plugin-only-warn": "^1.1.0", "murmurhash-js": "^1.0.0", "nock": "^13.5.5", "url-parse": "^1.5.10", diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/actions/assertCondition.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/actions/assertCondition.ts index a8b3acd773..4b44b2d734 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/actions/assertCondition.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/actions/assertCondition.ts @@ -42,7 +42,6 @@ export class AssertCondition extends Dialog implements * * @param property Properties that extend RecognizerConfiguration. * @returns Expression converter. - * */ getConverter(property: keyof AssertConditionConfiguration): Converter | ConverterFactory { switch (property) { diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/adaptiveTestBotComponent.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/adaptiveTestBotComponent.ts index 7eddf59a77..ee92efc65c 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/adaptiveTestBotComponent.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/adaptiveTestBotComponent.ts @@ -61,7 +61,7 @@ export class AdaptiveTestBotComponent extends BotComponent { { kind: AssertTelemetryContains.$kind, type: AssertTelemetryContains }, ]; }, - }) + }), ); } } diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/httpRequestMocks/httpResponseMock.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/httpRequestMocks/httpResponseMock.ts index 647d2fc411..91d58c3a18 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/httpRequestMocks/httpResponseMock.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/httpRequestMocks/httpResponseMock.ts @@ -27,18 +27,13 @@ export enum ResponseStatusCode { NoContent = 204, ResetContent = 205, PartialContent = 206, - Ambiguous = 300, MultipleChoices = 300, - Moved = 301, MovedPermanently = 301, Found = 302, - Redirect = 302, - RedirectMethod = 303, SeeOther = 303, NotModified = 304, UseProxy = 305, Unused = 306, - RedirectKeepVerb = 307, TemporaryRedirect = 307, BadRequest = 400, Unauthorized = 401, @@ -65,6 +60,30 @@ export enum ResponseStatusCode { ServiceUnavailable = 503, GatewayTimeout = 504, HttpVersionNotSupported = 505, + + // Synonyms + /* eslint-disable @typescript-eslint/no-duplicate-enum-values */ + /** + * Synonym for MultipleChoices. + */ + Ambiguous = 300, + /** + * Synonym for MovedPermanently. + */ + Moved = 301, + /** + * Synonym for Found. + */ + Redirect = 302, + /** + * Synonym for SeeOther. + */ + RedirectMethod = 303, + /** + * Synonym for TemporaryRedirect. + */ + RedirectKeepVerb = 307, + /* eslint-enable @typescript-eslint/no-duplicate-enum-values */ } /** diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/mocks/mockHttpRequestMiddleware.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/mocks/mockHttpRequestMiddleware.ts index 3c44cbd4a4..f029948b03 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/mocks/mockHttpRequestMiddleware.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/mocks/mockHttpRequestMiddleware.ts @@ -71,7 +71,7 @@ export class MockHttpRequestMiddleware implements Middleware { const origins = new Set( this._httpRequestMocks .filter((mock) => mock instanceof HttpRequestSequenceMock) - .map((mock: HttpRequestSequenceMock) => parse(mock.url).origin) + .map((mock: HttpRequestSequenceMock) => parse(mock.url).origin), ); // call fallback functions if mocks not catched diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/mocks/mockLuisExtensions.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/mocks/mockLuisExtensions.ts index 3422b7cf5e..f6fbd49b3d 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/mocks/mockLuisExtensions.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/mocks/mockLuisExtensions.ts @@ -52,7 +52,7 @@ function flattenSettings(settings: Record): Record */ export function useMockLuisSettings( directory: string, - endpoint = 'https://westus.api.cognitive.microsoft.com' + endpoint = 'https://westus.api.cognitive.microsoft.com', ): Record { const files = fs.readdirSync(directory); const settings = files diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/mocks/mockLuisLoader.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/mocks/mockLuisLoader.ts index 3b9cb9d65f..5da35127b3 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/mocks/mockLuisLoader.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/mocks/mockLuisLoader.ts @@ -24,7 +24,10 @@ export class MockLuisLoader implements CustomDeserializer} _configuration Configuration to use. */ - constructor(private _resourceExplorer: ResourceExplorer, private _configuration?: Record) {} + constructor( + private _resourceExplorer: ResourceExplorer, + private _configuration?: Record, + ) {} /** * @param config Config to recognize intents and entities in a users utterance. @@ -36,7 +39,7 @@ export class MockLuisLoader implements CustomDeserializer( - `${externalEntityRecognizer}.dialog` + `${externalEntityRecognizer}.dialog`, ); } let name = recognizer.applicationId.toString(); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/mocks/mockLuisRecognizer.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/mocks/mockLuisRecognizer.ts index b2b240f517..b7813d8b44 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/mocks/mockLuisRecognizer.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/mocks/mockLuisRecognizer.ts @@ -85,7 +85,7 @@ export class MockLuisRecognizer extends Recognizer { dialogContext: DialogContext, activity: Activity, telemetryProperties?: Record, - telemetryMetrics?: Record + telemetryMetrics?: Record, ): Promise { const options = this._recognizer.recognizerOptions(dialogContext); options.includeAPIResults = true; @@ -164,7 +164,7 @@ export class MockLuisRecognizer extends Recognizer { private async _fallback( _request: HttpRequestMessage, utterance: string, - options: LuisRecognizerOptionsV3 + options: LuisRecognizerOptionsV3, ): Promise { const responsePath: string = this._responsePath(utterance, options); if (fs.existsSync(responsePath)) { diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/testAction.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/testAction.ts index e179bd15a8..b00c836e21 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/testAction.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/testAction.ts @@ -22,6 +22,6 @@ export abstract class TestAction extends Configurable { abstract execute( adapter: TestAdapter, callback: (context: TurnContext) => Promise, - inspector?: Inspector + inspector?: Inspector, ): void; } diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/assertNoActivity.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/assertNoActivity.ts index b8f8f23844..0496c6b0d1 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/assertNoActivity.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/assertNoActivity.ts @@ -43,7 +43,7 @@ export class AssertNoActivity extends TestAction implements AssertNoActivityConf async execute( adapter: TestAdapter, _callback: (context: TurnContext) => Promise, - _inspector?: Inspector + _inspector?: Inspector, ): Promise { if (adapter.activeQueue.length > 0) { throw new Error(this.getConditionDescription()); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/assertReply.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/assertReply.ts index de8a2c6bcd..1fe31a32cd 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/assertReply.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/assertReply.ts @@ -49,7 +49,7 @@ export class AssertReply extends AssertReplyActivity implements AssertReplyConfi if (this.exact) { if (activity.type == ActivityTypes.Message && activity.text != this.text) { throw new Error( - this.description || `Text ${activity.text} didn't match expected text: ${this.text}` + this.description || `Text ${activity.text} didn't match expected text: ${this.text}`, ); } } else { @@ -58,7 +58,7 @@ export class AssertReply extends AssertReplyActivity implements AssertReplyConfi !activity.text.toLowerCase().trim().includes(this.text.toLowerCase().trim()) ) { throw new Error( - this.description || `Text ${activity.text} didn't match expected text: ${this.text}` + this.description || `Text ${activity.text} didn't match expected text: ${this.text}`, ); } } diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/assertReplyActivity.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/assertReplyActivity.ts index 0b3ef33b47..4c695beee5 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/assertReplyActivity.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/assertReplyActivity.ts @@ -75,10 +75,10 @@ export class AssertReplyActivity extends TestAction implements AssertReplyActivi async execute( testAdapter: TestAdapter, _callback: (context: TurnContext) => Promise, - _inspector?: Inspector + _inspector?: Inspector, ): Promise { const start = new Date(); - /* eslint-disable no-constant-condition */ + while (true) { const current = new Date(); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/assertReplyOneOf.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/assertReplyOneOf.ts index fcb0fd4c1a..acebe1c66b 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/assertReplyOneOf.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/assertReplyOneOf.ts @@ -67,7 +67,7 @@ export class AssertReplyOneOf extends AssertReplyActivity implements AssertReply if (!found) { throw new Error( - this.description || `Text ${activity.text} didn't match one of expected text: ${this.text.join('\n')}` + this.description || `Text ${activity.text} didn't match one of expected text: ${this.text.join('\n')}`, ); } diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/assertTelemetryContains.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/assertTelemetryContains.ts index a301b39a67..099f399a3b 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/assertTelemetryContains.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/assertTelemetryContains.ts @@ -42,7 +42,7 @@ export class AssertTelemetryContains extends TestAction implements AssertTelemet async execute( _adapter: TestAdapter, _callback: (context: TurnContext) => Promise, - inspector?: Inspector + inspector?: Inspector, ): Promise { if (inspector) { await inspector((dc) => { diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/customEvent.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/customEvent.ts index ab6dff462f..ce735e53e4 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/customEvent.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/customEvent.ts @@ -40,7 +40,7 @@ export class CustomEvent extends TestAction implements CustomEventC async execute( testAdapter: TestAdapter, callback: (context: TurnContext) => Promise, - _inspector?: Inspector + _inspector?: Inspector, ): Promise { if (!this.name) { throw Error('You must define the event name.'); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/memoryAssertions.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/memoryAssertions.ts index 529b370cd0..c4cb3b85bd 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/memoryAssertions.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/memoryAssertions.ts @@ -42,7 +42,7 @@ export class MemoryAssertions extends TestAction implements MemoryAssertionsConf async execute( _adapter: TestAdapter, _callback: (context: TurnContext) => Promise, - inspector?: Inspector + inspector?: Inspector, ): Promise { if (inspector) { await inspector((dc) => { diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/setProperties.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/setProperties.ts index e734b3f4dc..c5dcffe661 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/setProperties.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/setProperties.ts @@ -70,7 +70,7 @@ export class SetProperties extends TestAction { async execute( _adapter: TestAdapter, _callback: (context: TurnContext) => Promise, - inspector?: Inspector + inspector?: Inspector, ): Promise { if (inspector) { await inspector((dc) => { diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/userActivity.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/userActivity.ts index 03ec7a83e5..e3ebed3469 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/userActivity.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/userActivity.ts @@ -42,7 +42,7 @@ export class UserActivity extends TestAction implements UserActivityConfiguratio async execute( testAdapter: TestAdapter, callback: (context: TurnContext) => Promise, - _inspector?: Inspector + _inspector?: Inspector, ): Promise { if (!this.activity) { throw new Error('You must define one of Text of Activity properties'); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/userConversationUpdate.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/userConversationUpdate.ts index 68125123be..97da44bb5f 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/userConversationUpdate.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/userConversationUpdate.ts @@ -41,7 +41,7 @@ export class UserConversationUpdate extends TestAction implements UserConversati async execute( testAdapter: TestAdapter, callback: (context: TurnContext) => Promise, - _inspector?: Inspector + _inspector?: Inspector, ): Promise { const activity = testAdapter.makeActivity(); activity.type = ActivityTypes.ConversationUpdate; diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/userDelay.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/userDelay.ts index 6a16047afc..fb46dd7c68 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/userDelay.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/userDelay.ts @@ -35,7 +35,7 @@ export class UserDelay extends TestAction implements UserDelayConfiguration { async execute( _testAdapter: TestAdapter, _callback: (context: TurnContext) => Promise, - _inspector?: Inspector + _inspector?: Inspector, ): Promise { await Promise.resolve((resolve) => setTimeout(resolve, this.timespan)); } diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/userSays.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/userSays.ts index 3ffebcd254..a9c085feb4 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/userSays.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/userSays.ts @@ -46,7 +46,7 @@ export class UserSays extends TestAction implements UserSaysConfiguration { async execute( testAdapter: TestAdapter, callback: (context: TurnContext) => Promise, - _inspector?: Inspector + _inspector?: Inspector, ): Promise { if (!this.text) { throw new Error('You must define the text property'); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/userTyping.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/userTyping.ts index 16d6927afa..bb5172dfbd 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/userTyping.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/testActions/userTyping.ts @@ -36,7 +36,7 @@ export class UserTyping extends Configurable implements TestAction, UserTypingCo async execute( testAdapter: TestAdapter, callback: (context: TurnContext) => Promise, - _inspector?: Inspector + _inspector?: Inspector, ): Promise { const typing = testAdapter.makeActivity(); typing.type = ActivityTypes.Typing; diff --git a/libraries/botbuilder-dialogs-adaptive-testing/src/testScript.ts b/libraries/botbuilder-dialogs-adaptive-testing/src/testScript.ts index 8810dad51b..cf53372cbc 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/src/testScript.ts +++ b/libraries/botbuilder-dialogs-adaptive-testing/src/testScript.ts @@ -218,7 +218,7 @@ export class TestScript extends Configurable implements TestScriptConfiguration const activity = TurnContext.applyConversationReference( { name: 'inspector', type: ActivityTypes.Event }, adapter.conversation, - true + true, ); await adapter.processActivity(activity, async (turnContext) => await di.inspect(turnContext, inspector)); }; diff --git a/libraries/botbuilder-dialogs-adaptive-testing/tests/action.test.js b/libraries/botbuilder-dialogs-adaptive-testing/tests/action.test.js index a89ce8c7b1..5fb1a49151 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/tests/action.test.js +++ b/libraries/botbuilder-dialogs-adaptive-testing/tests/action.test.js @@ -123,6 +123,7 @@ class SetSkillBotFrameworkClientMiddleware { describe('ActionTests', function () { let resourceExplorer; + before(function () { resourceExplorer = makeResourceExplorer('ActionTests', LanguageGenerationBotComponent); }); @@ -158,7 +159,7 @@ describe('ActionTests', function () { undefined, undefined, new SetSkillConversationIdFactoryBaseMiddleware(), - new SetSkillBotFrameworkClientMiddleware() + new SetSkillBotFrameworkClientMiddleware(), ); }); @@ -214,7 +215,7 @@ describe('ActionTests', function () { undefined, undefined, new SetSkillConversationIdFactoryBaseMiddleware(), - new SetSkillBotFrameworkClientMiddleware() + new SetSkillBotFrameworkClientMiddleware(), ); }); @@ -400,8 +401,8 @@ describe('ActionTests', function () { Object.assign({}, [ { text: 'Joe is 52', age: 52 }, { text: 'text', age: 11 }, - ]) - ) + ]), + ), ) .reply(200, 'array'); nock('http://foo.com') diff --git a/libraries/botbuilder-dialogs-adaptive-testing/tests/actionScope.test.js b/libraries/botbuilder-dialogs-adaptive-testing/tests/actionScope.test.js index f2ff2ae421..98b20760b5 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/tests/actionScope.test.js +++ b/libraries/botbuilder-dialogs-adaptive-testing/tests/actionScope.test.js @@ -3,6 +3,7 @@ const { makeResourceExplorer } = require('./utils'); describe('ActionScopeTests', function () { let resourceExplorer; + before(function () { resourceExplorer = makeResourceExplorer('ActionScopeTests'); }); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/tests/adaptiveDialog.test.js b/libraries/botbuilder-dialogs-adaptive-testing/tests/adaptiveDialog.test.js index bba70f36c1..d1f28050c5 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/tests/adaptiveDialog.test.js +++ b/libraries/botbuilder-dialogs-adaptive-testing/tests/adaptiveDialog.test.js @@ -3,6 +3,7 @@ const { makeResourceExplorer } = require('./utils'); describe('AdaptiveDialogTests', function () { let resourceExplorer; + before(function () { resourceExplorer = makeResourceExplorer('AdaptiveDialogTests'); }); @@ -103,7 +104,7 @@ describe('AdaptiveDialogTests', function () { await TestUtils.runTestScript(resourceExplorer, 'AdaptiveDialog_NestedRecognizers'); }); - it('PropertySetInInterruption', async function () { + it('PropertyBotInterruption', async function () { await TestUtils.runTestScript(resourceExplorer, 'AdaptiveDialog_ParentBotInterruption'); }); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/tests/conditionals.test.js b/libraries/botbuilder-dialogs-adaptive-testing/tests/conditionals.test.js index 9d5bcdd9c0..a206d8c5d7 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/tests/conditionals.test.js +++ b/libraries/botbuilder-dialogs-adaptive-testing/tests/conditionals.test.js @@ -5,6 +5,7 @@ const { LuisAdaptiveRecognizer, LuisBotComponent } = require('botbuilder-ai'); describe('ConditionalsTests', function () { let resourceExplorer; + before(function () { resourceExplorer = makeResourceExplorer('ConditionalsTests'); }); @@ -24,7 +25,7 @@ describe('ConditionalsTests', function () { resourceExplorer.registerType( LuisAdaptiveRecognizer.$kind, MockLuisRecognizer, - new MockLuisLoader(resourceExplorer, config) + new MockLuisLoader(resourceExplorer, config), ); await TestUtils.runTestScript(resourceExplorer, 'ChooseEntity', undefined, config); }); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/tests/crossTrainedRecognizerSet.test.js b/libraries/botbuilder-dialogs-adaptive-testing/tests/crossTrainedRecognizerSet.test.js index f6bce77b81..eab2a9f46e 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/tests/crossTrainedRecognizerSet.test.js +++ b/libraries/botbuilder-dialogs-adaptive-testing/tests/crossTrainedRecognizerSet.test.js @@ -49,12 +49,13 @@ const getDialogContext = (testName, text, locale = 'en-us') => { from: bot, locale, }), - {} + {}, ); }; describe('CrossTrainedRecognizerSetTests', function () { let resourceExplorer; + before(function () { resourceExplorer = makeResourceExplorer('CrossTrainedRecognizerSetTests'); }); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/tests/functions.test.js b/libraries/botbuilder-dialogs-adaptive-testing/tests/functions.test.js index e118b12323..28cb578a94 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/tests/functions.test.js +++ b/libraries/botbuilder-dialogs-adaptive-testing/tests/functions.test.js @@ -3,6 +3,7 @@ const { makeResourceExplorer } = require('./utils'); describe('ActionScopeTests', function () { let resourceExplorer; + before(function () { resourceExplorer = makeResourceExplorer('FunctionsTests'); }); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/tests/injectLG.test.js b/libraries/botbuilder-dialogs-adaptive-testing/tests/injectLG.test.js index 96fc120bb2..94c6e2652e 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/tests/injectLG.test.js +++ b/libraries/botbuilder-dialogs-adaptive-testing/tests/injectLG.test.js @@ -3,6 +3,7 @@ const { makeResourceExplorer } = require('./utils'); describe('ActionScopeTests', function () { let resourceExplorer; + before(function () { resourceExplorer = makeResourceExplorer('InjectLGTests'); }); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/tests/lgGenerators.test.js b/libraries/botbuilder-dialogs-adaptive-testing/tests/lgGenerators.test.js index 0ed48c726b..45743cbd8a 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/tests/lgGenerators.test.js +++ b/libraries/botbuilder-dialogs-adaptive-testing/tests/lgGenerators.test.js @@ -3,6 +3,7 @@ const { makeResourceExplorer } = require('./utils'); describe('LGGeneratorTests', function () { let resourceExplorer; + before(function () { resourceExplorer = makeResourceExplorer('LGGeneratorTests'); }); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/tests/misc.test.js b/libraries/botbuilder-dialogs-adaptive-testing/tests/misc.test.js index 759d3365f3..ad47cc2ba9 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/tests/misc.test.js +++ b/libraries/botbuilder-dialogs-adaptive-testing/tests/misc.test.js @@ -3,6 +3,7 @@ const { makeResourceExplorer } = require('./utils'); describe('MiscTests', function () { let resourceExplorer; + before(function () { resourceExplorer = makeResourceExplorer('MiscTests'); }); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/tests/multiLanguageGeneratorTests.test.js b/libraries/botbuilder-dialogs-adaptive-testing/tests/multiLanguageGeneratorTests.test.js index b4a6d9f08e..a364f3aa89 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/tests/multiLanguageGeneratorTests.test.js +++ b/libraries/botbuilder-dialogs-adaptive-testing/tests/multiLanguageGeneratorTests.test.js @@ -3,6 +3,7 @@ const { makeResourceExplorer } = require('./utils'); describe('MultiLanguageGeneratorTests', function () { let resourceExplorer; + before(function () { resourceExplorer = makeResourceExplorer('MultiLanguageGeneratorTests'); }); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/tests/multiLanguageRecognizer.test.js b/libraries/botbuilder-dialogs-adaptive-testing/tests/multiLanguageRecognizer.test.js index 788e30323a..22d78d2216 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/tests/multiLanguageRecognizer.test.js +++ b/libraries/botbuilder-dialogs-adaptive-testing/tests/multiLanguageRecognizer.test.js @@ -25,6 +25,7 @@ const createRecognizer = () => describe('MultiLanguageRecognizerTests', function () { let resourceExplorer; + before(function () { resourceExplorer = makeResourceExplorer('MultiLanguageRecognizerTests'); }); @@ -48,7 +49,7 @@ describe('MultiLanguageRecognizerTests', function () { it('EnUsFallback_AcitivtyLocaleCasing', async function () { await TestUtils.runTestScript( resourceExplorer, - 'MultiLanguageRecognizerTest_EnUsFallback_ActivityLocaleCasing' + 'MultiLanguageRecognizerTest_EnUsFallback_ActivityLocaleCasing', ); }); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/tests/qnaMakerRecognizer.test.js b/libraries/botbuilder-dialogs-adaptive-testing/tests/qnaMakerRecognizer.test.js index 362bb44465..c84f192ed4 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/tests/qnaMakerRecognizer.test.js +++ b/libraries/botbuilder-dialogs-adaptive-testing/tests/qnaMakerRecognizer.test.js @@ -6,6 +6,7 @@ const { makeResourceExplorer } = require('./utils'); describe('QnAMakerRecognizerTests', function () { let resourceExplorer; + before(function () { resourceExplorer = makeResourceExplorer('QnAMakerRecognizerTests', QnAMakerBotComponent); }); @@ -24,7 +25,7 @@ describe('QnAMakerRecognizerTests', function () { .post(/knowledgebases/) .replyWithFile( 200, - path.join(__dirname, 'resources/QnAMakerRecognizerTests/QnaMaker_ReturnsAnswerWithIntent.json') + path.join(__dirname, 'resources/QnAMakerRecognizerTests/QnaMaker_ReturnsAnswerWithIntent.json'), ); await TestUtils.runTestScript(resourceExplorer, 'QnAMakerRecognizerTests_ReturnsAnswerWithIntent'); }); @@ -34,7 +35,7 @@ describe('QnAMakerRecognizerTests', function () { .post(/knowledgebases/) .replyWithFile( 200, - path.join(__dirname, 'resources/QnAMakerRecognizerTests/QnaMaker_ReturnsNoAnswer.json') + path.join(__dirname, 'resources/QnAMakerRecognizerTests/QnaMaker_ReturnsNoAnswer.json'), ); await TestUtils.runTestScript(resourceExplorer, 'QnAMakerRecognizerTests_ReturnsNoAnswer'); }); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/tests/recognizerSet.test.js b/libraries/botbuilder-dialogs-adaptive-testing/tests/recognizerSet.test.js index 92f1ee164c..ef8a1eb5df 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/tests/recognizerSet.test.js +++ b/libraries/botbuilder-dialogs-adaptive-testing/tests/recognizerSet.test.js @@ -31,7 +31,7 @@ const createRecognizer = () => new NumberEntityRecognizer(), new PercentageEntityRecognizer(), new PhoneNumberEntityRecognizer(), - new TemperatureEntityRecognizer() + new TemperatureEntityRecognizer(), ), }), new RegexRecognizer().configure({ @@ -41,7 +41,7 @@ const createRecognizer = () => new UrlEntityRecognizer(), new RegexEntityRecognizer('color', '(?i)(red|green|blue|purple|orange|violet|white|black)'), new RegexEntityRecognizer('backgroundColor', '(?i)(back|background)'), - new RegexEntityRecognizer('foregroundColor', '(?i)(foreground|front) {color}') + new RegexEntityRecognizer('foregroundColor', '(?i)(foreground|front) {color}'), ), }), ], @@ -49,6 +49,7 @@ const createRecognizer = () => describe('RecognizerSetTests', function () { let resourceExplorer; + before(function () { resourceExplorer = makeResourceExplorer('RecognizerSetTests'); }); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/tests/recognizerTelemetryUtils.js b/libraries/botbuilder-dialogs-adaptive-testing/tests/recognizerTelemetryUtils.js index 99a6b695e2..ed08124382 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/tests/recognizerTelemetryUtils.js +++ b/libraries/botbuilder-dialogs-adaptive-testing/tests/recognizerTelemetryUtils.js @@ -130,7 +130,7 @@ const validateTelemetry = async ({ recognizer, dialogContext, spy, activity, res strictEqual(actualTelemetryProps.name, `${recognizer.constructor.name}Result`); ok( hasValidTelemetryProps(actualTelemetryProps.properties, expectedTelemetryProps), - 'Expected telemetry property did not match actual telemetry property logged.' + 'Expected telemetry property did not match actual telemetry property logged.', ); }; diff --git a/libraries/botbuilder-dialogs-adaptive-testing/tests/regexRecognizer.test.js b/libraries/botbuilder-dialogs-adaptive-testing/tests/regexRecognizer.test.js index 5fb1809859..857aa67a18 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/tests/regexRecognizer.test.js +++ b/libraries/botbuilder-dialogs-adaptive-testing/tests/regexRecognizer.test.js @@ -3,6 +3,7 @@ const { makeResourceExplorer } = require('./utils'); describe('RegexRecognizerTests', function () { let resourceExplorer; + before(function () { resourceExplorer = makeResourceExplorer('RegexRecognizerTests'); }); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/tests/selector.test.js b/libraries/botbuilder-dialogs-adaptive-testing/tests/selector.test.js index 8c31df76ae..b1bd095129 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/tests/selector.test.js +++ b/libraries/botbuilder-dialogs-adaptive-testing/tests/selector.test.js @@ -3,6 +3,7 @@ const { makeResourceExplorer } = require('./utils'); describe('SelectorTests', function () { let resourceExplorer; + before(function () { resourceExplorer = makeResourceExplorer('SelectorTests'); }); @@ -27,7 +28,7 @@ describe('SelectorTests', function () { await TestUtils.runTestScript(resourceExplorer, 'SelectorTests_Priority'); }); - it('Priority', async function () { + it('FloatPriority', async function () { await TestUtils.runTestScript(resourceExplorer, 'SelectorTests_Float_Priority'); }); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/tests/settingsState.test.js b/libraries/botbuilder-dialogs-adaptive-testing/tests/settingsState.test.js index a14375320d..d6a6e1ebe3 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/tests/settingsState.test.js +++ b/libraries/botbuilder-dialogs-adaptive-testing/tests/settingsState.test.js @@ -3,6 +3,7 @@ const { makeResourceExplorer } = require('./utils'); describe('SettingsStateTests', function () { let resourceExplorer; + before(function () { resourceExplorer = makeResourceExplorer('SettingsStateTests'); }); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/tests/testScript.test.js b/libraries/botbuilder-dialogs-adaptive-testing/tests/testScript.test.js index 836b328bbe..9586a38c58 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/tests/testScript.test.js +++ b/libraries/botbuilder-dialogs-adaptive-testing/tests/testScript.test.js @@ -6,6 +6,7 @@ const { makeResourceExplorer } = require('./utils'); describe('TestScriptTests', function () { let resourceExplorer; + before(function () { resourceExplorer = makeResourceExplorer('TestScriptTests', QnAMakerBotComponent); }); @@ -24,7 +25,7 @@ describe('TestScriptTests', function () { (err) => { assert(err.message.includes('undefined text.length == 0 {"type":"message","text":"hi User1"')); return true; - } + }, ); }); @@ -74,7 +75,7 @@ describe('TestScriptTests', function () { resourceExplorer.registerType( LuisAdaptiveRecognizer.$kind, MockLuisRecognizer, - new MockLuisLoader(resourceExplorer, config) + new MockLuisLoader(resourceExplorer, config), ); await TestUtils.runTestScript(resourceExplorer, 'TestScriptTests_HttpRequestLuisMock', undefined, config); }); diff --git a/libraries/botbuilder-dialogs-adaptive-testing/tests/valueRecognizer.test.js b/libraries/botbuilder-dialogs-adaptive-testing/tests/valueRecognizer.test.js index 30e155fabb..b11a4f87dc 100644 --- a/libraries/botbuilder-dialogs-adaptive-testing/tests/valueRecognizer.test.js +++ b/libraries/botbuilder-dialogs-adaptive-testing/tests/valueRecognizer.test.js @@ -3,6 +3,7 @@ const { makeResourceExplorer } = require('./utils'); describe('ValueRecognizerTests', function () { let resourceExplorer; + before(function () { resourceExplorer = makeResourceExplorer('ValueRecognizerTests'); }); From fc263a21120f7cb8d58ab7186a803c484ac2e37b Mon Sep 17 00:00:00 2001 From: Joel Mut <62260472+sw-joelmut@users.noreply.github.com> Date: Mon, 6 Jan 2025 12:00:27 -0300 Subject: [PATCH 02/22] fix: [#4684] ESLint issues in botframework-connector (#4822) * Fix ESLint in botframework-connector * Fix jsdoc formatting --- .../botframework-connector/eslint.config.cjs | 12 +--- libraries/botframework-connector/package.json | 1 - .../src/auth/allowedCallersClaimsValidator.ts | 2 +- .../src/auth/appCredentials.ts | 4 +- .../src/auth/aseChannelValidation.ts | 19 +++-- .../src/auth/authenticationConfiguration.ts | 2 +- .../src/auth/authenticationError.ts | 7 +- .../src/auth/botFrameworkAuthentication.ts | 4 +- .../auth/botFrameworkAuthenticationFactory.ts | 10 +-- .../src/auth/botFrameworkClientImpl.ts | 6 +- .../src/auth/certificateAppCredentials.ts | 8 +-- ...tificateServiceClientCredentialsFactory.ts | 20 +++--- .../src/auth/channelValidation.ts | 12 ++-- .../src/auth/claimsIdentity.ts | 5 +- .../src/auth/connectorFactoryImpl.ts | 6 +- .../src/auth/emulatorValidation.ts | 18 ++--- .../src/auth/enterpriseChannelValidation.ts | 16 ++--- .../src/auth/federatedAppCredentials.ts | 8 +-- ...ederatedServiceClientCredentialsFactory.ts | 8 +-- .../src/auth/governmentChannelValidation.ts | 12 ++-- .../src/auth/jwtTokenExtractor.ts | 18 ++--- .../src/auth/jwtTokenValidation.ts | 30 ++++---- ...IdentityServiceClientCredentialsFactory.ts | 4 +- .../src/auth/microsoftAppCredentials.ts | 11 ++- .../auth/microsoftGovernmentAppCredentials.ts | 7 +- .../src/auth/msalAppCredentials.ts | 6 +- .../msalServiceClientCredentialsFactory.ts | 11 +-- .../src/auth/openIdMetadata.ts | 9 ++- ...parameterizedBotFrameworkAuthentication.ts | 70 +++++++++---------- .../passwordServiceClientCredentialFactory.ts | 10 +-- .../auth/serviceClientCredentialsFactory.ts | 2 +- .../src/auth/skillValidation.ts | 22 +++--- .../src/auth/userTokenClient.ts | 8 +-- .../src/auth/userTokenClientImpl.ts | 16 ++--- .../src/emulatorApiClient.ts | 2 +- .../src/skills/botFrameworkClient.ts | 3 +- .../src/teams/models/index.ts | 4 +- .../src/teams/retryAction.ts | 2 +- .../src/teams/teamsConnectorClient.ts | 10 ++- .../tests/appCredentials.test.js | 6 +- .../tests/auth/aseChannelValidation.test.js | 16 ++--- .../tests/auth/channelValidation.test.js | 30 ++++---- .../auth/enterpriseChannelValidation.test.js | 22 +++--- .../auth/governmentChannelValidation.test.js | 20 +++--- .../tests/auth/jwtTokenExtractor.test.js | 4 +- .../tests/auth/jwtTokenValidation.test.js | 6 +- .../auth/microsoftAppCredentials.test.js | 4 +- .../microsoftGovernmentAppCredentials.test.js | 4 +- .../tests/auth/userTokenClient.test.js | 2 +- .../botFrameworkAuthenticationFactory.test.js | 8 +-- .../tests/connector.test.js | 45 +++++++++--- .../tests/ms-rest-mappers-test.js | 1 + ...wordServiceClientCredentialFactory.test.js | 2 +- .../tests/skillValidation.test.js | 52 +++++++------- 54 files changed, 341 insertions(+), 306 deletions(-) diff --git a/libraries/botframework-connector/eslint.config.cjs b/libraries/botframework-connector/eslint.config.cjs index 8e98f7925b..bfbc7b2e3b 100644 --- a/libraries/botframework-connector/eslint.config.cjs +++ b/libraries/botframework-connector/eslint.config.cjs @@ -1,14 +1,8 @@ -const onlyWarn = require("eslint-plugin-only-warn"); -const sharedConfig = require("../../eslint.config.cjs") +const sharedConfig = require('../../eslint.config.cjs'); module.exports = [ ...sharedConfig, { - ignores: ["src/connectorApi/**/*", "src/tokenApi/**/*", "**/*.nock.js"], - + ignores: ['src/connectorApi/**/*', 'src/tokenApi/**/*', '**/*.nock.js'], }, - { - plugins: { - "only-warn": onlyWarn, - }, - }] +]; diff --git a/libraries/botframework-connector/package.json b/libraries/botframework-connector/package.json index 6181d9a7c9..8cd6fa24e5 100644 --- a/libraries/botframework-connector/package.json +++ b/libraries/botframework-connector/package.json @@ -37,7 +37,6 @@ "botframework-schema": "4.1.6", "buffer": "^6.0.3", "cross-fetch": "^4.0.0", - "eslint-plugin-only-warn": "^1.1.0", "https-proxy-agent": "^7.0.5", "jsonwebtoken": "^9.0.2", "node-fetch": "^2.7.0", diff --git a/libraries/botframework-connector/src/auth/allowedCallersClaimsValidator.ts b/libraries/botframework-connector/src/auth/allowedCallersClaimsValidator.ts index 01ccbbfc8d..28e78338c1 100644 --- a/libraries/botframework-connector/src/auth/allowedCallersClaimsValidator.ts +++ b/libraries/botframework-connector/src/auth/allowedCallersClaimsValidator.ts @@ -23,7 +23,7 @@ export function allowedCallersClaimsValidator(allowedCallers: string[]): Validat const appId = JwtTokenValidation.getAppIdFromClaims(claims); if (!allowed.has(appId)) { throw new Error( - `Received a request from an application with an appID of "${appId}". To enable requests from this skill, add the skill to your configuration file.` + `Received a request from an application with an appID of "${appId}". To enable requests from this skill, add the skill to your configuration file.`, ); } } diff --git a/libraries/botframework-connector/src/auth/appCredentials.ts b/libraries/botframework-connector/src/auth/appCredentials.ts index c02b78f940..1d0e8cb4aa 100644 --- a/libraries/botframework-connector/src/auth/appCredentials.ts +++ b/libraries/botframework-connector/src/auth/appCredentials.ts @@ -43,8 +43,8 @@ export abstract class AppCredentials implements ServiceClientCredentials { * * @param appId The App ID. * @param channelAuthTenant Tenant ID of the Azure AD tenant where the bot is created. - * * Required for SingleTenant app types. - * * Optional for MultiTenant app types. **Note**: '_botframework.com_' is the default tenant when no value is provided. + * - Required for SingleTenant app types. + * - Optional for MultiTenant app types. **Note**: '_botframework.com_' is the default tenant when no value is provided. * * More information: https://learn.microsoft.com/en-us/security/zero-trust/develop/identity-supported-account-types. * @param oAuthScope The scope for the token. diff --git a/libraries/botframework-connector/src/auth/aseChannelValidation.ts b/libraries/botframework-connector/src/auth/aseChannelValidation.ts index 4d326e6279..38ff101cc3 100644 --- a/libraries/botframework-connector/src/auth/aseChannelValidation.ts +++ b/libraries/botframework-connector/src/auth/aseChannelValidation.ts @@ -12,11 +12,10 @@ import { ClaimsIdentity } from './claimsIdentity'; import { AuthenticationConstants } from './authenticationConstants'; import { AuthenticationConfiguration } from './authenticationConfiguration'; import { GovernmentConstants } from './governmentConstants'; -import { ICredentialProvider } from './credentialProvider'; +import { ICredentialProvider, SimpleCredentialProvider } from './credentialProvider'; import { JwtTokenExtractor } from './jwtTokenExtractor'; import { JwtTokenValidation } from './jwtTokenValidation'; import { AuthenticationError } from './authenticationError'; -import { SimpleCredentialProvider } from './credentialProvider'; import { StatusCodes } from 'botframework-schema'; import { BetweenBotAndAseChannelTokenValidationParameters } from './tokenValidationParameters'; @@ -80,18 +79,18 @@ export namespace AseChannelValidation { */ export async function authenticateAseChannelToken( authHeader: string, - authConfig: AuthenticationConfiguration = new AuthenticationConfiguration() + authConfig: AuthenticationConfiguration = new AuthenticationConfiguration(), ): Promise { const tokenExtractor: JwtTokenExtractor = new JwtTokenExtractor( BetweenBotAndAseChannelTokenValidationParameters, MetadataUrl, - AuthenticationConstants.AllowedSigningAlgorithms + AuthenticationConstants.AllowedSigningAlgorithms, ); const identity: ClaimsIdentity = await tokenExtractor.getIdentityFromAuthHeader( authHeader, ChannelId, - authConfig.requiredEndorsements + authConfig.requiredEndorsements, ); if (!identity) { // No valid identity. Not Authorized. @@ -111,7 +110,7 @@ export namespace AseChannelValidation { if (versionClaim === null) { throw new AuthenticationError( 'Unauthorized. "ver" claim is required on Emulator Tokens.', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -127,7 +126,7 @@ export namespace AseChannelValidation { // No claim around AppID. Not Authorized. throw new AuthenticationError( 'Unauthorized. "appid" claim is required on Emulator Token version "1.0".', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -139,7 +138,7 @@ export namespace AseChannelValidation { // No claim around AppID. Not Authorized. throw new AuthenticationError( 'Unauthorized. "azp" claim is required on Emulator Token version "2.0".', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -148,14 +147,14 @@ export namespace AseChannelValidation { // Unknown Version. Not Authorized. throw new AuthenticationError( `Unauthorized. Unknown Emulator Token version "${versionClaim}".`, - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } if (!(await _creadentialProvider.isValidAppId(appId))) { throw new AuthenticationError( `Unauthorized. Invalid AppId passed on token: ${appId}`, - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } diff --git a/libraries/botframework-connector/src/auth/authenticationConfiguration.ts b/libraries/botframework-connector/src/auth/authenticationConfiguration.ts index e7b1cf607b..0061296123 100644 --- a/libraries/botframework-connector/src/auth/authenticationConfiguration.ts +++ b/libraries/botframework-connector/src/auth/authenticationConfiguration.ts @@ -28,6 +28,6 @@ export class AuthenticationConfiguration { constructor( public requiredEndorsements: string[] = [], public validateClaims?: ValidateClaims, - public validTokenIssuers?: string[] + public validTokenIssuers?: string[], ) {} } diff --git a/libraries/botframework-connector/src/auth/authenticationError.ts b/libraries/botframework-connector/src/auth/authenticationError.ts index 6796576932..df49bd2dcf 100644 --- a/libraries/botframework-connector/src/auth/authenticationError.ts +++ b/libraries/botframework-connector/src/auth/authenticationError.ts @@ -17,7 +17,10 @@ export class AuthenticationError extends Error implements IStatusCodeError { * @param message The Error message. * @param statusCode The `StatusCode` number to use. */ - constructor(message: string, public readonly statusCode: StatusCode) { + constructor( + message: string, + readonly statusCode: StatusCode, + ) { super(message); } @@ -27,7 +30,6 @@ export class AuthenticationError extends Error implements IStatusCodeError { * @param err The error to validate. * @returns If `err` is an [IStatusCodeError](xref:botframework-schema.IStatusCodeError), the result is true; otherwise false. */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types static isStatusCodeError(err: any): err is IStatusCodeError { return !!(err && typeof err.statusCode === 'number'); } @@ -38,7 +40,6 @@ export class AuthenticationError extends Error implements IStatusCodeError { * @param err The error thrown, used to determine an appropriate status code. * @returns The error message to be sent as a response. */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types static determineStatusCodeAndBuildMessage(err: any): string { const errMessage: string = err && err.message ? err.message : 'Internal Server Error'; const code: number = AuthenticationError.determineStatusCode(errMessage); diff --git a/libraries/botframework-connector/src/auth/botFrameworkAuthentication.ts b/libraries/botframework-connector/src/auth/botFrameworkAuthentication.ts index 0273aff0a2..0f948bf109 100644 --- a/libraries/botframework-connector/src/auth/botFrameworkAuthentication.ts +++ b/libraries/botframework-connector/src/auth/botFrameworkAuthentication.ts @@ -33,7 +33,7 @@ export abstract class BotFrameworkAuthentication { */ abstract authenticateStreamingRequest( authHeader: string, - channelIdHeader: string + channelIdHeader: string, ): Promise; /** @@ -96,7 +96,7 @@ export abstract class BotFrameworkAuthentication { protected async generateCallerId( credentialFactory: ServiceClientCredentialsFactory, claimsIdentity: ClaimsIdentity, - callerId: string + callerId: string, ): Promise { // Is the bot accepting all incoming messages? if (await credentialFactory.isAuthenticationDisabled()) { diff --git a/libraries/botframework-connector/src/auth/botFrameworkAuthenticationFactory.ts b/libraries/botframework-connector/src/auth/botFrameworkAuthenticationFactory.ts index a80e5b6e8b..87bef33c1c 100644 --- a/libraries/botframework-connector/src/auth/botFrameworkAuthenticationFactory.ts +++ b/libraries/botframework-connector/src/auth/botFrameworkAuthenticationFactory.ts @@ -52,7 +52,7 @@ export class BotFrameworkAuthenticationFactory { credentialFactory: ServiceClientCredentialsFactory, authConfiguration: AuthenticationConfiguration, botFrameworkClientFetch?: (input: RequestInfo, init?: RequestInit) => Promise, - connectorClientOptions?: ConnectorClientOptions + connectorClientOptions?: ConnectorClientOptions, ): BotFrameworkAuthentication; /** @@ -84,7 +84,7 @@ export class BotFrameworkAuthenticationFactory { maybeCredentialFactory?: ServiceClientCredentialsFactory, maybeAuthConfiguration?: AuthenticationConfiguration, maybeBotFrameworkClientFetch?: (input: RequestInfo, init?: RequestInit) => Promise, - maybeConnectorClientOptions: ConnectorClientOptions = {} + maybeConnectorClientOptions: ConnectorClientOptions = {}, ): BotFrameworkAuthentication { if ( !stringExt.isNilOrEmpty(maybeToChannelFromBotLoginUrl) || @@ -108,7 +108,7 @@ export class BotFrameworkAuthenticationFactory { maybeCredentialFactory, maybeAuthConfiguration, maybeBotFrameworkClientFetch, - maybeConnectorClientOptions + maybeConnectorClientOptions, ); } else { // else apply the built in default behavior, which is either the public cloud or the gov cloud depending on whether we have a channelService value present @@ -125,7 +125,7 @@ export class BotFrameworkAuthenticationFactory { maybeCredentialFactory, maybeAuthConfiguration, maybeBotFrameworkClientFetch, - maybeConnectorClientOptions + maybeConnectorClientOptions, ); } else if (maybeChannelService === GovernmentConstants.ChannelService) { return new ParameterizedBotFrameworkAuthentication( @@ -140,7 +140,7 @@ export class BotFrameworkAuthenticationFactory { maybeCredentialFactory, maybeAuthConfiguration, maybeBotFrameworkClientFetch, - maybeConnectorClientOptions + maybeConnectorClientOptions, ); } else { // The ChannelService value is used an indicator of which built in set of constants to use. If it is not recognized, a full configuration is expected. diff --git a/libraries/botframework-connector/src/auth/botFrameworkClientImpl.ts b/libraries/botframework-connector/src/auth/botFrameworkClientImpl.ts index 4a78f324a5..96ae30065c 100644 --- a/libraries/botframework-connector/src/auth/botFrameworkClientImpl.ts +++ b/libraries/botframework-connector/src/auth/botFrameworkClientImpl.ts @@ -52,7 +52,7 @@ export class BotFrameworkClientImpl implements BotFrameworkClient { private readonly credentialsFactory: ServiceClientCredentialsFactory, private readonly loginEndpoint: string, private readonly botFrameworkClientFetch?: ReturnType, - private readonly connectorClientOptions?: ConnectorClientOptions + private readonly connectorClientOptions?: ConnectorClientOptions, ) { this.botFrameworkClientFetch ??= botFrameworkClientFetchImpl(this.connectorClientOptions); @@ -82,7 +82,7 @@ export class BotFrameworkClientImpl implements BotFrameworkClient { toUrl: string, serviceUrl: string, conversationId: string, - activity: Activity + activity: Activity, ): Promise> { z.object({ fromBotId: z.string().optional(), @@ -104,7 +104,7 @@ export class BotFrameworkClientImpl implements BotFrameworkClient { fromBotId, toBotId, this.loginEndpoint, - true + true, ); // Capture current activity settings before changing them. diff --git a/libraries/botframework-connector/src/auth/certificateAppCredentials.ts b/libraries/botframework-connector/src/auth/certificateAppCredentials.ts index ae69051956..ac264f43e2 100644 --- a/libraries/botframework-connector/src/auth/certificateAppCredentials.ts +++ b/libraries/botframework-connector/src/auth/certificateAppCredentials.ts @@ -28,8 +28,8 @@ export class CertificateAppCredentials extends AppCredentials { * @param certificateThumbprint A hex encoded thumbprint of the certificate. * @param certificatePrivateKey A PEM encoded certificate private key. * @param channelAuthTenant Tenant ID of the Azure AD tenant where the bot is created. - * * Required for SingleTenant app types. - * * Optional for MultiTenant app types. **Note**: '_botframework.com_' is the default tenant when no value is provided. + * - Required for SingleTenant app types. + * - Optional for MultiTenant app types. **Note**: '_botframework.com_' is the default tenant when no value is provided. * * More information: https://learn.microsoft.com/en-us/security/zero-trust/develop/identity-supported-account-types. * @param oAuthScope Optional. The scope for the token. @@ -42,7 +42,7 @@ export class CertificateAppCredentials extends AppCredentials { certificatePrivateKey: string, channelAuthTenant?: string, oAuthScope?: string, - x5c?: string + x5c?: string, ) { super(appId, channelAuthTenant, oAuthScope); this.certificateThumbprint = certificateThumbprint; @@ -58,7 +58,7 @@ export class CertificateAppCredentials extends AppCredentials { this.createClientApplication(), this.appId, this.oAuthEndpoint, - this.oAuthScope + this.oAuthScope, ); return this.credentials.getToken(forceRefresh); } diff --git a/libraries/botframework-connector/src/auth/certificateServiceClientCredentialsFactory.ts b/libraries/botframework-connector/src/auth/certificateServiceClientCredentialsFactory.ts index ff2e607caa..9a9acb5ae1 100644 --- a/libraries/botframework-connector/src/auth/certificateServiceClientCredentialsFactory.ts +++ b/libraries/botframework-connector/src/auth/certificateServiceClientCredentialsFactory.ts @@ -31,8 +31,8 @@ export class CertificateServiceClientCredentialsFactory extends ServiceClientCre * @param certificateThumbprint A hex encoded thumbprint of the certificate. * @param certificatePrivateKey A PEM encoded certificate private key. * @param tenantId Tenant ID of the Azure AD tenant where the bot is created. - * * Required for SingleTenant app types. - * * Optional for MultiTenant app types. **Note**: '_botframework.com_' is the default tenant when no value is provided. + * - Required for SingleTenant app types. + * - Optional for MultiTenant app types. **Note**: '_botframework.com_' is the default tenant when no value is provided. * * More information: https://learn.microsoft.com/en-us/security/zero-trust/develop/identity-supported-account-types. * @param x5c Optional. Enables application developers to achieve easy certificates roll-over in Azure AD: @@ -43,7 +43,7 @@ export class CertificateServiceClientCredentialsFactory extends ServiceClientCre certificateThumbprint: string, certificatePrivateKey: string, tenantId?: string, - x5c?: string + x5c?: string, ); /** @@ -54,8 +54,8 @@ export class CertificateServiceClientCredentialsFactory extends ServiceClientCre * set this parameter to send the public certificate (BEGIN CERTIFICATE) to Azure AD, so that Azure AD can use it to validate the subject name based on a trusted issuer policy. * @param certificatePrivateKey A PEM encoded certificate private key. * @param tenantId Tenant ID of the Azure AD tenant where the bot is created. - * * Required for SingleTenant app types. - * * Optional for MultiTenant app types. **Note**: '_botframework.com_' is the default tenant when no value is provided. + * - Required for SingleTenant app types. + * - Optional for MultiTenant app types. **Note**: '_botframework.com_' is the default tenant when no value is provided. * * More information: https://learn.microsoft.com/en-us/security/zero-trust/develop/identity-supported-account-types. */ @@ -69,14 +69,14 @@ export class CertificateServiceClientCredentialsFactory extends ServiceClientCre certificateThumbprintOrx5c: string, certificatePrivateKey: string, tenantId?: string, - x5c?: string + x5c?: string, ) { super(); ok(appId?.trim(), 'CertificateServiceClientCredentialsFactory.constructor(): missing appId.'); ok( certificatePrivateKey?.trim(), - 'CertificateServiceClientCredentialsFactory.constructor(): missing certificatePrivateKey.' + 'CertificateServiceClientCredentialsFactory.constructor(): missing certificatePrivateKey.', ); if (certificateThumbprintOrx5c?.includes('-----BEGIN CERTIFICATE-----')) { @@ -84,7 +84,7 @@ export class CertificateServiceClientCredentialsFactory extends ServiceClientCre } else { ok( certificateThumbprintOrx5c?.trim(), - 'CertificateServiceClientCredentialsFactory.constructor(): missing certificateThumbprint or x5c value.' + 'CertificateServiceClientCredentialsFactory.constructor(): missing certificateThumbprint or x5c value.', ); this.certificateThumbprint = certificateThumbprintOrx5c; this.x5c = x5c; @@ -128,7 +128,7 @@ export class CertificateServiceClientCredentialsFactory extends ServiceClientCre async createCredentials(appId: string, audience: string): Promise { ok( await this.isValidAppId(appId), - 'CertificateServiceClientCredentialsFactory.createCredentials(): Invalid Managed ID.' + 'CertificateServiceClientCredentialsFactory.createCredentials(): Invalid Managed ID.', ); return new CertificateAppCredentials( @@ -137,7 +137,7 @@ export class CertificateServiceClientCredentialsFactory extends ServiceClientCre this.certificatePrivateKey, this.tenantId, audience, - this.x5c + this.x5c, ); } } diff --git a/libraries/botframework-connector/src/auth/channelValidation.ts b/libraries/botframework-connector/src/auth/channelValidation.ts index 0353d59f60..a2a7a6dd94 100644 --- a/libraries/botframework-connector/src/auth/channelValidation.ts +++ b/libraries/botframework-connector/src/auth/channelValidation.ts @@ -48,7 +48,7 @@ export namespace ChannelValidation { credentials: ICredentialProvider, serviceUrl: string, channelId: string, - authConfig: AuthenticationConfiguration = new AuthenticationConfiguration() + authConfig: AuthenticationConfiguration = new AuthenticationConfiguration(), ): Promise { const identity: ClaimsIdentity = await authenticateChannelToken(authHeader, credentials, channelId, authConfig); @@ -75,18 +75,18 @@ export namespace ChannelValidation { authHeader: string, credentials: ICredentialProvider, channelId: string, - authConfig: AuthenticationConfiguration = new AuthenticationConfiguration() + authConfig: AuthenticationConfiguration = new AuthenticationConfiguration(), ): Promise { const tokenExtractor: JwtTokenExtractor = new JwtTokenExtractor( ToBotFromChannelTokenValidationParameters, OpenIdMetadataEndpoint ? OpenIdMetadataEndpoint : AuthenticationConstants.ToBotFromChannelOpenIdMetadataUrl, - AuthenticationConstants.AllowedSigningAlgorithms + AuthenticationConstants.AllowedSigningAlgorithms, ); const identity: ClaimsIdentity = await tokenExtractor.getIdentityFromAuthHeader( authHeader, channelId, - authConfig.requiredEndorsements + authConfig.requiredEndorsements, ); return await validateIdentity(identity, credentials); @@ -101,7 +101,7 @@ export namespace ChannelValidation { */ export async function validateIdentity( identity: ClaimsIdentity, - credentials: ICredentialProvider + credentials: ICredentialProvider, ): Promise { if (!identity || !identity.isAuthenticated) { // The token is in some way invalid. Not Authorized. @@ -129,7 +129,7 @@ export namespace ChannelValidation { // The AppId is not valid or not present. Not Authorized. throw new AuthenticationError( `Unauthorized. Invalid AppId passed on token: ${audClaim}`, - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } diff --git a/libraries/botframework-connector/src/auth/claimsIdentity.ts b/libraries/botframework-connector/src/auth/claimsIdentity.ts index bee59db71f..39427ae874 100644 --- a/libraries/botframework-connector/src/auth/claimsIdentity.ts +++ b/libraries/botframework-connector/src/auth/claimsIdentity.ts @@ -24,7 +24,10 @@ export class ClaimsIdentity { * @param {Claim[]} claims An array of [Claim](xref:botframework-connector.Claim). * @param {string | boolean} authenticationType The type of auth for this set of claims, or boolean to override isAuthenticated */ - constructor(public readonly claims: Claim[], private readonly authenticationType?: string | boolean) {} + constructor( + readonly claims: Claim[], + private readonly authenticationType?: string | boolean, + ) {} /** * Returns authentication status. diff --git a/libraries/botframework-connector/src/auth/connectorFactoryImpl.ts b/libraries/botframework-connector/src/auth/connectorFactoryImpl.ts index ea6d77a6a6..5703531a13 100644 --- a/libraries/botframework-connector/src/auth/connectorFactoryImpl.ts +++ b/libraries/botframework-connector/src/auth/connectorFactoryImpl.ts @@ -7,7 +7,7 @@ import { ConnectorClientOptions } from '../connectorApi/models'; import { ConnectorFactory } from './connectorFactory'; import type { ServiceClientCredentialsFactory } from './serviceClientCredentialsFactory'; -// eslint-disable-next-line @typescript-eslint/no-var-requires +// eslint-disable-next-line @typescript-eslint/no-require-imports const packageInfo: Record<'name' | 'version', string> = require('../../package.json'); export const USER_AGENT = `Microsoft-BotFramework/3.1 ${packageInfo.name}/${ packageInfo.version @@ -32,7 +32,7 @@ export class ConnectorFactoryImpl extends ConnectorFactory { private readonly loginEndpoint: string, private readonly validateAuthority: boolean, private readonly credentialFactory: ServiceClientCredentialsFactory, - private readonly connectorClientOptions: ConnectorClientOptions = {} + private readonly connectorClientOptions: ConnectorClientOptions = {}, ) { super(); } @@ -48,7 +48,7 @@ export class ConnectorFactoryImpl extends ConnectorFactory { this.appId, audience ?? this.toChannelFromBotOAuthScope, this.loginEndpoint, - this.validateAuthority + this.validateAuthority, ); // A new connector client for making calls against this serviceUrl using credentials derived from the current appId and the specified audience. diff --git a/libraries/botframework-connector/src/auth/emulatorValidation.ts b/libraries/botframework-connector/src/auth/emulatorValidation.ts index 1972ccea53..2c55889b9e 100644 --- a/libraries/botframework-connector/src/auth/emulatorValidation.ts +++ b/libraries/botframework-connector/src/auth/emulatorValidation.ts @@ -62,7 +62,7 @@ export namespace EmulatorValidation { } // Parse the Big Long String into an actual token. - // eslint-disable-next-line @typescript-eslint/no-explicit-any + const token: any = decode(bearerToken, { complete: true }); if (!token) { return false; @@ -121,7 +121,7 @@ export namespace EmulatorValidation { credentials: ICredentialProvider, channelService: string, channelId: string, - authConfig: AuthenticationConfiguration = new AuthenticationConfiguration() + authConfig: AuthenticationConfiguration = new AuthenticationConfiguration(), ): Promise { const openIdMetadataUrl = channelService !== undefined && JwtTokenValidation.isGovernment(channelService) @@ -131,13 +131,13 @@ export namespace EmulatorValidation { const tokenExtractor: JwtTokenExtractor = new JwtTokenExtractor( ToBotFromEmulatorTokenValidationParameters, openIdMetadataUrl, - AuthenticationConstants.AllowedSigningAlgorithms + AuthenticationConstants.AllowedSigningAlgorithms, ); const identity: ClaimsIdentity = await tokenExtractor.getIdentityFromAuthHeader( authHeader, channelId, - authConfig.requiredEndorsements + authConfig.requiredEndorsements, ); if (!identity) { // No valid identity. Not Authorized. @@ -157,7 +157,7 @@ export namespace EmulatorValidation { if (versionClaim === null) { throw new AuthenticationError( 'Unauthorized. "ver" claim is required on Emulator Tokens.', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -173,7 +173,7 @@ export namespace EmulatorValidation { // No claim around AppID. Not Authorized. throw new AuthenticationError( 'Unauthorized. "appid" claim is required on Emulator Token version "1.0".', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -185,7 +185,7 @@ export namespace EmulatorValidation { // No claim around AppID. Not Authorized. throw new AuthenticationError( 'Unauthorized. "azp" claim is required on Emulator Token version "2.0".', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -194,14 +194,14 @@ export namespace EmulatorValidation { // Unknown Version. Not Authorized. throw new AuthenticationError( `Unauthorized. Unknown Emulator Token version "${versionClaim}".`, - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } if (!(await credentials.isValidAppId(appId))) { throw new AuthenticationError( `Unauthorized. Invalid AppId passed on token: ${appId}`, - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } diff --git a/libraries/botframework-connector/src/auth/enterpriseChannelValidation.ts b/libraries/botframework-connector/src/auth/enterpriseChannelValidation.ts index 9167b9c853..dddbd89cf3 100644 --- a/libraries/botframework-connector/src/auth/enterpriseChannelValidation.ts +++ b/libraries/botframework-connector/src/auth/enterpriseChannelValidation.ts @@ -47,13 +47,13 @@ export namespace EnterpriseChannelValidation { credentials: ICredentialProvider, serviceUrl: string, channelId: string, - channelService: string + channelService: string, ): Promise { const identity: ClaimsIdentity = await authenticateChannelToken( authHeader, credentials, channelId, - channelService + channelService, ); const serviceUrlClaim: string = identity.getClaimValue(AuthenticationConstants.ServiceUrlClaim); @@ -81,7 +81,7 @@ export namespace EnterpriseChannelValidation { credentials: ICredentialProvider, channelId: string, channelService: string, - authConfig: AuthenticationConfiguration = new AuthenticationConfiguration() + authConfig: AuthenticationConfiguration = new AuthenticationConfiguration(), ): Promise { const tokenExtractor: JwtTokenExtractor = new JwtTokenExtractor( ToBotFromEnterpriseChannelTokenValidationParameters, @@ -89,15 +89,15 @@ export namespace EnterpriseChannelValidation { ? ChannelValidation.OpenIdMetadataEndpoint : AuthenticationConstants.ToBotFromEnterpriseChannelOpenIdMetadataUrlFormat.replace( '{channelService}', - channelService + channelService, ), - AuthenticationConstants.AllowedSigningAlgorithms + AuthenticationConstants.AllowedSigningAlgorithms, ); const identity: ClaimsIdentity = await tokenExtractor.getIdentityFromAuthHeader( authHeader, channelId, - authConfig.requiredEndorsements + authConfig.requiredEndorsements, ); return await validateIdentity(identity, credentials); @@ -112,7 +112,7 @@ export namespace EnterpriseChannelValidation { */ export async function validateIdentity( identity: ClaimsIdentity, - credentials: ICredentialProvider + credentials: ICredentialProvider, ): Promise { if (!identity) { // No valid identity. Not Authorized. @@ -145,7 +145,7 @@ export namespace EnterpriseChannelValidation { // The AppId is not valid or not present. Not Authorized. throw new AuthenticationError( `Unauthorized. Invalid AppId passed on token: ${audClaim}`, - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } diff --git a/libraries/botframework-connector/src/auth/federatedAppCredentials.ts b/libraries/botframework-connector/src/auth/federatedAppCredentials.ts index 39029e8c88..8e487fb662 100644 --- a/libraries/botframework-connector/src/auth/federatedAppCredentials.ts +++ b/libraries/botframework-connector/src/auth/federatedAppCredentials.ts @@ -26,8 +26,8 @@ export class FederatedAppCredentials extends AppCredentials { * @param {string} appId App ID for the Application. * @param {string} clientId Client ID for the managed identity assigned to the bot. * @param {string} channelAuthTenant Tenant ID of the Azure AD tenant where the bot is created. - * * **Required** for SingleTenant app types. - * * **Optional** for MultiTenant app types. **Note**: '_botframework.com_' is the default tenant when no value is provided. + * - **Required** for SingleTenant app types. + * - **Optional** for MultiTenant app types. **Note**: '_botframework.com_' is the default tenant when no value is provided. * * More information: https://learn.microsoft.com/en-us/security/zero-trust/develop/identity-supported-account-types. * @param {string} oAuthScope **Optional**. The scope for the token. @@ -38,7 +38,7 @@ export class FederatedAppCredentials extends AppCredentials { clientId: string, channelAuthTenant?: string, oAuthScope?: string, - clientAudience?: string + clientAudience?: string, ) { super(appId, channelAuthTenant, oAuthScope); @@ -58,7 +58,7 @@ export class FederatedAppCredentials extends AppCredentials { this.createClientApplication(await this.fetchExternalToken(forceRefresh)), this.oAuthEndpoint, this.oAuthEndpoint, - this.oAuthScope + this.oAuthScope, ); return this.credentials.getToken(forceRefresh); } diff --git a/libraries/botframework-connector/src/auth/federatedServiceClientCredentialsFactory.ts b/libraries/botframework-connector/src/auth/federatedServiceClientCredentialsFactory.ts index 6f0df67a81..0ae06f91a6 100644 --- a/libraries/botframework-connector/src/auth/federatedServiceClientCredentialsFactory.ts +++ b/libraries/botframework-connector/src/auth/federatedServiceClientCredentialsFactory.ts @@ -19,8 +19,8 @@ export class FederatedServiceClientCredentialsFactory extends ServiceClientCrede * @param {string} appId App ID for the Application. * @param {string} clientId Client ID for the managed identity assigned to the bot. * @param {string} tenantId Tenant ID of the Azure AD tenant where the bot is created. - * * **Required** for SingleTenant app types. - * * **Optional** for MultiTenant app types. **Note**: '_botframework.com_' is the default tenant when no value is provided. + * - **Required** for SingleTenant app types. + * - **Optional** for MultiTenant app types. **Note**: '_botframework.com_' is the default tenant when no value is provided. * * More information: https://learn.microsoft.com/en-us/security/zero-trust/develop/identity-supported-account-types. * @param {string} clientAudience **Optional**. The Audience used in the Client's Federated Credential. **Default** (_api://AzureADTokenExchange_). @@ -29,7 +29,7 @@ export class FederatedServiceClientCredentialsFactory extends ServiceClientCrede private appId: string, private clientId: string, private tenantId?: string, - private clientAudience?: string + private clientAudience?: string, ) { super(); @@ -58,7 +58,7 @@ export class FederatedServiceClientCredentialsFactory extends ServiceClientCrede async createCredentials(appId: string, audience: string): Promise { ok( await this.isValidAppId(appId), - 'FederatedServiceClientCredentialsFactory.createCredentials(): Invalid App ID.' + 'FederatedServiceClientCredentialsFactory.createCredentials(): Invalid App ID.', ); return new FederatedAppCredentials(this.appId, this.clientId, this.tenantId, audience, this.clientAudience); diff --git a/libraries/botframework-connector/src/auth/governmentChannelValidation.ts b/libraries/botframework-connector/src/auth/governmentChannelValidation.ts index 0b8a151282..060d98e832 100644 --- a/libraries/botframework-connector/src/auth/governmentChannelValidation.ts +++ b/libraries/botframework-connector/src/auth/governmentChannelValidation.ts @@ -48,7 +48,7 @@ export namespace GovernmentChannelValidation { authHeader: string, credentials: ICredentialProvider, serviceUrl: string, - channelId: string + channelId: string, ): Promise { const identity: ClaimsIdentity = await authenticateChannelToken(authHeader, credentials, channelId); @@ -75,18 +75,18 @@ export namespace GovernmentChannelValidation { authHeader: string, credentials: ICredentialProvider, channelId: string, - authConfig: AuthenticationConfiguration = new AuthenticationConfiguration() + authConfig: AuthenticationConfiguration = new AuthenticationConfiguration(), ): Promise { const tokenExtractor: JwtTokenExtractor = new JwtTokenExtractor( ToBotFromGovernmentChannelTokenValidationParameters, OpenIdMetadataEndpoint ? OpenIdMetadataEndpoint : GovernmentConstants.ToBotFromChannelOpenIdMetadataUrl, - AuthenticationConstants.AllowedSigningAlgorithms + AuthenticationConstants.AllowedSigningAlgorithms, ); const identity: ClaimsIdentity = await tokenExtractor.getIdentityFromAuthHeader( authHeader, channelId, - authConfig.requiredEndorsements + authConfig.requiredEndorsements, ); return await validateIdentity(identity, credentials); @@ -101,7 +101,7 @@ export namespace GovernmentChannelValidation { */ export async function validateIdentity( identity: ClaimsIdentity, - credentials: ICredentialProvider + credentials: ICredentialProvider, ): Promise { if (!identity) { // No valid identity. Not Authorized. @@ -134,7 +134,7 @@ export namespace GovernmentChannelValidation { // The AppId is not valid or not present. Not Authorized. throw new AuthenticationError( `Unauthorized. Invalid AppId passed on token: ${audClaim}`, - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } diff --git a/libraries/botframework-connector/src/auth/jwtTokenExtractor.ts b/libraries/botframework-connector/src/auth/jwtTokenExtractor.ts index 36a0d6f496..110c77ed19 100644 --- a/libraries/botframework-connector/src/auth/jwtTokenExtractor.ts +++ b/libraries/botframework-connector/src/auth/jwtTokenExtractor.ts @@ -39,7 +39,7 @@ export class JwtTokenExtractor { tokenValidationParameters: VerifyOptions, metadataUrl: string, allowedSigningAlgorithms: string[] | Algorithm[], - proxySettings?: ProxySettings + proxySettings?: ProxySettings, ) { this.tokenValidationParameters = { ...tokenValidationParameters }; this.tokenValidationParameters.algorithms = allowedSigningAlgorithms as Algorithm[]; @@ -67,7 +67,7 @@ export class JwtTokenExtractor { async getIdentityFromAuthHeader( authorizationHeader: string, channelId: string, - requiredEndorsements?: string[] + requiredEndorsements?: string[], ): Promise { if (!authorizationHeader) { return null; @@ -94,7 +94,7 @@ export class JwtTokenExtractor { scheme: string, parameter: string, channelId: string, - requiredEndorsements: string[] = [] + requiredEndorsements: string[] = [], ): Promise { // No header in correct scheme or no token if (scheme !== 'Bearer' || !parameter) { @@ -139,7 +139,7 @@ export class JwtTokenExtractor { private async validateToken( jwtToken: string, channelId: string, - requiredEndorsements: string[] + requiredEndorsements: string[], ): Promise { let header: Partial = {}; const decodedToken = decode(jwtToken, { complete: true }); @@ -169,21 +169,21 @@ export class JwtTokenExtractor { if (!isEndorsed) { throw new AuthenticationError( `Could not validate endorsement for key: ${keyId} with endorsements: ${endorsements.join(',')}`, - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } // Verify that additional endorsements are satisfied. If no additional endorsements are expected, the requirement is satisfied as well const additionalEndorsementsSatisfied = requiredEndorsements.every((endorsement) => - EndorsementsValidator.validate(endorsement, endorsements) + EndorsementsValidator.validate(endorsement, endorsements), ); if (!additionalEndorsementsSatisfied) { throw new AuthenticationError( `Could not validate additional endorsement for key: ${keyId} with endorsements: ${requiredEndorsements.join( - ',' + ',', )}. Expected endorsements: ${requiredEndorsements.join(',')}`, - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } } @@ -192,7 +192,7 @@ export class JwtTokenExtractor { if (this.tokenValidationParameters.algorithms.indexOf(header.alg as Algorithm) === -1) { throw new AuthenticationError( `"Token signing algorithm '${header.alg}' not in allowed list`, - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } } diff --git a/libraries/botframework-connector/src/auth/jwtTokenValidation.ts b/libraries/botframework-connector/src/auth/jwtTokenValidation.ts index 6cfa5977da..3b58821dc8 100644 --- a/libraries/botframework-connector/src/auth/jwtTokenValidation.ts +++ b/libraries/botframework-connector/src/auth/jwtTokenValidation.ts @@ -41,7 +41,7 @@ export namespace JwtTokenValidation { authHeader: string, credentials: ICredentialProvider, channelService: string, - authConfig?: AuthenticationConfiguration + authConfig?: AuthenticationConfiguration, ): Promise { if (!authConfig) { authConfig = new AuthenticationConfiguration(); @@ -53,7 +53,7 @@ export namespace JwtTokenValidation { if (!isAuthDisabled) { throw new AuthenticationError( 'Unauthorized Access. Request is not authorized', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -78,7 +78,7 @@ export namespace JwtTokenValidation { channelService, activity.channelId, activity.serviceUrl, - authConfig + authConfig, ); return claimsIdentity; @@ -101,7 +101,7 @@ export namespace JwtTokenValidation { channelService: string, channelId: string, serviceUrl = '', - authConfig: AuthenticationConfiguration = new AuthenticationConfiguration() + authConfig: AuthenticationConfiguration = new AuthenticationConfiguration(), ): Promise { if (!authHeader.trim()) { throw new AuthenticationError("'authHeader' required.", StatusCodes.BAD_REQUEST); @@ -113,7 +113,7 @@ export namespace JwtTokenValidation { channelService, channelId, authConfig, - serviceUrl + serviceUrl, ); await validateClaims(authConfig, identity.claims); @@ -121,14 +121,13 @@ export namespace JwtTokenValidation { return identity; } - // eslint-disable-next-line jsdoc/require-jsdoc, no-inner-declarations async function authenticateToken( authHeader: string, credentials: ICredentialProvider, channelService: string, channelId: string, authConfig: AuthenticationConfiguration, - serviceUrl: string + serviceUrl: string, ): Promise { if (AseChannelValidation.isTokenFromAseChannel(channelId)) { return AseChannelValidation.authenticateAseChannelToken(authHeader); @@ -140,7 +139,7 @@ export namespace JwtTokenValidation { credentials, channelService, channelId, - authConfig + authConfig, ); } @@ -149,7 +148,7 @@ export namespace JwtTokenValidation { authHeader, credentials, channelService, - channelId + channelId, ); } @@ -160,7 +159,7 @@ export namespace JwtTokenValidation { authHeader, credentials, serviceUrl, - channelId + channelId, ); } @@ -174,7 +173,7 @@ export namespace JwtTokenValidation { authHeader, credentials, serviceUrl, - channelId + channelId, ); } @@ -189,7 +188,7 @@ export namespace JwtTokenValidation { credentials, serviceUrl, channelId, - channelService + channelService, ); } @@ -197,7 +196,7 @@ export namespace JwtTokenValidation { authHeader, credentials, channelId, - channelService + channelService, ); } @@ -207,7 +206,7 @@ export namespace JwtTokenValidation { * @param authConfig The authentication configuration. * @param claims The list of claims to validate. */ - // eslint-disable-next-line no-inner-declarations + async function validateClaims(authConfig: AuthenticationConfiguration, claims: Claim[] = []): Promise { if (authConfig.validateClaims) { // Call the validation method if defined (it should throw an exception if the validation fails) @@ -216,7 +215,7 @@ export namespace JwtTokenValidation { // Skill claims must be validated using AuthenticationConfiguration validateClaims throw new AuthenticationError( 'Unauthorized Access. Request is not authorized. Skill Claims require validation.', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } } @@ -267,7 +266,6 @@ export namespace JwtTokenValidation { return appId; } - // eslint-disable-next-line jsdoc/require-jsdoc, no-inner-declarations function isPublicAzure(channelService: string): boolean { return !channelService || channelService.length === 0; } diff --git a/libraries/botframework-connector/src/auth/managedIdentityServiceClientCredentialsFactory.ts b/libraries/botframework-connector/src/auth/managedIdentityServiceClientCredentialsFactory.ts index 127b54b29e..73ad3a5589 100644 --- a/libraries/botframework-connector/src/auth/managedIdentityServiceClientCredentialsFactory.ts +++ b/libraries/botframework-connector/src/auth/managedIdentityServiceClientCredentialsFactory.ts @@ -30,7 +30,7 @@ export class ManagedIdentityServiceClientCredentialsFactory extends ServiceClien ok(appId?.trim(), 'ManagedIdentityServiceClientCredentialsFactory.constructor(): missing appId.'); ok( tokenProviderFactory, - 'ManagedIdentityServiceClientCredentialsFactory.constructor(): missing tokenProviderFactory.' + 'ManagedIdentityServiceClientCredentialsFactory.constructor(): missing tokenProviderFactory.', ); this.appId = appId; @@ -58,7 +58,7 @@ export class ManagedIdentityServiceClientCredentialsFactory extends ServiceClien async createCredentials(appId: string, audience: string): Promise { ok( await this.isValidAppId(appId), - 'ManagedIdentityServiceClientCredentialsFactory.createCredentials(): Invalid Managed ID.' + 'ManagedIdentityServiceClientCredentialsFactory.createCredentials(): Invalid Managed ID.', ); return new ManagedIdentityAppCredentials(this.appId, audience, this.tokenProviderFactory); diff --git a/libraries/botframework-connector/src/auth/microsoftAppCredentials.ts b/libraries/botframework-connector/src/auth/microsoftAppCredentials.ts index 314fff0bb5..b8915e0f42 100644 --- a/libraries/botframework-connector/src/auth/microsoftAppCredentials.ts +++ b/libraries/botframework-connector/src/auth/microsoftAppCredentials.ts @@ -27,13 +27,18 @@ export class MicrosoftAppCredentials extends AppCredentials { * @param {string} appId The Microsoft app ID. * @param {string} appPassword The Microsoft app password. * @param {string} channelAuthTenant Tenant ID of the Azure AD tenant where the bot is created. - * * Required for SingleTenant app types. - * * Optional for MultiTenant app types. **Note**: '_botframework.com_' is the default tenant when no value is provided. + * - Required for SingleTenant app types. + * - Optional for MultiTenant app types. **Note**: '_botframework.com_' is the default tenant when no value is provided. * * More information: https://learn.microsoft.com/en-us/security/zero-trust/develop/identity-supported-account-types. * @param {string} oAuthScope Optional. The scope for the token. */ - constructor(appId: string, public appPassword: string, channelAuthTenant?: string, oAuthScope?: string) { + constructor( + appId: string, + public appPassword: string, + channelAuthTenant?: string, + oAuthScope?: string, + ) { super(appId, channelAuthTenant, oAuthScope); } diff --git a/libraries/botframework-connector/src/auth/microsoftGovernmentAppCredentials.ts b/libraries/botframework-connector/src/auth/microsoftGovernmentAppCredentials.ts index 4eb51a887a..4c12b4603c 100644 --- a/libraries/botframework-connector/src/auth/microsoftGovernmentAppCredentials.ts +++ b/libraries/botframework-connector/src/auth/microsoftGovernmentAppCredentials.ts @@ -21,7 +21,12 @@ export class MicrosoftGovernmentAppCredentials extends MicrosoftAppCredentials { * @param {string} channelAuthTenant Optional. The oauth token tenant. * @param {string} oAuthScope Optional. The scope for the token. */ - constructor(appId: string, public appPassword: string, channelAuthTenant?: string, oAuthScope?: string) { + constructor( + appId: string, + public appPassword: string, + channelAuthTenant?: string, + oAuthScope?: string, + ) { super(appId, appPassword, channelAuthTenant, oAuthScope); } diff --git a/libraries/botframework-connector/src/auth/msalAppCredentials.ts b/libraries/botframework-connector/src/auth/msalAppCredentials.ts index daed8ad0ff..91b62e62fd 100644 --- a/libraries/botframework-connector/src/auth/msalAppCredentials.ts +++ b/libraries/botframework-connector/src/auth/msalAppCredentials.ts @@ -64,14 +64,14 @@ export class MsalAppCredentials extends AppCredentials { maybeClientApplicationOrAppId?: ConfidentialClientApplication | string, maybeAppIdOrAppPasswordOrCertificate?: string | Certificate, maybeAuthority?: string, - maybeScope?: string + maybeScope?: string, ) { const appId = typeof maybeClientApplicationOrAppId === 'string' ? maybeClientApplicationOrAppId : typeof maybeAppIdOrAppPasswordOrCertificate === 'string' - ? maybeAppIdOrAppPasswordOrCertificate - : undefined; + ? maybeAppIdOrAppPasswordOrCertificate + : undefined; super(appId, undefined, maybeScope); diff --git a/libraries/botframework-connector/src/auth/msalServiceClientCredentialsFactory.ts b/libraries/botframework-connector/src/auth/msalServiceClientCredentialsFactory.ts index 997915d4c7..f97522f278 100644 --- a/libraries/botframework-connector/src/auth/msalServiceClientCredentialsFactory.ts +++ b/libraries/botframework-connector/src/auth/msalServiceClientCredentialsFactory.ts @@ -24,7 +24,10 @@ export class MsalServiceClientCredentialsFactory implements ServiceClientCredent * @param appId App ID for validation. * @param clientApplication An `@azure/msal-node` `ConfidentialClientApplication` instance. */ - constructor(appId: string, private readonly clientApplication: ConfidentialClientApplication) { + constructor( + appId: string, + private readonly clientApplication: ConfidentialClientApplication, + ) { this.appId = appId; } @@ -49,7 +52,7 @@ export class MsalServiceClientCredentialsFactory implements ServiceClientCredent appId: string, audience: string, loginEndpoint: string, - _validateAuthority: boolean + _validateAuthority: boolean, ): Promise { if (await this.isAuthenticationDisabled()) { return MsalAppCredentials.Empty; @@ -66,7 +69,7 @@ export class MsalServiceClientCredentialsFactory implements ServiceClientCredent this.clientApplication, appId, undefined, - audience || AuthenticationConstants.ToBotFromChannelTokenIssuer + audience || AuthenticationConstants.ToBotFromChannelTokenIssuer, ); } @@ -75,7 +78,7 @@ export class MsalServiceClientCredentialsFactory implements ServiceClientCredent this.clientApplication, appId, undefined, - audience || GovernmentConstants.ToChannelFromBotOAuthScope + audience || GovernmentConstants.ToChannelFromBotOAuthScope, ); } diff --git a/libraries/botframework-connector/src/auth/openIdMetadata.ts b/libraries/botframework-connector/src/auth/openIdMetadata.ts index e926dd9e4a..5abbe8ace3 100644 --- a/libraries/botframework-connector/src/auth/openIdMetadata.ts +++ b/libraries/botframework-connector/src/auth/openIdMetadata.ts @@ -27,7 +27,10 @@ export class OpenIdMetadata { * @param url Metadata Url. * @param proxySettings The proxy settings for the request. */ - constructor(private url: string, private proxySettings?: ProxySettings) {} + constructor( + private url: string, + private proxySettings?: ProxySettings, + ) {} /** * Gets the Signing key. @@ -76,13 +79,13 @@ export class OpenIdMetadata { } else { throw new AuthenticationError( `Failed to load Keys: ${getKeyResponse.status}`, - StatusCodes.INTERNAL_SERVER_ERROR + StatusCodes.INTERNAL_SERVER_ERROR, ); } } else { throw new AuthenticationError( `Failed to load openID config: ${res.status}`, - StatusCodes.INTERNAL_SERVER_ERROR + StatusCodes.INTERNAL_SERVER_ERROR, ); } } diff --git a/libraries/botframework-connector/src/auth/parameterizedBotFrameworkAuthentication.ts b/libraries/botframework-connector/src/auth/parameterizedBotFrameworkAuthentication.ts index bbfee0ee6a..4b5ddb5288 100644 --- a/libraries/botframework-connector/src/auth/parameterizedBotFrameworkAuthentication.ts +++ b/libraries/botframework-connector/src/auth/parameterizedBotFrameworkAuthentication.ts @@ -66,7 +66,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent private readonly credentialsFactory: ServiceClientCredentialsFactory, private readonly authConfiguration: AuthenticationConfiguration, private readonly botFrameworkClientFetch?: (input: RequestInfo, init?: RequestInit) => Promise, - private readonly connectorClientOptions: ConnectorClientOptions = {} + private readonly connectorClientOptions: ConnectorClientOptions = {}, ) { super(); } @@ -90,7 +90,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent if (!isAuthDisabled) { throw new AuthenticationError( 'Unauthorized Access. Request is not authorized', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -125,7 +125,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent this.toChannelFromBotLoginUrl, this.validateAuthority, this.credentialsFactory, - this.connectorClientOptions + this.connectorClientOptions, ); return { @@ -145,7 +145,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent */ async authenticateStreamingRequest( authHeader: string, - channelIdHeader: string + channelIdHeader: string, ): Promise { if (!channelIdHeader?.trim() && !(await this.credentialsFactory.isAuthenticationDisabled())) { throw new AuthenticationError("'channelIdHeader' required.", StatusCodes.UNAUTHORIZED); @@ -172,7 +172,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent appId, this.toChannelFromBotOAuthScope, this.toChannelFromBotLoginUrl, - this.validateAuthority + this.validateAuthority, ); return new UserTokenClientImpl(appId, credentials, this.oAuthUrl, this.connectorClientOptions); @@ -191,7 +191,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent this.toChannelFromBotLoginUrl, this.validateAuthority, this.credentialsFactory, - this.connectorClientOptions + this.connectorClientOptions, ); } @@ -205,20 +205,20 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent this.credentialsFactory, this.toChannelFromBotLoginUrl, this.botFrameworkClientFetch, - this.connectorClientOptions + this.connectorClientOptions, ); } private async JwtTokenValidation_authenticateRequest( activity: Partial, - authHeader: string + authHeader: string, ): Promise { if (!authHeader.trim()) { const isAuthDisabled = await this.credentialsFactory.isAuthenticationDisabled(); if (!isAuthDisabled) { throw new AuthenticationError( 'Unauthorized Access. Request is not authorized', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -236,7 +236,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent const claimsIdentity: ClaimsIdentity = await this.JwtTokenValidation_validateAuthHeader( authHeader, activity.channelId, - activity.serviceUrl + activity.serviceUrl, ); return claimsIdentity; @@ -245,7 +245,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent private async JwtTokenValidation_validateAuthHeader( authHeader: string, channelId: string, - serviceUrl = '' + serviceUrl = '', ): Promise { const identity = await this.JwtTokenValidation_authenticateToken(authHeader, channelId, serviceUrl); @@ -262,7 +262,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent // Skill claims must be validated using AuthenticationConfiguration validateClaims throw new AuthenticationError( 'Unauthorized Access. Request is not authorized. Skill Claims require validation.', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } } @@ -270,7 +270,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent private async JwtTokenValidation_authenticateToken( authHeader: string, channelId: string, - serviceUrl: string + serviceUrl: string, ): Promise { if (AseChannelValidation.isTokenFromAseChannel(channelId)) { return AseChannelValidation.authenticateAseChannelToken(authHeader); @@ -290,7 +290,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent private async SkillValidation_authenticateChannelToken( authHeader: string, - channelId: string + channelId: string, ): Promise { // Add allowed token issuers from configuration. const verifyOptions: VerifyOptions = { @@ -305,7 +305,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent verifyOptions, this.toBotFromEmulatorOpenIdMetadataUrl, AuthenticationConstants.AllowedSigningAlgorithms, - this.connectorClientOptions?.proxySettings + this.connectorClientOptions?.proxySettings, ); const parts: string[] = authHeader.split(' '); @@ -313,7 +313,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent parts[0], parts[1], channelId, - this.authConfiguration.requiredEndorsements + this.authConfiguration.requiredEndorsements, ); await this.SkillValidation_ValidateIdentity(identity); @@ -326,7 +326,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent // No valid identity. Not Authorized. throw new AuthenticationError( 'SkillValidation.validateIdentity(): Invalid identity', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -334,7 +334,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent // The token is in some way invalid. Not Authorized. throw new AuthenticationError( 'SkillValidation.validateIdentity(): Token not authenticated', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -343,7 +343,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent // No version claim throw new AuthenticationError( `SkillValidation.validateIdentity(): '${AuthenticationConstants.VersionClaim}' claim is required on skill Tokens.`, - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -353,7 +353,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent // Claim is not present or doesn't have a value. Not Authorized. throw new AuthenticationError( `SkillValidation.validateIdentity(): '${AuthenticationConstants.AudienceClaim}' claim is required on skill Tokens.`, - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -361,7 +361,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent // The AppId is not valid. Not Authorized. throw new AuthenticationError( 'SkillValidation.validateIdentity(): Invalid audience.', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -370,14 +370,14 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent // Invalid appId throw new AuthenticationError( 'SkillValidation.validateIdentity(): Invalid appId.', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } } private async EmulatorValidation_authenticateEmulatorToken( authHeader: string, - channelId: string + channelId: string, ): Promise { // Add allowed token issuers from configuration. const verifyOptions: VerifyOptions = { @@ -392,13 +392,13 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent verifyOptions, this.toBotFromEmulatorOpenIdMetadataUrl, AuthenticationConstants.AllowedSigningAlgorithms, - this.connectorClientOptions?.proxySettings + this.connectorClientOptions?.proxySettings, ); const identity: ClaimsIdentity = await tokenExtractor.getIdentityFromAuthHeader( authHeader, channelId, - this.authConfiguration.requiredEndorsements + this.authConfiguration.requiredEndorsements, ); if (!identity) { // No valid identity. Not Authorized. @@ -418,7 +418,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent if (versionClaim === null) { throw new AuthenticationError( 'Unauthorized. "ver" claim is required on Emulator Tokens.', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -434,7 +434,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent // No claim around AppID. Not Authorized. throw new AuthenticationError( 'Unauthorized. "appid" claim is required on Emulator Token version "1.0".', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -446,7 +446,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent // No claim around AppID. Not Authorized. throw new AuthenticationError( 'Unauthorized. "azp" claim is required on Emulator Token version "2.0".', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -455,14 +455,14 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent // Unknown Version. Not Authorized. throw new AuthenticationError( `Unauthorized. Unknown Emulator Token version "${versionClaim}".`, - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } if (!(await this.credentialsFactory.isValidAppId(appId))) { throw new AuthenticationError( `Unauthorized. Invalid AppId passed on token: ${appId}`, - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -472,20 +472,20 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent private async ChannelValidation_authenticateChannelToken( authHeader: string, serviceUrl: string, - channelId: string + channelId: string, ): Promise { const tokenValidationParameters = this.ChannelValidation_GetTokenValidationParameters(); const tokenExtractor: JwtTokenExtractor = new JwtTokenExtractor( tokenValidationParameters, this.toBotFromChannelOpenIdMetadataUrl, AuthenticationConstants.AllowedSigningAlgorithms, - this.connectorClientOptions?.proxySettings + this.connectorClientOptions?.proxySettings, ); const identity: ClaimsIdentity = await tokenExtractor.getIdentityFromAuthHeader( authHeader, channelId, - this.authConfiguration.requiredEndorsements + this.authConfiguration.requiredEndorsements, ); return this.governmentChannelValidation_ValidateIdentity(identity, serviceUrl); @@ -502,7 +502,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent private async governmentChannelValidation_ValidateIdentity( identity: ClaimsIdentity, - serviceUrl: string + serviceUrl: string, ): Promise { if (!identity) { // No valid identity. Not Authorized. @@ -532,7 +532,7 @@ export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthent // The AppId is not valid or not present. Not Authorized. throw new AuthenticationError( `Unauthorized. Invalid AppId passed on token: ${audClaim}`, - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } diff --git a/libraries/botframework-connector/src/auth/passwordServiceClientCredentialFactory.ts b/libraries/botframework-connector/src/auth/passwordServiceClientCredentialFactory.ts index 2584bbcbd6..ce6659821a 100644 --- a/libraries/botframework-connector/src/auth/passwordServiceClientCredentialFactory.ts +++ b/libraries/botframework-connector/src/auth/passwordServiceClientCredentialFactory.ts @@ -53,8 +53,8 @@ export class PasswordServiceClientCredentialFactory implements ServiceClientCred * @param appId The app ID. * @param password The app password. * @param tenantId Tenant ID of the Azure AD tenant where the bot is created. - * * Required for SingleTenant app types. - * * Optional for MultiTenant app types. **Note**: '_botframework.com_' is the default tenant when no value is provided. + * - Required for SingleTenant app types. + * - Optional for MultiTenant app types. **Note**: '_botframework.com_' is the default tenant when no value is provided. * * More information: https://learn.microsoft.com/en-us/security/zero-trust/develop/identity-supported-account-types. */ @@ -101,7 +101,7 @@ export class PasswordServiceClientCredentialFactory implements ServiceClientCred appId: string, audience: string, loginEndpoint: string, - validateAuthority: boolean + validateAuthority: boolean, ): Promise { if (await this.isAuthenticationDisabled()) { return MicrosoftAppCredentials.Empty; @@ -125,7 +125,7 @@ export class PasswordServiceClientCredentialFactory implements ServiceClientCred this.tenantId, audience, normalizedEndpoint, - validateAuthority + validateAuthority, ); } return credentials; @@ -142,7 +142,7 @@ class PrivateCloudAppCredentials extends MicrosoftAppCredentials { tenantId: string, oAuthScope: string, oAuthEndpoint: string, - validateAuthority: boolean + validateAuthority: boolean, ) { super(appId, password, tenantId, oAuthScope); this.oAuthEndpoint = oAuthEndpoint; diff --git a/libraries/botframework-connector/src/auth/serviceClientCredentialsFactory.ts b/libraries/botframework-connector/src/auth/serviceClientCredentialsFactory.ts index f790d97a21..647a1c3e14 100644 --- a/libraries/botframework-connector/src/auth/serviceClientCredentialsFactory.ts +++ b/libraries/botframework-connector/src/auth/serviceClientCredentialsFactory.ts @@ -39,6 +39,6 @@ export abstract class ServiceClientCredentialsFactory { appId: string, audience: string | undefined, loginEndpoint: string, - validateAuthority: boolean + validateAuthority: boolean, ): Promise; } diff --git a/libraries/botframework-connector/src/auth/skillValidation.ts b/libraries/botframework-connector/src/auth/skillValidation.ts index eb025b8232..c77fa0ff9e 100644 --- a/libraries/botframework-connector/src/auth/skillValidation.ts +++ b/libraries/botframework-connector/src/auth/skillValidation.ts @@ -124,12 +124,12 @@ export namespace SkillValidation { credentials: ICredentialProvider, channelService: string, channelId: string, - authConfig: AuthenticationConfiguration + authConfig: AuthenticationConfiguration, ): Promise { if (!authConfig) { throw new AuthenticationError( 'SkillValidation.authenticateChannelToken(): invalid authConfig parameter', - StatusCodes.INTERNAL_SERVER_ERROR + StatusCodes.INTERNAL_SERVER_ERROR, ); } @@ -149,7 +149,7 @@ export namespace SkillValidation { const tokenExtractor = new JwtTokenExtractor( verifyOptions, openIdMetadataUrl, - AuthenticationConstants.AllowedSigningAlgorithms + AuthenticationConstants.AllowedSigningAlgorithms, ); const parts: string[] = authHeader.split(' '); @@ -157,7 +157,7 @@ export namespace SkillValidation { parts[0], parts[1], channelId, - authConfig.requiredEndorsements + authConfig.requiredEndorsements, ); await validateIdentity(identity, credentials); @@ -176,7 +176,7 @@ export namespace SkillValidation { // No valid identity. Not Authorized. throw new AuthenticationError( 'SkillValidation.validateIdentity(): Invalid identity', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -184,7 +184,7 @@ export namespace SkillValidation { // The token is in some way invalid. Not Authorized. throw new AuthenticationError( 'SkillValidation.validateIdentity(): Token not authenticated', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -194,7 +194,7 @@ export namespace SkillValidation { // No version claim throw new AuthenticationError( `SkillValidation.validateIdentity(): '${AuthenticationConstants.VersionClaim}' claim is required on skill Tokens.`, - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -204,7 +204,7 @@ export namespace SkillValidation { // Claim is not present or doesn't have a value. Not Authorized. throw new AuthenticationError( `SkillValidation.validateIdentity(): '${AuthenticationConstants.AudienceClaim}' claim is required on skill Tokens.`, - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -212,7 +212,7 @@ export namespace SkillValidation { // The AppId is not valid. Not Authorized. throw new AuthenticationError( 'SkillValidation.validateIdentity(): Invalid audience.', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -221,7 +221,7 @@ export namespace SkillValidation { // Invalid appId throw new AuthenticationError( 'SkillValidation.validateIdentity(): Invalid appId.', - StatusCodes.UNAUTHORIZED + StatusCodes.UNAUTHORIZED, ); } @@ -244,7 +244,7 @@ export namespace SkillValidation { value: AuthenticationConstants.AnonymousSkillAppId, }, ], - AuthenticationConstants.AnonymousAuthType + AuthenticationConstants.AnonymousAuthType, ); } } diff --git a/libraries/botframework-connector/src/auth/userTokenClient.ts b/libraries/botframework-connector/src/auth/userTokenClient.ts index e967f7cc2c..eaa2d27364 100644 --- a/libraries/botframework-connector/src/auth/userTokenClient.ts +++ b/libraries/botframework-connector/src/auth/userTokenClient.ts @@ -30,7 +30,7 @@ export abstract class UserTokenClient { userId: string, connectionName: string, channelId: string, - magicCode: string + magicCode: string, ): Promise; /** @@ -44,7 +44,7 @@ export abstract class UserTokenClient { abstract getSignInResource( connectionName: string, activity: Activity, - finalRediect: string + finalRediect: string, ): Promise; /** @@ -79,7 +79,7 @@ export abstract class UserTokenClient { userId: string, connectionName: string, resourceUrls: string[], - channelId: string + channelId: string, ): Promise>; /** @@ -95,7 +95,7 @@ export abstract class UserTokenClient { userId: string, connectionName: string, channelId: string, - exchangeRequest: TokenExchangeRequest + exchangeRequest: TokenExchangeRequest, ): Promise; /** diff --git a/libraries/botframework-connector/src/auth/userTokenClientImpl.ts b/libraries/botframework-connector/src/auth/userTokenClientImpl.ts index 7946648ee1..4cca62fd67 100644 --- a/libraries/botframework-connector/src/auth/userTokenClientImpl.ts +++ b/libraries/botframework-connector/src/auth/userTokenClientImpl.ts @@ -24,12 +24,12 @@ export class UserTokenClientImpl extends UserTokenClient { private readonly appId: string, credentials: ServiceClientCredentials, oauthEndpoint: string, - connectorClientOptions: ConnectorClientOptions = {} + connectorClientOptions: ConnectorClientOptions = {}, ) { super(); this.client = new TokenApiClient( credentials, - Object.assign({ baseUri: oauthEndpoint }, connectorClientOptions) + Object.assign({ baseUri: oauthEndpoint }, connectorClientOptions), ); } @@ -46,7 +46,7 @@ export class UserTokenClientImpl extends UserTokenClient { userId: string, connectionName: string, channelId: string, - magicCode: string + magicCode: string, ): Promise { z.object({ userId: z.string(), @@ -73,7 +73,7 @@ export class UserTokenClientImpl extends UserTokenClient { async getSignInResource( connectionName: string, activity: Activity, - finalRedirect: string + finalRedirect: string, ): Promise { z.object({ activity: z.record(z.unknown()), @@ -85,7 +85,7 @@ export class UserTokenClientImpl extends UserTokenClient { const result = await this.client.botSignIn.getSignInResource( UserTokenClient.createTokenExchangeState(this.appId, connectionName, activity), - { finalRedirect } + { finalRedirect }, ); return result._response.parsedBody; @@ -149,7 +149,7 @@ export class UserTokenClientImpl extends UserTokenClient { userId: string, connectionName: string, resourceUrls: string[], - channelId: string + channelId: string, ): Promise> { z.object({ userId: z.string(), @@ -165,7 +165,7 @@ export class UserTokenClientImpl extends UserTokenClient { userId, connectionName, { resourceUrls }, - { channelId } + { channelId }, ); return result._response.parsedBody as Record; } @@ -183,7 +183,7 @@ export class UserTokenClientImpl extends UserTokenClient { userId: string, connectionName: string, channelId: string, - exchangeRequest: TokenExchangeRequest + exchangeRequest: TokenExchangeRequest, ): Promise { z.object({ userId: z.string(), diff --git a/libraries/botframework-connector/src/emulatorApiClient.ts b/libraries/botframework-connector/src/emulatorApiClient.ts index 1209b677d4..4d14d26d08 100644 --- a/libraries/botframework-connector/src/emulatorApiClient.ts +++ b/libraries/botframework-connector/src/emulatorApiClient.ts @@ -26,7 +26,7 @@ export class EmulatorApiClient { static async emulateOAuthCards( credentials: AppCredentials, emulatorUrl: string, - emulate: boolean + emulate: boolean, ): Promise { const token = await credentials.getToken(); const requestUrl: string = diff --git a/libraries/botframework-connector/src/skills/botFrameworkClient.ts b/libraries/botframework-connector/src/skills/botFrameworkClient.ts index 75acc017a5..ec9eff4a78 100644 --- a/libraries/botframework-connector/src/skills/botFrameworkClient.ts +++ b/libraries/botframework-connector/src/skills/botFrameworkClient.ts @@ -14,13 +14,12 @@ export interface BotFrameworkClient { * @param conversationId A conversation ID to use for the conversation with the skill. * @param activity Activity to forward. */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any postActivity: ( fromBotId: string, toBotId: string, toUrl: string, serviceUrl: string, conversationId: string, - activity: Activity + activity: Activity, ) => Promise>; } diff --git a/libraries/botframework-connector/src/teams/models/index.ts b/libraries/botframework-connector/src/teams/models/index.ts index 5981690659..d2feef3fe3 100644 --- a/libraries/botframework-connector/src/teams/models/index.ts +++ b/libraries/botframework-connector/src/teams/models/index.ts @@ -18,7 +18,7 @@ import { /** * @interface * An interface representing TeamsConnectorClientOptions. - * @extends ServiceClientOptions + * @augments ServiceClientOptions */ export interface TeamsConnectorClientOptions extends ServiceClientOptions { /** @@ -100,7 +100,7 @@ export type TeamsFetchMeetingParticipantResponse = TeamsMeetingParticipant & { * An interface representing TeamsFetchMeetingParticipantOptionalParams. * Optional Parameters. * - * @extends RequestOptionsBase + * @augments RequestOptionsBase */ export interface TeamsFetchMeetingParticipantOptionalParams extends RequestOptionsBase { /** diff --git a/libraries/botframework-connector/src/teams/retryAction.ts b/libraries/botframework-connector/src/teams/retryAction.ts index ee04c59f13..2bb2f7fea3 100644 --- a/libraries/botframework-connector/src/teams/retryAction.ts +++ b/libraries/botframework-connector/src/teams/retryAction.ts @@ -14,7 +14,7 @@ export async function retryAction( promise: (n: number) => Promise, maxRetries: number, - initialDelay = 500 + initialDelay = 500, ): Promise { let delay = initialDelay, n = 1; diff --git a/libraries/botframework-connector/src/teams/teamsConnectorClient.ts b/libraries/botframework-connector/src/teams/teamsConnectorClient.ts index dcfff5a484..fe943ce85d 100644 --- a/libraries/botframework-connector/src/teams/teamsConnectorClient.ts +++ b/libraries/botframework-connector/src/teams/teamsConnectorClient.ts @@ -9,6 +9,9 @@ import * as Mappers from './models/mappers'; import * as operations from './operations'; import { TeamsConnectorClientContext } from './teamsConnectorClientContext'; +/** + * Implements a client for the Teams Bot Connector service. + */ class TeamsConnectorClient extends TeamsConnectorClientContext { // Operation groups teams: operations.Teams; @@ -27,11 +30,6 @@ class TeamsConnectorClient extends TeamsConnectorClientContext { // Operation Specifications -export { - TeamsConnectorClient, - TeamsConnectorClientContext, - Models as TeamsConnectorModels, - Mappers as TeamsConnectorMappers, -}; +export { TeamsConnectorClient, Models as TeamsConnectorModels, Mappers as TeamsConnectorMappers }; export * from './operations'; diff --git a/libraries/botframework-connector/tests/appCredentials.test.js b/libraries/botframework-connector/tests/appCredentials.test.js index d8104402d9..9d10c0b3a6 100644 --- a/libraries/botframework-connector/tests/appCredentials.test.js +++ b/libraries/botframework-connector/tests/appCredentials.test.js @@ -20,7 +20,7 @@ describe('AppCredentials', function () { const certCreds = new CertificateAppCredentials(APP_ID, CERT_THUMBPRINT, CERT_KEY); strictEqual( certCreds.oAuthEndpoint, - AuthenticationConstants.ToChannelFromBotLoginUrlPrefix + AuthenticationConstants.DefaultChannelAuthTenant + AuthenticationConstants.ToChannelFromBotLoginUrlPrefix + AuthenticationConstants.DefaultChannelAuthTenant, ); strictEqual(certCreds.oAuthScope, AuthenticationConstants.ToBotFromChannelTokenIssuer); @@ -65,7 +65,7 @@ describe('AppCredentials', function () { const tokenGenerator = new MicrosoftAppCredentials(APP_ID); strictEqual( tokenGenerator.tokenCacheKey, - `${APP_ID}${AuthenticationConstants.ToBotFromChannelTokenIssuer}-cache` + `${APP_ID}${AuthenticationConstants.ToBotFromChannelTokenIssuer}-cache`, ); const oAuthScope = 'oAuthScope'; @@ -76,7 +76,7 @@ describe('AppCredentials', function () { const certCreds = new CertificateAppCredentials(APP_ID, CERT_THUMBPRINT, CERT_KEY); strictEqual( certCreds.tokenCacheKey, - `${APP_ID}${AuthenticationConstants.ToBotFromChannelTokenIssuer}-cache` + `${APP_ID}${AuthenticationConstants.ToBotFromChannelTokenIssuer}-cache`, ); certCreds.oAuthScope = oAuthScope; strictEqual(certCreds.tokenCacheKey, `${APP_ID}${oAuthScope}-cache`); diff --git a/libraries/botframework-connector/tests/auth/aseChannelValidation.test.js b/libraries/botframework-connector/tests/auth/aseChannelValidation.test.js index 5d2c167d1c..3017931adf 100644 --- a/libraries/botframework-connector/tests/auth/aseChannelValidation.test.js +++ b/libraries/botframework-connector/tests/auth/aseChannelValidation.test.js @@ -15,7 +15,7 @@ describe('AseChannelTestSuite', function () { AseChannelValidation.init(config); assert.strictEqual( AseChannelValidation.MetadataUrl, - GovernmentConstants.ToBotFromEmulatorOpenIdMetadataUrl + GovernmentConstants.ToBotFromEmulatorOpenIdMetadataUrl, ); }); @@ -24,7 +24,7 @@ describe('AseChannelTestSuite', function () { AseChannelValidation.init(config); assert.strictEqual( AseChannelValidation.MetadataUrl, - AuthenticationConstants.ToBotFromEmulatorOpenIdMetadataUrl + AuthenticationConstants.ToBotFromEmulatorOpenIdMetadataUrl, ); }); @@ -42,20 +42,20 @@ describe('AseChannelTestSuite', function () { assert.strictEqual( true, BetweenBotAndAseChannelTokenValidationParameters.issuer.includes( - `https://sts.windows.net/${tmpId}/` - ) + `https://sts.windows.net/${tmpId}/`, + ), ); assert.strictEqual( true, BetweenBotAndAseChannelTokenValidationParameters.issuer.includes( - `https://login.microsoftonline.com/${tmpId}/v2.0` - ) + `https://login.microsoftonline.com/${tmpId}/v2.0`, + ), ); assert.strictEqual( true, BetweenBotAndAseChannelTokenValidationParameters.issuer.includes( - `https://login.microsoftonline.us/${tmpId}/v2.0` - ) + `https://login.microsoftonline.us/${tmpId}/v2.0`, + ), ); }); }); diff --git a/libraries/botframework-connector/tests/auth/channelValidation.test.js b/libraries/botframework-connector/tests/auth/channelValidation.test.js index bca5a72810..774f581616 100644 --- a/libraries/botframework-connector/tests/auth/channelValidation.test.js +++ b/libraries/botframework-connector/tests/auth/channelValidation.test.js @@ -7,18 +7,19 @@ const { StatusCodes } = require('botframework-schema'); describe('ChannelValidation', function () { const credentials = new SimpleCredentialProvider('2cd87869-38a0-4182-9251-d056e8f0ac24', '2.30Vs3VQLKt974F'); + describe('validateIdentity', function () { it('should fail if unauthenticated', async function () { await assert.rejects( ChannelValidation.validateIdentity(new ClaimsIdentity([], false), undefined), - new AuthenticationError('Unauthorized. Is not authenticated', StatusCodes.UNAUTHORIZED) + new AuthenticationError('Unauthorized. Is not authenticated', StatusCodes.UNAUTHORIZED), ); }); it('should fail if no identity', async function () { await assert.rejects( ChannelValidation.validateIdentity(undefined, undefined), - new AuthenticationError('Unauthorized. Is not authenticated', StatusCodes.UNAUTHORIZED) + new AuthenticationError('Unauthorized. Is not authenticated', StatusCodes.UNAUTHORIZED), ); }); @@ -26,9 +27,9 @@ describe('ChannelValidation', function () { await assert.rejects( ChannelValidation.validateIdentity( new ClaimsIdentity([{ type: 'peanut', value: 'peanut' }], true), - credentials + credentials, ), - new AuthenticationError('Unauthorized. Issuer Claim MUST be present.', StatusCodes.UNAUTHORIZED) + new AuthenticationError('Unauthorized. Issuer Claim MUST be present.', StatusCodes.UNAUTHORIZED), ); }); @@ -36,9 +37,9 @@ describe('ChannelValidation', function () { await assert.rejects( ChannelValidation.validateIdentity( new ClaimsIdentity([{ type: 'iss', value: 'peanut' }], true), - credentials + credentials, ), - new AuthenticationError('Unauthorized. Issuer Claim MUST be present.', StatusCodes.UNAUTHORIZED) + new AuthenticationError('Unauthorized. Issuer Claim MUST be present.', StatusCodes.UNAUTHORIZED), ); }); @@ -46,9 +47,9 @@ describe('ChannelValidation', function () { await assert.rejects( ChannelValidation.validateIdentity( new ClaimsIdentity([{ type: 'iss', value: 'https://api.botframework.com' }], true), - credentials + credentials, ), - new AuthenticationError('Unauthorized. Invalid AppId passed on token: null', StatusCodes.UNAUTHORIZED) + new AuthenticationError('Unauthorized. Invalid AppId passed on token: null', StatusCodes.UNAUTHORIZED), ); }); @@ -60,11 +61,14 @@ describe('ChannelValidation', function () { { type: 'iss', value: 'https://api.botframework.com' }, { type: 'aud', value: 'peanut' }, ], - true + true, ), - credentials + credentials, + ), + new AuthenticationError( + 'Unauthorized. Invalid AppId passed on token: peanut', + StatusCodes.UNAUTHORIZED, ), - new AuthenticationError('Unauthorized. Invalid AppId passed on token: peanut', StatusCodes.UNAUTHORIZED) ); }); @@ -75,9 +79,9 @@ describe('ChannelValidation', function () { { type: 'iss', value: 'https://api.botframework.com' }, { type: 'aud', value: credentials.appId }, ], - true + true, ), - credentials + credentials, ); }); }); diff --git a/libraries/botframework-connector/tests/auth/enterpriseChannelValidation.test.js b/libraries/botframework-connector/tests/auth/enterpriseChannelValidation.test.js index d3fb98518b..7b8e50e515 100644 --- a/libraries/botframework-connector/tests/auth/enterpriseChannelValidation.test.js +++ b/libraries/botframework-connector/tests/auth/enterpriseChannelValidation.test.js @@ -11,14 +11,14 @@ describe('EnterpriseChannelValidator', function () { it('validateIdentity should fail if unauthenticated', async function () { await assert.rejects( EnterpriseChannelValidation.validateIdentity(new ClaimsIdentity([], false), undefined), - new AuthenticationError('Unauthorized. Is not authenticated', StatusCodes.UNAUTHORIZED) + new AuthenticationError('Unauthorized. Is not authenticated', StatusCodes.UNAUTHORIZED), ); }); it('validateIdentity should fail if no identity', async function () { await assert.rejects( EnterpriseChannelValidation.validateIdentity(undefined, undefined), - new AuthenticationError('Unauthorized. No valid identity.', StatusCodes.UNAUTHORIZED) + new AuthenticationError('Unauthorized. No valid identity.', StatusCodes.UNAUTHORIZED), ); }); @@ -26,9 +26,9 @@ describe('EnterpriseChannelValidator', function () { await assert.rejects( EnterpriseChannelValidation.validateIdentity( new ClaimsIdentity([{ type: 'iss', value: 'peanut' }], true), - credentials + credentials, ), - new AuthenticationError('Unauthorized. Issuer Claim MUST be present.', StatusCodes.UNAUTHORIZED) + new AuthenticationError('Unauthorized. Issuer Claim MUST be present.', StatusCodes.UNAUTHORIZED), ); }); @@ -36,9 +36,9 @@ describe('EnterpriseChannelValidator', function () { await assert.rejects( EnterpriseChannelValidation.validateIdentity( new ClaimsIdentity([{ type: 'iss', value: 'https://api.botframework.com' }], true), - credentials + credentials, ), - new AuthenticationError('Unauthorized. Invalid AppId passed on token: null', StatusCodes.UNAUTHORIZED) + new AuthenticationError('Unauthorized. Invalid AppId passed on token: null', StatusCodes.UNAUTHORIZED), ); }); @@ -50,11 +50,11 @@ describe('EnterpriseChannelValidator', function () { { type: 'iss', value: 'https://api.botframework.com' }, { type: 'aud', value: 'peanut' }, ], - true + true, ), - credentials + credentials, ), - new AuthenticationError('Unauthorized. Invalid AppId passed on token: peanut', StatusCodes.UNAUTHORIZED) + new AuthenticationError('Unauthorized. Invalid AppId passed on token: peanut', StatusCodes.UNAUTHORIZED), ); }); @@ -65,9 +65,9 @@ describe('EnterpriseChannelValidator', function () { { type: 'iss', value: 'https://api.botframework.com' }, { type: 'aud', value: credentials.appId }, ], - true + true, ), - credentials + credentials, ); }); }); diff --git a/libraries/botframework-connector/tests/auth/governmentChannelValidation.test.js b/libraries/botframework-connector/tests/auth/governmentChannelValidation.test.js index a96ea65683..fcb67184a9 100644 --- a/libraries/botframework-connector/tests/auth/governmentChannelValidation.test.js +++ b/libraries/botframework-connector/tests/auth/governmentChannelValidation.test.js @@ -11,7 +11,7 @@ describe('GovernmentChannelValidator', function () { it('validateIdentity should fail if no identity', async function () { await assert.rejects( GovernmentChannelValidation.validateIdentity(new ClaimsIdentity([], false), undefined), - new AuthenticationError('Unauthorized. Is not authenticated', StatusCodes.UNAUTHORIZED) + new AuthenticationError('Unauthorized. Is not authenticated', StatusCodes.UNAUTHORIZED), ); }); @@ -19,9 +19,9 @@ describe('GovernmentChannelValidator', function () { await assert.rejects( GovernmentChannelValidation.validateIdentity( new ClaimsIdentity([{ type: 'iss', value: 'peanut' }], true), - credentials + credentials, ), - new AuthenticationError('Unauthorized. Issuer Claim MUST be present.', StatusCodes.UNAUTHORIZED) + new AuthenticationError('Unauthorized. Issuer Claim MUST be present.', StatusCodes.UNAUTHORIZED), ); }); @@ -29,9 +29,9 @@ describe('GovernmentChannelValidator', function () { await assert.rejects( GovernmentChannelValidation.validateIdentity( new ClaimsIdentity([{ type: 'iss', value: 'https://api.botframework.us' }], true), - credentials + credentials, ), - new AuthenticationError('Unauthorized. Invalid AppId passed on token: null', StatusCodes.UNAUTHORIZED) + new AuthenticationError('Unauthorized. Invalid AppId passed on token: null', StatusCodes.UNAUTHORIZED), ); }); @@ -43,11 +43,11 @@ describe('GovernmentChannelValidator', function () { { type: 'iss', value: 'https://api.botframework.us' }, { type: 'aud', value: 'peanut' }, ], - true + true, ), - credentials + credentials, ), - new AuthenticationError('Unauthorized. Invalid AppId passed on token: peanut', StatusCodes.UNAUTHORIZED) + new AuthenticationError('Unauthorized. Invalid AppId passed on token: peanut', StatusCodes.UNAUTHORIZED), ); }); @@ -58,9 +58,9 @@ describe('GovernmentChannelValidator', function () { { type: 'iss', value: 'https://api.botframework.us' }, { type: 'aud', value: credentials.appId }, ], - true + true, ), - credentials + credentials, ); }); }); diff --git a/libraries/botframework-connector/tests/auth/jwtTokenExtractor.test.js b/libraries/botframework-connector/tests/auth/jwtTokenExtractor.test.js index f1027ae85e..5873329cd7 100644 --- a/libraries/botframework-connector/tests/auth/jwtTokenExtractor.test.js +++ b/libraries/botframework-connector/tests/auth/jwtTokenExtractor.test.js @@ -17,7 +17,7 @@ describe('JwtTokenExtractor', function () { issuer, }, metadata, - [algorithm] + [algorithm], ); return { client, issuer, sign, verify }; @@ -52,7 +52,7 @@ describe('JwtTokenExtractor', function () { clockTolerance: -10, }, metadata, - [algorithm] + [algorithm], ); await assert.rejects(client.getIdentityFromAuthHeader(`Bearer ${token}`), { diff --git a/libraries/botframework-connector/tests/auth/jwtTokenValidation.test.js b/libraries/botframework-connector/tests/auth/jwtTokenValidation.test.js index 261f2a5742..bf43d66754 100644 --- a/libraries/botframework-connector/tests/auth/jwtTokenValidation.test.js +++ b/libraries/botframework-connector/tests/auth/jwtTokenValidation.test.js @@ -68,7 +68,7 @@ describe('JwtTokenValidation', function () { [AuthenticationConstants.ServiceUrlClaim]: activity.serviceUrl, [AuthenticationConstants.VersionClaim]: version, tid: tenant, - }) + }), ); const credentials = makeCredentials(appId, appPassword, tenant, token); @@ -82,7 +82,7 @@ describe('JwtTokenValidation', function () { activity, makeAuthHeader('Bearer', accessToken), provider, - channelService + channelService, ); // Assert expected results @@ -140,7 +140,7 @@ describe('JwtTokenValidation', function () { assert(claims.isAuthenticated); assert.strictEqual( claims.getClaimValue(AuthenticationConstants.ServiceUrlClaim), - 'https://service.url' + 'https://service.url', ); }, label: 'succeeds with a specific tenant', diff --git a/libraries/botframework-connector/tests/auth/microsoftAppCredentials.test.js b/libraries/botframework-connector/tests/auth/microsoftAppCredentials.test.js index 83ca0f8059..dc512e3334 100644 --- a/libraries/botframework-connector/tests/auth/microsoftAppCredentials.test.js +++ b/libraries/botframework-connector/tests/auth/microsoftAppCredentials.test.js @@ -7,7 +7,7 @@ describe('MicrosoftAppCredentialsTestSuite', function () { const credentials1 = new MicrosoftAppCredentials('appId', 'password', 'tenantId', 'audience'); assert.strictEqual( AuthenticationConstants.ToChannelFromBotLoginUrlPrefix + 'tenantId', - credentials1.oAuthEndpoint + credentials1.oAuthEndpoint, ); assert.strictEqual('audience', credentials1.oAuthScope); @@ -15,7 +15,7 @@ describe('MicrosoftAppCredentialsTestSuite', function () { assert.strictEqual( AuthenticationConstants.ToChannelFromBotLoginUrlPrefix + AuthenticationConstants.DefaultChannelAuthTenant, - credentials2.oAuthEndpoint + credentials2.oAuthEndpoint, ); assert.strictEqual(AuthenticationConstants.ToChannelFromBotOAuthScope, credentials2.oAuthScope); }); diff --git a/libraries/botframework-connector/tests/auth/microsoftGovernmentAppCredentials.test.js b/libraries/botframework-connector/tests/auth/microsoftGovernmentAppCredentials.test.js index 01e9b7b166..7a23cf674e 100644 --- a/libraries/botframework-connector/tests/auth/microsoftGovernmentAppCredentials.test.js +++ b/libraries/botframework-connector/tests/auth/microsoftGovernmentAppCredentials.test.js @@ -7,14 +7,14 @@ describe('MicrosoftGovernmentAppCredentialsTestSuite', function () { const credentials1 = new MicrosoftGovernmentAppCredentials('appId', 'password', 'tenantId', 'audience'); assert.strictEqual( GovernmentConstants.ToChannelFromBotLoginUrlPrefix + 'tenantId', - credentials1.oAuthEndpoint + credentials1.oAuthEndpoint, ); assert.strictEqual('audience', credentials1.oAuthScope); const credentials2 = new MicrosoftGovernmentAppCredentials('appId', 'password'); assert.strictEqual( GovernmentConstants.ToChannelFromBotLoginUrlPrefix + GovernmentConstants.DefaultChannelAuthTenant, - credentials2.oAuthEndpoint + credentials2.oAuthEndpoint, ); assert.strictEqual(GovernmentConstants.ToChannelFromBotOAuthScope, credentials2.oAuthScope); }); diff --git a/libraries/botframework-connector/tests/auth/userTokenClient.test.js b/libraries/botframework-connector/tests/auth/userTokenClient.test.js index 5b6a208235..bf71af8643 100644 --- a/libraries/botframework-connector/tests/auth/userTokenClient.test.js +++ b/libraries/botframework-connector/tests/auth/userTokenClient.test.js @@ -13,7 +13,7 @@ describe('UserTokenClient', function () { it(`should throw with null ${paramName}`, function () { assert.throws( () => UserTokenClient.createTokenExchangeState(...values), - (thrown) => thrown.message.includes(paramName) && thrown.message.includes('received null') + (thrown) => thrown.message.includes(paramName) && thrown.message.includes('received null'), ); }); }); diff --git a/libraries/botframework-connector/tests/botFrameworkAuthenticationFactory.test.js b/libraries/botframework-connector/tests/botFrameworkAuthenticationFactory.test.js index 44090d10ee..90aae41a99 100644 --- a/libraries/botframework-connector/tests/botFrameworkAuthenticationFactory.test.js +++ b/libraries/botframework-connector/tests/botFrameworkAuthenticationFactory.test.js @@ -30,7 +30,7 @@ describe('BotFrameworkAuthenticationFactory', function () { it('should throw with an unknown channel service', function () { assert.throws( () => BotFrameworkAuthenticationFactory.create('unknown'), - new Error('The provided ChannelService value is not supported.') + new Error('The provided ChannelService value is not supported.'), ); }); @@ -66,7 +66,7 @@ describe('BotFrameworkAuthenticationFactory', function () { undefined, undefined, credsFactory, - { requiredEndorsements: [] } + { requiredEndorsements: [] }, ); assert.strictEqual(pBFA.getOriginatingAudience(), AuthenticationConstants.ToChannelFromBotOAuthScope); assert.strictEqual(pBFA.credentialsFactory, credsFactory); @@ -85,7 +85,7 @@ describe('BotFrameworkAuthenticationFactory', function () { // If authentication was enabled 'UnusedAudienceWhenAuthIsDisabled' would have been used, but is unnecessary with disabled authentication. assert.strictEqual( connectorClient.credentials.oAuthScope, - AuthenticationConstants.ToChannelFromBotOAuthScope + AuthenticationConstants.ToChannelFromBotOAuthScope, ); const userTokenClient = await pBFA.createUserTokenClient(claimsIdentity); @@ -107,7 +107,7 @@ describe('BotFrameworkAuthenticationFactory', function () { undefined, undefined, credsFactory, - { requiredEndorsements: [] } + { requiredEndorsements: [] }, ); assert.strictEqual(pBFA.getOriginatingAudience(), AuthenticationConstants.ToChannelFromBotOAuthScope); assert.strictEqual(pBFA.credentialsFactory, credsFactory); diff --git a/libraries/botframework-connector/tests/connector.test.js b/libraries/botframework-connector/tests/connector.test.js index 3de6c0be18..ed8c9bed09 100644 --- a/libraries/botframework-connector/tests/connector.test.js +++ b/libraries/botframework-connector/tests/connector.test.js @@ -136,6 +136,7 @@ describe('Bot Framework Connector SDK', function () { message: 'Invalid userId: invalid-id', }); }); + it('should fail without members', async function () { const params = createConversation(); params.members = []; @@ -145,6 +146,7 @@ describe('Bot Framework Connector SDK', function () { message: 'Conversations must be to a single member', }); }); + it('should fail with bot member', async function () { const params = createConversation(); params.members = [bot]; @@ -164,6 +166,7 @@ describe('Bot Framework Connector SDK', function () { const members = await client.conversations.getConversationMembers(result.id); members.should.matchAny((member) => member.id === user.id); }); + it('should fail with invalid conversationId', async function () { const params = createConversation(); @@ -173,7 +176,7 @@ describe('Bot Framework Connector SDK', function () { { code: 'BadArgument', message: 'Slack API error', - } + }, ); }); }); @@ -186,6 +189,7 @@ describe('Bot Framework Connector SDK', function () { const result2 = await client.conversations.sendToConversation(result.id, createActivity()); assert(!!result2.id); }); + it('should return a valid activityId with Teams activity', async function () { const params = createConversation(); const activity = createActivity(); @@ -212,6 +216,7 @@ describe('Bot Framework Connector SDK', function () { const result2 = await client.conversations.sendToConversation(result.id, activity); assert(!!result2.id); }); + it('should fail with invalid conversationId', async function () { const params = createConversation(); @@ -221,9 +226,10 @@ describe('Bot Framework Connector SDK', function () { { code: 'BadArgument', message: 'Slack API error', - } + }, ); }); + it('should send a Hero card', async function () { const params = createConversation(); const activity = createActivity(); @@ -235,8 +241,7 @@ describe('Bot Framework Connector SDK', function () { subtitle: 'JPEG image', images: [ { - url: - 'https://docs.microsoft.com/en-us/bot-framework/media/designing-bots/core/dialogs-screens.png', + url: 'https://docs.microsoft.com/en-us/bot-framework/media/designing-bots/core/dialogs-screens.png', }, ], }, @@ -258,6 +263,7 @@ describe('Bot Framework Connector SDK', function () { const members = await client.conversations.getActivityMembers(result.id, result.activityId); members.should.matchAny((member) => member.id === user.id); }); + it('should fail with invalid conversationId', async function () { const params = createConversation(); params.activity = createActivity(); @@ -268,7 +274,7 @@ describe('Bot Framework Connector SDK', function () { { code: 'BadArgument', message: 'Slack API error', - } + }, ); }); }); @@ -285,6 +291,7 @@ describe('Bot Framework Connector SDK', function () { const result3 = await client.conversations.replyToActivity(conversationId, result2.id, reply); assert(!!result3.id); }); + it('should fail with invalid conversationId', async function () { const result = await client.conversations.createConversation(createConversation()); const result2 = await client.conversations.sendToConversation(result.id, createActivity()); @@ -293,7 +300,7 @@ describe('Bot Framework Connector SDK', function () { { code: 'ServiceError', message: 'Invalid ConversationId: invalid-id', - } + }, ); }); }); @@ -304,9 +311,10 @@ describe('Bot Framework Connector SDK', function () { conversation.activity = createActivity(); const result = await client.conversations.createConversation(conversation); await assert.doesNotReject( - async () => await client.conversations.deleteActivity(result.id, result.activityId) + async () => await client.conversations.deleteActivity(result.id, result.activityId), ); }); + it('should fail with invalid conversationId', async function () { const result = await client.conversations.createConversation(createConversation()); const result2 = await client.conversations.sendToConversation(result.id, createActivity()); @@ -329,6 +337,7 @@ describe('Bot Framework Connector SDK', function () { const result3 = await client.conversations.updateActivity(conversationId, result2.id, updatedActivity); assert(!!result3.id); }); + it('should fail with invalid conversationId', async function () { const result = await client.conversations.createConversation(createConversation()); const result2 = await client.conversations.sendToConversation(result.id, createActivity()); @@ -337,7 +346,7 @@ describe('Bot Framework Connector SDK', function () { { code: 'ServiceError', message: 'Invalid ConversationId: invalid-id', - } + }, ); }); }); @@ -379,6 +388,7 @@ describe('Bot Framework Connector SDK', function () { }); }); }); + describe('TokenApiClient', function () { describe('tokenApiClient Construction', function () { it('should not throw on http url', function () { @@ -387,6 +397,7 @@ describe('Bot Framework Connector SDK', function () { }); assert(client); }); + it('should throw on null credentials', function () { assert.throws( () => @@ -395,10 +406,11 @@ describe('Bot Framework Connector SDK', function () { }), { message: "'credentials' cannot be null.", - } + }, ); }); }); + describe('botSignIn', function () { it('should return a valid sign in url', async function () { const urlRegex = /https:\/\/token.botframework.com\/api\/oauth\/signin\?signin=.*/i; @@ -415,6 +427,7 @@ describe('Bot Framework Connector SDK', function () { assert(result._response.bodyAsText.match(urlRegex)); }); }); + describe('userToken', function () { describe('getToken', function () { it('should throw on null userId', async function () { @@ -422,15 +435,18 @@ describe('Bot Framework Connector SDK', function () { message: 'userId cannot be null', }); }); + it('should throw on null connectionName', async function () { await assert.rejects(async () => await tokenApiClient.userToken.getToken(user.id, null), { message: 'connectionName cannot be null', }); }); + it('should return null on invalid connection string', async function () { const result = await tokenApiClient.userToken.getToken(user.id, 'invalid'); assert.strictEqual(result.token, null); }); + it('should return token with no magic code', async function () { const result = await tokenApiClient.userToken.getToken(user.id, 'slack', { code: null }); assert(result.channelId); @@ -439,6 +455,7 @@ describe('Bot Framework Connector SDK', function () { assert(result.expiration); }); }); + describe('getAadTokens', function () { it('should throw on null userId', async function () { await assert.rejects( @@ -448,9 +465,10 @@ describe('Bot Framework Connector SDK', function () { }), { message: 'userId cannot be null', - } + }, ); }); + it('should throw on null connectionName', async function () { await assert.rejects( async () => @@ -459,9 +477,10 @@ describe('Bot Framework Connector SDK', function () { }), { message: 'connectionName cannot be null', - } + }, ); }); + it('should return token', async function () { const result = await tokenApiClient.userToken.getAadTokens(user.id, 'slack', { resourceUrls: ['http://localhost'], @@ -472,12 +491,14 @@ describe('Bot Framework Connector SDK', function () { assert(result.expiration); }); }); + describe('getTokenStatus', function () { it('should throw on null userId', async function () { await assert.rejects(async () => await tokenApiClient.userToken.getTokenStatus(null), { message: 'userId cannot be null', }); }); + it('should return token', async function () { const result = await tokenApiClient.userToken.getTokenStatus(user.id); assert(result.channelId); @@ -486,12 +507,14 @@ describe('Bot Framework Connector SDK', function () { assert(result.serviceProviderDisplayName); }); }); + describe('signOut', function () { it('should throw on null userId', async function () { await assert.rejects(async () => tokenApiClient.userToken.signOut(null), { message: 'userId cannot be null', }); }); + it('should return a response', async function () { const result = await tokenApiClient.userToken.signOut(user.id); assert(result.body); diff --git a/libraries/botframework-connector/tests/ms-rest-mappers-test.js b/libraries/botframework-connector/tests/ms-rest-mappers-test.js index 75261898b3..71393e56d8 100644 --- a/libraries/botframework-connector/tests/ms-rest-mappers-test.js +++ b/libraries/botframework-connector/tests/ms-rest-mappers-test.js @@ -6,6 +6,7 @@ const assert = require('assert'); describe('serialize', function () { const entity = [{ type: 'mention', keyone: 'valueOne', keytwo: { keythree: 'valueThree' } }]; const activity = { type: 'message', entities: entity }; + it('should retain custom Entity properties', function () { const serializedObject = serializer.serialize(Mappers.Activity, activity); assert.deepStrictEqual(serializedObject.entities, entity); diff --git a/libraries/botframework-connector/tests/passwordServiceClientCredentialFactory.test.js b/libraries/botframework-connector/tests/passwordServiceClientCredentialFactory.test.js index 508111f080..6089617305 100644 --- a/libraries/botframework-connector/tests/passwordServiceClientCredentialFactory.test.js +++ b/libraries/botframework-connector/tests/passwordServiceClientCredentialFactory.test.js @@ -47,7 +47,7 @@ describe('PasswordServiceClientCredentialFactory', function () { ]; const credentials = await Promise.all( - testArgs.map((args) => credFactory.createCredentials(args[0], args[1], args[2])) + testArgs.map((args) => credFactory.createCredentials(args[0], args[1], args[2])), ); credentials.forEach((cred, idx) => { // The PasswordServiceClientCredentialFactory generates subclasses of the AppCredentials class. diff --git a/libraries/botframework-connector/tests/skillValidation.test.js b/libraries/botframework-connector/tests/skillValidation.test.js index e2a86fc5bc..6ea5219427 100644 --- a/libraries/botframework-connector/tests/skillValidation.test.js +++ b/libraries/botframework-connector/tests/skillValidation.test.js @@ -22,7 +22,7 @@ describe('SkillValidation', function () { // No claims (falsy value) assert.throws( () => SkillValidation.isSkillClaim(), - new TypeError('SkillValidation.isSkillClaim(): missing claims.') + new TypeError('SkillValidation.isSkillClaim(): missing claims.'), ); // Empty list of claims @@ -71,55 +71,55 @@ describe('SkillValidation', function () { // No Authentication Scheme assert( !SkillValidation.isSkillToken( - 'ew0KICAiYWxnIjogIlJTMjU2IiwNCiAgImtpZCI6ICJKVzNFWGRudy13WTJFcUxyV1RxUTJyVWtCLWciLA0KICAieDV0IjogIkpXM0VYZG53LXdZMkVxTHJXVHFRMnJVa0ItZyIsDQogICJ0eXAiOiAiSldUIg0KfQ.ew0KICAic2VydmljZXVybCI6ICJodHRwczovL2RpcmVjdGxpbmUuYm90ZnJhbWV3b3JrLmNvbS8iLA0KICAibmJmIjogMTU3MTE5MDM0OCwNCiAgImV4cCI6IDE1NzExOTA5NDgsDQogICJpc3MiOiAiaHR0cHM6Ly9hcGkuYm90ZnJhbWV3b3JrLmNvbSIsDQogICJhdWQiOiAiNGMwMDM5ZTUtNjgxNi00OGU4LWIzMTMtZjc3NjkxZmYxYzVlIg0KfQ.cEVHmQCTjL9HVHGk91sja5CqjgvM7B-nArkOg4bE83m762S_le94--GBb0_7aAy6DCdvkZP0d4yWwbpfOkukEXixCDZQM2kWPcOo6lz_VIuXxHFlZAGrTvJ1QkBsg7vk-6_HR8XSLJQZoWrVhE-E_dPj4GPBKE6s1aNxYytzazbKRAEYa8Cn4iVtuYbuj4XfH8PMDv5aC0APNvfgTGk-BlIiP6AGdo4JYs62lUZVSAYg5VLdBcJYMYcKt-h2n1saeapFDVHx_tdpRuke42M4RpGH_wzICeWC5tTExWEkQWApU85HRA5zzk4OpTv17Ct13JCvQ7cD5x9RK5f7CMnbhQ' - ) + 'ew0KICAiYWxnIjogIlJTMjU2IiwNCiAgImtpZCI6ICJKVzNFWGRudy13WTJFcUxyV1RxUTJyVWtCLWciLA0KICAieDV0IjogIkpXM0VYZG53LXdZMkVxTHJXVHFRMnJVa0ItZyIsDQogICJ0eXAiOiAiSldUIg0KfQ.ew0KICAic2VydmljZXVybCI6ICJodHRwczovL2RpcmVjdGxpbmUuYm90ZnJhbWV3b3JrLmNvbS8iLA0KICAibmJmIjogMTU3MTE5MDM0OCwNCiAgImV4cCI6IDE1NzExOTA5NDgsDQogICJpc3MiOiAiaHR0cHM6Ly9hcGkuYm90ZnJhbWV3b3JrLmNvbSIsDQogICJhdWQiOiAiNGMwMDM5ZTUtNjgxNi00OGU4LWIzMTMtZjc3NjkxZmYxYzVlIg0KfQ.cEVHmQCTjL9HVHGk91sja5CqjgvM7B-nArkOg4bE83m762S_le94--GBb0_7aAy6DCdvkZP0d4yWwbpfOkukEXixCDZQM2kWPcOo6lz_VIuXxHFlZAGrTvJ1QkBsg7vk-6_HR8XSLJQZoWrVhE-E_dPj4GPBKE6s1aNxYytzazbKRAEYa8Cn4iVtuYbuj4XfH8PMDv5aC0APNvfgTGk-BlIiP6AGdo4JYs62lUZVSAYg5VLdBcJYMYcKt-h2n1saeapFDVHx_tdpRuke42M4RpGH_wzICeWC5tTExWEkQWApU85HRA5zzk4OpTv17Ct13JCvQ7cD5x9RK5f7CMnbhQ', + ), ); // Incorrect Authentication Scheme assert( !SkillValidation.isSkillToken( - 'Potato ew0KICAiYWxnIjogIlJTMjU2IiwNCiAgImtpZCI6ICJKVzNFWGRudy13WTJFcUxyV1RxUTJyVWtCLWciLA0KICAieDV0IjogIkpXM0VYZG53LXdZMkVxTHJXVHFRMnJVa0ItZyIsDQogICJ0eXAiOiAiSldUIg0KfQ.ew0KICAic2VydmljZXVybCI6ICJodHRwczovL2RpcmVjdGxpbmUuYm90ZnJhbWV3b3JrLmNvbS8iLA0KICAibmJmIjogMTU3MTE5MDM0OCwNCiAgImV4cCI6IDE1NzExOTA5NDgsDQogICJpc3MiOiAiaHR0cHM6Ly9hcGkuYm90ZnJhbWV3b3JrLmNvbSIsDQogICJhdWQiOiAiNGMwMDM5ZTUtNjgxNi00OGU4LWIzMTMtZjc3NjkxZmYxYzVlIg0KfQ.cEVHmQCTjL9HVHGk91sja5CqjgvM7B-nArkOg4bE83m762S_le94--GBb0_7aAy6DCdvkZP0d4yWwbpfOkukEXixCDZQM2kWPcOo6lz_VIuXxHFlZAGrTvJ1QkBsg7vk-6_HR8XSLJQZoWrVhE-E_dPj4GPBKE6s1aNxYytzazbKRAEYa8Cn4iVtuYbuj4XfH8PMDv5aC0APNvfgTGk-BlIiP6AGdo4JYs62lUZVSAYg5VLdBcJYMYcKt-h2n1saeapFDVHx_tdpRuke42M4RpGH_wzICeWC5tTExWEkQWApU85HRA5zzk4OpTv17Ct13JCvQ7cD5x9RK5f7CMnbhQ' - ) + 'Potato ew0KICAiYWxnIjogIlJTMjU2IiwNCiAgImtpZCI6ICJKVzNFWGRudy13WTJFcUxyV1RxUTJyVWtCLWciLA0KICAieDV0IjogIkpXM0VYZG53LXdZMkVxTHJXVHFRMnJVa0ItZyIsDQogICJ0eXAiOiAiSldUIg0KfQ.ew0KICAic2VydmljZXVybCI6ICJodHRwczovL2RpcmVjdGxpbmUuYm90ZnJhbWV3b3JrLmNvbS8iLA0KICAibmJmIjogMTU3MTE5MDM0OCwNCiAgImV4cCI6IDE1NzExOTA5NDgsDQogICJpc3MiOiAiaHR0cHM6Ly9hcGkuYm90ZnJhbWV3b3JrLmNvbSIsDQogICJhdWQiOiAiNGMwMDM5ZTUtNjgxNi00OGU4LWIzMTMtZjc3NjkxZmYxYzVlIg0KfQ.cEVHmQCTjL9HVHGk91sja5CqjgvM7B-nArkOg4bE83m762S_le94--GBb0_7aAy6DCdvkZP0d4yWwbpfOkukEXixCDZQM2kWPcOo6lz_VIuXxHFlZAGrTvJ1QkBsg7vk-6_HR8XSLJQZoWrVhE-E_dPj4GPBKE6s1aNxYytzazbKRAEYa8Cn4iVtuYbuj4XfH8PMDv5aC0APNvfgTGk-BlIiP6AGdo4JYs62lUZVSAYg5VLdBcJYMYcKt-h2n1saeapFDVHx_tdpRuke42M4RpGH_wzICeWC5tTExWEkQWApU85HRA5zzk4OpTv17Ct13JCvQ7cD5x9RK5f7CMnbhQ', + ), ); }); it('should fail for messages to bot from WebChat using version claim v2', function () { assert( !SkillValidation.isSkillToken( - 'Bearer ew0KICAiYWxnIjogIlJTMjU2IiwNCiAgImtpZCI6ICJKVzNFWGRudy13WTJFcUxyV1RxUTJyVWtCLWciLA0KICAieDV0IjogIkpXM0VYZG53LXdZMkVxTHJXVHFRMnJVa0ItZyIsDQogICJ0eXAiOiAiSldUIg0KfQ.ew0KICAic2VydmljZXVybCI6ICJodHRwczovL2RpcmVjdGxpbmUuYm90ZnJhbWV3b3JrLmNvbS8iLA0KICAibmJmIjogMTU3MTE5MDM0OCwNCiAgImV4cCI6IDE1NzExOTA5NDgsDQogICJpc3MiOiAiaHR0cHM6Ly9hcGkuYm90ZnJhbWV3b3JrLmNvbSIsDQogICJhdWQiOiAiNGMwMDM5ZTUtNjgxNi00OGU4LWIzMTMtZjc3NjkxZmYxYzVlIg0KfQ.cEVHmQCTjL9HVHGk91sja5CqjgvM7B-nArkOg4bE83m762S_le94--GBb0_7aAy6DCdvkZP0d4yWwbpfOkukEXixCDZQM2kWPcOo6lz_VIuXxHFlZAGrTvJ1QkBsg7vk-6_HR8XSLJQZoWrVhE-E_dPj4GPBKE6s1aNxYytzazbKRAEYa8Cn4iVtuYbuj4XfH8PMDv5aC0APNvfgTGk-BlIiP6AGdo4JYs62lUZVSAYg5VLdBcJYMYcKt-h2n1saeapFDVHx_tdpRuke42M4RpGH_wzICeWC5tTExWEkQWApU85HRA5zzk4OpTv17Ct13JCvQ7cD5x9RK5f7CMnbhQ' - ) + 'Bearer ew0KICAiYWxnIjogIlJTMjU2IiwNCiAgImtpZCI6ICJKVzNFWGRudy13WTJFcUxyV1RxUTJyVWtCLWciLA0KICAieDV0IjogIkpXM0VYZG53LXdZMkVxTHJXVHFRMnJVa0ItZyIsDQogICJ0eXAiOiAiSldUIg0KfQ.ew0KICAic2VydmljZXVybCI6ICJodHRwczovL2RpcmVjdGxpbmUuYm90ZnJhbWV3b3JrLmNvbS8iLA0KICAibmJmIjogMTU3MTE5MDM0OCwNCiAgImV4cCI6IDE1NzExOTA5NDgsDQogICJpc3MiOiAiaHR0cHM6Ly9hcGkuYm90ZnJhbWV3b3JrLmNvbSIsDQogICJhdWQiOiAiNGMwMDM5ZTUtNjgxNi00OGU4LWIzMTMtZjc3NjkxZmYxYzVlIg0KfQ.cEVHmQCTjL9HVHGk91sja5CqjgvM7B-nArkOg4bE83m762S_le94--GBb0_7aAy6DCdvkZP0d4yWwbpfOkukEXixCDZQM2kWPcOo6lz_VIuXxHFlZAGrTvJ1QkBsg7vk-6_HR8XSLJQZoWrVhE-E_dPj4GPBKE6s1aNxYytzazbKRAEYa8Cn4iVtuYbuj4XfH8PMDv5aC0APNvfgTGk-BlIiP6AGdo4JYs62lUZVSAYg5VLdBcJYMYcKt-h2n1saeapFDVHx_tdpRuke42M4RpGH_wzICeWC5tTExWEkQWApU85HRA5zzk4OpTv17Ct13JCvQ7cD5x9RK5f7CMnbhQ', + ), ); }); it('should fail for messages to bot from Emulator using version claim v1', function () { assert( !SkillValidation.isSkillToken( - 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImFQY3R3X29kdlJPb0VOZzNWb09sSWgydGlFcyIsImtpZCI6ImFQY3R3X29kdlJPb0VOZzNWb09sSWgydGlFcyJ9.eyJhdWQiOiI0YzMzYzQyMS1mN2QzLTRiNmMtOTkyYi0zNmU3ZTZkZTg3NjEiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC9kNmQ0OTQyMC1mMzliLTRkZjctYTFkYy1kNTlhOTM1ODcxZGIvIiwiaWF0IjoxNTcxMTg5ODczLCJuYmYiOjE1NzExODk4NzMsImV4cCI6MTU3MTE5Mzc3MywiYWlvIjoiNDJWZ1lLaWJGUDIyMUxmL0NjL1Yzai8zcGF2RUFBPT0iLCJhcHBpZCI6IjRjMzNjNDIxLWY3ZDMtNGI2Yy05OTJiLTM2ZTdlNmRlODc2MSIsImFwcGlkYWNyIjoiMSIsImlkcCI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0L2Q2ZDQ5NDIwLWYzOWItNGRmNy1hMWRjLWQ1OWE5MzU4NzFkYi8iLCJ0aWQiOiJkNmQ0OTQyMC1mMzliLTRkZjctYTFkYy1kNTlhOTM1ODcxZGIiLCJ1dGkiOiJOdXJ3bTVOQnkwR2duT3dKRnFVREFBIiwidmVyIjoiMS4wIn0.GcKs3XZ_4GONVsAoPYI7otqUZPoNN8pULUnlJMxQa-JKXRKV0KtvTAdcMsfYudYxbz7HwcNYerFT1q3RZAimJFtfF4x_sMN23yEVxsQmYQrsf2YPmEsbCfNiEx0YEoWUdS38R1N0Iul2P_P_ZB7XreG4aR5dT6lY5TlXbhputv9pi_yAU7PB1aLuB05phQme5NwJEY22pUfx5pe1wVHogI0JyNLi-6gdoSL63DJ32tbQjr2DNYilPVtLsUkkz7fTky5OKd4p7FmG7P5EbEK4H5j04AGe_nIFs-X6x_FIS_5OSGK4LGA2RPnqa-JYpngzlNWVkUbnuH10AovcAprgdg' - ) + 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImFQY3R3X29kdlJPb0VOZzNWb09sSWgydGlFcyIsImtpZCI6ImFQY3R3X29kdlJPb0VOZzNWb09sSWgydGlFcyJ9.eyJhdWQiOiI0YzMzYzQyMS1mN2QzLTRiNmMtOTkyYi0zNmU3ZTZkZTg3NjEiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC9kNmQ0OTQyMC1mMzliLTRkZjctYTFkYy1kNTlhOTM1ODcxZGIvIiwiaWF0IjoxNTcxMTg5ODczLCJuYmYiOjE1NzExODk4NzMsImV4cCI6MTU3MTE5Mzc3MywiYWlvIjoiNDJWZ1lLaWJGUDIyMUxmL0NjL1Yzai8zcGF2RUFBPT0iLCJhcHBpZCI6IjRjMzNjNDIxLWY3ZDMtNGI2Yy05OTJiLTM2ZTdlNmRlODc2MSIsImFwcGlkYWNyIjoiMSIsImlkcCI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0L2Q2ZDQ5NDIwLWYzOWItNGRmNy1hMWRjLWQ1OWE5MzU4NzFkYi8iLCJ0aWQiOiJkNmQ0OTQyMC1mMzliLTRkZjctYTFkYy1kNTlhOTM1ODcxZGIiLCJ1dGkiOiJOdXJ3bTVOQnkwR2duT3dKRnFVREFBIiwidmVyIjoiMS4wIn0.GcKs3XZ_4GONVsAoPYI7otqUZPoNN8pULUnlJMxQa-JKXRKV0KtvTAdcMsfYudYxbz7HwcNYerFT1q3RZAimJFtfF4x_sMN23yEVxsQmYQrsf2YPmEsbCfNiEx0YEoWUdS38R1N0Iul2P_P_ZB7XreG4aR5dT6lY5TlXbhputv9pi_yAU7PB1aLuB05phQme5NwJEY22pUfx5pe1wVHogI0JyNLi-6gdoSL63DJ32tbQjr2DNYilPVtLsUkkz7fTky5OKd4p7FmG7P5EbEK4H5j04AGe_nIFs-X6x_FIS_5OSGK4LGA2RPnqa-JYpngzlNWVkUbnuH10AovcAprgdg', + ), ); }); it('should fail for messages to bot from Emulator using version claim v2', function () { assert( !SkillValidation.isSkillToken( - 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6ImFQY3R3X29kdlJPb0VOZzNWb09sSWgydGlFcyJ9.eyJhdWQiOiI0YzAwMzllNS02ODE2LTQ4ZTgtYjMxMy1mNzc2OTFmZjFjNWUiLCJpc3MiOiJodHRwczovL2xvZ2luLm1pY3Jvc29mdG9ubGluZS5jb20vZDZkNDk0MjAtZjM5Yi00ZGY3LWExZGMtZDU5YTkzNTg3MWRiL3YyLjAiLCJpYXQiOjE1NzExODkwMTEsIm5iZiI6MTU3MTE4OTAxMSwiZXhwIjoxNTcxMTkyOTExLCJhaW8iOiI0MlZnWUxnYWxmUE90Y2IxaEoxNzJvbmxIc3ZuQUFBPSIsImF6cCI6IjRjMDAzOWU1LTY4MTYtNDhlOC1iMzEzLWY3NzY5MWZmMWM1ZSIsImF6cGFjciI6IjEiLCJ0aWQiOiJkNmQ0OTQyMC1mMzliLTRkZjctYTFkYy1kNTlhOTM1ODcxZGIiLCJ1dGkiOiJucEVxVTFoR1pVbXlISy1MUVdJQ0FBIiwidmVyIjoiMi4wIn0.CXcPx7LfatlRsOX4QG-jaC-guwcY3PFxpFICqwfoOTxAjHpeJNFXOpFeA3Qb5VKM6Yw5LyA9eraL5QDJB_4uMLCCKErPXMyoSm8Hw-GGZkHgFV5ciQXSXhE-IfOinqHE_0Lkt_VLR2q6ekOncnJeCR111QCqt3D8R0Ud0gvyLv_oONxDtqg7HUgNGEfioB-BDnBsO4RN7NGrWQFbyPxPmhi8a_Xc7j5Bb9jeiiIQbVaWkIrrPN31aWY1tEZLvdN0VluYlOa0EBVrzpXXZkIyWx99mpklg0lsy7mRyjuM1xydmyyGkzbiCKtODOanf8UwTjkTg5XTIluxe79_hVk2JQ' - ) + 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6ImFQY3R3X29kdlJPb0VOZzNWb09sSWgydGlFcyJ9.eyJhdWQiOiI0YzAwMzllNS02ODE2LTQ4ZTgtYjMxMy1mNzc2OTFmZjFjNWUiLCJpc3MiOiJodHRwczovL2xvZ2luLm1pY3Jvc29mdG9ubGluZS5jb20vZDZkNDk0MjAtZjM5Yi00ZGY3LWExZGMtZDU5YTkzNTg3MWRiL3YyLjAiLCJpYXQiOjE1NzExODkwMTEsIm5iZiI6MTU3MTE4OTAxMSwiZXhwIjoxNTcxMTkyOTExLCJhaW8iOiI0MlZnWUxnYWxmUE90Y2IxaEoxNzJvbmxIc3ZuQUFBPSIsImF6cCI6IjRjMDAzOWU1LTY4MTYtNDhlOC1iMzEzLWY3NzY5MWZmMWM1ZSIsImF6cGFjciI6IjEiLCJ0aWQiOiJkNmQ0OTQyMC1mMzliLTRkZjctYTFkYy1kNTlhOTM1ODcxZGIiLCJ1dGkiOiJucEVxVTFoR1pVbXlISy1MUVdJQ0FBIiwidmVyIjoiMi4wIn0.CXcPx7LfatlRsOX4QG-jaC-guwcY3PFxpFICqwfoOTxAjHpeJNFXOpFeA3Qb5VKM6Yw5LyA9eraL5QDJB_4uMLCCKErPXMyoSm8Hw-GGZkHgFV5ciQXSXhE-IfOinqHE_0Lkt_VLR2q6ekOncnJeCR111QCqt3D8R0Ud0gvyLv_oONxDtqg7HUgNGEfioB-BDnBsO4RN7NGrWQFbyPxPmhi8a_Xc7j5Bb9jeiiIQbVaWkIrrPN31aWY1tEZLvdN0VluYlOa0EBVrzpXXZkIyWx99mpklg0lsy7mRyjuM1xydmyyGkzbiCKtODOanf8UwTjkTg5XTIluxe79_hVk2JQ', + ), ); }); it('should succeed for messages to skill using valid v1 token', function () { assert( SkillValidation.isSkillToken( - 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImFQY3R3X29kdlJPb0VOZzNWb09sSWgydGlFcyIsImtpZCI6ImFQY3R3X29kdlJPb0VOZzNWb09sSWgydGlFcyJ9.eyJhdWQiOiI0YzMzYzQyMS1mN2QzLTRiNmMtOTkyYi0zNmU3ZTZkZTg3NjEiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC9kNmQ0OTQyMC1mMzliLTRkZjctYTFkYy1kNTlhOTM1ODcxZGIvIiwiaWF0IjoxNTcxMTg5NjMwLCJuYmYiOjE1NzExODk2MzAsImV4cCI6MTU3MTE5MzUzMCwiYWlvIjoiNDJWZ1lJZzY1aDFXTUVPd2JmTXIwNjM5V1lLckFBPT0iLCJhcHBpZCI6IjRjMDAzOWU1LTY4MTYtNDhlOC1iMzEzLWY3NzY5MWZmMWM1ZSIsImFwcGlkYWNyIjoiMSIsImlkcCI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0L2Q2ZDQ5NDIwLWYzOWItNGRmNy1hMWRjLWQ1OWE5MzU4NzFkYi8iLCJ0aWQiOiJkNmQ0OTQyMC1mMzliLTRkZjctYTFkYy1kNTlhOTM1ODcxZGIiLCJ1dGkiOiJhWlpOUTY3RjRVNnNmY3d0S0R3RUFBIiwidmVyIjoiMS4wIn0.Yogk9fptxxJKO8jRkk6FrlLQsAulNNgoa0Lqv2JPkswyyizse8kcwQhxOaZOotY0UBduJ-pCcrejk6k4_O_ZReYXKz8biL9Q7Z02cU9WUMvuIGpAhttz8v0VlVSyaEJVJALc5B-U6XVUpZtG9LpE6MVror_0WMnT6T9Ijf9SuxUvdVCcmAJyZuoqudodseuFI-jtCpImEapZp0wVN4BUodrBacMbTeYjdZyAbNVBqF5gyzDztMKZR26HEz91gqulYZvJJZOJO6ejnm0j62s1tqvUVRBywvnSOon-MV0Xt2Vm0irhv6ipzTXKwWhT9rGHSLj0g8r6NqWRyPRFqLccvA' - ) + 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImFQY3R3X29kdlJPb0VOZzNWb09sSWgydGlFcyIsImtpZCI6ImFQY3R3X29kdlJPb0VOZzNWb09sSWgydGlFcyJ9.eyJhdWQiOiI0YzMzYzQyMS1mN2QzLTRiNmMtOTkyYi0zNmU3ZTZkZTg3NjEiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC9kNmQ0OTQyMC1mMzliLTRkZjctYTFkYy1kNTlhOTM1ODcxZGIvIiwiaWF0IjoxNTcxMTg5NjMwLCJuYmYiOjE1NzExODk2MzAsImV4cCI6MTU3MTE5MzUzMCwiYWlvIjoiNDJWZ1lJZzY1aDFXTUVPd2JmTXIwNjM5V1lLckFBPT0iLCJhcHBpZCI6IjRjMDAzOWU1LTY4MTYtNDhlOC1iMzEzLWY3NzY5MWZmMWM1ZSIsImFwcGlkYWNyIjoiMSIsImlkcCI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0L2Q2ZDQ5NDIwLWYzOWItNGRmNy1hMWRjLWQ1OWE5MzU4NzFkYi8iLCJ0aWQiOiJkNmQ0OTQyMC1mMzliLTRkZjctYTFkYy1kNTlhOTM1ODcxZGIiLCJ1dGkiOiJhWlpOUTY3RjRVNnNmY3d0S0R3RUFBIiwidmVyIjoiMS4wIn0.Yogk9fptxxJKO8jRkk6FrlLQsAulNNgoa0Lqv2JPkswyyizse8kcwQhxOaZOotY0UBduJ-pCcrejk6k4_O_ZReYXKz8biL9Q7Z02cU9WUMvuIGpAhttz8v0VlVSyaEJVJALc5B-U6XVUpZtG9LpE6MVror_0WMnT6T9Ijf9SuxUvdVCcmAJyZuoqudodseuFI-jtCpImEapZp0wVN4BUodrBacMbTeYjdZyAbNVBqF5gyzDztMKZR26HEz91gqulYZvJJZOJO6ejnm0j62s1tqvUVRBywvnSOon-MV0Xt2Vm0irhv6ipzTXKwWhT9rGHSLj0g8r6NqWRyPRFqLccvA', + ), ); }); it('should succeed for messages to skill using valid v2 token', function () { assert( SkillValidation.isSkillToken( - 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6ImFQY3R3X29kdlJPb0VOZzNWb09sSWgydGlFcyJ9.eyJhdWQiOiI0YzAwMzllNS02ODE2LTQ4ZTgtYjMxMy1mNzc2OTFmZjFjNWUiLCJpc3MiOiJodHRwczovL2xvZ2luLm1pY3Jvc29mdG9ubGluZS5jb20vZDZkNDk0MjAtZjM5Yi00ZGY3LWExZGMtZDU5YTkzNTg3MWRiL3YyLjAiLCJpYXQiOjE1NzExODk3NTUsIm5iZiI6MTU3MTE4OTc1NSwiZXhwIjoxNTcxMTkzNjU1LCJhaW8iOiI0MlZnWUpnZDROZkZKeG1tMTdPaVMvUk8wZll2QUE9PSIsImF6cCI6IjRjMzNjNDIxLWY3ZDMtNGI2Yy05OTJiLTM2ZTdlNmRlODc2MSIsImF6cGFjciI6IjEiLCJ0aWQiOiJkNmQ0OTQyMC1mMzliLTRkZjctYTFkYy1kNTlhOTM1ODcxZGIiLCJ1dGkiOiJMc2ZQME9JVkNVS1JzZ1IyYlFBQkFBIiwidmVyIjoiMi4wIn0.SggsEbEyXDYcg6EdhK-RA1y6S97z4hwEccXc6a3ymnHP-78frZ3N8rPLsqLoK5QPGA_cqOXsX1zduA4vlFSy3MfTV_npPfsyWa1FIse96-2_3qa9DIP8bhvOHXEVZeq-r-0iF972waFyPPC_KVYWnIgAcunGhFWvLhhOUx9dPgq7824qTq45ma1rOqRoYbhhlRn6PJDymIin5LeOzDGJJ8YVLnFUgntc6_4z0P_fnuMktzar88CUTtGvR4P7XNJhS8v9EwYQujglsJNXg7LNcwV7qOxDYWJtT_UMuMAts9ctD6FkuTGX_-6FTqmdUPPUS4RWwm4kkl96F_dXnos9JA' - ) + 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6ImFQY3R3X29kdlJPb0VOZzNWb09sSWgydGlFcyJ9.eyJhdWQiOiI0YzAwMzllNS02ODE2LTQ4ZTgtYjMxMy1mNzc2OTFmZjFjNWUiLCJpc3MiOiJodHRwczovL2xvZ2luLm1pY3Jvc29mdG9ubGluZS5jb20vZDZkNDk0MjAtZjM5Yi00ZGY3LWExZGMtZDU5YTkzNTg3MWRiL3YyLjAiLCJpYXQiOjE1NzExODk3NTUsIm5iZiI6MTU3MTE4OTc1NSwiZXhwIjoxNTcxMTkzNjU1LCJhaW8iOiI0MlZnWUpnZDROZkZKeG1tMTdPaVMvUk8wZll2QUE9PSIsImF6cCI6IjRjMzNjNDIxLWY3ZDMtNGI2Yy05OTJiLTM2ZTdlNmRlODc2MSIsImF6cGFjciI6IjEiLCJ0aWQiOiJkNmQ0OTQyMC1mMzliLTRkZjctYTFkYy1kNTlhOTM1ODcxZGIiLCJ1dGkiOiJMc2ZQME9JVkNVS1JzZ1IyYlFBQkFBIiwidmVyIjoiMi4wIn0.SggsEbEyXDYcg6EdhK-RA1y6S97z4hwEccXc6a3ymnHP-78frZ3N8rPLsqLoK5QPGA_cqOXsX1zduA4vlFSy3MfTV_npPfsyWa1FIse96-2_3qa9DIP8bhvOHXEVZeq-r-0iF972waFyPPC_KVYWnIgAcunGhFWvLhhOUx9dPgq7824qTq45ma1rOqRoYbhhlRn6PJDymIin5LeOzDGJJ8YVLnFUgntc6_4z0P_fnuMktzar88CUTtGvR4P7XNJhS8v9EwYQujglsJNXg7LNcwV7qOxDYWJtT_UMuMAts9ctD6FkuTGX_-6FTqmdUPPUS4RWwm4kkl96F_dXnos9JA', + ), ); }); }); @@ -131,9 +131,9 @@ describe('SkillValidation', function () { 'authHeader', new SimpleCredentialProvider('', ''), '', - 'unknown' + 'unknown', ), - new Error('SkillValidation.authenticateChannelToken(): invalid authConfig parameter') + new Error('SkillValidation.authenticateChannelToken(): invalid authConfig parameter'), ); }); }); @@ -176,7 +176,7 @@ describe('SkillValidation', function () { await assert.rejects( SkillValidation.validateIdentity(undefined, credentials), - new Error('SkillValidation.validateIdentity(): Invalid identity') + new Error('SkillValidation.validateIdentity(): Invalid identity'), ); }); @@ -187,7 +187,7 @@ describe('SkillValidation', function () { await assert.rejects( SkillValidation.validateIdentity(identity, credentials), - new Error('SkillValidation.validateIdentity(): Token not authenticated') + new Error('SkillValidation.validateIdentity(): Token not authenticated'), ); }); @@ -199,8 +199,8 @@ describe('SkillValidation', function () { await assert.rejects( SkillValidation.validateIdentity(identity, credentials), new Error( - `SkillValidation.validateIdentity(): '${AuthenticationConstants.VersionClaim}' claim is required on skill Tokens.` - ) + `SkillValidation.validateIdentity(): '${AuthenticationConstants.VersionClaim}' claim is required on skill Tokens.`, + ), ); }); @@ -212,8 +212,8 @@ describe('SkillValidation', function () { await assert.rejects( SkillValidation.validateIdentity(identity, credentials), new Error( - `SkillValidation.validateIdentity(): '${AuthenticationConstants.AudienceClaim}' claim is required on skill Tokens.` - ) + `SkillValidation.validateIdentity(): '${AuthenticationConstants.AudienceClaim}' claim is required on skill Tokens.`, + ), ); }); @@ -225,7 +225,7 @@ describe('SkillValidation', function () { await assert.rejects( SkillValidation.validateIdentity(identity, credentials), - new Error('SkillValidation.validateIdentity(): Invalid audience.') + new Error('SkillValidation.validateIdentity(): Invalid audience.'), ); }); @@ -237,7 +237,7 @@ describe('SkillValidation', function () { await assert.rejects( SkillValidation.validateIdentity(identity, credentials), - new Error('SkillValidation.validateIdentity(): Invalid appId.') + new Error('SkillValidation.validateIdentity(): Invalid appId.'), ); }); @@ -249,7 +249,7 @@ describe('SkillValidation', function () { await assert.rejects( SkillValidation.validateIdentity(identity, credentials), - new Error('SkillValidation.validateIdentity(): Invalid appId.') + new Error('SkillValidation.validateIdentity(): Invalid appId.'), ); }); From 18f95eda6405c2cf32f272616857aef33b34b850 Mon Sep 17 00:00:00 2001 From: Joel Mut <62260472+sw-joelmut@users.noreply.github.com> Date: Mon, 6 Jan 2025 12:00:50 -0300 Subject: [PATCH 03/22] fix: [#4684] ESLint issues in botbuilder-testing (#4823) * Fix ESLint with --fix flag * Fix ESLint issues --- .../botbuilder-testing/eslint.config.cjs | 10 ---- libraries/botbuilder-testing/package.json | 5 +- .../src/dialogTestClient.ts | 13 ++--- .../src/dialogTestLogger.ts | 48 +++++++++---------- 4 files changed, 30 insertions(+), 46 deletions(-) delete mode 100644 libraries/botbuilder-testing/eslint.config.cjs diff --git a/libraries/botbuilder-testing/eslint.config.cjs b/libraries/botbuilder-testing/eslint.config.cjs deleted file mode 100644 index 63647b52cc..0000000000 --- a/libraries/botbuilder-testing/eslint.config.cjs +++ /dev/null @@ -1,10 +0,0 @@ -const onlyWarn = require("eslint-plugin-only-warn"); -const sharedConfig = require("../../eslint.config.cjs") - -module.exports = [ - ...sharedConfig, - { - plugins: { - "only-warn": onlyWarn, - }, - }]; diff --git a/libraries/botbuilder-testing/package.json b/libraries/botbuilder-testing/package.json index 941b541e4e..e0ffc30476 100644 --- a/libraries/botbuilder-testing/package.json +++ b/libraries/botbuilder-testing/package.json @@ -28,8 +28,7 @@ }, "dependencies": { "botbuilder-core": "4.1.6", - "botbuilder-dialogs": "4.1.6", - "eslint-plugin-only-warn": "^1.1.0" + "botbuilder-dialogs": "4.1.6" }, "scripts": { "build": "tsc -b", @@ -37,7 +36,7 @@ "build:rollup": "yarn clean && yarn build && api-extractor run --verbose --local", "clean": "rimraf _ts3.4 lib tsconfig.tsbuildinfo", "depcheck": "depcheck --config ../../.depcheckrc", - "lint": "eslint .", + "lint": "eslint . --config ../../eslint.config.cjs", "postbuild": "downlevel-dts lib _ts3.4/lib --checksum", "test": "yarn build && nyc mocha tests/", "test:compat": "api-extractor run --verbose" diff --git a/libraries/botbuilder-testing/src/dialogTestClient.ts b/libraries/botbuilder-testing/src/dialogTestClient.ts index f762b5969f..17ff08f776 100644 --- a/libraries/botbuilder-testing/src/dialogTestClient.ts +++ b/libraries/botbuilder-testing/src/dialogTestClient.ts @@ -6,8 +6,6 @@ * Licensed under the MIT License. */ -/* eslint-disable @typescript-eslint/ban-types */ - import { Activity, TestAdapter, @@ -60,7 +58,7 @@ export class DialogTestClient { targetDialog: Dialog, initialDialogOptions?: unknown, middlewares?: Middleware[], - conversationState?: ConversationState + conversationState?: ConversationState, ); /** * Creates a [DialogTestClient](xref:botbuilder-testing.DialogTestClient) to test a [Dialog](xref:botbuilder-dialogs.Dialog) without having to create a full-fledged adapter. @@ -81,7 +79,7 @@ export class DialogTestClient { targetDialog: Dialog, initialDialogOptions?: unknown, middlewares?: Middleware[], - conversationState?: ConversationState + conversationState?: ConversationState, ); /** * Creates a [DialogTestClient](xref:botbuilder-testing.DialogTestClient) to test a [Dialog](xref:botbuilder-dialogs.Dialog) without having to create a full-fledged adapter. @@ -97,7 +95,7 @@ export class DialogTestClient { targetDialog: Dialog, initialDialogOptions?: object, middlewares?: Middleware[], - conversationState?: ConversationState + conversationState?: ConversationState, ) { this.conversationState = conversationState || new ConversationState(new MemoryStorage()); @@ -108,7 +106,7 @@ export class DialogTestClient { if (typeof channelOrAdapter == 'string') { const channelIdToUse: string = channelOrAdapter; this._testAdapter = new TestAdapter(this._callback, { channelId: channelIdToUse }).use( - new AutoSaveStateMiddleware(this.conversationState) + new AutoSaveStateMiddleware(this.conversationState), ); } else { const testAdapterToUse: TestAdapter = channelOrAdapter; @@ -140,7 +138,6 @@ export class DialogTestClient { * @param activity an activity potentially with text * @returns a TestFlow that can be used to assert replies etc */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any async sendActivity(activity: Partial | string): Promise { await this._testAdapter.receiveActivity(activity); return this._testAdapter.activityBuffer.shift(); @@ -158,7 +155,7 @@ export class DialogTestClient { private getDefaultCallback( targetDialog: Dialog, initialDialogOptions: object, - dialogState: StatePropertyAccessor + dialogState: StatePropertyAccessor, ): (turnContext: TurnContext) => Promise { return async (turnContext: TurnContext): Promise => { const dialogSet = new DialogSet(dialogState); diff --git a/libraries/botbuilder-testing/src/dialogTestLogger.ts b/libraries/botbuilder-testing/src/dialogTestLogger.ts index 734fb2a207..e521063ace 100644 --- a/libraries/botbuilder-testing/src/dialogTestLogger.ts +++ b/libraries/botbuilder-testing/src/dialogTestLogger.ts @@ -61,32 +61,30 @@ export class DialogTestLogger implements Middleware { const timestamp = `${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`; this.logger.log(`-> ts: ${timestamp}`); - context.onSendActivities( - async (context, activities, next): Promise => { - // log outgoing - activities.forEach((activity) => { - if (activity.type == ActivityTypes.Message) { - this.logger.log(`Bot: Text = ${activity.text}`); - this.logger.log(` Speak = ${activity.speak}`); - this.logger.log(` InputHint = ${activity.inputHint}`); - } else { - this.logger.log(`Bot: Activity = ${activity.type}`); - JSON.stringify(activity, null, 2) - .split(/\n/) - .forEach((line) => { - this.logger.log(line); - }); - } - }); - const now = new Date(); - const stopwatch = context.turnState[this._stopwatchStateKey]; - const mms = now.getTime() - stopwatch.getTime(); - const timestamp = `${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`; - this.logger.log(`-> ts: ${timestamp} elapsed ${mms} ms`); + context.onSendActivities(async (context, activities, next): Promise => { + // log outgoing + activities.forEach((activity) => { + if (activity.type == ActivityTypes.Message) { + this.logger.log(`Bot: Text = ${activity.text}`); + this.logger.log(` Speak = ${activity.speak}`); + this.logger.log(` InputHint = ${activity.inputHint}`); + } else { + this.logger.log(`Bot: Activity = ${activity.type}`); + JSON.stringify(activity, null, 2) + .split(/\n/) + .forEach((line) => { + this.logger.log(line); + }); + } + }); + const now = new Date(); + const stopwatch = context.turnState[this._stopwatchStateKey]; + const mms = now.getTime() - stopwatch.getTime(); + const timestamp = `${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`; + this.logger.log(`-> ts: ${timestamp} elapsed ${mms} ms`); - return next(); - } - ); + return next(); + }); await next(); } } From 551267e6fe656dbbf8663398d442875f5c6826d4 Mon Sep 17 00:00:00 2001 From: Cecilia Avila <44245136+ceciliaavila@users.noreply.github.com> Date: Mon, 6 Jan 2025 12:01:24 -0300 Subject: [PATCH 04/22] Fix issues in botbuilder-dialogs-declarative (#4813) --- .../botbuilder-dialogs-declarative/eslint.config.cjs | 10 ---------- libraries/botbuilder-dialogs-declarative/package.json | 3 +-- .../src/componentDeclarativeTypes.ts | 2 +- .../botbuilder-dialogs-declarative/src/pathUtil.ts | 3 +++ .../src/resources/fileResource.ts | 6 +++--- .../src/resources/folderResourceProvider.ts | 2 +- .../src/resources/resourceExplorer.ts | 4 ++-- .../tests/jsonLoad.test.js | 11 ++++++----- .../tests/resourceExplorer.test.js | 8 ++++---- .../tests/schemaMergeTest.js | 5 ++--- 10 files changed, 23 insertions(+), 31 deletions(-) delete mode 100644 libraries/botbuilder-dialogs-declarative/eslint.config.cjs diff --git a/libraries/botbuilder-dialogs-declarative/eslint.config.cjs b/libraries/botbuilder-dialogs-declarative/eslint.config.cjs deleted file mode 100644 index 63647b52cc..0000000000 --- a/libraries/botbuilder-dialogs-declarative/eslint.config.cjs +++ /dev/null @@ -1,10 +0,0 @@ -const onlyWarn = require("eslint-plugin-only-warn"); -const sharedConfig = require("../../eslint.config.cjs") - -module.exports = [ - ...sharedConfig, - { - plugins: { - "only-warn": onlyWarn, - }, - }]; diff --git a/libraries/botbuilder-dialogs-declarative/package.json b/libraries/botbuilder-dialogs-declarative/package.json index f44b9e5206..2d615130b1 100644 --- a/libraries/botbuilder-dialogs-declarative/package.json +++ b/libraries/botbuilder-dialogs-declarative/package.json @@ -31,7 +31,6 @@ "botbuilder-dialogs": "4.1.6", "botbuilder-stdlib": "4.1.6", "chokidar": "^3.6.0", - "eslint-plugin-only-warn": "^1.1.0", "zod": "^3.23.8" }, "devDependencies": { @@ -45,7 +44,7 @@ "build-docs": "typedoc --theme markdown --entryPoint botbuilder-dialogs-adaptive --excludePrivate --includeDeclarations --ignoreCompilerErrors --module amd --out ..\\..\\doc\\botbuilder-dialogs .\\lib\\index.d.ts --hideGenerator --name \"Bot Builder SDK - Dialogs\" --readme none", "clean": "rimraf _ts3.4 lib tsconfig.tsbuildinfo", "depcheck": "depcheck --config ../../.depcheckrc --ignores botbuilder-ai,botbuilder-dialogs-adaptive", - "lint": "eslint .", + "lint": "eslint . --config ../../eslint.config.cjs", "postbuild": "downlevel-dts lib _ts3.4/lib --checksum", "test": "yarn build && nyc mocha tests/**/*.test.js --exit", "test:compat": "api-extractor run --verbose" diff --git a/libraries/botbuilder-dialogs-declarative/src/componentDeclarativeTypes.ts b/libraries/botbuilder-dialogs-declarative/src/componentDeclarativeTypes.ts index 6ff9196107..e4f06c14d9 100644 --- a/libraries/botbuilder-dialogs-declarative/src/componentDeclarativeTypes.ts +++ b/libraries/botbuilder-dialogs-declarative/src/componentDeclarativeTypes.ts @@ -19,7 +19,7 @@ export interface ComponentDeclarativeTypes { const componentDeclarativeTypes = z.custom( (val: any) => typeof val.getDeclarativeTypes === 'function', - { message: 'ComponentDeclarativeTypes' } + { message: 'ComponentDeclarativeTypes' }, ); /** diff --git a/libraries/botbuilder-dialogs-declarative/src/pathUtil.ts b/libraries/botbuilder-dialogs-declarative/src/pathUtil.ts index 48d3b12a1c..1ee033356f 100644 --- a/libraries/botbuilder-dialogs-declarative/src/pathUtil.ts +++ b/libraries/botbuilder-dialogs-declarative/src/pathUtil.ts @@ -20,6 +20,7 @@ export class PathUtil { * @returns True if the path is a directory; false otherwise. */ static isDirectory(path: string): boolean { + // eslint-disable-next-line security/detect-non-literal-fs-filename return lstatSync(path).isDirectory(); } @@ -30,6 +31,7 @@ export class PathUtil { * @returns Sub folders in the directory. */ static getDirectories(path: string): string[] { + // eslint-disable-next-line security/detect-non-literal-fs-filename return readdirSync(path) .map((name: string): string => join(path, name)) .filter(PathUtil.isDirectory); @@ -43,6 +45,7 @@ export class PathUtil { * @returns The files in the directory. */ static getFiles(path: string, includeSubFolders = true): string[] { + // eslint-disable-next-line security/detect-non-literal-fs-filename return readdirSync(path) .map((name: string): string => join(path, name)) .reduce((files: string[], file: string): string[] => { diff --git a/libraries/botbuilder-dialogs-declarative/src/resources/fileResource.ts b/libraries/botbuilder-dialogs-declarative/src/resources/fileResource.ts index 04ed6a551f..21da8ec0dc 100644 --- a/libraries/botbuilder-dialogs-declarative/src/resources/fileResource.ts +++ b/libraries/botbuilder-dialogs-declarative/src/resources/fileResource.ts @@ -1,4 +1,3 @@ -/* eslint-disable security/detect-non-literal-fs-filename */ /** * @module botbuilder-dialogs-declarative */ @@ -7,7 +6,7 @@ * Licensed under the MIT License. */ -import fs = require('fs'); +import { readFileSync } from 'fs'; import { Resource } from './resource'; /** @@ -33,7 +32,8 @@ export class FileResource extends Resource { */ readText(): string { const filePath = this._fullname; - const text = fs.readFileSync(filePath, 'utf-8'); + // eslint-disable-next-line security/detect-non-literal-fs-filename + const text = readFileSync(filePath, 'utf-8'); return text; } } diff --git a/libraries/botbuilder-dialogs-declarative/src/resources/folderResourceProvider.ts b/libraries/botbuilder-dialogs-declarative/src/resources/folderResourceProvider.ts index 3fa2505547..f2a6b11f74 100644 --- a/libraries/botbuilder-dialogs-declarative/src/resources/folderResourceProvider.ts +++ b/libraries/botbuilder-dialogs-declarative/src/resources/folderResourceProvider.ts @@ -73,7 +73,7 @@ export class FolderResourceProvider extends ResourceProvider { this._resources.clear(); const files: string[] = PathUtil.getFiles(this.directory, this.includeSubFolders); const filteredFiles: string[] = files.filter((filename): boolean => - this.resourceExplorer.resourceTypes.has(extname(filename).toLowerCase().replace(/^\./, '')) + this.resourceExplorer.resourceTypes.has(extname(filename).toLowerCase().replace(/^\./, '')), ); for (let i = 0; i < filteredFiles.length; i++) { const filename = filteredFiles[i]; diff --git a/libraries/botbuilder-dialogs-declarative/src/resources/resourceExplorer.ts b/libraries/botbuilder-dialogs-declarative/src/resources/resourceExplorer.ts index 882618087f..399057dc59 100644 --- a/libraries/botbuilder-dialogs-declarative/src/resources/resourceExplorer.ts +++ b/libraries/botbuilder-dialogs-declarative/src/resources/resourceExplorer.ts @@ -208,7 +208,7 @@ export class ResourceExplorer { registerType( kind: string, type: Newable, - loader?: CustomDeserializer> + loader?: CustomDeserializer>, ): ResourceExplorer { this.registerComponentTypes(); this.registerTypeInternal(kind, type, loader); @@ -286,7 +286,7 @@ export class ResourceExplorer { return value; } return this.load(value as { $kind: string } & Record); - }) + }), ); if (result instanceof Dialog && !config['id']) { diff --git a/libraries/botbuilder-dialogs-declarative/tests/jsonLoad.test.js b/libraries/botbuilder-dialogs-declarative/tests/jsonLoad.test.js index c168751e18..aa60255286 100644 --- a/libraries/botbuilder-dialogs-declarative/tests/jsonLoad.test.js +++ b/libraries/botbuilder-dialogs-declarative/tests/jsonLoad.test.js @@ -201,7 +201,7 @@ const buildQnAMakerTestFlowPreciseAnswer = ( resourceExplorer, testName, enablePreciseAnswer, - displayPreciseAnswerOnly + displayPreciseAnswerOnly, ) => { const adapter = initializeAdapter(testName); const dialog = resourceExplorer.loadType('QnAMakerBot.main.dialog'); @@ -213,6 +213,7 @@ const buildQnAMakerTestFlowPreciseAnswer = ( describe('Json load tests', function () { let resourceExplorer; + beforeEach(function () { const services = new ServiceCollection({ declarativeTypes: [], @@ -226,7 +227,7 @@ describe('Json load tests', function () { resourceExplorer = new ResourceExplorer({ declarativeTypes }).addFolder( path.join(__dirname, 'resources/JsonDialog'), true, - false + false, ); }); @@ -510,7 +511,7 @@ describe('Json load tests', function () { const suggestionActivity = QnACardBuilder.getSuggestionsCard( suggestionList, 'Did you mean:', - 'None of the above.' + 'None of the above.', ); await buildQnAMakerTestFlow(resourceExplorer, this.fullTitle()) .send('Q11') @@ -528,7 +529,7 @@ describe('Json load tests', function () { const suggestionActivity = QnACardBuilder.getSuggestionsCard( suggestionList, 'Did you mean:', - 'None of the above.' + 'None of the above.', ); const noAnswerActivity = 'No QnAMaker answers found.'; await buildQnAMakerTestFlow(resourceExplorer, this.fullTitle()) @@ -547,7 +548,7 @@ describe('Json load tests', function () { const suggestionActivity = QnACardBuilder.getSuggestionsCard( suggestionList, 'Did you mean:', - 'None of the above.' + 'None of the above.', ); await buildQnAMakerTestFlow(resourceExplorer, this.fullTitle()) .send('Q11') diff --git a/libraries/botbuilder-dialogs-declarative/tests/resourceExplorer.test.js b/libraries/botbuilder-dialogs-declarative/tests/resourceExplorer.test.js index 4714a62cb7..68033438cb 100644 --- a/libraries/botbuilder-dialogs-declarative/tests/resourceExplorer.test.js +++ b/libraries/botbuilder-dialogs-declarative/tests/resourceExplorer.test.js @@ -19,7 +19,7 @@ function assertResourceFound(explorer, id) { const dialogs = explorer.getResources('dialog'); assert( dialogs.some((dialog) => dialog.id == id), - "getResources('dialog') should return resources" + "getResources('dialog') should return resources", ); } @@ -29,7 +29,7 @@ function assertResourceNotFound(explorer, id) { const dialogs = explorer.getResources('dialog'); assert( dialogs.every((dialog) => dialog.id != id), - "getResouces('dialog') should not return resources" + "getResouces('dialog') should not return resources", ); } @@ -110,7 +110,7 @@ describe('ResourceExplorer', function () { assert.strictEqual( dialog.id, 'test.dialog', - 'resource id should be used as default dialog id if none assigned.' + 'resource id should be used as default dialog id if none assigned.', ); assert.strictEqual(dialog.triggers[0].actions[0].id, '1234567890'); assert.strictEqual(dialog.triggers[0].actions[1].id, 'test3.dialog'); @@ -275,7 +275,7 @@ describe('ResourceExplorer', function () { const resourceExplorer = new ResourceExplorer({ declarativeTypes }).addFolder( join(__dirname, './resources/CycleDetection'), false, - false + false, ); const root = resourceExplorer.loadType('root.dialog'); diff --git a/libraries/botbuilder-dialogs-declarative/tests/schemaMergeTest.js b/libraries/botbuilder-dialogs-declarative/tests/schemaMergeTest.js index cc858cae7b..33d29d243b 100644 --- a/libraries/botbuilder-dialogs-declarative/tests/schemaMergeTest.js +++ b/libraries/botbuilder-dialogs-declarative/tests/schemaMergeTest.js @@ -4,7 +4,6 @@ const assert = require('assert'); const fs = require('fs'); const Validator = require('jsonschema').Validator; const util = require('util'); -// eslint-disable-next-line security/detect-child-process const exec = util.promisify(require('child_process').exec); // Note: This file is intentionally not named *.test.js to ensure it isn't run @@ -30,7 +29,7 @@ describe('Schema Merge Tests', function () { resourceExplorer, path.join(__dirname, '..', '..'), true, - false + false, ); const dialogResources = resourceProvider.getResources('dialog'); const dialogs = dialogResources @@ -92,7 +91,7 @@ describe('Schema Merge Tests', function () { [ 'Generated schema differs from committed schema.', 'Run this test locally and commit the tests.*schema files to upload the correct and updated schema.', - ].join('\n') + ].join('\n'), ); } From df3b3f54a7a6c71c2d94535563070477083b4392 Mon Sep 17 00:00:00 2001 From: Cecilia Avila <44245136+ceciliaavila@users.noreply.github.com> Date: Mon, 6 Jan 2025 12:02:02 -0300 Subject: [PATCH 05/22] Fix issues in botbuilder-stdlib (#4814) --- libraries/botbuilder-stdlib/eslint.config.cjs | 10 ---------- libraries/botbuilder-stdlib/package.json | 5 +---- libraries/botbuilder-stdlib/src/retry.ts | 2 +- libraries/botbuilder-stdlib/src/stringify.ts | 4 +--- libraries/botbuilder-stdlib/src/types.ts | 2 +- libraries/botbuilder-stdlib/tests/delay.test.js | 1 + libraries/botbuilder-stdlib/tests/stringify.test.js | 2 +- 7 files changed, 6 insertions(+), 20 deletions(-) delete mode 100644 libraries/botbuilder-stdlib/eslint.config.cjs diff --git a/libraries/botbuilder-stdlib/eslint.config.cjs b/libraries/botbuilder-stdlib/eslint.config.cjs deleted file mode 100644 index 63647b52cc..0000000000 --- a/libraries/botbuilder-stdlib/eslint.config.cjs +++ /dev/null @@ -1,10 +0,0 @@ -const onlyWarn = require("eslint-plugin-only-warn"); -const sharedConfig = require("../../eslint.config.cjs") - -module.exports = [ - ...sharedConfig, - { - plugins: { - "only-warn": onlyWarn, - }, - }]; diff --git a/libraries/botbuilder-stdlib/package.json b/libraries/botbuilder-stdlib/package.json index 0f9fe3500b..3ab4eff14b 100644 --- a/libraries/botbuilder-stdlib/package.json +++ b/libraries/botbuilder-stdlib/package.json @@ -9,9 +9,6 @@ "bugs": { "url": "https://github.com/Microsoft/botbuilder-js/issues" }, - "dependencies": { - "eslint-plugin-only-warn": "^1.1.0" - }, "repository": { "type": "git", "url": "https://github.com/Microsoft/botbuilder-js.git" @@ -20,7 +17,7 @@ "build": "tsc -b", "clean": "rimraf _ts3.4 lib tsconfig.tsbuildinfo", "depcheck": "depcheck --config ../../.depcheckrc", - "lint": "eslint .", + "lint": "eslint . --config ../../eslint.config.cjs", "postbuild": "downlevel-dts lib _ts3.4/lib", "test": "yarn build && nyc mocha --check-leaks tests" }, diff --git a/libraries/botbuilder-stdlib/src/retry.ts b/libraries/botbuilder-stdlib/src/retry.ts index 9bc9e1d060..803ed27d42 100644 --- a/libraries/botbuilder-stdlib/src/retry.ts +++ b/libraries/botbuilder-stdlib/src/retry.ts @@ -12,7 +12,7 @@ export async function retry( promise: (n: number) => Promise, maxRetries: number, - initialDelay = 500 + initialDelay = 500, ): Promise { let delay = initialDelay, n = 1, diff --git a/libraries/botbuilder-stdlib/src/stringify.ts b/libraries/botbuilder-stdlib/src/stringify.ts index 23b7e9909a..8c42d2edb4 100644 --- a/libraries/botbuilder-stdlib/src/stringify.ts +++ b/libraries/botbuilder-stdlib/src/stringify.ts @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -/* eslint-disable @typescript-eslint/no-explicit-any */ - /** * Encapsulates JSON.stringify function to detect and handle different types of errors (eg. Circular Structure). * @@ -64,7 +62,7 @@ export function stringify(value: any, replacer?: (key: string, value: any) => an const value = stringifyReplacer(replacer)(key, val); return value; }, - space + space, ); } } diff --git a/libraries/botbuilder-stdlib/src/types.ts b/libraries/botbuilder-stdlib/src/types.ts index 056a782b27..9e0f963ff9 100644 --- a/libraries/botbuilder-stdlib/src/types.ts +++ b/libraries/botbuilder-stdlib/src/types.ts @@ -11,4 +11,4 @@ export type Maybe = T | Nil; export type Newable = new (...args: A) => T; // Extends mimics Newable, but works for abstract classes as well -export type Extends = Function & { prototype: T }; // eslint-disable-line @typescript-eslint/ban-types +export type Extends = Function & { prototype: T }; // eslint-disable-line @typescript-eslint/no-unsafe-function-type diff --git a/libraries/botbuilder-stdlib/tests/delay.test.js b/libraries/botbuilder-stdlib/tests/delay.test.js index 27ebba5322..bba021902f 100644 --- a/libraries/botbuilder-stdlib/tests/delay.test.js +++ b/libraries/botbuilder-stdlib/tests/delay.test.js @@ -7,6 +7,7 @@ const { delay } = require('../'); describe('delay', function () { let sandbox; + beforeEach(function () { sandbox = sinon.createSandbox({ useFakeTimers: true }); }); diff --git a/libraries/botbuilder-stdlib/tests/stringify.test.js b/libraries/botbuilder-stdlib/tests/stringify.test.js index 0a4fa54f66..39e4d08cd2 100644 --- a/libraries/botbuilder-stdlib/tests/stringify.test.js +++ b/libraries/botbuilder-stdlib/tests/stringify.test.js @@ -99,7 +99,7 @@ describe('stringify', function () { const withoutReplacerToJSON = stringify(value); const assertWithReplacerToJSON = JSON.stringify( - _replacer.call(JSON.parse(JSON.stringify(value, replacer))) + _replacer.call(JSON.parse(JSON.stringify(value, replacer))), ); assert.ok(withReplacerToJSON.includes('"_id":":toJSON:replacer:_replacer"')); assert.strictEqual(withReplacerToJSON, assertWithReplacerToJSON); From 619153ac7d16d8375f56d48faae6cd1687ef8647 Mon Sep 17 00:00:00 2001 From: Cecilia Avila <44245136+ceciliaavila@users.noreply.github.com> Date: Mon, 6 Jan 2025 12:02:30 -0300 Subject: [PATCH 06/22] Fix issues in botframework-config (#4815) --- .../botframework-config/eslint.config.cjs | 10 ---------- libraries/botframework-config/package.json | 3 +-- .../src/botConfiguration.ts | 8 ++++---- .../src/models/connectedService.ts | 5 ++++- .../tests/botRecipe.test.js | 15 ++++++++------- .../tests/encryption.test.js | 2 +- .../tests/loadAndSave.test.js | 18 +++++++++--------- .../botframework-config/tests/service.test.js | 2 +- 8 files changed, 28 insertions(+), 35 deletions(-) delete mode 100644 libraries/botframework-config/eslint.config.cjs diff --git a/libraries/botframework-config/eslint.config.cjs b/libraries/botframework-config/eslint.config.cjs deleted file mode 100644 index 63647b52cc..0000000000 --- a/libraries/botframework-config/eslint.config.cjs +++ /dev/null @@ -1,10 +0,0 @@ -const onlyWarn = require("eslint-plugin-only-warn"); -const sharedConfig = require("../../eslint.config.cjs") - -module.exports = [ - ...sharedConfig, - { - plugins: { - "only-warn": onlyWarn, - }, - }]; diff --git a/libraries/botframework-config/package.json b/libraries/botframework-config/package.json index e747074b11..fa3eb0ee3b 100644 --- a/libraries/botframework-config/package.json +++ b/libraries/botframework-config/package.json @@ -34,7 +34,6 @@ "url": "git@github.com:Microsoft/botbuilder-js.git" }, "dependencies": { - "eslint-plugin-only-warn": "^1.1.0", "fs-extra": "^11.2.0", "uuid": "^10.0.0" }, @@ -45,7 +44,7 @@ "build": "tsc -b", "build:rollup": "yarn clean && yarn build && api-extractor run --verbose --local", "clean": "rimraf _ts3.4 lib tsconfig.tsbuildinfo", - "lint": "eslint .", + "lint": "eslint . --config ../../eslint.config.cjs", "postbuild": "downlevel-dts lib _ts3.4/lib --checksum", "test": "yarn build && nyc mocha tests/", "test:compat": "api-extractor run --verbose" diff --git a/libraries/botframework-config/src/botConfiguration.ts b/libraries/botframework-config/src/botConfiguration.ts index a39ee7fad5..65c907c852 100644 --- a/libraries/botframework-config/src/botConfiguration.ts +++ b/libraries/botframework-config/src/botConfiguration.ts @@ -71,7 +71,7 @@ export class BotConfiguration extends BotConfigurationBase { } } throw new Error( - `Error: no bot file found in ${folder}. Choose a different location or use msbot init to create a .bot file."` + `Error: no bot file found in ${folder}. Choose a different location or use msbot init to create a .bot file."`, ); } @@ -94,7 +94,7 @@ export class BotConfiguration extends BotConfigurationBase { } } throw new Error( - `Error: no bot file found in ${folder}. Choose a different location or use msbot init to create a .bot file."` + `Error: no bot file found in ${folder}. Choose a different location or use msbot init to create a .bot file."`, ); } @@ -330,7 +330,7 @@ export class BotConfiguration extends BotConfigurationBase { validateSecret(secret: string): void { if (!secret) { throw new Error( - 'You are attempting to perform an operation which needs access to the secret and --secret is missing' + 'You are attempting to perform an operation which needs access to the secret and --secret is missing', ); } @@ -344,7 +344,7 @@ export class BotConfiguration extends BotConfigurationBase { } } catch { throw new Error( - 'You are attempting to perform an operation which needs access to the secret and --secret is incorrect.' + 'You are attempting to perform an operation which needs access to the secret and --secret is incorrect.', ); } } diff --git a/libraries/botframework-config/src/models/connectedService.ts b/libraries/botframework-config/src/models/connectedService.ts index 81db2581de..415d0908be 100644 --- a/libraries/botframework-config/src/models/connectedService.ts +++ b/libraries/botframework-config/src/models/connectedService.ts @@ -28,7 +28,10 @@ export class ConnectedService implements IConnectedService { * @param source (Optional) JSON based service definition. * @param type (Optional) type of service being defined. */ - constructor(source: IConnectedService = {} as IConnectedService, public type?: ServiceTypes) { + constructor( + source: IConnectedService = {} as IConnectedService, + public type?: ServiceTypes, + ) { Object.assign(this, source); if (type) { this.type = type; diff --git a/libraries/botframework-config/tests/botRecipe.test.js b/libraries/botframework-config/tests/botRecipe.test.js index ee1cf3ff06..43e134b2f8 100644 --- a/libraries/botframework-config/tests/botRecipe.test.js +++ b/libraries/botframework-config/tests/botRecipe.test.js @@ -6,21 +6,22 @@ const { BotRecipe } = require('../lib'); function assertService(newService, oldService) { assert( newService.type === oldService.type, - `newService.type [${newService.type}] !== oldService.type [${oldService.type}]` + `newService.type [${newService.type}] !== oldService.type [${oldService.type}]`, ); assert(newService.id === oldService.id, `newService.id [${newService.id}] !== oldService.id [${oldService.id}]`); assert( newService.name === oldService.name, - `newService.name [${newService.name}] !== oldService.name [${oldService.name}]` + `newService.name [${newService.name}] !== oldService.name [${oldService.name}]`, ); assert( newService.url === oldService.url, - `newService.url [${newService.url}] !== oldService.url [${oldService.url}]` + `newService.url [${newService.url}] !== oldService.url [${oldService.url}]`, ); } describe('BotRecipe', function () { const recipe = new BotRecipe(); + it("should have a default version of '1.0'.", function () { assert(recipe.version === '1.0', `expected version '1.0', instead received ${recipe.version}`); }); @@ -28,7 +29,7 @@ describe('BotRecipe', function () { it('should have default resources be an empty array.', function () { assert( Array.isArray(recipe.resources), - `expected resources to be an Array, instead it is type "${typeof recipe.resources}"` + `expected resources to be an Array, instead it is type "${typeof recipe.resources}"`, ); assert(recipe.resources.length === 0, `initial resources should be length 0, not ${recipe.resources.length}`); }); @@ -45,15 +46,15 @@ describe('BotRecipe', function () { assert( newRecipe.version === oldVersion, - `expected version ${oldVersion}, instead received ${newRecipe.version}` + `expected version ${oldVersion}, instead received ${newRecipe.version}`, ); assert( Array.isArray(newRecipe.resources), - `expected resources to be an Array, instead it is type "${typeof newRecipe.resources}"` + `expected resources to be an Array, instead it is type "${typeof newRecipe.resources}"`, ); assert( newRecipe.resources.length === oldResources.length, - `initial resources should be length ${oldResources.length}, not ${newRecipe.resources.length}` + `initial resources should be length ${oldResources.length}, not ${newRecipe.resources.length}`, ); assertService(newRecipe.resources[0], oldEndpoint); }); diff --git a/libraries/botframework-config/tests/encryption.test.js b/libraries/botframework-config/tests/encryption.test.js index ca942beb2f..794e2ffc5d 100644 --- a/libraries/botframework-config/tests/encryption.test.js +++ b/libraries/botframework-config/tests/encryption.test.js @@ -65,7 +65,7 @@ describe('EncryptionTests', function () { assert.throws( () => encrypt.decryptString(encrypted, encrypt.generateKey()), - new Error('error:1C800064:Provider routines::bad decrypt') + new Error('error:1C800064:Provider routines::bad decrypt'), ); }); }); diff --git a/libraries/botframework-config/tests/loadAndSave.test.js b/libraries/botframework-config/tests/loadAndSave.test.js index d7d83ffa66..37470efc4c 100644 --- a/libraries/botframework-config/tests/loadAndSave.test.js +++ b/libraries/botframework-config/tests/loadAndSave.test.js @@ -99,7 +99,7 @@ describe('LoadAndSaveTests', function () { await assert.rejects( bf.BotConfiguration.load(saveBotPath), new Error( - 'You are attempting to perform an operation which needs access to the secret and --secret is missing' + 'You are attempting to perform an operation which needs access to the secret and --secret is missing', ), ); } @@ -158,12 +158,12 @@ describe('LoadAndSaveTests', function () { const appInsights = config2.services[i]; assert.ok( appInsights.instrumentationKey.includes('0000000'), - 'failed to decrypt instrumentationKey' + 'failed to decrypt instrumentationKey', ); assert.equal( appInsights.applicationId, '00000000-0000-0000-0000-000000000007', - 'failed to decrypt applicationId' + 'failed to decrypt applicationId', ); assert.equal(appInsights.apiKeys.key1, 'testKey1', 'failed to decrypt key1'); assert.equal(appInsights.apiKeys.key2, 'testKey2', 'failed to decrypt key2'); @@ -175,7 +175,7 @@ describe('LoadAndSaveTests', function () { const storage = config2.services[i]; assert.ok( storage.connectionString.includes('UseDevelopmentStorage'), - 'failed to decrypt connectionString' + 'failed to decrypt connectionString', ); assert.equal(storage.container, 'testContainer', 'failed to decrypt container'); } @@ -188,7 +188,7 @@ describe('LoadAndSaveTests', function () { assert.equal( storage.key, 'C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==', - 'failed to decrypt key' + 'failed to decrypt key', ); assert.equal(storage.database, 'testDatabase', 'failed to decrypt database'); assert.equal(storage.collection, 'testCollection', 'failed to decrypt collection'); @@ -264,12 +264,12 @@ describe('LoadAndSaveTests', function () { const appInsights = config2.services[i]; assert.ok( !appInsights.instrumentationKey.includes('0000000'), - 'failed to encrypt instrumentationKey' + 'failed to encrypt instrumentationKey', ); assert.equal( appInsights.applicationId, '00000000-0000-0000-0000-000000000007', - 'should not encrypt applicationId' + 'should not encrypt applicationId', ); assert.notEqual(appInsights.apiKeys.key1, 'testKey1', 'failed to encrypt key1'); assert.notEqual(appInsights.apiKeys.key2, 'testKey2', 'failed to encrypt key2'); @@ -281,7 +281,7 @@ describe('LoadAndSaveTests', function () { const storage = config2.services[i]; assert.ok( !storage.connectionString.includes('UseDevelopmentStorage'), - 'failed to encrypt connectionString' + 'failed to encrypt connectionString', ); assert.equal(storage.container, 'testContainer', 'should not have encrypted container'); } @@ -294,7 +294,7 @@ describe('LoadAndSaveTests', function () { assert.notEqual( storage.key, 'C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==', - 'failed to encrypt key' + 'failed to encrypt key', ); assert.equal(storage.database, 'testDatabase', 'should not have encrypted database'); assert.equal(storage.collection, 'testCollection', 'should not have encrypted collection'); diff --git a/libraries/botframework-config/tests/service.test.js b/libraries/botframework-config/tests/service.test.js index be8fc199ca..ae63b1c749 100644 --- a/libraries/botframework-config/tests/service.test.js +++ b/libraries/botframework-config/tests/service.test.js @@ -33,7 +33,7 @@ describe('Service Tests', function () { }); assert.equal( qnaWithQnamakerHostname.hostname, - 'https://MyServiceThatDoesntNeedAppending.azurewebsites.net/qnamaker' + 'https://MyServiceThatDoesntNeedAppending.azurewebsites.net/qnamaker', ); }); From 1fe90aa25a76b743860a2f8fcc5235857530ab69 Mon Sep 17 00:00:00 2001 From: Joel Mut <62260472+sw-joelmut@users.noreply.github.com> Date: Mon, 6 Jan 2025 12:02:54 -0300 Subject: [PATCH 07/22] Fix lint (#4824) --- libraries/botbuilder-ai-luis/eslint.config.cjs | 11 ----------- libraries/botbuilder-ai-luis/package.json | 5 ++--- 2 files changed, 2 insertions(+), 14 deletions(-) delete mode 100644 libraries/botbuilder-ai-luis/eslint.config.cjs diff --git a/libraries/botbuilder-ai-luis/eslint.config.cjs b/libraries/botbuilder-ai-luis/eslint.config.cjs deleted file mode 100644 index c56fd90ec6..0000000000 --- a/libraries/botbuilder-ai-luis/eslint.config.cjs +++ /dev/null @@ -1,11 +0,0 @@ -const onlyWarn = require("eslint-plugin-only-warn"); -const sharedConfig = require("../../eslint.config.cjs") - -module.exports = [ - ...sharedConfig, - { - plugins: { - "only-warn": onlyWarn, - }, - } -] diff --git a/libraries/botbuilder-ai-luis/package.json b/libraries/botbuilder-ai-luis/package.json index 9ea01dba9d..8cb39f9621 100644 --- a/libraries/botbuilder-ai-luis/package.json +++ b/libraries/botbuilder-ai-luis/package.json @@ -30,14 +30,13 @@ } }, "dependencies": { - "botbuilder-ai": "4.1.6", - "eslint-plugin-only-warn": "^1.1.0" + "botbuilder-ai": "4.1.6" }, "scripts": { "build": "tsc -b", "clean": "rimraf _ts3.4 lib tsconfig.tsbuildinfo", "depcheck": "depcheck --config ../../.depcheckrc", - "lint": "eslint .", + "lint": "eslint . --config ../../eslint.config.cjs", "postbuild": "downlevel-dts lib _ts3.4/lib --checksum" }, "files": [ From 8d39ef5fd2ae5c1c679754894a40591270ced607 Mon Sep 17 00:00:00 2001 From: Joel Mut <62260472+sw-joelmut@users.noreply.github.com> Date: Mon, 6 Jan 2025 12:03:23 -0300 Subject: [PATCH 08/22] fix: [#4684] ESLint issues in botframework-streaming (#4825) * Fix ESLint with --fix * Fix ESLint in botframework-streaming --- .../botframework-streaming/eslint.config.cjs | 11 +- libraries/botframework-streaming/package.json | 1 - .../src/assemblers/payloadAssembler.ts | 9 +- .../src/contentStream.ts | 18 +- .../src/disassemblers/cancelDisassembler.ts | 2 +- .../src/disassemblers/payloadDisassembler.ts | 5 +- .../src/disassemblers/requestDisassembler.ts | 6 +- .../src/httpContentStream.ts | 5 +- .../src/interfaces/IBrowserFileReader.ts | 2 - .../src/interfaces/IBrowserWebSocket.ts | 2 - .../src/interfaces/IEventEmitter.ts | 8 +- .../src/interfaces/INodeBuffer.ts | 5 +- .../src/interfaces/INodeDuplex.ts | 1 - .../src/interfaces/INodeIncomingMessage.ts | 2 - .../src/interfaces/INodeSocket.ts | 1 - .../src/interfaces/ISocket.ts | 3 - .../src/namedPipe/namedPipeClient.ts | 5 +- .../src/namedPipe/namedPipeServer.ts | 6 +- .../src/namedPipe/namedPipeTransport.ts | 1 - .../src/payloadTransport/payloadReceiver.ts | 6 +- .../transportDisconnectedEventHandler.ts | 1 - .../src/payloads/headerSerializer.ts | 2 +- .../src/payloads/index.ts | 1 - .../src/payloads/payloadAssemblerManager.ts | 2 +- .../src/payloads/requestManager.ts | 1 - .../src/payloads/sendOperations.ts | 16 +- .../src/protocolAdapter.ts | 6 +- .../src/streamingRequest.ts | 5 +- .../src/streamingResponse.ts | 5 +- .../src/subscribableStream.ts | 3 - .../src/utilities/createNodeServer.ts | 9 +- .../src/webSocket/browserWebSocket.ts | 6 +- .../src/webSocket/browserWebSocketClient.ts | 7 +- .../src/webSocket/nodeWebSocket.ts | 4 - .../src/webSocket/nodeWebSocketClient.ts | 7 +- .../src/webSocket/webSocketServer.ts | 2 +- .../src/webSocket/webSocketTransport.ts | 1 - .../tests/CancelDisassembler.test.js | 26 ++ .../tests/ContentStream.test.js | 8 +- .../tests/Disassembler.test.js | 46 -- .../tests/NamedPipe.test.js | 57 +-- .../tests/NodeWebSocket.test.js | 22 +- ...mbler.test.js => PayloadAssembler.test.js} | 393 +++++++----------- .../tests/PayloadAssemblerManager.test.js | 86 ++++ .../tests/PayloadSender.test.js | 12 +- .../tests/ProtocolAdapter.test.js | 32 +- .../tests/RequestDisassembler.test.js | 22 + .../tests/RequestManager.test.js | 2 +- .../tests/StreamManager.test.js | 4 +- .../tests/StreamingRequest.test.js | 2 +- .../tests/WebSocket.test.js | 58 +-- .../tests/WebSocketClientServer.test.js | 4 +- .../tests/helpers/fauxSock.js | 2 +- .../tests/helpers/fauxSocket.js | 4 - 54 files changed, 464 insertions(+), 493 deletions(-) create mode 100644 libraries/botframework-streaming/tests/CancelDisassembler.test.js delete mode 100644 libraries/botframework-streaming/tests/Disassembler.test.js rename libraries/botframework-streaming/tests/{Assembler.test.js => PayloadAssembler.test.js} (62%) create mode 100644 libraries/botframework-streaming/tests/PayloadAssemblerManager.test.js create mode 100644 libraries/botframework-streaming/tests/RequestDisassembler.test.js diff --git a/libraries/botframework-streaming/eslint.config.cjs b/libraries/botframework-streaming/eslint.config.cjs index 2b279a321f..f1b7a431b0 100644 --- a/libraries/botframework-streaming/eslint.config.cjs +++ b/libraries/botframework-streaming/eslint.config.cjs @@ -1,13 +1,8 @@ -const onlyWarn = require("eslint-plugin-only-warn"); -const sharedConfig = require("../../eslint.config.cjs") +const sharedConfig = require('../../eslint.config.cjs'); module.exports = [ ...sharedConfig, { - ignores: ["**/es5/"], + ignores: ['**/es5/'], }, - { - plugins: { - "only-warn": onlyWarn, - }, - }] +]; diff --git a/libraries/botframework-streaming/package.json b/libraries/botframework-streaming/package.json index a1b2d1a885..fbcc72a877 100644 --- a/libraries/botframework-streaming/package.json +++ b/libraries/botframework-streaming/package.json @@ -32,7 +32,6 @@ "dependencies": { "@types/node": "18.19.47", "@types/ws": "^6.0.3", - "eslint-plugin-only-warn": "^1.1.0", "uuid": "^10.0.0", "ws": "^7.5.10" }, diff --git a/libraries/botframework-streaming/src/assemblers/payloadAssembler.ts b/libraries/botframework-streaming/src/assemblers/payloadAssembler.ts index 2883426017..9eeb94a46e 100644 --- a/libraries/botframework-streaming/src/assemblers/payloadAssembler.ts +++ b/libraries/botframework-streaming/src/assemblers/payloadAssembler.ts @@ -39,7 +39,10 @@ export class PayloadAssembler { * @param streamManager The [StreamManager](xref:botframework-streaming.StreamManager) managing the stream being assembled. * @param params Parameters for a streaming assembler. */ - constructor(private readonly streamManager: StreamManager, params: IAssemblerParams) { + constructor( + private readonly streamManager: StreamManager, + params: IAssemblerParams, + ) { if (params.header) { this.id = params.header.id; this.payloadType = params.header.payloadType; @@ -141,7 +144,7 @@ export class PayloadAssembler { private async processStreams( responsePayload: IResponsePayload | IRequestPayload, - receiveResponse: IReceiveResponse | IReceiveRequest + receiveResponse: IReceiveResponse | IReceiveRequest, ): Promise { responsePayload.streams?.forEach((responseStream) => { // There was a bug in how streams were handled. In .NET, the StreamDescription definiton mapped the @@ -151,7 +154,7 @@ export class PayloadAssembler { // .NET code: // https://github.com/microsoft/botbuilder-dotnet/blob/a79036ddf6625ec3fd68a6f7295886eb7831bc1c/libraries/Microsoft.Bot.Streaming/Payloads/Models/StreamDescription.cs#L28-L29 const contentType = - ((responseStream as unknown) as Record).type ?? responseStream.contentType; + (responseStream as unknown as Record).type ?? responseStream.contentType; const contentAssembler = this.streamManager.getPayloadAssembler(responseStream.id); diff --git a/libraries/botframework-streaming/src/contentStream.ts b/libraries/botframework-streaming/src/contentStream.ts index b554df3e28..b67059a694 100644 --- a/libraries/botframework-streaming/src/contentStream.ts +++ b/libraries/botframework-streaming/src/contentStream.ts @@ -91,7 +91,6 @@ export class ContentStream { return JSON.parse(stringToParse); } - // eslint-disable-next-line @typescript-eslint/no-explicit-any private async readAll(): Promise> { // do a read-all const allData: INodeBuffer[] = []; @@ -107,14 +106,15 @@ export class ContentStream { if (count < this.length) { const readToEnd = new Promise((resolve): void => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const callback = (cs: ContentStream) => (chunk: any): void => { - allData.push(chunk); - count += (chunk as INodeBuffer).length; - if (count === cs.length) { - resolve(true); - } - }; + const callback = + (cs: ContentStream) => + (chunk: any): void => { + allData.push(chunk); + count += (chunk as INodeBuffer).length; + if (count === cs.length) { + resolve(true); + } + }; stream.subscribe(callback(this)); }); diff --git a/libraries/botframework-streaming/src/disassemblers/cancelDisassembler.ts b/libraries/botframework-streaming/src/disassemblers/cancelDisassembler.ts index a4bf7ec5b9..1c08feb1b3 100644 --- a/libraries/botframework-streaming/src/disassemblers/cancelDisassembler.ts +++ b/libraries/botframework-streaming/src/disassemblers/cancelDisassembler.ts @@ -22,7 +22,7 @@ export class CancelDisassembler { constructor( private readonly sender: PayloadSender, private readonly id: string, - private readonly payloadType: PayloadTypes + private readonly payloadType: PayloadTypes, ) {} /** diff --git a/libraries/botframework-streaming/src/disassemblers/payloadDisassembler.ts b/libraries/botframework-streaming/src/disassemblers/payloadDisassembler.ts index ad4b70bf27..3d5a8c27da 100644 --- a/libraries/botframework-streaming/src/disassemblers/payloadDisassembler.ts +++ b/libraries/botframework-streaming/src/disassemblers/payloadDisassembler.ts @@ -24,7 +24,10 @@ export abstract class PayloadDisassembler { * @param sender The [PayloadSender](xref:botframework-streaming.PayloadSender) used to send the disassembled payload chunks. * @param id The ID of this disassembler. */ - constructor(private readonly sender: PayloadSender, private readonly id: string) {} + constructor( + private readonly sender: PayloadSender, + private readonly id: string, + ) {} /** * Serializes the item into the [IStreamWrapper](xref:botframework-streaming.IStreamWrapper) that exposes the stream and length of the result. diff --git a/libraries/botframework-streaming/src/disassemblers/requestDisassembler.ts b/libraries/botframework-streaming/src/disassemblers/requestDisassembler.ts index 8042e2e7e4..7fa5eabf4a 100644 --- a/libraries/botframework-streaming/src/disassemblers/requestDisassembler.ts +++ b/libraries/botframework-streaming/src/disassemblers/requestDisassembler.ts @@ -25,7 +25,11 @@ export class RequestDisassembler extends PayloadDisassembler { * @param id The ID of this disassembler. * @param request The request to be disassembled. */ - constructor(sender: PayloadSender, id: string, public request?: StreamingRequest) { + constructor( + sender: PayloadSender, + id: string, + public request?: StreamingRequest, + ) { super(sender, id); } diff --git a/libraries/botframework-streaming/src/httpContentStream.ts b/libraries/botframework-streaming/src/httpContentStream.ts index 0f32a1e885..7599d661ed 100644 --- a/libraries/botframework-streaming/src/httpContentStream.ts +++ b/libraries/botframework-streaming/src/httpContentStream.ts @@ -41,7 +41,10 @@ export class HttpContent { * @param headers The Streaming Http content header definition. * @param stream The stream of buffered data. */ - constructor(public headers: IHttpContentHeaders, private readonly stream: SubscribableStream) {} + constructor( + public headers: IHttpContentHeaders, + private readonly stream: SubscribableStream, + ) {} /** * Gets the data contained within this [HttpContent](xref:botframework-streaming.HttpContent). diff --git a/libraries/botframework-streaming/src/interfaces/IBrowserFileReader.ts b/libraries/botframework-streaming/src/interfaces/IBrowserFileReader.ts index 0e0f3ef23e..ccf351e441 100644 --- a/libraries/botframework-streaming/src/interfaces/IBrowserFileReader.ts +++ b/libraries/botframework-streaming/src/interfaces/IBrowserFileReader.ts @@ -13,9 +13,7 @@ * This interface supports the framework and is not intended to be called directly for your code. */ export interface IBrowserFileReader { - /* eslint-disable @typescript-eslint/no-explicit-any */ result: any; onload: (event: any) => void; readAsArrayBuffer: (blobOrFile: any) => void; - /* eslint-enable @typescript-eslint/no-explicit-any */ } diff --git a/libraries/botframework-streaming/src/interfaces/IBrowserWebSocket.ts b/libraries/botframework-streaming/src/interfaces/IBrowserWebSocket.ts index 0a03f808b6..c62976e4fc 100644 --- a/libraries/botframework-streaming/src/interfaces/IBrowserWebSocket.ts +++ b/libraries/botframework-streaming/src/interfaces/IBrowserWebSocket.ts @@ -13,13 +13,11 @@ * This interface supports the framework and is not intended to be called directly for your code. */ export interface IBrowserWebSocket { - /* eslint-disable @typescript-eslint/no-explicit-any */ onclose: (event: any) => void; onerror: (event: any) => void; onmessage: (event: any) => void; onopen: (event: any) => void; send(buffer: any): void; - /* eslint-enable @typescript-eslint/no-explicit-any */ readyState: number; close(): void; } diff --git a/libraries/botframework-streaming/src/interfaces/IEventEmitter.ts b/libraries/botframework-streaming/src/interfaces/IEventEmitter.ts index 8da005acb1..aa8b2e64b0 100644 --- a/libraries/botframework-streaming/src/interfaces/IEventEmitter.ts +++ b/libraries/botframework-streaming/src/interfaces/IEventEmitter.ts @@ -12,7 +12,6 @@ * This interface supports the framework and is not intended to be called directly for your code. */ export interface IEventEmitter { - /* eslint-disable @typescript-eslint/no-explicit-any */ addListener(event: string | symbol, listener: (...args: any[]) => void): this; emit(event: string | symbol, ...args: any[]): boolean; off(event: string | symbol, listener: (...args: any[]) => void): this; @@ -21,14 +20,11 @@ export interface IEventEmitter { removeListener(event: string | symbol, listener: (...args: any[]) => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - /* eslint-enable @typescript-eslint/no-explicit-any */ removeAllListeners(event?: string | symbol): this; setMaxListeners(n: number): this; getMaxListeners(): number; - /* eslint-disable @typescript-eslint/ban-types */ - listeners(event: string | symbol): Function[]; - rawListeners(event: string | symbol): Function[]; - /* eslint-enable @typescript-eslint/ban-types */ + listeners(event: string | symbol): ((...args: any[]) => void)[]; + rawListeners(event: string | symbol): ((...args: any[]) => void)[]; listenerCount(type: string | symbol): number; eventNames(): Array; } diff --git a/libraries/botframework-streaming/src/interfaces/INodeBuffer.ts b/libraries/botframework-streaming/src/interfaces/INodeBuffer.ts index 78a3bf09eb..5658ae88a7 100644 --- a/libraries/botframework-streaming/src/interfaces/INodeBuffer.ts +++ b/libraries/botframework-streaming/src/interfaces/INodeBuffer.ts @@ -26,11 +26,9 @@ export type BufferEncoding = * This interface supports the framework and is not intended to be called directly for your code. */ export interface INodeBuffer extends Uint8Array { - // eslint-disable-next-line @typescript-eslint/no-explicit-any constructor: any; write(string: string, offset?: number, length?: number, encoding?: string): number; toString(encoding?: string, start?: number, end?: number): string; - // eslint-disable-next-line @typescript-eslint/no-explicit-any toJSON(): { type: 'Buffer'; data: any[] }; equals(otherBuffer: Uint8Array): boolean; compare( @@ -38,7 +36,7 @@ export interface INodeBuffer extends Uint8Array { targetStart?: number, targetEnd?: number, sourceStart?: number, - sourceEnd?: number + sourceEnd?: number, ): number; copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; slice(start?: number, end?: number): this; @@ -92,7 +90,6 @@ export interface INodeBuffer extends Uint8Array { writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - // eslint-disable-next-line @typescript-eslint/no-explicit-any fill(value: any, offset?: number, end?: number): this; indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: string): number; lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: string): number; diff --git a/libraries/botframework-streaming/src/interfaces/INodeDuplex.ts b/libraries/botframework-streaming/src/interfaces/INodeDuplex.ts index bf9db21bdb..4020bece05 100644 --- a/libraries/botframework-streaming/src/interfaces/INodeDuplex.ts +++ b/libraries/botframework-streaming/src/interfaces/INodeDuplex.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types */ /** * @module botframework-streaming */ diff --git a/libraries/botframework-streaming/src/interfaces/INodeIncomingMessage.ts b/libraries/botframework-streaming/src/interfaces/INodeIncomingMessage.ts index efa181a64a..b48a8de2ff 100644 --- a/libraries/botframework-streaming/src/interfaces/INodeIncomingMessage.ts +++ b/libraries/botframework-streaming/src/interfaces/INodeIncomingMessage.ts @@ -15,12 +15,10 @@ export interface INodeIncomingMessage { /** * Optional. The request headers. */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any headers?: any; /** * Optional. The request method. */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any method?: any; } diff --git a/libraries/botframework-streaming/src/interfaces/INodeSocket.ts b/libraries/botframework-streaming/src/interfaces/INodeSocket.ts index 5453a66a44..81aee33eae 100644 --- a/libraries/botframework-streaming/src/interfaces/INodeSocket.ts +++ b/libraries/botframework-streaming/src/interfaces/INodeSocket.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types */ /** * @module botframework-streaming */ diff --git a/libraries/botframework-streaming/src/interfaces/ISocket.ts b/libraries/botframework-streaming/src/interfaces/ISocket.ts index 84844176f8..915dbb806a 100644 --- a/libraries/botframework-streaming/src/interfaces/ISocket.ts +++ b/libraries/botframework-streaming/src/interfaces/ISocket.ts @@ -18,10 +18,7 @@ export interface ISocket { write(buffer: INodeBuffer); connect(serverAddress: string): Promise; close(); - // eslint-disable-next-line @typescript-eslint/no-explicit-any setOnMessageHandler(handler: (x: any) => void); - // eslint-disable-next-line @typescript-eslint/no-explicit-any setOnErrorHandler(handler: (x: any) => void); - // eslint-disable-next-line @typescript-eslint/no-explicit-any setOnCloseHandler(handler: (x: any) => void); } diff --git a/libraries/botframework-streaming/src/namedPipe/namedPipeClient.ts b/libraries/botframework-streaming/src/namedPipe/namedPipeClient.ts index dc86172118..4da283e313 100644 --- a/libraries/botframework-streaming/src/namedPipe/namedPipeClient.ts +++ b/libraries/botframework-streaming/src/namedPipe/namedPipeClient.ts @@ -47,7 +47,7 @@ export class NamedPipeClient implements IStreamingTransportClient { this._requestHandler, this._requestManager, this._sender, - this._receiver + this._receiver, ); } @@ -83,7 +83,6 @@ export class NamedPipeClient implements IStreamingTransportClient { return this._protocolAdapter.sendRequest(request); } - // eslint-disable-next-line @typescript-eslint/no-explicit-any private onConnectionDisconnected(sender: Record, args: any): void { if (!this._isDisconnecting) { this._isDisconnecting = true; @@ -101,7 +100,7 @@ export class NamedPipeClient implements IStreamingTransportClient { .then((): void => {}) .catch((error): void => { throw new Error( - `Failed to reconnect. Reason: ${error.message} Sender: ${sender} Args: ${args}. ` + `Failed to reconnect. Reason: ${error.message} Sender: ${sender} Args: ${args}. `, ); }); } diff --git a/libraries/botframework-streaming/src/namedPipe/namedPipeServer.ts b/libraries/botframework-streaming/src/namedPipe/namedPipeServer.ts index 0ebe42752e..635b69f908 100644 --- a/libraries/botframework-streaming/src/namedPipe/namedPipeServer.ts +++ b/libraries/botframework-streaming/src/namedPipe/namedPipeServer.ts @@ -32,7 +32,11 @@ export class NamedPipeServer implements IStreamingTransportServer { * @param requestHandler Optional [RequestHandler](xref:botframework-streaming.RequestHandler) to process incoming messages received by this client. * @param autoReconnect Deprecated: Automatic reconnection is the default behavior. */ - constructor(private readonly baseName: string, requestHandler?: RequestHandler, autoReconnect?: boolean) { + constructor( + private readonly baseName: string, + requestHandler?: RequestHandler, + autoReconnect?: boolean, + ) { if (!baseName) { throw new TypeError('NamedPipeServer: Missing baseName parameter'); } diff --git a/libraries/botframework-streaming/src/namedPipe/namedPipeTransport.ts b/libraries/botframework-streaming/src/namedPipe/namedPipeTransport.ts index 2daebe1306..909e896ac4 100644 --- a/libraries/botframework-streaming/src/namedPipe/namedPipeTransport.ts +++ b/libraries/botframework-streaming/src/namedPipe/namedPipeTransport.ts @@ -20,7 +20,6 @@ export class NamedPipeTransport implements ITransportSender, ITransportReceiver private _activeOffset = 0; private _activeReceiveCount = 0; private _activeReceiveResolve: (resolve: INodeBuffer) => void; - // eslint-disable-next-line @typescript-eslint/no-explicit-any private _activeReceiveReject: (reason?: any) => void; /** diff --git a/libraries/botframework-streaming/src/payloadTransport/payloadReceiver.ts b/libraries/botframework-streaming/src/payloadTransport/payloadReceiver.ts index 870b5d32d6..3ad941fc86 100644 --- a/libraries/botframework-streaming/src/payloadTransport/payloadReceiver.ts +++ b/libraries/botframework-streaming/src/payloadTransport/payloadReceiver.ts @@ -54,7 +54,7 @@ export class PayloadReceiver { */ subscribe( getStream: (header: IHeader) => SubscribableStream, - receiveAction: (header: IHeader, stream: SubscribableStream, count: number) => void + receiveAction: (header: IHeader, stream: SubscribableStream, count: number) => void, ): void { this._getStream = getStream; this._receiveAction = receiveAction; @@ -86,7 +86,7 @@ export class PayloadReceiver { let readSoFar = 0; while (readSoFar < PayloadConstants.MaxHeaderLength) { this._receiveHeaderBuffer = await this._receiver.receive( - PayloadConstants.MaxHeaderLength - readSoFar + PayloadConstants.MaxHeaderLength - readSoFar, ); if (this._receiveHeaderBuffer) { @@ -108,7 +108,7 @@ export class PayloadReceiver { ) { const count = Math.min( header.payloadLength - bytesActuallyRead, - PayloadConstants.MaxPayloadLength + PayloadConstants.MaxPayloadLength, ); this._receivePayloadBuffer = await this._receiver.receive(count); bytesActuallyRead += this._receivePayloadBuffer.byteLength; diff --git a/libraries/botframework-streaming/src/payloadTransport/transportDisconnectedEventHandler.ts b/libraries/botframework-streaming/src/payloadTransport/transportDisconnectedEventHandler.ts index dcc00f39c4..5012fbfad3 100644 --- a/libraries/botframework-streaming/src/payloadTransport/transportDisconnectedEventHandler.ts +++ b/libraries/botframework-streaming/src/payloadTransport/transportDisconnectedEventHandler.ts @@ -8,5 +8,4 @@ import { TransportDisconnectedEvent } from './transportDisconnectedEvent'; -// eslint-disable-next-line @typescript-eslint/no-explicit-any export type TransportDisconnectedEventHandler = (sender: any, e: TransportDisconnectedEvent) => void; diff --git a/libraries/botframework-streaming/src/payloads/headerSerializer.ts b/libraries/botframework-streaming/src/payloads/headerSerializer.ts index 67eeef8972..cb54b56e3e 100644 --- a/libraries/botframework-streaming/src/payloads/headerSerializer.ts +++ b/libraries/botframework-streaming/src/payloads/headerSerializer.ts @@ -41,7 +41,7 @@ export class HeaderSerializer { this.headerLengthPadder(header.payloadLength, this.LengthLength, '0'), this.LengthOffset, this.LengthLength, - this.Encoding + this.Encoding, ); buffer.write(this.Delimiter, this.LengthDelimeterOffset, 1, this.Encoding); buffer.write(header.id, this.IdOffset); diff --git a/libraries/botframework-streaming/src/payloads/index.ts b/libraries/botframework-streaming/src/payloads/index.ts index 3f13e4f3e7..17ec994684 100644 --- a/libraries/botframework-streaming/src/payloads/index.ts +++ b/libraries/botframework-streaming/src/payloads/index.ts @@ -12,4 +12,3 @@ export * from './payloadAssemblerManager'; export * from './payloadTypes'; export * from './requestManager'; export * from './sendOperations'; -export * from './streamManager'; diff --git a/libraries/botframework-streaming/src/payloads/payloadAssemblerManager.ts b/libraries/botframework-streaming/src/payloads/payloadAssemblerManager.ts index 6e03145a3e..417723194d 100644 --- a/libraries/botframework-streaming/src/payloads/payloadAssemblerManager.ts +++ b/libraries/botframework-streaming/src/payloads/payloadAssemblerManager.ts @@ -27,7 +27,7 @@ export class PayloadAssemblerManager { constructor( private readonly streamManager: StreamManager, private readonly onReceiveResponse: (id: string, receiveResponse: IReceiveResponse) => Promise, - private readonly onReceiveRequest: (id: string, receiveRequest: IReceiveRequest) => Promise + private readonly onReceiveRequest: (id: string, receiveRequest: IReceiveRequest) => Promise, ) {} /** diff --git a/libraries/botframework-streaming/src/payloads/requestManager.ts b/libraries/botframework-streaming/src/payloads/requestManager.ts index 2b7d9d46b7..524cc2bb75 100644 --- a/libraries/botframework-streaming/src/payloads/requestManager.ts +++ b/libraries/botframework-streaming/src/payloads/requestManager.ts @@ -13,7 +13,6 @@ import { IReceiveResponse } from '../interfaces'; class PendingRequest { requestId: string; resolve: (response: IReceiveResponse) => void; - // eslint-disable-next-line @typescript-eslint/no-explicit-any reject: (reason?: any) => void; } diff --git a/libraries/botframework-streaming/src/payloads/sendOperations.ts b/libraries/botframework-streaming/src/payloads/sendOperations.ts index 13da105a9c..c24c8b2a54 100644 --- a/libraries/botframework-streaming/src/payloads/sendOperations.ts +++ b/libraries/botframework-streaming/src/payloads/sendOperations.ts @@ -41,11 +41,9 @@ export class SendOperations { await disassembler.disassemble(); if (request.streams) { - request.streams.forEach( - async (contentStream): Promise => { - await new HttpContentStreamDisassembler(this.payloadSender, contentStream).disassemble(); - } - ); + request.streams.forEach(async (contentStream): Promise => { + await new HttpContentStreamDisassembler(this.payloadSender, contentStream).disassemble(); + }); } } @@ -61,11 +59,9 @@ export class SendOperations { await disassembler.disassemble(); if (response.streams) { - response.streams.forEach( - async (contentStream): Promise => { - await new HttpContentStreamDisassembler(this.payloadSender, contentStream).disassemble(); - } - ); + response.streams.forEach(async (contentStream): Promise => { + await new HttpContentStreamDisassembler(this.payloadSender, contentStream).disassemble(); + }); } } diff --git a/libraries/botframework-streaming/src/protocolAdapter.ts b/libraries/botframework-streaming/src/protocolAdapter.ts index 9690e739f8..104373670e 100644 --- a/libraries/botframework-streaming/src/protocolAdapter.ts +++ b/libraries/botframework-streaming/src/protocolAdapter.ts @@ -43,7 +43,7 @@ export class ProtocolAdapter { requestHandler: RequestHandler, requestManager: RequestManager, sender: PayloadSender, - receiver: PayloadReceiver + receiver: PayloadReceiver, ) { this.requestHandler = requestHandler; this.requestManager = requestManager; @@ -54,12 +54,12 @@ export class ProtocolAdapter { this.assemblerManager = new PayloadAssemblerManager( this.streamManager, (id: string, response: IReceiveResponse): Promise => this.onReceiveResponse(id, response), - (id: string, request: IReceiveRequest): Promise => this.onReceiveRequest(id, request) + (id: string, request: IReceiveRequest): Promise => this.onReceiveRequest(id, request), ); this.payloadReceiver.subscribe( (header: IHeader): SubscribableStream => this.assemblerManager.getPayloadStream(header), (header: IHeader, contentStream: SubscribableStream, contentLength: number): void => - this.assemblerManager.onReceive(header, contentStream, contentLength) + this.assemblerManager.onReceive(header, contentStream, contentLength), ); } diff --git a/libraries/botframework-streaming/src/streamingRequest.ts b/libraries/botframework-streaming/src/streamingRequest.ts index 84870da62f..819977701f 100644 --- a/libraries/botframework-streaming/src/streamingRequest.ts +++ b/libraries/botframework-streaming/src/streamingRequest.ts @@ -64,7 +64,6 @@ export class StreamingRequest { * * @param body The JSON text to write to the body of the streamingRequest. */ - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any setBody(body: any): void { if (typeof body === 'string') { const stream = new SubscribableStream(); @@ -75,8 +74,8 @@ export class StreamingRequest { type: 'application/json; charset=utf-8', contentLength: stream.length, }, - stream - ) + stream, + ), ); } else if (typeof body === 'object') { this.addStream(body); diff --git a/libraries/botframework-streaming/src/streamingResponse.ts b/libraries/botframework-streaming/src/streamingResponse.ts index 55109d8485..f730e1250b 100644 --- a/libraries/botframework-streaming/src/streamingResponse.ts +++ b/libraries/botframework-streaming/src/streamingResponse.ts @@ -46,7 +46,6 @@ export class StreamingResponse { * * @param body The JSON text to write to the body of the streaming response. */ - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any setBody(body: any): void { const stream = new SubscribableStream(); stream.write(JSON.stringify(body), 'utf8'); @@ -56,8 +55,8 @@ export class StreamingResponse { type: 'application/json; charset=utf-8', contentLength: stream.length, }, - stream - ) + stream, + ), ); } } diff --git a/libraries/botframework-streaming/src/subscribableStream.ts b/libraries/botframework-streaming/src/subscribableStream.ts index f99959e81c..2b2702d372 100644 --- a/libraries/botframework-streaming/src/subscribableStream.ts +++ b/libraries/botframework-streaming/src/subscribableStream.ts @@ -14,7 +14,6 @@ export class SubscribableStream extends Duplex { length = 0; private readonly bufferList: Buffer[] = []; - // eslint-disable-next-line @typescript-eslint/no-explicit-any private _onData: (chunk: any) => void; /** @@ -34,7 +33,6 @@ export class SubscribableStream extends Duplex { * @param _encoding The encoding. Unused in the implementation of Duplex. * @param callback Callback for when this chunk of data is flushed. */ - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any _write(chunk: any, _encoding: string, callback: (error?: Error | null) => void): void { const buffer = Buffer.from(chunk); this.bufferList.push(buffer); @@ -72,7 +70,6 @@ export class SubscribableStream extends Duplex { * * @param onData Callback to be called when onData is executed. */ - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any subscribe(onData: (chunk: any) => void): void { this._onData = onData; } diff --git a/libraries/botframework-streaming/src/utilities/createNodeServer.ts b/libraries/botframework-streaming/src/utilities/createNodeServer.ts index 47d2edcd60..f8ec5e6203 100644 --- a/libraries/botframework-streaming/src/utilities/createNodeServer.ts +++ b/libraries/botframework-streaming/src/utilities/createNodeServer.ts @@ -35,27 +35,24 @@ export function createNodeServer(callback?: ConnectionListener): INodeServer { * @returns a server factory function */ export function getServerFactory(): (callback?: ConnectionListener) => INodeServer { - if (typeof require !== undefined) { - // eslint-disable-next-line @typescript-eslint/no-var-requires + if (typeof require !== 'undefined') { + // eslint-disable-next-line @typescript-eslint/no-require-imports return require('net').Server; } throw TypeError( - "require is undefined. Must be in a Node module to require 'net' dynamically in order to fetch Server factory." + "require is undefined. Must be in a Node module to require 'net' dynamically in order to fetch Server factory.", ); } -// eslint-disable-next-line @typescript-eslint/no-explicit-any function isNetServer(o: any): o is INodeServer { return hasCloseMethod(o) && hasListenMethod(o); } -// eslint-disable-next-line @typescript-eslint/no-explicit-any function hasCloseMethod(o: any): o is INodeServer { return o.close && typeof o.close === 'function'; } -// eslint-disable-next-line @typescript-eslint/no-explicit-any function hasListenMethod(o: any): o is INodeServer { return o.listen && typeof o.listen === 'function'; } diff --git a/libraries/botframework-streaming/src/webSocket/browserWebSocket.ts b/libraries/botframework-streaming/src/webSocket/browserWebSocket.ts index bbec707294..83d885b9f7 100644 --- a/libraries/botframework-streaming/src/webSocket/browserWebSocket.ts +++ b/libraries/botframework-streaming/src/webSocket/browserWebSocket.ts @@ -32,7 +32,6 @@ export class BrowserWebSocket implements ISocket { */ async connect(serverAddress: string): Promise { let resolver: (value: void | PromiseLike) => void; - // eslint-disable-next-line @typescript-eslint/no-explicit-any let rejector: (reason?: any) => void; if (!this.webSocket) { @@ -83,7 +82,6 @@ export class BrowserWebSocket implements ISocket { * * @param handler The callback to handle the "message" event. */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any setOnMessageHandler(handler: (x: any) => void): void { const bufferKey = 'buffer'; const packets = []; @@ -92,7 +90,7 @@ export class BrowserWebSocket implements ISocket { const queueEntry = { buffer: null }; packets.push(queueEntry); fileReader.onload = (e): void => { - const t = (e.target as unknown) as IBrowserFileReader; + const t = e.target as unknown as IBrowserFileReader; queueEntry[bufferKey] = t.result; if (packets[0] === queueEntry) { while (0 < packets.length && packets[0][bufferKey]) { @@ -110,7 +108,6 @@ export class BrowserWebSocket implements ISocket { * * @param handler The callback to handle the "error" event. */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any setOnErrorHandler(handler: (x: any) => void): void { this.webSocket.onerror = (error): void => { if (error) { @@ -124,7 +121,6 @@ export class BrowserWebSocket implements ISocket { * * @param handler The callback to handle the "close" event. */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any setOnCloseHandler(handler: (x: any) => void): void { this.webSocket.onclose = handler; } diff --git a/libraries/botframework-streaming/src/webSocket/browserWebSocketClient.ts b/libraries/botframework-streaming/src/webSocket/browserWebSocketClient.ts index 7d7902cfd1..fa7a5fe5d2 100644 --- a/libraries/botframework-streaming/src/webSocket/browserWebSocketClient.ts +++ b/libraries/botframework-streaming/src/webSocket/browserWebSocketClient.ts @@ -59,7 +59,7 @@ export class WebSocketClient implements IStreamingTransportClient { this._requestHandler, this._requestManager, this._sender, - this._receiver + this._receiver, ); } @@ -94,7 +94,6 @@ export class WebSocketClient implements IStreamingTransportClient { return this._protocolAdapter.sendRequest(request); } - // eslint-disable-next-line @typescript-eslint/no-explicit-any private onConnectionDisconnected(sender: Record, args: any): void { // Rejects all pending requests on disconnect. this._requestManager.rejectAllResponses(new Error('Disconnect was called.')); @@ -106,8 +105,8 @@ export class WebSocketClient implements IStreamingTransportClient { throw new Error( `Unable to re-connect client to transport for url ${this._url}. Sender: '${JSON.stringify( - sender - )}'. Args:' ${JSON.stringify(args)}` + sender, + )}'. Args:' ${JSON.stringify(args)}`, ); } } diff --git a/libraries/botframework-streaming/src/webSocket/nodeWebSocket.ts b/libraries/botframework-streaming/src/webSocket/nodeWebSocket.ts index 1ce6ddc24b..bf0a3bbd13 100644 --- a/libraries/botframework-streaming/src/webSocket/nodeWebSocket.ts +++ b/libraries/botframework-streaming/src/webSocket/nodeWebSocket.ts @@ -126,7 +126,6 @@ export class NodeWebSocket implements ISocket { req.on('upgrade', (res, socket, head): void => { // @types/ws does not contain the signature for completeUpgrade // https://github.com/websockets/ws/blob/0a612364e69fc07624b8010c6873f7766743a8e3/lib/websocket-server.js#L269 - // eslint-disable-next-line @typescript-eslint/no-explicit-any (this.wsServer as any).completeUpgrade(wskey, undefined, res, socket, head, (websocket): void => { this.wsSocket = websocket; }); @@ -143,7 +142,6 @@ export class NodeWebSocket implements ISocket { * * @param handler The callback to handle the "message" event. */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any setOnMessageHandler(handler: (x: any) => void): void { this.wsSocket.on('message', handler); } @@ -165,7 +163,6 @@ export class NodeWebSocket implements ISocket { * * @param handler The callback to handle the "close" event. */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any setOnCloseHandler(handler: (x: any) => void): void { this.wsSocket.on('close', handler); } @@ -175,7 +172,6 @@ export class NodeWebSocket implements ISocket { * * @param handler The callback to handle the "error" event. */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any setOnErrorHandler(handler: (x: any) => void): void { this.wsSocket.on('error', (error): void => { if (error) { diff --git a/libraries/botframework-streaming/src/webSocket/nodeWebSocketClient.ts b/libraries/botframework-streaming/src/webSocket/nodeWebSocketClient.ts index 3f32628529..8df9a81718 100644 --- a/libraries/botframework-streaming/src/webSocket/nodeWebSocketClient.ts +++ b/libraries/botframework-streaming/src/webSocket/nodeWebSocketClient.ts @@ -59,7 +59,7 @@ export class WebSocketClient implements IStreamingTransportClient { this._requestHandler, this._requestManager, this._sender, - this._receiver + this._receiver, ); } @@ -98,7 +98,6 @@ export class WebSocketClient implements IStreamingTransportClient { return this._protocolAdapter.sendRequest(request); } - // eslint-disable-next-line @typescript-eslint/no-explicit-any private onConnectionDisconnected(sender: Record, args: any): void { // Rejects all pending requests on disconnect. this._requestManager.rejectAllResponses(new Error('Disconnect was called.')); @@ -110,8 +109,8 @@ export class WebSocketClient implements IStreamingTransportClient { throw new Error( `Unable to re-connect client to Node transport for url ${this._url}. Sender: '${JSON.stringify( - sender - )}'. Args:' ${JSON.stringify(args)}` + sender, + )}'. Args:' ${JSON.stringify(args)}`, ); } } diff --git a/libraries/botframework-streaming/src/webSocket/webSocketServer.ts b/libraries/botframework-streaming/src/webSocket/webSocketServer.ts index 89b4c64b25..d082a1467f 100644 --- a/libraries/botframework-streaming/src/webSocket/webSocketServer.ts +++ b/libraries/botframework-streaming/src/webSocket/webSocketServer.ts @@ -53,7 +53,7 @@ export class WebSocketServer implements IStreamingTransportServer { this._requestHandler, this._requestManager, this._sender, - this._receiver + this._receiver, ); this._closedSignal = (x: string): string => { diff --git a/libraries/botframework-streaming/src/webSocket/webSocketTransport.ts b/libraries/botframework-streaming/src/webSocket/webSocketTransport.ts index 215d286026..f4331ccf17 100644 --- a/libraries/botframework-streaming/src/webSocket/webSocketTransport.ts +++ b/libraries/botframework-streaming/src/webSocket/webSocketTransport.ts @@ -16,7 +16,6 @@ export class WebSocketTransport implements ITransportSender, ITransportReceiver private _active: INodeBuffer; private _activeOffset = 0; private _activeReceiveResolve: (resolve: INodeBuffer) => void; - // eslint-disable-next-line @typescript-eslint/no-explicit-any private _activeReceiveReject: (reason?: any) => void; private _activeReceiveCount = 0; diff --git a/libraries/botframework-streaming/tests/CancelDisassembler.test.js b/libraries/botframework-streaming/tests/CancelDisassembler.test.js new file mode 100644 index 0000000000..d33f33e8d2 --- /dev/null +++ b/libraries/botframework-streaming/tests/CancelDisassembler.test.js @@ -0,0 +1,26 @@ +const { expect } = require('chai'); +const { CancelDisassembler } = require('../lib/disassemblers'); +const { PayloadSender } = require('../lib/payloadTransport'); +const { PayloadTypes } = require('../lib/payloads'); + +describe('CancelDisassembler', function () { + it('constructs correctly.', function () { + const sender = new PayloadSender(); + const cd = new CancelDisassembler(sender, '42', PayloadTypes.cancelStream); + + expect(cd.id).to.equal('42'); + expect(cd.payloadType).to.equal(PayloadTypes.cancelStream); + expect(cd.sender).to.equal(sender); + }); + + it('sends payload without throwing.', function () { + const sender = new PayloadSender(); + const cd = new CancelDisassembler(sender, '42', PayloadTypes.cancelStream); + + expect(cd.id).to.equal('42'); + expect(cd.payloadType).to.equal(PayloadTypes.cancelStream); + expect(cd.sender).to.equal(sender); + + expect(() => cd.disassemble()).to.not.throw(); + }); +}); diff --git a/libraries/botframework-streaming/tests/ContentStream.test.js b/libraries/botframework-streaming/tests/ContentStream.test.js index 5350ce39b3..6af56b0325 100644 --- a/libraries/botframework-streaming/tests/ContentStream.test.js +++ b/libraries/botframework-streaming/tests/ContentStream.test.js @@ -67,7 +67,7 @@ describe('Streaming Extensions ContentStream Tests ', function () { it('does not return the stream when it is is undefined', function () { const cs = new ContentStream('1', new PayloadAssembler(streamManager, { id: 'csa1', header: header })); - expect(cs.getStream()).to.not.be.undefined; + expect(cs.getStream()).to.not.equal(undefined); }); it('reads a stream of length 0 and returns an empty string', function () { @@ -76,7 +76,7 @@ describe('Streaming Extensions ContentStream Tests ', function () { new PayloadAssembler(streamManager, { id: 'csa1', header: { ...header, payloadLength: 0 }, - }) + }), ); return cs.readAsString().then((data) => { @@ -93,13 +93,13 @@ describe('Streaming Extensions ContentStream Tests ', function () { new PayloadAssembler(streamManager, { id: 'csa1', header: assemblerHeader, - }) + }), ); return cs .readAsJson() .then((data) => { - expect(data).to.not.be.undefined; + expect(data).to.not.be.undefined(); }) .catch((err) => { expect(err.toString()).to.equal('SyntaxError: Unexpected end of JSON input'); diff --git a/libraries/botframework-streaming/tests/Disassembler.test.js b/libraries/botframework-streaming/tests/Disassembler.test.js deleted file mode 100644 index 193b742827..0000000000 --- a/libraries/botframework-streaming/tests/Disassembler.test.js +++ /dev/null @@ -1,46 +0,0 @@ -const { CancelDisassembler, RequestDisassembler } = require('../lib/disassemblers'); -const { HttpContentStream } = require('../lib/httpContentStream'); -const { HttpContent, StreamingRequest, SubscribableStream } = require('..'); -const { PayloadSender } = require('../lib/payloadTransport'); -const { PayloadTypes } = require('../lib/payloads'); -const { expect } = require('chai'); - -describe('RequestDisassembler', function () { - it('resolves calls to get stream.', async function () { - const sender = new PayloadSender(); - const req = new StreamingRequest(); - const headers = { contentLength: 40, contentType: 'A' }; - const stream = new SubscribableStream(); - stream.write('This is the data inside of the stream.', 'UTF-8'); - const content = new HttpContent(headers, stream); - const contentStream = new HttpContentStream(content); - contentStream.content.headers = headers; - - req.addStream(contentStream); - const rd = new RequestDisassembler(sender, '42', req); - - await rd.getStream(); - }); -}); - -describe('CancelDisassembler', function () { - it('constructs correctly.', function () { - const sender = new PayloadSender(); - const cd = new CancelDisassembler(sender, '42', PayloadTypes.cancelStream); - - expect(cd.id).to.equal('42'); - expect(cd.payloadType).to.equal(PayloadTypes.cancelStream); - expect(cd.sender).to.equal(sender); - }); - - it('sends payload without throwing.', function () { - const sender = new PayloadSender(); - const cd = new CancelDisassembler(sender, '42', PayloadTypes.cancelStream); - - expect(cd.id).to.equal('42'); - expect(cd.payloadType).to.equal(PayloadTypes.cancelStream); - expect(cd.sender).to.equal(sender); - - expect(() => cd.disassemble()).to.not.throw(); - }); -}); diff --git a/libraries/botframework-streaming/tests/NamedPipe.test.js b/libraries/botframework-streaming/tests/NamedPipe.test.js index 5892db99b2..0cef91f9ba 100644 --- a/libraries/botframework-streaming/tests/NamedPipe.test.js +++ b/libraries/botframework-streaming/tests/NamedPipe.test.js @@ -88,7 +88,7 @@ describe.windowsOnly('Streaming Extensions NamedPipe Library Tests', function () it('Client connect', function () { const c = new TestClient('pipeName'); const t = c.connect(); - expect(t).to.not.be.undefined; + expect(t).to.not.equal(undefined); c.disconnect(); }); @@ -122,7 +122,7 @@ describe.windowsOnly('Streaming Extensions NamedPipe Library Tests', function () sock.writable = true; const transport = new NamedPipeTransport(sock, 'fakeSocket2'); expect(transport).to.be.instanceOf(NamedPipeTransport); - expect(transport.isConnected).to.be.true; + expect(transport.isConnected).to.equal(true); expect(() => transport.close()).to.not.throw(); }); @@ -134,7 +134,7 @@ describe.windowsOnly('Streaming Extensions NamedPipe Library Tests', function () const transport = new NamedPipeTransport(sock, 'fakeSocket3'); expect(transport).to.be.instanceOf(NamedPipeTransport); expect(() => transport.close()).to.not.throw(); - expect(transport.isConnected).to.be.false; + expect(transport.isConnected).to.equal(false); }); it('writes to the socket', function () { @@ -144,7 +144,7 @@ describe.windowsOnly('Streaming Extensions NamedPipe Library Tests', function () sock.writable = true; const transport = new NamedPipeTransport(sock, 'fakeSocket4'); expect(transport).to.be.instanceOf(NamedPipeTransport); - expect(transport.isConnected).to.be.true; + expect(transport.isConnected).to.equal(true); const buff = Buffer.from('hello', 'utf8'); const sent = transport.send(buff); expect(sent).to.equal(5); @@ -158,7 +158,7 @@ describe.windowsOnly('Streaming Extensions NamedPipe Library Tests', function () sock.writable = true; const transport = new NamedPipeTransport(sock, 'fakeSocket5'); expect(transport).to.be.instanceOf(NamedPipeTransport); - expect(transport.isConnected).to.be.true; + expect(transport.isConnected).to.equal(true); sock.writable = false; const buff = Buffer.from('hello', 'utf8'); const sent = transport.send(buff); @@ -168,6 +168,7 @@ describe.windowsOnly('Streaming Extensions NamedPipe Library Tests', function () // TODO: 2023-04-24 [hawo] #4462 The code today does not allows the receive() call to be rejected by reading a dead socket. // The receive() call will be rejected IFF the socket is closed/error AFTER the receive() call. + // eslint-disable-next-line mocha/no-skipped-tests it.skip('throws when reading from a dead socket', async function () { const sock = new FauxSock(); sock.destroyed = true; @@ -175,7 +176,7 @@ describe.windowsOnly('Streaming Extensions NamedPipe Library Tests', function () sock.writable = true; const transport = new NamedPipeTransport(sock, 'fakeSocket5'); expect(transport).to.be.instanceOf(NamedPipeTransport); - expect(transport.isConnected).to.be.false; + expect(transport.isConnected).to.equal(false); (await expectEventually(transport.receive(5))).to.throw(); expect(() => transport.close()).to.not.throw(); }); @@ -187,7 +188,7 @@ describe.windowsOnly('Streaming Extensions NamedPipe Library Tests', function () sock.writable = true; const transport = new NamedPipeTransport(sock); expect(transport).to.be.instanceOf(NamedPipeTransport); - expect(transport.isConnected).to.be.true; + expect(transport.isConnected).to.equal(true); transport.receive(12).catch(); transport.socketReceive(Buffer.from('Hello World!', 'utf8')); @@ -201,12 +202,12 @@ describe.windowsOnly('Streaming Extensions NamedPipe Library Tests', function () sock.writable = true; const transport = new NamedPipeTransport(sock, 'fakeSocket6'); expect(transport).to.be.instanceOf(NamedPipeTransport); - expect(transport.isConnected).to.be.true; + expect(transport.isConnected).to.equal(true); transport.socketClose(); - expect(transport._active).to.be.null; - expect(transport._activeReceiveResolve).to.be.null; - expect(transport._activeReceiveReject).to.be.null; - expect(transport.socket).to.be.null; + expect(transport._active).to.equal(null); + expect(transport._activeReceiveResolve).to.equal(null); + expect(transport._activeReceiveReject).to.equal(null); + expect(transport.socket).to.equal(null); expect(transport._activeOffset).to.equal(0); expect(transport._activeReceiveCount).to.equal(0); }); @@ -218,12 +219,12 @@ describe.windowsOnly('Streaming Extensions NamedPipe Library Tests', function () sock.writable = true; const transport = new NamedPipeTransport(sock, 'fakeSocket6'); expect(transport).to.be.instanceOf(NamedPipeTransport); - expect(transport.isConnected).to.be.true; + expect(transport.isConnected).to.equal(true); transport.socketError(); - expect(transport._active).to.be.null; - expect(transport._activeReceiveResolve).to.be.null; - expect(transport._activeReceiveReject).to.be.null; - expect(transport.socket).to.be.null; + expect(transport._active).to.equal(null); + expect(transport._activeReceiveResolve).to.equal(null); + expect(transport._activeReceiveReject).to.equal(null); + expect(transport.socket).to.equal(null); expect(transport._activeOffset).to.equal(0); expect(transport._activeReceiveCount).to.equal(0); }); @@ -235,7 +236,7 @@ describe.windowsOnly('Streaming Extensions NamedPipe Library Tests', function () sock.writable = true; const transport = new NamedPipeTransport(sock, 'fakeSocket6'); expect(transport).to.be.instanceOf(NamedPipeTransport); - expect(transport.isConnected).to.be.true; + expect(transport.isConnected).to.equal(true); const buff = Buffer.from('hello', 'utf8'); expect(() => transport.socketReceive(buff)).to.not.throw(); }); @@ -261,6 +262,7 @@ describe.windowsOnly('Streaming Extensions NamedPipe Library Tests', function () // TODO: 2023-04-24 [hawo] #4462 The client.send() call will only resolve when the other side responded. // Because the other side is not connected to anything, thus, no response is received. // Thus, the Promise is not resolved. + // eslint-disable-next-line mocha/no-skipped-tests it.skip('sends without throwing', function (done) { const req = new StreamingRequest(); req.Verb = 'POST'; @@ -269,7 +271,7 @@ describe.windowsOnly('Streaming Extensions NamedPipe Library Tests', function () client .send(req) .catch((err) => { - expect(err).to.be.undefined; + expect(err).to.equal(undefined); }) .then(done); }); @@ -304,15 +306,16 @@ describe.windowsOnly('Streaming Extensions NamedPipe Library Tests', function () it('returns true if isConnected === true on _receiver & _sender', function () { const server = new NamedPipeServer('pipeisConnected', new RequestHandler()); - expect(server.isConnected).to.be.false; + expect(server.isConnected).to.equal(false); server._receiver = { isConnected: true }; server._sender = { isConnected: true }; - expect(server.isConnected).to.be.true; + expect(server.isConnected).to.equal(true); }); // TODO: 2023-04-24 [hawo] #4462 The client.send() call will only resolve when the other side responded. // Because the other side is not connected to anything, thus, no response is received. // Thus, the Promise is not resolved. + // eslint-disable-next-line mocha/no-skipped-tests it.skip('sends without throwing', function (done) { const server = new NamedPipeServer('pipeA', new RequestHandler()); expect(server).to.be.instanceOf(NamedPipeServer); @@ -321,7 +324,7 @@ describe.windowsOnly('Streaming Extensions NamedPipe Library Tests', function () server .send(req) .catch((err) => { - expect(err).to.be.undefined; + expect(err).to.equal(undefined); }) .then(expect(() => server.disconnect()).to.not.throw()) .then(done); @@ -354,7 +357,7 @@ describe.windowsOnly('Streaming Extensions NamedPipe Library Tests', function () err.server = server; throw err; } - }) + }), ), (err) => { // Verify we did get an addr in use error @@ -363,12 +366,12 @@ describe.windowsOnly('Streaming Extensions NamedPipe Library Tests', function () assert(err.server, 'server attached to error'); assert( err.server._incomingServer && !err.server._incomingServer.listening, - 'incoming server attached but not listening' + 'incoming server attached but not listening', ); assert(!err.server._outgoingServer, 'no outgoing server attached'); return true; - } + }, ); } finally { servers.forEach((server) => server.disconnect()); @@ -386,7 +389,7 @@ describe.windowsOnly('Streaming Extensions NamedPipe Library Tests', function () it('should return a Server when calling createNodeServer()', function () { const server = createNodeServer(); - expect(server).to.not.be.null; + expect(server).to.not.equal(null); expect(server).to.be.instanceOf(Object); expect(typeof server.listen).to.equal('function'); expect(typeof server.close).to.equal('function'); @@ -395,7 +398,7 @@ describe.windowsOnly('Streaming Extensions NamedPipe Library Tests', function () it('should return the factory when calling getServerFactory()', function () { expect(() => getServerFactory()).to.not.throw(); const serverFactoryFunction = getServerFactory(); - expect(serverFactoryFunction).to.not.be.null; + expect(serverFactoryFunction).to.not.equal(null); expect(typeof serverFactoryFunction).to.equal('function'); }); diff --git a/libraries/botframework-streaming/tests/NodeWebSocket.test.js b/libraries/botframework-streaming/tests/NodeWebSocket.test.js index 895c027fb0..af83ad5b45 100644 --- a/libraries/botframework-streaming/tests/NodeWebSocket.test.js +++ b/libraries/botframework-streaming/tests/NodeWebSocket.test.js @@ -15,7 +15,7 @@ describe('NodeWebSocket', function () { it('starts out connected', function () { const socket = new NodeWebSocket(new FauxSock()); - expect(socket.isConnected).to.be.true; + expect(socket.isConnected).to.equal(true); }); it('writes to the socket', function () { @@ -30,34 +30,34 @@ describe('NodeWebSocket', function () { socket.connect().catch((error) => { expect( error.message === 'connect ECONNREFUSED 127.0.0.1:8082' || - error.message === 'connect ECONNREFUSED ::1:8082' - ).to.be.true; - }) + error.message === 'connect ECONNREFUSED ::1:8082', + ).to.equal(true); + }), ); }); it('can set message handlers on the socket', function () { const sock = new FauxSock(); const socket = new NodeWebSocket(sock); - expect(sock.messageHandler).to.be.undefined; + expect(sock.messageHandler).to.equal(undefined); expect(() => socket.setOnMessageHandler(() => {})).to.not.throw(); - expect(sock.messageHandler).to.not.be.undefined; + expect(sock.messageHandler).to.not.equal(undefined); }); it('can set error handler on the socket', function () { const sock = new FauxSock(); const socket = new NodeWebSocket(sock); - expect(sock.errorHandler).to.be.undefined; + expect(sock.errorHandler).to.equal(undefined); expect(() => socket.setOnErrorHandler(() => {})).to.not.throw(); - expect(sock.errorHandler).to.not.be.undefined; + expect(sock.errorHandler).to.not.equal(undefined); }); it('can set end handler on the socket', function () { const sock = new FauxSock(); const socket = new NodeWebSocket(sock); - expect(sock.closeHandler).to.be.undefined; + expect(sock.closeHandler).to.equal(undefined); expect(() => socket.setOnCloseHandler(() => {})).to.not.throw(); - expect(sock.closeHandler).to.not.be.undefined; + expect(sock.closeHandler).to.not.equal(undefined); }); it('create() should be successful and set a WebSocket', async function () { @@ -142,7 +142,7 @@ describe('NodeWebSocket', function () { describe('isConnected property', function () { it('should be true', function () { - expect(nodeSocket.isConnected).to.be.true; + expect(nodeSocket.isConnected).to.equal(true); }); }); diff --git a/libraries/botframework-streaming/tests/Assembler.test.js b/libraries/botframework-streaming/tests/PayloadAssembler.test.js similarity index 62% rename from libraries/botframework-streaming/tests/Assembler.test.js rename to libraries/botframework-streaming/tests/PayloadAssembler.test.js index ebd7f28df4..21a717ca8f 100644 --- a/libraries/botframework-streaming/tests/Assembler.test.js +++ b/libraries/botframework-streaming/tests/PayloadAssembler.test.js @@ -1,237 +1,156 @@ -const { SubscribableStream } = require('../lib/subscribableStream'); -const { PayloadAssemblerManager, PayloadTypes, StreamManager } = require('../lib/payloads'); -const { PayloadAssembler } = require('../lib/assemblers'); -const { expect } = require('chai'); - -const streamManager = new StreamManager(); - -describe('PayloadAssembler', function () { - it('constructs correctly.', function () { - const header = { - payloadType: PayloadTypes.request, - payloadLength: '42', - id: '100', - end: true, - }; - const rra = new PayloadAssembler(streamManager, { header, onCompleted: () => {} }); - - expect(rra.id).equals('100'); - expect(rra.streamManager).equals(streamManager); - }); - - it('closes without throwing', function () { - const header = { - payloadType: PayloadTypes.request, - payloadLength: '42', - id: '99', - end: true, - }; - const rra = new PayloadAssembler(streamManager, { header, onCompleted: () => {} }); - - expect(() => { - rra.close(); - }).to.not.throw(); - }); - - it('returns a new stream.', function () { - const header = { - payloadType: PayloadTypes.response, - payloadLength: '42', - id: '100', - end: true, - }; - const rra = new PayloadAssembler(streamManager, { header, onCompleted: () => {} }); - - expect(rra.createPayloadStream()).to.be.instanceOf(SubscribableStream); - }); - - it('processes a Request without throwing.', function (done) { - const header = { - payloadType: PayloadTypes.request, - payloadLength: '5', - id: '98', - end: true, - }; - const s = new SubscribableStream(); - - s.write('12345'); - const rp = { verb: 'POST', path: '/some/path' }; - rp.streams = s; - const rra = new PayloadAssembler(streamManager, { - header, - onCompleted: () => done(), - }); - rra.onReceive(header, s, 5); - rra.close(); - }); - - it('processes a Response without throwing.', function (done) { - const header = { - payloadType: PayloadTypes.response, - payloadLength: '5', - id: '100', - end: true, - }; - const s = new SubscribableStream(); - - s.write('12345'); - const rp = { statusCode: 200 }; - rp.streams = s; - const rra = new PayloadAssembler(streamManager, { - header, - onCompleted: () => done(), - }); - rra.onReceive(header, s, 5); - }); - - it('assigns values when constructed', function () { - const header = { - payloadType: PayloadTypes.stream, - payloadLength: 50, - id: '1', - end: undefined, - }; - const csa = new PayloadAssembler(streamManager, { header, onCompleted: () => {} }); - - expect(csa.id).equals('1'); - expect(csa.contentLength).equals(50); - expect(csa.payloadType).equals('S'); - expect(csa.end).equals(undefined); - }); - - it('returns a Stream', function () { - const header = { - payloadType: PayloadTypes.stream, - payloadLength: 50, - id: '1', - end: true, - }; - const csa = new PayloadAssembler(streamManager, { header, onCompleted: () => {} }); - - expect(csa.createPayloadStream()).instanceOf(SubscribableStream); - }); - - it('closes a Stream', function () { - const header = { - payloadType: PayloadTypes.stream, - payloadLength: 50, - id: '97', - end: true, - }; - const csa = new PayloadAssembler(streamManager, { header, onCompleted: () => {} }); - - expect(csa.createPayloadStream()).instanceOf(SubscribableStream); - expect(() => csa.close()).to.not.throw(); - }); -}); - -describe('PayloadAssemblerManager', function () { - it('creates a response stream', function () { - const p = new PayloadAssemblerManager(streamManager); - const head = { - payloadType: PayloadTypes.response, - payloadLength: '42', - id: '100', - end: true, - }; - - expect(p.getPayloadStream(head)).to.be.instanceOf(SubscribableStream); - }); - - it('creates a request stream', function () { - const p = new PayloadAssemblerManager(streamManager); - const head = { - payloadType: PayloadTypes.request, - payloadLength: '42', - id: '100', - end: true, - }; - - expect(p.getPayloadStream(head)).to.be.instanceOf(SubscribableStream); - }); - - it('does not throw when receiving a request', function () { - const p = new PayloadAssemblerManager(streamManager); - const head = { - payloadType: PayloadTypes.request, - payloadLength: '42', - id: '100', - end: true, - }; - const s = p.getPayloadStream(head); - expect(s).to.be.instanceOf(SubscribableStream); - expect(() => p.onReceive(head, s, 0)).to.not.throw(); - }); - - it('does not throw when receiving a stream', function () { - const p = new PayloadAssemblerManager(streamManager); - const head = { - payloadType: PayloadTypes.stream, - payloadLength: '42', - id: '100', - end: true, - }; - const s = p.getPayloadStream(head); - - expect(s).to.be.instanceOf(SubscribableStream); - expect(() => p.onReceive(head, s, 0)).to.not.throw(); - }); - - it('does not throw when receiving a response', function () { - const p = new PayloadAssemblerManager(streamManager); - const head = { - payloadType: PayloadTypes.response, - payloadLength: '42', - id: '100', - end: true, - }; - const s = p.getPayloadStream(head); - - expect(s).to.be.instanceOf(SubscribableStream); - expect(() => p.onReceive(head, s, 0)).to.not.throw(); - }); - - it('returns undefined when asked to create an existing stream', function () { - const p = new PayloadAssemblerManager(streamManager); - const head = { - payloadType: PayloadTypes.request, - payloadLength: '42', - id: '100', - end: true, - }; - const s = p.getPayloadStream(head); - - expect(s).to.be.instanceOf(SubscribableStream); - expect(p.getPayloadStream(head)).to.be.undefined; - }); - - it('throws if not given an ID', function () { - const header = { - payloadType: PayloadTypes.request, - payloadLength: '5', - id: undefined, - end: true, - }; - expect(() => new PayloadAssembler(streamManager, { header })).to.throw( - 'An ID must be supplied when creating an assembler.' - ); - }); - - it('processes a response with streams without throwing.', function (done) { - const header = { payloadType: PayloadTypes.response, payloadLength: '5', id: '96', end: true }; - const s = new SubscribableStream(); - s.write( - '{"statusCode": "12345","streams": [{"id": "1","contentType": "text","length": "2"},{"id": "2","contentType": "text","length": "2"},{"id": "3","contentType": "text","length": "2"}]}' - ); - const rp = { verb: 'POST', path: '/some/path' }; - rp.streams = []; - rp.streams.push(s); - - const rra = new PayloadAssembler(streamManager, { - header: header, - onCompleted: () => done(), - }); - rra.onReceive(header, s, 5); - rra.close(); - }); -}); +const { SubscribableStream } = require('../lib/subscribableStream'); +const { PayloadTypes, StreamManager } = require('../lib/payloads'); +const { PayloadAssembler } = require('../lib/assemblers'); +const { expect } = require('chai'); + +const streamManager = new StreamManager(); + +describe('PayloadAssembler', function () { + it('constructs correctly.', function () { + const header = { + payloadType: PayloadTypes.request, + payloadLength: '42', + id: '100', + end: true, + }; + const rra = new PayloadAssembler(streamManager, { header, onCompleted: () => {} }); + + expect(rra.id).equals('100'); + expect(rra.streamManager).equals(streamManager); + }); + + it('closes without throwing', function () { + const header = { + payloadType: PayloadTypes.request, + payloadLength: '42', + id: '99', + end: true, + }; + const rra = new PayloadAssembler(streamManager, { header, onCompleted: () => {} }); + + expect(() => { + rra.close(); + }).to.not.throw(); + }); + + it('returns a new stream.', function () { + const header = { + payloadType: PayloadTypes.response, + payloadLength: '42', + id: '100', + end: true, + }; + const rra = new PayloadAssembler(streamManager, { header, onCompleted: () => {} }); + + expect(rra.createPayloadStream()).to.be.instanceOf(SubscribableStream); + }); + + it('processes a Request without throwing.', function (done) { + const header = { + payloadType: PayloadTypes.request, + payloadLength: '5', + id: '98', + end: true, + }; + const s = new SubscribableStream(); + + s.write('12345'); + const rp = { verb: 'POST', path: '/some/path' }; + rp.streams = s; + const rra = new PayloadAssembler(streamManager, { + header, + onCompleted: () => done(), + }); + rra.onReceive(header, s, 5); + rra.close(); + }); + + it('processes a Response without throwing.', function (done) { + const header = { + payloadType: PayloadTypes.response, + payloadLength: '5', + id: '100', + end: true, + }; + const s = new SubscribableStream(); + + s.write('12345'); + const rp = { statusCode: 200 }; + rp.streams = s; + const rra = new PayloadAssembler(streamManager, { + header, + onCompleted: () => done(), + }); + rra.onReceive(header, s, 5); + }); + + it('assigns values when constructed', function () { + const header = { + payloadType: PayloadTypes.stream, + payloadLength: 50, + id: '1', + end: undefined, + }; + const csa = new PayloadAssembler(streamManager, { header, onCompleted: () => {} }); + + expect(csa.id).equals('1'); + expect(csa.contentLength).equals(50); + expect(csa.payloadType).equals('S'); + expect(csa.end).equals(undefined); + }); + + it('returns a Stream', function () { + const header = { + payloadType: PayloadTypes.stream, + payloadLength: 50, + id: '1', + end: true, + }; + const csa = new PayloadAssembler(streamManager, { header, onCompleted: () => {} }); + + expect(csa.createPayloadStream()).instanceOf(SubscribableStream); + }); + + it('closes a Stream', function () { + const header = { + payloadType: PayloadTypes.stream, + payloadLength: 50, + id: '97', + end: true, + }; + const csa = new PayloadAssembler(streamManager, { header, onCompleted: () => {} }); + + expect(csa.createPayloadStream()).instanceOf(SubscribableStream); + expect(() => csa.close()).to.not.throw(); + }); + + it('throws if not given an ID', function () { + const header = { + payloadType: PayloadTypes.request, + payloadLength: '5', + id: undefined, + end: true, + }; + expect(() => new PayloadAssembler(streamManager, { header })).to.throw( + 'An ID must be supplied when creating an assembler.', + ); + }); + + it('processes a response with streams without throwing.', function (done) { + const header = { payloadType: PayloadTypes.response, payloadLength: '5', id: '96', end: true }; + const s = new SubscribableStream(); + s.write( + '{"statusCode": "12345","streams": [{"id": "1","contentType": "text","length": "2"},{"id": "2","contentType": "text","length": "2"},{"id": "3","contentType": "text","length": "2"}]}', + ); + const rp = { verb: 'POST', path: '/some/path' }; + rp.streams = []; + rp.streams.push(s); + + const rra = new PayloadAssembler(streamManager, { + header: header, + onCompleted: () => done(), + }); + rra.onReceive(header, s, 5); + rra.close(); + }); +}); diff --git a/libraries/botframework-streaming/tests/PayloadAssemblerManager.test.js b/libraries/botframework-streaming/tests/PayloadAssemblerManager.test.js new file mode 100644 index 0000000000..8590a817b5 --- /dev/null +++ b/libraries/botframework-streaming/tests/PayloadAssemblerManager.test.js @@ -0,0 +1,86 @@ +const { SubscribableStream } = require('../lib/subscribableStream'); +const { PayloadAssemblerManager, PayloadTypes, StreamManager } = require('../lib/payloads'); +const { expect } = require('chai'); + +const streamManager = new StreamManager(); + +describe('PayloadAssemblerManager', function () { + it('creates a response stream', function () { + const p = new PayloadAssemblerManager(streamManager); + const head = { + payloadType: PayloadTypes.response, + payloadLength: '42', + id: '100', + end: true, + }; + + expect(p.getPayloadStream(head)).to.be.instanceOf(SubscribableStream); + }); + + it('creates a request stream', function () { + const p = new PayloadAssemblerManager(streamManager); + const head = { + payloadType: PayloadTypes.request, + payloadLength: '42', + id: '100', + end: true, + }; + + expect(p.getPayloadStream(head)).to.be.instanceOf(SubscribableStream); + }); + + it('does not throw when receiving a request', function () { + const p = new PayloadAssemblerManager(streamManager); + const head = { + payloadType: PayloadTypes.request, + payloadLength: '42', + id: '100', + end: true, + }; + const s = p.getPayloadStream(head); + expect(s).to.be.instanceOf(SubscribableStream); + expect(() => p.onReceive(head, s, 0)).to.not.throw(); + }); + + it('does not throw when receiving a stream', function () { + const p = new PayloadAssemblerManager(streamManager); + const head = { + payloadType: PayloadTypes.stream, + payloadLength: '42', + id: '100', + end: true, + }; + const s = p.getPayloadStream(head); + + expect(s).to.be.instanceOf(SubscribableStream); + expect(() => p.onReceive(head, s, 0)).to.not.throw(); + }); + + it('does not throw when receiving a response', function () { + const p = new PayloadAssemblerManager(streamManager); + const head = { + payloadType: PayloadTypes.response, + payloadLength: '42', + id: '100', + end: true, + }; + const s = p.getPayloadStream(head); + + expect(s).to.be.instanceOf(SubscribableStream); + expect(() => p.onReceive(head, s, 0)).to.not.throw(); + }); + + it('returns undefined when asked to create an existing stream', function () { + const p = new PayloadAssemblerManager(streamManager); + const head = { + payloadType: PayloadTypes.request, + payloadLength: '42', + id: '100', + end: true, + }; + const s = p.getPayloadStream(head); + + expect(s).to.be.instanceOf(SubscribableStream); + expect(p.getPayloadStream(head)).to.equal(undefined); + }); +}); diff --git a/libraries/botframework-streaming/tests/PayloadSender.test.js b/libraries/botframework-streaming/tests/PayloadSender.test.js index 0b4fac80be..2462154935 100644 --- a/libraries/botframework-streaming/tests/PayloadSender.test.js +++ b/libraries/botframework-streaming/tests/PayloadSender.test.js @@ -60,7 +60,7 @@ describe('PayloadTransport', function () { const psSenderSpy = sinon.spy(ps._sender, 'send'); expect(ps.sendPayload(header, stream, () => done())); - expect(psSenderSpy.calledTwice).to.be.true; + expect(psSenderSpy.calledTwice).to.equal(true); }); it('writes a large stream to its sender.', function (done) { @@ -95,7 +95,7 @@ describe('PayloadTransport', function () { } catch (e) { done(e); } - }) + }), ); }); @@ -157,7 +157,7 @@ describe('PayloadTransport', function () { describe('PayloadReceiver', function () { it('begins disconnected.', function () { const pr = new PayloadReceiver(); - expect(pr.isConnected).to.be.false; + expect(pr.isConnected).to.equal(false); }); it('connects to and reads a header with no payload from the transport.', function () { @@ -167,7 +167,7 @@ describe('PayloadTransport', function () { sock.setReceiver(pr); pr.connect(sock); - expect(pr.isConnected).to.be.true; + expect(pr.isConnected).to.equal(true); }); it('connects to and reads a header with a stream the transport.', function (done) { @@ -182,13 +182,13 @@ describe('PayloadTransport', function () { pr.subscribe( (header) => assemblerManager.getPayloadStream(header), (header, contentStream, contentLength) => - assemblerManager.onReceive(header, contentStream, contentLength) + assemblerManager.onReceive(header, contentStream, contentLength), ); expect(() => pr.connect(sock)).to.not.throw(); pr.disconnected = () => done(); - expect(pr.isConnected).to.be.true; + expect(pr.isConnected).to.equal(true); }); }); }); diff --git a/libraries/botframework-streaming/tests/ProtocolAdapter.test.js b/libraries/botframework-streaming/tests/ProtocolAdapter.test.js index 85fda449b9..2ebfa6ac9e 100644 --- a/libraries/botframework-streaming/tests/ProtocolAdapter.test.js +++ b/libraries/botframework-streaming/tests/ProtocolAdapter.test.js @@ -50,22 +50,22 @@ describe('Streaming Extensions ProtocolAdapter', function () { requestHandler, requestManager, payloadSender, - payloadReceiver + payloadReceiver, ); - expect(protocolAdapter.assemblerManager).to.not.be.undefined; + expect(protocolAdapter.assemblerManager).to.not.equal(undefined); - expect(protocolAdapter.payloadReceiver).to.not.be.undefined; + expect(protocolAdapter.payloadReceiver).to.not.equal(undefined); - expect(protocolAdapter.payloadSender).to.not.be.undefined; + expect(protocolAdapter.payloadSender).to.not.equal(undefined); - expect(protocolAdapter.sendOperations).to.not.be.undefined; + expect(protocolAdapter.sendOperations).to.not.equal(undefined); - expect(protocolAdapter.streamManager).to.not.be.undefined; + expect(protocolAdapter.streamManager).to.not.equal(undefined); - expect(protocolAdapter.requestHandler).to.not.be.undefined; + expect(protocolAdapter.requestHandler).to.not.equal(undefined); - expect(protocolAdapter.requestManager).to.not.be.undefined; + expect(protocolAdapter.requestManager).to.not.equal(undefined); }); it('processes requests.', async function () { @@ -79,13 +79,13 @@ describe('Streaming Extensions ProtocolAdapter', function () { requestHandler, requestManager, payloadSender, - payloadReceiver + payloadReceiver, ); const requestHandlerSpy = sinon.spy(requestHandler, 'processRequest'); protocolAdapter.onReceiveRequest('42', { verb: 'POST', path: '/api/messages', streams: [] }); - expect(requestHandlerSpy.called).to.be.true; + expect(requestHandlerSpy.called).to.equal(true); }); it('processes responses.', async function () { @@ -99,13 +99,13 @@ describe('Streaming Extensions ProtocolAdapter', function () { requestHandler, requestManager, payloadSender, - payloadReceiver + payloadReceiver, ); const requestManagerSpy = sinon.spy(requestManager, 'signalResponse'); protocolAdapter.onReceiveResponse('42', { statusCode: '200', streams: [] }); - expect(requestManagerSpy.called).to.be.true; + expect(requestManagerSpy.called).to.equal(true); }); it('does not throw when processing a cancellation for an already processed stream', async function () { @@ -119,7 +119,7 @@ describe('Streaming Extensions ProtocolAdapter', function () { requestHandler, requestManager, payloadSender, - payloadReceiver + payloadReceiver, ); const header = { payloadType: 'A', payloadLength: '5', id: '100', end: true }; const assembler = new PayloadAssembler.PayloadAssembler(new StreamManager.StreamManager(), { @@ -139,7 +139,7 @@ describe('Streaming Extensions ProtocolAdapter', function () { requestHandler, requestManager, payloadSender, - payloadReceiver + payloadReceiver, ); expect(() => protocolAdapter.sendRequest(new Request.StreamingRequest())).to.not.throw(); @@ -159,14 +159,14 @@ describe('Streaming Extensions ProtocolAdapter', function () { }; const s = new SubscribableStream.SubscribableStream(); s.write( - '{"statusCode": "12345","streams": [{"id": "1","contentType": "text","length": "2"},{"id": "2","contentType": "text","length": "2"},{"id": "3","contentType": "text","length": "2"}]}' + '{"statusCode": "12345","streams": [{"id": "1","contentType": "text","length": "2"},{"id": "2","contentType": "text","length": "2"},{"id": "3","contentType": "text","length": "2"}]}', ); const rp = { verb: 'POST', path: '/some/path' }; rp.streams = []; rp.streams.push(s); pa.connect(receiver); - expect(pa.isConnected).to.be.true; + expect(pa.isConnected).to.equal(true); expect(() => pa.connect(receiver)).to.not.throw(); pa.disconnect(); diff --git a/libraries/botframework-streaming/tests/RequestDisassembler.test.js b/libraries/botframework-streaming/tests/RequestDisassembler.test.js new file mode 100644 index 0000000000..4161037e2c --- /dev/null +++ b/libraries/botframework-streaming/tests/RequestDisassembler.test.js @@ -0,0 +1,22 @@ +const { RequestDisassembler } = require('../lib/disassemblers'); +const { HttpContentStream } = require('../lib/httpContentStream'); +const { HttpContent, StreamingRequest, SubscribableStream } = require('..'); +const { PayloadSender } = require('../lib/payloadTransport'); + +describe('RequestDisassembler', function () { + it('resolves calls to get stream.', async function () { + const sender = new PayloadSender(); + const req = new StreamingRequest(); + const headers = { contentLength: 40, contentType: 'A' }; + const stream = new SubscribableStream(); + stream.write('This is the data inside of the stream.', 'UTF-8'); + const content = new HttpContent(headers, stream); + const contentStream = new HttpContentStream(content); + contentStream.content.headers = headers; + + req.addStream(contentStream); + const rd = new RequestDisassembler(sender, '42', req); + + await rd.getStream(); + }); +}); diff --git a/libraries/botframework-streaming/tests/RequestManager.test.js b/libraries/botframework-streaming/tests/RequestManager.test.js index 450c60fd9c..e79bd5518e 100644 --- a/libraries/botframework-streaming/tests/RequestManager.test.js +++ b/libraries/botframework-streaming/tests/RequestManager.test.js @@ -17,7 +17,7 @@ describe('RequestManager', function () { rm.getResponse(REQUEST_ID); rm.getResponse(REQUEST_ID).catch((reason) => - expect(reason).to.equal(`requestId '${REQUEST_ID}' already exists in RequestManager`) + expect(reason).to.equal(`requestId '${REQUEST_ID}' already exists in RequestManager`), ); }); diff --git a/libraries/botframework-streaming/tests/StreamManager.test.js b/libraries/botframework-streaming/tests/StreamManager.test.js index e817c5ab9c..cd26683883 100644 --- a/libraries/botframework-streaming/tests/StreamManager.test.js +++ b/libraries/botframework-streaming/tests/StreamManager.test.js @@ -82,7 +82,7 @@ describe('StreamManager', function () { const stream = new SubscribableStream(); stream.write('hello'); expect(() => sm.closeStream(pa.id)).to.not.throw(); - expect(called).to.be.true; + expect(called).to.equal(true); }); it('does not throw when asked to close a stream that does not exist', function () { @@ -95,6 +95,6 @@ describe('StreamManager', function () { end: true, }; expect(() => sm.closeStream(head.id)).to.not.throw(); - expect(called).to.be.false; + expect(called).to.equal(false); }); }); diff --git a/libraries/botframework-streaming/tests/StreamingRequest.test.js b/libraries/botframework-streaming/tests/StreamingRequest.test.js index 5c4bef4621..ed8b87ca1f 100644 --- a/libraries/botframework-streaming/tests/StreamingRequest.test.js +++ b/libraries/botframework-streaming/tests/StreamingRequest.test.js @@ -46,7 +46,7 @@ describe('Streaming Extensions Request tests', function () { expect(() => { r.addStream(undefined); - }).throws; + }).to.throw(); }); it('is able to add streams to the request', function () { diff --git a/libraries/botframework-streaming/tests/WebSocket.test.js b/libraries/botframework-streaming/tests/WebSocket.test.js index 85f3c460c8..581bc69596 100644 --- a/libraries/botframework-streaming/tests/WebSocket.test.js +++ b/libraries/botframework-streaming/tests/WebSocket.test.js @@ -32,7 +32,7 @@ describe('Streaming Extensions WebSocket Library Tests', function () { sock.writable = true; const transport = new WebSocketTransport(sock); expect(transport).to.be.instanceOf(WebSocketTransport); - expect(transport.isConnected).to.be.true; + expect(transport.isConnected).to.equal(true); expect(() => transport.close()).to.not.throw(); }); @@ -43,7 +43,7 @@ describe('Streaming Extensions WebSocket Library Tests', function () { sock.writable = true; const transport = new WebSocketTransport(sock); expect(() => transport.close()).to.not.throw(); - expect(transport.isConnected).to.be.false; + expect(transport.isConnected).to.equal(false); }); it('writes to the socket', function () { @@ -52,7 +52,7 @@ describe('Streaming Extensions WebSocket Library Tests', function () { sock.connecting = false; sock.writable = true; const transport = new WebSocketTransport(sock); - expect(transport.isConnected).to.be.true; + expect(transport.isConnected).to.equal(true); const buff = Buffer.from('hello', 'utf8'); const sent = transport.send(buff); expect(sent).to.equal(5); @@ -65,7 +65,7 @@ describe('Streaming Extensions WebSocket Library Tests', function () { sock.connecting = false; sock.writable = true; const transport = new WebSocketTransport(sock); - expect(transport.isConnected).to.be.true; + expect(transport.isConnected).to.equal(true); sock.writable = false; sock.connected = false; const buff = Buffer.from('hello', 'utf8'); @@ -80,7 +80,7 @@ describe('Streaming Extensions WebSocket Library Tests', function () { sock.connecting = false; sock.writable = true; const transport = new WebSocketTransport(sock); - expect(transport.isConnected).to.be.true; + expect(transport.isConnected).to.equal(true); const promise = transport.receive(5); expect(() => transport.close()).to.not.throw(); (await expectEventually(promise)).to.throw('Socket was closed.'); @@ -92,7 +92,7 @@ describe('Streaming Extensions WebSocket Library Tests', function () { sock.connecting = false; sock.writable = true; const transport = new WebSocketTransport(sock); - expect(transport.isConnected).to.be.true; + expect(transport.isConnected).to.equal(true); transport.receive(12).catch(); transport.onReceive(Buffer.from('{"VERB":"POST", "PATH":"somewhere/something"}', 'utf8')); @@ -105,12 +105,12 @@ describe('Streaming Extensions WebSocket Library Tests', function () { sock.connecting = false; sock.writable = true; const transport = new WebSocketTransport(sock); - expect(transport.isConnected).to.be.true; + expect(transport.isConnected).to.equal(true); transport.onClose(); - expect(transport._active).to.be.null; - expect(transport._activeReceiveResolve).to.be.null; - expect(transport._activeReceiveReject).to.be.null; - expect(transport.ws).to.be.null; + expect(transport._active).to.equal(null); + expect(transport._activeReceiveResolve).to.equal(null); + expect(transport._activeReceiveReject).to.equal(null); + expect(transport.ws).to.equal(null); expect(transport._activeOffset).to.equal(0); expect(transport._activeReceiveCount).to.equal(0); }); @@ -121,12 +121,12 @@ describe('Streaming Extensions WebSocket Library Tests', function () { sock.connecting = false; sock.writable = true; const transport = new WebSocketTransport(sock); - expect(transport.isConnected).to.be.true; + expect(transport.isConnected).to.equal(true); transport.onError(); - expect(transport._active).to.be.null; - expect(transport._activeReceiveResolve).to.be.null; - expect(transport._activeReceiveReject).to.be.null; - expect(transport.ws).to.be.null; + expect(transport._active).to.equal(null); + expect(transport._activeReceiveResolve).to.equal(null); + expect(transport._activeReceiveReject).to.equal(null); + expect(transport.ws).to.equal(null); expect(transport._activeOffset).to.equal(0); expect(transport._activeReceiveCount).to.equal(0); }); @@ -137,7 +137,7 @@ describe('Streaming Extensions WebSocket Library Tests', function () { sock.connecting = false; sock.writable = true; const transport = new WebSocketTransport(sock); - expect(transport.isConnected).to.be.true; + expect(transport.isConnected).to.equal(true); const buff = Buffer.from('hello', 'utf8'); expect(() => transport.onReceive(buff)).to.not.throw(); }); @@ -153,7 +153,7 @@ describe('Streaming Extensions WebSocket Library Tests', function () { it('knows its connected', function () { const bs = new BrowserWebSocket(new FauxSock()); bs.connect('fakeUrl'); - expect(bs.isConnected).to.be.true; + expect(bs.isConnected).to.equal(true); }); it('writes to the socket', function () { @@ -170,45 +170,45 @@ describe('Streaming Extensions WebSocket Library Tests', function () { it('can set error handler on the socket', function () { const sock = new FauxSock(); const bs = new BrowserWebSocket(sock); - expect(sock.onerror).to.be.undefined; + expect(sock.onerror).to.equal(undefined); expect(() => bs.setOnErrorHandler(() => {})).to.not.throw(); - expect(sock.onerror).to.not.be.undefined; + expect(sock.onerror).to.not.equal(undefined); }); it('can set end handler on the socket', function () { const sock = new FauxSock(); const bs = new BrowserWebSocket(sock); - expect(sock.onclose).to.be.undefined; + expect(sock.onclose).to.equal(undefined); expect(() => bs.setOnCloseHandler(() => {})).to.not.throw(); - expect(sock.onclose).to.not.be.undefined; + expect(sock.onclose).to.not.equal(undefined); }); it('can set onerror on the socket', function () { const sock = new FauxSock(); const bs = new BrowserWebSocket(sock); bs.connect('nowhere'); - expect(sock.onerror).to.not.be.undefined; - expect(sock.onopen).to.not.be.undefined; + expect(sock.onerror).to.not.equal(undefined); + expect(sock.onopen).to.not.equal(undefined); }); it('can set onopen on the socket', function () { const sock = new FauxSock(); const bs = new BrowserWebSocket(sock); bs.connect('nowhere'); - expect(sock.onerror).to.not.be.undefined; - expect(sock.onopen).to.not.be.undefined; + expect(sock.onerror).to.not.equal(undefined); + expect(sock.onopen).to.not.equal(undefined); }); it('can close', function () { const sock = new FauxSock(); const bs = new BrowserWebSocket(sock); bs.connect('nowhere'); - expect(sock.onerror).to.not.be.undefined; - expect(sock.onopen).to.not.be.undefined; + expect(sock.onerror).to.not.equal(undefined); + expect(sock.onopen).to.not.equal(undefined); const closeSpy = spy(sock, 'close'); bs.close(); - expect(closeSpy.called).to.be.true; + expect(closeSpy.called).to.equal(true); }); }); }); diff --git a/libraries/botframework-streaming/tests/WebSocketClientServer.test.js b/libraries/botframework-streaming/tests/WebSocketClientServer.test.js index e8b8a20e3d..eb7f9c01f3 100644 --- a/libraries/botframework-streaming/tests/WebSocketClientServer.test.js +++ b/libraries/botframework-streaming/tests/WebSocketClientServer.test.js @@ -119,7 +119,7 @@ describe('WebSocket Client/Server Tests', function () { }); it('should call disconnectHandler', function () { - expect(disconnectionHandler.called).to.be.true; + expect(disconnectionHandler.called).to.equal(true); }); it('should disconnect', function () { @@ -186,7 +186,7 @@ describe('WebSocket Client/Server Tests', function () { }); it('should call disconnectHandler', function () { - expect(disconnectionHandler.called).to.be.true; + expect(disconnectionHandler.called).to.equal(true); }); it('should disconnect', function () { diff --git a/libraries/botframework-streaming/tests/helpers/fauxSock.js b/libraries/botframework-streaming/tests/helpers/fauxSock.js index f800d682d1..ec32e2234f 100644 --- a/libraries/botframework-streaming/tests/helpers/fauxSock.js +++ b/libraries/botframework-streaming/tests/helpers/fauxSock.js @@ -66,7 +66,7 @@ class FauxSock { close() { if (this.connected) { this.connected = false; - this.closeHandler && this.closeHandler(); + this.closeHandler?.(); } } end() { diff --git a/libraries/botframework-streaming/tests/helpers/fauxSocket.js b/libraries/botframework-streaming/tests/helpers/fauxSocket.js index 562a1e51af..c7b5eef64e 100644 --- a/libraries/botframework-streaming/tests/helpers/fauxSocket.js +++ b/libraries/botframework-streaming/tests/helpers/fauxSocket.js @@ -1,15 +1,11 @@ const { Duplex } = require('stream'); module.exports.FauxSocket = class FauxSocket extends Duplex { - // eslint-disable-next-line no-empty _read() {} - // eslint-disable-next-line no-empty _write() {} - // eslint-disable-next-line no-empty setNoDelay() {} - // eslint-disable-next-line no-empty setTimeout() {} }; From 7fc052b2aa319955dee8f54f65da9f2a7276e9b6 Mon Sep 17 00:00:00 2001 From: Joel Mut <62260472+sw-joelmut@users.noreply.github.com> Date: Mon, 6 Jan 2025 12:03:57 -0300 Subject: [PATCH 09/22] fix: [#4684] ESLint issues in botbuilder-dialogs-adaptive (#4826) * Fix eslint * Remove unnecessary empty line --- .../eslint.config.cjs | 11 ++-- .../botbuilder-dialogs-adaptive/package.json | 1 - .../src/actionContext.ts | 2 +- .../src/actions/actionScope.ts | 5 +- .../src/actions/baseInvokeDialog.ts | 3 +- .../src/actions/beginSkill.ts | 2 +- .../src/actions/cancelAllDialogsBase.ts | 3 +- .../src/actions/continueConversation.ts | 2 +- .../src/actions/continueConversationLater.ts | 2 +- .../src/actions/editActions.ts | 19 ++++--- .../src/actions/editArray.ts | 4 +- .../src/actions/forEach.ts | 2 +- .../src/actions/forEachPage.ts | 2 +- .../src/actions/getConversationMembers.ts | 3 +- .../src/actions/httpRequest.ts | 3 +- .../src/actions/ifCondition.ts | 3 +- .../src/actions/sendActivity.ts | 2 +- .../src/actions/setProperties.ts | 2 +- .../src/actions/switchCondition.ts | 25 +++++----- .../src/actions/telemetryTrackEventAction.ts | 3 +- .../src/actions/updateActivity.ts | 2 +- .../src/adaptiveBotComponent.ts | 4 +- .../src/adaptiveDialog.ts | 45 ++++++++--------- .../src/conditions/onActivity.ts | 2 +- .../src/conditions/onChooseIntent.ts | 10 ++-- .../src/conditions/onCondition.ts | 6 +-- .../src/conditions/onContinueConversation.ts | 2 +- .../src/conditions/onDialogEvent.ts | 2 +- .../src/conditions/onIntent.ts | 4 +- .../src/conditions/onUnknownIntent.ts | 4 +- .../converters/dialogExpressionConverter.ts | 2 +- .../src/dynamicBeginDialogDeserializer.ts | 8 ++- .../src/entityAssignment.ts | 2 +- .../src/entityInfo.ts | 2 + .../generators/languageGeneratorManager.ts | 2 +- .../generators/multiLanguageGeneratorBase.ts | 7 +-- .../resourceMultiLanguageGenerator.ts | 3 +- .../templateEngineLanguageGenerator.ts | 3 +- .../src/input/ask.ts | 4 +- .../src/input/attachmentInput.ts | 2 +- .../src/input/choiceInput.ts | 2 +- .../src/input/confirmInput.ts | 1 - .../src/input/dateTimeInput.ts | 1 - .../src/input/inputDialog.ts | 4 +- .../src/input/oauthInput.ts | 17 +++---- .../src/languageGenerationBotComponent.ts | 2 +- .../src/languageResourceLoader.ts | 6 +-- .../src/recognizers/adaptiveRecognizer.ts | 8 +-- .../recognizers/crossTrainedRecognizerSet.ts | 10 ++-- .../channelMentionEntityRecognizer.ts | 2 +- .../entityRecognizers/entityRecognizer.ts | 6 +-- .../entityRecognizers/entityRecognizerSet.ts | 8 +-- .../entityRecognizers/textEntityRecognizer.ts | 16 +++--- .../recognizers/multiLanguageRecognizer.ts | 8 +-- .../src/recognizers/recognizerSet.ts | 17 +++---- .../src/recognizers/regexRecognizer.ts | 6 +-- .../src/recognizers/valueRecognizer.ts | 4 +- .../src/skillExtensions.ts | 2 +- .../src/templates/activityTemplate.ts | 3 +- .../src/templates/staticActivityTemplate.ts | 3 +- .../src/templates/textTemplate.ts | 3 +- .../tests/LGGenerator.test.js | 6 +-- .../tests/activityFactory.test.js | 12 ++--- .../tests/beginSkill.test.js | 2 +- .../tests/choiceSet.test.ts | 3 +- .../tests/conditionals.test.js | 50 +++++++++---------- .../tests/conversationAction.test.js | 6 +-- .../tests/entityRecognizer.test.js | 4 +- .../tests/entityRecognizerRecognizer.test.js | 2 +- .../tests/expressionProperty.test.ts | 1 - .../tests/languageGeneratorConverter.test.js | 2 +- .../tests/memory_memoryScopes.test.js | 8 +-- .../tests/regexRecognizer.test.js | 9 ++-- .../tests/telemetryUtils.js | 2 +- 74 files changed, 222 insertions(+), 229 deletions(-) diff --git a/libraries/botbuilder-dialogs-adaptive/eslint.config.cjs b/libraries/botbuilder-dialogs-adaptive/eslint.config.cjs index 8a8c64d165..e7903d2781 100644 --- a/libraries/botbuilder-dialogs-adaptive/eslint.config.cjs +++ b/libraries/botbuilder-dialogs-adaptive/eslint.config.cjs @@ -1,13 +1,8 @@ -const onlyWarn = require("eslint-plugin-only-warn"); -const sharedConfig = require("../../eslint.config.cjs") +const sharedConfig = require('../../eslint.config.cjs'); module.exports = [ ...sharedConfig, { - ignores: ["tests/choiceSet.test.js", "tests/expressionProperty.test.js"], + ignores: ['tests/choiceSet.test.js', 'tests/expressionProperty.test.js'], }, - { - plugins: { - "only-warn": onlyWarn, - }, - }]; +]; diff --git a/libraries/botbuilder-dialogs-adaptive/package.json b/libraries/botbuilder-dialogs-adaptive/package.json index e20f5f9a58..73cdc8779d 100644 --- a/libraries/botbuilder-dialogs-adaptive/package.json +++ b/libraries/botbuilder-dialogs-adaptive/package.json @@ -43,7 +43,6 @@ "botbuilder-dialogs-declarative": "4.1.6", "botbuilder-lg": "4.1.6", "botframework-connector": "4.1.6", - "eslint-plugin-only-warn": "^1.1.0", "lodash": "^4.17.21", "node-fetch": "^2.7.0" }, diff --git a/libraries/botbuilder-dialogs-adaptive/src/actionContext.ts b/libraries/botbuilder-dialogs-adaptive/src/actionContext.ts index a3c5385057..31797e24a2 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/actionContext.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/actionContext.ts @@ -32,7 +32,7 @@ export class ActionContext extends DialogContext { parentDialogContext: DialogContext, state: DialogState, actions: ActionState[], - changeKey: symbol + changeKey: symbol, ) { super(dialogs, parentDialogContext, state); this.actions = actions; diff --git a/libraries/botbuilder-dialogs-adaptive/src/actions/actionScope.ts b/libraries/botbuilder-dialogs-adaptive/src/actions/actionScope.ts index 048702e7c7..fe99b3ea9e 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/actions/actionScope.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/actions/actionScope.ts @@ -42,7 +42,8 @@ export interface ActionScopeConfiguration extends DialogConfiguration { */ export class ActionScope extends Dialog - implements DialogDependencies, ActionScopeConfiguration { + implements DialogDependencies, ActionScopeConfiguration +{ /** * Creates a new `ActionScope` instance. * @@ -144,7 +145,7 @@ export class ActionScope */ protected async onActionScopeResult( dc: DialogContext, - actionScopeResult: ActionScopeResult + actionScopeResult: ActionScopeResult, ): Promise { switch (actionScopeResult.actionScopeCommand) { case ActionScopeCommands.GotoAction: diff --git a/libraries/botbuilder-dialogs-adaptive/src/actions/baseInvokeDialog.ts b/libraries/botbuilder-dialogs-adaptive/src/actions/baseInvokeDialog.ts index 7512fb9965..418ecf13a9 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/actions/baseInvokeDialog.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/actions/baseInvokeDialog.ts @@ -39,7 +39,8 @@ export interface BaseInvokeDialogConfiguration extends DialogConfiguration { */ export class BaseInvokeDialog extends Dialog - implements DialogDependencies, BaseInvokeDialogConfiguration { + implements DialogDependencies, BaseInvokeDialogConfiguration +{ /** * Initializes a new instance of the [BaseInvokeDialog](xref:botbuilder-dialogs-adaptive.BaseInvokeDialog) class. * diff --git a/libraries/botbuilder-dialogs-adaptive/src/actions/beginSkill.ts b/libraries/botbuilder-dialogs-adaptive/src/actions/beginSkill.ts index e5f096efc9..d8bfc719f8 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/actions/beginSkill.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/actions/beginSkill.ts @@ -165,7 +165,7 @@ export class BeginSkill extends SkillDialog implements BeginSkillConfiguration { const { conversationState, skillClient, conversationIdFactory, ...rest } = this; return rest; }, - }) + }), ); } diff --git a/libraries/botbuilder-dialogs-adaptive/src/actions/cancelAllDialogsBase.ts b/libraries/botbuilder-dialogs-adaptive/src/actions/cancelAllDialogsBase.ts index 185942f319..17bc2652f0 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/actions/cancelAllDialogsBase.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/actions/cancelAllDialogsBase.ts @@ -39,7 +39,8 @@ export interface CancelAllDialogsBaseConfiguration extends DialogConfiguration { */ export class CancelAllDialogsBase extends Dialog - implements CancelAllDialogsBaseConfiguration { + implements CancelAllDialogsBaseConfiguration +{ constructor(); /** diff --git a/libraries/botbuilder-dialogs-adaptive/src/actions/continueConversation.ts b/libraries/botbuilder-dialogs-adaptive/src/actions/continueConversation.ts index 740821db3e..d86d005fe6 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/actions/continueConversation.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/actions/continueConversation.ts @@ -100,7 +100,7 @@ export class ContinueConversation extends Dialog implements ContinueConversation value: this.value?.getValue(dc.state), }, conversationReference, - true + true, ); const queueStorage: QueueStorage = dc.context.turnState.get(DialogTurnStateConstants.queueStorage); diff --git a/libraries/botbuilder-dialogs-adaptive/src/actions/continueConversationLater.ts b/libraries/botbuilder-dialogs-adaptive/src/actions/continueConversationLater.ts index 0086d235c9..6d95e4a5cb 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/actions/continueConversationLater.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/actions/continueConversationLater.ts @@ -110,7 +110,7 @@ export class ContinueConversationLater extends Dialog implements ContinueConvers relatesTo: reference as ConversationReference, }, reference, - true + true, ); activity.value = this.value && this.value.getValue(dc.state); diff --git a/libraries/botbuilder-dialogs-adaptive/src/actions/editActions.ts b/libraries/botbuilder-dialogs-adaptive/src/actions/editActions.ts index 3a30392267..23aa80c6e7 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/actions/editActions.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/actions/editActions.ts @@ -36,7 +36,8 @@ export interface EditActionsConfiguration extends DialogConfiguration { */ export class EditActions extends Dialog - implements DialogDependencies, EditActionsConfiguration { + implements DialogDependencies, EditActionsConfiguration +{ static $kind = 'Microsoft.EditActions'; constructor(); @@ -120,15 +121,13 @@ export class EditActions } if (dc.parent instanceof ActionContext) { - const planActions = this.actions.map( - (action: Dialog): ActionState => { - return { - dialogStack: [], - dialogId: action.id, - options: options, - }; - } - ); + const planActions = this.actions.map((action: Dialog): ActionState => { + return { + dialogStack: [], + dialogId: action.id, + options: options, + }; + }); const changes: ActionChangeList = { changeType: this.changeType.getValue(dc.state), diff --git a/libraries/botbuilder-dialogs-adaptive/src/actions/editArray.ts b/libraries/botbuilder-dialogs-adaptive/src/actions/editArray.ts index 50c2aa1369..b189a7aa04 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/actions/editArray.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/actions/editArray.ts @@ -152,7 +152,7 @@ export class EditArray extends Dialog implements EditA if (!this.itemsProperty) { throw new Error( - `EditArray: "${this.changeType.toString()}" operation couldn't be performed because the itemsProperty wasn't specified.` + `EditArray: "${this.changeType.toString()}" operation couldn't be performed because the itemsProperty wasn't specified.`, ); } @@ -224,7 +224,7 @@ export class EditArray extends Dialog implements EditA throw new Error( `EditArray: "${this.changeType.toString()}" operation couldn't be performed for list "${ this.itemsProperty - }" because a value wasn't specified.` + }" because a value wasn't specified.`, ); } } diff --git a/libraries/botbuilder-dialogs-adaptive/src/actions/forEach.ts b/libraries/botbuilder-dialogs-adaptive/src/actions/forEach.ts index f00525e149..2febb0b645 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/actions/forEach.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/actions/forEach.ts @@ -145,7 +145,7 @@ export class ForEach extends ActionScope implements Fo */ protected async onContinueLoop( dc: DialogContext, - _actionScopeResult: ActionScopeResult + _actionScopeResult: ActionScopeResult, ): Promise { return await this.nextItem(dc); } diff --git a/libraries/botbuilder-dialogs-adaptive/src/actions/forEachPage.ts b/libraries/botbuilder-dialogs-adaptive/src/actions/forEachPage.ts index d13a7b4708..982facf1ca 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/actions/forEachPage.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/actions/forEachPage.ts @@ -162,7 +162,7 @@ export class ForEachPage extends ActionScope implement */ protected async onContinueLoop( dc: DialogContext, - _actionScopeResult: ActionScopeResult + _actionScopeResult: ActionScopeResult, ): Promise { return await this.nextPage(dc); } diff --git a/libraries/botbuilder-dialogs-adaptive/src/actions/getConversationMembers.ts b/libraries/botbuilder-dialogs-adaptive/src/actions/getConversationMembers.ts index 649ee25c0a..1526951cf4 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/actions/getConversationMembers.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/actions/getConversationMembers.ts @@ -35,7 +35,8 @@ export interface GetConversationMembersConfiguration extends DialogConfiguration */ export class GetConversationMembers extends Dialog - implements GetConversationMembersConfiguration { + implements GetConversationMembersConfiguration +{ static $kind = 'Microsoft.GetConversationMembers'; constructor(); diff --git a/libraries/botbuilder-dialogs-adaptive/src/actions/httpRequest.ts b/libraries/botbuilder-dialogs-adaptive/src/actions/httpRequest.ts index 128cbc9e93..c1bf767392 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/actions/httpRequest.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/actions/httpRequest.ts @@ -6,10 +6,9 @@ * Licensed under the MIT License. */ import { StatusCodes } from 'botbuilder-core'; -import fetch, { FetchError } from 'node-fetch'; +import fetch, { FetchError, Response, Headers } from 'node-fetch'; import { Activity } from 'botbuilder'; import { BoolProperty, EnumProperty, StringProperty, UnknownProperty } from '../properties'; -import { Response, Headers } from 'node-fetch'; import { evaluateExpression } from '../jsonExtensions'; import { diff --git a/libraries/botbuilder-dialogs-adaptive/src/actions/ifCondition.ts b/libraries/botbuilder-dialogs-adaptive/src/actions/ifCondition.ts index e6927bdfc7..a3fcafc9fd 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/actions/ifCondition.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/actions/ifCondition.ts @@ -33,7 +33,8 @@ export interface IfConditionConfiguration extends DialogConfiguration { */ export class IfCondition extends Dialog - implements DialogDependencies, IfConditionConfiguration { + implements DialogDependencies, IfConditionConfiguration +{ static $kind = 'Microsoft.IfCondition'; constructor(); diff --git a/libraries/botbuilder-dialogs-adaptive/src/actions/sendActivity.ts b/libraries/botbuilder-dialogs-adaptive/src/actions/sendActivity.ts index b7aae98699..e4c73452d3 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/actions/sendActivity.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/actions/sendActivity.ts @@ -102,7 +102,7 @@ export class SendActivity extends Dialog implements Se { utterance: dc.context.activity.text || '', }, - options + options, ); const activityResult = await this.activity.bind(dc, data); diff --git a/libraries/botbuilder-dialogs-adaptive/src/actions/setProperties.ts b/libraries/botbuilder-dialogs-adaptive/src/actions/setProperties.ts index 08caf92cf1..656dd6a50d 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/actions/setProperties.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/actions/setProperties.ts @@ -123,7 +123,7 @@ export class SetProperties extends Dialog implements S protected onComputeId(): string { return `SetProperties[${StringUtils.ellipsis( this.assignments.map((item): string => item.property.toString()).join(','), - 50 + 50, )}]`; } } diff --git a/libraries/botbuilder-dialogs-adaptive/src/actions/switchCondition.ts b/libraries/botbuilder-dialogs-adaptive/src/actions/switchCondition.ts index b9f692e2a5..9e180671de 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/actions/switchCondition.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/actions/switchCondition.ts @@ -39,7 +39,7 @@ type CaseInput = { class CasesConverter implements Converter, Case[]> { convert(items: Array): Case[] { return items.map( - (item: CaseInput | Case): Case => (item instanceof Case ? item : new Case(item.value, item.actions)) + (item: CaseInput | Case): Case => (item instanceof Case ? item : new Case(item.value, item.actions)), ); } } @@ -59,7 +59,8 @@ export interface SwitchConditionConfiguration extends DialogConfiguration { */ export class SwitchCondition extends Dialog - implements DialogDependencies, SwitchConditionConfiguration { + implements DialogDependencies, SwitchConditionConfiguration +{ static $kind = 'Microsoft.SwitchCondition'; constructor(); @@ -176,8 +177,8 @@ export class SwitchCondition caseScope.value, Expression.orExpression( Expression.equalsExpression(this.condition, new Constant(intVal)), - Expression.equalsExpression(this.condition, new Constant(caseScope.value)) - ) + Expression.equalsExpression(this.condition, new Constant(caseScope.value)), + ), ); continue; } @@ -188,8 +189,8 @@ export class SwitchCondition caseScope.value, Expression.orExpression( Expression.equalsExpression(this.condition, new Constant(floatVal)), - Expression.equalsExpression(this.condition, new Constant(caseScope.value)) - ) + Expression.equalsExpression(this.condition, new Constant(caseScope.value)), + ), ); continue; } @@ -200,8 +201,8 @@ export class SwitchCondition caseScope.value, Expression.orExpression( Expression.equalsExpression(this.condition, new Constant(true)), - Expression.equalsExpression(this.condition, new Constant(caseScope.value)) - ) + Expression.equalsExpression(this.condition, new Constant(caseScope.value)), + ), ); continue; } @@ -211,8 +212,8 @@ export class SwitchCondition caseScope.value, Expression.orExpression( Expression.equalsExpression(this.condition, new Constant(false)), - Expression.equalsExpression(this.condition, new Constant(caseScope.value)) - ) + Expression.equalsExpression(this.condition, new Constant(caseScope.value)), + ), ); continue; } @@ -221,7 +222,7 @@ export class SwitchCondition const { value } = new ValueExpression(caseScope.value).tryGetValue(dc.state); this._caseExpresssions.set( caseScope.value, - Expression.equalsExpression(this.condition, new Constant(value)) + Expression.equalsExpression(this.condition, new Constant(value)), ); } } @@ -234,7 +235,7 @@ export class SwitchCondition const { value, error } = caseCondition.tryEvaluate(dc.state); if (error) { throw new Error( - `Expression evaluation resulted in an error. Expression: ${caseCondition.toString()}. Error: ${error}` + `Expression evaluation resulted in an error. Expression: ${caseCondition.toString()}. Error: ${error}`, ); } diff --git a/libraries/botbuilder-dialogs-adaptive/src/actions/telemetryTrackEventAction.ts b/libraries/botbuilder-dialogs-adaptive/src/actions/telemetryTrackEventAction.ts index 764d09453d..c9d27d41f0 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/actions/telemetryTrackEventAction.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/actions/telemetryTrackEventAction.ts @@ -55,7 +55,8 @@ export interface TelemetryTrackEventActionConfiguration extends DialogConfigurat */ export class TelemetryTrackEventAction extends Dialog - implements TelemetryTrackEventActionConfiguration { + implements TelemetryTrackEventActionConfiguration +{ static $kind = 'Microsoft.TelemetryTrackEventAction'; /** diff --git a/libraries/botbuilder-dialogs-adaptive/src/actions/updateActivity.ts b/libraries/botbuilder-dialogs-adaptive/src/actions/updateActivity.ts index 8c665b7822..7c481d0d15 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/actions/updateActivity.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/actions/updateActivity.ts @@ -120,7 +120,7 @@ export class UpdateActivity extends Dialog implements utterance: dc.context.activity.text || '', }, dc.state, - options + options, ); const activityResult = await this.activity.bind(dc, data); diff --git a/libraries/botbuilder-dialogs-adaptive/src/adaptiveBotComponent.ts b/libraries/botbuilder-dialogs-adaptive/src/adaptiveBotComponent.ts index 77d0f0fbfd..dde9a1dc98 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/adaptiveBotComponent.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/adaptiveBotComponent.ts @@ -272,8 +272,8 @@ export class AdaptiveBotComponent extends BotComponent { loader: new DynamicBeginDialogDeserializer(resourceExplorer, resourceId), })); }, - } - ) + }, + ), ); } } diff --git a/libraries/botbuilder-dialogs-adaptive/src/adaptiveDialog.ts b/libraries/botbuilder-dialogs-adaptive/src/adaptiveDialog.ts index ff69c5b504..740459f348 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/adaptiveDialog.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/adaptiveDialog.ts @@ -58,9 +58,8 @@ import { FirstSelector, MostSpecificSelector } from './selectors'; import { TriggerSelector } from './triggerSelector'; import { TelemetryLoggerConstants } from './telemetryLoggerConstants'; -// eslint-disable-next-line @typescript-eslint/no-explicit-any function isDialogDependencies(val: any): val is DialogDependencies { - return typeof ((val as unknown) as DialogDependencies).getDependencies === 'function'; + return typeof (val as unknown as DialogDependencies).getDependencies === 'function'; } export interface AdaptiveDialogConfiguration extends DialogConfiguration { @@ -485,7 +484,7 @@ export class AdaptiveDialog extends DialogContainer im protected async processEvent( actionContext: ActionContext, dialogEvent: DialogEvent, - preBubble: boolean + preBubble: boolean, ): Promise { // Save into turn actionContext.state.setValue(TurnPath.dialogEvent, dialogEvent); @@ -501,7 +500,7 @@ export class AdaptiveDialog extends DialogContainer im // we have received a RecognizedIntent event // get the value and promote to turn.recognized, topintent, topscore and lastintent const recognizedResult = actionContext.state.getValue( - `${TurnPath.dialogEvent}.value` + `${TurnPath.dialogEvent}.value`, ); const { intent, score } = getTopScoringIntent(recognizedResult); actionContext.state.setValue(TurnPath.recognized, recognizedResult); @@ -1069,7 +1068,7 @@ export class AdaptiveDialog extends DialogContainer im properties: string[], turn: number, text: string, - entityToInfo: Record + entityToInfo: Record, ): void { Object.keys(entities).forEach((entityName) => { const instances = entities[this.instanceKey][entityName]; @@ -1084,7 +1083,7 @@ export class AdaptiveDialog extends DialogContainer im properties, turn, text, - entityToInfo + entityToInfo, ); }); } @@ -1103,7 +1102,7 @@ export class AdaptiveDialog extends DialogContainer im properties: string[], turn: number, text: string, - entityToInfo: Record + entityToInfo: Record, ): void { if (!name.startsWith('$')) { // Entities representing schema properties end in "Property" to prevent name collisions with the property itself. @@ -1140,7 +1139,7 @@ export class AdaptiveDialog extends DialogContainer im property, turn, text, - entityToInfo + entityToInfo, ); } else if (typeof entity === 'object' && entity !== null) { if (isEmpty(entity)) { @@ -1161,7 +1160,7 @@ export class AdaptiveDialog extends DialogContainer im properties, turn, text, - entityToInfo + entityToInfo, ); } } else if (isOp) { @@ -1185,7 +1184,7 @@ export class AdaptiveDialog extends DialogContainer im property: string, turn: number, text: string, - entityToInfo: Record + entityToInfo: Record, ): void { if (instance && rootInstance) { entityToInfo[name] ??= []; @@ -1224,7 +1223,7 @@ export class AdaptiveDialog extends DialogContainer im lastEvent: string, nextAssignment: EntityAssignment, askDefault: Record, - dialogDefault: Record + dialogDefault: Record, ): EntityAssignment[] { const globalExpectedOnly: string[] = this.dialogSchema.schema[this.expectedOnlyKey] ?? []; const requiresValue: string[] = this.dialogSchema.schema[this.requiresValueKey] ?? []; @@ -1240,7 +1239,7 @@ export class AdaptiveDialog extends DialogContainer im property: alternative.property, operation: alternative.operation, isExpected: expected.includes(alternative.property), - }) + }), ); } }); @@ -1262,7 +1261,7 @@ export class AdaptiveDialog extends DialogContainer im property: propSchema.name, operation: entity.operation, isExpected, - }) + }), ); } else if (entity.property === entityName && !entity.value && !entity.operation && isExpected) { // Recast property with no value as match for property entities. @@ -1272,7 +1271,7 @@ export class AdaptiveDialog extends DialogContainer im property: propSchema.name, operation: null, isExpected, - }) + }), ); } } @@ -1305,7 +1304,7 @@ export class AdaptiveDialog extends DialogContainer im if (!alternative.value) { // If alternative matches one alternative, it answers chooseProperty. const matches = nextAssignment.alternatives.filter((a) => - this.matchesAssignment(alternative, a) + this.matchesAssignment(alternative, a), ); if (matches.length === 1) { assignments.push( @@ -1313,7 +1312,7 @@ export class AdaptiveDialog extends DialogContainer im value: alternative, operation: AdaptiveEvents.chooseProperty, isExpected: true, - }) + }), ); } } @@ -1331,7 +1330,7 @@ export class AdaptiveDialog extends DialogContainer im property: null, operation: alternative.operation, isExpected: false, - }) + }), ); } }); @@ -1383,7 +1382,7 @@ export class AdaptiveDialog extends DialogContainer im private defaultOperation( assignment: EntityAssignment, askDefault: Record, - dialogDefault: Record + dialogDefault: Record, ): string { let operation: string; if (assignment.property) { @@ -1411,7 +1410,7 @@ export class AdaptiveDialog extends DialogContainer im ...acc, [assignment.property]: [...(acc[assignment.property] ?? []), assignment], }), - {} + {}, ); const output: EntityAssignment[] = []; @@ -1433,7 +1432,7 @@ export class AdaptiveDialog extends DialogContainer im (choice): boolean => !isEqual(choice, candidate) || (EntityInfo.sharesRoot(choice.value, candidate.value) && - !EntityInfo.overlaps(choice.value, candidate.value)) + !EntityInfo.overlaps(choice.value, candidate.value)), ); output.push(candidate); } @@ -1449,7 +1448,7 @@ export class AdaptiveDialog extends DialogContainer im actionContext: ActionContext, entities: NormalizedEntityInfos, existing: EntityAssignments, - lastEvent: string + lastEvent: string, ): Partial[] { const assignments = new EntityAssignments(); const expected: string[] = actionContext.state.getValue(DialogPath.expectedProperties, []); @@ -1462,7 +1461,7 @@ export class AdaptiveDialog extends DialogContainer im const nextAssignment = existing.nextAssignment; let candidates = this.removeOverlappingPerProperty( - this.candidates(entities, expected, lastEvent, nextAssignment, askDefaultOp, defaultOp) + this.candidates(entities, expected, lastEvent, nextAssignment, askDefaultOp, defaultOp), ).sort((a, b): number => (a.isExpected === b.isExpected ? 0 : a.isExpected ? -1 : 1)); const usedEntities = new Set(candidates.map((candidate) => candidate.value)); @@ -1607,7 +1606,7 @@ export class AdaptiveDialog extends DialogContainer im private mergeAssignments( newAssignments: EntityAssignments, old: EntityAssignments, - comparer: EntityAssignmentComparer + comparer: EntityAssignmentComparer, ): void { let list = old.assignments; for (const assign of newAssignments.assignments) { diff --git a/libraries/botbuilder-dialogs-adaptive/src/conditions/onActivity.ts b/libraries/botbuilder-dialogs-adaptive/src/conditions/onActivity.ts index 43c149d66a..65254a50dd 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/conditions/onActivity.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/conditions/onActivity.ts @@ -46,7 +46,7 @@ export class OnActivity extends OnDialogEvent implements OnActivityConfiguration // add constraints for activity type return Expression.andExpression( Expression.parse(`${TurnPath.activity}.type == '${this.type}'`), - super.createExpression() + super.createExpression(), ); } } diff --git a/libraries/botbuilder-dialogs-adaptive/src/conditions/onChooseIntent.ts b/libraries/botbuilder-dialogs-adaptive/src/conditions/onChooseIntent.ts index c0770234e2..13bd9426c8 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/conditions/onChooseIntent.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/conditions/onChooseIntent.ts @@ -39,13 +39,9 @@ export class OnChooseIntent extends OnIntent implements OnChooseIntentConfigurat */ protected createExpression(): Expression { if (this.intents?.length) { - const constraints = this.intents.map( - (intent: string): Expression => { - return Expression.parse( - `contains(jPath(${TurnPath.recognized}, '.candidates.intent'), '${intent}')` - ); - } - ); + const constraints = this.intents.map((intent: string): Expression => { + return Expression.parse(`contains(jPath(${TurnPath.recognized}, '.candidates.intent'), '${intent}')`); + }); return Expression.andExpression(super.createExpression(), ...constraints); } return super.createExpression(); diff --git a/libraries/botbuilder-dialogs-adaptive/src/conditions/onCondition.ts b/libraries/botbuilder-dialogs-adaptive/src/conditions/onCondition.ts index 545e2f8b1b..5056128a32 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/conditions/onCondition.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/conditions/onCondition.ts @@ -226,14 +226,14 @@ export class OnCondition extends Configurable implements DialogDependencies, OnC return { value: changed, error: undefined }; }, ReturnType.Boolean, - FunctionUtils.validateUnary + FunctionUtils.validateUnary, ); allExpressions.push( new Expression( ExpressionType.Ignore, Expression.lookup(ExpressionType.Ignore), - new Expression(evaluator.type, evaluator) - ) + new Expression(evaluator.type, evaluator), + ), ); } diff --git a/libraries/botbuilder-dialogs-adaptive/src/conditions/onContinueConversation.ts b/libraries/botbuilder-dialogs-adaptive/src/conditions/onContinueConversation.ts index f1862c696c..9b0280e6f0 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/conditions/onContinueConversation.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/conditions/onContinueConversation.ts @@ -34,7 +34,7 @@ export class OnContinueConversation extends OnEventActivity { // add constraints for activity type return Expression.andExpression( Expression.parse(`${TurnPath.activity}.name == 'ContinueConversation'`), - super.createExpression() + super.createExpression(), ); } } diff --git a/libraries/botbuilder-dialogs-adaptive/src/conditions/onDialogEvent.ts b/libraries/botbuilder-dialogs-adaptive/src/conditions/onDialogEvent.ts index 0f5d364cee..2d37738c66 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/conditions/onDialogEvent.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/conditions/onDialogEvent.ts @@ -44,7 +44,7 @@ export class OnDialogEvent extends OnCondition implements OnDialogEventConfigura protected createExpression(): Expression { return Expression.andExpression( Expression.parse(`${TurnPath.dialogEvent}.name == '${this.event}'`), - super.createExpression() + super.createExpression(), ); } } diff --git a/libraries/botbuilder-dialogs-adaptive/src/conditions/onIntent.ts b/libraries/botbuilder-dialogs-adaptive/src/conditions/onIntent.ts index 611bf99629..11e4c44d60 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/conditions/onIntent.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/conditions/onIntent.ts @@ -73,8 +73,8 @@ export class OnIntent extends OnDialogEvent implements OnIntentConfiguration { return Expression.parse(`exists(${entity})`); } return Expression.parse(`exists(@${entity})`); - }) - ) + }), + ), ); } diff --git a/libraries/botbuilder-dialogs-adaptive/src/conditions/onUnknownIntent.ts b/libraries/botbuilder-dialogs-adaptive/src/conditions/onUnknownIntent.ts index 05c368a322..6615e60e92 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/conditions/onUnknownIntent.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/conditions/onUnknownIntent.ts @@ -17,8 +17,8 @@ import { OnDialogEvent } from './onDialogEvent'; * there is no active plan being executed. * This trigger is run when the utterance is not recognized and the fallback consultation is happening * It will only trigger if and when - * * it is the leaf dialog AND - * * none of the parent dialogs handle the event + * it is the leaf dialog AND + * none of the parent dialogs handle the event * This provides the parent dialogs the opportunity to handle global commands as fallback interruption. */ export class OnUnknownIntent extends OnDialogEvent { diff --git a/libraries/botbuilder-dialogs-adaptive/src/converters/dialogExpressionConverter.ts b/libraries/botbuilder-dialogs-adaptive/src/converters/dialogExpressionConverter.ts index 860ff3af6f..c2c79f792a 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/converters/dialogExpressionConverter.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/converters/dialogExpressionConverter.ts @@ -42,6 +42,6 @@ export class DialogExpressionConverter implements Converter { + implements CustomDeserializer +{ /** * Intializes an instance of `DynamicBeginDialogDeserializer`. * * @param _resourceExplorer The `ResourceExplorer` used by the deserializer. * @param _resourceId The resource id of the dynamic dialog. */ - constructor(private readonly _resourceExplorer: ResourceExplorer, private readonly _resourceId: string) {} + constructor( + private readonly _resourceExplorer: ResourceExplorer, + private readonly _resourceId: string, + ) {} /** * The method that loads the configuration object to a `DynamicBeginDialog` object. diff --git a/libraries/botbuilder-dialogs-adaptive/src/entityAssignment.ts b/libraries/botbuilder-dialogs-adaptive/src/entityAssignment.ts index 980b93e410..5ec4a21d1b 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/entityAssignment.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/entityAssignment.ts @@ -157,7 +157,7 @@ export class EntityAssignment implements EntityAssignmentConfiguration { */ toString(): string { return `${this.isExpected ? '+' : ''}${this.event}: ${this.property} = ${this.operation}(${EntityInfo.toString( - this.value + this.value, )})`; } } diff --git a/libraries/botbuilder-dialogs-adaptive/src/entityInfo.ts b/libraries/botbuilder-dialogs-adaptive/src/entityInfo.ts index ef60e8b110..c9a4d36a2e 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/entityInfo.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/entityInfo.ts @@ -9,6 +9,7 @@ /** * Extended information about an entity including $instance data. */ +// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging export interface EntityInfo { /** * Name of entity. @@ -86,6 +87,7 @@ export interface NormalizedEntityInfos { /** * Extended information about an entity including $instance data. */ +// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging export class EntityInfo { /** * Print an entity as a string. diff --git a/libraries/botbuilder-dialogs-adaptive/src/generators/languageGeneratorManager.ts b/libraries/botbuilder-dialogs-adaptive/src/generators/languageGeneratorManager.ts index 898a8a3542..a673f2fd66 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/generators/languageGeneratorManager.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/generators/languageGeneratorManager.ts @@ -81,7 +81,7 @@ export class LanguageGeneratorManager LanguageResourceLoader.parseLGFileName(u.id).prefix === - LanguageResourceLoader.parseLGFileName(resourceName).prefix + LanguageResourceLoader.parseLGFileName(resourceName).prefix, ); if (resource === undefined) { diff --git a/libraries/botbuilder-dialogs-adaptive/src/generators/multiLanguageGeneratorBase.ts b/libraries/botbuilder-dialogs-adaptive/src/generators/multiLanguageGeneratorBase.ts index 8642867c96..f46b9610f3 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/generators/multiLanguageGeneratorBase.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/generators/multiLanguageGeneratorBase.ts @@ -20,10 +20,11 @@ export interface MultiLanguageGeneratorBaseConfiguration { */ export abstract class MultiLanguageGeneratorBase< T = unknown, - D extends Record = Record + D extends Record = Record, > extends Configurable - implements LanguageGenerator, MultiLanguageGeneratorBaseConfiguration { + implements LanguageGenerator, MultiLanguageGeneratorBaseConfiguration +{ /** * Language policy required by language generator. */ @@ -50,7 +51,7 @@ export abstract class MultiLanguageGeneratorBase< */ abstract tryGetGenerator( dialogContext: DialogContext, - locale: string + locale: string, ): { exist: boolean; result: LanguageGenerator }; /** diff --git a/libraries/botbuilder-dialogs-adaptive/src/generators/resourceMultiLanguageGenerator.ts b/libraries/botbuilder-dialogs-adaptive/src/generators/resourceMultiLanguageGenerator.ts index 01e322ea12..54d91a72c3 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/generators/resourceMultiLanguageGenerator.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/generators/resourceMultiLanguageGenerator.ts @@ -26,7 +26,8 @@ export interface ResourceMultiLanguageGeneratorConfiguration extends MultiLangua */ export class ResourceMultiLanguageGenerator = Record> extends MultiLanguageGeneratorBase - implements ResourceMultiLanguageGeneratorConfiguration { + implements ResourceMultiLanguageGeneratorConfiguration +{ static $kind = 'Microsoft.ResourceMultiLanguageGenerator'; /** diff --git a/libraries/botbuilder-dialogs-adaptive/src/generators/templateEngineLanguageGenerator.ts b/libraries/botbuilder-dialogs-adaptive/src/generators/templateEngineLanguageGenerator.ts index 517be513f6..4be3e1e712 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/generators/templateEngineLanguageGenerator.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/generators/templateEngineLanguageGenerator.ts @@ -22,7 +22,8 @@ export interface TemplateEngineLanguageGeneratorConfiguration { */ export class TemplateEngineLanguageGenerator = Record> extends Configurable - implements LanguageGenerator, TemplateEngineLanguageGeneratorConfiguration { + implements LanguageGenerator, TemplateEngineLanguageGeneratorConfiguration +{ static $kind = 'Microsoft.TemplateEngineLanguageGenerator'; private readonly DEFAULTLABEL: string = 'Unknown'; diff --git a/libraries/botbuilder-dialogs-adaptive/src/input/ask.ts b/libraries/botbuilder-dialogs-adaptive/src/input/ask.ts index a48a533617..db64376fb4 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/input/ask.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/input/ask.ts @@ -111,10 +111,10 @@ export class Ask extends SendActivity implements AskConfiguration { lastTrigger && !expected.some( (prop: string): boolean => - !lastExpectedProperties.some((lastProp: string): boolean => lastProp === prop) + !lastExpectedProperties.some((lastProp: string): boolean => lastProp === prop), ) && !lastExpectedProperties.some( - (lastProp: string): boolean => !expected.some((prop: string): boolean => prop === lastProp) + (lastProp: string): boolean => !expected.some((prop: string): boolean => prop === lastProp), ) && lastTrigger.name === trigger.name ) { diff --git a/libraries/botbuilder-dialogs-adaptive/src/input/attachmentInput.ts b/libraries/botbuilder-dialogs-adaptive/src/input/attachmentInput.ts index cecfa01770..7c9d424107 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/input/attachmentInput.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/input/attachmentInput.ts @@ -26,7 +26,7 @@ export interface AttachmentInputConfiguration extends InputDialogConfiguration { export class AttachmentInput extends InputDialog implements AttachmentInputConfiguration { static $kind = 'Microsoft.AttachmentInput'; outputFormat: EnumExpression = new EnumExpression( - AttachmentOutputFormat.first + AttachmentOutputFormat.first, ); /** diff --git a/libraries/botbuilder-dialogs-adaptive/src/input/choiceInput.ts b/libraries/botbuilder-dialogs-adaptive/src/input/choiceInput.ts index 4c383b6921..af118bfed1 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/input/choiceInput.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/input/choiceInput.ts @@ -141,7 +141,7 @@ export class ChoiceInput extends InputDialog implements ChoiceInputConfiguration protected trackGeneratorResultEvent( dc: DialogContext, activityTemplate: TemplateInterface, DialogStateManager>, - msg: Partial + msg: Partial, ): void { const options = dc.state.getValue(ChoiceInput.OPTIONS_PROPERTY); const properties = { diff --git a/libraries/botbuilder-dialogs-adaptive/src/input/confirmInput.ts b/libraries/botbuilder-dialogs-adaptive/src/input/confirmInput.ts index 2c5bf848ae..f0e34c5436 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/input/confirmInput.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/input/confirmInput.ts @@ -31,7 +31,6 @@ import { recognizeChoices, } from 'botbuilder-dialogs'; -// eslint-disable-next-line import/no-extraneous-dependencies import * as Recognizers from '@microsoft/recognizers-text-choice'; import { ChoiceOptionsSet } from './choiceOptionsSet'; diff --git a/libraries/botbuilder-dialogs-adaptive/src/input/dateTimeInput.ts b/libraries/botbuilder-dialogs-adaptive/src/input/dateTimeInput.ts index 3428502491..b61ab7bf13 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/input/dateTimeInput.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/input/dateTimeInput.ts @@ -11,7 +11,6 @@ import { StringExpression, StringExpressionConverter } from 'adaptive-expression import { InputDialog, InputDialogConfiguration, InputState } from './inputDialog'; import { StringProperty } from '../properties'; -// eslint-disable-next-line import/no-extraneous-dependencies import * as Recognizers from '@microsoft/recognizers-text-date-time'; export interface DateTimeInputConfiguration extends InputDialogConfiguration { diff --git a/libraries/botbuilder-dialogs-adaptive/src/input/inputDialog.ts b/libraries/botbuilder-dialogs-adaptive/src/input/inputDialog.ts index de0146bdd3..7533247c1b 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/input/inputDialog.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/input/inputDialog.ts @@ -397,7 +397,7 @@ export abstract class InputDialog extends Dialog implements InputDialogConfigura protected trackGeneratorResultEvent( dc: DialogContext, activityTemplate: TemplateInterface, DialogStateManager>, - msg: Partial + msg: Partial, ): void { this.telemetryClient.trackEvent({ name: TelemetryLoggerConstants.GeneratorResultEvent, @@ -424,7 +424,7 @@ export abstract class InputDialog extends Dialog implements InputDialogConfigura channelId: string, choices: Choice[], style: ListStyle, - options?: ChoiceFactoryOptions + options?: ChoiceFactoryOptions, ): Partial { // Create temporary msg let msg: Partial; diff --git a/libraries/botbuilder-dialogs-adaptive/src/input/oauthInput.ts b/libraries/botbuilder-dialogs-adaptive/src/input/oauthInput.ts index 1dba2fdf9b..588f3ffc1d 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/input/oauthInput.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/input/oauthInput.ts @@ -15,6 +15,13 @@ import { tokenExchangeOperationName, tokenResponseEventName, verifyStateOperationName, + Activity, + ActivityTypes, + InputHints, + StatusCodes, + TokenExchangeInvokeRequest, + TokenResponse, + TurnContext, } from 'botbuilder'; import { @@ -25,16 +32,6 @@ import { StringExpressionConverter, } from 'adaptive-expressions'; -import { - Activity, - ActivityTypes, - InputHints, - StatusCodes, - TokenExchangeInvokeRequest, - TokenResponse, - TurnContext, -} from 'botbuilder'; - import { Converter, ConverterFactory, diff --git a/libraries/botbuilder-dialogs-adaptive/src/languageGenerationBotComponent.ts b/libraries/botbuilder-dialogs-adaptive/src/languageGenerationBotComponent.ts index dd55d518d5..858cb7a71a 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/languageGenerationBotComponent.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/languageGenerationBotComponent.ts @@ -33,7 +33,7 @@ export class LanguageGenerationBotComponent extends BotComponent { }, ]; }, - }) + }), ); } } diff --git a/libraries/botbuilder-dialogs-adaptive/src/languageResourceLoader.ts b/libraries/botbuilder-dialogs-adaptive/src/languageResourceLoader.ts index cd067dfeda..2ee8a2944a 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/languageResourceLoader.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/languageResourceLoader.ts @@ -36,7 +36,7 @@ export class LanguageResourceLoader { const suffix = suffixs[index]; const resourcesWithSuffix = allResouces.filter( (u): boolean => - this.parseLGFileName(u.id).language.toLocaleLowerCase() === suffix.toLocaleLowerCase() + this.parseLGFileName(u.id).language.toLocaleLowerCase() === suffix.toLocaleLowerCase(), ); resourcesWithSuffix.forEach((u): void => { const resourceName = u.id; @@ -57,7 +57,7 @@ export class LanguageResourceLoader { if (resourceMapping.has(locale)) { const resourcesWithEmptySuffix = allResouces.filter( - (u): boolean => this.parseLGFileName(u.id).language === '' + (u): boolean => this.parseLGFileName(u.id).language === '', ); resourcesWithEmptySuffix.forEach((u): void => { const resourceName = u.id; @@ -133,7 +133,7 @@ export class LanguageResourceLoader { for (const currentLocale of resourceMapping.keys()) { const currentResourcePool: Resource[] = resourceMapping.get(currentLocale); const existLocale = Array.from(resourcePoolDict.keys()).find((u) => - this.hasSameResourcePool(resourcePoolDict.get(u), currentResourcePool) + this.hasSameResourcePool(resourcePoolDict.get(u), currentResourcePool), ); if (existLocale === undefined) { resourcePoolDict.set(currentLocale, currentResourcePool); diff --git a/libraries/botbuilder-dialogs-adaptive/src/recognizers/adaptiveRecognizer.ts b/libraries/botbuilder-dialogs-adaptive/src/recognizers/adaptiveRecognizer.ts index 0ea6d56b13..22591c4279 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/recognizers/adaptiveRecognizer.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/recognizers/adaptiveRecognizer.ts @@ -22,7 +22,7 @@ export abstract class AdaptiveRecognizer extends Recognizer implements AdaptiveR * (Optional) Flag that designates whether personally identifiable information (PII) should log to telemetry. */ logPersonalInformation: BoolExpression = new BoolExpression( - '=settings.runtimeSettings.telemetry.logPersonalInformation' + '=settings.runtimeSettings.telemetry.logPersonalInformation', ); /** @@ -36,11 +36,11 @@ export abstract class AdaptiveRecognizer extends Recognizer implements AdaptiveR protected fillRecognizerResultTelemetryProperties( recognizerResult: RecognizerResult, telemetryProperties: Record, - dialogContext: DialogContext + dialogContext: DialogContext, ): Record { if (!dialogContext) { throw new Error( - 'DialogContext needed for state in AdaptiveRecognizer.fillRecognizerResultTelemetryProperties method.' + 'DialogContext needed for state in AdaptiveRecognizer.fillRecognizerResultTelemetryProperties method.', ); } const { intent, score } = getTopScoringIntent(recognizerResult); @@ -51,7 +51,7 @@ export abstract class AdaptiveRecognizer extends Recognizer implements AdaptiveR Intents: intentsCount > 0 ? JSON.stringify(recognizerResult.intents) : undefined, Entities: recognizerResult.entities ? JSON.stringify(recognizerResult.entities) : undefined, AdditionalProperties: JSON.stringify( - omit(recognizerResult, ['text', 'alteredText', 'intents', 'entities']) + omit(recognizerResult, ['text', 'alteredText', 'intents', 'entities']), ), }; diff --git a/libraries/botbuilder-dialogs-adaptive/src/recognizers/crossTrainedRecognizerSet.ts b/libraries/botbuilder-dialogs-adaptive/src/recognizers/crossTrainedRecognizerSet.ts index 7deaf1739a..2f964dfde3 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/recognizers/crossTrainedRecognizerSet.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/recognizers/crossTrainedRecognizerSet.ts @@ -60,7 +60,7 @@ export class CrossTrainedRecognizerSet extends AdaptiveRecognizer implements Cro dialogContext: DialogContext, activity: Activity, telemetryProperties?: Record, - telemetryMetrics?: Record + telemetryMetrics?: Record, ): Promise { if (!this.recognizers.length) { return { @@ -80,11 +80,11 @@ export class CrossTrainedRecognizerSet extends AdaptiveRecognizer implements Cro dialogContext, activity, telemetryProperties, - telemetryMetrics + telemetryMetrics, ); result['id'] = recognizer.id; return result; - }) + }), ); const result = this.processResults(results); @@ -92,7 +92,7 @@ export class CrossTrainedRecognizerSet extends AdaptiveRecognizer implements Cro dialogContext, TelemetryLoggerConstants.CrossTrainedRecognizerSetResultEvent, this.fillRecognizerResultTelemetryProperties(result, telemetryProperties, dialogContext), - telemetryMetrics + telemetryMetrics, ); return result; } @@ -162,7 +162,7 @@ export class CrossTrainedRecognizerSet extends AdaptiveRecognizer implements Cro // filter out redirect results and return `ChooseIntent`. const recognizersWithRealIntents = pickBy( recognizerResults, - (value) => !this.isRedirect(getTopScoringIntent(value).intent) + (value) => !this.isRedirect(getTopScoringIntent(value).intent), ); return this.createChooseIntentResult(recognizersWithRealIntents); } diff --git a/libraries/botbuilder-dialogs-adaptive/src/recognizers/entityRecognizers/channelMentionEntityRecognizer.ts b/libraries/botbuilder-dialogs-adaptive/src/recognizers/entityRecognizers/channelMentionEntityRecognizer.ts index 116d111294..56a799be25 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/recognizers/entityRecognizers/channelMentionEntityRecognizer.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/recognizers/entityRecognizers/channelMentionEntityRecognizer.ts @@ -29,7 +29,7 @@ export class ChannelMentionEntityRecognizer extends AdaptiveRecognizer { _dialogContext: DialogContext, activity: Partial, _telemetryProperties?: Record, - _telemetryMetrics?: Record + _telemetryMetrics?: Record, ): Promise { const result: RecognizerResult = { text: '', diff --git a/libraries/botbuilder-dialogs-adaptive/src/recognizers/entityRecognizers/entityRecognizer.ts b/libraries/botbuilder-dialogs-adaptive/src/recognizers/entityRecognizers/entityRecognizer.ts index 194e0e0c72..01fa2ec0b6 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/recognizers/entityRecognizers/entityRecognizer.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/recognizers/entityRecognizers/entityRecognizer.ts @@ -28,7 +28,7 @@ export class EntityRecognizer extends AdaptiveRecognizer { dialogContext: DialogContext, activity: Partial, _telemetryProperties?: Record, - _telemetryMetrics?: Record + _telemetryMetrics?: Record, ): Promise { // Identify matched intents const text = activity.text ?? ''; @@ -56,7 +56,7 @@ export class EntityRecognizer extends AdaptiveRecognizer { dialogContext, dialogContext.context.activity.text, dialogContext.context.activity.locale, - entityPool + entityPool, ); entityPool.push(...newEntities); @@ -109,7 +109,7 @@ export class EntityRecognizer extends AdaptiveRecognizer { _dialogContext: DialogContext, _text: string, _locale: string, - _entities: Entity[] + _entities: Entity[], ): Promise { return []; } diff --git a/libraries/botbuilder-dialogs-adaptive/src/recognizers/entityRecognizers/entityRecognizerSet.ts b/libraries/botbuilder-dialogs-adaptive/src/recognizers/entityRecognizers/entityRecognizerSet.ts index d04846d0ab..64f4889b83 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/recognizers/entityRecognizers/entityRecognizerSet.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/recognizers/entityRecognizers/entityRecognizerSet.ts @@ -30,7 +30,7 @@ export class EntityRecognizerSet extends Array { dialogContext: DialogContext, text: string, locale: string, - entities: Entity[] = [] + entities: Entity[] = [], ): Promise { const allNewEntities: Entity[] = []; let entitiesToProcess: Entity[] = [...entities]; @@ -53,14 +53,14 @@ export class EntityRecognizerSet extends Array { dialogContext, text, locale, - entitiesToProcess + entitiesToProcess, ); for (let j = 0; j < newEntities.length; j++) { const newEntity = newEntities[j]; - // eslint-disable-next-line @typescript-eslint/explicit-function-return-type + if ( !allNewEntities.find( - (entity) => !newEntity && JSON.stringify(entity) == JSON.stringify(newEntity) + (entity) => !newEntity && JSON.stringify(entity) == JSON.stringify(newEntity), ) ) { allNewEntities.push(newEntity); diff --git a/libraries/botbuilder-dialogs-adaptive/src/recognizers/entityRecognizers/textEntityRecognizer.ts b/libraries/botbuilder-dialogs-adaptive/src/recognizers/entityRecognizers/textEntityRecognizer.ts index a4276033ab..21f0fe63e0 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/recognizers/entityRecognizers/textEntityRecognizer.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/recognizers/entityRecognizers/textEntityRecognizer.ts @@ -29,17 +29,15 @@ export abstract class TextEntityRecognizer extends EntityRecognizer { dialogContext: DialogContext, text: string, locale: string, - entities: Entity[] + entities: Entity[], ): Promise { const culture = Culture.mapToNearestLanguage(locale ?? ''); return entities .filter((e: Entity): boolean => e.type == 'text') - .map( - (e: Entity): TextEntity => { - const textEntity = new TextEntity(); - return Object.assign(textEntity, e); - } - ) + .map((e: Entity): TextEntity => { + const textEntity = new TextEntity(); + return Object.assign(textEntity, e); + }) .reduce((entities: Entity[], textEntity: TextEntity) => { return entities.concat( this._recognize(textEntity.text, culture).map((result: ModelResult) => { @@ -47,14 +45,14 @@ export abstract class TextEntityRecognizer extends EntityRecognizer { { type: result.typeName, }, - result + result, ); delete newEntity.typeName; // The text recognizer libraries return models with End => array inclusive endIndex. // We want end to be (end-start) = length, length = endIndex - startIndex. newEntity.end += 1; return newEntity; - }) + }), ); }, []); } diff --git a/libraries/botbuilder-dialogs-adaptive/src/recognizers/multiLanguageRecognizer.ts b/libraries/botbuilder-dialogs-adaptive/src/recognizers/multiLanguageRecognizer.ts index 3c7c746239..290386a9d8 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/recognizers/multiLanguageRecognizer.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/recognizers/multiLanguageRecognizer.ts @@ -57,7 +57,7 @@ export class MultiLanguageRecognizer extends AdaptiveRecognizer implements Multi dialogContext: DialogContext, activity: Activity, telemetryProperties?: { [key: string]: string }, - telemetryMetrics?: { [key: string]: number } + telemetryMetrics?: { [key: string]: number }, ): Promise { let languagepolicy: LanguagePolicy = this.languagePolicy; if (!languagepolicy) { @@ -91,13 +91,13 @@ export class MultiLanguageRecognizer extends AdaptiveRecognizer implements Multi dialogContext, activity, telemetryProperties, - telemetryMetrics + telemetryMetrics, ); this.trackRecognizerResult( dialogContext, TelemetryLoggerConstants.MultiLanguageRecognizerResultEvent, this.fillRecognizerResultTelemetryProperties(result, telemetryProperties, dialogContext), - telemetryMetrics + telemetryMetrics, ); return result; } @@ -112,7 +112,7 @@ export class MultiLanguageRecognizer extends AdaptiveRecognizer implements Multi dialogContext, TelemetryLoggerConstants.MultiLanguageRecognizerResultEvent, this.fillRecognizerResultTelemetryProperties(recognizerResult, telemetryProperties, dialogContext), - telemetryMetrics + telemetryMetrics, ); return recognizerResult; diff --git a/libraries/botbuilder-dialogs-adaptive/src/recognizers/recognizerSet.ts b/libraries/botbuilder-dialogs-adaptive/src/recognizers/recognizerSet.ts index 37f46e4791..11574b0c10 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/recognizers/recognizerSet.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/recognizers/recognizerSet.ts @@ -50,14 +50,12 @@ export class RecognizerSet extends AdaptiveRecognizer implements RecognizerSetCo dialogContext: DialogContext, activity: Activity, telemetryProperties?: { [key: string]: string }, - telemetryMetrics?: { [key: string]: number } + telemetryMetrics?: { [key: string]: number }, ): Promise { const results = await Promise.all( - this.recognizers.map( - (recognizer: Recognizer): Promise => { - return recognizer.recognize(dialogContext, activity, telemetryProperties, telemetryMetrics); - } - ) + this.recognizers.map((recognizer: Recognizer): Promise => { + return recognizer.recognize(dialogContext, activity, telemetryProperties, telemetryMetrics); + }), ); const recognizerResult: RecognizerResult = this.mergeResults(results); @@ -66,7 +64,7 @@ export class RecognizerSet extends AdaptiveRecognizer implements RecognizerSetCo dialogContext, TelemetryLoggerConstants.RecognizerSetResultEvent, this.fillRecognizerResultTelemetryProperties(recognizerResult, telemetryProperties, dialogContext), - telemetryMetrics + telemetryMetrics, ); return recognizerResult; @@ -118,9 +116,8 @@ export class RecognizerSet extends AdaptiveRecognizer implements RecognizerSetCo for (const [propertyName, propertyVal] of Object.entries(result.entities)) { if (propertyName === '$instance') { for (const [entityName, entityValue] of Object.entries(propertyVal)) { - const mergedInstanceEntities = (mergedRecognizerResult.entities['$instance'][ - entityName - ] ??= []); + const mergedInstanceEntities = (mergedRecognizerResult.entities['$instance'][entityName] ??= + []); mergedInstanceEntities.push(...entityValue); } } else { diff --git a/libraries/botbuilder-dialogs-adaptive/src/recognizers/regexRecognizer.ts b/libraries/botbuilder-dialogs-adaptive/src/recognizers/regexRecognizer.ts index d5f95ed071..184091f972 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/recognizers/regexRecognizer.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/recognizers/regexRecognizer.ts @@ -75,7 +75,7 @@ export class RegexRecognizer extends AdaptiveRecognizer implements RegexRecogniz dialogContext: DialogContext, activity: Activity, telemetryProperties?: { [key: string]: string }, - telemetryMetrics?: { [key: string]: number } + telemetryMetrics?: { [key: string]: number }, ): Promise { const text = activity.text ?? ''; const locale = activity.locale ?? Culture.English; @@ -176,13 +176,13 @@ export class RegexRecognizer extends AdaptiveRecognizer implements RegexRecogniz 'RegexRecognizer', recognizerResult, 'RecognizerResult', - 'Regex RecognizerResult' + 'Regex RecognizerResult', ); this.trackRecognizerResult( dialogContext, TelemetryLoggerConstants.RegexRecognizerResultEvent, this.fillRecognizerResultTelemetryProperties(recognizerResult, telemetryProperties, dialogContext), - telemetryMetrics + telemetryMetrics, ); return recognizerResult; } diff --git a/libraries/botbuilder-dialogs-adaptive/src/recognizers/valueRecognizer.ts b/libraries/botbuilder-dialogs-adaptive/src/recognizers/valueRecognizer.ts index 63cdff515a..40c3cca12e 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/recognizers/valueRecognizer.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/recognizers/valueRecognizer.ts @@ -33,7 +33,7 @@ export class ValueRecognizer extends AdaptiveRecognizer { dialogContext: DialogContext, activity: Activity, telemetryProperties?: { [key: string]: string }, - telemetryMetrics?: { [key: string]: number } + telemetryMetrics?: { [key: string]: number }, ): Promise { const recognizerResult: RecognizerResult = { text: activity.text, @@ -60,7 +60,7 @@ export class ValueRecognizer extends AdaptiveRecognizer { dialogContext, TelemetryLoggerConstants.ValueRecognizerResultEvent, this.fillRecognizerResultTelemetryProperties(recognizerResult, telemetryProperties, dialogContext), - telemetryMetrics + telemetryMetrics, ); return recognizerResult; diff --git a/libraries/botbuilder-dialogs-adaptive/src/skillExtensions.ts b/libraries/botbuilder-dialogs-adaptive/src/skillExtensions.ts index 043f6c893d..95f97a4f9e 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/skillExtensions.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/skillExtensions.ts @@ -44,7 +44,7 @@ export class SkillExtensions { */ static useSkillConversationIdFactory( dialogManager: DialogManager, - skillConversationIdFactory: SkillConversationIdFactoryBase + skillConversationIdFactory: SkillConversationIdFactoryBase, ): DialogManager { dialogManager.initialTurnState.set(skillConversationIdFactoryKey, skillConversationIdFactory); return dialogManager; diff --git a/libraries/botbuilder-dialogs-adaptive/src/templates/activityTemplate.ts b/libraries/botbuilder-dialogs-adaptive/src/templates/activityTemplate.ts index ebe78f04af..54162241d9 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/templates/activityTemplate.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/templates/activityTemplate.ts @@ -28,7 +28,8 @@ export interface ActivityTemplateConguration { * and processed through registered language generator. */ export class ActivityTemplate - implements TemplateInterface, DialogStateManager>, ActivityTemplateConguration, Configurable { + implements TemplateInterface, DialogStateManager>, ActivityTemplateConguration, Configurable +{ static $kind = 'Microsoft.ActivityTemplate'; /** diff --git a/libraries/botbuilder-dialogs-adaptive/src/templates/staticActivityTemplate.ts b/libraries/botbuilder-dialogs-adaptive/src/templates/staticActivityTemplate.ts index 5c22ae0c9c..f4973269c6 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/templates/staticActivityTemplate.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/templates/staticActivityTemplate.ts @@ -17,7 +17,8 @@ export interface StaticActivityTemplateConfiguration { * Defines a static activity as a template. */ export class StaticActivityTemplate - implements TemplateInterface, unknown>, StaticActivityTemplateConfiguration, Configurable { + implements TemplateInterface, unknown>, StaticActivityTemplateConfiguration, Configurable +{ static $kind = 'Microsoft.StaticActivityTemplate'; /** diff --git a/libraries/botbuilder-dialogs-adaptive/src/templates/textTemplate.ts b/libraries/botbuilder-dialogs-adaptive/src/templates/textTemplate.ts index 955d57cc79..0e7d745c68 100644 --- a/libraries/botbuilder-dialogs-adaptive/src/templates/textTemplate.ts +++ b/libraries/botbuilder-dialogs-adaptive/src/templates/textTemplate.ts @@ -20,7 +20,8 @@ export interface TextTemplateConfiguration { * and processed through registered language generator. */ export class TextTemplate> - implements TemplateInterface, TextTemplateConfiguration, Configurable { + implements TemplateInterface, TextTemplateConfiguration, Configurable +{ static $kind = 'Microsoft.TextTemplate'; /** diff --git a/libraries/botbuilder-dialogs-adaptive/tests/LGGenerator.test.js b/libraries/botbuilder-dialogs-adaptive/tests/LGGenerator.test.js index c30e8edc7f..ef372289d8 100644 --- a/libraries/botbuilder-dialogs-adaptive/tests/LGGenerator.test.js +++ b/libraries/botbuilder-dialogs-adaptive/tests/LGGenerator.test.js @@ -49,7 +49,7 @@ describe('LGLanguageGenerator', function () { assert.equal(resourceNames.length, 7); assert.deepStrictEqual( new Set(resourceNames), - new Set(['a.lg', 'b.lg', 'c.lg', 'NormalStructuredLG.lg', 'root.lg', 'subDialog.lg', 'test.lg']) + new Set(['a.lg', 'b.lg', 'c.lg', 'NormalStructuredLG.lg', 'root.lg', 'subDialog.lg', 'test.lg']), ); }); @@ -67,7 +67,7 @@ describe('LGLanguageGenerator', function () { 'NormalStructuredLG.lg', 'root.lg', 'subDialog.lg', - ]) + ]), ); }); @@ -85,7 +85,7 @@ describe('LGLanguageGenerator', function () { 'NormalStructuredLG.lg', 'root.lg', 'subDialog.lg', - ]) + ]), ); }); }); diff --git a/libraries/botbuilder-dialogs-adaptive/tests/activityFactory.test.js b/libraries/botbuilder-dialogs-adaptive/tests/activityFactory.test.js index 141f395976..e4aa75cb4a 100644 --- a/libraries/botbuilder-dialogs-adaptive/tests/activityFactory.test.js +++ b/libraries/botbuilder-dialogs-adaptive/tests/activityFactory.test.js @@ -38,7 +38,7 @@ describe('ActivityFactoryTest', function () { assert.strictEqual(result.attachments, undefined); assert.strictEqual( result.text.replace(/\r\n/g, '\n').replace(/\n/g, '').replace(/\s+/g, ''), - '{"lgType":"Acti","key":"value"}' + '{"lgType":"Acti","key":"value"}', ); }); @@ -567,7 +567,7 @@ function assertAdaptiveCardActivity(activity) { assert.strictEqual( activity.attachments[0].contentType, 'application/vnd.microsoft.card.adaptive', - 'attachment type should be adaptivecard' + 'attachment type should be adaptivecard', ); assert.strictEqual(activity.attachments[0].content.body[0].text, 'test', 'text of first body should have value'); } @@ -603,7 +603,7 @@ function assertAnimationCardActivity(activity) { assert.strictEqual(card.autostart, true); assert.strictEqual( card.image.url, - 'https://docs.microsoft.com/en-us/bot-framework/media/how-it-works/architecture-resize.png' + 'https://docs.microsoft.com/en-us/bot-framework/media/how-it-works/architecture-resize.png', ); assert.strictEqual(card.media[0].url, 'http://oi42.tinypic.com/1rchlx.jpg'); } @@ -627,7 +627,7 @@ function assertReceiptCardActivity(activity) { assert.strictEqual(button.value, 'https://azure.microsoft.com/en-us/pricing/'); assert.strictEqual( button.image, - 'https://account.windowsazure.com/content/6.10.1.38-.8225.160809-1618/aux-pre/images/offer-icon-freetrial.png' + 'https://account.windowsazure.com/content/6.10.1.38-.8225.160809-1618/aux-pre/images/offer-icon-freetrial.png', ); const facts = card.facts; @@ -642,14 +642,14 @@ function assertReceiptCardActivity(activity) { assert.strictEqual(items[0].title, 'Data Transfer'); assert.strictEqual( items[0].image.url, - 'https://github.com/amido/azure-vector-icons/raw/master/renders/traffic-manager.png' + 'https://github.com/amido/azure-vector-icons/raw/master/renders/traffic-manager.png', ); assert.strictEqual(items[0].price, '$ 38.45'); assert.strictEqual(items[0].quantity, '368'); assert.strictEqual(items[1].title, 'App Service'); assert.strictEqual( items[1].image.url, - 'https://github.com/amido/azure-vector-icons/raw/master/renders/cloud-service.png' + 'https://github.com/amido/azure-vector-icons/raw/master/renders/cloud-service.png', ); assert.strictEqual(items[1].price, '$ 45.00'); assert.strictEqual(items[1].quantity, '720'); diff --git a/libraries/botbuilder-dialogs-adaptive/tests/beginSkill.test.js b/libraries/botbuilder-dialogs-adaptive/tests/beginSkill.test.js index 009a93efa5..f35b5e2605 100644 --- a/libraries/botbuilder-dialogs-adaptive/tests/beginSkill.test.js +++ b/libraries/botbuilder-dialogs-adaptive/tests/beginSkill.test.js @@ -174,7 +174,7 @@ function createSkillClientAndStub(captureAction, returnStatusCode = StatusCodes. if (captureAction && typeof captureAction !== 'function') { throw new TypeError( - `Failed test arrangement - createSkillClientAndStub() received ${typeof captureAction} instead of undefined or a function.` + `Failed test arrangement - createSkillClientAndStub() received ${typeof captureAction} instead of undefined or a function.`, ); } diff --git a/libraries/botbuilder-dialogs-adaptive/tests/choiceSet.test.ts b/libraries/botbuilder-dialogs-adaptive/tests/choiceSet.test.ts index 340f95bec2..3914b47153 100644 --- a/libraries/botbuilder-dialogs-adaptive/tests/choiceSet.test.ts +++ b/libraries/botbuilder-dialogs-adaptive/tests/choiceSet.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/explicit-function-return-type */ import 'mocha'; import { ObjectExpression } from 'adaptive-expressions'; import * as assert from 'assert'; @@ -30,7 +29,7 @@ describe('ChoiceSetTests', function () { it('TestValue', async function () { const state = {}; const ep = new ObjectExpression( - new ChoiceSet([{ value: 'test1' }, { value: 'test2' }, { value: 'test3' }]) + new ChoiceSet([{ value: 'test1' }, { value: 'test2' }, { value: 'test3' }]), ); const { value } = ep.tryGetValue(state); assertValues(value); diff --git a/libraries/botbuilder-dialogs-adaptive/tests/conditionals.test.js b/libraries/botbuilder-dialogs-adaptive/tests/conditionals.test.js index 896cc57dd9..724565e143 100644 --- a/libraries/botbuilder-dialogs-adaptive/tests/conditionals.test.js +++ b/libraries/botbuilder-dialogs-adaptive/tests/conditionals.test.js @@ -79,105 +79,105 @@ describe('ConditionalsTests', function () { it('OnCondition with condition', function () { assertExpression( new OnActivity('event', [], 'turn.test == 1'), - "((turn.activity.type == 'event') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))" + "((turn.activity.type == 'event') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))", ); assertExpression( new OnAssignEntity('property', 'entity', 'operation', [], 'turn.test == 1'), - "(((turn.dialogEvent.name == 'assignEntity') && (turn.test == 1)) && (turn.dialogEvent.value.property == 'property') && (turn.dialogEvent.value.value.name == 'entity') && (turn.dialogEvent.value.operation == 'operation'))" + "(((turn.dialogEvent.name == 'assignEntity') && (turn.test == 1)) && (turn.dialogEvent.value.property == 'property') && (turn.dialogEvent.value.value.name == 'entity') && (turn.dialogEvent.value.operation == 'operation'))", ); assertExpression( new OnBeginDialog([], 'turn.test == 1'), - "((turn.dialogEvent.name == 'beginDialog') && (turn.test == 1))" + "((turn.dialogEvent.name == 'beginDialog') && (turn.test == 1))", ); assertExpression( new OnCancelDialog([], 'turn.test == 1'), - "((turn.dialogEvent.name == 'cancelDialog') && (turn.test == 1))" + "((turn.dialogEvent.name == 'cancelDialog') && (turn.test == 1))", ); assertExpression( new OnChooseEntity('property', 'entity', 'Add()', [], 'turn.test == 1'), - "(((turn.dialogEvent.name == 'chooseEntity') && (turn.test == 1)) && (turn.dialogEvent.value.property == 'property') && (turn.dialogEvent.value.value.name == 'entity') && (turn.dialogEvent.value.operation == 'Add()'))" + "(((turn.dialogEvent.name == 'chooseEntity') && (turn.test == 1)) && (turn.dialogEvent.value.property == 'property') && (turn.dialogEvent.value.value.name == 'entity') && (turn.dialogEvent.value.operation == 'Add()'))", ); assertExpression( new OnCommandActivity([], 'turn.test == 1'), - `((turn.activity.type == '${ActivityTypes.Command}') && ((turn.dialogEvent.name == '${AdaptiveEvents.activityReceived}') && (turn.test == 1)))` + `((turn.activity.type == '${ActivityTypes.Command}') && ((turn.dialogEvent.name == '${AdaptiveEvents.activityReceived}') && (turn.test == 1)))`, ); assertExpression( new OnCommandResultActivity([], 'turn.test == 1'), - `((turn.activity.type == '${ActivityTypes.CommandResult}') && ((turn.dialogEvent.name == '${AdaptiveEvents.activityReceived}') && (turn.test == 1)))` + `((turn.activity.type == '${ActivityTypes.CommandResult}') && ((turn.dialogEvent.name == '${AdaptiveEvents.activityReceived}') && (turn.test == 1)))`, ); assertExpression(new OnCondition('turn.test == 1'), '(turn.test == 1)'); assertExpression( new OnContinueConversation([], 'turn.test == 1'), - "((turn.activity.name == 'ContinueConversation') && ((turn.activity.type == 'event') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1))))" + "((turn.activity.name == 'ContinueConversation') && ((turn.activity.type == 'event') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1))))", ); assertExpression( new OnConversationUpdateActivity([], 'turn.test == 1'), - "((turn.activity.type == 'conversationUpdate') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))" + "((turn.activity.type == 'conversationUpdate') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))", ); assertExpression( new OnDialogEvent('DialogEvent', [], 'turn.test == 1'), - "((turn.dialogEvent.name == 'DialogEvent') && (turn.test == 1))" + "((turn.dialogEvent.name == 'DialogEvent') && (turn.test == 1))", ); assertExpression( new OnEndOfActions([], 'turn.test == 1'), - "((turn.dialogEvent.name == 'endOfActions') && (turn.test == 1))" + "((turn.dialogEvent.name == 'endOfActions') && (turn.test == 1))", ); assertExpression( new OnEndOfConversationActivity([], 'turn.test == 1'), - "((turn.activity.type == 'endOfConversation') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))" + "((turn.activity.type == 'endOfConversation') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))", ); assertExpression(new OnError([], 'turn.test == 1'), "((turn.dialogEvent.name == 'error') && (turn.test == 1))"); assertExpression( new OnEventActivity([], 'turn.test == 1'), - "((turn.activity.type == 'event') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))" + "((turn.activity.type == 'event') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))", ); assertExpression( new OnHandoffActivity([], 'turn.test == 1'), - "((turn.activity.type == 'handoff') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))" + "((turn.activity.type == 'handoff') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))", ); assertExpression( new OnInstallationUpdateActivity([], 'turn.test == 1'), - "((turn.activity.type == 'installationUpdate') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))" + "((turn.activity.type == 'installationUpdate') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))", ); assertExpression( new OnIntent('Intent', ['@foo', '@@bar', 'turn.recognized.entities.blat', 'gronk'], [], 'turn.test == 1'), - "(((turn.recognized.intent == 'Intent') && (exists(@foo) && exists(@@bar) && exists(turn.recognized.entities.blat) && exists(@gronk))) && ((turn.dialogEvent.name == 'recognizedIntent') && (turn.test == 1)))" + "(((turn.recognized.intent == 'Intent') && (exists(@foo) && exists(@@bar) && exists(turn.recognized.entities.blat) && exists(@gronk))) && ((turn.dialogEvent.name == 'recognizedIntent') && (turn.test == 1)))", ); assertExpression( new OnInvokeActivity([], 'turn.test == 1'), - "((turn.activity.type == 'invoke') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))" + "((turn.activity.type == 'invoke') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))", ); assertExpression( new OnMessageActivity([], 'turn.test == 1'), - "((turn.activity.type == 'message') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))" + "((turn.activity.type == 'message') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))", ); assertExpression( new OnMessageDeleteActivity([], 'turn.test == 1'), - "((turn.activity.type == 'messageDelete') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))" + "((turn.activity.type == 'messageDelete') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))", ); assertExpression( new OnMessageReactionActivity([], 'turn.test == 1'), - "((turn.activity.type == 'messageReaction') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))" + "((turn.activity.type == 'messageReaction') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))", ); assertExpression( new OnMessageUpdateActivity([], 'turn.test == 1'), - "((turn.activity.type == 'messageUpdate') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))" + "((turn.activity.type == 'messageUpdate') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))", ); assertExpression( new OnQnAMatch([], 'turn.test == 1'), - "((turn.recognized.intent == 'QnAMatch') && ((turn.dialogEvent.name == 'recognizedIntent') && (turn.test == 1)))" + "((turn.recognized.intent == 'QnAMatch') && ((turn.dialogEvent.name == 'recognizedIntent') && (turn.test == 1)))", ); assertExpression( new OnRepromptDialog([], 'turn.test == 1'), - "((turn.dialogEvent.name == 'repromptDialog') && (turn.test == 1))" + "((turn.dialogEvent.name == 'repromptDialog') && (turn.test == 1))", ); assertExpression( new OnTypingActivity([], 'turn.test == 1'), - "((turn.activity.type == 'typing') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))" + "((turn.activity.type == 'typing') && ((turn.dialogEvent.name == 'activityReceived') && (turn.test == 1)))", ); assertExpression( new OnUnknownIntent([], 'turn.test == 1'), - "((turn.dialogEvent.name == 'unknownIntent') && (turn.test == 1))" + "((turn.dialogEvent.name == 'unknownIntent') && (turn.test == 1))", ); }); }); diff --git a/libraries/botbuilder-dialogs-adaptive/tests/conversationAction.test.js b/libraries/botbuilder-dialogs-adaptive/tests/conversationAction.test.js index c21090fc52..abd82fb360 100644 --- a/libraries/botbuilder-dialogs-adaptive/tests/conversationAction.test.js +++ b/libraries/botbuilder-dialogs-adaptive/tests/conversationAction.test.js @@ -69,7 +69,7 @@ describe('ConversationAction', function () { new ContinueConversationLater().configure({ date: '=addSeconds(utcNow(), 2)', value: 'foo', - }) + }), ); dm.initialTurnState.set(DialogTurnStateConstants.queueStorage, queueStorage); @@ -118,7 +118,7 @@ describe('ConversationAction', function () { ], }), ], - }) + }), ); dm.initialTurnState.set(DialogTurnStateConstants.queueStorage, queueStorage); const adapter = new TestAdapter((turnContext) => { @@ -176,7 +176,7 @@ describe('ConversationAction', function () { ], }), ], - }) + }), ); dm.initialTurnState.set(DialogTurnStateConstants.queueStorage, queueStorage); const adapter = new TestAdapter((turnContext) => { diff --git a/libraries/botbuilder-dialogs-adaptive/tests/entityRecognizer.test.js b/libraries/botbuilder-dialogs-adaptive/tests/entityRecognizer.test.js index f89a4c1935..aa09944b71 100644 --- a/libraries/botbuilder-dialogs-adaptive/tests/entityRecognizer.test.js +++ b/libraries/botbuilder-dialogs-adaptive/tests/entityRecognizer.test.js @@ -40,7 +40,7 @@ const getDialogContext = (testName, text, locale = 'en-us') => { from: bot, locale, }), - {} + {}, ); }; @@ -69,7 +69,7 @@ describe('EntityRecognizer Tests', function () { new RegexEntityRecognizer().configure({ name: 'size', pattern: '(?i)(small|medium|large)', - }) + }), ); it('test age', async function () { diff --git a/libraries/botbuilder-dialogs-adaptive/tests/entityRecognizerRecognizer.test.js b/libraries/botbuilder-dialogs-adaptive/tests/entityRecognizerRecognizer.test.js index b7f9da3ef0..d427d10351 100644 --- a/libraries/botbuilder-dialogs-adaptive/tests/entityRecognizerRecognizer.test.js +++ b/libraries/botbuilder-dialogs-adaptive/tests/entityRecognizerRecognizer.test.js @@ -44,7 +44,7 @@ const getDialogContext = (testName, text, locale = 'en-us') => { from: bot, locale, }), - {} + {}, ); }; diff --git a/libraries/botbuilder-dialogs-adaptive/tests/expressionProperty.test.ts b/libraries/botbuilder-dialogs-adaptive/tests/expressionProperty.test.ts index fea3edc696..9182bc9784 100644 --- a/libraries/botbuilder-dialogs-adaptive/tests/expressionProperty.test.ts +++ b/libraries/botbuilder-dialogs-adaptive/tests/expressionProperty.test.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/explicit-function-return-type */ import * as assert from 'assert'; import { DialogExpression, AdaptiveDialog } from '../'; diff --git a/libraries/botbuilder-dialogs-adaptive/tests/languageGeneratorConverter.test.js b/libraries/botbuilder-dialogs-adaptive/tests/languageGeneratorConverter.test.js index aff5bbb01e..562496311c 100644 --- a/libraries/botbuilder-dialogs-adaptive/tests/languageGeneratorConverter.test.js +++ b/libraries/botbuilder-dialogs-adaptive/tests/languageGeneratorConverter.test.js @@ -8,7 +8,7 @@ describe('LanguageGeneratorConverter', function () { const newGenerator = converter.convert(''); ok( newGenerator instanceof ResourceMultiLanguageGenerator, - 'expected newGenerator to be instance of ResourceMultiLanguageGenerator' + 'expected newGenerator to be instance of ResourceMultiLanguageGenerator', ); }); diff --git a/libraries/botbuilder-dialogs-adaptive/tests/memory_memoryScopes.test.js b/libraries/botbuilder-dialogs-adaptive/tests/memory_memoryScopes.test.js index aad46de13c..a71be14d2e 100644 --- a/libraries/botbuilder-dialogs-adaptive/tests/memory_memoryScopes.test.js +++ b/libraries/botbuilder-dialogs-adaptive/tests/memory_memoryScopes.test.js @@ -28,7 +28,7 @@ describe('Memory - Memory Scopes', function () { new SendActivity("${contains(dialogcontext.stack, 'foo')}"), new SendActivity("${contains(dialogcontext.stack, 'adaptiveDialog')}"), new SendActivity("${contains(dialogcontext.stack, 'adaptiveDialog2')}"), - ]) + ]), ); const storage = new MemoryStorage(); @@ -67,15 +67,15 @@ describe('Memory - Memory Scopes', function () { id: 'askForName', }), new SendActivity('I have ${user.name}'), - ]) + ]), ); root.triggers.push( new OnIntent( 'why', [], [new SendActivity('I need your name to complete the sample')], - "contains(dialogcontext.stack, 'askForName')" - ) + "contains(dialogcontext.stack, 'askForName')", + ), ); root.triggers.push(new OnIntent('why', [], [new SendActivity('why what?')])); diff --git a/libraries/botbuilder-dialogs-adaptive/tests/regexRecognizer.test.js b/libraries/botbuilder-dialogs-adaptive/tests/regexRecognizer.test.js index f7ac69a9e0..23fc315a08 100644 --- a/libraries/botbuilder-dialogs-adaptive/tests/regexRecognizer.test.js +++ b/libraries/botbuilder-dialogs-adaptive/tests/regexRecognizer.test.js @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/no-var-requires */ const assert = require('assert'); const { Recognizer } = require('botbuilder-dialogs'); const { @@ -59,7 +58,7 @@ describe('RegexRecognizer Tests', function () { new UrlEntityRecognizer(), new RegexEntityRecognizer('color', '(red|green|blue|purple|orange|violet|white|black)'), new RegexEntityRecognizer('backgroundColor', '(back|background) {color}'), - new RegexEntityRecognizer('foregroundColor', '(foreground|front) {color}') + new RegexEntityRecognizer('foregroundColor', '(foreground|front) {color}'), ), }); @@ -177,7 +176,7 @@ describe('RegexRecognizer Tests', function () { new OrdinalEntityRecognizer(), new RegexEntityRecognizer('color', '(red|green|blue|purple|orange|violet|white|black)'), new RegexEntityRecognizer('backgroundColor', '(back|background) {color}'), - new RegexEntityRecognizer('foregroundColor', '(foreground|front) {color}') + new RegexEntityRecognizer('foregroundColor', '(foreground|front) {color}'), ), }); const trackEventSpy = spyOnTelemetryClientTrackEvent(recognizerWithDefaultLogPii); @@ -263,7 +262,7 @@ describe('RegexRecognizer Tests', function () { it('recognize dimension', async function () { const dc = createContext(''); const activity = createMessageActivity( - 'The six-mile trip to my airport hotel that had taken 20 minutes earlier in the day took more than three hours.' + 'The six-mile trip to my airport hotel that had taken 20 minutes earlier in the day took more than three hours.', ); const result = await recognizer.recognize(dc, activity); const entities = result.entities; @@ -450,7 +449,7 @@ describe('RegexRecognizer Tests', function () { }; const properties = recognizer.fillRecognizerResultTelemetryProperties( recognizerResultSample, - telemetryProperties + telemetryProperties, ); assert('Text' in properties); assert.strictEqual(properties['Text'], recognizerResultSample['text']); diff --git a/libraries/botbuilder-dialogs-adaptive/tests/telemetryUtils.js b/libraries/botbuilder-dialogs-adaptive/tests/telemetryUtils.js index ce85187f81..61e180cc82 100644 --- a/libraries/botbuilder-dialogs-adaptive/tests/telemetryUtils.js +++ b/libraries/botbuilder-dialogs-adaptive/tests/telemetryUtils.js @@ -9,7 +9,7 @@ const { NullTelemetryClient } = require('botbuilder'); function createTelemetryClientAndStub(captureTelemetryAction) { if (captureTelemetryAction && typeof captureTelemetryAction !== 'function') { throw new TypeError( - `Failed test arrangement - createtelemetryClientAndStub() received ${typeof captureTelemetryAction} instead of undefined or a function.` + `Failed test arrangement - createtelemetryClientAndStub() received ${typeof captureTelemetryAction} instead of undefined or a function.`, ); } From 808f392e910eb3c025a1a3e799703797215ea1e5 Mon Sep 17 00:00:00 2001 From: Joel Mut <62260472+sw-joelmut@users.noreply.github.com> Date: Mon, 6 Jan 2025 12:04:21 -0300 Subject: [PATCH 10/22] Fix ESLint in botbuilder-azure (#4828) --- libraries/botbuilder-azure/eslint.config.cjs | 10 - libraries/botbuilder-azure/package.json | 3 +- .../src/azureBlobTranscriptStore.ts | 8 +- libraries/botbuilder-azure/src/blobStorage.ts | 12 +- .../botbuilder-azure/src/cosmosDbKeyEscape.ts | 6 +- .../src/cosmosDbPartitionedStorage.ts | 163 +++--- .../tests/azureBlobTranscriptStore.test.js | 6 +- .../tests/blobStorage.test.js | 178 +++--- .../tests/cosmosDbKeyEscape.test.js | 6 +- .../tests/cosmosDbPartitionedStorage.test.js | 506 +++++++++--------- 10 files changed, 448 insertions(+), 450 deletions(-) delete mode 100644 libraries/botbuilder-azure/eslint.config.cjs diff --git a/libraries/botbuilder-azure/eslint.config.cjs b/libraries/botbuilder-azure/eslint.config.cjs deleted file mode 100644 index 63647b52cc..0000000000 --- a/libraries/botbuilder-azure/eslint.config.cjs +++ /dev/null @@ -1,10 +0,0 @@ -const onlyWarn = require("eslint-plugin-only-warn"); -const sharedConfig = require("../../eslint.config.cjs") - -module.exports = [ - ...sharedConfig, - { - plugins: { - "only-warn": onlyWarn, - }, - }]; diff --git a/libraries/botbuilder-azure/package.json b/libraries/botbuilder-azure/package.json index 6cb5aec105..57cb715a4b 100644 --- a/libraries/botbuilder-azure/package.json +++ b/libraries/botbuilder-azure/package.json @@ -34,7 +34,6 @@ "bcryptjs": "^2.4.3", "botbuilder": "4.1.6", "botbuilder-stdlib": "4.1.6", - "eslint-plugin-only-warn": "^1.1.0", "lodash": "^4.17.20", "p-map": "^4.0.0" }, @@ -49,7 +48,7 @@ "build:rollup": "yarn clean && yarn build && api-extractor run --verbose --local", "clean": "rimraf _ts3.4 lib tsconfig.tsbuildinfo", "depcheck": "depcheck --config ../../.depcheckrc", - "lint": "eslint .", + "lint": "eslint . --config ../../eslint.config.cjs", "postbuild": "downlevel-dts lib _ts3.4/lib --checksum", "test": "yarn build && nyc mocha tests/", "test:compat": "api-extractor run --verbose" diff --git a/libraries/botbuilder-azure/src/azureBlobTranscriptStore.ts b/libraries/botbuilder-azure/src/azureBlobTranscriptStore.ts index 5b4ae52097..c6fb1879ef 100644 --- a/libraries/botbuilder-azure/src/azureBlobTranscriptStore.ts +++ b/libraries/botbuilder-azure/src/azureBlobTranscriptStore.ts @@ -84,7 +84,7 @@ export class AzureBlobTranscriptStore implements TranscriptStore { this.containerClient = new ContainerClient( this.settings.storageAccountOrConnectionString, this.settings.containerName, - pipeline.options + pipeline.options, ); } @@ -137,7 +137,7 @@ export class AzureBlobTranscriptStore implements TranscriptStore { channelId: string, conversationId: string, continuationToken?: string, - startDate?: Date + startDate?: Date, ): Promise> { if (!channelId) { throw new Error('Missing channelId'); @@ -174,7 +174,7 @@ export class AzureBlobTranscriptStore implements TranscriptStore { const fromIdx = startDate != null ? blobItems.findIndex( - (blobItem) => blobItem?.properties?.createdOn && blobItem?.properties?.createdOn >= startDate + (blobItem) => blobItem?.properties?.createdOn && blobItem?.properties?.createdOn >= startDate, ) : 0; @@ -193,7 +193,7 @@ export class AzureBlobTranscriptStore implements TranscriptStore { const activity = (await StreamConsumers.json(readableStreamBody)) as any; return { ...activity, timestamp: new Date(activity.timestamp) } as Activity; }, - { concurrency: this.concurrency } + { concurrency: this.concurrency }, ); activities.forEach((activity) => { diff --git a/libraries/botbuilder-azure/src/blobStorage.ts b/libraries/botbuilder-azure/src/blobStorage.ts index 31ea7c31e5..5fe692b7cc 100644 --- a/libraries/botbuilder-azure/src/blobStorage.ts +++ b/libraries/botbuilder-azure/src/blobStorage.ts @@ -90,7 +90,7 @@ const ResolvePromisesSerial = (values, promise) => .map((value) => () => promise(value)) .reduce( (promise, func) => promise.then((result) => func().then(Array.prototype.concat.bind(result))), - Promise.resolve([]) + Promise.resolve([]), ); /** @@ -155,7 +155,7 @@ export class BlobStorage implements Storage { this.containerClient = new ContainerClient( this.settings.storageAccountOrConnectionString, this.settings.containerName, - pipeline.options + pipeline.options, ); this.useEmulator = settings.storageAccountOrConnectionString === 'UseDevelopmentStorage=true;'; @@ -194,7 +194,7 @@ export class BlobStorage implements Storage { // If blob does not exist, return an empty DocumentStoreItem. return { document: {} } as DocumentStoreItem; } - }) + }), ) .then((items: DocumentStoreItem[]) => { if (items !== null && items.length > 0) { @@ -257,7 +257,7 @@ export class BlobStorage implements Storage { // depending on the payload's size. The default maximum size for a single blob upload is 128MB. // An 'InvalidBlockList' error is commonly caused due to concurrently uploading an object larger than 128MB in size. const promise: (b: any) => Promise = ( - blob: any + blob: any, ): Promise => { const blockBlobClient = this.containerClient.getBlockBlobClient(blob.id); const uploadBlobResponse = blockBlobClient.upload(blob.data, blob.data.length, blob.options); @@ -301,7 +301,7 @@ export class BlobStorage implements Storage { sanitizedKeys.map(async (key: string) => { const blockBlobClient = this.containerClient.getBlockBlobClient(key); return await blockBlobClient.deleteIfExists(); - }) + }), ); }) .then(() => { @@ -328,7 +328,7 @@ export class BlobStorage implements Storage { // The number of path segments comprising the blob name cannot exceed 254 const validKey: string = segments.reduce( (acc: any, curr: any, index: number) => [acc, curr].join(index < 255 ? '/' : ''), - base + base, ); // Reserved URL characters must be escaped. diff --git a/libraries/botbuilder-azure/src/cosmosDbKeyEscape.ts b/libraries/botbuilder-azure/src/cosmosDbKeyEscape.ts index bd48d50e71..ed2c5f2ff6 100644 --- a/libraries/botbuilder-azure/src/cosmosDbKeyEscape.ts +++ b/libraries/botbuilder-azure/src/cosmosDbKeyEscape.ts @@ -21,7 +21,7 @@ export namespace CosmosDbKeyEscape { return map; }, - new Map() + new Map(), ); /** @@ -43,7 +43,7 @@ export namespace CosmosDbKeyEscape { const keySplitted: string[] = key.split(''); const firstIllegalCharIndex: number = keySplitted.findIndex((c: string): boolean => - illegalKeys.some((i: string) => i === c) + illegalKeys.some((i: string) => i === c), ); // If there are no illegal characters return immediately and avoid any further processing/allocations @@ -54,7 +54,7 @@ export namespace CosmosDbKeyEscape { const sanitizedKey = keySplitted.reduce( (result: string, c: string) => result + (illegalKeyCharacterReplacementMap.has(c) ? illegalKeyCharacterReplacementMap.get(c) : c), - '' + '', ); return truncateKey(`${sanitizedKey}${keySuffix || ''}`, compatibilityMode); diff --git a/libraries/botbuilder-azure/src/cosmosDbPartitionedStorage.ts b/libraries/botbuilder-azure/src/cosmosDbPartitionedStorage.ts index f49cea76fc..b1384130dd 100644 --- a/libraries/botbuilder-azure/src/cosmosDbPartitionedStorage.ts +++ b/libraries/botbuilder-azure/src/cosmosDbPartitionedStorage.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/ban-types */ /** * @module botbuilder-azure */ @@ -13,7 +12,7 @@ import { DoOnce } from './doOnce'; import { Storage, StoreItems } from 'botbuilder'; import { TokenCredential } from '@azure/core-auth'; -// eslint-disable-next-line @typescript-eslint/no-var-requires +// eslint-disable-next-line @typescript-eslint/no-require-imports const pjson: Record<'name' | 'version', string> = require('../package.json'); const _doOnce: DoOnce = new DoOnce(); @@ -173,7 +172,7 @@ export class CosmosDbPartitionedStorage implements Storage { const suffixEscaped = CosmosDbKeyEscape.escapeKey(cosmosDbStorageOptions.keySuffix); if (cosmosDbStorageOptions.keySuffix !== suffixEscaped) { throw new ReferenceError( - `Cannot use invalid Row Key characters: ${cosmosDbStorageOptions.keySuffix} in keySuffix` + `Cannot use invalid Row Key characters: ${cosmosDbStorageOptions.keySuffix} in keySuffix`, ); } } @@ -202,43 +201,41 @@ export class CosmosDbPartitionedStorage implements Storage { const storeItems: StoreItems = {}; await Promise.all( - keys.map( - async (k: string): Promise => { - try { - const escapedKey = CosmosDbKeyEscape.escapeKey( - k, - this.cosmosDbStorageOptions.keySuffix, - this.cosmosDbStorageOptions.compatibilityMode - ); + keys.map(async (k: string): Promise => { + try { + const escapedKey = CosmosDbKeyEscape.escapeKey( + k, + this.cosmosDbStorageOptions.keySuffix, + this.cosmosDbStorageOptions.compatibilityMode, + ); - const readItemResponse = await this.container - .item(escapedKey, this.getPartitionKey(escapedKey)) - .read(); - const documentStoreItem = readItemResponse.resource; - if (documentStoreItem) { - storeItems[documentStoreItem.realId] = documentStoreItem.document; - storeItems[documentStoreItem.realId].eTag = documentStoreItem._etag; - } - } catch (err) { - // When an item is not found a CosmosException is thrown, but we want to - // return an empty collection so in this instance we catch and do not rethrow. - // Throw for any other exception. - if (err.code === 404) { - // no-op - } - // Throw unique error for 400s - else if (err.code === 400) { - this.throwInformativeError( - `Error reading from container. You might be attempting to read from a non-partitioned + const readItemResponse = await this.container + .item(escapedKey, this.getPartitionKey(escapedKey)) + .read(); + const documentStoreItem = readItemResponse.resource; + if (documentStoreItem) { + storeItems[documentStoreItem.realId] = documentStoreItem.document; + storeItems[documentStoreItem.realId].eTag = documentStoreItem._etag; + } + } catch (err) { + // When an item is not found a CosmosException is thrown, but we want to + // return an empty collection so in this instance we catch and do not rethrow. + // Throw for any other exception. + if (err.code === 404) { + // no-op + } + // Throw unique error for 400s + else if (err.code === 400) { + this.throwInformativeError( + `Error reading from container. You might be attempting to read from a non-partitioned container or a container that does not use '/id' as the partitionKeyPath`, - err - ); - } else { - this.throwInformativeError('Error reading from container', err); - } + err, + ); + } else { + this.throwInformativeError('Error reading from container', err); } } - ) + }), ); return storeItems; @@ -259,38 +256,36 @@ export class CosmosDbPartitionedStorage implements Storage { await this.initialize(); await Promise.all( - Object.entries(changes).map( - async ([key, { eTag, ...change }]): Promise => { - const document = new DocumentStoreItem({ - id: CosmosDbKeyEscape.escapeKey( - key, - this.cosmosDbStorageOptions.keySuffix, - this.cosmosDbStorageOptions.compatibilityMode - ), - realId: key, - document: change, - }); + Object.entries(changes).map(async ([key, { eTag, ...change }]): Promise => { + const document = new DocumentStoreItem({ + id: CosmosDbKeyEscape.escapeKey( + key, + this.cosmosDbStorageOptions.keySuffix, + this.cosmosDbStorageOptions.compatibilityMode, + ), + realId: key, + document: change, + }); - const accessCondition = - eTag !== '*' && eTag != null && eTag.length > 0 - ? { accessCondition: { type: 'IfMatch', condition: eTag } } - : undefined; - - try { - await this.container.items.upsert(document, accessCondition); - } catch (err) { - // This check could potentially be performed before even attempting to upsert the item - // so that a request wouldn't be made to Cosmos if it's expected to fail. - // However, performing the check here ensures that this custom exception is only thrown - // if Cosmos returns an error first. - // This way, the nesting limit is not imposed on the Bot Framework side - // and no exception will be thrown if the limit is eventually changed on the Cosmos side. - this.checkForNestingError(change, err); - - this.throwInformativeError('Error upserting document', err); - } + const accessCondition = + eTag !== '*' && eTag != null && eTag.length > 0 + ? { accessCondition: { type: 'IfMatch', condition: eTag } } + : undefined; + + try { + await this.container.items.upsert(document, accessCondition); + } catch (err) { + // This check could potentially be performed before even attempting to upsert the item + // so that a request wouldn't be made to Cosmos if it's expected to fail. + // However, performing the check here ensures that this custom exception is only thrown + // if Cosmos returns an error first. + // This way, the nesting limit is not imposed on the Bot Framework side + // and no exception will be thrown if the limit is eventually changed on the Cosmos side. + this.checkForNestingError(change, err); + + this.throwInformativeError('Error upserting document', err); } - ) + }), ); } @@ -303,25 +298,23 @@ export class CosmosDbPartitionedStorage implements Storage { await this.initialize(); await Promise.all( - keys.map( - async (k: string): Promise => { - const escapedKey = CosmosDbKeyEscape.escapeKey( - k, - this.cosmosDbStorageOptions.keySuffix, - this.cosmosDbStorageOptions.compatibilityMode - ); - try { - await this.container.item(escapedKey, this.getPartitionKey(escapedKey)).delete(); - } catch (err) { - // If trying to delete a document that doesn't exist, do nothing. Otherwise, throw - if (err.code === 404) { - // no-op - } else { - this.throwInformativeError('Unable to delete document', err); - } + keys.map(async (k: string): Promise => { + const escapedKey = CosmosDbKeyEscape.escapeKey( + k, + this.cosmosDbStorageOptions.keySuffix, + this.cosmosDbStorageOptions.compatibilityMode, + ); + try { + await this.container.item(escapedKey, this.getPartitionKey(escapedKey)).delete(); + } catch (err) { + // If trying to delete a document that doesn't exist, do nothing. Otherwise, throw + if (err.code === 404) { + // no-op + } else { + this.throwInformativeError('Unable to delete document', err); } } - ) + }), ); } @@ -350,7 +343,7 @@ export class CosmosDbPartitionedStorage implements Storage { const dbAndContainerKey = `${this.cosmosDbStorageOptions.databaseId}-${this.cosmosDbStorageOptions.containerId}`; this.container = await _doOnce.waitFor( dbAndContainerKey, - async (): Promise => await this.getOrCreateContainer() + async (): Promise => await this.getOrCreateContainer(), ); } } @@ -372,7 +365,7 @@ export class CosmosDbPartitionedStorage implements Storage { } else if (paths.indexOf(DocumentStoreItem.partitionKeyPath) === -1) { // We are not supporting custom Partition Key Paths. new Error( - `Custom Partition Key Paths are not supported. ${this.cosmosDbStorageOptions.containerId} has a custom Partition Key Path of ${paths[0]}.` + `Custom Partition Key Paths are not supported. ${this.cosmosDbStorageOptions.containerId} has a custom Partition Key Path of ${paths[0]}.`, ); } } else { diff --git a/libraries/botbuilder-azure/tests/azureBlobTranscriptStore.test.js b/libraries/botbuilder-azure/tests/azureBlobTranscriptStore.test.js index bf39796b11..ab6ef68632 100644 --- a/libraries/botbuilder-azure/tests/azureBlobTranscriptStore.test.js +++ b/libraries/botbuilder-azure/tests/azureBlobTranscriptStore.test.js @@ -47,6 +47,7 @@ describe('The AzureBlobTranscriptStore', function () { let mockBlobClient; let mockContainer; let pagedAsyncIterableIterator; + beforeEach(function () { sandbox = sinon.createSandbox(); @@ -110,6 +111,7 @@ describe('The AzureBlobTranscriptStore', function () { storage = new AzureBlobTranscriptStore(getSettings()); storage.containerClient = mockContainer; }); + after(function () { // reset mock sandbox.restore(); @@ -127,14 +129,14 @@ describe('The AzureBlobTranscriptStore', function () { it('it is constructed with an invalid container name', function () { assert.throws( () => new AzureBlobTranscriptStore({ containerName: '$%^$@' }), - new Error('Invalid container name.') + new Error('Invalid container name.'), ); }); it('it is constructed without the storageAccountOrConnectionString in the settings', function () { assert.throws( () => new AzureBlobTranscriptStore({ ...getSettings(), storageAccountOrConnectionString: '' }), - new Error('The storageAccountOrConnectionString is required.') + new Error('The storageAccountOrConnectionString is required.'), ); }); diff --git a/libraries/botbuilder-azure/tests/blobStorage.test.js b/libraries/botbuilder-azure/tests/blobStorage.test.js index c642ec7f98..698f929703 100644 --- a/libraries/botbuilder-azure/tests/blobStorage.test.js +++ b/libraries/botbuilder-azure/tests/blobStorage.test.js @@ -32,7 +32,7 @@ const reset = async () => { const checkEmulator = () => { if (!fs.existsSync(emulatorPath)) { console.warn( - 'These tests require Azure Storage Emulator! go to https://docs.microsoft.com/en-us/azure/storage/common/storage-use-emulator#get-the-storage-emulator to download and install.' + 'These tests require Azure Storage Emulator! go to https://docs.microsoft.com/en-us/azure/storage/common/storage-use-emulator#get-the-storage-emulator to download and install.', ); } return true; @@ -40,115 +40,123 @@ const checkEmulator = () => { const storage = new BlobStorage(getSettings()); -describe('BlobStorage - Constructor', function () { - before('cleanup', reset); - after('cleanup', reset); - - it('missing settings should throw error', function () { - assert.throws(() => new BlobStorage(), Error, 'constructor should have thrown error about missing settings.'); +describe('BlobStorage', function () { + describe('Constructor', function () { + before('cleanup', reset); + + after('cleanup', reset); + + it('missing settings should throw error', function () { + assert.throws( + () => new BlobStorage(), + Error, + 'constructor should have thrown error about missing settings.', + ); + }); + + it('Invalid container name should throw error', function () { + assert.throws( + () => new BlobStorage(getSettings('invalid--name')), + Error, + 'constructor should have thrown error about invalid container name.', + ); + }); }); - it('Invalid container name should throw error', function () { - assert.throws( - () => new BlobStorage(getSettings('invalid--name')), - Error, - 'constructor should have thrown error about invalid container name.' + describe('BlobStorage - Base Storage Tests', function () { + before( + 'cleanup', + flow(() => reset, checkEmulator), ); - }); -}); -describe('BlobStorage - Base Storage Tests', function () { - before( - 'cleanup', - flow(() => reset, checkEmulator) - ); - after('cleanup', reset); + after('cleanup', reset); - it('return empty object when reading unknown key', async function () { - const { nockDone } = await usingNock(this.test, mode); - const testRan = await StorageBaseTests.returnEmptyObjectWhenReadingUnknownKey(storage); + it('return empty object when reading unknown key', async function () { + const { nockDone } = await usingNock(this.test, mode); + const testRan = await StorageBaseTests.returnEmptyObjectWhenReadingUnknownKey(storage); - assert.strictEqual(testRan, true); - nockDone(); - }); + assert.strictEqual(testRan, true); + nockDone(); + }); - it('throws when reading null keys', async function () { - const { nockDone } = await usingNock(this.test, mode); - const testRan = await StorageBaseTests.handleNullKeysWhenReading(storage); + it('throws when reading null keys', async function () { + const { nockDone } = await usingNock(this.test, mode); + const testRan = await StorageBaseTests.handleNullKeysWhenReading(storage); - assert.strictEqual(testRan, true); - nockDone(); - }); + assert.strictEqual(testRan, true); + nockDone(); + }); - it('throws when writing null keys', async function () { - const { nockDone } = await usingNock(this.test, mode); - const testRan = await StorageBaseTests.handleNullKeysWhenWriting(storage); + it('throws when writing null keys', async function () { + const { nockDone } = await usingNock(this.test, mode); + const testRan = await StorageBaseTests.handleNullKeysWhenWriting(storage); - assert.strictEqual(testRan, true); - nockDone(); - }); + assert.strictEqual(testRan, true); + nockDone(); + }); - it('does not throw when writing no items', async function () { - const { nockDone } = await usingNock(this.test, mode); - const testRan = await StorageBaseTests.doesNotThrowWhenWritingNoItems(storage); + it('does not throw when writing no items', async function () { + const { nockDone } = await usingNock(this.test, mode); + const testRan = await StorageBaseTests.doesNotThrowWhenWritingNoItems(storage); - assert.strictEqual(testRan, true); - nockDone(); - }); + assert.strictEqual(testRan, true); + nockDone(); + }); - it('create an object', async function () { - const { nockDone } = await usingNock(this.test, mode); - const testRan = await StorageBaseTests.createObject(storage); + it('create an object', async function () { + const { nockDone } = await usingNock(this.test, mode); + const testRan = await StorageBaseTests.createObject(storage); - assert.strictEqual(testRan, true); - nockDone(); - }); + assert.strictEqual(testRan, true); + nockDone(); + }); - it('handle crazy keys', async function () { - const { nockDone } = await usingNock(this.test, mode); - const testRan = await StorageBaseTests.handleCrazyKeys(storage); + it('handle crazy keys', async function () { + const { nockDone } = await usingNock(this.test, mode); + const testRan = await StorageBaseTests.handleCrazyKeys(storage); - assert.strictEqual(testRan, true); - nockDone(); - }); + assert.strictEqual(testRan, true); + nockDone(); + }); - it('update an object', async function () { - const { nockDone } = await usingNock(this.test, mode); - const testRan = await StorageBaseTests.updateObject(storage); + it('update an object', async function () { + const { nockDone } = await usingNock(this.test, mode); + const testRan = await StorageBaseTests.updateObject(storage); - assert.strictEqual(testRan, true); - nockDone(); - }); + assert.strictEqual(testRan, true); + nockDone(); + }); - it('delete an object', async function () { - const { nockDone } = await usingNock(this.test, mode); - const testRan = await StorageBaseTests.deleteObject(storage); + it('delete an object', async function () { + const { nockDone } = await usingNock(this.test, mode); + const testRan = await StorageBaseTests.deleteObject(storage); - assert.strictEqual(testRan, true); - nockDone(); - }); + assert.strictEqual(testRan, true); + nockDone(); + }); - it('does not throw when deleting an unknown object', async function () { - const { nockDone } = await usingNock(this.test, mode); - const testRan = await StorageBaseTests.deleteUnknownObject(storage); + it('does not throw when deleting an unknown object', async function () { + const { nockDone } = await usingNock(this.test, mode); + const testRan = await StorageBaseTests.deleteUnknownObject(storage); - assert.strictEqual(testRan, true); - nockDone(); - }); + assert.strictEqual(testRan, true); + nockDone(); + }); - it('performs batch operations', async function () { - const { nockDone } = await usingNock(this.test, mode); - const testRan = await StorageBaseTests.performBatchOperations(storage); + it('performs batch operations', async function () { + const { nockDone } = await usingNock(this.test, mode); + const testRan = await StorageBaseTests.performBatchOperations(storage); - assert.strictEqual(testRan, true); - nockDone(); - }); + assert.strictEqual(testRan, true); + nockDone(); + }); - it('proceeds through a waterfall dialog', async function () { - const { nockDone } = await usingNock(this.test, mode); - const testRan = await StorageBaseTests.proceedsThroughWaterfall(storage); + it('proceeds through a waterfall dialog', async function () { + const { nockDone } = await usingNock(this.test, mode); + const testRan = await StorageBaseTests.proceedsThroughWaterfall(storage); - assert.strictEqual(testRan, true); - nockDone(); + assert.strictEqual(testRan, true); + nockDone(); + }); }); }); diff --git a/libraries/botbuilder-azure/tests/cosmosDbKeyEscape.test.js b/libraries/botbuilder-azure/tests/cosmosDbKeyEscape.test.js index 4e27249fe0..09ef69d51d 100644 --- a/libraries/botbuilder-azure/tests/cosmosDbKeyEscape.test.js +++ b/libraries/botbuilder-azure/tests/cosmosDbKeyEscape.test.js @@ -6,7 +6,7 @@ describe('CosmosDbKeyEscape', function () { assert.throws( () => new CosmosDbKeyEscape(), Error, - 'constructor should have thrown error about missing key parameter.' + 'constructor should have thrown error about missing key parameter.', ); }); @@ -14,7 +14,7 @@ describe('CosmosDbKeyEscape', function () { assert.throws( () => new CosmosDbKeyEscape(''), Error, - 'constructor should have thrown error about missing key parameter.' + 'constructor should have thrown error about missing key parameter.', ); }); @@ -22,7 +22,7 @@ describe('CosmosDbKeyEscape', function () { assert.throws( () => new CosmosDbKeyEscape(' '), Error, - 'constructor should have thrown error about missing key parameter.' + 'constructor should have thrown error about missing key parameter.', ); }); diff --git a/libraries/botbuilder-azure/tests/cosmosDbPartitionedStorage.test.js b/libraries/botbuilder-azure/tests/cosmosDbPartitionedStorage.test.js index 92413e9e34..e945c514cc 100644 --- a/libraries/botbuilder-azure/tests/cosmosDbPartitionedStorage.test.js +++ b/libraries/botbuilder-azure/tests/cosmosDbPartitionedStorage.test.js @@ -63,7 +63,7 @@ const checkEmulator = async () => { } if (!canConnectToEmulator) console.warn( - `Unable to connect to Cosmos Emulator at ${emulatorEndpoint}. Running tests against Nock recordings.` + `Unable to connect to Cosmos Emulator at ${emulatorEndpoint}. Running tests against Nock recordings.`, ); } return canConnectToEmulator; @@ -130,339 +130,345 @@ const options = { scope: getSettings().cosmosDbEndpoint, }; -describe('CosmosDbPartitionedStorage - Constructor Tests', function () { - it('throws when provided with null options', function () { - assert.throws( - () => new CosmosDbPartitionedStorage(null), - ReferenceError('CosmosDbPartitionedStorageOptions is required.') - ); - }); +describe('CosmosDbPartitionedStorage', function () { + describe('CosmosDbPartitionedStorage - Constructor Tests', function () { + it('throws when provided with null options', function () { + assert.throws( + () => new CosmosDbPartitionedStorage(null), + ReferenceError('CosmosDbPartitionedStorageOptions is required.'), + ); + }); - it('throws when no endpoint provided', function () { - const noEndpoint = getSettings(this.test); - noEndpoint.cosmosDbEndpoint = null; - assert.throws( - () => new CosmosDbPartitionedStorage(noEndpoint), - ReferenceError('cosmosDbEndpoint for CosmosDB is required.') - ); - }); + it('throws when no endpoint provided', function () { + const noEndpoint = getSettings(this.test); + noEndpoint.cosmosDbEndpoint = null; + assert.throws( + () => new CosmosDbPartitionedStorage(noEndpoint), + ReferenceError('cosmosDbEndpoint for CosmosDB is required.'), + ); + }); - it('throws when no authKey or tokenCredential provided', function () { - const noAuthKey = getSettings(this.test); - noAuthKey.authKey = null; - assert.throws( - () => new CosmosDbPartitionedStorage(noAuthKey), - ReferenceError('authKey or tokenCredential for CosmosDB is required.') - ); - }); + it('throws when no authKey or tokenCredential provided', function () { + const noAuthKey = getSettings(this.test); + noAuthKey.authKey = null; + assert.throws( + () => new CosmosDbPartitionedStorage(noAuthKey), + ReferenceError('authKey or tokenCredential for CosmosDB is required.'), + ); + }); - it('throws when no databaseId provided', function () { - const noDatabaseId = getSettings(this.test); - noDatabaseId.databaseId = null; - assert.throws( - () => new CosmosDbPartitionedStorage(noDatabaseId), - ReferenceError('databaseId is for CosmosDB required.') - ); - }); + it('throws when no databaseId provided', function () { + const noDatabaseId = getSettings(this.test); + noDatabaseId.databaseId = null; + assert.throws( + () => new CosmosDbPartitionedStorage(noDatabaseId), + ReferenceError('databaseId is for CosmosDB required.'), + ); + }); - it('throws when no containerId provided', function () { - const noContainerId = getSettings(this.test); - noContainerId.containerId = null; - assert.throws( - () => new CosmosDbPartitionedStorage(noContainerId), - ReferenceError('containerId for CosmosDB is required.') - ); + it('throws when no containerId provided', function () { + const noContainerId = getSettings(this.test); + noContainerId.containerId = null; + assert.throws( + () => new CosmosDbPartitionedStorage(noContainerId), + ReferenceError('containerId for CosmosDB is required.'), + ); + }); }); -}); -describe('CosmosDbPartitionedStorage - Base Storage Tests', function () { - this.timeout(5000); - before('cleanup', cleanup); // Ensure we start from scratch - beforeEach('prep', prep); - afterEach('cleanup', cleanup); + describe('CosmosDbPartitionedStorage - Base Storage Tests', function () { + this.timeout(5000); - it('passes cosmosClientOptions to CosmosClient', async function () { - const { nockDone } = await usingNock(this.test, mode, options); + before('cleanup', cleanup); + // Ensure we start from scratch + beforeEach('prep', prep); - const settingsWithClientOptions = getSettings(this.test); - settingsWithClientOptions.cosmosClientOptions = { - agent: new https.Agent({ rejectUnauthorized: false }), - connectionPolicy: { requestTimeout: 999 }, - userAgentSuffix: 'test', - }; + afterEach('cleanup', cleanup); - const client = new CosmosDbPartitionedStorage(settingsWithClientOptions); - await client.initialize(); // Force client to go through initialization + it('passes cosmosClientOptions to CosmosClient', async function () { + const { nockDone } = await usingNock(this.test, mode, options); - assert.strictEqual(client.client.clientContext.connectionPolicy.requestTimeout, 999); - assert.strictEqual(client.client.clientContext.cosmosClientOptions.userAgentSuffix, 'test'); + const settingsWithClientOptions = getSettings(this.test); + settingsWithClientOptions.cosmosClientOptions = { + agent: new https.Agent({ rejectUnauthorized: false }), + connectionPolicy: { requestTimeout: 999 }, + userAgentSuffix: 'test', + }; - nockDone(); - }); + const client = new CosmosDbPartitionedStorage(settingsWithClientOptions); + await client.initialize(); // Force client to go through initialization - it('passes cosmosClientOptions with default userAgentSuffix', async function () { - const { nockDone } = await usingNock(this.test, mode, options); + assert.strictEqual(client.client.clientContext.connectionPolicy.requestTimeout, 999); + assert.strictEqual(client.client.clientContext.cosmosClientOptions.userAgentSuffix, 'test'); - const settingsWithClientOptions = getSettings(this.test); - settingsWithClientOptions.cosmosClientOptions = { - agent: new https.Agent({ rejectUnauthorized: false }), - connectionPolicy: { requestTimeout: 999 }, - }; + nockDone(); + }); - const client = new CosmosDbPartitionedStorage(settingsWithClientOptions); - await client.initialize(); // Force client to go through initialization + it('passes cosmosClientOptions with default userAgentSuffix', async function () { + const { nockDone } = await usingNock(this.test, mode, options); - const userAgent = client.container.clientContext.cosmosClientOptions.defaultHeaders['User-Agent'].split(' '); - const length = userAgent.length; + const settingsWithClientOptions = getSettings(this.test); + settingsWithClientOptions.cosmosClientOptions = { + agent: new https.Agent({ rejectUnauthorized: false }), + connectionPolicy: { requestTimeout: 999 }, + }; - assert.strictEqual(client.client.clientContext.connectionPolicy.requestTimeout, 999); - assert.strictEqual(userAgent[length - 1], pjson.version); - assert.strictEqual(userAgent[length - 2], pjson.name); + const client = new CosmosDbPartitionedStorage(settingsWithClientOptions); + await client.initialize(); // Force client to go through initialization - nockDone(); - }); + const userAgent = + client.container.clientContext.cosmosClientOptions.defaultHeaders['User-Agent'].split(' '); + const length = userAgent.length; - it('return empty object when reading unknown key', async function () { - const { nockDone } = await usingNock(this.test, mode, options); - const testRan = await StorageBaseTests.returnEmptyObjectWhenReadingUnknownKey(storage); + assert.strictEqual(client.client.clientContext.connectionPolicy.requestTimeout, 999); + assert.strictEqual(userAgent[length - 1], pjson.version); + assert.strictEqual(userAgent[length - 2], pjson.name); - assert.strictEqual(testRan, true); + nockDone(); + }); - nockDone(); - }); + it('return empty object when reading unknown key', async function () { + const { nockDone } = await usingNock(this.test, mode, options); + const testRan = await StorageBaseTests.returnEmptyObjectWhenReadingUnknownKey(storage); - it('throws when reading null keys', async function () { - const { nockDone } = await usingNock(this.test, mode, options); + assert.strictEqual(testRan, true); - const testRan = await StorageBaseTests.handleNullKeysWhenReading(storage); + nockDone(); + }); - assert.strictEqual(testRan, true); - nockDone(); - }); + it('throws when reading null keys', async function () { + const { nockDone } = await usingNock(this.test, mode, options); - it('throws when writing null keys', async function () { - const { nockDone } = await usingNock(this.test, mode, options); + const testRan = await StorageBaseTests.handleNullKeysWhenReading(storage); - const testRan = await StorageBaseTests.handleNullKeysWhenWriting(storage); + assert.strictEqual(testRan, true); + nockDone(); + }); - assert.strictEqual(testRan, true); - nockDone(); - }); + it('throws when writing null keys', async function () { + const { nockDone } = await usingNock(this.test, mode, options); - it('does not throw when writing no items', async function () { - const { nockDone } = await usingNock(this.test, mode, options); + const testRan = await StorageBaseTests.handleNullKeysWhenWriting(storage); - const testRan = await StorageBaseTests.doesNotThrowWhenWritingNoItems(storage); + assert.strictEqual(testRan, true); + nockDone(); + }); - assert.strictEqual(testRan, true); - nockDone(); - }); + it('does not throw when writing no items', async function () { + const { nockDone } = await usingNock(this.test, mode, options); - it('create an object', async function () { - const { nockDone } = await usingNock(this.test, mode, options); + const testRan = await StorageBaseTests.doesNotThrowWhenWritingNoItems(storage); - const testRan = await StorageBaseTests.createObject(storage); + assert.strictEqual(testRan, true); + nockDone(); + }); - assert.strictEqual(testRan, true); - nockDone(); - }); + it('create an object', async function () { + const { nockDone } = await usingNock(this.test, mode, options); - it('handle crazy keys', async function () { - const { nockDone } = await usingNock(this.test, mode, options); + const testRan = await StorageBaseTests.createObject(storage); - const testRan = await StorageBaseTests.handleCrazyKeys(storage); + assert.strictEqual(testRan, true); + nockDone(); + }); - assert.strictEqual(testRan, true); - nockDone(); - }); + it('handle crazy keys', async function () { + const { nockDone } = await usingNock(this.test, mode, options); - it('update an object', async function () { - const { nockDone } = await usingNock(this.test, mode, options); + const testRan = await StorageBaseTests.handleCrazyKeys(storage); - const testRan = await StorageBaseTests.updateObject(storage); + assert.strictEqual(testRan, true); + nockDone(); + }); - assert.strictEqual(testRan, true); - nockDone(); - }); + it('update an object', async function () { + const { nockDone } = await usingNock(this.test, mode, options); - it('delete an object', async function () { - const { nockDone } = await usingNock(this.test, mode, options); + const testRan = await StorageBaseTests.updateObject(storage); - const testRan = await StorageBaseTests.deleteObject(storage); + assert.strictEqual(testRan, true); + nockDone(); + }); - assert.strictEqual(testRan, true); - nockDone(); - }); + it('delete an object', async function () { + const { nockDone } = await usingNock(this.test, mode, options); - it('does not throw when deleting an unknown object', async function () { - const { nockDone } = await usingNock(this.test, mode, options); + const testRan = await StorageBaseTests.deleteObject(storage); - const testRan = await StorageBaseTests.deleteUnknownObject(storage); + assert.strictEqual(testRan, true); + nockDone(); + }); - assert.strictEqual(testRan, true); - nockDone(); - }); + it('does not throw when deleting an unknown object', async function () { + const { nockDone } = await usingNock(this.test, mode, options); - it('performs batch operations', async function () { - const { nockDone } = await usingNock(this.test, mode, options); + const testRan = await StorageBaseTests.deleteUnknownObject(storage); - const testRan = await StorageBaseTests.performBatchOperations(storage); + assert.strictEqual(testRan, true); + nockDone(); + }); - assert.strictEqual(testRan, true); - nockDone(); - }); + it('performs batch operations', async function () { + const { nockDone } = await usingNock(this.test, mode, options); - it('proceeds through a waterfall dialog', async function () { - const { nockDone } = await usingNock(this.test, mode, options); + const testRan = await StorageBaseTests.performBatchOperations(storage); - const testRan = await StorageBaseTests.proceedsThroughWaterfall(storage); + assert.strictEqual(testRan, true); + nockDone(); + }); - assert.strictEqual(testRan, true); - nockDone(); - }); + it('proceeds through a waterfall dialog', async function () { + const { nockDone } = await usingNock(this.test, mode, options); - it('support using multiple databases', async function () { - const { nockDone } = await usingNock(this.test, mode, options); + const testRan = await StorageBaseTests.proceedsThroughWaterfall(storage); - const newDb = 'new-db'; + assert.strictEqual(testRan, true); + nockDone(); + }); - const defaultSettings = getSettings(this.test); - const settingsWithNewDb = getSettings(this.test); - settingsWithNewDb.databaseId = newDb; + it('support using multiple databases', async function () { + const { nockDone } = await usingNock(this.test, mode, options); - // cosmosDbPartitionedStorage requires the user creates the db, - // so we need to create it for the test - const dbCreateClient = new CosmosClient({ - endpoint: settingsWithNewDb.cosmosDbEndpoint, - key: settingsWithNewDb.authKey, - agent: new https.Agent({ rejectUnauthorized: false }), - }); - try { - await dbCreateClient.database(newDb).delete(); - } catch { - //This throws if the db is already deleted. - } - await dbCreateClient.databases.create({ id: newDb }); + const newDb = 'new-db'; - const defaultClient = new CosmosDbPartitionedStorage(defaultSettings); - await assert.doesNotReject(async () => await defaultClient.initialize()); + const defaultSettings = getSettings(this.test); + const settingsWithNewDb = getSettings(this.test); + settingsWithNewDb.databaseId = newDb; - const newClient = new CosmosDbPartitionedStorage(settingsWithNewDb); - await assert.doesNotReject(async () => await newClient.initialize()); + // cosmosDbPartitionedStorage requires the user creates the db, + // so we need to create it for the test + const dbCreateClient = new CosmosClient({ + endpoint: settingsWithNewDb.cosmosDbEndpoint, + key: settingsWithNewDb.authKey, + agent: new https.Agent({ rejectUnauthorized: false }), + }); + try { + await dbCreateClient.database(newDb).delete(); + } catch { + //This throws if the db is already deleted. + } + await dbCreateClient.databases.create({ id: newDb }); - await assert.doesNotReject( - async () => await newClient.client.database(newDb).container(settingsWithNewDb.containerId).read() - ); + const defaultClient = new CosmosDbPartitionedStorage(defaultSettings); + await assert.doesNotReject(async () => await defaultClient.initialize()); - await dbCreateClient.database(newDb).delete(); + const newClient = new CosmosDbPartitionedStorage(settingsWithNewDb); + await assert.doesNotReject(async () => await newClient.initialize()); - nockDone(); - }); + await assert.doesNotReject( + async () => await newClient.client.database(newDb).container(settingsWithNewDb.containerId).read(), + ); - it('support using multiple containers', async function () { - const { nockDone } = await usingNock(this.test, mode, options); + await dbCreateClient.database(newDb).delete(); - const newContainer = 'new-container'; + nockDone(); + }); - const defaultSettings = getSettings(this.test); - const settingsWithNewContainer = getSettings(this.test); - settingsWithNewContainer.containerId = newContainer; + it('support using multiple containers', async function () { + const { nockDone } = await usingNock(this.test, mode, options); - const defaultClient = new CosmosDbPartitionedStorage(defaultSettings); - await assert.doesNotReject(async () => await defaultClient.initialize()); + const newContainer = 'new-container'; - const newClient = new CosmosDbPartitionedStorage(settingsWithNewContainer); - await assert.doesNotReject(async () => await newClient.initialize()); + const defaultSettings = getSettings(this.test); + const settingsWithNewContainer = getSettings(this.test); + settingsWithNewContainer.containerId = newContainer; - await assert.doesNotReject( - async () => - await newClient.client.database(settingsWithNewContainer.databaseId).container(newContainer).read() - ); + const defaultClient = new CosmosDbPartitionedStorage(defaultSettings); + await assert.doesNotReject(async () => await defaultClient.initialize()); - nockDone(); - }); + const newClient = new CosmosDbPartitionedStorage(settingsWithNewContainer); + await assert.doesNotReject(async () => await newClient.initialize()); - it('is aware of nesting limit', async function () { - const { nockDone } = await usingNock(this.test, mode, options); + await assert.doesNotReject( + async () => + await newClient.client.database(settingsWithNewContainer.databaseId).container(newContainer).read(), + ); - async function testNest(depth) { - // This creates nested data with both objects and arrays - const createNestedData = (count, isArray = false) => - count > 0 - ? isArray - ? [createNestedData(count - 1, false)] - : { data: createNestedData(count - 1, true) } - : null; + nockDone(); + }); - const changes = { CONTEXTKEY: createNestedData(depth) }; + it('is aware of nesting limit', async function () { + const { nockDone } = await usingNock(this.test, mode, options); - await storage.write(changes); - } + async function testNest(depth) { + // This creates nested data with both objects and arrays + const createNestedData = (count, isArray = false) => + count > 0 + ? isArray + ? [createNestedData(count - 1, false)] + : { data: createNestedData(count - 1, true) } + : null; - // Should not throw - await testNest(127); + const changes = { CONTEXTKEY: createNestedData(depth) }; - try { - // Should either not throw or throw a special exception - await testNest(128); - } catch (err) { - // If the nesting limit is changed on the Cosmos side - // then this assertion won't be reached, which is okay - assert.strictEqual(err.message.includes('recursion'), true); - } + await storage.write(changes); + } - nockDone(); - }); + // Should not throw + await testNest(127); - it('is aware of nesting limit with dialogs', async function () { - const { nockDone } = await usingNock(this.test, mode, options); + try { + // Should either not throw or throw a special exception + await testNest(128); + } catch (err) { + // If the nesting limit is changed on the Cosmos side + // then this assertion won't be reached, which is okay + assert.strictEqual(err.message.includes('recursion'), true); + } - async function testDialogNest(dialogDepth) { - const createNestedDialog = (depth) => - new ComponentDialog('componentDialog').addDialog( - depth > 0 - ? createNestedDialog(depth - 1) - : new WaterfallDialog('waterfallDialog', [async () => Dialog.EndOfTurn]) - ); + nockDone(); + }); - const convoState = new ConversationState(storage); - const dialogState = convoState.createProperty('dialogStateForNestingTest'); - const dialogs = new DialogSet(dialogState); + it('is aware of nesting limit with dialogs', async function () { + const { nockDone } = await usingNock(this.test, mode, options); - const adapter = new TestAdapter(async (turnContext) => { - if (turnContext.activity.text == 'reset') { - await dialogState.delete(turnContext); - } else { - const dc = await dialogs.createContext(turnContext); + async function testDialogNest(dialogDepth) { + const createNestedDialog = (depth) => + new ComponentDialog('componentDialog').addDialog( + depth > 0 + ? createNestedDialog(depth - 1) + : new WaterfallDialog('waterfallDialog', [async () => Dialog.EndOfTurn]), + ); - await dc.beginDialog('componentDialog'); - } - }).use(new AutoSaveStateMiddleware(convoState)); + const convoState = new ConversationState(storage); + const dialogState = convoState.createProperty('dialogStateForNestingTest'); + const dialogs = new DialogSet(dialogState); - adapter.conversation = TestAdapter.createConversation('nestingTest'); + const adapter = new TestAdapter(async (turnContext) => { + if (turnContext.activity.text == 'reset') { + await dialogState.delete(turnContext); + } else { + const dc = await dialogs.createContext(turnContext); - dialogs.add(createNestedDialog(dialogDepth)); + await dc.beginDialog('componentDialog'); + } + }).use(new AutoSaveStateMiddleware(convoState)); - await adapter.send('reset').send('hello').startTest(); - } + adapter.conversation = TestAdapter.createConversation('nestingTest'); - // Note that the C# test places the "cutoff" between 23 and 24 dialogs. - // These tests use 29 and 30 because Node doesn't nest data as deeply - // due to the lack of type names, so more dialogs are needed to reach - // the limit of 128 levels. + dialogs.add(createNestedDialog(dialogDepth)); - // Should not throw - await testDialogNest(29); + await adapter.send('reset').send('hello').startTest(); + } - try { - // Should either not throw or throw a special exception - await testDialogNest(30); - } catch (err) { - // If the nesting limit is changed on the Cosmos side - // then this assertion won't be reached, which is okay - assert.strictEqual(err.message.includes('dialogs'), true); - } + // Note that the C# test places the "cutoff" between 23 and 24 dialogs. + // These tests use 29 and 30 because Node doesn't nest data as deeply + // due to the lack of type names, so more dialogs are needed to reach + // the limit of 128 levels. + + // Should not throw + await testDialogNest(29); - nockDone(); + try { + // Should either not throw or throw a special exception + await testDialogNest(30); + } catch (err) { + // If the nesting limit is changed on the Cosmos side + // then this assertion won't be reached, which is okay + assert.strictEqual(err.message.includes('dialogs'), true); + } + + nockDone(); + }); }); }); From cf798130509af0bd99ab25e27e3cfa17fe899d63 Mon Sep 17 00:00:00 2001 From: Jhonatan Sandoval Velasco <122501764+JhontSouth@users.noreply.github.com> Date: Mon, 6 Jan 2025 10:04:47 -0500 Subject: [PATCH 11/22] fix: ESLint issues in bobuilder-core (#4827) * fix lint issues in bobuilder-core * Merge branch 'southworks/update/eslint-packages' into southworks/fix/eslint-issues-botbuilder-core * remove useless config file * Merge branch 'southworks/update/eslint-packages' into southworks/fix/eslint-issues-botbuilder-core * remove unnecesary packages * update yarn.lock * update API signature --- libraries/botbuilder-core/eslint.config.cjs | 10 --- .../etc/botbuilder-core.api.md | 1 - libraries/botbuilder-core/package.json | 3 +- .../botbuilder-core/src/activityHandler.ts | 39 ++------- .../src/activityHandlerBase.ts | 24 +----- libraries/botbuilder-core/src/botAdapter.ts | 21 ++--- libraries/botbuilder-core/src/botComponent.ts | 1 - libraries/botbuilder-core/src/botState.ts | 5 +- .../src/botStatePropertyAccessor.ts | 14 +++- libraries/botbuilder-core/src/botStateSet.ts | 2 +- .../botbuilder-core/src/botTelemetryClient.ts | 2 +- libraries/botbuilder-core/src/cardFactory.ts | 29 +++---- .../botbuilder-core/src/cloudAdapterBase.ts | 41 +++++---- ...configurationBotFrameworkAuthentication.ts | 10 +-- ...igurationServiceClientCredentialFactory.ts | 20 ++--- .../botbuilder-core/src/conversationState.ts | 5 +- .../src/extendedUserTokenProvider.ts | 21 ++--- libraries/botbuilder-core/src/internal.ts | 2 +- .../botbuilder-core/src/invokeException.ts | 5 +- .../src/memoryTranscriptStore.ts | 6 +- .../botbuilder-core/src/messageFactory.ts | 12 +-- .../src/privateConversationState.ts | 5 +- .../botbuilder-core/src/propertyManager.ts | 2 +- libraries/botbuilder-core/src/queueStorage.ts | 2 +- .../src/showTypingMiddleware.ts | 7 +- .../src/skills/skillConversationIdFactory.ts | 4 +- libraries/botbuilder-core/src/storage.ts | 5 +- libraries/botbuilder-core/src/stringUtils.ts | 1 - .../src/telemetryLoggerMiddleware.ts | 18 ++-- libraries/botbuilder-core/src/testAdapter.ts | 84 ++++++++++--------- .../botbuilder-core/src/transcriptLogger.ts | 8 +- libraries/botbuilder-core/src/turnContext.ts | 20 ++--- libraries/botbuilder-core/src/userState.ts | 5 +- .../botbuilder-core/src/userTokenProvider.ts | 4 +- .../tests/ActivityHandler.test.js | 10 +-- .../tests/activityHandlerBase.test.js | 3 +- .../tests/autoSaveStateMiddleware.test.js | 2 +- .../botbuilder-core/tests/botAdapter.test.js | 9 +- .../botbuilder-core/tests/botState.test.js | 5 +- .../tests/botStatePropertyAccessor.test.js | 2 +- .../tests/botTelemetryClient.test.js | 4 +- .../tests/browserStorage.test.js | 16 ++-- .../tests/cloudAdapterBase.test.js | 31 +++---- ...tionServiceClientCredentialFactory.test.js | 2 +- .../tests/conversationState.test.js | 3 +- .../tests/memoryStorage.test.js | 22 ++--- .../tests/messageFactory.test.js | 12 +-- .../tests/middlewareSet.test.js | 4 +- .../tests/privateConversationState.test.js | 3 +- .../botbuilder-core/tests/storageBaseTests.js | 14 ++-- .../tests/telemetryMiddleware.test.js | 1 + .../botbuilder-core/tests/testAdapter.test.js | 10 +-- .../tests/transcriptMiddleware.test.js | 1 + .../tests/transcriptStoreBaseTest.js | 53 ++++++------ .../botbuilder-core/tests/turnContext.test.js | 10 +-- .../botbuilder-core/tests/userState.test.js | 3 +- 56 files changed, 316 insertions(+), 342 deletions(-) delete mode 100644 libraries/botbuilder-core/eslint.config.cjs diff --git a/libraries/botbuilder-core/eslint.config.cjs b/libraries/botbuilder-core/eslint.config.cjs deleted file mode 100644 index 63647b52cc..0000000000 --- a/libraries/botbuilder-core/eslint.config.cjs +++ /dev/null @@ -1,10 +0,0 @@ -const onlyWarn = require("eslint-plugin-only-warn"); -const sharedConfig = require("../../eslint.config.cjs") - -module.exports = [ - ...sharedConfig, - { - plugins: { - "only-warn": onlyWarn, - }, - }]; diff --git a/libraries/botbuilder-core/etc/botbuilder-core.api.md b/libraries/botbuilder-core/etc/botbuilder-core.api.md index a551446d4b..425beadb03 100644 --- a/libraries/botbuilder-core/etc/botbuilder-core.api.md +++ b/libraries/botbuilder-core/etc/botbuilder-core.api.md @@ -624,7 +624,6 @@ export class SkypeMentionNormalizeMiddleware implements Middleware { export interface StatePropertyAccessor { delete(context: TurnContext): Promise; get(context: TurnContext): Promise; - // (undocumented) get(context: TurnContext, defaultValue: T): Promise; set(context: TurnContext, value: T): Promise; } diff --git a/libraries/botbuilder-core/package.json b/libraries/botbuilder-core/package.json index ecd8145966..dc220e3534 100644 --- a/libraries/botbuilder-core/package.json +++ b/libraries/botbuilder-core/package.json @@ -31,7 +31,6 @@ "botbuilder-stdlib": "4.1.6", "botframework-connector": "4.1.6", "botframework-schema": "4.1.6", - "eslint-plugin-only-warn": "^1.1.0", "uuid": "^10.0.0", "zod": "^3.23.8" }, @@ -46,7 +45,7 @@ "build:rollup": "yarn clean && yarn build && api-extractor run --verbose --local", "clean": "rimraf _ts3.4 lib tsconfig.tsbuildinfo", "depcheck": "depcheck --config ../../.depcheckrc", - "lint": "eslint .", + "lint": "eslint . --config ../../eslint.config.cjs", "postbuild": "downlevel-dts lib _ts3.4/lib --checksum", "test": "npm-run-all build test:mocha", "test:compat": "api-extractor run --verbose", diff --git a/libraries/botbuilder-core/src/activityHandler.ts b/libraries/botbuilder-core/src/activityHandler.ts index b553cf2adc..004e37e9b5 100644 --- a/libraries/botbuilder-core/src/activityHandler.ts +++ b/libraries/botbuilder-core/src/activityHandler.ts @@ -424,7 +424,6 @@ export class ActivityHandler extends ActivityHandlerBase { * Called to initiate the event emission process. * * @param context The context object for the current turn. - * * @remarks * Typically, you would provide this method as the function handler that the adapter calls * to perform the bot's logic after the received activity has been pre-processed by the adapter @@ -451,7 +450,6 @@ export class ActivityHandler extends ActivityHandlerBase { * Called at the start of the event emission process. * * @param context The context object for the current turn. - * * @remarks * Override this method to use custom logic for emitting events. * @@ -468,7 +466,6 @@ export class ActivityHandler extends ActivityHandlerBase { * Runs all registered _message_ handlers and then continues the event emission process. * * @param context The context object for the current turn. - * * @remarks * Override this method to support channel-specific behavior across multiple channels. * @@ -484,7 +481,6 @@ export class ActivityHandler extends ActivityHandlerBase { * Runs all registered _message update_ handlers and then continues the event emission process. * * @param context The context object for the current turn. - * * @remarks * Override this method to support channel-specific behavior across multiple channels. * @@ -502,7 +498,6 @@ export class ActivityHandler extends ActivityHandlerBase { * Runs all registered _message delete_ handlers and then continues the event emission process. * * @param context The context object for the current turn. - * * @remarks * Override this method to support channel-specific behavior across multiple channels. * @@ -568,7 +563,6 @@ export class ActivityHandler extends ActivityHandlerBase { * Handle _signin invoke activity type_. * * @param _context The context object for the current turn. - * * @remarks * Override this method to support channel-specific behavior across multiple channels. */ @@ -585,7 +579,7 @@ export class ActivityHandler extends ActivityHandlerBase { */ protected onAdaptiveCardInvoke( _context: TurnContext, - _invokeValue: AdaptiveCardInvokeValue + _invokeValue: AdaptiveCardInvokeValue, ): Promise { return Promise.reject(new InvokeException(StatusCodes.NOT_IMPLEMENTED)); } @@ -605,7 +599,6 @@ export class ActivityHandler extends ActivityHandlerBase { * Runs all registered _endOfConversation_ handlers and then continues the event emission process. * * @param context The context object for the current turn. - * * @remarks * Override this method to support channel-specific behavior across multiple channels. * @@ -621,7 +614,6 @@ export class ActivityHandler extends ActivityHandlerBase { * Runs all registered _typing_ handlers and then continues the event emission process. * * @param context The context object for the current turn. - * * @remarks * Override this method to support channel-specific behavior across multiple channels. * @@ -637,7 +629,6 @@ export class ActivityHandler extends ActivityHandlerBase { * Runs all registered _instllationupdate_ handlers and then continues the event emission process. * * @param context The context object for the current turn. - * * @remarks * Override this method to support channel-specific behavior across multiple channels. * @@ -673,7 +664,6 @@ export class ActivityHandler extends ActivityHandlerBase { * Runs the _installation update_ sub-type handlers, as appropriate, and then continues the event emission process. * * @param context The context object for the current turn. - * * @remarks * Override this method to support channel-specific behavior across multiple channels or to add * custom conversation update sub-type events. @@ -700,7 +690,6 @@ export class ActivityHandler extends ActivityHandlerBase { * Runs all registered _installation update add_ handlers and then continues the event emission process. * * @param context The context object for the current turn. - * * @remarks * Override this method to support channel-specific behavior across multiple channels. * @@ -716,7 +705,6 @@ export class ActivityHandler extends ActivityHandlerBase { * Runs all registered _installation update remove_ handlers and then continues the event emission process. * * @param context The context object for the current turn. - * * @remarks * Override this method to support channel-specific behavior across multiple channels. * @@ -732,7 +720,6 @@ export class ActivityHandler extends ActivityHandlerBase { * Runs all registered _unrecognized activity type_ handlers and then continues the event emission process. * * @param context The context object for the current turn. - * * @remarks * Override this method to support channel-specific behavior across multiple channels. * @@ -750,7 +737,7 @@ export class ActivityHandler extends ActivityHandlerBase { const response = this.createAdaptiveCardInvokeErrorResponse( StatusCodes.BAD_REQUEST, 'BadRequest', - 'Missing value property for search' + 'Missing value property for search', ); throw new InvokeException(StatusCodes.BAD_REQUEST, response); @@ -763,7 +750,7 @@ export class ActivityHandler extends ActivityHandlerBase { const response = this.createAdaptiveCardInvokeErrorResponse( StatusCodes.BAD_REQUEST, 'BadRequest', - 'Missing kind property for search.' + 'Missing kind property for search.', ); throw new InvokeException(StatusCodes.BAD_REQUEST, response); @@ -774,7 +761,7 @@ export class ActivityHandler extends ActivityHandlerBase { const response = this.createAdaptiveCardInvokeErrorResponse( StatusCodes.BAD_REQUEST, 'BadRequest', - 'Missing queryText for search.' + 'Missing queryText for search.', ); throw new InvokeException(StatusCodes.BAD_REQUEST, response); @@ -789,7 +776,7 @@ export class ActivityHandler extends ActivityHandlerBase { const response = this.createAdaptiveCardInvokeErrorResponse( StatusCodes.BAD_REQUEST, 'BadRequest', - 'Missing value property' + 'Missing value property', ); throw new InvokeException(StatusCodes.BAD_REQUEST, response); @@ -799,7 +786,7 @@ export class ActivityHandler extends ActivityHandlerBase { const response = this.createAdaptiveCardInvokeErrorResponse( StatusCodes.BAD_REQUEST, 'NotSupported', - `The action '${value.action.type}' is not supported.` + `The action '${value.action.type}' is not supported.`, ); throw new InvokeException(StatusCodes.BAD_REQUEST, response); @@ -828,7 +815,7 @@ export class ActivityHandler extends ActivityHandlerBase { private createAdaptiveCardInvokeErrorResponse( statusCode: StatusCodes, code: string, - message: string + message: string, ): AdaptiveCardInvokeResponse { return { statusCode, @@ -841,7 +828,6 @@ export class ActivityHandler extends ActivityHandlerBase { * Runs all registered _conversation update_ handlers and then continues the event emission process. * * @param context The context object for the current turn. - * * @remarks * Override this method to support channel-specific behavior across multiple channels. * @@ -860,7 +846,6 @@ export class ActivityHandler extends ActivityHandlerBase { * Runs the _conversation update_ sub-type handlers, as appropriate, and then continues the event emission process. * * @param context The context object for the current turn. - * * @remarks * Override this method to support channel-specific behavior across multiple channels or to add * custom conversation update sub-type events. @@ -884,7 +869,6 @@ export class ActivityHandler extends ActivityHandlerBase { * Runs the _message update_ sub-type handlers, as appropriate, and then continues the event emission process. * * @param context The context object for the current turn. - * * @remarks * Override this method to support channel-specific behavior across multiple channels or to add * custom conversation update sub-type events. @@ -899,7 +883,6 @@ export class ActivityHandler extends ActivityHandlerBase { * Runs the _message delete_ sub-type handlers, as appropriate, and then continues the event emission process. * * @param context The context object for the current turn. - * * @remarks * Override this method to support channel-specific behavior across multiple channels or to add * custom conversation update sub-type events. @@ -913,7 +896,6 @@ export class ActivityHandler extends ActivityHandlerBase { * Runs all registered _message reaction_ handlers and then continues the event emission process. * * @param context The context object for the current turn. - * * @remarks * Override this method to support channel-specific behavior across multiple channels. * @@ -933,7 +915,6 @@ export class ActivityHandler extends ActivityHandlerBase { * * @param reactionsAdded The list of reactions added. * @param context The context object for the current turn. - * * @remarks * Override this method to support channel-specific behavior across multiple channels. * @@ -950,7 +931,6 @@ export class ActivityHandler extends ActivityHandlerBase { * * @param reactionsRemoved The list of reactions removed. * @param context The context object for the current turn. - * * @remarks * Override this method to support channel-specific behavior across multiple channels. * @@ -960,7 +940,7 @@ export class ActivityHandler extends ActivityHandlerBase { */ protected async onReactionsRemovedActivity( reactionsRemoved: MessageReaction[], - context: TurnContext + context: TurnContext, ): Promise { await this.handle(context, 'ReactionsRemoved', this.defaultNextEvent(context)); } @@ -969,7 +949,6 @@ export class ActivityHandler extends ActivityHandlerBase { * Runs the _message reaction_ sub-type handlers, as appropriate, and then continues the event emission process. * * @param context The context object for the current turn. - * * @remarks * Override this method to support channel-specific behavior across multiple channels or to add * custom message reaction sub-type events. @@ -991,7 +970,6 @@ export class ActivityHandler extends ActivityHandlerBase { * Runs all registered event_ handlers and then continues the event emission process. * * @param context The context object for the current turn. - * * @remarks * Override this method to support channel-specific behavior across multiple channels. * @@ -1010,7 +988,6 @@ export class ActivityHandler extends ActivityHandlerBase { * Runs the _event_ sub-type handlers, as appropriate, and then continues the event emission process. * * @param context The context object for the current turn. - * * @remarks * Override this method to support channel-specific behavior across multiple channels or to add custom event sub-type events. * For certain channels, such as Web Chat and custom Direct Line clients, developers can emit custom event activities from the client. diff --git a/libraries/botbuilder-core/src/activityHandlerBase.ts b/libraries/botbuilder-core/src/activityHandlerBase.ts index 7358527323..b6363902e9 100644 --- a/libraries/botbuilder-core/src/activityHandlerBase.ts +++ b/libraries/botbuilder-core/src/activityHandlerBase.ts @@ -35,7 +35,6 @@ export class ActivityHandlerBase { * Called at the start of the event emission process. * * @param context The context object for the current turn. - * * @remarks * Override this method to use custom logic for emitting events. * @@ -102,7 +101,6 @@ export class ActivityHandlerBase { * Provides a hook for emitting the _message_ event. * * @param _context The context object for the current turn. - * * @remarks * Override this method to run registered _message_ handlers and then continue the event * emission process. @@ -115,7 +113,6 @@ export class ActivityHandlerBase { * Provides a hook for emitting the _message update_ event. * * @param _context The context object for the current turn. - * * @remarks * Override this method to run registered _message update_ handlers and then continue the event * emission process. @@ -128,7 +125,6 @@ export class ActivityHandlerBase { * Provides a hook for emitting the _message delete_ event. * * @param _context The context object for the current turn. - * * @remarks * Override this method to run registered _message delete_ handlers and then continue the event * emission process. @@ -141,7 +137,6 @@ export class ActivityHandlerBase { * Provides a hook for emitting the _conversation update_ event. * * @param context The context object for the current turn. - * * @remarks * Override this method to run registered _conversation update_ handlers and then continue the event * emission process. @@ -156,7 +151,7 @@ export class ActivityHandlerBase { if (context.activity.membersAdded && context.activity.membersAdded.length > 0) { if ( context.activity.membersAdded.filter( - (m) => context.activity.recipient && context.activity.recipient.id !== m.id + (m) => context.activity.recipient && context.activity.recipient.id !== m.id, ).length ) { await this.onMembersAddedActivity(context.activity.membersAdded, context); @@ -164,7 +159,7 @@ export class ActivityHandlerBase { } else if (context.activity.membersRemoved && context.activity.membersRemoved.length > 0) { if ( context.activity.membersRemoved.filter( - (m) => context.activity.recipient && context.activity.recipient.id !== m.id + (m) => context.activity.recipient && context.activity.recipient.id !== m.id, ).length ) { await this.onMembersRemovedActivity(context.activity.membersRemoved, context); @@ -176,7 +171,6 @@ export class ActivityHandlerBase { * Provides a hook for emitting the _message reaction_ event. * * @param context The context object for the current turn. - * * @remarks * Override this method to run registered _message reaction_ handlers and then continue the event * emission process. @@ -201,7 +195,6 @@ export class ActivityHandlerBase { * Provides a hook for emitting the _event_ event. * * @param _context The context object for the current turn. - * * @remarks * Override this method to run registered _event_ handlers and then continue the event * emission process. @@ -226,7 +219,6 @@ export class ActivityHandlerBase { * Provides a hook for emitting the _end of conversation_ event. * * @param _context The context object for the current turn. - * * @remarks * Override this method to run registered _end of conversation_ handlers and then continue the event * emission process. @@ -239,7 +231,6 @@ export class ActivityHandlerBase { * Provides a hook for emitting the _typing_ event. * * @param _context The context object for the current turn. - * * @remarks * Override this method to run registered _typing_ handlers and then continue the event * emission process. @@ -252,7 +243,6 @@ export class ActivityHandlerBase { * Provides a hook for emitting the _installationupdate_ event. * * @param context The context object for the current turn. - * * @remarks * Override this method to run registered _installationupdate_ handlers and then continue the event * emission process. @@ -274,7 +264,6 @@ export class ActivityHandlerBase { * Provides a hook for emitting the _installationupdateadd_ event. * * @param _context The context object for the current turn. - * * @remarks * Override this method to run registered _installationupdateadd_ handlers and then continue the event * emission process. @@ -287,7 +276,6 @@ export class ActivityHandlerBase { * Provides a hook for emitting the _installationupdateremove_ event. * * @param _context The context object for the current turn. - * * @remarks * Override this method to run registered _installationupdateremove_ handlers and then continue the event * emission process. @@ -300,7 +288,6 @@ export class ActivityHandlerBase { * Provides a hook for emitting the _unrecognized_ event. * * @param _context The context object for the current turn. - * * @remarks * Override this method to run registered _unrecognized_ handlers and then continue the event * emission process. @@ -315,7 +302,6 @@ export class ActivityHandlerBase { * * @param _membersAdded An array of the members added to the conversation. * @param _context The context object for the current turn. - * * @remarks * Override this method to run registered _members added_ handlers and then continue the event * emission process. @@ -330,7 +316,6 @@ export class ActivityHandlerBase { * * @param _membersRemoved An array of the members removed from the conversation. * @param _context The context object for the current turn. - * * @remarks * Override this method to run registered _members removed_ handlers and then continue the event * emission process. @@ -345,7 +330,6 @@ export class ActivityHandlerBase { * * @param _reactionsAdded An array of the reactions added to a message. * @param _context The context object for the current turn. - * * @remarks * Override this method to run registered _reactions added_ handlers and then continue the event * emission process. @@ -360,14 +344,13 @@ export class ActivityHandlerBase { * * @param _reactionsRemoved An array of the reactions removed from a message. * @param _context The context object for the current turn. - * * @remarks * Override this method to run registered _reactions removed_ handlers and then continue the event * emission process. */ protected async onReactionsRemovedActivity( _reactionsRemoved: MessageReaction[], - _context: TurnContext + _context: TurnContext, ): Promise { return; } @@ -402,7 +385,6 @@ export class ActivityHandlerBase { * Called to initiate the event emission process. * * @param context The context object for the current turn. - * * @remarks * Typically, you would provide this method as the function handler that the adapter calls * to perform the bot's logic after the received activity has been pre-processed by the adapter diff --git a/libraries/botbuilder-core/src/botAdapter.ts b/libraries/botbuilder-core/src/botAdapter.ts index 214064d942..7f0ee0c6df 100644 --- a/libraries/botbuilder-core/src/botAdapter.ts +++ b/libraries/botbuilder-core/src/botAdapter.ts @@ -45,9 +45,7 @@ export abstract class BotAdapter { * * @param context The context object for the turn. * @param activities The activities to send. - * * @returns An array of [ResourceResponse](xref:) - * * @remarks * The activities will be sent one after another in the order in which they're received. A * response object will be returned for each sent activity. For `message` activities this will @@ -64,7 +62,6 @@ export abstract class BotAdapter { * * @param context The context object for the turn. * @param activity The updated version of the activity to replace. - * * @remarks * Not all channels support this operation. For channels that don't, this call may throw an exception. */ @@ -79,7 +76,6 @@ export abstract class BotAdapter { * * @param context The context object for the turn. * @param reference Conversation reference information for the activity to delete. - * * @remarks * Not all channels support this operation. For channels that don't, this call may throw an exception. */ @@ -90,7 +86,6 @@ export abstract class BotAdapter { * * @param reference A reference to the conversation to continue. * @param logic The asynchronous method to call after the adapter middleware runs. - * * @remarks * This is often referred to as a _proactive notification_, the bot can proactively * send a message to a conversation or user without waiting for an incoming message. @@ -98,7 +93,7 @@ export abstract class BotAdapter { */ abstract continueConversation( reference: Partial, - logic: (revocableContext: TurnContext) => Promise + logic: (revocableContext: TurnContext) => Promise, ): Promise; /** @@ -112,7 +107,7 @@ export abstract class BotAdapter { continueConversationAsync( botAppId: string, reference: Partial, - logic: (context: TurnContext) => Promise + logic: (context: TurnContext) => Promise, ): Promise; /** @@ -126,7 +121,7 @@ export abstract class BotAdapter { continueConversationAsync( claimsIdentity: ClaimsIdentity, reference: Partial, - logic: (context: TurnContext) => Promise + logic: (context: TurnContext) => Promise, ): Promise; /** @@ -142,7 +137,7 @@ export abstract class BotAdapter { claimsIdentity: ClaimsIdentity, reference: Partial, audience: string, - logic: (context: TurnContext) => Promise + logic: (context: TurnContext) => Promise, ): Promise; /** @@ -152,7 +147,7 @@ export abstract class BotAdapter { _botAppIdOrClaimsIdentity: string | ClaimsIdentity, _reference: Partial, _logicOrAudience: ((context: TurnContext) => Promise) | string, - _maybeLogic?: (context: TurnContext) => Promise + _maybeLogic?: (context: TurnContext) => Promise, ): Promise { throw new Error('NotImplemented'); } @@ -168,7 +163,6 @@ export abstract class BotAdapter { * @param _conversationParameters The conversation information to use to create the conversation * @param _logic The method to call for the resulting bot turn. * @returns A promise that represents the asynchronous operation - * * @remarks * To start a conversation, your bot must know its account information and the user's account information on that * channel. Most _channels only support initiating a direct message (non-group) conversation. @@ -185,7 +179,7 @@ export abstract class BotAdapter { _serviceUrl: string, _audience: string, _conversationParameters: ConversationParameters, - _logic: (context: TurnContext) => Promise + _logic: (context: TurnContext) => Promise, ): Promise { throw new Error('NotImplemented'); } @@ -241,7 +235,6 @@ export abstract class BotAdapter { * @param context The context object for the turn. * @param next A callback method to run at the end of the pipeline. * @returns A promise that resolves when the middleware chain is finished - * * @remarks * The adapter creates a revokable proxy for the turn context and then calls its middleware in * the order in which you added it. If the middleware chain completes without short circuiting, @@ -258,7 +251,7 @@ export abstract class BotAdapter { */ protected async runMiddleware( context: TurnContext, - next: (revocableContext: TurnContext) => Promise + next: (revocableContext: TurnContext) => Promise, ): Promise { if (context && context.activity && context.activity.locale) { context.locale = context.activity.locale; diff --git a/libraries/botbuilder-core/src/botComponent.ts b/libraries/botbuilder-core/src/botComponent.ts index 3273bfc184..f14809fc16 100644 --- a/libraries/botbuilder-core/src/botComponent.ts +++ b/libraries/botbuilder-core/src/botComponent.ts @@ -12,7 +12,6 @@ import { Configuration, ServiceCollection } from 'botbuilder-dialogs-adaptive-ru * gets called automatically on the components by the bot runtime, as long as the components are registered in the configuration. */ export abstract class BotComponent { - // eslint-disable-next-line @typescript-eslint/no-explicit-any static z = z.custom((val: any) => typeof val.configureServices === 'function', { message: 'BotComponent', }); diff --git a/libraries/botbuilder-core/src/botState.ts b/libraries/botbuilder-core/src/botState.ts index cf05501305..6d78ed932d 100644 --- a/libraries/botbuilder-core/src/botState.ts +++ b/libraries/botbuilder-core/src/botState.ts @@ -45,7 +45,10 @@ export class BotState implements PropertyManager { * @param storage Storage provider to persist the state object to. * @param storageKey Function called anytime the storage key for a given turn needs to be calculated. */ - constructor(protected storage: Storage, protected storageKey: StorageKeyFactory) {} + constructor( + protected storage: Storage, + protected storageKey: StorageKeyFactory, + ) {} /** * Creates a new property accessor for reading and writing an individual property to the bot diff --git a/libraries/botbuilder-core/src/botStatePropertyAccessor.ts b/libraries/botbuilder-core/src/botStatePropertyAccessor.ts index b6b1db2f1f..f05e2f3860 100644 --- a/libraries/botbuilder-core/src/botStatePropertyAccessor.ts +++ b/libraries/botbuilder-core/src/botStatePropertyAccessor.ts @@ -13,7 +13,6 @@ import { TurnContext } from './turnContext'; * [BotState](xref:botbuilder-core.BotState) object. * * @template T The type of the state property to access. Default type is `any`. - * * @remarks * To create a state property in a state management objet, use the * [createProperty\](xref:botbuilder-core.BotState.createProperty) method. @@ -46,9 +45,15 @@ export interface StatePropertyAccessor { * const value = await myProperty.get(context, { count: 0 }); * ``` * @param context Context for the current turn of conversation with the user. - * @param defaultValue (Optional) default value to copy to the backing storage object if the property isn't found. */ get(context: TurnContext): Promise; + + /** + * Reads a persisted property from its backing storage object. + * + * @param context Context for the current turn of conversation with the user. + * @param defaultValue (Optional) default value to copy to the backing storage object if the property isn't found. + */ get(context: TurnContext, defaultValue: T): Promise; /** @@ -88,7 +93,10 @@ export class BotStatePropertyAccessor implements StatePropertyAccessor< * @param state Parent BotState instance. * @param name Unique name of the property for the parent BotState. */ - constructor(protected readonly state: BotState, public readonly name: string) {} + constructor( + protected readonly state: BotState, + readonly name: string, + ) {} /** * Deletes the persisted property from its backing storage object. diff --git a/libraries/botbuilder-core/src/botStateSet.ts b/libraries/botbuilder-core/src/botStateSet.ts index e8e4027e78..1b73f9f7c8 100644 --- a/libraries/botbuilder-core/src/botStateSet.ts +++ b/libraries/botbuilder-core/src/botStateSet.ts @@ -79,7 +79,7 @@ export class BotStateSet { */ async saveAllChanges(context: TurnContext, force = false): Promise { const promises: Promise[] = this.botStates.map((botstate: BotState) => - botstate.saveChanges(context, force) + botstate.saveChanges(context, force), ); await Promise.all(promises); diff --git a/libraries/botbuilder-core/src/botTelemetryClient.ts b/libraries/botbuilder-core/src/botTelemetryClient.ts index 916215da7a..a715ae87d5 100644 --- a/libraries/botbuilder-core/src/botTelemetryClient.ts +++ b/libraries/botbuilder-core/src/botTelemetryClient.ts @@ -149,7 +149,7 @@ export function telemetryTrackDialogView( telemetryClient: BotTelemetryClient, dialogName: string, properties?: { [key: string]: any }, - metrics?: { [key: string]: number } + metrics?: { [key: string]: number }, ): void { if (!clientSupportsTrackDialogView(telemetryClient)) { throw new TypeError('"telemetryClient" parameter does not have methods trackPageView() or trackTrace()'); diff --git a/libraries/botbuilder-core/src/cardFactory.ts b/libraries/botbuilder-core/src/cardFactory.ts index 68b2b4e356..4b34bfbcee 100644 --- a/libraries/botbuilder-core/src/cardFactory.ts +++ b/libraries/botbuilder-core/src/cardFactory.ts @@ -65,7 +65,6 @@ export class CardFactory { * * @param card A description of the Adaptive Card to return. * @returns An [Attachment](xref:botframework-schema.Attachment). - * * @remarks * Adaptive Cards are an open card exchange format enabling developers to exchange UI content in a common and consistent way. * For channels that don't yet support Adaptive Cards natively, the Bot Framework will @@ -115,7 +114,7 @@ export class CardFactory { title: string, media: (MediaUrl | string)[], buttons?: (CardAction | string)[], - other?: Partial + other?: Partial, ): Attachment { return mediaCard(CardFactory.contentTypes.animationCard, title, media, buttons, other); } @@ -134,7 +133,7 @@ export class CardFactory { title: string, media: (MediaUrl | string)[], buttons?: (CardAction | string)[], - other?: Partial + other?: Partial, ): Attachment { return mediaCard(CardFactory.contentTypes.audioCard, title, media, buttons, other); } @@ -149,7 +148,6 @@ export class CardFactory { * is converted to an `imBack` button with a title and value set to the value of the string. * @param other Optional. Any additional properties to include on the card. * @returns An [Attachment](xref:botframework-schema.Attachment). - * * @remarks * Hero cards tend to have one dominant, full-width image. * Channels typically render the card's text and buttons below the image. @@ -167,7 +165,7 @@ export class CardFactory { title: string, images?: (CardImage | string)[], buttons?: (CardAction | string)[], - other?: Partial + other?: Partial, ): Attachment; /** * Returns an attachment for a hero card. @@ -180,7 +178,6 @@ export class CardFactory { * is converted to an `imBack` button with a title and value set to the value of the string. * @param other Optional. Any additional properties to include on the card. * @returns An [Attachment](xref:botframework-schema.Attachment). - * * @remarks * Hero cards tend to have one dominant, full-width image. * Channels typically render the card's text and buttons below the image. @@ -198,7 +195,7 @@ export class CardFactory { text: string, images?: (CardImage | string)[], buttons?: (CardAction | string)[], - other?: Partial + other?: Partial, ): Attachment; /** * Returns an attachment for a hero card. @@ -211,7 +208,6 @@ export class CardFactory { * is converted to an `imBack` button with a title and value set to the value of the string. * @param other Optional. Any additional properties to include on the card. * @returns An [Attachment](xref:botframework-schema.Attachment). - * * @remarks * Hero cards tend to have one dominant, full-width image. * Channels typically render the card's text and buttons below the image. @@ -248,7 +244,7 @@ export class CardFactory { text?: string, link?: string, tokenExchangeResource?: TokenExchangeResource, - tokenPostResource?: TokenPostResource + tokenPostResource?: TokenPostResource, ): Attachment { const card: Partial = { buttons: [{ type: ActionTypes.Signin, title: title, value: link, channelData: undefined }], @@ -268,7 +264,6 @@ export class CardFactory { * * @param card a description of the Office 365 connector card to return. * @returns An [Attachment](xref:botframework-schema.Attachment). - * * @remarks * For example: * ```JavaScript @@ -308,7 +303,6 @@ export class CardFactory { * @param url The URL of the sign-in page to use. * @param text Optional. Additional text to include on the card. * @returns An [Attachment](xref:botframework-schema.Attachment). - * * @remarks * For channels that don't natively support sign-in cards, an alternative message is rendered. */ @@ -333,7 +327,6 @@ export class CardFactory { * is converted to an `imBack` button with a title and value set to the value of the string. * @param other Optional. Any additional properties to include on the card. * @returns An [Attachment](xref:botframework-schema.Attachment). - * * @remarks * Thumbnail cards are similar to hero cards but instead of a full width image, * they're typically rendered with a smaller thumbnail version of the image. @@ -344,7 +337,7 @@ export class CardFactory { title: string, images?: (CardImage | string)[], buttons?: (CardAction | string)[], - other?: Partial + other?: Partial, ): Attachment; /** * Returns an attachment for a thumbnail card. @@ -357,7 +350,6 @@ export class CardFactory { * is converted to an `imBack` button with a title and value set to the value of the string. * @param other Optional. Any additional properties to include on the card. * @returns An [Attachment](xref:botframework-schema.Attachment). - * * @remarks * Thumbnail cards are similar to hero cards but instead of a full width image, * they're typically rendered with a smaller thumbnail version of the image. @@ -369,7 +361,7 @@ export class CardFactory { text: string, images?: (CardImage | string)[], buttons?: (CardAction | string)[], - other?: Partial + other?: Partial, ): Attachment; /** * Returns an attachment for a thumbnail card. @@ -382,7 +374,6 @@ export class CardFactory { * is converted to an `imBack` button with a title and value set to the value of the string. * @param other Optional. Any additional properties to include on the card. * @returns An [Attachment](xref:botframework-schema.Attachment). - * * @remarks * Thumbnail cards are similar to hero cards but instead of a full width image, * they're typically rendered with a smaller thumbnail version of the image. @@ -394,7 +385,7 @@ export class CardFactory { text?: any, images?: any, buttons?: any, - other?: Partial + other?: Partial, ): Attachment { if (typeof text !== 'string') { other = buttons; @@ -433,7 +424,7 @@ export class CardFactory { title: string, media: (MediaUrl | string)[], buttons?: (CardAction | string)[], - other?: Partial + other?: Partial, ): Attachment { return mediaCard(CardFactory.contentTypes.videoCard, title, media, buttons, other); } @@ -511,7 +502,7 @@ function mediaCard( title: string, media: (MediaUrl | string)[], buttons?: (CardAction | string)[], - other?: any + other?: any, ): Attachment { const card: VideoCard = { ...other }; if (title) { diff --git a/libraries/botbuilder-core/src/cloudAdapterBase.ts b/libraries/botbuilder-core/src/cloudAdapterBase.ts index 362f9dc158..4c5e97812a 100644 --- a/libraries/botbuilder-core/src/cloudAdapterBase.ts +++ b/libraries/botbuilder-core/src/cloudAdapterBase.ts @@ -88,12 +88,12 @@ export abstract class CloudAdapterBase extends BotAdapter { response = await connectorClient.conversations.replyToActivity( activity.conversation.id, activity.replyToId, - activity + activity, ); } else { response = await connectorClient.conversations.sendToConversation( activity.conversation.id, - activity + activity, ); } } @@ -128,7 +128,7 @@ export abstract class CloudAdapterBase extends BotAdapter { const response = await connectorClient.conversations.updateActivity( activity.conversation.id, activity.id, - activity + activity, ); return response?.id ? { id: response.id } : undefined; @@ -156,15 +156,14 @@ export abstract class CloudAdapterBase extends BotAdapter { /** * @inheritdoc - * * @deprecated */ async continueConversation( _reference: Partial, - _logic: (context: TurnContext) => Promise + _logic: (context: TurnContext) => Promise, ): Promise { throw new Error( - '`CloudAdapterBase.continueConversation` is deprecated, please use `CloudAdapterBase.continueConversationAsync`' + '`CloudAdapterBase.continueConversation` is deprecated, please use `CloudAdapterBase.continueConversationAsync`', ); } @@ -175,7 +174,7 @@ export abstract class CloudAdapterBase extends BotAdapter { botAppIdOrClaimsIdentity: string | ClaimsIdentity, reference: Partial, logicOrAudience: ((context: TurnContext) => Promise) | string, - maybeLogic?: (context: TurnContext) => Promise + maybeLogic?: (context: TurnContext) => Promise, ): Promise { const botAppId = typeof botAppIdOrClaimsIdentity === 'string' ? botAppIdOrClaimsIdentity : undefined; @@ -200,7 +199,7 @@ export abstract class CloudAdapterBase extends BotAdapter { serviceUrl: string, audience: string, conversationParameters: ConversationParameters, - logic: (context: TurnContext) => Promise + logic: (context: TurnContext) => Promise, ): Promise { if (typeof serviceUrl !== 'string' || !serviceUrl) { throw new TypeError('`serviceUrl` must be a non-empty string'); @@ -227,7 +226,7 @@ export abstract class CloudAdapterBase extends BotAdapter { createConversationResult.id, channelId, serviceUrl, - conversationParameters + conversationParameters, ); // Create a UserTokenClient instance for the application to use. (For example, in the OAuthPrompt.) @@ -241,7 +240,7 @@ export abstract class CloudAdapterBase extends BotAdapter { connectorClient, userTokenClient, logic, - connectorFactory + connectorFactory, ); // Run the pipeline. @@ -252,7 +251,7 @@ export abstract class CloudAdapterBase extends BotAdapter { createdConversationId: string | undefined, channelId: string, serviceUrl: string, - conversationParameters: ConversationParameters + conversationParameters: ConversationParameters, ): Partial { // Create a conversation update activity to represent the result. const activity = ActivityEx.createEventActivity(); @@ -287,7 +286,7 @@ export abstract class CloudAdapterBase extends BotAdapter { claimsIdentity: ClaimsIdentity, continuationActivity: Partial, audience: string | undefined, - logic: (context: TurnContext) => Promise + logic: (context: TurnContext) => Promise, ): Promise { // Create the connector factory and the inbound request, extracting parameters and then create a connector for outbound requests. const connectorFactory = this.botFrameworkAuthentication.createConnectorFactory(claimsIdentity); @@ -306,7 +305,7 @@ export abstract class CloudAdapterBase extends BotAdapter { connectorClient, userTokenClient, logic, - connectorFactory + connectorFactory, ); // Run the pipeline. @@ -324,7 +323,7 @@ export abstract class CloudAdapterBase extends BotAdapter { protected processActivity( authHeader: string, activity: Activity, - logic: (context: TurnContext) => Promise + logic: (context: TurnContext) => Promise, ): Promise; /** @@ -338,7 +337,7 @@ export abstract class CloudAdapterBase extends BotAdapter { protected processActivity( authenticateRequestResult: AuthenticateRequestResult, activity: Activity, - logic: (context: TurnContext) => Promise + logic: (context: TurnContext) => Promise, ): Promise; /** @@ -347,14 +346,14 @@ export abstract class CloudAdapterBase extends BotAdapter { protected async processActivity( authHeaderOrAuthenticateRequestResult: string | AuthenticateRequestResult, activity: Activity, - logic: (context: TurnContext) => Promise + logic: (context: TurnContext) => Promise, ): Promise { // Authenticate the inbound request, extracting parameters and create a ConnectorFactory for creating a Connector for outbound requests. const authenticateRequestResult = typeof authHeaderOrAuthenticateRequestResult === 'string' ? await this.botFrameworkAuthentication.authenticateRequest( activity, - authHeaderOrAuthenticateRequestResult + authHeaderOrAuthenticateRequestResult, ) : authHeaderOrAuthenticateRequestResult; @@ -364,7 +363,7 @@ export abstract class CloudAdapterBase extends BotAdapter { // Create the connector client to use for outbound requests. const connectorClient = await authenticateRequestResult.connectorFactory?.create( activity.serviceUrl, - authenticateRequestResult.audience + authenticateRequestResult.audience, ); if (!connectorClient) { @@ -373,7 +372,7 @@ export abstract class CloudAdapterBase extends BotAdapter { // Create a UserTokenClient instance for the application to use. (For example, it would be used in a sign-in prompt.) const userTokenClient = await this.botFrameworkAuthentication.createUserTokenClient( - authenticateRequestResult.claimsIdentity + authenticateRequestResult.claimsIdentity, ); // Create a turn context and run the pipeline. @@ -384,7 +383,7 @@ export abstract class CloudAdapterBase extends BotAdapter { connectorClient, userTokenClient, logic, - authenticateRequestResult.connectorFactory + authenticateRequestResult.connectorFactory, ); // Run the pipeline. @@ -421,7 +420,7 @@ export abstract class CloudAdapterBase extends BotAdapter { connectorClient: ConnectorClient, userTokenClient: UserTokenClient, logic: (context: TurnContext) => Promise, - connectorFactory: ConnectorFactory + connectorFactory: ConnectorFactory, ): TurnContext { const context = new TurnContext(this, activity); diff --git a/libraries/botbuilder-core/src/configurationBotFrameworkAuthentication.ts b/libraries/botbuilder-core/src/configurationBotFrameworkAuthentication.ts index f80d6a62e4..f6053ff236 100644 --- a/libraries/botbuilder-core/src/configurationBotFrameworkAuthentication.ts +++ b/libraries/botbuilder-core/src/configurationBotFrameworkAuthentication.ts @@ -137,7 +137,7 @@ export class ConfigurationBotFrameworkAuthentication extends BotFrameworkAuthent credentialsFactory?: ServiceClientCredentialsFactory, authConfiguration?: AuthenticationConfiguration, botFrameworkClientFetch?: (input: RequestInfo, init?: RequestInit) => Promise, - connectorClientOptions: ConnectorClientOptions = {} + connectorClientOptions: ConnectorClientOptions = {}, ) { super(); @@ -177,11 +177,11 @@ export class ConfigurationBotFrameworkAuthentication extends BotFrameworkAuthent CallerId, credentialsFactory ?? new ConfigurationServiceClientCredentialFactory( - typedBotFrameworkAuthConfig as ConfigurationServiceClientCredentialFactoryOptions + typedBotFrameworkAuthConfig as ConfigurationServiceClientCredentialFactoryOptions, ), authConfiguration ?? { requiredEndorsements: [] }, botFrameworkClientFetch, - connectorClientOptions + connectorClientOptions, ); } catch (err) { // Throw a new error with the validation details prominently featured. @@ -272,7 +272,7 @@ export function createBotFrameworkAuthenticationFromConfiguration( credentialsFactory?: ServiceClientCredentialsFactory, authConfiguration?: AuthenticationConfiguration, botFrameworkClientFetch?: (input: RequestInfo, init?: RequestInit) => Promise, - connectorClientOptions: ConnectorClientOptions = {} + connectorClientOptions: ConnectorClientOptions = {}, ): BotFrameworkAuthentication { const botFrameworkAuthConfig = configuration?.get(); @@ -281,6 +281,6 @@ export function createBotFrameworkAuthenticationFromConfiguration( credentialsFactory, authConfiguration, botFrameworkClientFetch, - connectorClientOptions + connectorClientOptions, ); } diff --git a/libraries/botbuilder-core/src/configurationServiceClientCredentialFactory.ts b/libraries/botbuilder-core/src/configurationServiceClientCredentialFactory.ts index 29000496fe..edee37fa16 100644 --- a/libraries/botbuilder-core/src/configurationServiceClientCredentialFactory.ts +++ b/libraries/botbuilder-core/src/configurationServiceClientCredentialFactory.ts @@ -85,11 +85,11 @@ export class ConfigurationServiceClientCredentialFactory extends PasswordService if (withCertificate) { ok( CertificateThumbprint?.trim(), - 'CertificateThumbprint is required when using a Certificate in configuration.' + 'CertificateThumbprint is required when using a Certificate in configuration.', ); ok( CertificatePrivateKey?.trim(), - 'CertificatePrivateKey is required when using a Certificate in configuration.' + 'CertificatePrivateKey is required when using a Certificate in configuration.', ); } @@ -101,7 +101,7 @@ export class ConfigurationServiceClientCredentialFactory extends PasswordService this.inner = new ManagedIdentityServiceClientCredentialsFactory( MicrosoftAppId, - new JwtTokenProviderFactory() + new JwtTokenProviderFactory(), ); break; case SingleTenant.toLocaleLowerCase(): @@ -113,18 +113,18 @@ export class ConfigurationServiceClientCredentialFactory extends PasswordService MicrosoftAppId, CertificateThumbprint, CertificatePrivateKey, - MicrosoftAppTenantId + MicrosoftAppTenantId, ); } else { ok( MicrosoftAppPassword?.trim(), - 'MicrosoftAppPassword is required for SingleTenant in configuration.' + 'MicrosoftAppPassword is required for SingleTenant in configuration.', ); this.inner = new PasswordServiceClientCredentialFactory( MicrosoftAppId, MicrosoftAppPassword, - MicrosoftAppTenantId + MicrosoftAppTenantId, ); } break; @@ -133,13 +133,13 @@ export class ConfigurationServiceClientCredentialFactory extends PasswordService if (withCertificate) { ok( MicrosoftAppId?.trim(), - 'MicrosoftAppId is required for MultiTenant when using a Certificate in configuration.' + 'MicrosoftAppId is required for MultiTenant when using a Certificate in configuration.', ); this.inner = new CertificateServiceClientCredentialsFactory( MicrosoftAppId, CertificateThumbprint, - CertificatePrivateKey + CertificatePrivateKey, ); } else { this.inner = new PasswordServiceClientCredentialFactory(MicrosoftAppId, MicrosoftAppPassword, ''); @@ -169,7 +169,7 @@ export class ConfigurationServiceClientCredentialFactory extends PasswordService microsoftAppId: string, audience: string, loginEndpoint: string, - validateAuthority: boolean + validateAuthority: boolean, ): Promise { return this.inner.createCredentials(microsoftAppId, audience, loginEndpoint, validateAuthority); } @@ -185,7 +185,7 @@ export class ConfigurationServiceClientCredentialFactory extends PasswordService * @returns A [ConfigurationServiceClientCredentialFactory](xref:botbuilder-core.ConfigurationServiceClientCredentialFactory) instance. */ export function createServiceClientCredentialFactoryFromConfiguration( - configuration: Configuration + configuration: Configuration, ): ConfigurationServiceClientCredentialFactory { const factoryOptions = configuration.get(); return new ConfigurationServiceClientCredentialFactory(factoryOptions); diff --git a/libraries/botbuilder-core/src/conversationState.ts b/libraries/botbuilder-core/src/conversationState.ts index 241e69aeb6..8e16efb212 100644 --- a/libraries/botbuilder-core/src/conversationState.ts +++ b/libraries/botbuilder-core/src/conversationState.ts @@ -33,7 +33,10 @@ export class ConversationState extends BotState { * @param storage Storage provider to persist conversation state to. * @param namespace (Optional) namespace to append to storage keys. Defaults to an empty string. */ - constructor(storage: Storage, private namespace: string = '') { + constructor( + storage: Storage, + private namespace: string = '', + ) { super(storage, (context: TurnContext) => { // Calculate storage key const key: string = this.getStorageKey(context); diff --git a/libraries/botbuilder-core/src/extendedUserTokenProvider.ts b/libraries/botbuilder-core/src/extendedUserTokenProvider.ts index 8373f01936..f1b0c19181 100644 --- a/libraries/botbuilder-core/src/extendedUserTokenProvider.ts +++ b/libraries/botbuilder-core/src/extendedUserTokenProvider.ts @@ -28,7 +28,7 @@ export interface ExtendedUserTokenProvider extends IUserTokenProvider { context: TurnContext, connectionName: string, magicCode?: string, - appCredentials?: CoreAppCredentials + appCredentials?: CoreAppCredentials, ): Promise; /** @@ -37,13 +37,13 @@ export interface ExtendedUserTokenProvider extends IUserTokenProvider { * @param context Context for the current turn of conversation with the user. * @param connectionName Name of the auth connection to use. * @param userId User id of user to sign out. - * @param oAuthAppCredentials AppCredentials for OAuth. + * @param appCredentials AppCredentials for OAuth. */ signOutUser( context: TurnContext, connectionName: string, userId?: string, - appCredentials?: CoreAppCredentials + appCredentials?: CoreAppCredentials, ): Promise; /** @@ -51,7 +51,7 @@ export interface ExtendedUserTokenProvider extends IUserTokenProvider { * * @param context Context for the current turn of conversation with the user. * @param connectionName Name of the auth connection to use. - * @param oAuthAppCredentials AppCredentials for OAuth. + * @param appCredentials AppCredentials for OAuth. */ getSignInLink(context: TurnContext, connectionName: string, appCredentials?: CoreAppCredentials): Promise; @@ -60,13 +60,14 @@ export interface ExtendedUserTokenProvider extends IUserTokenProvider { * * @param context Context for the current turn of conversation with the user. * @param connectionName Name of the auth connection to use. - * @param oAuthAppCredentials AppCredentials for OAuth. + * @param resourceUrls Array with the resource Urls. + * @param appCredentials AppCredentials for OAuth. */ getAadTokens( context: TurnContext, connectionName: string, resourceUrls: string[], - appCredentials?: CoreAppCredentials + appCredentials?: CoreAppCredentials, ): Promise<{ [propertyName: string]: TokenResponse; }>; @@ -91,7 +92,7 @@ export interface ExtendedUserTokenProvider extends IUserTokenProvider { context: TurnContext, connectionName: string, userId: string, - finalRedirect?: string + finalRedirect?: string, ): Promise; /** @@ -107,7 +108,7 @@ export interface ExtendedUserTokenProvider extends IUserTokenProvider { connectionName: string, userId: string, finalRedirect?: string, - appCredentials?: CoreAppCredentials + appCredentials?: CoreAppCredentials, ): Promise; /** @@ -122,7 +123,7 @@ export interface ExtendedUserTokenProvider extends IUserTokenProvider { context: TurnContext, connectionName: string, userId: string, - tokenExchangeRequest: TokenExchangeRequest + tokenExchangeRequest: TokenExchangeRequest, ): Promise; /** @@ -138,6 +139,6 @@ export interface ExtendedUserTokenProvider extends IUserTokenProvider { connectionName: string, userId: string, tokenExchangeRequest: TokenExchangeRequest, - appCredentials: CoreAppCredentials + appCredentials: CoreAppCredentials, ): Promise; } diff --git a/libraries/botbuilder-core/src/internal.ts b/libraries/botbuilder-core/src/internal.ts index 3c16d1595a..d088345ed3 100644 --- a/libraries/botbuilder-core/src/internal.ts +++ b/libraries/botbuilder-core/src/internal.ts @@ -24,7 +24,7 @@ export function shallowCopy(value: T): T { */ export function makeRevocable>( target: T, - handler?: ProxyHandler + handler?: ProxyHandler, ): { proxy: T; revoke(): void } { // Ensure proxy supported (some browsers don't) if (typeof Proxy !== 'undefined' && Proxy.revocable) { diff --git a/libraries/botbuilder-core/src/invokeException.ts b/libraries/botbuilder-core/src/invokeException.ts index 8ef46eb159..593ccde39d 100644 --- a/libraries/botbuilder-core/src/invokeException.ts +++ b/libraries/botbuilder-core/src/invokeException.ts @@ -12,7 +12,10 @@ export class InvokeException extends Error { * @param status The Http status code of the error. * @param response optional. The body of the exception. Default is null. */ - constructor(private readonly status: StatusCodes, private readonly response?: T) { + constructor( + private readonly status: StatusCodes, + private readonly response?: T, + ) { super(); this.name = 'InvokeException'; diff --git a/libraries/botbuilder-core/src/memoryTranscriptStore.ts b/libraries/botbuilder-core/src/memoryTranscriptStore.ts index 51f2894757..5d6c4cc7f1 100644 --- a/libraries/botbuilder-core/src/memoryTranscriptStore.ts +++ b/libraries/botbuilder-core/src/memoryTranscriptStore.ts @@ -68,7 +68,7 @@ export class MemoryTranscriptStore implements TranscriptStore { channelId: string, conversationId: string, continuationToken?: string, - startDate?: Date + startDate?: Date, ): Promise> { if (!channelId) { throw new Error('Missing channelId'); @@ -182,7 +182,7 @@ export class MemoryTranscriptStore implements TranscriptStore { */ const createdSorter: (a: TranscriptInfo, b: TranscriptInfo) => number = ( a: TranscriptInfo, - b: TranscriptInfo + b: TranscriptInfo, ): number => a.created.getTime() - b.created.getTime(); /** @@ -195,7 +195,7 @@ const timestampSorter: (a: Activity, b: Activity) => number = (a: Activity, b: A * @private */ const skipWhileExpression: (expression: any) => (item: any) => boolean = ( - expression: any + expression: any, ): ((item: any) => boolean) => { let skipping = true; diff --git a/libraries/botbuilder-core/src/messageFactory.ts b/libraries/botbuilder-core/src/messageFactory.ts index 68e122ee41..34ecac4557 100644 --- a/libraries/botbuilder-core/src/messageFactory.ts +++ b/libraries/botbuilder-core/src/messageFactory.ts @@ -82,7 +82,7 @@ export class MessageFactory { actions: (CardAction | string)[], text?: string, speak?: string, - inputHint?: InputHints | string + inputHint?: InputHints | string, ): Partial { const msg: Partial = { type: ActivityTypes.Message, @@ -126,7 +126,7 @@ export class MessageFactory { attachment: Attachment, text?: string, speak?: string, - inputHint?: InputHints | string + inputHint?: InputHints | string, ): Partial { return attachmentActivity(AttachmentLayoutTypes.List, [attachment], text, speak, inputHint); } @@ -154,7 +154,7 @@ export class MessageFactory { attachments: Attachment[], text?: string, speak?: string, - inputHint?: InputHints | string + inputHint?: InputHints | string, ): Partial { return attachmentActivity(AttachmentLayoutTypes.List, attachments, text, speak, inputHint); } @@ -182,7 +182,7 @@ export class MessageFactory { attachments: Attachment[], text?: string, speak?: string, - inputHint?: InputHints | string + inputHint?: InputHints | string, ): Partial { return attachmentActivity(AttachmentLayoutTypes.Carousel, attachments, text, speak, inputHint); } @@ -210,7 +210,7 @@ export class MessageFactory { name?: string, text?: string, speak?: string, - inputHint?: InputHints | string + inputHint?: InputHints | string, ): Partial { const a: Attachment = { contentType: contentType, contentUrl: url }; if (name) { @@ -234,7 +234,7 @@ function attachmentActivity( attachments: Attachment[], text?: string, speak?: string, - inputHint?: InputHints | string + inputHint?: InputHints | string, ): Partial { const msg: Partial = { type: ActivityTypes.Message, diff --git a/libraries/botbuilder-core/src/privateConversationState.ts b/libraries/botbuilder-core/src/privateConversationState.ts index f15fae8181..8347c8231a 100644 --- a/libraries/botbuilder-core/src/privateConversationState.ts +++ b/libraries/botbuilder-core/src/privateConversationState.ts @@ -33,7 +33,10 @@ export class PrivateConversationState extends BotState { * @param storage Storage provider to persist PrivateConversation state to. * @param namespace (Optional) namespace to append to storage keys. Defaults to an empty string. */ - constructor(storage: Storage, private namespace: string = '') { + constructor( + storage: Storage, + private namespace: string = '', + ) { super(storage, (context: TurnContext) => { // Calculate storage key const key: string = this.getStorageKey(context); diff --git a/libraries/botbuilder-core/src/propertyManager.ts b/libraries/botbuilder-core/src/propertyManager.ts index ec7ac92eec..22c3f2118a 100644 --- a/libraries/botbuilder-core/src/propertyManager.ts +++ b/libraries/botbuilder-core/src/propertyManager.ts @@ -15,7 +15,7 @@ export interface PropertyManager { * Creates a new property accessor for reading and writing an individual property to the bots * state management system. * - * @param T (Optional) type of property to create. Defaults to `any` type. + * @template T (Optional) type of property to create. Defaults to `any` type. * @param name Name of the property being created. */ createProperty(name: string): StatePropertyAccessor; diff --git a/libraries/botbuilder-core/src/queueStorage.ts b/libraries/botbuilder-core/src/queueStorage.ts index cbb70cedf8..45457dfdc6 100644 --- a/libraries/botbuilder-core/src/queueStorage.ts +++ b/libraries/botbuilder-core/src/queueStorage.ts @@ -23,6 +23,6 @@ export abstract class QueueStorage { abstract queueActivity( activity: Partial, visibilityTimeout?: number, - timeToLive?: number + timeToLive?: number, ): Promise; } diff --git a/libraries/botbuilder-core/src/showTypingMiddleware.ts b/libraries/botbuilder-core/src/showTypingMiddleware.ts index e73bf77694..447bb0593b 100644 --- a/libraries/botbuilder-core/src/showTypingMiddleware.ts +++ b/libraries/botbuilder-core/src/showTypingMiddleware.ts @@ -27,7 +27,10 @@ export class ShowTypingMiddleware implements Middleware { * @param delay {number} Number of milliseconds to wait before sending the first typing indicator. * @param period {number} Number of milliseconds to wait before sending each following indicator. */ - constructor(private readonly delay: number = 500, private readonly period: number = 2000) { + constructor( + private readonly delay: number = 500, + private readonly period: number = 2000, + ) { if (delay < 0) { throw new Error('Delay must be greater than or equal to zero'); } @@ -97,7 +100,7 @@ export class ShowTypingMiddleware implements Middleware { type: ActivityTypes.Typing, relatesTo: context.activity.relatesTo, }, - conversationReference + conversationReference, ); await context.adapter.sendActivities(context, [typingActivity]); diff --git a/libraries/botbuilder-core/src/skills/skillConversationIdFactory.ts b/libraries/botbuilder-core/src/skills/skillConversationIdFactory.ts index 03999fee33..8b78b47baa 100644 --- a/libraries/botbuilder-core/src/skills/skillConversationIdFactory.ts +++ b/libraries/botbuilder-core/src/skills/skillConversationIdFactory.ts @@ -52,12 +52,12 @@ export class SkillConversationIdFactory extends SkillConversationIdFactoryBase { async getSkillConversationReference(skillConversationId: string): Promise { const skillConversationInfo = await this.storage.read([skillConversationId]); if (!skillConversationInfo) { - return undefined!; // eslint-disable-line @typescript-eslint/no-non-null-assertion + return undefined!; } const skillConversationReference = skillConversationInfo[skillConversationId]; if (!skillConversationReference) { - return undefined!; // eslint-disable-line @typescript-eslint/no-non-null-assertion + return undefined!; } return skillConversationReference as SkillConversationReference; diff --git a/libraries/botbuilder-core/src/storage.ts b/libraries/botbuilder-core/src/storage.ts index 2c772ca654..f799946b05 100644 --- a/libraries/botbuilder-core/src/storage.ts +++ b/libraries/botbuilder-core/src/storage.ts @@ -76,7 +76,7 @@ export interface StoreItem { /** * Key/value pairs. */ - [key: string]: any; // eslint-disable-line @typescript-eslint/no-explicit-any + [key: string]: any; /** * (Optional) eTag field for stores that support optimistic concurrency. @@ -91,7 +91,7 @@ export interface StoreItems { /** * List of store items indexed by key. */ - [key: string]: any; // eslint-disable-line @typescript-eslint/no-explicit-any + [key: string]: any; } const storeItems = z.record(z.unknown()); @@ -124,7 +124,6 @@ export function assertStoreItems(val: unknown, ..._args: unknown[]): asserts val * await storage.write({ 'botState': state }); * } * ``` - * * @param item Item to calculate the change hash for. * @returns change hash string */ diff --git a/libraries/botbuilder-core/src/stringUtils.ts b/libraries/botbuilder-core/src/stringUtils.ts index 24a2c8406e..30df65d040 100644 --- a/libraries/botbuilder-core/src/stringUtils.ts +++ b/libraries/botbuilder-core/src/stringUtils.ts @@ -33,7 +33,6 @@ export class StringUtils { * The source for this function was derived from the following article: * * https://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/ - * * @param text Text to hash. * @returns A string which is an unique hash. */ diff --git a/libraries/botbuilder-core/src/telemetryLoggerMiddleware.ts b/libraries/botbuilder-core/src/telemetryLoggerMiddleware.ts index ed579355e9..e71cdd23fc 100644 --- a/libraries/botbuilder-core/src/telemetryLoggerMiddleware.ts +++ b/libraries/botbuilder-core/src/telemetryLoggerMiddleware.ts @@ -102,7 +102,7 @@ export class TelemetryLoggerMiddleware implements Middleware { async ( ctx: TurnContext, activities: Partial[], - nextSend: () => Promise + nextSend: () => Promise, ): Promise => { // run full pipeline const responses: ResourceResponse[] = await nextSend(); @@ -111,7 +111,7 @@ export class TelemetryLoggerMiddleware implements Middleware { }); return responses; - } + }, ); // hook up update activity pipeline @@ -123,7 +123,7 @@ export class TelemetryLoggerMiddleware implements Middleware { await this.onUpdateActivity(activity); return response; - } + }, ); // hook up delete activity pipeline @@ -138,10 +138,10 @@ export class TelemetryLoggerMiddleware implements Middleware { id: reference.activityId, }, reference, - false + false, ); await this.onDeleteActivity(deletedActivity); - } + }, ); if (next !== null) { @@ -215,7 +215,7 @@ export class TelemetryLoggerMiddleware implements Middleware { */ protected async fillReceiveEventProperties( activity: Activity, - telemetryProperties?: Record + telemetryProperties?: Record, ): Promise> { const properties: Record = {}; @@ -273,7 +273,7 @@ export class TelemetryLoggerMiddleware implements Middleware { */ protected async fillSendEventProperties( activity: Activity, - telemetryProperties?: Record + telemetryProperties?: Record, ): Promise> { const properties: Record = {}; @@ -329,7 +329,7 @@ export class TelemetryLoggerMiddleware implements Middleware { */ protected async fillUpdateEventProperties( activity: Activity, - telemetryProperties?: Record + telemetryProperties?: Record, ): Promise> { const properties: Record = {}; @@ -368,7 +368,7 @@ export class TelemetryLoggerMiddleware implements Middleware { */ protected async fillDeleteEventProperties( activity: Activity, - telemetryProperties?: Record + telemetryProperties?: Record, ): Promise> { const properties: Record = {}; diff --git a/libraries/botbuilder-core/src/testAdapter.ts b/libraries/botbuilder-core/src/testAdapter.ts index 4136751f5a..c847449138 100644 --- a/libraries/botbuilder-core/src/testAdapter.ts +++ b/libraries/botbuilder-core/src/testAdapter.ts @@ -68,7 +68,7 @@ export class TestAdapter extends BotAdapter implements ExtendedUserTokenProvider constructor( logicOrConversation?: ((context: TurnContext) => Promise) | ConversationReference, template?: Partial, - sendTraceActivity = false + sendTraceActivity = false, ) { super(); this._sendTraceActivity = sendTraceActivity; @@ -215,7 +215,7 @@ export class TestAdapter extends BotAdapter implements ExtendedUserTokenProvider */ async processActivity( activity: string | Partial, - callback?: (context: TurnContext) => Promise + callback?: (context: TurnContext) => Promise, ): Promise { const request: Partial = typeof activity === 'string' ? { type: ActivityTypes.Message, text: activity } : activity; @@ -346,7 +346,7 @@ export class TestAdapter extends BotAdapter implements ExtendedUserTokenProvider */ continueConversation( _reference: Partial, - _logic: (revocableContext: TurnContext) => Promise + _logic: (revocableContext: TurnContext) => Promise, ): Promise { return Promise.reject(new Error('not implemented')); } @@ -404,7 +404,7 @@ export class TestAdapter extends BotAdapter implements ExtendedUserTokenProvider userSays: string | Partial, expected: string | Partial | ((activity: Partial, description?: string) => void), description?: string, - _timeout?: number + _timeout?: number, ): TestFlow { return this.send(userSays).assertReply(expected, description); } @@ -425,20 +425,23 @@ export class TestAdapter extends BotAdapter implements ExtendedUserTokenProvider throw new Error('Missing array of activities'); } - const activityInspector: any = (expected: Partial): TestActivityInspector => ( - actual: Partial, - description2: string - ): any => validateTranscriptActivity(actual, expected, description2); + const activityInspector: any = + (expected: Partial): TestActivityInspector => + (actual: Partial, description2: string): any => + validateTranscriptActivity(actual, expected, description2); // Chain all activities in a TestFlow, check if its a user message (send) or a bot reply (assert) - return activities.reduce((flow: TestFlow, activity: Partial) => { - // tslint:disable-next-line:prefer-template - const assertDescription = `reply ${description ? ' from ' + description : ''}`; - - return this.isReply(activity) - ? flow.assertReply(activityInspector(activity, description), assertDescription, timeout) - : flow.send(activity); - }, new TestFlow(Promise.resolve(), this)); + return activities.reduce( + (flow: TestFlow, activity: Partial) => { + // tslint:disable-next-line:prefer-template + const assertDescription = `reply ${description ? ' from ' + description : ''}`; + + return this.isReply(activity) + ? flow.assertReply(activityInspector(activity, description), assertDescription, timeout) + : flow.send(activity); + }, + new TestFlow(Promise.resolve(), this), + ); } private _userTokens: UserToken[] = []; @@ -479,14 +482,13 @@ export class TestAdapter extends BotAdapter implements ExtendedUserTokenProvider * @param includeFilter Optional. A comma-separated list of connection's to include. If present, * the `includeFilter` parameter limits the tokens this method returns. * @param _oAuthAppCredentials AppCredentials for OAuth. - * * @returns The [TokenStatus](xref:botframework-connector.TokenStatus) objects retrieved. */ async getTokenStatus( context: TurnContext, userId: string, includeFilter?: string, - _oAuthAppCredentials?: any + _oAuthAppCredentials?: any, ): Promise { if (!context || !context.activity) { throw new Error('testAdapter.getTokenStatus(): context with activity is required'); @@ -506,7 +508,7 @@ export class TestAdapter extends BotAdapter implements ExtendedUserTokenProvider (x) => x.channelId === context.activity.channelId && x.userId === userId && - (!filter || filter.includes(x.connectionName)) + (!filter || filter.includes(x.connectionName)), ) .map((token) => ({ ConnectionName: token.connectionName, @@ -531,7 +533,7 @@ export class TestAdapter extends BotAdapter implements ExtendedUserTokenProvider if (magicCode) { const magicCodeRecord = this._magicCodes.find( - (item) => key.equalsKey(item.key) && item.magicCode === magicCode + (item) => key.equalsKey(item.key) && item.magicCode === magicCode, ); if (magicCodeRecord) { // move the token to long term dictionary @@ -560,7 +562,7 @@ export class TestAdapter extends BotAdapter implements ExtendedUserTokenProvider this._userTokens = this._userTokens.filter( (token) => connectionName && - (connectionName !== token.connectionName || channelId !== token.channelId || userId !== token.userId) + (connectionName !== token.connectionName || channelId !== token.channelId || userId !== token.userId), ); } @@ -586,7 +588,7 @@ export class TestAdapter extends BotAdapter implements ExtendedUserTokenProvider async getAadTokens( _context: TurnContext, _connectionName: string, - _resourceUrls: string[] + _resourceUrls: string[], ): Promise<{ [propertyName: string]: TokenResponse; }> { @@ -609,7 +611,7 @@ export class TestAdapter extends BotAdapter implements ExtendedUserTokenProvider channelId: string, userId: string, exchangeableItem: string, - token: string + token: string, ) { const key: ExchangeableToken = new ExchangeableToken(); key.channelId = channelId; @@ -633,7 +635,7 @@ export class TestAdapter extends BotAdapter implements ExtendedUserTokenProvider context: TurnContext, connectionName: string, userId?: string, - _finalRedirect?: string + _finalRedirect?: string, ): Promise { return { signInLink: `https://botframeworktestadapter.com/oauthsignin/${connectionName}/${context.activity.channelId}/${userId}`, @@ -658,7 +660,7 @@ export class TestAdapter extends BotAdapter implements ExtendedUserTokenProvider context: TurnContext, connectionName: string, userId: string, - tokenExchangeRequest: TokenExchangeRequest + tokenExchangeRequest: TokenExchangeRequest, ): Promise { const exchangeableValue: string = tokenExchangeRequest.token ? tokenExchangeRequest.token @@ -789,7 +791,7 @@ export class TestFlow { constructor( public previous: Promise, private adapter: TestAdapter, - private callback?: (turnContext: TurnContext) => Promise + private callback?: (turnContext: TurnContext) => Promise, ) {} /** @@ -807,7 +809,7 @@ export class TestFlow { userSays: string | Partial, expected: string | Partial | ((activity: Partial, description?: string) => void), description?: string, - timeout?: number + timeout?: number, ): TestFlow { return this.send(userSays).assertReply(expected, description || `test("${userSays}", "${expected}")`, timeout); } @@ -822,7 +824,7 @@ export class TestFlow { return new TestFlow( this.previous.then(() => this.adapter.processActivity(userSays, this.callback)), this.adapter, - this.callback + this.callback, ); } @@ -840,7 +842,7 @@ export class TestFlow { return this.adapter.processActivity(cu, this.callback); }), this.adapter, - this.callback + this.callback, ); } @@ -855,7 +857,7 @@ export class TestFlow { assertReply( expected: string | Partial | TestActivityInspector, description?: string, - timeout?: number + timeout?: number, ): TestFlow { function defaultInspector(reply: Partial, description2?: string): void { if (typeof expected === 'object') { @@ -902,8 +904,8 @@ export class TestFlow { new Error( `TestAdapter.assertReply(${expecting}): ${description} Timed out after ${ current - start - }ms.` - ) + }ms.`, + ), ); } else if (adapter.activeQueue.length > 0) { // Activity received @@ -922,7 +924,7 @@ export class TestFlow { }); }), this.adapter, - this.callback + this.callback, ); } @@ -955,7 +957,7 @@ export class TestFlow { assert.strictEqual( reply, undefined, - `${JSON.stringify(reply)} is responded when waiting for no reply: '${description}'` + `${JSON.stringify(reply)} is responded when waiting for no reply: '${description}'`, ); resolve(); } else { @@ -966,7 +968,7 @@ export class TestFlow { }); }), this.adapter, - this.callback + this.callback, ); } @@ -988,12 +990,12 @@ export class TestFlow { } assert.fail( `TestAdapter.assertReplyOneOf(): ${description2 || ''} FAILED, Expected one of :${JSON.stringify( - candidates - )}` + candidates, + )}`, ); }, description, - timeout + timeout, ); } @@ -1011,7 +1013,7 @@ export class TestFlow { }); }), this.adapter, - this.callback + this.callback, ); } @@ -1079,7 +1081,7 @@ function validateActivity(activity: Partial, expected: Partial, expected: Partial, - description: string + description: string, ): void { assert.equal(activity.type, expected.type, `failed "type" assert on ${description}`); assert.equal(activity.text, expected.text, `failed "text" assert on ${description}`); @@ -1087,6 +1089,6 @@ function validateTranscriptActivity( assert.deepEqual( activity.suggestedActions, expected.suggestedActions, - `failed "suggestedActions" assert on ${description}` + `failed "suggestedActions" assert on ${description}`, ); } diff --git a/libraries/botbuilder-core/src/transcriptLogger.ts b/libraries/botbuilder-core/src/transcriptLogger.ts index 58497c9141..b1745e3b6c 100644 --- a/libraries/botbuilder-core/src/transcriptLogger.ts +++ b/libraries/botbuilder-core/src/transcriptLogger.ts @@ -81,7 +81,7 @@ export class TranscriptLoggerMiddleware implements Middleware { }); return responses; - } + }, ); // hook up update activity pipeline @@ -111,11 +111,11 @@ export class TranscriptLoggerMiddleware implements Middleware { id: reference.activityId, }, reference, - false + false, ); this.logActivity(transcript, this.cloneActivity(deleteActivity)); - } + }, ); // process bot logic @@ -236,7 +236,7 @@ export interface TranscriptStore extends TranscriptLogger { channelId: string, conversationId: string, continuationToken?: string, - startDate?: Date + startDate?: Date, ): Promise>; /** diff --git a/libraries/botbuilder-core/src/turnContext.ts b/libraries/botbuilder-core/src/turnContext.ts index ec9f81ec3b..0073c42d81 100644 --- a/libraries/botbuilder-core/src/turnContext.ts +++ b/libraries/botbuilder-core/src/turnContext.ts @@ -53,7 +53,7 @@ import { export type SendActivitiesHandler = ( context: TurnContext, activities: Partial[], - next: () => Promise + next: () => Promise, ) => Promise; /** @@ -85,7 +85,7 @@ export type SendActivitiesHandler = ( export type UpdateActivityHandler = ( context: TurnContext, activity: Partial, - next: () => Promise + next: () => Promise, ) => Promise; /** @@ -117,7 +117,7 @@ export type UpdateActivityHandler = ( export type DeleteActivityHandler = ( context: TurnContext, reference: Partial, - next: () => Promise + next: () => Promise, ) => Promise; export const BotCallbackHandlerKey = 'botCallbackHandler'; @@ -133,7 +133,7 @@ function getAppropriateReplyToId(source: Partial): string | undefined return undefined; } -// eslint-disable-next-line @typescript-eslint/no-empty-interface +// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging, @typescript-eslint/no-empty-object-type export interface TurnContext {} /** @@ -143,6 +143,7 @@ export interface TurnContext {} * Context provides information needed to process an incoming activity. The context object is * created by a [BotAdapter](xref:botbuilder-core.BotAdapter) and persists for the length of the turn. */ +// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging export class TurnContext { private _adapter?: BotAdapter; private _activity?: Activity; @@ -324,7 +325,7 @@ export class TurnContext { static applyConversationReference( activity: Partial, reference: Partial, - isIncoming = false + isIncoming = false, ): Partial { activity.channelId = reference.channelId; activity.locale ??= reference.locale; @@ -371,7 +372,7 @@ export class TurnContext { */ static getReplyConversationReference( activity: Partial, - reply: ResourceResponse + reply: ResourceResponse, ): Partial { const reference: Partial = TurnContext.getConversationReference(activity); @@ -410,7 +411,7 @@ export class TurnContext { name: string, value?: any, valueType?: string, - label?: string + label?: string, ): Promise { const traceActivity: Partial = { type: ActivityTypes.Trace, @@ -456,7 +457,7 @@ export class TurnContext { async sendActivity( activityOrText: string | Partial, speak?: string, - inputHint?: string + inputHint?: string, ): Promise { let a: Partial; if (typeof activityOrText === 'string') { @@ -722,7 +723,6 @@ export class TurnContext { * Called when this turn context object is passed into the constructor for a new turn context. * * @param context The new turn context object. - * * @remarks * This copies private members from this object to the new object. * All property values are copied by reference. @@ -862,7 +862,7 @@ export class TurnContext { private emit( handlers: Array<(context: TurnContext, arg: A, next: () => Promise) => Promise>, arg: A, - next: () => Promise + next: () => Promise, ): Promise { const runHandlers = ([handler, ...remaining]: typeof handlers): Promise => { try { diff --git a/libraries/botbuilder-core/src/userState.ts b/libraries/botbuilder-core/src/userState.ts index 5533f32fd8..2f641b473f 100644 --- a/libraries/botbuilder-core/src/userState.ts +++ b/libraries/botbuilder-core/src/userState.ts @@ -32,7 +32,10 @@ export class UserState extends BotState { * @param storage Storage provider to persist user state to. * @param namespace (Optional) namespace to append to storage keys. Defaults to an empty string. */ - constructor(storage: Storage, private namespace: string = '') { + constructor( + storage: Storage, + private namespace: string = '', + ) { super(storage, (context: TurnContext) => { // Calculate storage key const key: string = this.getStorageKey(context); diff --git a/libraries/botbuilder-core/src/userTokenProvider.ts b/libraries/botbuilder-core/src/userTokenProvider.ts index 15a542a3b2..5136c4424e 100644 --- a/libraries/botbuilder-core/src/userTokenProvider.ts +++ b/libraries/botbuilder-core/src/userTokenProvider.ts @@ -45,7 +45,7 @@ export interface IUserTokenProvider { context: TurnContext, userId: string, includeFilter?: string, - oAuthAppCredentials?: any + oAuthAppCredentials?: any, ): Promise; /** @@ -65,7 +65,7 @@ export interface IUserTokenProvider { getAadTokens( context: TurnContext, connectionName: string, - resourceUrls: string[] + resourceUrls: string[], ): Promise<{ [propertyName: string]: TokenResponse; }>; diff --git a/libraries/botbuilder-core/tests/ActivityHandler.test.js b/libraries/botbuilder-core/tests/ActivityHandler.test.js index 0598ff8224..995b351ced 100644 --- a/libraries/botbuilder-core/tests/ActivityHandler.test.js +++ b/libraries/botbuilder-core/tests/ActivityHandler.test.js @@ -340,7 +340,7 @@ describe('ActivityHandler', function () { }, }, }, - bot + bot, ); assert(onAdpativeCardInvokeCalled); }); @@ -637,7 +637,7 @@ describe('ActivityHandler', function () { assertFalseFlag( dispatchMessageUpdateActivityCalled, 'dispatchMessageUpdateActivity', - 'onMessageUpdate' + 'onMessageUpdate', ); dispatchMessageUpdateActivityCalled = true; } @@ -689,7 +689,7 @@ describe('ActivityHandler', function () { assertFalseFlag( dispatchMessageDeleteActivityCalled, 'dispatchMessageDeleteActivity', - 'onMessageDelete' + 'onMessageDelete', ); dispatchMessageDeleteActivityCalled = true; } @@ -922,7 +922,7 @@ describe('ActivityHandler', function () { assertFalseFlag(onTokenResponseEventCalled, 'onTokenResponseEvent', 'onTurn', 'onEvent'); assert( !onTokenResponseEventCalled, - 'onEvent should not be true before onTurn and onEvent handlers complete.' + 'onEvent should not be true before onTurn and onEvent handlers complete.', ); onTokenResponseEventCalled = true; await next(); @@ -950,7 +950,7 @@ describe('ActivityHandler', function () { assertFalseFlag(onUnrecognizedActivityTypeCalled, 'onUnrecognizedActivityType', 'onTurn'); assert( !onUnrecognizedActivityTypeCalled, - 'onUnrecognizedActivityType should not be true before onTurn and onUnrecognizedActivityType handlers complete.' + 'onUnrecognizedActivityType should not be true before onTurn and onUnrecognizedActivityType handlers complete.', ); onUnrecognizedActivityTypeCalled = true; await next(); diff --git a/libraries/botbuilder-core/tests/activityHandlerBase.test.js b/libraries/botbuilder-core/tests/activityHandlerBase.test.js index 0cebf89a68..770f47a392 100644 --- a/libraries/botbuilder-core/tests/activityHandlerBase.test.js +++ b/libraries/botbuilder-core/tests/activityHandlerBase.test.js @@ -72,6 +72,7 @@ describe('ActivityHandlerBase', function () { super.onTurnActivity(context); } } + it('should call onActivity from run()', async function () { const bot = new OverrideOnTurnActivity(); await processActivity({ type: 'any' }, bot); @@ -290,7 +291,7 @@ describe('ActivityHandlerBase', function () { assert(reactionsRemoved, 'reactionsRemoved not found'); assert( reactionsRemoved.length === 1, - `unexpected number of reactionsRemoved: ${reactionsRemoved.length}` + `unexpected number of reactionsRemoved: ${reactionsRemoved.length}`, ); onReactionsRemovedActivityCalled = true; } diff --git a/libraries/botbuilder-core/tests/autoSaveStateMiddleware.test.js b/libraries/botbuilder-core/tests/autoSaveStateMiddleware.test.js index 93c7bcdc29..af3f3f9daa 100644 --- a/libraries/botbuilder-core/tests/autoSaveStateMiddleware.test.js +++ b/libraries/botbuilder-core/tests/autoSaveStateMiddleware.test.js @@ -90,7 +90,7 @@ describe('AutoSaveStateMiddleware', function () { it('should throw exception if invalid plugin passed in.', function () { assert.throws( () => new AutoSaveStateMiddleware(fooState, { read: () => {} }), - new Error("BotStateSet: a object was added that isn't an instance of BotState.") + new Error("BotStateSet: a object was added that isn't an instance of BotState."), ); }); diff --git a/libraries/botbuilder-core/tests/botAdapter.test.js b/libraries/botbuilder-core/tests/botAdapter.test.js index 3ac1eca9ff..ef068d5f0b 100644 --- a/libraries/botbuilder-core/tests/botAdapter.test.js +++ b/libraries/botbuilder-core/tests/botAdapter.test.js @@ -13,6 +13,7 @@ class SimpleAdapter extends BotAdapter { describe('BotAdapter', function () { let sandbox; + beforeEach(function () { sandbox = sinon.createSandbox(); }); @@ -50,7 +51,7 @@ describe('BotAdapter', function () { assert( middlewares.every((middleware) => middleware.called), - 'every middleware was called' + 'every middleware was called', ); assert(handler.called, 'handler was called'); }); @@ -105,7 +106,7 @@ describe('BotAdapter', function () { await assert.rejects( adapter.processRequest(testMessage, handler), - 'unhandled handler error should yield promise rejection' + 'unhandled handler error should yield promise rejection', ); assert(handler.called, 'handler was called'); @@ -124,7 +125,7 @@ describe('BotAdapter', function () { await assert.rejects( adapter.processRequest(testMessage, handler), - 'unhandled onTurnError error should yield promise rejection' + 'unhandled onTurnError error should yield promise rejection', ); assert(adapter.onTurnError.called, 'onTurnError was called'); @@ -171,7 +172,7 @@ describe('BotAdapter', function () { await assert.rejects( adapter.processRequest(testMessage, handler), - 'unhandled handler error should yield promise rejection' + 'unhandled handler error should yield promise rejection', ); assert(handler.called, 'handler was called'); diff --git a/libraries/botbuilder-core/tests/botState.test.js b/libraries/botbuilder-core/tests/botState.test.js index 983cc605d6..a70df49643 100644 --- a/libraries/botbuilder-core/tests/botState.test.js +++ b/libraries/botbuilder-core/tests/botState.test.js @@ -19,6 +19,7 @@ describe('BotState', function () { assert(context, 'context not passed into storage stateKey factory.'); return storageKey; }); + it('should return undefined from get() if nothing cached.', async function () { const state = botState.get(context); assert(state === undefined, 'state returned.'); @@ -40,7 +41,7 @@ describe('BotState', function () { await botState.load(context); const state = cachedState(context, botState.stateKey); assert(state.test === 'foo', 'invalid initial state'); - delete state.test === 'foo'; + delete state.test; await botState.load(context, true); assert(cachedState(context, botState.stateKey).test === 'foo', 'state not reloaded'); }); @@ -51,7 +52,7 @@ describe('BotState', function () { await botState.clear(context); assert( !Object.prototype.hasOwnProperty.call(cachedState(context, botState.stateKey), 'test'), - 'state not cleared on context.' + 'state not cleared on context.', ); await botState.saveChanges(context); diff --git a/libraries/botbuilder-core/tests/botStatePropertyAccessor.test.js b/libraries/botbuilder-core/tests/botStatePropertyAccessor.test.js index be6c462bc6..8817fc2c17 100644 --- a/libraries/botbuilder-core/tests/botStatePropertyAccessor.test.js +++ b/libraries/botbuilder-core/tests/botStatePropertyAccessor.test.js @@ -124,7 +124,7 @@ describe('BotStatePropertyAccessor', function () { assert(typeof addressValue === 'object', 'default value for PropertyAccessor was not properly set.'); assert( addressValue.street === '1 Microsoft Way', - 'default value for PropertyAccessor was not properly set.' + 'default value for PropertyAccessor was not properly set.', ); assert(addressValue.zipCode === 98052, 'default value for PropertyAccessor was not properly set.'); assert(addressValue.state === 'WA', 'default value for PropertyAccessor was not properly set.'); diff --git a/libraries/botbuilder-core/tests/botTelemetryClient.test.js b/libraries/botbuilder-core/tests/botTelemetryClient.test.js index 0fd5a3d537..85bd7cd840 100644 --- a/libraries/botbuilder-core/tests/botTelemetryClient.test.js +++ b/libraries/botbuilder-core/tests/botTelemetryClient.test.js @@ -31,12 +31,12 @@ describe('BotTelemetryClient', function () { it('should throw TypeError if trackTrace and trackPageView do not exist', function () { assert.throws( () => telemetryTrackDialogView(undefined, 'dialogName'), - TypeError('"telemetryClient" parameter does not have methods trackPageView() or trackTrace()') + TypeError('"telemetryClient" parameter does not have methods trackPageView() or trackTrace()'), ); assert.throws( () => telemetryTrackDialogView({}, 'dialogName'), - TypeError('"telemetryClient" parameter does not have methods trackPageView() or trackTrace()') + TypeError('"telemetryClient" parameter does not have methods trackPageView() or trackTrace()'), ); }); }); diff --git a/libraries/botbuilder-core/tests/browserStorage.test.js b/libraries/botbuilder-core/tests/browserStorage.test.js index c48c76840b..1f4be9d639 100644 --- a/libraries/botbuilder-core/tests/browserStorage.test.js +++ b/libraries/botbuilder-core/tests/browserStorage.test.js @@ -110,11 +110,15 @@ function testStorage(storage) { } global.localStorage = {}; -describe('BrowserLocalStorage', function () { - testStorage(new BrowserLocalStorage()); -}); -global.sessionStorage = {}; -describe('BrowserSessionStorage', function () { - testStorage(new BrowserSessionStorage()); +describe('Browser Storage Tests', function () { + describe('BrowserLocalStorage', function () { + testStorage(new BrowserLocalStorage()); + }); + + global.sessionStorage = {}; + + describe('BrowserSessionStorage', function () { + testStorage(new BrowserSessionStorage()); + }); }); diff --git a/libraries/botbuilder-core/tests/cloudAdapterBase.test.js b/libraries/botbuilder-core/tests/cloudAdapterBase.test.js index 3529858472..146e44636e 100644 --- a/libraries/botbuilder-core/tests/cloudAdapterBase.test.js +++ b/libraries/botbuilder-core/tests/cloudAdapterBase.test.js @@ -17,6 +17,7 @@ const noop = () => null; describe('CloudAdapterBase', function () { let sandbox; + beforeEach(function () { sandbox = sinon.createSandbox({ useFakeTimers: true }); }); @@ -270,7 +271,7 @@ describe('CloudAdapterBase', function () { activity: { name: 'ContinueConversation', }, - }) + }), ); }); @@ -289,7 +290,7 @@ describe('CloudAdapterBase', function () { const { logic, verify } = bootstrap( sinon.match({ claims: sinon.match.some(sinon.match({ type: AuthenticationConstants.AppIdClaim, value: appId })), - }) + }), ); await adapter.continueConversationAsync(appId, {}, undefined, logic); @@ -303,13 +304,13 @@ describe('CloudAdapterBase', function () { const { logic, verify } = bootstrap( sinon.match({ claims: sinon.match.some(sinon.match({ type: AuthenticationConstants.AppIdClaim, value: appId })), - }) + }), ); await adapter.continueConversationAsync( new ClaimsIdentity([{ type: AuthenticationConstants.AppIdClaim, value: appId }]), {}, - logic + logic, ); verify(); @@ -321,7 +322,7 @@ describe('CloudAdapterBase', function () { const { logic } = bootstrap( sinon.match({ claims: sinon.match.some(sinon.match({ type: AuthenticationConstants.AppIdClaim, value: appId })), - }) + }), ); const error = new Error('oh no'); @@ -332,7 +333,7 @@ describe('CloudAdapterBase', function () { throw error; }), - error + error, ); }); }); @@ -372,7 +373,7 @@ describe('CloudAdapterBase', function () { activity: { name: 'CreateConversation', }, - }) + }), ); }); @@ -389,12 +390,12 @@ describe('CloudAdapterBase', function () { it('throws for bad args', async function () { await assert.rejects( adapter.createConversationAsync('botAppId', 'channelId', undefined, 'audience', {}, () => null), - { name: 'TypeError' } + { name: 'TypeError' }, ); await assert.rejects( adapter.createConversationAsync('botAppId', 'channelId', '', 'audience', {}, () => null), - { name: 'TypeError' } + { name: 'TypeError' }, ); await assert.rejects( @@ -404,14 +405,14 @@ describe('CloudAdapterBase', function () { 'serviceUrl', 'audience', undefined, - () => null + () => null, ), - { name: 'TypeError' } + { name: 'TypeError' }, ); await assert.rejects( adapter.createConversationAsync('botAppId', 'channelId', 'serviceUrl', 'audience', {}, undefined), - { name: 'TypeError' } + { name: 'TypeError' }, ); }); @@ -425,7 +426,7 @@ describe('CloudAdapterBase', function () { [serviceUrl, audience], sinon.match({ claims: sinon.match.some(sinon.match({ type: AuthenticationConstants.AppIdClaim, value: appId })), - }) + }), ); mockedConnectorClient.expects('createConversation').withArgs(parameters).once().resolves({ id: 'id' }); @@ -445,7 +446,7 @@ describe('CloudAdapterBase', function () { [serviceUrl, audience], sinon.match({ claims: sinon.match.some(sinon.match({ type: AuthenticationConstants.AppIdClaim, value: appId })), - }) + }), ); const error = new Error('oh no'); @@ -454,7 +455,7 @@ describe('CloudAdapterBase', function () { await assert.rejects( adapter.createConversationAsync(appId, 'channelId', serviceUrl, audience, parameters, logic), - error + error, ); }); }); diff --git a/libraries/botbuilder-core/tests/configurationServiceClientCredentialFactory.test.js b/libraries/botbuilder-core/tests/configurationServiceClientCredentialFactory.test.js index 6bbfec8f17..ce82ec9f25 100644 --- a/libraries/botbuilder-core/tests/configurationServiceClientCredentialFactory.test.js +++ b/libraries/botbuilder-core/tests/configurationServiceClientCredentialFactory.test.js @@ -77,7 +77,7 @@ describe('ConfigurationServiceClientCredentialFactory', function () { assert(err.message.includes('MicrosoftAppId')); assert(err.message.includes('MicrosoftAppPassword')); return true; - } + }, ); }); diff --git a/libraries/botbuilder-core/tests/conversationState.test.js b/libraries/botbuilder-core/tests/conversationState.test.js index 2578afe802..cb902e92db 100644 --- a/libraries/botbuilder-core/tests/conversationState.test.js +++ b/libraries/botbuilder-core/tests/conversationState.test.js @@ -12,6 +12,7 @@ describe('ConversationState', function () { const adapter = new TestAdapter(); const context = new TurnContext(adapter, receivedMessage); const conversationState = new ConversationState(storage); + it('should load and save state from storage.', async function () { // Simulate a "Turn" in a conversation by loading the state, // changing it and then saving the changes to state. @@ -53,7 +54,7 @@ describe('ConversationState', function () { conversationState.getStorageKey = (_turnContext) => undefined; await assert.rejects( conversationState.load(context, true), - new Error('ConversationState: overridden getStorageKey method did not return a key.') + new Error('ConversationState: overridden getStorageKey method did not return a key.'), ); }); }); diff --git a/libraries/botbuilder-core/tests/memoryStorage.test.js b/libraries/botbuilder-core/tests/memoryStorage.test.js index 6379657a3d..05a11738c7 100644 --- a/libraries/botbuilder-core/tests/memoryStorage.test.js +++ b/libraries/botbuilder-core/tests/memoryStorage.test.js @@ -70,18 +70,20 @@ function testStorage(storage) { }); } -describe('MemoryStorage - Empty', function () { - testStorage(new MemoryStorage()); -}); +describe('Memory Storage Tests', function () { + describe('MemoryStorage - Empty', function () { + testStorage(new MemoryStorage()); + }); -describe('MemoryStorage - PreExisting', function () { - const dictionary = { test: JSON.stringify({ counter: 12 }) }; - const storage = new MemoryStorage(dictionary); - testStorage(storage); + describe('MemoryStorage - PreExisting', function () { + const dictionary = { test: JSON.stringify({ counter: 12 }) }; + const storage = new MemoryStorage(dictionary); + testStorage(storage); - it('should still have test', function () { - return storage.read(['test']).then((result) => { - assert(result.test.counter == 12, 'read() test.counter should be 12'); + it('should still have test', function () { + return storage.read(['test']).then((result) => { + assert(result.test.counter == 12, 'read() test.counter should be 12'); + }); }); }); }); diff --git a/libraries/botbuilder-core/tests/messageFactory.test.js b/libraries/botbuilder-core/tests/messageFactory.test.js index 765e2ff1b9..dd5670ac9f 100644 --- a/libraries/botbuilder-core/tests/messageFactory.test.js +++ b/libraries/botbuilder-core/tests/messageFactory.test.js @@ -129,7 +129,7 @@ describe('MessageFactory', function () { [{ contentType: 'a' }, { contentType: 'b' }], 'foo', 'bar', - InputHints.IgnoringInput + InputHints.IgnoringInput, ); assertMessage(activity); assertAttachments(activity, 2, ['a', 'b']); @@ -151,7 +151,7 @@ describe('MessageFactory', function () { [{ contentType: 'a' }, { contentType: 'b' }], 'foo', 'bar', - InputHints.IgnoringInput + InputHints.IgnoringInput, ); assertMessage(activity); assertAttachments(activity, 2, ['a', 'b']); @@ -167,7 +167,7 @@ describe('MessageFactory', function () { assertAttachments(activity, 1, ['content-type']); assert( activity.attachments[0].contentUrl === 'https://example.com/content', - 'invalid attachment[0].contentUrl.' + 'invalid attachment[0].contentUrl.', ); }); @@ -177,7 +177,7 @@ describe('MessageFactory', function () { assertAttachments(activity, 1, ['content-type']); assert( activity.attachments[0].contentUrl === 'https://example.com/content', - 'invalid attachment[0].contentUrl.' + 'invalid attachment[0].contentUrl.', ); assert(activity.attachments[0].name === 'file name', 'invalid attachment[0].name.'); }); @@ -189,13 +189,13 @@ describe('MessageFactory', function () { 'file name', 'foo', 'bar', - InputHints.IgnoringInput + InputHints.IgnoringInput, ); assertMessage(activity); assertAttachments(activity, 1, ['content-type']); assert( activity.attachments[0].contentUrl === 'https://example.com/content', - 'invalid attachment[0].contentUrl.' + 'invalid attachment[0].contentUrl.', ); assert(activity.attachments[0].name === 'file name', 'invalid attachment[0].name.'); assert(activity.text === 'foo', 'invalid text field.'); diff --git a/libraries/botbuilder-core/tests/middlewareSet.test.js b/libraries/botbuilder-core/tests/middlewareSet.test.js index c30aba9a33..3d8a70f0a9 100644 --- a/libraries/botbuilder-core/tests/middlewareSet.test.js +++ b/libraries/botbuilder-core/tests/middlewareSet.test.js @@ -135,7 +135,7 @@ describe('MiddlewareSet', function () { } }, () => Promise.reject(new Error('rejected')), - middleware(4) + middleware(4), ); await assert.rejects(set.run(context, noop), (err) => { @@ -163,7 +163,7 @@ describe('MiddlewareSet', function () { assert.strictEqual(err.message, 'rejected'); assert.deepStrictEqual(stack, [1]); return true; - } + }, ); }); }); diff --git a/libraries/botbuilder-core/tests/privateConversationState.test.js b/libraries/botbuilder-core/tests/privateConversationState.test.js index 2b2d033ff6..4018f2f70a 100644 --- a/libraries/botbuilder-core/tests/privateConversationState.test.js +++ b/libraries/botbuilder-core/tests/privateConversationState.test.js @@ -19,6 +19,7 @@ describe('PrivateConversationState', function () { const adapter = new TestAdapter(); const context = new TurnContext(adapter, receivedMessage); const privateConversationState = new PrivateConversationState(storage); + it('should load and save state from storage.', async function () { // Simulate a "Turn" in a conversation by loading the state, // changing it and then saving the changes to state. @@ -65,7 +66,7 @@ describe('PrivateConversationState', function () { privateConversationState.getStorageKey = (_turnContext) => undefined; await assert.rejects( privateConversationState.load(context, true), - new Error('PrivateConversationState: overridden getStorageKey method did not return a key.') + new Error('PrivateConversationState: overridden getStorageKey method did not return a key.'), ); }); }); diff --git a/libraries/botbuilder-core/tests/storageBaseTests.js b/libraries/botbuilder-core/tests/storageBaseTests.js index 039cc4c28d..45f557f459 100644 --- a/libraries/botbuilder-core/tests/storageBaseTests.js +++ b/libraries/botbuilder-core/tests/storageBaseTests.js @@ -33,12 +33,12 @@ class StorageBaseTests { if (storage instanceof BlobStorage) { await assert.rejects( async () => await storage.read(null), - new Error('Please provide at least one key to read from storage.') + new Error('Please provide at least one key to read from storage.'), ); } else if (storage instanceof CosmosDbPartitionedStorage || storage instanceof MemoryStorage) { await assert.rejects( async () => await storage.read(null), - ReferenceError('Keys are required when reading.') + ReferenceError('Keys are required when reading.'), ); // CosmosDbStorage and catch-all } else { @@ -53,12 +53,12 @@ class StorageBaseTests { if (storage instanceof BlobStorage) { await assert.rejects( async () => await storage.write(null), - new Error('Please provide a StoreItems with changes to persist.') + new Error('Please provide a StoreItems with changes to persist.'), ); } else if (storage instanceof CosmosDbPartitionedStorage || storage instanceof MemoryStorage) { await assert.rejects( async () => await storage.write(null), - ReferenceError('Changes are required when writing.') + ReferenceError('Changes are required when writing.'), ); // CosmosDbStorage and catch-all } else { @@ -261,18 +261,18 @@ class StorageBaseTests { const result = promptContext.recognized.value; if (result.length > 3) { const succeededMessage = MessageFactory.text( - `You got it at the ${promptContext.attemptCount}th try!` + `You got it at the ${promptContext.attemptCount}th try!`, ); await promptContext.context.sendActivity(succeededMessage); return true; } const reply = MessageFactory.text( - `Please send a name that is longer than 3 characters. ${promptContext.attemptCount}` + `Please send a name that is longer than 3 characters. ${promptContext.attemptCount}`, ); await promptContext.context.sendActivity(reply); return false; - }) + }), ); const steps = [ diff --git a/libraries/botbuilder-core/tests/telemetryMiddleware.test.js b/libraries/botbuilder-core/tests/telemetryMiddleware.test.js index c6a4a6deb2..437123b36a 100644 --- a/libraries/botbuilder-core/tests/telemetryMiddleware.test.js +++ b/libraries/botbuilder-core/tests/telemetryMiddleware.test.js @@ -23,6 +23,7 @@ const createReply = (activity, text, locale = null) => ({ describe('TelemetryMiddleware', function () { let sandbox; + beforeEach(function () { sandbox = sinon.createSandbox(); }); diff --git a/libraries/botbuilder-core/tests/testAdapter.test.js b/libraries/botbuilder-core/tests/testAdapter.test.js index 54dc83cd13..355606e6d0 100644 --- a/libraries/botbuilder-core/tests/testAdapter.test.js +++ b/libraries/botbuilder-core/tests/testAdapter.test.js @@ -199,7 +199,7 @@ describe('TestAdapter', function () { }); await assert.rejects( async () => await adapter.send('test').assertReply('received', 'received failed', 500).startTest(), - /.*Timed out after.*/ + /.*Timed out after.*/, ); }); @@ -212,7 +212,7 @@ describe('TestAdapter', function () { await assert.rejects( async () => await adapter.send('test').assertReply({ text: 'received' }, 'received failed', 500).startTest(), - /.*Timed out after.*/ + /.*Timed out after.*/, ); }); @@ -228,7 +228,7 @@ describe('TestAdapter', function () { .send('test') .assertReply(() => assert(false, "inspector shouldn't be called."), 'received failed', 500) .startTest(), - /.*Timed out after.*/ + /.*Timed out after.*/, ); }); @@ -239,7 +239,7 @@ describe('TestAdapter', function () { }); }); await assert.doesNotReject( - async () => await adapter.send('test').assertNoReply('no message received', 500).startTest() + async () => await adapter.send('test').assertNoReply('no message received', 500).startTest(), ); }); @@ -266,7 +266,7 @@ describe('TestAdapter', function () { .assertReply({ text: 'received' }) .assertNoReply('should be no additional replies') .startTest(), - /.*should be no additional replies.*/ + /.*should be no additional replies.*/, ); }); diff --git a/libraries/botbuilder-core/tests/transcriptMiddleware.test.js b/libraries/botbuilder-core/tests/transcriptMiddleware.test.js index 2c0b41f266..2bcb832287 100644 --- a/libraries/botbuilder-core/tests/transcriptMiddleware.test.js +++ b/libraries/botbuilder-core/tests/transcriptMiddleware.test.js @@ -316,6 +316,7 @@ describe('TranscriptLoggerMiddleware', function () { describe("'s error handling", function () { let sandbox; + beforeEach(function () { sandbox = sinon.createSandbox(); }); diff --git a/libraries/botbuilder-core/tests/transcriptStoreBaseTest.js b/libraries/botbuilder-core/tests/transcriptStoreBaseTest.js index cea2a7887a..4199fbaae0 100644 --- a/libraries/botbuilder-core/tests/transcriptStoreBaseTest.js +++ b/libraries/botbuilder-core/tests/transcriptStoreBaseTest.js @@ -84,23 +84,23 @@ exports._badArgs = function _badArgs(store) { assertPromise(() => store.logActivity(null), 'logActivity should have thrown error about missing activity'), assertPromise( () => store.getTranscriptActivities(null, null), - 'getTranscriptActivities should have thrown error about missing channelId' + 'getTranscriptActivities should have thrown error about missing channelId', ), assertPromise( () => store.getTranscriptActivities('foo', null), - 'getTranscriptActivities should have thrown error about missing conversationId' + 'getTranscriptActivities should have thrown error about missing conversationId', ), assertPromise( () => store.listTranscripts(null), - 'listTranscripts should have thrown error about missing channelId' + 'listTranscripts should have thrown error about missing channelId', ), assertPromise( () => store.deleteTranscript(null, null), - 'deleteTranscript should have thrown error about missing channelId' + 'deleteTranscript should have thrown error about missing channelId', ), assertPromise( () => store.deleteTranscript('foo', null), - 'deleteTranscript should have thrown error about missing conversationId' + 'deleteTranscript should have thrown error about missing conversationId', ), ]); }; @@ -207,12 +207,13 @@ exports._getTranscriptActivities = function _getTranscriptActivities(store, useP // log in parallel batches of 10 const groups = group(activities, 10); return promiseSeq( - groups.map((group) => () => - resolvePromises( - group.map((item) => () => store.logActivity(item)), - useParallel - ) - ) + groups.map( + (group) => () => + resolvePromises( + group.map((item) => () => store.logActivity(item)), + useParallel, + ), + ), ) .then(async () => { let actualPageSize = 0; @@ -222,7 +223,7 @@ exports._getTranscriptActivities = function _getTranscriptActivities(store, useP pagedResult = await store.getTranscriptActivities( 'test', conversationId, - pagedResult.continuationToken + pagedResult.continuationToken, ); assert(pagedResult); assert(pagedResult.items); @@ -253,12 +254,13 @@ exports._getTranscriptActivitiesStartDate = function _getTranscriptActivitiesSta // log in parallel batches of 10 const groups = group(activities, 10); return promiseSeq( - groups.map((group) => () => - resolvePromises( - group.map((item) => () => store.logActivity(item)), - useParallel - ) - ) + groups.map( + (group) => () => + resolvePromises( + group.map((item) => () => store.logActivity(item)), + useParallel, + ), + ), ) .then(async () => { let actualPageSize = 0; @@ -270,7 +272,7 @@ exports._getTranscriptActivitiesStartDate = function _getTranscriptActivitiesSta 'test', conversationId, pagedResult.continuationToken, - referenceDate + referenceDate, ); assert(pagedResult); assert(pagedResult.items); @@ -311,12 +313,13 @@ exports._listTranscripts = function _listTranscripts(store, useParallel = true) // log in parallel batches of 10 const groups = group(activities, 10); return promiseSeq( - groups.map((group) => () => - resolvePromises( - group.map((item) => () => store.logActivity(item)), - useParallel - ) - ) + groups.map( + (group) => () => + resolvePromises( + group.map((item) => () => store.logActivity(item)), + useParallel, + ), + ), ) .then(async () => { let actualPageSize = 0; diff --git a/libraries/botbuilder-core/tests/turnContext.test.js b/libraries/botbuilder-core/tests/turnContext.test.js index 596c2cad6d..f065ad12d5 100644 --- a/libraries/botbuilder-core/tests/turnContext.test.js +++ b/libraries/botbuilder-core/tests/turnContext.test.js @@ -47,7 +47,7 @@ class SimpleAdapter extends BotAdapter { assert(reference, 'SimpleAdapter.deleteActivity: missing reference.'); assert( reference.activityId === '1234', - `SimpleAdapter.deleteActivity: invalid activityId of "${reference.activityId}".` + `SimpleAdapter.deleteActivity: invalid activityId of "${reference.activityId}".`, ); return Promise.resolve(); } @@ -127,7 +127,7 @@ describe('TurnContext', function () { context.turnState.set('foo', 'bar'); assert( context.turnState.get('foo') === 'bar', - `invalid value of "${context.turnState.get('foo')}" after set().` + `invalid value of "${context.turnState.get('foo')}" after set().`, ); }); @@ -156,7 +156,7 @@ describe('TurnContext', function () { context.turnState.push('foo', 'b'); assert( context.turnState.get('foo') === 'b', - `invalid value of "${context.turnState.get('foo')}" after push().` + `invalid value of "${context.turnState.get('foo')}" after push().`, ); const old = context.turnState.pop('foo'); assert(old == 'b', 'popped value not returned.'); @@ -340,7 +340,7 @@ describe('TurnContext', function () { const activity2 = TurnContext.applyConversationReference( { text: 'foo', type: 'message', locale: 'es-ES' }, reference, - true + true, ); assert(activity2.id, 'activity2 missing id'); assert(activity2.from, 'activity2 missing from'); @@ -350,7 +350,7 @@ describe('TurnContext', function () { assert(activity2.locale, 'activity2 missing locale.'); assert( activity2.locale !== testMessageWithLocale.locale, - 'the activity2 locale is being overwritten by the reference locale' + 'the activity2 locale is being overwritten by the reference locale', ); // Round trip outgoing activity without a replyToId diff --git a/libraries/botbuilder-core/tests/userState.test.js b/libraries/botbuilder-core/tests/userState.test.js index 1a43f30afa..94e97b4a8b 100644 --- a/libraries/botbuilder-core/tests/userState.test.js +++ b/libraries/botbuilder-core/tests/userState.test.js @@ -12,6 +12,7 @@ describe('UserState', function () { const adapter = new TestAdapter(); const context = new TurnContext(adapter, receivedMessage); const userState = new UserState(storage); + it('should load and save state from storage.', async function () { // Simulate a "Turn" in a conversation by loading the state, // changing it and then saving the changes to state. @@ -43,7 +44,7 @@ describe('UserState', function () { userState.getStorageKey = (_turnContext) => undefined; await assert.rejects( userState.load(context, true), - new Error('UserState: overridden getStorageKey method did not return a key.') + new Error('UserState: overridden getStorageKey method did not return a key.'), ); }); }); From 228ca6e9fcde23544b07899b3e6648f5268a5f86 Mon Sep 17 00:00:00 2001 From: Jhonatan Sandoval Velasco <122501764+JhontSouth@users.noreply.github.com> Date: Mon, 6 Jan 2025 10:05:09 -0500 Subject: [PATCH 12/22] fix: Remove ESLint config file in bobuilder-ai-qna (#4829) * remove useless config file * remove eslint-plugin-only-warn --- libraries/botbuilder-ai-qna/eslint.config.cjs | 10 ---------- libraries/botbuilder-ai-qna/package.json | 5 ++--- 2 files changed, 2 insertions(+), 13 deletions(-) delete mode 100644 libraries/botbuilder-ai-qna/eslint.config.cjs diff --git a/libraries/botbuilder-ai-qna/eslint.config.cjs b/libraries/botbuilder-ai-qna/eslint.config.cjs deleted file mode 100644 index 63647b52cc..0000000000 --- a/libraries/botbuilder-ai-qna/eslint.config.cjs +++ /dev/null @@ -1,10 +0,0 @@ -const onlyWarn = require("eslint-plugin-only-warn"); -const sharedConfig = require("../../eslint.config.cjs") - -module.exports = [ - ...sharedConfig, - { - plugins: { - "only-warn": onlyWarn, - }, - }]; diff --git a/libraries/botbuilder-ai-qna/package.json b/libraries/botbuilder-ai-qna/package.json index dd827b3851..9a7b1d4ea8 100644 --- a/libraries/botbuilder-ai-qna/package.json +++ b/libraries/botbuilder-ai-qna/package.json @@ -31,14 +31,13 @@ } }, "dependencies": { - "botbuilder-ai": "4.1.6", - "eslint-plugin-only-warn": "^1.1.0" + "botbuilder-ai": "4.1.6" }, "scripts": { "build": "tsc -b", "clean": "rimraf _ts3.4 lib tsconfig.tsbuildinfo", "depcheck": "depcheck --config ../../.depcheckrc", - "lint": "eslint .", + "lint": "eslint . --config ../../eslint.config.cjs", "postbuild": "downlevel-dts lib _ts3.4/lib --checksum" }, "files": [ From a36641b5ea193ea61002ee9378ef6436f6a48aff Mon Sep 17 00:00:00 2001 From: Jhonatan Sandoval Velasco <122501764+JhontSouth@users.noreply.github.com> Date: Mon, 6 Jan 2025 10:05:31 -0500 Subject: [PATCH 13/22] fix: ESLint issues in botbuilder (#4830) * fix eslint issues in botbuilder * Merge branch 'southworks/update/eslint-packages' into southworks/fix/eslint-issues-botbuilder * remove eslint-plugin-chai-friendly package * remove eslint-plugin-only-warn * cast authorization variable * apply sub-bullet format * apply missing format * update yarn.lock --- eslint.config.cjs | 1 + libraries/botbuilder/eslint.config.cjs | 10 - libraries/botbuilder/package.json | 5 +- .../botbuilder/src/botFrameworkAdapter.ts | 206 ++++++++--------- .../botbuilder/src/botFrameworkHttpAdapter.ts | 4 +- .../botbuilder/src/botFrameworkHttpClient.ts | 5 +- .../botbuilder/src/channelServiceHandler.ts | 4 +- .../src/channelServiceHandlerBase.ts | 90 ++++---- .../botbuilder/src/channelServiceRoutes.ts | 32 +-- libraries/botbuilder/src/cloudAdapter.ts | 44 ++-- libraries/botbuilder/src/eventFactory.ts | 6 +- .../botbuilder/src/fileTranscriptStore.ts | 12 +- .../botbuilder/src/inspectionMiddleware.ts | 12 +- .../src/interfaces/connectorClientBuilder.ts | 2 +- .../botbuilder/src/interfaces/request.ts | 2 +- .../botbuilder/src/interfaces/response.ts | 2 +- .../botbuilder/src/interfaces/webRequest.ts | 1 - .../botbuilder/src/interfaces/webResponse.ts | 3 - .../botbuilder/src/setSpeakMiddleware.ts | 7 +- .../sharepoint/sharePointActivityHandler.ts | 26 +-- .../src/skills/cloudSkillHandler.ts | 25 +-- .../botbuilder/src/skills/skillHandler.ts | 22 +- .../botbuilder/src/skills/skillHandlerImpl.ts | 20 +- .../botbuilder/src/skills/skillHttpClient.ts | 17 +- libraries/botbuilder/src/statusCodeError.ts | 5 +- .../src/streaming/streamingHttpClient.ts | 2 +- .../botbuilder/src/streaming/tokenResolver.ts | 10 +- .../teams/teamsSSOTokenExchangeMiddleware.ts | 13 +- .../botbuilder/src/teamsActivityHandler.ts | 129 ++++++----- .../botbuilder/src/teamsActivityHelpers.ts | 2 +- libraries/botbuilder/src/teamsInfo.ts | 43 ++-- libraries/botbuilder/src/zod.ts | 2 +- .../tests/botFrameworkAdapter.test.js | 209 +++++++++--------- .../tests/botFrameworkHttpClient.test.js | 24 +- .../tests/channelServiceHandler.test.js | 25 ++- .../tests/channelServiceRoutes.test.js | 62 +++--- .../botbuilder/tests/cloudAdapter.test.js | 21 +- .../tests/eventFactoryTests.test.js | 6 +- .../tests/fileTranscriptStore.test.js | 55 +++-- .../tests/inspectionMiddleware.test.js | 73 +++--- .../tests/skills/cloudSkillHandler.test.js | 2 + .../tests/skills/skillHandler.test.js | 24 +- .../tests/skills/skillHttpClient.test.js | 2 +- .../botbuilder/tests/statusCodeError.test.js | 4 +- .../botFrameworkAdapterStreaming.test.js | 50 ++--- .../tests/streaming/mockHttpRequest.js | 2 +- .../tests/streaming/mockStreamingRequest.js | 4 +- .../streaming/streamingHttpClient.test.js | 6 +- .../tests/streaming/tokenResolver.test.js | 2 +- .../teamsSSOTokenExchangeMiddleware.test.js | 9 +- .../tests/teamsActivityHandler.test.js | 112 ++++------ libraries/botbuilder/tests/teamsInfo.test.js | 85 +++---- 52 files changed, 753 insertions(+), 788 deletions(-) delete mode 100644 libraries/botbuilder/eslint.config.cjs diff --git a/eslint.config.cjs b/eslint.config.cjs index 0fc0670e19..644791d452 100644 --- a/eslint.config.cjs +++ b/eslint.config.cjs @@ -38,6 +38,7 @@ module.exports = [ '**/*.lu', '**/*.dialog', '**/*.js.map', + '**/vendors' ], }, diff --git a/libraries/botbuilder/eslint.config.cjs b/libraries/botbuilder/eslint.config.cjs deleted file mode 100644 index 63647b52cc..0000000000 --- a/libraries/botbuilder/eslint.config.cjs +++ /dev/null @@ -1,10 +0,0 @@ -const onlyWarn = require("eslint-plugin-only-warn"); -const sharedConfig = require("../../eslint.config.cjs") - -module.exports = [ - ...sharedConfig, - { - plugins: { - "only-warn": onlyWarn, - }, - }]; diff --git a/libraries/botbuilder/package.json b/libraries/botbuilder/package.json index 7d3bf49cfa..ac9b75b479 100644 --- a/libraries/botbuilder/package.json +++ b/libraries/botbuilder/package.json @@ -36,7 +36,6 @@ "botframework-schema": "4.1.6", "botframework-streaming": "4.1.6", "dayjs": "^1.11.13", - "eslint-plugin-only-warn": "^1.1.0", "filenamify": "^6.0.0", "fs-extra": "^11.2.0", "htmlparser2": "^9.0.1", @@ -55,7 +54,7 @@ "build:rollup": "yarn clean && yarn build && api-extractor run --verbose --local", "clean": "rimraf _ts3.4 lib vendors tsconfig.tsbuildinfo", "depcheck": "depcheck --config ../../.depcheckrc", - "lint": "eslint .", + "lint": "eslint . --config ../../eslint.config.cjs", "prebuild": "tsup ./node_modules/filenamify/*.js --format cjs --dts --out-dir vendors/filenamify --clean --sourcemap", "postbuild": "downlevel-dts lib _ts3.4/lib --checksum", "test": "npm-run-all build test:mocha", @@ -73,4 +72,4 @@ "src", "vendors" ] -} \ No newline at end of file +} diff --git a/libraries/botbuilder/src/botFrameworkAdapter.ts b/libraries/botbuilder/src/botFrameworkAdapter.ts index 7df7cc2599..d45f309687 100644 --- a/libraries/botbuilder/src/botFrameworkAdapter.ts +++ b/libraries/botbuilder/src/botFrameworkAdapter.ts @@ -157,7 +157,8 @@ const TYPE = type(); const RELEASE = release(); const NODE_VERSION = process.version; -const pjson: Record<'version', string> = require('../package.json'); // eslint-disable-line @typescript-eslint/no-var-requires +// eslint-disable-next-line @typescript-eslint/no-require-imports +const pjson: Record<'version', string> = require('../package.json'); export const USER_AGENT = `Microsoft-BotFramework/3.1 BotBuilder/${pjson.version} (Node.js,Version=${NODE_VERSION}; ${TYPE} ${RELEASE}; ${ARCHITECTURE})`; const OAUTH_ENDPOINT = 'https://api.botframework.com'; @@ -203,7 +204,8 @@ const US_GOV_OAUTH_ENDPOINT = 'https://api.botframework.azure.us'; */ export class BotFrameworkAdapter extends BotAdapter - implements BotFrameworkHttpAdapter, ConnectorClientBuilder, ExtendedUserTokenProvider, RequestHandler { + implements BotFrameworkHttpAdapter, ConnectorClientBuilder, ExtendedUserTokenProvider, RequestHandler +{ // These keys are public to permit access to the keys from the adapter when it's a being // from library that does not have access to static properties off of BotFrameworkAdapter. // E.g. botbuilder-dialogs @@ -228,7 +230,6 @@ export class BotFrameworkAdapter * Creates a new instance of the [BotFrameworkAdapter](xref:botbuilder.BotFrameworkAdapter) class. * * @param settings Optional. The settings to use for this adapter instance. - * * @remarks * If the `settings` parameter does not include * [channelService](xref:botbuilder.BotFrameworkAdapterSettings.channelService) or @@ -251,7 +252,7 @@ export class BotFrameworkAdapter this.settings.appId, settings.certificateThumbprint, settings.certificatePrivateKey, - this.settings.channelAuthTenant + this.settings.channelAuthTenant, ); this.credentialsProvider = new SimpleCredentialProvider(this.credentials.appId, ''); } else { @@ -259,18 +260,18 @@ export class BotFrameworkAdapter this.credentials = new MicrosoftGovernmentAppCredentials( this.settings.appId, this.settings.appPassword || '', - this.settings.channelAuthTenant + this.settings.channelAuthTenant, ); } else { this.credentials = new MicrosoftAppCredentials( this.settings.appId, this.settings.appPassword || '', - this.settings.channelAuthTenant + this.settings.channelAuthTenant, ); } this.credentialsProvider = new SimpleCredentialProvider( this.credentials.appId, - this.settings.appPassword || '' + this.settings.appPassword || '', ); } @@ -298,21 +299,19 @@ export class BotFrameworkAdapter // Relocate the tenantId field used by MS Teams to a new location (from channelData to conversation) // This will only occur on activities from teams that include tenant info in channelData but NOT in conversation, // thus should be future friendly. However, once the the transition is complete. we can remove this. - this.use( - async (context, next): Promise => { - if ( - context.activity.channelId === 'msteams' && - context.activity && - context.activity.conversation && - !context.activity.conversation.tenantId && - context.activity.channelData && - context.activity.channelData.tenant - ) { - context.activity.conversation.tenantId = context.activity.channelData.tenant.id; - } - await next(); + this.use(async (context, next): Promise => { + if ( + context.activity.channelId === 'msteams' && + context.activity && + context.activity.conversation && + !context.activity.conversation.tenantId && + context.activity.channelData && + context.activity.channelData.tenant + ) { + context.activity.conversation.tenantId = context.activity.channelData.tenant.id; } - ); + await next(); + }); } /** @@ -330,7 +329,6 @@ export class BotFrameworkAdapter * @param reference A reference to the conversation to continue. * @param oAuthScope The intended recipient of any sent activities. * @param logic The asynchronous method to call after the adapter middleware runs. - * * @remarks * This is often referred to as a _proactive notification_, the bot can proactively * send a message to a conversation or user without waiting for an incoming message. @@ -372,7 +370,7 @@ export class BotFrameworkAdapter */ async continueConversation( reference: Partial, - logic: (context: TurnContext) => Promise + logic: (context: TurnContext) => Promise, ): Promise; /** @@ -385,7 +383,7 @@ export class BotFrameworkAdapter async continueConversation( reference: Partial, oAuthScope: string, - logic: (context: TurnContext) => Promise + logic: (context: TurnContext) => Promise, ): Promise; /** @@ -394,7 +392,7 @@ export class BotFrameworkAdapter async continueConversation( reference: Partial, oAuthScopeOrlogic: string | ((context: TurnContext) => Promise), - maybeLogic?: (context: TurnContext) => Promise + maybeLogic?: (context: TurnContext) => Promise, ): Promise { let audience: string; if (LogicT.safeParse(oAuthScopeOrlogic).success) { @@ -430,7 +428,7 @@ export class BotFrameworkAdapter const request = TurnContext.applyConversationReference( { type: ActivityTypes.Event, name: ActivityEventNames.ContinueConversation }, reference, - true + true, ); const context = this.createContext(request); @@ -447,7 +445,6 @@ export class BotFrameworkAdapter * @param {Partial} reference A reference for the conversation to create. * @param {(context: TurnContext) => Promise} logic The asynchronous method to call after the adapter middleware runs. * @returns {Promise} a promise representing the asynchronous operation - * * @summary * To use this method, you need both the bot's and the user's account information on a channel. * The Bot Connector service supports the creating of group conversations; however, this @@ -488,7 +485,7 @@ export class BotFrameworkAdapter */ createConversation( reference: Partial, - logic: (context: TurnContext) => Promise + logic: (context: TurnContext) => Promise, ): Promise; /** @@ -502,7 +499,7 @@ export class BotFrameworkAdapter createConversation( reference: Partial, parameters: Partial, - logic: (context: TurnContext) => Promise + logic: (context: TurnContext) => Promise, ): Promise; /** @@ -511,7 +508,7 @@ export class BotFrameworkAdapter async createConversation( reference: Partial, parametersOrLogic: Partial | ((context: TurnContext) => Promise), - maybeLogic?: (context: TurnContext) => Promise + maybeLogic?: (context: TurnContext) => Promise, ): Promise { if (!reference.serviceUrl) { throw new Error('BotFrameworkAdapter.createConversation(): missing serviceUrl.'); @@ -534,7 +531,7 @@ export class BotFrameworkAdapter activity: null, channelData: null, }, - parameters + parameters, ); const client = this.createConnectorClient(reference.serviceUrl); @@ -554,7 +551,7 @@ export class BotFrameworkAdapter const request = TurnContext.applyConversationReference( { type: ActivityTypes.Event, name: ActivityEventNames.CreateConversation }, reference, - true + true, ); request.conversation = { @@ -585,7 +582,6 @@ export class BotFrameworkAdapter * * @param context The context object for the turn. * @param reference Conversation reference information for the activity to delete. - * * @remarks * Not all channels support this operation. For channels that don't, this call may throw an exception. */ @@ -602,7 +598,7 @@ export class BotFrameworkAdapter const client: ConnectorClient = this.getOrCreateConnectorClient( context, reference.serviceUrl, - this.credentials + this.credentials, ); await client.conversations.deleteActivity(reference.conversation.id, reference.activityId); } @@ -612,7 +608,6 @@ export class BotFrameworkAdapter * * @param context The context object for the turn. * @param memberId The ID of the member to remove from the conversation. - * * @remarks * Remove a member's identity information from the conversation. * @@ -636,10 +631,8 @@ export class BotFrameworkAdapter * * @param context The context object for the turn. * @param activityId Optional. The ID of the activity to get the members of. If not specified, the current activity ID is used. - * * @returns An array of [ChannelAccount](xref:botframework-schema.ChannelAccount) objects for * the users involved in a given activity. - * * @remarks * Returns an array of [ChannelAccount](xref:botframework-schema.ChannelAccount) objects for * the users involved in a given activity. @@ -659,7 +652,7 @@ export class BotFrameworkAdapter } if (!activityId) { throw new Error( - 'BotFrameworkAdapter.getActivityMembers(): missing both activityId and context.activity.id' + 'BotFrameworkAdapter.getActivityMembers(): missing both activityId and context.activity.id', ); } const serviceUrl: string = context.activity.serviceUrl; @@ -673,10 +666,8 @@ export class BotFrameworkAdapter * Asynchronously lists the members of the current conversation. * * @param context The context object for the turn. - * * @returns An array of [ChannelAccount](xref:botframework-schema.ChannelAccount) objects for * all users currently involved in a conversation. - * * @remarks * Returns an array of [ChannelAccount](xref:botframework-schema.ChannelAccount) objects for * all users currently involved in a conversation. @@ -705,10 +696,8 @@ export class BotFrameworkAdapter * [TurnContext](xref:botbuilder-core.TurnContext) object from a conversation on the channel. * @param continuationToken Optional. The continuation token from the previous page of results. * Omit this parameter or use `undefined` to retrieve the first page of results. - * * @returns A [ConversationsResult](xref:botframework-schema.ConversationsResult) object containing a page of results * and a continuation token. - * * @remarks * The the return value's [conversations](xref:botframework-schema.ConversationsResult.conversations) property contains a page of * [ConversationMembers](xref:botframework-schema.ConversationMembers) objects. Each object's @@ -724,7 +713,7 @@ export class BotFrameworkAdapter */ async getConversations( contextOrServiceUrl: TurnContext | string, - continuationToken?: string + continuationToken?: string, ): Promise { let client: ConnectorClient; if (typeof contextOrServiceUrl === 'object') { @@ -735,7 +724,7 @@ export class BotFrameworkAdapter } return await client.conversations.getConversations( - continuationToken ? { continuationToken: continuationToken } : undefined + continuationToken ? { continuationToken: continuationToken } : undefined, ); } @@ -746,7 +735,6 @@ export class BotFrameworkAdapter * @param connectionName The name of the auth connection to use. * @param magicCode Optional. The validation code the user entered. * @param oAuthAppCredentials AppCredentials for OAuth. - * * @returns A [TokenResponse](xref:botframework-schema.TokenResponse) object that contains the user token. */ async getUserToken(context: TurnContext, connectionName: string, magicCode?: string): Promise; @@ -754,7 +742,7 @@ export class BotFrameworkAdapter context: TurnContext, connectionName: string, magicCode?: string, - oAuthAppCredentials?: CoreAppCredentials + oAuthAppCredentials?: CoreAppCredentials, ): Promise; /** * Asynchronously attempts to retrieve the token for a user that's in a login flow. @@ -763,14 +751,13 @@ export class BotFrameworkAdapter * @param connectionName The name of the auth connection to use. * @param magicCode Optional. The validation code the user entered. * @param oAuthAppCredentials Optional. [AppCredentials](xref:botframework-connector.AppCredentials) for OAuth. - * * @returns A [TokenResponse](xref:botframework-schema.TokenResponse) object that contains the user token. */ async getUserToken( context: TurnContext, connectionName: string, magicCode?: string, - oAuthAppCredentials?: AppCredentials + oAuthAppCredentials?: AppCredentials, ): Promise { if (!context.activity.from || !context.activity.from.id) { throw new Error('BotFrameworkAdapter.getUserToken(): missing from or from.id'); @@ -787,7 +774,7 @@ export class BotFrameworkAdapter const result: TokenApiModels.UserTokenGetTokenResponse = await client.userToken.getToken( userId, connectionName, - { code: magicCode, channelId: context.activity.channelId } + { code: magicCode, channelId: context.activity.channelId }, ); if (!result || !result.token || result._response.status == 404) { return undefined; @@ -809,7 +796,7 @@ export class BotFrameworkAdapter context: TurnContext, connectionName?: string, userId?: string, - oAuthAppCredentials?: CoreAppCredentials + oAuthAppCredentials?: CoreAppCredentials, ): Promise; /** * Asynchronously signs out the user from the token server. @@ -823,7 +810,7 @@ export class BotFrameworkAdapter context: TurnContext, connectionName?: string, userId?: string, - oAuthAppCredentials?: AppCredentials + oAuthAppCredentials?: AppCredentials, ): Promise { if (!context.activity.from || !context.activity.from.id) { throw new Error('BotFrameworkAdapter.signOutUser(): missing from or from.id'); @@ -858,14 +845,14 @@ export class BotFrameworkAdapter connectionName: string, oAuthAppCredentials?: AppCredentials, userId?: string, - finalRedirect?: string + finalRedirect?: string, ): Promise; async getSignInLink( context: TurnContext, connectionName: string, oAuthAppCredentials?: CoreAppCredentials, userId?: string, - finalRedirect?: string + finalRedirect?: string, ): Promise; /** * Asynchronously gets a sign-in link from the token server that can be sent as part @@ -883,11 +870,11 @@ export class BotFrameworkAdapter connectionName: string, oAuthAppCredentials?: AppCredentials, userId?: string, - finalRedirect?: string + finalRedirect?: string, ): Promise { if (userId && userId != context.activity.from.id) { throw new ReferenceError( - "cannot retrieve OAuth signin link for a user that's different from the conversation" + "cannot retrieve OAuth signin link for a user that's different from the conversation", ); } @@ -918,7 +905,6 @@ export class BotFrameworkAdapter * @param includeFilter Optional. A comma-separated list of connection's to include. If present, * the `includeFilter` parameter limits the tokens this method returns. * @param oAuthAppCredentials AppCredentials for OAuth. - * * @returns The [TokenStatus](xref:botframework-connector.TokenStatus) objects retrieved. */ async getTokenStatus(context: TurnContext, userId?: string, includeFilter?: string): Promise; @@ -926,7 +912,7 @@ export class BotFrameworkAdapter context: TurnContext, userId?: string, includeFilter?: string, - oAuthAppCredentials?: CoreAppCredentials + oAuthAppCredentials?: CoreAppCredentials, ): Promise; /** * Asynchronously retrieves the token status for each configured connection for the given user. @@ -937,14 +923,13 @@ export class BotFrameworkAdapter * @param includeFilter Optional. A comma-separated list of connection's to include. If present, * the `includeFilter` parameter limits the tokens this method returns. * @param oAuthAppCredentials Optional. [AppCredentials](xref:botframework-connector.AppCredentials) for OAuth. - * * @returns The [TokenStatus](xref:botframework-connector.TokenStatus) objects retrieved. */ async getTokenStatus( context: TurnContext, userId?: string, includeFilter?: string, - oAuthAppCredentials?: AppCredentials + oAuthAppCredentials?: AppCredentials, ): Promise { if (!userId && (!context.activity.from || !context.activity.from.id)) { throw new Error('BotFrameworkAdapter.getTokenStatus(): missing from or from.id'); @@ -970,19 +955,18 @@ export class BotFrameworkAdapter * @param connectionName The name of the auth connection to use. * @param resourceUrls The list of resource URLs to retrieve tokens for. * @param oAuthAppCredentials AppCredentials for OAuth. - * * @returns A map of the [TokenResponse](xref:botframework-schema.TokenResponse) objects by resource URL. */ async getAadTokens( context: TurnContext, connectionName: string, - resourceUrls: string[] + resourceUrls: string[], ): Promise<{ [propertyName: string]: TokenResponse }>; async getAadTokens( context: TurnContext, connectionName: string, resourceUrls: string[], - oAuthAppCredentials?: CoreAppCredentials + oAuthAppCredentials?: CoreAppCredentials, ): Promise<{ [propertyName: string]: TokenResponse }>; /** * Asynchronously signs out the user from the token server. @@ -991,14 +975,13 @@ export class BotFrameworkAdapter * @param connectionName The name of the auth connection to use. * @param resourceUrls The list of resource URLs to retrieve tokens for. * @param oAuthAppCredentials Optional. [AppCredentials](xref:botframework-connector.AppCredentials) for OAuth. - * * @returns A map of the [TokenResponse](xref:botframework-schema.TokenResponse) objects by resource URL. */ async getAadTokens( context: TurnContext, connectionName: string, resourceUrls: string[], - oAuthAppCredentials?: AppCredentials + oAuthAppCredentials?: AppCredentials, ): Promise<{ [propertyName: string]: TokenResponse }> { if (!context.activity.from || !context.activity.from.id) { throw new Error('BotFrameworkAdapter.getAadTokens(): missing from or from.id'); @@ -1014,7 +997,7 @@ export class BotFrameworkAdapter userId, connectionName, { resourceUrls: resourceUrls }, - { channelId: context.activity.channelId } + { channelId: context.activity.channelId }, ) )._response.parsedBody as { [propertyName: string]: TokenResponse }; } @@ -1034,7 +1017,7 @@ export class BotFrameworkAdapter connectionName: string, userId?: string, finalRedirect?: string, - appCredentials?: CoreAppCredentials + appCredentials?: CoreAppCredentials, ): Promise { if (!connectionName) { throw new Error('getUserToken() requires a connectionName but none was provided.'); @@ -1047,7 +1030,7 @@ export class BotFrameworkAdapter // The provided userId doesn't match the from.id on the activity. (same for finalRedirect) if (userId && context.activity.from.id !== userId) { throw new Error( - 'BotFrameworkAdapter.getSiginInResource(): cannot get signin resource for a user that is different from the conversation' + 'BotFrameworkAdapter.getSiginInResource(): cannot get signin resource for a user that is different from the conversation', ); } @@ -1082,7 +1065,7 @@ export class BotFrameworkAdapter connectionName: string, userId: string, tokenExchangeRequest: TokenExchangeRequest, - appCredentials?: CoreAppCredentials + appCredentials?: CoreAppCredentials, ): Promise; /** * Asynchronously Performs a token exchange operation such as for single sign-on. @@ -1099,7 +1082,7 @@ export class BotFrameworkAdapter connectionName: string, userId: string, tokenExchangeRequest: TokenExchangeRequest, - appCredentials?: AppCredentials + appCredentials?: AppCredentials, ): Promise { if (!connectionName) { throw new Error('exchangeToken() requires a connectionName but none was provided.'); @@ -1111,7 +1094,7 @@ export class BotFrameworkAdapter if (tokenExchangeRequest && !tokenExchangeRequest.token && !tokenExchangeRequest.uri) { throw new Error( - 'BotFrameworkAdapter.exchangeToken(): Either a Token or Uri property is required on the TokenExchangeRequest' + 'BotFrameworkAdapter.exchangeToken(): Either a Token or Uri property is required on the TokenExchangeRequest', ); } @@ -1123,7 +1106,7 @@ export class BotFrameworkAdapter userId, connectionName, context.activity.channelId, - tokenExchangeRequest + tokenExchangeRequest, ) )._response.parsedBody as TokenResponse; } @@ -1135,7 +1118,6 @@ export class BotFrameworkAdapter * * @param contextOrServiceUrl The URL of the emulator. * @param emulate `true` to send an emulated OAuth card to the emulator; or `false` to not send the card. - * * @remarks * When testing a bot in the Bot Framework Emulator, this method can emulate the OAuth card interaction. */ @@ -1151,7 +1133,6 @@ export class BotFrameworkAdapter * @param req An Express or Restify style request object. * @param res An Express or Restify style response object. * @param logic The function to call at the end of the middleware pipeline. - * * @remarks * This is the main way a bot receives incoming messages and defines a turn in the conversation. This method: * @@ -1198,7 +1179,7 @@ export class BotFrameworkAdapter async processActivity( req: WebRequest, res: WebResponse, - logic: (context: TurnContext) => Promise + logic: (context: TurnContext) => Promise, ): Promise { let body: any; let status: number; @@ -1292,7 +1273,6 @@ export class BotFrameworkAdapter * * @param activity The activity to process. * @param logic The function to call at the end of the middleware pipeline. - * * @remarks * This is the main way a bot receives incoming messages and defines a turn in the conversation. This method: * @@ -1342,9 +1322,7 @@ export class BotFrameworkAdapter * * @param context The context object for the turn. * @param activities The activities to send. - * * @returns An array of [ResourceResponse](xref:) - * * @remarks * The activities will be sent one after another in the order in which they're received. A * response object will be returned for each sent activity. For `message` activities this will @@ -1374,7 +1352,7 @@ export class BotFrameworkAdapter if (activity && BotFrameworkAdapter.isStreamingServiceUrl(activity.serviceUrl)) { if (!this.isStreamingConnectionOpen) { throw new Error( - 'BotFrameworkAdapter.sendActivities(): Unable to send activity as Streaming connection is closed.' + 'BotFrameworkAdapter.sendActivities(): Unable to send activity as Streaming connection is closed.', ); } TokenResolver.checkForOAuthCards(this, context, activity as Activity); @@ -1388,12 +1366,12 @@ export class BotFrameworkAdapter await client.conversations.replyToActivity( activity.conversation.id, activity.replyToId, - activity - ) + activity, + ), ); } else { responses.push( - await client.conversations.sendToConversation(activity.conversation.id, activity) + await client.conversations.sendToConversation(activity.conversation.id, activity), ); } break; @@ -1466,7 +1444,7 @@ export class BotFrameworkAdapter async createConnectorClientWithIdentity( serviceUrl: string, identity: ClaimsIdentity, - audience: string + audience: string, ): Promise; /** * Create a [ConnectorClient](xref:botbuilder-connector.ConnectorClient) with a [ClaimsIdentity](xref:botbuilder-connector.ClaimsIdentity). @@ -1482,7 +1460,7 @@ export class BotFrameworkAdapter async createConnectorClientWithIdentity( serviceUrl: string, identity: ClaimsIdentity, - audience?: string + audience?: string, ): Promise { if (!identity) { throw new Error('BotFrameworkAdapter.createConnectorClientWithIdentity(): invalid identity parameter.'); @@ -1506,7 +1484,7 @@ export class BotFrameworkAdapter // for a non-existent streaming connection results in an error if (!this.streamingServer) { throw new Error( - `Cannot create streaming connector client for serviceUrl ${serviceUrl} without a streaming connection. Call 'useWebSocket' or 'useNamedPipe' to start a streaming connection.` + `Cannot create streaming connector client for serviceUrl ${serviceUrl} without a streaming connection. Call 'useWebSocket' or 'useNamedPipe' to start a streaming connection.`, ); } @@ -1576,7 +1554,7 @@ export class BotFrameworkAdapter private getOrCreateConnectorClient( context: TurnContext, serviceUrl: string, - credentials: AppCredentials + credentials: AppCredentials, ): ConnectorClient { if (!context || !context.turnState) throw new Error('invalid context parameter'); if (!serviceUrl) throw new Error('invalid serviceUrl'); @@ -1596,7 +1574,6 @@ export class BotFrameworkAdapter * * @param botAppId The bot's AppId. * @param claims The [Claim](xref:botbuilder-connector.Claim) list to check. - * * @returns The current credentials' OAuthScope. */ private async getOAuthScope(botAppId: string, claims: Claim[]): Promise { @@ -1629,7 +1606,7 @@ export class BotFrameworkAdapter appId, this.settings.certificateThumbprint, this.settings.certificatePrivateKey, - this.settings.channelAuthTenant + this.settings.channelAuthTenant, ); } else { if (JwtTokenValidation.isGovernment(this.settings.channelService)) { @@ -1637,14 +1614,14 @@ export class BotFrameworkAdapter appId, appPassword, this.settings.channelAuthTenant, - oAuthScope + oAuthScope, ); } else { credentials = new MicrosoftAppCredentials( appId, appPassword, this.settings.channelAuthTenant, - oAuthScope + oAuthScope, ); } } @@ -1657,7 +1634,6 @@ export class BotFrameworkAdapter * * @param serviceUrl The client's service URL. * @param oAuthAppCredentials AppCredentials for OAuth. - * * @remarks * Override this in a derived class to create a mock OAuth API client for unit testing. */ @@ -1667,7 +1643,6 @@ export class BotFrameworkAdapter * * @param serviceUrl The client's service URL. * @param oAuthAppCredentials Optional. The [AppCredentials](xref:botframework-connector.AppCredentials)for OAuth. - * * @remarks * Override this in a derived class to create a mock OAuth API client for unit testing. * @returns The client. @@ -1711,7 +1686,7 @@ export class BotFrameworkAdapter authHeader, this.credentialsProvider, this.settings.channelService, - this.authConfiguration + this.authConfiguration, ); } @@ -1770,17 +1745,16 @@ export class BotFrameworkAdapter ? contextOrServiceUrl.activity.serviceUrl : contextOrServiceUrl : this.settings.oAuthEndpoint - ? this.settings.oAuthEndpoint - : JwtTokenValidation.isGovernment(this.settings.channelService) - ? US_GOV_OAUTH_ENDPOINT - : OAUTH_ENDPOINT; + ? this.settings.oAuthEndpoint + : JwtTokenValidation.isGovernment(this.settings.channelService) + ? US_GOV_OAUTH_ENDPOINT + : OAUTH_ENDPOINT; } /** * Checks the environment and can set a flag to emulate OAuth cards. * * @param context The context object for the turn. - * * @remarks * Override this in a derived class to control how OAuth cards are emulated for unit testing. */ @@ -1854,7 +1828,7 @@ export class BotFrameworkAdapter response.setBody( `Invalid verb received for ${request.verb.toLocaleLowerCase()}. Only GET and POST are accepted. Verb: ${ request.verb - }` + }`, ); return response; @@ -1915,7 +1889,7 @@ export class BotFrameworkAdapter req: Request, socket: INodeSocket, head: INodeBuffer, - logic: (context: TurnContext) => Promise + logic: (context: TurnContext) => Promise, ): Promise; /** @@ -1925,14 +1899,14 @@ export class BotFrameworkAdapter req: Request, resOrSocket: Response | INodeSocket, logicOrHead: ((context: TurnContext) => Promise) | INodeBuffer, - maybeLogic?: (context: TurnContext) => Promise + maybeLogic?: (context: TurnContext) => Promise, ): Promise { if (maybeLogic) { return this.useWebSocket( req, INodeSocketT.parse(resOrSocket), INodeBufferT.parse(logicOrHead), - LogicT.parse(maybeLogic) + LogicT.parse(maybeLogic), ); } else { return this.processActivity(req, ResponseT.parse(resOrSocket), LogicT.parse(logicOrHead)); @@ -1951,7 +1925,7 @@ export class BotFrameworkAdapter logic: (context: TurnContext) => Promise, pipeName = defaultPipeName, retryCount = 7, - onListen?: () => void + onListen?: () => void, ): Promise { if (!logic) { throw new Error('Bot logic needs to be provided to `useNamedPipe`'); @@ -1967,7 +1941,7 @@ export class BotFrameworkAdapter // Each BotFrameworkAdapter instance is scoped to a stream, so switching streams // results in dropped conversations that the bot cannot reconnect to. throw new Error( - 'This BotFrameworkAdapter instance is already connected to a different stream. Use a new instance to connect to the provided pipeName.' + 'This BotFrameworkAdapter instance is already connected to a different stream. Use a new instance to connect to the provided pipeName.', ); } } @@ -1989,7 +1963,7 @@ export class BotFrameworkAdapter req: WebRequest, socket: INodeSocket, head: INodeBuffer, - logic: (context: TurnContext) => Promise + logic: (context: TurnContext) => Promise, ): Promise { // Use the provided NodeWebSocketFactoryBase on BotFrameworkAdapter construction, // otherwise create a new NodeWebSocketFactory. @@ -2037,7 +2011,7 @@ export class BotFrameworkAdapter authHeader, this.credentialsProvider, channelService, - channelIdHeader + channelIdHeader, ); if (!claims.isAuthenticated) { @@ -2070,7 +2044,7 @@ export class BotFrameworkAdapter : await attachmentStream.readAsString(); return { contentType, content }; - }) + }), ); return activity; @@ -2078,7 +2052,7 @@ export class BotFrameworkAdapter private async handleVersionRequest( request: IReceiveRequest, - response: StreamingResponse + response: StreamingResponse, ): Promise { if (request.verb.toLocaleUpperCase() === GET) { response.statusCode = StatusCodes.OK; @@ -2105,7 +2079,7 @@ export class BotFrameworkAdapter } else { response.statusCode = StatusCodes.METHOD_NOT_ALLOWED; response.setBody( - `Invalid verb received for path: ${request.path}. Only GET is accepted. Verb: ${request.verb}` + `Invalid verb received for path: ${request.path}. Only GET is accepted. Verb: ${request.verb}`, ); } @@ -2115,8 +2089,8 @@ export class BotFrameworkAdapter /** * Determine if the serviceUrl was sent via an Http/Https connection or Streaming * This can be determined by looking at the ServiceUrl property: - * (1) All channels that send messages via http/https are not streaming - * (2) Channels that send messages via streaming have a ServiceUrl that does not begin with http/https. + * (1) All channels that send messages via http/https are not streaming + * (2) Channels that send messages via streaming have a ServiceUrl that does not begin with http/https. * * @param serviceUrl the serviceUrl provided in the resquest. * @returns True if the serviceUrl is a streaming url, otherwise false. @@ -2169,11 +2143,13 @@ function abortWebSocketUpgrade(socket: INodeSocket, err: any): void { const connectionHeader = "Connection: 'close'\r\n"; let message = ''; - AuthenticationError.isStatusCodeError(err) - ? (message = `HTTP/1.1 ${err.statusCode} ${StatusCodes[err.statusCode]}\r\n${ - err.message - }\r\n${connectionHeader}\r\n`) - : (message = AuthenticationError.determineStatusCodeAndBuildMessage(err)); + if (AuthenticationError.isStatusCodeError(err)) { + message = `HTTP/1.1 ${err.statusCode} ${StatusCodes[err.statusCode]}\r\n${ + err.message + }\r\n${connectionHeader}\r\n`; + } else { + message = AuthenticationError.determineStatusCodeAndBuildMessage(err); + } socket.write(message); } diff --git a/libraries/botbuilder/src/botFrameworkHttpAdapter.ts b/libraries/botbuilder/src/botFrameworkHttpAdapter.ts index 5e174b67db..25b949f6fb 100644 --- a/libraries/botbuilder/src/botFrameworkHttpAdapter.ts +++ b/libraries/botbuilder/src/botFrameworkHttpAdapter.ts @@ -24,7 +24,7 @@ export interface BotFrameworkHttpAdapter { req: Request, socket: INodeSocket, head: INodeBuffer, - logic: (context: TurnContext) => Promise + logic: (context: TurnContext) => Promise, ): Promise; /** @@ -35,6 +35,6 @@ export interface BotFrameworkHttpAdapter { req: Request, socket: INodeDuplex, head: INodeBuffer, - logic: (context: TurnContext) => Promise + logic: (context: TurnContext) => Promise, ): Promise; } diff --git a/libraries/botbuilder/src/botFrameworkHttpClient.ts b/libraries/botbuilder/src/botFrameworkHttpClient.ts index 1586cf64f5..dbcf196cb3 100644 --- a/libraries/botbuilder/src/botFrameworkHttpClient.ts +++ b/libraries/botbuilder/src/botFrameworkHttpClient.ts @@ -69,12 +69,12 @@ export class BotFrameworkHttpClient implements BotFrameworkClient { toUrl: string, serviceUrl: string, conversationId: string, - activity: Activity + activity: Activity, ): Promise> { const appCredentials = await this.getAppCredentials(fromBotId, toBotId); if (!appCredentials) { throw new Error( - 'BotFrameworkHttpClient.postActivity(): Unable to get appCredentials to connect to the skill' + 'BotFrameworkHttpClient.postActivity(): Unable to get appCredentials to connect to the skill', ); } @@ -152,7 +152,6 @@ export class BotFrameworkHttpClient implements BotFrameworkClient { * * @param appId The application id. * @param oAuthScope Optional. The OAuth scope. - * * @returns The app credentials to be used to acquire tokens. */ protected async buildCredentials(appId: string, oAuthScope?: string): Promise { diff --git a/libraries/botbuilder/src/channelServiceHandler.ts b/libraries/botbuilder/src/channelServiceHandler.ts index 1cf75ce0ff..d58d6bc9f4 100644 --- a/libraries/botbuilder/src/channelServiceHandler.ts +++ b/libraries/botbuilder/src/channelServiceHandler.ts @@ -30,7 +30,7 @@ export class ChannelServiceHandler extends ChannelServiceHandlerBase { constructor( private readonly credentialProvider: ICredentialProvider, private readonly authConfig: AuthenticationConfiguration, - protected readonly channelService = process.env[AuthenticationConstants.ChannelService] + protected readonly channelService = process.env[AuthenticationConstants.ChannelService], ) { super(); @@ -62,7 +62,7 @@ export class ChannelServiceHandler extends ChannelServiceHandlerBase { this.channelService, 'unknown', undefined, - this.authConfig + this.authConfig, ); } } diff --git a/libraries/botbuilder/src/channelServiceHandlerBase.ts b/libraries/botbuilder/src/channelServiceHandlerBase.ts index 02a91a8537..575897edd9 100644 --- a/libraries/botbuilder/src/channelServiceHandlerBase.ts +++ b/libraries/botbuilder/src/channelServiceHandlerBase.ts @@ -34,7 +34,7 @@ export abstract class ChannelServiceHandlerBase { async handleSendToConversation( authHeader: string, conversationId: string, - activity: Activity + activity: Activity, ): Promise { const claimsIdentity = await this.authenticate(authHeader); return this.onSendToConversation(claimsIdentity, conversationId, activity); @@ -53,7 +53,7 @@ export abstract class ChannelServiceHandlerBase { authHeader: string, conversationId: string, activityId: string, - activity: Activity + activity: Activity, ): Promise { const claimsIdentity = await this.authenticate(authHeader); return this.onReplyToActivity(claimsIdentity, conversationId, activityId, activity); @@ -72,7 +72,7 @@ export abstract class ChannelServiceHandlerBase { authHeader: string, conversationId: string, activityId: string, - activity: Activity + activity: Activity, ): Promise { const claimsIdentity = await this.authenticate(authHeader); return this.onUpdateActivity(claimsIdentity, conversationId, activityId, activity); @@ -101,7 +101,7 @@ export abstract class ChannelServiceHandlerBase { async handleGetActivityMembers( authHeader: string, conversationId: string, - activityId: string + activityId: string, ): Promise { const claimsIdentity = await this.authenticate(authHeader); return this.onGetActivityMembers(claimsIdentity, conversationId, activityId); @@ -116,7 +116,7 @@ export abstract class ChannelServiceHandlerBase { */ async handleCreateConversation( authHeader: string, - parameters: ConversationParameters + parameters: ConversationParameters, ): Promise { const claimsIdentity = await this.authenticate(authHeader); return this.onCreateConversation(claimsIdentity, parameters); @@ -133,7 +133,7 @@ export abstract class ChannelServiceHandlerBase { async handleGetConversations( authHeader: string, conversationId: string, - continuationToken?: string /* some default */ + continuationToken?: string /* some default */, ): Promise { const claimsIdentity = await this.authenticate(authHeader); return this.onGetConversations(claimsIdentity, conversationId, continuationToken); @@ -162,7 +162,7 @@ export abstract class ChannelServiceHandlerBase { async handleGetConversationMember( authHeader: string, userId: string, - conversationId: string + conversationId: string, ): Promise { const claimsIdentity = await this.authenticate(authHeader); return this.onGetConversationMember(claimsIdentity, userId, conversationId); @@ -181,7 +181,7 @@ export abstract class ChannelServiceHandlerBase { authHeader: string, conversationId: string, pageSize = -1, - continuationToken?: string + continuationToken?: string, ): Promise { const claimsIdentity = await this.authenticate(authHeader); return this.onGetConversationPagedMembers(claimsIdentity, conversationId, pageSize, continuationToken); @@ -210,7 +210,7 @@ export abstract class ChannelServiceHandlerBase { async handleSendConversationHistory( authHeader: string, conversationId: string, - transcript: Transcript + transcript: Transcript, ): Promise { const claimsIdentity = await this.authenticate(authHeader); return this.onSendConversationHistory(claimsIdentity, conversationId, transcript); @@ -227,7 +227,7 @@ export abstract class ChannelServiceHandlerBase { async handleUploadAttachment( authHeader: string, conversationId: string, - attachmentUpload: AttachmentData + attachmentUpload: AttachmentData, ): Promise { const claimsIdentity = await this.authenticate(authHeader); return this.onUploadAttachment(claimsIdentity, conversationId, attachmentUpload); @@ -239,9 +239,9 @@ export abstract class ChannelServiceHandlerBase { * @remarks * This method allows you to send an activity to the end of a conversation. * This is slightly different from ReplyToActivity(). - * * SendToConversation(conversationId) - will append the activity to the end + * SendToConversation(conversationId) - will append the activity to the end * of the conversation according to the timestamp or semantics of the channel. - * * ReplyToActivity(conversationId,ActivityId) - adds the activity as a reply + * ReplyToActivity(conversationId,ActivityId) - adds the activity as a reply * to another activity, if the channel supports it. If the channel does not * support nested replies, ReplyToActivity falls back to SendToConversation. * @@ -256,13 +256,13 @@ export abstract class ChannelServiceHandlerBase { protected async onSendToConversation( _claimsIdentity: ClaimsIdentity, _conversationId: string, - _activity: Activity + _activity: Activity, ): Promise { throw new StatusCodeError( StatusCodes.NOT_IMPLEMENTED, `ChannelServiceHandler.onSendToConversation(): ${StatusCodes.NOT_IMPLEMENTED}: ${ STATUS_CODES[StatusCodes.NOT_IMPLEMENTED] - }` + }`, ); } @@ -273,9 +273,9 @@ export abstract class ChannelServiceHandlerBase { * This method allows you to reply to an activity. * * This is slightly different from SendToConversation(). - * * SendToConversation(conversationId) - will append the activity to the end + * SendToConversation(conversationId) - will append the activity to the end * of the conversation according to the timestamp or semantics of the channel. - * * ReplyToActivity(conversationId,ActivityId) - adds the activity as a reply + * ReplyToActivity(conversationId,ActivityId) - adds the activity as a reply * to another activity, if the channel supports it. If the channel does not * support nested replies, ReplyToActivity falls back to SendToConversation. * @@ -292,13 +292,13 @@ export abstract class ChannelServiceHandlerBase { _claimsIdentity: ClaimsIdentity, _conversationId: string, _activityId: string, - _activity: Activity + _activity: Activity, ): Promise { throw new StatusCodeError( StatusCodes.NOT_IMPLEMENTED, `ChannelServiceHandler.onReplyToActivity(): ${StatusCodes.NOT_IMPLEMENTED}: ${ STATUS_CODES[StatusCodes.NOT_IMPLEMENTED] - }` + }`, ); } @@ -321,13 +321,13 @@ export abstract class ChannelServiceHandlerBase { _claimsIdentity: ClaimsIdentity, _conversationId: string, _activityId: string, - _activity: Activity + _activity: Activity, ): Promise { throw new StatusCodeError( StatusCodes.NOT_IMPLEMENTED, `ChannelServiceHandler.onUpdateActivity(): ${StatusCodes.NOT_IMPLEMENTED}: ${ STATUS_CODES[StatusCodes.NOT_IMPLEMENTED] - }` + }`, ); } @@ -339,8 +339,6 @@ export abstract class ChannelServiceHandlerBase { * * Some channels allow you to delete an existing activity, and if successful * this method will remove the specified activity. - * - * * @param _claimsIdentity ClaimsIdentity for the bot, should have AudienceClaim, AppIdClaim and ServiceUrlClaim. * @param _conversationId Conversation ID. * @param _activityId activityId to delete. @@ -348,13 +346,13 @@ export abstract class ChannelServiceHandlerBase { protected async onDeleteActivity( _claimsIdentity: ClaimsIdentity, _conversationId: string, - _activityId: string + _activityId: string, ): Promise { throw new StatusCodeError( StatusCodes.NOT_IMPLEMENTED, `ChannelServiceHandler.onDeleteActivity(): ${StatusCodes.NOT_IMPLEMENTED}: ${ STATUS_CODES[StatusCodes.NOT_IMPLEMENTED] - }` + }`, ); } @@ -374,13 +372,13 @@ export abstract class ChannelServiceHandlerBase { protected async onGetActivityMembers( _claimsIdentity: ClaimsIdentity, _conversationId: string, - _activityId: string + _activityId: string, ): Promise { throw new StatusCodeError( StatusCodes.NOT_IMPLEMENTED, `ChannelServiceHandler.onGetActivityMembers(): ${StatusCodes.NOT_IMPLEMENTED}: ${ STATUS_CODES[StatusCodes.NOT_IMPLEMENTED] - }` + }`, ); } @@ -391,28 +389,27 @@ export abstract class ChannelServiceHandlerBase { * Create a new Conversation. * * POST to this method with a - * * Bot being the bot creating the conversation - * * IsGroup set to true if this is not a direct message (default is false) - * * Array containing the members to include in the conversation + * Bot being the bot creating the conversation + * IsGroup set to true if this is not a direct message (default is false) + * Array containing the members to include in the conversation * * The return value is a ResourceResponse which contains a conversation id * which is suitable for use in the message payload and REST API uris. * * Most channels only support the semantics of bots initiating a direct * message conversation. - * * @param _claimsIdentity ClaimsIdentity for the bot, should have AudienceClaim, AppIdClaim and ServiceUrlClaim. * @param _parameters Parameters to create the conversation from. */ protected async onCreateConversation( _claimsIdentity: ClaimsIdentity, - _parameters: ConversationParameters + _parameters: ConversationParameters, ): Promise { throw new StatusCodeError( StatusCodes.NOT_IMPLEMENTED, `ChannelServiceHandler.onCreateConversation(): ${StatusCodes.NOT_IMPLEMENTED}: ${ STATUS_CODES[StatusCodes.NOT_IMPLEMENTED] - }` + }`, ); } @@ -431,7 +428,6 @@ export abstract class ChannelServiceHandlerBase { * * Each ConversationMembers object contains the ID of the conversation and an * array of ChannelAccounts that describe the members of the conversation. - * * @param _claimsIdentity ClaimsIdentity for the bot, should have AudienceClaim, AppIdClaim and ServiceUrlClaim. * @param _conversationId Conversation ID. * @param _continuationToken Skip or continuation token. @@ -439,13 +435,13 @@ export abstract class ChannelServiceHandlerBase { protected async onGetConversations( _claimsIdentity: ClaimsIdentity, _conversationId: string, - _continuationToken?: string + _continuationToken?: string, ): Promise { throw new StatusCodeError( StatusCodes.NOT_IMPLEMENTED, `ChannelServiceHandler.onGetConversations(): ${StatusCodes.NOT_IMPLEMENTED}: ${ STATUS_CODES[StatusCodes.NOT_IMPLEMENTED] - }` + }`, ); } @@ -462,13 +458,13 @@ export abstract class ChannelServiceHandlerBase { */ protected async onGetConversationMembers( _claimsIdentity: ClaimsIdentity, - _conversationId: string + _conversationId: string, ): Promise { throw new StatusCodeError( StatusCodes.NOT_IMPLEMENTED, `ChannelServiceHandler.onGetConversationMembers(): ${StatusCodes.NOT_IMPLEMENTED}: ${ STATUS_CODES[StatusCodes.NOT_IMPLEMENTED] - }` + }`, ); } @@ -487,13 +483,13 @@ export abstract class ChannelServiceHandlerBase { protected async onGetConversationMember( _claimsIdentity: ClaimsIdentity, _userId: string, - _conversationId: string + _conversationId: string, ): Promise { throw new StatusCodeError( StatusCodes.NOT_IMPLEMENTED, `ChannelServiceHandler.onGetConversationMember(): ${StatusCodes.NOT_IMPLEMENTED}: ${ STATUS_CODES[StatusCodes.NOT_IMPLEMENTED] - }` + }`, ); } @@ -527,13 +523,13 @@ export abstract class ChannelServiceHandlerBase { _claimsIdentity: ClaimsIdentity, _conversationId: string, _pageSize = -1, - _continuationToken?: string + _continuationToken?: string, ): Promise { throw new StatusCodeError( StatusCodes.NOT_IMPLEMENTED, `ChannelServiceHandler.onGetConversationPagedMembers(): ${StatusCodes.NOT_IMPLEMENTED}: ${ STATUS_CODES[StatusCodes.NOT_IMPLEMENTED] - }` + }`, ); } @@ -553,13 +549,13 @@ export abstract class ChannelServiceHandlerBase { protected async onDeleteConversationMember( _claimsIdentity: ClaimsIdentity, _conversationId: string, - _memberId: string + _memberId: string, ): Promise { throw new StatusCodeError( StatusCodes.NOT_IMPLEMENTED, `ChannelServiceHandler.onDeleteConversationMember(): ${StatusCodes.NOT_IMPLEMENTED}: ${ STATUS_CODES[StatusCodes.NOT_IMPLEMENTED] - }` + }`, ); } @@ -581,13 +577,13 @@ export abstract class ChannelServiceHandlerBase { protected async onSendConversationHistory( _claimsIdentity: ClaimsIdentity, _conversationId: string, - _transcript: Transcript + _transcript: Transcript, ): Promise { throw new StatusCodeError( StatusCodes.NOT_IMPLEMENTED, `ChannelServiceHandler.onSendConversationHistory(): ${StatusCodes.NOT_IMPLEMENTED}: ${ STATUS_CODES[StatusCodes.NOT_IMPLEMENTED] - }` + }`, ); } @@ -609,13 +605,13 @@ export abstract class ChannelServiceHandlerBase { protected async onUploadAttachment( _claimsIdentity: ClaimsIdentity, _conversationId: string, - _attachmentUpload: AttachmentData + _attachmentUpload: AttachmentData, ): Promise { throw new StatusCodeError( StatusCodes.NOT_IMPLEMENTED, `ChannelServiceHandler.onUploadAttachment(): ${StatusCodes.NOT_IMPLEMENTED}: ${ STATUS_CODES[StatusCodes.NOT_IMPLEMENTED] - }` + }`, ); } diff --git a/libraries/botbuilder/src/channelServiceRoutes.ts b/libraries/botbuilder/src/channelServiceRoutes.ts index b2c597a543..63793d1f49 100644 --- a/libraries/botbuilder/src/channelServiceRoutes.ts +++ b/libraries/botbuilder/src/channelServiceRoutes.ts @@ -58,7 +58,7 @@ export class ChannelServiceRoutes { server.get(basePath + RouteConstants.ConversationMember, this.processGetConversationMember.bind(this)); server.get( basePath + RouteConstants.ConversationPagedMembers, - this.processGetConversationPagedMembers.bind(this) + this.processGetConversationPagedMembers.bind(this), ); server.post(basePath + RouteConstants.ConversationHistory, this.processSendConversationHistory.bind(this)); server.post(basePath + RouteConstants.Attachments, this.processUploadAttachment.bind(this)); @@ -68,7 +68,7 @@ export class ChannelServiceRoutes { if (typeof server.delete === 'function') { server.delete( basePath + RouteConstants.ConversationMember, - this.processDeleteConversationMember.bind(this) + this.processDeleteConversationMember.bind(this), ); server.delete(basePath + RouteConstants.Activity, this.processDeleteActivity.bind(this)); } else if (typeof server.del === 'function') { @@ -80,7 +80,7 @@ export class ChannelServiceRoutes { /** * @private */ - private processSendToConversation(req: WebRequest, res: WebResponse, next: Function): void { + private processSendToConversation(req: WebRequest, res: WebResponse, next: () => void): void { const authHeader = req.headers.authorization || req.headers.Authorization || ''; ChannelServiceRoutes.readActivity(req) .then((activity) => { @@ -106,7 +106,7 @@ export class ChannelServiceRoutes { /** * @private */ - private processReplyToActivity(req: WebRequest, res: WebResponse, next: Function): void { + private processReplyToActivity(req: WebRequest, res: WebResponse, next: () => void): void { const authHeader = req.headers.authorization || req.headers.Authorization || ''; ChannelServiceRoutes.readActivity(req) .then((activity) => { @@ -132,7 +132,7 @@ export class ChannelServiceRoutes { /** * @private */ - private processUpdateActivity(req: WebRequest, res: WebResponse, next: Function): void { + private processUpdateActivity(req: WebRequest, res: WebResponse, next: () => void): void { const authHeader = req.headers.authorization || req.headers.Authorization || ''; ChannelServiceRoutes.readActivity(req) .then((activity) => { @@ -158,7 +158,7 @@ export class ChannelServiceRoutes { /** * @private */ - private processDeleteActivity(req: WebRequest, res: WebResponse, next: Function): void { + private processDeleteActivity(req: WebRequest, res: WebResponse, next: () => void): void { const authHeader = req.headers.authorization || req.headers.Authorization || ''; this.channelServiceHandler .handleDeleteActivity(authHeader, req.params.conversationId, req.params.activityId) @@ -175,7 +175,7 @@ export class ChannelServiceRoutes { /** * @private */ - private processGetActivityMembers(req: WebRequest, res: WebResponse, next: Function): void { + private processGetActivityMembers(req: WebRequest, res: WebResponse, next: () => void): void { const authHeader = req.headers.authorization || req.headers.Authorization || ''; this.channelServiceHandler .handleGetActivityMembers(authHeader, req.params.conversationId, req.params.activityId) @@ -195,7 +195,7 @@ export class ChannelServiceRoutes { /** * @private */ - private processCreateConversation(req: WebRequest, res: WebResponse, next: Function): void { + private processCreateConversation(req: WebRequest, res: WebResponse, next: () => void): void { const authHeader = req.headers.authorization || req.headers.Authorization || ''; ChannelServiceRoutes.readBody(req).then((conversationParameters) => { this.channelServiceHandler @@ -217,7 +217,7 @@ export class ChannelServiceRoutes { /** * @private */ - private processGetConversations(req: WebRequest, res: WebResponse, next: Function): void { + private processGetConversations(req: WebRequest, res: WebResponse, next: () => void): void { const authHeader = req.headers.authorization || req.headers.Authorization || ''; this.channelServiceHandler .handleGetConversations(authHeader, req.params.conversationId, req.query.continuationToken) @@ -237,7 +237,7 @@ export class ChannelServiceRoutes { /** * @private */ - private processGetConversationMembers(req: WebRequest, res: WebResponse, next: Function): void { + private processGetConversationMembers(req: WebRequest, res: WebResponse, next: () => void): void { const authHeader = req.headers.authorization || req.headers.Authorization || ''; this.channelServiceHandler .handleGetConversationMembers(authHeader, req.params.conversationId) @@ -257,7 +257,7 @@ export class ChannelServiceRoutes { /** * @private */ - private processGetConversationMember(req: WebRequest, res: WebResponse, next: Function): void { + private processGetConversationMember(req: WebRequest, res: WebResponse, next: () => void): void { const authHeader = req.headers.authorization || req.headers.Authorization || ''; this.channelServiceHandler .handleGetConversationMember(authHeader, req.params.memberId, req.params.conversationId) @@ -277,7 +277,7 @@ export class ChannelServiceRoutes { /** * @private */ - private processGetConversationPagedMembers(req: WebRequest, res: WebResponse, next: Function): void { + private processGetConversationPagedMembers(req: WebRequest, res: WebResponse, next: () => void): void { const authHeader = req.headers.authorization || req.headers.Authorization || ''; let pageSize = parseInt(req.query.pageSize); if (isNaN(pageSize)) { @@ -288,7 +288,7 @@ export class ChannelServiceRoutes { authHeader, req.params.conversationId, pageSize, - req.query.continuationToken + req.query.continuationToken, ) .then((pagedMembersResult) => { res.status(200); @@ -306,7 +306,7 @@ export class ChannelServiceRoutes { /** * @private */ - private processDeleteConversationMember(req: WebRequest, res: WebResponse, next: Function): void { + private processDeleteConversationMember(req: WebRequest, res: WebResponse, next: () => void): void { const authHeader = req.headers.authorization || req.headers.Authorization || ''; this.channelServiceHandler .handleDeleteConversationMember(authHeader, req.params.conversationId, req.params.memberId) @@ -323,7 +323,7 @@ export class ChannelServiceRoutes { /** * @private */ - private processSendConversationHistory(req: WebRequest, res: WebResponse, next: Function): void { + private processSendConversationHistory(req: WebRequest, res: WebResponse, next: () => void): void { const authHeader = req.headers.authorization || req.headers.Authorization || ''; ChannelServiceRoutes.readBody(req) .then((transcript) => { @@ -349,7 +349,7 @@ export class ChannelServiceRoutes { /** * @private */ - private processUploadAttachment(req: WebRequest, res: WebResponse, next: Function): void { + private processUploadAttachment(req: WebRequest, res: WebResponse, next: () => void): void { const authHeader = req.headers.authorization || req.headers.Authorization || ''; ChannelServiceRoutes.readBody(req) .then((attachmentData) => { diff --git a/libraries/botbuilder/src/cloudAdapter.ts b/libraries/botbuilder/src/cloudAdapter.ts index c914aa8f93..7cbd4230bb 100644 --- a/libraries/botbuilder/src/cloudAdapter.ts +++ b/libraries/botbuilder/src/cloudAdapter.ts @@ -78,7 +78,7 @@ export class CloudAdapter extends CloudAdapterBase implements BotFrameworkHttpAd req: Request, socket: INodeSocket, head: INodeBuffer, - logic: (context: TurnContext) => Promise + logic: (context: TurnContext) => Promise, ): Promise; /** @@ -95,7 +95,7 @@ export class CloudAdapter extends CloudAdapterBase implements BotFrameworkHttpAd req: Request, socket: INodeDuplex, head: INodeBuffer, - logic: (context: TurnContext) => Promise + logic: (context: TurnContext) => Promise, ): Promise; /** @@ -105,7 +105,7 @@ export class CloudAdapter extends CloudAdapterBase implements BotFrameworkHttpAd req: Request, resOrSocket: Response | INodeSocket | INodeDuplex, logicOrHead: ((context: TurnContext) => Promise) | INodeBuffer, - maybeLogic?: (context: TurnContext) => Promise + maybeLogic?: (context: TurnContext) => Promise, ): Promise { // Early return with web socket handler if function invocation matches that signature if (maybeLogic) { @@ -139,7 +139,7 @@ export class CloudAdapter extends CloudAdapterBase implements BotFrameworkHttpAd if (!z.record(z.unknown()).safeParse(req.body).success) { return end( StatusCodes.BAD_REQUEST, - '`req.body` not an object, make sure you are using middleware to parse incoming requests.' + '`req.body` not an object, make sure you are using middleware to parse incoming requests.', ); } @@ -158,7 +158,7 @@ export class CloudAdapter extends CloudAdapterBase implements BotFrameworkHttpAd console.error(err); return end( err instanceof AuthenticationError ? StatusCodes.UNAUTHORIZED : StatusCodes.INTERNAL_SERVER_ERROR, - err.message ?? err + err.message ?? err, ); } } @@ -174,12 +174,10 @@ export class CloudAdapter extends CloudAdapterBase implements BotFrameworkHttpAd async processActivityDirect( authorization: string | AuthenticateRequestResult, activity: Activity, - logic: (context: TurnContext) => Promise + logic: (context: TurnContext) => Promise, ): Promise { try { - typeof authorization === 'string' - ? await this.processActivity(authorization, activity, logic) - : await this.processActivity(authorization, activity, logic); + await this.processActivity(authorization as any, activity, logic); } catch (err) { throw new Error(`CloudAdapter.processActivityDirect(): ERROR\n ${err.stack}`); } @@ -201,7 +199,7 @@ export class CloudAdapter extends CloudAdapterBase implements BotFrameworkHttpAd appId: string, audience: string, callerId?: string, - retryCount = 7 + retryCount = 7, ): Promise { z.object({ pipeName: z.string(), @@ -221,7 +219,7 @@ export class CloudAdapter extends CloudAdapterBase implements BotFrameworkHttpAd // Creat request handler const requestHandler = new StreamingRequestHandler( authenticateRequestResult, - (authenticateRequestResult, activity) => this.processActivity(authenticateRequestResult, activity, logic) + (authenticateRequestResult, activity) => this.processActivity(authenticateRequestResult, activity, logic), ); // Create server @@ -238,7 +236,7 @@ export class CloudAdapter extends CloudAdapterBase implements BotFrameworkHttpAd req: Request, socket: INodeSocket, head: INodeBuffer, - logic: (context: TurnContext) => Promise + logic: (context: TurnContext) => Promise, ): Promise { // Grab the auth header from the inbound http request const authHeader = z.string().parse(req.headers.Authorization ?? req.headers.authorization ?? ''); @@ -249,19 +247,19 @@ export class CloudAdapter extends CloudAdapterBase implements BotFrameworkHttpAd // Authenticate inbound request const authenticateRequestResult = await this.botFrameworkAuthentication.authenticateStreamingRequest( authHeader, - channelIdHeader + channelIdHeader, ); // Creat request handler const requestHandler = new StreamingRequestHandler( authenticateRequestResult, - (authenticateRequestResult, activity) => this.processActivity(authenticateRequestResult, activity, logic) + (authenticateRequestResult, activity) => this.processActivity(authenticateRequestResult, activity, logic), ); // Create server const server = new WebSocketServer( await new NodeWebSocketFactory().createWebSocket(req, socket, head), - requestHandler + requestHandler, ); // Attach server to request handler @@ -284,8 +282,8 @@ class StreamingRequestHandler extends RequestHandler { private readonly authenticateRequestResult: AuthenticateRequestResult, private readonly processActivity: ( authenticateRequestResult: AuthenticateRequestResult, - activity: Activity - ) => Promise + activity: Activity, + ) => Promise, ) { super(); @@ -311,14 +309,14 @@ class StreamingRequestHandler extends RequestHandler { if (!request.verb || !request.path) { return end( StatusCodes.BAD_REQUEST, - `Request missing verb and/or path. Verb: ${request.verb}, Path: ${request.path}` + `Request missing verb and/or path. Verb: ${request.verb}, Path: ${request.path}`, ); } if (request.verb.toUpperCase() !== POST && request.verb.toUpperCase() !== GET) { return end( StatusCodes.METHOD_NOT_ALLOWED, - `Invalid verb received. Only GET and POST are accepted. Verb: ${request.verb}` + `Invalid verb received. Only GET and POST are accepted. Verb: ${request.verb}`, ); } @@ -328,7 +326,7 @@ class StreamingRequestHandler extends RequestHandler { } else { return end( StatusCodes.METHOD_NOT_ALLOWED, - `Invalid verb received for path: ${request.path}. Only GET is accepted. Verb: ${request.verb}` + `Invalid verb received for path: ${request.path}. Only GET is accepted. Verb: ${request.verb}`, ); } } @@ -349,7 +347,7 @@ class StreamingRequestHandler extends RequestHandler { : await attachmentStream.readAsString(); return { contentType, content }; - }) + }), ); } catch (err) { return end(StatusCodes.BAD_REQUEST, `Request body missing or malformed: ${err}`); @@ -377,7 +375,7 @@ class StreamingConnectorFactory implements ConnectorFactory { if (serviceUrl !== this.serviceUrl) { throw new Error( - 'This is a streaming scenario, all connectors from this factory must all be for the same url.' + 'This is a streaming scenario, all connectors from this factory must all be for the same url.', ); } @@ -411,7 +409,7 @@ class StreamingHttpClient implements HttpClient { private async createHttpResponse( receiveResponse: IReceiveResponse, - httpRequest: WebResource + httpRequest: WebResource, ): Promise { const [bodyAsText] = (await Promise.all(receiveResponse.streams?.map((stream) => stream.readAsString()) ?? [])) ?? []; diff --git a/libraries/botbuilder/src/eventFactory.ts b/libraries/botbuilder/src/eventFactory.ts index e73380ea68..9e0ba5a5f7 100644 --- a/libraries/botbuilder/src/eventFactory.ts +++ b/libraries/botbuilder/src/eventFactory.ts @@ -33,7 +33,7 @@ export class EventFactory { static createHandoffInitiation( context: TurnContext, handoffContext: T, - transcript?: Transcript + transcript?: Transcript, ): Activity { if (!context) { throw new TypeError('EventFactory.createHandoffInitiation(): Missing context.'); @@ -42,7 +42,7 @@ export class EventFactory { const handoffEvent = this.createHandoffEvent( HandoffEventNames.InitiateHandoff, handoffContext, - context.activity.conversation + context.activity.conversation, ); handoffEvent.from = context.activity.from; @@ -89,7 +89,7 @@ export class EventFactory { private static createHandoffEvent( name: string, value: T, - conversation: ConversationAccount + conversation: ConversationAccount, ): Activity { const handoffEvent: Partial = { type: ActivityTypes.Event }; diff --git a/libraries/botbuilder/src/fileTranscriptStore.ts b/libraries/botbuilder/src/fileTranscriptStore.ts index f57a8de62f..864a8f977c 100644 --- a/libraries/botbuilder/src/fileTranscriptStore.ts +++ b/libraries/botbuilder/src/fileTranscriptStore.ts @@ -142,7 +142,7 @@ export class FileTranscriptStore implements TranscriptStore { channelId: string, conversationId: string, continuationToken?: string, - startDate?: Date + startDate?: Date, ): Promise> { if (!channelId) { throw new Error('Missing channelId'); @@ -160,10 +160,12 @@ export class FileTranscriptStore implements TranscriptStore { return pagedResult; } + //eslint-disable-next-line security/detect-non-literal-fs-filename const transcriptFolderContents = await readdir(transcriptFolder); const include = includeWhen((fileName) => !continuationToken || parse(fileName).name === continuationToken); const items = transcriptFolderContents.filter( - (transcript) => transcript.endsWith('.json') && withDateFilter(startDate, transcript) && include(transcript) + (transcript) => + transcript.endsWith('.json') && withDateFilter(startDate, transcript) && include(transcript), ); pagedResult.items = await Promise.all( @@ -171,9 +173,10 @@ export class FileTranscriptStore implements TranscriptStore { .slice(0, FileTranscriptStore.PageSize) .sort() .map(async (activityFilename) => { + //eslint-disable-next-line security/detect-non-literal-fs-filename const json = await readFile(join(transcriptFolder, activityFilename), 'utf8'); return parseActivity(json); - }) + }), ); const { length } = pagedResult.items; if (length === FileTranscriptStore.PageSize && items[length]) { @@ -201,6 +204,8 @@ export class FileTranscriptStore implements TranscriptStore { if (!exists) { return pagedResult; } + + //eslint-disable-next-line security/detect-non-literal-fs-filename const channels = await readdir(channelFolder); const items = channels.filter(includeWhen((di) => !continuationToken || di === continuationToken)); pagedResult.items = items @@ -250,6 +255,7 @@ export class FileTranscriptStore implements TranscriptStore { if (!exists) { await mkdirp(transcriptPath); } + //eslint-disable-next-line security/detect-non-literal-fs-filename return writeFile(join(transcriptPath, activityFilename), json, 'utf8'); } diff --git a/libraries/botbuilder/src/inspectionMiddleware.ts b/libraries/botbuilder/src/inspectionMiddleware.ts index 4fed361e04..0cd579f257 100644 --- a/libraries/botbuilder/src/inspectionMiddleware.ts +++ b/libraries/botbuilder/src/inspectionMiddleware.ts @@ -90,7 +90,7 @@ abstract class InterceptionMiddleware implements Middleware { async onTurn(turnContext: TurnContext, next: () => Promise): Promise { const { shouldForwardToApplication, shouldIntercept } = await this.invokeInbound( turnContext, - TraceActivity.fromActivity(turnContext.activity, 'ReceivedActivity', 'Received Activity') + TraceActivity.fromActivity(turnContext.activity, 'ReceivedActivity', 'Received Activity'), ); if (shouldIntercept) { @@ -168,7 +168,6 @@ abstract class InterceptionMiddleware implements Middleware { * * @remarks * InspectionMiddleware for emulator inspection of runtime Activities and BotState. - * * @deprecated This class will be removed in a future version of the framework. */ export class InspectionMiddleware extends InterceptionMiddleware { @@ -192,7 +191,7 @@ export class InspectionMiddleware extends InterceptionMiddleware { inspectionState: InspectionState, userState?: UserState, conversationState?: ConversationState, - credentials?: Partial + credentials?: Partial, ) { super(); @@ -312,7 +311,7 @@ export class InspectionMiddleware extends InterceptionMiddleware { const sessions = await this.inspectionStateAccessor.get(turnContext, InspectionSessionsByStatus.DefaultValue); const sessionId = this.openCommand(sessions, TurnContext.getConversationReference(turnContext.activity)); await turnContext.sendActivity( - TraceActivity.makeCommandActivity(`${InspectionMiddleware.command} attach ${sessionId}`) + TraceActivity.makeCommandActivity(`${InspectionMiddleware.command} attach ${sessionId}`), ); await this.inspectionState.saveChanges(turnContext, false); } @@ -336,7 +335,7 @@ export class InspectionMiddleware extends InterceptionMiddleware { */ private openCommand( sessions: InspectionSessionsByStatus, - conversationReference: Partial + conversationReference: Partial, ): string { const sessionId = uuidv4(); sessions.openedSessions[sessionId] = conversationReference; @@ -376,7 +375,7 @@ export class InspectionMiddleware extends InterceptionMiddleware { private async invokeSend( turnContext: TurnContext, session: InspectionSession, - activity: Partial + activity: Partial, ): Promise { if (await session.send(activity)) { return true; @@ -444,7 +443,6 @@ class InspectionSessionsByStatus { * * @remarks * InspectionState for use by the InspectionMiddleware for emulator inspection of runtime Activities and BotState. - * * @deprecated This class will be removed in a future version of the framework. */ export class InspectionState extends BotState { diff --git a/libraries/botbuilder/src/interfaces/connectorClientBuilder.ts b/libraries/botbuilder/src/interfaces/connectorClientBuilder.ts index 5645674239..f6cb3bfffb 100644 --- a/libraries/botbuilder/src/interfaces/connectorClientBuilder.ts +++ b/libraries/botbuilder/src/interfaces/connectorClientBuilder.ts @@ -22,6 +22,6 @@ export interface ConnectorClientBuilder { createConnectorClientWithIdentity: ( serviceUrl: string, claimsIdentity: ClaimsIdentity, - audience: string + audience: string, ) => Promise; } diff --git a/libraries/botbuilder/src/interfaces/request.ts b/libraries/botbuilder/src/interfaces/request.ts index 741170b574..d344eac0f3 100644 --- a/libraries/botbuilder/src/interfaces/request.ts +++ b/libraries/botbuilder/src/interfaces/request.ts @@ -7,7 +7,7 @@ */ export interface Request< Body extends Record = Record, - Headers extends Record = Record + Headers extends Record = Record, > { body?: Body; headers: Headers; diff --git a/libraries/botbuilder/src/interfaces/response.ts b/libraries/botbuilder/src/interfaces/response.ts index 13936873fd..b9ed0bcb8d 100644 --- a/libraries/botbuilder/src/interfaces/response.ts +++ b/libraries/botbuilder/src/interfaces/response.ts @@ -25,5 +25,5 @@ export const ResponseT = z.custom( typeof val.status === 'function', { message: 'Response', - } + }, ); diff --git a/libraries/botbuilder/src/interfaces/webRequest.ts b/libraries/botbuilder/src/interfaces/webRequest.ts index 448580c9ca..4ebcabb82f 100644 --- a/libraries/botbuilder/src/interfaces/webRequest.ts +++ b/libraries/botbuilder/src/interfaces/webRequest.ts @@ -44,7 +44,6 @@ export interface WebRequest { * * @param event The event name. * @param args Arguments used to handle the event. - * * @returns A reference to the request object. */ on?(event: string, ...args: any[]): any; diff --git a/libraries/botbuilder/src/interfaces/webResponse.ts b/libraries/botbuilder/src/interfaces/webResponse.ts index 9b3a8b4862..35d0c0fe6f 100644 --- a/libraries/botbuilder/src/interfaces/webResponse.ts +++ b/libraries/botbuilder/src/interfaces/webResponse.ts @@ -22,7 +22,6 @@ export interface WebResponse { * When implemented in a derived class, sends a FIN packet. * * @param args The arguments for the end event. - * * @returns A reference to the response object. */ end(...args: any[]): any; @@ -31,7 +30,6 @@ export interface WebResponse { * When implemented in a derived class, sends the response. * * @param body The response payload. - * * @returns A reference to the response object. */ send(body: any): any; @@ -40,7 +38,6 @@ export interface WebResponse { * When implemented in a derived class, sets the HTTP status code for the response. * * @param status The status code to use. - * * @returns The status code. */ status(status: number): any; diff --git a/libraries/botbuilder/src/setSpeakMiddleware.ts b/libraries/botbuilder/src/setSpeakMiddleware.ts index 78480d4c99..89276c7eca 100644 --- a/libraries/botbuilder/src/setSpeakMiddleware.ts +++ b/libraries/botbuilder/src/setSpeakMiddleware.ts @@ -42,7 +42,10 @@ export class SetSpeakMiddleware implements Middleware { * @param voiceName The SSML voice name attribute value. * @param fallbackToTextForSpeak true if an empty Activity.Speak is populated with Activity.Text. */ - constructor(private readonly voiceName: string | null, private readonly fallbackToTextForSpeak: boolean) {} + constructor( + private readonly voiceName: string | null, + private readonly fallbackToTextForSpeak: boolean, + ) {} /** * Processes an incoming activity. @@ -78,7 +81,7 @@ export class SetSpeakMiddleware implements Middleware { }'>${activity.speak}`; } } - }) + }), ); return next(); diff --git a/libraries/botbuilder/src/sharepoint/sharePointActivityHandler.ts b/libraries/botbuilder/src/sharepoint/sharePointActivityHandler.ts index 0a017f68b7..821251e3f8 100644 --- a/libraries/botbuilder/src/sharepoint/sharePointActivityHandler.ts +++ b/libraries/botbuilder/src/sharepoint/sharePointActivityHandler.ts @@ -26,7 +26,7 @@ export class SharePointActivityHandler extends ActivityHandler { /** * Invoked when an invoke activity is received from the connector. * Invoke activities can be used to communicate many different things. - * * Invoke activities communicate programmatic commands from a client or channel to a bot. + * Invoke activities communicate programmatic commands from a client or channel to a bot. * * @param context A strongly-typed context object for this turn * @returns A task that represents the work queued to execute @@ -39,32 +39,32 @@ export class SharePointActivityHandler extends ActivityHandler { switch (context.activity.name) { case 'cardExtension/getCardView': return ActivityHandler.createInvokeResponse( - await this.onSharePointTaskGetCardViewAsync(context, context.activity.value as AceRequest) + await this.onSharePointTaskGetCardViewAsync(context, context.activity.value as AceRequest), ); case 'cardExtension/getQuickView': return ActivityHandler.createInvokeResponse( - await this.onSharePointTaskGetQuickViewAsync(context, context.activity.value as AceRequest) + await this.onSharePointTaskGetQuickViewAsync(context, context.activity.value as AceRequest), ); case 'cardExtension/getPropertyPaneConfiguration': return ActivityHandler.createInvokeResponse( await this.onSharePointTaskGetPropertyPaneConfigurationAsync( context, - context.activity.value as AceRequest - ) + context.activity.value as AceRequest, + ), ); case 'cardExtension/setPropertyPaneConfiguration': return ActivityHandler.createInvokeResponse( await this.onSharePointTaskSetPropertyPaneConfigurationAsync( context, - context.activity.value as AceRequest - ) + context.activity.value as AceRequest, + ), ); case 'cardExtension/handleAction': return ActivityHandler.createInvokeResponse( - await this.onSharePointTaskHandleActionAsync(context, context.activity.value as AceRequest) + await this.onSharePointTaskHandleActionAsync(context, context.activity.value as AceRequest), ); default: return super.onInvokeActivity(context); @@ -89,7 +89,7 @@ export class SharePointActivityHandler extends ActivityHandler { */ protected async onSharePointTaskGetCardViewAsync( _context: TurnContext, - _aceRequest: AceRequest + _aceRequest: AceRequest, ): Promise { throw new Error('NotImplemented'); } @@ -103,7 +103,7 @@ export class SharePointActivityHandler extends ActivityHandler { */ protected async onSharePointTaskGetQuickViewAsync( _context: TurnContext, - _aceRequest: AceRequest + _aceRequest: AceRequest, ): Promise { throw new Error('NotImplemented'); } @@ -117,7 +117,7 @@ export class SharePointActivityHandler extends ActivityHandler { */ protected async onSharePointTaskGetPropertyPaneConfigurationAsync( _context: TurnContext, - _aceRequest: AceRequest + _aceRequest: AceRequest, ): Promise { throw new Error('NotImplemented'); } @@ -131,7 +131,7 @@ export class SharePointActivityHandler extends ActivityHandler { */ protected async onSharePointTaskSetPropertyPaneConfigurationAsync( _context: TurnContext, - _aceRequest: AceRequest + _aceRequest: AceRequest, ): Promise { throw new Error('NotImplemented'); } @@ -145,7 +145,7 @@ export class SharePointActivityHandler extends ActivityHandler { */ protected async onSharePointTaskHandleActionAsync( _context: TurnContext, - _aceRequest: AceRequest + _aceRequest: AceRequest, ): Promise { throw new Error('NotImplemented'); } diff --git a/libraries/botbuilder/src/skills/cloudSkillHandler.ts b/libraries/botbuilder/src/skills/cloudSkillHandler.ts index 027995a96e..5c1d1939fe 100644 --- a/libraries/botbuilder/src/skills/cloudSkillHandler.ts +++ b/libraries/botbuilder/src/skills/cloudSkillHandler.ts @@ -39,7 +39,7 @@ export class CloudSkillHandler extends CloudChannelServiceHandler { adapter: BotAdapter, logic: (context: TurnContext) => Promise, conversationIdFactory: SkillConversationIdFactoryBase, - auth: BotFrameworkAuthentication + auth: BotFrameworkAuthentication, ) { super(auth); @@ -60,7 +60,7 @@ export class CloudSkillHandler extends CloudChannelServiceHandler { adapter, logic, conversationIdFactory, - () => auth.getOriginatingAudience() + () => auth.getOriginatingAudience(), ); } @@ -71,9 +71,9 @@ export class CloudSkillHandler extends CloudChannelServiceHandler { * This method allows you to send an activity to the end of a conversation. * * This is slightly different from replyToActivity(). - * * sendToConversation(conversationId) - will append the activity to the end + * - sendToConversation(conversationId) - will append the activity to the end * of the conversation according to the timestamp or semantics of the channel. - * * replyToActivity(conversationId,ActivityId) - adds the activity as a reply + * - replyToActivity(conversationId,ActivityId) - adds the activity as a reply * to another activity, if the channel supports it. If the channel does not * support nested replies, replyToActivity falls back to sendToConversation. * @@ -88,7 +88,7 @@ export class CloudSkillHandler extends CloudChannelServiceHandler { protected onSendToConversation( claimsIdentity: ClaimsIdentity, conversationId: string, - activity: Activity + activity: Activity, ): Promise { return this.inner.onSendToConversation(claimsIdentity, conversationId, activity); } @@ -100,9 +100,9 @@ export class CloudSkillHandler extends CloudChannelServiceHandler { * This method allows you to reply to an activity. * * This is slightly different from sendToConversation(). - * * sendToConversation(conversationId) - will append the activity to the end + * - sendToConversation(conversationId) - will append the activity to the end * of the conversation according to the timestamp or semantics of the channel. - * * replyToActivity(conversationId,ActivityId) - adds the activity as a reply + * - replyToActivity(conversationId,ActivityId) - adds the activity as a reply * to another activity, if the channel supports it. If the channel does not * support nested replies, replyToActivity falls back to sendToConversation. * @@ -119,7 +119,7 @@ export class CloudSkillHandler extends CloudChannelServiceHandler { claimsIdentity: ClaimsIdentity, conversationId: string, activityId: string, - activity: Activity + activity: Activity, ): Promise { return this.inner.onReplyToActivity(claimsIdentity, conversationId, activityId, activity); } @@ -145,7 +145,7 @@ export class CloudSkillHandler extends CloudChannelServiceHandler { claimsIdentity: ClaimsIdentity, conversationId: string, activityId: string, - activity: Activity + activity: Activity, ): Promise { return this.inner.onUpdateActivity(claimsIdentity, conversationId, activityId, activity); } @@ -158,8 +158,6 @@ export class CloudSkillHandler extends CloudChannelServiceHandler { * * Some channels allow you to delete an existing activity, and if successful * this method will remove the specified activity. - * - * * @param claimsIdentity ClaimsIdentity for the bot, should have AudienceClaim, AppIdClaim and ServiceUrlClaim. * @param conversationId Conversation ID. * @param activityId activityId to delete. @@ -168,7 +166,7 @@ export class CloudSkillHandler extends CloudChannelServiceHandler { protected async onDeleteActivity( claimsIdentity: ClaimsIdentity, conversationId: string, - activityId: string + activityId: string, ): Promise { return this.inner.onDeleteActivity(claimsIdentity, conversationId, activityId); } @@ -184,13 +182,12 @@ export class CloudSkillHandler extends CloudChannelServiceHandler { * @param claimsIdentity ClaimsIdentity for the bot, should have AudienceClaim, AppIdClaim and ServiceUrlClaim. * @param userId User ID. * @param conversationId Conversation ID. - * * @returns The ChannelAccount object representing the member of the conversation. */ protected async onGetConversationMember( claimsIdentity: ClaimsIdentity, userId: string, - conversationId: string + conversationId: string, ): Promise { return this.inner.onGetMember(claimsIdentity, userId, conversationId); } diff --git a/libraries/botbuilder/src/skills/skillHandler.ts b/libraries/botbuilder/src/skills/skillHandler.ts index df81af5eb8..3f956a22ba 100644 --- a/libraries/botbuilder/src/skills/skillHandler.ts +++ b/libraries/botbuilder/src/skills/skillHandler.ts @@ -54,7 +54,7 @@ export class SkillHandler extends ChannelServiceHandler { conversationIdFactory: SkillConversationIdFactoryBase, credentialProvider: ICredentialProvider, authConfig: AuthenticationConfiguration, - channelService?: string + channelService?: string, ) { super(credentialProvider, authConfig, channelService); @@ -78,7 +78,7 @@ export class SkillHandler extends ChannelServiceHandler { () => JwtTokenValidation.isGovernment(channelService) ? GovernmentConstants.ToChannelFromBotOAuthScope - : AuthenticationConstants.ToChannelFromBotOAuthScope + : AuthenticationConstants.ToChannelFromBotOAuthScope, ); } @@ -89,9 +89,9 @@ export class SkillHandler extends ChannelServiceHandler { * This method allows you to send an activity to the end of a conversation. * * This is slightly different from replyToActivity(). - * * sendToConversation(conversationId) - will append the activity to the end + * - sendToConversation(conversationId) - will append the activity to the end * of the conversation according to the timestamp or semantics of the channel. - * * replyToActivity(conversationId,ActivityId) - adds the activity as a reply + * - replyToActivity(conversationId,ActivityId) - adds the activity as a reply * to another activity, if the channel supports it. If the channel does not * support nested replies, replyToActivity falls back to sendToConversation. * @@ -106,7 +106,7 @@ export class SkillHandler extends ChannelServiceHandler { protected onSendToConversation( claimsIdentity: ClaimsIdentity, conversationId: string, - activity: Activity + activity: Activity, ): Promise { return this.inner.onSendToConversation(claimsIdentity, conversationId, activity); } @@ -118,9 +118,9 @@ export class SkillHandler extends ChannelServiceHandler { * This method allows you to reply to an activity. * * This is slightly different from sendToConversation(). - * * sendToConversation(conversationId) - will append the activity to the end + * - sendToConversation(conversationId) - will append the activity to the end * of the conversation according to the timestamp or semantics of the channel. - * * replyToActivity(conversationId,ActivityId) - adds the activity as a reply + * - replyToActivity(conversationId,ActivityId) - adds the activity as a reply * to another activity, if the channel supports it. If the channel does not * support nested replies, replyToActivity falls back to sendToConversation. * @@ -137,7 +137,7 @@ export class SkillHandler extends ChannelServiceHandler { claimsIdentity: ClaimsIdentity, conversationId: string, activityId: string, - activity: Activity + activity: Activity, ): Promise { return this.inner.onReplyToActivity(claimsIdentity, conversationId, activityId, activity); } @@ -163,7 +163,7 @@ export class SkillHandler extends ChannelServiceHandler { claimsIdentity: ClaimsIdentity, conversationId: string, activityId: string, - activity: Activity + activity: Activity, ): Promise { return this.inner.onUpdateActivity(claimsIdentity, conversationId, activityId, activity); } @@ -176,8 +176,6 @@ export class SkillHandler extends ChannelServiceHandler { * * Some channels allow you to delete an existing activity, and if successful * this method will remove the specified activity. - * - * * @param claimsIdentity ClaimsIdentity for the bot, should have AudienceClaim, AppIdClaim and ServiceUrlClaim. * @param conversationId Conversation ID. * @param activityId activityId to delete. @@ -186,7 +184,7 @@ export class SkillHandler extends ChannelServiceHandler { protected async onDeleteActivity( claimsIdentity: ClaimsIdentity, conversationId: string, - activityId: string + activityId: string, ): Promise { return this.inner.onDeleteActivity(claimsIdentity, conversationId, activityId); } diff --git a/libraries/botbuilder/src/skills/skillHandlerImpl.ts b/libraries/botbuilder/src/skills/skillHandlerImpl.ts index a12b778a77..b44fe0ac52 100644 --- a/libraries/botbuilder/src/skills/skillHandlerImpl.ts +++ b/libraries/botbuilder/src/skills/skillHandlerImpl.ts @@ -28,7 +28,7 @@ export class SkillHandlerImpl { private readonly adapter: BotAdapter, private readonly logic: (context: TurnContext) => Promise, private readonly conversationIdFactory: SkillConversationIdFactoryBase, - private readonly getOauthScope: () => string | undefined = () => undefined + private readonly getOauthScope: () => string | undefined = () => undefined, ) {} /** @@ -37,7 +37,7 @@ export class SkillHandlerImpl { onSendToConversation( claimsIdentity: ClaimsIdentity, conversationId: string, - activity: Activity + activity: Activity, ): Promise { return this.processActivity(claimsIdentity, conversationId, null, activity); } @@ -49,7 +49,7 @@ export class SkillHandlerImpl { claimsIdentity: ClaimsIdentity, conversationId: string, activityId: string, - activity: Activity + activity: Activity, ): Promise { return this.processActivity(claimsIdentity, conversationId, activityId, activity); } @@ -61,7 +61,7 @@ export class SkillHandlerImpl { claimsIdentity: ClaimsIdentity, conversationId: string, activityId: string, - activity: Activity + activity: Activity, ): Promise { let resourceResponse: ResourceResponse | void; @@ -70,7 +70,7 @@ export class SkillHandlerImpl { context.activity.id = activityId; context.activity.callerId = `${CallerIdConstants.BotToBotPrefix}${JwtTokenValidation.getAppIdFromClaims( - claimsIdentity.claims + claimsIdentity.claims, )}`; resourceResponse = await context.updateActivity(newActivity); @@ -84,7 +84,7 @@ export class SkillHandlerImpl { */ async onDeleteActivity(claimsIdentity: ClaimsIdentity, conversationId: string, activityId: string): Promise { return this.continueConversation(claimsIdentity, conversationId, (context) => - context.deleteActivity(activityId) + context.deleteActivity(activityId), ); } @@ -135,7 +135,7 @@ export class SkillHandlerImpl { claimsIdentity: ClaimsIdentity, conversationId: string, replyToActivityId: string, - activity: Activity + activity: Activity, ): Promise { let resourceResponse: ResourceResponse; @@ -151,7 +151,7 @@ export class SkillHandlerImpl { context.activity.id = replyToActivityId; context.activity.callerId = `${CallerIdConstants.BotToBotPrefix}${JwtTokenValidation.getAppIdFromClaims( - claimsIdentity.claims + claimsIdentity.claims, )}`; switch (newActivity.type) { @@ -185,7 +185,7 @@ export class SkillHandlerImpl { private async continueConversation( claimsIdentity: ClaimsIdentity, conversationId: string, - callback: (context: TurnContext, ref: SkillConversationReference) => Promise + callback: (context: TurnContext, ref: SkillConversationReference) => Promise, ): Promise { const ref = await this.getSkillConversationReference(conversationId); @@ -199,7 +199,7 @@ export class SkillHandlerImpl { claimsIdentity, ref.conversationReference, ref.oAuthScope, - continueCallback + continueCallback, ); } catch (err) { if (err.message === 'NotImplemented') { diff --git a/libraries/botbuilder/src/skills/skillHttpClient.ts b/libraries/botbuilder/src/skills/skillHttpClient.ts index 28c74bcb66..fb145bb2de 100644 --- a/libraries/botbuilder/src/skills/skillHttpClient.ts +++ b/libraries/botbuilder/src/skills/skillHttpClient.ts @@ -38,7 +38,7 @@ export class SkillHttpClient extends BotFrameworkHttpClient { constructor( credentialProvider: ICredentialProvider, conversationIdFactory: SkillConversationIdFactoryBase, - channelService?: string + channelService?: string, ) { super(credentialProvider, channelService); if (!conversationIdFactory) { @@ -63,7 +63,7 @@ export class SkillHttpClient extends BotFrameworkHttpClient { fromBotId: string, toSkill: BotFrameworkSkill, callbackUrl: string, - activity: Activity + activity: Activity, ): Promise>; /** * Uses the SkillConversationIdFactory to create or retrieve a Skill Conversation Id, and sends the activity. @@ -78,7 +78,7 @@ export class SkillHttpClient extends BotFrameworkHttpClient { fromBotId: string, toSkill: BotFrameworkSkill, callbackUrl: string, - activity: Activity + activity: Activity, ): Promise; /** * Uses the `SkillConversationIdFactory` to create or retrieve a Skill Conversation Id, and sends the [Activity](xref:botframework-schema.Activity). @@ -95,7 +95,7 @@ export class SkillHttpClient extends BotFrameworkHttpClient { fromBotIdOrSkill: string | BotFrameworkSkill, toSkillOrCallbackUrl: BotFrameworkSkill | string, callbackUrlOrActivity: string | Activity, - activityToForward?: Activity + activityToForward?: Activity, ): Promise> { let originatingAudience: string; let fromBotId: string; @@ -125,13 +125,12 @@ export class SkillHttpClient extends BotFrameworkHttpClient { fromBotOAuthScope: originatingAudience, }; - skillConversationId = await this.conversationIdFactory.createSkillConversationIdWithOptions( - createIdOptions - ); + skillConversationId = + await this.conversationIdFactory.createSkillConversationIdWithOptions(createIdOptions); } catch (err) { if (err.message === 'Not Implemented') { skillConversationId = await this.conversationIdFactory.createSkillConversationId( - TurnContext.getConversationReference(activity) as ConversationReference + TurnContext.getConversationReference(activity) as ConversationReference, ); } else { throw err; @@ -144,7 +143,7 @@ export class SkillHttpClient extends BotFrameworkHttpClient { toSkill.skillEndpoint, callbackUrl, skillConversationId, - activity + activity, ); } } diff --git a/libraries/botbuilder/src/statusCodeError.ts b/libraries/botbuilder/src/statusCodeError.ts index 9c2e59d0d5..18d5bc00eb 100644 --- a/libraries/botbuilder/src/statusCodeError.ts +++ b/libraries/botbuilder/src/statusCodeError.ts @@ -18,7 +18,10 @@ export class StatusCodeError extends Error { * @param statusCode The status code. * @param message Optional. The error message. */ - constructor(public readonly statusCode: StatusCodes, message?: string) { + constructor( + readonly statusCode: StatusCodes, + message?: string, + ) { super(message); this.name = 'StatusCodeError'; diff --git a/libraries/botbuilder/src/streaming/streamingHttpClient.ts b/libraries/botbuilder/src/streaming/streamingHttpClient.ts index 0d631ba2bb..bfe8d35bf7 100644 --- a/libraries/botbuilder/src/streaming/streamingHttpClient.ts +++ b/libraries/botbuilder/src/streaming/streamingHttpClient.ts @@ -41,7 +41,7 @@ export class StreamingHttpClient implements HttpClient { } if (!this.server.isConnected) { throw new Error( - 'StreamingHttpClient.sendRequest(): Streaming connection is disconnected, and the request could not be sent.' + 'StreamingHttpClient.sendRequest(): Streaming connection is disconnected, and the request could not be sent.', ); } diff --git a/libraries/botbuilder/src/streaming/tokenResolver.ts b/libraries/botbuilder/src/streaming/tokenResolver.ts index 1ac144248e..9c0b1089f6 100644 --- a/libraries/botbuilder/src/streaming/tokenResolver.ts +++ b/libraries/botbuilder/src/streaming/tokenResolver.ts @@ -60,7 +60,7 @@ export class TokenResolver { setTimeout( () => this.pollForToken(adapter, context, activity, oauthCard.connectionName, pollingTimeout, log), - TokenResolver.PollingIntervalMs + TokenResolver.PollingIntervalMs, ); } } @@ -75,7 +75,7 @@ export class TokenResolver { activity: Activity, connectionName: string, pollingTimeout: Date, - log?: string[] + log?: string[], ) { if (pollingTimeout > new Date()) { const tokenApiClientCredentials = context.turnState.get(adapter.TokenApiClientCredentialsKey); @@ -90,7 +90,7 @@ export class TokenResolver { TokenResolver.createTokenResponseActivity( TurnContext.getConversationReference(activity), tokenResponse.token, - connectionName + connectionName, ) ); // received a token, send it to the bot and end polling @@ -121,7 +121,7 @@ export class TokenResolver { if (log) log.push('Polling again'); setTimeout( () => this.pollForToken(adapter, context, activity, connectionName, pollingTimeout), - pollingIntervalMs + pollingIntervalMs, ); }); } @@ -130,7 +130,7 @@ export class TokenResolver { private static createTokenResponseActivity( relatesTo: Partial, token: string, - connectionName: string + connectionName: string, ): Partial { const tokenResponse: Partial = { id: uuidv4(), diff --git a/libraries/botbuilder/src/teams/teamsSSOTokenExchangeMiddleware.ts b/libraries/botbuilder/src/teams/teamsSSOTokenExchangeMiddleware.ts index 76a8f8378e..284baf5f06 100644 --- a/libraries/botbuilder/src/teams/teamsSSOTokenExchangeMiddleware.ts +++ b/libraries/botbuilder/src/teams/teamsSSOTokenExchangeMiddleware.ts @@ -50,7 +50,7 @@ async function sendInvokeResponse(context: TurnContext, body: unknown = null, st const ExchangeToken = z.custom>( (val: any) => typeof val.exchangeToken === 'function', - { message: 'ExtendedUserTokenProvider' } + { message: 'ExtendedUserTokenProvider' }, ); /** @@ -75,7 +75,10 @@ export class TeamsSSOTokenExchangeMiddleware implements Middleware { * @param storage The [Storage](xref:botbuilder-core.Storage) to use for deduplication * @param oAuthConnectionName The connection name to use for the single sign on token exchange */ - constructor(private readonly storage: Storage, private readonly oAuthConnectionName: string) { + constructor( + private readonly storage: Storage, + private readonly oAuthConnectionName: string, + ) { if (!storage) { throw new TypeError('`storage` parameter is required'); } @@ -142,7 +145,7 @@ export class TeamsSSOTokenExchangeMiddleware implements Middleware { try { const userTokenClient = context.turnState.get( - (context.adapter as CloudAdapterBase).UserTokenClientKey + (context.adapter as CloudAdapterBase).UserTokenClientKey, ); const exchangeToken = ExchangeToken.safeParse(context.adapter); @@ -151,14 +154,14 @@ export class TeamsSSOTokenExchangeMiddleware implements Middleware { context.activity.from.id, this.oAuthConnectionName, context.activity.channelId, - { token: tokenExchangeRequest.token } + { token: tokenExchangeRequest.token }, ); } else if (exchangeToken.success) { tokenExchangeResponse = await exchangeToken.data.exchangeToken( context, this.oAuthConnectionName, context.activity.from.id, - { token: tokenExchangeRequest.token } + { token: tokenExchangeRequest.token }, ); } else { new Error('Token Exchange is not supported by the current adapter.'); diff --git a/libraries/botbuilder/src/teamsActivityHandler.ts b/libraries/botbuilder/src/teamsActivityHandler.ts index fe95022307..43bd322d33 100644 --- a/libraries/botbuilder/src/teamsActivityHandler.ts +++ b/libraries/botbuilder/src/teamsActivityHandler.ts @@ -90,15 +90,15 @@ export class TeamsActivityHandler extends ActivityHandler { switch (context.activity.name) { case 'config/fetch': return ActivityHandler.createInvokeResponse( - await this.handleTeamsConfigFetch(context, context.activity.value) + await this.handleTeamsConfigFetch(context, context.activity.value), ); case 'config/submit': return ActivityHandler.createInvokeResponse( - await this.handleTeamsConfigSubmit(context, context.activity.value) + await this.handleTeamsConfigSubmit(context, context.activity.value), ); case 'fileConsent/invoke': return ActivityHandler.createInvokeResponse( - await this.handleTeamsFileConsent(context, context.activity.value) + await this.handleTeamsFileConsent(context, context.activity.value), ); case 'actionableMessage/executeAction': @@ -107,43 +107,43 @@ export class TeamsActivityHandler extends ActivityHandler { case 'composeExtension/queryLink': return ActivityHandler.createInvokeResponse( - await this.handleTeamsAppBasedLinkQuery(context, context.activity.value) + await this.handleTeamsAppBasedLinkQuery(context, context.activity.value), ); case 'composeExtension/anonymousQueryLink': return ActivityHandler.createInvokeResponse( - await this.handleTeamsAnonymousAppBasedLinkQuery(context, context.activity.value) + await this.handleTeamsAnonymousAppBasedLinkQuery(context, context.activity.value), ); case 'composeExtension/query': return ActivityHandler.createInvokeResponse( - await this.handleTeamsMessagingExtensionQuery(context, context.activity.value) + await this.handleTeamsMessagingExtensionQuery(context, context.activity.value), ); case 'composeExtension/selectItem': return ActivityHandler.createInvokeResponse( - await this.handleTeamsMessagingExtensionSelectItem(context, context.activity.value) + await this.handleTeamsMessagingExtensionSelectItem(context, context.activity.value), ); case 'composeExtension/submitAction': return ActivityHandler.createInvokeResponse( await this.handleTeamsMessagingExtensionSubmitActionDispatch( context, - context.activity.value - ) + context.activity.value, + ), ); case 'composeExtension/fetchTask': return ActivityHandler.createInvokeResponse( - await this.handleTeamsMessagingExtensionFetchTask(context, context.activity.value) + await this.handleTeamsMessagingExtensionFetchTask(context, context.activity.value), ); case 'composeExtension/querySettingUrl': return ActivityHandler.createInvokeResponse( await this.handleTeamsMessagingExtensionConfigurationQuerySettingUrl( context, - context.activity.value - ) + context.activity.value, + ), ); case 'composeExtension/setting': @@ -156,22 +156,22 @@ export class TeamsActivityHandler extends ActivityHandler { case 'task/fetch': return ActivityHandler.createInvokeResponse( - await this.handleTeamsTaskModuleFetch(context, context.activity.value) + await this.handleTeamsTaskModuleFetch(context, context.activity.value), ); case 'task/submit': return ActivityHandler.createInvokeResponse( - await this.handleTeamsTaskModuleSubmit(context, context.activity.value) + await this.handleTeamsTaskModuleSubmit(context, context.activity.value), ); case 'tab/fetch': return ActivityHandler.createInvokeResponse( - await this.handleTeamsTabFetch(context, context.activity.value) + await this.handleTeamsTabFetch(context, context.activity.value), ); case 'tab/submit': return ActivityHandler.createInvokeResponse( - await this.handleTeamsTabSubmit(context, context.activity.value) + await this.handleTeamsTabSubmit(context, context.activity.value), ); default: @@ -237,7 +237,7 @@ export class TeamsActivityHandler extends ActivityHandler { */ protected async handleTeamsFileConsent( context: TurnContext, - fileConsentCardResponse: FileConsentCardResponse + fileConsentCardResponse: FileConsentCardResponse, ): Promise { switch (fileConsentCardResponse.action) { case 'accept': @@ -260,7 +260,7 @@ export class TeamsActivityHandler extends ActivityHandler { */ protected async handleTeamsFileConsentAccept( _context: TurnContext, - _fileConsentCardResponse: FileConsentCardResponse + _fileConsentCardResponse: FileConsentCardResponse, ): Promise { throw new Error('NotImplemented'); } @@ -276,7 +276,7 @@ export class TeamsActivityHandler extends ActivityHandler { */ protected async handleTeamsFileConsentDecline( _context: TurnContext, - _fileConsentCardResponse: FileConsentCardResponse + _fileConsentCardResponse: FileConsentCardResponse, ): Promise { throw new Error('NotImplemented'); } @@ -290,7 +290,7 @@ export class TeamsActivityHandler extends ActivityHandler { */ protected async handleTeamsO365ConnectorCardAction( _context: TurnContext, - _query: O365ConnectorCardActionQuery + _query: O365ConnectorCardActionQuery, ): Promise { throw new Error('NotImplemented'); } @@ -319,7 +319,7 @@ export class TeamsActivityHandler extends ActivityHandler { */ protected async handleTeamsSigninVerifyState( _context: TurnContext, - _query: SigninStateVerificationQuery + _query: SigninStateVerificationQuery, ): Promise { throw new Error('NotImplemented'); } @@ -333,7 +333,7 @@ export class TeamsActivityHandler extends ActivityHandler { */ protected async handleTeamsSigninTokenExchange( _context: TurnContext, - _query: SigninStateVerificationQuery + _query: SigninStateVerificationQuery, ): Promise { throw new Error('NotImplemented'); } @@ -347,7 +347,7 @@ export class TeamsActivityHandler extends ActivityHandler { */ protected async handleTeamsMessagingExtensionCardButtonClicked( _context: TurnContext, - _cardData: any + _cardData: any, ): Promise { throw new Error('NotImplemented'); } @@ -361,7 +361,7 @@ export class TeamsActivityHandler extends ActivityHandler { */ protected async handleTeamsTaskModuleFetch( _context: TurnContext, - _taskModuleRequest: TaskModuleRequest + _taskModuleRequest: TaskModuleRequest, ): Promise { throw new Error('NotImplemented'); } @@ -375,7 +375,7 @@ export class TeamsActivityHandler extends ActivityHandler { */ protected async handleTeamsTaskModuleSubmit( _context: TurnContext, - _taskModuleRequest: TaskModuleRequest + _taskModuleRequest: TaskModuleRequest, ): Promise { throw new Error('NotImplemented'); } @@ -413,7 +413,7 @@ export class TeamsActivityHandler extends ActivityHandler { */ protected async handleTeamsAppBasedLinkQuery( _context: TurnContext, - _query: AppBasedLinkQuery + _query: AppBasedLinkQuery, ): Promise { throw new Error('NotImplemented'); } @@ -429,7 +429,7 @@ export class TeamsActivityHandler extends ActivityHandler { */ protected async handleTeamsAnonymousAppBasedLinkQuery( _context: TurnContext, - _query: AppBasedLinkQuery + _query: AppBasedLinkQuery, ): Promise { throw new Error('NotImplemented'); } @@ -445,7 +445,7 @@ export class TeamsActivityHandler extends ActivityHandler { */ protected async handleTeamsMessagingExtensionQuery( _context: TurnContext, - _query: MessagingExtensionQuery + _query: MessagingExtensionQuery, ): Promise { throw new Error('NotImplemented'); } @@ -461,7 +461,7 @@ export class TeamsActivityHandler extends ActivityHandler { */ protected async handleTeamsMessagingExtensionSelectItem( _context: TurnContext, - _query: any + _query: any, ): Promise { throw new Error('NotImplemented'); } @@ -479,7 +479,7 @@ export class TeamsActivityHandler extends ActivityHandler { */ protected async handleTeamsMessagingExtensionSubmitActionDispatch( context: TurnContext, - action: MessagingExtensionAction + action: MessagingExtensionAction, ): Promise { if (action.botMessagePreviewAction) { switch (action.botMessagePreviewAction) { @@ -504,7 +504,7 @@ export class TeamsActivityHandler extends ActivityHandler { */ protected async handleTeamsMessagingExtensionSubmitAction( _context: TurnContext, - _action: MessagingExtensionAction + _action: MessagingExtensionAction, ): Promise { throw new Error('NotImplemented'); } @@ -519,7 +519,7 @@ export class TeamsActivityHandler extends ActivityHandler { */ protected async handleTeamsMessagingExtensionBotMessagePreviewEdit( _context: TurnContext, - _action: MessagingExtensionAction + _action: MessagingExtensionAction, ): Promise { throw new Error('NotImplemented'); } @@ -534,7 +534,7 @@ export class TeamsActivityHandler extends ActivityHandler { */ protected async handleTeamsMessagingExtensionBotMessagePreviewSend( _context: TurnContext, - _action: MessagingExtensionAction + _action: MessagingExtensionAction, ): Promise { throw new Error('NotImplemented'); } @@ -548,7 +548,7 @@ export class TeamsActivityHandler extends ActivityHandler { */ protected async handleTeamsMessagingExtensionFetchTask( _context: TurnContext, - _action: MessagingExtensionAction + _action: MessagingExtensionAction, ): Promise { throw new Error('NotImplemented'); } @@ -562,7 +562,7 @@ export class TeamsActivityHandler extends ActivityHandler { */ protected async handleTeamsMessagingExtensionConfigurationQuerySettingUrl( _context: TurnContext, - _query: MessagingExtensionQuery + _query: MessagingExtensionQuery, ): Promise { throw new Error('NotImplemented'); } @@ -967,8 +967,8 @@ export class TeamsActivityHandler extends ActivityHandler { membersAdded: TeamsChannelAccount[], teamInfo: TeamInfo, context: TurnContext, - next: () => Promise - ) => Promise + next: () => Promise, + ) => Promise, ): this { return this.on('TeamsMembersAdded', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; @@ -988,8 +988,8 @@ export class TeamsActivityHandler extends ActivityHandler { membersRemoved: TeamsChannelAccount[], teamInfo: TeamInfo, context: TurnContext, - next: () => Promise - ) => Promise + next: () => Promise, + ) => Promise, ): this { return this.on('TeamsMembersRemoved', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; @@ -1008,8 +1008,8 @@ export class TeamsActivityHandler extends ActivityHandler { channelInfo: ChannelInfo, teamInfo: TeamInfo, context: TurnContext, - next: () => Promise - ) => Promise + next: () => Promise, + ) => Promise, ): this { return this.on('TeamsChannelCreated', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; @@ -1028,8 +1028,8 @@ export class TeamsActivityHandler extends ActivityHandler { channelInfo: ChannelInfo, teamInfo: TeamInfo, context: TurnContext, - next: () => Promise - ) => Promise + next: () => Promise, + ) => Promise, ): this { return this.on('TeamsChannelDeleted', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; @@ -1048,8 +1048,8 @@ export class TeamsActivityHandler extends ActivityHandler { channelInfo: ChannelInfo, teamInfo: TeamInfo, context: TurnContext, - next: () => Promise - ) => Promise + next: () => Promise, + ) => Promise, ): this { return this.on('TeamsChannelRenamed', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; @@ -1064,7 +1064,7 @@ export class TeamsActivityHandler extends ActivityHandler { * @returns A promise that represents the work queued. */ onTeamsTeamArchivedEvent( - handler: (teamInfo: TeamInfo, context: TurnContext, next: () => Promise) => Promise + handler: (teamInfo: TeamInfo, context: TurnContext, next: () => Promise) => Promise, ): this { return this.on('TeamsTeamArchived', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; @@ -1079,7 +1079,7 @@ export class TeamsActivityHandler extends ActivityHandler { * @returns A promise that represents the work queued. */ onTeamsTeamDeletedEvent( - handler: (teamInfo: TeamInfo, context: TurnContext, next: () => Promise) => Promise + handler: (teamInfo: TeamInfo, context: TurnContext, next: () => Promise) => Promise, ): this { return this.on('TeamsTeamDeleted', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; @@ -1094,7 +1094,7 @@ export class TeamsActivityHandler extends ActivityHandler { * @returns A promise that represents the work queued. */ onTeamsTeamHardDeletedEvent( - handler: (teamInfo: TeamInfo, context: TurnContext, next: () => Promise) => Promise + handler: (teamInfo: TeamInfo, context: TurnContext, next: () => Promise) => Promise, ): this { return this.on('TeamsTeamHardDeleted', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; @@ -1113,8 +1113,8 @@ export class TeamsActivityHandler extends ActivityHandler { channelInfo: ChannelInfo, teamInfo: TeamInfo, context: TurnContext, - next: () => Promise - ) => Promise + next: () => Promise, + ) => Promise, ): this { return this.on('TeamsChannelRestored', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; @@ -1129,7 +1129,7 @@ export class TeamsActivityHandler extends ActivityHandler { * @returns A promise that represents the work queued. */ onTeamsTeamRenamedEvent( - handler: (teamInfo: TeamInfo, context: TurnContext, next: () => Promise) => Promise + handler: (teamInfo: TeamInfo, context: TurnContext, next: () => Promise) => Promise, ): this { return this.on('TeamsTeamRenamed', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; @@ -1144,7 +1144,7 @@ export class TeamsActivityHandler extends ActivityHandler { * @returns A promise that represents the work queued. */ onTeamsTeamRestoredEvent( - handler: (teamInfo: TeamInfo, context: TurnContext, next: () => Promise) => Promise + handler: (teamInfo: TeamInfo, context: TurnContext, next: () => Promise) => Promise, ): this { return this.on('TeamsTeamRestored', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; @@ -1159,7 +1159,7 @@ export class TeamsActivityHandler extends ActivityHandler { * @returns A promise that represents the work queued. */ onTeamsTeamUnarchivedEvent( - handler: (teamInfo: TeamInfo, context: TurnContext, next: () => Promise) => Promise + handler: (teamInfo: TeamInfo, context: TurnContext, next: () => Promise) => Promise, ): this { return this.on('TeamsTeamUnarchived', async (context, next) => { const teamsChannelData = context.activity.channelData as TeamsChannelData; @@ -1172,7 +1172,6 @@ export class TeamsActivityHandler extends ActivityHandler { * * @param context The context object for the current turn. * @returns A promise that represents the work queued. - * * @remarks * Override this method to support channel-specific behavior across multiple channels or to add * custom event sub-type events. @@ -1258,7 +1257,7 @@ export class TeamsActivityHandler extends ActivityHandler { * @returns A promise that represents the work queued. */ onTeamsMeetingStartEvent( - handler: (meeting: MeetingStartEventDetails, context: TurnContext, next: () => Promise) => Promise + handler: (meeting: MeetingStartEventDetails, context: TurnContext, next: () => Promise) => Promise, ): this { return this.on('TeamsMeetingStart', async (context, next) => { const meeting = TeamsMeetingStartT.parse(context.activity.value); @@ -1271,7 +1270,7 @@ export class TeamsActivityHandler extends ActivityHandler { title: meeting.Title, }, context, - next + next, ); }); } @@ -1283,7 +1282,7 @@ export class TeamsActivityHandler extends ActivityHandler { * @returns A promise that represents the work queued. */ onTeamsMeetingEndEvent( - handler: (meeting: MeetingEndEventDetails, context: TurnContext, next: () => Promise) => Promise + handler: (meeting: MeetingEndEventDetails, context: TurnContext, next: () => Promise) => Promise, ): this { return this.on('TeamsMeetingEnd', async (context, next) => { const meeting = TeamsMeetingEndT.parse(context.activity.value); @@ -1296,7 +1295,7 @@ export class TeamsActivityHandler extends ActivityHandler { title: meeting.Title, }, context, - next + next, ); }); } @@ -1308,7 +1307,7 @@ export class TeamsActivityHandler extends ActivityHandler { * @returns A promise that represents the work queued. */ onTeamsReadReceiptEvent( - handler: (receiptInfo: ReadReceiptInfo, context: TurnContext, next: () => Promise) => Promise + handler: (receiptInfo: ReadReceiptInfo, context: TurnContext, next: () => Promise) => Promise, ): this { return this.on('TeamsReadReceipt', async (context, next) => { const receiptInfo = context.activity.value; @@ -1326,8 +1325,8 @@ export class TeamsActivityHandler extends ActivityHandler { handler: ( meeting: MeetingParticipantsEventDetails, context: TurnContext, - next: () => Promise - ) => Promise + next: () => Promise, + ) => Promise, ): this { return this.on('TeamsMeetingParticipantsJoin', async (context, next) => { const meeting = context.activity.value; @@ -1336,7 +1335,7 @@ export class TeamsActivityHandler extends ActivityHandler { members: meeting?.members, }, context, - next + next, ); }); } @@ -1351,8 +1350,8 @@ export class TeamsActivityHandler extends ActivityHandler { handler: ( meeting: MeetingParticipantsEventDetails, context: TurnContext, - next: () => Promise - ) => Promise + next: () => Promise, + ) => Promise, ): this { return this.on('TeamsMeetingParticipantsLeave', async (context, next) => { const meeting = context.activity.value; @@ -1361,7 +1360,7 @@ export class TeamsActivityHandler extends ActivityHandler { members: meeting?.members, }, context, - next + next, ); }); } diff --git a/libraries/botbuilder/src/teamsActivityHelpers.ts b/libraries/botbuilder/src/teamsActivityHelpers.ts index 85b12f7fa9..9004f6be8b 100644 --- a/libraries/botbuilder/src/teamsActivityHelpers.ts +++ b/libraries/botbuilder/src/teamsActivityHelpers.ts @@ -119,7 +119,7 @@ export function teamsGetChannelId(activity: Activity): string | null { export function teamsNotifyUser( activity: Partial, alertInMeeting = false, - externalResourceUrl?: string + externalResourceUrl?: string, ): void { validateActivity(activity); diff --git a/libraries/botbuilder/src/teamsInfo.ts b/libraries/botbuilder/src/teamsInfo.ts index 736c143086..11a4ebdbd5 100644 --- a/libraries/botbuilder/src/teamsInfo.ts +++ b/libraries/botbuilder/src/teamsInfo.ts @@ -58,7 +58,7 @@ export class TeamsInfo { context: TurnContext, meetingId?: string, participantId?: string, - tenantId?: string + tenantId?: string, ): Promise { if (!context) { throw new Error('context is required.'); @@ -151,7 +151,7 @@ export class TeamsInfo { context: TurnContext, activity: Activity, teamsChannelId: string, - botAppId?: string + botAppId?: string, ): Promise<[ConversationReference, string]> { if (!context) { throw new Error('TurnContext cannot be null'); @@ -188,11 +188,11 @@ export class TeamsInfo { async (turnContext) => { conversationReference = TurnContext.getConversationReference(turnContext.activity); newActivityId = turnContext.activity.id; - } + }, ); } else { const connectorClient = (context.adapter as BotFrameworkAdapter).createConnectorClient( - context.activity.serviceUrl + context.activity.serviceUrl, ); const conversationResourceResponse = await connectorClient.conversations.createConversation(convoParams); conversationReference = TurnContext.getConversationReference(context.activity); @@ -225,7 +225,6 @@ export class TeamsInfo { * * @param context The [TurnContext](xref:botbuilder-core.TurnContext) for this turn. * @returns The list of [TeamsChannelAccount](xref:botframework-schema.TeamsChannelAccount). - * * @deprecated Use `getPagedTeamMembers` instead. */ static async getMembers(context: TurnContext): Promise { @@ -250,7 +249,7 @@ export class TeamsInfo { static async getPagedMembers( context: TurnContext, pageSize?: number, - continuationToken?: string + continuationToken?: string, ): Promise { const teamId = this.getTeamId(context); const options: TeamsConnectorModels.ConversationsGetConversationPagedMembersOptionalParams = { @@ -290,7 +289,6 @@ export class TeamsInfo { * @param context The [TurnContext](xref:botbuilder-core.TurnContext) for this turn. * @param teamId ID of the Teams team. * @returns The list of [TeamsChannelAccount](xref:botframework-schema.TeamsChannelAccount) of the members. - * * @deprecated Use `getPagedTeamMembers` instead. */ static async getTeamMembers(context: TurnContext, teamId?: string): Promise { @@ -314,7 +312,7 @@ export class TeamsInfo { context: TurnContext, teamId?: string, pageSize?: number, - continuationToken?: string + continuationToken?: string, ): Promise { const t = teamId || this.getTeamId(context); if (!t) { @@ -357,7 +355,7 @@ export class TeamsInfo { static async sendMeetingNotification( context: TurnContext, notification: MeetingNotification, - meetingId?: string + meetingId?: string, ): Promise { const activity = context.activity; @@ -386,7 +384,7 @@ export class TeamsInfo { context: TurnContext, activity: Activity, tenantId: string, - members: TeamsMember[] + members: TeamsMember[], ): Promise { if (!activity) { throw new Error('activity is required.'); @@ -412,7 +410,7 @@ export class TeamsInfo { static async sendMessageToAllUsersInTenant( context: TurnContext, activity: Activity, - tenantId: string + tenantId: string, ): Promise { if (!activity) { throw new Error('activity is required.'); @@ -437,7 +435,7 @@ export class TeamsInfo { context: TurnContext, activity: Activity, tenantId: string, - teamId: string + teamId: string, ): Promise { if (!activity) { throw new Error('activity is required.'); @@ -452,7 +450,7 @@ export class TeamsInfo { return await this.getTeamsConnectorClient(context).teams.sendMessageToAllUsersInTeam( activity, tenantId, - teamId + teamId, ); } @@ -469,7 +467,7 @@ export class TeamsInfo { context: TurnContext, activity: Activity, tenantId: string, - members: TeamsMember[] + members: TeamsMember[], ): Promise { if (!activity) { throw new Error('activity is required.'); @@ -484,7 +482,7 @@ export class TeamsInfo { return await this.getTeamsConnectorClient(context).teams.sendMessageToListOfChannels( activity, tenantId, - members + members, ); } @@ -538,15 +536,14 @@ export class TeamsInfo { */ private static async getMembersInternal( connectorClient: ConnectorClient, - conversationId: string + conversationId: string, ): Promise { if (!conversationId) { throw new Error('The getMembers operation needs a valid conversationId.'); } - const teamMembers: ChannelAccount[] = await connectorClient.conversations.getConversationMembers( - conversationId - ); + const teamMembers: ChannelAccount[] = + await connectorClient.conversations.getConversationMembers(conversationId); teamMembers.forEach((member): void => { member.aadObjectId = (member as any).objectId; }); @@ -560,7 +557,7 @@ export class TeamsInfo { private static async getPagedMembersInternal( connectorClient: ConnectorClient, conversationId: string, - options: TeamsConnectorModels.ConversationsGetConversationPagedMembersOptionalParams + options: TeamsConnectorModels.ConversationsGetConversationPagedMembersOptionalParams, ): Promise { if (!conversationId) { throw new Error('The getPagedMembers operation needs a valid conversationId.'); @@ -568,7 +565,7 @@ export class TeamsInfo { const pagedMembersResult: PagedMembersResult = await connectorClient.conversations.getConversationPagedMembers( conversationId, - options + options, ); const teamsPagedMembersResult: TeamsPagedMembersResult = { @@ -585,7 +582,7 @@ export class TeamsInfo { private static async getMemberInternal( connectorClient: ConnectorClient, conversationId: string, - userId: string + userId: string, ): Promise { if (!conversationId) { throw new Error('The getMember operation needs a valid conversationId.'); @@ -597,7 +594,7 @@ export class TeamsInfo { const teamMember: ChannelAccount = await connectorClient.conversations.getConversationMember( conversationId, - userId + userId, ); return teamMember as TeamsChannelAccount; diff --git a/libraries/botbuilder/src/zod.ts b/libraries/botbuilder/src/zod.ts index 5a90ebd52a..00f39909bf 100644 --- a/libraries/botbuilder/src/zod.ts +++ b/libraries/botbuilder/src/zod.ts @@ -16,7 +16,7 @@ export const INodeSocketT = z.custom( typeof val.once === 'function' && typeof val.pipe === 'function' && typeof val.write === 'function', - { message: 'INodeSocket' } + { message: 'INodeSocket' }, ); export const LogicT = z.custom<(context: TurnContext) => Promise>((val) => typeof val === 'function'); diff --git a/libraries/botbuilder/tests/botFrameworkAdapter.test.js b/libraries/botbuilder/tests/botFrameworkAdapter.test.js index ca5d995d69..96f5ef0a0d 100644 --- a/libraries/botbuilder/tests/botFrameworkAdapter.test.js +++ b/libraries/botbuilder/tests/botFrameworkAdapter.test.js @@ -89,7 +89,7 @@ class AdapterUnderTest extends BotFrameworkAdapter { assert.strictEqual( authHeader, this.expectAuthHeader, - 'authenticateRequestInternal() not passed expected authHeader.' + 'authenticateRequestInternal() not passed expected authHeader.', ); return this.failAuth ? Promise.reject(new Error('failed auth')) : Promise.resolve({ claims: [] }); } @@ -256,6 +256,7 @@ function createActivity() { describe('BotFrameworkAdapter', function () { let sandbox; + beforeEach(function () { sandbox = sinon.createSandbox(); }); @@ -344,7 +345,7 @@ describe('BotFrameworkAdapter', function () { assert.strictEqual( adapter.webSocketFactory, 'test-web-socket', - 'Adapter should have read settings.webSocketFactory' + 'Adapter should have read settings.webSocketFactory', ); }); }); @@ -368,7 +369,7 @@ describe('BotFrameworkAdapter', function () { const incoming = TurnContext.applyConversationReference( { type: 'message', text: 'foo', callerId: 'foo' }, reference, - true + true, ); incoming.channelId = 'msteams'; @@ -388,7 +389,7 @@ describe('BotFrameworkAdapter', function () { const incoming = TurnContext.applyConversationReference( { type: 'message', text: 'foo', callerId: 'foo' }, reference, - true + true, ); incoming.channelId = 'msteams'; @@ -407,7 +408,7 @@ describe('BotFrameworkAdapter', function () { const adapter = new AdapterUnderTest({ appId: 'bogusApp', appPassword: 'bogusPassword' }); await assert.rejects( adapter.testAuthenticateRequest(req, ''), - new Error('Unauthorized Access. Request is not authorized') + new Error('Unauthorized Access. Request is not authorized'), ); }); }); @@ -483,7 +484,7 @@ describe('BotFrameworkAdapter', function () { headers: new HttpHeaders(), readableStreamBody: undefined, bodyAsText: '', - }) + }), ); const adapter = new BotFrameworkAdapter({ clientOptions: { httpClient: { sendRequest } } }); @@ -497,14 +498,14 @@ describe('BotFrameworkAdapter', function () { assert( sendRequest.called, - 'sendRequest on HttpClient provided to BotFrameworkAdapter.clientOptions was not called when sending an activity' + 'sendRequest on HttpClient provided to BotFrameworkAdapter.clientOptions was not called when sending an activity', ); const [request] = sendRequest.args[0]; assert.deepStrictEqual( JSON.parse(request.body), outgoingMessageLocale, - 'sentActivity should flow through custom httpClient.sendRequest' + 'sentActivity should flow through custom httpClient.sendRequest', ); }); @@ -519,7 +520,7 @@ describe('BotFrameworkAdapter', function () { assert( connectorClient._requestPolicyFactories.find((policy) => policy === setUserAgent), - 'requestPolicyFactories from clientOptions parameter is not used.' + 'requestPolicyFactories from clientOptions parameter is not used.', ); }); }); @@ -555,7 +556,7 @@ describe('BotFrameworkAdapter', function () { const adapter = new BotFrameworkAdapter(); await assert.rejects( adapter.createConnectorClientWithIdentity('https://serviceurl.com'), - new Error('BotFrameworkAdapter.createConnectorClientWithIdentity(): invalid identity parameter.') + new Error('BotFrameworkAdapter.createConnectorClientWithIdentity(): invalid identity parameter.'), ); }); @@ -575,7 +576,7 @@ describe('BotFrameworkAdapter', function () { .mock(adapter) .expects('buildCredentials') .callsFake((appId, oAuthScope) => - Promise.resolve(new MicrosoftAppCredentials(appId, '', undefined, oAuthScope)) + Promise.resolve(new MicrosoftAppCredentials(appId, '', undefined, oAuthScope)), ) .once(); @@ -606,7 +607,7 @@ describe('BotFrameworkAdapter', function () { .mock(adapter) .expects('buildCredentials') .callsFake((appId, oAuthScope) => - Promise.resolve(new MicrosoftAppCredentials(appId, '', undefined, oAuthScope)) + Promise.resolve(new MicrosoftAppCredentials(appId, '', undefined, oAuthScope)), ) .once(); @@ -635,7 +636,7 @@ describe('BotFrameworkAdapter', function () { .mock(adapter) .expects('buildCredentials') .callsFake((appId, oAuthScope) => - Promise.resolve(new MicrosoftAppCredentials(appId, '', undefined, oAuthScope)) + Promise.resolve(new MicrosoftAppCredentials(appId, '', undefined, oAuthScope)), ) .once(); @@ -655,7 +656,7 @@ describe('BotFrameworkAdapter', function () { const connector = await adapter.createConnectorClientWithIdentity( 'https://serviceurl.com', - new ClaimsIdentity([{ type: AuthenticationConstants.AppIdClaim, value: appId }]) + new ClaimsIdentity([{ type: AuthenticationConstants.AppIdClaim, value: appId }]), ); const credentials = connector.credentials; @@ -673,7 +674,7 @@ describe('BotFrameworkAdapter', function () { const connector = await adapter.createConnectorClientWithIdentity( 'https://serviceurl.com', - new ClaimsIdentity([{ type: AuthenticationConstants.AppIdClaim, value: appId }]) + new ClaimsIdentity([{ type: AuthenticationConstants.AppIdClaim, value: appId }]), ); const credentials = connector.credentials; @@ -692,7 +693,7 @@ describe('BotFrameworkAdapter', function () { const connector = await adapter.createConnectorClientWithIdentity( 'https://serviceurl.com', - new ClaimsIdentity([{ type: AuthenticationConstants.AudienceClaim, value: appId }]) + new ClaimsIdentity([{ type: AuthenticationConstants.AudienceClaim, value: appId }]), ); const credentials = connector.credentials; @@ -726,7 +727,7 @@ describe('BotFrameworkAdapter', function () { await context.sendActivity({ type: 'invokeResponse', text: '1st message' }); await context.sendActivity({ type: 'invokeResponse', text: '2nd message' }); }, - { activity } + { activity }, ); assertResponse(response, StatusCodes.OK, true); @@ -743,7 +744,7 @@ describe('BotFrameworkAdapter', function () { text: '2nd message', type: 'invokeResponse', }, - ] + ], ); }); @@ -760,7 +761,7 @@ describe('BotFrameworkAdapter', function () { await context.sendActivity({ type: 'invokeResponse', text: 'message' }); await context.sendActivity(testTraceMessage); }, - { activity } + { activity }, ); assertResponse(response, StatusCodes.OK, true); @@ -773,7 +774,7 @@ describe('BotFrameworkAdapter', function () { text: 'message', type: 'invokeResponse', }, - ] + ], ); }); @@ -790,7 +791,7 @@ describe('BotFrameworkAdapter', function () { await context.sendActivity({ type: 'invokeResponse', text: 'message' }); await context.sendActivity(testTraceMessage); }, - { activity } + { activity }, ); assertResponse(response, StatusCodes.OK, true); @@ -798,7 +799,7 @@ describe('BotFrameworkAdapter', function () { assert.deepStrictEqual( response.body.activities.map(({ type }) => type), - ['invokeResponse', 'trace'] + ['invokeResponse', 'trace'], ); }); @@ -843,7 +844,7 @@ describe('BotFrameworkAdapter', function () { assert.strictEqual( typeof context.activity.timestamp, 'object', - "'context.activity.timestamp' is not a date" + "'context.activity.timestamp' is not a date", ); assert(context.activity.timestamp instanceof Date, "'context.activity.timestamp' is not a date"); @@ -851,15 +852,15 @@ describe('BotFrameworkAdapter', function () { assert.strictEqual( typeof context.activity.localTimestamp, 'object', - "'context.activity.localTimestamp' is not a date" + "'context.activity.localTimestamp' is not a date", ); assert( context.activity.localTimestamp instanceof Date, - "'context.activity.localTimestamp' is not a date" + "'context.activity.localTimestamp' is not a date", ); }, - { activity } + { activity }, ); assertResponse(response, StatusCodes.OK); @@ -874,7 +875,7 @@ describe('BotFrameworkAdapter', function () { assert(!fake.called); assertResponse(response, 400, true); return true; - } + }, ); }); @@ -886,7 +887,7 @@ describe('BotFrameworkAdapter', function () { assert(!fake.called); assertResponse(response, 400, true); return true; - } + }, ); }); @@ -894,7 +895,7 @@ describe('BotFrameworkAdapter', function () { const activity = TurnContext.applyConversationReference( { type: 'message', text: 'foo', channelData: { tenant: { id: '1234' } } }, reference, - true + true, ); activity.channelId = 'msteams'; @@ -903,10 +904,10 @@ describe('BotFrameworkAdapter', function () { assert.strictEqual( context.activity.conversation.tenantId, '1234', - 'should have copied tenant id from channelData to conversation address' + 'should have copied tenant id from channelData to conversation address', ); }, - { activity } + { activity }, ); assertResponse(response, StatusCodes.OK); @@ -917,7 +918,7 @@ describe('BotFrameworkAdapter', function () { const activity = TurnContext.applyConversationReference( { type: 'message', text: 'foo', semanticAction: { state: 'start' } }, reference, - true + true, ); activity.channelId = 'msteams'; @@ -925,7 +926,7 @@ describe('BotFrameworkAdapter', function () { (context) => { assert(context.activity.semanticAction.state === 'start'); }, - { activity } + { activity }, ); assertResponse(response, StatusCodes.OK); @@ -936,7 +937,7 @@ describe('BotFrameworkAdapter', function () { const processIncoming = async ( incoming, handler, - { adapterArgs = {}, authDisabled = false, claims = [] } = {} + { adapterArgs = {}, authDisabled = false, claims = [] } = {}, ) => { // Sets up expectation for JWT validation to pass back claims mockReturns(JwtTokenValidation, 'authenticateRequest', new ClaimsIdentity(claims, true)); @@ -965,7 +966,7 @@ describe('BotFrameworkAdapter', function () { const incoming = TurnContext.applyConversationReference( { type: 'message', text: 'foo', callerId: 'foo' }, reference, - true + true, ); incoming.channelId = 'msteams'; @@ -986,7 +987,7 @@ describe('BotFrameworkAdapter', function () { (context) => { assert.strictEqual( context.activity.callerId, - `${CallerIdConstants.BotToBotPrefix}${skillConsumerAppId}` + `${CallerIdConstants.BotToBotPrefix}${skillConsumerAppId}`, ); }, { @@ -995,7 +996,7 @@ describe('BotFrameworkAdapter', function () { { type: AuthenticationConstants.AppIdClaim, value: skillConsumerAppId }, { type: AuthenticationConstants.VersionClaim, value: '1.0' }, ], - } + }, ); }); @@ -1003,7 +1004,7 @@ describe('BotFrameworkAdapter', function () { const incoming = TurnContext.applyConversationReference( { type: 'message', text: 'foo', callerId: 'foo' }, reference, - true + true, ); incoming.channelId = 'msteams'; @@ -1012,7 +1013,7 @@ describe('BotFrameworkAdapter', function () { (context) => { assert.strictEqual(context.activity.callerId, undefined); }, - { authDisabled: true } + { authDisabled: true }, ); }); @@ -1033,7 +1034,7 @@ describe('BotFrameworkAdapter', function () { { type: AuthenticationConstants.AudienceClaim, value: skillAppId }, { type: AuthenticationConstants.VersionClaim, value: '1.0' }, ], - } + }, ); }); }); @@ -1042,7 +1043,7 @@ describe('BotFrameworkAdapter', function () { const incoming = TurnContext.applyConversationReference( { type: 'message', text: 'foo', callerId: 'foo' }, reference, - true + true, ); incoming.channelId = 'msteams'; @@ -1063,7 +1064,7 @@ describe('BotFrameworkAdapter', function () { assert(!fake.called); return true; - } + }, ); }); @@ -1078,7 +1079,7 @@ describe('BotFrameworkAdapter', function () { assert(fake.called); return true; - } + }, ); }); @@ -1086,7 +1087,7 @@ describe('BotFrameworkAdapter', function () { const createConversation = async ( reference, handler, - { adapterArgs, createConversationParams, testAdapterArgs } = {} + { adapterArgs, createConversationParams, testAdapterArgs } = {}, ) => { const adapter = new AdapterUnderTest(adapterArgs, testAdapterArgs); @@ -1120,7 +1121,7 @@ describe('BotFrameworkAdapter', function () { assert(context.activity.conversation, 'activity has no conversation'); assert(context.activity.conversation.isGroup, 'activity isGroup is not true'); }, - { createConversationParams: { isGroup: true } } + { createConversationParams: { isGroup: true } }, ); }); @@ -1133,17 +1134,17 @@ describe('BotFrameworkAdapter', function () { assert.strictEqual( context.activity.conversation.id, 'convo2', - 'request has invalid conversation.id.' + 'request has invalid conversation.id.', ); assert.strictEqual( context.activity.serviceUrl, 'https://example.org/channel2', - 'request has invalid conversation.id.' + 'request has invalid conversation.id.', ); }, { testAdapterArgs: { newServiceUrl: 'https://example.org/channel2' }, - } + }, ); }); @@ -1158,7 +1159,7 @@ describe('BotFrameworkAdapter', function () { assert(!fake.called); return true; - } + }, ); }); @@ -1179,13 +1180,13 @@ describe('BotFrameworkAdapter', function () { assert.strictEqual( context.activity.conversation.tenantId, tenantReference.conversation.tenantId, - 'request has invalid tenantId on conversation.' + 'request has invalid tenantId on conversation.', ); assert.strictEqual( context.activity.channelData.tenant.id, tenantReference.conversation.tenantId, - 'request has invalid tenantId in channelData.' + 'request has invalid tenantId in channelData.', ); }); }); @@ -1198,7 +1199,7 @@ describe('BotFrameworkAdapter', function () { const responses = await adapter.sendActivities(context, [outgoingMessage]); assert.deepStrictEqual( responses.map(({ id }) => id), - ['5678'] + ['5678'], ); }); @@ -1251,7 +1252,7 @@ describe('BotFrameworkAdapter', function () { it('should return bots invokeResponse', async function () { const { response, verify } = await processActivity( (context) => context.sendActivity({ type: 'invokeResponse', value: { status: 200, body: 'body' } }), - { activity: incomingInvoke } + { activity: incomingInvoke }, ); assertResponse(response, StatusCodes.OK, true); verify(); @@ -1266,7 +1267,7 @@ describe('BotFrameworkAdapter', function () { assert(fake.called); return true; - } + }, ); }); @@ -1298,7 +1299,7 @@ describe('BotFrameworkAdapter', function () { const responses = await adapter.sendActivities(context, [copy]); assert.deepStrictEqual( responses.map(({ id }) => id), - ['5678'] + ['5678'], ); }); @@ -1404,7 +1405,7 @@ describe('BotFrameworkAdapter', function () { assert.strictEqual( testEndpoint, connector.ChannelValidation.OpenIdMetadataEndpoint, - 'ChannelValidation.OpenIdMetadataEndpoint was not set.' + 'ChannelValidation.OpenIdMetadataEndpoint was not set.', ); }); @@ -1415,7 +1416,7 @@ describe('BotFrameworkAdapter', function () { assert.strictEqual( testEndpoint, connector.GovernmentChannelValidation.OpenIdMetadataEndpoint, - 'GovernmentChannelValidation.OpenIdMetadataEndpoint was not set.' + 'GovernmentChannelValidation.OpenIdMetadataEndpoint was not set.', ); }); }); @@ -1431,7 +1432,7 @@ describe('BotFrameworkAdapter', function () { const adapter = new AdapterUnderTest(); await assert.rejects( adapter.deleteConversationMember({ activity: {} }), - new Error('BotFrameworkAdapter.deleteConversationMember(): missing serviceUrl') + new Error('BotFrameworkAdapter.deleteConversationMember(): missing serviceUrl'), ); }); @@ -1439,7 +1440,7 @@ describe('BotFrameworkAdapter', function () { const adapter = new AdapterUnderTest(); await assert.rejects( adapter.deleteConversationMember({ activity: { serviceUrl: 'https://test.com' } }), - new Error('BotFrameworkAdapter.deleteConversationMember(): missing conversation or conversation.id') + new Error('BotFrameworkAdapter.deleteConversationMember(): missing conversation or conversation.id'), ); }); @@ -1447,7 +1448,7 @@ describe('BotFrameworkAdapter', function () { const adapter = new AdapterUnderTest(); await assert.rejects( adapter.deleteConversationMember({ activity: { serviceUrl: 'https://test.com', conversation: {} } }), - new Error('BotFrameworkAdapter.deleteConversationMember(): missing conversation or conversation.id') + new Error('BotFrameworkAdapter.deleteConversationMember(): missing conversation or conversation.id'), ); }); @@ -1461,7 +1462,7 @@ describe('BotFrameworkAdapter', function () { await adapter.deleteConversationMember( { activity: { serviceUrl: 'https://test.com', conversation: { id: 'convo1' } } }, - 'test-member' + 'test-member', ); sandbox.verify(); @@ -1471,7 +1472,7 @@ describe('BotFrameworkAdapter', function () { const adapter = new AdapterUnderTest(); await assert.rejects( adapter.getActivityMembers({ activity: {} }), - new Error('BotFrameworkAdapter.getActivityMembers(): missing serviceUrl') + new Error('BotFrameworkAdapter.getActivityMembers(): missing serviceUrl'), ); }); @@ -1479,7 +1480,7 @@ describe('BotFrameworkAdapter', function () { const adapter = new AdapterUnderTest(); await assert.rejects( adapter.getActivityMembers({ activity: { serviceUrl: 'https://test.com' } }), - new Error('BotFrameworkAdapter.getActivityMembers(): missing conversation or conversation.id') + new Error('BotFrameworkAdapter.getActivityMembers(): missing conversation or conversation.id'), ); }); @@ -1487,7 +1488,7 @@ describe('BotFrameworkAdapter', function () { const adapter = new AdapterUnderTest(); await assert.rejects( adapter.getActivityMembers({ activity: { serviceUrl: 'https://test.com', conversation: {} } }), - new Error('BotFrameworkAdapter.getActivityMembers(): missing conversation or conversation.id') + new Error('BotFrameworkAdapter.getActivityMembers(): missing conversation or conversation.id'), ); }); @@ -1497,7 +1498,7 @@ describe('BotFrameworkAdapter', function () { adapter.getActivityMembers({ activity: { serviceUrl: 'https://test.com', conversation: { id: '1' } }, }), - new Error('BotFrameworkAdapter.getActivityMembers(): missing both activityId and context.activity.id') + new Error('BotFrameworkAdapter.getActivityMembers(): missing both activityId and context.activity.id'), ); }); @@ -1512,7 +1513,7 @@ describe('BotFrameworkAdapter', function () { await adapter.getActivityMembers( { activity: { serviceUrl: 'https://test.com', conversation: { id: 'convo1' } } }, - 'activityId' + 'activityId', ); sandbox.verify(); @@ -1522,7 +1523,7 @@ describe('BotFrameworkAdapter', function () { const adapter = new AdapterUnderTest(); await assert.rejects( adapter.getConversationMembers({ activity: {} }), - new Error('BotFrameworkAdapter.getConversationMembers(): missing serviceUrl') + new Error('BotFrameworkAdapter.getConversationMembers(): missing serviceUrl'), ); }); @@ -1530,7 +1531,7 @@ describe('BotFrameworkAdapter', function () { const adapter = new AdapterUnderTest(); await assert.rejects( adapter.getConversationMembers({ activity: { serviceUrl: 'https://test.com' } }), - new Error('BotFrameworkAdapter.getConversationMembers(): missing conversation or conversation.id') + new Error('BotFrameworkAdapter.getConversationMembers(): missing conversation or conversation.id'), ); }); @@ -1538,7 +1539,7 @@ describe('BotFrameworkAdapter', function () { const adapter = new AdapterUnderTest(); await assert.rejects( adapter.getConversationMembers({ activity: { serviceUrl: 'https://test.com', conversation: {} } }), - new Error('BotFrameworkAdapter.getConversationMembers(): missing conversation or conversation.id') + new Error('BotFrameworkAdapter.getConversationMembers(): missing conversation or conversation.id'), ); }); @@ -1561,7 +1562,7 @@ describe('BotFrameworkAdapter', function () { const adapter = new AdapterUnderTest(); await assert.rejects( adapter.getUserToken({ activity: {}, turnState: new Map() }), - new Error('BotFrameworkAdapter.getUserToken(): missing from or from.id') + new Error('BotFrameworkAdapter.getUserToken(): missing from or from.id'), ); }); @@ -1569,7 +1570,7 @@ describe('BotFrameworkAdapter', function () { const adapter = new AdapterUnderTest(); await assert.rejects( adapter.getUserToken({ activity: { from: {} }, turnState: new Map() }), - new Error('BotFrameworkAdapter.getUserToken(): missing from or from.id') + new Error('BotFrameworkAdapter.getUserToken(): missing from or from.id'), ); }); @@ -1577,7 +1578,7 @@ describe('BotFrameworkAdapter', function () { const adapter = new AdapterUnderTest(); await assert.rejects( adapter.getUserToken({ activity: { from: { id: 'some id' } }, turnState: new Map() }), - new Error('getUserToken() requires a connectionName but none was provided.') + new Error('getUserToken() requires a connectionName but none was provided.'), ); }); @@ -1590,7 +1591,7 @@ describe('BotFrameworkAdapter', function () { const token = await adapter.getUserToken( { activity: { channelId: 'The Facebook', from: { id: 'some id' } }, turnState: new Map() }, - 'aConnectionName' + 'aConnectionName', ); sandbox.verify(); @@ -1608,7 +1609,7 @@ describe('BotFrameworkAdapter', function () { const adapter = new AdapterUnderTest(); await assert.rejects( adapter.signOutUser({ activity: {}, turnState: new Map() }), - new Error('BotFrameworkAdapter.signOutUser(): missing from or from.id') + new Error('BotFrameworkAdapter.signOutUser(): missing from or from.id'), ); }); @@ -1616,7 +1617,7 @@ describe('BotFrameworkAdapter', function () { const adapter = new AdapterUnderTest(); await assert.rejects( adapter.signOutUser({ activity: { from: {} }, turnState: new Map() }), - new Error('BotFrameworkAdapter.signOutUser(): missing from or from.id') + new Error('BotFrameworkAdapter.signOutUser(): missing from or from.id'), ); }); @@ -1637,7 +1638,7 @@ describe('BotFrameworkAdapter', function () { const adapter = new AdapterUnderTest(); await assert.rejects( adapter.getAadTokens({ activity: {}, turnState: new Map() }), - new Error('BotFrameworkAdapter.getAadTokens(): missing from or from.id') + new Error('BotFrameworkAdapter.getAadTokens(): missing from or from.id'), ); }); @@ -1645,7 +1646,7 @@ describe('BotFrameworkAdapter', function () { const adapter = new AdapterUnderTest(); await assert.rejects( adapter.getAadTokens({ activity: { from: {} }, turnState: new Map() }), - new Error('BotFrameworkAdapter.getAadTokens(): missing from or from.id') + new Error('BotFrameworkAdapter.getAadTokens(): missing from or from.id'), ); }); @@ -1693,9 +1694,9 @@ describe('BotFrameworkAdapter', function () { context, 'aConnectionName', new MicrosoftAppCredentials('abc', 'abc'), - 'invalidId' + 'invalidId', ), - ReferenceError("cannot retrieve OAuth signin link for a user that's different from the conversation") + ReferenceError("cannot retrieve OAuth signin link for a user that's different from the conversation"), ); }); @@ -1711,7 +1712,7 @@ describe('BotFrameworkAdapter', function () { const response = await adapter.getSignInLink( context, 'aConnectionName', - new MicrosoftAppCredentials('abc', 'abc') + new MicrosoftAppCredentials('abc', 'abc'), ); assert(response, mockedUrl); verify(); @@ -1724,7 +1725,7 @@ describe('BotFrameworkAdapter', function () { 'aConnectionName', new MicrosoftAppCredentials('abc', 'abc'), incomingMessage.from.id, - 'http://finalredirect.com' + 'http://finalredirect.com', ); assert(response, mockedUrl); verify(); @@ -1755,7 +1756,7 @@ describe('BotFrameworkAdapter', function () { const { adapter, context } = getMockedAdapter(); await assert.rejects( adapter.getSignInResource(context), - new Error('getUserToken() requires a connectionName but none was provided.') + new Error('getUserToken() requires a connectionName but none was provided.'), ); }); @@ -1766,7 +1767,7 @@ describe('BotFrameworkAdapter', function () { const { adapter, context } = getMockedAdapter(activity); await assert.rejects( adapter.getSignInResource(context, 'TestConnectionName'), - new Error('BotFrameworkAdapter.getSignInResource(): missing from or from.id') + new Error('BotFrameworkAdapter.getSignInResource(): missing from or from.id'), ); }); @@ -1777,7 +1778,7 @@ describe('BotFrameworkAdapter', function () { const { adapter, context } = getMockedAdapter(activity); await assert.rejects( adapter.getSignInResource(context, 'TestConnectionName'), - new Error('BotFrameworkAdapter.getSignInResource(): missing from or from.id') + new Error('BotFrameworkAdapter.getSignInResource(): missing from or from.id'), ); }); @@ -1786,8 +1787,8 @@ describe('BotFrameworkAdapter', function () { await assert.rejects( adapter.getSignInResource(context, 'TestConnectionName', 'OtherUserId'), new Error( - 'BotFrameworkAdapter.getSiginInResource(): cannot get signin resource for a user that is different from the conversation' - ) + 'BotFrameworkAdapter.getSiginInResource(): cannot get signin resource for a user that is different from the conversation', + ), ); }); @@ -1815,7 +1816,7 @@ describe('BotFrameworkAdapter', function () { const { adapter, context } = getMockedAdapter(); await assert.rejects( adapter.exchangeToken(context), - new Error('exchangeToken() requires a connectionName but none was provided.') + new Error('exchangeToken() requires a connectionName but none was provided.'), ); }); @@ -1823,7 +1824,7 @@ describe('BotFrameworkAdapter', function () { const { adapter, context } = getMockedAdapter(); await assert.rejects( adapter.exchangeToken(context, 'TestConnectionName'), - new Error('exchangeToken() requires an userId but none was provided.') + new Error('exchangeToken() requires an userId but none was provided.'), ); }); @@ -1832,8 +1833,8 @@ describe('BotFrameworkAdapter', function () { await assert.rejects( adapter.exchangeToken(context, 'TestConnectionName', 'TestUser', {}), new Error( - 'BotFrameworkAdapter.exchangeToken(): Either a Token or Uri property is required on the TokenExchangeRequest' - ) + 'BotFrameworkAdapter.exchangeToken(): Either a Token or Uri property is required on the TokenExchangeRequest', + ), ); }); @@ -1881,7 +1882,7 @@ describe('BotFrameworkAdapter', function () { const adapter = new AdapterUnderTest(); await assert.rejects( adapter.getTokenStatus({ activity: {}, turnState: new Map() }), - new Error('BotFrameworkAdapter.getTokenStatus(): missing from or from.id') + new Error('BotFrameworkAdapter.getTokenStatus(): missing from or from.id'), ); }); @@ -1889,7 +1890,7 @@ describe('BotFrameworkAdapter', function () { const adapter = new AdapterUnderTest(); await assert.rejects( adapter.getTokenStatus({ activity: { from: {} }, turnState: new Map() }), - new Error('BotFrameworkAdapter.getTokenStatus(): missing from or from.id') + new Error('BotFrameworkAdapter.getTokenStatus(): missing from or from.id'), ); }); }); @@ -1902,7 +1903,7 @@ describe('BotFrameworkAdapter', function () { // Empty Claims assert.strictEqual( AuthenticationConstants.ToChannelFromBotOAuthScope, - await adapter.getOAuthScope('botAppId', []) + await adapter.getOAuthScope('botAppId', []), ); // Non-skill Claims @@ -1911,7 +1912,7 @@ describe('BotFrameworkAdapter', function () { await adapter.getOAuthScope('botAppId', [ { type: 'aud', value: 'botAppId' }, { type: 'azp', value: 'botAppId' }, - ]) + ]), ); const govAdapter = new BotFrameworkAdapter({ channelService: GovernmentConstants.ChannelService }); @@ -1921,7 +1922,7 @@ describe('BotFrameworkAdapter', function () { // Empty Claims assert.strictEqual( GovernmentConstants.ToChannelFromBotOAuthScope, - await govAdapter.getOAuthScope('botAppId', []) + await govAdapter.getOAuthScope('botAppId', []), ); // Non-skill Claims @@ -1930,7 +1931,7 @@ describe('BotFrameworkAdapter', function () { await govAdapter.getOAuthScope('botAppId', [ { type: 'aud', value: 'botAppId' }, { type: 'azp', value: 'botAppId' }, - ]) + ]), ); }); @@ -1960,7 +1961,7 @@ describe('BotFrameworkAdapter', function () { assert.strictEqual( context.activity.recipient.id, reference.bot.id, - 'request has invalid recipient.id.' + 'request has invalid recipient.id.', ); }); }); @@ -1974,7 +1975,7 @@ describe('BotFrameworkAdapter', function () { assert.strictEqual( context.activity.recipient.id, reference.bot.id, - 'request has invalid recipient.id.' + 'request has invalid recipient.id.', ); }); }); @@ -1988,7 +1989,7 @@ describe('BotFrameworkAdapter', function () { assert.strictEqual( context.activity.recipient.id, reference.bot.id, - 'request has invalid recipient.id.' + 'request has invalid recipient.id.', ); }); }); @@ -2006,7 +2007,7 @@ describe('BotFrameworkAdapter', function () { assert.strictEqual(context.activity.recipient.id, reference.bot.id); assert.strictEqual(context.turnState.get(context.adapter.OAuthScopeKey), oauthScope); }, - { oauthScope } + { oauthScope }, ); }); @@ -2023,12 +2024,12 @@ describe('BotFrameworkAdapter', function () { assert.strictEqual( context.turnState.get(context.adapter.OAuthScopeKey), - GovernmentConstants.ToChannelFromBotOAuthScope + GovernmentConstants.ToChannelFromBotOAuthScope, ); }, { adapterArgs: { channelService: GovernmentConstants.ChannelService }, - } + }, ); }); }); @@ -2086,7 +2087,7 @@ describe('BotFrameworkAdapter', function () { await assert.rejects( adapter.processActivityDirect(createActivity(), () => null), - new Error('BotFrameworkAdapter.processActivityDirect(): ERROR\n test-error') + new Error('BotFrameworkAdapter.processActivityDirect(): ERROR\n test-error'), ); sandbox.verify(); @@ -2098,7 +2099,7 @@ describe('BotFrameworkAdapter', function () { await assert.rejects( adapter.processActivityDirect(createActivity(), 'callbackLogic'), - new Error('BotFrameworkAdapter.processActivityDirect(): ERROR') + new Error('BotFrameworkAdapter.processActivityDirect(): ERROR'), ); sandbox.verify(); diff --git a/libraries/botbuilder/tests/botFrameworkHttpClient.test.js b/libraries/botbuilder/tests/botFrameworkHttpClient.test.js index e7068ff9ff..f8d54e0257 100644 --- a/libraries/botbuilder/tests/botFrameworkHttpClient.test.js +++ b/libraries/botbuilder/tests/botFrameworkHttpClient.test.js @@ -55,7 +55,7 @@ describe('BotFrameworkHttpClient', function () { it('should fail to construct without required parameters', function () { assert.throws( () => new BotFrameworkHttpClient(), - new Error('BotFrameworkHttpClient(): missing credentialProvider') + new Error('BotFrameworkHttpClient(): missing credentialProvider'), ); }); @@ -74,7 +74,7 @@ describe('BotFrameworkHttpClient', function () { 'http://skillUrl/api/good', 'serviceUrl', 'conversationId', - { type: 'message', conversation: {} } + { type: 'message', conversation: {} }, ); assert.strictEqual(response.status, 200); }); @@ -94,7 +94,7 @@ describe('BotFrameworkHttpClient', function () { 'http://skillUrl/api/bad', 'serviceUrl', 'conversationId', - { type: 'message', conversation: {} } + { type: 'message', conversation: {} }, ); assert.strictEqual(response.status, 404); }); @@ -114,7 +114,7 @@ describe('BotFrameworkHttpClient', function () { 'http://skillUrl/api/good', 'serviceUrl', 'conversationId', - { type: 'message', conversation: {} } + { type: 'message', conversation: {} }, ); assert.strictEqual(response.status, 200); }); @@ -135,9 +135,11 @@ describe('BotFrameworkHttpClient', function () { 'http://skillUrl/api/good', 'serviceUrl', 'conversationId', - { type: 'message', conversation: {} } + { type: 'message', conversation: {} }, + ), + new Error( + 'BotFrameworkHttpClient.postActivity(): Unable to get appCredentials to connect to the skill', ), - new Error('BotFrameworkHttpClient.postActivity(): Unable to get appCredentials to connect to the skill') ); }); @@ -153,7 +155,7 @@ describe('BotFrameworkHttpClient', function () { await assert.rejects( client.postActivity(fromBotId, 'toBotId', 'http://skillUrl/api/good', 'serviceUrl', 'conversationId'), - new Error('BotFrameworkHttpClient.postActivity(): missing activity') + new Error('BotFrameworkHttpClient.postActivity(): missing activity'), ); }); @@ -175,9 +177,9 @@ describe('BotFrameworkHttpClient', function () { 'http://skillUrl/api/good', 'serviceUrl', 'conversationId', - activity + activity, ), - new Error('BotFrameworkHttpClient.postActivity(): Activity must have a ConversationReference') + new Error('BotFrameworkHttpClient.postActivity(): Activity must have a ConversationReference'), ); }); @@ -197,7 +199,7 @@ describe('BotFrameworkHttpClient', function () { 'http://skillUrl/api/good', 'serviceUrl', 'conversationId', - activity + activity, ); assert.strictEqual(response.status, 200); assert.strictEqual(activity.recipient, undefined); @@ -220,7 +222,7 @@ describe('BotFrameworkHttpClient', function () { 'http://skillUrl/api/good', 'serviceUrl', 'conversationId', - forwardedActivity + forwardedActivity, ); assert.strictEqual(forwardedActivity.relatesTo, originalRelatesTo); }); diff --git a/libraries/botbuilder/tests/channelServiceHandler.test.js b/libraries/botbuilder/tests/channelServiceHandler.test.js index 97de7039b9..a6ae97d439 100644 --- a/libraries/botbuilder/tests/channelServiceHandler.test.js +++ b/libraries/botbuilder/tests/channelServiceHandler.test.js @@ -41,6 +41,7 @@ describe('ChannelServiceHandler', function () { const handler = new ChannelServiceHandler(CREDENTIALS, AUTH_CONFIG, 'channels'); let sandbox; + beforeEach(function () { sandbox = sinon.createSandbox(); }); @@ -86,7 +87,7 @@ describe('ChannelServiceHandler', function () { await assert.rejects( handler.handleSendToConversation(AUTH_HEADER, 'convId', { type: ActivityTypes.Message }), - matchStatusCodeError('onSendToConversation') + matchStatusCodeError('onSendToConversation'), ); }); }); @@ -97,7 +98,7 @@ describe('ChannelServiceHandler', function () { await assert.rejects( handler.handleReplyToActivity(AUTH_HEADER, 'convId', ACTIVITY.id, ACTIVITY), - matchStatusCodeError('onReplyToActivity') + matchStatusCodeError('onReplyToActivity'), ); }); }); @@ -108,7 +109,7 @@ describe('ChannelServiceHandler', function () { await assert.rejects( handler.handleUpdateActivity(AUTH_HEADER, 'convId', ACTIVITY.id, ACTIVITY), - matchStatusCodeError('onUpdateActivity') + matchStatusCodeError('onUpdateActivity'), ); }); }); @@ -119,7 +120,7 @@ describe('ChannelServiceHandler', function () { await assert.rejects( handler.handleDeleteActivity(AUTH_HEADER, 'convId', ACTIVITY.id, ACTIVITY), - matchStatusCodeError('onDeleteActivity') + matchStatusCodeError('onDeleteActivity'), ); }); }); @@ -130,7 +131,7 @@ describe('ChannelServiceHandler', function () { await assert.rejects( handler.handleGetActivityMembers(AUTH_HEADER, 'convId', ACTIVITY.id), - matchStatusCodeError('onGetActivityMembers') + matchStatusCodeError('onGetActivityMembers'), ); }); }); @@ -141,7 +142,7 @@ describe('ChannelServiceHandler', function () { await assert.rejects( handler.handleCreateConversation(AUTH_HEADER, { isGroup: false }), - matchStatusCodeError('onCreateConversation') + matchStatusCodeError('onCreateConversation'), ); }); }); @@ -152,7 +153,7 @@ describe('ChannelServiceHandler', function () { await assert.rejects( handler.handleGetConversations(AUTH_HEADER, 'convId'), - matchStatusCodeError('onGetConversations') + matchStatusCodeError('onGetConversations'), ); }); }); @@ -163,7 +164,7 @@ describe('ChannelServiceHandler', function () { await assert.rejects( handler.handleGetConversationMembers(AUTH_HEADER, 'convId'), - matchStatusCodeError('onGetConversationMembers') + matchStatusCodeError('onGetConversationMembers'), ); }); @@ -172,7 +173,7 @@ describe('ChannelServiceHandler', function () { await assert.rejects( handler.handleGetConversationPagedMembers(AUTH_HEADER, 'convId'), - matchStatusCodeError('onGetConversationPagedMembers') + matchStatusCodeError('onGetConversationPagedMembers'), ); }); @@ -181,7 +182,7 @@ describe('ChannelServiceHandler', function () { await assert.rejects( handler.handleDeleteConversationMember(AUTH_HEADER, 'convId', 'memberId'), - matchStatusCodeError('onDeleteConversationMember') + matchStatusCodeError('onDeleteConversationMember'), ); }); }); @@ -192,7 +193,7 @@ describe('ChannelServiceHandler', function () { await assert.rejects( handler.handleSendConversationHistory(AUTH_HEADER, 'convId', { ACTIVITY }), - matchStatusCodeError('onSendConversationHistory') + matchStatusCodeError('onSendConversationHistory'), ); }); }); @@ -203,7 +204,7 @@ describe('ChannelServiceHandler', function () { await assert.rejects( handler.handleUploadAttachment(AUTH_HEADER, 'convId', { type: 'string', name: 'attachment' }), - matchStatusCodeError('onUploadAttachment') + matchStatusCodeError('onUploadAttachment'), ); }); }); diff --git a/libraries/botbuilder/tests/channelServiceRoutes.test.js b/libraries/botbuilder/tests/channelServiceRoutes.test.js index 6f3467be71..8d830a4ff4 100644 --- a/libraries/botbuilder/tests/channelServiceRoutes.test.js +++ b/libraries/botbuilder/tests/channelServiceRoutes.test.js @@ -31,6 +31,7 @@ class MockResponse { describe('channelServiceRoutes', function () { let sandbox; + beforeEach(function () { sandbox = sinon.createSandbox(); }); @@ -50,6 +51,7 @@ describe('channelServiceRoutes', function () { describe('register()', function () { let channel, server; + beforeEach(function () { const testHandler = sandbox.mock(ChannelServiceHandler); channel = new ChannelServiceRoutes(testHandler); @@ -120,7 +122,7 @@ describe('channelServiceRoutes', function () { statusCode: 200, body: testResource, }, - done + done, ); const service = sandbox.createStubInstance(ChannelServiceHandler); @@ -145,7 +147,7 @@ describe('channelServiceRoutes', function () { assert.deepStrictEqual( err, resourceResponse, - `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}` + `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}`, ); done(); }; @@ -171,7 +173,7 @@ describe('channelServiceRoutes', function () { assert.deepStrictEqual( err, resourceResponse, - `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}` + `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}`, ); done(); }; @@ -197,7 +199,7 @@ describe('channelServiceRoutes', function () { statusCode: 200, body: testResource, }, - done + done, ); const service = sandbox.createStubInstance(ChannelServiceHandler); @@ -222,7 +224,7 @@ describe('channelServiceRoutes', function () { assert.deepStrictEqual( err, resourceResponse, - `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}` + `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}`, ); done(); }; @@ -249,7 +251,7 @@ describe('channelServiceRoutes', function () { assert.deepStrictEqual( err, resourceResponse, - `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}` + `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}`, ); done(); }; @@ -275,7 +277,7 @@ describe('channelServiceRoutes', function () { statusCode: 200, body: testResource, }, - done + done, ); const service = sandbox.createStubInstance(ChannelServiceHandler); @@ -300,7 +302,7 @@ describe('channelServiceRoutes', function () { assert.deepStrictEqual( err, resourceResponse, - `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}` + `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}`, ); done(); }; @@ -327,7 +329,7 @@ describe('channelServiceRoutes', function () { assert.deepStrictEqual( err, resourceResponse, - `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}` + `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}`, ); done(); }; @@ -353,7 +355,7 @@ describe('channelServiceRoutes', function () { statusCode: 200, body: {}, }, - done + done, ); const service = sandbox.createStubInstance(ChannelServiceHandler); @@ -378,7 +380,7 @@ describe('channelServiceRoutes', function () { assert.deepStrictEqual( err, resourceResponse, - `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}` + `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}`, ); done(); }; @@ -402,7 +404,7 @@ describe('channelServiceRoutes', function () { statusCode: 200, body: testResource, }, - done + done, ); const service = sandbox.createStubInstance(ChannelServiceHandler); @@ -427,7 +429,7 @@ describe('channelServiceRoutes', function () { assert.deepStrictEqual( err, resourceResponse, - `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}` + `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}`, ); done(); }; @@ -451,7 +453,7 @@ describe('channelServiceRoutes', function () { statusCode: 201, body: testResource, }, - done + done, ); const service = sandbox.createStubInstance(ChannelServiceHandler); @@ -476,7 +478,7 @@ describe('channelServiceRoutes', function () { assert.deepStrictEqual( err, resourceResponse, - `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}` + `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}`, ); done(); }; @@ -500,7 +502,7 @@ describe('channelServiceRoutes', function () { statusCode: 200, body: testResource, }, - done + done, ); const service = sandbox.createStubInstance(ChannelServiceHandler); @@ -525,7 +527,7 @@ describe('channelServiceRoutes', function () { assert.deepStrictEqual( err, resourceResponse, - `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}` + `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}`, ); done(); }; @@ -549,7 +551,7 @@ describe('channelServiceRoutes', function () { statusCode: 200, body: testResource, }, - done + done, ); const service = sandbox.createStubInstance(ChannelServiceHandler); @@ -574,7 +576,7 @@ describe('channelServiceRoutes', function () { assert.deepStrictEqual( err, resourceResponse, - `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}` + `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}`, ); done(); }; @@ -598,7 +600,7 @@ describe('channelServiceRoutes', function () { statusCode: 200, body: testResource, }, - done + done, ); const service = sandbox.createStubInstance(ChannelServiceHandler); @@ -623,7 +625,7 @@ describe('channelServiceRoutes', function () { assert.deepStrictEqual( err, resourceResponse, - `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}` + `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}`, ); done(); }; @@ -647,7 +649,7 @@ describe('channelServiceRoutes', function () { statusCode: 200, body: {}, }, - done + done, ); const service = sandbox.createStubInstance(ChannelServiceHandler); @@ -672,7 +674,7 @@ describe('channelServiceRoutes', function () { assert.deepStrictEqual( err, resourceResponse, - `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}` + `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}`, ); done(); }; @@ -696,7 +698,7 @@ describe('channelServiceRoutes', function () { statusCode: 200, body: testResource, }, - done + done, ); const service = sandbox.createStubInstance(ChannelServiceHandler); @@ -721,7 +723,7 @@ describe('channelServiceRoutes', function () { assert.deepStrictEqual( err, resourceResponse, - `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}` + `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}`, ); done(); }; @@ -748,7 +750,7 @@ describe('channelServiceRoutes', function () { assert.deepStrictEqual( err, resourceResponse, - `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}` + `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}`, ); done(); }; @@ -774,7 +776,7 @@ describe('channelServiceRoutes', function () { statusCode: 200, body: testResource, }, - done + done, ); const service = sandbox.createStubInstance(ChannelServiceHandler); @@ -799,7 +801,7 @@ describe('channelServiceRoutes', function () { assert.deepStrictEqual( err, resourceResponse, - `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}` + `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}`, ); done(); }; @@ -826,7 +828,7 @@ describe('channelServiceRoutes', function () { assert.deepStrictEqual( err, resourceResponse, - `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}` + `expected: ${JSON.stringify(resourceResponse)}. received: ${JSON.stringify(err)}`, ); done(); }; @@ -885,7 +887,7 @@ describe('channelServiceRoutes', function () { assert.deepStrictEqual( body, source, - `expected: ${JSON.stringify(source)}. received: ${JSON.stringify(body)}` + `expected: ${JSON.stringify(source)}. received: ${JSON.stringify(body)}`, ); done(); }) diff --git a/libraries/botbuilder/tests/cloudAdapter.test.js b/libraries/botbuilder/tests/cloudAdapter.test.js index 013aa0fac4..2af3657225 100644 --- a/libraries/botbuilder/tests/cloudAdapter.test.js +++ b/libraries/botbuilder/tests/cloudAdapter.test.js @@ -30,6 +30,7 @@ const noop = () => null; describe('CloudAdapter', function () { let sandbox; + beforeEach(function () { sandbox = sinon.createSandbox({ useFakeTimers: false }); }); @@ -85,6 +86,7 @@ describe('CloudAdapter', function () { const activity = { type: ActivityTypes.Invoke, value: 'invoke' }; const authorization = 'Bearer Authorization'; + it('delegates to connect', async function () { const req = {}; const socket = FakeNodeSocket(); @@ -128,6 +130,7 @@ describe('CloudAdapter', function () { mock.verify(); }); + //eslint-disable-next-line mocha/no-skipped-tests it.skip('throws exception on expired token', async function () { const consoleStub = sandbox.stub(console, 'error'); @@ -170,7 +173,7 @@ describe('CloudAdapter', function () { credentialsFactory, authConfig, undefined, - undefined + undefined, ); const adapter = new CloudAdapter(botFrameworkAuthentication); @@ -178,7 +181,7 @@ describe('CloudAdapter', function () { await adapter.process(req, res, logic); assert.equal(StatusCodes.UNAUTHORIZED, res.statusCode); - expect(consoleStub.calledWithMatch({ message: 'The token has expired' })).to.be.true; + expect(consoleStub.calledWithMatch({ message: 'The token has expired' })).to.equal(true); }); it('calls processActivityDirect with string authorization', async function () { @@ -205,7 +208,7 @@ describe('CloudAdapter', function () { const claimsIdentity = adapter.createClaimsIdentity('appId'); const audience = AuthenticationConstants.ToChannelFromBotOAuthScope; const botFrameworkAuthentication = new ConfigurationBotFrameworkAuthentication( - TestConfiguration.DefaultConfig + TestConfiguration.DefaultConfig, ); const connectorFactory = botFrameworkAuthentication.createConnectorFactory(claimsIdentity); //AuthenticateRequestResult @@ -249,7 +252,7 @@ describe('CloudAdapter', function () { await assert.rejects( adapter.processActivityDirect(authorization, activity, logic), - new Error('CloudAdapter.processActivityDirect(): ERROR\n error stack') + new Error('CloudAdapter.processActivityDirect(): ERROR\n error stack'), ); }); }); @@ -263,27 +266,27 @@ describe('CloudAdapter', function () { await assert.rejects( adapter.connectNamedPipe(undefined, noop, 'appId', 'audience', 'callerId'), - includesParam('pipeName') + includesParam('pipeName'), ); await assert.rejects( adapter.connectNamedPipe('pipeName', undefined, 'appId', 'audience', 'callerId'), - includesParam('logic') + includesParam('logic'), ); await assert.rejects( adapter.connectNamedPipe('pipeName', noop, undefined, 'audience', 'callerId'), - includesParam('appId') + includesParam('appId'), ); await assert.rejects( adapter.connectNamedPipe('pipeName', noop, 'appId', undefined, 'callerId'), - includesParam('audience') + includesParam('audience'), ); await assert.rejects( adapter.connectNamedPipe('pipeName', noop, 'appId', 'audience', 10), - includesParam('callerId') + includesParam('callerId'), ); }); diff --git a/libraries/botbuilder/tests/eventFactoryTests.test.js b/libraries/botbuilder/tests/eventFactoryTests.test.js index eab0c29322..9cb56595e5 100644 --- a/libraries/botbuilder/tests/eventFactoryTests.test.js +++ b/libraries/botbuilder/tests/eventFactoryTests.test.js @@ -42,7 +42,7 @@ describe('EventFactory', function () { it('should throw if turnContext is falsy', function () { assert.throws( () => EventFactory.createHandoffInitiation(null, 'some text'), - TypeError('EventFactory.createHandoffInitiation(): Missing context.') + TypeError('EventFactory.createHandoffInitiation(): Missing context.'), ); }); }); @@ -82,14 +82,14 @@ describe('EventFactory', function () { it('should throw if conversation is falsy', function () { assert.throws( () => EventFactory.createHandoffStatus(null, 'some text'), - TypeError('EventFactory.createHandoffStatus(): missing conversation.') + TypeError('EventFactory.createHandoffStatus(): missing conversation.'), ); }); it('should throw if state is falsy', function () { assert.throws( () => EventFactory.createHandoffStatus({}, null), - TypeError('EventFactory.createHandoffStatus(): missing state.') + TypeError('EventFactory.createHandoffStatus(): missing state.'), ); }); }); diff --git a/libraries/botbuilder/tests/fileTranscriptStore.test.js b/libraries/botbuilder/tests/fileTranscriptStore.test.js index 79979e1089..4e02d3ca0a 100644 --- a/libraries/botbuilder/tests/fileTranscriptStore.test.js +++ b/libraries/botbuilder/tests/fileTranscriptStore.test.js @@ -12,10 +12,12 @@ const workingFolder = path.join(os.tmpdir(), 'botbuilder-transcript-tests'); describe('The FileTranscriptStore', function () { let storage; const startDate = new Date(); + before(async function () { await fs.remove(workingFolder); storage = new FileTranscriptStore(workingFolder); }); + after(function () { return fs.remove(workingFolder); }); @@ -27,14 +29,14 @@ describe('The FileTranscriptStore', function () { let pagedResult = await storage.getTranscriptActivities('test', 'deleteActivitySpec'); assert.ok( pagedResult.items.length === 1, - `Expected pagedResult.items.length to be 1 but it was ${pagedResult.items.length}` + `Expected pagedResult.items.length to be 1 but it was ${pagedResult.items.length}`, ); await storage.deleteTranscript('test', 'deleteActivitySpec'); pagedResult = await storage.getTranscriptActivities('test', 'deleteActivitySpec'); assert.ok( pagedResult.items.length === 0, - `Expected pagedResult.items.length to be 0 but it was ${pagedResult.items.length}` + `Expected pagedResult.items.length to be 0 but it was ${pagedResult.items.length}`, ); }); @@ -46,13 +48,14 @@ describe('The FileTranscriptStore', function () { const pagedResult = await storage.getTranscriptActivities('test', 'deleteActivitySpec'); assert.ok( pagedResult.items.length === 1, - `Expected pagedResult.items.length to be 1 but it was ${pagedResult.items.length}` + `Expected pagedResult.items.length to be 1 but it was ${pagedResult.items.length}`, ); }); describe('should log activities', function () { const conversationId = 'logActivitySpec'; let activities; + before(function () { activities = createActivities(conversationId, startDate); return Promise.all(activities.map((activity) => storage.logActivity(activity))); @@ -72,7 +75,7 @@ describe('The FileTranscriptStore', function () { const pagedResult = await storage.getTranscriptActivities('otherChannelId', conversationId); assert.ok( !pagedResult.continuationToken, - 'expected pagedResult.continuationToken to be false but it was not' + 'expected pagedResult.continuationToken to be false but it was not', ); assert.ok(pagedResult.items.length === 0, 'Expected pagedResult.items.length to be 0 but it was not'); }); @@ -81,7 +84,7 @@ describe('The FileTranscriptStore', function () { const pagedResult = await storage.getTranscriptActivities('test', 'someOtherConversation'); assert.ok( !pagedResult.continuationToken, - 'expected pagedResult.continuationToken to be false but it was not' + 'expected pagedResult.continuationToken to be false but it was not', ); assert.ok(pagedResult.items.length === 0, 'Expected pagedResult.items.length to be 0 but it was not'); }); @@ -92,8 +95,8 @@ describe('The FileTranscriptStore', function () { pagedResult.items.forEach((item, index) => assert.ok( JSON.stringify(item) === JSON.stringify(activities[index]), - `item #${index} does not match what was persisted to disk` - ) + `item #${index} does not match what was persisted to disk`, + ), ); }); @@ -102,11 +105,11 @@ describe('The FileTranscriptStore', function () { 'test', conversationId, null, - new Date(startDate.getTime() + 60000 * 5) + new Date(startDate.getTime() + 60000 * 5), ); assert.ok( pagedResult.items.length === 5, - `Expected the pagedResult.items.length to be 5 but it was ${pagedResult.items.length}` + `Expected the pagedResult.items.length to be 5 but it was ${pagedResult.items.length}`, ); }); }); @@ -119,21 +122,21 @@ describe('The FileTranscriptStore', function () { it('no activity is passed to the "logActivity" function', async function () { await assert.rejects( storage.logActivity(null), - new Error('activity cannot be null for logActivity()', 'An error should exist') + new Error('activity cannot be null for logActivity()', 'An error should exist'), ); }); it('no channelId is passed to the "getTranscriptActivities" function', async function () { await assert.rejects( storage.getTranscriptActivities(null, '123456'), - new Error('Missing channelId', 'An error should exist') + new Error('Missing channelId', 'An error should exist'), ); }); it('no conversationId is passed to the "getTranscriptActivities" function', async function () { await assert.rejects( storage.getTranscriptActivities({}), - new Error('Missing conversationId', 'An error should exist') + new Error('Missing conversationId', 'An error should exist'), ); }); @@ -148,7 +151,7 @@ describe('The FileTranscriptStore', function () { it('no conversationId is passed to the "deleteTranscript" function', async function () { await assert.rejects( storage.deleteTranscript({}), - new Error('Missing conversationId', 'An error should exist') + new Error('Missing conversationId', 'An error should exist'), ); }); }); @@ -156,11 +159,13 @@ describe('The FileTranscriptStore', function () { describe('should retrieve activities', function () { const conversationId = 'retrieveActivitiesSpec'; let activities; + before(function () { activities = createActivities(conversationId, startDate, 60); storage = new FileTranscriptStore(workingFolder); return Promise.all(activities.map((activity) => storage.logActivity(activity))); }); + after(function () { return fs.remove(workingFolder); }); @@ -169,12 +174,12 @@ describe('The FileTranscriptStore', function () { const pagedResult = await storage.getTranscriptActivities('test', conversationId); assert.ok( typeof pagedResult.continuationToken === 'string', - `Expected a continuationToken but got ${pagedResult.continuationToken}` + `Expected a continuationToken but got ${pagedResult.continuationToken}`, ); const pagedResult1 = await storage.getTranscriptActivities( 'test', conversationId, - pagedResult.continuationToken + pagedResult.continuationToken, ); assert.ok(!!pagedResult1.items.length, 'Expected the pagedResult to contain items but it did not'); assert.ok(JSON.stringify(pagedResult) !== JSON.stringify(pagedResult1)); @@ -189,12 +194,12 @@ describe('The FileTranscriptStore', function () { set(target, p, value) { if (target[p]) { assert.fail( - 'This ID already returned by getTranscriptActivities and it should not have been' + 'This ID already returned by getTranscriptActivities and it should not have been', ); } return (target[p] = value); }, - } + }, ); let increments = ~~(activities.length / 20); while (increments--) { @@ -219,23 +224,23 @@ describe('The FileTranscriptStore', function () { set(target, p, value) { if (target[p]) { assert.fail( - 'This ID already returned by getTranscriptActivities and it should not have been' + 'This ID already returned by getTranscriptActivities and it should not have been', ); } return (target[p] = value); }, - } + }, ); while (i--) { continuationToken = pagedResult.continuationToken; pagedResult = await storage.getTranscriptActivities('test', conversationId, continuationToken); assert.ok( i === 0 || !!pagedResult.continuationToken, - 'Expected a continuationToken but did not receive one' + 'Expected a continuationToken but did not receive one', ); assert.ok( continuationToken !== pagedResult.continuationToken, - 'The newly returned continuationToken should not match the last one received' + 'The newly returned continuationToken should not match the last one received', ); pagedResult.items.forEach((item) => (seen[item.id] = true)); } @@ -245,6 +250,7 @@ describe('The FileTranscriptStore', function () { describe('should list transcripts', function () { let activities; + before(function () { activities = []; let ct = 100; @@ -254,6 +260,7 @@ describe('The FileTranscriptStore', function () { storage = new FileTranscriptStore(workingFolder); return Promise.all(activities.map((activity) => storage.logActivity(activity))); }); + after(function () { return fs.remove(workingFolder); }); @@ -271,18 +278,18 @@ describe('The FileTranscriptStore', function () { } return (target[p] = value); }, - } + }, ); while (i--) { continuationToken = pagedResult.continuationToken; pagedResult = await storage.listTranscripts('test', continuationToken); assert.ok( i === 0 || !!pagedResult.continuationToken, - 'Expected a continuationToken but did not receive one' + 'Expected a continuationToken but did not receive one', ); assert.ok( continuationToken !== pagedResult.continuationToken, - 'The newly returned continuationToken should not match the last one received' + 'The newly returned continuationToken should not match the last one received', ); pagedResult.items.forEach((item) => (seen[item.id] = true)); } diff --git a/libraries/botbuilder/tests/inspectionMiddleware.test.js b/libraries/botbuilder/tests/inspectionMiddleware.test.js index fcd1b00dff..1cb858261a 100644 --- a/libraries/botbuilder/tests/inspectionMiddleware.test.js +++ b/libraries/botbuilder/tests/inspectionMiddleware.test.js @@ -39,20 +39,21 @@ describe('InspectionMiddleware', function () { assert(adapter.activityBuffer[0].type === 'message', 'expected a message activity'); assert(adapter.activityBuffer[0].text === 'hi', "expected text saying 'hi'"); }); + it('should replicate activity data to listening emulator following open and attach', async function () { // set up our expectations in nock - each corresponds to a trace message we expect to receive in the emulator const inboundExpectation = nock('https://test.com') .post( '/v3/conversations/Convo1/activities', - (activity) => activity.type === 'trace' && activity.value.text == 'hi' + (activity) => activity.type === 'trace' && activity.value.text == 'hi', ) .reply(200, { id: 'test' }); const outboundExpectation = nock('https://test.com') .post( '/v3/conversations/Convo1/activities', - (activity) => activity.type === 'trace' && activity.value.text == 'echo: hi' + (activity) => activity.type === 'trace' && activity.value.text == 'echo: hi', ) .reply(200, { id: 'test' }); @@ -64,7 +65,7 @@ describe('InspectionMiddleware', function () { activity.value.userState && activity.value.userState.x.property == 'hello' && activity.value.conversationState && - activity.value.conversationState.y.property == 'world' + activity.value.conversationState.y.property == 'world', ) .reply(200, { id: 'test' }); @@ -85,7 +86,7 @@ describe('InspectionMiddleware', function () { await inspectionMiddleware.processCommand(turnContext); }, null, - true + true, ); await inspectionAdapter.receiveActivity(openActivity); @@ -109,7 +110,7 @@ describe('InspectionMiddleware', function () { await conversationState.saveChanges(turnContext); }, null, - true + true, ); // IMPORTANT add the InspectionMiddleware to the adapter that is running our bot @@ -129,24 +130,25 @@ describe('InspectionMiddleware', function () { assert(inboundExpectation.isDone(), 'The expectation of a trace message for the inbound activity was not met'); assert( outboundExpectation.isDone(), - 'The expectation of a trace message for the outbound activity was not met' + 'The expectation of a trace message for the outbound activity was not met', ); assert(stateExpectation.isDone(), 'The expectation of a trace message for the bot state was not met'); }); + it('should replicate activity data to listening emulator following open and attach with at mention', async function () { // set up our expectations in nock - each corresponds to a trace message we expect to receive in the emulator const inboundExpectation = nock('https://test.com') .post( '/v3/conversations/Convo1/activities', - (activity) => activity.type === 'trace' && activity.value.text == 'hi' + (activity) => activity.type === 'trace' && activity.value.text == 'hi', ) .reply(200, { id: 'test' }); const outboundExpectation = nock('https://test.com') .post( '/v3/conversations/Convo1/activities', - (activity) => activity.type === 'trace' && activity.value.text == 'echo: hi' + (activity) => activity.type === 'trace' && activity.value.text == 'echo: hi', ) .reply(200, { id: 'test' }); @@ -158,7 +160,7 @@ describe('InspectionMiddleware', function () { activity.value.userState && activity.value.userState.x.property == 'hello' && activity.value.conversationState && - activity.value.conversationState.y.property == 'world' + activity.value.conversationState.y.property == 'world', ) .reply(200, { id: 'test' }); @@ -179,7 +181,7 @@ describe('InspectionMiddleware', function () { await inspectionMiddleware.processCommand(turnContext); }, null, - true + true, ); await inspectionAdapter.receiveActivity(openActivity); @@ -205,7 +207,7 @@ describe('InspectionMiddleware', function () { await conversationState.saveChanges(turnContext); }, null, - true + true, ); // IMPORTANT add the InspectionMiddleware to the adapter that is running our bot @@ -241,24 +243,25 @@ describe('InspectionMiddleware', function () { assert(inboundExpectation.isDone(), 'The expectation of a trace message for the inbound activity was not met'); assert( outboundExpectation.isDone(), - 'The expectation of a trace message for the outbound activity was not met' + 'The expectation of a trace message for the outbound activity was not met', ); assert(stateExpectation.isDone(), 'The expectation of a trace message for the bot state was not met'); }); + it('should replicate activity data to listening emulator following open and attach within Teams Team', async function () { // set up our expectations in nock - each corresponds to a trace message we expect to receive in the emulator const inboundExpectation = nock('https://test.com') .post( '/v3/conversations/Convo1/activities', - (activity) => activity.type === 'trace' && activity.value.text == 'hi' + (activity) => activity.type === 'trace' && activity.value.text == 'hi', ) .reply(200, { id: 'test' }); const outboundExpectation = nock('https://test.com') .post( '/v3/conversations/Convo1/activities', - (activity) => activity.type === 'trace' && activity.value.text == 'echo: hi' + (activity) => activity.type === 'trace' && activity.value.text == 'echo: hi', ) .reply(200, { id: 'test' }); @@ -270,7 +273,7 @@ describe('InspectionMiddleware', function () { activity.value.userState && activity.value.userState.x.property == 'hello' && activity.value.conversationState && - activity.value.conversationState.y.property == 'world' + activity.value.conversationState.y.property == 'world', ) .reply(200, { id: 'test' }); @@ -291,7 +294,7 @@ describe('InspectionMiddleware', function () { await inspectionMiddleware.processCommand(turnContext); }, null, - true + true, ); await inspectionAdapter.receiveActivity(openActivity); @@ -315,7 +318,7 @@ describe('InspectionMiddleware', function () { await conversationState.saveChanges(turnContext); }, null, - true + true, ); // IMPORTANT add the InspectionMiddleware to the adapter that is running our bot @@ -341,7 +344,7 @@ describe('InspectionMiddleware', function () { assert(inboundExpectation.isDone(), 'The expectation of a trace message for the inbound activity was not met'); assert( outboundExpectation.isDone(), - 'The expectation of a trace message for the outbound activity was not met' + 'The expectation of a trace message for the outbound activity was not met', ); assert(stateExpectation.isDone(), 'The expectation of a trace message for the bot state was not met'); }); @@ -352,14 +355,14 @@ describe('InspectionMiddleware', function () { nock('https://test.com') .post( '/v3/conversations/Convo1/activities', - (activity) => activity.type === 'trace' && activity.value.text == 'hi' + (activity) => activity.type === 'trace' && activity.value.text == 'hi', ) .reply(200, { id: 'test' }); nock('https://test.com') .post( '/v3/conversations/Convo1/activities', - (activity) => activity.type === 'trace' && activity.value.text == 'echo: hi' + (activity) => activity.type === 'trace' && activity.value.text == 'echo: hi', ) .reply(200, { id: 'test' }); @@ -371,7 +374,7 @@ describe('InspectionMiddleware', function () { activity.value.userState && activity.value.userState.x.property == 'hello' && activity.value.conversationState && - activity.value.conversationState.y.property == 'world' + activity.value.conversationState.y.property == 'world', ) .reply(200, { id: 'test' }); @@ -390,7 +393,7 @@ describe('InspectionMiddleware', function () { await inspectionMiddleware.processCommand(turnContext); }, null, - true + true, ); await inspectionAdapter.receiveActivity(openActivity); @@ -412,7 +415,7 @@ describe('InspectionMiddleware', function () { await conversationState.saveChanges(turnContext); }, null, - true + true, ); adapter.use(inspectionMiddleware); @@ -433,14 +436,14 @@ describe('InspectionMiddleware', function () { nock('https://test.com') .post( '/v3/conversations/Convo1/activities', - (activity) => activity.type === 'trace' && activity.value.text == 'hi' + (activity) => activity.type === 'trace' && activity.value.text == 'hi', ) .reply(200, { id: 'test' }); nock('https://test.com') .post( '/v3/conversations/Convo1/activities', - (activity) => activity.type === 'trace' && activity.value.text == 'echo: hi' + (activity) => activity.type === 'trace' && activity.value.text == 'echo: hi', ) .reply(200, { id: 'test' }); @@ -452,7 +455,7 @@ describe('InspectionMiddleware', function () { activity.value.userState && activity.value.userState.x.property == 'hello' && activity.value.conversationState && - activity.value.conversationState.y.property == 'world' + activity.value.conversationState.y.property == 'world', ) .reply(200, { id: 'test' }); @@ -472,7 +475,7 @@ describe('InspectionMiddleware', function () { await inspectionMiddleware.processCommand(turnContext); }, null, - true + true, ); await inspectionAdapter.receiveActivity(openActivity); @@ -493,7 +496,7 @@ describe('InspectionMiddleware', function () { await conversationState.saveChanges(turnContext); }, null, - true + true, ); adapter.use(inspectionMiddleware); @@ -513,14 +516,14 @@ describe('InspectionMiddleware', function () { nock('https://test.com') .post( '/v3/conversations/Convo1/activities', - (activity) => activity.type === 'trace' && activity.value.text == 'hi' + (activity) => activity.type === 'trace' && activity.value.text == 'hi', ) .reply(200, { id: 'test' }); nock('https://test.com') .post( '/v3/conversations/Convo1/activities', - (activity) => activity.type === 'trace' && activity.value.text == 'echo: hi' + (activity) => activity.type === 'trace' && activity.value.text == 'echo: hi', ) .reply(200, { id: 'test' }); @@ -532,7 +535,7 @@ describe('InspectionMiddleware', function () { activity.value.userState && activity.value.userState.x.property == 'hello' && activity.value.conversationState && - activity.value.conversationState.y.property == 'world' + activity.value.conversationState.y.property == 'world', ) .reply(200, { id: 'test' }); @@ -551,7 +554,7 @@ describe('InspectionMiddleware', function () { await inspectionMiddleware.processCommand(turnContext); }, null, - true + true, ); await inspectionAdapter.receiveActivity(openActivity); @@ -563,11 +566,11 @@ describe('InspectionMiddleware', function () { async (turnContext) => { await assert.rejects( inspectionMiddleware.onTurn(turnContext, null), - TypeError('next is not a function', 'next function should be null') + TypeError('next is not a function', 'next function should be null'), ); }, null, - true + true, ); adapter.use(inspectionMiddleware); @@ -641,7 +644,7 @@ describe('InspectionMiddleware', function () { const result = await inspectionMiddleware.attachCommand( '', { openedSessions: { 'session-1': undefined } }, - 'session-1' + 'session-1', ); assert.strictEqual(result, false, 'should be returning false'); }); diff --git a/libraries/botbuilder/tests/skills/cloudSkillHandler.test.js b/libraries/botbuilder/tests/skills/cloudSkillHandler.test.js index a46b02b1af..04b4951066 100644 --- a/libraries/botbuilder/tests/skills/cloudSkillHandler.test.js +++ b/libraries/botbuilder/tests/skills/cloudSkillHandler.test.js @@ -13,9 +13,11 @@ describe('CloudSkillHandler', function () { const handler = new CloudSkillHandler(adapter, bot, factory, authConfig); let sandbox; + beforeEach(function () { sandbox = sinon.createSandbox(); }); + afterEach(function () { sandbox.restore(); }); diff --git a/libraries/botbuilder/tests/skills/skillHandler.test.js b/libraries/botbuilder/tests/skills/skillHandler.test.js index 1a50be399f..b19700e4e5 100644 --- a/libraries/botbuilder/tests/skills/skillHandler.test.js +++ b/libraries/botbuilder/tests/skills/skillHandler.test.js @@ -27,9 +27,11 @@ describe('SkillHandler', function () { const handler = new SkillHandler(adapter, bot, factory, creds, authConfig); let sandbox; + beforeEach(function () { sandbox = sinon.createSandbox(); }); + afterEach(function () { sandbox.restore(); }); @@ -73,7 +75,7 @@ describe('SkillHandler', function () { assert.deepStrictEqual(context.turnState.get(adapter.BotIdentityKey), identity); return true; }) - .and(sinon.match({ activity })) + .and(sinon.match({ activity })), ) .once(); @@ -133,7 +135,7 @@ describe('SkillHandler', function () { expectsGetSkillConversationReference(convId, updatedActivity.serviceUrl); expectsContext((context) => - context.expects('updateActivity').withArgs(sinon.match(updatedActivity)).once().resolves() + context.expects('updateActivity').withArgs(sinon.match(updatedActivity)).once().resolves(), ); await handler.onUpdateActivity(new ClaimsIdentity([]), convId, activityId, updatedActivity); @@ -166,13 +168,13 @@ describe('SkillHandler', function () { assert.deepStrictEqual( context.turnState.get(adapter.BotIdentityKey), identity, - 'cached identity exists' + 'cached identity exists', ); assert.deepStrictEqual( context.turnState.get(handler.SkillConversationReferenceKey), ref, - 'cached conversation ref exists' + 'cached conversation ref exists', ); sandbox.verify(); @@ -186,7 +188,7 @@ describe('SkillHandler', function () { await assert.rejects( handler.inner.processActivity({}, 'convId', 'replyId', {}), - new Error('skillConversationReference not found') + new Error('skillConversationReference not found'), ); sandbox.verify(); @@ -197,7 +199,7 @@ describe('SkillHandler', function () { await assert.rejects( handler.inner.processActivity({}, 'convId', 'replyId', {}), - new Error('conversationReference not found.') + new Error('conversationReference not found.'), ); sandbox.verify(); @@ -233,7 +235,7 @@ describe('SkillHandler', function () { { type: AuthenticationConstants.AppIdClaim, value: '00000000-0000-0000-0000-000000000000' }, { type: AuthenticationConstants.VersionClaim, value: '1.0' }, ], - true + true, ); const skillActivity = { @@ -289,7 +291,7 @@ describe('SkillHandler', function () { { type: AuthenticationConstants.AppIdClaim, value: skillAppId }, { type: AuthenticationConstants.VersionClaim, value: '1.0' }, ], - true + true, ); const skillActivity = { @@ -313,16 +315,16 @@ describe('SkillHandler', function () { assert.strictEqual( fromKey, fromHandlerKey, - 'the keys should return the same cached values' + 'the keys should return the same cached values', ); assert.strictEqual( context.activity.callerId, - `${CallerIdConstants.BotToBotPrefix}${skillAppId}` + `${CallerIdConstants.BotToBotPrefix}${skillAppId}`, ); return true; - }) + }), ) .once(); diff --git a/libraries/botbuilder/tests/skills/skillHttpClient.test.js b/libraries/botbuilder/tests/skills/skillHttpClient.test.js index 3bfd849c82..04008dbc8b 100644 --- a/libraries/botbuilder/tests/skills/skillHttpClient.test.js +++ b/libraries/botbuilder/tests/skills/skillHttpClient.test.js @@ -10,7 +10,7 @@ describe('SkillHttpClient', function () { it('should fail to construct without required parameters', function () { assert.throws( () => new SkillHttpClient(new SimpleCredentialProvider('', '')), - new Error('conversationIdFactory missing') + new Error('conversationIdFactory missing'), ); }); }); diff --git a/libraries/botbuilder/tests/statusCodeError.test.js b/libraries/botbuilder/tests/statusCodeError.test.js index e0e132ec96..5e1c05efbe 100644 --- a/libraries/botbuilder/tests/statusCodeError.test.js +++ b/libraries/botbuilder/tests/statusCodeError.test.js @@ -17,7 +17,7 @@ describe('StatusCodeError', function () { assert.strictEqual( error.statusCode, StatusCodes.NOT_FOUND, - `statusCode should be the code ${StatusCodes.NOT_FOUND}` + `statusCode should be the code ${StatusCodes.NOT_FOUND}`, ); }); @@ -28,7 +28,7 @@ describe('StatusCodeError', function () { assert.strictEqual( error.statusCode, StatusCodes.NOT_FOUND, - `statusCode should be the code ${StatusCodes.NOT_FOUND}` + `statusCode should be the code ${StatusCodes.NOT_FOUND}`, ); }); diff --git a/libraries/botbuilder/tests/streaming/botFrameworkAdapterStreaming.test.js b/libraries/botbuilder/tests/streaming/botFrameworkAdapterStreaming.test.js index e0a7961231..e28ed4d472 100644 --- a/libraries/botbuilder/tests/streaming/botFrameworkAdapterStreaming.test.js +++ b/libraries/botbuilder/tests/streaming/botFrameworkAdapterStreaming.test.js @@ -52,7 +52,7 @@ describe('BotFrameworkAdapter Streaming tests', function () { const adapter = new BotFrameworkAdapter(); adapter.useNamedPipe(async (_) => {}, 'PipeyMcPipeface'); - expect(adapter.streamingServer.disconnect()).to.not.throw; + expect(() => adapter.streamingServer.disconnect()).to.not.throw(); }); it("throws exception when trying to connect to a different named pipe than it's connected to", async function () { @@ -66,7 +66,7 @@ describe('BotFrameworkAdapter Streaming tests', function () { { message: 'This BotFrameworkAdapter instance is already connected to a different stream. Use a new instance to connect to the provided pipeName.', - } + }, ); }); @@ -83,7 +83,7 @@ describe('BotFrameworkAdapter Streaming tests', function () { it('isStreamingConnectionOpen returns false without a streamingServer', function () { const adapter = new BotFrameworkAdapter(); - expect(adapter.isStreamingConnectionOpen).to.be.false; + expect(adapter.isStreamingConnectionOpen).to.equal(false); }); it('sendActivities should throw an error if streaming connection is closed.', async function () { @@ -102,8 +102,8 @@ describe('BotFrameworkAdapter Streaming tests', function () { await assert.rejects( adapter.sendActivities(new TurnContext(adapter, activity), [reply]), new Error( - 'BotFrameworkAdapter.sendActivities(): Unable to send activity as Streaming connection is closed.' - ) + 'BotFrameworkAdapter.sendActivities(): Unable to send activity as Streaming connection is closed.', + ), ); }); @@ -142,7 +142,7 @@ describe('BotFrameworkAdapter Streaming tests', function () { await adapter.useWebSocket(request, realSocket, Buffer.from([]), async (context) => { await bot.run(context); }); - expect(writeSpy.called).to.be.true; + expect(writeSpy.called).to.equal(true); }); it('returns status code 401 when request is not authorized', async function () { @@ -165,13 +165,13 @@ describe('BotFrameworkAdapter Streaming tests', function () { expect(err.message).to.equal('Unauthorized. Is not authenticated'); const socketResponse = MockNetSocket.createNonSuccessResponse( StatusCodes.UNAUTHORIZED, - err.message + err.message, ); - expect(writeSpy.called).to.be.true; - expect(writeSpy.calledWithExactly(socketResponse)).to.be.true; - expect(destroySpy.calledOnceWithExactly()).to.be.true; + expect(writeSpy.called).to.equal(true); + expect(writeSpy.calledWithExactly(socketResponse)).to.equal(true); + expect(destroySpy.calledOnceWithExactly()).to.equal(true); return true; - } + }, ); }); @@ -193,11 +193,11 @@ describe('BotFrameworkAdapter Streaming tests', function () { expect(err.message).to.equal("'authHeader' required."); expect(err.statusCode).to.equal(StatusCodes.BAD_REQUEST); const socketResponse = MockNetSocket.createNonSuccessResponse(StatusCodes.BAD_REQUEST, err.message); - expect(writeSpy.called).to.be.true; - expect(writeSpy.calledWithExactly(socketResponse)).to.be.true; - expect(destroySpy.calledOnceWithExactly()).to.be.true; + expect(writeSpy.called).to.equal(true); + expect(writeSpy.calledWithExactly(socketResponse)).to.equal(true); + expect(destroySpy.calledOnceWithExactly()).to.equal(true); return true; - } + }, ); }); @@ -211,7 +211,7 @@ describe('BotFrameworkAdapter Streaming tests', function () { await assert.rejects(adapter.useWebSocket(request, socket, Buffer.from([]), uncallableLogic), (err) => { expect(err.message).to.equal('Streaming logic needs to be provided to `useWebSocket`'); - expect(useWebSocketSpy.called).to.be.true; + expect(useWebSocketSpy.called).to.equal(true); return true; }); }); @@ -257,7 +257,7 @@ describe('BotFrameworkAdapter Streaming tests', function () { const response = await adapter.processRequest(request); expect(response.statusCode).to.equal(StatusCodes.OK); - expect(response.streams[0].content).to.not.be.undefined; + expect(response.streams[0].content).to.not.equal(undefined); }); it('returns user agent information from cache when a GET hits the version endpoint more than once', async function () { @@ -269,11 +269,11 @@ describe('BotFrameworkAdapter Streaming tests', function () { const response = await adapter.processRequest(request); expect(response.statusCode).to.equal(StatusCodes.OK); - expect(response.streams[0].content).to.not.be.undefined; + expect(response.streams[0].content).to.not.equal(undefined); const response2 = await adapter.processRequest(request); expect(response2.statusCode).to.equal(StatusCodes.OK); - expect(response2.streams[0].content).to.not.be.undefined; + expect(response2.streams[0].content).to.not.equal(undefined); }); it('should return 405 for unsupported methods to valid paths', async function () { @@ -353,7 +353,7 @@ describe('BotFrameworkAdapter Streaming tests', function () { const response = await adapter.processRequest(request); expect(response.statusCode).to.equal(StatusCodes.INTERNAL_SERVER_ERROR); - expect(middlewareCalled).to.be.true; + expect(middlewareCalled).to.equal(true); }); it('executes middleware', async function () { @@ -379,8 +379,8 @@ describe('BotFrameworkAdapter Streaming tests', function () { const response = await adapter.processRequest(request); expect(response.statusCode).to.equal(StatusCodes.NOT_IMPLEMENTED); - expect(runSpy.called).to.be.true; - expect(middlewareCalled).to.be.true; + expect(runSpy.called).to.equal(true); + expect(middlewareCalled).to.equal(true); }); }); @@ -398,7 +398,7 @@ describe('BotFrameworkAdapter Streaming tests', function () { const connection = adapter.createConnectorClient('fakeUrl'); connection.sendRequest({ method: 'POST', url: 'testResultDotCom', body: 'Test body!' }); - expect(writeSpy.called).to.be.true; + expect(writeSpy.called).to.equal(true); }).timeout(2000); describe('private methods', function () { @@ -409,7 +409,7 @@ describe('BotFrameworkAdapter Streaming tests', function () { ]; serviceUrls.forEach((serviceUrl) => { - expect(BotFrameworkAdapter.isStreamingServiceUrl(serviceUrl)).to.be.true; + expect(BotFrameworkAdapter.isStreamingServiceUrl(serviceUrl)).to.equal(true); }); }); @@ -417,7 +417,7 @@ describe('BotFrameworkAdapter Streaming tests', function () { const serviceUrls = ['http://yayay.com', 'HTTPS://yayay.com']; serviceUrls.forEach((serviceUrl) => { - expect(BotFrameworkAdapter.isStreamingServiceUrl(serviceUrl)).to.be.false; + expect(BotFrameworkAdapter.isStreamingServiceUrl(serviceUrl)).to.equal(false); }); }); }); diff --git a/libraries/botbuilder/tests/streaming/mockHttpRequest.js b/libraries/botbuilder/tests/streaming/mockHttpRequest.js index b97aad8300..c9e64f861c 100644 --- a/libraries/botbuilder/tests/streaming/mockHttpRequest.js +++ b/libraries/botbuilder/tests/streaming/mockHttpRequest.js @@ -12,7 +12,7 @@ class MockHttpRequest { 'sec-websocket-protocol': '', }, }, - options + options, ); this.method = config.method; diff --git a/libraries/botbuilder/tests/streaming/mockStreamingRequest.js b/libraries/botbuilder/tests/streaming/mockStreamingRequest.js index ac65f92c07..771532c286 100644 --- a/libraries/botbuilder/tests/streaming/mockStreamingRequest.js +++ b/libraries/botbuilder/tests/streaming/mockStreamingRequest.js @@ -7,7 +7,7 @@ class MockContentStream { { readAsJson: async () => ({ type: ActivityTypes.Invoke, serviceUrl: 'somewhere/', channelId: 'test' }), }, - options + options, ); this.readAsJson = config.readAsJson; @@ -23,7 +23,7 @@ class MockStreamingRequest { path: '/api/messages', streams: [new MockContentStream()], }, - options + options, ); this.verb = config.verb; diff --git a/libraries/botbuilder/tests/streaming/streamingHttpClient.test.js b/libraries/botbuilder/tests/streaming/streamingHttpClient.test.js index 348cacad71..e353583d1d 100644 --- a/libraries/botbuilder/tests/streaming/streamingHttpClient.test.js +++ b/libraries/botbuilder/tests/streaming/streamingHttpClient.test.js @@ -19,7 +19,7 @@ describe('StreamingHttpClient', function () { await assert.rejects( client.sendRequest(), - new Error('StreamingHttpClient.sendRequest(): missing "httpRequest" parameter') + new Error('StreamingHttpClient.sendRequest(): missing "httpRequest" parameter'), ); }); @@ -29,8 +29,8 @@ describe('StreamingHttpClient', function () { await assert.rejects( client.sendRequest({}), new Error( - 'StreamingHttpClient.sendRequest(): Streaming connection is disconnected, and the request could not be sent.' - ) + 'StreamingHttpClient.sendRequest(): Streaming connection is disconnected, and the request could not be sent.', + ), ); }); }); diff --git a/libraries/botbuilder/tests/streaming/tokenResolver.test.js b/libraries/botbuilder/tests/streaming/tokenResolver.test.js index 489cbf5b7d..6dbc32e703 100644 --- a/libraries/botbuilder/tests/streaming/tokenResolver.test.js +++ b/libraries/botbuilder/tests/streaming/tokenResolver.test.js @@ -61,7 +61,7 @@ describe('TokenResolver', function () { assert(!gotToken, 'did not receive token'); await assert.throws( () => TokenResolver.checkForOAuthCards(adapter, context, activity), - new Error("The OAuthPrompt's ConnectionName property is missing a value.", 'did not receive token') + new Error("The OAuthPrompt's ConnectionName property is missing a value.", 'did not receive token'), ); }); diff --git a/libraries/botbuilder/tests/teams/teamsSSOTokenExchangeMiddleware.test.js b/libraries/botbuilder/tests/teams/teamsSSOTokenExchangeMiddleware.test.js index 5f63d31985..bde0085cd3 100644 --- a/libraries/botbuilder/tests/teams/teamsSSOTokenExchangeMiddleware.test.js +++ b/libraries/botbuilder/tests/teams/teamsSSOTokenExchangeMiddleware.test.js @@ -102,7 +102,7 @@ describe('TeamsSSOTokenExchangeMiddleware', function () { }); const adapter = new TeamsSSOAdapter(createConversationReference(), logic).use( - new TeamsSSOTokenExchangeMiddleware(new MemoryStorage(), connectionName) + new TeamsSSOTokenExchangeMiddleware(new MemoryStorage(), connectionName), ); adapter.addExchangeableToken(connectionName, Channels.Msteams, teamsUserId, fakeExchangeableItem, token); @@ -120,7 +120,7 @@ describe('TeamsSSOTokenExchangeMiddleware', function () { }); const adapter = new TeamsSSOAdapter(createConversationReference(), logic).use( - new TeamsSSOTokenExchangeMiddleware(new MemoryStorage(), connectionName) + new TeamsSSOTokenExchangeMiddleware(new MemoryStorage(), connectionName), ); adapter.addExchangeableToken(connectionName, Channels.Msteams, teamsUserId, fakeExchangeableItem, token); @@ -148,7 +148,7 @@ describe('TeamsSSOTokenExchangeMiddleware', function () { // Note: addExchangeableToken omitted so exchange does not take place const adapter = new TeamsSSOAdapter(createConversationReference(), logic).use( - new TeamsSSOTokenExchangeMiddleware(new MemoryStorage(), connectionName) + new TeamsSSOTokenExchangeMiddleware(new MemoryStorage(), connectionName), ); await adapter @@ -177,7 +177,7 @@ describe('TeamsSSOTokenExchangeMiddleware', function () { }); const adapter = new TeamsSSOAdapter(createConversationReference(Channels.Directline), logic).use( - new TeamsSSOTokenExchangeMiddleware(new MemoryStorage(), connectionName) + new TeamsSSOTokenExchangeMiddleware(new MemoryStorage(), connectionName), ); await adapter.send('test').assertReply('processed').startTest(); @@ -194,6 +194,7 @@ describe('TeamsSSOTokenExchangeMiddleware', function () { afterEach(function () { this.sandbox.restore(); }); + it('exchange token with CloudAdapter', async function () { class TestCloudAdapter extends CloudAdapterBase {} const conversation = TestAdapter.createConversation('Convo1'); diff --git a/libraries/botbuilder/tests/teamsActivityHandler.test.js b/libraries/botbuilder/tests/teamsActivityHandler.test.js index 234a2e580e..3f1aa42aca 100644 --- a/libraries/botbuilder/tests/teamsActivityHandler.test.js +++ b/libraries/botbuilder/tests/teamsActivityHandler.test.js @@ -676,17 +676,17 @@ describe('TeamsActivityHandler', function () { .assertReply((activity) => { assert( activity.type === 'invokeResponse', - `incorrect activity type "${activity.type}", expected "invokeResponse"` + `incorrect activity type "${activity.type}", expected "invokeResponse"`, ); assert( activity.value.status === 400, - `incorrect status code "${activity.value.status}", expected "400"` + `incorrect status code "${activity.value.status}", expected "400"`, ); assert( !activity.value.body, `expected empty body for invokeResponse from fileConsent flow.\nReceived: ${JSON.stringify( - activity.value.body - )}` + activity.value.body, + )}`, ); }) .startTest(); @@ -706,17 +706,17 @@ describe('TeamsActivityHandler', function () { .assertReply((activity) => { assert( activity.type === 'invokeResponse', - `incorrect activity type "${activity.type}", expected "invokeResponse"` + `incorrect activity type "${activity.type}", expected "invokeResponse"`, ); assert( activity.value.status === 400, - `incorrect status code "${activity.value.status}", expected "400"` + `incorrect status code "${activity.value.status}", expected "400"`, ); assert( !activity.value.body, `expected empty body for invokeResponse from fileConsent flow.\nReceived: ${JSON.stringify( - activity.value.body - )}` + activity.value.body, + )}`, ); }) .startTest(); @@ -774,17 +774,17 @@ describe('TeamsActivityHandler', function () { .assertReply((activity) => { assert( activity.type === 'invokeResponse', - `incorrect activity type "${activity.type}", expected "invokeResponse"` + `incorrect activity type "${activity.type}", expected "invokeResponse"`, ); assert( activity.value.status === 501, - `incorrect status code "${activity.value.status}", expected "501"` + `incorrect status code "${activity.value.status}", expected "501"`, ); assert( !activity.value.body, `expected empty body for invokeResponse from fileConsent flow.\nReceived: ${JSON.stringify( - activity.value.body - )}` + activity.value.body, + )}`, ); }) .startTest(); @@ -806,17 +806,17 @@ describe('TeamsActivityHandler', function () { .assertReply((activity) => { assert( activity.type === 'invokeResponse', - `incorrect activity type "${activity.type}", expected "invokeResponse"` + `incorrect activity type "${activity.type}", expected "invokeResponse"`, ); assert( activity.value.status === 501, - `incorrect status code "${activity.value.status}", expected "501"` + `incorrect status code "${activity.value.status}", expected "501"`, ); assert( !activity.value.body, `expected empty body for invokeResponse from fileConsent flow.\nReceived: ${JSON.stringify( - activity.value.body - )}` + activity.value.body, + )}`, ); }) .startTest(); @@ -838,17 +838,17 @@ describe('TeamsActivityHandler', function () { .assertReply((activity) => { assert( activity.type === 'invokeResponse', - `incorrect activity type "${activity.type}", expected "invokeResponse"` + `incorrect activity type "${activity.type}", expected "invokeResponse"`, ); assert( activity.value.status === 501, - `incorrect status code "${activity.value.status}", expected "501"` + `incorrect status code "${activity.value.status}", expected "501"`, ); assert( !activity.value.body, `expected empty body for invokeResponse from fileConsent flow.\nReceived: ${JSON.stringify( - activity.value.body - )}` + activity.value.body, + )}`, ); }) .startTest(); @@ -868,17 +868,17 @@ describe('TeamsActivityHandler', function () { .assertReply((activity) => { assert( activity.type === 'invokeResponse', - `incorrect activity type "${activity.type}", expected "invokeResponse"` + `incorrect activity type "${activity.type}", expected "invokeResponse"`, ); assert( activity.value.status === 501, - `incorrect status code "${activity.value.status}", expected "501"` + `incorrect status code "${activity.value.status}", expected "501"`, ); assert( !activity.value.body, `expected empty body for invokeResponse from fileConsent flow.\nReceived: ${JSON.stringify( - activity.value.body - )}` + activity.value.body, + )}`, ); }) .startTest(); @@ -1148,24 +1148,6 @@ describe('TeamsActivityHandler', function () { .startTest(); }); - it('handleTeamsMessagingExtensionConfigurationQuerySettingUrl is not overridden', async function () { - const bot = new TeamsActivityHandler(); - - const adapter = new TestAdapter(async (context) => { - await bot.run(context); - }); - - const taskSubmitActivity = createInvokeActivity('composeExtension/querySettingUrl'); - await adapter - .send(taskSubmitActivity) - .assertReply((activity) => { - assert.strictEqual(activity.type, 'invokeResponse'); - assert.strictEqual(activity.value.status, 501); - assert.strictEqual(activity.value.body, undefined); - }) - .startTest(); - }); - it('handleTeamsMessagingExtensionConfigurationSetting is not overridden', async function () { const bot = new TeamsActivityHandler(); @@ -1211,17 +1193,17 @@ describe('TeamsActivityHandler', function () { .assertReply((activity) => { assert( activity.type === 'invokeResponse', - `incorrect activity type "${activity.type}", expected "invokeResponse"` + `incorrect activity type "${activity.type}", expected "invokeResponse"`, ); assert( activity.value.status === 200, - `incorrect status code "${activity.value.status}", expected "200"` + `incorrect status code "${activity.value.status}", expected "200"`, ); assert( !activity.value.body, `expected empty body for invokeResponse from fileConsent flow.\nReceived: ${JSON.stringify( - activity.value.body - )}` + activity.value.body, + )}`, ); }) .startTest(); @@ -1240,17 +1222,17 @@ describe('TeamsActivityHandler', function () { .assertReply((activity) => { assert( activity.type === 'invokeResponse', - `incorrect activity type "${activity.type}", expected "invokeResponse"` + `incorrect activity type "${activity.type}", expected "invokeResponse"`, ); assert( activity.value.status === 200, - `incorrect status code "${activity.value.status}", expected "200"` + `incorrect status code "${activity.value.status}", expected "200"`, ); assert( !activity.value.body, `expected empty body for invokeResponse from fileConsent flow.\nReceived: ${JSON.stringify( - activity.value.body - )}` + activity.value.body, + )}`, ); }) .startTest(); @@ -1275,17 +1257,17 @@ describe('TeamsActivityHandler', function () { .assertReply((activity) => { assert( activity.type === 'invokeResponse', - `incorrect activity type "${activity.type}", expected "invokeResponse"` + `incorrect activity type "${activity.type}", expected "invokeResponse"`, ); assert( activity.value.status === 200, - `incorrect status code "${activity.value.status}", expected "200"` + `incorrect status code "${activity.value.status}", expected "200"`, ); assert( !activity.value.body, `expected empty body for invokeResponse from fileConsent flow.\nReceived: ${JSON.stringify( - activity.value.body - )}` + activity.value.body, + )}`, ); }) .startTest(); @@ -1481,7 +1463,7 @@ describe('TeamsActivityHandler', function () { assert(fileConsentCardResponse, 'fileConsentCardResponse not found'); assert( fileConsentCalled, - 'handleTeamsFileConsent handler was not called before handleTeamsFileConsentAccept handler' + 'handleTeamsFileConsent handler was not called before handleTeamsFileConsentAccept handler', ); fileConsentAcceptCalled = true; } @@ -1491,7 +1473,7 @@ describe('TeamsActivityHandler', function () { assert(fileConsentCardResponse, 'fileConsentCardResponse not found'); assert( fileConsentCalled, - 'handleTeamsFileConsent handler was not called before handleTeamsFileConsentDecline handler' + 'handleTeamsFileConsent handler was not called before handleTeamsFileConsentDecline handler', ); fileConsentDeclineCalled = true; } @@ -1521,17 +1503,17 @@ describe('TeamsActivityHandler', function () { .assertReply((activity) => { assert( activity.type === 'invokeResponse', - `incorrect activity type "${activity.type}", expected "invokeResponse"` + `incorrect activity type "${activity.type}", expected "invokeResponse"`, ); assert( activity.value.status === 200, - `incorrect status code "${activity.value.status}", expected "200"` + `incorrect status code "${activity.value.status}", expected "200"`, ); assert( !activity.value.body, `expected empty body for invokeResponse from fileConsent flow.\nReceived: ${JSON.stringify( - activity.value.body - )}` + activity.value.body, + )}`, ); }) .then(() => { @@ -1553,17 +1535,17 @@ describe('TeamsActivityHandler', function () { .assertReply((activity) => { assert( activity.type === 'invokeResponse', - `incorrect activity type "${activity.type}", expected "invokeResponse"` + `incorrect activity type "${activity.type}", expected "invokeResponse"`, ); assert( activity.value.status === 200, - `incorrect status code "${activity.value.status}", expected "200"` + `incorrect status code "${activity.value.status}", expected "200"`, ); assert( !activity.value.body, `expected empty body for invokeResponse from fileConsent flow.\nReceived: ${JSON.stringify( - activity.value.body - )}` + activity.value.body, + )}`, ); }) .then(() => { @@ -2574,7 +2556,7 @@ describe('TeamsActivityHandler', function () { .then(() => { assert( ncalls === 1, - 'On ConversationUpdate handler should only be called once, times called: ' + ncalls.toString() + 'On ConversationUpdate handler should only be called once, times called: ' + ncalls.toString(), ); }) .startTest(); diff --git a/libraries/botbuilder/tests/teamsInfo.test.js b/libraries/botbuilder/tests/teamsInfo.test.js index 718d85a8a2..9cee971de0 100644 --- a/libraries/botbuilder/tests/teamsInfo.test.js +++ b/libraries/botbuilder/tests/teamsInfo.test.js @@ -279,7 +279,7 @@ describe('TeamsInfo', function () { it('should error if context is null', async function () { await assert.rejects( TeamsInfo.sendMessageToTeamsChannel(null, teamActivity, 'teamID'), - new Error('TurnContext cannot be null') + new Error('TurnContext cannot be null'), ); }); @@ -288,7 +288,7 @@ describe('TeamsInfo', function () { await assert.rejects( TeamsInfo.sendMessageToTeamsChannel(context, null, 'teamID'), - new Error('Activity cannot be null') + new Error('Activity cannot be null'), ); }); @@ -297,7 +297,7 @@ describe('TeamsInfo', function () { await assert.rejects( TeamsInfo.sendMessageToTeamsChannel(context, teamActivity, ''), - new Error('The teamsChannelId cannot be null or empty') + new Error('The teamsChannelId cannot be null or empty'), ); }); @@ -306,7 +306,7 @@ describe('TeamsInfo', function () { await assert.rejects( TeamsInfo.sendMessageToTeamsChannel(context, teamActivity, null), - new Error('The teamsChannelId cannot be null or empty') + new Error('The teamsChannelId cannot be null or empty'), ); }); }); @@ -317,7 +317,7 @@ describe('TeamsInfo', function () { await assert.rejects( TeamsInfo.getTeamChannels(context), - new Error('This method is only valid within the scope of a MS Teams Team.') + new Error('This method is only valid within the scope of a MS Teams Team.'), ); }); @@ -326,7 +326,7 @@ describe('TeamsInfo', function () { await assert.rejects( TeamsInfo.getTeamChannels(context), - new Error('This method is only valid within the scope of a MS Teams Team.') + new Error('This method is only valid within the scope of a MS Teams Team.'), ); }); @@ -365,7 +365,7 @@ describe('TeamsInfo', function () { // There should be a channel in the conversations returned from the conversations assert( channels.find((channel) => channel.id === '19:generalChannelIdgeneralChannelId@thread.skype'), - 'did not find general channel/team id in response' + 'did not find general channel/team id in response', ); }); @@ -404,7 +404,7 @@ describe('TeamsInfo', function () { // There should be a channel in the conversations returned from the conversations assert( channels.find((channel) => channel.id === '19:ChannelIdgeneralChannelId@thread.skype'), - 'did not find general channel/team id in response' + 'did not find general channel/team id in response', ); }); }); @@ -415,7 +415,7 @@ describe('TeamsInfo', function () { await assert.rejects( TeamsInfo.getTeamDetails(context), - new Error('This method is only valid within the scope of a MS Teams Team.') + new Error('This method is only valid within the scope of a MS Teams Team.'), ); }); @@ -424,7 +424,7 @@ describe('TeamsInfo', function () { await assert.rejects( TeamsInfo.getTeamDetails(context), - new Error('This method is only valid within the scope of a MS Teams Team.') + new Error('This method is only valid within the scope of a MS Teams Team.'), ); }); @@ -474,7 +474,7 @@ describe('TeamsInfo', function () { context.turnState.set(context.adapter.ConnectorClientKey, connectorClient); const fetchedTeamDetails = await TeamsInfo.getTeamDetails( context, - '19:ChannelIdgeneralChannelId@thread.skype' + '19:ChannelIdgeneralChannelId@thread.skype', ); assert(fetchTeamDetailsExpectation.isDone()); @@ -516,7 +516,7 @@ describe('TeamsInfo', function () { assert.deepStrictEqual( fetchedMembers, - members.map((member) => ({ ...member, aadObjectId: member.objectId })) + members.map((member) => ({ ...member, aadObjectId: member.objectId })), ); }); @@ -569,7 +569,7 @@ describe('TeamsInfo', function () { assert.deepStrictEqual( fetchedMembers, - members.map((member) => ({ ...member, aadObjectId: member.objectId })) + members.map((member) => ({ ...member, aadObjectId: member.objectId })), ); }); @@ -612,7 +612,7 @@ describe('TeamsInfo', function () { assert.deepStrictEqual( fetchedMembers, - members.map((member) => ({ ...member, aadObjectId: member.objectId })) + members.map((member) => ({ ...member, aadObjectId: member.objectId })), ); }); @@ -693,7 +693,7 @@ describe('TeamsInfo', function () { await assert.rejects( TeamsInfo.getTeamMember(context), - new Error('This method is only valid within the scope of a MS Teams Team.') + new Error('This method is only valid within the scope of a MS Teams Team.'), ); }); }); @@ -836,7 +836,7 @@ describe('TeamsInfo', function () { it('should throw error for missing meetingId', async function () { await assert.rejects( TeamsInfo.getMeetingInfo({ activity: {} }), - Error('meetingId or TurnContext containing meetingId is required.') + Error('meetingId or TurnContext containing meetingId is required.'), ); }); }); @@ -847,7 +847,7 @@ describe('TeamsInfo', function () { await assert.rejects( TeamsInfo.getTeamMembers(context), - new Error('This method is only valid within the scope of a MS Teams Team.') + new Error('This method is only valid within the scope of a MS Teams Team.'), ); }); @@ -856,7 +856,7 @@ describe('TeamsInfo', function () { await assert.rejects( TeamsInfo.getTeamMembers(context), - new Error('This method is only valid within the scope of a MS Teams Team.') + new Error('This method is only valid within the scope of a MS Teams Team.'), ); }); @@ -899,7 +899,7 @@ describe('TeamsInfo', function () { assert.deepStrictEqual( fetchedMembers, - members.map((member) => ({ ...member, aadObjectId: member.objectId })) + members.map((member) => ({ ...member, aadObjectId: member.objectId })), ); }); @@ -942,7 +942,7 @@ describe('TeamsInfo', function () { assert.deepStrictEqual( fetchedMembers, - members.map((member) => ({ ...member, aadObjectId: member.objectId })) + members.map((member) => ({ ...member, aadObjectId: member.objectId })), ); }); }); @@ -1015,7 +1015,7 @@ describe('TeamsInfo', function () { const sendTeamsMeetingNotification = await TeamsInfo.sendMeetingNotification( context, notification, - meetingId + meetingId, ); assert(sendTeamsMeetingNotificationExpectation.isDone()); @@ -1054,7 +1054,7 @@ describe('TeamsInfo', function () { const sendTeamsMeetingNotification = await TeamsInfo.sendMeetingNotification( context, notification, - meetingId + meetingId, ); assert(sendTeamsMeetingNotificationExpectation.isDone()); @@ -1125,7 +1125,7 @@ describe('TeamsInfo', function () { const sendTeamsMeetingNotificationExpectation = nock('https://smba.trafficmanager.net/amer') .post( `/v1/meetings/${encodeURIComponent(teamActivity.channelData.meeting.id)}/notification`, - notification + notification, ) .matchHeader('Authorization', expectedAuthHeader) .reply(202, {}); @@ -1226,21 +1226,21 @@ describe('TeamsInfo', function () { it('should throw an error if an empty activity is provided', async function () { await assert.rejects( TeamsInfo.sendMessageToListOfUsers(context, null, tenantId, members), - Error('activity is required.') + Error('activity is required.'), ); }); it('should throw an error if an empty member list is provided', async function () { await assert.rejects( TeamsInfo.sendMessageToListOfUsers(context, activity, tenantId, null), - Error('members list is required.') + Error('members list is required.'), ); }); it('should throw an error if an empty tenant id is provided', async function () { await assert.rejects( TeamsInfo.sendMessageToListOfUsers(context, activity, null, members), - Error('tenantId is required.') + Error('tenantId is required.'), ); }); }); @@ -1319,14 +1319,14 @@ describe('TeamsInfo', function () { it('should throw an error if an empty activity is provided', async function () { await assert.rejects( TeamsInfo.sendMessageToAllUsersInTenant(context, null, tenantId), - Error('activity is required.') + Error('activity is required.'), ); }); it('should throw an error if an empty tenant id is provided', async function () { await assert.rejects( TeamsInfo.sendMessageToAllUsersInTenant(context, activity, null), - Error('tenantId is required.') + Error('tenantId is required.'), ); }); }); @@ -1407,21 +1407,21 @@ describe('TeamsInfo', function () { it('should throw an error if an empty activity is provided', async function () { await assert.rejects( TeamsInfo.sendMessageToAllUsersInTeam(context, null, tenantId, teamId), - Error('activity is required.') + Error('activity is required.'), ); }); it('should throw an error if an empty tenant id is provided', async function () { await assert.rejects( TeamsInfo.sendMessageToAllUsersInTeam(context, activity, null, teamId), - Error('tenantId is required.') + Error('tenantId is required.'), ); }); it('should throw an error if an empty team id is provided', async function () { await assert.rejects( TeamsInfo.sendMessageToAllUsersInTeam(context, activity, teamId, null), - Error('teamId is required.') + Error('teamId is required.'), ); }); }); @@ -1514,21 +1514,21 @@ describe('TeamsInfo', function () { it('should throw an error if an empty activity is provided', async function () { await assert.rejects( TeamsInfo.sendMessageToListOfChannels(context, null, tenantId, members), - Error('activity is required.') + Error('activity is required.'), ); }); it('should throw an error if an empty member list is provided', async function () { await assert.rejects( TeamsInfo.sendMessageToListOfChannels(context, activity, tenantId, null), - Error('members list is required.') + Error('members list is required.'), ); }); it('should throw an error if an empty tenant id is provided', async function () { await assert.rejects( TeamsInfo.sendMessageToListOfChannels(context, activity, null, members), - Error('tenantId is required.') + Error('tenantId is required.'), ); }); }); @@ -1716,7 +1716,7 @@ describe('TeamsInfo', function () { it("should error if the context doesn't have an adapter", function () { assert.throws( () => TeamsInfo.getConnectorClient({}), - new Error('This method requires a connector client.') + new Error('This method requires a connector client.'), ); }); @@ -1729,30 +1729,31 @@ describe('TeamsInfo', function () { }); describe('getMembersInternal()', function () { - it('should error if an invalid conversationId is passed in.', async function () { + it('getMembers should throw error if an invalid conversationId is passed in.', async function () { await assert.rejects( TeamsInfo.getMembersInternal({}, undefined), - new Error('The getMembers operation needs a valid conversationId.') + new Error('The getMembers operation needs a valid conversationId.'), ); }); - it('should error if an invalid conversationId is passed in.', async function () { + it('getMember should throw error if an invalid conversationId is passed in.', async function () { await assert.rejects( TeamsInfo.getMemberInternal({}, undefined), - new Error('The getMember operation needs a valid conversationId.') + new Error('The getMember operation needs a valid conversationId.'), ); }); it('should error if an invalid userId is passed in.', async function () { await assert.rejects( TeamsInfo.getMemberInternal({}, 'conversationId', undefined), - new Error('The getMember operation needs a valid userId.') + new Error('The getMember operation needs a valid userId.'), ); }); }); describe('getPagedMembersInternal()', function () { let sandbox; + beforeEach(function () { sandbox = sinon.createSandbox(); }); @@ -1764,7 +1765,7 @@ describe('TeamsInfo', function () { it('should error if an invalid conversationId is passed in.', async function () { await assert.rejects( TeamsInfo.getPagedMembersInternal({}, undefined, 'options'), - new Error('The getPagedMembers operation needs a valid conversationId.') + new Error('The getPagedMembers operation needs a valid conversationId.'), ); }); @@ -1802,7 +1803,7 @@ describe('TeamsInfo', function () { assert.strictEqual( getPagedMembers.calledOnce, true, - 'should have called conversations.getConversationPagedMembers' + 'should have called conversations.getConversationPagedMembers', ); }); }); From d5d82e6b9cf2b71b0d65f327ff94b71544fe87fc Mon Sep 17 00:00:00 2001 From: Jhonatan Sandoval Velasco <122501764+JhontSouth@users.noreply.github.com> Date: Mon, 6 Jan 2025 10:05:50 -0500 Subject: [PATCH 14/22] fix: ESLint issues in botbuilder-azure-queues (#4831) * fix eslint issues in botbuilder-azure-queues * remove eslint config * remove eslint-plugin-only-warn --- libraries/botbuilder-azure-queues/eslint.config.cjs | 10 ---------- libraries/botbuilder-azure-queues/package.json | 5 ++--- .../botbuilder-azure-queues/src/azureQueueStorage.ts | 2 +- .../tests/azureQueueStorage.test.js | 4 ++-- 4 files changed, 5 insertions(+), 16 deletions(-) delete mode 100644 libraries/botbuilder-azure-queues/eslint.config.cjs diff --git a/libraries/botbuilder-azure-queues/eslint.config.cjs b/libraries/botbuilder-azure-queues/eslint.config.cjs deleted file mode 100644 index 63647b52cc..0000000000 --- a/libraries/botbuilder-azure-queues/eslint.config.cjs +++ /dev/null @@ -1,10 +0,0 @@ -const onlyWarn = require("eslint-plugin-only-warn"); -const sharedConfig = require("../../eslint.config.cjs") - -module.exports = [ - ...sharedConfig, - { - plugins: { - "only-warn": onlyWarn, - }, - }]; diff --git a/libraries/botbuilder-azure-queues/package.json b/libraries/botbuilder-azure-queues/package.json index 775131505c..caf93ed10b 100644 --- a/libraries/botbuilder-azure-queues/package.json +++ b/libraries/botbuilder-azure-queues/package.json @@ -29,8 +29,7 @@ }, "dependencies": { "@azure/storage-queue": "^12.23.0", - "botbuilder-core": "4.1.6", - "eslint-plugin-only-warn": "^1.1.0" + "botbuilder-core": "4.1.6" }, "devDependencies": { "botbuilder-dialogs": "4.1.6", @@ -41,7 +40,7 @@ "build-docs": "typedoc --theme markdown --entryPoint botbuilder-azure-queues --excludePrivate --includeDeclarations --ignoreCompilerErrors --module amd --out ..\\..\\doc\\botbuilder-azure-queues .\\lib\\index.d.ts --hideGenerator --name \"Bot Builder SDK - Azure Queues\" --readme none", "clean": "rimraf _ts3.4 lib tsconfig.tsbuildinfo", "depcheck": "depcheck --config ../../.depcheckrc", - "lint": "eslint .", + "lint": "eslint . --config ../../eslint.config.cjs", "postbuild": "downlevel-dts lib _ts3.4/lib", "test": "yarn build && nyc mocha --check-leaks tests", "test:compat": "api-extractor run --verbose" diff --git a/libraries/botbuilder-azure-queues/src/azureQueueStorage.ts b/libraries/botbuilder-azure-queues/src/azureQueueStorage.ts index c044efd381..850195baa0 100644 --- a/libraries/botbuilder-azure-queues/src/azureQueueStorage.ts +++ b/libraries/botbuilder-azure-queues/src/azureQueueStorage.ts @@ -42,7 +42,7 @@ export class AzureQueueStorage extends QueueStorage { async queueActivity( activity: Partial, visibilityTimeout?: number, - messageTimeToLive?: number + messageTimeToLive?: number, ): Promise { await this._initialize(); diff --git a/libraries/botbuilder-azure-queues/tests/azureQueueStorage.test.js b/libraries/botbuilder-azure-queues/tests/azureQueueStorage.test.js index 936bba5b06..4948b3b3e8 100644 --- a/libraries/botbuilder-azure-queues/tests/azureQueueStorage.test.js +++ b/libraries/botbuilder-azure-queues/tests/azureQueueStorage.test.js @@ -47,7 +47,7 @@ describe('AzureQueueStorage', function () { new ContinueConversationLater().configure({ date: '=addSeconds(utcNow(), 2)', value: 'foo', - }) + }), ); dm.initialTurnState.set(DialogTurnStateConstants.queueStorage, queueStorage); @@ -62,7 +62,7 @@ describe('AzureQueueStorage', function () { await adapter.send('hi').startTest(); const { receivedMessageItems } = await new Promise((resolve) => setTimeout(resolve, 2000)).then(() => - queue.receiveMessages() + queue.receiveMessages(), ); assert.strictEqual(receivedMessageItems.length, 1); From 5464ddddb99286e5001049ee9ae1303455c26398 Mon Sep 17 00:00:00 2001 From: Jhonatan Sandoval Velasco <122501764+JhontSouth@users.noreply.github.com> Date: Mon, 6 Jan 2025 10:06:10 -0500 Subject: [PATCH 15/22] fix: ESLint issues in botbuilder-dialogs (#4832) * fix eslint issues in botbuilder-dialogs * add eslint config file * combine unit tests and remove duplicated * initialize this.endReason --- .../botbuilder-dialogs/eslint.config.cjs | 11 +- libraries/botbuilder-dialogs/package.json | 3 +- .../scripts/gen-cldr-data.js | 8 +- .../src/choices/choiceFactory.ts | 8 +- .../src/choices/findChoices.ts | 4 +- .../src/choices/findValues.ts | 6 +- .../src/choices/recognizeChoices.ts | 6 +- .../botbuilder-dialogs/src/dialogContext.ts | 15 +- .../src/dialogContextError.ts | 5 +- .../botbuilder-dialogs/src/dialogHelper.ts | 13 +- libraries/botbuilder-dialogs/src/dialogSet.ts | 8 +- .../src/dialogsBotComponent.ts | 6 +- .../src/dialogsComponentRegistration.ts | 3 +- libraries/botbuilder-dialogs/src/i18n.ts | 2 +- .../src/memory/componentPathResolvers.ts | 2 +- .../src/memory/dialogStateManager.ts | 8 +- .../src/memory/scopes/settingsMemoryScope.ts | 2 +- .../src/prompts/activityPrompt.ts | 11 +- .../src/prompts/attachmentPrompt.ts | 4 +- .../src/prompts/choicePrompt.ts | 8 +- .../src/prompts/confirmPrompt.ts | 8 +- .../src/prompts/datetimePrompt.ts | 4 +- .../src/prompts/numberPrompt.ts | 10 +- .../src/prompts/oauthPrompt.ts | 22 +- .../botbuilder-dialogs/src/prompts/prompt.ts | 13 +- .../src/prompts/textPrompt.ts | 4 +- .../src/prompts/userTokenAccess.ts | 40 ++- .../botbuilder-dialogs/src/recognizer.ts | 10 +- .../botbuilder-dialogs/src/skillDialog.ts | 31 +-- .../botbuilder-dialogs/src/waterfallDialog.ts | 10 +- .../tests/activityPrompt.test.js | 8 +- .../tests/attachmentPrompt.test.js | 6 +- .../tests/choicePrompt.test.js | 18 +- .../tests/choices_recognizers.test.js | 246 +++++++++--------- .../tests/choices_tokenizer.test.js | 2 +- .../tests/componentDialog.test.js | 22 +- .../tests/confirmPrompt.test.js | 12 +- .../tests/datetimePrompt.test.js | 8 +- .../tests/dialogContext.test.js | 44 ++-- .../tests/dialogHelper.test.js | 9 +- .../tests/dialogManager.test.js | 8 +- .../tests/dialogSet.test.js | 10 +- .../tests/memory/dialogStateManager.test.js | 10 +- .../tests/memory/memoryScopes.test.js | 10 +- .../tests/numberPrompt.test.js | 22 +- .../tests/oauthPrompt.test.js | 48 ++-- .../tests/skillDialog.test.js | 42 ++- .../tests/textPrompt.test.js | 4 +- .../tests/waterfallDialog.test.js | 68 ++--- 49 files changed, 440 insertions(+), 442 deletions(-) diff --git a/libraries/botbuilder-dialogs/eslint.config.cjs b/libraries/botbuilder-dialogs/eslint.config.cjs index 2a93ef4cf1..d2cc418c22 100644 --- a/libraries/botbuilder-dialogs/eslint.config.cjs +++ b/libraries/botbuilder-dialogs/eslint.config.cjs @@ -1,13 +1,8 @@ -const onlyWarn = require("eslint-plugin-only-warn"); -const sharedConfig = require("../../eslint.config.cjs") +const sharedConfig = require('../../eslint.config.cjs'); module.exports = [ ...sharedConfig, { - ignores: ["**/vendor/"], + ignores: ['**/vendor/'], }, - { - plugins: { - "only-warn": onlyWarn, - }, - }]; +]; diff --git a/libraries/botbuilder-dialogs/package.json b/libraries/botbuilder-dialogs/package.json index 7e996fa365..e02294e682 100644 --- a/libraries/botbuilder-dialogs/package.json +++ b/libraries/botbuilder-dialogs/package.json @@ -33,8 +33,7 @@ "@microsoft/recognizers-text-suite": "1.1.4", "botbuilder-core": "4.1.6", "botbuilder-dialogs-adaptive-runtime-core": "4.1.6", - "botframework-connector": "4.1.6", - "eslint-plugin-only-warn": "^1.1.0", + "botframework-connector": "4.1.6", "globalize": "^1.7.0", "lodash": "^4.17.21", "uuid": "^10.0.0", diff --git a/libraries/botbuilder-dialogs/scripts/gen-cldr-data.js b/libraries/botbuilder-dialogs/scripts/gen-cldr-data.js index 91b65e5a37..007515dcd4 100644 --- a/libraries/botbuilder-dialogs/scripts/gen-cldr-data.js +++ b/libraries/botbuilder-dialogs/scripts/gen-cldr-data.js @@ -61,7 +61,7 @@ async function main() { await exec( process.platform === 'win32' ? 'npm.cmd' : 'npm', ['i', `${cldrDataPackageName}@${cldrDataPackageVersion}`, '--no-save'], - { cwd: tempDirectory, env: process.env } + { cwd: tempDirectory, env: process.env }, ); } catch (err) { plog('Could not install cldr-data'); @@ -88,17 +88,17 @@ async function main() { numbersDirectoryPaths.forEach((v) => { fs.copyFileSync( path.join(cldrDataDirectory, v, numbersFileName), - path.join(vendorDirectory, v, numbersFileName) + path.join(vendorDirectory, v, numbersFileName), ); }); fs.copyFileSync( path.join(cldrDataDirectory, supplementalDirectoryName, likelySubtagsFileName), - path.join(vendorDirectory, supplementalDirectoryName, likelySubtagsFileName) + path.join(vendorDirectory, supplementalDirectoryName, likelySubtagsFileName), ); fs.copyFileSync( path.join(cldrDataDirectory, supplementalDirectoryName, numberingSystemsFileName), - path.join(vendorDirectory, supplementalDirectoryName, numberingSystemsFileName) + path.join(vendorDirectory, supplementalDirectoryName, numberingSystemsFileName), ); } catch (err) { plog('Could not copy files'); diff --git a/libraries/botbuilder-dialogs/src/choices/choiceFactory.ts b/libraries/botbuilder-dialogs/src/choices/choiceFactory.ts index 83b48eb11f..4b6aa44924 100644 --- a/libraries/botbuilder-dialogs/src/choices/choiceFactory.ts +++ b/libraries/botbuilder-dialogs/src/choices/choiceFactory.ts @@ -96,7 +96,7 @@ export class ChoiceFactory { choices: (string | Choice)[], text?: string, speak?: string, - options?: ChoiceFactoryOptions + options?: ChoiceFactoryOptions, ): Partial { const channelId: string = typeof channelOrContext === 'string' ? channelOrContext : channel.getChannelId(channelOrContext); @@ -150,7 +150,7 @@ export class ChoiceFactory { title: choice.value, type: ActionTypes.ImBack, value: choice.value, - } as CardAction) + }) as CardAction, ); const attachment = CardFactory.heroCard(undefined, text, undefined, buttons); @@ -178,7 +178,7 @@ export class ChoiceFactory { choices: (string | Choice)[], text?: string, speak?: string, - options?: ChoiceFactoryOptions + options?: ChoiceFactoryOptions, ): Partial { const opt: ChoiceFactoryOptions = { inlineSeparator: ', ', @@ -229,7 +229,7 @@ export class ChoiceFactory { choices: (string | Choice)[], text?: string, speak?: string, - options?: ChoiceFactoryOptions + options?: ChoiceFactoryOptions, ): Partial { const opt: ChoiceFactoryOptions = { includeNumbers: true, diff --git a/libraries/botbuilder-dialogs/src/choices/findChoices.ts b/libraries/botbuilder-dialogs/src/choices/findChoices.ts index 3ec634968c..a62193a12f 100644 --- a/libraries/botbuilder-dialogs/src/choices/findChoices.ts +++ b/libraries/botbuilder-dialogs/src/choices/findChoices.ts @@ -135,13 +135,13 @@ export interface FoundChoice { export function findChoices( utterance: string, choices: (string | Choice)[], - options?: FindChoicesOptions + options?: FindChoicesOptions, ): ModelResult[] { const opt: FindChoicesOptions = options || {}; // Normalize choices const list: Choice[] = (choices || []).map((choice: Choice) => - typeof choice === 'string' ? { value: choice } : choice + typeof choice === 'string' ? { value: choice } : choice, ); // Build up full list of synonyms to search over. diff --git a/libraries/botbuilder-dialogs/src/choices/findValues.ts b/libraries/botbuilder-dialogs/src/choices/findValues.ts index 48786bf5d6..404662dfdd 100644 --- a/libraries/botbuilder-dialogs/src/choices/findValues.ts +++ b/libraries/botbuilder-dialogs/src/choices/findValues.ts @@ -88,7 +88,7 @@ export interface SortedValue { export function findValues( utterance: string, values: SortedValue[], - options?: FindValuesOptions + options?: FindValuesOptions, ): ModelResult[] { function indexOfToken(token: Token, startPos: number): number { for (let i: number = startPos; i < tokens.length; i++) { @@ -126,7 +126,7 @@ export function findValues( index: number, value: string, vTokens: Token[], - startPos: number + startPos: number, ): ModelResult | undefined { // Match value to utterance and calculate total deviation. // - The tokens are matched in order so "second last" will match in @@ -223,7 +223,7 @@ export function findValues( // Sort matches by score descending matches = matches.sort( - (a: ModelResult, b: ModelResult) => b.resolution.score - a.resolution.score + (a: ModelResult, b: ModelResult) => b.resolution.score - a.resolution.score, ); // Filter out duplicate matching indexes and overlapping characters. diff --git a/libraries/botbuilder-dialogs/src/choices/recognizeChoices.ts b/libraries/botbuilder-dialogs/src/choices/recognizeChoices.ts index ad0a7b42b3..f41c31505f 100644 --- a/libraries/botbuilder-dialogs/src/choices/recognizeChoices.ts +++ b/libraries/botbuilder-dialogs/src/choices/recognizeChoices.ts @@ -45,7 +45,7 @@ import { ModelResult } from './modelResult'; export function recognizeChoices( utterance: string, choices: (string | Choice)[], - options?: FindChoicesOptions + options?: FindChoicesOptions, ): ModelResult[] { function matchChoiceByIndex(match: ModelResult): void { try { @@ -77,14 +77,14 @@ export function recognizeChoices( recognizeNumbers: true, recognizeOrdinals: true, } as FindChoicesOptions, - options + options, ); // Normalize choices const list: Choice[] = (choices || []) .map((choice: Choice) => (typeof choice === 'string' ? { value: choice } : choice)) .filter( - (choice: Choice) => choice // TODO: does this do anything? + (choice: Choice) => choice, // TODO: does this do anything? ); // Try finding choices by text search first diff --git a/libraries/botbuilder-dialogs/src/dialogContext.ts b/libraries/botbuilder-dialogs/src/dialogContext.ts index ad936922ea..fcd151fe65 100644 --- a/libraries/botbuilder-dialogs/src/dialogContext.ts +++ b/libraries/botbuilder-dialogs/src/dialogContext.ts @@ -247,7 +247,7 @@ export class DialogContext { if (!dialog) { throw new DialogContextError( `DialogContext.beginDialog(): A dialog with an id of '${dialogId}' wasn't found.`, - this + this, ); } @@ -360,7 +360,7 @@ export class DialogContext { */ async prompt( dialogId: string, - promptOrOptions: string | Partial | PromptOptions + promptOrOptions: string | Partial | PromptOptions, ): Promise; /** @@ -383,7 +383,7 @@ export class DialogContext { async prompt( dialogId: string, promptOrOptions: string | Partial | PromptOptions, - choices: (string | Choice)[] + choices: (string | Choice)[], ): Promise; /** @@ -405,7 +405,7 @@ export class DialogContext { async prompt( dialogId: string, promptOrOptions: string | Partial, - choices?: (string | Choice)[] + choices?: (string | Choice)[], ): Promise { let options: PromptOptions; if ( @@ -466,7 +466,7 @@ export class DialogContext { if (!dialog) { throw new DialogContextError( `DialogContext.continueDialog(): Can't continue dialog. A dialog with an id of '${instance.id}' wasn't found.`, - this + this, ); } @@ -520,7 +520,7 @@ export class DialogContext { if (!dialog) { throw new DialogContextError( `DialogContext.endDialog(): Can't resume previous dialog. A dialog with an id of '${instance.id}' wasn't found.`, - this + this, ); } @@ -582,7 +582,7 @@ export class DialogContext { if (!dialog) { throw new DialogContextError( `DialogContext.repromptDialog(): Can't find a dialog with an id of '${instance.id}'.`, - this + this, ); } @@ -615,7 +615,6 @@ export class DialogContext { // eslint-disable-next-line @typescript-eslint/no-this-alias let dc: DialogContext = this; if (fromLeaf) { - // eslint-disable-next-line no-constant-condition while (true) { const childDc = dc.child; if (childDc != undefined) { diff --git a/libraries/botbuilder-dialogs/src/dialogContextError.ts b/libraries/botbuilder-dialogs/src/dialogContextError.ts index 279f6bafff..13acdf18af 100644 --- a/libraries/botbuilder-dialogs/src/dialogContextError.ts +++ b/libraries/botbuilder-dialogs/src/dialogContextError.ts @@ -24,7 +24,10 @@ export class DialogContextError extends Error { * @param {Error | string} error Source error or error message. * @param {DialogContext} dialogContext Dialog context that is the source of the error. */ - constructor(public readonly error: Error | string, dialogContext: DialogContext) { + constructor( + readonly error: Error | string, + dialogContext: DialogContext, + ) { super(); if (!(error instanceof Error) && typeof error !== 'string') { diff --git a/libraries/botbuilder-dialogs/src/dialogHelper.ts b/libraries/botbuilder-dialogs/src/dialogHelper.ts index 962d23b363..5724f6d70f 100644 --- a/libraries/botbuilder-dialogs/src/dialogHelper.ts +++ b/libraries/botbuilder-dialogs/src/dialogHelper.ts @@ -36,7 +36,7 @@ import { export async function runDialog( dialog: Dialog, context: TurnContext, - accessor: StatePropertyAccessor + accessor: StatePropertyAccessor, ): Promise { if (!dialog) { throw new Error('runDialog(): missing dialog'); @@ -76,7 +76,7 @@ export async function internalRun( context: TurnContext, dialogId: string, dialogContext: DialogContext, - dialogStateManagerConfiguration?: DialogStateManagerConfiguration + dialogStateManagerConfiguration?: DialogStateManagerConfiguration, ): Promise { // map TurnState into root dialog context.services context.turnState.forEach((service, key) => { @@ -122,7 +122,7 @@ export async function internalRun( async function innerRun( context: TurnContext, dialogId: string, - dialogContext: DialogContext + dialogContext: DialogContext, ): Promise { // Handle EoC and Reprompt event from a parent bot (can be root bot to skill or skill to skill) if (isFromParentToSkill(context)) { @@ -197,9 +197,8 @@ export function shouldSendEndOfConversationToParent(context: TurnContext, turnRe if (claimIdentity && SkillValidation.isSkillClaim(claimIdentity.claims)) { // EoC Activities returned by skills are bounced back to the bot by SkillHandler. // In those cases we will have a SkillConversationReference instance in state. - const skillConversationReference: SkillConversationReference = context.turnState.get( - SkillConversationReferenceKey - ); + const skillConversationReference: SkillConversationReference = + context.turnState.get(SkillConversationReferenceKey); if (skillConversationReference) { // If the skillConversationReference.OAuthScope is for one of the supported channels, we are at the root and we should not send an EoC. return ( @@ -259,7 +258,7 @@ const sendStateSnapshotTrace = async (dialogContext: DialogContext): Promise { + if (typeof (dialog as any as DialogDependencies).getDependencies == 'function') { + (dialog as any as DialogDependencies).getDependencies().forEach((child: Dialog): void => { this.add(child); }); } @@ -184,7 +184,7 @@ export class DialogSet { async createContext(context: TurnContext): Promise { if (!this.dialogState) { throw new Error( - 'DialogSet.createContext(): the dialog set was not bound to a stateProperty when constructed.' + 'DialogSet.createContext(): the dialog set was not bound to a stateProperty when constructed.', ); } const state: DialogState = await this.dialogState.get(context, { dialogStack: [] } as DialogState); diff --git a/libraries/botbuilder-dialogs/src/dialogsBotComponent.ts b/libraries/botbuilder-dialogs/src/dialogsBotComponent.ts index d4766f6ff6..776103a0bd 100644 --- a/libraries/botbuilder-dialogs/src/dialogsBotComponent.ts +++ b/libraries/botbuilder-dialogs/src/dialogsBotComponent.ts @@ -51,7 +51,7 @@ export class DialogsBotComponent extends BotComponent { new ClassMemoryScope(), new ThisMemoryScope(), new ConversationMemoryScope(), - new UserMemoryScope() + new UserMemoryScope(), ); }); @@ -61,8 +61,8 @@ export class DialogsBotComponent extends BotComponent { new HashPathResolver(), new AtAtPathResolver(), new AtPathResolver(), - new PercentPathResolver() - ) + new PercentPathResolver(), + ), ); } } diff --git a/libraries/botbuilder-dialogs/src/dialogsComponentRegistration.ts b/libraries/botbuilder-dialogs/src/dialogsComponentRegistration.ts index 5be3de209a..d51d17af92 100644 --- a/libraries/botbuilder-dialogs/src/dialogsComponentRegistration.ts +++ b/libraries/botbuilder-dialogs/src/dialogsComponentRegistration.ts @@ -16,7 +16,8 @@ import { ComponentMemoryScopes, ComponentPathResolvers, MemoryScope, PathResolve */ export class DialogsComponentRegistration extends ComponentRegistration - implements ComponentMemoryScopes, ComponentPathResolvers { + implements ComponentMemoryScopes, ComponentPathResolvers +{ private readonly services = new ServiceCollection({ memoryScopes: [], pathResolvers: [], diff --git a/libraries/botbuilder-dialogs/src/i18n.ts b/libraries/botbuilder-dialogs/src/i18n.ts index 745030a1fc..053e4239e5 100644 --- a/libraries/botbuilder-dialogs/src/i18n.ts +++ b/libraries/botbuilder-dialogs/src/i18n.ts @@ -6,7 +6,7 @@ * Licensed under the MIT License. */ -/* eslint-disable @typescript-eslint/no-var-requires */ +/* eslint-disable @typescript-eslint/no-require-imports */ const Chinese = require('../vendor/cldr-data/main/zh/numbers.json'); const English = require('../vendor/cldr-data/main/en/numbers.json'); const French = require('../vendor/cldr-data/main/fr/numbers.json'); diff --git a/libraries/botbuilder-dialogs/src/memory/componentPathResolvers.ts b/libraries/botbuilder-dialogs/src/memory/componentPathResolvers.ts index 11ff2f48ce..c57a823f96 100644 --- a/libraries/botbuilder-dialogs/src/memory/componentPathResolvers.ts +++ b/libraries/botbuilder-dialogs/src/memory/componentPathResolvers.ts @@ -18,7 +18,7 @@ export interface ComponentPathResolvers { const componentPathResolvers = z.custom( (val: any) => typeof val.getPathResolvers === 'function', - { message: 'ComponentPathResolvers' } + { message: 'ComponentPathResolvers' }, ); /** diff --git a/libraries/botbuilder-dialogs/src/memory/dialogStateManager.ts b/libraries/botbuilder-dialogs/src/memory/dialogStateManager.ts index a8dece5407..f061155e01 100644 --- a/libraries/botbuilder-dialogs/src/memory/dialogStateManager.ts +++ b/libraries/botbuilder-dialogs/src/memory/dialogStateManager.ts @@ -106,7 +106,7 @@ export class DialogStateManager { */ getValue(pathExpression: string, defaultValue?: T | (() => T)): T { function returnDefault(): T { - return typeof defaultValue == 'function' ? (defaultValue as Function)() : defaultValue; + return typeof defaultValue == 'function' ? (defaultValue as () => T)() : defaultValue; } // Get path segments @@ -119,7 +119,7 @@ export class DialogStateManager { const scope = this.getMemoryScope(segments[0].toString()); if (scope == undefined) { console.warn( - `DialogStateManager.getValue: a scope of '${segments[0]}' wasn't found for '${pathExpression}'.` + `DialogStateManager.getValue: a scope of '${segments[0]}' wasn't found for '${pathExpression}'.`, ); return returnDefault(); } @@ -170,7 +170,7 @@ export class DialogStateManager { // Only allow positive indexes if (key < 0) { throw new Error( - `DialogStateManager.setValue: unable to update value for '${pathExpression}'. Negative indexes aren't allowed.` + `DialogStateManager.setValue: unable to update value for '${pathExpression}'. Negative indexes aren't allowed.`, ); } @@ -386,7 +386,7 @@ export class DialogStateManager { segment += c; } else { throw new Error( - `DialogStateManager.normalizePath: Invalid path detected - ${pathExpression}` + `DialogStateManager.normalizePath: Invalid path detected - ${pathExpression}`, ); } break; diff --git a/libraries/botbuilder-dialogs/src/memory/scopes/settingsMemoryScope.ts b/libraries/botbuilder-dialogs/src/memory/scopes/settingsMemoryScope.ts index aa99e6a07b..4a0b2079bc 100644 --- a/libraries/botbuilder-dialogs/src/memory/scopes/settingsMemoryScope.ts +++ b/libraries/botbuilder-dialogs/src/memory/scopes/settingsMemoryScope.ts @@ -114,7 +114,7 @@ export class SettingsMemoryScope extends MemoryScope { const root = this.convertFlattenSettingToNode(Object.entries(configuration)); settings = root.children.reduce( (acc, child) => ({ ...acc, [child.value]: this.convertNodeToObject(child) }), - settings + settings, ); } diff --git a/libraries/botbuilder-dialogs/src/prompts/activityPrompt.ts b/libraries/botbuilder-dialogs/src/prompts/activityPrompt.ts index 7243c20cd8..ef9ab4cadd 100644 --- a/libraries/botbuilder-dialogs/src/prompts/activityPrompt.ts +++ b/libraries/botbuilder-dialogs/src/prompts/activityPrompt.ts @@ -25,7 +25,10 @@ export class ActivityPrompt extends Dialog { * @param dialogId Unique ID of the dialog within its parent `DialogSet` or `ComponentDialog`. * @param validator Validator that will be called each time a new activity is received. */ - constructor(dialogId: string, private validator: PromptValidator) { + constructor( + dialogId: string, + private validator: PromptValidator, + ) { super(dialogId); } @@ -80,7 +83,7 @@ export class ActivityPrompt extends Dialog { const recognized: PromptRecognizerResult = await this.onRecognize( dc.context, state.state, - state.options + state.options, ); if (state.state['attemptCount'] === undefined) { @@ -162,7 +165,7 @@ export class ActivityPrompt extends Dialog { context: TurnContext, state: object, options: PromptOptions, - isRetry: boolean + isRetry: boolean, ): Promise { if (isRetry && options.retryPrompt) { await context.sendActivity(options.retryPrompt, undefined, InputHints.ExpectingInput); @@ -184,7 +187,7 @@ export class ActivityPrompt extends Dialog { protected async onRecognize( context: TurnContext, _state: object, - _options: PromptOptions + _options: PromptOptions, ): Promise> { return { succeeded: true, value: context.activity }; } diff --git a/libraries/botbuilder-dialogs/src/prompts/attachmentPrompt.ts b/libraries/botbuilder-dialogs/src/prompts/attachmentPrompt.ts index 1ef43b03d3..5a3ec97812 100644 --- a/libraries/botbuilder-dialogs/src/prompts/attachmentPrompt.ts +++ b/libraries/botbuilder-dialogs/src/prompts/attachmentPrompt.ts @@ -40,7 +40,7 @@ export class AttachmentPrompt extends Prompt { context: TurnContext, state: any, options: PromptOptions, - isRetry: boolean + isRetry: boolean, ): Promise { if (isRetry && options.retryPrompt) { await context.sendActivity(options.retryPrompt, undefined, InputHints.ExpectingInput); @@ -61,7 +61,7 @@ export class AttachmentPrompt extends Prompt { protected async onRecognize( context: TurnContext, _state: any, - _options: PromptOptions + _options: PromptOptions, ): Promise> { const value: Attachment[] = context.activity.attachments; diff --git a/libraries/botbuilder-dialogs/src/prompts/choicePrompt.ts b/libraries/botbuilder-dialogs/src/prompts/choicePrompt.ts index 66864e96cc..2d1e3d5700 100644 --- a/libraries/botbuilder-dialogs/src/prompts/choicePrompt.ts +++ b/libraries/botbuilder-dialogs/src/prompts/choicePrompt.ts @@ -66,7 +66,7 @@ export class ChoicePrompt extends Prompt { dialogId: string, validator?: PromptValidator, defaultLocale?: string, - choiceDefaults?: ChoiceDefaultsChoicePrompt + choiceDefaults?: ChoiceDefaultsChoicePrompt, ) { super(dialogId, validator); this.style = ListStyle.auto; @@ -104,7 +104,7 @@ export class ChoicePrompt extends Prompt { context: TurnContext, state: any, options: PromptOptions, - isRetry: boolean + isRetry: boolean, ): Promise { // Determine locale const locale = this.determineCulture(context.activity); @@ -140,7 +140,7 @@ export class ChoicePrompt extends Prompt { protected async onRecognize( context: TurnContext, state: any, - options: PromptOptions + options: PromptOptions, ): Promise> { const result: PromptRecognizerResult = { succeeded: false }; const activity = context.activity; @@ -168,7 +168,7 @@ export class ChoicePrompt extends Prompt { private determineCulture(activity: Activity, opt?: FindChoicesOptions): string { const optLocale = opt && opt.locale ? opt.locale : null; let culture = PromptCultureModels.mapToNearestLanguage( - activity.locale || optLocale || this.defaultLocale || PromptCultureModels.English.locale + activity.locale || optLocale || this.defaultLocale || PromptCultureModels.English.locale, ); if (!(culture && this.choiceDefaults[culture])) { culture = PromptCultureModels.English.locale; diff --git a/libraries/botbuilder-dialogs/src/prompts/confirmPrompt.ts b/libraries/botbuilder-dialogs/src/prompts/confirmPrompt.ts index 79ff6d6fc4..c41d991aa6 100644 --- a/libraries/botbuilder-dialogs/src/prompts/confirmPrompt.ts +++ b/libraries/botbuilder-dialogs/src/prompts/confirmPrompt.ts @@ -66,7 +66,7 @@ export class ConfirmPrompt extends Prompt { dialogId: string, validator?: PromptValidator, defaultLocale?: string, - choiceDefaults?: ChoiceDefaultsConfirmPrompt + choiceDefaults?: ChoiceDefaultsConfirmPrompt, ) { super(dialogId, validator); this.style = ListStyle.auto; @@ -107,7 +107,7 @@ export class ConfirmPrompt extends Prompt { context: TurnContext, state: any, options: PromptOptions, - isRetry: boolean + isRetry: boolean, ): Promise { // Format prompt to send let prompt: Partial; @@ -138,7 +138,7 @@ export class ConfirmPrompt extends Prompt { protected async onRecognize( context: TurnContext, _state, - _options: PromptOptions + _options: PromptOptions, ): Promise> { const result: PromptRecognizerResult = { succeeded: false }; const activity = context.activity; @@ -174,7 +174,7 @@ export class ConfirmPrompt extends Prompt { */ private determineCulture(activity: Activity): string { let culture = PromptCultureModels.mapToNearestLanguage( - activity.locale || this.defaultLocale || PromptCultureModels.English.locale + activity.locale || this.defaultLocale || PromptCultureModels.English.locale, ); if (!(culture && this.choiceDefaults[culture])) { culture = PromptCultureModels.English.locale; diff --git a/libraries/botbuilder-dialogs/src/prompts/datetimePrompt.ts b/libraries/botbuilder-dialogs/src/prompts/datetimePrompt.ts index 20f080c9f9..ef8738b69c 100644 --- a/libraries/botbuilder-dialogs/src/prompts/datetimePrompt.ts +++ b/libraries/botbuilder-dialogs/src/prompts/datetimePrompt.ts @@ -71,7 +71,7 @@ export class DateTimePrompt extends Prompt { context: TurnContext, state: any, options: PromptOptions, - isRetry: boolean + isRetry: boolean, ): Promise { if (isRetry && options.retryPrompt) { await context.sendActivity(options.retryPrompt, undefined, InputHints.ExpectingInput); @@ -93,7 +93,7 @@ export class DateTimePrompt extends Prompt { protected async onRecognize( context: TurnContext, _state: any, - _options: PromptOptions + _options: PromptOptions, ): Promise> { const result: PromptRecognizerResult = { succeeded: false }; const activity: Activity = context.activity; diff --git a/libraries/botbuilder-dialogs/src/prompts/numberPrompt.ts b/libraries/botbuilder-dialogs/src/prompts/numberPrompt.ts index 14438c0746..f91ab42e66 100644 --- a/libraries/botbuilder-dialogs/src/prompts/numberPrompt.ts +++ b/libraries/botbuilder-dialogs/src/prompts/numberPrompt.ts @@ -6,9 +6,9 @@ * Licensed under the MIT License. */ -/* eslint-disable @typescript-eslint/no-var-requires */ +/* eslint-disable-next-line @typescript-eslint/no-require-imports */ const Globalize = require('globalize'); -import Recognizers from '@microsoft/recognizers-text-number'; +import { recognizeNumber } from '@microsoft/recognizers-text-number'; import * as locales from '../i18n'; import { InputHints, TurnContext } from 'botbuilder-core'; import { Prompt, PromptOptions, PromptRecognizerResult, PromptValidator } from './prompt'; @@ -56,7 +56,7 @@ export class NumberPrompt extends Prompt { context: TurnContext, state: unknown, options: PromptOptions, - isRetry: boolean + isRetry: boolean, ): Promise { if (isRetry && options.retryPrompt) { await context.sendActivity(options.retryPrompt, undefined, InputHints.ExpectingInput); @@ -78,7 +78,7 @@ export class NumberPrompt extends Prompt { protected async onRecognize( context: TurnContext, _state: unknown, - _options: PromptOptions + _options: PromptOptions, ): Promise> { const result: PromptRecognizerResult = { succeeded: false }; const activity = context.activity; @@ -91,7 +91,7 @@ export class NumberPrompt extends Prompt { const defaultLocale = this.defaultLocale || 'en-us'; const locale = activity.locale || defaultLocale; - const [{ resolution = null } = {}] = Recognizers.recognizeNumber(utterance, locale) || []; + const [{ resolution = null } = {}] = recognizeNumber(utterance, locale) || []; if (resolution) { result.succeeded = true; diff --git a/libraries/botbuilder-dialogs/src/prompts/oauthPrompt.ts b/libraries/botbuilder-dialogs/src/prompts/oauthPrompt.ts index 8360a3379e..c2fd2db8b6 100644 --- a/libraries/botbuilder-dialogs/src/prompts/oauthPrompt.ts +++ b/libraries/botbuilder-dialogs/src/prompts/oauthPrompt.ts @@ -171,7 +171,7 @@ export class OAuthPrompt extends Dialog { constructor( dialogId: string, private settings: OAuthPromptSettings, - private validator?: PromptValidator + private validator?: PromptValidator, ) { super(dialogId); } @@ -326,7 +326,7 @@ export class OAuthPrompt extends Dialog { static async sendOAuthCard( settings: OAuthPromptSettings, turnContext: TurnContext, - prompt?: string | Partial + prompt?: string | Partial, ): Promise { // Initialize outgoing message const msg: Partial = @@ -377,7 +377,7 @@ export class OAuthPrompt extends Dialog { settings.text, link, signInResource.tokenExchangeResource, - signInResource.tokenPostResource + signInResource.tokenPostResource, ); // Set the appropriate ActionType for the button. @@ -425,7 +425,7 @@ export class OAuthPrompt extends Dialog { context, context.activity.serviceUrl, claimsIdentity, - state.scope + state.scope, ); context.turnState.set(context.adapter.ConnectorClientKey, connectorClient); @@ -450,8 +450,8 @@ export class OAuthPrompt extends Dialog { await context.sendActivity( this.getTokenExchangeInvokeResponse( StatusCodes.BAD_REQUEST, - 'The bot received an InvokeActivity that is missing a TokenExchangeInvokeRequest value. This is required to be sent with the InvokeActivity.' - ) + 'The bot received an InvokeActivity that is missing a TokenExchangeInvokeRequest value. This is required to be sent with the InvokeActivity.', + ), ); } else if (context.activity.value.connectionName != this.settings.connectionName) { // Connection name on activity does not match that of setting @@ -459,8 +459,8 @@ export class OAuthPrompt extends Dialog { this.getTokenExchangeInvokeResponse( StatusCodes.BAD_REQUEST, 'The bot received an InvokeActivity with a TokenExchangeInvokeRequest containing a ConnectionName that does not match the ConnectionName' + - 'expected by the bots active OAuthPrompt. Ensure these names match when sending the InvokeActivityInvalid ConnectionName in the TokenExchangeInvokeRequest' - ) + 'expected by the bots active OAuthPrompt. Ensure these names match when sending the InvokeActivityInvalid ConnectionName in the TokenExchangeInvokeRequest', + ), ); } else { let tokenExchangeResponse: TokenResponse; @@ -478,12 +478,12 @@ export class OAuthPrompt extends Dialog { await context.sendActivity( this.getTokenExchangeInvokeResponse( StatusCodes.PRECONDITION_FAILED, - 'The bot is unable to exchange token. Proceed with regular login.' - ) + 'The bot is unable to exchange token. Proceed with regular login.', + ), ); } else { await context.sendActivity( - this.getTokenExchangeInvokeResponse(StatusCodes.OK, null, context.activity.value.id) + this.getTokenExchangeInvokeResponse(StatusCodes.OK, null, context.activity.value.id), ); token = { channelId: tokenExchangeResponse.channelId, diff --git a/libraries/botbuilder-dialogs/src/prompts/prompt.ts b/libraries/botbuilder-dialogs/src/prompts/prompt.ts index d8a276a7fe..8926a9920a 100644 --- a/libraries/botbuilder-dialogs/src/prompts/prompt.ts +++ b/libraries/botbuilder-dialogs/src/prompts/prompt.ts @@ -179,7 +179,10 @@ export abstract class Prompt extends Dialog { * @param dialogId Unique ID of the prompt within its parent `DialogSet` or `ComponentDialog`. * @param validator (Optional) custom validator used to provide additional validation and re-prompting logic for the prompt. */ - protected constructor(dialogId: string, private validator?: PromptValidator) { + protected constructor( + dialogId: string, + private validator?: PromptValidator, + ) { super(dialogId); } @@ -294,7 +297,7 @@ export abstract class Prompt extends Dialog { const recognized: PromptRecognizerResult = await this.onRecognize( dc.context, state.state, - state.options + state.options, ); return recognized.succeeded; } @@ -352,7 +355,7 @@ export abstract class Prompt extends Dialog { context: TurnContext, state: object, options: PromptOptions, - isRetry: boolean + isRetry: boolean, ): Promise; /** @@ -368,7 +371,7 @@ export abstract class Prompt extends Dialog { protected abstract onRecognize( context: TurnContext, state: object, - options: PromptOptions + options: PromptOptions, ): Promise>; /** @@ -386,7 +389,7 @@ export abstract class Prompt extends Dialog { channelId: string, choices: (string | Choice)[], style: ListStyle, - options?: ChoiceFactoryOptions + options?: ChoiceFactoryOptions, ): Partial { // Get base prompt text (if any) let text = ''; diff --git a/libraries/botbuilder-dialogs/src/prompts/textPrompt.ts b/libraries/botbuilder-dialogs/src/prompts/textPrompt.ts index 2de237d3fc..fd47eba6c4 100644 --- a/libraries/botbuilder-dialogs/src/prompts/textPrompt.ts +++ b/libraries/botbuilder-dialogs/src/prompts/textPrompt.ts @@ -43,7 +43,7 @@ export class TextPrompt extends Prompt { context: TurnContext, state: any, options: PromptOptions, - isRetry: boolean + isRetry: boolean, ): Promise { if (isRetry && options.retryPrompt) { await context.sendActivity(options.retryPrompt, undefined, InputHints.ExpectingInput); @@ -65,7 +65,7 @@ export class TextPrompt extends Prompt { protected async onRecognize( context: TurnContext, _state: any, - _options: PromptOptions + _options: PromptOptions, ): Promise> { const value: string = context.activity.text; diff --git a/libraries/botbuilder-dialogs/src/prompts/userTokenAccess.ts b/libraries/botbuilder-dialogs/src/prompts/userTokenAccess.ts index 3aeebc8af2..4b938a8983 100644 --- a/libraries/botbuilder-dialogs/src/prompts/userTokenAccess.ts +++ b/libraries/botbuilder-dialogs/src/prompts/userTokenAccess.ts @@ -15,7 +15,6 @@ import { } from 'botframework-connector'; const ExtendedUserTokenProviderT = z.custom( - // eslint-disable-next-line @typescript-eslint/no-explicit-any (val: any) => typeof val.exchangeToken === 'function' && typeof val.getSignInResource === 'function' && @@ -23,23 +22,22 @@ const ExtendedUserTokenProviderT = z.custom( typeof val.signOutUser === 'function', { message: 'ExtendedUserTokenProvider', - } + }, ); type ConnectorClientBuilder = { createConnectorClientWithIdentity: ( serviceUrl: string, claimsIdentity: ClaimsIdentity, - audience: string + audience: string, ) => Promise; }; const ConnectorClientBuilderT = z.custom( - // eslint-disable-next-line @typescript-eslint/no-explicit-any (val: any) => typeof val.createConnectorClientWithIdentity === 'function', { message: 'ConnectorClientBuilder', - } + }, ); /** @@ -48,10 +46,10 @@ const ConnectorClientBuilderT = z.custom( export async function getUserToken( context: TurnContext, settings: OAuthPromptSettings, - magicCode: string + magicCode: string, ): Promise { const userTokenClient = context.turnState.get( - (context.adapter as CloudAdapterBase).UserTokenClientKey + (context.adapter as CloudAdapterBase).UserTokenClientKey, ); const extendedUserTokenProvider = ExtendedUserTokenProviderT.safeParse(context.adapter); @@ -60,14 +58,14 @@ export async function getUserToken( context.activity?.from?.id, settings.connectionName, context.activity?.channelId, - magicCode + magicCode, ); } else if (extendedUserTokenProvider.success) { return extendedUserTokenProvider.data.getUserToken( context, settings.connectionName, magicCode, - settings.oAuthAppCredentials + settings.oAuthAppCredentials, ); } else { throw new Error('OAuth prompt is not supported by the current adapter'); @@ -79,10 +77,10 @@ export async function getUserToken( */ export async function getSignInResource( context: TurnContext, - settings: OAuthPromptSettings + settings: OAuthPromptSettings, ): Promise { const userTokenClient = context.turnState.get( - (context.adapter as CloudAdapterBase).UserTokenClientKey + (context.adapter as CloudAdapterBase).UserTokenClientKey, ); const extendedUserTokenProvider = ExtendedUserTokenProviderT.safeParse(context.adapter); if (userTokenClient) { @@ -93,7 +91,7 @@ export async function getSignInResource( settings.connectionName, context.activity?.from?.id, undefined, - settings.oAuthAppCredentials + settings.oAuthAppCredentials, ); } else { throw new Error('OAuth prompt is not supported by the current adapter'); @@ -105,21 +103,21 @@ export async function getSignInResource( */ export async function signOutUser(context: TurnContext, settings: OAuthPromptSettings): Promise { const userTokenClient = context.turnState.get( - (context.adapter as CloudAdapterBase).UserTokenClientKey + (context.adapter as CloudAdapterBase).UserTokenClientKey, ); const extendedUserTokenProvider = ExtendedUserTokenProviderT.safeParse(context.adapter); if (userTokenClient) { await userTokenClient.signOutUser( context.activity?.from?.id, settings.connectionName, - context.activity?.channelId + context.activity?.channelId, ); } else if (extendedUserTokenProvider.success) { await extendedUserTokenProvider.data.signOutUser( context, settings.connectionName, context.activity?.from?.id, - settings.oAuthAppCredentials + settings.oAuthAppCredentials, ); } else { throw new Error('OAuth prompt is not supported by the current adapter'); @@ -132,10 +130,10 @@ export async function signOutUser(context: TurnContext, settings: OAuthPromptSet export async function exchangeToken( context: TurnContext, settings: OAuthPromptSettings, - tokenExchangeRequest: TokenExchangeRequest + tokenExchangeRequest: TokenExchangeRequest, ): Promise { const userTokenClient = context.turnState.get( - (context.adapter as CloudAdapterBase).UserTokenClientKey + (context.adapter as CloudAdapterBase).UserTokenClientKey, ); const extendedUserTokenProvider = ExtendedUserTokenProviderT.safeParse(context.adapter); @@ -144,14 +142,14 @@ export async function exchangeToken( context.activity?.from?.id, settings.connectionName, context.activity?.channelId, - tokenExchangeRequest + tokenExchangeRequest, ); } else if (extendedUserTokenProvider.success) { return extendedUserTokenProvider.data.exchangeToken( context, settings.connectionName, context.activity?.from?.id, - tokenExchangeRequest + tokenExchangeRequest, ); } else { throw new Error('OAuth prompt is not supported by the current adapter'); @@ -165,10 +163,10 @@ export async function createConnectorClient( context: TurnContext, serviceUrl: string, claimsIdentity: ClaimsIdentity, - audience: string + audience: string, ): Promise { const connectorFactory = context.turnState.get( - (context.adapter as CloudAdapterBase).ConnectorFactoryKey + (context.adapter as CloudAdapterBase).ConnectorFactoryKey, ); const connectorClientBuilder = ConnectorClientBuilderT.safeParse(context.adapter); if (connectorFactory) { diff --git a/libraries/botbuilder-dialogs/src/recognizer.ts b/libraries/botbuilder-dialogs/src/recognizer.ts index 6e28043276..f613acf02e 100644 --- a/libraries/botbuilder-dialogs/src/recognizer.ts +++ b/libraries/botbuilder-dialogs/src/recognizer.ts @@ -17,7 +17,7 @@ import { import { Configurable } from './configurable'; import { DialogContext } from './dialogContext'; import { DialogTurnStateConstants } from './dialogTurnStateConstants'; -import omit = require('lodash/omit'); +import omit from 'lodash/omit'; export interface RecognizerConfiguration { id?: string; @@ -51,7 +51,7 @@ export class Recognizer extends Configurable implements RecognizerConfiguration _dialogContext: DialogContext, _activity: Partial, _telemetryProperties?: Record, - _telemetryMetrics?: Record + _telemetryMetrics?: Record, ): Promise { throw new Error('Please implement recognize function.'); } @@ -113,7 +113,7 @@ export class Recognizer extends Configurable implements RecognizerConfiguration protected fillRecognizerResultTelemetryProperties( recognizerResult: RecognizerResult, telemetryProperties: Record, - _dialogContext?: DialogContext + _dialogContext?: DialogContext, ): Record { const { intent, score } = getTopScoringIntent(recognizerResult); const intents = Object.entries(recognizerResult.intents); @@ -126,7 +126,7 @@ export class Recognizer extends Configurable implements RecognizerConfiguration Intents: intents.length > 0 ? JSON.stringify(recognizerResult.intents) : undefined, Entities: recognizerResult.entities ? JSON.stringify(recognizerResult.entities) : undefined, AdditionalProperties: JSON.stringify( - omit(recognizerResult, ['text', 'alteredText', 'intents', 'entities']) + omit(recognizerResult, ['text', 'alteredText', 'intents', 'entities']), ), }; @@ -161,7 +161,7 @@ export class Recognizer extends Configurable implements RecognizerConfiguration dialogContext: DialogContext, eventName: string, telemetryProperties?: Record, - telemetryMetrics?: Record + telemetryMetrics?: Record, ): void { if (this.telemetryClient instanceof NullTelemetryClient) { const turnStateTelemetryClient = diff --git a/libraries/botbuilder-dialogs/src/skillDialog.ts b/libraries/botbuilder-dialogs/src/skillDialog.ts index 8a7cf0ef6d..c9cd94b664 100644 --- a/libraries/botbuilder-dialogs/src/skillDialog.ts +++ b/libraries/botbuilder-dialogs/src/skillDialog.ts @@ -82,7 +82,7 @@ export class SkillDialog extends Dialog> { const skillActivity = TurnContext.applyConversationReference( clonedActivity, TurnContext.getConversationReference(dc.context.activity), - true + true, ) as Activity; // Store delivery mode and connection name in dialog state for later use. @@ -161,7 +161,7 @@ export class SkillDialog extends Dialog> { const activity = TurnContext.applyConversationReference( { type: ActivityTypes.EndOfConversation }, reference, - true + true, ); activity.channelData = context.activity.channelData; @@ -253,7 +253,7 @@ export class SkillDialog extends Dialog> { private async sendToSkill( context: TurnContext, activity: Activity, - skillConversationId: string + skillConversationId: string, ): Promise { if (activity.type === ActivityTypes.Invoke) { // Force ExpectReplies for invoke activities so we can get the replies right away and send them back to the channel if needed. @@ -272,13 +272,13 @@ export class SkillDialog extends Dialog> { skillInfo.skillEndpoint, this.dialogOptions.skillHostEndpoint, skillConversationId, - activity + activity, ); // Inspect the skill response status if (!isSuccessStatusCode(response.status)) { throw new Error( - `Error invoking the skill id: "${skillInfo.id}" at "${skillInfo.skillEndpoint}" (status is ${response.status}). \r\n ${response.body}` + `Error invoking the skill id: "${skillInfo.id}" at "${skillInfo.skillEndpoint}" (status is ${response.status}). \r\n ${response.body}`, ); } @@ -331,14 +331,14 @@ export class SkillDialog extends Dialog> { private async interceptOAuthCards( context: TurnContext, activity: Activity, - connectionName: string + connectionName: string, ): Promise { if (!connectionName) { return false; } const oAuthCardAttachment: Attachment = (activity.attachments || []).find( - (c) => c.contentType === CardFactory.contentTypes.oauthCard + (c) => c.contentType === CardFactory.contentTypes.oauthCard, ); if (!oAuthCardAttachment) { return false; @@ -355,7 +355,7 @@ export class SkillDialog extends Dialog> { const result: TokenResponse = await UserTokenAccess.exchangeToken( context, { title: 'Sign In', connectionName: connectionName }, - { uri } + { uri }, ); if (!result || !result.token) { @@ -367,7 +367,7 @@ export class SkillDialog extends Dialog> { activity, oAuthCard.tokenExchangeResource.id, oAuthCard.connectionName, - result.token + result.token, ); } catch { // Failures in token exchange are not fatal. They simply mean that the user needs to be shown the skill's OAuthCard. @@ -382,7 +382,7 @@ export class SkillDialog extends Dialog> { incomingActivity: Activity, id: string, connectionName: string, - token: string + token: string, ): Promise { const ref: Partial = TurnContext.getConversationReference(incomingActivity); const activity: Activity = TurnContext.applyConversationReference({ ...incomingActivity }, ref) as any; @@ -398,7 +398,7 @@ export class SkillDialog extends Dialog> { skillInfo.skillEndpoint, this.dialogOptions.skillHostEndpoint, incomingActivity.conversation.id, - activity + activity, ); // Check response status: true if success, false if failure @@ -423,15 +423,16 @@ export class SkillDialog extends Dialog> { // Create a conversationId to interact with the skill and send the activity let skillConversationId: string; try { - skillConversationId = await this.dialogOptions.conversationIdFactory.createSkillConversationIdWithOptions( - conversationIdFactoryOptions - ); + skillConversationId = + await this.dialogOptions.conversationIdFactory.createSkillConversationIdWithOptions( + conversationIdFactoryOptions, + ); } catch (err) { if (err.message !== 'Not Implemented') throw err; // If the SkillConversationIdFactoryBase implementation doesn't support createSkillConversationIdWithOptions(), // use createSkillConversationId() instead. skillConversationId = await this.dialogOptions.conversationIdFactory.createSkillConversationId( - TurnContext.getConversationReference(activity) as ConversationReference + TurnContext.getConversationReference(activity) as ConversationReference, ); } return skillConversationId; diff --git a/libraries/botbuilder-dialogs/src/waterfallDialog.ts b/libraries/botbuilder-dialogs/src/waterfallDialog.ts index 35774cc91d..481046d0aa 100644 --- a/libraries/botbuilder-dialogs/src/waterfallDialog.ts +++ b/libraries/botbuilder-dialogs/src/waterfallDialog.ts @@ -6,10 +6,8 @@ * Licensed under the MIT License. */ import { v4 as uuidv4 } from 'uuid'; -import { ActivityTypes } from 'botbuilder-core'; -import { TurnContext, telemetryTrackDialogView } from 'botbuilder-core'; -import { DialogInstance } from './dialog'; -import { Dialog, DialogReason, DialogTurnResult } from './dialog'; +import { ActivityTypes, TurnContext, telemetryTrackDialogView } from 'botbuilder-core'; +import { DialogInstance, Dialog, DialogReason, DialogTurnResult } from './dialog'; import { DialogContext } from './dialogContext'; import { WaterfallStepContext } from './waterfallStepContext'; @@ -260,7 +258,7 @@ export class WaterfallDialog extends Dialog { dc: DialogContext, index: number, reason: DialogReason, - result?: any + result?: any, ): Promise { if (index < this.steps.length) { // Update persisted step index @@ -278,7 +276,7 @@ export class WaterfallDialog extends Dialog { onNext: async (stepResult?: any): Promise> => { if (nextCalled) { throw new Error( - `WaterfallStepContext.next(): method already called for dialog and step '${this.id}[${index}]'.` + `WaterfallStepContext.next(): method already called for dialog and step '${this.id}[${index}]'.`, ); } nextCalled = true; diff --git a/libraries/botbuilder-dialogs/tests/activityPrompt.test.js b/libraries/botbuilder-dialogs/tests/activityPrompt.test.js index 88a65d8cd2..cffe225c7e 100644 --- a/libraries/botbuilder-dialogs/tests/activityPrompt.test.js +++ b/libraries/botbuilder-dialogs/tests/activityPrompt.test.js @@ -40,7 +40,7 @@ describe('ActivityPrompt', function () { assert(prompt, 'validator missing PromptValidatorContext.'); assert(typeof prompt.recognized.value === 'object', 'recognized.value was not an object.'); return true; - }) + }), ); await adapter @@ -73,7 +73,7 @@ describe('ActivityPrompt', function () { assert(prompt, 'validator missing PromptValidatorContext.'); assert(typeof prompt.recognized.value === 'object', 'recognized.value was not an object.'); return false; - }) + }), ); await adapter @@ -106,7 +106,7 @@ describe('ActivityPrompt', function () { assert(prompt, 'validator missing PromptValidatorContext.'); assert(typeof prompt.recognized.value === 'object', 'recognized.value was not an object.'); return false; - }) + }), ); await adapter @@ -132,7 +132,7 @@ describe('ActivityPrompt', function () { return false; } return true; - }) + }), ); const adapter = new TestAdapter(async (turnContext) => { diff --git a/libraries/botbuilder-dialogs/tests/attachmentPrompt.test.js b/libraries/botbuilder-dialogs/tests/attachmentPrompt.test.js index 50e34880b8..e434150052 100644 --- a/libraries/botbuilder-dialogs/tests/attachmentPrompt.test.js +++ b/libraries/botbuilder-dialogs/tests/attachmentPrompt.test.js @@ -68,7 +68,7 @@ describe('AttachmentPrompt', function () { new AttachmentPrompt('prompt', async (prompt) => { assert(prompt); return prompt.recognized.succeeded; - }) + }), ); await adapter @@ -102,7 +102,7 @@ describe('AttachmentPrompt', function () { new AttachmentPrompt('prompt', async (prompt) => { assert(prompt); return prompt.recognized.succeeded; - }) + }), ); await adapter @@ -142,7 +142,7 @@ describe('AttachmentPrompt', function () { await prompt.context.sendActivity('Bad input.'); } return prompt.recognized.succeeded; - }) + }), ); await adapter diff --git a/libraries/botbuilder-dialogs/tests/choicePrompt.test.js b/libraries/botbuilder-dialogs/tests/choicePrompt.test.js index 95f649a79a..183d06c175 100644 --- a/libraries/botbuilder-dialogs/tests/choicePrompt.test.js +++ b/libraries/botbuilder-dialogs/tests/choicePrompt.test.js @@ -120,7 +120,7 @@ describe('ChoicePrompt', function () { 'Please choose a color.', stringChoices.map((choice) => { return { value: choice, action: {} }; - }) + }), ); } else if (results.status === DialogTurnStatus.complete) { const selectedChoice = results.result; @@ -286,7 +286,7 @@ describe('ChoicePrompt', function () { } return prompt.recognized.succeeded; }, - 'es-es' + 'es-es', ); dialogs.add(choicePrompt); @@ -362,7 +362,7 @@ describe('ChoicePrompt', function () { } return prompt.recognized.succeeded; }, - 'es-es' + 'es-es', ); dialogs.add(choicePrompt); @@ -439,7 +439,7 @@ describe('ChoicePrompt', function () { } return prompt.recognized.succeeded; }, - 'es-es' + 'es-es', ); dialogs.add(choicePrompt); @@ -454,9 +454,9 @@ describe('ChoicePrompt', function () { assert.strictEqual(activity.text, expectedAnswer); }) .startTest(); - }) + }), ); - }) + }), ); }); @@ -489,7 +489,7 @@ describe('ChoicePrompt', function () { } return prompt.recognized.succeeded; }, - null + null, ); dialogs.add(choicePrompt); @@ -504,7 +504,7 @@ describe('ChoicePrompt', function () { assert.strictEqual(activity.text, `Please choose a color.${expectedChoices}`); }) .startTest(); - }) + }), ); }); @@ -553,7 +553,7 @@ describe('ChoicePrompt', function () { return prompt.recognized.succeeded; }, culture.locale, - customDict + customDict, ); dialogs.add(choicePrompt); diff --git a/libraries/botbuilder-dialogs/tests/choices_recognizers.test.js b/libraries/botbuilder-dialogs/tests/choices_recognizers.test.js index 46b88ff686..90258d5fb4 100644 --- a/libraries/botbuilder-dialogs/tests/choices_recognizers.test.js +++ b/libraries/botbuilder-dialogs/tests/choices_recognizers.test.js @@ -26,7 +26,7 @@ function assertChoice(result, value, index, score, synonym) { if (synonym) { assert( resolution.synonym === synonym, - `Invalid resolution.synonym of '${resolution.synonym}' for '${value}' choice.` + `Invalid resolution.synonym of '${resolution.synonym}' for '${value}' choice.`, ); } } @@ -59,152 +59,154 @@ const valuesWithSpecialCharacters = [ { value: 'A ??? B', index: 2 }, ]; -describe('findValues()', function () { - this.timeout(5000); +describe('Choices Recognizers Tests', function () { + describe('findValues()', function () { + this.timeout(5000); - it('should find a simple value in an single word utterance.', function () { - const found = findValues('red', colorValues); - assert(found.length === 1, `Invalid token count of '${found.length}' returned.`); - assertResult(found[0], 0, 2, 'red'); - assertValue(found[0], 'red', 0, 1.0); - }); + it('should find a simple value in an single word utterance.', function () { + const found = findValues('red', colorValues); + assert(found.length === 1, `Invalid token count of '${found.length}' returned.`); + assertResult(found[0], 0, 2, 'red'); + assertValue(found[0], 'red', 0, 1.0); + }); - it('should find a simple value in an utterance.', function () { - const found = findValues('the red one please.', colorValues); - assert(found.length === 1, `Invalid token count of '${found.length}' returned.`); - assertResult(found[0], 4, 6, 'red'); - assertValue(found[0], 'red', 0, 1.0); - }); + it('should find a simple value in an utterance.', function () { + const found = findValues('the red one please.', colorValues); + assert(found.length === 1, `Invalid token count of '${found.length}' returned.`); + assertResult(found[0], 4, 6, 'red'); + assertValue(found[0], 'red', 0, 1.0); + }); - it('should find multiple values within an utterance.', function () { - const found = findValues('the red and blue ones please.', colorValues); - assert(found.length === 2, `Invalid token count of '${found.length}' returned.`); - assertResult(found[0], 4, 6, 'red'); - assertValue(found[0], 'red', 0, 1.0); - assertValue(found[1], 'blue', 2, 1.0); - }); + it('should find multiple values within an utterance.', function () { + const found = findValues('the red and blue ones please.', colorValues); + assert(found.length === 2, `Invalid token count of '${found.length}' returned.`); + assertResult(found[0], 4, 6, 'red'); + assertValue(found[0], 'red', 0, 1.0); + assertValue(found[1], 'blue', 2, 1.0); + }); - it('should find multiple values that overlap.', function () { - const found = findValues('the bread pudding and bread please.', overlappingValues); - assert(found.length === 2, `Invalid token count of '${found.length}' returned.`); - assertResult(found[0], 4, 16, 'bread pudding'); - assertValue(found[0], 'bread pudding', 1, 1.0); - assertValue(found[1], 'bread', 0, 1.0); - }); + it('should find multiple values that overlap.', function () { + const found = findValues('the bread pudding and bread please.', overlappingValues); + assert(found.length === 2, `Invalid token count of '${found.length}' returned.`); + assertResult(found[0], 4, 16, 'bread pudding'); + assertValue(found[0], 'bread pudding', 1, 1.0); + assertValue(found[1], 'bread', 0, 1.0); + }); - it('should correctly disambiguate between very similar values.', function () { - const found = findValues('option B', similarValues, { allowPartialMatches: true }); - assert(found.length === 1, `Invalid token count of '${found.length}' returned.`); - assertValue(found[0], 'option B', 1, 1.0); - }); + it('should correctly disambiguate between very similar values.', function () { + const found = findValues('option B', similarValues, { allowPartialMatches: true }); + assert(found.length === 1, `Invalid token count of '${found.length}' returned.`); + assertValue(found[0], 'option B', 1, 1.0); + }); - it('should prefer exact match.', function () { - const index = 1; - const utterance = valuesWithSpecialCharacters[index].value; - const found = findValues(utterance, valuesWithSpecialCharacters); - assert(found.length === 1, `Invalid token count of '${found.length}' returned.`); - assertValue(found[0], utterance, index, 1); + it('should prefer exact match.', function () { + const index = 1; + const utterance = valuesWithSpecialCharacters[index].value; + const found = findValues(utterance, valuesWithSpecialCharacters); + assert(found.length === 1, `Invalid token count of '${found.length}' returned.`); + assertValue(found[0], utterance, index, 1); + }); }); -}); -//============================================================================= -// findChoices() tests -//============================================================================= + //============================================================================= + // findChoices() tests + //============================================================================= -const colorChoices = ['red', 'green', 'blue']; -const overlappingChoices = ['bread', 'bread pudding', 'pudding']; + const colorChoices = ['red', 'green', 'blue']; + const overlappingChoices = ['bread', 'bread pudding', 'pudding']; -describe('findChoices()', function () { - this.timeout(5000); + describe('findChoices()', function () { + this.timeout(5000); - it('should find a single choice in an utterance.', function () { - const found = findChoices('the red one please.', colorChoices); - assert(found.length === 1, `Invalid token count of '${found.length}' returned.`); - assertResult(found[0], 4, 6, 'red'); - assertChoice(found[0], 'red', 0, 1.0, 'red'); - }); + it('should find a single choice in an utterance.', function () { + const found = findChoices('the red one please.', colorChoices); + assert(found.length === 1, `Invalid token count of '${found.length}' returned.`); + assertResult(found[0], 4, 6, 'red'); + assertChoice(found[0], 'red', 0, 1.0, 'red'); + }); - it('should find multiple choices within an utterance.', function () { - const found = findChoices('the red and blue ones please.', colorChoices); - assert(found.length === 2, `Invalid token count of '${found.length}' returned.`); - assertResult(found[0], 4, 6, 'red'); - assertChoice(found[0], 'red', 0, 1.0); - assertChoice(found[1], 'blue', 2, 1.0); - }); + it('should find multiple choices within an utterance.', function () { + const found = findChoices('the red and blue ones please.', colorChoices); + assert(found.length === 2, `Invalid token count of '${found.length}' returned.`); + assertResult(found[0], 4, 6, 'red'); + assertChoice(found[0], 'red', 0, 1.0); + assertChoice(found[1], 'blue', 2, 1.0); + }); - it('should find multiple choices that overlap.', function () { - const found = findChoices('the bread pudding and bread please.', overlappingChoices); - assert(found.length === 2, `Invalid token count of '${found.length}' returned.`); - assertResult(found[0], 4, 16, 'bread pudding'); - assertChoice(found[0], 'bread pudding', 1, 1.0); - assertChoice(found[1], 'bread', 0, 1.0); + it('should find multiple choices that overlap.', function () { + const found = findChoices('the bread pudding and bread please.', overlappingChoices); + assert(found.length === 2, `Invalid token count of '${found.length}' returned.`); + assertResult(found[0], 4, 16, 'bread pudding'); + assertChoice(found[0], 'bread pudding', 1, 1.0); + assertChoice(found[1], 'bread', 0, 1.0); + }); }); -}); -//============================================================================= -// recognizeChoices() tests -//============================================================================= + //============================================================================= + // recognizeChoices() tests + //============================================================================= -describe('recognizeChoices()', function () { - this.timeout(5000); + describe('recognizeChoices()', function () { + this.timeout(5000); - it('should find a choice in an utterance by name.', function () { - const found = recognizeChoices('the red one please.', colorChoices); - assert(found.length === 1, `Invalid token count of '${found.length}' returned.`); - assertResult(found[0], 4, 6, 'red'); - assertChoice(found[0], 'red', 0, 1.0, 'red'); - }); + it('should find a choice in an utterance by name.', function () { + const found = recognizeChoices('the red one please.', colorChoices); + assert(found.length === 1, `Invalid token count of '${found.length}' returned.`); + assertResult(found[0], 4, 6, 'red'); + assertChoice(found[0], 'red', 0, 1.0, 'red'); + }); - it('should find a choice in an utterance by ordinal position.', function () { - const found = recognizeChoices('the first one please.', colorChoices); - assert(found.length === 1, `Invalid token count of '${found.length}' returned.`); - assertResult(found[0], 4, 8, 'first'); - assertChoice(found[0], 'red', 0, 1.0); - }); + it('should find a choice in an utterance by ordinal position.', function () { + const found = recognizeChoices('the first one please.', colorChoices); + assert(found.length === 1, `Invalid token count of '${found.length}' returned.`); + assertResult(found[0], 4, 8, 'first'); + assertChoice(found[0], 'red', 0, 1.0); + }); - it('should find multiple choices in an utterance by ordinal position.', function () { - const found = recognizeChoices('the first and third one please.', colorChoices); - assert(found.length === 2, `Invalid token count of '${found.length}' returned.`); - assertChoice(found[0], 'red', 0, 1.0); - assertChoice(found[1], 'blue', 2, 1.0); - }); + it('should find multiple choices in an utterance by ordinal position.', function () { + const found = recognizeChoices('the first and third one please.', colorChoices); + assert(found.length === 2, `Invalid token count of '${found.length}' returned.`); + assertChoice(found[0], 'red', 0, 1.0); + assertChoice(found[1], 'blue', 2, 1.0); + }); - it('should find a choice in an utterance by numerical index (as digit.)', function () { - const found = recognizeChoices('1', colorChoices); - assert(found.length === 1, `Invalid token count of '${found.length}' returned.`); - assertResult(found[0], 0, 0, '1'); - assertChoice(found[0], 'red', 0, 1.0); - }); + it('should find a choice in an utterance by numerical index (as digit.)', function () { + const found = recognizeChoices('1', colorChoices); + assert(found.length === 1, `Invalid token count of '${found.length}' returned.`); + assertResult(found[0], 0, 0, '1'); + assertChoice(found[0], 'red', 0, 1.0); + }); - it('should find a choice in an utterance by numerical index (as text.)', function () { - const found = recognizeChoices('one', colorChoices); - assert(found.length === 1, `Invalid token count of '${found.length}' returned.`); - assertResult(found[0], 0, 2, 'one'); - assertChoice(found[0], 'red', 0, 1.0); - }); + it('should find a choice in an utterance by numerical index (as text.)', function () { + const found = recognizeChoices('one', colorChoices); + assert(found.length === 1, `Invalid token count of '${found.length}' returned.`); + assertResult(found[0], 0, 2, 'one'); + assertChoice(found[0], 'red', 0, 1.0); + }); - it('should find multiple choices in an utterance by numerical index.', function () { - const found = recognizeChoices('option one and 3.', colorChoices); - assert(found.length === 2, `Invalid token count of '${found.length}' returned.`); - assertChoice(found[0], 'red', 0, 1.0); - assertChoice(found[1], 'blue', 2, 1.0); - }); + it('should find multiple choices in an utterance by numerical index.', function () { + const found = recognizeChoices('option one and 3.', colorChoices); + assert(found.length === 2, `Invalid token count of '${found.length}' returned.`); + assertChoice(found[0], 'red', 0, 1.0); + assertChoice(found[1], 'blue', 2, 1.0); + }); - it('should not find a choice if recognizeOrdinals option disabled.', function () { - const found = recognizeChoices('first', colorChoices, { recognizeOrdinals: false }); - assert(found.length === 0, `Invalid token count of '${found.length}' returned.`); - }); + it('should not find a choice if recognizeOrdinals option disabled.', function () { + const found = recognizeChoices('first', colorChoices, { recognizeOrdinals: false }); + assert(found.length === 0, `Invalid token count of '${found.length}' returned.`); + }); - it('should not find a choice if recognizeNumbers option disabled.', function () { - const found = recognizeChoices('1', colorChoices, { recognizeNumbers: false }); - assert(found.length === 0, `Invalid token count of '${found.length}' returned.`); - }); + it('should not find a choice if recognizeNumbers option disabled.', function () { + const found = recognizeChoices('1', colorChoices, { recognizeNumbers: false }); + assert(found.length === 0, `Invalid token count of '${found.length}' returned.`); + }); - it('should not find a choice if both recognizeOrdinals and recognizeNumbers options are disabled.', function () { - const found = recognizeChoices('the first and third one please.', colorChoices, { - recognizeOrdinals: false, - recognizeNumbers: false, + it('should not find a choice if both recognizeOrdinals and recognizeNumbers options are disabled.', function () { + const found = recognizeChoices('the first and third one please.', colorChoices, { + recognizeOrdinals: false, + recognizeNumbers: false, + }); + assert(found.length === 0, `Invalid token count of '${found.length}' returned.`); }); - assert(found.length === 0, `Invalid token count of '${found.length}' returned.`); }); }); diff --git a/libraries/botbuilder-dialogs/tests/choices_tokenizer.test.js b/libraries/botbuilder-dialogs/tests/choices_tokenizer.test.js index 9e897803a4..21cbae00d7 100644 --- a/libraries/botbuilder-dialogs/tests/choices_tokenizer.test.js +++ b/libraries/botbuilder-dialogs/tests/choices_tokenizer.test.js @@ -7,7 +7,7 @@ function assertToken(token, start, end, text, normalized) { assert(token.text === text, `Invalid token.text of '${token.text}' for '${text}' token.`); assert( token.normalized === normalized || text, - `Invalid token.normalized of '${token.normalized}' for '${text}' token.` + `Invalid token.normalized of '${token.normalized}' for '${text}' token.`, ); } diff --git a/libraries/botbuilder-dialogs/tests/componentDialog.test.js b/libraries/botbuilder-dialogs/tests/componentDialog.test.js index 1d534a2139..ff8a9e10ea 100644 --- a/libraries/botbuilder-dialogs/tests/componentDialog.test.js +++ b/libraries/botbuilder-dialogs/tests/componentDialog.test.js @@ -29,7 +29,7 @@ describe('ComponentDialog', function () { component.addDialog(simpleH2ofall); assert( component.initialDialogId === 'simpleWaterfall', - `unexpected change in initialDialogId, it is now ${component.initialDialogId}` + `unexpected change in initialDialogId, it is now ${component.initialDialogId}`, ); }); @@ -101,7 +101,7 @@ describe('ComponentDialog', function () { const results = await dc.beginDialog('composite'); assert( results.status === DialogTurnStatus.complete, - `unexpected DialogTurnStatus received: ${results.status}` + `unexpected DialogTurnStatus received: ${results.status}`, ); assert(results.result === undefined, `unexpected results.result received: ${results.result}`); }); @@ -134,7 +134,7 @@ describe('ComponentDialog', function () { const results = await dc.beginDialog('composite'); assert( results.status === DialogTurnStatus.waiting, - `unexpected DialogTurnStatus received: ${results.status}` + `unexpected DialogTurnStatus received: ${results.status}`, ); assert(results.result === undefined, `unexpected results.result received: ${results.result}`); }); @@ -187,7 +187,7 @@ describe('ComponentDialog', function () { } else { assert( results.status === DialogTurnStatus.complete, - `results.status should be 'complete' not ${results.status}` + `results.status should be 'complete' not ${results.status}`, ); assert(results.result === undefined, `results.result should be undefined, not ${results.result}`); await turnContext.sendActivity('Done.'); @@ -242,11 +242,11 @@ describe('ComponentDialog', function () { const results = await dc.beginDialog('component'); assert( results.status === DialogTurnStatus.cancelled, - `should have returned ${DialogTurnStatus.cancelled} not ${results.status}` + `should have returned ${DialogTurnStatus.cancelled} not ${results.status}`, ); assert( dc.stack.length === 0, - `should have a dialogStack without 0 dialogs, not ${dc.stack.length} dialogs` + `should have a dialogStack without 0 dialogs, not ${dc.stack.length} dialogs`, ); }); @@ -270,7 +270,7 @@ describe('ComponentDialog', function () { simpleStepContextCheck(step); assert( step.reason === DialogReason.endCalled, - `called ComponentDialog should have bubbled up "cancelCalled" not "${step.reason}".` + `called ComponentDialog should have bubbled up "cancelCalled" not "${step.reason}".`, ); await step.context.sendActivity('Cancelled successfully.'); return await step.endDialog(); @@ -327,7 +327,7 @@ describe('ComponentDialog', function () { await step.context.sendActivity('Child finished.'); return await step.endDialog(); }, - ]) + ]), ); const parentComponent = new ComponentDialog('parentComponent'); @@ -339,7 +339,7 @@ describe('ComponentDialog', function () { await step.context.sendActivity(`Parent called with: ${step.options.value}`); return await step.endDialog(step.options.value); }, - ]) + ]), ); const dialogs = new DialogSet(dialogState); @@ -354,7 +354,7 @@ describe('ComponentDialog', function () { } else { assert( results.status === DialogTurnStatus.complete, - `results.status should be 'complete' not ${results.status}` + `results.status should be 'complete' not ${results.status}`, ); assert(results.result === undefined, `results.result should be undefined, not ${results.result}`); await turnContext.sendActivity('Done.'); @@ -408,7 +408,7 @@ describe('ComponentDialog', function () { } else { assert( results.status === DialogTurnStatus.complete, - `results.status should be 'complete' not ${results.status}` + `results.status should be 'complete' not ${results.status}`, ); assert(results.result === undefined, `results.result should be undefined, not ${results.result}`); await turnContext.sendActivity('Done.'); diff --git a/libraries/botbuilder-dialogs/tests/confirmPrompt.test.js b/libraries/botbuilder-dialogs/tests/confirmPrompt.test.js index 90655b9c62..0a22bd720b 100644 --- a/libraries/botbuilder-dialogs/tests/confirmPrompt.test.js +++ b/libraries/botbuilder-dialogs/tests/confirmPrompt.test.js @@ -311,7 +311,7 @@ describe('ConfirmPrompt', function () { } return prompt.recognized.succeeded; }, - 'ja-jp' + 'ja-jp', ); dialogs.add(confirmPrompt); @@ -393,7 +393,7 @@ describe('ConfirmPrompt', function () { } return prompt.recognized.succeeded; }, - 'es-es' + 'es-es', ); dialogs.add(confirmPrompt); @@ -474,7 +474,7 @@ describe('ConfirmPrompt', function () { } return prompt.recognized.succeeded; }, - testLocale + testLocale, ); dialogs.add(confirmPrompt); @@ -489,9 +489,9 @@ describe('ConfirmPrompt', function () { assert.strictEqual(activity.text, expectedAnswer); }) .startTest(); - }) + }), ); - }) + }), ); }); @@ -547,7 +547,7 @@ describe('ConfirmPrompt', function () { return prompt.recognized.succeeded; }, culture.locale, - customDict + customDict, ); dialogs.add(confirmPrompt); diff --git a/libraries/botbuilder-dialogs/tests/datetimePrompt.test.js b/libraries/botbuilder-dialogs/tests/datetimePrompt.test.js index e228d06e56..2d61c83af9 100644 --- a/libraries/botbuilder-dialogs/tests/datetimePrompt.test.js +++ b/libraries/botbuilder-dialogs/tests/datetimePrompt.test.js @@ -88,7 +88,7 @@ describe('DatetimePrompt', function () { new DateTimePrompt('prompt', async (prompt) => { assert(prompt); return prompt.recognized.succeeded; - }) + }), ); await adapter @@ -124,7 +124,7 @@ describe('DatetimePrompt', function () { new DateTimePrompt('prompt', async (prompt) => { assert(prompt); return prompt.recognized.succeeded; - }) + }), ); await adapter @@ -165,7 +165,7 @@ describe('DatetimePrompt', function () { await prompt.context.sendActivity('That was a bad date.'); } return prompt.recognized.succeeded; - }) + }), ); await adapter @@ -200,7 +200,7 @@ describe('DatetimePrompt', function () { new DateTimePrompt('prompt', async (prompt) => { assert(prompt); return prompt.recognized.succeeded; - }) + }), ); await adapter.send('Hello').send(invalidMessage).send(answerMessage2).assertReply('2012-09-02').startTest(); diff --git a/libraries/botbuilder-dialogs/tests/dialogContext.test.js b/libraries/botbuilder-dialogs/tests/dialogContext.test.js index d74847766a..6dfc0935ee 100644 --- a/libraries/botbuilder-dialogs/tests/dialogContext.test.js +++ b/libraries/botbuilder-dialogs/tests/dialogContext.test.js @@ -32,7 +32,7 @@ describe('DialogContext', function () { assert(step, 'WaterfallStepContext not passed in to WaterfallStep.'); return await step.endDialog(true); }, - ]) + ]), ); await adapter.send(beginMessage).startTest(); @@ -60,7 +60,7 @@ describe('DialogContext', function () { assert(step.options.z === 'z', 'Correct DialogOptions was not passed in to WaterfallDialog.'); return await step.endDialog(true); }, - ]) + ]), ); await adapter.send(beginMessage).startTest(); @@ -79,13 +79,13 @@ describe('DialogContext', function () { assert.strictEqual( err.message, "DialogContext.beginDialog(): A dialog with an id of 'b' wasn't found.", - `unexpected error message thrown: "${err.message}"` + `unexpected error message thrown: "${err.message}"`, ); assert(err instanceof DialogContextError, 'err should be a DialogContextError'); assert(err.dialogContext, 'err should include dialogContext'); return true; - } + }, ); }); @@ -98,7 +98,7 @@ describe('DialogContext', function () { async function (step) { return await step.endDialog(); }, - ]) + ]), ); await adapter.send(beginMessage).startTest(); @@ -123,11 +123,11 @@ describe('DialogContext', function () { assert.strictEqual( step.options.prompt, 'test', - 'promptOrOptions arg was not correctly passed through.' + 'promptOrOptions arg was not correctly passed through.', ); return await step.endDialog(); }, - ]) + ]), ); await adapter.send(beginMessage).startTest(); @@ -151,7 +151,7 @@ describe('DialogContext', function () { assert(step, 'WaterfallStepContext not passed in to WaterfallStep.'); return await step.endDialog(); }, - ]) + ]), ); await adapter.send(beginMessage).startTest(); @@ -177,7 +177,7 @@ describe('DialogContext', function () { assert.strictEqual(step.options.choices.length, 3, 'not all choices were passed in.'); return await step.endDialog(); }, - ]) + ]), ); await adapter.send(beginMessage).startTest(); @@ -207,7 +207,7 @@ describe('DialogContext', function () { assert.strictEqual(step.result, 120, "incorrect step.result value received from 'b' dialog."); return await step.endDialog(119); }, - ]) + ]), ); dialogs.add( @@ -216,7 +216,7 @@ describe('DialogContext', function () { assert(step, 'WaterfallStepContext not passed in to WaterfallStep.'); return await step.endDialog(120); }, - ]) + ]), ); await adapter.send(beginMessage).startTest(); @@ -254,7 +254,7 @@ describe('DialogContext', function () { assert(step, 'WaterfallStepContext not passed in to WaterfallStep.'); return await step.endDialog(true); }, - ]) + ]), ); await adapter.send(beginMessage).send(continueMessage).startTest(); @@ -286,7 +286,7 @@ describe('DialogContext', function () { async function () { assert(false, "shouldn't continue"); }, - ]) + ]), ); await assert.rejects( @@ -296,13 +296,13 @@ describe('DialogContext', function () { assert.strictEqual( err.message, "DialogContext.continueDialog(): Can't continue dialog. A dialog with an id of 'b' wasn't found.", - `unexpected error message thrown: "${err.message}"` + `unexpected error message thrown: "${err.message}"`, ); assert(err instanceof DialogContextError, 'err should be a DialogContextError'); assert(err.dialogContext, 'err should include dialogContext'); return true; - } + }, ); }); @@ -349,7 +349,7 @@ describe('DialogContext', function () { assert(step.result, 'ended dialog.', 'unexpected step.result received.'); return await step.endDialog(true); }, - ]) + ]), ); dialogs.add( @@ -358,7 +358,7 @@ describe('DialogContext', function () { assert(step, 'WaterfallStepContext not passed in to WaterfallStep.'); return await step.endDialog('ended dialog.'); }, - ]) + ]), ); await adapter.send(beginMessage).startTest(); @@ -374,7 +374,7 @@ describe('DialogContext', function () { assert.strictEqual( results.result, undefined, - 'received unexpected value for results.result (expected undefined).' + 'received unexpected value for results.result (expected undefined).', ); }); @@ -389,7 +389,7 @@ describe('DialogContext', function () { assert(step, 'WaterfallStepContext not passed in to WaterfallStep.'); return await step.replaceDialog('b', { z: step.options.z }); }, - ]) + ]), ); await adapter.send(beginMessage).startTest(); @@ -415,7 +415,7 @@ describe('DialogContext', function () { assert(step, 'WaterfallStepContext not passed in to WaterfallStep.'); return await step.replaceDialog('b', { z: step.options.z }); }, - ]) + ]), ); dialogs.add( @@ -426,7 +426,7 @@ describe('DialogContext', function () { assert.strictEqual(step.options.z, 'z', 'incorrect step.options received.'); return await step.endDialog(step.options.z); }, - ]) + ]), ); await adapter.send(beginMessage).startTest(); @@ -450,7 +450,7 @@ describe('DialogContext', function () { assert(step, 'WaterfallStepContext not passed in to WaterfallStep.'); return await step.endDialog(); }, - ]) + ]), ); await adapter.send(beginMessage).startTest(); diff --git a/libraries/botbuilder-dialogs/tests/dialogHelper.test.js b/libraries/botbuilder-dialogs/tests/dialogHelper.test.js index 0b9f93135f..0dca013cb8 100644 --- a/libraries/botbuilder-dialogs/tests/dialogHelper.test.js +++ b/libraries/botbuilder-dialogs/tests/dialogHelper.test.js @@ -114,10 +114,10 @@ class SimpleComponentDialog extends ComponentDialog { this.WaterfallDialog = 'WaterfallDialog'; this.addDialog(new TextPrompt(this.TextPrompt)); this.addDialog( - new WaterfallDialog(this.WaterfallDialog, [this.promptForName.bind(this), this.finalStep.bind(this)]) + new WaterfallDialog(this.WaterfallDialog, [this.promptForName.bind(this), this.finalStep.bind(this)]), ); this.initialDialogId = this.WaterfallDialog; - this.endReason; + this.endReason = ''; } async onEndDialog(context, instance, reason) { @@ -144,7 +144,7 @@ class ComponentDialogWithPrematureEnd extends ComponentDialog { const waterfallDialog = 'waterfallDialog'; this.addDialog(new WaterfallDialog(waterfallDialog, [this.finalStep.bind(this)])); this.initialDialogId = waterfallDialog; - this.endReason; + this.endReason = ''; } async onEndDialog(context, instance, reason) { @@ -163,7 +163,7 @@ class ComponentDialogWithCancellation extends ComponentDialog { const waterfallDialog = 'waterfallDialog'; this.addDialog(new WaterfallDialog(waterfallDialog, [this.finalStep.bind(this)])); this.initialDialogId = waterfallDialog; - this.endReason; + this.endReason = ''; } async onEndDialog(context, instance, reason) { @@ -259,6 +259,7 @@ describe('runDialog()', function () { assert.strictEqual(_eocSent.type, ActivityTypes.EndOfConversation); assert.strictEqual(_eocSent.code, EndOfConversationCodes.CompletedSuccessfully); }); + it('handles premature dialog cancellation', async function () { const dialog = new ComponentDialogWithCancellation(); const testFlow = createTestFlow(dialog, FlowTestCase.MiddleSkill); diff --git a/libraries/botbuilder-dialogs/tests/dialogManager.test.js b/libraries/botbuilder-dialogs/tests/dialogManager.test.js index ebbbcbefdc..f853429eac 100644 --- a/libraries/botbuilder-dialogs/tests/dialogManager.test.js +++ b/libraries/botbuilder-dialogs/tests/dialogManager.test.js @@ -118,7 +118,7 @@ function createTestFlow(dialog, testCase = FlowTestCase.RootBotOnly, enabledTrac _dmTurnResult = await dm.onTurn(context); }, convRef, - enabledTrace + enabledTrace, ); adapter.use(new AutoSaveStateMiddleware(userState, convoState)); @@ -133,10 +133,10 @@ class SimpleComponentDialog extends ComponentDialog { this.WaterfallDialog = 'WaterfallDialog'; this.addDialog(new TextPrompt(this.TextPrompt)); this.addDialog( - new WaterfallDialog(this.WaterfallDialog, [this.promptForName.bind(this), this.finalStep.bind(this)]) + new WaterfallDialog(this.WaterfallDialog, [this.promptForName.bind(this), this.finalStep.bind(this)]), ); this.initialDialogId = this.WaterfallDialog; - this.endReason; + this.endReason = ''; } async onEndDialog(context, instance, reason) { @@ -378,7 +378,7 @@ describe('DialogManager', function () { // Leaf nodes / non-containers should not be registered. strictEqual( dm.dialogs.getDialogs().find((d) => d instanceof SendActivity), - undefined + undefined, ); }); diff --git a/libraries/botbuilder-dialogs/tests/dialogSet.test.js b/libraries/botbuilder-dialogs/tests/dialogSet.test.js index 6d479c8f71..008c95531a 100644 --- a/libraries/botbuilder-dialogs/tests/dialogSet.test.js +++ b/libraries/botbuilder-dialogs/tests/dialogSet.test.js @@ -24,7 +24,7 @@ describe('DialogSet', function () { function (step) { assert(step); }, - ]) + ]), ); }); @@ -32,7 +32,7 @@ describe('DialogSet', function () { const dialogs = new DialogSet(); await assert.rejects( dialogs.createContext({ type: 'message', text: 'hi' }), - new Error('DialogSet.createContext(): the dialog set was not bound to a stateProperty when constructed.') + new Error('DialogSet.createContext(): the dialog set was not bound to a stateProperty when constructed.'), ); }); @@ -45,14 +45,14 @@ describe('DialogSet', function () { function (dc) { assert(dc); }, - ]) + ]), ) .add( new WaterfallDialog('B', [ function (dc) { assert(dc); }, - ]) + ]), ); assert(dialogs.find('A'), 'dialog A not found.'); assert(dialogs.find('B'), 'dialog B not found.'); @@ -92,7 +92,7 @@ describe('DialogSet', function () { await step.context.sendActivity('Good bye!'); return await step.endDialog(); }, - ]) + ]), ); const adapter = new TestAdapter(async (turnContext) => { diff --git a/libraries/botbuilder-dialogs/tests/memory/dialogStateManager.test.js b/libraries/botbuilder-dialogs/tests/memory/dialogStateManager.test.js index 4027b21f0e..cd62921c09 100644 --- a/libraries/botbuilder-dialogs/tests/memory/dialogStateManager.test.js +++ b/libraries/botbuilder-dialogs/tests/memory/dialogStateManager.test.js @@ -114,8 +114,8 @@ describe('Dialog State Manager', function () { const config = this.dc.state.configuration; assert( config.memoryScopes.find( - (scope) => scope instanceof ConversationMemoryScope && scope.name === 'conversation' - ) + (scope) => scope instanceof ConversationMemoryScope && scope.name === 'conversation', + ), ); assert(config.memoryScopes.find((scope) => scope instanceof UserMemoryScope && scope.name === 'user')); }); @@ -142,7 +142,7 @@ describe('Dialog State Manager', function () { it(`read & write values to ${scope} memory scope`, function () { this.dc.state.setValue(`${scope}.foo`, 'bar'); assert.strictEqual(this.dc.state.getValue(`${scope}.foo`), 'bar'); - }) + }), ); [ @@ -154,7 +154,7 @@ describe('Dialog State Manager', function () { this.dc.state.setValue(`${short}foo`, value); assertion(this.dc.state.getValue(`${long}.foo`), value); assertion(this.dc.state.getValue(`${short}foo`), value); - }) + }), ); it('read entities using @ alias.', function () { @@ -224,7 +224,7 @@ describe('Dialog State Manager', function () { it('support passing a function to getValue() for the default.', function () { assert.strictEqual( this.dc.state.getValue('', () => 'default'), - 'default' + 'default', ); }); diff --git a/libraries/botbuilder-dialogs/tests/memory/memoryScopes.test.js b/libraries/botbuilder-dialogs/tests/memory/memoryScopes.test.js index bdfd87dc01..6dd8598ef9 100644 --- a/libraries/botbuilder-dialogs/tests/memory/memoryScopes.test.js +++ b/libraries/botbuilder-dialogs/tests/memory/memoryScopes.test.js @@ -223,7 +223,7 @@ describe('Memory Scopes', function () { it('returns parent containers state for children', async function () { const { dc, scope } = await initialize( - new TestContainer('container', new TestDialog('child', 'test message')) + new TestContainer('container', new TestDialog('child', 'test message')), ); assert(dc.child); @@ -238,7 +238,7 @@ describe('Memory Scopes', function () { it('overwrites parents memory', async function () { const { dc, scope } = await initialize( - new TestContainer('container', new TestDialog('child', 'test message')) + new TestContainer('container', new TestDialog('child', 'test message')), ); assert(dc.child); @@ -334,7 +334,7 @@ describe('Memory Scopes', function () { }, }, BlobsStorage: {}, - } + }, ); }); @@ -365,7 +365,7 @@ describe('Memory Scopes', function () { 'to_be_overridden', 'MicrosoftAppPassword', 'runtimeSettings', - 'BlobsStorage' + 'BlobsStorage', ), { array: ['one', 'two'], @@ -381,7 +381,7 @@ describe('Memory Scopes', function () { }, }, BlobsStorage: {}, - } + }, ); }); diff --git a/libraries/botbuilder-dialogs/tests/numberPrompt.test.js b/libraries/botbuilder-dialogs/tests/numberPrompt.test.js index c4f93ae4d6..f7518c545d 100644 --- a/libraries/botbuilder-dialogs/tests/numberPrompt.test.js +++ b/libraries/botbuilder-dialogs/tests/numberPrompt.test.js @@ -34,7 +34,7 @@ describe('NumberPrompt', function () { it('should call NumberPrompt using dc.prompt().', async function () { const adapter = createAdapter( (dialogContext) => dialogContext.prompt('prompt', 'Please send a number.'), - (turnContext, result) => turnContext.sendActivity(result.toString()) + (turnContext, result) => turnContext.sendActivity(result.toString()), ); await adapter.send('Hello').assertReply('Please send a number.').send('35').assertReply('35').startTest(); @@ -48,7 +48,7 @@ describe('NumberPrompt', function () { assert(prompt); const value = prompt.recognized.value; return value !== undefined && value >= 1 && value <= 100; - } + }, ); await adapter @@ -73,7 +73,7 @@ describe('NumberPrompt', function () { assert(prompt); const value = prompt.recognized.value; return value !== undefined && value >= 1 && value <= 100; - } + }, ); await adapter @@ -102,7 +102,7 @@ describe('NumberPrompt', function () { await prompt.context.sendActivity('out of range'); } return valid; - } + }, ); await adapter @@ -123,7 +123,7 @@ describe('NumberPrompt', function () { assert(prompt); const value = prompt.recognized.value; return value !== undefined && value >= 1 && value <= 100; - } + }, ); await adapter.send('Hello').send('0').send('25').assertReply('25').startTest(); @@ -137,7 +137,7 @@ describe('NumberPrompt', function () { (prompt) => { assert(prompt); return prompt.recognized.value === 0; - } + }, ); await adapter @@ -166,7 +166,7 @@ describe('NumberPrompt', function () { } return true; - } + }, ); await adapter @@ -201,7 +201,7 @@ describe('NumberPrompt', function () { return turnContext.sendActivity(reply); }, undefined, - 'es-es' + 'es-es', ); await adapter.send('Hello').assertReply('Please send a number.').send('3,14').startTest(); @@ -215,7 +215,7 @@ describe('NumberPrompt', function () { return turnContext.sendActivity(reply); }, undefined, - 'en-us' + 'en-us', ); await adapter @@ -231,7 +231,7 @@ describe('NumberPrompt', function () { (turnContext, reply) => { assert.strictEqual(reply, 1500.25); return turnContext.sendActivity(reply); - } + }, ); await adapter.send('Hello').assertReply('Please send a number.').send('1,500.25').startTest(); @@ -243,7 +243,7 @@ describe('NumberPrompt', function () { (turnContext, reply) => { assert.strictEqual(reply, 3.14); return turnContext.sendActivity(reply); - } + }, ); await adapter diff --git a/libraries/botbuilder-dialogs/tests/oauthPrompt.test.js b/libraries/botbuilder-dialogs/tests/oauthPrompt.test.js index e7a762652e..0d5bfccefb 100644 --- a/libraries/botbuilder-dialogs/tests/oauthPrompt.test.js +++ b/libraries/botbuilder-dialogs/tests/oauthPrompt.test.js @@ -60,7 +60,7 @@ describe('OAuthPrompt', function () { connectionName, title: 'Login', timeout: 300000, - }) + }), ); await adapter @@ -124,7 +124,7 @@ describe('OAuthPrompt', function () { connectionName, title: 'Login', timeout: 300000, - }) + }), ); await adapter @@ -207,8 +207,8 @@ describe('OAuthPrompt', function () { } return false; - } - ) + }, + ), ); // Initialize TestAdapter. @@ -240,7 +240,7 @@ describe('OAuthPrompt', function () { activity.channelId, activity.recipient.id, exchangeToken, - token + token, ); }) .send('invalid text message here') @@ -274,8 +274,8 @@ describe('OAuthPrompt', function () { } prompt.context.sendActivity(`attemptCount ${prompt.attemptCount}`); return false; - } - ) + }, + ), ); // Initialize TestAdapter. @@ -315,7 +315,7 @@ describe('OAuthPrompt', function () { adapter.signOutUser( new TurnContext(adapter, { channelId: activity.channelId, from: activity.recipient }), - connectionName + connectionName, ); }) .send('Another!') @@ -368,7 +368,7 @@ describe('OAuthPrompt', function () { connectionName, title: 'Login', timeout: 300000, - }) + }), ); const streamingActivity = { @@ -465,7 +465,7 @@ describe('OAuthPrompt', function () { await assert.rejects( OAuthPrompt.sendOAuthCard({}, context), - new Error('OAuth prompt is not supported by the current adapter') + new Error('OAuth prompt is not supported by the current adapter'), ); }); @@ -541,7 +541,7 @@ describe('OAuthPrompt', function () { { type: 'azp', value: uuid() }, { type: 'ver', value: '2.0' }, { type: 'aud', value: uuid() }, - ]) + ]), ); // Override sendActivity context.sendActivity = async function (activity) { @@ -623,7 +623,7 @@ describe('OAuthPrompt', function () { { type: 'azp', value: uuid() }, { type: 'ver', value: '2.0' }, { type: 'aud', value: AuthenticationConstants.ToBotFromChannelTokenIssuer }, - ]) + ]), ); // Override sendActivity context.sendActivity = async function (activity) { @@ -668,7 +668,7 @@ describe('OAuthPrompt', function () { name: tokenResponseEventName, conversation: { id: 'conversationId' }, channelId: Channels.Test, - }) + }), ); function setActiveDialog(dc, dialog) { // Create stack if not already there. @@ -706,7 +706,7 @@ describe('OAuthPrompt', function () { undefined, undefined, credsFactory, - { requiredEndorsements: [] } + { requiredEndorsements: [] }, ); const adapter = new TestCloudAdapter(botFrameworkAuthentication); const oAuthPrompt = new OAuthPrompt('OAuthPrompt'); @@ -766,7 +766,7 @@ describe('OAuthPrompt', function () { undefined, undefined, credsFactory, - { requiredEndorsements: [] } + { requiredEndorsements: [] }, ); const adapter = new TestCloudAdapter(botFrameworkAuthentication); const oAuthPrompt = new OAuthPrompt('OAuthPrompt'); @@ -829,7 +829,7 @@ describe('OAuthPrompt', function () { title: 'Sign in', timeout: 30000, text: 'Please sign in', - }) + }), ); const adapter = new TestAdapter(async (turnContext) => { @@ -866,7 +866,7 @@ describe('OAuthPrompt', function () { title: 'Sign in', timeout: 30000, text: 'Please sign in', - }) + }), ); const adapter = new SignInTestAdapter(async (turnContext) => { @@ -906,7 +906,7 @@ describe('OAuthPrompt', function () { turnContext.activity.channelId, userId, exchangeToken, - token + token, ); // Positive case: Token @@ -968,7 +968,7 @@ describe('OAuthPrompt', function () { title: 'Sign in', timeout: 30000, text: 'Please sign in', - }) + }), ); }); @@ -986,7 +986,7 @@ describe('OAuthPrompt', function () { activity.channelId, activity.recipient.id, exchangeToken, - token + token, ); }) .send({ @@ -1194,7 +1194,7 @@ async function testTimeout( oauthPromptActivity, shouldSucceed = true, tokenResponse = 'Failed', - noTokenResponse = 'Ended' + noTokenResponse = 'Ended', ) { const connectionName = 'myConnection'; const token = 'abc123'; @@ -1223,8 +1223,8 @@ async function testTimeout( assert(!shouldSucceed, 'recognition failed during testTimeout'); return false; - } - ) + }, + ), ); const adapter = new TestAdapter(async (turnContext) => { @@ -1266,7 +1266,7 @@ async function testTimeout( activity.channelId, activity.recipient.id, exchangeToken, - token + token, ); }) .send(oauthPromptActivity) diff --git a/libraries/botbuilder-dialogs/tests/skillDialog.test.js b/libraries/botbuilder-dialogs/tests/skillDialog.test.js index 55c9e1efde..bf05b063a5 100644 --- a/libraries/botbuilder-dialogs/tests/skillDialog.test.js +++ b/libraries/botbuilder-dialogs/tests/skillDialog.test.js @@ -31,7 +31,7 @@ describe('SkillDialog', function () { BOTBUILDER_TESTING = require('../../botbuilder-testing'); } catch (_err) { console.warn( - '=====\nUnable to load botbuilder or botbuilder-testing module. "beginDialog should call skill" tests will not be run.\n' + '=====\nUnable to load botbuilder or botbuilder-testing module. "beginDialog should call skill" tests will not be run.\n', ); } @@ -67,7 +67,7 @@ describe('SkillDialog', function () { conversationState, skillClient, undefined, - useCreateSkillConversationId + useCreateSkillConversationId, ); let createSkillConversationIdSpy; @@ -86,7 +86,7 @@ describe('SkillDialog', function () { dialog, { activity: activityToSend }, undefined, - conversationState + conversationState, ); assert.strictEqual(dialogOptions.conversationIdFactory.createCount, 0); @@ -123,12 +123,12 @@ describe('SkillDialog', function () { assert.strictEqual( await dialogOptions.conversationIdFactory.getSkillConversationReference('Convo1'), undefined, - 'no test should use TestAdapter ConversationId as SkillConversationId.' + 'no test should use TestAdapter ConversationId as SkillConversationId.', ); assert.strictEqual( await dialogOptions.conversationIdFactory.getSkillConversationReference(undefined), undefined, - 'no test should use TestAdapter ConversationId as SkillConversationId.' + 'no test should use TestAdapter ConversationId as SkillConversationId.', ); } @@ -153,7 +153,7 @@ describe('SkillDialog', function () { return; }, undefined, - expectedReplies + expectedReplies, ); const conversationState = new ConversationState(new MemoryStorage()); const dialogOptions = createSkillDialogOptions(conversationState, skillClient, undefined, false); @@ -217,7 +217,7 @@ describe('SkillDialog', function () { dialog, { activity: activityToSend }, undefined, - conversationState + conversationState, ); assert.strictEqual(dialogOptions.conversationIdFactory.createCount, 0); @@ -296,10 +296,6 @@ describe('SkillDialog', function () { const validatedActivity = validatedArgs.activity; assert.strictEqual(validatedActivity.type, ActivityTypes.Message); assert.strictEqual(validatedActivity.text, 'Hello SkillDialog!'); - }); - - it('should fail if options is falsy', function () { - const dialog = new SkillDialog({}, 'SkillDialog'); assert.throws(() => dialog.validateBeginDialogArgs(), new TypeError('Missing options parameter')); }); @@ -307,7 +303,7 @@ describe('SkillDialog', function () { const dialog = new SkillDialog({}, 'SkillDialog'); assert.throws( () => dialog.validateBeginDialogArgs({}), - new TypeError('"activity" is undefined or null in options.') + new TypeError('"activity" is undefined or null in options.'), ); }); }); @@ -330,7 +326,7 @@ describe('SkillDialog', function () { skill: {}, skillHostEndpoint: 'http://localhost:3980/api/messages', }, - 'SkillDialog' + 'SkillDialog', ); dialog.state = {}; @@ -368,7 +364,7 @@ describe('SkillDialog', function () { }, }, }, - 'SkillDialog' + 'SkillDialog', ); dialog.state = {}; @@ -421,14 +417,14 @@ describe('SkillDialog', function () { dialogUnderTest, beginSkillDialogOptions, [new AutoSaveStateMiddleware(conversationState)], - conversationState + conversationState, ); client._testAdapter.addExchangeableToken( connectionName, Channels.Test, 'user1', 'https://test', - 'https://test1' + 'https://test1', ); const finalActivity = await client.sendActivity('irrelevant'); @@ -456,14 +452,14 @@ describe('SkillDialog', function () { dialogUnderTest, beginSkillDialogOptions, [new AutoSaveStateMiddleware(conversationState)], - conversationState + conversationState, ); client._testAdapter.addExchangeableToken( connectionName, Channels.Test, 'user1', 'https://test', - 'https://test1' + 'https://test1', ); const finalActivity = await client.sendActivity('irrelevant'); @@ -491,7 +487,7 @@ describe('SkillDialog', function () { dialogUnderTest, beginSkillDialogOptions, [new AutoSaveStateMiddleware(conversationState)], - conversationState + conversationState, ); // dont add exchangeable token to test adapter const finalActivity = await client.sendActivity('irrelevant'); @@ -521,7 +517,7 @@ describe('SkillDialog', function () { dialogUnderTest, beginSkillDialogOptions, [new AutoSaveStateMiddleware(conversationState)], - conversationState + conversationState, ); client._testAdapter.addExchangeableToken(connectionName, Channels.Test, 'user1', 'https://test'); @@ -553,14 +549,14 @@ describe('SkillDialog', function () { dialogUnderTest, beginSkillDialogOptions, [new AutoSaveStateMiddleware(conversationState)], - conversationState + conversationState, ); client._testAdapter.addExchangeableToken( connectionName, Channels.Test, 'user1', 'https://test', - 'https://test1' + 'https://test1', ); const finalActivity = await client.sendActivity('irrelevant'); @@ -586,7 +582,7 @@ function createSkillClientAndStub(captureAction, returnStatusCode = StatusCodes. if (captureAction && typeof captureAction !== 'function') { throw new TypeError( - `Failed test arrangement - createSkillClientAndStub() received ${typeof captureAction} instead of undefined or a function.` + `Failed test arrangement - createSkillClientAndStub() received ${typeof captureAction} instead of undefined or a function.`, ); } diff --git a/libraries/botbuilder-dialogs/tests/textPrompt.test.js b/libraries/botbuilder-dialogs/tests/textPrompt.test.js index 8eae6f292e..29a7513ae4 100644 --- a/libraries/botbuilder-dialogs/tests/textPrompt.test.js +++ b/libraries/botbuilder-dialogs/tests/textPrompt.test.js @@ -56,7 +56,7 @@ describe('TextPrompt', function () { new TextPrompt('prompt', async (prompt) => { assert(prompt); return prompt.recognized.value.length >= 3; - }) + }), ); await adapter @@ -157,7 +157,7 @@ describe('TextPrompt', function () { await prompt.context.sendActivity('too short'); } return valid; - }) + }), ); await adapter diff --git a/libraries/botbuilder-dialogs/tests/waterfallDialog.test.js b/libraries/botbuilder-dialogs/tests/waterfallDialog.test.js index f9b0f31e54..ff4fbb479b 100644 --- a/libraries/botbuilder-dialogs/tests/waterfallDialog.test.js +++ b/libraries/botbuilder-dialogs/tests/waterfallDialog.test.js @@ -66,7 +66,7 @@ describe('WaterfallDialog', function () { assert(step); return await step.endDialog('ending WaterfallDialog.'); }, - ]) + ]), ); await adapter @@ -179,7 +179,7 @@ describe('WaterfallDialog', function () { assert(step); return await step.endDialog(step.result); }, - ]) + ]), ); await adapter @@ -217,7 +217,7 @@ describe('WaterfallDialog', function () { assert.strictEqual( step.options.test, 'test', - `step.options.test "${step.options.test}", was not expected value of "test".` + `step.options.test "${step.options.test}", was not expected value of "test".`, ); await step.context.sendActivity('bot responding.'); return Dialog.EndOfTurn; @@ -226,7 +226,7 @@ describe('WaterfallDialog', function () { assert(step); return await step.endDialog('ending WaterfallDialog.'); }, - ]) + ]), ); await adapter @@ -265,7 +265,7 @@ describe('WaterfallDialog', function () { assert.strictEqual( step.options.test, 'test1', - `step.options.test "${step.options.test}", was not expected value of "test1".` + `step.options.test "${step.options.test}", was not expected value of "test1".`, ); step.options.test = 'test2'; await step.context.sendActivity('bot responding.'); @@ -277,7 +277,7 @@ describe('WaterfallDialog', function () { assert.strictEqual( step.options.test, 'test2', - `step.options.test "${step.options.test}", was not expected value of "test2".` + `step.options.test "${step.options.test}", was not expected value of "test2".`, ); step.options.test = 'test3'; await step.context.sendActivity('bot responding again.'); @@ -288,11 +288,11 @@ describe('WaterfallDialog', function () { assert.strictEqual( step.options.test, 'test3', - `step.options.test "${step.options.test}", was not expected value of "test3".` + `step.options.test "${step.options.test}", was not expected value of "test3".`, ); return await step.endDialog('ending WaterfallDialog.'); }, - ]) + ]), ); await adapter @@ -340,7 +340,7 @@ describe('WaterfallDialog', function () { assert.strictEqual( step.values.test, 'test1', - `step.values.test ["${step.values.test}"] was not expected value "test1".` + `step.values.test ["${step.values.test}"] was not expected value "test1".`, ); step.values.test2 = 'test2'; await step.context.sendActivity('bot responding again.'); @@ -352,16 +352,16 @@ describe('WaterfallDialog', function () { assert.strictEqual( step.values.test, 'test1', - `step.values.test ["${step.values.test}"] was not expected value "test1".` + `step.values.test ["${step.values.test}"] was not expected value "test1".`, ); assert.strictEqual( step.values.test2, 'test2', - `step.values.test2 ["${step.values.test2}"] was not expected value "test2".` + `step.values.test2 ["${step.values.test2}"] was not expected value "test2".`, ); return await step.endDialog('ending WaterfallDialog.'); }, - ]) + ]), ); await adapter @@ -409,16 +409,16 @@ describe('WaterfallDialog', function () { assert.strictEqual( step.values.test, 'test1', - `step.values.test ["${step.values.test}"] was not expected value "test1".` + `step.values.test ["${step.values.test}"] was not expected value "test1".`, ); assert.strictEqual( step.values.test_b, undefined, - "step.values.test_b should not be available in WaterfallDialog('a')." + "step.values.test_b should not be available in WaterfallDialog('a').", ); return await step.endDialog('ending WaterfallDialog.'); }, - ]) + ]), ); dialogs.add( @@ -428,11 +428,11 @@ describe('WaterfallDialog', function () { assert.equal( typeof step.values, 'object', - 'new step.values for second WaterfallDialog should be an object.' + 'new step.values for second WaterfallDialog should be an object.', ); assert( !step.values.test, - "new WaterfallDialog's step.values shouldn't have values from parent dialog's step.values." + "new WaterfallDialog's step.values shouldn't have values from parent dialog's step.values.", ); // Add a new value to this WaterfallDialog's step.values. @@ -445,21 +445,21 @@ describe('WaterfallDialog', function () { assert.equal( typeof step.values, 'object', - 'step.values for second WaterfallDialog should be an object.' + 'step.values for second WaterfallDialog should be an object.', ); assert( !step.values.test, - "new WaterfallDialog's step.values shouldn't have values from parent dialog's step.values." + "new WaterfallDialog's step.values shouldn't have values from parent dialog's step.values.", ); assert.strictEqual( step.values.test_b, 'test_b', - "step.values.test_b should not be available in WaterfallDialog 'a'." + "step.values.test_b should not be available in WaterfallDialog 'a'.", ); return await step.endDialog(); }, - ]) + ]), ); await adapter @@ -498,7 +498,7 @@ describe('WaterfallDialog', function () { assert.strictEqual( step.options.test_a, 'test_a', - `step.options.test_a "${step.options.test_a}", was not expected value of "test_a".` + `step.options.test_a "${step.options.test_a}", was not expected value of "test_a".`, ); await step.context.sendActivity('bot responding.'); return await step.beginDialog('b'); @@ -509,11 +509,11 @@ describe('WaterfallDialog', function () { assert.strictEqual( step.options.test_a, 'test_a', - `step.options.test_a "${step.options.test_a}", was not expected value of "test_a".` + `step.options.test_a "${step.options.test_a}", was not expected value of "test_a".`, ); return await step.endDialog('ending WaterfallDialog.'); }, - ]) + ]), ); dialogs.add( @@ -524,7 +524,7 @@ describe('WaterfallDialog', function () { assert.strictEqual( step.options.test_a, undefined, - `step.options.test_a "${step.options.test_a}", was not expected value of "undefined".` + `step.options.test_a "${step.options.test_a}", was not expected value of "undefined".`, ); step.options.test_b = 'test_b'; return Dialog.EndOfTurn; @@ -535,11 +535,11 @@ describe('WaterfallDialog', function () { assert.strictEqual( step.options.test_b, 'test_b', - `step.options.test_b "${step.options.test_b}", was not expected value of "test_b".` + `step.options.test_b "${step.options.test_b}", was not expected value of "test_b".`, ); return await step.endDialog(); }, - ]) + ]), ); await adapter @@ -581,7 +581,7 @@ describe('WaterfallDialog', function () { assert(step, 'step not found.'); return Dialog.EndOfTurn; }, - ]) + ]), ); await adapter @@ -625,7 +625,7 @@ describe('WaterfallDialog', function () { assert( err.message === "WaterfallStepContext.next(): method already called for dialog and step 'a[0]'.", - err.message + err.message, ); } return Dialog.EndOfTurn; @@ -636,7 +636,7 @@ describe('WaterfallDialog', function () { async function (step) { assert(step, 'step not found.'); }, - ]) + ]), ); await adapter.send(beginMessage).assertReply('bot responding.').startTest(); @@ -672,11 +672,11 @@ describe('WaterfallDialog', function () { assert(step, 'step not found.'); assert( step.context.activity.text === 'continue.', - `expected "continue." not ${step.context.activity.text}` + `expected "continue." not ${step.context.activity.text}`, ); return await step.endDialog('done.'); }, - ]) + ]), ); await adapter @@ -697,7 +697,7 @@ describe('WaterfallDialog', function () { trackEvent(telemetry) { assert( telemetry.properties.StepName == dialog.steps[index].name, - `telemetry contains incorrect step name: "${telemetry.properties.StepName}"` + `telemetry contains incorrect step name: "${telemetry.properties.StepName}"`, ); trackEventCalled = true; }, @@ -711,7 +711,7 @@ describe('WaterfallDialog', function () { values: { instanceId: '(guid)' }, }, }, - DialogReason.cancelCalled + DialogReason.cancelCalled, ); assert(trackEventCalled, 'trackEvent was never called.'); }); From 7cafc93084efe797211149d372f80edbea2c1dda Mon Sep 17 00:00:00 2001 From: Jhonatan Sandoval Velasco <122501764+JhontSouth@users.noreply.github.com> Date: Mon, 6 Jan 2025 10:06:31 -0500 Subject: [PATCH 16/22] fix eslint issues in adaptive expressions (#4833) --- .../adaptive-expressions/eslint.config.cjs | 11 +--- libraries/adaptive-expressions/package.json | 1 - .../src/builtinFunctions/add.ts | 2 +- .../src/builtinFunctions/addDays.ts | 13 ++-- .../src/builtinFunctions/addHours.ts | 13 ++-- .../src/builtinFunctions/addMinutes.ts | 13 ++-- .../src/builtinFunctions/addOrdinal.ts | 2 +- .../src/builtinFunctions/addSeconds.ts | 13 ++-- .../src/builtinFunctions/addToTime.ts | 4 +- .../src/builtinFunctions/average.ts | 2 +- .../src/builtinFunctions/base64ToBinary.ts | 2 +- .../src/builtinFunctions/base64ToString.ts | 2 +- .../src/builtinFunctions/binary.ts | 2 +- .../builtinFunctions/comparisonEvaluator.ts | 4 +- .../src/builtinFunctions/concat.ts | 2 +- .../src/builtinFunctions/convertFromUTC.ts | 4 +- .../src/builtinFunctions/convertToUTC.ts | 2 +- .../src/builtinFunctions/countWord.ts | 2 +- .../src/builtinFunctions/dataUri.ts | 2 +- .../src/builtinFunctions/dataUriToBinary.ts | 4 +- .../src/builtinFunctions/dataUriToString.ts | 4 +- .../src/builtinFunctions/endsWith.ts | 4 +- .../src/builtinFunctions/eol.ts | 3 +- .../src/builtinFunctions/equal.ts | 2 +- .../src/builtinFunctions/foreach.ts | 2 +- .../src/builtinFunctions/formatNumber.ts | 58 +++++++++-------- .../src/builtinFunctions/formatTicks.ts | 60 +++++++++--------- .../src/builtinFunctions/getFutureTime.ts | 2 +- .../src/builtinFunctions/getNextViableDate.ts | 4 +- .../src/builtinFunctions/getNextViableTime.ts | 6 +- .../src/builtinFunctions/getPastTime.ts | 2 +- .../builtinFunctions/getPreviousViableDate.ts | 4 +- .../builtinFunctions/getPreviousViableTime.ts | 6 +- .../src/builtinFunctions/getProperty.ts | 2 +- .../src/builtinFunctions/getTimeOfDay.ts | 2 +- .../builtinFunctions/greaterThanOrEqual.ts | 2 +- .../src/builtinFunctions/index.ts | 1 - .../src/builtinFunctions/indexOf.ts | 2 +- .../src/builtinFunctions/indicesAndValues.ts | 3 +- .../src/builtinFunctions/int.ts | 34 +++++----- .../src/builtinFunctions/isDateTime.ts | 2 +- .../src/builtinFunctions/isFloat.ts | 2 +- .../src/builtinFunctions/isInteger.ts | 2 +- .../src/builtinFunctions/jPath.ts | 2 - .../src/builtinFunctions/length.ts | 2 +- .../src/builtinFunctions/lessThanOrEqual.ts | 2 +- .../src/builtinFunctions/merge.ts | 26 ++++---- .../multivariateNumericEvaluator.ts | 2 +- .../src/builtinFunctions/notEqual.ts | 2 +- .../src/builtinFunctions/replaceIgnoreCase.ts | 4 +- .../src/builtinFunctions/select.ts | 2 +- .../src/builtinFunctions/sortByDescending.ts | 2 +- .../src/builtinFunctions/split.ts | 4 +- .../src/builtinFunctions/startsWith.ts | 4 +- .../src/builtinFunctions/string.ts | 62 +++++++++---------- .../src/builtinFunctions/stringOrValue.ts | 2 +- .../stringTransformEvaluator.ts | 2 +- .../src/builtinFunctions/subtractFromTime.ts | 4 +- .../src/builtinFunctions/sum.ts | 2 +- .../src/builtinFunctions/ticksToHours.ts | 2 +- .../src/builtinFunctions/ticksToMinutes.ts | 2 +- .../timeTransformEvaluator.ts | 2 +- .../src/builtinFunctions/titleCase.ts | 2 +- .../src/builtinFunctions/uriComponent.ts | 2 +- .../builtinFunctions/uriComponentToString.ts | 2 +- .../src/builtinFunctions/uriPathAndQuery.ts | 2 +- .../src/builtinFunctions/utcNow.ts | 20 +++--- .../src/builtinFunctions/xml.ts | 2 +- .../src/builtinFunctions/xpath.ts | 7 ++- .../adaptive-expressions/src/constant.ts | 21 +++---- .../converters/objectExpressionConverter.ts | 1 - .../adaptive-expressions/src/expression.ts | 8 +-- .../src/expressionEvaluator.ts | 4 +- .../src/expressionFunctions.ts | 6 +- .../expressionProperty.ts | 2 - .../src/expressionProperties/intExpression.ts | 1 - .../adaptive-expressions/src/functionTable.ts | 8 +-- .../src/functionUtils.internal.ts | 12 ++-- .../adaptive-expressions/src/functionUtils.ts | 16 ++--- .../src/memory/simpleObjectMemory.ts | 2 +- .../src/parser/expressionParser.ts | 12 ++-- .../src/parser/parseErrorListener.ts | 2 +- .../src/regexErrorListener.ts | 2 +- .../src/triggerTrees/clause.ts | 4 +- .../src/triggerTrees/node.ts | 2 +- .../src/triggerTrees/quantifier.ts | 6 +- .../src/triggerTrees/trigger.ts | 16 ++--- .../tests/badExpression.test.js | 2 +- .../tests/expressionParser.test.js | 52 ++-------------- .../tests/triggerTree.test.js | 20 +++--- 90 files changed, 299 insertions(+), 376 deletions(-) diff --git a/libraries/adaptive-expressions/eslint.config.cjs b/libraries/adaptive-expressions/eslint.config.cjs index 9035d1b1d7..d75641f9bf 100644 --- a/libraries/adaptive-expressions/eslint.config.cjs +++ b/libraries/adaptive-expressions/eslint.config.cjs @@ -1,13 +1,8 @@ -const onlyWarn = require("eslint-plugin-only-warn"); -const sharedConfig = require("../../eslint.config.cjs") +const sharedConfig = require('../../eslint.config.cjs'); module.exports = [ ...sharedConfig, { - ignores: ["**/generated/*", "**/expressionProperty.test.js"], + ignores: ['**/generated/*', '**/expressionProperty.test.js'], }, - { - plugins: { - "only-warn": onlyWarn, - }, - }]; +]; diff --git a/libraries/adaptive-expressions/package.json b/libraries/adaptive-expressions/package.json index 67ab331696..c709d5d30b 100644 --- a/libraries/adaptive-expressions/package.json +++ b/libraries/adaptive-expressions/package.json @@ -38,7 +38,6 @@ "btoa-lite": "^1.0.0", "d3-format": "^2.0.0", "dayjs": "^1.11.13", - "eslint-plugin-only-warn": "^1.1.0", "jspath": "^0.4.0", "lodash": "^4.17.21", "lru-cache": "^5.1.1", diff --git a/libraries/adaptive-expressions/src/builtinFunctions/add.ts b/libraries/adaptive-expressions/src/builtinFunctions/add.ts index 1300f24d9b..93ff53f766 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/add.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/add.ts @@ -62,7 +62,7 @@ export class Add extends ExpressionEvaluator { expression, 2, Number.MAX_SAFE_INTEGER, - ReturnType.String | ReturnType.Number + ReturnType.String | ReturnType.Number, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/addDays.ts b/libraries/adaptive-expressions/src/builtinFunctions/addDays.ts index f6ac186bd9..d323fae162 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/addDays.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/addDays.ts @@ -17,13 +17,10 @@ export class AddDays extends TimeTransformEvaluator { * Initializes a new instance of the [AddDays](xref:adaptive-expressions.AddDays) class. */ constructor() { - super( - ExpressionType.AddDays, - (ts: Date, num: number): Date => { - const newDate = new Date(ts); - newDate.setDate(ts.getDate() + num); - return newDate; - } - ); + super(ExpressionType.AddDays, (ts: Date, num: number): Date => { + const newDate = new Date(ts); + newDate.setDate(ts.getDate() + num); + return newDate; + }); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/addHours.ts b/libraries/adaptive-expressions/src/builtinFunctions/addHours.ts index 75a040596c..c4a11ddb9a 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/addHours.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/addHours.ts @@ -17,13 +17,10 @@ export class AddHours extends TimeTransformEvaluator { * Initializes a new instance of the [AddHours](xref:adaptive-expressions.AddHours) class. */ constructor() { - super( - ExpressionType.AddHours, - (ts: Date, num: number): Date => { - const newDate = new Date(ts); - newDate.setHours(ts.getHours() + num); - return newDate; - } - ); + super(ExpressionType.AddHours, (ts: Date, num: number): Date => { + const newDate = new Date(ts); + newDate.setHours(ts.getHours() + num); + return newDate; + }); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/addMinutes.ts b/libraries/adaptive-expressions/src/builtinFunctions/addMinutes.ts index ae9f709ce1..1fcfdc0028 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/addMinutes.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/addMinutes.ts @@ -17,13 +17,10 @@ export class AddMinutes extends TimeTransformEvaluator { * Initializes a new instance of the [AddMinutes](xref:adaptive-expressions.AddMinutes) class. */ constructor() { - super( - ExpressionType.AddMinutes, - (ts: Date, num: number): Date => { - const newDate = new Date(ts); - newDate.setMinutes(ts.getMinutes() + num); - return newDate; - } - ); + super(ExpressionType.AddMinutes, (ts: Date, num: number): Date => { + const newDate = new Date(ts); + newDate.setMinutes(ts.getMinutes() + num); + return newDate; + }); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/addOrdinal.ts b/libraries/adaptive-expressions/src/builtinFunctions/addOrdinal.ts index 7166e78694..d4875cacf3 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/addOrdinal.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/addOrdinal.ts @@ -29,7 +29,7 @@ export class AddOrdinal extends ExpressionEvaluator { private static evaluator(): EvaluateExpressionDelegate { return FunctionUtils.apply( (args: any[]): string => AddOrdinal.evalAddOrdinal(args[0]), - FunctionUtils.verifyInteger + FunctionUtils.verifyInteger, ); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/addSeconds.ts b/libraries/adaptive-expressions/src/builtinFunctions/addSeconds.ts index 60f59ec287..9f42779b7c 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/addSeconds.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/addSeconds.ts @@ -17,13 +17,10 @@ export class AddSeconds extends TimeTransformEvaluator { * Initializes a new instance of the [AddSeconds](xref:adaptive-expressions.AddSeconds) class. */ constructor() { - super( - ExpressionType.AddSeconds, - (ts: Date, num: number): Date => { - const newDate = new Date(ts); - newDate.setSeconds(ts.getSeconds() + num); - return newDate; - } - ); + super(ExpressionType.AddSeconds, (ts: Date, num: number): Date => { + const newDate = new Date(ts); + newDate.setSeconds(ts.getSeconds() + num); + return newDate; + }); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/addToTime.ts b/libraries/adaptive-expressions/src/builtinFunctions/addToTime.ts index 9ca6b7a51b..ebca5e9038 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/addToTime.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/addToTime.ts @@ -60,7 +60,7 @@ export class AddToTime extends ExpressionEvaluator { interval: number, timeUnit: string, format?: string, - locale?: string + locale?: string, ): ValueWithError { let result: string; const error = InternalFunctionUtils.verifyISOTimestamp(timeStamp); @@ -81,7 +81,7 @@ export class AddToTime extends ExpressionEvaluator { [ReturnType.String, ReturnType.String], ReturnType.String, ReturnType.Number, - ReturnType.String + ReturnType.String, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/average.ts b/libraries/adaptive-expressions/src/builtinFunctions/average.ts index 9902857420..0d89b25c85 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/average.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/average.ts @@ -28,7 +28,7 @@ export class Average extends ExpressionEvaluator { private static evaluator(): EvaluateExpressionDelegate { return FunctionUtils.apply( (args: any[]): number => args[0].reduce((x: number, y: number): number => x + y) / args[0].length, - FunctionUtils.verifyNumericList + FunctionUtils.verifyNumericList, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/base64ToBinary.ts b/libraries/adaptive-expressions/src/builtinFunctions/base64ToBinary.ts index 88a8b8786e..568ba31c50 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/base64ToBinary.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/base64ToBinary.ts @@ -26,7 +26,7 @@ export class Base64ToBinary extends ExpressionEvaluator { ExpressionType.Base64ToBinary, Base64ToBinary.evaluator(), ReturnType.Object, - FunctionUtils.validateUnary + FunctionUtils.validateUnary, ); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/base64ToString.ts b/libraries/adaptive-expressions/src/builtinFunctions/base64ToString.ts index c4d143680d..cd72baf0dc 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/base64ToString.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/base64ToString.ts @@ -24,7 +24,7 @@ export class Base64ToString extends ExpressionEvaluator { ExpressionType.Base64ToString, Base64ToString.evaluator(), ReturnType.String, - FunctionUtils.validateUnary + FunctionUtils.validateUnary, ); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/binary.ts b/libraries/adaptive-expressions/src/builtinFunctions/binary.ts index fa091877e6..61065fdc14 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/binary.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/binary.ts @@ -29,7 +29,7 @@ export class Binary extends ExpressionEvaluator { private static evaluator(): EvaluateExpressionDelegate { return FunctionUtils.apply( (args: any[]): Uint8Array => InternalFunctionUtils.getTextEncoder().encode(args[0]), - FunctionUtils.verifyString + FunctionUtils.verifyString, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/comparisonEvaluator.ts b/libraries/adaptive-expressions/src/builtinFunctions/comparisonEvaluator.ts index c827c59896..686c9785b2 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/comparisonEvaluator.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/comparisonEvaluator.ts @@ -34,7 +34,7 @@ export class ComparisonEvaluator extends ExpressionEvaluator { type: string, func: (arg0: any[]) => boolean, validator: ValidateExpressionDelegate, - verify?: VerifyExpression + verify?: VerifyExpression, ) { super(type, ComparisonEvaluator.evaluator(func, verify), ReturnType.Boolean, validator); } @@ -52,7 +52,7 @@ export class ComparisonEvaluator extends ExpressionEvaluator { expression, state, newOptions, - verify + verify, ); let error = childrenError; if (!error) { diff --git a/libraries/adaptive-expressions/src/builtinFunctions/concat.ts b/libraries/adaptive-expressions/src/builtinFunctions/concat.ts index 09bc1110dc..1d698f7bc2 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/concat.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/concat.ts @@ -24,7 +24,7 @@ export class Concat extends ExpressionEvaluator { ExpressionType.Concat, Concat.evaluator(), ReturnType.String | ReturnType.Array, - FunctionUtils.validateAtLeastOne + FunctionUtils.validateAtLeastOne, ); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/convertFromUTC.ts b/libraries/adaptive-expressions/src/builtinFunctions/convertFromUTC.ts index eb640f819c..aa714ea5ab 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/convertFromUTC.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/convertFromUTC.ts @@ -60,7 +60,7 @@ export class ConvertFromUTC extends ExpressionEvaluator { timeStamp: string, destinationTimeZone: string, format?: string, - locale?: string + locale?: string, ): ValueWithError { let result: string; let error: string; @@ -89,7 +89,7 @@ export class ConvertFromUTC extends ExpressionEvaluator { expression, [ReturnType.String, ReturnType.String], ReturnType.String, - ReturnType.String + ReturnType.String, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/convertToUTC.ts b/libraries/adaptive-expressions/src/builtinFunctions/convertToUTC.ts index cfccf64474..f228f41eb5 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/convertToUTC.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/convertToUTC.ts @@ -69,7 +69,7 @@ export class ConvertToUTC extends ExpressionEvaluator { timeStamp: string, sourceTimezone: string, format?: string, - locale?: string + locale?: string, ): ValueWithError { let result: string; let error: string; diff --git a/libraries/adaptive-expressions/src/builtinFunctions/countWord.ts b/libraries/adaptive-expressions/src/builtinFunctions/countWord.ts index 35c0a20cc2..c8824bf6e4 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/countWord.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/countWord.ts @@ -29,7 +29,7 @@ export class CountWord extends ExpressionEvaluator { private static evaluator(): EvaluateExpressionDelegate { return FunctionUtils.apply( (args: any[]): number => InternalFunctionUtils.parseStringOrUndefined(args[0]).trim().split(/\s+/).length, - FunctionUtils.verifyStringOrNull + FunctionUtils.verifyStringOrNull, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/dataUri.ts b/libraries/adaptive-expressions/src/builtinFunctions/dataUri.ts index 435eb89477..a155da9838 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/dataUri.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/dataUri.ts @@ -29,7 +29,7 @@ export class DataUri extends ExpressionEvaluator { private static evaluator(): EvaluateExpressionDelegate { return FunctionUtils.apply( (args: any[]): string => 'data:text/plain;charset=utf-8;base64,'.concat(btoa(args[0])), - FunctionUtils.verifyString + FunctionUtils.verifyString, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/dataUriToBinary.ts b/libraries/adaptive-expressions/src/builtinFunctions/dataUriToBinary.ts index 3849d4e41f..8df2f936e1 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/dataUriToBinary.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/dataUriToBinary.ts @@ -24,7 +24,7 @@ export class DataUriToBinary extends ExpressionEvaluator { ExpressionType.DataUriToBinary, DataUriToBinary.evaluator(), ReturnType.Object, - FunctionUtils.validateUnary + FunctionUtils.validateUnary, ); } @@ -34,7 +34,7 @@ export class DataUriToBinary extends ExpressionEvaluator { private static evaluator(): EvaluateExpressionDelegate { return FunctionUtils.apply( (args: any[]): Uint8Array => InternalFunctionUtils.getTextEncoder().encode(args[0]), - FunctionUtils.verifyString + FunctionUtils.verifyString, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/dataUriToString.ts b/libraries/adaptive-expressions/src/builtinFunctions/dataUriToString.ts index 2539ff5858..aad93e8643 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/dataUriToString.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/dataUriToString.ts @@ -24,7 +24,7 @@ export class DataUriToString extends ExpressionEvaluator { ExpressionType.DataUriToString, DataUriToString.evaluator(), ReturnType.String, - FunctionUtils.validateUnary + FunctionUtils.validateUnary, ); } @@ -34,7 +34,7 @@ export class DataUriToString extends ExpressionEvaluator { private static evaluator(): EvaluateExpressionDelegate { return FunctionUtils.apply( (args: any[]): string => atob(args[0].slice(args[0].indexOf(',') + 1)), - FunctionUtils.verifyString + FunctionUtils.verifyString, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/endsWith.ts b/libraries/adaptive-expressions/src/builtinFunctions/endsWith.ts index 26ce295aea..2701d5c700 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/endsWith.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/endsWith.ts @@ -32,9 +32,9 @@ export class EndsWith extends ExpressionEvaluator { return FunctionUtils.apply( (args: any[]): boolean => InternalFunctionUtils.parseStringOrUndefined(args[0]).endsWith( - InternalFunctionUtils.parseStringOrUndefined(args[1]) + InternalFunctionUtils.parseStringOrUndefined(args[1]), ), - FunctionUtils.verifyStringOrNull + FunctionUtils.verifyStringOrNull, ); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/eol.ts b/libraries/adaptive-expressions/src/builtinFunctions/eol.ts index 56519d2e80..13f8a55f11 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/eol.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/eol.ts @@ -11,6 +11,7 @@ import { EvaluateExpressionDelegate, ExpressionEvaluator } from '../expressionEv import { ExpressionType } from '../expressionType'; import { FunctionUtils } from '../functionUtils'; import { ReturnType } from '../returnType'; +import os from 'os'; /** * Return the newline string according to the environment. @@ -39,8 +40,6 @@ export class EOL extends ExpressionEvaluator { } else if (typeof self !== 'undefined') { return self.navigator.platform.includes('Win') ? '\r\n' : '\n'; } else { - // eslint-disable-next-line @typescript-eslint/no-var-requires - const os = require('os'); return os.EOL; } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/equal.ts b/libraries/adaptive-expressions/src/builtinFunctions/equal.ts index 24234dc8d5..def66df5cb 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/equal.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/equal.ts @@ -22,7 +22,7 @@ export class Equal extends ComparisonEvaluator { super( ExpressionType.Equal, (args) => FunctionUtils.commonEquals(args[0], args[1]), - FunctionUtils.validateBinary + FunctionUtils.validateBinary, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/foreach.ts b/libraries/adaptive-expressions/src/builtinFunctions/foreach.ts index 6191e08499..36711e25c1 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/foreach.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/foreach.ts @@ -23,7 +23,7 @@ export class Foreach extends ExpressionEvaluator { ExpressionType.Foreach, InternalFunctionUtils.foreach, ReturnType.Array, - InternalFunctionUtils.ValidateLambdaExpression + InternalFunctionUtils.ValidateLambdaExpression, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/formatNumber.ts b/libraries/adaptive-expressions/src/builtinFunctions/formatNumber.ts index 673da73cca..e07fe83f0d 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/formatNumber.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/formatNumber.ts @@ -1,4 +1,3 @@ -/* eslint-disable security/detect-object-injection */ /** * @module adaptive-expressions */ @@ -31,35 +30,40 @@ export class FormatNumber extends ExpressionEvaluator { * @private */ private static evaluator(): EvaluateExpressionDelegate { - return FunctionUtils.applyWithOptionsAndError((args: unknown[], options: Options): { - value: unknown; - error: string; - } => { - let value: unknown = null; - let error: string; - const number = args[0]; - const precision = args[1]; - let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; - locale = FunctionUtils.determineLocale(args, 3, locale); - if (!FunctionUtils.isNumber(number)) { - error = `formatNumber first argument ${number} must be a number`; - } else if (!FunctionUtils.isNumber(precision)) { - error = `formatNumber second argument ${precision} must be a number`; - } else if (locale && typeof locale !== 'string') { - error = `formatNubmer third argument ${locale} is not a valid locale`; - } else { - const fixedNotation = `,.${precision}f`; - const roundedNumber = this.roundToPrecision(number, precision); - const formatLocale = localeInfo[locale]; - if (formatLocale !== undefined) { - value = d3formatLocale(formatLocale).format(fixedNotation)(roundedNumber); + return FunctionUtils.applyWithOptionsAndError( + ( + args: unknown[], + options: Options, + ): { + value: unknown; + error: string; + } => { + let value: unknown = null; + let error: string; + const number = args[0]; + const precision = args[1]; + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + locale = FunctionUtils.determineLocale(args, 3, locale); + if (!FunctionUtils.isNumber(number)) { + error = `formatNumber first argument ${number} must be a number`; + } else if (!FunctionUtils.isNumber(precision)) { + error = `formatNumber second argument ${precision} must be a number`; + } else if (locale && typeof locale !== 'string') { + error = `formatNubmer third argument ${locale} is not a valid locale`; } else { - value = d3format(fixedNotation)(roundedNumber); + const fixedNotation = `,.${precision}f`; + const roundedNumber = this.roundToPrecision(number, precision); + const formatLocale = localeInfo[locale]; + if (formatLocale !== undefined) { + value = d3formatLocale(formatLocale).format(fixedNotation)(roundedNumber); + } else { + value = d3format(fixedNotation)(roundedNumber); + } } - } - return { value, error }; - }); + return { value, error }; + }, + ); } private static roundToPrecision = (num: number, digits: number): number => diff --git a/libraries/adaptive-expressions/src/builtinFunctions/formatTicks.ts b/libraries/adaptive-expressions/src/builtinFunctions/formatTicks.ts index d8f5be6a09..b485a1b11f 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/formatTicks.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/formatTicks.ts @@ -32,40 +32,38 @@ export class FormatTicks extends ExpressionEvaluator { * @private */ private static evaluator(): EvaluateExpressionDelegate { - return FunctionUtils.applyWithOptionsAndError( - (args: unknown[], options: Options): ValueWithError => { - let error: string; - let arg = args[0]; - let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; - let format = FunctionUtils.DefaultDateTimeFormat; - if (FunctionUtils.isNumber(arg)) { - arg = bigInt(arg); - } - if (typeof arg === 'string') { - arg = bigInt(arg); - } - if (!bigInt.isInstance(arg)) { - error = `formatTicks first argument ${arg} is not a number, numeric string or bigInt`; - } else { - // Convert to ms - arg = arg - .subtract(InternalFunctionUtils.UnixMilliSecondToTicksConstant) - .divide(InternalFunctionUtils.MillisecondToTickConstant) - .toJSNumber(); - } + return FunctionUtils.applyWithOptionsAndError((args: unknown[], options: Options): ValueWithError => { + let error: string; + let arg = args[0]; + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + let format = FunctionUtils.DefaultDateTimeFormat; + if (FunctionUtils.isNumber(arg)) { + arg = bigInt(arg); + } + if (typeof arg === 'string') { + arg = bigInt(arg); + } + if (!bigInt.isInstance(arg)) { + error = `formatTicks first argument ${arg} is not a number, numeric string or bigInt`; + } else { + // Convert to ms + arg = arg + .subtract(InternalFunctionUtils.UnixMilliSecondToTicksConstant) + .divide(InternalFunctionUtils.MillisecondToTickConstant) + .toJSNumber(); + } - let value: any; - if (!error) { - ({ format, locale } = FunctionUtils.determineFormatAndLocale(args, 3, format, locale)); - if (FunctionUtils.isNumber(arg)) { - const dateString: string = new Date(arg).toISOString(); - value = dayjs(dateString).locale(locale).utc().format(format); - } + let value: any; + if (!error) { + ({ format, locale } = FunctionUtils.determineFormatAndLocale(args, 3, format, locale)); + if (FunctionUtils.isNumber(arg)) { + const dateString: string = new Date(arg).toISOString(); + value = dayjs(dateString).locale(locale).utc().format(format); } - - return { value, error }; } - ); + + return { value, error }; + }); } /** diff --git a/libraries/adaptive-expressions/src/builtinFunctions/getFutureTime.ts b/libraries/adaptive-expressions/src/builtinFunctions/getFutureTime.ts index 1a2430e0bd..fef335543c 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/getFutureTime.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/getFutureTime.ts @@ -63,7 +63,7 @@ export class GetFutureTime extends ExpressionEvaluator { expression, [ReturnType.String, ReturnType.String], ReturnType.Number, - ReturnType.String + ReturnType.String, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/getNextViableDate.ts b/libraries/adaptive-expressions/src/builtinFunctions/getNextViableDate.ts index a86397d9b5..11cc5ec019 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/getNextViableDate.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/getNextViableDate.ts @@ -34,7 +34,7 @@ export class GetNextViableDate extends ExpressionEvaluator { ExpressionType.GetNextViableDate, GetNextViableDate.evaluator, ReturnType.String, - FunctionUtils.validateUnaryOrBinaryString + FunctionUtils.validateUnaryOrBinaryString, ); } @@ -44,7 +44,7 @@ export class GetNextViableDate extends ExpressionEvaluator { private static evaluator( expr: Expression, state: MemoryInterface, - options: Options + options: Options, ): { value: any; error: string } { let parsed: TimexProperty; const currentTime = dayjs(new Date().toISOString()); diff --git a/libraries/adaptive-expressions/src/builtinFunctions/getNextViableTime.ts b/libraries/adaptive-expressions/src/builtinFunctions/getNextViableTime.ts index ebdfc72931..b8ce69be30 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/getNextViableTime.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/getNextViableTime.ts @@ -33,7 +33,7 @@ export class GetNextViableTime extends ExpressionEvaluator { ExpressionType.GetNextViableTime, GetNextViableTime.evaluator, ReturnType.String, - FunctionUtils.validateUnaryOrBinaryString + FunctionUtils.validateUnaryOrBinaryString, ); } @@ -43,7 +43,7 @@ export class GetNextViableTime extends ExpressionEvaluator { private static evaluator( expr: Expression, state: MemoryInterface, - options: Options + options: Options, ): { value: any; error: string } { let parsed: TimexProperty; const currentTime = dayjs(new Date().toISOString()); @@ -77,7 +77,7 @@ export class GetNextViableTime extends ExpressionEvaluator { if (!error) { ({ timexProperty: parsed, error: error } = InternalFunctionUtils.parseTimexProperty( - (args[0] as string).replace('XX', '00') + (args[0] as string).replace('XX', '00'), )); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/getPastTime.ts b/libraries/adaptive-expressions/src/builtinFunctions/getPastTime.ts index 3ce2d1e392..a011c9bf19 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/getPastTime.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/getPastTime.ts @@ -63,7 +63,7 @@ export class GetPastTime extends ExpressionEvaluator { expression, [ReturnType.String, ReturnType.String], ReturnType.Number, - ReturnType.String + ReturnType.String, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/getPreviousViableDate.ts b/libraries/adaptive-expressions/src/builtinFunctions/getPreviousViableDate.ts index d02bbe22e7..d7e82326fc 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/getPreviousViableDate.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/getPreviousViableDate.ts @@ -34,7 +34,7 @@ export class GetPreviousViableDate extends ExpressionEvaluator { ExpressionType.GetPreviousViableDate, GetPreviousViableDate.evaluator, ReturnType.String, - FunctionUtils.validateUnaryOrBinaryString + FunctionUtils.validateUnaryOrBinaryString, ); } @@ -44,7 +44,7 @@ export class GetPreviousViableDate extends ExpressionEvaluator { private static evaluator( expr: Expression, state: MemoryInterface, - options: Options + options: Options, ): { value: any; error: string } { let parsed: TimexProperty; const currentTime = dayjs(new Date().toISOString()); diff --git a/libraries/adaptive-expressions/src/builtinFunctions/getPreviousViableTime.ts b/libraries/adaptive-expressions/src/builtinFunctions/getPreviousViableTime.ts index a2eddb4712..681729e972 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/getPreviousViableTime.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/getPreviousViableTime.ts @@ -31,7 +31,7 @@ export class GetPreviousViableTime extends ExpressionEvaluator { ExpressionType.GetPreviousViableTime, GetPreviousViableTime.evaluator, ReturnType.String, - FunctionUtils.validateUnaryOrBinaryString + FunctionUtils.validateUnaryOrBinaryString, ); } @@ -41,7 +41,7 @@ export class GetPreviousViableTime extends ExpressionEvaluator { private static evaluator( expr: Expression, state: MemoryInterface, - options: Options + options: Options, ): { value: any; error: string } { let parsed: TimexProperty; const currentTime = dayjs(new Date().toISOString()); @@ -75,7 +75,7 @@ export class GetPreviousViableTime extends ExpressionEvaluator { if (!error) { ({ timexProperty: parsed, error: error } = InternalFunctionUtils.parseTimexProperty( - (args[0] as string).replace('XX', '00') + (args[0] as string).replace('XX', '00'), )); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/getProperty.ts b/libraries/adaptive-expressions/src/builtinFunctions/getProperty.ts index de2ff81b64..b65aec2a13 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/getProperty.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/getProperty.ts @@ -53,7 +53,7 @@ export class GetProperty extends ExpressionEvaluator { value = InternalFunctionUtils.wrapGetValue( new SimpleObjectMemory(firstItem), property.toString(), - options + options, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/getTimeOfDay.ts b/libraries/adaptive-expressions/src/builtinFunctions/getTimeOfDay.ts index efcf83a484..b5dca03a50 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/getTimeOfDay.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/getTimeOfDay.ts @@ -26,7 +26,7 @@ export class GetTimeOfDay extends ExpressionEvaluator { ExpressionType.GetTimeOfDay, GetTimeOfDay.evaluator(), ReturnType.String, - FunctionUtils.validateUnaryString + FunctionUtils.validateUnaryString, ); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/greaterThanOrEqual.ts b/libraries/adaptive-expressions/src/builtinFunctions/greaterThanOrEqual.ts index cdc484b2e0..138aff8157 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/greaterThanOrEqual.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/greaterThanOrEqual.ts @@ -23,7 +23,7 @@ export class GreaterThanOrEqual extends ComparisonEvaluator { ExpressionType.GreaterThanOrEqual, GreaterThanOrEqual.func, FunctionUtils.validateBinary, - FunctionUtils.verifyNotNull + FunctionUtils.verifyNotNull, ); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/index.ts b/libraries/adaptive-expressions/src/builtinFunctions/index.ts index 3aab6a4f54..2ecabc1e9a 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/index.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/index.ts @@ -66,7 +66,6 @@ export * from './getNextViableTime'; export * from './getPastTime'; export * from './getPreviousViableDate'; export * from './getPreviousViableTime'; -export * from './getPastTime'; export * from './getProperty'; export * from './getTimeOfDay'; export * from './greaterThan'; diff --git a/libraries/adaptive-expressions/src/builtinFunctions/indexOf.ts b/libraries/adaptive-expressions/src/builtinFunctions/indexOf.ts index a05487de98..e71afa941b 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/indexOf.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/indexOf.ts @@ -38,7 +38,7 @@ export class IndexOf extends ExpressionEvaluator { if (args[0] == null || typeof args[0] === 'string') { if (args[1] === undefined || typeof args[1] === 'string') { value = InternalFunctionUtils.parseStringOrUndefined(args[0]).indexOf( - InternalFunctionUtils.parseStringOrUndefined(args[1]) + InternalFunctionUtils.parseStringOrUndefined(args[1]), ); } else { error = `Can only look for indexof string in ${expression}`; diff --git a/libraries/adaptive-expressions/src/builtinFunctions/indicesAndValues.ts b/libraries/adaptive-expressions/src/builtinFunctions/indicesAndValues.ts index 54dc306ff4..6bb902c140 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/indicesAndValues.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/indicesAndValues.ts @@ -27,7 +27,7 @@ export class IndicesAndValues extends ExpressionEvaluator { ExpressionType.IndicesAndValues, IndicesAndValues.evaluator, ReturnType.Array, - FunctionUtils.validateUnary + FunctionUtils.validateUnary, ); } @@ -35,7 +35,6 @@ export class IndicesAndValues extends ExpressionEvaluator { * @private */ private static evaluator(expression: Expression, state: any, options: Options): ValueWithError { - // eslint-disable-next-line @typescript-eslint/ban-types let result: object = undefined; let error: string = undefined; let value: any = undefined; diff --git a/libraries/adaptive-expressions/src/builtinFunctions/int.ts b/libraries/adaptive-expressions/src/builtinFunctions/int.ts index 1b927416b7..228eda2770 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/int.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/int.ts @@ -27,25 +27,23 @@ export class Int extends ExpressionEvaluator { * @private */ private static evaluator(): EvaluateExpressionDelegate { - return FunctionUtils.applyWithError( - (args: readonly unknown[]): ValueWithError => { - let error: string; - let value: unknown; - const firstChild = args[0]; - if (bigInt.isInstance(firstChild)) { - return { value: firstChild.toJSNumber(), error }; - } - if (typeof firstChild === 'string') { - value = parseInt(firstChild, 10); - if (!FunctionUtils.isNumber(value)) { - error = `parameter ${args[0]} is not a valid number string.`; - } - } else if (FunctionUtils.isNumber(firstChild)) { - value = parseInt(firstChild.toString(), 10); + return FunctionUtils.applyWithError((args: readonly unknown[]): ValueWithError => { + let error: string; + let value: unknown; + const firstChild = args[0]; + if (bigInt.isInstance(firstChild)) { + return { value: firstChild.toJSNumber(), error }; + } + if (typeof firstChild === 'string') { + value = parseInt(firstChild, 10); + if (!FunctionUtils.isNumber(value)) { + error = `parameter ${args[0]} is not a valid number string.`; } - - return { value, error }; + } else if (FunctionUtils.isNumber(firstChild)) { + value = parseInt(firstChild.toString(), 10); } - ); + + return { value, error }; + }); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/isDateTime.ts b/libraries/adaptive-expressions/src/builtinFunctions/isDateTime.ts index 2782a11b50..052ff408c4 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/isDateTime.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/isDateTime.ts @@ -29,7 +29,7 @@ export class IsDateTime extends ExpressionEvaluator { private static evaluator(): EvaluateExpressionDelegate { return FunctionUtils.apply( (args: any[]): boolean => - typeof args[0] === 'string' && InternalFunctionUtils.verifyISOTimestamp(args[0]) === undefined + typeof args[0] === 'string' && InternalFunctionUtils.verifyISOTimestamp(args[0]) === undefined, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/isFloat.ts b/libraries/adaptive-expressions/src/builtinFunctions/isFloat.ts index 62af5eb8e7..f0064ad0cc 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/isFloat.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/isFloat.ts @@ -28,7 +28,7 @@ export class IsFloat extends ExpressionEvaluator { */ private static evaluator(): EvaluateExpressionDelegate { return FunctionUtils.apply( - (args: any[]): boolean => FunctionUtils.isNumber(args[0]) && !Number.isInteger(args[0]) + (args: any[]): boolean => FunctionUtils.isNumber(args[0]) && !Number.isInteger(args[0]), ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/isInteger.ts b/libraries/adaptive-expressions/src/builtinFunctions/isInteger.ts index a0ee58f36c..9a4c75b903 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/isInteger.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/isInteger.ts @@ -27,7 +27,7 @@ export class IsInteger extends ExpressionEvaluator { */ private static evaluator(): EvaluateExpressionDelegate { return FunctionUtils.apply( - (args: any[]): boolean => FunctionUtils.isNumber(args[0]) && Number.isInteger(args[0]) + (args: any[]): boolean => FunctionUtils.isNumber(args[0]) && Number.isInteger(args[0]), ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/jPath.ts b/libraries/adaptive-expressions/src/builtinFunctions/jPath.ts index ec694ad3cc..e56b37224a 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/jPath.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/jPath.ts @@ -35,11 +35,9 @@ export class JPath extends ExpressionEvaluator { /** * @private */ - // eslint-disable-next-line @typescript-eslint/ban-types private static evalJPath(jsonEntity: object | string, path: string): ValueWithError { let error: string; let evaled: any; - // eslint-disable-next-line @typescript-eslint/ban-types let json: object; if (typeof jsonEntity === 'string') { try { diff --git a/libraries/adaptive-expressions/src/builtinFunctions/length.ts b/libraries/adaptive-expressions/src/builtinFunctions/length.ts index be82af942f..5caf7cc00c 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/length.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/length.ts @@ -29,7 +29,7 @@ export class Length extends ExpressionEvaluator { private static evaluator(): EvaluateExpressionDelegate { return FunctionUtils.apply( (args: any[]): number => InternalFunctionUtils.parseStringOrUndefined(args[0]).length, - FunctionUtils.verifyStringOrNull + FunctionUtils.verifyStringOrNull, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/lessThanOrEqual.ts b/libraries/adaptive-expressions/src/builtinFunctions/lessThanOrEqual.ts index 6735d56115..143e4e5f3d 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/lessThanOrEqual.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/lessThanOrEqual.ts @@ -23,7 +23,7 @@ export class LessThanOrEqual extends ComparisonEvaluator { ExpressionType.LessThanOrEqual, LessThanOrEqual.func, FunctionUtils.validateBinary, - FunctionUtils.verifyNotNull + FunctionUtils.verifyNotNull, ); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/merge.ts b/libraries/adaptive-expressions/src/builtinFunctions/merge.ts index 76593a6a29..0d7ed20a5f 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/merge.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/merge.ts @@ -27,23 +27,21 @@ export class Merge extends ExpressionEvaluator { * @private */ private static evaluator(): EvaluateExpressionDelegate { - return FunctionUtils.applyWithError( - (args: unknown[]): ValueWithError => { - const result = {}; - for (const arg of args) { - const objectResult = this.parseToObjectList(arg); - if (objectResult.error != null) { - return { value: undefined, error: objectResult.error }; - } - - for (const item of objectResult.result) { - Object.assign(result, item); - } + return FunctionUtils.applyWithError((args: unknown[]): ValueWithError => { + const result = {}; + for (const arg of args) { + const objectResult = this.parseToObjectList(arg); + if (objectResult.error != null) { + return { value: undefined, error: objectResult.error }; } - return { value: result, error: undefined }; + for (const item of objectResult.result) { + Object.assign(result, item); + } } - ); + + return { value: result, error: undefined }; + }); } private static parseToObjectList(arg: unknown): { result: Record[]; error: string } { diff --git a/libraries/adaptive-expressions/src/builtinFunctions/multivariateNumericEvaluator.ts b/libraries/adaptive-expressions/src/builtinFunctions/multivariateNumericEvaluator.ts index d7af23c451..e921aa7b45 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/multivariateNumericEvaluator.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/multivariateNumericEvaluator.ts @@ -26,7 +26,7 @@ export class MultivariateNumericEvaluator extends ExpressionEvaluator { type, MultivariateNumericEvaluator.evaluator(func, verify), ReturnType.Number, - FunctionUtils.validateTwoOrMoreThanTwoNumbers + FunctionUtils.validateTwoOrMoreThanTwoNumbers, ); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/notEqual.ts b/libraries/adaptive-expressions/src/builtinFunctions/notEqual.ts index f97b0bee05..a8412ef29f 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/notEqual.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/notEqual.ts @@ -21,7 +21,7 @@ export class NotEqual extends ComparisonEvaluator { super( ExpressionType.NotEqual, (args) => !FunctionUtils.commonEquals(args[0], args[1]), - FunctionUtils.validateBinary + FunctionUtils.validateBinary, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/replaceIgnoreCase.ts b/libraries/adaptive-expressions/src/builtinFunctions/replaceIgnoreCase.ts index b8c2169c93..92e5baeabe 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/replaceIgnoreCase.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/replaceIgnoreCase.ts @@ -26,7 +26,7 @@ export class ReplaceIgnoreCase extends ExpressionEvaluator { ExpressionType.ReplaceIgnoreCase, ReplaceIgnoreCase.evaluator(), ReturnType.String, - ReplaceIgnoreCase.validator + ReplaceIgnoreCase.validator, ); } @@ -45,7 +45,7 @@ export class ReplaceIgnoreCase extends ExpressionEvaluator { result = InternalFunctionUtils.parseStringOrUndefined(args[0]).replace( // eslint-disable-next-line security/detect-non-literal-regexp new RegExp(InternalFunctionUtils.parseStringOrUndefined(args[1]), 'gi'), - InternalFunctionUtils.parseStringOrUndefined(args[2]) + InternalFunctionUtils.parseStringOrUndefined(args[2]), ); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/select.ts b/libraries/adaptive-expressions/src/builtinFunctions/select.ts index aabffbb0f2..37fa9b1813 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/select.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/select.ts @@ -23,7 +23,7 @@ export class Select extends ExpressionEvaluator { ExpressionType.Select, InternalFunctionUtils.foreach, ReturnType.Array, - InternalFunctionUtils.ValidateLambdaExpression + InternalFunctionUtils.ValidateLambdaExpression, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/sortByDescending.ts b/libraries/adaptive-expressions/src/builtinFunctions/sortByDescending.ts index e2c18100cf..a31357a527 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/sortByDescending.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/sortByDescending.ts @@ -25,7 +25,7 @@ export class SortByDescending extends ExpressionEvaluator { ExpressionType.SortByDescending, InternalFunctionUtils.sortBy(true), ReturnType.Array, - SortByDescending.validator + SortByDescending.validator, ); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/split.ts b/libraries/adaptive-expressions/src/builtinFunctions/split.ts index bca100688f..c62a3af25c 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/split.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/split.ts @@ -31,9 +31,9 @@ export class Split extends ExpressionEvaluator { return FunctionUtils.apply( (args: any[]): string[] => InternalFunctionUtils.parseStringOrUndefined(args[0]).split( - InternalFunctionUtils.parseStringOrUndefined(args[1] || '') + InternalFunctionUtils.parseStringOrUndefined(args[1] || ''), ), - FunctionUtils.verifyStringOrNull + FunctionUtils.verifyStringOrNull, ); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/startsWith.ts b/libraries/adaptive-expressions/src/builtinFunctions/startsWith.ts index ac29e01c29..5f4e97c5db 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/startsWith.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/startsWith.ts @@ -32,9 +32,9 @@ export class StartsWith extends ExpressionEvaluator { return FunctionUtils.apply( (args: any[]): boolean => InternalFunctionUtils.parseStringOrUndefined(args[0]).startsWith( - InternalFunctionUtils.parseStringOrUndefined(args[1]) + InternalFunctionUtils.parseStringOrUndefined(args[1]), ), - FunctionUtils.verifyStringOrNull + FunctionUtils.verifyStringOrNull, ); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/string.ts b/libraries/adaptive-expressions/src/builtinFunctions/string.ts index c64474982c..bc3ddc6757 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/string.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/string.ts @@ -31,44 +31,42 @@ export class String extends ExpressionEvaluator { * @private */ private static evaluator(): EvaluateExpressionDelegate { - return FunctionUtils.applyWithOptionsAndError( - (args: any[], options: Options): ValueWithError => { - let result: any; - let error: string; - let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; - if (!error) { - locale = FunctionUtils.determineLocale(args, 2, locale); - } + return FunctionUtils.applyWithOptionsAndError((args: any[], options: Options): ValueWithError => { + let result: any; + let error: string; + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + if (!error) { + locale = FunctionUtils.determineLocale(args, 2, locale); + } - if (!error) { - if (typeof args[0] === 'string') { - result = args[0]; - } else if (FunctionUtils.isNumber(args[0])) { - const formatLocale = localeInfo[locale]; - const tempStrValue = args[0].toString(); - let precision = 0; - if (tempStrValue.includes('.')) { - precision = tempStrValue.split('.')[1].length; - } + if (!error) { + if (typeof args[0] === 'string') { + result = args[0]; + } else if (FunctionUtils.isNumber(args[0])) { + const formatLocale = localeInfo[locale]; + const tempStrValue = args[0].toString(); + let precision = 0; + if (tempStrValue.includes('.')) { + precision = tempStrValue.split('.')[1].length; + } - const fixedNotation = `,.${precision}f`; - if (formatLocale !== undefined) { - result = d3formatLocale(formatLocale).format(fixedNotation)(args[0]); - } else { - result = d3format(fixedNotation)(args[0]); - } - } else if (args[0] instanceof Date) { - result = args[0].toLocaleDateString(locale); - } else if (args[0] instanceof Uint8Array) { - result = InternalFunctionUtils.getTextDecoder().decode(args[0]); + const fixedNotation = `,.${precision}f`; + if (formatLocale !== undefined) { + result = d3formatLocale(formatLocale).format(fixedNotation)(args[0]); } else { - result = InternalFunctionUtils.commonStringify(args[0]); + result = d3format(fixedNotation)(args[0]); } + } else if (args[0] instanceof Date) { + result = args[0].toLocaleDateString(locale); + } else if (args[0] instanceof Uint8Array) { + result = InternalFunctionUtils.getTextDecoder().decode(args[0]); + } else { + result = InternalFunctionUtils.commonStringify(args[0]); } - - return { value: result, error: error }; } - ); + + return { value: result, error: error }; + }); } /** diff --git a/libraries/adaptive-expressions/src/builtinFunctions/stringOrValue.ts b/libraries/adaptive-expressions/src/builtinFunctions/stringOrValue.ts index bf205c70e7..d218b90473 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/stringOrValue.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/stringOrValue.ts @@ -28,7 +28,7 @@ export class StringOrValue extends ExpressionEvaluator { ExpressionType.StringOrValue, StringOrValue.evaluator, ReturnType.Object, - FunctionUtils.validateUnaryString + FunctionUtils.validateUnaryString, ); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/stringTransformEvaluator.ts b/libraries/adaptive-expressions/src/builtinFunctions/stringTransformEvaluator.ts index 1691a52998..2dd86b3c9d 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/stringTransformEvaluator.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/stringTransformEvaluator.ts @@ -28,7 +28,7 @@ export class StringTransformEvaluator extends ExpressionEvaluator { type, FunctionUtils.applyWithOptions(func, FunctionUtils.verifyStringOrNull), ReturnType.String, - validator ? validator : FunctionUtils.validateUnaryString + validator ? validator : FunctionUtils.validateUnaryString, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/subtractFromTime.ts b/libraries/adaptive-expressions/src/builtinFunctions/subtractFromTime.ts index 99a164eccb..13435e5170 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/subtractFromTime.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/subtractFromTime.ts @@ -30,7 +30,7 @@ export class SubtractFromTime extends ExpressionEvaluator { ExpressionType.SubtractFromTime, SubtractFromTime.evaluator, ReturnType.String, - SubtractFromTime.validator + SubtractFromTime.validator, ); } @@ -73,7 +73,7 @@ export class SubtractFromTime extends ExpressionEvaluator { [ReturnType.String, ReturnType.String], ReturnType.String, ReturnType.Number, - ReturnType.String + ReturnType.String, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/sum.ts b/libraries/adaptive-expressions/src/builtinFunctions/sum.ts index 6b971a2f72..57d82a90ed 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/sum.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/sum.ts @@ -29,7 +29,7 @@ export class Sum extends ExpressionEvaluator { private static evaluator(): EvaluateExpressionDelegate { return FunctionUtils.apply( (args: any[]): number => args[0].reduce((x: number, y: number): number => x + y), - FunctionUtils.verifyNumericList + FunctionUtils.verifyNumericList, ); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/ticksToHours.ts b/libraries/adaptive-expressions/src/builtinFunctions/ticksToHours.ts index 551d73216c..464391a016 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/ticksToHours.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/ticksToHours.ts @@ -29,7 +29,7 @@ export class TicksToHours extends ExpressionEvaluator { ExpressionType.TicksToHours, TicksToHours.evaluator, ReturnType.Number, - FunctionUtils.validateUnaryNumber + FunctionUtils.validateUnaryNumber, ); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/ticksToMinutes.ts b/libraries/adaptive-expressions/src/builtinFunctions/ticksToMinutes.ts index 5c825cfc0e..c36de85b17 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/ticksToMinutes.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/ticksToMinutes.ts @@ -29,7 +29,7 @@ export class TicksToMinutes extends ExpressionEvaluator { ExpressionType.TicksToMinutes, TicksToMinutes.evaluator, ReturnType.Number, - FunctionUtils.validateUnaryNumber + FunctionUtils.validateUnaryNumber, ); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/timeTransformEvaluator.ts b/libraries/adaptive-expressions/src/builtinFunctions/timeTransformEvaluator.ts index 1fbbcb48da..e1731dfbd7 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/timeTransformEvaluator.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/timeTransformEvaluator.ts @@ -68,7 +68,7 @@ export class TimeTransformEvaluator extends ExpressionEvaluator { expression, [ReturnType.String, ReturnType.String], ReturnType.String, - ReturnType.Number + ReturnType.Number, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/titleCase.ts b/libraries/adaptive-expressions/src/builtinFunctions/titleCase.ts index cbb12ae636..4fd2d6272c 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/titleCase.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/titleCase.ts @@ -34,7 +34,7 @@ export class TitleCase extends StringTransformEvaluator { } else { return inputStr.replace( /\w\S*/g, - (txt): string => txt.charAt(0).toUpperCase() + txt.substr(1).toLocaleLowerCase(locale) + (txt): string => txt.charAt(0).toUpperCase() + txt.substr(1).toLocaleLowerCase(locale), ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/uriComponent.ts b/libraries/adaptive-expressions/src/builtinFunctions/uriComponent.ts index a175a68f94..c642fbab85 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/uriComponent.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/uriComponent.ts @@ -28,7 +28,7 @@ export class UriComponent extends ExpressionEvaluator { private static evaluator(): EvaluateExpressionDelegate { return FunctionUtils.apply( (args: Readonly): string => encodeURIComponent(args[0]), - FunctionUtils.verifyString + FunctionUtils.verifyString, ); } } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/uriComponentToString.ts b/libraries/adaptive-expressions/src/builtinFunctions/uriComponentToString.ts index 142a821f6d..9b76534175 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/uriComponentToString.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/uriComponentToString.ts @@ -23,7 +23,7 @@ export class UriComponentToString extends ExpressionEvaluator { ExpressionType.UriComponentToString, UriComponentToString.evaluator(), ReturnType.String, - FunctionUtils.validateUnary + FunctionUtils.validateUnary, ); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/uriPathAndQuery.ts b/libraries/adaptive-expressions/src/builtinFunctions/uriPathAndQuery.ts index 93d02294fe..9149d6f86e 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/uriPathAndQuery.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/uriPathAndQuery.ts @@ -27,7 +27,7 @@ export class UriPathAndQuery extends ExpressionEvaluator { ExpressionType.UriPathAndQuery, UriPathAndQuery.evaluator, ReturnType.String, - FunctionUtils.validateUnary + FunctionUtils.validateUnary, ); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/utcNow.ts b/libraries/adaptive-expressions/src/builtinFunctions/utcNow.ts index e58f6ee6bc..89be448188 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/utcNow.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/utcNow.ts @@ -31,18 +31,16 @@ export class UtcNow extends ExpressionEvaluator { * @private */ private static evaluator(): EvaluateExpressionDelegate { - return FunctionUtils.applyWithOptionsAndError( - (args: unknown[], options: Options): ValueWithError => { - let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; - let format = FunctionUtils.DefaultDateTimeFormat; - ({ format, locale } = FunctionUtils.determineFormatAndLocale(args, 2, format, locale)); + return FunctionUtils.applyWithOptionsAndError((args: unknown[], options: Options): ValueWithError => { + let locale = options.locale ? options.locale : Intl.DateTimeFormat().resolvedOptions().locale; + let format = FunctionUtils.DefaultDateTimeFormat; + ({ format, locale } = FunctionUtils.determineFormatAndLocale(args, 2, format, locale)); - return { - value: dayjs(new Date()).locale(locale).utc().format(format), - error: undefined, - }; - } - ); + return { + value: dayjs(new Date()).locale(locale).utc().format(format), + error: undefined, + }; + }); } /** diff --git a/libraries/adaptive-expressions/src/builtinFunctions/xml.ts b/libraries/adaptive-expressions/src/builtinFunctions/xml.ts index 6a0d8d443a..b6a0bce0bf 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/xml.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/xml.ts @@ -24,7 +24,7 @@ export class XML extends ExpressionEvaluator { private static evaluator(): EvaluateExpressionDelegate { return FunctionUtils.applyWithError((args: unknown[]): { value: unknown; error: string } => - XML.platformSpecificXML(args) + XML.platformSpecificXML(args), ); } diff --git a/libraries/adaptive-expressions/src/builtinFunctions/xpath.ts b/libraries/adaptive-expressions/src/builtinFunctions/xpath.ts index 118e7f2f2e..eb1bd367cd 100644 --- a/libraries/adaptive-expressions/src/builtinFunctions/xpath.ts +++ b/libraries/adaptive-expressions/src/builtinFunctions/xpath.ts @@ -25,7 +25,7 @@ export class XPath extends ExpressionEvaluator { private static evaluator(): EvaluateExpressionDelegate { return FunctionUtils.applyWithError((args: unknown[]): { value: unknown; error: string } => - XPath.platformSpecificXPath(args) + XPath.platformSpecificXPath(args), ); } @@ -64,9 +64,10 @@ export class XPath extends ExpressionEvaluator { } else { let error: string; let result: unknown; - // eslint-disable-next-line @typescript-eslint/no-var-requires + + //eslint-disable-next-line @typescript-eslint/no-require-imports const xpath = require('xpath'); - // eslint-disable-next-line @typescript-eslint/no-var-requires + //eslint-disable-next-line @typescript-eslint/no-require-imports const { DOMParser } = require('@xmldom/xmldom'); let doc: XMLDocument; try { diff --git a/libraries/adaptive-expressions/src/constant.ts b/libraries/adaptive-expressions/src/constant.ts index 344714d983..990b8356d4 100644 --- a/libraries/adaptive-expressions/src/constant.ts +++ b/libraries/adaptive-expressions/src/constant.ts @@ -34,12 +34,12 @@ export class Constant extends Expression { typeof theValue === 'string' ? ReturnType.String : typeof theValue === 'boolean' - ? ReturnType.Boolean - : FunctionUtils.isNumber(theValue) - ? ReturnType.Number - : Array.isArray(theValue) - ? ReturnType.Array - : ReturnType.Object; + ? ReturnType.Boolean + : FunctionUtils.isNumber(theValue) + ? ReturnType.Number + : Array.isArray(theValue) + ? ReturnType.Array + : ReturnType.Object; this._value = theValue; } @@ -55,12 +55,9 @@ export class Constant extends Expression { constructor(value: any) { super( ExpressionType.Constant, - new ExpressionEvaluator( - ExpressionType.Constant, - (expression: Expression): ValueWithError => { - return { value: (expression as Constant).value, error: undefined }; - } - ) + new ExpressionEvaluator(ExpressionType.Constant, (expression: Expression): ValueWithError => { + return { value: (expression as Constant).value, error: undefined }; + }), ); this.value = value; } diff --git a/libraries/adaptive-expressions/src/converters/objectExpressionConverter.ts b/libraries/adaptive-expressions/src/converters/objectExpressionConverter.ts index c27efc82b4..9de97f89a3 100644 --- a/libraries/adaptive-expressions/src/converters/objectExpressionConverter.ts +++ b/libraries/adaptive-expressions/src/converters/objectExpressionConverter.ts @@ -16,7 +16,6 @@ type Input = T | string | Expression; * * @template T The type of the value. */ -// eslint-disable-next-line @typescript-eslint/ban-types export class ObjectExpressionConverter { /** * Converts value of type `T` into an [ObjectExpression](xref:adaptive-expressions.ObjectExpression). diff --git a/libraries/adaptive-expressions/src/expression.ts b/libraries/adaptive-expressions/src/expression.ts index 3b63ea4bc2..ba581d4edc 100644 --- a/libraries/adaptive-expressions/src/expression.ts +++ b/libraries/adaptive-expressions/src/expression.ts @@ -142,7 +142,7 @@ export class Expression { */ referenceWalk( expression: Expression, - extension?: (arg0: Expression) => boolean + extension?: (arg0: Expression) => boolean, ): { path: string; refs: Set } { let path: string; let refs = new Set(); @@ -206,7 +206,7 @@ export class Expression { const iteratorName = (children[1].children[0] as Constant).value as string; const nonLocalRefs2 = Array.from(refs2).filter( (x): boolean => - !(x === iteratorName || x.startsWith(iteratorName + '.') || x.startsWith(iteratorName + '[')) + !(x === iteratorName || x.startsWith(iteratorName + '.') || x.startsWith(iteratorName + '[')), ); refs = new Set([...refs, ...refs0, ...nonLocalRefs2]); } else { @@ -298,8 +298,8 @@ export class Expression { } return { value, error }; - } - ) + }, + ), ); } diff --git a/libraries/adaptive-expressions/src/expressionEvaluator.ts b/libraries/adaptive-expressions/src/expressionEvaluator.ts index e9e5be7a8e..4d5de9f16f 100644 --- a/libraries/adaptive-expressions/src/expressionEvaluator.ts +++ b/libraries/adaptive-expressions/src/expressionEvaluator.ts @@ -31,7 +31,7 @@ export type ValueWithError = { export type EvaluateExpressionDelegate = ( expression: Expression, state: MemoryInterface, - options: Options + options: Options, ) => ValueWithError; /** @@ -67,7 +67,7 @@ export class ExpressionEvaluator { type: string, evaluator: EvaluateExpressionDelegate, returnType: ReturnType = ReturnType.Object, - validator?: ValidateExpressionDelegate + validator?: ValidateExpressionDelegate, ) { this.type = type; this._evaluator = evaluator; diff --git a/libraries/adaptive-expressions/src/expressionFunctions.ts b/libraries/adaptive-expressions/src/expressionFunctions.ts index 6105d90035..7df0316e0a 100644 --- a/libraries/adaptive-expressions/src/expressionFunctions.ts +++ b/libraries/adaptive-expressions/src/expressionFunctions.ts @@ -28,10 +28,8 @@ export class ExpressionFunctions { /** * Read only Dictionary of built in functions. */ - static readonly standardFunctions: ReadonlyMap< - string, - ExpressionEvaluator - > = ExpressionFunctions.getStandardFunctions(); + static readonly standardFunctions: ReadonlyMap = + ExpressionFunctions.getStandardFunctions(); /** * @private diff --git a/libraries/adaptive-expressions/src/expressionProperties/expressionProperty.ts b/libraries/adaptive-expressions/src/expressionProperties/expressionProperty.ts index 47dfbc8900..2f3aaebd63 100644 --- a/libraries/adaptive-expressions/src/expressionProperties/expressionProperty.ts +++ b/libraries/adaptive-expressions/src/expressionProperties/expressionProperty.ts @@ -92,7 +92,6 @@ export class ExpressionProperty { * @param data Data to use for expression binding. * @returns The value. */ - // eslint-disable-next-line @typescript-eslint/ban-types getValue(data: object): T { const { value, error } = this.tryGetValue(data); if (error) { @@ -108,7 +107,6 @@ export class ExpressionProperty { * @param data Data to use for expression binding. * @returns the value or an error. */ - // eslint-disable-next-line @typescript-eslint/ban-types tryGetValue(data: object): { value: T; error: Error } { if (!this.expression && this.expressionText) { try { diff --git a/libraries/adaptive-expressions/src/expressionProperties/intExpression.ts b/libraries/adaptive-expressions/src/expressionProperties/intExpression.ts index d73985d327..8a90a80359 100644 --- a/libraries/adaptive-expressions/src/expressionProperties/intExpression.ts +++ b/libraries/adaptive-expressions/src/expressionProperties/intExpression.ts @@ -31,7 +31,6 @@ export class IntExpression extends ExpressionProperty { * @param data Data to use for expression binding. * @returns Value of int number */ - // eslint-disable-next-line @typescript-eslint/ban-types tryGetValue(data: object): { value: number; error: Error } { const result = super.tryGetValue(data); if (FunctionUtils.isNumber(result.value)) { diff --git a/libraries/adaptive-expressions/src/functionTable.ts b/libraries/adaptive-expressions/src/functionTable.ts index ee789e45a3..553d37073d 100644 --- a/libraries/adaptive-expressions/src/functionTable.ts +++ b/libraries/adaptive-expressions/src/functionTable.ts @@ -25,7 +25,7 @@ export class FunctionTable implements Map { */ keys(): MapIterator { const keysOfAllFunctions = Array.from(ExpressionFunctions.standardFunctions.keys()).concat( - Array.from(this.customFunctions.keys()) + Array.from(this.customFunctions.keys()), ); return keysOfAllFunctions[Symbol.iterator](); } @@ -37,7 +37,7 @@ export class FunctionTable implements Map { */ values(): MapIterator { const valuesOfAllFunctions = Array.from(ExpressionFunctions.standardFunctions.values()).concat( - Array.from(this.customFunctions.values()) + Array.from(this.customFunctions.values()), ); return valuesOfAllFunctions[Symbol.iterator](); } @@ -106,7 +106,7 @@ export class FunctionTable implements Map { */ add( param1: { key: string; value: ExpressionEvaluator } | string, - param2?: ExpressionEvaluator | customFunction + param2?: ExpressionEvaluator | customFunction, ): void { if (arguments.length === 1) { if (param1 instanceof Object) { @@ -159,7 +159,7 @@ export class FunctionTable implements Map { */ forEach( _callbackfn: (value: ExpressionEvaluator, key: string, map: Map) => void, - _thisArg?: any + _thisArg?: any, ): void { throw Error('forEach function not implemented'); } diff --git a/libraries/adaptive-expressions/src/functionUtils.internal.ts b/libraries/adaptive-expressions/src/functionUtils.internal.ts index 9c713941b1..df9acbaf6d 100644 --- a/libraries/adaptive-expressions/src/functionUtils.internal.ts +++ b/libraries/adaptive-expressions/src/functionUtils.internal.ts @@ -16,8 +16,8 @@ import { Options } from './options'; import { EvaluateExpressionDelegate, ValueWithError } from './expressionEvaluator'; import { MemoryInterface, SimpleObjectMemory, StackedMemory } from './memory'; import { TimexProperty } from '@microsoft/recognizers-text-data-types-timex-expression'; -import bigInt = require('big-integer'); -import util = require('util'); +import bigInt from 'big-integer'; +import util from 'util'; /** * Utility functions only used internal @@ -185,7 +185,7 @@ export class InternalFunctionUtils { if (!error) { const unixMilliSec: number = dayjs(timeStamp).utc().valueOf(); result = this.UnixMilliSecondToTicksConstant.add( - bigInt(unixMilliSec).times(this.MillisecondToTickConstant) + bigInt(unixMilliSec).times(this.MillisecondToTickConstant), ); } @@ -212,7 +212,7 @@ export class InternalFunctionUtils { value = instanceMap.get(property); if (value === undefined) { const prop: string = Array.from(instanceMap.keys()).find( - (k: string): boolean => k.toLowerCase() === property.toLowerCase() + (k: string): boolean => k.toLowerCase() === property.toLowerCase(), ); if (prop !== undefined) { value = instanceMap.get(prop); @@ -220,7 +220,7 @@ export class InternalFunctionUtils { } } else { const prop: string = Object.keys(instance).find( - (k: string): boolean => k.toLowerCase() === property.toLowerCase() + (k: string): boolean => k.toLowerCase() === property.toLowerCase(), ); if (prop !== undefined) { value = instance[prop]; @@ -334,7 +334,7 @@ export class InternalFunctionUtils { state: MemoryInterface, options: Options, list: T[], - callback: (currentItem: T, result: U, error: string) => boolean + callback: (currentItem: T, result: U, error: string) => boolean, ): void { const firstChild = expression.children[1].children[0]; if (!(firstChild instanceof Constant) || typeof firstChild.value !== 'string') { diff --git a/libraries/adaptive-expressions/src/functionUtils.ts b/libraries/adaptive-expressions/src/functionUtils.ts index c2a6090652..ffd4bd4f31 100644 --- a/libraries/adaptive-expressions/src/functionUtils.ts +++ b/libraries/adaptive-expressions/src/functionUtils.ts @@ -47,7 +47,7 @@ export class FunctionUtils { expression: Expression, minArity: number, maxArity: number, - returnType: ReturnType = ReturnType.Object + returnType: ReturnType = ReturnType.Object, ): void { if (expression.children.length < minArity) { throw new Error(`${expression} should have at least ${minArity} children.`); @@ -82,7 +82,7 @@ export class FunctionUtils { ? `${expression} should have ${types.length} children.` : `${expression} should have between ${types.length} and ${ types.length + optional.length - } children.` + } children.`, ); } @@ -494,7 +494,7 @@ export class FunctionUtils { expression: Expression, state: MemoryInterface, options: Options, - verify?: VerifyExpression + verify?: VerifyExpression, ): { args: any[]; error: string } { const args: any[] = []; let value: any; @@ -551,7 +551,7 @@ export class FunctionUtils { */ static applyWithError( func: (arg0: any[]) => ValueWithError, - verify?: VerifyExpression + verify?: VerifyExpression, ): EvaluateExpressionDelegate { return (expression: Expression, state: MemoryInterface, options: Options): ValueWithError => { let value: any; @@ -578,7 +578,7 @@ export class FunctionUtils { */ static applyWithOptionsAndError( func: (arg0: unknown[], options: Options) => { value: unknown; error: string }, - verify?: VerifyExpression + verify?: VerifyExpression, ): EvaluateExpressionDelegate { return (expression: Expression, state: MemoryInterface, options: Options): ValueWithError => { let value: unknown; @@ -605,7 +605,7 @@ export class FunctionUtils { */ static applyWithOptions( func: (arg0: unknown[], options: Options) => unknown, - verify?: VerifyExpression + verify?: VerifyExpression, ): EvaluateExpressionDelegate { return (expression: Expression, state: MemoryInterface, options: Options): ValueWithError => { let value: unknown; @@ -702,7 +702,7 @@ export class FunctionUtils { args: unknown[], maxArgsLength: number, format: string, - locale = 'en-us' + locale = 'en-us', ): { format: string; locale: string } { if (maxArgsLength >= 2) { if (args.length === maxArgsLength) { @@ -757,7 +757,7 @@ export class FunctionUtils { static tryAccumulatePath( expression: Expression, state: MemoryInterface, - options: Options + options: Options, ): { path: string; left: any; error: string } { let path = ''; let left = expression; diff --git a/libraries/adaptive-expressions/src/memory/simpleObjectMemory.ts b/libraries/adaptive-expressions/src/memory/simpleObjectMemory.ts index 22922ac14d..00b3ca3b46 100644 --- a/libraries/adaptive-expressions/src/memory/simpleObjectMemory.ts +++ b/libraries/adaptive-expressions/src/memory/simpleObjectMemory.ts @@ -184,7 +184,7 @@ export class SimpleObjectMemory implements MemoryInterface { */ private getCircularReplacer(): any { const seen = new WeakSet(); - // eslint-disable-next-line @typescript-eslint/ban-types + return (_key: any, value: object): any => { if (typeof value === 'object' && value) { if (seen.has(value)) { diff --git a/libraries/adaptive-expressions/src/parser/expressionParser.ts b/libraries/adaptive-expressions/src/parser/expressionParser.ts index e93fc7458b..42d2a35654 100644 --- a/libraries/adaptive-expressions/src/parser/expressionParser.ts +++ b/libraries/adaptive-expressions/src/parser/expressionParser.ts @@ -1,4 +1,3 @@ -/* eslint-disable security/detect-object-injection */ /** * @module adaptive-expressions */ @@ -31,7 +30,8 @@ export class ExpressionParser implements ExpressionParserInterface { private readonly ExpressionTransformer = class extends AbstractParseTreeVisitor - implements ExpressionAntlrParserVisitor { + implements ExpressionAntlrParserVisitor + { private readonly escapeRegex: RegExp = new RegExp(/\\[^\r\n]?/g); private readonly _lookupFunction: EvaluatorLookup = undefined; constructor(lookup: EvaluatorLookup) { @@ -162,7 +162,7 @@ export class ExpressionParser implements ExpressionParserInterface { ExpressionType.SetProperty, expr, new Constant(key), - this.visit(kvPair.expression()) + this.visit(kvPair.expression()), ); } } @@ -200,7 +200,7 @@ export class ExpressionParser implements ExpressionParserInterface { private readonly makeExpression = (functionType: string, ...children: Expression[]): Expression => { if (!this._lookupFunction(functionType)) { throw new Error( - `${functionType} does not have an evaluator, it's not a built-in function or a custom function.` + `${functionType} does not have an evaluator, it's not a built-in function or a custom function.`, ); } @@ -217,7 +217,7 @@ export class ExpressionParser implements ExpressionParserInterface { if (child instanceof ep.LambdaContext) { const evalParam = this.makeExpression( ExpressionType.Accessor, - new Constant(child.IDENTIFIER().text) + new Constant(child.IDENTIFIER().text), ); const evalFun = this.visit(child.expression()); result.push(evalParam); @@ -313,7 +313,7 @@ export class ExpressionParser implements ExpressionParserInterface { return new Constant(''); } else { return new this.ExpressionTransformer(this.EvaluatorLookup).transform( - ExpressionParser.antlrParse(expression) + ExpressionParser.antlrParse(expression), ); } } diff --git a/libraries/adaptive-expressions/src/parser/parseErrorListener.ts b/libraries/adaptive-expressions/src/parser/parseErrorListener.ts index 3e71055f04..28d2d16f0d 100644 --- a/libraries/adaptive-expressions/src/parser/parseErrorListener.ts +++ b/libraries/adaptive-expressions/src/parser/parseErrorListener.ts @@ -30,7 +30,7 @@ export class ParseErrorListener implements ANTLRErrorListener { line: number, charPositionInLine: number, _msg: string, - _e: RecognitionException | undefined + _e: RecognitionException | undefined, ): void { const syntaxErrorMessage = 'Invalid expression format.'; throw Error(`syntax error at line ${line}:${charPositionInLine} ${syntaxErrorMessage}`); diff --git a/libraries/adaptive-expressions/src/regexErrorListener.ts b/libraries/adaptive-expressions/src/regexErrorListener.ts index 2e3fba4bc0..5775e63507 100644 --- a/libraries/adaptive-expressions/src/regexErrorListener.ts +++ b/libraries/adaptive-expressions/src/regexErrorListener.ts @@ -30,7 +30,7 @@ export class RegexErrorListener implements ANTLRErrorListener { _line: number, _charPositionInLine: number, _msg: string, - _e: RecognitionException | undefined + _e: RecognitionException | undefined, ): void { throw Error('Regular expression is invalid.'); } diff --git a/libraries/adaptive-expressions/src/triggerTrees/clause.ts b/libraries/adaptive-expressions/src/triggerTrees/clause.ts index acde1e7545..f8edca523e 100644 --- a/libraries/adaptive-expressions/src/triggerTrees/clause.ts +++ b/libraries/adaptive-expressions/src/triggerTrees/clause.ts @@ -104,7 +104,7 @@ export class Clause extends Expression { let longerCount = longer.children.length; let swapped = false; if (longerCount < shorterCount) { - longer = this; + longer = this as Clause; shorter = other; const tmp = longerCount; longerCount = shorterCount; @@ -219,7 +219,7 @@ export class Clause extends Expression { private _bindingRelationship( soFar: RelationshipType, shorterClause: Clause, - longerClause: Clause + longerClause: Clause, ): RelationshipType { if (soFar === RelationshipType.equal) { let swapped = false; diff --git a/libraries/adaptive-expressions/src/triggerTrees/node.ts b/libraries/adaptive-expressions/src/triggerTrees/node.ts index 2135bc8b96..49f020d837 100644 --- a/libraries/adaptive-expressions/src/triggerTrees/node.ts +++ b/libraries/adaptive-expressions/src/triggerTrees/node.ts @@ -147,7 +147,7 @@ export class Node { // Ensure action is not already there const found = this._allTriggers.find( - (existing) => trigger.action != undefined && trigger.action === existing.action + (existing) => trigger.action != undefined && trigger.action === existing.action, ) !== undefined; op = Operation.found; if (!found) { diff --git a/libraries/adaptive-expressions/src/triggerTrees/quantifier.ts b/libraries/adaptive-expressions/src/triggerTrees/quantifier.ts index cb6d1cecf6..2883530ec3 100644 --- a/libraries/adaptive-expressions/src/triggerTrees/quantifier.ts +++ b/libraries/adaptive-expressions/src/triggerTrees/quantifier.ts @@ -32,7 +32,11 @@ export class Quantifier { * @param type Type of quantifier. * @param bindings Possible bindings for variable. */ - constructor(readonly variable: string, readonly type: QuantifierType, readonly bindings: string[]) {} + constructor( + readonly variable: string, + readonly type: QuantifierType, + readonly bindings: string[], + ) {} /** * @returns A string that represents the quantifier. diff --git a/libraries/adaptive-expressions/src/triggerTrees/trigger.ts b/libraries/adaptive-expressions/src/triggerTrees/trigger.ts index 0e005090b3..bdfbb718f7 100644 --- a/libraries/adaptive-expressions/src/triggerTrees/trigger.ts +++ b/libraries/adaptive-expressions/src/triggerTrees/trigger.ts @@ -39,10 +39,10 @@ const pushDownNot = (expression: Expression, inNot = false): Expression => { ? ExpressionType.Or : ExpressionType.And : inNot - ? ExpressionType.And - : ExpressionType.Or, + ? ExpressionType.And + : ExpressionType.Or, undefined, - ...children + ...children, ); } break; @@ -58,7 +58,7 @@ const pushDownNot = (expression: Expression, inNot = false): Expression => { newExpr = Expression.makeExpression( undefined, negation, - ...expression.children.map((child) => pushDownNot(child, true)) + ...expression.children.map((child) => pushDownNot(child, true)), ); } else { // Replace with negation and stop @@ -391,7 +391,7 @@ export class Trigger { const { expression: newPredicate, changed } = this._substituteVariable( quantifier.variable, binding, - predicate + predicate, ); children.push(newPredicate); if (!changed) { @@ -423,7 +423,7 @@ export class Trigger { const { expression: newPredicate, changed: predicateChanged } = this._substituteVariable( quantifier.variable, binding, - predicate + predicate, ); changed = changed || predicateChanged; children.push(newPredicate); @@ -463,7 +463,7 @@ export class Trigger { private _substituteVariable( variable: string, binding: string, - expression: Expression + expression: Expression, ): { expression: Expression; changed: boolean } { let newExpr = expression; let changed = false; @@ -483,7 +483,7 @@ export class Trigger { const { expression: childExpr, changed: childChanged } = this._substituteVariable( variable, binding, - child + child, ); children.push(childExpr); changed = changed || childChanged; diff --git a/libraries/adaptive-expressions/tests/badExpression.test.js b/libraries/adaptive-expressions/tests/badExpression.test.js index 7754c5858b..b9f0f029e7 100644 --- a/libraries/adaptive-expressions/tests/badExpression.test.js +++ b/libraries/adaptive-expressions/tests/badExpression.test.js @@ -546,7 +546,7 @@ describe('expression functional test', function () { assert.throws( () => parser.parse(invalidExpression), /syntax error at line [0-9]+:[0-9]+ Invalid expression format./, - 'Error message not match.' + 'Error message not match.', ); }); }); diff --git a/libraries/adaptive-expressions/tests/expressionParser.test.js b/libraries/adaptive-expressions/tests/expressionParser.test.js index 2822ab4ffa..dcce75dce5 100644 --- a/libraries/adaptive-expressions/tests/expressionParser.test.js +++ b/libraries/adaptive-expressions/tests/expressionParser.test.js @@ -1,4 +1,3 @@ -/* eslint-disable security/detect-object-injection */ const assert = require('assert'); const bigInt = require('big-integer'); const { Expression, SimpleObjectMemory, FunctionUtils, Options, NumericEvaluator, StackedMemory } = require('../lib'); @@ -441,50 +440,8 @@ const testCases = [ [ 'dataUriToBinary(dataUri(hello))', new Uint8Array([ - 100, - 97, - 116, - 97, - 58, - 116, - 101, - 120, - 116, - 47, - 112, - 108, - 97, - 105, - 110, - 59, - 99, - 104, - 97, - 114, - 115, - 101, - 116, - 61, - 117, - 116, - 102, - 45, - 56, - 59, - 98, - 97, - 115, - 101, - 54, - 52, - 44, - 97, - 71, - 86, - 115, - 98, - 71, - 56, + 100, 97, 116, 97, 58, 116, 101, 120, 116, 47, 112, 108, 97, 105, 110, 59, 99, 104, 97, 114, 115, + 101, 116, 61, 117, 116, 102, 45, 56, 59, 98, 97, 115, 101, 54, 52, 44, 97, 71, 86, 115, 98, 71, 56, 61, ]), ], @@ -1088,8 +1045,7 @@ const scope = { subTitle: 'Dialog Sub Title', }, doubleNestedItems: [[{ x: 1 }, { x: 2 }], [{ x: 3 }]], - xmlStr: - " Gala apple 20 Honeycrisp apple 10 ", + xmlStr: " Gala apple 20 Honeycrisp apple 10 ", callStack: [ { x: 3, @@ -1291,7 +1247,7 @@ const assertObjectEquals = (actual, expected, input) => { assert.strictEqual( parseFloat(actual.toString()), parseFloat(expected.toString()), - `Numbers don't match. ${debugMessage}` + `Numbers don't match. ${debugMessage}`, ); } else if (Array.isArray(actual) && Array.isArray(expected)) { assert.strictEqual(actual.length, expected.length); diff --git a/libraries/adaptive-expressions/tests/triggerTree.test.js b/libraries/adaptive-expressions/tests/triggerTree.test.js index 1faa0c62b8..2f4f483101 100644 --- a/libraries/adaptive-expressions/tests/triggerTree.test.js +++ b/libraries/adaptive-expressions/tests/triggerTree.test.js @@ -1,4 +1,3 @@ -/* eslint-disable security/detect-object-injection */ const { Constant, Expression, @@ -28,7 +27,7 @@ class Generator { expressions.push( this.randomWeighted([1.0, 1.0]) ? this.generateSimpleComparison(name) - : this.generateHasValueComparison(name) + : this.generateHasValueComparison(name), ); } return expressions; @@ -105,7 +104,7 @@ class Generator { let optional = Expression.makeExpression( undefined, Expression.lookup(ExpressionType.Optional), - predicate.expression + predicate.expression, ); if (Math.random() < 0.25) { optional = Expression.notExpression(optional); @@ -237,7 +236,7 @@ class Generator { type, undefined, Expression.makeExpression(ExpressionType.Accessor, undefined, new Constant(name)), - new Constant(this.adjustIntValue(value, type)) + new Constant(this.adjustIntValue(value, type)), ); break; case 1: @@ -246,7 +245,7 @@ class Generator { type, undefined, Expression.makeExpression(ExpressionType.Accessor, undefined, new Constant(name)), - new Constant(this.adjustDoubleValue(value, type)) + new Constant(this.adjustDoubleValue(value, type)), ); break; } @@ -266,7 +265,7 @@ class Generator { expression = Expression.makeExpression( ExpressionType.Exists, undefined, - Expression.makeExpression(ExpressionType.Accessor, undefined, new Constant(name)) + Expression.makeExpression(ExpressionType.Accessor, undefined, new Constant(name)), ); value = Math.floor(Math.random() * 2147483647); break; @@ -274,7 +273,7 @@ class Generator { expression = Expression.makeExpression( ExpressionType.Exists, undefined, - Expression.makeExpression(ExpressionType.Accessor, undefined, new Constant(name)) + Expression.makeExpression(ExpressionType.Accessor, undefined, new Constant(name)), ); value = Math.random(); break; @@ -283,7 +282,7 @@ class Generator { ExpressionType.NotEqual, undefined, Expression.makeExpression(ExpressionType.Accessor, undefined, new Constant(name)), - new Constant(null) + new Constant(null), ); value = this.randomString(5); break; @@ -513,6 +512,7 @@ describe('TriggerTree', function () { assert.strictEqual(matches[1].action, 3); }); + //eslint-disable-next-line mocha/no-skipped-tests it.skip('Test Tree', function () { const numPredicates = 50; const numSingletons = 25; @@ -586,7 +586,7 @@ describe('TriggerTree', function () { assert.strictEqual( tree.totalTriggers, - numSingletons + numConjunctions + numDisjunctions + numOptionals + numQuantifiers + numSingletons + numConjunctions + numDisjunctions + numOptionals + numQuantifiers, ); all.push(...quantified); @@ -597,7 +597,7 @@ describe('TriggerTree', function () { assert.strictEqual( tree.totalTriggers, - numSingletons + numConjunctions + numDisjunctions + numOptionals + numQuantifiers + numNots + numSingletons + numConjunctions + numDisjunctions + numOptionals + numQuantifiers + numNots, ); all.push(...nots); From bb2bf0fa1a27a500a9af963d9a9541414b73972f Mon Sep 17 00:00:00 2001 From: Jhonatan Sandoval Velasco <122501764+JhontSouth@users.noreply.github.com> Date: Mon, 6 Jan 2025 10:06:54 -0500 Subject: [PATCH 17/22] remove eslint configuration (#4835) --- libraries/adaptive-expressions-ie11/eslint.config.cjs | 11 ----------- libraries/adaptive-expressions-ie11/package.json | 2 +- 2 files changed, 1 insertion(+), 12 deletions(-) delete mode 100644 libraries/adaptive-expressions-ie11/eslint.config.cjs diff --git a/libraries/adaptive-expressions-ie11/eslint.config.cjs b/libraries/adaptive-expressions-ie11/eslint.config.cjs deleted file mode 100644 index c56fd90ec6..0000000000 --- a/libraries/adaptive-expressions-ie11/eslint.config.cjs +++ /dev/null @@ -1,11 +0,0 @@ -const onlyWarn = require("eslint-plugin-only-warn"); -const sharedConfig = require("../../eslint.config.cjs") - -module.exports = [ - ...sharedConfig, - { - plugins: { - "only-warn": onlyWarn, - }, - } -] diff --git a/libraries/adaptive-expressions-ie11/package.json b/libraries/adaptive-expressions-ie11/package.json index 56bb20da87..a4e20fc516 100644 --- a/libraries/adaptive-expressions-ie11/package.json +++ b/libraries/adaptive-expressions-ie11/package.json @@ -25,7 +25,7 @@ "build": "npm-run-all clean build:browser", "build:browser": "tsup --config ../../tsup/browser.config.ts --define.outfile dist/index.js --dts", "clean": "rimraf dist", - "lint": "eslint ." + "lint": "eslint . --config ../../eslint.config.cjs" }, "files": [ "dist" From 050ee9fea001984a11dc25618e8cf8e92b04610a Mon Sep 17 00:00:00 2001 From: Jhonatan Sandoval Velasco <122501764+JhontSouth@users.noreply.github.com> Date: Mon, 6 Jan 2025 10:07:12 -0500 Subject: [PATCH 18/22] fix eslint issues in botframework-schema (#4836) --- .../botframework-schema/eslint.config.cjs | 10 -- libraries/botframework-schema/package.json | 5 +- .../botframework-schema/src/activityEx.ts | 8 +- .../src/activityInterfaces.ts | 10 +- libraries/botframework-schema/src/index.ts | 54 +++++------ .../cardView/cardSearchBoxComponent.ts | 3 +- .../sharepoint/cardView/cardViewParameters.ts | 12 +-- .../sharepoint/propertyPaneFieldProperties.ts | 3 +- .../propertyPaneGroupOrConditionalGroup.ts | 3 +- .../src/teams/extension/index.ts | 3 - .../botframework-schema/src/teams/index.ts | 94 +++++-------------- .../tests/speechConstants.test.js | 2 +- 12 files changed, 72 insertions(+), 135 deletions(-) delete mode 100644 libraries/botframework-schema/eslint.config.cjs diff --git a/libraries/botframework-schema/eslint.config.cjs b/libraries/botframework-schema/eslint.config.cjs deleted file mode 100644 index 63647b52cc..0000000000 --- a/libraries/botframework-schema/eslint.config.cjs +++ /dev/null @@ -1,10 +0,0 @@ -const onlyWarn = require("eslint-plugin-only-warn"); -const sharedConfig = require("../../eslint.config.cjs") - -module.exports = [ - ...sharedConfig, - { - plugins: { - "only-warn": onlyWarn, - }, - }]; diff --git a/libraries/botframework-schema/package.json b/libraries/botframework-schema/package.json index a97a0f9c48..38a847802c 100644 --- a/libraries/botframework-schema/package.json +++ b/libraries/botframework-schema/package.json @@ -29,8 +29,7 @@ "dependencies": { "uuid": "^10.0.0", "zod": "^3.23.8", - "adaptivecards": "1.2.3", - "eslint-plugin-only-warn": "^1.1.0" + "adaptivecards": "1.2.3" }, "scripts": { "build": "tsc -b", @@ -38,7 +37,7 @@ "build:rollup": "yarn clean && yarn build && api-extractor run --verbose --local", "clean": "rimraf _ts3.4 lib tsconfig.tsbuildinfo", "depcheck": "depcheck --config ../../.depcheckrc", - "lint": "eslint .", + "lint": "eslint . --config ../../eslint.config.cjs", "test": "yarn build && nyc mocha tests/", "test:compat": "api-extractor run --verbose" }, diff --git a/libraries/botframework-schema/src/activityEx.ts b/libraries/botframework-schema/src/activityEx.ts index 6ba4cd87b9..75012142cb 100644 --- a/libraries/botframework-schema/src/activityEx.ts +++ b/libraries/botframework-schema/src/activityEx.ts @@ -122,7 +122,7 @@ export namespace ActivityEx { name: string, valueType?: string, value?: unknown, - label?: string + label?: string, ): Partial { return { type: ActivityTypes.Trace, @@ -188,7 +188,7 @@ export namespace ActivityEx { name: string, value?: unknown, valueType?: string, - label?: string + label?: string, ): ITraceActivity { return { type: ActivityTypes.Trace, @@ -229,7 +229,7 @@ export namespace ActivityEx { * @returns This activity as a contact relation update activity; or null. */ export function asContactRelationUpdateActivity( - source: Partial + source: Partial, ): Partial { return isActivity(source, ActivityTypes.ContactRelationUpdate) ? source : null; } @@ -371,7 +371,7 @@ export namespace ActivityEx { * @returns This activity as a command result activity; or null. */ export function asCommandResultActivity( - source: Partial + source: Partial, ): Partial> { return isActivity(source, ActivityTypes.CommandResult) ? source : null; } diff --git a/libraries/botframework-schema/src/activityInterfaces.ts b/libraries/botframework-schema/src/activityInterfaces.ts index afa6ee70a5..2677b0010a 100644 --- a/libraries/botframework-schema/src/activityInterfaces.ts +++ b/libraries/botframework-schema/src/activityInterfaces.ts @@ -82,7 +82,7 @@ export interface IActivity { /** * Contains channel-specific content. */ - channelData?: any; // eslint-disable-line @typescript-eslint/no-explicit-any + channelData?: any; } export interface IConversationUpdateActivity extends IActivity { @@ -196,7 +196,7 @@ export interface IMessageActivity extends IActivity { /** * A value that is associated with the activity. */ - value?: any; // eslint-disable-line @typescript-eslint/no-explicit-any + value?: any; } export interface IMessageUpdateActivity extends IMessageActivity, IActivity {} @@ -247,7 +247,7 @@ export interface IEventActivity extends IActivity { /** * A value that is associated with the activity. */ - value?: any; // eslint-disable-line @typescript-eslint/no-explicit-any + value?: any; /** * A reference to another conversation or activity. @@ -264,7 +264,7 @@ export interface IInvokeActivity extends IActivity { /** * A value that is associated with the activity. */ - value?: any; // eslint-disable-line @typescript-eslint/no-explicit-any + value?: any; /** * A reference to another conversation or activity. @@ -291,7 +291,7 @@ export interface ITraceActivity extends IActivity { /** * A value that is associated with the activity. */ - value?: any; // eslint-disable-line @typescript-eslint/no-explicit-any + value?: any; /** * A reference to another conversation or activity. diff --git a/libraries/botframework-schema/src/index.ts b/libraries/botframework-schema/src/index.ts index 9198b6e170..e7b0486810 100644 --- a/libraries/botframework-schema/src/index.ts +++ b/libraries/botframework-schema/src/index.ts @@ -102,7 +102,7 @@ export interface InnerHttpError { /** * Body from failed request */ - body: any; // eslint-disable-line @typescript-eslint/no-explicit-any + body: any; } /** @@ -159,7 +159,7 @@ export interface ChannelAccount { /** * Custom properties object (optional) */ - properties?: any; // eslint-disable-line @typescript-eslint/no-explicit-any + properties?: any; } const channelAccount = z.object({ @@ -221,7 +221,7 @@ export interface ConversationAccount { /** * Custom properties object (optional) */ - properties?: any; // eslint-disable-line @typescript-eslint/no-explicit-any + properties?: any; } const conversationAccount = z.object({ @@ -306,11 +306,11 @@ export interface CardAction { /** * Supplementary parameter for action. Content of this property depends on the ActionType */ - value: any; // eslint-disable-line @typescript-eslint/no-explicit-any + value: any; /** * Channel-specific data associated with this action */ - channelData?: any; // eslint-disable-line @typescript-eslint/no-explicit-any + channelData?: any; /** * Alternate image text to be used in place of the `image` field */ @@ -391,7 +391,7 @@ export interface Attachment { /** * Embedded content */ - content?: any; // eslint-disable-line @typescript-eslint/no-explicit-any + content?: any; /** * (OPTIONAL) The name of the attachment */ @@ -435,7 +435,7 @@ export interface Entity { /** * Additional properties. */ - [key: string]: any; // eslint-disable-line @typescript-eslint/no-explicit-any + [key: string]: any; } const entity = z.record(z.unknown()).refine((val) => typeof val.type === 'string'); @@ -702,7 +702,7 @@ export interface Activity { /** * Contains channel-specific content. */ - channelData?: any; // eslint-disable-line @typescript-eslint/no-explicit-any + channelData?: any; /** * Indicates whether the recipient of a contactRelationUpdate was added or removed from the * sender's contact list. @@ -723,7 +723,7 @@ export interface Activity { /** * A value that is associated with the activity. */ - value?: any; // eslint-disable-line @typescript-eslint/no-explicit-any + value?: any; /** * The name of the operation associated with an invoke or event activity. */ @@ -877,7 +877,7 @@ export interface ConversationParameters { /** * Channel specific payload for creating the conversation */ - channelData: any; // eslint-disable-line @typescript-eslint/no-explicit-any + channelData: any; } /** @@ -1121,7 +1121,7 @@ export interface AnimationCard { /** * Supplementary parameter for this card */ - value: any; // eslint-disable-line @typescript-eslint/no-explicit-any + value: any; } /** @@ -1177,7 +1177,7 @@ export interface AudioCard { /** * Supplementary parameter for this card */ - value: any; // eslint-disable-line @typescript-eslint/no-explicit-any + value: any; } /** @@ -1263,7 +1263,7 @@ export interface MediaCard { /** * Supplementary parameter for this card */ - value: any; // eslint-disable-line @typescript-eslint/no-explicit-any + value: any; } /** @@ -1477,7 +1477,7 @@ export interface VideoCard { /** * Supplementary parameter for this card */ - value: any; // eslint-disable-line @typescript-eslint/no-explicit-any + value: any; } /** @@ -1531,15 +1531,15 @@ export interface Place { /** * Address of the place (may be `string` or complex object of type `PostalAddress`) */ - address: any; // eslint-disable-line @typescript-eslint/no-explicit-any + address: any; /** * Geo coordinates of the place (may be complex object of type `GeoCoordinates` or `GeoShape`) */ - geo: any; // eslint-disable-line @typescript-eslint/no-explicit-any + geo: any; /** * Map to the place (may be `string` (URL) or complex object of type `Map`) */ - hasMap: any; // eslint-disable-line @typescript-eslint/no-explicit-any + hasMap: any; /** * The type of the thing */ @@ -1571,7 +1571,7 @@ export interface MediaEventValue { /** * Callback parameter specified in the Value field of the MediaCard that originated this event */ - cardValue: any; // eslint-disable-line @typescript-eslint/no-explicit-any + cardValue: any; } /** @@ -1585,7 +1585,7 @@ export interface TokenRequest { /** * A collection of settings for the specific provider for this request */ - settings: { [propertyName: string]: any }; // eslint-disable-line @typescript-eslint/no-explicit-any + settings: { [propertyName: string]: any }; } /** @@ -1611,7 +1611,7 @@ export interface TokenResponse { /** * A collection of properties about this response, such as token polling parameters */ - properties?: { [propertyName: string]: any }; // eslint-disable-line @typescript-eslint/no-explicit-any + properties?: { [propertyName: string]: any }; } /** @@ -1779,7 +1779,7 @@ export interface PaymentDetailsModifier { * A JSON-serializable object that provides optional information that might be needed by the * supported payment methods */ - data: any; // eslint-disable-line @typescript-eslint/no-explicit-any + data: any; } /** @@ -1826,7 +1826,7 @@ export interface PaymentMethodData { * A JSON-serializable object that provides optional information that might be needed by the * supported payment methods */ - data: any; // eslint-disable-line @typescript-eslint/no-explicit-any + data: any; } /** @@ -1906,7 +1906,7 @@ export interface PaymentResponse { * A JSON-serializable object that provides a payment method specific message used by the * merchant to process the transaction and determine successful fund transfer */ - details: any; // eslint-disable-line @typescript-eslint/no-explicit-any + details: any; /** * If the requestShipping flag was set to true in the PaymentOptions passed to the PaymentRequest * constructor, then shippingAddress will be the full and final shipping address chosen by the @@ -2347,7 +2347,7 @@ export interface IStatusCodeError { * Defines the structure that arrives in the Activity.Value.Authentication for Invoke * activity with Name of 'adaptiveCard/action'. */ -// eslint-disable-next-line @typescript-eslint/no-empty-interface +// eslint-disable-next-line @typescript-eslint/no-empty-object-type export interface AdaptiveCardAuthentication extends TokenExchangeInvokeRequest { // No-op. This interface was accidentally created as a duplicate of TokenExchangeInvokeRequest but must remain for backwards-compatibility. } @@ -2439,7 +2439,7 @@ export interface SearchInvokeValue { * The type of the context field is object and is dependent on the kind field. * For search and searchAnswers, there is no defined context value. */ - context: any; // eslint-disable-line @typescript-eslint/no-explicit-any + context: any; /** * The dataset to be queried to get the choices. */ @@ -2464,7 +2464,7 @@ export interface SearchInvokeOptions { * Defines the structure that is returned as the result of an Invoke activity with * Name of 'application/search'. */ -// eslint-disable-next-line @typescript-eslint/no-empty-interface +// eslint-disable-next-line @typescript-eslint/no-empty-object-type export interface SearchInvokeResponse extends AdaptiveCardInvokeResponse {} /** @@ -2472,7 +2472,7 @@ export interface SearchInvokeResponse extends AdaptiveCardInvokeResponse {} * * This interface supports the framework and is not intended to be called directly for your code. */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any + export interface InvokeResponse { /** * The HTTP status code of the response. diff --git a/libraries/botframework-schema/src/sharepoint/cardView/cardSearchBoxComponent.ts b/libraries/botframework-schema/src/sharepoint/cardView/cardSearchBoxComponent.ts index e1894ed17e..fc84def720 100644 --- a/libraries/botframework-schema/src/sharepoint/cardView/cardSearchBoxComponent.ts +++ b/libraries/botframework-schema/src/sharepoint/cardView/cardSearchBoxComponent.ts @@ -7,7 +7,8 @@ import type { CardButtonBase } from './cardButtonBase'; /** * Search box button properties. */ -// eslint-disable-next-line @typescript-eslint/no-empty-interface + +// eslint-disable-next-line @typescript-eslint/no-empty-object-type export interface ICardSearchBoxButton extends CardButtonBase { // reserved for future. Not additional properties. } diff --git a/libraries/botframework-schema/src/sharepoint/cardView/cardViewParameters.ts b/libraries/botframework-schema/src/sharepoint/cardView/cardViewParameters.ts index 8de587613b..1e2cf25175 100644 --- a/libraries/botframework-schema/src/sharepoint/cardView/cardViewParameters.ts +++ b/libraries/botframework-schema/src/sharepoint/cardView/cardViewParameters.ts @@ -153,7 +153,7 @@ export type CardViewParameters = export function BasicCardView( cardBar: CardBarComponent, header: CardTextComponent, - footer?: CardViewFooterParameters + footer?: CardViewFooterParameters, ): TextCardViewParameters { return { cardViewType: 'text', @@ -182,7 +182,7 @@ export function PrimaryTextCardView( cardBar: CardBarComponent, header: CardTextComponent, body: CardTextComponent, - footer?: CardViewFooterParameters + footer?: CardViewFooterParameters, ): TextCardViewParameters { return { cardViewType: 'text', @@ -211,7 +211,7 @@ export function ImageCardView( cardBar: CardBarComponent, header: CardTextComponent, image: CardImage, - footer?: CardViewFooterParameters + footer?: CardViewFooterParameters, ): TextCardViewParameters { return { cardViewType: 'text', @@ -242,7 +242,7 @@ export function TextInputCardView( cardBar: CardBarComponent, header: CardTextComponent, body: CardTextInputComponent, - footer?: CardViewActionsFooterParameters + footer?: CardViewActionsFooterParameters, ): TextInputCardViewParameters { return { cardViewType: 'textInput', @@ -271,7 +271,7 @@ export function SearchCardView( cardBar: CardBarComponent, header: CardTextComponent, body: CardSearchBoxComponent, - footer: CardSearchFooterComponent + footer: CardSearchFooterComponent, ): SearchCardViewParameters { return { cardViewType: 'search', @@ -301,7 +301,7 @@ export function SignInCardView( cardBar: CardBarComponent, header: CardTextComponent, body: CardTextComponent, - footer: CardButtonComponent + footer: CardButtonComponent, ): SignInCardViewParameters { return { cardViewType: 'signIn', diff --git a/libraries/botframework-schema/src/sharepoint/propertyPaneFieldProperties.ts b/libraries/botframework-schema/src/sharepoint/propertyPaneFieldProperties.ts index 62b8be7c0f..799fff8880 100644 --- a/libraries/botframework-schema/src/sharepoint/propertyPaneFieldProperties.ts +++ b/libraries/botframework-schema/src/sharepoint/propertyPaneFieldProperties.ts @@ -4,7 +4,8 @@ /** * SharePoint base property pane field properties */ -// eslint-disable-next-line @typescript-eslint/no-empty-interface + +// eslint-disable-next-line @typescript-eslint/no-empty-object-type export interface PropertyPaneFieldProperties { // keep this empty - used as base type in property group definition } diff --git a/libraries/botframework-schema/src/sharepoint/propertyPaneGroupOrConditionalGroup.ts b/libraries/botframework-schema/src/sharepoint/propertyPaneGroupOrConditionalGroup.ts index 723c891508..f7c5317ef2 100644 --- a/libraries/botframework-schema/src/sharepoint/propertyPaneGroupOrConditionalGroup.ts +++ b/libraries/botframework-schema/src/sharepoint/propertyPaneGroupOrConditionalGroup.ts @@ -1,7 +1,8 @@ /** * SharePoint property pane group or conditional group */ -// eslint-disable-next-line @typescript-eslint/no-empty-interface + +// eslint-disable-next-line @typescript-eslint/no-empty-object-type export interface PropertyPaneGroupOrConditionalGroup { // keep this empty - used as base type in property page definition } diff --git a/libraries/botframework-schema/src/teams/extension/index.ts b/libraries/botframework-schema/src/teams/extension/index.ts index 635e0bebce..b284b2a020 100644 --- a/libraries/botframework-schema/src/teams/extension/index.ts +++ b/libraries/botframework-schema/src/teams/extension/index.ts @@ -37,7 +37,6 @@ export type O365ConnectorCardActionType = 'ViewAction' | 'OpenUri' | 'HttpPOST' * @interface * An interface representing O365ConnectorCardActionBase. * O365 connector card action base - * */ export interface O365ConnectorCardActionBase { /** @@ -69,7 +68,6 @@ export type O365ConnectorCardInputType = 'textInput' | 'dateInput' | 'multichoic * @interface * An interface representing O365ConnectorCardInputBase. * O365 connector card input for ActionCard action - * */ export interface O365ConnectorCardInputBase { /** @@ -107,7 +105,6 @@ export type FileDownloadInfoAttachment = TeamsAttachment; * @interface * An interface representing MessageActionsPayloadBody. * Plaintext/HTML representation of the content of the message. - * */ export interface MessageActionsPayloadBody { /** diff --git a/libraries/botframework-schema/src/teams/index.ts b/libraries/botframework-schema/src/teams/index.ts index b1dc15c1c0..8c70cb6a6f 100644 --- a/libraries/botframework-schema/src/teams/index.ts +++ b/libraries/botframework-schema/src/teams/index.ts @@ -30,7 +30,6 @@ export type ConfigResponseConfig = BotConfigAuth | TaskModuleResponse; * @interface * An interface representing ChannelInfo. * A channel info object which decribes the channel. - * */ export interface ChannelInfo { /** @@ -69,7 +68,6 @@ export interface ConfigResponse { * @interface * An interface representing ConversationList. * List of channels under a team - * */ export interface ConversationList { /** @@ -82,7 +80,6 @@ export interface ConversationList { * @interface * An interface representing TeamDetails. * Details related to a team - * */ export interface TeamDetails { /** @@ -117,7 +114,6 @@ export interface TeamDetails { * @interface * An interface representing TeamInfo. * Describes a team - * */ export interface TeamInfo { /** @@ -138,7 +134,6 @@ export interface TeamInfo { * @interface * An interface representing NotificationInfo. * Specifies if a notification is to be sent for the mentions. - * */ export interface NotificationInfo { /** @@ -161,7 +156,6 @@ export interface NotificationInfo { * @interface * An interface representing TenantInfo. * Describes a tenant - * */ export interface TenantInfo { /** @@ -174,7 +168,6 @@ export interface TenantInfo { * @interface * An interface representing TeamsMeetingInfo. * Describes a meeting - * */ export interface TeamsMeetingInfo { /** @@ -187,7 +180,6 @@ export interface TeamsMeetingInfo { * @interface * An interface representing TeamsChannelData. * Channel data specific to messages received in Microsoft Teams - * */ export interface TeamsChannelData { /** @@ -234,7 +226,7 @@ export interface TeamsChannelData { * An interface representing TeamsChannelAccount. * Teams channel account detailing user Azure Active Directory details. * - * @extends ChannelAccount + * @augments ChannelAccount */ export interface TeamsChannelAccount extends ChannelAccount { /** @@ -302,7 +294,6 @@ export interface Meeting { * @interface * An interface representing TeamsMeetingParticipant. * Teams meeting participant detailing user Azure Active Directory details. - * */ export interface TeamsMeetingParticipant { /** @@ -334,7 +325,6 @@ export interface TeamsPagedMembersResult { * @interface * An interface representing O365ConnectorCardFact. * O365 connector card fact - * */ export interface O365ConnectorCardFact { /** @@ -351,7 +341,6 @@ export interface O365ConnectorCardFact { * @interface * An interface representing O365ConnectorCardImage. * O365 connector card image - * */ export interface O365ConnectorCardImage { /** @@ -368,7 +357,6 @@ export interface O365ConnectorCardImage { * @interface * An interface representing O365ConnectorCardSection. * O365 connector card section - * */ export interface O365ConnectorCardSection { /** @@ -426,7 +414,6 @@ export interface O365ConnectorCardSection { * @interface * An interface representing O365ConnectorCard. * O365 connector card - * */ export interface O365ConnectorCard { /** @@ -462,7 +449,7 @@ export interface O365ConnectorCard { * An interface representing O365ConnectorCardViewAction. * O365 connector card ViewAction action * - * @extends O365ConnectorCardActionBase + * @augments O365ConnectorCardActionBase */ export interface O365ConnectorCardViewAction extends O365ConnectorCardActionBase { /** @@ -476,7 +463,6 @@ export interface O365ConnectorCardViewAction extends O365ConnectorCardActionBase * @interface * An interface representing O365ConnectorCardOpenUriTarget. * O365 connector card OpenUri target - * */ export interface O365ConnectorCardOpenUriTarget { /** @@ -495,7 +481,7 @@ export interface O365ConnectorCardOpenUriTarget { * An interface representing O365ConnectorCardOpenUri. * O365 connector card OpenUri action * - * @extends O365ConnectorCardActionBase + * @augments O365ConnectorCardActionBase */ export interface O365ConnectorCardOpenUri extends O365ConnectorCardActionBase { /** @@ -509,7 +495,7 @@ export interface O365ConnectorCardOpenUri extends O365ConnectorCardActionBase { * An interface representing O365ConnectorCardHttpPOST. * O365 connector card HttpPOST action * - * @extends O365ConnectorCardActionBase + * @augments O365ConnectorCardActionBase */ export interface O365ConnectorCardHttpPOST extends O365ConnectorCardActionBase { /** @@ -523,7 +509,7 @@ export interface O365ConnectorCardHttpPOST extends O365ConnectorCardActionBase { * An interface representing O365ConnectorCardActionCard. * O365 connector card ActionCard action * - * @extends O365ConnectorCardActionBase + * @augments O365ConnectorCardActionBase */ export interface O365ConnectorCardActionCard extends O365ConnectorCardActionBase { /** @@ -546,7 +532,7 @@ export interface O365ConnectorCardActionCard extends O365ConnectorCardActionBase * An interface representing O365ConnectorCardTextInput. * O365 connector card text input * - * @extends O365ConnectorCardInputBase + * @augments O365ConnectorCardInputBase */ export interface O365ConnectorCardTextInput extends O365ConnectorCardInputBase { /** @@ -566,7 +552,7 @@ export interface O365ConnectorCardTextInput extends O365ConnectorCardInputBase { * An interface representing O365ConnectorCardDateInput. * O365 connector card date input * - * @extends O365ConnectorCardInputBase + * @augments O365ConnectorCardInputBase */ export interface O365ConnectorCardDateInput extends O365ConnectorCardInputBase { /** @@ -580,7 +566,6 @@ export interface O365ConnectorCardDateInput extends O365ConnectorCardInputBase { * @interface * An interface representing O365ConnectorCardMultichoiceInputChoice. * O365O365 connector card multiple choice input item - * */ export interface O365ConnectorCardMultichoiceInputChoice { /** @@ -598,7 +583,7 @@ export interface O365ConnectorCardMultichoiceInputChoice { * An interface representing O365ConnectorCardMultichoiceInput. * O365 connector card multiple choice input * - * @extends O365ConnectorCardInputBase + * @augments O365ConnectorCardInputBase */ export interface O365ConnectorCardMultichoiceInput extends O365ConnectorCardInputBase { /** @@ -623,7 +608,6 @@ export interface O365ConnectorCardMultichoiceInput extends O365ConnectorCardInpu * @interface * An interface representing O365ConnectorCardActionQuery. * O365 connector card HttpPOST invoke query - * */ export interface O365ConnectorCardActionQuery { /** @@ -642,7 +626,6 @@ export interface O365ConnectorCardActionQuery { * @interface * An interface representing SigninStateVerificationQuery. * Signin state (part of signin action auth flow) verification invoke query - * */ export interface SigninStateVerificationQuery { /** @@ -657,7 +640,6 @@ export interface SigninStateVerificationQuery { * @interface * An interface representing MessagingExtensionQueryOptions. * Messaging extension query options - * */ export interface MessagingExtensionQueryOptions { /** @@ -674,7 +656,6 @@ export interface MessagingExtensionQueryOptions { * @interface * An interface representing MessagingExtensionParameter. * Messaging extension query parameters - * */ export interface MessagingExtensionParameter { /** @@ -684,14 +665,13 @@ export interface MessagingExtensionParameter { /** * @member {any} [value] Value of the parameter */ - value?: any; // eslint-disable-line @typescript-eslint/no-explicit-any + value?: any; } /** * @interface * An interface representing MessagingExtensionQuery. * Messaging extension query - * */ export interface MessagingExtensionQuery { /** @@ -718,7 +698,6 @@ export interface MessagingExtensionQuery { * @interface * An interface representing MessageActionsPayloadUser. * Represents a user entity. - * */ export interface MessageActionsPayloadUser { /** @@ -741,7 +720,6 @@ export interface MessageActionsPayloadUser { * @interface * An interface representing MessageActionsPayloadApp. * Represents an application entity. - * */ export interface MessageActionsPayloadApp { /** @@ -765,7 +743,6 @@ export interface MessageActionsPayloadApp { * @interface * An interface representing MessageActionsPayloadConversation. * Represents a team or channel entity. - * */ export interface MessageActionsPayloadConversation { /** @@ -790,7 +767,6 @@ export interface MessageActionsPayloadConversation { * An interface representing MessageActionsPayloadFrom. * Represents a user, application, or conversation type that either sent or was * referenced in a message. - * */ export interface MessageActionsPayloadFrom { /** @@ -813,7 +789,6 @@ export interface MessageActionsPayloadFrom { * @interface * An interface representing MessageActionsPayloadAttachment. * Represents the attachment in a message. - * */ export interface MessageActionsPayloadAttachment { /** @@ -833,7 +808,7 @@ export interface MessageActionsPayloadAttachment { * @member {any} [content] The content of the attachment, in case of a code * snippet, email, or file. */ - content?: any; // eslint-disable-line @typescript-eslint/no-explicit-any + content?: any; /** * @member {string} [name] The plaintext display name of the attachment. */ @@ -849,7 +824,6 @@ export interface MessageActionsPayloadAttachment { * @interface * An interface representing MessageActionsPayloadMention. * Represents the entity that was mentioned in the message. - * */ export interface MessageActionsPayloadMention { /** @@ -872,7 +846,6 @@ export interface MessageActionsPayloadMention { * @interface * An interface representing MessageActionsPayloadReaction. * Represents the reaction of a user to a message. - * */ export interface MessageActionsPayloadReaction { /** @@ -898,7 +871,6 @@ export interface MessageActionsPayloadReaction { * An interface representing MessageActionsPayload. * Represents the individual message within a chat or channel where a message * actions is taken. - * */ export interface MessageActionsPayload { /** @@ -986,13 +958,12 @@ export interface MessageActionsPayload { * @interface * An interface representing TaskModuleRequest. * Task module invoke request value payload - * */ export interface TaskModuleRequest { /** * @member {any} [data] User input data. Free payload with key-value pairs. */ - data?: any; // eslint-disable-line @typescript-eslint/no-explicit-any + data?: any; /** * @member {TaskModuleRequestContext} [context] Current user context, i.e., * the current theme @@ -1009,7 +980,7 @@ export interface TaskModuleRequest { * An interface representing MessagingExtensionAction. * Messaging extension action * - * @extends TaskModuleRequest + * @augments TaskModuleRequest */ export interface MessagingExtensionAction extends TaskModuleRequest { /** @@ -1042,7 +1013,6 @@ export interface MessagingExtensionAction extends TaskModuleRequest { * @interface * An interface representing TaskModuleResponseBase. * Base class for Task Module responses - * */ export interface TaskModuleResponseBase { /** @@ -1057,7 +1027,7 @@ export interface TaskModuleResponseBase { * An interface representing MessagingExtensionAttachment. * Messaging extension attachment. * - * @extends Attachment + * @augments Attachment */ export interface MessagingExtensionAttachment extends Attachment { /** @@ -1070,7 +1040,6 @@ export interface MessagingExtensionAttachment extends Attachment { * @interface * An interface representing MessagingExtensionSuggestedAction. * Messaging extension Actions (Only when type is auth or config) - * */ export interface MessagingExtensionSuggestedAction { /** @@ -1083,7 +1052,6 @@ export interface MessagingExtensionSuggestedAction { * @interface * An interface representing MessagingExtensionResult. * Messaging extension result - * */ export interface MessagingExtensionResult { /** @@ -1135,7 +1103,6 @@ export interface CacheInfo { * @interface * An interface representing MessagingExtensionActionResponse. * Response of messaging extension action - * */ export interface MessagingExtensionActionResponse { /** @@ -1157,7 +1124,6 @@ export interface MessagingExtensionActionResponse { * @interface * An interface representing MessagingExtensionResponse. * Messaging extension response - * */ export interface MessagingExtensionResponse { /** @@ -1174,7 +1140,6 @@ export interface MessagingExtensionResponse { * @interface * An interface representing FileConsentCard. * File consent card attachment. - * */ export interface FileConsentCard { /** @@ -1190,20 +1155,19 @@ export interface FileConsentCard { * consented to upload. This is free flow schema and is sent back in Value * field of Activity. */ - acceptContext?: any; // eslint-disable-line @typescript-eslint/no-explicit-any + acceptContext?: any; /** * @member {any} [declineContext] Context sent back to the Bot if user * declined. This is free flow schema and is sent back in Value field of * Activity. */ - declineContext?: any; // eslint-disable-line @typescript-eslint/no-explicit-any + declineContext?: any; } /** * @interface * An interface representing FileDownloadInfo. * File download info attachment. - * */ export interface FileDownloadInfo { /** @@ -1221,14 +1185,13 @@ export interface FileDownloadInfo { /** * @member {any} [etag] ETag for the file. */ - etag?: any; // eslint-disable-line @typescript-eslint/no-explicit-any + etag?: any; } /** * @interface * An interface representing FileInfoCard. * File info card. - * */ export interface FileInfoCard { /** @@ -1242,14 +1205,13 @@ export interface FileInfoCard { /** * @member {any} [etag] ETag for the file. */ - etag?: any; // eslint-disable-line @typescript-eslint/no-explicit-any + etag?: any; } /** * @interface * An interface representing FileUploadInfo. * Information about the file to be uploaded. - * */ export interface FileUploadInfo { /** @@ -1280,7 +1242,6 @@ export interface FileUploadInfo { * An interface representing FileConsentCardResponse. * Represents the value of the invoke activity sent when the user acts on a * file consent card - * */ export interface FileConsentCardResponse { /** @@ -1291,7 +1252,7 @@ export interface FileConsentCardResponse { /** * @member {any} [context] The context associated with the action. */ - context?: any; // eslint-disable-line @typescript-eslint/no-explicit-any + context?: any; /** * @member {FileUploadInfo} [uploadInfo] If the user accepted the file, * contains information about the file to be uploaded. @@ -1313,7 +1274,6 @@ export interface TabContext { /** * @interface * Current TabRequest entity context, or 'tabEntityId'. - * */ export interface TabEntityContext { /** @@ -1325,7 +1285,6 @@ export interface TabEntityContext { /** * @interface * Invoke ('tab/fetch') request value payload. - * */ export interface TabRequest { /** @@ -1345,7 +1304,6 @@ export interface TabRequest { /** * @interface * Envelope for Card Tab Response Payload. - * */ export interface TabResponse { /** @@ -1357,7 +1315,6 @@ export interface TabResponse { /** * @interface * Envelope for cards for a Tab request. - * */ export interface TabResponseCard { /** @@ -1369,7 +1326,6 @@ export interface TabResponseCard { /** * @interface * Envelope for cards for a TabResponse. - * */ export interface TabResponseCards { /** @@ -1381,7 +1337,6 @@ export interface TabResponseCards { /** * @interface * Payload for Tab Response. - * */ export interface TabResponsePayload { /** @@ -1402,7 +1357,6 @@ export interface TabResponsePayload { /** * @interface * Invoke ('tab/submit') request value payload. - * */ export interface TabSubmit { /** @@ -1422,7 +1376,6 @@ export interface TabSubmit { /** * @interface * Invoke ('tab/submit') request value payload data. - * */ export interface TabSubmitData { /** @@ -1438,7 +1391,6 @@ export interface TabSubmitData { /** * @interface * Tab SuggestedActions (Only when type is 'auth' or 'silentAuth'). - * */ export interface TabSuggestedActions { /** @@ -1451,7 +1403,7 @@ export interface TabSuggestedActions { * @interface * Tab response to 'task/submit'. * - * @extends TaskModuleResponseBase + * @augments TaskModuleResponseBase */ export interface TaskModuleCardResponse extends TaskModuleResponseBase { /** @@ -1464,7 +1416,6 @@ export interface TaskModuleCardResponse extends TaskModuleResponseBase { * @interface * An interface representing TaskModuleTaskInfo. * Metadata for a Task Module. - * */ export interface TaskModuleTaskInfo { /** @@ -1509,7 +1460,7 @@ export interface TaskModuleTaskInfo { * An interface representing TaskModuleContinueResponse. * Task Module Response with continue action. * - * @extends TaskModuleResponseBase + * @augments TaskModuleResponseBase */ export interface TaskModuleContinueResponse extends TaskModuleResponseBase { /** @@ -1524,7 +1475,7 @@ export interface TaskModuleContinueResponse extends TaskModuleResponseBase { * An interface representing TaskModuleMessageResponse. * Task Module response with message action. * - * @extends TaskModuleResponseBase + * @augments TaskModuleResponseBase */ export interface TaskModuleMessageResponse extends TaskModuleResponseBase { /** @@ -1538,7 +1489,6 @@ export interface TaskModuleMessageResponse extends TaskModuleResponseBase { * @interface * An interface representing TaskModuleResponse. * Envelope for Task Module Response. - * */ export interface TaskModuleResponse { /** @@ -1556,7 +1506,6 @@ export interface TaskModuleResponse { * @interface * An interface representing TaskModuleRequestContext. * Current user context, i.e., the current theme - * */ export interface TaskModuleRequestContext { /** @@ -1569,7 +1518,6 @@ export interface TaskModuleRequestContext { * @interface * An interface representing AppBasedLinkQuery. * Invoke request body type for app-based link query. - * */ export interface AppBasedLinkQuery { /** diff --git a/libraries/botframework-schema/tests/speechConstants.test.js b/libraries/botframework-schema/tests/speechConstants.test.js index 385405b95b..86a45bbb2f 100644 --- a/libraries/botframework-schema/tests/speechConstants.test.js +++ b/libraries/botframework-schema/tests/speechConstants.test.js @@ -9,7 +9,7 @@ describe('SpeechConstants', function () { // Expected value derived from https://github.com/microsoft/botframework-obi/blame/5c2542115b110a1dae8e597473271abc8e67c30d/protocols/botframework-activity/botframework-activity.md#L353 strictEqual( SpeechConstants.EmptySpeakTag, - '' + '', ); }); }); From 9198d2a03f742c35972dce874745a9e4d35e8734 Mon Sep 17 00:00:00 2001 From: Jhonatan Sandoval Velasco <122501764+JhontSouth@users.noreply.github.com> Date: Mon, 6 Jan 2025 10:07:31 -0500 Subject: [PATCH 19/22] fix: ESLint issues in bobuilder-ai-orchestrator (#4837) * fix ESLint issues in botbuilder-ai-orchestrator * Merge branch 'southworks/update/eslint-packages' into southworks/fix/eslint-issues-botbuilder-ai-orchestrator * remove eslint config file * update yarn.lock --- .../eslint.config.cjs | 11 ------- .../botbuilder-ai-orchestrator/package.json | 3 +- .../src/orchestratorBotComponent.ts | 2 +- .../src/orchestratorRecognizer.ts | 33 ++++++++++--------- .../tests/mockResolver.js | 2 -- 5 files changed, 20 insertions(+), 31 deletions(-) delete mode 100644 libraries/botbuilder-ai-orchestrator/eslint.config.cjs diff --git a/libraries/botbuilder-ai-orchestrator/eslint.config.cjs b/libraries/botbuilder-ai-orchestrator/eslint.config.cjs deleted file mode 100644 index c56fd90ec6..0000000000 --- a/libraries/botbuilder-ai-orchestrator/eslint.config.cjs +++ /dev/null @@ -1,11 +0,0 @@ -const onlyWarn = require("eslint-plugin-only-warn"); -const sharedConfig = require("../../eslint.config.cjs") - -module.exports = [ - ...sharedConfig, - { - plugins: { - "only-warn": onlyWarn, - }, - } -] diff --git a/libraries/botbuilder-ai-orchestrator/package.json b/libraries/botbuilder-ai-orchestrator/package.json index c738a05935..38e21fb972 100644 --- a/libraries/botbuilder-ai-orchestrator/package.json +++ b/libraries/botbuilder-ai-orchestrator/package.json @@ -35,7 +35,6 @@ "botbuilder-dialogs-adaptive": "4.1.6", "botbuilder-dialogs-adaptive-runtime-core": "4.1.6", "botbuilder-dialogs-declarative": "4.1.6", - "eslint-plugin-only-warn": "^1.1.0", "@microsoft/orchestrator-core": "~4.15.1", "uuid": "^10.0.0" }, @@ -45,7 +44,7 @@ "build:rollup": "yarn clean && yarn build && api-extractor run --verbose --local", "clean": "rimraf _ts3.4 lib tsconfig.tsbuildinfo", "depcheck": "depcheck --config ../../.depcheckrc", - "lint": "eslint .", + "lint": "eslint . --config ../../eslint.config.cjs", "postbuild": "downlevel-dts lib _ts3.4/lib --checksum", "test": "yarn build && nyc mocha tests/", "test:compat": "api-extractor run --verbose" diff --git a/libraries/botbuilder-ai-orchestrator/src/orchestratorBotComponent.ts b/libraries/botbuilder-ai-orchestrator/src/orchestratorBotComponent.ts index ebde0032d9..be75f28dce 100644 --- a/libraries/botbuilder-ai-orchestrator/src/orchestratorBotComponent.ts +++ b/libraries/botbuilder-ai-orchestrator/src/orchestratorBotComponent.ts @@ -25,7 +25,7 @@ export class OrchestratorBotComponent extends BotComponent { }, ]; }, - }) + }), ); } } diff --git a/libraries/botbuilder-ai-orchestrator/src/orchestratorRecognizer.ts b/libraries/botbuilder-ai-orchestrator/src/orchestratorRecognizer.ts index e571ef22ee..4a204e9abd 100644 --- a/libraries/botbuilder-ai-orchestrator/src/orchestratorRecognizer.ts +++ b/libraries/botbuilder-ai-orchestrator/src/orchestratorRecognizer.ts @@ -24,7 +24,7 @@ import { AdaptiveRecognizer } from 'botbuilder-dialogs-adaptive'; import { Activity, RecognizerResult } from 'botbuilder-core'; import { Converter, ConverterFactory, DialogContext, Recognizer, RecognizerConfiguration } from 'botbuilder-dialogs'; -// eslint-disable-next-line @typescript-eslint/no-var-requires +//eslint-disable-next-line @typescript-eslint/no-require-imports const oc = require('@microsoft/orchestrator-core'); export interface OrchestratorRecognizerConfiguration extends RecognizerConfiguration { @@ -173,7 +173,7 @@ export class OrchestratorRecognizer extends AdaptiveRecognizer implements Orches dc: DialogContext, activity: Partial, telemetryProperties?: Record, - telemetryMetrics?: Record + telemetryMetrics?: Record, ): Promise { if (!this._resolver) { const modelFolder: string = this.modelFolder.getValue(dc.state); @@ -209,30 +209,28 @@ export class OrchestratorRecognizer extends AdaptiveRecognizer implements Orches // add all scores recognizerResult.intents = results.reduce(function ( intents: { [index: string]: { score: number } }, - result + result, ) { intents[result.label.name] = { score: result.score }; return intents; - }, - {}); + }, {}); recognizerResult.intents.None = { score: 1.0 }; } else { // add all scores recognizerResult.intents = results.reduce(function ( intents: { [index: string]: { score: number } }, - result + result, ) { intents[result.label.name] = { score: result.score }; return intents; - }, - {}); + }, {}); // disambiguate if (detectAmbiguity) { const disambiguationScoreThreshold = this.disambiguationScoreThreshold.getValue(dc.state); const classifyingScore = topScore - disambiguationScoreThreshold; const ambiguousResults = results.filter( - (item: { score: number }) => item.score >= classifyingScore + (item: { score: number }) => item.score >= classifyingScore, ); if (ambiguousResults.length > 1) { const recognizerResults: Record = ambiguousResults @@ -242,7 +240,7 @@ export class OrchestratorRecognizer extends AdaptiveRecognizer implements Orches alteredText: result.closest_text, entities: recognizerResult.entities, intents: { [result.label.name]: { score: result.score } }, - }) + }), ) .reduce((results: Record, result: RecognizerResult) => { const guid = uuidv4(); @@ -266,7 +264,7 @@ export class OrchestratorRecognizer extends AdaptiveRecognizer implements Orches dc, activity, telemetryProperties, - telemetryMetrics + telemetryMetrics, ); recognizerResult.entities = externalResults.entities; } @@ -277,13 +275,13 @@ export class OrchestratorRecognizer extends AdaptiveRecognizer implements Orches 'OrchestratorRecognizer', recognizerResult, 'OrchestratorRecognizer', - 'Orchestrator Recognition' + 'Orchestrator Recognition', ); this.trackRecognizerResult( dc, 'OrchestratorRecognizerResult', this.fillRecognizerResultTelemetryProperties(recognizerResult, telemetryProperties, dc), - telemetryMetrics + telemetryMetrics, ); return recognizerResult; @@ -318,7 +316,7 @@ export class OrchestratorRecognizer extends AdaptiveRecognizer implements Orches protected fillRecognizerResultTelemetryProperties( recognizerResult: RecognizerResult, telemetryProperties?: Record, - dialogContext?: DialogContext + dialogContext?: DialogContext, ): Record { const topTwo = this.getTopTwoIntents(recognizerResult); const intent = Object.entries(recognizerResult.intents); @@ -379,16 +377,19 @@ export class OrchestratorRecognizer extends AdaptiveRecognizer implements Orches this._orchestrator = OrchestratorRecognizer.orchestratorMap.has(fullModelFolder) ? OrchestratorRecognizer.orchestratorMap.get(fullModelFolder) : ((): OrchestratorDictionaryEntry => { + // eslint-disable-next-line security/detect-non-literal-fs-filename if (!existsSync(fullModelFolder)) { throw new Error(`Model folder does not exist at ${fullModelFolder}.`); } + const entityModelFolder: string = resolve(modelFolder, 'entity'); + // eslint-disable-next-line security/detect-non-literal-fs-filename const isEntityExtractionCapable: boolean = existsSync(entityModelFolder); const orchestrator = new oc.Orchestrator(); if (isEntityExtractionCapable) { if (!orchestrator.load(fullModelFolder, entityModelFolder)) { throw new Error( - `Model load failed - model folder ${fullModelFolder}, entity model folder ${entityModelFolder}.` + `Model load failed - model folder ${fullModelFolder}, entity model folder ${entityModelFolder}.`, ); } } else { @@ -405,11 +406,13 @@ export class OrchestratorRecognizer extends AdaptiveRecognizer implements Orches })(); const fullSnapshotPath = resolve(snapshotFile); + // eslint-disable-next-line security/detect-non-literal-fs-filename if (!existsSync(fullSnapshotPath)) { throw new Error(`Snapshot file does not exist at ${fullSnapshotPath}.`); } // Load the snapshot + // eslint-disable-next-line security/detect-non-literal-fs-filename const snapshot: Uint8Array = readFileSync(fullSnapshotPath); // Load snapshot and create resolver diff --git a/libraries/botbuilder-ai-orchestrator/tests/mockResolver.js b/libraries/botbuilder-ai-orchestrator/tests/mockResolver.js index 7e4cc78919..46331d40c6 100644 --- a/libraries/botbuilder-ai-orchestrator/tests/mockResolver.js +++ b/libraries/botbuilder-ai-orchestrator/tests/mockResolver.js @@ -3,8 +3,6 @@ * Licensed under the MIT License. */ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ - const { LabelType } = require('../lib'); class MockResolver { constructor(score, entityScore) { From 75ed816cf7396de522d50ed9d3b31c3b4484c24b Mon Sep 17 00:00:00 2001 From: Jhonatan Sandoval Velasco <122501764+JhontSouth@users.noreply.github.com> Date: Mon, 6 Jan 2025 10:07:50 -0500 Subject: [PATCH 20/22] fix eslint issues in botbuilder-repo-utils (#4838) --- .../botbuilder-repo-utils/eslint.config.cjs | 10 - libraries/botbuilder-repo-utils/package.json | 3 +- libraries/botbuilder-repo-utils/src/file.ts | 2 - .../src/updateVersions.ts | 194 +++++++++--------- .../botbuilder-repo-utils/src/workspace.ts | 94 +++++---- .../tests/updateVersions.test.ts | 9 +- 6 files changed, 150 insertions(+), 162 deletions(-) delete mode 100644 libraries/botbuilder-repo-utils/eslint.config.cjs diff --git a/libraries/botbuilder-repo-utils/eslint.config.cjs b/libraries/botbuilder-repo-utils/eslint.config.cjs deleted file mode 100644 index 63647b52cc..0000000000 --- a/libraries/botbuilder-repo-utils/eslint.config.cjs +++ /dev/null @@ -1,10 +0,0 @@ -const onlyWarn = require("eslint-plugin-only-warn"); -const sharedConfig = require("../../eslint.config.cjs") - -module.exports = [ - ...sharedConfig, - { - plugins: { - "only-warn": onlyWarn, - }, - }]; diff --git a/libraries/botbuilder-repo-utils/package.json b/libraries/botbuilder-repo-utils/package.json index 4bb1a7c8ee..8fa9531004 100644 --- a/libraries/botbuilder-repo-utils/package.json +++ b/libraries/botbuilder-repo-utils/package.json @@ -14,7 +14,6 @@ "dayjs": "^1.11.13", "fast-glob": "^3.3.2", "lodash": "^4.17.20", - "eslint-plugin-only-warn": "^1.1.0", "minimatch": "^9.0.5", "minimist": "^1.2.6", "p-map": "^4.0.0" @@ -27,7 +26,7 @@ "typescript": "~4.7" }, "scripts": { - "lint": "eslint .", + "lint": "eslint . --config ../../eslint.config.cjs", "test": "mocha -r ts-node/register tests/*.test.ts", "update-versions": "ts-node src/updateVersions.ts" } diff --git a/libraries/botbuilder-repo-utils/src/file.ts b/libraries/botbuilder-repo-utils/src/file.ts index dc653fb965..6978761088 100644 --- a/libraries/botbuilder-repo-utils/src/file.ts +++ b/libraries/botbuilder-repo-utils/src/file.ts @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -/* eslint-disable security/detect-non-literal-fs-filename */ - import fs from 'fs'; import util from 'util'; diff --git a/libraries/botbuilder-repo-utils/src/updateVersions.ts b/libraries/botbuilder-repo-utils/src/updateVersions.ts index 5894824e31..e8d9fd5e22 100644 --- a/libraries/botbuilder-repo-utils/src/updateVersions.ts +++ b/libraries/botbuilder-repo-utils/src/updateVersions.ts @@ -32,7 +32,7 @@ export interface PackageVersionOptions { export const getPackageVersion = ( pkg: Partial, newVersion: string, - options: PackageVersionOptions + options: PackageVersionOptions, ): string => { const prerelease = []; @@ -59,109 +59,111 @@ export const getPackageVersion = ( return compact([newVersion, compact(prerelease).join('.')]).join('-'); }; -export const command = (argv: string[], quiet = false) => async (): Promise => { - // Obtain the path of the repo root, useful for constructing absolute paths - const repoRoot = await gitRoot(); - - const packageFile = await readJsonFile(path.join(repoRoot, 'package.json')); - if (!packageFile) { - return failure('package.json not found', 20); - } - - // Parse process.argv for all configuration options - const { - _: [maybeNewVersion], - ...flags - } = minimist(argv, { - default: { - deprecated: 'deprecated', - git: 'false', - internal: 'internal', - preview: 'preview', - }, - string: ['buildLabel', 'date', 'deprecated', 'git', 'internal', 'preview'], - }); - - // If `maybeNewVersion` is falsy use version from the root packge.json file - const newVersion = maybeNewVersion || packageFile.version; - if (!newVersion) { - return failure('unable to resolve new version', 21); - } - - // Fetch and format date, if instructed - const date = flags.date ? dayjs().format(flags.date) : undefined; - - // Read git commit sha if instructed (JSON.parse properly coerces strings to boolean) - const commitSha = JSON.parse(flags.git) ? await gitSha('HEAD') : undefined; +export const command = + (argv: string[], quiet = false) => + async (): Promise => { + // Obtain the path of the repo root, useful for constructing absolute paths + const repoRoot = await gitRoot(); + + const packageFile = await readJsonFile(path.join(repoRoot, 'package.json')); + if (!packageFile) { + return failure('package.json not found', 20); + } + + // Parse process.argv for all configuration options + const { + _: [maybeNewVersion], + ...flags + } = minimist(argv, { + default: { + deprecated: 'deprecated', + git: 'false', + internal: 'internal', + preview: 'preview', + }, + string: ['buildLabel', 'date', 'deprecated', 'git', 'internal', 'preview'], + }); + + // If `maybeNewVersion` is falsy use version from the root packge.json file + const newVersion = maybeNewVersion || packageFile.version; + if (!newVersion) { + return failure('unable to resolve new version', 21); + } + + // Fetch and format date, if instructed + const date = flags.date ? dayjs().format(flags.date) : undefined; + + // Read git commit sha if instructed (JSON.parse properly coerces strings to boolean) + const commitSha = JSON.parse(flags.git) ? await gitSha('HEAD') : undefined; const projects: string[] = [ ...(packageFile.workspaces?.packages || []), ...(packageFile.workspaces?.generators || []), ]; - // Collect all workspaces from the repo root. Returns workspaces with absolute paths. - const workspaces = await collectWorkspacePackages(repoRoot, projects); - - // Build an object mapping a package name to its new, updated version - const workspaceVersions = workspaces.reduce>( - (acc, { pkg }) => ({ - ...acc, - [pkg.name]: getPackageVersion(pkg, pkg.private ? pkg.version : newVersion, { - buildLabel: flags.buildLabel, - commitSha, - date, - deprecated: flags.deprecated, - internal: flags.internal, - preview: flags.preview, + // Collect all workspaces from the repo root. Returns workspaces with absolute paths. + const workspaces = await collectWorkspacePackages(repoRoot, projects); + + // Build an object mapping a package name to its new, updated version + const workspaceVersions = workspaces.reduce>( + (acc, { pkg }) => ({ + ...acc, + [pkg.name]: getPackageVersion(pkg, pkg.private ? pkg.version : newVersion, { + buildLabel: flags.buildLabel, + commitSha, + date, + deprecated: flags.deprecated, + internal: flags.internal, + preview: flags.preview, + }), }), - }), - {} - ); - - // Rewrites the version for any dependencies found in `workspaceVersions` - const rewriteWithNewVersions = (dependencies: Record) => - Object.entries(dependencies) - .map(([dependency, version]) => [dependency, workspaceVersions[dependency] ?? version]) - .reduce>((acc, [dependency, version]) => { - acc[dependency] = version; - return acc; - }, {}); - - // Rewrite package.json files by updating version as well as dependencies, devDependencies and peerDependencies. - const results = await Promise.all( - workspaces.map(async ({ absPath, pkg }) => { - const newVersion = workspaceVersions[pkg.name]; - - if (newVersion) { - if (!quiet) { - console.log(`Updating ${pkg.name} to ${newVersion}`); + {}, + ); + + // Rewrites the version for any dependencies found in `workspaceVersions` + const rewriteWithNewVersions = (dependencies: Record) => + Object.entries(dependencies) + .map(([dependency, version]) => [dependency, workspaceVersions[dependency] ?? version]) + .reduce>((acc, [dependency, version]) => { + acc[dependency] = version; + return acc; + }, {}); + + // Rewrite package.json files by updating version as well as dependencies, devDependencies and peerDependencies. + const results = await Promise.all( + workspaces.map(async ({ absPath, pkg }) => { + const newVersion = workspaceVersions[pkg.name]; + + if (newVersion) { + if (!quiet) { + console.log(`Updating ${pkg.name} to ${newVersion}`); + } + pkg.version = newVersion.toString(); } - pkg.version = newVersion.toString(); - } - - if (pkg.dependencies) { - pkg.dependencies = rewriteWithNewVersions(pkg.dependencies); - } - - if (pkg.devDependencies) { - pkg.devDependencies = rewriteWithNewVersions(pkg.devDependencies); - } - - if (pkg.peerDependencies) { - pkg.peerDependencies = rewriteWithNewVersions(pkg.peerDependencies); - } - - try { - await writeJsonFile(absPath, pkg); - return success(); - } catch (err: any) { - return failure(err instanceof Error ? err.message : err, 22); - } - }) - ); - - return results.find(isFailure) ?? success(); -}; + + if (pkg.dependencies) { + pkg.dependencies = rewriteWithNewVersions(pkg.dependencies); + } + + if (pkg.devDependencies) { + pkg.devDependencies = rewriteWithNewVersions(pkg.devDependencies); + } + + if (pkg.peerDependencies) { + pkg.peerDependencies = rewriteWithNewVersions(pkg.peerDependencies); + } + + try { + await writeJsonFile(absPath, pkg); + return success(); + } catch (err: any) { + return failure(err instanceof Error ? err.message : err, 22); + } + }), + ); + + return results.find(isFailure) ?? success(); + }; if (require.main === module) { run(command(process.argv.slice(2))); diff --git a/libraries/botbuilder-repo-utils/src/workspace.ts b/libraries/botbuilder-repo-utils/src/workspace.ts index aa2feea71c..b2b43641a4 100644 --- a/libraries/botbuilder-repo-utils/src/workspace.ts +++ b/libraries/botbuilder-repo-utils/src/workspace.ts @@ -38,7 +38,7 @@ export interface Filters { export async function collectWorkspacePackages( repoRoot: string, workspaces: string[] = [], - filters: Partial = {} + filters: Partial = {}, ): Promise> { // Note: posix is required, this emits absolute paths that are platform specific const paths = await glob( @@ -48,54 +48,52 @@ export async function collectWorkspacePackages( ); const maybeWorkspaces = await Promise.all( - paths.map( - async (absPath): Promise => { - let relPath = absPath.replace(repoRoot, ''); - if (relPath[0] === path.sep) { - relPath = relPath.slice(1); - } - - // Strip `package.json` filename for path filters - const relWorkspacePath = path.dirname(relPath); - - if (filters.path?.length && !filters.path.some((path) => minimatch(relWorkspacePath, path))) { - return; - } - - if ( - filters.ignorePath?.length && - filters.ignorePath.some((ignorePath) => minimatch(relWorkspacePath, ignorePath)) - ) { - return; - } - - const pkg = await readJsonFile(absPath); - if (!pkg) { - return undefined; - } - - if (filters.noPrivate && pkg.private) { - return; - } - - if (filters.script && !(pkg.scripts ?? {})[filters.script]) { - return; - } - - if (filters.name?.length && !filters.name.some((name) => minimatch(pkg.name, name))) { - return; - } - - if ( - filters.ignoreName?.length && - filters.ignoreName.some((ignoreName) => minimatch(pkg.name, ignoreName)) - ) { - return; - } - - return { absPath, pkg, relPath }; + paths.map(async (absPath): Promise => { + let relPath = absPath.replace(repoRoot, ''); + if (relPath[0] === path.sep) { + relPath = relPath.slice(1); } - ) + + // Strip `package.json` filename for path filters + const relWorkspacePath = path.dirname(relPath); + + if (filters.path?.length && !filters.path.some((path) => minimatch(relWorkspacePath, path))) { + return; + } + + if ( + filters.ignorePath?.length && + filters.ignorePath.some((ignorePath) => minimatch(relWorkspacePath, ignorePath)) + ) { + return; + } + + const pkg = await readJsonFile(absPath); + if (!pkg) { + return undefined; + } + + if (filters.noPrivate && pkg.private) { + return; + } + + if (filters.script && !(pkg.scripts ?? {})[filters.script]) { + return; + } + + if (filters.name?.length && !filters.name.some((name) => minimatch(pkg.name, name))) { + return; + } + + if ( + filters.ignoreName?.length && + filters.ignoreName.some((ignoreName) => minimatch(pkg.name, ignoreName)) + ) { + return; + } + + return { absPath, pkg, relPath }; + }), ); return compact(maybeWorkspaces); diff --git a/libraries/botbuilder-repo-utils/tests/updateVersions.test.ts b/libraries/botbuilder-repo-utils/tests/updateVersions.test.ts index b2f9ec1f3b..70c5927067 100644 --- a/libraries/botbuilder-repo-utils/tests/updateVersions.test.ts +++ b/libraries/botbuilder-repo-utils/tests/updateVersions.test.ts @@ -8,7 +8,7 @@ import assert from 'assert'; import dayjs from 'dayjs'; import path from 'path'; import semver from 'semver'; -import sinon from 'sinon'; +import { createSandbox, match } from 'sinon'; import { Package } from '../src/package'; import { command, getPackageVersion } from '../src/updateVersions'; import { isSuccess } from '../src/run'; @@ -147,8 +147,9 @@ describe('updateVersions', function () { describe('command', function () { let sandbox: sinon.SinonSandbox; + beforeEach(function () { - sandbox = sinon.createSandbox(); + sandbox = createSandbox(); }); afterEach(function () { @@ -223,10 +224,10 @@ describe('updateVersions', function () { ), }); - let packageMatch = sinon.match.hasOwn('version', workspace.expectedVersion); + let packageMatch = match.hasOwn('version', workspace.expectedVersion); if (workspace.expectedDependencies) { packageMatch = packageMatch.and( - sinon.match.hasOwn('dependencies', sinon.match(workspace.expectedDependencies)), + match.hasOwn('dependencies', match(workspace.expectedDependencies)), ); } From 4bac80c6ab79743b257aa6a371183356d9ac8971 Mon Sep 17 00:00:00 2001 From: Jhonatan Sandoval Velasco <122501764+JhontSouth@users.noreply.github.com> Date: Mon, 6 Jan 2025 10:09:24 -0500 Subject: [PATCH 21/22] update nightwatch (#4816) --- package.json | 7 --- testing/browser-functional/package.json | 2 +- yarn.lock | 73 ++++++++++++++----------- 3 files changed, 43 insertions(+), 39 deletions(-) diff --git a/package.json b/package.json index 2352fddc46..990f7822bf 100644 --- a/package.json +++ b/package.json @@ -55,17 +55,10 @@ }, "resolutions": { "@microsoft/recognizers-text-number": "~1.3.1", - "@types/ramda": "0.26.0", - "lodash.pick": "file:overrides/lodash.pick", - "**/nightwatch/ejs": "^3.1.10", - "**/nightwatch/semver": "^7.5.2", "**/botbuilder-dialogs-adaptive-runtime-integration-restify/restify/send": "^0.19.0", "**/restify/find-my-way": "^8.2.2" }, "resolutionComments": { - "lodash.pick": "Remove the resolution and override project when supporting Node >=18. Because we can't update nightwatch due to jsdom requires node >= 18. https://github.com/lodash/lodash/issues/5809#issuecomment-1910560681", - "**/nightwatch/ejs": "Remove the resolution when supporting Node >=18. Because we can't update nightwatch due to jsdom requires node >= 18. https://github.com/lodash/lodash/issues/5809#issuecomment-1910560681", - "**/nightwatch/semver": "Remove the resolution when nightwatch is updated to a latest version", "**/restify/find-my-way": "Remove the resolution when restify publishes a new version with the patch" }, "devDependencies": { diff --git a/testing/browser-functional/package.json b/testing/browser-functional/package.json index 85bdae45ca..6ba9dcdc15 100644 --- a/testing/browser-functional/package.json +++ b/testing/browser-functional/package.json @@ -7,7 +7,7 @@ "devDependencies": { "axios": "^1.7.7", "dotenv": "^16.4.5", - "nightwatch": "^3.7.0" + "nightwatch": "^3.9.0" }, "directories": { "test": "tests" diff --git a/yarn.lock b/yarn.lock index 1cf28bf893..9b8df9db54 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2442,10 +2442,10 @@ lodash "^4.17.19" to-fast-properties "^2.0.0" -"@bazel/runfiles@^5.8.1": - version "5.8.1" - resolved "https://registry.yarnpkg.com/@bazel/runfiles/-/runfiles-5.8.1.tgz#737d5b3dc9739767054820265cfe432a80564c82" - integrity sha512-NDdfpdQ6rZlylgv++iMn5FkObC/QlBQvipinGLSOguTYpRywmieOyJ29XHvUilspwTFSILWpoE9CqMGkHXug1g== +"@bazel/runfiles@^6.3.1": + version "6.3.1" + resolved "https://registry.yarnpkg.com/@bazel/runfiles/-/runfiles-6.3.1.tgz#3f8824b2d82853377799d42354b4df78ab0ace0b" + integrity sha512-1uLNT5NZsUVIGS4syuHwTzZ8HycMPyr6POA3FCE4GbMtc4rhoJk8aZKtNIRthJYfL+iioppi+rTfH3olMPr9nA== "@colors/colors@1.5.0": version "1.5.0" @@ -4370,10 +4370,12 @@ resolved "https://registry.yarnpkg.com/@types/qs/-/qs-6.9.5.tgz#434711bdd49eb5ee69d90c1d67c354a9a8ecb18b" integrity sha512-/JHkVHtx/REVG0VVToGRGH2+23hsYLHdyG+GrvoUGlGAd0ErauXDyvHtRI/7H7mzLm+tBCKA7pfcpkQ1lf58iQ== -"@types/ramda@0.26.0", "@types/ramda@~0.30.0": - version "0.26.0" - resolved "https://registry.yarnpkg.com/@types/ramda/-/ramda-0.26.0.tgz#ce45c2c61b3e510f907cc84941c8cdb99f089b6a" - integrity sha512-6FCz2E3SrkgbuV3piRNfjThSRyMbcIxHknnGYPfrg4k55PHnNRR80boVdl1AME/KfDW+FBVmKrKPyRbFo8HjaQ== +"@types/ramda@~0.30.0": + version "0.30.2" + resolved "https://registry.yarnpkg.com/@types/ramda/-/ramda-0.30.2.tgz#70661b20c1bb969589a551b7134ae75008ffbfb6" + integrity sha512-PyzHvjCalm2BRYjAU6nIB3TprYwMNOUY/7P/N8bSzp9W/yM2YrtGtAnnVtaCNSeOZ8DzKyFDvaqQs7LnWwwmBA== + dependencies: + types-ramda "^0.30.1" "@types/range-parser@*": version "1.2.3" @@ -10766,9 +10768,6 @@ lodash.once@^4.0.0: resolved "https://registry.yarnpkg.com/lodash.once/-/lodash.once-4.1.1.tgz#0dd3971213c7c56df880977d504c88fb471a97ac" integrity sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg== -"lodash.pick@file:overrides/lodash.pick": - version "0.0.1" - lodash.sortby@^4.7.0: version "4.7.0" resolved "https://registry.yarnpkg.com/lodash.sortby/-/lodash.sortby-4.7.0.tgz#edd14c824e2cc9c1e0b0a1b42bb5210516a42438" @@ -11719,10 +11718,10 @@ nightwatch-axe-verbose@^2.3.0: dependencies: axe-core "^4.9.1" -nightwatch@^3.7.0: - version "3.8.0" - resolved "https://registry.yarnpkg.com/nightwatch/-/nightwatch-3.8.0.tgz#e841252c9920616eb5c0b4cdb92256f9a541fd08" - integrity sha512-aO2u05Tbc+RIfUESa0k+3SKByxoiOKDqTiJWk/B5GU//ZfhJE/EYT+NKB/drkKRUAh8tvD3O47aPWTXTAwaqZA== +nightwatch@^3.9.0: + version "3.9.0" + resolved "https://registry.yarnpkg.com/nightwatch/-/nightwatch-3.9.0.tgz#31e71cf14ace22f05f962e9ea06487a65b76e3dc" + integrity sha512-SIkcvRXtGtPy33fodtZC4xDUXKY444dfYvyiODB2sP1M4Ewt7KqE+cxdPuGY0qr+Hsb982KhOnjDUjhSSaX+AA== dependencies: "@nightwatch/chai" "5.0.3" "@nightwatch/html-reporter-template" "^0.3.0" @@ -11752,7 +11751,7 @@ nightwatch@^3.7.0: open "8.4.2" ora "5.4.1" piscina "^4.3.1" - selenium-webdriver "4.24.1" + selenium-webdriver "4.26.0" semver "7.5.4" stacktrace-parser "0.1.10" strip-ansi "6.0.1" @@ -13724,12 +13723,12 @@ select-hose@^2.0.0: resolved "https://registry.yarnpkg.com/select-hose/-/select-hose-2.0.0.tgz#625d8658f865af43ec962bfc376a37359a4994ca" integrity sha1-Yl2GWPhlr0Psliv8N2o3NZpJlMo= -selenium-webdriver@4.24.1: - version "4.24.1" - resolved "https://registry.yarnpkg.com/selenium-webdriver/-/selenium-webdriver-4.24.1.tgz#4315214420cc26dddaa21ae26863dd452aec2829" - integrity sha512-fcK5BTI/54cSqIhiVtrd9li1YL6LW109yIwuVw6V+FlVE6y4riGiX2qdZxVzHq+sm2TJyps+D2sjzXrpDZe1Og== +selenium-webdriver@4.26.0: + version "4.26.0" + resolved "https://registry.yarnpkg.com/selenium-webdriver/-/selenium-webdriver-4.26.0.tgz#23163cdad20388214a4ad17c1f38262a0857c902" + integrity sha512-nA7jMRIPV17mJmAiTDBWN96Sy0Uxrz5CCLb7bLVV6PpL417SyBMPc2Zo/uoREc2EOHlzHwHwAlFtgmSngSY4WQ== dependencies: - "@bazel/runfiles" "^5.8.1" + "@bazel/runfiles" "^6.3.1" jszip "^3.10.1" tmp "^0.2.3" ws "^8.18.0" @@ -13764,22 +13763,22 @@ semver-greatest-satisfied-range@^2.0.0: resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.2.tgz#48d55db737c3287cd4835e17fa13feace1c41ef8" integrity sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g== -semver@7.5.4, semver@^7.1.1, semver@^7.3.2, semver@^7.3.4, semver@^7.3.5, semver@^7.3.8, semver@^7.5.2, semver@^7.5.3, semver@^7.5.4, semver@^7.6.0, semver@^7.6.3: - version "7.6.3" - resolved "https://registry.yarnpkg.com/semver/-/semver-7.6.3.tgz#980f7b5550bc175fb4dc09403085627f9eb33143" - integrity sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A== +semver@7.5.4, semver@~7.5.4: + version "7.5.4" + resolved "https://registry.yarnpkg.com/semver/-/semver-7.5.4.tgz#483986ec4ed38e1c6c48c34894a9182dbff68a6e" + integrity sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA== + dependencies: + lru-cache "^6.0.0" semver@^6.0.0, semver@^6.3.0, semver@^6.3.1: version "6.3.1" resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.1.tgz#556d2ef8689146e46dcea4bfdd095f3434dffcb4" integrity sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA== -semver@~7.5.4: - version "7.5.4" - resolved "https://registry.yarnpkg.com/semver/-/semver-7.5.4.tgz#483986ec4ed38e1c6c48c34894a9182dbff68a6e" - integrity sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA== - dependencies: - lru-cache "^6.0.0" +semver@^7.1.1, semver@^7.3.2, semver@^7.3.4, semver@^7.3.5, semver@^7.3.8, semver@^7.5.2, semver@^7.5.3, semver@^7.5.4, semver@^7.6.0, semver@^7.6.3: + version "7.6.3" + resolved "https://registry.yarnpkg.com/semver/-/semver-7.6.3.tgz#980f7b5550bc175fb4dc09403085627f9eb33143" + integrity sha512-oVekP1cKtI+CTDvHWYFUcMtsK/00wmAEfyqKfNdARm8u1wNVhSgaX7A8d4UuIlUI5e84iEwOhs7ZPYRmzU9U6A== send@0.19.0: version "0.19.0" @@ -14961,6 +14960,11 @@ ts-node@^10.9.2: v8-compile-cache-lib "^3.0.1" yn "3.1.1" +ts-toolbelt@^9.6.0: + version "9.6.0" + resolved "https://registry.yarnpkg.com/ts-toolbelt/-/ts-toolbelt-9.6.0.tgz#50a25426cfed500d4a09bd1b3afb6f28879edfd5" + integrity sha512-nsZd8ZeNUzukXPlJmTBwUAuABDe/9qtVDelJeT/qW0ow3ZS3BsQJtNkan1802aM9Uf68/Y8ljw86Hu0h5IUW3w== + tsconfig-paths@^3.15.0: version "3.15.0" resolved "https://registry.yarnpkg.com/tsconfig-paths/-/tsconfig-paths-3.15.0.tgz#5299ec605e55b1abb23ec939ef15edaf483070d4" @@ -15150,6 +15154,13 @@ typedoc@^0.26.7: shiki "^1.16.2" yaml "^2.5.1" +types-ramda@^0.30.1: + version "0.30.1" + resolved "https://registry.yarnpkg.com/types-ramda/-/types-ramda-0.30.1.tgz#03d255128e3696aeaac76281ca19949e01dddc78" + integrity sha512-1HTsf5/QVRmLzcGfldPFvkVsAdi1db1BBKzi7iW3KBUlOICg/nKnFS+jGqDJS3YD8VsWbAh7JiHeBvbsw8RPxA== + dependencies: + ts-toolbelt "^9.6.0" + typescript-compare@^0.0.2: version "0.0.2" resolved "https://registry.yarnpkg.com/typescript-compare/-/typescript-compare-0.0.2.tgz#7ee40a400a406c2ea0a7e551efd3309021d5f425" From 4c055b7f7924c07ee754d39c9e21ce66de9857bc Mon Sep 17 00:00:00 2001 From: Jhonatan Sandoval Velasco <122501764+JhontSouth@users.noreply.github.com> Date: Mon, 6 Jan 2025 10:16:10 -0500 Subject: [PATCH 22/22] update path-to-regexp dependency (#4817) --- yarn.lock | 48 ++++++++++++++++++++++++++++++++++++------------ 1 file changed, 36 insertions(+), 12 deletions(-) diff --git a/yarn.lock b/yarn.lock index 9b8df9db54..a85d6d6480 100644 --- a/yarn.lock +++ b/yarn.lock @@ -8317,9 +8317,9 @@ expand-tilde@^2.0.0, expand-tilde@^2.0.2: homedir-polyfill "^1.0.1" express@^4.19.2, express@^4.21.0: - version "4.21.1" - resolved "https://registry.yarnpkg.com/express/-/express-4.21.1.tgz#9dae5dda832f16b4eec941a4e44aa89ec481b281" - integrity sha512-YSFlK1Ee0/GC8QaO91tHcDxJiE/X4FbpAyQWkxAvG6AXCuR65YzK8ua6D9hvi/TzUfZMpc+BwuM1IPw8fmQBiQ== + version "4.21.2" + resolved "https://registry.yarnpkg.com/express/-/express-4.21.2.tgz#cf250e48362174ead6cea4a566abef0162c1ec32" + integrity sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA== dependencies: accepts "~1.3.8" array-flatten "1.1.1" @@ -8340,7 +8340,7 @@ express@^4.19.2, express@^4.21.0: methods "~1.1.2" on-finished "2.4.1" parseurl "~1.3.3" - path-to-regexp "0.1.10" + path-to-regexp "0.1.12" proxy-addr "~2.0.7" qs "6.13.0" range-parser "~1.2.1" @@ -12488,10 +12488,10 @@ path-scurry@^1.11.1: lru-cache "^10.2.0" minipass "^5.0.0 || ^6.0.2 || ^7.0.0" -path-to-regexp@0.1.10: - version "0.1.10" - resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-0.1.10.tgz#67e9108c5c0551b9e5326064387de4763c4d5f8b" - integrity sha512-7lf7qcQidTku0Gu3YDPc8DJ1q7OOucfa/BSsIwjuh56VU7katFvuM8hULfkwB3Fns/rsVF7PwPKVw1sl5KQS9w== +path-to-regexp@0.1.12: + version "0.1.12" + resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-0.1.12.tgz#d5e1a12e478a976d432ef3c58d534b9923164bb7" + integrity sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ== path-to-regexp@^8.1.0: version "8.2.0" @@ -14396,8 +14396,16 @@ string-argv@~0.3.1: resolved "https://registry.yarnpkg.com/string-argv/-/string-argv-0.3.1.tgz#95e2fbec0427ae19184935f816d74aaa4c5c19da" integrity sha512-a1uQGz7IyVy9YwhqjZIZu1c8JO8dNIe20xBmSS6qu9kv++k3JGzCVmprbNN5Kn+BgzD5E7YYwg1CcjuJMRNsvg== -"string-width-cjs@npm:string-width@^4.2.0", "string-width@^1.0.2 || 2 || 3 || 4", string-width@^4.0.0, string-width@^4.2.2, string-width@^4.2.3: - name string-width-cjs +"string-width-cjs@npm:string-width@^4.2.0": + version "4.2.3" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" + integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== + dependencies: + emoji-regex "^8.0.0" + is-fullwidth-code-point "^3.0.0" + strip-ansi "^6.0.1" + +"string-width@^1.0.2 || 2 || 3 || 4", string-width@^4.0.0, string-width@^4.2.2, string-width@^4.2.3: version "4.2.3" resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== @@ -14512,7 +14520,14 @@ stringify-entities@^4.0.0: character-entities-html4 "^2.0.0" character-entities-legacy "^3.0.0" -"strip-ansi-cjs@npm:strip-ansi@^6.0.1", strip-ansi@6.0.1, strip-ansi@^6.0.1: +"strip-ansi-cjs@npm:strip-ansi@^6.0.1": + version "6.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" + integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== + dependencies: + ansi-regex "^5.0.1" + +strip-ansi@6.0.1, strip-ansi@^6.0.1: version "6.0.1" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== @@ -15953,7 +15968,7 @@ workerpool@^6.5.1: resolved "https://registry.yarnpkg.com/workerpool/-/workerpool-6.5.1.tgz#060f73b39d0caf97c6db64da004cd01b4c099544" integrity sha512-Fs4dNYcsdpYSAfVxhnl1L5zTksjvOJxtC5hzMNl+1t9B8hTJTdKDyZ5ju7ztgPy+ft9tBFXoOlDNiOT9WUXZlA== -"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0", wrap-ansi@^7.0.0: +"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0": version "7.0.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== @@ -15980,6 +15995,15 @@ wrap-ansi@^6.2.0: string-width "^4.1.0" strip-ansi "^6.0.0" +wrap-ansi@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" + integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== + dependencies: + ansi-styles "^4.0.0" + string-width "^4.1.0" + strip-ansi "^6.0.0" + wrap-ansi@^8.1.0: version "8.1.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-8.1.0.tgz#56dc22368ee570face1b49819975d9b9a5ead214"